Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Show Assistant tool starts while streaming

rcourtmanab99112ad272
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 2b2d32cb53..3d9eec12cd 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -2996,6 +2996,17 @@
"src/api/__tests__/aiChatEvents.test.ts"
]
},
+ {
+ "id": "assistant-chat-stream-json-contract-tests",
+ "run": [
+ "go",
+ "test",
+ "./internal/api",
+ "-run",
+ "TestContract_ChatStreamEventJSONSnapshots",
+ "-count=1"
+ ]
+ },
{
"id": "assistant-context-prefetch-structured-mentions-tests",
"run": [
@@ -6811,11 +6822,11 @@
{
"id": "codex-lane-followup-architecture-post-rc-canonicalization",
"agent_id": "codex",
- "summary": "Align Assistant model selection with OpenCode source workflow",
+ "summary": "Align Assistant live tool progress with OpenCode source workflow",
"target_id": "v6-product-lane-expansion",
"claimed_at": "2026-06-05T21:57:48Z",
- "heartbeat_at": "2026-06-06T01:33:49Z",
- "expires_at": "2026-06-06T03:33:49Z",
+ "heartbeat_at": "2026-06-06T01:58:08Z",
+ "expires_at": "2026-06-06T03:58:08Z",
"work_item": {
"kind": "lane-followup",
"id": "architecture-post-rc-canonicalization"
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index c959282bbd..d317104f80 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -245,6 +245,18 @@ runtime cost control, and shared AI transport surfaces.
stream contract adapts that model with `tool_start`, `tool_progress`, and
`tool_end` events that update the same visible pending tool row in place.
The referenced OpenCode source at fetched `origin/dev` commit
+ `9ed17da55ab1f7360cc0e01075f763e27fa899e9` creates a tool message part as
+ soon as tool input starts in `packages/opencode/src/session/processor.ts`,
+ mutates that part through running/completed/error states via
+ `packages/opencode/src/session/tools.ts`, and renders the same live part in
+ `packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` through
+ pending/running/completed rows. Pulse's Assistant stream must mirror that
+ timing: model-selected tools become visible when the tool name is known,
+ later argument/progress updates mutate the row, and completion replaces that
+ row rather than appending a delayed batch of steps. Policy-hidden placeholder
+ attempts remain governed by the runtime and may cancel a pending row instead
+ of persisting a failed tool card.
+ The referenced OpenCode source at fetched `origin/dev` commit
`fa2b63f850fc0a23bec2bdff9e660450d3fe7913` also keeps assistant text,
reasoning, and tool invocation as typed message parts in
`packages/opencode/src/session/message.ts`, while
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index cbe84990e3..8e4e27faad 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -443,9 +443,10 @@ payload shape change when the portal presents compact client rows.
boundary. Browser Assistant output is owned by the AI runtime presentation
contract rather than by API-client event typing.
Tool execution progress is part of this SSE contract: `tool_start`,
- `tool_progress`, and `tool_end` must carry typed payloads generated from
- `internal/ai/chat` structs so the frontend can mutate one visible tool row
- from pending to running/waiting to completed/error without inventing a
+ `tool_progress`, `tool_cancel`, and `tool_end` must carry typed payloads
+ generated from `internal/ai/chat` structs so the frontend can mutate one
+ visible tool row from pending to running/waiting to completed/error, or
+ cancel a runtime-policy-hidden pending row, without inventing a
browser-only event shape.
Cold Assistant streams must include a typed `session` event backed by
`internal/ai/chat.SessionData` as soon as the HTTP SSE writer is ready and
@@ -909,7 +910,8 @@ the canonical monitored-system blocked payload.
`frontend-modern/src/api/generated/aiChatEvents.ts` type must stay derived
from `internal/ai/chat/types.go` through `scripts/generate-types.go`, and
frontend API tests must pin any new generated SSE fields, including live
- tool-progress payload fields such as `phase` and `message`.
+ tool-progress payload fields such as `phase` and `message` and pending tool
+ cancellation payloads such as `reason`.
That same shared org-management client boundary now owns target-consent
sharing semantics across `frontend-modern/src/api/orgs.ts`,
`internal/api/org_handlers.go`, and the shared org route wiring. Cross-org
diff --git a/frontend-modern/src/api/__tests__/aiChatEvents.test.ts b/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
index 00ca197cdc..f35f2dca91 100644
--- a/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
@@ -4,6 +4,7 @@ import type {
AIChatStreamEvent,
DoneData,
SessionData,
+ ToolCancelData,
ToolProgressData,
WorkflowStateData,
} from '@/api/generated/aiChatEvents';
@@ -58,6 +59,19 @@ describe('AI chat stream event contract', () => {
expect(aiChatEventsSource).toContain("type: 'tool_progress'");
});
+ it('exposes pending tool cancellation as a typed stream contract', () => {
+ const cancel: ToolCancelData = {
+ id: 'tool-1',
+ name: 'pulse_read',
+ reason: 'current_resource unavailable',
+ };
+ const event: AIChatStreamEvent = { type: 'tool_cancel', data: cancel };
+
+ expect(event.data.reason).toBe('current_resource unavailable');
+ expect(aiChatEventsSource).toContain('export interface ToolCancelData');
+ expect(aiChatEventsSource).toContain("type: 'tool_cancel'");
+ });
+
it('exposes the effective completion model on done events', () => {
const done: DoneData = {
session_id: 'sess-stream',
diff --git a/frontend-modern/src/api/generated/aiChatEvents.ts b/frontend-modern/src/api/generated/aiChatEvents.ts
index 6056fd03cf..bd0ecee7c8 100644
--- a/frontend-modern/src/api/generated/aiChatEvents.ts
+++ b/frontend-modern/src/api/generated/aiChatEvents.ts
@@ -92,6 +92,12 @@ export interface ThinkingData {
text: string;
}
+export interface ToolCancelData {
+ id: string;
+ name: string;
+ reason?: string;
+}
+
export interface ToolEndData {
id: string;
name: string;
@@ -135,6 +141,7 @@ export type AIChatStreamEvent =
| { type: 'workflow_state'; data: WorkflowStateData }
| { type: 'tool_start'; data: ToolStartData }
| { type: 'tool_progress'; data: ToolProgressData }
+ | { type: 'tool_cancel'; data: ToolCancelData }
| { type: 'tool_end'; data: ToolEndData }
| { type: 'approval_needed'; data: ApprovalNeededData }
| { type: 'question'; data: QuestionData & { session_id?: string } }
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
index 8d018aa7bb..fdbd157b46 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/useChat.test.ts
@@ -858,7 +858,8 @@ describe('useChat', () => {
fire({ type: 'content', data: compacted });
expect(chat.messages().find((m) => m.role === 'assistant')?.content).toBe('');
expect(
- chat.messages()
+ chat
+ .messages()
.find((m) => m.role === 'assistant')
?.streamEvents?.filter((e) => e.type === 'content'),
).toEqual([]);
@@ -2403,5 +2404,34 @@ describe('useChat', () => {
);
dispose();
});
+
+ it('removes a canceled pending tool without adding a completed tool call', async () => {
+ const { getFireEvent } = setupWithEventCapture();
+ const { value: chat, dispose } = withRoot(() => useChat({ sessionId: 's' }));
+
+ await chat.sendMessage('hi');
+ const fire = getFireEvent();
+
+ fire({ type: 'tool_start', data: { id: 'a', name: 'pulse_read', input: '{}' } });
+
+ let assistant = chat.messages().find((m) => m.role === 'assistant')!;
+ expect(assistant.pendingTools).toHaveLength(1);
+ expect(assistant.streamEvents?.filter((event) => event.type === 'pending_tool')).toHaveLength(
+ 1,
+ );
+
+ fire({
+ type: 'tool_cancel',
+ data: { id: 'a', name: 'pulse_read', reason: 'current_resource unavailable' },
+ });
+
+ assistant = chat.messages().find((m) => m.role === 'assistant')!;
+ expect(assistant.pendingTools).toEqual([]);
+ expect(assistant.toolCalls).toEqual([]);
+ expect(assistant.streamEvents?.filter((event) => event.type === 'pending_tool')).toHaveLength(
+ 0,
+ );
+ dispose();
+ });
});
});
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index ef1eee76c0..18ffd7ae2d 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -723,6 +723,34 @@ export function useChat(options: UseChatOptions = {}) {
return updatePendingToolProgress(msg, data);
}
+ case 'tool_cancel': {
+ clearSuppressedOutputBoundary(assistantId);
+ const data = event.data as {
+ id?: string;
+ name?: string;
+ };
+ const normalizedName = normalizeChatToolName(data.name || '');
+ const matchesTool = (tool?: PendingTool, toolId?: string) => {
+ if (!tool) return false;
+ if (data.id && toolId === data.id) return true;
+ if (data.id && tool.id === data.id) return true;
+ return normalizedName !== '' && normalizeChatToolName(tool.name) === normalizedName;
+ };
+
+ return {
+ ...msg,
+ workflowStatus: undefined,
+ pendingTools: (msg.pendingTools || []).filter(
+ (tool) => !matchesTool(tool, tool.id),
+ ),
+ streamEvents: (msg.streamEvents || []).filter(
+ (streamEvent) =>
+ streamEvent.type !== 'pending_tool' ||
+ !matchesTool(streamEvent.pendingTool, streamEvent.toolId),
+ ),
+ };
+ }
+
case 'tool_end': {
clearSuppressedOutputBoundary(assistantId);
const data = event.data as {
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
index 27aacd3708..79ea0e8510 100644
--- a/internal/ai/chat/agentic.go
+++ b/internal/ai/chat/agentic.go
@@ -180,6 +180,37 @@ func toolStartKey(id, name string) string {
return strings.TrimSpace(name)
}
+func toolStartKeys(id, name string) []string {
+ keys := make([]string, 0, 2)
+ if key := strings.TrimSpace(id); key != "" {
+ keys = append(keys, key)
+ }
+ if key := strings.TrimSpace(name); key != "" {
+ for _, existing := range keys {
+ if existing == key {
+ return keys
+ }
+ }
+ keys = append(keys, key)
+ }
+ return keys
+}
+
+func toolStartMapHas(values map[string]bool, id, name string) bool {
+ for _, key := range toolStartKeys(id, name) {
+ if values[key] {
+ return true
+ }
+ }
+ return false
+}
+
+func markToolStartMap(values map[string]bool, id, name string) {
+ for _, key := range toolStartKeys(id, name) {
+ values[key] = true
+ }
+}
+
func normalizeSummaryOnlyPulseQueryInput(prefer bool, name string, input map[string]interface{}) map[string]interface{} {
if !prefer || name != "pulse_query" || len(input) == 0 {
return input
@@ -229,6 +260,18 @@ func emitToolProgressEvent(callback StreamCallback, id, name string, input map[s
callback(StreamEvent{Type: "tool_progress", Data: jsonData})
}
+func emitToolCancelEvent(callback StreamCallback, id, name, reason string) {
+ if callback == nil {
+ return
+ }
+ jsonData, _ := json.Marshal(ToolCancelData{
+ ID: id,
+ Name: name,
+ Reason: strings.TrimSpace(reason),
+ })
+ callback(StreamEvent{Type: "tool_cancel", Data: jsonData})
+}
+
func emitToolEndEvent(callback StreamCallback, id, name string, input map[string]interface{}, output string, success bool) {
if callback == nil {
return
@@ -758,38 +801,20 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
var suppressLeakedToolContent bool
var pendingVisibleContent string
visibleToolStarts := make(map[string]bool)
- deferredToolStarts := make(map[string]providers.ToolStartEvent)
suppressedToolStarts := make(map[string]bool)
- emitDeferredToolStart := func(tc providers.ToolCall) {
- key := toolStartKey(tc.ID, tc.Name)
- if key == "" || visibleToolStarts[key] || suppressedToolStarts[key] {
- return
- }
- if _, ok := deferredToolStarts[key]; !ok {
+ emitToolStartIfNeeded := func(tc providers.ToolCall) {
+ keys := toolStartKeys(tc.ID, tc.Name)
+ if len(keys) == 0 || toolStartMapHas(visibleToolStarts, tc.ID, tc.Name) || toolStartMapHas(suppressedToolStarts, tc.ID, tc.Name) {
return
}
emitToolStartEvent(callback, tc.ID, tc.Name, tc.Input)
- visibleToolStarts[key] = true
+ markToolStartMap(visibleToolStarts, tc.ID, tc.Name)
}
emitCurrentResourceBlock := func(tc providers.ToolCall, blockMsg string) {
- key := toolStartKey(tc.ID, tc.Name)
- if key != "" && visibleToolStarts[key] {
- emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, blockMsg, false)
- resultMessages = append(resultMessages, Message{
- ID: uuid.New().String(),
- Role: "user",
- Timestamp: time.Now(),
- ToolResult: &ToolResult{
- ToolUseID: tc.ID,
- Content: blockMsg,
- IsError: true,
- },
- })
- return
- }
- if key != "" {
- suppressedToolStarts[key] = true
+ if toolStartMapHas(visibleToolStarts, tc.ID, tc.Name) {
+ emitToolCancelEvent(callback, tc.ID, tc.Name, "current_resource unavailable")
}
+ markToolStartMap(suppressedToolStarts, tc.ID, tc.Name)
resultMessages = removeToolCallFromResultMessages(resultMessages, tc.ID)
}
@@ -844,8 +869,10 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
data.Input = normalizeSummaryOnlyPulseQueryInput(preferSummaryOnlyQueries, data.Name, data.Input)
key := toolStartKey(data.ID, data.Name)
if len(data.Input) == 0 {
- if key != "" {
- deferredToolStarts[key] = data
+ if key != "" && !toolStartMapHas(visibleToolStarts, data.ID, data.Name) && !toolStartMapHas(suppressedToolStarts, data.ID, data.Name) {
+ attemptEmittedVisibleEvents = true
+ emitToolStartEvent(callback, data.ID, data.Name, data.Input)
+ markToolStartMap(visibleToolStarts, data.ID, data.Name)
}
return
}
@@ -855,15 +882,11 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
Str("id", data.ID).
Str("reason", blockMsg).
Msg("[AgenticLoop] Suppressed invalid current_resource tool_start before user-visible execution")
- if key != "" {
- suppressedToolStarts[key] = true
- }
+ markToolStartMap(suppressedToolStarts, data.ID, data.Name)
return
}
attemptEmittedVisibleEvents = true
- if key != "" {
- visibleToolStarts[key] = true
- }
+ markToolStartMap(visibleToolStarts, data.ID, data.Name)
emitToolStartEvent(callback, data.ID, data.Name, data.Input)
}
@@ -1189,7 +1212,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
}
- emitDeferredToolStart(tc)
+ emitToolStartIfNeeded(tc)
emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, fsmErr.Error(), false)
toolResultMsg := Message{
@@ -1221,7 +1244,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
if recentCallCounts[callKey] > maxIdenticalCalls {
loopMsg := fmt.Sprintf("LOOP_DETECTED: You have called %s with the same arguments %d times. This call is blocked. Try a different tool or approach.", tc.Name, recentCallCounts[callKey])
- emitDeferredToolStart(tc)
+ emitToolStartIfNeeded(tc)
emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, loopMsg, false)
toolResultMsg := Message{
@@ -1250,7 +1273,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
if tc.Name != pulseQuestionToolName {
skipMsg := fmt.Sprintf("SKIPPED: %s was requested this turn. Wait for the user's answer, then re-issue this tool call with the clarified inputs.", pulseQuestionToolName)
- emitDeferredToolStart(tc)
+ emitToolStartIfNeeded(tc)
emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, skipMsg, false)
toolResultMsg := Message{
@@ -1378,7 +1401,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
}
// Send tool_end event with error
- emitDeferredToolStart(tc)
+ emitToolStartIfNeeded(tc)
emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, fsmErr.Error(), false)
// Create tool result message with the error
@@ -1421,7 +1444,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
loopMsg := fmt.Sprintf("LOOP_DETECTED: You have called %s with the same arguments %d times. This call is blocked. Try a different tool or approach.", tc.Name, recentCallCounts[callKey])
- emitDeferredToolStart(tc)
+ emitToolStartIfNeeded(tc)
emitToolEndEvent(callback, tc.ID, tc.Name, tc.Input, loopMsg, false)
toolResultMsg := Message{
@@ -1457,7 +1480,7 @@ func (a *AgenticLoop) executeWithTools(ctx context.Context, sessionID string, me
execResults := make([]parallelToolResult, len(pendingExec))
if len(pendingExec) > 0 {
for _, pe := range pendingExec {
- emitDeferredToolStart(pe.tc)
+ emitToolStartIfNeeded(pe.tc)
emitToolProgressEvent(
callback,
pe.tc.ID,
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
index 102339548e..0e95c85c3d 100644
--- a/internal/ai/chat/agentic_additional_test.go
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -555,7 +555,7 @@ func TestAgenticLoop_DoesNotAutoRecoverStructuredToolCall(t *testing.T) {
}
}
-func TestAgenticLoop_HidesUnavailableCurrentResourceToolCall(t *testing.T) {
+func TestAgenticLoop_CancelsUnavailableCurrentResourcePendingToolCall(t *testing.T) {
executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
provider := &stubStreamingProvider{}
loop := NewAgenticLoop(provider, executor, "prompt")
@@ -624,12 +624,28 @@ func TestAgenticLoop_HidesUnavailableCurrentResourceToolCall(t *testing.T) {
if callCount != 2 {
t.Fatalf("expected recovery turn after hidden current_resource block, got %d provider calls", callCount)
}
+ toolStarts := 0
+ toolCancels := 0
for _, event := range events {
switch event.Type {
- case "tool_start", "tool_end":
- t.Fatalf("current_resource placeholder block should not emit visible tool event: %+v", event)
+ case "tool_start":
+ toolStarts++
+ case "tool_cancel":
+ toolCancels++
+ var data ToolCancelData
+ if err := json.Unmarshal(event.Data, &data); err != nil {
+ t.Fatalf("unmarshal tool_cancel event: %v", err)
+ }
+ if data.ID != "call-read-dev" || data.Name != "pulse_read" {
+ t.Fatalf("unexpected tool_cancel payload: %+v", data)
+ }
+ case "tool_end":
+ t.Fatalf("current_resource placeholder block should cancel the pending tool, not complete it: %+v", event)
}
}
+ if toolStarts != 1 || toolCancels != 1 {
+ t.Fatalf("expected one early tool_start and one tool_cancel, got starts=%d cancels=%d events=%+v", toolStarts, toolCancels, events)
+ }
if len(results) != 1 {
t.Fatalf("expected only final assistant message to be session-visible, got %d: %+v", len(results), results)
}
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
index 9a9d0aea26..68422daadd 100644
--- a/internal/ai/chat/types.go
+++ b/internal/ai/chat/types.go
@@ -283,6 +283,15 @@ type ToolProgressData struct {
Message string `json:"message,omitempty"` // Compact user-facing status text
}
+// ToolCancelData is the data for "tool_cancel" events.
+// It removes a pending tool row when a model-selected call is consumed by an
+// internal policy boundary instead of becoming user-visible tool execution.
+type ToolCancelData struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Reason string `json:"reason,omitempty"`
+}
+
// ToolEndData is the data for "tool_end" events
type ToolEndData struct {
ID string `json:"id"`
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index b40c51a9f2..99c6c7a156 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -10637,6 +10637,15 @@ func TestContract_ChatStreamEventJSONSnapshots(t *testing.T) {
}),
want: `{"type":"tool_progress","data":{"id":"tool-1","name":"pulse_read","input":"{\"path\":\"/tmp/x.log\"}","raw_input":"{\"path\":\"/tmp/x.log\"}","phase":"running","message":"Reading target."}}`,
},
+ {
+ name: "tool_cancel",
+ event: mustStreamEvent(t, "tool_cancel", chat.ToolCancelData{
+ ID: "tool-1",
+ Name: "pulse_read",
+ Reason: "current_resource unavailable",
+ }),
+ want: `{"type":"tool_cancel","data":{"id":"tool-1","name":"pulse_read","reason":"current_resource unavailable"}}`,
+ },
{
name: "tool_end",
event: mustStreamEvent(t, "tool_end", chat.ToolEndData{
diff --git a/scripts/generate-types.go b/scripts/generate-types.go
index c0dce4d723..1c8c7b6166 100644
--- a/scripts/generate-types.go
+++ b/scripts/generate-types.go
@@ -41,6 +41,7 @@ func main() {
reflect.TypeOf(chat.SessionData{}),
reflect.TypeOf(chat.ToolStartData{}),
reflect.TypeOf(chat.ToolProgressData{}),
+ reflect.TypeOf(chat.ToolCancelData{}),
reflect.TypeOf(chat.ToolEndData{}),
reflect.TypeOf(chat.ApprovalPlanData{}),
reflect.TypeOf(chat.ApprovalContextConfidenceData{}),
@@ -79,6 +80,7 @@ func main() {
buf.WriteString(" | { type: 'workflow_state'; data: WorkflowStateData }\n")
buf.WriteString(" | { type: 'tool_start'; data: ToolStartData }\n")
buf.WriteString(" | { type: 'tool_progress'; data: ToolProgressData }\n")
+ buf.WriteString(" | { type: 'tool_cancel'; data: ToolCancelData }\n")
buf.WriteString(" | { type: 'tool_end'; data: ToolEndData }\n")
buf.WriteString(" | { type: 'approval_needed'; data: ApprovalNeededData }\n")
// QuestionData is wrapped by the backend as {question_id, questions} plus session_id in some callers.