Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

session-logic.ts

920 lines27.3 KB

1import {
2 ApprovalRequestId,
3 isToolLifecycleItemType,
4 type OrchestrationLatestTurn,
5 type OrchestrationThreadActivity,
6 type OrchestrationProposedPlanId,
7 type ProviderKind,
8 type ToolLifecycleItemType,
9 type UserInputQuestion,
10 type ThreadId,
11 type TurnId,
12} from "@t3tools/contracts";
13​
14import type {
15 ChatMessage,
16 ProposedPlan,
17 SessionPhase,
18 Thread,
19 ThreadSession,
20 TurnDiffSummary,
21} from "./types";
22​
23export type ProviderPickerKind = ProviderKind | "cursor";
24​
25export const PROVIDER_OPTIONS: Array<{
26 value: ProviderPickerKind;
27 label: string;
28 available: boolean;
29}> = [
30 { value: "codex", label: "Codex", available: true },
31 { value: "claudeAgent", label: "Claude", available: true },
32 { value: "cursor", label: "Cursor", available: false },
33];
34​
35export interface WorkLogEntry {
36 id: string;
37 createdAt: string;
38 label: string;
39 detail?: string;
40 command?: string;
41 changedFiles?: ReadonlyArray<string>;
42 tone: "thinking" | "tool" | "info" | "error";
43 toolTitle?: string;
44 itemType?: ToolLifecycleItemType;
45 requestKind?: PendingApproval["requestKind"];
47​
48interface DerivedWorkLogEntry extends WorkLogEntry {
49 activityKind: OrchestrationThreadActivity["kind"];
50 collapseKey?: string;
52​
53export interface PendingApproval {
54 requestId: ApprovalRequestId;
55 requestKind: "command" | "file-read" | "file-change";
56 createdAt: string;
57 detail?: string;
59​
60export interface PendingUserInput {
61 requestId: ApprovalRequestId;
62 createdAt: string;
63 questions: ReadonlyArray<UserInputQuestion>;
65​
66export interface ActivePlanState {
67 createdAt: string;
68 turnId: TurnId | null;
69 explanation?: string | null;
70 steps: Array<{
71 step: string;
72 status: "pending" | "inProgress" | "completed";
73 }>;
75​
76export interface LatestProposedPlanState {
77 id: OrchestrationProposedPlanId;
78 createdAt: string;
79 updatedAt: string;
80 turnId: TurnId | null;
81 planMarkdown: string;
82 implementedAt: string | null;
83 implementationThreadId: ThreadId | null;
85​
86export type TimelineEntry =
87 | {
88 id: string;
89 kind: "message";
90 createdAt: string;
91 message: ChatMessage;
92 }
93 | {
94 id: string;
95 kind: "proposed-plan";
96 createdAt: string;
97 proposedPlan: ProposedPlan;
98 }
99 | {
100 id: string;
101 kind: "work";
102 createdAt: string;
103 entry: WorkLogEntry;
104 };
105​
106export function formatDuration(durationMs: number): string {
107 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
108 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
109 if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
110 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
111 const minutes = Math.floor(durationMs / 60_000);
112 const seconds = Math.round((durationMs % 60_000) / 1_000);
113 if (seconds === 0) return `${minutes}m`;
114 if (seconds === 60) return `${minutes + 1}m`;
115 return `${minutes}m ${seconds}s`;
117​
118export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
119 if (!endIso) return null;
120 const startedAt = Date.parse(startIso);
121 const endedAt = Date.parse(endIso);
122 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
123 return null;
124 }
125 return formatDuration(endedAt - startedAt);
127​
128type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
129type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
130​
131export function isLatestTurnSettled(
132 latestTurn: LatestTurnTiming | null,
133 session: SessionActivityState | null,
134): boolean {
135 if (!latestTurn?.startedAt) return false;
136 if (!latestTurn.completedAt) return false;
137 if (!session) return true;
138 if (session.orchestrationStatus === "running") return false;
139 return true;
141​
142export function deriveActiveWorkStartedAt(
143 latestTurn: LatestTurnTiming | null,
144 session: SessionActivityState | null,
145 sendStartedAt: string | null,
146): string | null {
147 if (!isLatestTurnSettled(latestTurn, session)) {
148 return latestTurn?.startedAt ?? sendStartedAt;
149 }
150 return sendStartedAt;
152​
153function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
154 switch (requestType) {
155 case "command_execution_approval":
156 case "exec_command_approval":
157 return "command";
158 case "file_read_approval":
159 return "file-read";
160 case "file_change_approval":
161 case "apply_patch_approval":
162 return "file-change";
163 default:
164 return null;
165 }
167​
168function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
169 const normalized = detail?.toLowerCase();
170 if (!normalized) {
171 return false;
172 }
173 return (
174 normalized.includes("stale pending approval request") ||
175 normalized.includes("stale pending user-input request") ||
176 normalized.includes("unknown pending approval request") ||
177 normalized.includes("unknown pending permission request") ||
178 normalized.includes("unknown pending user-input request")
179 );
181​
182export function derivePendingApprovals(
183 activities: ReadonlyArray<OrchestrationThreadActivity>,
184): PendingApproval[] {
185 const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
186 const ordered = [...activities].toSorted(compareActivitiesByOrder);
187​
188 for (const activity of ordered) {
189 const payload =
190 activity.payload && typeof activity.payload === "object"
191 ? (activity.payload as Record<string, unknown>)
192 : null;
193 const requestId =
194 payload && typeof payload.requestId === "string"
195 ? ApprovalRequestId.makeUnsafe(payload.requestId)
196 : null;
197 const requestKind =
198 payload &&
199 (payload.requestKind === "command" ||
200 payload.requestKind === "file-read" ||
201 payload.requestKind === "file-change")
202 ? payload.requestKind
203 : payload
204 ? requestKindFromRequestType(payload.requestType)
205 : null;
206 const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
207​
208 if (activity.kind === "approval.requested" && requestId && requestKind) {
209 openByRequestId.set(requestId, {
210 requestId,
211 requestKind,
212 createdAt: activity.createdAt,
213 ...(detail ? { detail } : {}),
214 });
215 continue;
216 }
217​
218 if (activity.kind === "approval.resolved" && requestId) {
219 openByRequestId.delete(requestId);
220 continue;
221 }
222​
223 if (
224 activity.kind === "provider.approval.respond.failed" &&
225 requestId &&
226 isStalePendingRequestFailureDetail(detail)
227 ) {
228 openByRequestId.delete(requestId);
229 continue;
230 }
231 }
232​
233 return [...openByRequestId.values()].toSorted((left, right) =>
234 left.createdAt.localeCompare(right.createdAt),
235 );
237​
238function parseUserInputQuestions(
239 payload: Record<string, unknown> | null,
240): ReadonlyArray<UserInputQuestion> | null {
241 const questions = payload?.questions;
242 if (!Array.isArray(questions)) {
243 return null;
244 }
245 const parsed = questions
246 .map<UserInputQuestion | null>((entry) => {
247 if (!entry || typeof entry !== "object") return null;
248 const question = entry as Record<string, unknown>;
249 if (
250 typeof question.id !== "string" ||
251 typeof question.header !== "string" ||
252 typeof question.question !== "string" ||
253 !Array.isArray(question.options)
254 ) {
255 return null;
256 }
257 const options = question.options
258 .map<UserInputQuestion["options"][number] | null>((option) => {
259 if (!option || typeof option !== "object") return null;
260 const optionRecord = option as Record<string, unknown>;
261 if (
262 typeof optionRecord.label !== "string" ||
263 typeof optionRecord.description !== "string"
264 ) {
265 return null;
266 }
267 return {
268 label: optionRecord.label,
269 description: optionRecord.description,
270 };
271 })
272 .filter((option): option is UserInputQuestion["options"][number] => option !== null);
273 if (options.length === 0) {
274 return null;
275 }
276 return {
277 id: question.id,
278 header: question.header,
279 question: question.question,
280 options,
281 };
282 })
283 .filter((question): question is UserInputQuestion => question !== null);
284 return parsed.length > 0 ? parsed : null;
286​
287export function derivePendingUserInputs(
288 activities: ReadonlyArray<OrchestrationThreadActivity>,
289): PendingUserInput[] {
290 const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
291 const ordered = [...activities].toSorted(compareActivitiesByOrder);
292​
293 for (const activity of ordered) {
294 const payload =
295 activity.payload && typeof activity.payload === "object"
296 ? (activity.payload as Record<string, unknown>)
297 : null;
298 const requestId =
299 payload && typeof payload.requestId === "string"
300 ? ApprovalRequestId.makeUnsafe(payload.requestId)
301 : null;
302 const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
303​
304 if (activity.kind === "user-input.requested" && requestId) {
305 const questions = parseUserInputQuestions(payload);
306 if (!questions) {
307 continue;
308 }
309 openByRequestId.set(requestId, {
310 requestId,
311 createdAt: activity.createdAt,
312 questions,
313 });
314 continue;
315 }
316​
317 if (activity.kind === "user-input.resolved" && requestId) {
318 openByRequestId.delete(requestId);
319 continue;
320 }
321​
322 if (
323 activity.kind === "provider.user-input.respond.failed" &&
324 requestId &&
325 isStalePendingRequestFailureDetail(detail)
326 ) {
327 openByRequestId.delete(requestId);
328 }
329 }
330​
331 return [...openByRequestId.values()].toSorted((left, right) =>
332 left.createdAt.localeCompare(right.createdAt),
333 );
335​
336export function deriveActivePlanState(
337 activities: ReadonlyArray<OrchestrationThreadActivity>,
338 latestTurnId: TurnId | undefined,
339): ActivePlanState | null {
340 const ordered = [...activities].toSorted(compareActivitiesByOrder);
341 const candidates = ordered.filter((activity) => {
342 if (activity.kind !== "turn.plan.updated") {
343 return false;
344 }
345 if (!latestTurnId) {
346 return true;
347 }
348 return activity.turnId === latestTurnId;
349 });
350 const latest = candidates.at(-1);
351 if (!latest) {
352 return null;
353 }
354 const payload =
355 latest.payload && typeof latest.payload === "object"
356 ? (latest.payload as Record<string, unknown>)
357 : null;
358 const rawPlan = payload?.plan;
359 if (!Array.isArray(rawPlan)) {
360 return null;
361 }
362 const steps = rawPlan
363 .map((entry) => {
364 if (!entry || typeof entry !== "object") return null;
365 const record = entry as Record<string, unknown>;
366 if (typeof record.step !== "string") {
367 return null;
368 }
369 const status =
370 record.status === "completed" || record.status === "inProgress" ? record.status : "pending";
371 return {
372 step: record.step,
373 status,
374 };
375 })
376 .filter(
377 (
378 step,
379 ): step is {
380 step: string;
381 status: "pending" | "inProgress" | "completed";
382 } => step !== null,
383 );
384 if (steps.length === 0) {
385 return null;
386 }
387 return {
388 createdAt: latest.createdAt,
389 turnId: latest.turnId,
390 ...(payload && "explanation" in payload
391 ? { explanation: payload.explanation as string | null }
392 : {}),
393 steps,
394 };
396​
397export function findLatestProposedPlan(
398 proposedPlans: ReadonlyArray<ProposedPlan>,
399 latestTurnId: TurnId | string | null | undefined,
400): LatestProposedPlanState | null {
401 if (latestTurnId) {
402 const matchingTurnPlan = [...proposedPlans]
403 .filter((proposedPlan) => proposedPlan.turnId === latestTurnId)
404 .toSorted(
405 (left, right) =>
406 left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id),
407 )
408 .at(-1);
409 if (matchingTurnPlan) {
410 return toLatestProposedPlanState(matchingTurnPlan);
411 }
412 }
413​
414 const latestPlan = [...proposedPlans]
415 .toSorted(
416 (left, right) =>
417 left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id),
418 )
419 .at(-1);
420 if (!latestPlan) {
421 return null;
422 }
423​
424 return toLatestProposedPlanState(latestPlan);
426​
427export function findSidebarProposedPlan(input: {
428 threads: ReadonlyArray<Pick<Thread, "id" | "proposedPlans">>;
429 latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "sourceProposedPlan"> | null;
430 latestTurnSettled: boolean;
431 threadId: ThreadId | string | null | undefined;
432}): LatestProposedPlanState | null {
433 const activeThreadPlans =
434 input.threads.find((thread) => thread.id === input.threadId)?.proposedPlans ?? [];
435​
436 if (!input.latestTurnSettled) {
437 const sourceProposedPlan = input.latestTurn?.sourceProposedPlan;
438 if (sourceProposedPlan) {
439 const sourcePlan = input.threads
440 .find((thread) => thread.id === sourceProposedPlan.threadId)
441 ?.proposedPlans.find((plan) => plan.id === sourceProposedPlan.planId);
442 if (sourcePlan) {
443 return toLatestProposedPlanState(sourcePlan);
444 }
445 }
446 }
447​
448 return findLatestProposedPlan(activeThreadPlans, input.latestTurn?.turnId ?? null);
450​
451export function hasActionableProposedPlan(
452 proposedPlan: LatestProposedPlanState | Pick<ProposedPlan, "implementedAt"> | null,
453): boolean {
454 return proposedPlan !== null && proposedPlan.implementedAt === null;
456​
457export function deriveWorkLogEntries(
458 activities: ReadonlyArray<OrchestrationThreadActivity>,
459 latestTurnId: TurnId | undefined,
460): WorkLogEntry[] {
461 const ordered = [...activities].toSorted(compareActivitiesByOrder);
462 const entries = ordered
463 .filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
464 .filter((activity) => activity.kind !== "tool.started")
465 .filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
466 .filter((activity) => activity.kind !== "context-window.updated")
467 .filter((activity) => activity.summary !== "Checkpoint captured")
468 .filter((activity) => !isPlanBoundaryToolActivity(activity))
469 .map(toDerivedWorkLogEntry);
470 return collapseDerivedWorkLogEntries(entries).map(
471 ({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
472 );
474​
475function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
476 if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
477 return false;
478 }
479​
480 const payload =
481 activity.payload && typeof activity.payload === "object"
482 ? (activity.payload as Record<string, unknown>)
483 : null;
484 return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
486​
487function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
488 const payload =
489 activity.payload && typeof activity.payload === "object"
490 ? (activity.payload as Record<string, unknown>)
491 : null;
492 const command = extractToolCommand(payload);
493 const changedFiles = extractChangedFiles(payload);
494 const title = extractToolTitle(payload);
495 const entry: DerivedWorkLogEntry = {
496 id: activity.id,
497 createdAt: activity.createdAt,
498 label: activity.summary,
499 tone: activity.tone === "approval" ? "info" : activity.tone,
500 activityKind: activity.kind,
501 };
502 const itemType = extractWorkLogItemType(payload);
503 const requestKind = extractWorkLogRequestKind(payload);
504 if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
505 const detail = stripTrailingExitCode(payload.detail).output;
506 if (detail) {
507 entry.detail = detail;
508 }
509 }
510 if (command) {
511 entry.command = command;
512 }
513 if (changedFiles.length > 0) {
514 entry.changedFiles = changedFiles;
515 }
516 if (title) {
517 entry.toolTitle = title;
518 }
519 if (itemType) {
520 entry.itemType = itemType;
521 }
522 if (requestKind) {
523 entry.requestKind = requestKind;
524 }
525 const collapseKey = deriveToolLifecycleCollapseKey(entry);
526 if (collapseKey) {
527 entry.collapseKey = collapseKey;
528 }
529 return entry;
531​
532function collapseDerivedWorkLogEntries(
533 entries: ReadonlyArray<DerivedWorkLogEntry>,
534): DerivedWorkLogEntry[] {
535 const collapsed: DerivedWorkLogEntry[] = [];
536 for (const entry of entries) {
537 const previous = collapsed.at(-1);
538 if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
539 collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
540 continue;
541 }
542 collapsed.push(entry);
543 }
544 return collapsed;
546​
547function shouldCollapseToolLifecycleEntries(
548 previous: DerivedWorkLogEntry,
549 next: DerivedWorkLogEntry,
550): boolean {
551 if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") {
552 return false;
553 }
554 if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") {
555 return false;
556 }
557 if (previous.activityKind === "tool.completed") {
558 return false;
559 }
560 return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
562​
563function mergeDerivedWorkLogEntries(
564 previous: DerivedWorkLogEntry,
565 next: DerivedWorkLogEntry,
566): DerivedWorkLogEntry {
567 const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
568 const detail = next.detail ?? previous.detail;
569 const command = next.command ?? previous.command;
570 const toolTitle = next.toolTitle ?? previous.toolTitle;
571 const itemType = next.itemType ?? previous.itemType;
572 const requestKind = next.requestKind ?? previous.requestKind;
573 const collapseKey = next.collapseKey ?? previous.collapseKey;
574 return {
575 ...previous,
576 ...next,
577 ...(detail ? { detail } : {}),
578 ...(command ? { command } : {}),
579 ...(changedFiles.length > 0 ? { changedFiles } : {}),
580 ...(toolTitle ? { toolTitle } : {}),
581 ...(itemType ? { itemType } : {}),
582 ...(requestKind ? { requestKind } : {}),
583 ...(collapseKey ? { collapseKey } : {}),
584 };
586​
587function mergeChangedFiles(
588 previous: ReadonlyArray<string> | undefined,
589 next: ReadonlyArray<string> | undefined,
590): string[] {
591 const merged = [...(previous ?? []), ...(next ?? [])];
592 if (merged.length === 0) {
593 return [];
594 }
595 return [...new Set(merged)];
597​
598function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
599 if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
600 return undefined;
601 }
602 const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
603 const detail = entry.detail?.trim() ?? "";
604 const itemType = entry.itemType ?? "";
605 if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) {
606 return undefined;
607 }
608 return [itemType, normalizedLabel, detail].join("\u001f");
610​
611function normalizeCompactToolLabel(value: string): string {
612 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
614​
615function toLatestProposedPlanState(proposedPlan: ProposedPlan): LatestProposedPlanState {
616 return {
617 id: proposedPlan.id,
618 createdAt: proposedPlan.createdAt,
619 updatedAt: proposedPlan.updatedAt,
620 turnId: proposedPlan.turnId,
621 planMarkdown: proposedPlan.planMarkdown,
622 implementedAt: proposedPlan.implementedAt,
623 implementationThreadId: proposedPlan.implementationThreadId,
624 };
626​
627function asRecord(value: unknown): Record<string, unknown> | null {
628 return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
630​
631function asTrimmedString(value: unknown): string | null {
632 if (typeof value !== "string") {
633 return null;
634 }
635 const trimmed = value.trim();
636 return trimmed.length > 0 ? trimmed : null;
638​
639function normalizeCommandValue(value: unknown): string | null {
640 const direct = asTrimmedString(value);
641 if (direct) {
642 return direct;
643 }
644 if (!Array.isArray(value)) {
645 return null;
646 }
647 const parts = value
648 .map((entry) => asTrimmedString(entry))
649 .filter((entry): entry is string => entry !== null);
650 return parts.length > 0 ? parts.join(" ") : null;
652​
653function extractToolCommand(payload: Record<string, unknown> | null): string | null {
654 const data = asRecord(payload?.data);
655 const item = asRecord(data?.item);
656 const itemResult = asRecord(item?.result);
657 const itemInput = asRecord(item?.input);
658 const candidates = [
659 normalizeCommandValue(item?.command),
660 normalizeCommandValue(itemInput?.command),
661 normalizeCommandValue(itemResult?.command),
662 normalizeCommandValue(data?.command),
663 ];
664 return candidates.find((candidate) => candidate !== null) ?? null;
666​
667function extractToolTitle(payload: Record<string, unknown> | null): string | null {
668 return asTrimmedString(payload?.title);
670​
671function stripTrailingExitCode(value: string): {
672 output: string | null;
673 exitCode?: number | undefined;
674} {
675 const trimmed = value.trim();
676 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(
677 trimmed,
678 );
679 if (!match?.groups) {
680 return {
681 output: trimmed.length > 0 ? trimmed : null,
682 };
683 }
684 const exitCode = Number.parseInt(match.groups.code ?? "", 10);
685 const normalizedOutput = match.groups.output?.trim() ?? "";
686 return {
687 output: normalizedOutput.length > 0 ? normalizedOutput : null,
688 ...(Number.isInteger(exitCode) ? { exitCode } : {}),
689 };
691​
692function extractWorkLogItemType(
693 payload: Record<string, unknown> | null,
694): WorkLogEntry["itemType"] | undefined {
695 if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) {
696 return payload.itemType;
697 }
698 return undefined;
700​
701function extractWorkLogRequestKind(
702 payload: Record<string, unknown> | null,
703): WorkLogEntry["requestKind"] | undefined {
704 if (
705 payload?.requestKind === "command" ||
706 payload?.requestKind === "file-read" ||
707 payload?.requestKind === "file-change"
708 ) {
709 return payload.requestKind;
710 }
711 return requestKindFromRequestType(payload?.requestType) ?? undefined;
713​
714function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
715 const normalized = asTrimmedString(value);
716 if (!normalized || seen.has(normalized)) {
717 return;
718 }
719 seen.add(normalized);
720 target.push(normalized);
722​
723function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
724 if (depth > 4 || target.length >= 12) {
725 return;
726 }
727 if (Array.isArray(value)) {
728 for (const entry of value) {
729 collectChangedFiles(entry, target, seen, depth + 1);
730 if (target.length >= 12) {
731 return;
732 }
733 }
734 return;
735 }
736​
737 const record = asRecord(value);
738 if (!record) {
739 return;
740 }
741​
742 pushChangedFile(target, seen, record.path);
743 pushChangedFile(target, seen, record.filePath);
744 pushChangedFile(target, seen, record.relativePath);
745 pushChangedFile(target, seen, record.filename);
746 pushChangedFile(target, seen, record.newPath);
747 pushChangedFile(target, seen, record.oldPath);
748​
749 for (const nestedKey of [
750 "item",
751 "result",
752 "input",
753 "data",
754 "changes",
755 "files",
756 "edits",
757 "patch",
758 "patches",
759 "operations",
760 ]) {
761 if (!(nestedKey in record)) {
762 continue;
763 }
764 collectChangedFiles(record[nestedKey], target, seen, depth + 1);
765 if (target.length >= 12) {
766 return;
767 }
768 }
770​
771function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
772 const changedFiles: string[] = [];
773 const seen = new Set<string>();
774 collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0);
775 return changedFiles;
777​
778function compareActivitiesByOrder(
779 left: OrchestrationThreadActivity,
780 right: OrchestrationThreadActivity,
781): number {
782 if (left.sequence !== undefined && right.sequence !== undefined) {
783 if (left.sequence !== right.sequence) {
784 return left.sequence - right.sequence;
785 }
786 } else if (left.sequence !== undefined) {
787 return 1;
788 } else if (right.sequence !== undefined) {
789 return -1;
790 }
791​
792 const createdAtComparison = left.createdAt.localeCompare(right.createdAt);
793 if (createdAtComparison !== 0) {
794 return createdAtComparison;
795 }
796​
797 const lifecycleRankComparison =
798 compareActivityLifecycleRank(left.kind) - compareActivityLifecycleRank(right.kind);
799 if (lifecycleRankComparison !== 0) {
800 return lifecycleRankComparison;
801 }
802​
803 return left.id.localeCompare(right.id);
805​
806function compareActivityLifecycleRank(kind: string): number {
807 if (kind.endsWith(".started") || kind === "tool.started") {
808 return 0;
809 }
810 if (kind.endsWith(".progress") || kind.endsWith(".updated")) {
811 return 1;
812 }
813 if (kind.endsWith(".completed") || kind.endsWith(".resolved")) {
814 return 2;
815 }
816 return 1;
818​
819export function hasToolActivityForTurn(
820 activities: ReadonlyArray<OrchestrationThreadActivity>,
821 turnId: TurnId | null | undefined,
822): boolean {
823 if (!turnId) return false;
824 return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
826​
827export function deriveTimelineEntries(
828 messages: ChatMessage[],
829 proposedPlans: ProposedPlan[],
830 workEntries: WorkLogEntry[],
831): TimelineEntry[] {
832 const messageRows: TimelineEntry[] = messages.map((message) => ({
833 id: message.id,
834 kind: "message",
835 createdAt: message.createdAt,
836 message,
837 }));
838 const proposedPlanRows: TimelineEntry[] = proposedPlans.map((proposedPlan) => ({
839 id: proposedPlan.id,
840 kind: "proposed-plan",
841 createdAt: proposedPlan.createdAt,
842 proposedPlan,
843 }));
844 const workRows: TimelineEntry[] = workEntries.map((entry) => ({
845 id: entry.id,
846 kind: "work",
847 createdAt: entry.createdAt,
848 entry,
849 }));
850 return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) =>
851 a.createdAt.localeCompare(b.createdAt),
852 );
854​
855export function deriveCompletionDividerBeforeEntryId(
856 timelineEntries: ReadonlyArray<TimelineEntry>,
857 latestTurn: Pick<
858 OrchestrationLatestTurn,
859 "assistantMessageId" | "startedAt" | "completedAt"
860 > | null,
861): string | null {
862 if (!latestTurn?.startedAt || !latestTurn.completedAt) {
863 return null;
864 }
865​
866 if (latestTurn.assistantMessageId) {
867 const exactMatch = timelineEntries.find(
868 (timelineEntry) =>
869 timelineEntry.kind === "message" &&
870 timelineEntry.message.role === "assistant" &&
871 timelineEntry.message.id === latestTurn.assistantMessageId,
872 );
873 if (exactMatch) {
874 return exactMatch.id;
875 }
876 }
877​
878 const turnStartedAt = Date.parse(latestTurn.startedAt);
879 const turnCompletedAt = Date.parse(latestTurn.completedAt);
880 if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) {
881 return null;
882 }
883​
884 let inRangeMatch: string | null = null;
885 let fallbackMatch: string | null = null;
886 for (const timelineEntry of timelineEntries) {
887 if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") {
888 continue;
889 }
890 const messageAt = Date.parse(timelineEntry.message.createdAt);
891 if (Number.isNaN(messageAt) || messageAt < turnStartedAt) {
892 continue;
893 }
894 fallbackMatch = timelineEntry.id;
895 if (messageAt <= turnCompletedAt) {
896 inRangeMatch = timelineEntry.id;
897 }
898 }
899 return inRangeMatch ?? fallbackMatch;
901​
902export function inferCheckpointTurnCountByTurnId(
903 summaries: TurnDiffSummary[],
904): Record<TurnId, number> {
905 const sorted = [...summaries].toSorted((a, b) => a.completedAt.localeCompare(b.completedAt));
906 const result: Record<TurnId, number> = {};
907 for (let index = 0; index < sorted.length; index += 1) {
908 const summary = sorted[index];
909 if (!summary) continue;
910 result[summary.turnId] = index + 1;
911 }
912 return result;
914​
915export function derivePhase(session: ThreadSession | null): SessionPhase {
916 if (!session || session.status === "closed") return "disconnected";
917 if (session.status === "connecting") return "connecting";
918 if (session.status === "running") return "running";
919 return "ready";