-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathbuildConversationItems.ts
More file actions
942 lines (861 loc) · 26.3 KB
/
Copy pathbuildConversationItems.ts
File metadata and controls
942 lines (861 loc) · 26.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
import type {
ContentBlock,
SessionNotification,
} from "@agentclientprotocol/sdk";
import {
isNotification,
POSTHOG_NOTIFICATIONS,
} from "@posthog/agent/acp-extensions";
import { extractPromptDisplayContent } from "@posthog/core/sessions/promptContent";
import {
type AcpMessage,
isJsonRpcNotification,
isJsonRpcRequest,
isJsonRpcResponse,
type UserShellExecuteParams,
} from "@posthog/shared";
import {
type GitActionType,
parseGitActionMessage,
} from "@posthog/ui/features/sessions/components/GitActionMessage";
import type { UserShellExecute } from "@posthog/ui/features/sessions/components/session-update/UserShellExecuteView";
import type {
SessionUpdate,
ToolCall,
} from "@posthog/ui/features/sessions/types";
import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";
import {
extractSkillButtonId,
type SkillButtonId,
} from "@posthog/ui/features/skill-buttons/prompts";
import type { Step, StepStatus } from "@posthog/ui/primitives/StepList";
import type { RenderItem } from "./session-update/SessionUpdateView";
export interface TurnContext {
toolCalls: Map<string, ToolCall>;
childItems: Map<string, ConversationItem[]>;
turnCancelled: boolean;
turnComplete: boolean;
}
export type ConversationItem =
| {
type: "user_message";
id: string;
content: string;
timestamp: number;
attachments?: UserMessageAttachment[];
pinToTop?: boolean;
}
| { type: "git_action"; id: string; actionType: GitActionType }
| { type: "skill_button_action"; id: string; buttonId: SkillButtonId }
| {
type: "session_update";
id: string;
update: RenderItem;
turnContext: TurnContext;
thoughtComplete?: boolean;
timestamp?: number;
}
| {
type: "git_action_result";
id: string;
actionType: GitActionType;
turnId: string;
}
| { type: "turn_cancelled"; id: string; interruptReason?: string }
| UserShellExecute;
export interface LastTurnInfo {
isComplete: boolean;
durationMs: number;
stopReason?: string;
}
export interface BuildResult {
items: ConversationItem[];
lastTurnInfo: LastTurnInfo | null;
isCompacting: boolean;
/** Number of tool calls settled into a terminal status so far. Monotonic
* within a thread; consumers treat a change as "a tool/MCP call finished". */
completedToolCallCount: number;
}
interface ProgressCardState {
/** Step key → full step entry. Key order reflects arrival order. */
steps: Map<string, Step>;
/** Reference to the pushed render item; mutated in place as events arrive. */
renderItem: {
sessionUpdate: "progress_group";
steps: Step[];
isActive: boolean;
};
/** Index in `items` where this card sits. */
itemIndex: number;
/** Run id parsed from the `group` (`setup:<runId>`); empty if absent. */
runId: string;
}
interface TurnState {
id: string;
promptId: number;
isComplete: boolean;
stopReason?: string;
interruptReason?: string;
durationMs: number;
toolCalls: Map<string, ToolCall>;
context: TurnContext;
gitAction: ReturnType<typeof parseGitActionMessage>;
itemCount: number;
}
export interface ItemBuilder {
items: ConversationItem[];
currentTurn: TurnState | null;
/** Index in `items` where the current turn's first item sits. Lets an
* incremental consumer treat everything before it (completed turns) as
* frozen and only re-derive the active turn. */
currentTurnStartIndex: number;
pendingPrompts: Map<number, TurnState>;
shellExecutes: Map<string, { item: UserShellExecute; index: number }>;
isCompacting: boolean;
nextId: () => number;
/** Progress cards keyed by the backend-supplied `group` id. The first event
* for a group opens the card inline where it arrived; every subsequent
* event for the same id mutates the same card, regardless of which turn is
* currently active. */
progressCards: Map<string, ProgressCardState>;
/** Lowest item index touched by a progress event since it was last reset.
* An incremental consumer resets this before feeding a batch of events and
* reads it after to detect a card being mutated inside an already frozen
* (completed) turn, which would otherwise go unseen. */
lowestTouchedProgressIndex: number;
/** Count of tool calls that have reached a terminal status (completed /
* failed / cancelled). Increments once per tool call when it first settles.
* Drives the generating indicator's status word so it advances on real work
* finishing rather than on a timer. */
completedToolCallCount: number;
/** Runs that emitted `_posthog/run_started`; until then the setup card's
* "agent" step stays in_progress rather than completing at HTTP-boot time. */
runStartedRunIds: Set<string>;
}
export function createItemBuilder(): ItemBuilder {
let idCounter = 0;
return {
items: [],
currentTurn: null,
currentTurnStartIndex: 0,
pendingPrompts: new Map(),
shellExecutes: new Map(),
isCompacting: false,
nextId: () => idCounter++,
progressCards: new Map(),
lowestTouchedProgressIndex: Number.POSITIVE_INFINITY,
completedToolCallCount: 0,
runStartedRunIds: new Set(),
};
}
const TERMINAL_TOOL_STATUSES = new Set(["completed", "failed", "cancelled"]);
function isTerminalToolStatus(status: string | null | undefined): boolean {
return status != null && TERMINAL_TOOL_STATUSES.has(status);
}
function isThoughtItem(
item: ConversationItem,
): item is ConversationItem & { type: "session_update" } {
return (
item.type === "session_update" &&
item.update.sessionUpdate === "agent_thought_chunk"
);
}
export function markThoughtCompletion(items: ConversationItem[]) {
const seenContexts = new Set<TurnContext>();
for (let i = items.length - 1; i >= 0; i--) {
const item = items[i];
if (isThoughtItem(item)) {
item.thoughtComplete =
seenContexts.has(item.turnContext) || item.turnContext.turnComplete;
}
if (item.type === "session_update") {
seenContexts.add(item.turnContext);
}
}
}
function pushItem(b: ItemBuilder, update: RenderItem, ts?: number) {
const turn = b.currentTurn;
if (!turn) return;
turn.itemCount++;
b.items.push({
type: "session_update",
id: `${turn.id}-item-${b.nextId()}`,
update,
turnContext: turn.context,
timestamp: ts,
});
}
export interface BuildConversationOptions {
/** Render `debug`-level console logs inline; without this only info/warn/error show up. */
showDebugLogs?: boolean;
}
export function buildConversationItems(
events: AcpMessage[],
isPromptPending: boolean | null,
options?: BuildConversationOptions,
): BuildResult {
const b = createItemBuilder();
let ordered = events;
for (let i = 1; i < events.length; i++) {
if (events[i].ts < events[i - 1].ts) {
ordered = [...events].sort((a, b) => a.ts - b.ts);
break;
}
}
for (const event of ordered) {
processEvent(b, event, options);
}
finalizeBuilder(b, isPromptPending);
const lastTurnInfo = readLastTurnInfo(b);
return {
items: b.items,
lastTurnInfo,
isCompacting: b.isCompacting,
completedToolCallCount: b.completedToolCallCount,
};
}
/**
* Apply one raw event to the builder. This is the append-only core: it never
* runs end-of-stream finalization, so it is safe to call incrementally as new
* events arrive without corrupting prior state.
*/
export function processEvent(
b: ItemBuilder,
event: AcpMessage,
options?: BuildConversationOptions,
) {
const msg = event.message;
if (isJsonRpcNotification(msg)) {
handleNotification(b, msg, event.ts, options);
return;
}
if (isJsonRpcRequest(msg) && msg.method === "session/prompt") {
handlePromptRequest(b, msg, event.ts);
return;
}
if (isJsonRpcResponse(msg) && b.pendingPrompts.has(msg.id)) {
handlePromptResponse(b, msg, event.ts);
}
}
/**
* End-of-stream finalization: speculative completions that assume no further
* events arrive. Mutates the builder in place, so an incremental consumer must
* only apply it to a snapshot it is about to read, never to state it will keep
* feeding events into.
*/
export function finalizeBuilder(
b: ItemBuilder,
isPromptPending: boolean | null,
) {
// Only mark unresolved prompts as cancelled when we actively track prompt
// state (local sessions). For cloud sessions isPromptPending is
// null, meaning that the response hasn't streamed "in" yet
if (isPromptPending === false) {
for (const turn of b.pendingPrompts.values()) {
turn.isComplete = true;
turn.durationMs = 0;
turn.context.turnComplete = true;
}
}
// Mark implicit turn complete if it's still the current turn after all events
if (b.currentTurn?.promptId === -1) {
b.currentTurn.isComplete = true;
b.currentTurn.context.turnComplete = true;
}
markThoughtCompletion(b.items);
}
export function readLastTurnInfo(b: ItemBuilder): LastTurnInfo | null {
return b.currentTurn
? {
isComplete: b.currentTurn.isComplete,
durationMs: b.currentTurn.durationMs,
stopReason: b.currentTurn.stopReason,
}
: null;
}
function handlePromptRequest(
b: ItemBuilder,
msg: { id: number; params?: unknown },
ts: number,
) {
// If the current turn is the implicit one, mark it complete before starting a real turn
if (b.currentTurn && b.currentTurn.promptId === -1) {
b.currentTurn.isComplete = true;
b.currentTurn.context.turnComplete = true;
}
const userPrompt = extractUserPrompt(msg.params);
const userContent = userPrompt.content;
if (userContent.trim().length === 0 && userPrompt.attachments.length === 0) {
return;
}
const turnId = `turn-${ts}-${msg.id}`;
const toolCalls = new Map<string, ToolCall>();
const gitAction = parseGitActionMessage(userContent);
const skillButtonId = extractSkillButtonId(userPrompt.blocks);
const childItems = new Map<string, ConversationItem[]>();
const context: TurnContext = {
toolCalls,
childItems,
turnCancelled: false,
turnComplete: false,
};
// The orchestrator emits its setup progress ("Started agent") before the
// prompt it responds to is replayed onto the stream, so the card would sit
// above the user's message. Open the turn before any trailing progress cards
// so the transcript reads user message → setup → work.
let insertIndex = b.items.length;
while (insertIndex > 0) {
const prev = b.items[insertIndex - 1];
if (
prev.type === "session_update" &&
prev.update.sessionUpdate === "progress_group"
) {
insertIndex--;
} else {
break;
}
}
if (insertIndex < b.items.length) {
for (const card of b.progressCards.values()) {
if (card.itemIndex >= insertIndex) card.itemIndex++;
}
// The shifted cards may live inside a turn the incremental builder already
// froze; flag the mutation so it falls back to a full rebuild.
if (insertIndex < b.lowestTouchedProgressIndex) {
b.lowestTouchedProgressIndex = insertIndex;
}
}
b.currentTurnStartIndex = insertIndex;
b.currentTurn = {
id: turnId,
promptId: msg.id,
isComplete: false,
durationMs: -ts,
toolCalls,
context,
gitAction,
itemCount: 0,
};
b.pendingPrompts.set(msg.id, b.currentTurn);
if (gitAction.isGitAction && gitAction.actionType) {
b.items.splice(insertIndex, 0, {
type: "git_action",
id: `${turnId}-git-action`,
actionType: gitAction.actionType,
});
} else if (skillButtonId) {
b.items.splice(insertIndex, 0, {
type: "skill_button_action",
id: `${turnId}-skill-action`,
buttonId: skillButtonId,
});
} else {
b.items.splice(insertIndex, 0, {
type: "user_message",
id: `${turnId}-user`,
content: userContent,
timestamp: ts,
attachments: userPrompt.attachments,
});
}
}
function handlePromptResponse(
b: ItemBuilder,
msg: { id: number; result?: unknown },
ts: number,
) {
const turn = b.pendingPrompts.get(msg.id);
if (!turn) return;
const result = msg.result as {
stopReason?: string;
_meta?: { interruptReason?: string };
};
completePromptTurn(b, turn, ts, {
stopReason: result?.stopReason,
interruptReason: result?._meta?.interruptReason,
});
}
function completePromptTurn(
b: ItemBuilder,
turn: TurnState,
ts: number,
result: { stopReason?: string; interruptReason?: string } = {},
) {
if (turn.isComplete) return;
turn.isComplete = true;
if (turn.promptId !== -1) {
turn.durationMs += ts;
}
turn.stopReason = result?.stopReason;
turn.interruptReason = result?.interruptReason;
turn.context.turnComplete = true;
const wasCancelled = turn.stopReason === "cancelled";
turn.context.turnCancelled = wasCancelled;
if (turn.gitAction.isGitAction && turn.gitAction.actionType) {
b.items.push({
type: "git_action_result",
id: `${turn.id}-git-result`,
actionType: turn.gitAction.actionType,
turnId: turn.id,
});
}
if (wasCancelled) {
b.items.push({
type: "turn_cancelled",
id: `${turn.id}-cancelled`,
interruptReason: turn.interruptReason,
});
}
if (turn.promptId !== -1) {
b.pendingPrompts.delete(turn.promptId);
}
}
function handleNotification(
b: ItemBuilder,
msg: { method: string; params?: unknown },
ts: number,
options?: BuildConversationOptions,
) {
if (msg.method === "_array/user_shell_execute") {
const params = msg.params as UserShellExecuteParams;
const existing = b.shellExecutes.get(params.id);
if (existing) {
existing.item.result = params.result;
} else {
const item: UserShellExecute = {
type: "user_shell_execute",
id: params.id,
command: params.command,
cwd: params.cwd,
result: params.result,
};
b.shellExecutes.set(params.id, { item, index: b.items.length });
b.items.push(item);
}
return;
}
if (msg.method === "session/update") {
const update = (msg.params as SessionNotification)?.update;
if (!update) return;
if (!b.currentTurn) {
ensureImplicitTurn(b, ts);
}
processSessionUpdate(b, update, ts);
return;
}
// `_posthog/resources_used` is intentionally NOT rendered inline here — the
// products are surfaced as a persistent, de-duplicated bar above the composer
// (see accumulateSessionResources / SessionResourcesBar).
if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.TURN_COMPLETE)) {
const params = msg.params as { stopReason?: string } | undefined;
if (!b.currentTurn) return;
completePromptTurn(b, b.currentTurn, ts, {
stopReason: params?.stopReason,
});
return;
}
if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.CONSOLE)) {
const params = msg.params as { level?: string; message?: string };
if (!params?.message) return;
const level = params.level ?? "info";
if (level === "debug" && !options?.showDebugLogs) return;
if (!b.currentTurn) ensureImplicitTurn(b, ts);
pushItem(b, {
sessionUpdate: "console",
level,
message: params.message,
timestamp: new Date(ts).toISOString(),
});
return;
}
if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.PROGRESS)) {
handleProgress(b, msg.params, ts);
return;
}
if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.RUN_STARTED)) {
const runId = (msg.params as { runId?: string } | undefined)?.runId;
if (runId) {
b.runStartedRunIds.add(runId);
const card = b.progressCards.get(`setup:${runId}`);
if (card) {
if (card.itemIndex < b.lowestTouchedProgressIndex) {
b.lowestTouchedProgressIndex = card.itemIndex;
}
syncProgressCard(card, b);
}
}
return;
}
if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.COMPACT_BOUNDARY)) {
if (!b.currentTurn) ensureImplicitTurn(b, ts);
const params = msg.params as {
trigger: "manual" | "auto";
preTokens: number;
contextSize?: number;
};
markCompactingStatusComplete(b);
pushItem(b, {
sessionUpdate: "compact_boundary",
trigger: params.trigger,
preTokens: params.preTokens,
contextSize: params.contextSize,
});
return;
}
if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.STATUS)) {
if (!b.currentTurn) ensureImplicitTurn(b, ts);
const params = msg.params as {
status: string;
isComplete?: boolean;
error?: string;
explanation?: string;
fromModel?: string;
toModel?: string;
};
if (params.status === "refusal" || params.status === "refusal_fallback") {
pushItem(b, {
sessionUpdate: "status",
status: params.status,
explanation: params.explanation,
fromModel: params.fromModel,
toModel: params.toModel,
});
return;
}
if (params.status === "compacting") {
if (params.isComplete) {
// Successful compaction — flip the existing "Compacting…" status to
// complete instead of pushing a second item, so the spinner stops.
markCompactingStatusComplete(b);
return;
}
b.isCompacting = true;
} else if (params.status === "compacting_failed") {
// A failed compaction emits no `compact_boundary`, so clear the spinner
// and render the outcome as its own status row.
markCompactingStatusComplete(b);
pushItem(b, {
sessionUpdate: "status",
status: "compacting_failed",
error: params.error,
});
return;
}
pushItem(b, {
sessionUpdate: "status",
status: params.status,
isComplete: params.isComplete,
});
return;
}
}
function ensureProgressCardForGroup(
b: ItemBuilder,
group: string,
ts: number,
): ProgressCardState | null {
const existing = b.progressCards.get(group);
if (existing) return existing;
if (!b.currentTurn) ensureImplicitTurn(b, ts);
if (!b.currentTurn) return null;
const renderItem = {
sessionUpdate: "progress_group" as const,
steps: [] as Step[],
isActive: true,
};
const colon = group.indexOf(":");
const card: ProgressCardState = {
steps: new Map(),
renderItem,
itemIndex: b.items.length,
runId: colon >= 0 ? group.slice(colon + 1) : "",
};
b.progressCards.set(group, card);
pushItem(b, renderItem);
return card;
}
function syncProgressCard(card: ProgressCardState, b: ItemBuilder) {
const gateAgentStep =
card.runId !== "" && !b.runStartedRunIds.has(card.runId);
const ordered: Step[] = Array.from(card.steps.values()).map((step) =>
step.key === "agent" && step.status === "completed" && gateAgentStep
? { ...step, status: "in_progress" as StepStatus }
: step,
);
card.renderItem.steps = ordered;
card.renderItem.isActive = ordered.some((s) => s.status === "in_progress");
}
function handleProgress(b: ItemBuilder, rawParams: unknown, ts: number) {
const params = rawParams as
| {
step?: string;
status?: string;
label?: string;
detail?: string;
group?: string;
}
| undefined;
if (!params?.step || !params.label || !params.group) return;
const status = normalizeStepStatus(params.status);
const card = ensureProgressCardForGroup(b, params.group, ts);
if (!card) return;
if (card.itemIndex < b.lowestTouchedProgressIndex) {
b.lowestTouchedProgressIndex = card.itemIndex;
}
card.steps.set(params.step, {
key: params.step,
status,
label: params.label,
detail: params.detail,
});
syncProgressCard(card, b);
}
function normalizeStepStatus(raw: string | undefined): StepStatus {
switch (raw) {
case "in_progress":
case "completed":
case "failed":
return raw;
default:
return "in_progress";
}
}
function markCompactingStatusComplete(b: ItemBuilder) {
b.isCompacting = false;
for (let i = b.items.length - 1; i >= 0; i--) {
const item = b.items[i];
if (
item.type === "session_update" &&
item.update.sessionUpdate === "status" &&
item.update.status === "compacting"
) {
item.update.isComplete = true;
return;
}
}
}
function ensureImplicitTurn(b: ItemBuilder, ts: number) {
if (b.currentTurn) return;
b.currentTurnStartIndex = b.items.length;
const turnId = `turn-${ts}-implicit`;
const toolCalls = new Map<string, ToolCall>();
const childItems = new Map<string, ConversationItem[]>();
const context: TurnContext = {
toolCalls,
childItems,
turnCancelled: false,
turnComplete: false,
};
b.currentTurn = {
id: turnId,
promptId: -1,
isComplete: false,
durationMs: 0,
toolCalls,
context,
gitAction: { isGitAction: false, actionType: null, prompt: "" },
itemCount: 0,
};
}
function extractUserPrompt(params: unknown): {
content: string;
attachments: UserMessageAttachment[];
blocks: ContentBlock[];
} {
const p = params as { prompt?: ContentBlock[] };
if (!p?.prompt?.length) {
return { content: "", attachments: [], blocks: [] };
}
const { text, attachments } = extractPromptDisplayContent(p.prompt, {
filterHidden: true,
});
return { content: text, attachments, blocks: p.prompt };
}
function getParentToolCallId(update: SessionUpdate): string | undefined {
const meta = (update as Record<string, unknown>)?._meta as
| { claudeCode?: { parentToolCallId?: string } }
| undefined;
return meta?.claudeCode?.parentToolCallId;
}
function pushChildItem(b: ItemBuilder, parentId: string, update: RenderItem) {
const turn = b.currentTurn;
if (!turn) return;
let children = turn.context.childItems.get(parentId);
if (!children) {
children = [];
turn.context.childItems.set(parentId, children);
}
turn.itemCount++;
children.push({
type: "session_update",
id: `${turn.id}-child-${b.nextId()}`,
update,
turnContext: turn.context,
});
}
function appendTextChunkToChildren(
b: ItemBuilder,
parentId: string,
update: SessionUpdate & {
sessionUpdate: "agent_message_chunk" | "agent_thought_chunk";
},
) {
if (update.content.type !== "text") return;
const turn = b.currentTurn;
if (!turn) return;
let children = turn.context.childItems.get(parentId);
if (!children) {
children = [];
turn.context.childItems.set(parentId, children);
}
const lastChild = children[children.length - 1];
if (
lastChild?.type === "session_update" &&
lastChild.update.sessionUpdate === update.sessionUpdate &&
"content" in lastChild.update &&
lastChild.update.content.type === "text"
) {
const prevText = (
lastChild.update.content as { type: "text"; text: string }
).text;
children[children.length - 1] = {
...lastChild,
update: {
...lastChild.update,
content: {
type: "text",
text: prevText + update.content.text,
},
},
};
} else {
turn.itemCount++;
children.push({
type: "session_update",
id: `${turn.id}-child-${b.nextId()}`,
update: { ...update, content: { ...update.content } },
turnContext: turn.context,
});
}
}
function processSessionUpdate(
b: ItemBuilder,
update: SessionUpdate,
ts: number,
) {
switch (update.sessionUpdate) {
case "user_message_chunk":
break;
case "agent_message_chunk":
case "agent_thought_chunk": {
if (update.content.type !== "text") break;
const parentId = getParentToolCallId(update);
if (parentId) {
appendTextChunkToChildren(b, parentId, update);
} else {
appendTextChunk(b, update, ts);
}
break;
}
case "tool_call": {
const turn = b.currentTurn;
if (!turn) break;
const existing = turn.toolCalls.get(update.toolCallId);
if (existing) {
const wasTerminal = isTerminalToolStatus(existing.status);
Object.assign(existing, update);
if (!wasTerminal && isTerminalToolStatus(existing.status)) {
b.completedToolCallCount++;
}
} else {
const toolCall = { ...update };
turn.toolCalls.set(update.toolCallId, toolCall);
if (isTerminalToolStatus(toolCall.status)) {
b.completedToolCallCount++;
}
const parentId = getParentToolCallId(update);
if (parentId) {
pushChildItem(b, parentId, toolCall);
} else {
pushItem(b, toolCall, ts);
}
}
break;
}
case "tool_call_update": {
const turn = b.currentTurn;
if (!turn) break;
const existing = turn.toolCalls.get(update.toolCallId);
if (existing) {
const wasTerminal = isTerminalToolStatus(existing.status);
const { sessionUpdate: _, ...rest } = update;
Object.assign(existing, rest);
if (!wasTerminal && isTerminalToolStatus(existing.status)) {
b.completedToolCallCount++;
}
}
break;
}
case "plan":
case "available_commands_update":
case "config_option_update":
case "usage_update":
break;
default: {
const customUpdate = update as unknown as {
sessionUpdate: string;
content?: { type: string; text?: string };
status?: string;
errorType?: string;
message?: string;
};
if (customUpdate.sessionUpdate === "agent_message") {
if (customUpdate.content?.type === "text") {
appendTextChunk(
b,
{
sessionUpdate: "agent_message_chunk" as const,
content: customUpdate.content as { type: "text"; text: string },
},
ts,
);
}
} else if (
customUpdate.sessionUpdate === "status" ||
customUpdate.sessionUpdate === "error"
) {
pushItem(b, customUpdate as unknown as SessionUpdate, ts);
}
break;
}
}
}
function appendTextChunk(
b: ItemBuilder,
update: SessionUpdate & {
sessionUpdate: "agent_message_chunk" | "agent_thought_chunk";
},
ts: number,
) {
if (update.content.type !== "text") return;
const lastItem = b.items[b.items.length - 1];
if (
lastItem?.type === "session_update" &&
lastItem.update.sessionUpdate === update.sessionUpdate &&
"content" in lastItem.update &&
lastItem.update.content.type === "text"
) {
b.items[b.items.length - 1] = {
...lastItem,
update: {
...lastItem.update,
content: {
type: "text",
text: lastItem.update.content.text + update.content.text,
},
},
};
} else {
pushItem(b, { ...update, content: { ...update.content } }, ts);
}
}