@myrialabs/clopen 0.4.23 → 0.4.25

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 (53) hide show
  1. package/backend/chat/stream-manager.ts +41 -13
  2. package/backend/engine/README.md +18 -0
  3. package/backend/engine/adapters/claude/message-converter.test.ts +36 -0
  4. package/backend/engine/adapters/claude/message-converter.ts +40 -4
  5. package/backend/engine/adapters/claude/stream.ts +68 -3
  6. package/backend/engine/adapters/claude/workflow-transcript.test.ts +65 -0
  7. package/backend/engine/adapters/claude/workflow-transcript.ts +248 -0
  8. package/backend/engine/adapters/coordination-tool-mapping.test.ts +17 -0
  9. package/backend/engine/adapters/copilot/message-converter.ts +20 -1
  10. package/backend/engine/adapters/opencode/message-converter.test.ts +80 -0
  11. package/backend/engine/adapters/opencode/message-converter.ts +32 -0
  12. package/backend/engine/adapters/opencode/stream.ts +29 -23
  13. package/backend/engine/adapters/qwen/message-converter.ts +5 -8
  14. package/backend/engine/docs/adapter-contract.md +29 -1
  15. package/backend/engine/docs/adding-an-engine.md +8 -1
  16. package/backend/engine/docs/frontend-and-chat.md +32 -1
  17. package/backend/engine/docs/lessons-learned.md +49 -2
  18. package/backend/engine/docs/quick-reference.md +2 -0
  19. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +3 -0
  20. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +3 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +5 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +8 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +10 -0
  24. package/backend/mcp/internal/servers/browser-automation/context.ts +6 -0
  25. package/backend/mcp/internal/servers/browser-automation/description.ts +1 -1
  26. package/backend/mcp/internal/servers/browser-automation/runner.ts +21 -1
  27. package/backend/mcp/internal/servers/browser-automation/schema.ts +1 -1
  28. package/backend/module-shadowing.test.ts +135 -0
  29. package/backend/preview/browser/browser-host-bridge.ts +8 -2
  30. package/backend/preview/browser/browser-interaction-handler.ts +95 -38
  31. package/backend/preview/browser/browser-mcp-control.ts +332 -22
  32. package/backend/preview/browser/browser-preview-service.ts +152 -33
  33. package/backend/preview/browser/browser-tab-manager.ts +25 -1
  34. package/backend/preview/browser/browser-video-capture.ts +551 -247
  35. package/backend/preview/browser/scripts/host-bridge.ts +61 -89
  36. package/backend/preview/browser/scripts/video-stream.ts +32 -0
  37. package/backend/preview/browser/types.ts +22 -0
  38. package/backend/preview/index.ts +6 -1
  39. package/backend/ws/preview/browser/console.ts +12 -10
  40. package/backend/ws/preview/browser/interact.ts +40 -10
  41. package/backend/ws/preview/browser/native-ui.ts +35 -10
  42. package/backend/ws/preview/browser/tab-info.ts +46 -7
  43. package/backend/ws/preview/browser/webcodecs.ts +6 -1
  44. package/backend/ws/preview/index.ts +23 -3
  45. package/dist/assets/{index-DH_GO0Lf.js → index-C4PD7B-x.js} +1 -1
  46. package/dist/assets/{index-igSQ3JaM.js → index-KBGloYDk.js} +1 -1
  47. package/dist/assets/{main-D-d8SFfW.js → main-B0AA-88X.js} +364 -358
  48. package/dist/assets/main-OsjA5Ab5.css +1 -0
  49. package/dist/index.html +2 -2
  50. package/package.json +1 -1
  51. package/shared/types/unified/index.ts +7 -0
  52. package/shared/types/unified/tool.ts +57 -2
  53. package/dist/assets/main-BD3-qPfT.css +0 -1
@@ -139,6 +139,11 @@ const COPILOT_TOOL_NAME_MAP: Record<string, string> = {
139
139
  // asynchronously; events from the sub-agent arrive with `agentId` set and
140
140
  // must thread back to this tool's call id via parent.toolUseId).
141
141
  'task': 'Agent',
142
+ 'write_agent': 'SendMessage',
143
+ 'list_agents': 'ListAgents',
144
+ 'read_agent': 'ReadAgent',
145
+ 'send_inbox': 'SendInbox',
146
+ 'context_board': 'ContextBoard',
142
147
 
143
148
  // User interaction
144
149
  'ask_user': 'AskUserQuestion',
@@ -177,7 +182,7 @@ export function isIgnoredCopilotTool(rawName: string, mcpServerName?: string): b
177
182
  }
178
183
 
179
184
  /** Map a raw Copilot tool name (with optional MCP server) to a canonical UI name. */
