@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.
Files changed (255) hide show
  1. package/README.md +227 -2
  2. package/catalog.yaml +140 -0
  3. package/cli/copypasta.js +4 -0
  4. package/cli/lib/catalog.js +131 -0
  5. package/cli/lib/commands.js +162 -0
  6. package/cli/lib/index.js +4 -0
  7. package/cli/lib/main.js +130 -0
  8. package/package.json +38 -4
  9. package/recipes/agents/agent-memory/RECIPE.md +75 -0
  10. package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
  11. package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
  12. package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
  13. package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
  14. package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
  15. package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
  16. package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
  17. package/recipes/agents/agent-memory/files/pytest.ini +5 -0
  18. package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
  19. package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
  20. package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
  21. package/recipes/agents/langchain-agent/RECIPE.md +101 -0
  22. package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
  23. package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
  24. package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
  25. package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
  26. package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
  27. package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
  28. package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
  29. package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
  30. package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
  31. package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
  32. package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
  33. package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
  34. package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
  35. package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
  36. package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
  37. package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
  38. package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
  39. package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
  40. package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
  41. package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
  42. package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
  43. package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
  44. package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
  45. package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
  46. package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
  47. package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
  48. package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
  49. package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
  50. package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
  51. package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
  52. package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
  53. package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
  54. package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
  55. package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
  56. package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
  57. package/recipes/backend/.gitkeep +0 -0
  58. package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
  59. package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
  60. package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
  61. package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
  62. package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
  63. package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
  64. package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
  65. package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
  66. package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
  67. package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
  68. package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
  69. package/recipes/backend/agent-feedback/RECIPE.md +63 -0
  70. package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
  71. package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
  72. package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
  73. package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
  74. package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
  75. package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
  76. package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
  77. package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
  78. package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
  79. package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
  80. package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
  81. package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
  82. package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
  83. package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
  84. package/recipes/backend/auth-verifier/RECIPE.md +63 -0
  85. package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
  86. package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
  87. package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
  88. package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
  89. package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
  90. package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
  91. package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
  92. package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
  93. package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
  94. package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
  95. package/recipes/backend/conversation-history/RECIPE.md +49 -0
  96. package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
  97. package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
  98. package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
  99. package/recipes/backend/conversation-history/files/pytest.ini +5 -0
  100. package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
  101. package/recipes/backend/fastapi-base/RECIPE.md +57 -0
  102. package/recipes/backend/fastapi-base/files/api/app.py +37 -0
  103. package/recipes/backend/fastapi-base/files/api/base.py +54 -0
  104. package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
  105. package/recipes/backend/fastapi-base/files/api/health.py +19 -0
  106. package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
  107. package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
  108. package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
  109. package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
  110. package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
  111. package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
  112. package/recipes/backend/observability/RECIPE.md +68 -0
  113. package/recipes/backend/observability/files/observability/__init__.py +34 -0
  114. package/recipes/backend/observability/files/observability/factory.py +73 -0
  115. package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
  116. package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
  117. package/recipes/backend/observability/files/observability/models.py +90 -0
  118. package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
  119. package/recipes/backend/observability/files/observability/settings.py +58 -0
  120. package/recipes/backend/observability/files/observability/tracer.py +142 -0
  121. package/recipes/backend/observability/files/observability/usage.py +61 -0
  122. package/recipes/backend/observability/files/pytest.ini +5 -0
  123. package/recipes/backend/observability/files/tests/__init__.py +0 -0
  124. package/recipes/backend/observability/files/tests/test_observability.py +219 -0
  125. package/recipes/backend/project-settings/RECIPE.md +40 -0
  126. package/recipes/backend/project-settings/files/.env.example +7 -0
  127. package/recipes/backend/project-settings/files/core/__init__.py +0 -0
  128. package/recipes/backend/project-settings/files/core/config.py +41 -0
  129. package/recipes/backend/project-settings/files/pytest.ini +3 -0
  130. package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
  131. package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
  132. package/recipes/backend/rag-retriever/RECIPE.md +79 -0
  133. package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
  134. package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
  135. package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
  136. package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
  137. package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
  138. package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
  139. package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
  140. package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
  141. package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
  142. package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
  143. package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
  144. package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
  145. package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
  146. package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
  147. package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
  148. package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
  149. package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
  150. package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
  151. package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
  152. package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
  153. package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
  154. package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
  155. package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
  156. package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
  157. package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
  158. package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
  159. package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
  160. package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
  161. package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
  162. package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
  163. package/recipes/backend/voice-providers/RECIPE.md +73 -0
  164. package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
  165. package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
  166. package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
  167. package/recipes/backend/voice-providers/files/pytest.ini +5 -0
  168. package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
  169. package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
  170. package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
  171. package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
  172. package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
  173. package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
  174. package/recipes/backend/voice-providers/files/voice/base.py +116 -0
  175. package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
  176. package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
  177. package/recipes/backend/voice-providers/files/voice/models.py +85 -0
  178. package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
  179. package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
  180. package/recipes/frontend/.gitkeep +0 -0
  181. package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
  182. package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
  183. package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
  184. package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
  185. package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
  186. package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
  187. package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
  188. package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
  189. package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
  190. package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
  191. package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
  192. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
  193. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
  194. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
  195. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
  196. package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
  197. package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
  198. package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
  199. package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
  200. package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
  201. package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
  202. package/recipes/frontend/react-app-router/RECIPE.md +58 -0
  203. package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
  204. package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
  205. package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
  206. package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
  207. package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
  208. package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
  209. package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
  210. package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
  211. package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
  212. package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
  213. package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
  214. package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
  215. package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
  216. package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
  217. package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
  218. package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
  219. package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
  220. package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
  221. package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
  222. package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
  223. package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
  224. package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
  225. package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
  226. package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
  227. package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
  228. package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
  229. package/recipes/frontend/vite-react-base/files/.env +6 -0
  230. package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
  231. package/recipes/frontend/vite-react-base/files/index.html +12 -0
  232. package/recipes/frontend/vite-react-base/files/package.json +30 -0
  233. package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
  234. package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
  235. package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
  236. package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
  237. package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
  238. package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
  239. package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
  240. package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
  241. package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
  242. package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
  243. package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
  244. package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
  245. package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
  246. package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
  247. package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
  248. package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
  249. package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
  250. package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
  251. package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
  252. package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
  253. package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
  254. package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
  255. package/unpacked-files.json +3 -0
