@myrialabs/clopen 0.4.46 → 0.4.48

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 (328) hide show
  1. package/README.md +11 -11
  2. package/backend/artifacts/project/sources.ts +1 -1
  3. package/backend/auth/auth-service.ts +52 -358
  4. package/backend/auth/onboarding.test.ts +2 -3
  5. package/backend/auth/permissions.test.ts +10 -20
  6. package/backend/auth/permissions.ts +4 -290
  7. package/backend/auth/rate-limiter.test.ts +8 -9
  8. package/backend/auth/rate-limiter.ts +0 -2
  9. package/backend/auth/tokens.ts +1 -8
  10. package/backend/bootstrap.ts +7 -0
  11. package/backend/chat/attachments.test.ts +88 -0
  12. package/backend/chat/attachments.ts +159 -0
  13. package/backend/chat/engine-handoff.test.ts +0 -2
  14. package/backend/chat/stream-manager.ts +62 -62
  15. package/backend/chat/turn-answer.test.ts +64 -0
  16. package/backend/chat/turn-answer.ts +125 -0
  17. package/backend/chat-apps/awaiting.test.ts +39 -0
  18. package/backend/chat-apps/awaiting.ts +49 -0
  19. package/backend/chat-apps/conversation.ts +746 -0
  20. package/backend/chat-apps/inbound.ts +324 -0
  21. package/backend/chat-apps/index.ts +309 -0
  22. package/backend/chat-apps/link-events.ts +20 -0
  23. package/backend/chat-apps/media.test.ts +62 -0
  24. package/backend/chat-apps/media.ts +208 -0
  25. package/backend/chat-apps/messages.test.ts +229 -0
  26. package/backend/chat-apps/messages.ts +365 -0
  27. package/backend/chat-apps/outbound.ts +243 -0
  28. package/backend/chat-apps/pairing.test.ts +45 -0
  29. package/backend/chat-apps/pairing.ts +74 -0
  30. package/backend/chat-apps/platforms/index.ts +20 -0
  31. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  32. package/backend/chat-apps/platforms/telegram.ts +191 -0
  33. package/backend/chat-apps/platforms/types.ts +114 -0
  34. package/backend/chat-apps/questions.ts +133 -0
  35. package/backend/chat-apps/runtime.ts +572 -0
  36. package/backend/chat-apps/storage.test.ts +201 -0
  37. package/backend/chat-apps/turns.test.ts +45 -0
  38. package/backend/chat-apps/turns.ts +208 -0
  39. package/backend/containers/pty.ts +3 -11
  40. package/backend/control/actions/accounts.ts +89 -0
  41. package/backend/control/actions/files.ts +116 -0
  42. package/backend/control/actions/models.ts +188 -0
  43. package/backend/control/actions/projects.ts +272 -0
  44. package/backend/control/actions/sessions.ts +280 -0
  45. package/backend/control/actions/skills.ts +111 -0
  46. package/backend/control/control.test.ts +169 -0
  47. package/backend/control/define.ts +20 -0
  48. package/backend/control/folders.test.ts +67 -0
  49. package/backend/control/index.ts +213 -0
  50. package/backend/control/invoke.ts +44 -0
  51. package/backend/control/links.ts +35 -0
  52. package/backend/control/paging.ts +26 -0
  53. package/backend/control/types.ts +117 -0
  54. package/backend/control/workspace.ts +127 -0
  55. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  56. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  57. package/backend/database/migrations/086_single_owner.test.ts +170 -0
  58. package/backend/database/migrations/086_single_owner.ts +418 -0
  59. package/backend/database/migrations/index.ts +21 -0
  60. package/backend/database/queries/auth-queries.ts +7 -85
  61. package/backend/database/queries/channel-queries.ts +270 -0
  62. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  63. package/backend/database/queries/file-share-queries.ts +5 -23
  64. package/backend/database/queries/git-identity-queries.ts +31 -42
  65. package/backend/database/queries/graph-queries.ts +1 -1
  66. package/backend/database/queries/index.ts +13 -1
  67. package/backend/database/queries/message-queries.test.ts +146 -0
  68. package/backend/database/queries/message-queries.ts +42 -1
  69. package/backend/database/queries/permission-set-queries.ts +1 -1
  70. package/backend/database/queries/profile-queries.ts +1 -1
  71. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  72. package/backend/database/queries/project-queries.ts +50 -63
  73. package/backend/database/queries/session-queries.ts +28 -56
  74. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  75. package/backend/db-client/integrations/projector.ts +0 -5
  76. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  77. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  78. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  79. package/backend/engine/adapters/cline/stream.ts +11 -15
  80. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  81. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  82. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  83. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  84. package/backend/engine/adapters/opencode/presets.ts +27 -2
  85. package/backend/engine/adapters/opencode/server.ts +6 -4
  86. package/backend/engine/adapters/opencode/stream.ts +11 -0
  87. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  88. package/backend/engine/adapters/parent-scope.ts +44 -0
  89. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  90. package/backend/engine/adapters/pi/stream.ts +4 -5
  91. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  92. package/backend/engine/bootstrap-default-engine.ts +2 -2
  93. package/backend/engine/docs/adapter-contract.md +8 -1
  94. package/backend/engine/install-runner.ts +8 -17
  95. package/backend/files/file-shares.ts +20 -44
  96. package/backend/files/file-size-limit.ts +3 -3
  97. package/backend/files/image-processing.ts +1 -1
  98. package/backend/files/os-clipboard.ts +2 -2
  99. package/backend/git/git-executor.ts +25 -5
  100. package/backend/git/git-service.ts +420 -19
  101. package/backend/git/identity/credential-helper.test.ts +2 -7
  102. package/backend/git/identity/import-local.test.ts +11 -16
  103. package/backend/git/identity/import-local.ts +12 -12
  104. package/backend/git/identity/index.ts +10 -24
  105. package/backend/git/identity/resolve.ts +13 -14
  106. package/backend/git/identity/scope-config.ts +33 -28
  107. package/backend/git/identity/service.ts +44 -47
  108. package/backend/git/op-lock.test.ts +111 -0
  109. package/backend/git/op-lock.ts +180 -0
  110. package/backend/git/remote-sync.test.ts +249 -0
  111. package/backend/host/metrics.ts +1 -1
  112. package/backend/http/bearer-auth.ts +1 -2
  113. package/backend/http/files-download.test.ts +8 -9
  114. package/backend/http/files-download.ts +2 -2
  115. package/backend/http/files-shared.test.ts +62 -89
  116. package/backend/http/files-shared.ts +2 -2
  117. package/backend/http/files-upload.test.ts +3 -7
  118. package/backend/http/files-upload.ts +3 -3
  119. package/backend/http/notes-images.test.ts +15 -38
  120. package/backend/http/notes-images.ts +6 -8
  121. package/backend/http/ssh-sftp.ts +5 -10
  122. package/backend/index.ts +21 -7
  123. package/backend/integrations/accounts.ts +61 -3
  124. package/backend/integrations/index.ts +2 -2
  125. package/backend/integrations/registry/define.ts +15 -0
  126. package/backend/integrations/registry/index.ts +2 -0
  127. package/backend/integrations/registry/providers/telegram.ts +54 -0
  128. package/backend/integrations/registry/types.ts +21 -1
  129. package/backend/integrations/webhooks/gateway.ts +7 -6
  130. package/backend/integrations/webhooks/verify.test.ts +30 -0
  131. package/backend/integrations/webhooks/verify.ts +4 -0
  132. package/backend/mcp/external/project.ts +1 -1
  133. package/backend/mcp/internal/remote-server.test.ts +1 -3
  134. package/backend/mcp/internal/remote-server.ts +4 -4
  135. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  136. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  137. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  138. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  139. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  140. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  141. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  142. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  143. package/backend/memory/redact.ts +1 -1
  144. package/backend/notes/access.test.ts +28 -29
  145. package/backend/notes/access.ts +6 -11
  146. package/backend/permissions/service.ts +1 -1
  147. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  148. package/backend/preview/browser/browser-clipboard.ts +67 -0
  149. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  150. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  151. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  152. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  153. package/backend/preview/browser/browser-pool.ts +67 -6
  154. package/backend/preview/browser/browser-preview-service.ts +361 -25
  155. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  156. package/backend/preview/browser/browser-video-capture.ts +92 -5
  157. package/backend/preview/browser/element-locator.ts +190 -17
  158. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  159. package/backend/preview/browser/keyboard-chords.ts +132 -0
  160. package/backend/preview/browser/paste.ts +81 -0
  161. package/backend/preview/browser/process-usage.ts +142 -0
  162. package/backend/preview/browser/profile-lock.ts +209 -0
  163. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  164. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  165. package/backend/preview/browser/types.ts +40 -2
  166. package/backend/preview/browser/viewport.test.ts +45 -0
  167. package/backend/preview/browser/viewport.ts +96 -0
  168. package/backend/profiles/service.ts +2 -2
  169. package/backend/project/status-manager.ts +43 -172
  170. package/backend/projects/home.ts +61 -0
  171. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  172. package/backend/projects/project-cleanup.ts +0 -8
  173. package/backend/skills/service.ts +2 -3
  174. package/backend/snapshot/helpers.ts +0 -1
  175. package/backend/snapshot/restore.ts +252 -0
  176. package/backend/ssh/ptykit.ts +1 -2
  177. package/backend/terminal/ptykit.ts +5 -8
  178. package/backend/tunnel/public-origin.ts +31 -20
  179. package/backend/utils/user-helpers.ts +0 -55
  180. package/backend/utils/ws.ts +61 -154
  181. package/backend/worktrees/branching/engine.ts +3 -16
  182. package/backend/worktrees/branching/index.ts +1 -1
  183. package/backend/worktrees/branching/projector.ts +1 -1
  184. package/backend/worktrees/branching/service.ts +13 -25
  185. package/backend/ws/access.ts +12 -21
  186. package/backend/ws/artifacts/generate.ts +2 -2
  187. package/backend/ws/auth/device.ts +16 -71
  188. package/backend/ws/auth/index.ts +4 -22
  189. package/backend/ws/auth/login.test.ts +14 -60
  190. package/backend/ws/auth/login.ts +24 -124
  191. package/backend/ws/auth/status.ts +0 -1
  192. package/backend/ws/chat/composer.ts +118 -118
  193. package/backend/ws/chat/stream.ts +64 -47
  194. package/backend/ws/chat-apps/index.ts +117 -0
  195. package/backend/ws/containers/actions.ts +11 -25
  196. package/backend/ws/containers/index.ts +3 -4
  197. package/backend/ws/containers/list.ts +10 -36
  198. package/backend/ws/containers/logs.ts +2 -2
  199. package/backend/ws/containers/tunnel.ts +1 -2
  200. package/backend/ws/db-client/access.ts +2 -16
  201. package/backend/ws/db-client/accounts.ts +5 -15
  202. package/backend/ws/db-client/connections.ts +17 -25
  203. package/backend/ws/db-client/context.ts +1 -1
  204. package/backend/ws/db-client/env.ts +7 -10
  205. package/backend/ws/db-client/index.ts +2 -2
  206. package/backend/ws/db-client/io.ts +5 -5
  207. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  208. package/backend/ws/db-client/query.ts +18 -17
  209. package/backend/ws/db-client/schema.ts +13 -13
  210. package/backend/ws/db-client/structure.ts +35 -35
  211. package/backend/ws/db-client/supabase.ts +4 -21
  212. package/backend/ws/deployments/context.ts +1 -1
  213. package/backend/ws/deployments/crud.ts +0 -5
  214. package/backend/ws/engine/access.ts +7 -20
  215. package/backend/ws/engine/claude/accounts.ts +4 -4
  216. package/backend/ws/engine/cline/accounts.ts +5 -5
  217. package/backend/ws/engine/codex/accounts.ts +3 -3
  218. package/backend/ws/engine/opencode/providers.ts +2 -1
  219. package/backend/ws/engine/pi/accounts.ts +5 -5
  220. package/backend/ws/files/clipboard.ts +8 -27
  221. package/backend/ws/files/image-edit.ts +6 -6
  222. package/backend/ws/files/index.ts +1 -1
  223. package/backend/ws/files/path-access.test.ts +32 -131
  224. package/backend/ws/files/path-access.ts +8 -87
  225. package/backend/ws/files/read.ts +15 -19
  226. package/backend/ws/files/reveal.ts +3 -3
  227. package/backend/ws/files/search.ts +7 -7
  228. package/backend/ws/files/share.ts +9 -13
  229. package/backend/ws/files/state.ts +9 -12
  230. package/backend/ws/files/watch.ts +3 -3
  231. package/backend/ws/files/write.ts +30 -31
  232. package/backend/ws/git/branch.ts +80 -59
  233. package/backend/ws/git/commit.ts +63 -44
  234. package/backend/ws/git/conflict.ts +16 -18
  235. package/backend/ws/git/identity-context.ts +8 -17
  236. package/backend/ws/git/identity.ts +17 -27
  237. package/backend/ws/git/index.ts +3 -1
  238. package/backend/ws/git/op-state.ts +139 -0
  239. package/backend/ws/git/remote.ts +241 -141
  240. package/backend/ws/git/repo-context.ts +67 -0
  241. package/backend/ws/git/staging.ts +18 -28
  242. package/backend/ws/git/status.ts +5 -2
  243. package/backend/ws/index.ts +5 -1
  244. package/backend/ws/instructions/crud.ts +1 -1
  245. package/backend/ws/integrations/crud.ts +1 -3
  246. package/backend/ws/mcp/crud.ts +3 -5
  247. package/backend/ws/mcp/tools.ts +1 -1
  248. package/backend/ws/memory/crud.ts +14 -46
  249. package/backend/ws/memory/index.ts +2 -2
  250. package/backend/ws/messages/crud.ts +29 -8
  251. package/backend/ws/notes/index.ts +33 -39
  252. package/backend/ws/permissions/crud.ts +3 -4
  253. package/backend/ws/ports/index.ts +1 -2
  254. package/backend/ws/ports/kill.ts +5 -10
  255. package/backend/ws/ports/list.ts +4 -10
  256. package/backend/ws/preview/access.ts +1 -1
  257. package/backend/ws/preview/browser/interact.ts +52 -79
  258. package/backend/ws/preview/browser/native-ui.ts +24 -0
  259. package/backend/ws/preview/browser/stats.ts +98 -1
  260. package/backend/ws/preview/browser/tab-info.ts +15 -0
  261. package/backend/ws/preview/browser/tab.ts +19 -4
  262. package/backend/ws/preview/index.ts +27 -0
  263. package/backend/ws/profiles/crud.ts +6 -8
  264. package/backend/ws/project-artifacts/index.ts +30 -31
  265. package/backend/ws/projects/crud.ts +33 -35
  266. package/backend/ws/projects/index.ts +3 -8
  267. package/backend/ws/projects/info.ts +3 -3
  268. package/backend/ws/projects/overview.ts +19 -30
  269. package/backend/ws/projects/status.ts +17 -57
  270. package/backend/ws/sessions/crud.ts +34 -45
  271. package/backend/ws/sessions/index.ts +1 -1
  272. package/backend/ws/settings/crud.ts +1 -1
  273. package/backend/ws/skills/crud.ts +3 -4
  274. package/backend/ws/skills/index.ts +1 -1
  275. package/backend/ws/snapshot/changes.ts +7 -7
  276. package/backend/ws/snapshot/restore.ts +11 -295
  277. package/backend/ws/snapshot/timeline.ts +2 -4
  278. package/backend/ws/ssh/access.ts +6 -21
  279. package/backend/ws/ssh/connections.ts +21 -31
  280. package/backend/ws/ssh/forwards.ts +12 -12
  281. package/backend/ws/ssh/sftp.ts +34 -34
  282. package/backend/ws/ssh/tunnel.ts +1 -2
  283. package/backend/ws/stack/install.ts +7 -17
  284. package/backend/ws/subagents/crud.ts +1 -1
  285. package/backend/ws/tunnel/share.ts +0 -2
  286. package/backend/ws/user/crud.ts +1 -59
  287. package/backend/ws/user/index.ts +1 -1
  288. package/backend/ws/work/context.ts +1 -1
  289. package/backend/ws/work/crud.ts +0 -5
  290. package/backend/ws/workspace/state.ts +10 -13
  291. package/backend/ws/worktrees/branching.ts +7 -36
  292. package/backend/ws/worktrees/crud.ts +2 -2
  293. package/bin/clopen.ts +10 -11
  294. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  295. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  296. package/dist/assets/main-BUiUL3eZ.css +1 -0
  297. package/dist/assets/main-nBOb9YOA.js +1240 -0
  298. package/dist/index.html +2 -2
  299. package/package.json +2 -1
  300. package/shared/constants/attachments.ts +14 -0
  301. package/shared/constants/engine-tools.ts +1 -1
  302. package/shared/constants/preview.test.ts +259 -0
  303. package/shared/constants/preview.ts +1018 -57
  304. package/shared/constants/tool-icons.ts +5 -0
  305. package/shared/types/containers/container.ts +1 -1
  306. package/shared/types/database/schema.ts +9 -6
  307. package/shared/types/git-identity.ts +1 -1
  308. package/shared/types/git.ts +116 -0
  309. package/shared/types/integrations.ts +7 -0
  310. package/shared/types/stores/settings.ts +1 -1
  311. package/shared/types/unified/index.ts +1 -1
  312. package/shared/types/unified/message.ts +0 -7
  313. package/shared/types/unified/stream.ts +2 -4
  314. package/shared/types/unified/tool.ts +15 -1
  315. package/shared/utils/ask-user-question.test.ts +319 -0
  316. package/shared/utils/ask-user-question.ts +154 -0
  317. package/shared/utils/home-project.ts +25 -0
  318. package/shared/utils/logger.ts +2 -0
  319. package/shared/utils/ws-server.ts +32 -7
  320. package/backend/auth/session-invalidation.test.ts +0 -112
  321. package/backend/auth/session-invalidation.ts +0 -77
  322. package/backend/project/status-manager.test.ts +0 -32
  323. package/backend/ws/auth/invites.ts +0 -94
  324. package/backend/ws/auth/users.ts +0 -112
  325. package/backend/ws/projects/presence.ts +0 -46
  326. package/backend/ws/stack/access.ts +0 -31
  327. package/dist/assets/main-BiDNMWb3.css +0 -1
  328. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Attachments — one rule for every way a file reaches a prompt.
