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