180
- function mapCopilotToolName(rawName: string, mcpServerName?: string): string {
185
+ export function mapCopilotToolName(rawName: string, mcpServerName?: string): string {
181
186
  if (mcpServerName) {
182
187
  // Tools served via our remote MCP HTTP endpoint (`clopen-mcp`) come
183
188
  // back as `{ name: '<bare-tool>', mcpServerName: 'clopen-mcp' }`. Resolve
@@ -406,6 +411,14 @@ function normalizeAgentInput(raw: RawToolArgs): AgentInput {
406
411
  };
407
412
  }
408
413
 
414
+ function normalizeCoordinationInput(raw: RawToolArgs): Record<string, unknown> {
415
+ const result: Record<string, unknown> = {};
416
+ for (const [key, value] of Object.entries(raw)) {
417
+ result[key.replace(/_([a-z])/g, (_, char: string) => char.toUpperCase())] = value;
418
+ }
419
+ return result;
420
+ }
421
+
409
422
  /**
410
423
  * Normalize raw Copilot tool arguments → canonical input shape. Unknown/MCP
411
424
  * tools fall through with their args unchanged.
@@ -426,6 +439,12 @@ function normalizeCopilotToolInput(canonical: string, raw: RawToolArgs): Record<
426
439
  case 'TodoWrite': return normalizeTodoWriteInput(raw) as unknown as Record<string, unknown>;
427
440
  case 'ToolSearch': return normalizeToolSearchInput(raw) as unknown as Record<string, unknown>;
428
441
  case 'Agent': return normalizeAgentInput(raw) as unknown as Record<string, unknown>;
442
+ case 'SendMessage':
443
+ case 'ListAgents':
444
+ case 'ReadAgent':
445
+ case 'SendInbox':
446
+ case 'ContextBoard':
447
+ return normalizeCoordinationInput(raw);
429
448
  default: return raw;
430
449
  }
431
450
  }
@@ -0,0 +1,80 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { AssistantMessage, Part, TextPart } from '@opencode-ai/sdk';
3
+
4
+ import { convertPendingTextParts } from './message-converter';
5
+
6
+ const sessionId = 'session-1';
7
+ const messageId = 'message-1';
8
+
9
+ const assistantMessage: AssistantMessage = {
10
+ id: messageId,
11
+ sessionID: sessionId,
12
+ role: 'assistant',
13
+ time: { created: 1 },
14
+ parentID: 'user-1',
15
+ modelID: 'model-1',
16
+ providerID: 'provider-1',
17
+ mode: 'build',
18
+ path: { cwd: '/project', root: '/project' },
19
+ cost: 0,
20
+ tokens: {
21
+ input: 0,
22
+ output: 0,
23
+ reasoning: 0,
24
+ cache: { read: 0, write: 0 },
25
+ },
26
+ };
27
+
28
+ function textPart(id: string, text: string): TextPart {
29
+ return {
30
+ id,
31
+ sessionID: sessionId,
32
+ messageID: messageId,
33
+ type: 'text',
34
+ text,
35
+ };
36
+ }
37
+
38
+ describe('convertPendingTextParts', () => {
39
+ test('finalizes each text segment once across successive tool boundaries', () => {
40
+ const emittedTextPartIds = new Set<string>();
41
+ const parts: Part[] = [textPart('text-1', 'A3')];
42
+
43
+ const beforeFirstTool = convertPendingTextParts(
44
+ assistantMessage,
45
+ parts,
46
+ sessionId,
47
+ emittedTextPartIds,
48
+ );
49
+
50
+ expect(beforeFirstTool).toHaveLength(1);
51
+ expect(beforeFirstTool[0]).toMatchObject({
52
+ type: 'assistant',
53
+ content: [{ type: 'text', text: 'A3' }],
54
+ });
55
+ expect(emittedTextPartIds).toEqual(new Set(['text-1']));
56
+
57
+ // The normal message finalizer sees the same accumulated parts later.
58
+ expect(convertPendingTextParts(
59
+ assistantMessage,
60
+ parts,
61
+ sessionId,
62
+ emittedTextPartIds,
63
+ )).toEqual([]);
64
+
65
+ parts.push(textPart('text-2', 'A7'));
66
+ const beforeSecondTool = convertPendingTextParts(
67
+ assistantMessage,
68
+ parts,
69
+ sessionId,
70
+ emittedTextPartIds,
71
+ );
72
+
73
+ expect(beforeSecondTool).toHaveLength(1);
74
+ expect(beforeSecondTool[0]).toMatchObject({
75
+ type: 'assistant',
76
+ content: [{ type: 'text', text: 'A7' }],
77
+ });
78
+ expect(emittedTextPartIds).toEqual(new Set(['text-1', 'text-2']));
79
+ });
80
+ });
@@ -660,6 +660,38 @@ export function convertAssistantMessages(
660
660
  return messages;
661
661
  }
662
662
 
663
+ /**
664
+ * Convert text parts that have not yet been finalized.
665
+ *
666
+ * OpenCode can append a tool part to the same assistant message while the
667
+ * preceding text is still represented by a live stream placeholder. Flushing
668
+ * that text before emitting the tool preserves the source part order. Tracking
669
+ * part IDs prevents the normal message/session finalizer from emitting it a
670
+ * second time later.
671
+ */
672
+ export function convertPendingTextParts(
673
+ ocMessage: OCMessage,
674
+ ocParts: Part[],
675
+ sessionId: string,
676
+ emittedTextPartIds: Set<string>,
677
+ ): EngineOutput[] {
678
+ const pendingTextParts = ocParts.filter(part =>
679
+ part.type === 'text' && !emittedTextPartIds.has(part.id)
680
+ );
681
+
682
+ for (const part of pendingTextParts) {
683
+ emittedTextPartIds.add(part.id);
684
+ }
685
+
686
+ const visibleTextParts = pendingTextParts.filter(part =>
687
+ part.type === 'text' && Boolean(part.text)
688
+ );
689
+
690
+ return visibleTextParts.length > 0
691
+ ? convertAssistantMessages(ocMessage, visibleTextParts, sessionId)
692
+ : [];
693
+ }
694
+
663
695
  /**
664
696
  * Convert Open Code result/completion → ResultEvent
665
697
  */
@@ -25,6 +25,7 @@ import type {
25
25
  import { fetchOpenCodeModels } from './models';
26
26
  import {
27
27
  convertAssistantMessages,
28
+ convertPendingTextParts,
28
29
  convertResultMessage,
29
30
  convertSystemInitMessage,
30
31
  convertStreamStart,
@@ -291,6 +292,7 @@ export class OpenCodeEngine implements AIEngine {
291
292
  let streamingText = '';
292
293
  const emittedToolParts = new Set<string>(); // Tool parts already emitted as tool_use
293
294
  const completedToolParts = new Set<string>(); // Tool parts whose tool_result was emitted
295
+ const emittedTextParts = new Set<string>(); // Text parts finalized before a tool boundary
294
296
  // callID/partId → raw tool name, so a `permission.asked` event (which
295
297
  // carries only a callID) can be resolved to the tool being permitted.
296
298
  const callIdToTool = new Map<string, string>();
@@ -318,6 +320,25 @@ export class OpenCodeEngine implements AIEngine {
318
320
  reasoningText = '';
319
321
  };
320
322
 
323
+ /** Finalize text accumulated before an eagerly emitted tool/subtask. */
324
+ const flushPendingText = function* (msgId: string, msg: OCMessage) {
325
+ const parts = messageParts.get(msgId) || [];
326
+ for (const output of convertPendingTextParts(msg, parts, sessionId, emittedTextParts)) {
327
+ yield output;
328
+ }
329
+ };
330
+
331
+ /** Parts that still need to be emitted by the message/session finalizer. */
332
+ const getRemainingParts = (msgId: string): Part[] => {
333
+ return (messageParts.get(msgId) || []).filter(part => {
334
+ if (part.type === 'text') return !emittedTextParts.has(part.id);
335
+ if (part.type === 'tool') return !emittedToolParts.has(part.id);
336
+ if (part.type === 'subtask') return !emittedToolParts.has(part.id);
337
+ if (part.type === 'reasoning') return false;
338
+ return true;
339
+ });
340
+ };
341
+
321
342
  /**
322
343
  * Finalize and yield an assistant message by ID
323
344
  * Emits stop stream event, the assembled message, and restarts stream for next message
@@ -334,14 +355,7 @@ export class OpenCodeEngine implements AIEngine {
334
355
  // Stop current stream
335
356
  yield convertStreamStop(sessionId);
336
357
 
337
- const parts = messageParts.get(msgId) || [];
338
- // Filter out tool parts, subtask parts, and reasoning parts already emitted
339
- const remainingParts = parts.filter(p => {
340
- if (p.type === 'tool') return !emittedToolParts.has(p.id);
341
- if (p.type === 'subtask') return !emittedToolParts.has(p.id);
342
- if (p.type === 'reasoning') return false; // Already emitted as reasoning message
343
- return true;
344
- });
358
+ const remainingParts = getRemainingParts(msgId);
345
359
 
346
360
  if (remainingParts.length > 0) {
347
361
  const splitMessages = convertAssistantMessages(msg, remainingParts, sessionId);
@@ -485,6 +499,10 @@ export class OpenCodeEngine implements AIEngine {
485
499
  }
486
500
 
487
501
  yield convertStreamStop(sessionId);
502
+ // OpenCode keeps text + tool parts in one assistant message.
503
+ // Materialize the visible text placeholder before the tool
504
+ // can replace it in the frontend.
505
+ yield* flushPendingText(msgId, msg);
488
506
  yield convertToolUseOnly(toolPart, msg, sessionId);
489
507
 
490
508
  // If already completed on first sight, emit result immediately too
@@ -544,6 +562,7 @@ export class OpenCodeEngine implements AIEngine {
544
562
  yield* flushReasoning(msg);
545
563
  }
546
564
  yield convertStreamStop(sessionId);
565
+ yield* flushPendingText(msgId, msg);
547
566
  yield convertSubtaskToolUseOnly(subtaskPart, msg, sessionId);
548
567
  yield convertStreamStart(sessionId);
549
568
  streamingText = '';
@@ -609,14 +628,7 @@ export class OpenCodeEngine implements AIEngine {
609
628
  }
610
629
  yield convertStreamStop(sessionId);
611
630
  if (msg) {
612
- const parts = messageParts.get(currentAssistantId) || [];
613
- // Filter out tool parts and reasoning parts already emitted
614
- const remainingParts = parts.filter(p => {
615
- if (p.type === 'tool') return !emittedToolParts.has(p.id);
616
- if (p.type === 'subtask') return !emittedToolParts.has(p.id);
617
- if (p.type === 'reasoning') return false;
618
- return true;
619
- });
631
+ const remainingParts = getRemainingParts(currentAssistantId);
620
632
  if (remainingParts.length > 0) {
621
633
  const splitMsgs1 = convertAssistantMessages(msg, remainingParts, sessionId);
622
634
  for (const m of splitMsgs1) {
@@ -654,13 +666,7 @@ export class OpenCodeEngine implements AIEngine {
654
666
  }
655
667
  yield convertStreamStop(sessionId);
656
668
  if (msg) {
657
- const parts = messageParts.get(currentAssistantId) || [];
658
- const remainingParts = parts.filter(p => {
659
- if (p.type === 'tool') return !emittedToolParts.has(p.id);
660
- if (p.type === 'subtask') return !emittedToolParts.has(p.id);
661
- if (p.type === 'reasoning') return false;
662
- return true;
663
- });
669
+ const remainingParts = getRemainingParts(currentAssistantId);
664
670
  if (remainingParts.length > 0) {
665
671
  const splitMsgs2 = convertAssistantMessages(msg, remainingParts, sessionId);
666
672
  for (const m of splitMsgs2) {
@@ -199,6 +199,7 @@ const QWEN_TOOL_NAME_MAP: Record<string, string> = {
199
199
  'task': 'Agent',
200
200
  'dispatch_agent': 'Agent',
201
201
  'task_stop': 'TaskStop',
202
+ 'send_message': 'SendMessage',
202
203
  // Question / harness
203
204
  'ask_user_question': 'AskUserQuestion',
204
205
  'skill': 'Skill',
@@ -207,21 +208,17 @@ const QWEN_TOOL_NAME_MAP: Record<string, string> = {
207
208
  'cron_create': 'CronCreate',
208
209
  'cron_list': 'CronList',
209
210
  'cron_delete': 'CronDelete',
210
- // `send_message` is the Qwen-specific channel the parent uses to push a
211
- // follow-up prompt into a backgrounded sub-agent. There's no canonical
212
- // equivalent — keep its raw name so the UI renders it as Unknown:* rather
213
- // than silently swallowing the call.
214
211
  };
215
212
 
216
- function canonicaliseToolName(rawName: string): string {
213
+ export function canonicaliseToolName(rawName: string): string {
214
+ const mapped = QWEN_TOOL_NAME_MAP[rawName];
215
+ if (mapped) return mapped;
216
+
217
217
  // MCP tools come through as `clopen-mcp_<tool>` or `clopen-mcp-<tool>` —
218
218
  // route through the shared resolver so they collapse to the canonical
219
219
  // `mcp__<server>__<tool>` form (README §10.12).
220
220
  const resolved = resolveOpenCodeToolName(rawName);
221
221
  if (resolved) return resolved;
222
-
223
- const mapped = QWEN_TOOL_NAME_MAP[rawName];
224
- if (mapped) return mapped;
225
222
  // Already canonical (PascalCase) — let toCanonicalToolName decide.
226
223
  return rawName;
227
224
  }
@@ -96,6 +96,35 @@ type EngineOutput =
96
96
  > `shared/types/unified/stream.ts` first, teach `stream-manager` how to
97
97
  > route it, and only then emit it from the adapter.
98
98
 
99
+ #### Parent-tool activity contract (`Agent` / `Workflow`)
100
+
101
+ Nested activity is still ordinary `AssistantMessage` / `UserMessage` output;
102
+ its placement is determined by `message.parent.toolUseId`.
103
+
104
+ The following invariants are mandatory:
105
+
106
+ 1. Emit the parent tool message before any child activity.
107
+ 2. Set every child message's `parent.toolUseId` to the parent tool call id
108
+ before yielding it. Never emit a root-shaped child and patch it later.
109
+ 3. Keep top-level tool results at `parent.toolUseId = null`; the id of the tool
110
+ they answer belongs on the inner `tool_result.toolUseId`.
111
+ 4. Do not forward nested text/reasoning `stream_event` deltas unless the
112
+ protocol can carry their parent id. Suppress them and emit the finalized
113
+ parent-tagged message instead.
114
+ 5. When activity comes from a side channel, merge it with the SDK stream using
115
+ a push queue. Use the source's native notification mechanism (for example
116
+ filesystem change events for JSONL transcripts), not interval polling.
117
+ 6. Preserve source timestamps and byte/file offsets so events retain their
118
+ actual order and are emitted exactly once.
119
+ 7. Keep the merged stream open until the parent run reports a terminal status,
120
+ then perform one final drain and release watchers/listeners on success,
121
+ cancellation, and error.
122
+
123
+ The frontend groups parent-tagged messages directly into `subActivities`.
124
+ They must never claim a root `stream_event` placeholder; doing so produces a
125
+ visible root-to-child jump even though the persisted DB relation is correct.
126
+ See §10.15 and frontend-and-chat §6.5.
127
+
99
128
  ### 2.4 `EngineQueryOptions`
100
129
 
101
130
  ```ts
@@ -249,4 +278,3 @@ Important conventions:
249
278
  the per-adapter taxonomy — the adapter only calls them. See §8.3.
250
279
 
251
280
  ---
252
-
@@ -92,6 +92,14 @@ mandatory files; optional files use the canonical names from §2.6.
92
92
  (`cline/agent-tool.ts`), register it + `toolPolicies.Agent`, route the
93
93
  sub-agent's messages into the stream tagged with `parent.toolUseId`, and
94
94
  push **tool_use only** as sub-activities — see §10.15.
95
+ - [ ] **Parent/background tools (native or synthetic).** Emit the canonical
96
+ parent before its children and stamp the parent tool call id onto every
97
+ child before yielding it. Suppress child partial deltas when they lack a
98
+ parent id. If activity arrives through a side channel, bridge its native
99
+ notifications into the stream with an event queue—never timer polling—
100
+ retain offsets/timestamps, continue through terminal run status, and
101
+ clean up listeners in `finally`. Verify that a child can never replace a
102
+ root frontend placeholder. See §10.15 and frontend-and-chat §6.5.
95
103
  - [ ] `models.ts` (mandatory) → static `NEWENGINE_MODELS: EngineModel[]`
96
104
  OR `fetchNewengineModels(...): Promise<EngineModel[]>` (dynamic;
97
105
  return `[]` on failure — see §4.5).
@@ -275,4 +283,3 @@ Then the minimum UI scenarios that must pass:
275
283
  in chat).
276
284
 
277
285
  ---
278
-
@@ -269,5 +269,36 @@ Backend `chat:stream` then `streamManager.startStream(...)`, which:
269
269
  it — wire the engine's native hook to `resolveUserAnswer` when it
270
270
  exists. See §10.12 point 3.
271
271
 
272
- ---
272
+ ### 6.5 Parent tools and root-placeholder isolation
273
+
274
+ `Agent`, `Workflow`, and future background/delegation tools use
275
+ `parent.toolUseId` as their placement contract:
276
+
277
+ - The parent assistant message contains the canonical parent `tool_use` block.
278
+ - Every child assistant/user message carries that block's id in
279
+ `message.parent.toolUseId` from its first WebSocket emission.
280
+ - `groupMessages()` removes those child rows from the root timeline and stores
281
+ them in `subAgentMap[parentToolUseId]`.
282
+ - `processToolMessage()` converts the collected child messages into the
283
+ parent's `subActivities`.
284
+
285
+ The live message handler must preserve that contract before Svelte renders a
286
+ frame. In `chat.service.ts::handleMessageEvent`, only a root assistant
287
+ (`!message.parent?.toolUseId`) may replace the root non-reasoning
288
+ `stream_event` placeholder. A parent-tagged assistant is appended intact so
289
+ the grouper consumes it immediately. Do not insert a child at root with the
290
+ intention of moving it later; transitions and reactive passes make that move
291
+ visible as flicker.
292
+
293
+ Current transient `stream_event` messages do not carry parent metadata.
294
+ Adapters must therefore suppress child text/reasoning deltas and emit
295
+ finalized parent-tagged messages, unless the unified stream protocol is first
296
+ extended to make placeholders parent-aware end to end.
297
+
298
+ For a file-backed producer such as Claude Workflow, the adapter watches the
299
+ transcript source and pushes complete parent-tagged messages through the same
300
+ engine output stream. The frontend should not know whether activity came from
301
+ an SDK event or a filesystem event; grouping behavior must be identical to
302
+ Agent/Task.
273
303
 
304
+ ---
@@ -568,7 +568,7 @@ spawns a fresh subprocess per turn, you almost certainly want the
568
568
  auth-blob swap (§10.13) instead — adding the restart event ships dead
569
569
  code and confuses the UX (button that does nothing observable).
570
570
 
571
- ### 10.15 Sub-agent (`Task` / `Agent` tool) routing — name, input, parent id
571
+ ### 10.15 Parent-tool activity (`Task` / `Agent` / `Workflow`) — route before render
572
572
 
573
573
  Every engine SDK we support exposes a "dispatch sub-agent" tool. Each
574
574
  SDK names it differently (Claude → `Task`, OpenCode → `task`, Copilot →
@@ -693,6 +693,54 @@ conversation, nor a later checkpoint fork of it (§10.10). See
693
693
  `cline/agent-tool.ts` + the dispatch block in `cline/stream.ts` (and the
694
694
  Pi equivalents) for the reference implementation.
695
695
 
696
+ **File-backed background tools (`Workflow`) need a push bridge, not a timer.**
697
+ Claude's `Workflow` differs from `Task`: the SDK stream contains the Workflow
698
+ tool call and launch result, but child agents append their conversations to
699
+ `agent-*.jsonl` files under the reported transcript directory. Waiting for the
700
+ next SDK heartbeat batches unrelated records together; polling every N
701
+ milliseconds merely hides that defect and adds guessed latency.
702
+
703
+ The reference implementation is
704
+ `claude/workflow-transcript.ts` + the merge queue in `claude/stream.ts`:
705
+
706
+ 1. Observe the complete `Workflow` tool call and launch result, then register
707
+ the transcript directory against that exact tool call id.
708
+ 2. Watch the transcript and run-status directories with filesystem change
709
+ events. A file create/append wakes the producer immediately.
710
+ 3. Read only complete newline-delimited records after each file's saved byte
711
+ offset. Coalesced filesystem notifications are harmless because the file,
712
+ not the notification count, is the source of truth.
713
+ 4. Convert visible child messages and stamp the Workflow id onto
714
+ `parent.toolUseId` before pushing them into the merged `EventQueue`.
715
+ 5. Preserve each transcript record's timestamp. Assigning `new Date()` while
716
+ draining makes a batch look simultaneous and destroys useful ordering.
717
+ 6. Continue watching after the main SDK iterator ends. The background process
718
+ can still be writing; close only after the run status is terminal, perform
719
+ a final drain, and dispose every watcher in `finally`.
720
+
721
+ Do not display a Workflow as *running* from a partial `tool_use` start event.
722
+ At that point its JSON input/script is incomplete and execution has not begun.
723
+ The valid empty-`subActivities` state starts when the complete parent tool call
724
+ is emitted; subsequent filesystem events populate it.
725
+
726
+ **Frontend invariant: a child may never claim a root placeholder.**
727
+ `chat.service.ts::handleMessageEvent` replaces a transient text placeholder
728
+ only for assistant messages whose `parent.toolUseId` is null. A child assistant
729
+ must be pushed intact so `message-grouper.ts` folds it into the parent's
730
+ `subActivities` in the same reactive pass. If the handler replaces a root
731
+ placeholder indiscriminately, every nested tool flashes at root and then
732
+ appears to move under its parent even though the database relation was correct
733
+ from the beginning.
734
+
735
+ Regression checks for any new parent tool should prove all of the following:
736
+
737
+ - the parent is emitted before children and initially accepts an empty activity list;
738
+ - every child has the correct parent id on its first emitted shape;
739
+ - source notifications wake the side-channel producer without a timer;
740
+ - repeated/coalesced notifications do not duplicate records;
741
+ - SDK completion does not truncate a still-running background producer;
742
+ - no parent-tagged assistant replaces a root streaming placeholder.
743
+
696
744
  ### 10.16 `generateStructured` — schema strictness & part-extraction fallback
697
745
 
698
746
  `generateStructured` powers three one-shot JSON callers: the AI
@@ -1224,4 +1272,3 @@ costs one effect and buys two things: the value sent with the turn always
1224
1272
  matches what actually ran (so `MessageEngine.reasoningEffort` in the Raw
1225
1273
  view is truthful), and a level valid for the previous model can never
1226
1274
  leak into a request for the next one.
1227
-
@@ -22,6 +22,8 @@
22
22
  | Cancel-before-RPC ordering | `opencode/stream.ts::cancel`, `claude/stream.ts::cancel`, `copilot/stream.ts::cancel` |
23
23
  | Fork session (native vs. on-disk vs. in-memory) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state), `pi/session-fork.ts` (`SessionManager.forkFrom`), `cline/stream.ts` (**session-less** — fresh id per turn + in-memory copy-on-branch; see §10.10) |
24
24
  | Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap`; **synthesized** `Agent` tool for bare-loop SDKs in `cline/agent-tool.ts` + `pi/agent-tool.ts` (see §10.15) |
25
+ | File-backed Workflow activity (event-driven) | `claude/workflow-transcript.ts` (filesystem watchers, byte offsets, terminal status) + `claude/stream.ts::EventQueue` merge; no interval polling (§10.15) |
26
+ | Keep parent-tool children out of root placeholders | `frontend/services/chat/chat.service.ts::handleMessageEvent` (`!message.parent?.toolUseId`) + `frontend/utils/chat/message-grouper.ts` (`subAgentMap`); frontend-and-chat §6.5 |
25
27
  | AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
26
28
  | MCP servers exposed over HTTP (single source) | `backend/mcp/internal/remote-server.ts`, `backend/mcp/internal/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
27
29
  | Materialize an artifact per engine (matrix) | `backend/artifacts/matrix.ts::resolveArtifact`, generic writer `backend/artifacts/sync.ts`, scanner `backend/artifacts/detect.ts` (see §8.2) |
@@ -9,6 +9,7 @@ import { commonFields } from './shared';
9
9
  export const consoleLogs: ActionDef = {
10
10
  type: 'console_logs',
11
11
  kind: 'control',
12
+ activity: 'Reading the console',
12
13
  doc: `console_logs {limit?, level?} — the page's console output, oldest first.
13
14
  Where to look when an action "worked" but the page did not react: the error is usually here and invisible on screen.`,
14
15
  schema: z.object({
@@ -37,6 +38,7 @@ export const consoleLogs: ActionDef = {
37
38
  export const clearConsole: ActionDef = {
38
39
  type: 'clear_console',
39
40
  kind: 'control',
41
+ activity: 'Clearing the console',
40
42
  doc: `clear_console {} — drop stored console output.
41
43
  Put this before the step you are debugging so what follows is only that step's output.`,
42
44
  schema: z.object({ type: z.literal('clear_console'), ...commonFields }),
@@ -49,6 +51,7 @@ export const clearConsole: ActionDef = {
49
51
  export const evaluate: ActionDef = {
50
52
  type: 'eval',
51
53
  kind: 'control',
54
+ activity: 'Running a script',
52
55
  doc: `eval {expression} — run JavaScript in the page and return the result.
53
56
  For state that is not in the DOM: computed styles, localStorage, framework internals, window globals. The result must be JSON-serialisable.`,
54
57
  schema: z.object({
@@ -15,6 +15,7 @@ import { resolveWritePath } from '../paths';
15
15
  export const find: ActionDef = {
16
16
  type: 'find',
17
17
  kind: 'control',
18
+ activity: 'Looking for an element',
18
19
  doc: `find {selector?, text?, role?, limit?} — locate elements and get their positions.
19
20
  Returns tag, text, a reusable selector and a centre point for each match, iframes included.
20
21
  This is the cheap alternative to a screenshot: to click something you can name, find it and click by selector — no image, no vision, no coordinate guessing.`,
@@ -60,6 +61,7 @@ export const find: ActionDef = {
60
61
  export const analyzeDom: ActionDef = {
61
62
  type: 'analyze_dom',
62
63
  kind: 'control',
64
+ activity: 'Reading the page',
63
65
  doc: `analyze_dom {include?} — the page as text: links, headings, content, forms, metadata.
64
66
  The primary tool for reading and exploring. Far cheaper than a screenshot and it sees the whole document, not just the part currently on screen — scrolling to "see more" is never necessary.
65
67
  include: navigation | structure | content | forms | summary. Omit for all.
@@ -91,6 +93,7 @@ export const analyzeDom: ActionDef = {
91
93
  export const screenshot: ActionDef = {
92
94
  type: 'screenshot',
93
95
  kind: 'control',
96
+ activity: 'Taking a screenshot',
94
97
  doc: `screenshot {fullPage?, selector?, format?, quality?, saveTo?, return?} — capture the page.
95
98
  Needed for what the DOM cannot express: canvases, charts, iframes, captchas, and any visual check of layout or styling.
96
99
  saveTo writes a file under the project directory; with return:"file" the image is not sent back at all, which is what makes "capture twenty pages" affordable.
@@ -13,6 +13,7 @@ import { commonFields } from './shared';
13
13
  export const navigate: ActionDef = {
14
14
  type: 'navigate',
15
15
  kind: 'control',
16
+ activity: 'Navigating',
16
17
  doc: `navigate {url} — load a URL in the current tab.
17
18
  Following a link you already have the href for is cheaper and far more reliable than clicking it. Session state (cookies, storage) is kept.`,
18
19
  schema: z.object({
@@ -33,6 +34,7 @@ export const navigate: ActionDef = {
33
34
  export const goBack: ActionDef = {
34
35
  type: 'go_back',
35
36
  kind: 'control',
37
+ activity: 'Going back',
36
38
  doc: `go_back {steps?} — walk back through the tab's history.`,
37
39
  schema: z.object({
38
40
  type: z.literal('go_back'),
@@ -50,6 +52,7 @@ export const goBack: ActionDef = {
50
52
  export const goForward: ActionDef = {
51
53
  type: 'go_forward',
52
54
  kind: 'control',
55
+ activity: 'Going forward',
53
56
  doc: `go_forward {steps?} — walk forward through the tab's history.`,
54
57
  schema: z.object({
55
58
  type: z.literal('go_forward'),
@@ -67,6 +70,7 @@ export const goForward: ActionDef = {
67
70
  export const reload: ActionDef = {
68
71
  type: 'reload',
69
72
  kind: 'control',
73
+ activity: 'Reloading',
70
74
  doc: `reload {hard?} — reload the page. hard bypasses the cache.`,
71
75
  schema: z.object({
72
76
  type: z.literal('reload'),
@@ -87,6 +91,7 @@ export const reload: ActionDef = {
87
91
  export const waitFor: ActionDef = {
88
92
  type: 'wait_for',
89
93
  kind: 'control',
94
+ activity: 'Waiting for the page',
90
95
  doc: `wait_for {selector|text|urlContains|state, timeout?} — wait for the page to catch up.
91
96
  Returns the moment the condition holds, so it costs only what it has to.
92
97
  state: visible (default, with selector/text) · hidden · navigation · networkIdle.
@@ -28,6 +28,7 @@ function defaultRotation(deviceSize: string): 'portrait' | 'landscape' {
28
28
  export const listTabs: ActionDef = {
29
29
  type: 'list_tabs',
30
30
  kind: 'control',
31
+ activity: 'Checking tabs',
31
32
  doc: `list_tabs {} — every open tab with its id, URL, viewport and who controls it.
32
33
  Use the id, not the position, with switch_tab/close_tab.`,
33
34
  schema: z.object({ type: z.literal('list_tabs'), ...commonFields }),
@@ -53,6 +54,7 @@ export const listTabs: ActionDef = {
53
54
  export const openTab: ActionDef = {
54
55
  type: 'open_tab',
55
56
  kind: 'control',
57
+ activity: 'Opening a tab',
56
58
  doc: `open_tab {url?, deviceSize?, rotation?} — open a tab and make it the target.
57
59
  deviceSize: desktop 1920×1080 · laptop 1440×900 (default) · tablet 834×1194 · mobile 402×874.
58
60
  rotation defaults to landscape for desktop/laptop, portrait for tablet/mobile.`,
@@ -80,6 +82,7 @@ export const openTab: ActionDef = {
80
82
  export const switchTab: ActionDef = {
81
83
  type: 'switch_tab',
82
84
  kind: 'control',
85
+ activity: 'Switching tab',
83
86
  doc: `switch_tab {tabId} — make another tab the target of following actions.`,
84
87
  schema: z.object({
85
88
  type: z.literal('switch_tab'),
@@ -94,6 +97,9 @@ export const switchTab: ActionDef = {
94
97
  if (tab) {
95
98
  const acquired = browserMcpControl.acquireControl(tab.id, ctx.chatSessionId, ctx.projectId);
96
99
  if (!acquired) {
100
+ if (!browserMcpControl.isSessionLive(ctx.chatSessionId)) {
101
+ throw new Error('This chat session is no longer running — the browser was released when it stopped.');
102
+ }
97
103
  const owner = browserMcpControl.getTabOwner(tab.id);
98
104
  throw new Error(`Tab '${args.tabId}' is controlled by another chat session (${owner?.slice(0, 8)}...)`);
99
105
  }
@@ -109,6 +115,7 @@ export const switchTab: ActionDef = {
109
115
  export const closeTab: ActionDef = {
110
116
  type: 'close_tab',
111
117
  kind: 'control',
118
+ activity: 'Closing a tab',
112
119
  doc: `close_tab {tabId?} — close a tab (default: the current one).`,
113
120
  schema: z.object({
114
121
  type: z.literal('close_tab'),
@@ -135,6 +142,7 @@ export const closeTab: ActionDef = {
135
142
  export const setViewport: ActionDef = {
136
143
  type: 'set_viewport',
137
144
  kind: 'control',
145
+ activity: 'Changing the viewport',
138
146
  doc: `set_viewport {deviceSize?, rotation?} — resize the current tab.
139
147
  Changing this re-runs the page's media queries, so it is how responsive layouts get tested.`,
140
148
  schema: z.object({
@@ -72,6 +72,16 @@ export interface ActionDef {
72
72
  * what stops it from reading a `tab` that may be null.
73
73
  */
74
74
  needsTab?: boolean;
75
+ /**
76
+ * Two or three words for the caption beside the agent's cursor while this
77
+ * runs — "Navigating", "Taking a screenshot".
78
+ *
79
+ * Only `control` actions carry one. An `input` action's caption is written by
80
+ * the interaction handler from the gesture itself, which is the only place
81
+ * that knows whether a `type` is text or a keystroke, or a `click` is a right
82
+ * click — and the runner has already coalesced the group by then anyway.
83
+ */
84
+ activity?: string;
75
85
  /** `input` actions: translate to the native gesture primitive. */
76
86
  toInput?: (args: any, ctx: ActionContext) => BrowserAutonomousAction | Promise<BrowserAutonomousAction>;
77
87
  /** `control` actions: run directly. */
@@ -84,6 +84,12 @@ export async function getActiveTabSession(
84
84
  if (existing) {
85
85
  const acquired = browserMcpControl.acquireControl(existing.id, chatSessionId, resolvedProjectId);
86
86
  if (!acquired) {
87
+ // Two very different refusals. Saying "another session" for both sent
88
+ // an agent looking for a tab conflict that does not exist, when what
89
+ // actually happened is that its own run was interrupted.
90
+ if (!browserMcpControl.isSessionLive(chatSessionId)) {
91
+ throw new Error('This chat session is no longer running — the browser was released when it stopped.');
92
+ }
87
93
  const owner = browserMcpControl.getTabOwner(existing.id);
88
94
  throw new Error(`Tab '${existing.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
89
95
  }