3
+ *
4
+ * The web composer and the chat apps both hand the stream image and document
5
+ * blocks. What an engine can READ natively depends on the model: images and
6
+ * PDFs when its input modalities say so, nothing else. Everything else is
7
+ * still worth sending — a CSV, a log, a zip, a screenshot for a text-only
8
+ * model — so instead of refusing it, the file is written into the session's
9
+ * working tree and the prompt names it, which every engine can act on with its
10
+ * own file tools.
11
+ *
12
+ * Files land in `.clopen/attachments/` under the session's working root. The
13
+ * folder ignores itself (`.clopen/.gitignore` is `*`), so an attachment never
14
+ * shows up in git or in a turn's snapshot as a change the agent made.
15
+ */
16
+
17
+ import { mkdirSync, writeFileSync, existsSync } from 'fs';
18
+ import { join, extname, basename } from 'path';
19
+ import type { EngineModel, EngineType, StreamRequest } from '$shared/types/unified';
20
+ import { getModelsByEngine, registerModels } from '$shared/constants/engines';
21
+ import { debug } from '$shared/utils/logger';
22
+ import { MAX_ATTACHMENT_BYTES, MAX_INLINE_ATTACHMENT_BYTES } from '$shared/constants/attachments';
23
+
24
+ /** Image types every vision model takes inline. */
25
+ export const NATIVE_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'] as const;
26
+ export const PDF_TYPE = 'application/pdf';
27
+
28
+
29
+ export const ATTACHMENTS_DIR = join('.clopen', 'attachments');
30
+
31
+ type Modalities = EngineModel['modalities']['input'];
32
+
33
+ /** When the model is unknown, assume what the web composer assumes. */
34
+ const FALLBACK_MODALITIES: Modalities = { text: true, image: true, pdf: true, audio: false, video: false };
35
+
36
+ /** A model's input modalities — from the registry, filling it on first use. */
37
+ export async function inputModalities(engine: EngineType, modelId: string): Promise<Modalities> {
38
+ let models = getModelsByEngine(engine);
39
+ if (models.length === 0) {
40
+ try {
41
+ const { initializeEngine } = await import('$backend/engine');
42
+ models = await (await initializeEngine(engine)).getAvailableModels();
43
+ registerModels(engine, models);
44
+ } catch (error) {
45
+ debug.warn('chat', 'Could not load models to check attachment support:', error);
46
+ }
47
+ }
48
+ return models.find((model) => model.engine.model.id === modelId)?.modalities.input ?? FALLBACK_MODALITIES;
49
+ }
50
+
51
+ /** Can this model read a file of `mediaType` inline? */
52
+ export function isNative(mediaType: string, modalities: Modalities): boolean {
53
+ if ((NATIVE_IMAGE_TYPES as readonly string[]).includes(mediaType)) return modalities.image;
54
+ if (mediaType === PDF_TYPE) return modalities.pdf;
55
+ return false;
56
+ }
57
+
58
+ export function base64Size(data: string): number {
59
+ const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
60
+ return Math.max(0, Math.floor((data.length * 3) / 4) - padding);
61
+ }
62
+
63
+ export function formatBytes(bytes: number): string {
64
+ if (bytes < 1024) return `${bytes} B`;
65
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
66
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
67
+ }
68
+
69
+ const EXTENSION_BY_TYPE: Record<string, string> = {
70
+ 'image/jpeg': '.jpg',
71
+ 'image/png': '.png',
72
+ 'image/gif': '.gif',
73
+ 'image/webp': '.webp',
74
+ 'application/pdf': '.pdf',
75
+ 'text/plain': '.txt',
76
+ 'audio/ogg': '.ogg',
77
+ 'audio/mpeg': '.mp3',
78
+ 'video/mp4': '.mp4'
79
+ };
80
+
81
+ /** A file name that is safe on every OS and keeps its extension. */
82
+ function safeName(name: string | null | undefined, mediaType: string): string {
83
+ const base = basename(name?.trim() || 'attachment').replace(/[^\w.\- ]+/g, '_').replace(/\s+/g, '-').slice(0, 120) || 'attachment';
84
+ return extname(base) ? base : `${base}${EXTENSION_BY_TYPE[mediaType] ?? ''}`;
85
+ }
86
+
87
+ function stamp(date = new Date()): string {
88
+ const pad = (value: number) => String(value).padStart(2, '0');
89
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
90
+ }
91
+
92
+ /** Write one attachment under `root` and return its path relative to `root`. */
93
+ export function saveAttachment(root: string, input: { data: Uint8Array; mediaType: string; name?: string | null }): string {
94
+ const dir = join(root, ATTACHMENTS_DIR);
95
+ mkdirSync(dir, { recursive: true });
96
+ const ignore = join(root, '.clopen', '.gitignore');
97
+ if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
98
+
99
+ const name = safeName(input.name, input.mediaType);
100
+ let file = `${stamp()}-${name}`;
101
+ for (let n = 2; existsSync(join(dir, file)); n++) file = `${stamp()}-${n}-${name}`;
102
+ writeFileSync(join(dir, file), input.data);
103
+ return join(ATTACHMENTS_DIR, file);
104
+ }
105
+
106
+ /** The line a prompt carries for a file it does not hold inline. */
107
+ export function attachmentMention(relativePath: string, input: { mediaType: string; size: number; name?: string | null }): string {
108
+ const label = input.name?.trim() ? `"${input.name.trim()}"` : 'a file';
109
+ return `[Attached ${label} (${input.mediaType || 'unknown type'}, ${formatBytes(input.size)}), saved at ./${relativePath.split('\\').join('/')}]`;
110
+ }
111
+
112
+ /**
113
+ * Keep what the model reads inline; save the rest under `root` and name it in
114
+ * the prompt instead. Returns the request unchanged when nothing had to move.
115
+ */
116
+ export async function normalizeAttachments(request: StreamRequest, root: string): Promise<StreamRequest> {
117
+ const content = (request.prompt as { content?: unknown })?.content;
118
+ if (!Array.isArray(content)) return request;
119
+ const files = content.filter((block) => block?.type === 'image' || block?.type === 'document');
120
+ if (files.length === 0) return request;
121
+
122
+ const modalities = await inputModalities(request.engine.type, request.engine.model.id);
123
+ const mentions: string[] = [];
124
+ const kept: unknown[] = [];
125
+ for (const block of content) {
126
+ if ((block?.type !== 'image' && block?.type !== 'document') || typeof block.data !== 'string') {
127
+ kept.push(block);
128
+ continue;
129
+ }
130
+ const mediaType = typeof block.mediaType === 'string' ? block.mediaType : 'application/octet-stream';
131
+ const size = base64Size(block.data);
132
+ if (isNative(mediaType, modalities) && size <= MAX_INLINE_ATTACHMENT_BYTES) {
133
+ kept.push(block);
134
+ continue;
135
+ }
136
+ if (size > MAX_ATTACHMENT_BYTES) {
137
+ mentions.push(`[An attached file "${block.title ?? 'attachment'}" (${formatBytes(size)}) was too large to keep. The limit is ${formatBytes(MAX_ATTACHMENT_BYTES)}.]`);
138
+ continue;
139
+ }
140
+ try {
141
+ const path = saveAttachment(root, { data: Buffer.from(block.data, 'base64'), mediaType, name: block.title });
142
+ mentions.push(attachmentMention(path, { mediaType, size, name: block.title }));
143
+ } catch (error) {
144
+ debug.warn('chat', 'Saving an attachment failed:', error);
145
+ mentions.push(`[An attached file "${block.title ?? 'attachment'}" could not be saved.]`);
146
+ }
147
+ }
148
+ if (mentions.length === 0) return request;
149
+
150
+ // The mention leads the text, so "summarise this" still reads as being about the file.
151
+ const textIndex = kept.findIndex((block) => (block as { type?: string })?.type === 'text');
152
+ const note = mentions.join('\n');
153
+ if (textIndex === -1) kept.push({ type: 'text', text: note });
154
+ else {
155
+ const text = kept[textIndex] as { type: 'text'; text: string };
156
+ kept[textIndex] = { type: 'text', text: text.text.trim() ? `${note}\n\n${text.text}` : note };
157
+ }
158
+ return { ...request, prompt: { ...request.prompt, content: kept } as StreamRequest['prompt'] };
159
+ }
@@ -36,7 +36,6 @@ function user(id: string, text: string, extra: Partial<UserMessage> = {}): UserM
36
36
  return {
37
37
  ...base(id),
38
38
  type: 'user',
39
- sender: { id: 'u', name: 'U' },
40
39
  content: [{ type: 'text', text }],
41
40
  synthetic: false,
42
41
  ...extra,
@@ -77,7 +76,6 @@ function toolResult(id: string, toolUseId: string, content: string): UserMessage
77
76
  return {
78
77
  ...base(id),
79
78
  type: 'user',
80
- sender: { id: '', name: '' },
81
79
  content: [{ type: 'tool_result', toolUseId, content, isError: false }],
82
80
  synthetic: true,
83
81
  };
@@ -5,7 +5,7 @@
5
5
  * - Event-driven push model (no polling)
6
6
  * - Background processing that continues even when browser is closed
7
7
  * - Reconnection to active streams after browser refresh
8
- * - Multiple concurrent streams per user/session
8
+ * - Multiple concurrent streams per session
9
9
  */
10
10
 
11
11
  import { EventEmitter } from 'events';
@@ -48,6 +48,7 @@ import { buildMemoryContext, withMemoryContext } from '../memory/context';
48
48
  import { buildEngineHandoff, resolveBranchEngine, withHandoff } from './engine-handoff';
49
49
  import { resolveGitEnv } from '$backend/git/identity';
50
50
  import { debug } from '$shared/utils/logger';
51
+ import { attachSubmittedAnswers } from '$shared/utils/ask-user-question';
51
52
  import { DEFAULT_MODEL_ID, DEFAULT_MODEL_NAME } from '$shared/constants/engines';
52
53
 
53
54
  // ============================================================================
@@ -95,6 +96,12 @@ export interface StreamState {
95
96
  preStreamSessionId?: string | null;
96
97
  hasCompactBoundary?: boolean;
97
98
  eventSeq: number;
99
+ /**
100
+ * AskUserQuestion answers the user submitted, keyed by tool_use id, held
101
+ * until the engine's tool_result for that id arrives and they are attached
102
+ * to it (see attachSubmittedAnswers).
103
+ */
104
+ submittedAnswers: Map<string, Record<string, string>>;
98
105
  }
99
106
 
100
107
  // ============================================================================
@@ -102,11 +109,7 @@ export interface StreamState {
102
109
  // ============================================================================
103
110
 
104
111
  /** Normalize raw UserMessage prompt from WS handler into a validated UserMessage */
105
- function convertRawPromptToUserMessage(
106
- rawPrompt: any,
107
- senderId?: string,
108
- senderName?: string,
109
- ): UserMessage {
112
+ function convertRawPromptToUserMessage(rawPrompt: any): UserMessage {
110
113
  const content: UserContentBlock[] = Array.isArray(rawPrompt?.content) && rawPrompt.content.length > 0
111
114
  ? rawPrompt.content as UserContentBlock[]
112
115
  : [{ type: 'text', text: '' }];
@@ -136,10 +139,6 @@ function convertRawPromptToUserMessage(
136
139
  toolUseId: rawPrompt?.parent?.toolUseId ?? rawPrompt?.parentToolUseId ?? null,
137
140
  },
138
141
  engine: engineObj,
139
- sender: {
140
- id: senderId || rawPrompt?.sender?.id || '',
141
- name: senderName || rawPrompt?.sender?.name || '',
142
- },
143
142
  content,
144
143
  synthetic: rawPrompt?.synthetic ?? false,
145
144
  };
@@ -412,7 +411,8 @@ class StreamManager extends EventEmitter {
412
411
  startedAt: new Date(),
413
412
  messages: [],
414
413
  abortController: new AbortController(),
415
- eventSeq: 0 // Initialize sequence for deduplication
414
+ eventSeq: 0, // Initialize sequence for deduplication
415
+ submittedAnswers: new Map()
416
416
  };
417
417
 
418
418
  this.activeStreams.set(streamId, streamState);
@@ -519,6 +519,22 @@ class StreamManager extends EventEmitter {
519
519
  // Emit to stream-specific channel only
520
520
  // (session channel removed to prevent duplicate dispatches)
521
521
  this.emit(`stream:${streamState.streamId}`, event);
522
+
523
+ // Messages also go out on one GLOBAL channel, exactly once per message.
524
+ // The per-stream channel above is only heard while some connection has
525
+ // bridged the stream into a room — and a bridge closes with its
526
+ // connection — so anything that must react to a message whether or not
527
+ // a tab is open (a question arriving after the user closed the browser
528
+ // is the whole point of a notification) listens here instead.
529
+ if (type === 'message') {
530
+ this.emit('stream:message', {
531
+ event,
532
+ streamId: streamState.streamId,
533
+ projectId: streamState.projectId,
534
+ chatSessionId: streamState.chatSessionId,
535
+ requestedByUserId: streamState.requestedByUserId
536
+ });
537
+ }
522
538
  }
523
539
 
524
540
  /**
@@ -569,7 +585,7 @@ class StreamManager extends EventEmitter {
569
585
  }
570
586
 
571
587
  try {
572
- const { projectPath, prompt: rawPrompt, chatSessionId, engine: requestEngine, sender: requestSender } = requestData;
588
+ const { projectPath, prompt: rawPrompt, chatSessionId, engine: requestEngine } = requestData;
573
589
 
574
590
  // Engine context that stream-manager injects into every SDK-emitted message.
575
591
  // (SDK adapters cannot know these values; only the request layer can.)
@@ -632,25 +648,26 @@ class StreamManager extends EventEmitter {
632
648
  streamState.preStreamSessionId = resumeSessionId ?? null;
633
649
 
634
650
  // Convert raw SDK prompt → UserMessage (unified)
635
- const userMessage = convertRawPromptToUserMessage(rawPrompt, requestSender.id, requestSender.name);
651
+ const userMessage = convertRawPromptToUserMessage(rawPrompt);
636
652
 
637
- // Save user message to DB
653
+ // Save user message to DB under the id the composer already shows it
654
+ // with, so its optimistic bubble names a real row from the start.
638
655
  const userMessageTimestamp = new Date().toISOString();
639
656
  const savedMessage = await this.saveMessage(
640
657
  userMessage,
641
658
  chatSessionId,
642
- userMessageTimestamp
659
+ userMessageTimestamp,
660
+ userMessage.messageId
643
661
  );
644
662
  userMessageId = savedMessage?.id;
663
+ if (savedMessage) this.emit('session:turn-started', chatSessionId);
645
664
 
646
665
  streamState.messages.push({
647
666
  processId: streamState.processId,
648
667
  message: userMessage as any,
649
668
  timestamp: userMessageTimestamp,
650
669
  message_id: savedMessage?.id,
651
- parent_message_id: savedMessage?.parent_message_id || null,
652
- sender_id: requestSender.id,
653
- sender_name: requestSender.name
670
+ parent_message_id: savedMessage?.parent_message_id || null
654
671
  });
655
672
 
656
673
  this.emitStreamEvent(streamState, 'message', {
@@ -658,9 +675,7 @@ class StreamManager extends EventEmitter {
658
675
  message: userMessage,
659
676
  timestamp: userMessageTimestamp,
660
677
  message_id: savedMessage?.id,
661
- parent_message_id: savedMessage?.parent_message_id || null,
662
- sender_id: requestSender.id,
663
- sender_name: requestSender.name
678
+ parent_message_id: savedMessage?.parent_message_id || null
664
679
  });
665
680
 
666
681
  if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
@@ -894,13 +909,10 @@ class StreamManager extends EventEmitter {
894
909
  ...(projectId && chatSessionId && {
895
910
  mcpContext: { projectId, chatSessionId, streamId: streamState.streamId, ...(activeProfileId != null && { profileId: activeProfileId }) }
896
911
  }),
897
- // The agent commits as the person who asked it to. Resolved here
898
- // because this is the only layer that knows both the project and
899
- // the requester; omitted when either is missing, which leaves git
900
- // behaving exactly as it did before identities existed.
901
- ...(projectId && streamState.requestedByUserId && {
902
- gitIdentityEnv: resolveGitEnv(projectId, streamState.requestedByUserId)
903
- }),
912
+ // The agent commits as the project's git identity; with none chosen
913
+ // the fragment is empty and git behaves exactly as it did before
914
+ // identities existed.
915
+ ...(projectId && { gitIdentityEnv: resolveGitEnv(projectId) }),
904
916
  });
905
917
 
906
918
  await projectContextService.runWithContextAsync(
@@ -1000,9 +1012,7 @@ class StreamManager extends EventEmitter {
1000
1012
  message: boundary,
1001
1013
  timestamp: compactTimestamp,
1002
1014
  message_id: savedCompactId,
1003
- parent_message_id: savedCompactParentId,
1004
- sender_id: requestSender.id,
1005
- sender_name: requestSender.name
1015
+ parent_message_id: savedCompactParentId
1006
1016
  });
1007
1017
  continue;
1008
1018
  }
@@ -1072,9 +1082,7 @@ class StreamManager extends EventEmitter {
1072
1082
  message: patched,
1073
1083
  timestamp: patched.createdAt,
1074
1084
  message_id: lastEntry?.message_id ?? undefined,
1075
- parent_message_id: lastEntry?.parent_message_id ?? null,
1076
- sender_id: requestSender.id,
1077
- sender_name: requestSender.name
1085
+ parent_message_id: lastEntry?.parent_message_id ?? null
1078
1086
  });
1079
1087
  }
1080
1088
  }
@@ -1083,7 +1091,7 @@ class StreamManager extends EventEmitter {
1083
1091
  // usage:null. Backfill the turn's aggregate to every saved
1084
1092
  // assistant without usage so it survives a refresh.
1085
1093
  if (successResult.usage && (streamState.engine === 'codex' || streamState.engine === 'cursor')) {
1086
- this.backfillUsageForStream(streamState, successResult.usage, requestSender);
1094
+ this.backfillUsageForStream(streamState, successResult.usage);
1087
1095
  }
1088
1096
  } else {
1089
1097
  const errResult = output as ErrorResultEvent;
@@ -1163,7 +1171,9 @@ class StreamManager extends EventEmitter {
1163
1171
  // ── Reasoning Message ──────────────────────────────────
1164
1172
  case 'reasoning': {
1165
1173
  const reasoning = enrichMessageEngine(output, engineCtx) as ReasoningMessage;
1166
- streamState.currentReasoningText = undefined;
1174
+ // Only a root message settles the root's live text — a sub-agent's
1175
+ // (parent-tagged) one finishing must not wipe the main turn's partial.
1176
+ if (!reasoning.parent.toolUseId) streamState.currentReasoningText = undefined;
1167
1177
 
1168
1178
  const reasoningTimestamp = reasoning.createdAt;
1169
1179
  let savedReasoningId: string | undefined;
@@ -1183,9 +1193,7 @@ class StreamManager extends EventEmitter {
1183
1193
  message: reasoning,
1184
1194
  timestamp: reasoningTimestamp,
1185
1195
  message_id: savedReasoningId,
1186
- parent_message_id: savedReasoningParentId,
1187
- sender_id: requestSender.id,
1188
- sender_name: requestSender.name
1196
+ parent_message_id: savedReasoningParentId
1189
1197
  });
1190
1198
  continue;
1191
1199
  }
@@ -1220,7 +1228,7 @@ class StreamManager extends EventEmitter {
1220
1228
  savedParentId = saved?.parent_message_id || null;
1221
1229
  }
1222
1230
 
1223
- streamState.currentPartialText = undefined;
1231
+ if (!assistantMsg.parent.toolUseId) streamState.currentPartialText = undefined;
1224
1232
 
1225
1233
  streamState.messages.push({
1226
1234
  processId: streamState.processId,
@@ -1228,9 +1236,7 @@ class StreamManager extends EventEmitter {
1228
1236
  usage: usage as any,
1229
1237
  timestamp: messageTimestamp,
1230
1238
  message_id: savedMsgId,
1231
- parent_message_id: savedParentId,
1232
- sender_id: requestSender.id,
1233
- sender_name: requestSender.name
1239
+ parent_message_id: savedParentId
1234
1240
  });
1235
1241
 
1236
1242
  streamState.currentMessage = assistantMsg;
@@ -1241,9 +1247,7 @@ class StreamManager extends EventEmitter {
1241
1247
  usage,
1242
1248
  timestamp: messageTimestamp,
1243
1249
  message_id: savedMsgId,
1244
- parent_message_id: savedParentId,
1245
- sender_id: requestSender.id,
1246
- sender_name: requestSender.name
1250
+ parent_message_id: savedParentId
1247
1251
  });
1248
1252
  continue;
1249
1253
  }
@@ -1252,6 +1256,7 @@ class StreamManager extends EventEmitter {
1252
1256
  case 'user': {
1253
1257
  const userMsg = enrichMessageEngine(output, engineCtx) as UserMessage;
1254
1258
  lastAssistantTextContent = null; // Reset dedup tracker
1259
+ attachSubmittedAnswers(userMsg, streamState.submittedAnswers);
1255
1260
 
1256
1261
  const messageTimestamp = userMsg.createdAt;
1257
1262
  let savedMsgId: string | undefined;
@@ -1271,9 +1276,7 @@ class StreamManager extends EventEmitter {
1271
1276
  message: userMsg as any,
1272
1277
  timestamp: messageTimestamp,
1273
1278
  message_id: savedMsgId,
1274
- parent_message_id: savedParentId,
1275
- sender_id: requestSender.id,
1276
- sender_name: requestSender.name
1279
+ parent_message_id: savedParentId
1277
1280
  });
1278
1281
 
1279
1282
  streamState.currentMessage = userMsg;
@@ -1283,9 +1286,7 @@ class StreamManager extends EventEmitter {
1283
1286
  message: userMsg,
1284
1287
  timestamp: messageTimestamp,
1285
1288
  message_id: savedMsgId,
1286
- parent_message_id: savedParentId,
1287
- sender_id: requestSender.id,
1288
- sender_name: requestSender.name
1289
+ parent_message_id: savedParentId
1289
1290
  });
1290
1291
  continue;
1291
1292
  }
@@ -1351,8 +1352,6 @@ class StreamManager extends EventEmitter {
1351
1352
  timestamp: errorTimestamp,
1352
1353
  message_id: savedErrorMsgId,
1353
1354
  parent_message_id: savedErrorParentId,
1354
- sender_id: requestData.sender.id,
1355
- sender_name: requestData.sender.name,
1356
1355
  });
1357
1356
 
1358
1357
  this.emitStreamEvent(streamState, 'error', {
@@ -1481,7 +1480,11 @@ class StreamManager extends EventEmitter {
1481
1480
  }
1482
1481
 
1483
1482
  debug.log('chat', 'Resolving AskUserQuestion answer:', { toolUseId, answers });
1484
- return engine.resolveUserAnswer(toolUseId, answers);
1483
+ // Recorded first: an engine may emit the tool_result before this returns.
1484
+ streamState.submittedAnswers.set(toolUseId, answers);
1485
+ const handled = engine.resolveUserAnswer(toolUseId, answers);
1486
+ if (!handled) streamState.submittedAnswers.delete(toolUseId);
1487
+ return handled;
1485
1488
  }
1486
1489
 
1487
1490
  async cancelStream(streamId: string, reason?: string): Promise<boolean> {
@@ -1681,7 +1684,8 @@ class StreamManager extends EventEmitter {
1681
1684
  private async saveMessage(
1682
1685
  message: UnifiedMessage,
1683
1686
  sessionId: string,
1684
- timestamp: string
1687
+ timestamp: string,
1688
+ preferredId?: string
1685
1689
  ): Promise<DatabaseMessage | null> {
1686
1690
  try {
1687
1691
  const currentHead = sessionQueries.getHead(sessionId);
@@ -1690,7 +1694,8 @@ class StreamManager extends EventEmitter {
1690
1694
  session_id: sessionId,
1691
1695
  message: message,
1692
1696
  timestamp,
1693
- parent_message_id: currentHead || undefined
1697
+ parent_message_id: currentHead || undefined,
1698
+ preferred_id: preferredId
1694
1699
  });
1695
1700
 
1696
1701
  sessionQueries.updateHead(sessionId, savedMessage.id);
@@ -1700,8 +1705,6 @@ class StreamManager extends EventEmitter {
1700
1705
  const text = extractMessageText(message);
1701
1706
  const updateOpts: Parameters<typeof sessionQueries.updateOnMessage>[1] = {
1702
1707
  messageType: message.type,
1703
- senderId: message.type === 'user' ? message.sender?.id : undefined,
1704
- senderName: message.type === 'user' ? message.sender?.name : undefined,
1705
1708
  timestamp,
1706
1709
  };
1707
1710
 
@@ -1804,7 +1807,6 @@ class StreamManager extends EventEmitter {
1804
1807
  private backfillUsageForStream(
1805
1808
  streamState: StreamState,
1806
1809
  usage: TokenUsage,
1807
- requestSender: StreamRequest['sender'],
1808
1810
  ): void {
1809
1811
  try {
1810
1812
  const { getDatabase } = require('../database');
@@ -1835,8 +1837,6 @@ class StreamManager extends EventEmitter {
1835
1837
  timestamp: patched.createdAt,
1836
1838
  message_id: entry.message_id,
1837
1839
  parent_message_id: entry.parent_message_id ?? null,
1838
- sender_id: requestSender.id,
1839
- sender_name: requestSender.name,
1840
1840
  });
1841
1841
  }
1842
1842
  } catch (err) {
@@ -0,0 +1,64 @@
1
+ /**
2
+ * What a turn's "answer" is, read back from the stored chain: the last text,
3
+ * the failure apart from it, and a turn that opened with only a photo.
4
+ */
5
+
6
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
7
+ import { initializeDatabase, closeDatabase } from '$backend/database';
8
+ import { messageQueries, projectQueries, sessionQueries } from '$backend/database/queries';
9
+ import type { UnifiedMessage } from '$shared/types/unified';
10
+ import { lastTurnAnswer } from './turn-answer';
11
+
12
+ let projectId: string;
13
+
14
+ function chain(sessionId: string, messages: UnifiedMessage[]): string[] {
15
+ const ids: string[] = [];
16
+ let parent: string | undefined;
17
+ for (const message of messages) {
18
+ const row = messageQueries.create({ session_id: sessionId, message, parent_message_id: parent });
19
+ parent = row.id;
20
+ ids.push(row.id);
21
+ sessionQueries.updateHead(sessionId, row.id);
22
+ }
23
+ return ids;
24
+ }
25
+
26
+ const base = { createdAt: '', messageId: '', sessionId: null, parent: { messageId: null, sessionId: null, toolUseId: null } };
27
+ const engine = { type: 'claude-code', provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } };
28
+ const user = (content: unknown[]) => ({ ...base, type: 'user', engine, content }) as unknown as UnifiedMessage;
29
+ const assistant = (text: string) => ({ ...base, type: 'assistant', engine, content: [{ type: 'text', text }], stopReason: null, usage: null }) as unknown as UnifiedMessage;
30
+
31
+ function newSession(): string {
32
+ return sessionQueries.create({ project_id: projectId, engine: 'claude-code', started_at: new Date().toISOString() } as never).id;
33
+ }
34
+
35
+ beforeAll(async () => {
36
+ await initializeDatabase();
37
+ projectId = projectQueries.create({ name: 'turn-answer', path: `/tmp/turn-answer-${crypto.randomUUID()}`, created_at: new Date().toISOString(), last_opened_at: new Date().toISOString() } as never).id;
38
+ });
39
+
40
+ afterAll(() => {
41
+ sessionQueries.deleteAllByProjectId(projectId);
42
+ projectQueries.deleteProject(projectId);
43
+ closeDatabase();
44
+ });
45
+
46
+ describe('lastTurnAnswer', () => {
47
+ it('is the last text of the turn, with the turn’s own user message', () => {
48
+ const session = newSession();
49
+ const [, , ask] = chain(session, [user([{ type: 'text', text: 'one' }]), assistant('first'), user([{ type: 'text', text: 'two' }]), assistant('looking…'), assistant('second')]);
50
+ expect(lastTurnAnswer(session)).toMatchObject({ text: 'second', error: null, userMessageId: ask });
51
+ });
52
+
53
+ it('keeps a failure apart from what the turn said before it', () => {
54
+ const session = newSession();
55
+ chain(session, [user([{ type: 'text', text: 'do it' }]), assistant('half done'), assistant('**Error:** rate limited')]);
56
+ expect(lastTurnAnswer(session)).toMatchObject({ text: 'half done', error: 'rate limited' });
57
+ });
58
+
59
+ it('stops at a turn that opened with only a photo, never reaching the turn before', () => {
60
+ const session = newSession();
61
+ const ids = chain(session, [user([{ type: 'text', text: 'one' }]), assistant('first'), user([{ type: 'image', mediaType: 'image/png', data: 'AAAA' }])]);
62
+ expect(lastTurnAnswer(session)).toMatchObject({ text: '', userMessageId: ids[2] });
63
+ });
64
+ });