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