forked from tinyhumansai/openhuman
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChatRuntimeProvider.tsx
More file actions
1568 lines (1490 loc) · 62.3 KB
/
Copy pathChatRuntimeProvider.tsx
File metadata and controls
1568 lines (1490 loc) · 62.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import debug from 'debug';
import { useCallback, useEffect, useRef } from 'react';
import { requestUsageRefresh } from '../hooks/usageRefresh';
import { useRefetchSnapshotOnTurnEnd } from '../hooks/useRefetchSnapshotOnTurnEnd';
import {
createSkillToolChainLatencyTracker,
SKILL_TOOL_CHAIN_TARGET_MS,
} from '../lib/ai/skillToolChainLatency';
import { ingestRuntimeErrorSignal } from '../lib/userErrors/report';
import {
type ChatApprovalRequestEvent,
type ChatDoneEvent,
type ChatInferenceHeartbeatEvent,
type ChatInferenceStartEvent,
type ChatIterationStartEvent,
type ChatPlanReviewRequestEvent,
type ChatSegmentEvent,
type ChatSubagentDoneEvent,
type ChatSubagentTextDeltaEvent,
type ChatSubagentThinkingDeltaEvent,
type ChatTaskBoardUpdatedEvent,
type ChatToolCallEvent,
type ChatToolResultEvent,
type ProactiveMessageEvent,
segmentText,
subscribeChatEvents,
} from '../services/chatService';
import { store } from '../store';
import {
appendProcessingProse,
appendSubagentStreamDelta,
bumpInferenceHeartbeatForThread,
clearInferenceStatusForThread,
clearParallelRequest,
clearPendingApprovalForThread,
clearPendingPlanReviewForThread,
clearProcessingForThread,
clearStreamingAssistantForThread,
endInferenceTurn,
markInferenceTurnStreaming,
parseToolFailure,
recordChatTurnUsage,
recordProcessingTool,
recordSubagentTranscriptTool,
resolveSubagentTranscriptTool,
setInferenceStatusForThread,
setParallelStream,
setPendingApprovalForThread,
setPendingPlanReviewForThread,
setStreamingAssistantForThread,
setTaskBoardForThread,
setToolTimelineForThread,
setWorkflowProposalForThread,
type StreamingAssistantState,
type ToolTimelineEntry,
type ToolTimelineEntryStatus,
upsertArtifactFailedForThread,
upsertArtifactInProgressForThread,
upsertArtifactReadyForThread,
type WorkflowProposal,
} from '../store/chatRuntimeSlice';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { selectSocketStatus } from '../store/socketSelectors';
import {
addInferenceResponse,
addMessageLocal,
clearThreadInferenceActive,
createNewThread,
generateThreadTitleIfNeeded,
setActiveThread,
setSelectedThread,
} from '../store/threadSlice';
import { IS_PROD } from '../utils/config';
import {
formatTimelineEntry,
isKnownClientTool,
promptFromArgsBuffer,
} from '../utils/toolTimelineFormatting';
const logChatRuntime = debug('openhuman:chat-runtime');
const USER_FACING_AGENT_ERROR_MESSAGE =
'Something went wrong. Please try again.\nThis error has been reported. You can also report it on Discord.\n<openhuman-link path="community/discord-report">Report on Discord</openhuman-link>';
const SEGMENT_DELIVERY_TTL_MS = 5 * 60 * 1000;
const MAX_SEGMENT_DELIVERIES = 100;
type SegmentDelivery = { segments: Map<number, string>; createdAt: number; lastSeenAt: number };
type ThreadSliceState = ReturnType<typeof store.getState>['thread'];
/**
* Whether a thread should be treated as occupied for proactive delivery — a
* thread is only a valid target when it is provably "fresh" (holds no
* messages). We check the in-memory message cache and the persisted
* `messageCount` snapshot, so a thread that already has a conversation
* server-side (but whose messages aren't loaded into the cache yet) is still
* treated as occupied and never reused.
*
* Crucially, *unknown* thread metadata counts as occupied: when only a
* rehydrated `selectedThreadId` is present (e.g. before `loadThreads`
* resolves, or after caches were reset while selection was preserved),
* `state.threads.find` returns `undefined`. Treating that as fresh would let
* a proactive event append into a conversation we simply haven't loaded yet.
* We fail closed and open a new thread instead. See #3713.
*/
function threadHasMessages(state: ThreadSliceState, threadId: string): boolean {
const cached = state.messagesByThreadId[threadId];
if (cached && cached.length > 0) return true;
if (threadId === state.selectedThreadId && state.messages.length > 0) return true;
const thread = state.threads.find(t => t.id === threadId);
// Unknown metadata → fail closed (occupied) rather than risk interrupting an
// unloaded conversation.
if (!thread) return true;
return thread.messageCount > 0;
}
function rtLog(message: string, fields?: Record<string, string | number | null | undefined>) {
if (IS_PROD) return;
if (fields && Object.keys(fields).length > 0) {
const parts = Object.entries(fields)
.filter(([, v]) => v !== undefined && v !== '' && v !== null)
.map(([k, v]) => `${k}=${v}`);
logChatRuntime('[chat-runtime] %s %s', message, parts.join(' '));
} else {
logChatRuntime('[chat-runtime] %s', message);
}
}
function segmentDeliveryKey(threadId: string, requestId?: string | null): string {
return `${threadId}:${requestId ?? 'none'}`;
}
function pruneSegmentDeliveries(deliveries: Map<string, SegmentDelivery>, now = Date.now()) {
for (const [key, delivery] of deliveries) {
if (now - delivery.createdAt > SEGMENT_DELIVERY_TTL_MS) {
deliveries.delete(key);
}
}
while (deliveries.size > MAX_SEGMENT_DELIVERIES) {
let oldestKey: string | undefined;
let oldestLastSeenAt = Number.POSITIVE_INFINITY;
for (const [key, delivery] of deliveries) {
if (delivery.lastSeenAt < oldestLastSeenAt) {
oldestKey = key;
oldestLastSeenAt = delivery.lastSeenAt;
}
}
if (!oldestKey) break;
deliveries.delete(oldestKey);
}
}
function getOrCreateSegmentDelivery(
deliveries: Map<string, SegmentDelivery>,
key: string,
now = Date.now()
): SegmentDelivery {
pruneSegmentDeliveries(deliveries, now);
const existing = deliveries.get(key);
if (existing) {
existing.lastSeenAt = now;
return existing;
}
const delivery = { segments: new Map<number, string>(), createdAt: now, lastSeenAt: now };
deliveries.set(key, delivery);
pruneSegmentDeliveries(deliveries, now);
return delivery;
}
function takeSegmentDelivery(
deliveries: Map<string, SegmentDelivery>,
key: string,
now = Date.now()
): SegmentDelivery | undefined {
pruneSegmentDeliveries(deliveries, now);
const delivery = deliveries.get(key);
deliveries.delete(key);
return delivery;
}
function deleteSegmentDelivery(deliveries: Map<string, SegmentDelivery>, key: string) {
pruneSegmentDeliveries(deliveries);
deliveries.delete(key);
}
// Delivery is complete iff every expected segment_index arrived. Do NOT also
// compare reconstructed segments against event.full_response — the server
// trims each segment and normalises joiners during segmentation
// (presentation.rs::segment_for_delivery), while full_response keeps the raw
// LLM text. A byte-equality check therefore fails on virtually every
// multi-segment turn and triggers the reconciliation path, producing a
// duplicate assistant message.
function hasCompleteSegmentDelivery(
event: ChatDoneEvent,
delivery: SegmentDelivery | undefined
): boolean {
const expected = event.segment_total ?? 0;
if (expected <= 0 || !delivery) return false;
if (delivery.segments.size < expected) return false;
for (let i = 0; i < expected; i += 1) {
if (!delivery.segments.has(i)) return false;
}
return true;
}
function chatDoneExtraMetadata(event: ChatDoneEvent): Record<string, unknown> | undefined {
return event.citations?.length ? { citations: event.citations } : undefined;
}
/**
* Map a `chat_done` event's holistic usage onto the `recordChatTurnUsage`
* payload. Prefers the structured `usage` object (tokens + cost + context window
* + per-sub-agent breakdown); falls back to the deprecated flat token fields for
* any older core that still emits them.
*/
function chatTurnUsagePayload(event: ChatDoneEvent): {
inputTokens: number;
outputTokens: number;
cachedTokens?: number;
costUsd?: number;
contextWindow?: number;
threadId?: string;
subAgents?: Array<{
agentId: string;
inputTokens: number;
outputTokens: number;
costUsd: number;
}>;
} {
const u = event.usage;
if (u) {
return {
inputTokens: u.input_tokens,
outputTokens: u.output_tokens,
cachedTokens: u.cached_input_tokens,
costUsd: u.cost_usd,
contextWindow: u.context_window,
threadId: event.thread_id,
subAgents: (u.subagents ?? []).map(s => ({
agentId: s.agent_id,
inputTokens: s.input_tokens,
outputTokens: s.output_tokens,
costUsd: s.cost_usd,
})),
};
}
return {
inputTokens: event.total_input_tokens ?? 0,
outputTokens: event.total_output_tokens ?? 0,
threadId: event.thread_id,
};
}
/**
* Parses a completed `propose_workflow` tool call's JSON `output` into a
* `WorkflowProposal` for `WorkflowProposalCard` (issue B4 — agent-first
* Workflow authoring). The tool's `execute()`
* (`src/openhuman/flows/tools.rs`) returns
* `{ type: "workflow_proposal", name, graph, require_approval, summary }` as
* its `ToolResult` body; this maps that wire shape onto the store's camelCase
* `WorkflowProposal`. Returns `null` for anything that fails to parse or
* doesn't match the expected shape — defensive, since a malformed proposal
* must never crash the chat runtime, it should just silently not render a
* card.
*/
function parseWorkflowProposal(output: string): WorkflowProposal | null {
let parsed: unknown;
try {
parsed = JSON.parse(output);
} catch {
return null;
}
if (!parsed || typeof parsed !== 'object') return null;
const obj = parsed as Record<string, unknown>;
if (obj.type !== 'workflow_proposal') return null;
if (typeof obj.name !== 'string' || obj.graph == null) return null;
const summary = (obj.summary ?? {}) as Record<string, unknown>;
const rawSteps = Array.isArray(summary.steps) ? summary.steps : [];
const steps = rawSteps
.filter((s): s is Record<string, unknown> => !!s && typeof s === 'object')
.map(s => ({
kind: typeof s.kind === 'string' ? s.kind : 'unknown',
name: typeof s.name === 'string' ? s.name : '',
config_hint: typeof s.config_hint === 'string' ? s.config_hint : undefined,
}));
return {
name: obj.name,
graph: obj.graph,
// The Rust tool defaults `require_approval` to `true` when the caller
// omits it, so treat anything other than an explicit `false` as `true`
// here too — keeps the client's fallback in lockstep with the server's.
requireApproval: obj.require_approval !== false,
summary: { trigger: typeof summary.trigger === 'string' ? summary.trigger : '', steps },
};
}
export function findPendingDelegationContext(
entries: ToolTimelineEntry[],
round: number
): { sourceToolName?: string; prompt?: string; spawnEntryId?: string } {
for (let i = entries.length - 1; i >= 0; i -= 1) {
const entry = entries[i];
if (entry.status !== 'running' || entry.round !== round) continue;
if (
['spawn_subagent', 'spawn_async_subagent'].includes(entry.name) ||
entry.name.startsWith('delegate_')
) {
return {
sourceToolName: entry.name,
prompt: entry.detail ?? promptFromArgsBuffer(entry.argsBuffer),
spawnEntryId: entry.id,
};
}
}
return {};
}
const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
const dispatch = useAppDispatch();
const { refetch: refetchSnapshot } = useRefetchSnapshotOnTurnEnd();
const socketStatus = useAppSelector(selectSocketStatus);
const toolTimelineByThread = useAppSelector(state => state.chatRuntime.toolTimelineByThread);
const inferenceStatusByThread = useAppSelector(
state => state.chatRuntime.inferenceStatusByThread
);
const streamingAssistantByThread = useAppSelector(
state => state.chatRuntime.streamingAssistantByThread
);
const seenChatEventsRef = useRef<Map<string, number>>(new Map());
const segmentDeliveriesRef = useRef<Map<string, SegmentDelivery>>(new Map());
const proactiveThreadCreationPromiseRef = useRef<Promise<string | null> | null>(null);
const proactiveDispatchQueueRef = useRef<Promise<void>>(Promise.resolve());
const toolTimelineRef = useRef(toolTimelineByThread);
const inferenceStatusRef = useRef(inferenceStatusByThread);
const streamingAssistantRef = useRef(streamingAssistantByThread);
// Measures wall-clock of each turn's tool chain against the 60s target
// (#4273, AC3). Single instance for the provider's lifetime; observability
// only — it never gates or cancels a turn.
const skillLatencyRef = useRef(createSkillToolChainLatencyTracker());
useEffect(() => {
toolTimelineRef.current = toolTimelineByThread;
}, [toolTimelineByThread]);
useEffect(() => {
inferenceStatusRef.current = inferenceStatusByThread;
}, [inferenceStatusByThread]);
useEffect(() => {
streamingAssistantRef.current = streamingAssistantByThread;
}, [streamingAssistantByThread]);
const markChatEventSeen = (
key: string,
meta?: { threadId?: string; requestId?: string }
): boolean => {
const now = Date.now();
const cache = seenChatEventsRef.current;
const ttlMs = 10 * 60_000;
const maxEntries = 500;
if (cache.has(key)) {
rtLog('dedupe_drop', {
key: key.length > 160 ? `${key.slice(0, 160)}…` : key,
thread: meta?.threadId,
request: meta?.requestId,
});
return false;
}
cache.set(key, now);
for (const [existingKey, timestamp] of cache) {
if (now - timestamp > ttlMs) {
cache.delete(existingKey);
}
}
while (cache.size > maxEntries) {
const oldest = cache.keys().next().value;
if (!oldest) break;
cache.delete(oldest);
}
return true;
};
const proactiveMessageDigest = (input: string): string => {
// Small non-cryptographic digest to keep dedupe keys bounded.
let hash = 2166136261;
for (let i = 0; i < input.length; i += 1) {
hash ^= input.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(36);
};
const resolveVisibleThreadForProactive = useCallback(
async (incomingThreadId: string): Promise<string | null> => {
if (!incomingThreadId.startsWith('proactive:')) {
return incomingThreadId;
}
const state = store.getState().thread;
// Reuse an existing thread for proactive delivery ONLY when it is
// fresh (no messages). Injecting a morning brief / subconscious
// update into a thread that already holds a conversation interrupts
// the active chat flow (#3713). Candidate priority is selected >
// first thread; if the candidate already has messages we fall
// through and open a dedicated new thread instead. An in-flight
// inference thread always has at least the user's message, so it is
// never considered fresh — that is why `activeThreadIds` is no
// longer used as a target here.
const candidateThreadId = state.selectedThreadId ?? state.threads[0]?.id ?? null;
if (candidateThreadId && !threadHasMessages(state, candidateThreadId)) {
return candidateThreadId;
}
if (proactiveThreadCreationPromiseRef.current) {
return proactiveThreadCreationPromiseRef.current;
}
const createPromise: Promise<string | null> = (async () => {
try {
const newThread = await dispatch(createNewThread()).unwrap();
dispatch(setSelectedThread(newThread.id));
return newThread.id;
} catch (error) {
rtLog('proactive_thread_create_failed', {
err: error instanceof Error ? error.message : String(error),
});
return null;
} finally {
proactiveThreadCreationPromiseRef.current = null;
}
})();
proactiveThreadCreationPromiseRef.current = createPromise;
try {
return await createPromise;
} finally {
// no-op: cleared in createPromise.finally
}
},
[dispatch]
);
useEffect(() => {
if (socketStatus !== 'connected') return;
const decorateEntry = (entry: ToolTimelineEntry): ToolTimelineEntry => {
const formatted = formatTimelineEntry(entry);
// The server now attaches a human label/detail for dynamic
// Composio/MCP/integration tools the client can't know. Trust it for
// those; for the fixed set of built-ins the client formatter labels
// well (with args-aware detail), the client label stays authoritative.
if (entry.displayName && !isKnownClientTool(entry.name)) {
return {
...entry,
displayName: entry.displayName,
detail: entry.detail ?? formatted.detail,
};
}
return { ...entry, displayName: formatted.title, detail: formatted.detail ?? entry.detail };
};
// When a turn ends, any follow-ups the user queued behind it are about to be
// dispatched by the backend as fresh turns. Nothing else persists their
// prompt — the web channel never writes user messages; the composer does
// (`addMessageLocal` → `appendMessage`) — so append them to the transcript
// now. Doing it here (after this turn's assistant reply was appended, before
// `endInferenceTurn` clears the pills) keeps the append-log order correct:
// user → assistant → queued follow-up. Without this the queued prompts are
// lost on reload and the dispatched answer has no visible user message.
const flushQueuedFollowups = async (threadId: string) => {
const queued = store.getState().chatRuntime.queuedFollowupsByThread[threadId] ?? [];
// Persist sequentially so the queued prompts land in the append-log in the
// order the user queued them (concurrent dispatches would race), and
// surface failures instead of dropping them silently. The stored message
// carries the original content + attachment metadata, so the follow-up
// persists identically to an interactive send.
for (const item of queued) {
try {
await dispatch(addMessageLocal({ threadId, message: item.message })).unwrap();
} catch (error) {
rtLog('flush_followup_append_failed', {
thread: threadId,
message: item.message.id,
error: error instanceof Error ? error.message : String(error),
});
}
}
};
const finishChatDoneTurn = async (event: ChatDoneEvent, path: string) => {
rtLog('refresh_usage_counter', {
thread: event.thread_id,
request: event.request_id,
reason: 'chat_done',
});
requestUsageRefresh();
rtLog('snapshot_refetch_queued', {
thread: event.thread_id,
request: event.request_id,
reason: 'chat_done',
path,
});
refetchSnapshot();
// Persist queued follow-ups (in order, after this turn's assistant reply)
// and only then clear the queue + lifecycle.
await flushQueuedFollowups(event.thread_id);
dispatch(endInferenceTurn({ threadId: event.thread_id }));
dispatch(clearThreadInferenceActive(event.thread_id));
};
rtLog('subscribe_chat_events', { socket: socketStatus });
const cleanup = subscribeChatEvents({
onInferenceStart: (event: ChatInferenceStartEvent) => {
rtLog('inference_start', { thread: event.thread_id, request: event.request_id });
// Fresh turn: drop the previous turn's live processing transcript so a
// new turn's narration/steps don't append onto the old one.
dispatch(clearProcessingForThread({ threadId: event.thread_id }));
dispatch(markInferenceTurnStreaming({ threadId: event.thread_id }));
dispatch(
setInferenceStatusForThread({
threadId: event.thread_id,
status: { phase: 'thinking', iteration: 0, maxIterations: 0 },
})
);
},
onInferenceHeartbeat: (event: ChatInferenceHeartbeatEvent) => {
// #4270: liveness beat — bump the per-thread counter so the
// Conversations silence timer rearms even when the turn is in a long
// prefill / buffered-reasoning phase that emits no other progress.
rtLog('inference_heartbeat', { thread: event.thread_id, request: event.request_id });
// A parallel (forked) turn streams into its own lane and must NOT keep
// the thread's primary silence timer alive — otherwise a sibling branch
// would mask a stalled primary turn. Mirror the text/thinking-delta
// routing: ignore heartbeats owned by a parallel request.
if (store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined) {
return;
}
dispatch(bumpInferenceHeartbeatForThread({ threadId: event.thread_id }));
},
onIterationStart: (event: ChatIterationStartEvent) => {
const prev = inferenceStatusRef.current[event.thread_id];
rtLog('iteration_start', {
thread: event.thread_id,
request: event.request_id,
iteration: event.round,
});
dispatch(
setInferenceStatusForThread({
threadId: event.thread_id,
status: {
phase: 'thinking',
iteration: event.round,
maxIterations: prev?.maxIterations ?? 0,
},
})
);
},
onToolCall: (event: ChatToolCallEvent) => {
const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
dispatch(
setInferenceStatusForThread({
threadId: event.thread_id,
status: {
...(prev ?? { iteration: event.round, maxIterations: 0 }),
phase: 'tool_use',
activeTool: event.tool_name,
},
})
);
const eventKey = `tool_call:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.tool_call_id ?? ''}`;
if (
!markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
)
return;
// Start (or extend) the tool-chain latency window for this turn (#4273).
// Key by thread+request (same scheme as segment delivery) so parallel /
// forked turns that share a thread_id keep independent chains (#4288).
skillLatencyRef.current.noteToolCall(segmentDeliveryKey(event.thread_id, event.request_id));
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
const existingIdx = event.tool_call_id
? existing.findIndex(entry => entry.id === event.tool_call_id)
: -1;
// Stable row id, shared with the processing-transcript tool pointer so
// the panel can resolve the row by `callId`.
const rowId =
event.tool_call_id ??
`${event.thread_id}:${event.round}:${existing.length}:${event.tool_name}`;
let entries: ToolTimelineEntry[];
if (existingIdx >= 0) {
entries = [...existing];
entries[existingIdx] = decorateEntry({
...entries[existingIdx],
name: event.tool_name,
round: event.round,
status: 'running',
displayName: event.tool_display_label ?? entries[existingIdx].displayName,
detail: event.tool_display_detail ?? entries[existingIdx].detail,
});
} else {
entries = [
...existing,
decorateEntry({
id: rowId,
name: event.tool_name,
round: event.round,
status: 'running',
displayName: event.tool_display_label,
detail: event.tool_display_detail,
}),
];
}
dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));
dispatch(
recordProcessingTool({ threadId: event.thread_id, round: event.round, callId: rowId })
);
},
onToolResult: (event: ChatToolResultEvent) => {
const eventKey = `tool_result:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.success}:${event.tool_call_id ?? ''}`;
if (
!markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
)
return;
// On failure, parse the optional structured explanation (#4254) once so
// both the id-match and name/round-fallback paths can attach it. A
// successful result clears any stale failure carried on the row.
const failure = event.success ? undefined : parseToolFailure(event.failure);
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
if (existing.length > 0) {
const nextEntries = [...existing];
let changed = false;
// The core forwards the (size-capped) tool result text on `output`;
// keep it on the row so the timeline can show what the tool
// returned. Older cores sent a metadata stub here — accept only
// non-empty payloads so a stub-less row stays `undefined`.
const result = event.output && event.output.length > 0 ? event.output : undefined;
if (event.tool_call_id) {
const idx = nextEntries.findIndex(entry => entry.id === event.tool_call_id);
if (idx >= 0) {
nextEntries[idx] = {
...nextEntries[idx],
status: event.success ? 'success' : 'error',
failure,
result,
};
changed = true;
}
}
if (!changed) {
for (let i = nextEntries.length - 1; i >= 0; i -= 1) {
const entry = nextEntries[i];
if (
entry.status === 'running' &&
entry.name === event.tool_name &&
entry.round === event.round
) {
nextEntries[i] = {
...entry,
status: event.success ? 'success' : 'error',
failure,
result,
};
changed = true;
break;
}
}
}
if (changed) {
dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries: nextEntries }));
}
}
// Agent-first Workflow authoring (issue B4): a completed
// `propose_workflow` call carries a `workflow_proposal` JSON payload
// in `output` — surface it as a `WorkflowProposalCard` above the
// composer. The tool only validates; only the card's "Save & enable"
// action ever calls `flows_create`, so this dispatch alone can never
// create a flow.
if (event.tool_name === 'propose_workflow' && event.success) {
const proposal = parseWorkflowProposal(event.output);
if (proposal) {
rtLog('propose_workflow proposal parsed', {
thread: event.thread_id,
name: proposal.name,
});
dispatch(setWorkflowProposalForThread({ threadId: event.thread_id, proposal }));
} else {
rtLog('propose_workflow result did not parse as a workflow_proposal', {
thread: event.thread_id,
});
}
}
const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
if (!current) return;
dispatch(
setInferenceStatusForThread({
threadId: event.thread_id,
status: { ...current, phase: 'thinking', activeTool: undefined },
})
);
},
onSubagentSpawned: event => {
const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
dispatch(
setInferenceStatusForThread({
threadId: event.thread_id,
status: {
...(prev ?? { iteration: event.round, maxIterations: 0 }),
phase: 'subagent',
activeSubagent: event.tool_name,
},
})
);
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
const pendingContext = findPendingDelegationContext(existing, event.round);
// Collapse the parent's `spawn_subagent`/`spawn_async_subagent`/`delegate_*` tool-call row into
// the subagent row so the timeline shows ONE entry per delegation
// instead of "Research" (the tool call) + "Researching" (the child).
// The tool call's prompt is carried onto the subagent as the parent's
// delegation message, which the drawer renders as the opening turn.
const base = pendingContext.spawnEntryId
? existing.filter(e => e.id !== pendingContext.spawnEntryId)
: existing;
dispatch(
setToolTimelineForThread({
threadId: event.thread_id,
entries: [
...base,
decorateEntry({
id: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
name: `subagent:${event.tool_name}`,
round: event.round,
status: 'running',
detail: pendingContext.prompt,
sourceToolName: pendingContext.sourceToolName,
subagent: {
taskId: event.skill_id,
agentId: event.tool_name,
displayName: event.subagent?.display_name,
workerThreadId: event.subagent?.worker_thread_id,
mode: event.subagent?.mode,
dedicatedThread: event.subagent?.dedicated_thread,
prompt: pendingContext.prompt,
toolCalls: [],
transcript: [],
},
}),
],
})
);
},
onSubagentAwaitingUser: (event: ChatSubagentDoneEvent) => {
const subagentRowId = `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`;
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
if (existing.length > 0) {
const entries = existing.map(entry => {
if (entry.id !== subagentRowId || entry.status !== 'running') return entry;
return decorateEntry({
...entry,
status: 'awaiting_user' as ToolTimelineEntryStatus,
subagent: entry.subagent
? { ...entry.subagent, status: 'awaiting_user' }
: entry.subagent,
});
});
dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));
}
},
onSubagentDone: (event: ChatSubagentDoneEvent) => {
const subagentRowId = `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`;
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
if (existing.length > 0) {
const entries = existing.map(entry => {
if (entry.id !== subagentRowId || entry.status !== 'running') return entry;
return decorateEntry({
...entry,
status: (event.success ? 'success' : 'error') as ToolTimelineEntryStatus,
subagent: entry.subagent
? {
...entry.subagent,
iterations: event.subagent?.iterations ?? entry.subagent.iterations,
elapsedMs: event.subagent?.elapsed_ms ?? entry.subagent.elapsedMs,
outputChars: event.subagent?.output_chars ?? entry.subagent.outputChars,
// Worktree isolation metadata (#3376) — present only for
// workers that ran with `isolation = "worktree"`. Drives the
// inline worktree row's open/diff/remove affordances.
worktreePath: event.subagent?.worktree_path ?? entry.subagent.worktreePath,
changedFiles: event.subagent?.changed_files ?? entry.subagent.changedFiles,
isDirty: event.subagent?.dirty_status ?? entry.subagent.isDirty,
}
: entry.subagent,
});
});
dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));
}
const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
if (!current) return;
dispatch(
setInferenceStatusForThread({
threadId: event.thread_id,
status: { ...current, phase: 'thinking', activeSubagent: undefined },
})
);
},
onSubagentIterationStart: event => {
const taskId = event.subagent?.task_id ?? event.skill_id;
const agentId = event.subagent?.agent_id ?? event.tool_name;
const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
const idx = existing.findIndex(entry => entry.id === rowId);
if (idx < 0) return;
const entry = existing[idx];
if (!entry.subagent) return;
const next = [...existing];
next[idx] = {
...entry,
subagent: {
...entry.subagent,
childIteration: event.subagent?.child_iteration ?? entry.subagent.childIteration,
childMaxIterations:
event.subagent?.child_max_iterations ?? entry.subagent.childMaxIterations,
},
};
dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries: next }));
},
onSubagentToolCall: event => {
const taskId = event.subagent?.task_id ?? event.skill_id;
const agentId = event.subagent?.agent_id;
if (!agentId) return;
const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
const idx = existing.findIndex(entry => entry.id === rowId);
if (idx < 0) return;
const entry = existing[idx];
if (!entry.subagent) return;
// De-dupe on call_id — the same call should not append twice if
// the socket layer redelivers (e.g. on reconnect during a run).
if (entry.subagent.toolCalls.some(c => c.callId === event.tool_call_id)) return;
const next = [...existing];
next[idx] = {
...entry,
subagent: {
...entry.subagent,
toolCalls: [
...entry.subagent.toolCalls,
{
callId: event.tool_call_id,
toolName: event.tool_name,
status: 'running',
iteration: event.subagent?.child_iteration,
args: event.args,
displayName: event.tool_display_label,
detail: event.tool_display_detail,
},
],
},
};
dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries: next }));
// Mirror the call into the ordered transcript so the drawer renders
// it right after the text that triggered it (chronological view).
dispatch(
recordSubagentTranscriptTool({
threadId: event.thread_id,
rowId,
callId: event.tool_call_id,
toolName: event.tool_name,
iteration: event.subagent?.child_iteration,
args: event.args,
displayName: event.tool_display_label,
detail: event.tool_display_detail,
})
);
},
onSubagentToolResult: event => {
const taskId = event.subagent?.task_id ?? event.skill_id;
const agentId = event.subagent?.agent_id;
if (!agentId) return;
const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
const idx = existing.findIndex(entry => entry.id === rowId);
if (idx < 0) return;
const entry = existing[idx];
if (!entry.subagent) return;
const callIdx = entry.subagent.toolCalls.findIndex(c => c.callId === event.tool_call_id);
if (callIdx < 0) return;
const updatedCalls = [...entry.subagent.toolCalls];
updatedCalls[callIdx] = {
...updatedCalls[callIdx],
status: event.success ? 'success' : 'error',
elapsedMs: event.subagent?.elapsed_ms ?? updatedCalls[callIdx].elapsedMs,
outputChars: event.subagent?.output_chars ?? updatedCalls[callIdx].outputChars,
result: event.output ?? updatedCalls[callIdx].result,
// Carry the structured failure so the child row keeps its "why / next"
// copy live instead of losing it until a snapshot reload (#4459). A
// successful result clears any stale failure on the row.
failure: event.success ? undefined : parseToolFailure(event.failure),
};
const next = [...existing];
next[idx] = { ...entry, subagent: { ...entry.subagent, toolCalls: updatedCalls } };
dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries: next }));
dispatch(
resolveSubagentTranscriptTool({
threadId: event.thread_id,
rowId,
callId: event.tool_call_id,
success: event.success,
elapsedMs: event.subagent?.elapsed_ms,
outputChars: event.subagent?.output_chars,
result: event.output,
failure: event.success ? undefined : parseToolFailure(event.failure),
})
);
},
onSubagentTextDelta: (event: ChatSubagentTextDeltaEvent) => {
const taskId = event.subagent?.task_id;
const agentId = event.subagent?.agent_id;
if (!taskId || !agentId || !event.delta) return;
dispatch(
appendSubagentStreamDelta({
threadId: event.thread_id,
rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
kind: 'text',
delta: event.delta,
iteration: event.subagent?.child_iteration,
})
);
},
onSubagentThinkingDelta: (event: ChatSubagentThinkingDeltaEvent) => {
const taskId = event.subagent?.task_id;
const agentId = event.subagent?.agent_id;
if (!taskId || !agentId || !event.delta) return;
dispatch(
appendSubagentStreamDelta({
threadId: event.thread_id,
rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
kind: 'thinking',
delta: event.delta,
iteration: event.subagent?.child_iteration,
})
);
},
onSegment: (event: ChatSegmentEvent) => {
const eventKey = `segment:${event.thread_id}:${event.request_id}:${event.segment_index}`;
if (
!markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
)
return;
const content = segmentText(event);
const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
const delivery = getOrCreateSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
delivery.segments.set(event.segment_index, content);
void dispatch(
addInferenceResponse({
content,
threadId: event.thread_id,
extraMetadata: event.citations?.length ? { citations: event.citations } : undefined,
})
);
},
onTextDelta: event => {
const cr = store.getState().chatRuntime;
// A parallel (forked) turn streams into its own lane so it doesn't
// clobber the primary turn's stream on the same thread.
if (cr.parallelRequestThreads[event.request_id] !== undefined) {
const prev = cr.parallelStreamsByThread[event.thread_id]?.[event.request_id];
dispatch(
setParallelStream({
threadId: event.thread_id,
streaming: {
requestId: event.request_id,
content: `${prev?.content ?? ''}${event.delta}`,
thinking: prev?.thinking ?? '',
},
})
);
return;
}
const existing = cr.streamingAssistantByThread[event.thread_id];
let streaming: StreamingAssistantState;