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 // A linked thread inherited nothing, so it must not be labelled a fork.
93 kind:
94 thread.lineage.relationshipToParent === "subagent"
95 ? "subagent"
96 : thread.lineage.relationshipToParent === "fork"
97 ? "fork"
98 : thread.forkedFrom?.type === "run"
99 ? "fork"
100 : "parent",
101 status: thread.activityRunStatus ?? thread.status,
102 });
103 }
104
105 if (input.projection !== null) {
106 const ownerThreadId = input.projection.thread.id;
107 for (const subagent of input.projection.subagents) {
108 if (subagent.childThreadId === null) continue;
109 const child = threadsById.get(subagent.childThreadId);
110 addEdge({
111 sourceThreadId: ownerThreadId,
112 targetThreadId: subagent.childThreadId,
113 kind: "subagent",
114 status:
115 child?.activityRunStatus ??
116 (child?.latestRunId != null && !isOrchestrationV2WorkActive(subagent.status)
117 ? child.status
118 : subagent.status),
119 });
120 }
121 for (const transfer of input.projection.contextTransfers) {
122 if (transfer.sourceThreadId === transfer.targetThreadId) continue;
123 addEdge({
124 sourceThreadId: transfer.sourceThreadId,
125 targetThreadId: transfer.targetThreadId,
126 kind: "transfer",
127 status: transfer.status,
128 });
129 }
130 }
131
132 return { nodes, edges: [...edgesByKey.values()] };
133}
134
135export function immediateThreadRelationships(
136 graph: ThreadRelationshipGraph,
137 threadId: ThreadId,
138): ReadonlyArray<ThreadRelationshipWalkRow> {
139 const visited = new Set<ThreadId>();
140 const rows: ThreadRelationshipWalkRow[] = [];
141
142 for (const edge of graph.edges) {
143 const relatedId =
144 edge.sourceThreadId === threadId
145 ? edge.targetThreadId
146 : edge.targetThreadId === threadId
147 ? edge.sourceThreadId
148 : null;
149 if (relatedId === null || visited.has(relatedId)) continue;
150 visited.add(relatedId);
151 rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge });
152 }
153
154 return rows;
155}
156
157export function isParentThreadRelationship(
158 edge: ThreadRelationshipEdge,
159 currentThreadId: ThreadId,
160): boolean {
161 return edge.kind !== "transfer" && edge.targetThreadId === currentThreadId;
162}
163
164export function threadRelationshipRowStatus(
165 graph: ThreadRelationshipGraph,
166 row: Pick<ThreadRelationshipWalkRow, "threadId" | "edge">,
167): string | null {
168 if (row.edge.kind === "transfer" || row.threadId === row.edge.targetThreadId) {
169 return row.edge.status;
170 }
171 const thread = graph.nodes.get(row.threadId)?.thread;
172 return thread?.activityRunStatus ?? thread?.status ?? null;
173}
174
175function threadCreatedAtMillis(node: ThreadRelationshipNode | undefined): number | null {
176 const createdAt: unknown = node?.thread?.createdAt;
177 if (!DateTime.isDateTime(createdAt)) return null;
178 const millis = DateTime.toEpochMillis(createdAt);
179 return Number.isFinite(millis) ? millis : null;
180}
181
182/**
183 * Web pins the parent and distinct merge-back target before newest-created-first ordering.
184 * Mobile does not share this exception; do not reuse it as the canonical relationship order.
185 */
186export function orderWebThreadLineageRows(input: {
187 readonly graph: ThreadRelationshipGraph;
188 readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
189 readonly currentThreadId: ThreadId;
190 readonly mergeTargetThreadId: ThreadId | null;
191}): ReadonlyArray<ThreadRelationshipWalkRow> {
192 const pinRank = (row: ThreadRelationshipWalkRow): number => {
193 if (isParentThreadRelationship(row.edge, input.currentThreadId)) return 0;
194 if (row.threadId === input.mergeTargetThreadId) return 1;
195 return 2;
196 };
197
198 return [...input.rows].sort((left, right) => {
199 const rankDelta = pinRank(left) - pinRank(right);
200 if (rankDelta !== 0) return rankDelta;
201 const leftCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(left.threadId));
202 const rightCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(right.threadId));
203 if (leftCreatedAt !== rightCreatedAt) {
204 if (leftCreatedAt === null) return 1;
205 if (rightCreatedAt === null) return -1;
206 return rightCreatedAt - leftCreatedAt;
207 }
208 return left.threadId < right.threadId ? -1 : left.threadId > right.threadId ? 1 : 0;
209 });
210}