@damiangilgonzalez/copypasta 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -2
- package/catalog.yaml +140 -0
- package/cli/copypasta.js +4 -0
- package/cli/lib/catalog.js +131 -0
- package/cli/lib/commands.js +162 -0
- package/cli/lib/index.js +4 -0
- package/cli/lib/main.js +130 -0
- package/package.json +38 -4
- package/recipes/agents/agent-memory/RECIPE.md +75 -0
- package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
- package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
- package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
- package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
- package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
- package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
- package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
- package/recipes/agents/agent-memory/files/pytest.ini +5 -0
- package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
- package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
- package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
- package/recipes/agents/langchain-agent/RECIPE.md +101 -0
- package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
- package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
- package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
- package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
- package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
- package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
- package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
- package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
- package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
- package/recipes/backend/.gitkeep +0 -0
- package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
- package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
- package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
- package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
- package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
- package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
- package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
- package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
- package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
- package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
- package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
- package/recipes/backend/agent-feedback/RECIPE.md +63 -0
- package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
- package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
- package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
- package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
- package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
- package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
- package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
- package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
- package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
- package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
- package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
- package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
- package/recipes/backend/auth-verifier/RECIPE.md +63 -0
- package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
- package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
- package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
- package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
- package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
- package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
- package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
- package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
- package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
- package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
- package/recipes/backend/conversation-history/RECIPE.md +49 -0
- package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
- package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
- package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
- package/recipes/backend/conversation-history/files/pytest.ini +5 -0
- package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
- package/recipes/backend/fastapi-base/RECIPE.md +57 -0
- package/recipes/backend/fastapi-base/files/api/app.py +37 -0
- package/recipes/backend/fastapi-base/files/api/base.py +54 -0
- package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
- package/recipes/backend/fastapi-base/files/api/health.py +19 -0
- package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
- package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
- package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
- package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
- package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
- package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
- package/recipes/backend/observability/RECIPE.md +68 -0
- package/recipes/backend/observability/files/observability/__init__.py +34 -0
- package/recipes/backend/observability/files/observability/factory.py +73 -0
- package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
- package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
- package/recipes/backend/observability/files/observability/models.py +90 -0
- package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
- package/recipes/backend/observability/files/observability/settings.py +58 -0
- package/recipes/backend/observability/files/observability/tracer.py +142 -0
- package/recipes/backend/observability/files/observability/usage.py +61 -0
- package/recipes/backend/observability/files/pytest.ini +5 -0
- package/recipes/backend/observability/files/tests/__init__.py +0 -0
- package/recipes/backend/observability/files/tests/test_observability.py +219 -0
- package/recipes/backend/project-settings/RECIPE.md +40 -0
- package/recipes/backend/project-settings/files/.env.example +7 -0
- package/recipes/backend/project-settings/files/core/__init__.py +0 -0
- package/recipes/backend/project-settings/files/core/config.py +41 -0
- package/recipes/backend/project-settings/files/pytest.ini +3 -0
- package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
- package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
- package/recipes/backend/rag-retriever/RECIPE.md +79 -0
- package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
- package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
- package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
- package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
- package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
- package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
- package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
- package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
- package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
- package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
- package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
- package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
- package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
- package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
- package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
- package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
- package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
- package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
- package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
- package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
- package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
- package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
- package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
- package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
- package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
- package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
- package/recipes/backend/voice-providers/RECIPE.md +73 -0
- package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
- package/recipes/backend/voice-providers/files/pytest.ini +5 -0
- package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
- package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
- package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
- package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
- package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
- package/recipes/backend/voice-providers/files/voice/base.py +116 -0
- package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
- package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
- package/recipes/backend/voice-providers/files/voice/models.py +85 -0
- package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
- package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
- package/recipes/frontend/.gitkeep +0 -0
- package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
- package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
- package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
- package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
- package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
- package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
- package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
- package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
- package/recipes/frontend/react-app-router/RECIPE.md +58 -0
- package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
- package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
- package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
- package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
- package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
- package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
- package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
- package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
- package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
- package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
- package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
- package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
- package/recipes/frontend/vite-react-base/files/.env +6 -0
- package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
- package/recipes/frontend/vite-react-base/files/index.html +12 -0
- package/recipes/frontend/vite-react-base/files/package.json +30 -0
- package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
- package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
- package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
- package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
- package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
- package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
- package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
- package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
- package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
- package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
- package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
- package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
- package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
- package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
- package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
- package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
- package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
- package/unpacked-files.json +3 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Data of the voice layer. The audio never touches disk: `AudioInput` is bytes plus its MIME."""
|
|
2
|
+
|
|
3
|
+
from enum import StrEnum
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SttProvider(StrEnum):
|
|
9
|
+
OPENAI = "openai"
|
|
10
|
+
FAKE = "fake"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TtsProvider(StrEnum):
|
|
14
|
+
OPENAI = "openai"
|
|
15
|
+
FAKE = "fake"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class VoiceErrorCode(StrEnum):
|
|
19
|
+
INVALID_AUDIO = "invalid_audio" # format, size, empty, too short: the client's fault
|
|
20
|
+
EMPTY_TEXT = "empty_text"
|
|
21
|
+
TEXT_TOO_LONG = "text_too_long"
|
|
22
|
+
INVALID_VOICE = "invalid_voice"
|
|
23
|
+
RATE_LIMITED = "rate_limited" # the provider's 429
|
|
24
|
+
TIMEOUT = "timeout"
|
|
25
|
+
UNAVAILABLE = "unavailable" # provider down, misconfigured or 5xx
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class VoiceError(Exception):
|
|
29
|
+
"""The only error the voice layer raises. `kind` is the class name of the underlying error,
|
|
30
|
+
never its text (it may hold the API key). `retryable` is for the caller: the provider never retries."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, code: VoiceErrorCode, *, retryable: bool, kind: str | None = None) -> None:
|
|
33
|
+
super().__init__(code.value if kind is None else f"{code.value} ({kind})")
|
|
34
|
+
self.code = code
|
|
35
|
+
self.retryable = retryable
|
|
36
|
+
self.kind = kind
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# MIME -> extension the providers understand. What `MediaRecorder` produces (webm/opus, mp4 on
|
|
40
|
+
# Safari, ogg on Firefox) plus the usual files. `audio/aac` is left out: OpenAI rejects it.
|
|
41
|
+
AUDIO_FORMATS: dict[str, str] = {
|
|
42
|
+
"audio/webm": "webm",
|
|
43
|
+
"video/webm": "webm",
|
|
44
|
+
"audio/mp4": "mp4",
|
|
45
|
+
"video/mp4": "mp4",
|
|
46
|
+
"audio/x-m4a": "m4a",
|
|
47
|
+
"audio/mpeg": "mp3",
|
|
48
|
+
"audio/mp3": "mp3",
|
|
49
|
+
"audio/wav": "wav",
|
|
50
|
+
"audio/x-wav": "wav",
|
|
51
|
+
"audio/wave": "wav",
|
|
52
|
+
"audio/ogg": "ogg",
|
|
53
|
+
"audio/flac": "flac",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class AudioInput(BaseModel):
|
|
58
|
+
model_config = ConfigDict(frozen=True)
|
|
59
|
+
|
|
60
|
+
content: bytes
|
|
61
|
+
mime: str = Field(description="Media type without parameters: 'audio/webm', not 'audio/webm;codecs=opus'.")
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def extension(self) -> str | None:
|
|
65
|
+
return AUDIO_FORMATS.get(self.mime.split(";")[0].strip().lower())
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Transcription(BaseModel):
|
|
69
|
+
"""`text == ""` means no speech was detected: the caller decides what that is (422, skip...)."""
|
|
70
|
+
|
|
71
|
+
model_config = ConfigDict(frozen=True)
|
|
72
|
+
|
|
73
|
+
text: str
|
|
74
|
+
language: str | None = Field(default=None, description="The language asked for or detected, if known.")
|
|
75
|
+
engine: str
|
|
76
|
+
duration_ms: int
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Speech(BaseModel):
|
|
80
|
+
model_config = ConfigDict(frozen=True)
|
|
81
|
+
|
|
82
|
+
audio: bytes
|
|
83
|
+
mime: str
|
|
84
|
+
engine: str
|
|
85
|
+
duration_ms: int = Field(description="Time the provider took, not the length of the audio.")
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""OpenAI audio: `audio.transcriptions.create` (whisper-1, gpt-4o-transcribe, gpt-4o-mini-transcribe)
|
|
2
|
+
and `audio.speech.create` (gpt-4o-mini-tts, tts-1, tts-1-hd). One `AsyncOpenAI` client with
|
|
3
|
+
`max_retries=0` (the caller decides on retries) shared by both; `http_client=` is the test seam.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from pydantic import SecretStr
|
|
11
|
+
|
|
12
|
+
from .base import Synthesizer, Transcriber
|
|
13
|
+
from .models import AudioInput, VoiceError, VoiceErrorCode
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
OPENAI_VOICES = frozenset({"alloy", "ash", "ballad", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer", "verse"})
|
|
18
|
+
SPEECH_MIME = {"mp3": "audio/mpeg", "opus": "audio/ogg", "aac": "audio/aac", "flac": "audio/flac", "wav": "audio/wav", "pcm": "audio/pcm"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def openai_client(api_key: SecretStr, *, base_url: str | None = None, http_client: Any | None = None) -> Any:
|
|
22
|
+
from openai import AsyncOpenAI # lazy: install `openai` only if you use this provider
|
|
23
|
+
|
|
24
|
+
return AsyncOpenAI(api_key=api_key.get_secret_value(), base_url=base_url, max_retries=0, http_client=http_client)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def translate_openai_error(error: Exception) -> VoiceError:
|
|
28
|
+
"""The SDK's exceptions -> `VoiceError`. 4xx that point at the audio are the client's fault;
|
|
29
|
+
the rest is the provider's (or ours: a bad model name is 400 too, logged with its `param`)."""
|
|
30
|
+
import openai
|
|
31
|
+
|
|
32
|
+
kind = type(error).__name__
|
|
33
|
+
if isinstance(error, openai.APITimeoutError):
|
|
34
|
+
return VoiceError(VoiceErrorCode.TIMEOUT, retryable=True, kind=kind)
|
|
35
|
+
if isinstance(error, openai.APIConnectionError):
|
|
36
|
+
return VoiceError(VoiceErrorCode.UNAVAILABLE, retryable=True, kind=kind)
|
|
37
|
+
if isinstance(error, openai.RateLimitError):
|
|
38
|
+
return VoiceError(VoiceErrorCode.RATE_LIMITED, retryable=True, kind=kind)
|
|
39
|
+
if isinstance(error, openai.APIStatusError):
|
|
40
|
+
status = error.status_code
|
|
41
|
+
if status in (413, 415):
|
|
42
|
+
return VoiceError(VoiceErrorCode.INVALID_AUDIO, retryable=False, kind=kind)
|
|
43
|
+
if status in (400, 422):
|
|
44
|
+
body = error.body if isinstance(error.body, dict) else {}
|
|
45
|
+
body = body.get("error", body) if isinstance(body.get("error"), dict) else body # the SDK may unwrap it
|
|
46
|
+
param, code = str(body.get("param") or ""), str(body.get("code") or "")
|
|
47
|
+
if param == "file" or "audio" in param or code in ("audio_too_short", "unsupported_format"):
|
|
48
|
+
return VoiceError(VoiceErrorCode.INVALID_AUDIO, retryable=False, kind=kind)
|
|
49
|
+
logger.warning("openai rejected the request (status=%s, param=%s, code=%s)", status, param, code)
|
|
50
|
+
return VoiceError(VoiceErrorCode.UNAVAILABLE, retryable=False, kind=kind)
|
|
51
|
+
if status == 401:
|
|
52
|
+
return VoiceError(VoiceErrorCode.UNAVAILABLE, retryable=False, kind=kind)
|
|
53
|
+
return VoiceError(VoiceErrorCode.UNAVAILABLE, retryable=status >= 500, kind=kind)
|
|
54
|
+
return VoiceError(VoiceErrorCode.UNAVAILABLE, retryable=True, kind=kind)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class OpenAITranscriber(Transcriber):
|
|
58
|
+
engine = "openai"
|
|
59
|
+
|
|
60
|
+
def __init__(self, client: Any, *, model: str = "gpt-4o-mini-transcribe", no_speech_threshold: float = 0.6, **kwargs: Any) -> None:
|
|
61
|
+
super().__init__(**kwargs)
|
|
62
|
+
self._client = client
|
|
63
|
+
self.model = model
|
|
64
|
+
self.no_speech_threshold = no_speech_threshold
|
|
65
|
+
|
|
66
|
+
async def _transcribe(self, audio: AudioInput, language: str | None) -> str:
|
|
67
|
+
params: dict[str, Any] = {"file": (f"audio.{audio.extension}", audio.content), "model": self.model}
|
|
68
|
+
if language:
|
|
69
|
+
params["language"] = language
|
|
70
|
+
if self.prompt:
|
|
71
|
+
params["prompt"] = self.prompt
|
|
72
|
+
if self.model.startswith("whisper"):
|
|
73
|
+
# whisper-1 reports no_speech_prob per segment: the only signal it gives against hallucinated text
|
|
74
|
+
result = await self._client.audio.transcriptions.create(response_format="verbose_json", **params)
|
|
75
|
+
segments = getattr(result, "segments", None) or []
|
|
76
|
+
if segments and all((getattr(s, "no_speech_prob", 0.0) or 0.0) >= self.no_speech_threshold for s in segments):
|
|
77
|
+
return ""
|
|
78
|
+
return result.text
|
|
79
|
+
result = await self._client.audio.transcriptions.create(response_format="json", **params)
|
|
80
|
+
return result.text
|
|
81
|
+
|
|
82
|
+
def _translate(self, error: Exception) -> VoiceError:
|
|
83
|
+
return translate_openai_error(error)
|
|
84
|
+
|
|
85
|
+
async def close(self) -> None:
|
|
86
|
+
await self._client.close()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class OpenAISynthesizer(Synthesizer):
|
|
90
|
+
engine = "openai"
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
client: Any,
|
|
95
|
+
*,
|
|
96
|
+
model: str = "gpt-4o-mini-tts",
|
|
97
|
+
audio_format: str = "mp3",
|
|
98
|
+
voice: str = "nova",
|
|
99
|
+
voices: Iterable[str] = OPENAI_VOICES,
|
|
100
|
+
**kwargs: Any,
|
|
101
|
+
) -> None:
|
|
102
|
+
super().__init__(voice=voice, voices=voices, **kwargs)
|
|
103
|
+
self._client = client
|
|
104
|
+
self.model = model
|
|
105
|
+
self.audio_format = audio_format
|
|
106
|
+
self.mime = SPEECH_MIME[audio_format]
|
|
107
|
+
|
|
108
|
+
async def _synthesize(self, text: str, voice: str) -> bytes:
|
|
109
|
+
response = await self._client.audio.speech.create(model=self.model, voice=voice, input=text, response_format=self.audio_format)
|
|
110
|
+
return response.content
|
|
111
|
+
|
|
112
|
+
def _translate(self, error: Exception) -> VoiceError:
|
|
113
|
+
return translate_openai_error(error)
|
|
114
|
+
|
|
115
|
+
async def close(self) -> None:
|
|
116
|
+
await self._client.close()
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Voice settings BLOCK, meant to be mixed into the project settings (`project-settings`):
|
|
2
|
+
|
|
3
|
+
class Settings(VoiceSettings, LLMSettings, BaseAppSettings): ...
|
|
4
|
+
|
|
5
|
+
Env vars:
|
|
6
|
+
STT_PROVIDER=openai|fake required
|
|
7
|
+
STT_MODEL=gpt-4o-mini-transcribe (whisper-1 adds the no_speech check; gpt-4o-transcribe is the accurate one)
|
|
8
|
+
STT_LANGUAGE=es STT_PROMPT="vocabulario, siglas" STT_MAX_BYTES=10485760 STT_TIMEOUT_SECONDS=60
|
|
9
|
+
TTS_PROVIDER=openai|fake required (delete tts if your app only dictates)
|
|
10
|
+
TTS_MODEL=gpt-4o-mini-tts TTS_VOICE=nova TTS_FORMAT=mp3 TTS_MAX_CHARS=4096 TTS_TIMEOUT_SECONDS=60
|
|
11
|
+
OPENAI_API_KEY=... same name as the `langchain-agent` block: one key
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from typing import Literal
|
|
15
|
+
|
|
16
|
+
from pydantic import Field, SecretStr, model_validator
|
|
17
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
18
|
+
|
|
19
|
+
from .models import SttProvider, TtsProvider
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class VoiceSettings(BaseSettings):
|
|
23
|
+
model_config = SettingsConfigDict(extra="ignore")
|
|
24
|
+
|
|
25
|
+
stt_provider: SttProvider = Field(description="No default on purpose: the fake must be chosen, never fallen into.")
|
|
26
|
+
stt_model: str = "gpt-4o-mini-transcribe"
|
|
27
|
+
stt_language: str | None = Field(default="es", description="Hint for the provider. None = auto-detect.")
|
|
28
|
+
stt_prompt: str | None = Field(default=None, description="Domain vocabulary and acronyms, as a sentence.")
|
|
29
|
+
stt_max_bytes: int = Field(default=10 * 1024 * 1024, gt=0)
|
|
30
|
+
stt_timeout_seconds: float = Field(default=60.0, gt=0)
|
|
31
|
+
stt_no_speech_threshold: float = Field(default=0.6, ge=0, le=1, description="whisper-1 only.")
|
|
32
|
+
|
|
33
|
+
tts_provider: TtsProvider
|
|
34
|
+
tts_model: str = "gpt-4o-mini-tts"
|
|
35
|
+
tts_voice: str = "nova"
|
|
36
|
+
tts_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] = "mp3"
|
|
37
|
+
tts_max_chars: int = Field(default=4096, gt=0)
|
|
38
|
+
tts_timeout_seconds: float = Field(default=60.0, gt=0)
|
|
39
|
+
|
|
40
|
+
openai_api_key: SecretStr | None = None
|
|
41
|
+
openai_base_url: str | None = Field(default=None, description="An OpenAI-compatible endpoint (Groq, Azure...).")
|
|
42
|
+
|
|
43
|
+
@model_validator(mode="after")
|
|
44
|
+
def _openai_needs_its_key(self) -> "VoiceSettings":
|
|
45
|
+
uses_openai = SttProvider.OPENAI is self.stt_provider or TtsProvider.OPENAI is self.tts_provider
|
|
46
|
+
if uses_openai and self.openai_api_key is None:
|
|
47
|
+
raise ValueError("STT_PROVIDER/TTS_PROVIDER=openai needs OPENAI_API_KEY")
|
|
48
|
+
return self
|
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# playwright-e2e
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Para **probar el frontend de punta a punta en un navegador real sin backend ni Supabase**: Playwright compila la app en modo fake, la sirve con `vite preview` y recorre login, navegación y pantallas en escritorio y móvil. Corre en CI en cada push con un workflow incluido.
|
|
6
|
+
|
|
7
|
+
No cubre el e2e contra el stack real (backend + base de datos + Supabase local): los proyectos de origen lo tienen, cada uno con su arranque (uv + Postgres, docker compose + `supabase start`) y ninguno lo ejecuta en CI. Si lo necesitas, es otra configuración con `testDir: 'e2e-real'` y el mismo Playwright.
|
|
8
|
+
|
|
9
|
+
**Requiere `vite-react-base`, `react-supabase-auth` y `react-app-router`**: los specs entran con la cuenta del fake y navegan por las rutas de la receta. Sin auth, borra `login.spec.ts` y el login de `enter()`; sin router, borra `navigation.spec.ts`.
|
|
10
|
+
|
|
11
|
+
## Qué incluye
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
playwright.config.ts webServer: vite build --mode fake + vite preview; puerto derivado del cwd; proyectos desktop y phone; traza y captura solo al fallar
|
|
15
|
+
e2e/
|
|
16
|
+
helpers.ts DEMO (cuenta del fake) · enter(page, path) · failOnConsoleErrors(page)
|
|
17
|
+
home.spec.ts la home muestra los datos del fake sin errores de consola
|
|
18
|
+
login.spec.ts contraseña mal → mensaje; la sesión sobrevive a una recarga; salir la termina
|
|
19
|
+
navigation.spec.ts enlaces, atrás, deep link, 404 y vuelta; el login conserva la URL pedida
|
|
20
|
+
.github/workflows/frontend.yml npm ci → typecheck → test → build → playwright install chromium → e2e; informe como artefacto si falla
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Scripts que añade a `package.json`: `e2e`, `e2e:ui`, `e2e:install`.
|
|
24
|
+
|
|
25
|
+
## Decisiones
|
|
26
|
+
|
|
27
|
+
- **Contra la build en modo fake, no contra `vite dev`.** `vite build --mode fake` carga `.env.fake` (`VITE_API_MODE=fake`, `VITE_AUTH_PROVIDER=fake`) y `vite preview` sirve lo mismo que irá a producción, con fallback a `index.html` para los deep links. Así el e2e prueba el bundle real y no depende de red.
|
|
28
|
+
- **Puerto derivado del cwd** (`40000 + sha1(cwd) % 10000`): dos checkouts o worktrees pueden correr a la vez; `E2E_PORT` lo fija. `--host 127.0.0.1` porque `vite preview` sin `--host` escucha en `localhost`, que en Windows resuelve a IPv6 y Playwright esperaría para siempre.
|
|
29
|
+
- **Dos proyectos, escritorio y móvil:** el mismo spec corre en los dos; un layout que se rompe en 412 px se ve aquí.
|
|
30
|
+
- **Helpers como funciones, no page objects.** `enter(page)` hace el login con la cuenta del fake y un spec se lee de arriba abajo. Los selectores son de accesibilidad (`getByRole`, `getByLabel`), los mismos que usan los tests de Vitest.
|
|
31
|
+
- **Cualquier error de consola hace fallar el test** (`failOnConsoleErrors`): un warning de React o una promesa sin capturar no pasan desapercibidos.
|
|
32
|
+
- **Traza y captura solo al fallar, reintentos solo en CI.** El informe HTML se sube como artefacto si el job falla.
|
|
33
|
+
- **El e2e sí corre en CI.** Los proyectos de origen no lo ejecutan en cada push (como mucho, a mano contra el stack real). Como esta receta no necesita nada externo, no hay motivo para dejarlo fuera: dura menos de un minuto.
|
|
34
|
+
|
|
35
|
+
## Cómo adaptarla
|
|
36
|
+
|
|
37
|
+
1. Copia `files/` en la raíz del frontend (el workflow va en `.github/workflows/` del repo; ajusta `paths` y `working-directory` si el frontend no está en `frontend/`). Ejecuta `npm install -D @playwright/test@^1.65.1 && npx playwright install chromium`.
|
|
38
|
+
2. En `package.json` añade `"e2e": "playwright test"`, `"e2e:ui": "playwright test --ui"` y `"e2e:install": "playwright install chromium"`. En `tsconfig.json` incluye `"e2e"` y `"playwright.config.ts"` para que `typecheck` los cubra. En `.gitignore`: `e2e/.results`, `e2e/.report`, `dist-fake`.
|
|
39
|
+
3. **Un spec nuevo:** `e2e/<pantalla>.spec.ts` que empiece por `await enter(page, PATH)`. Si la pantalla necesita datos, dáselos al fake (`createFakeApi({...})` lee opciones; para escenarios por spec, guarda uno en `localStorage` con `page.addInitScript` antes de `goto` y que el fake lo lea al arrancar).
|
|
40
|
+
4. **Chat (`react-agent-chat`):** con la ruta `/chat` montada, un spec escribe en el `textbox`, pulsa Enter y espera el texto que emite `createFakeChatApi`; cancelar y "Nueva conversación" se prueban igual.
|
|
41
|
+
5. Para comprobarla: `npm run e2e` (10 tests, 5 por proyecto, ~35 s). `npm run e2e:ui` para verlos en el navegador.
|
|
42
|
+
|
|
43
|
+
**Dependencias:** `@playwright/test` (probado con 1.65.1 y Chromium 1255).
|
|
44
|
+
|
|
45
|
+
## Origen
|
|
46
|
+
|
|
47
|
+
- Probado en producción: `webServer` que compila en modo fake y sirve con `vite preview`, puerto derivado del cwd, proyectos escritorio y móvil, helpers como funciones, specs de login con contraseña mal, de sesión que sobrevive a la recarga y de rutas con `toHaveURL`; `trace: retain-on-failure`, captura solo al fallar, reintentos solo en CI, informe HTML como artefacto, errores de consola que hacen fallar el test, login por `getByLabel`.
|
|
48
|
+
- Nuevo en esta receta: e2e en modo fake dentro del CI de cada push y `--host 127.0.0.1`.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
name: frontend
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
paths: ['frontend/**']
|
|
6
|
+
pull_request:
|
|
7
|
+
paths: ['frontend/**']
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
check:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
defaults:
|
|
13
|
+
run:
|
|
14
|
+
working-directory: frontend
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: actions/setup-node@v4
|
|
18
|
+
with:
|
|
19
|
+
node-version: 24
|
|
20
|
+
cache: npm
|
|
21
|
+
cache-dependency-path: frontend/package-lock.json
|
|
22
|
+
- run: npm ci
|
|
23
|
+
- run: npm run typecheck
|
|
24
|
+
- run: npm test
|
|
25
|
+
- run: npm run build
|
|
26
|
+
- run: npx playwright install --with-deps chromium
|
|
27
|
+
- run: npm run e2e
|
|
28
|
+
- uses: actions/upload-artifact@v4
|
|
29
|
+
if: failure()
|
|
30
|
+
with:
|
|
31
|
+
name: playwright-report
|
|
32
|
+
path: |
|
|
33
|
+
frontend/e2e/.report
|
|
34
|
+
frontend/e2e/.results
|
|
35
|
+
retention-days: 7
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Shared steps. Plain functions, not page objects: a spec reads top to bottom. */
|
|
2
|
+
|
|
3
|
+
import { expect, type Page } from '@playwright/test'
|
|
4
|
+
|
|
5
|
+
/** The account of the fake auth (src/auth/fake-auth.ts). */
|
|
6
|
+
export const DEMO = { email: 'demo@example.com', password: 'demo' }
|
|
7
|
+
|
|
8
|
+
/** Opens `path` and signs in with the fake account. */
|
|
9
|
+
export async function enter(page: Page, path = '/') {
|
|
10
|
+
await page.goto(path)
|
|
11
|
+
await page.getByLabel('Correo').fill(DEMO.email)
|
|
12
|
+
await page.getByLabel('Contraseña').fill(DEMO.password)
|
|
13
|
+
await page.getByRole('button', { name: 'Entrar' }).click()
|
|
14
|
+
await expect(page.getByRole('heading', { name: 'Entrar' })).toBeHidden()
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Fails the test on any console error (a React warning, an unhandled rejection). */
|
|
18
|
+
export function failOnConsoleErrors(page: Page) {
|
|
19
|
+
const errors: string[] = []
|
|
20
|
+
page.on('console', (message) => {
|
|
21
|
+
if (message.type() === 'error') errors.push(message.text())
|
|
22
|
+
})
|
|
23
|
+
page.on('pageerror', (error) => errors.push(error.message))
|
|
24
|
+
return () => expect(errors, 'console errors').toEqual([])
|
|
25
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { expect, test } from '@playwright/test'
|
|
2
|
+
|
|
3
|
+
import { enter, failOnConsoleErrors } from './helpers'
|
|
4
|
+
|
|
5
|
+
test('the home shows the data of the fake api', async ({ page }) => {
|
|
6
|
+
const check = failOnConsoleErrors(page)
|
|
7
|
+
await enter(page)
|
|
8
|
+
await expect(page.getByRole('heading', { name: 'Hola, Demo User' })).toBeVisible()
|
|
9
|
+
check()
|
|
10
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { expect, test } from '@playwright/test'
|
|
2
|
+
|
|
3
|
+
import { DEMO, enter } from './helpers'
|
|
4
|
+
|
|
5
|
+
test('a wrong password shows a message and the right one gets in', async ({ page }) => {
|
|
6
|
+
await page.goto('/')
|
|
7
|
+
await page.getByLabel('Correo').fill(DEMO.email)
|
|
8
|
+
await page.getByLabel('Contraseña').fill('wrong')
|
|
9
|
+
await page.getByRole('button', { name: 'Entrar' }).click()
|
|
10
|
+
await expect(page.getByRole('alert')).toHaveText('No coinciden el correo y la contraseña')
|
|
11
|
+
|
|
12
|
+
await page.getByLabel('Contraseña').fill(DEMO.password)
|
|
13
|
+
await page.getByRole('button', { name: 'Entrar' }).click()
|
|
14
|
+
await expect(page.getByRole('heading', { name: 'Hola, Demo User' })).toBeVisible()
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
test('the session survives a reload and signing out ends it', async ({ page }) => {
|
|
18
|
+
await enter(page)
|
|
19
|
+
await page.reload()
|
|
20
|
+
await expect(page.getByRole('heading', { name: 'Hola, Demo User' })).toBeVisible()
|
|
21
|
+
|
|
22
|
+
await page.getByRole('button', { name: /^Salir/ }).click()
|
|
23
|
+
await expect(page.getByRole('heading', { name: 'Entrar' })).toBeVisible()
|
|
24
|
+
await page.reload()
|
|
25
|
+
await expect(page.getByRole('heading', { name: 'Entrar' })).toBeVisible()
|
|
26
|
+
})
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { expect, test } from '@playwright/test'
|
|
2
|
+
|
|
3
|
+
import { enter } from './helpers'
|
|
4
|
+
|
|
5
|
+
test('links, deep links and the 404 work with the browser history', async ({ page }) => {
|
|
6
|
+
await enter(page)
|
|
7
|
+
await page.getByRole('link', { name: 'Ajustes' }).click()
|
|
8
|
+
await expect(page).toHaveURL(/\/settings$/)
|
|
9
|
+
await expect(page.getByRole('heading', { name: 'Ajustes' })).toBeVisible()
|
|
10
|
+
|
|
11
|
+
await page.goBack()
|
|
12
|
+
await expect(page.getByRole('heading', { name: 'Hola, Demo User' })).toBeVisible()
|
|
13
|
+
|
|
14
|
+
await page.goto('/settings') // deep link: the server answers index.html for every path
|
|
15
|
+
await expect(page.getByRole('heading', { name: 'Ajustes' })).toBeVisible()
|
|
16
|
+
|
|
17
|
+
await page.goto('/nope')
|
|
18
|
+
await expect(page.getByRole('heading', { name: 'Página no encontrada' })).toBeVisible()
|
|
19
|
+
await page.getByRole('link', { name: 'Volver al inicio' }).click()
|
|
20
|
+
await expect(page.getByRole('heading', { name: 'Hola, Demo User' })).toBeVisible()
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
test('the login keeps the URL you asked for', async ({ page }) => {
|
|
24
|
+
await enter(page, '/settings')
|
|
25
|
+
await expect(page).toHaveURL(/\/settings$/)
|
|
26
|
+
await expect(page.getByRole('heading', { name: 'Ajustes' })).toBeVisible()
|
|
27
|
+
})
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* E2E against the app in fake mode: no backend, no Supabase, no network. Playwright builds the app with
|
|
3
|
+
* `--mode fake` (VITE_API_MODE=fake, VITE_AUTH_PROVIDER=fake) and serves it with `vite preview`.
|
|
4
|
+
* The port is derived from the checkout path, so two worktrees can run at once.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createHash } from 'node:crypto'
|
|
8
|
+
|
|
9
|
+
import { defineConfig, devices } from '@playwright/test'
|
|
10
|
+
|
|
11
|
+
const port = Number(process.env.E2E_PORT ?? 40000 + (parseInt(createHash('sha1').update(process.cwd()).digest('hex').slice(0, 8), 16) % 10000))
|
|
12
|
+
const ci = Boolean(process.env.CI)
|
|
13
|
+
|
|
14
|
+
export default defineConfig({
|
|
15
|
+
testDir: 'e2e',
|
|
16
|
+
outputDir: 'e2e/.results',
|
|
17
|
+
timeout: 30_000,
|
|
18
|
+
retries: ci ? 2 : 0,
|
|
19
|
+
reporter: ci ? [['list'], ['html', { open: 'never', outputFolder: 'e2e/.report' }]] : 'list',
|
|
20
|
+
use: {
|
|
21
|
+
baseURL: `http://127.0.0.1:${port}`,
|
|
22
|
+
trace: 'retain-on-failure',
|
|
23
|
+
screenshot: 'only-on-failure',
|
|
24
|
+
},
|
|
25
|
+
webServer: {
|
|
26
|
+
command: `vite build --mode fake --outDir dist-fake --emptyOutDir && vite preview --outDir dist-fake --host 127.0.0.1 --port ${port} --strictPort`,
|
|
27
|
+
url: `http://127.0.0.1:${port}`,
|
|
28
|
+
reuseExistingServer: false,
|
|
29
|
+
timeout: 120_000,
|
|
30
|
+
},
|
|
31
|
+
projects: [
|
|
32
|
+
{ name: 'desktop', use: { ...devices['Desktop Chrome'] } },
|
|
33
|
+
{ name: 'phone', use: { ...devices['Pixel 7'] } },
|
|
34
|
+
],
|
|
35
|
+
})
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# react-agent-chat
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Para la **interfaz de chat con un agente que responde en streaming** (SSE): tokens a medida que llegan, pasos de las tools, cancelar, errores y Markdown. Consume tal cual los eventos de la receta `langgraph-graph` servidos por `agent-chat-api`.
|
|
6
|
+
|
|
7
|
+
**Requiere `vite-react-base`**, copiada antes, porque usa su `HttpClient`, sus `TokenProvider` y sus variables de diseño.
|
|
8
|
+
|
|
9
|
+
## Qué incluye
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
src/features/chat/
|
|
13
|
+
events.ts ChatEvent: unión tipada del contrato (token, tool_start, tool_end, routing, error, done{answer, conversation_id, message_id})
|
|
14
|
+
sse-parser.ts SseParser + readSse(stream): SSE sobre fetch
|
|
15
|
+
chat-api.ts type ChatApi + createHttpChatApi(client): POST /agent/stream
|
|
16
|
+
fake-chat-api.ts createFakeChatApi(): emite los mismos eventos, sin backend
|
|
17
|
+
use-chat.ts useChat(chat): estado del chat (mensajes, pasos, borrador, cancelar, nueva conversación)
|
|
18
|
+
components/
|
|
19
|
+
ChatView.tsx el chat completo; recibe su ChatApi desde fuera
|
|
20
|
+
MessageList.tsx mensajes, pasos de tools, estados y autoscroll
|
|
21
|
+
Composer.tsx Enter envía, Shift+Enter hace salto de línea; mientras responde, el botón detiene
|
|
22
|
+
Markdown.tsx react-markdown + remark-gfm (sin HTML crudo)
|
|
23
|
+
chat.css solo usa las variables de vite-react-base
|
|
24
|
+
index.ts
|
|
25
|
+
sse-parser.test.ts 9 tests: chunks cortados, CRLF, multilínea, pings, JSON inválido, eventos terminales, UTF-8 partido
|
|
26
|
+
chat.test.tsx 8 tests: streaming, conversation_id estable, error_id, stream cortado, cancelar, HTML, nueva conversación, HTTP
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Decisiones
|
|
30
|
+
|
|
31
|
+
- **`fetch` POST + `body.getReader()`, nunca `EventSource`.** `EventSource` solo hace GET y no admite cabecera `Authorization`.
|
|
32
|
+
- **Parser robusto.** Partimos de un parser probado en producción y añadimos lo que no trataba ningún proyecto de origen:
|
|
33
|
+
- Guarda en un buffer la línea cortada entre chunks.
|
|
34
|
+
- Acepta CRLF, que es lo que envía sse-starlette, y `data:` con o sin espacio.
|
|
35
|
+
- Une las líneas de `data:` multilínea con `\n`, como dice la especificación.
|
|
36
|
+
- Ignora comentarios, pings, `id:`, `retry:`, el JSON inválido y los eventos desconocidos.
|
|
37
|
+
- `error` y `done` cierran el stream.
|
|
38
|
+
- **Mismo patrón de dos implementaciones que la base:** `ChatApi` es el tipo, y la versión HTTP y la falsa lo cumplen. El fake emite la misma secuencia que el backend real.
|
|
39
|
+
- **Estado del chat.**
|
|
40
|
+
- Mensaje del asistente vacío desde el principio, porque `tool_start` puede llegar antes que el primer token. Los tools van como pasos con estado (`running`, `done`, `error`), y los que siguen abiertos al terminar pasan a `error`.
|
|
41
|
+
- Si el stream termina sin `done`, se trata como un fallo.
|
|
42
|
+
- Un error enseña el `error_id` del backend, nunca el detalle.
|
|
43
|
+
- Si falla, la pregunta vuelve al borrador. Cancelar no se considera un error.
|
|
44
|
+
- **El cliente genera el `conversation_id`**, uno por conversación. Coincide con `MemoryKey.conversation_id` de `agent-memory`, y el tenant y el usuario salen del token en el backend.
|
|
45
|
+
- **Markdown seguro.** react-markdown crea elementos de React, así que el HTML que venga en la respuesta se muestra como texto. Un `<script>` inyectado en la respuesta del agente no se ejecuta, y hay un test que lo comprueba.
|
|
46
|
+
|
|
47
|
+
## Cómo adaptarla
|
|
48
|
+
|
|
49
|
+
1. Copia `files/` encima del frontend de `vite-react-base` y ejecuta `npm install react-markdown@^10.1.0 remark-gfm@^4.0.1`.
|
|
50
|
+
2. **Conéctalo en `main.tsx`.** El chat sigue el mismo `VITE_API_MODE` que el resto:
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
import { createHttpClient } from './api/http-client'
|
|
54
|
+
import { ChatView, createFakeChatApi, createHttpChatApi } from './features/chat'
|
|
55
|
+
|
|
56
|
+
const chat = CONFIG.apiMode === 'fake'
|
|
57
|
+
? createFakeChatApi()
|
|
58
|
+
: createHttpChatApi(createHttpClient({ baseUrl: CONFIG.apiUrl, tokens, onSessionExpired }))
|
|
59
|
+
// y en el render: <ChatView chat={chat} />
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
3. **El endpoint del backend** está en `createHttpChatApi(client, path)` (por defecto `/agent/stream`), con el cuerpo `{question, conversation_id}`. Es el contrato de la receta `agent-chat-api`. El `done` trae `message_id`, el id de la respuesta guardada, que es lo que se envía al votar.
|
|
63
|
+
4. **Un evento nuevo:** añádelo en `ChatEvent` y `toChatEvent` (`events.ts`), trátalo en el `switch` de `use-chat.ts` y emítelo también en el fake. Cambia el `events.py` del backend al mismo tiempo.
|
|
64
|
+
5. Para comprobarlo: `npm run typecheck && npm test` (40 tests junto con la base).
|
|
65
|
+
|
|
66
|
+
## Origen
|
|
67
|
+
|
|
68
|
+
- Probado en producción: streaming con fetch POST + reader, buffer de líneas, `token`/`tool_start`/`tool_end`/`error`/`done`, mensaje del asistente vacío al principio y pasos con estado; CRLF, pings y eventos desconocidos ignorados, un stream sin `done` como fallo y el error solo en los logs; `AbortController` por envío, restaurar el borrador y `conversation_id` generado por el cliente.
|
|
69
|
+
- Nuevo en esta receta: `data:` multilínea, `error_id` en la interfaz y el test de HTML.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chat port: what the chat UI needs from the backend. Two implementations, same type:
|
|
3
|
+
* `createHttpChatApi` (POST + SSE against the `langgraph-graph` endpoint) and `createFakeChatApi`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { HttpClient } from '../../api/http-client'
|
|
7
|
+
import type { ChatEvent } from './events'
|
|
8
|
+
import { readSse } from './sse-parser'
|
|
9
|
+
|
|
10
|
+
export type ChatRequest = {
|
|
11
|
+
question: string
|
|
12
|
+
/** Generated by the client (one per conversation). The backend keys memory by tenant + user + this id. */
|
|
13
|
+
conversationId: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type ChatApi = {
|
|
17
|
+
streamAnswer(request: ChatRequest, signal?: AbortSignal): AsyncIterable<ChatEvent>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createHttpChatApi(client: HttpClient, path = '/agent/stream'): ChatApi {
|
|
21
|
+
return {
|
|
22
|
+
async *streamAnswer(request, signal) {
|
|
23
|
+
const body = { question: request.question, conversation_id: request.conversationId }
|
|
24
|
+
yield* readSse(await client.stream(path, body, signal))
|
|
25
|
+
},
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/* Uses only the tokens of the vite-react-base recipe (styles/tokens.css). */
|
|
2
|
+
.chat { display: flex; flex-direction: column; gap: var(--space-3); min-height: 70vh; }
|
|
3
|
+
.chat-header { display: flex; justify-content: flex-end; }
|
|
4
|
+
.chat-messages { list-style: none; margin: 0; padding: 0; flex: 1; display: flex; flex-direction: column; gap: var(--space-3); overflow-y: auto; }
|
|
5
|
+
.chat-message { max-width: 85%; padding: var(--space-2) var(--space-3); border-radius: var(--radius); border: 1px solid var(--color-border); }
|
|
6
|
+
.chat-message--user { align-self: flex-end; background: var(--color-surface); }
|
|
7
|
+
.chat-message--assistant { align-self: flex-start; background: var(--color-bg); }
|
|
8
|
+
.chat-message p { margin: 0; }
|
|
9
|
+
.chat-steps { list-style: none; margin: 0 0 var(--space-2); padding: 0; font-size: 0.85em; color: var(--color-muted); font-family: var(--font-mono); }
|
|
10
|
+
.chat-steps [data-status='error'] { color: var(--color-danger); }
|
|
11
|
+
.chat-error { color: var(--color-danger); }
|
|
12
|
+
.chat-composer { display: flex; gap: var(--space-2); align-items: flex-end; }
|
|
13
|
+
.chat-composer textarea { flex: 1; font: inherit; resize: vertical; padding: var(--space-2); border-radius: var(--radius); border: 1px solid var(--color-border); background: var(--color-bg); color: var(--color-text); }
|
|
14
|
+
.button.button--ghost { background: transparent; color: var(--color-primary); border: 1px solid var(--color-border); }
|
|
15
|
+
.markdown > :first-child { margin-top: 0; }
|
|
16
|
+
.markdown > :last-child { margin-bottom: 0; }
|
|
17
|
+
.markdown pre { overflow-x: auto; background: var(--color-surface); padding: var(--space-2); border-radius: var(--radius); }
|
|
18
|
+
.markdown code { font-family: var(--font-mono); }
|