Open History to see the last commit
1import {
2 isOrchestrationV2WorkActive,
3 type OrchestrationV2ThreadShell,
4 type ThreadId,
5} from "@t3tools/contracts";
6import * as DateTime from "effect/DateTime";
7
8import type { ThreadStructure } from "./models.ts";
9
10export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer";
11
12export interface ThreadRelationshipNode {
13 readonly threadId: ThreadId;
14 readonly thread: OrchestrationV2ThreadShell | null;
15 readonly missing: boolean;
16}
17
18export interface ThreadRelationshipEdge {
19 readonly sourceThreadId: ThreadId;
20 readonly targetThreadId: ThreadId;
21 readonly kind: ThreadRelationshipKind;
22 readonly status: string | null;
23}
24
25export interface ThreadRelationshipGraph {
26 readonly nodes: ReadonlyMap<ThreadId, ThreadRelationshipNode>;
27 readonly edges: ReadonlyArray<ThreadRelationshipEdge>;
28}
29
30export interface ThreadRelationshipWalkRow {
31 readonly threadId: ThreadId;
32 readonly fromThreadId: ThreadId;
33 readonly depth: number;
34 readonly edge: ThreadRelationshipEdge;
35}
36
37export function resolveMergeBackTargetThreadId(
38 projection: Pick<ThreadStructure, "thread"> | null,
39): ThreadId | null {
40 if (projection?.thread.lineage.relationshipToParent !== "fork") return null;
41 return projection.thread.forkedFrom?.type === "run"
42 ? projection.thread.forkedFrom.threadId
43 : projection.thread.lineage.parentThreadId;
44}
45
46function edgeKey(edge: ThreadRelationshipEdge): string {
47 return `${edge.sourceThreadId}\u001f${edge.targetThreadId}\u001f${edge.kind}`;
48}
49
50export function selectLatestSubagentsByChildThread<
51 Subagent extends {
52 readonly childThreadId: ThreadId | null;
53 readonly status: Parameters<typeof isOrchestrationV2WorkActive>[0];
54 readonly startedAt: DateTime.Utc | null;
55 readonly updatedAt: DateTime.Utc;
56 },
57>(subagents: ReadonlyArray<Subagent>): Map<ThreadId, Subagent> {
58 // A queued follow-up is stamped startedAt while still pending; only its status says it waits.
59 const isRunning = (subagent: Subagent) =>
60 subagent.status !== "pending" && isOrchestrationV2WorkActive(subagent.status);
61 const orderMs = (subagent: Subagent) =>
62 DateTime.toEpochMillis(subagent.startedAt ?? subagent.updatedAt);
63 const latestByChildId = new Map<ThreadId, Subagent>();
64 for (const subagent of subagents) {
65 if (subagent.childThreadId === null) continue;
66 const previous = latestByChildId.get(subagent.childThreadId);
67 if (previous === undefined) {
68 latestByChildId.set(subagent.childThreadId, subagent);
69 continue;
70 }
71 const previousRunning = isRunning(previous);
72 const nextRunning = isRunning(subagent);
73 if (previousRunning && !nextRunning) continue;
74 if ((!previousRunning && nextRunning) || orderMs(subagent) >= orderMs(previous)) {
75 latestByChildId.set(subagent.childThreadId, subagent);
76 }
77 }
78 return latestByChildId;
79}
80
81export function deriveThreadRelationshipGraph(input: {
82 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
83 readonly projection: ThreadStructure | null;
84}): ThreadRelationshipGraph {
85 const threadsById = new Map<ThreadId, OrchestrationV2ThreadShell>();
86 for (const thread of input.threads) {
87 // Callers order shells from most to least authoritative. In particular,
88 // live shells precede archived snapshots, which may still contain a stale
89 // copy during archive refresh.
90 if (!threadsById.has(thread.id)) {
91 threadsById.set(thread.id, thread);
92 }
93 }
94 const threads = [...threadsById.values()];
95 const nodes = new Map<ThreadId, ThreadRelationshipNode>(
96 threads.map((thread) => [thread.id, { threadId: thread.id, thread, missing: false }]),
97 );
98 const edgesByKey = new Map<string, ThreadRelationshipEdge>();
99 const ensureNode = (threadId: ThreadId) => {
100 if (!nodes.has(threadId)) {
101 nodes.set(threadId, { threadId, thread: null, missing: true });
102 }
103 };
104 const addEdge = (edge: ThreadRelationshipEdge) => {
105 ensureNode(edge.sourceThreadId);
106 ensureNode(edge.targetThreadId);
107 edgesByKey.set(
108 edgeKey(edge),
109 edge.kind === "subagent" && edge.status === "rolled_back"
110 ? { ...edge, status: "interrupted" }
111 : edge,
112 );
113 };
114
115 const selectedThread = input.projection?.thread;
116 const lineageThreads =
117 selectedThread !== undefined && !threadsById.has(selectedThread.id)
118 ? [...threads, { ...selectedThread, activityRunStatus: null, status: null }]
119 : threads;
120 for (const thread of lineageThreads) {
121 const parentThreadId =
122 thread.forkedFrom?.type === "run"
123 ? thread.forkedFrom.threadId
124 : thread.lineage.parentThreadId;
125 if (parentThreadId === null) continue;
126 addEdge({
127 sourceThreadId: parentThreadId,
128 targetThreadId: thread.id,
129 kind: thread.lineage.relationshipToParent === "subagent" ? "subagent" : "fork",
130 status: thread.activityRunStatus ?? thread.status,
131 });
132 }
133
134 if (input.projection !== null) {
135 const ownerThreadId = input.projection.thread.id;
136 const latestByChildId = selectLatestSubagentsByChildThread(input.projection.subagents);
137 for (const [childThreadId, subagent] of latestByChildId) {
138 const child = threadsById.get(childThreadId);
139 addEdge({
140 sourceThreadId: ownerThreadId,
141 targetThreadId: childThreadId,
142 kind: "subagent",
143 status:
144 child?.activityRunStatus ??
145 (child?.latestRunId != null && !isOrchestrationV2WorkActive(subagent.status)
146 ? child.status
147 : subagent.status),
148 });
149 }
150 for (const transfer of input.projection.contextTransfers) {
151 if (transfer.sourceThreadId === transfer.targetThreadId) continue;
152 addEdge({
153 sourceThreadId: transfer.sourceThreadId,
154 targetThreadId: transfer.targetThreadId,
155 kind: "transfer",
156 status: transfer.status,
157 });
158 }
159 }
160
161 return { nodes, edges: [...edgesByKey.values()] };
162}
163
164export function immediateThreadRelationships(
165 graph: ThreadRelationshipGraph,
166 threadId: ThreadId,
167): ReadonlyArray<ThreadRelationshipWalkRow> {
168 const visited = new Set<ThreadId>();
169 const rows: ThreadRelationshipWalkRow[] = [];
170
171 for (const edge of graph.edges) {
172 const relatedId =
173 edge.sourceThreadId === threadId
174 ? edge.targetThreadId
175 : edge.targetThreadId === threadId
176 ? edge.sourceThreadId
177 : null;
178 if (relatedId === null || visited.has(relatedId)) continue;
179 visited.add(relatedId);
180 rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge });
181 }
182
183 return rows;
184}
185
186export function isParentThreadRelationship(
187 edge: ThreadRelationshipEdge,
188 currentThreadId: ThreadId,
189): boolean {
190 return edge.kind !== "transfer" && edge.targetThreadId === currentThreadId;
191}
192
193export function threadRelationshipRowStatus(
194 graph: ThreadRelationshipGraph,
195 row: Pick<ThreadRelationshipWalkRow, "threadId" | "edge">,
196): string | null {
197 if (row.edge.kind === "transfer" || row.threadId === row.edge.targetThreadId) {
198 return row.edge.status;
199 }
200 const thread = graph.nodes.get(row.threadId)?.thread;
201 return thread?.activityRunStatus ?? thread?.status ?? null;
202}
203
204function threadCreatedAtMillis(node: ThreadRelationshipNode | undefined): number | null {
205 const createdAt: unknown = node?.thread?.createdAt;
206 if (!DateTime.isDateTime(createdAt)) return null;
207 const millis = DateTime.toEpochMillis(createdAt);
208 return Number.isFinite(millis) ? millis : null;
209}
210
211/**
212 * Web pins the parent and distinct merge-back target before newest-created-first ordering.
213 * Mobile does not share this exception; do not reuse it as the canonical relationship order.
214 */
215export function orderWebThreadLineageRows(input: {
216 readonly graph: ThreadRelationshipGraph;
217 readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
218 readonly currentThreadId: ThreadId;
219 readonly mergeTargetThreadId: ThreadId | null;
220}): ReadonlyArray<ThreadRelationshipWalkRow> {
221 const pinRank = (row: ThreadRelationshipWalkRow): number => {
222 if (isParentThreadRelationship(row.edge, input.currentThreadId)) return 0;
223 if (row.threadId === input.mergeTargetThreadId) return 1;
224 return 2;
225 };
226
227 return [...input.rows].sort((left, right) => {
228 const rankDelta = pinRank(left) - pinRank(right);
229 if (rankDelta !== 0) return rankDelta;
230 const leftCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(left.threadId));
231 const rightCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(right.threadId));
232 if (leftCreatedAt !== rightCreatedAt) {
233 if (leftCreatedAt === null) return 1;
234 if (rightCreatedAt === null) return -1;
235 return rightCreatedAt - leftCreatedAt;
236 }
237 return left.threadId < right.threadId ? -1 : left.threadId > right.threadId ? 1 : 0;
238 });
239}