@myrialabs/clopen 0.4.47 → 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 (325) 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/stream.ts +11 -0
  85. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  86. package/backend/engine/adapters/parent-scope.ts +44 -0
  87. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  88. package/backend/engine/adapters/pi/stream.ts +4 -5
  89. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  90. package/backend/engine/bootstrap-default-engine.ts +2 -2
  91. package/backend/engine/docs/adapter-contract.md +8 -1
  92. package/backend/engine/install-runner.ts +8 -17
  93. package/backend/files/file-shares.ts +20 -44
  94. package/backend/files/file-size-limit.ts +3 -3
  95. package/backend/files/image-processing.ts +1 -1
  96. package/backend/files/os-clipboard.ts +2 -2
  97. package/backend/git/git-executor.ts +25 -5
  98. package/backend/git/git-service.ts +420 -19
  99. package/backend/git/identity/credential-helper.test.ts +2 -7
  100. package/backend/git/identity/import-local.test.ts +11 -16
  101. package/backend/git/identity/import-local.ts +12 -12
  102. package/backend/git/identity/index.ts +10 -24
  103. package/backend/git/identity/resolve.ts +13 -14
  104. package/backend/git/identity/scope-config.ts +33 -28
  105. package/backend/git/identity/service.ts +44 -47
  106. package/backend/git/op-lock.test.ts +111 -0
  107. package/backend/git/op-lock.ts +180 -0
  108. package/backend/git/remote-sync.test.ts +249 -0
  109. package/backend/host/metrics.ts +1 -1
  110. package/backend/http/bearer-auth.ts +1 -2
  111. package/backend/http/files-download.test.ts +8 -9
  112. package/backend/http/files-download.ts +2 -2
  113. package/backend/http/files-shared.test.ts +62 -89
  114. package/backend/http/files-shared.ts +2 -2
  115. package/backend/http/files-upload.test.ts +3 -7
  116. package/backend/http/files-upload.ts +3 -3
  117. package/backend/http/notes-images.test.ts +15 -38
  118. package/backend/http/notes-images.ts +6 -8
  119. package/backend/http/ssh-sftp.ts +5 -10
  120. package/backend/index.ts +21 -7
  121. package/backend/integrations/accounts.ts +61 -3
  122. package/backend/integrations/index.ts +2 -2
  123. package/backend/integrations/registry/define.ts +15 -0
  124. package/backend/integrations/registry/index.ts +2 -0
  125. package/backend/integrations/registry/providers/telegram.ts +54 -0
  126. package/backend/integrations/registry/types.ts +21 -1
  127. package/backend/integrations/webhooks/gateway.ts +7 -6
  128. package/backend/integrations/webhooks/verify.test.ts +30 -0
  129. package/backend/integrations/webhooks/verify.ts +4 -0
  130. package/backend/mcp/external/project.ts +1 -1
  131. package/backend/mcp/internal/remote-server.test.ts +1 -3
  132. package/backend/mcp/internal/remote-server.ts +4 -4
  133. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  134. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  135. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  136. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  137. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  138. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  139. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  140. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  141. package/backend/memory/redact.ts +1 -1
  142. package/backend/notes/access.test.ts +28 -29
  143. package/backend/notes/access.ts +6 -11
  144. package/backend/permissions/service.ts +1 -1
  145. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  146. package/backend/preview/browser/browser-clipboard.ts +67 -0
  147. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  148. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  149. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  150. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  151. package/backend/preview/browser/browser-pool.ts +67 -6
  152. package/backend/preview/browser/browser-preview-service.ts +361 -25
  153. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  154. package/backend/preview/browser/browser-video-capture.ts +92 -5
  155. package/backend/preview/browser/element-locator.ts +190 -17
  156. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  157. package/backend/preview/browser/keyboard-chords.ts +132 -0
  158. package/backend/preview/browser/paste.ts +81 -0
  159. package/backend/preview/browser/process-usage.ts +142 -0
  160. package/backend/preview/browser/profile-lock.ts +209 -0
  161. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  162. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  163. package/backend/preview/browser/types.ts +40 -2
  164. package/backend/preview/browser/viewport.test.ts +45 -0
  165. package/backend/preview/browser/viewport.ts +96 -0
  166. package/backend/profiles/service.ts +2 -2
  167. package/backend/project/status-manager.ts +43 -172
  168. package/backend/projects/home.ts +61 -0
  169. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  170. package/backend/projects/project-cleanup.ts +0 -8
  171. package/backend/skills/service.ts +2 -3
  172. package/backend/snapshot/helpers.ts +0 -1
  173. package/backend/snapshot/restore.ts +252 -0
  174. package/backend/ssh/ptykit.ts +1 -2
  175. package/backend/terminal/ptykit.ts +5 -8
  176. package/backend/tunnel/public-origin.ts +31 -20
  177. package/backend/utils/user-helpers.ts +0 -55
  178. package/backend/utils/ws.ts +61 -154
  179. package/backend/worktrees/branching/engine.ts +3 -16
  180. package/backend/worktrees/branching/index.ts +1 -1
  181. package/backend/worktrees/branching/projector.ts +1 -1
  182. package/backend/worktrees/branching/service.ts +13 -25
  183. package/backend/ws/access.ts +12 -21
  184. package/backend/ws/artifacts/generate.ts +2 -2
  185. package/backend/ws/auth/device.ts +16 -71
  186. package/backend/ws/auth/index.ts +4 -22
  187. package/backend/ws/auth/login.test.ts +14 -60
  188. package/backend/ws/auth/login.ts +24 -124
  189. package/backend/ws/auth/status.ts +0 -1
  190. package/backend/ws/chat/composer.ts +118 -118
  191. package/backend/ws/chat/stream.ts +64 -47
  192. package/backend/ws/chat-apps/index.ts +117 -0
  193. package/backend/ws/containers/actions.ts +11 -25
  194. package/backend/ws/containers/index.ts +3 -4
  195. package/backend/ws/containers/list.ts +10 -36
  196. package/backend/ws/containers/logs.ts +2 -2
  197. package/backend/ws/containers/tunnel.ts +1 -2
  198. package/backend/ws/db-client/access.ts +2 -16
  199. package/backend/ws/db-client/accounts.ts +5 -15
  200. package/backend/ws/db-client/connections.ts +17 -25
  201. package/backend/ws/db-client/context.ts +1 -1
  202. package/backend/ws/db-client/env.ts +7 -10
  203. package/backend/ws/db-client/index.ts +2 -2
  204. package/backend/ws/db-client/io.ts +5 -5
  205. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  206. package/backend/ws/db-client/query.ts +18 -17
  207. package/backend/ws/db-client/schema.ts +13 -13
  208. package/backend/ws/db-client/structure.ts +35 -35
  209. package/backend/ws/db-client/supabase.ts +4 -21
  210. package/backend/ws/deployments/context.ts +1 -1
  211. package/backend/ws/deployments/crud.ts +0 -5
  212. package/backend/ws/engine/access.ts +7 -20
  213. package/backend/ws/engine/claude/accounts.ts +4 -4
  214. package/backend/ws/engine/cline/accounts.ts +5 -5
  215. package/backend/ws/engine/codex/accounts.ts +3 -3
  216. package/backend/ws/engine/pi/accounts.ts +5 -5
  217. package/backend/ws/files/clipboard.ts +8 -27
  218. package/backend/ws/files/image-edit.ts +6 -6
  219. package/backend/ws/files/index.ts +1 -1
  220. package/backend/ws/files/path-access.test.ts +32 -131
  221. package/backend/ws/files/path-access.ts +8 -87
  222. package/backend/ws/files/read.ts +15 -19
  223. package/backend/ws/files/reveal.ts +3 -3
  224. package/backend/ws/files/search.ts +7 -7
  225. package/backend/ws/files/share.ts +9 -13
  226. package/backend/ws/files/state.ts +9 -12
  227. package/backend/ws/files/watch.ts +3 -3
  228. package/backend/ws/files/write.ts +30 -31
  229. package/backend/ws/git/branch.ts +80 -59
  230. package/backend/ws/git/commit.ts +63 -44
  231. package/backend/ws/git/conflict.ts +16 -18
  232. package/backend/ws/git/identity-context.ts +8 -17
  233. package/backend/ws/git/identity.ts +17 -27
  234. package/backend/ws/git/index.ts +3 -1
  235. package/backend/ws/git/op-state.ts +139 -0
  236. package/backend/ws/git/remote.ts +241 -141
  237. package/backend/ws/git/repo-context.ts +67 -0
  238. package/backend/ws/git/staging.ts +18 -28
  239. package/backend/ws/git/status.ts +5 -2
  240. package/backend/ws/index.ts +5 -1
  241. package/backend/ws/instructions/crud.ts +1 -1
  242. package/backend/ws/integrations/crud.ts +1 -3
  243. package/backend/ws/mcp/crud.ts +3 -5
  244. package/backend/ws/mcp/tools.ts +1 -1
  245. package/backend/ws/memory/crud.ts +14 -46
  246. package/backend/ws/memory/index.ts +2 -2
  247. package/backend/ws/messages/crud.ts +29 -8
  248. package/backend/ws/notes/index.ts +33 -39
  249. package/backend/ws/permissions/crud.ts +3 -4
  250. package/backend/ws/ports/index.ts +1 -2
  251. package/backend/ws/ports/kill.ts +5 -10
  252. package/backend/ws/ports/list.ts +4 -10
  253. package/backend/ws/preview/access.ts +1 -1
  254. package/backend/ws/preview/browser/interact.ts +52 -79
  255. package/backend/ws/preview/browser/native-ui.ts +24 -0
  256. package/backend/ws/preview/browser/stats.ts +98 -1
  257. package/backend/ws/preview/browser/tab-info.ts +15 -0
  258. package/backend/ws/preview/browser/tab.ts +19 -4
  259. package/backend/ws/preview/index.ts +27 -0
  260. package/backend/ws/profiles/crud.ts +6 -8
  261. package/backend/ws/project-artifacts/index.ts +30 -31
  262. package/backend/ws/projects/crud.ts +33 -35
  263. package/backend/ws/projects/index.ts +3 -8
  264. package/backend/ws/projects/info.ts +3 -3
  265. package/backend/ws/projects/overview.ts +19 -30
  266. package/backend/ws/projects/status.ts +17 -57
  267. package/backend/ws/sessions/crud.ts +34 -45
  268. package/backend/ws/sessions/index.ts +1 -1
  269. package/backend/ws/settings/crud.ts +1 -1
  270. package/backend/ws/skills/crud.ts +3 -4
  271. package/backend/ws/skills/index.ts +1 -1
  272. package/backend/ws/snapshot/changes.ts +7 -7
  273. package/backend/ws/snapshot/restore.ts +11 -295
  274. package/backend/ws/snapshot/timeline.ts +2 -4
  275. package/backend/ws/ssh/access.ts +6 -21
  276. package/backend/ws/ssh/connections.ts +21 -31
  277. package/backend/ws/ssh/forwards.ts +12 -12
  278. package/backend/ws/ssh/sftp.ts +34 -34
  279. package/backend/ws/ssh/tunnel.ts +1 -2
  280. package/backend/ws/stack/install.ts +7 -17
  281. package/backend/ws/subagents/crud.ts +1 -1
  282. package/backend/ws/tunnel/share.ts +0 -2
  283. package/backend/ws/user/crud.ts +1 -59
  284. package/backend/ws/user/index.ts +1 -1
  285. package/backend/ws/work/context.ts +1 -1
  286. package/backend/ws/work/crud.ts +0 -5
  287. package/backend/ws/workspace/state.ts +10 -13
  288. package/backend/ws/worktrees/branching.ts +7 -36
  289. package/backend/ws/worktrees/crud.ts +2 -2
  290. package/bin/clopen.ts +10 -11
  291. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  292. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  293. package/dist/assets/main-BUiUL3eZ.css +1 -0
  294. package/dist/assets/main-nBOb9YOA.js +1240 -0
  295. package/dist/index.html +2 -2
  296. package/package.json +2 -1
  297. package/shared/constants/attachments.ts +14 -0
  298. package/shared/constants/engine-tools.ts +1 -1
  299. package/shared/constants/preview.test.ts +259 -0
  300. package/shared/constants/preview.ts +1018 -57
  301. package/shared/constants/tool-icons.ts +5 -0
  302. package/shared/types/containers/container.ts +1 -1
  303. package/shared/types/database/schema.ts +9 -6
  304. package/shared/types/git-identity.ts +1 -1
  305. package/shared/types/git.ts +116 -0
  306. package/shared/types/integrations.ts +7 -0
  307. package/shared/types/stores/settings.ts +1 -1
  308. package/shared/types/unified/index.ts +1 -1
  309. package/shared/types/unified/message.ts +0 -7
  310. package/shared/types/unified/stream.ts +2 -4
  311. package/shared/types/unified/tool.ts +15 -1
  312. package/shared/utils/ask-user-question.test.ts +319 -0
  313. package/shared/utils/ask-user-question.ts +154 -0
  314. package/shared/utils/home-project.ts +25 -0
  315. package/shared/utils/logger.ts +2 -0
  316. package/shared/utils/ws-server.ts +32 -7
  317. package/backend/auth/session-invalidation.test.ts +0 -112
  318. package/backend/auth/session-invalidation.ts +0 -77
  319. package/backend/project/status-manager.test.ts +0 -32
  320. package/backend/ws/auth/invites.ts +0 -94
  321. package/backend/ws/auth/users.ts +0 -112
  322. package/backend/ws/projects/presence.ts +0 -46
  323. package/backend/ws/stack/access.ts +0 -31
  324. package/dist/assets/main-BiDNMWb3.css +0 -1
  325. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -142,12 +142,10 @@ export const sessionQueries = {
142
142
 
143
143
  /**
144
144
  * Update session metadata after a message is saved.
145
- * Increments counts, updates sender, timestamps, and HEAD content snapshot.
145
+ * Increments counts, updates timestamps, and HEAD content snapshot.
146
146
  */
147
147
  updateOnMessage(id: string, opts: {
148
148
  messageType: string;
149
- senderId?: string | null;
150
- senderName?: string | null;
151
149
  timestamp: string;
152
150
  headTitle?: string | null;
153
151
  headSummary?: string | null;
@@ -165,14 +163,6 @@ export const sessionQueries = {
165
163
  sets.push('user_count = COALESCE(user_count, 0) + 1');
166
164
  }
167
165
 
168
- if (opts.senderId !== undefined) {
169
- sets.push('sender_id = ?');
170
- params.push(opts.senderId ?? null);
171
- }
172
- if (opts.senderName !== undefined) {
173
- sets.push('sender_name = ?');
174
- params.push(opts.senderName ?? null);
175
- }
176
166
 
177
167
  if (opts.headTitle !== undefined) {
178
168
  sets.push('head_title = ?');
@@ -312,13 +302,13 @@ export const sessionQueries = {
312
302
  },
313
303
 
314
304
  /**
315
- * Search sessions across every project the user has access to.
305
+ * Search sessions across every project in the workspace list.
316
306
  * Two passes, merged: cheap metadata match (title/head_title/head_summary)
317
307
  * plus an FTS5 index lookup over message content — the latter also returns
318
308
  * a highlighted snippet (wrapped in ... markers) showing where
319
309
  * the match occurred. Backs the global Command Palette session search.
320
310
  */
321
- searchGlobal(userId: string, query: string, limit: number = 20): SessionSearchResult[] {
311
+ searchGlobal(query: string, limit: number = 20): SessionSearchResult[] {
322
312
  const db = getDatabase();
323
313
  const trimmed = query.trim();
324
314
  if (!trimmed) return [];
@@ -329,11 +319,11 @@ export const sessionQueries = {
329
319
  const like = `%${trimmed}%`;
330
320
  const metaRows = db.prepare(`
331
321
  SELECT * FROM chat_sessions cs
332
- WHERE cs.project_id IN (SELECT project_id FROM user_projects WHERE user_id = ?)
322
+ WHERE cs.project_id IN (SELECT project_id FROM workspace_projects)
333
323
  AND (cs.title LIKE ? OR cs.head_title LIKE ? OR cs.head_summary LIKE ?)
334
324
  ORDER BY COALESCE(cs.last_message_at, cs.started_at) DESC
335
325
  LIMIT ?
336
- `).all(userId, like, like, like, limit) as ChatSession[];
326
+ `).all(like, like, like, limit) as ChatSession[];
337
327
  for (const row of metaRows) {
338
328
  results.set(row.id, row);
339
329
  }
@@ -346,11 +336,11 @@ export const sessionQueries = {
346
336
  SELECT cs.*, snippet(messages_fts, 3, char(1), char(2), '…', 12) AS match_snippet
347
337
  FROM messages_fts fts
348
338
  INNER JOIN chat_sessions cs ON cs.id = fts.session_id
349
- WHERE fts.project_id IN (SELECT project_id FROM user_projects WHERE user_id = ?)
339
+ WHERE fts.project_id IN (SELECT project_id FROM workspace_projects)
350
340
  AND fts.text MATCH ?
351
341
  ORDER BY rank
352
342
  LIMIT ?
353
- `).all(userId, ftsQuery, limit * 2) as (ChatSession & { match_snippet: string })[];
343
+ `).all(ftsQuery, limit * 2) as (ChatSession & { match_snippet: string })[];
354
344
 
355
345
  for (const row of contentRows) {
356
346
  if (results.has(row.id)) continue;
@@ -409,9 +399,9 @@ export const sessionQueries = {
409
399
  db.prepare('DELETE FROM session_relationships WHERE parent_session_id = ? OR child_session_id = ?').run(id, id);
410
400
  db.prepare('DELETE FROM messages WHERE session_id = ?').run(id);
411
401
  db.prepare('DELETE FROM messages_fts WHERE session_id = ?').run(id);
412
- db.prepare('DELETE FROM user_unread_sessions WHERE session_id = ?').run(id);
413
- // Clear current_session_id references in user_projects
414
- db.prepare('UPDATE user_projects SET current_session_id = NULL WHERE current_session_id = ?').run(id);
402
+ db.prepare('DELETE FROM unread_sessions WHERE session_id = ?').run(id);
403
+ // Clear current_session_id references in workspace_projects
404
+ db.prepare('UPDATE workspace_projects SET current_session_id = NULL WHERE current_session_id = ?').run(id);
415
405
  db.prepare('DELETE FROM chat_sessions WHERE id = ?').run(id);
416
406
  },
417
407
 
@@ -437,9 +427,9 @@ export const sessionQueries = {
437
427
  `).run(projectId, projectId);
438
428
  db.prepare('DELETE FROM messages WHERE session_id IN (SELECT id FROM chat_sessions WHERE project_id = ?)').run(projectId);
439
429
  db.prepare('DELETE FROM messages_fts WHERE project_id = ?').run(projectId);
440
- db.prepare('DELETE FROM user_unread_sessions WHERE project_id = ?').run(projectId);
441
- // Clear current_session_id references in user_projects for this project
442
- db.prepare('UPDATE user_projects SET current_session_id = NULL WHERE project_id = ?').run(projectId);
430
+ db.prepare('DELETE FROM unread_sessions WHERE project_id = ?').run(projectId);
431
+ // Clear current_session_id references in workspace_projects for this project
432
+ db.prepare('UPDATE workspace_projects SET current_session_id = NULL WHERE project_id = ?').run(projectId);
443
433
  db.prepare('DELETE FROM chat_sessions WHERE project_id = ?').run(projectId);
444
434
 
445
435
  return sessionIds;
@@ -636,51 +626,33 @@ export const sessionQueries = {
636
626
  `).run(newHeadMessageId, sessionId, branchName);
637
627
  },
638
628
 
639
- // ==================== PER-USER UNREAD SESSION TRACKING ====================
629
+ // ==================== UNREAD SESSION TRACKING ====================
640
630
 
641
- /**
642
- * Mark a session as unread for a specific user
643
- */
644
- markUnread(userId: string, sessionId: string, projectId: string): void {
631
+ markUnread(sessionId: string, projectId: string): void {
645
632
  const db = getDatabase();
646
633
  const now = new Date().toISOString();
647
634
  db.prepare(`
648
- INSERT OR IGNORE INTO user_unread_sessions (user_id, session_id, project_id, marked_at)
649
- VALUES (?, ?, ?, ?)
650
- `).run(userId, sessionId, projectId, now);
635
+ INSERT OR IGNORE INTO unread_sessions (session_id, project_id, marked_at)
636
+ VALUES (?, ?, ?)
637
+ `).run(sessionId, projectId, now);
651
638
  },
652
639
 
653
- /**
654
- * Mark a session as read for a specific user
655
- */
656
- markRead(userId: string, sessionId: string): void {
640
+ markRead(sessionId: string): void {
657
641
  const db = getDatabase();
658
- db.prepare(`
659
- DELETE FROM user_unread_sessions
660
- WHERE user_id = ? AND session_id = ?
661
- `).run(userId, sessionId);
642
+ db.prepare('DELETE FROM unread_sessions WHERE session_id = ?').run(sessionId);
662
643
  },
663
644
 
664
- /**
665
- * Mark every unread session in a project as read for a specific user
666
- */
667
- markAllRead(userId: string, projectId: string): void {
645
+ /** Mark every unread session in a project as read. */
646
+ markAllRead(projectId: string): void {
668
647
  const db = getDatabase();
669
- db.prepare(`
670
- DELETE FROM user_unread_sessions
671
- WHERE user_id = ? AND project_id = ?
672
- `).run(userId, projectId);
648
+ db.prepare('DELETE FROM unread_sessions WHERE project_id = ?').run(projectId);
673
649
  },
674
650
 
675
- /**
676
- * Get all unread session IDs for a user within a project
677
- * Returns array of { sessionId, projectId }
678
- */
679
- getUnreadSessions(userId: string, projectId: string): { session_id: string; project_id: string }[] {
651
+ /** Unread sessions within a project. */
652
+ getUnreadSessions(projectId: string): { session_id: string; project_id: string }[] {
680
653
  const db = getDatabase();
681
654
  return db.prepare(`
682
- SELECT session_id, project_id FROM user_unread_sessions
683
- WHERE user_id = ? AND project_id = ?
684
- `).all(userId, projectId) as { session_id: string; project_id: string }[];
655
+ SELECT session_id, project_id FROM unread_sessions WHERE project_id = ?
656
+ `).all(projectId) as { session_id: string; project_id: string }[];
685
657
  }
686
- };
658
+ };
@@ -51,11 +51,6 @@ function redactConnectionSecrets(connection: SshConnection): SshConnection {
51
51
  };
52
52
  }
53
53
 
54
- function hasConnectionAccess(row: DBSshConnectionRow, userId: string, isAdmin: boolean): boolean {
55
- if (isAdmin) return true;
56
- return row.owner_user_id === userId;
57
- }
58
-
59
54
  /**
60
55
  * An empty string in a patch means "the form did not re-send this secret",
61
56
  * not "clear it" — otherwise editing the name of a key-authenticated host
@@ -87,7 +82,7 @@ function wouldCycle(connectionId: string, jumpConnectionId: string | null): bool
87
82
  return false;
88
83
  }
89
84
 
90
- function insertConnection(input: SshConnectionInput, ownerUserId: string | null): SshConnection {
85
+ function insertConnection(input: SshConnectionInput): SshConnection {
91
86
  const db = getDatabase();
92
87
  const id = crypto.randomUUID();
93
88
  const now = new Date().toISOString();
@@ -97,12 +92,12 @@ function insertConnection(input: SshConnectionInput, ownerUserId: string | null)
97
92
  id, name, host, port, username, auth_method,
98
93
  password, private_key, private_key_path, passphrase, agent_socket,
99
94
  jump_connection_id, initial_path, keepalive_seconds, strict_host_key,
100
- color, owner_user_id, created_at, updated_at, last_used_at
95
+ color, created_at, updated_at, last_used_at
101
96
  ) VALUES (
102
97
  ?, ?, ?, ?, ?, ?,
103
98
  ?, ?, ?, ?, ?,
104
99
  ?, ?, ?, ?,
105
- ?, ?, ?, ?, ?
100
+ ?, ?, ?, ?
106
101
  )
107
102
  `).run(
108
103
  id,
@@ -121,7 +116,6 @@ function insertConnection(input: SshConnectionInput, ownerUserId: string | null)
121
116
  input.keepaliveSeconds ?? 30,
122
117
  input.strictHostKey === false ? 0 : 1,
123
118
  input.color || null,
124
- ownerUserId,
125
119
  now,
126
120
  now,
127
121
  null
@@ -133,32 +127,25 @@ function insertConnection(input: SshConnectionInput, ownerUserId: string | null)
133
127
  }
134
128
 
135
129
  export const sshConnectionQueries = {
136
- listForUser(userId: string, isAdmin: boolean): SshConnection[] {
130
+ /** Every connection with its secrets removed — what a client is sent. */
131
+ listRedacted(): SshConnection[] {
137
132
  const db = getDatabase();
138
- const rows = (isAdmin
139
- ? db.prepare(`
140
- SELECT * FROM ssh_connections
141
- ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
142
- `).all()
143
- : db.prepare(`
144
- SELECT * FROM ssh_connections
145
- WHERE owner_user_id = ?
146
- ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
147
- `).all(userId)) as DBSshConnectionRow[];
148
-
133
+ const rows = db.prepare(`
134
+ SELECT * FROM ssh_connections
135
+ ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
136
+ `).all() as DBSshConnectionRow[];
149
137
  return rows.map((row) => redactConnectionSecrets(rowToConnection(openConnectionRow(row))));
150
138
  },
151
139
 
152
- getForUser(id: string, userId: string, isAdmin: boolean): SshConnection | null {
140
+ getRedacted(id: string): SshConnection | null {
153
141
  const row = getRowById(id);
154
- if (!row || !hasConnectionAccess(row, userId, isAdmin)) return null;
155
- return redactConnectionSecrets(rowToConnection(row));
142
+ return row ? redactConnectionSecrets(rowToConnection(row)) : null;
156
143
  },
157
144
 
158
- /** Full connection including secrets — server-side callers only. Throws on denial. */
159
- ensureAccess(id: string, userId: string, isAdmin: boolean): SshConnection {
145
+ /** Full connection including secrets — server-side callers only. Throws when missing. */
146
+ require(id: string): SshConnection {
160
147
  const row = getRowById(id);
161
- if (!row || !hasConnectionAccess(row, userId, isAdmin)) {
148
+ if (!row) {
162
149
  throw new Error('ssh connection not found');
163
150
  }
164
151
  return rowToConnection(row);
@@ -169,11 +156,11 @@ export const sshConnectionQueries = {
169
156
  return row ? rowToConnection(row) : null;
170
157
  },
171
158
 
172
- createForUser(input: SshConnectionInput, ownerUserId: string): SshConnection {
159
+ createRedacted(input: SshConnectionInput): SshConnection {
173
160
  if (input.jumpConnectionId && !getRowById(input.jumpConnectionId)) {
174
161
  throw new Error('Jump host not found');
175
162
  }
176
- return redactConnectionSecrets(insertConnection(input, ownerUserId));
163
+ return redactConnectionSecrets(insertConnection(input));
177
164
  },
178
165
 
179
166
  update(id: string, patch: Partial<SshConnectionInput>): SshConnection {
@@ -228,13 +215,8 @@ export const sshConnectionQueries = {
228
215
  return rowToConnection(row);
229
216
  },
230
217
 
231
- updateForUser(
232
- id: string,
233
- patch: Partial<SshConnectionInput>,
234
- userId: string,
235
- isAdmin: boolean
236
- ): SshConnection {
237
- this.ensureAccess(id, userId, isAdmin);
218
+ updateRedacted(id: string, patch: Partial<SshConnectionInput>): SshConnection {
219
+ this.require(id);
238
220
  return redactConnectionSecrets(this.update(id, patch));
239
221
  },
240
222
 
@@ -243,11 +225,6 @@ export const sshConnectionQueries = {
243
225
  db.prepare('DELETE FROM ssh_connections WHERE id = ?').run(id);
244
226
  },
245
227
 
246
- deleteForUser(id: string, userId: string, isAdmin: boolean): void {
247
- this.ensureAccess(id, userId, isAdmin);
248
- this.delete(id);
249
- },
250
-
251
228
  markUsed(id: string): void {
252
229
  const db = getDatabase();
253
230
  db.prepare('UPDATE ssh_connections SET last_used_at = ? WHERE id = ?').run(new Date().toISOString(), id);
@@ -11,11 +11,6 @@
11
11
  * database answers was resolved when the link was created (see `links.ts`) and
12
12
  * stored on the link; here it is only copied onto a row. That keeps a token
13
13
  * rotation from waiting on a third-party API before the account can be saved.
14
- *
15
- * A projected row is created with NO OWNER, which in db-client's access model
16
- * means admins see it and members do not. That matches who can create it:
17
- * `integrations:*` is admin-gated, because connecting an account changes what
18
- * the whole install can reach.
19
14
  */
20
15
 
21
16
  import {
@@ -34,3 +34,50 @@ describe('Claude workflow tools', () => {
34
34
  expect(staticHeartbeat).toEqual([]);
35
35
  });
36
36
  });
37
+
38
+ describe('Claude sub-agent scoping', () => {
39
+ const thinkingMessage = (parentToolUseId: string | null) => ({
40
+ type: 'assistant', session_id: 'session-1', uuid: crypto.randomUUID(), parent_tool_use_id: parentToolUseId,
41
+ message: {
42
+ model: 'claude-test', stop_reason: null, usage: null,
43
+ content: [
44
+ { type: 'thinking', thinking: 'considering the files' },
45
+ { type: 'text', text: 'done', citations: null },
46
+ ],
47
+ },
48
+ } as any);
49
+
50
+ test('keeps a sub-agent\'s thinking inside its Agent tool', () => {
51
+ const outputs = [...createSdkMessageConverter()(thinkingMessage('agent-1'))];
52
+ const reasoning = outputs.find(o => o.type === 'reasoning');
53
+ const assistant = outputs.find(o => o.type === 'assistant');
54
+ expect(reasoning).toMatchObject({ parent: { toolUseId: 'agent-1' }, text: 'considering the files' });
55
+ expect(assistant).toMatchObject({ parent: { toolUseId: 'agent-1' } });
56
+ });
57
+
58
+ test('leaves root thinking at the root', () => {
59
+ const outputs = [...createSdkMessageConverter()(thinkingMessage(null))];
60
+ expect(outputs.find(o => o.type === 'reasoning')).toMatchObject({ parent: { toolUseId: null } });
61
+ });
62
+
63
+ test('drops a sub-agent\'s live partials without disturbing the root block state', () => {
64
+ const convert = createSdkMessageConverter();
65
+ const partial = (parent: string | null, event: Record<string, unknown>) => ({
66
+ type: 'stream_event', session_id: 'session-1', uuid: crypto.randomUUID(), parent_tool_use_id: parent, event,
67
+ } as any);
68
+
69
+ // Root opens a thinking block at index 0.
70
+ [...convert(partial(null, { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '' } }))];
71
+ // A sub-agent opens and closes a text block at the same index.
72
+ const child = [
73
+ ...convert(partial('agent-1', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } })),
74
+ ...convert(partial('agent-1', { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'child' } })),
75
+ ...convert(partial('agent-1', { type: 'content_block_stop', index: 0 })),
76
+ ];
77
+ expect(child).toEqual([]);
78
+
79
+ // The root's block still closes as reasoning.
80
+ const stop = [...convert(partial(null, { type: 'content_block_stop', index: 0 }))];
81
+ expect(stop).toEqual([{ type: 'stream_event', event: 'stop', sessionId: 'session-1', reasoning: true }]);
82
+ });
83
+ });
@@ -45,6 +45,7 @@ import type {
45
45
  StopReason,
46
46
  } from '$shared/types/unified';
47
47
  import { toCanonicalToolName, toMcpServerStatus } from '$shared/types/unified';
48
+ import { scopeToParentTool } from '../parent-scope';
48
49
 
49
50
  // ============================================================
50
51
  // Helper Mappers
@@ -220,7 +221,7 @@ export function convertAssistantMessage(msg: SDKAssistantMessage): EngineOutput[
220
221
  createdAt: new Date().toISOString(),
221
222
  messageId: crypto.randomUUID(),
222
223
  sessionId,
223
- parent: { messageId: null, sessionId: null, toolUseId: null },
224
+ parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
224
225
  engine: { type: 'claude-code', provider: 'anthropic', model: { id: betaMessage.model || '', name: '' }, account: { id: 0, name: '' } },
225
226
  text: reasoningText,
226
227
  };
@@ -262,7 +263,6 @@ export function convertUserMessage(msg: SDKUserMessage): UserMessage {
262
263
  sessionId: msg.session_id || null,
263
264
  parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
264
265
  engine: { type: 'claude-code', provider: 'anthropic', model: { id: '', name: '' }, account: { id: 0, name: '' } },
265
- sender: { id: '', name: '' },
266
266
  content,
267
267
  synthetic: true, // SDK-generated tool_result messages
268
268
  };
@@ -522,7 +522,30 @@ export function* convertSdkMessage(msg: SDKMessage): Generator<EngineOutput> {
522
522
  yield* dispatchSdkMessage(msg, createStreamConverterState());
523
523
  }
524
524
 
525
+ /**
526
+ * With `forwardSubagentText` on, the SDK forwards a sub-agent's whole
527
+ * conversation — thinking, text, and its live `stream_event` partials — tagged
528
+ * with `parent_tool_use_id`. Everything converted from such a frame is scoped to
529
+ * that parent tool here, by output type, so no converter below can let a
530
+ * child's output reach the main turn (see parent-scope.ts).
531
+ */
525
532
  function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Generator<EngineOutput> {
533
+ const parentToolUseId = (msg as { parent_tool_use_id?: string | null }).parent_tool_use_id || null;
534
+ if (!parentToolUseId) {
535
+ yield* dispatchUnscopedSdkMessage(msg, state);
536
+ return;
537
+ }
538
+ // A child's partials never reach the converter: their content-block indices
539
+ // would collide with the main turn's in `state.reasoningBlocks`, and the
540
+ // finalized child message arrives anyway.
541
+ if (msg.type === 'stream_event') return;
542
+ for (const output of dispatchUnscopedSdkMessage(msg, state)) {
543
+ const scoped = scopeToParentTool(output, parentToolUseId);
544
+ if (scoped) yield scoped;
545
+ }
546
+ }
547
+
548
+ function* dispatchUnscopedSdkMessage(msg: SDKMessage, state: StreamConverterState): Generator<EngineOutput> {
526
549
  switch (msg.type) {
527
550
  case 'assistant':
528
551
  for (const output of convertAssistantMessage(msg as SDKAssistantMessage)) {
@@ -349,7 +349,6 @@ export function createClineMessageConverter(options: ClineConverterOptions): Cli
349
349
  sessionId,
350
350
  parent: { messageId: null, sessionId: null, toolUseId: null },
351
351
  engine,
352
- sender: { id: '', name: '' },
353
352
  content: [{ type: 'tool_result', toolUseId: part.toolCallId, content: extractResultText(part.output), isError: !!part.isError }],
354
353
  synthetic: true,
355
354
  });
@@ -36,6 +36,7 @@ import { artifactFilter } from '$backend/profiles';
36
36
  import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
37
37
  import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
38
38
  import { EngineRuns } from '../run-registry';
39
+ import { scopeToParentTool } from '../parent-scope';
39
40
  import { subagentQueries } from '$backend/database/queries';
40
41
  import { readSubagentMd } from '$backend/subagents/store';
41
42
  import { getClineAccountForProvider, parseClineCredential, resolveClineAuth } from './credential';
@@ -251,26 +252,21 @@ export class ClineEngine implements AIEngine {
251
252
  });
252
253
 
253
254
  // Route the sub-agent's persisted messages into the PARENT stream as
254
- // sub-activities: tag each with `parent.toolUseId = <Agent block id>`
255
- // so the frontend folds them under the Agent tool. Only tool_use
256
- // steps (+ their tool_result) are surfaced — the collapsed sub-agent
257
- // view is a tool trail; the sub-agent's prose is already returned as
258
- // the Agent tool's result (its `outputText`). So we drop transient
259
- // events, reasoning, and text-only assistant messages.
255
+ // sub-activities: `scopeToParentTool` tags each with
256
+ // `parent.toolUseId = <Agent block id>` so the frontend folds them
257
+ // under the Agent tool, and drops transient events. Tool steps (+
258
+ // their tool_result) and reasoning are surfaced; text-only assistant
259
+ // messages are not — the sub-agent's prose is already returned as the
260
+ // Agent tool's result (its `outputText`).
260
261
  const subConverter = createClineMessageConverter({
261
262
  engine: { type: 'cline', provider, model: { id: modelId, name: modelId }, account: { id: account.id, name: account.name } },
262
263
  sessionId: crypto.randomUUID(),
263
264
  });
264
265
  const unsub = subAgent.subscribe((ev) => {
265
- for (const out of subConverter.convert(ev)) {
266
- if (out.type === 'user') {
267
- // tool_result messages — carry the sub-agent's tool outputs.
268
- } else if (out.type === 'assistant' && out.content.some(b => b.type === 'tool_use')) {
269
- // tool_use step — keep.
270
- } else {
271
- continue; // drop stream/result/init/notification/reasoning/text-only
272
- }
273
- out.parent = { messageId: null, sessionId: null, toolUseId: toolCallId };
266
+ for (const raw of subConverter.convert(ev)) {
267
+ const out = scopeToParentTool(raw, toolCallId);
268
+ if (!out) continue;
269
+ if (out.type === 'assistant' && !out.content.some(b => b.type === 'tool_use')) continue;
274
270
  queueHolder.queue?.push(out);
275
271
  }
276
272
  });
@@ -442,7 +442,6 @@ function buildToolResultUserMessage(
442
442
  // IMPORTANT: parent.toolUseId stays null (README §10.5 sharp edge).
443
443
  parent: { messageId: null, sessionId: null, toolUseId: null },
444
444
  engine: buildEngine(state.modelId),
445
- sender: { id: '', name: '' },
446
445
  content: [block],
447
446
  synthetic: true,
448
447
  };
@@ -613,7 +612,6 @@ function buildErrorUserMessage(item: ErrorItem, state: CodexStreamState): UserMe
613
612
  sessionId: state.sessionId,
614
613
  parent: { messageId: null, sessionId: null, toolUseId: null },
615
614
  engine: buildEngine(state.modelId),
616
- sender: { id: '', name: '' },
617
615
  content: [{ type: 'text', text: `Codex error: ${item.message}` }],
618
616
  synthetic: true,
619
617
  };
@@ -855,7 +855,7 @@ export function convertToolComplete(
855
855
 
856
856
  // AskUserQuestion: rewrite Copilot's plain-text result
857
857
  // (e.g. "User selected: X") into the `{"answers": {<q>: <a>}}` JSON
858
- // shape the UI's parseResultAnswers expects. Without this rewrite, the
858
+ // shape the UI's legacy parser reads. Without this rewrite, the
859
859
  // parser finds no matching question key and renders the bubble in the
860
860
  // red error state even though the user answered successfully.
861
861
  if (state.toolNames.get(data.toolCallId) === 'AskUserQuestion') {
@@ -881,7 +881,6 @@ export function convertToolComplete(
881
881
  sessionId: state.sessionId,
882
882
  parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
883
883
  engine: buildEngine(state.modelId),
884
- sender: { id: '', name: '' },
885
884
  content: [userBlock],
886
885
  synthetic: true,
887
886
  };
@@ -430,7 +430,6 @@ export function createCursorMessageConverter(options: CursorConverterOptions): C
430
430
  sessionId,
431
431
  parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
432
432
  engine,
433
- sender: { id: '', name: '' },
434
433
  content: [block],
435
434
  synthetic: true,
436
435
  };
@@ -484,7 +484,6 @@ export function convertUserMessage(
484
484
  sessionId,
485
485
  parent: { messageId: null, sessionId: null, toolUseId: null },
486
486
  engine: { type: 'opencode' as const, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } },
487
- sender: { id: '', name: '' },
488
487
  content,
489
488
  synthetic: false,
490
489
  };
@@ -649,7 +648,6 @@ export function convertAssistantMessages(
649
648
  sessionId,
650
649
  parent: { messageId: null, sessionId: null, toolUseId: null },
651
650
  engine: { type: 'opencode' as const, provider: providerID, model: { id: modelID, name: '' }, account: { id: 0, name: '' } },
652
- sender: { id: '', name: '' },
653
651
  content: [result],
654
652
  synthetic: true,
655
653
  };
@@ -826,6 +824,7 @@ export function convertReasoningMessage(
826
824
  reasoningText: string,
827
825
  ocMessage: OCMessage,
828
826
  sessionId: string,
827
+ parentToolUseId?: string,
829
828
  ): ReasoningMessage {
830
829
  const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
831
830
  const provId = assistantMsg?.providerID || '';
@@ -836,7 +835,7 @@ export function convertReasoningMessage(
836
835
  createdAt: new Date().toISOString(),
837
836
  messageId: crypto.randomUUID(),
838
837
  sessionId,
839
- parent: { messageId: null, sessionId: null, toolUseId: null },
838
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId || null },
840
839
  engine: { type: 'opencode' as const, provider: provId, model: { id: mdlId, name: '' }, account: { id: 0, name: '' } },
841
840
  text: reasoningText,
842
841
  };
@@ -948,7 +947,6 @@ export function convertToolResultOnly(
948
947
  sessionId,
949
948
  parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId || null },
950
949
  engine: { type: 'opencode' as const, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } },
951
- sender: { id: '', name: '' },
952
950
  content: [{
953
951
  type: 'tool_result',
954
952
  toolUseId,
@@ -20,6 +20,7 @@ import type {
20
20
  EventSessionError,
21
21
  Part,
22
22
  ToolPart,
23
+ ReasoningPart,
23
24
  Message as OCMessage,
24
25
  } from '@opencode-ai/sdk';
25
26
  import { fetchOpenCodeModels } from './models';
@@ -357,6 +358,7 @@ export class OpenCodeEngine implements AIEngine {
357
358
  const childAssistantMessages = new Map<string, OCMessage>(); // child msgID → message
358
359
  const childEmittedToolParts = new Set<string>();
359
360
  const childCompletedToolParts = new Set<string>();
361
+ const childEmittedReasoningParts = new Set<string>();
360
362
  let lastAgentToolCallId: string | null = null;
361
363
 
362
364
  /**
@@ -492,6 +494,15 @@ export class OpenCodeEngine implements AIEngine {
492
494
  yield convertToolResultOnly(childToolPart, sessionId, agentCallId);
493
495
  }
494
496
  }
497
+ } else if (part.type === 'reasoning') {
498
+ // The sub-agent's thinking belongs to its Agent block. Its
499
+ // deltas never stream (they would land in the main turn's
500
+ // placeholder); the finished part is emitted once, tagged.
501
+ const childReasoning = part as ReasoningPart;
502
+ if (childReasoning.time?.end && childReasoning.text?.trim() && !childEmittedReasoningParts.has(part.id)) {
503
+ childEmittedReasoningParts.add(part.id);
504
+ yield convertReasoningMessage(childReasoning.text, childMsg, sessionId, agentCallId);
505
+ }
495
506
  }
496
507
  }
497
508
  break;
@@ -0,0 +1,38 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { EngineOutput } from '$shared/types/unified';
3
+ import { scopeToParentTool } from './parent-scope';
4
+
5
+ const engine = { type: 'claude-code', provider: 'anthropic', model: { id: '', name: '' }, account: { id: 0, name: '' } } as const;
6
+ const base = { createdAt: '', messageId: 'm', sessionId: 's', engine, parent: { messageId: null, sessionId: null, toolUseId: null } };
7
+
8
+ describe('scopeToParentTool', () => {
9
+ test('tags every persisted message kind with the parent tool', () => {
10
+ const messages: EngineOutput[] = [
11
+ { ...base, type: 'reasoning', text: 'thinking' },
12
+ { ...base, type: 'assistant', content: [{ type: 'text', text: 'hi' }], stopReason: null, usage: null },
13
+ { ...base, type: 'user', content: [{ type: 'text', text: 'hi' }], synthetic: true },
14
+ { ...base, type: 'compact_boundary', trigger: 'auto', preTokens: 0 },
15
+ ];
16
+ for (const message of messages) {
17
+ expect(scopeToParentTool(message, 'agent-1')).toMatchObject({ type: message.type, parent: { toolUseId: 'agent-1' } });
18
+ }
19
+ });
20
+
21
+ test('keeps the closer parent of a nested sub-agent and does not mutate', () => {
22
+ const nested: EngineOutput = { ...base, type: 'reasoning', text: 't', parent: { ...base.parent, toolUseId: 'inner' } };
23
+ expect(scopeToParentTool(nested, 'outer')).toBe(nested);
24
+
25
+ const root: EngineOutput = { ...base, type: 'reasoning', text: 't' };
26
+ scopeToParentTool(root, 'agent-1');
27
+ expect(root.parent.toolUseId).toBeNull();
28
+ });
29
+
30
+ test('drops turn-level output a child must never drive', () => {
31
+ const transient: EngineOutput[] = [
32
+ { type: 'stream_event', event: 'delta', sessionId: 's', text: 'x', reasoning: true },
33
+ { type: 'stream_event', event: 'start', sessionId: 's', reasoning: false },
34
+ { type: 'result', subtype: 'success', sessionId: 's', numTurns: 1, totalCostUsd: 0, usage: { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 }, stopReason: null },
35
+ ];
36
+ for (const output of transient) expect(scopeToParentTool(output, 'agent-1')).toBeNull();
37
+ });
38
+ });