@@ -0,0 +1,139 @@
1
+ import { render, screen, waitFor } from '@testing-library/react'
2
+ import userEvent from '@testing-library/user-event'
3
+ import { describe, expect, it, vi } from 'vitest'
4
+
5
+ import { createHttpClient } from '../../api/http-client'
6
+ import { staticToken } from '../../auth/token-provider'
7
+ import { createHttpChatApi, type ChatApi } from './chat-api'
8
+ import { ChatView } from './components/ChatView'
9
+ import type { ChatEvent } from './events'
10
+ import { createFakeChatApi } from './fake-chat-api'
11
+
12
+ /** A ChatApi that plays a fixed list of events. */
13
+ function scripted(events: ChatEvent[], options: { hangAfter?: boolean } = {}): ChatApi {
14
+ return {
15
+ async *streamAnswer(_request, signal) {
16
+ for (const event of events) yield event
17
+ if (options.hangAfter) {
18
+ await new Promise((_, reject) =>
19
+ signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))),
20
+ )
21
+ }
22
+ },
23
+ }
24
+ }
25
+
26
+ const typeAndSend = async (text: string) => {
27
+ await userEvent.type(screen.getByLabelText('Mensaje'), text)
28
+ await userEvent.click(screen.getByRole('button', { name: 'Enviar' }))
29
+ }
30
+
31
+ describe('ChatView', () => {
32
+ it('streams tokens into the assistant message and closes tool steps', async () => {
33
+ render(<ChatView chat={createFakeChatApi({ stepMs: 0, reply: () => 'Hola **mundo**' })} />)
34
+
35
+ await typeAndSend('hola')
36
+
37
+ await waitFor(() => expect(screen.getByText('mundo').tagName).toBe('STRONG'))
38
+ expect(screen.getByText('hola')).toBeTruthy()
39
+ expect(screen.getByLabelText('Herramientas').textContent).toContain('✓ search_documents')
40
+ expect(screen.getByRole('button', { name: 'Enviar' })).toBeTruthy()
41
+ })
42
+
43
+ it('sends question and the same conversation id on every turn', async () => {
44
+ const calls: { question: string; conversationId: string }[] = []
45
+ const chat: ChatApi = {
46
+ async *streamAnswer(request) {
47
+ calls.push(request)
48
+ yield { type: 'done', answer: 'ok' }
49
+ },
50
+ }
51
+ render(<ChatView chat={chat} />)
52
+
53
+ await typeAndSend('uno')
54
+ await screen.findByText('ok')
55
+ await typeAndSend('dos')
56
+ await waitFor(() => expect(calls).toHaveLength(2))
57
+
58
+ expect(calls.map((c) => c.question)).toEqual(['uno', 'dos'])
59
+ expect(calls[0].conversationId).toBe(calls[1].conversationId)
60
+ })
61
+
62
+ it('shows the error id and puts the question back in the draft', async () => {
63
+ render(<ChatView chat={scripted([{ type: 'tool_start', tool: 'search' }, { type: 'error', errorId: 'err-42' }])} />)
64
+
65
+ await typeAndSend('pregunta')
66
+
67
+ expect((await screen.findByRole('alert')).textContent).toContain('err-42')
68
+ expect((screen.getByLabelText('Mensaje') as HTMLTextAreaElement).value).toBe('pregunta')
69
+ expect(screen.getByLabelText('Herramientas').textContent).toContain('✕ search')
70
+ })
71
+
72
+ it('treats a stream that ends without done as a failure', async () => {
73
+ render(<ChatView chat={scripted([{ type: 'token', text: 'a medias' }])} />)
74
+
75
+ await typeAndSend('x')
76
+
77
+ expect(await screen.findByRole('alert')).toBeTruthy()
78
+ })
79
+
80
+ it('cancels without showing an error', async () => {
81
+ render(<ChatView chat={scripted([{ type: 'token', text: 'empiezo' }], { hangAfter: true })} />)
82
+
83
+ await typeAndSend('x')
84
+ await screen.findByText('empiezo')
85
+ await userEvent.click(screen.getByRole('button', { name: 'Detener' }))
86
+
87
+ expect(await screen.findByText('Respuesta cancelada.')).toBeTruthy()
88
+ expect(screen.queryByRole('alert')).toBeNull()
89
+ })
90
+
91
+ it('does not run raw HTML coming from the agent', async () => {
92
+ render(<ChatView chat={scripted([{ type: 'token', text: '<img src=x onerror="alert(1)">' }, { type: 'done', answer: '' }])} />)
93
+
94
+ await typeAndSend('x')
95
+
96
+ await screen.findByText(/onerror/)
97
+ expect(document.querySelector('img')).toBeNull()
98
+ })
99
+
100
+ it('new conversation clears messages and changes the id', async () => {
101
+ const ids: string[] = []
102
+ const chat: ChatApi = {
103
+ async *streamAnswer(request) {
104
+ ids.push(request.conversationId)
105
+ yield { type: 'done', answer: 'ok' }
106
+ },
107
+ }
108
+ render(<ChatView chat={chat} />)
109
+ await typeAndSend('uno')
110
+ await screen.findByText('ok')
111
+
112
+ await userEvent.click(screen.getByRole('button', { name: 'Nueva conversación' }))
113
+ expect(screen.queryByText('ok')).toBeNull()
114
+ await typeAndSend('dos')
115
+ await waitFor(() => expect(ids).toHaveLength(2))
116
+
117
+ expect(ids[0]).not.toBe(ids[1])
118
+ })
119
+ })
120
+
121
+ describe('createHttpChatApi', () => {
122
+ it('POSTs with bearer and snake_case body and parses the SSE answer', async () => {
123
+ const sse = 'event: token\r\ndata: {"text":"hi"}\r\n\r\nevent: done\r\ndata: {"answer":"hi"}\r\n\r\n'
124
+ const fetcher = vi.fn<typeof fetch>(async () => new Response(sse, { headers: { 'Content-Type': 'text/event-stream' } }))
125
+ const chat = createHttpChatApi(createHttpClient({ baseUrl: '/api', tokens: staticToken('tok'), fetcher }))
126
+
127
+ const events = []
128
+ for await (const event of chat.streamAnswer({ question: 'q', conversationId: 'c1' })) events.push(event)
129
+
130
+ expect(events).toEqual([
131
+ { type: 'token', text: 'hi' },
132
+ { type: 'done', answer: 'hi' },
133
+ ])
134
+ const [url, init] = fetcher.mock.calls[0]
135
+ expect(url).toBe('/api/agent/stream')
136
+ expect(JSON.parse(init!.body as string)).toEqual({ question: 'q', conversation_id: 'c1' })
137
+ expect((init!.headers as Record<string, string>).Authorization).toBe('Bearer tok')
138
+ })
139
+ })
@@ -0,0 +1,22 @@
1
+ import type { ChatApi } from '../chat-api'
2
+ import { useChat } from '../use-chat'
3
+ import { Composer } from './Composer'
4
+ import { MessageList } from './MessageList'
5
+ import '../chat.css'
6
+
7
+ /** The whole chat. Receives its `ChatApi` from outside (real or fake), like every screen. */
8
+ export function ChatView({ chat }: { chat: ChatApi }) {
9
+ const { messages, draft, setDraft, sending, send, cancel, newConversation } = useChat(chat)
10
+
11
+ return (
12
+ <section className="chat">
13
+ <header className="chat-header">
14
+ <button className="button button--ghost" onClick={newConversation} disabled={messages.length === 0}>
15
+ Nueva conversación
16
+ </button>
17
+ </header>
18
+ <MessageList messages={messages} />
19
+ <Composer draft={draft} onDraft={setDraft} onSend={() => void send()} onCancel={cancel} sending={sending} />
20
+ </section>
21
+ )
22
+ }
@@ -0,0 +1,40 @@
1
+ import type { FormEvent, KeyboardEvent } from 'react'
2
+
3
+ type Props = {
4
+ draft: string
5
+ onDraft: (text: string) => void
6
+ onSend: () => void
7
+ onCancel: () => void
8
+ sending: boolean
9
+ }
10
+
11
+ /** Enter sends, Shift+Enter is a new line. While streaming, the button cancels. */
12
+ export function Composer({ draft, onDraft, onSend, onCancel, sending }: Props) {
13
+ const submit = (event: FormEvent) => {
14
+ event.preventDefault()
15
+ if (sending) onCancel()
16
+ else onSend()
17
+ }
18
+ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
19
+ if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
20
+ event.preventDefault()
21
+ if (!sending) onSend()
22
+ }
23
+ }
24
+
25
+ return (
26
+ <form className="chat-composer" onSubmit={submit}>
27
+ <textarea
28
+ aria-label="Mensaje"
29
+ rows={2}
30
+ value={draft}
31
+ onChange={(event) => onDraft(event.target.value)}
32
+ onKeyDown={onKeyDown}
33
+ placeholder="Escribe tu pregunta…"
34
+ />
35
+ <button className="button" type="submit" disabled={!sending && !draft.trim()}>
36
+ {sending ? 'Detener' : 'Enviar'}
37
+ </button>
38
+ </form>
39
+ )
40
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Agent answers are Markdown. react-markdown builds React elements (no innerHTML): raw HTML in the
3
+ * answer is shown as text, so a prompt-injected <script> cannot run. Links open in a new tab.
4
+ */
5
+
6
+ import ReactMarkdown from 'react-markdown'
7
+ import remarkGfm from 'remark-gfm'
8
+
9
+ export function Markdown({ text }: { text: string }) {
10
+ return (
11
+ <div className="markdown">
12
+ <ReactMarkdown
13
+ remarkPlugins={[remarkGfm]}
14
+ components={{ a: ({ node: _node, ...props }) => <a {...props} target="_blank" rel="noreferrer noopener" /> }}
15
+ >
16
+ {text}
17
+ </ReactMarkdown>
18
+ </div>
19
+ )
20
+ }
@@ -0,0 +1,42 @@
1
+ import { useEffect, useRef } from 'react'
2
+
3
+ import type { ChatMessage, Step } from '../use-chat'
4
+ import { Markdown } from './Markdown'
5
+
6
+ const STEP_LABEL: Record<Step['status'], string> = { running: '…', done: '✓', error: '✕' }
7
+
8
+ export function MessageList({ messages }: { messages: ChatMessage[] }) {
9
+ const bottom = useRef<HTMLDivElement>(null)
10
+
11
+ // Follow the answer while it streams. (jsdom has no scrollIntoView, hence the ?.)
12
+ useEffect(() => {
13
+ bottom.current?.scrollIntoView?.({ block: 'end' })
14
+ }, [messages])
15
+
16
+ return (
17
+ <ol className="chat-messages" aria-live="polite">
18
+ {messages.map((message) => (
19
+ <li key={message.id} className={`chat-message chat-message--${message.role}`} data-status={message.status}>
20
+ {message.steps.length > 0 && (
21
+ <ul className="chat-steps" aria-label="Herramientas">
22
+ {message.steps.map((step) => (
23
+ <li key={step.id} data-status={step.status}>
24
+ {STEP_LABEL[step.status]} {step.tool}
25
+ </li>
26
+ ))}
27
+ </ul>
28
+ )}
29
+ {message.role === 'assistant' ? <Markdown text={message.content} /> : <p>{message.content}</p>}
30
+ {message.status === 'streaming' && !message.content && <p className="muted">Pensando…</p>}
31
+ {message.status === 'cancelled' && <p className="muted">Respuesta cancelada.</p>}
32
+ {message.status === 'error' && (
33
+ <p role="alert" className="chat-error">
34
+ No se ha podido responder.{message.errorId && ` Referencia: ${message.errorId}`}
35
+ </p>
36
+ )}
37
+ </li>
38
+ ))}
39
+ <div ref={bottom} />
40
+ </ol>
41
+ )
42
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Events of the agent stream: the frontend side of the contract in the `langgraph-graph` recipe
3
+ * (agentic/graph/events.py). Change both at once.
4
+ */
5
+
6
+ export type ChatEvent =
7
+ | { type: 'token'; text: string }
8
+ | { type: 'tool_start'; tool: string }
9
+ | { type: 'tool_end'; tool: string }
10
+ | { type: 'routing'; data: Record<string, unknown> }
11
+ | { type: 'error'; errorId?: string }
12
+ | { type: 'done'; answer: string; conversationId?: string; messageId?: string }
13
+
14
+ type Raw = Record<string, unknown>
15
+
16
+ const str = (value: unknown): value is string => typeof value === 'string'
17
+
18
+ /** Raw SSE `event` + parsed `data` -> typed event. Unknown events or bad payloads -> null (ignored). */
19
+ export function toChatEvent(event: string, data: unknown): ChatEvent | null {
20
+ if (typeof data !== 'object' || data === null) return null
21
+ const raw = data as Raw
22
+ switch (event) {
23
+ case 'token':
24
+ return str(raw.text) ? { type: 'token', text: raw.text } : null
25
+ case 'tool_start':
26
+ case 'tool_end':
27
+ return str(raw.tool) ? { type: event, tool: raw.tool } : null
28
+ case 'routing':
29
+ return { type: 'routing', data: raw }
30
+ case 'error':
31
+ return { type: 'error', errorId: str(raw.error_id) ? raw.error_id : undefined }
32
+ case 'done':
33
+ return {
34
+ type: 'done',
35
+ answer: str(raw.answer) ? raw.answer : '',
36
+ conversationId: str(raw.conversation_id) ? raw.conversation_id : undefined,
37
+ messageId: str(raw.message_id) ? raw.message_id : undefined,
38
+ }
39
+ default:
40
+ return null
41
+ }
42
+ }
@@ -0,0 +1,44 @@
1
+ /** Fake agent: emits the same events as the real stream (routing, a tool, tokens, done). No backend needed. */
2
+
3
+ import type { ChatApi } from './chat-api'
4
+ import type { ChatEvent } from './events'
5
+
6
+ export type FakeChatOptions = {
7
+ /** Delay between events in ms. 0 in tests. */
8
+ stepMs?: number
9
+ reply?: (question: string) => string
10
+ /** Tool to show as a step, or null for none. */
11
+ tool?: string | null
12
+ }
13
+
14
+ export function createFakeChatApi(options: FakeChatOptions = {}): ChatApi {
15
+ const { stepMs = 40, reply = (q) => `Has preguntado: **${q}**`, tool = 'search_documents' } = options
16
+
17
+ const sleep = (signal?: AbortSignal) =>
18
+ new Promise<void>((resolve, reject) => {
19
+ if (signal?.aborted) return reject(new DOMException('aborted', 'AbortError'))
20
+ const timer = setTimeout(resolve, stepMs)
21
+ signal?.addEventListener('abort', () => {
22
+ clearTimeout(timer)
23
+ reject(new DOMException('aborted', 'AbortError'))
24
+ })
25
+ })
26
+
27
+ return {
28
+ async *streamAnswer({ question }, signal): AsyncGenerator<ChatEvent> {
29
+ const answer = reply(question)
30
+ yield { type: 'routing', data: { category: 'technical' } }
31
+ if (tool) {
32
+ await sleep(signal)
33
+ yield { type: 'tool_start', tool }
34
+ await sleep(signal)
35
+ yield { type: 'tool_end', tool }
36
+ }
37
+ for (const word of answer.split(/(?<= )/)) {
38
+ await sleep(signal)
39
+ yield { type: 'token', text: word }
40
+ }
41
+ yield { type: 'done', answer }
42
+ },
43
+ }
44
+ }
@@ -0,0 +1,6 @@
1
+ export type { ChatApi, ChatRequest } from './chat-api'
2
+ export { createHttpChatApi } from './chat-api'
3
+ export { ChatView } from './components/ChatView'
4
+ export type { ChatEvent } from './events'
5
+ export { createFakeChatApi } from './fake-chat-api'
6
+ export { useChat, type ChatMessage, type Step } from './use-chat'
@@ -0,0 +1,97 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { readSse, SseParser } from './sse-parser'
4
+
5
+ const enc = new TextEncoder()
6
+
7
+ function streamOf(chunks: string[]): ReadableStream<Uint8Array> {
8
+ return new ReadableStream({
9
+ start(controller) {
10
+ for (const chunk of chunks) controller.enqueue(enc.encode(chunk))
11
+ controller.close()
12
+ },
13
+ })
14
+ }
15
+
16
+ async function collect(chunks: string[]) {
17
+ const events = []
18
+ for await (const event of readSse(streamOf(chunks))) events.push(event)
19
+ return events
20
+ }
21
+
22
+ describe('SseParser', () => {
23
+ it('parses event + data framed by a blank line', () => {
24
+ const parser = new SseParser()
25
+ expect(parser.push('event: token\ndata: {"text": "Hola"}\n\n')).toEqual([{ type: 'token', text: 'Hola' }])
26
+ })
27
+
28
+ it('keeps a line cut between chunks, even inside the JSON', () => {
29
+ const parser = new SseParser()
30
+ expect(parser.push('event: tok')).toEqual([])
31
+ expect(parser.push('en\ndata: {"te')).toEqual([])
32
+ expect(parser.push('xt": "a b"}\n\n')).toEqual([{ type: 'token', text: 'a b' }])
33
+ })
34
+
35
+ it('accepts CRLF (sse-starlette) and data without a space', () => {
36
+ const parser = new SseParser()
37
+ expect(parser.push('event: tool_start\r\ndata:{"tool":"search"}\r\n\r\n')).toEqual([
38
+ { type: 'tool_start', tool: 'search' },
39
+ ])
40
+ })
41
+
42
+ it('joins multi-line data with \\n', () => {
43
+ const parser = new SseParser()
44
+ expect(parser.push('event: done\ndata: {"answer":\ndata: "x"}\n\n')).toEqual([{ type: 'done', answer: 'x' }])
45
+ })
46
+
47
+ it('ignores comments, pings, id/retry, unknown events and bad JSON', () => {
48
+ const parser = new SseParser()
49
+ const events = parser.push(
50
+ ': ping\n\nid: 1\nretry: 100\n\nevent: weird\ndata: {"a":1}\n\nevent: token\ndata: {not json\n\nevent: token\ndata: {"text":"ok"}\n\n',
51
+ )
52
+ expect(events).toEqual([{ type: 'token', text: 'ok' }])
53
+ })
54
+
55
+ it('maps error and done payloads', () => {
56
+ const parser = new SseParser()
57
+ expect(parser.push('event: error\ndata: {"error_id":"e-1"}\n\nevent: done\ndata: {"answer":"fin"}\n\n')).toEqual([
58
+ { type: 'error', errorId: 'e-1' },
59
+ { type: 'done', answer: 'fin' },
60
+ ])
61
+ })
62
+
63
+ it('flushes a last event without trailing blank line', () => {
64
+ const parser = new SseParser()
65
+ expect(parser.push('event: done\ndata: {"answer":"x"}')).toEqual([])
66
+ expect(parser.flush()).toEqual([{ type: 'done', answer: 'x' }])
67
+ })
68
+ })
69
+
70
+ describe('readSse', () => {
71
+ it('reads a stream split at arbitrary byte boundaries', async () => {
72
+ const body = 'event: routing\ndata: {"category":"billing"}\n\nevent: token\ndata: {"text":"ñandú "}\n\nevent: done\ndata: {"answer":"ñandú"}\n\n'
73
+ const bytes = enc.encode(body)
74
+ const chunks: Uint8Array[] = []
75
+ for (let i = 0; i < bytes.length; i += 3) chunks.push(bytes.slice(i, i + 3)) // splits the ñ in half
76
+ const stream = new ReadableStream<Uint8Array>({
77
+ start(controller) {
78
+ chunks.forEach((c) => controller.enqueue(c))
79
+ controller.close()
80
+ },
81
+ })
82
+
83
+ const events = []
84
+ for await (const event of readSse(stream)) events.push(event)
85
+
86
+ expect(events).toEqual([
87
+ { type: 'routing', data: { category: 'billing' } },
88
+ { type: 'token', text: 'ñandú ' },
89
+ { type: 'done', answer: 'ñandú' },
90
+ ])
91
+ })
92
+
93
+ it('stops after a terminal event', async () => {
94
+ const events = await collect(['event: error\ndata: {}\n\nevent: token\ndata: {"text":"late"}\n\n'])
95
+ expect(events).toEqual([{ type: 'error', errorId: undefined }])
96
+ })
97
+ })
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Server-Sent Events over `fetch` (not EventSource: it only does GET and cannot send Authorization).
3
+ *
4
+ * - Chunks may cut a line or a JSON payload in half: the partial line stays in the buffer.
5
+ * - CRLF and LF line endings (sse-starlette sends CRLF).
6
+ * - `data:` with or without a space; several `data:` lines are joined with "\n" (SSE spec).
7
+ * - Comments (`: ping`), `id:` and `retry:` are ignored. Bad JSON and unknown events are ignored.
8
+ * - `error` and `done` are terminal: the reader is cancelled after them.
9
+ */
10
+
11
+ import { toChatEvent, type ChatEvent } from './events'
12
+
13
+ export class SseParser {
14
+ private buffer = ''
15
+ private event = ''
16
+ private data: string[] = []
17
+
18
+ /** Feed a decoded chunk; returns the events it completed. */
19
+ push(chunk: string): ChatEvent[] {
20
+ this.buffer += chunk
21
+ const lines = this.buffer.split(/\r\n|\n|\r/)
22
+ this.buffer = lines.pop() ?? ''
23
+ const events: ChatEvent[] = []
24
+ for (const line of lines) {
25
+ const event = this.line(line)
26
+ if (event) events.push(event)
27
+ }
28
+ return events
29
+ }
30
+
31
+ /** End of stream: a last event without the trailing blank line still counts. */
32
+ flush(): ChatEvent[] {
33
+ const pending = this.buffer
34
+ this.buffer = ''
35
+ const events = pending ? this.push(`${pending}\n`) : []
36
+ const last = this.dispatch()
37
+ return last ? [...events, last] : events
38
+ }
39
+
40
+ private line(line: string): ChatEvent | null {
41
+ if (line === '') return this.dispatch()
42
+ if (line.startsWith(':')) return null
43
+ const colon = line.indexOf(':')
44
+ const field = colon === -1 ? line : line.slice(0, colon)
45
+ let value = colon === -1 ? '' : line.slice(colon + 1)
46
+ if (value.startsWith(' ')) value = value.slice(1)
47
+ if (field === 'event') this.event = value
48
+ else if (field === 'data') this.data.push(value)
49
+ return null
50
+ }
51
+
52
+ private dispatch(): ChatEvent | null {
53
+ const event = this.event || 'message'
54
+ const data = this.data.join('\n')
55
+ this.event = ''
56
+ this.data = []
57
+ if (!data) return null
58
+ try {
59
+ return toChatEvent(event, JSON.parse(data))
60
+ } catch {
61
+ return null
62
+ }
63
+ }
64
+ }
65
+
66
+ const isTerminal = (event: ChatEvent) => event.type === 'error' || event.type === 'done'
67
+
68
+ export async function* readSse(stream: ReadableStream<Uint8Array>): AsyncGenerator<ChatEvent> {
69
+ const reader = stream.getReader()
70
+ const decoder = new TextDecoder()
71
+ const parser = new SseParser()
72
+ try {
73
+ while (true) {
74
+ const { value, done } = await reader.read()
75
+ const events = done ? [...parser.push(decoder.decode()), ...parser.flush()] : parser.push(decoder.decode(value, { stream: true }))
76
+ for (const event of events) {
77
+ yield event
78
+ if (isTerminal(event)) return
79
+ }
80
+ if (done) return
81
+ }
82
+ } finally {
83
+ await reader.cancel().catch(() => undefined)
84
+ }
85
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Chat state machine over a `ChatApi`. The UI only renders what this hook returns.
3
+ *
4
+ * - The user message and an EMPTY assistant message are added up front (`tool_start` may arrive
5
+ * before any token); tokens are appended to it.
6
+ * - Tools are steps with a status (running -> done). Steps still open when the turn ends -> error.
7
+ * - One AbortController per send. Cancelling is not an error: the turn is marked `cancelled`.
8
+ * - On failure the question goes back to the draft so the user can resend it.
9
+ * - A stream that closes without `done` is a failure (the backend died mid-answer).
10
+ * - `conversationId` is generated here, one per conversation; `newConversation()` starts another.
11
+ */
12
+
13
+ import { useCallback, useEffect, useRef, useState } from 'react'
14
+
15
+ import type { ChatApi } from './chat-api'
16
+
17
+ export type StepStatus = 'running' | 'done' | 'error'
18
+ export type Step = { id: string; tool: string; status: StepStatus }
19
+ export type MessageStatus = 'streaming' | 'done' | 'error' | 'cancelled'
20
+
21
+ export type ChatMessage = {
22
+ id: string
23
+ role: 'user' | 'assistant'
24
+ content: string
25
+ steps: Step[]
26
+ status: MessageStatus
27
+ /** Backend error id to quote to support (never the error detail). */
28
+ errorId?: string
29
+ }
30
+
31
+ const newId = () => crypto.randomUUID()
32
+
33
+ export function useChat(chat: ChatApi) {
34
+ const [messages, setMessages] = useState<ChatMessage[]>([])
35
+ const [draft, setDraft] = useState('')
36
+ const [sending, setSending] = useState(false)
37
+ const [conversationId, setConversationId] = useState(newId)
38
+ const controller = useRef<AbortController | null>(null)
39
+
40
+ useEffect(() => () => controller.current?.abort(), [])
41
+
42
+ const patchAssistant = (id: string, patch: (m: ChatMessage) => ChatMessage) =>
43
+ setMessages((all) => all.map((m) => (m.id === id ? patch(m) : m)))
44
+
45
+ const send = useCallback(
46
+ async (text: string = draft) => {
47
+ const question = text.trim()
48
+ if (!question || sending) return
49
+ const assistantId = newId()
50
+ const abort = new AbortController()
51
+ controller.current = abort
52
+ setDraft('')
53
+ setSending(true)
54
+ setMessages((all) => [
55
+ ...all,
56
+ { id: newId(), role: 'user', content: question, steps: [], status: 'done' },
57
+ { id: assistantId, role: 'assistant', content: '', steps: [], status: 'streaming' },
58
+ ])
59
+
60
+ let finished = false
61
+ try {
62
+ for await (const event of chat.streamAnswer({ question, conversationId }, abort.signal)) {
63
+ switch (event.type) {
64
+ case 'token':
65
+ patchAssistant(assistantId, (m) => ({ ...m, content: m.content + event.text }))
66
+ break
67
+ case 'tool_start':
68
+ patchAssistant(assistantId, (m) => ({
69
+ ...m,
70
+ steps: [...m.steps, { id: newId(), tool: event.tool, status: 'running' }],
71
+ }))
72
+ break
73
+ case 'tool_end':
74
+ patchAssistant(assistantId, (m) => ({ ...m, steps: closeStep(m.steps, event.tool) }))
75
+ break
76
+ case 'error':
77
+ throw new ChatStreamError(event.errorId)
78
+ case 'done':
79
+ finished = true
80
+ patchAssistant(assistantId, (m) => ({
81
+ ...m,
82
+ content: m.content || event.answer,
83
+ steps: failOpenSteps(m.steps),
84
+ status: 'done',
85
+ }))
86
+ break
87
+ case 'routing':
88
+ break
89
+ }
90
+ }
91
+ if (!finished) throw new ChatStreamError()
92
+ } catch (error) {
93
+ if (abort.signal.aborted) {
94
+ patchAssistant(assistantId, (m) => ({ ...m, steps: failOpenSteps(m.steps), status: 'cancelled' }))
95
+ } else {
96
+ const errorId = error instanceof ChatStreamError ? error.errorId : undefined
97
+ patchAssistant(assistantId, (m) => ({ ...m, steps: failOpenSteps(m.steps), status: 'error', errorId }))
98
+ setDraft((current) => current || question)
99
+ }
100
+ } finally {
101
+ if (controller.current === abort) controller.current = null
102
+ setSending(false)
103
+ }
104
+ },
105
+ [chat, conversationId, draft, sending],
106
+ )
107
+
108
+ const cancel = useCallback(() => controller.current?.abort(), [])
109
+
110
+ const newConversation = useCallback(() => {
111
+ controller.current?.abort()
112
+ setMessages([])
113
+ setDraft('')
114
+ setConversationId(newId())
115
+ }, [])
116
+
117
+ return { messages, draft, setDraft, sending, conversationId, send, cancel, newConversation }
118
+ }
119
+
120
+ export class ChatStreamError extends Error {
121
+ constructor(readonly errorId?: string) {
122
+ super(errorId ? `Agent error ${errorId}` : 'The answer was interrupted')
123
+ this.name = 'ChatStreamError'
124
+ }
125
+ }
126
+
127
+ /** Close the oldest running step of that tool. */
128
+ export function closeStep(steps: Step[], tool: string): Step[] {
129
+ const index = steps.findIndex((s) => s.tool === tool && s.status === 'running')
130
+ if (index === -1) return steps
131
+ return steps.map((s, i) => (i === index ? { ...s, status: 'done' } : s))
132
+ }
133
+
134
+ export function failOpenSteps(steps: Step[]): Step[] {
135
+ return steps.map((s) => (s.status === 'running' ? { ...s, status: 'error' } : s))
136
+ }