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 addEdge({
96 sourceThreadId: ownerThreadId,
97 targetThreadId: subagent.childThreadId,
98 kind: "subagent",
99 status: subagent.status,
100 });
101 }
102 for (const transfer of input.projection.contextTransfers) {
103 if (transfer.sourceThreadId === transfer.targetThreadId) continue;
104 addEdge({
105 sourceThreadId: transfer.sourceThreadId,
106 targetThreadId: transfer.targetThreadId,
107 kind: "transfer",
108 status: transfer.status,
109 });
110 }
111 }
112
113 return { nodes, edges: [...edgesByKey.values()] };
114}
115
116export function relatedThreadIds(
117 graph: ThreadRelationshipGraph,
118 threadId: ThreadId,
119): ReadonlyArray<ThreadId> {
120 const ids = new Set<ThreadId>();
121 for (const edge of graph.edges) {
122 if (edge.sourceThreadId === threadId) ids.add(edge.targetThreadId);
123 if (edge.targetThreadId === threadId) ids.add(edge.sourceThreadId);
124 }
125 return [...ids];
126}
127
128export function walkThreadRelationships(
129 graph: ThreadRelationshipGraph,
130 threadId: ThreadId,
131): ReadonlyArray<ThreadRelationshipWalkRow> {
132 const visited = new Set<ThreadId>([threadId]);
133 const pending: Array<{ readonly threadId: ThreadId; readonly depth: number }> = [
134 { threadId, depth: 0 },
135 ];
136 const rows: ThreadRelationshipWalkRow[] = [];
137
138 for (let index = 0; index < pending.length; index += 1) {
139 const current = pending[index];
140 if (current === undefined) continue;
141 for (const edge of graph.edges) {
142 const relatedId =
143 edge.sourceThreadId === current.threadId
144 ? edge.targetThreadId
145 : edge.targetThreadId === current.threadId
146 ? edge.sourceThreadId
147 : null;
148 if (relatedId === null || visited.has(relatedId)) continue;
149 visited.add(relatedId);
150 const depth = current.depth + 1;
151 rows.push({ threadId: relatedId, fromThreadId: current.threadId, depth, edge });
152 pending.push({ threadId: relatedId, depth });
153 }
154 }
155
156 return rows;
157}
158
159export function immediateThreadRelationships(
160 graph: ThreadRelationshipGraph,
161 threadId: ThreadId,
162): ReadonlyArray<ThreadRelationshipWalkRow> {
163 const visited = new Set<ThreadId>();
164 const rows: ThreadRelationshipWalkRow[] = [];
165
166 for (const edge of graph.edges) {
167 const relatedId =
168 edge.sourceThreadId === threadId
169 ? edge.targetThreadId
170 : edge.targetThreadId === threadId
171 ? edge.sourceThreadId
172 : null;
173 if (relatedId === null || visited.has(relatedId)) continue;
174 visited.add(relatedId);
175 rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge });
176 }
177
178 return rows;
179}
180
181/** True when `edge` reaches `currentThreadId` from its parent or owning agent. */
182export function isParentThreadRelationship(
183 edge: ThreadRelationshipEdge,
184 currentThreadId: ThreadId,
185): boolean {
186 return edge.kind !== "transfer" && edge.targetThreadId === currentThreadId;
187}
188
189function threadCreatedAtMillis(node: ThreadRelationshipNode | undefined): number | null {
190 // `createdAt` is typed as a DateTime, but the value reaches here from a
191 // decoded shell that may be missing (a related thread we have no shell for).
192 const createdAt: unknown = node?.thread?.createdAt;
193 if (!DateTime.isDateTime(createdAt)) return null;
194 const millis = DateTime.toEpochMillis(createdAt);
195 return Number.isFinite(millis) ? millis : null;
196}
197
198/**
199 * Orders the web thread-details Lineage rows for display.
200 *
201 * Web-specific by design: the panel pins the parent row first and a distinct
202 * merge-back target second so their actions stay where the user expects, and
203 * only then falls back to newest-created-first. Mobile does not share that
204 * exception, so this is not the canonical relationship order and should not be
205 * reused as one.
206 *
207 * Ordering below the pins is `createdAt` descending, which is immutable, so
208 * rows never move when messages or status changes arrive on a related thread.
209 * Threads whose shell is missing (or whose `createdAt` did not decode) sink to
210 * the bottom. Ties break by thread id ascending so the order is total.
211 */
212export function orderWebThreadLineageRows(input: {
213 readonly graph: ThreadRelationshipGraph;
214 readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
215 readonly currentThreadId: ThreadId;
216 readonly mergeTargetThreadId: ThreadId | null;
217}): ReadonlyArray<ThreadRelationshipWalkRow> {
218 const pinRank = (row: ThreadRelationshipWalkRow): number => {
219 if (isParentThreadRelationship(row.edge, input.currentThreadId)) return 0;
220 if (row.threadId === input.mergeTargetThreadId) return 1;
221 return 2;
222 };
223
224 return input.rows.toSorted((left, right) => {
225 const rankDelta = pinRank(left) - pinRank(right);
226 if (rankDelta !== 0) return rankDelta;
227 const leftCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(left.threadId));
228 const rightCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(right.threadId));
229 if (leftCreatedAt !== rightCreatedAt) {
230 if (leftCreatedAt === null) return 1;
231 if (rightCreatedAt === null) return -1;
232 return rightCreatedAt - leftCreatedAt;
233 }
234 return left.threadId < right.threadId ? -1 : left.threadId > right.threadId ? 1 : 0;
235 });
236}