Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadRelationships.ts

202 lines7.0 KB

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;
16​
17export interface ThreadRelationshipEdge {
18 readonly sourceThreadId: ThreadId;
19 readonly targetThreadId: ThreadId;
20 readonly kind: ThreadRelationshipKind;
21 readonly status: string | null;
23​
24export interface ThreadRelationshipGraph {
25 readonly nodes: ReadonlyMap<ThreadId, ThreadRelationshipNode>;
26 readonly edges: ReadonlyArray<ThreadRelationshipEdge>;
28​
29export interface ThreadRelationshipWalkRow {
30 readonly threadId: ThreadId;
31 readonly fromThreadId: ThreadId;
32 readonly depth: number;
33 readonly edge: ThreadRelationshipEdge;
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;
44​
45function edgeKey(edge: ThreadRelationshipEdge): string {
46 return `${edge.sourceThreadId}\u001f${edge.targetThreadId}\u001f${edge.kind}`;
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()] };
126​
127export function immediateThreadRelationships(
128 graph: ThreadRelationshipGraph,
129 threadId: ThreadId,
130): ReadonlyArray<ThreadRelationshipWalkRow> {
131 const visited = new Set<ThreadId>();
132 const rows: ThreadRelationshipWalkRow[] = [];
133​
134 for (const edge of graph.edges) {
135 const relatedId =
136 edge.sourceThreadId === threadId
137 ? edge.targetThreadId
138 : edge.targetThreadId === threadId
139 ? edge.sourceThreadId
140 : null;
141 if (relatedId === null || visited.has(relatedId)) continue;
142 visited.add(relatedId);
143 rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge });
144 }
145​
146 return rows;
148​
149export function isParentThreadRelationship(
150 edge: ThreadRelationshipEdge,
151 currentThreadId: ThreadId,
152): boolean {
153 return edge.kind !== "transfer" && edge.targetThreadId === currentThreadId;
155​
156export function threadRelationshipRowStatus(
157 graph: ThreadRelationshipGraph,
158 row: Pick<ThreadRelationshipWalkRow, "threadId" | "edge">,
159): string | null {
160 if (row.edge.kind === "transfer" || row.threadId === row.edge.targetThreadId) {
161 return row.edge.status;
162 }
163 const thread = graph.nodes.get(row.threadId)?.thread;
164 return thread?.activityRunStatus ?? thread?.status ?? null;
166​
167function threadCreatedAtMillis(node: ThreadRelationshipNode | undefined): number | null {
168 const createdAt: unknown = node?.thread?.createdAt;
169 if (!DateTime.isDateTime(createdAt)) return null;
170 const millis = DateTime.toEpochMillis(createdAt);
171 return Number.isFinite(millis) ? millis : null;
173​
174/**
175 * Web pins the parent and distinct merge-back target before newest-created-first ordering.
176 * Mobile does not share this exception; do not reuse it as the canonical relationship order.
177 */
178export function orderWebThreadLineageRows(input: {
179 readonly graph: ThreadRelationshipGraph;
180 readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
181 readonly currentThreadId: ThreadId;
182 readonly mergeTargetThreadId: ThreadId | null;
183}): ReadonlyArray<ThreadRelationshipWalkRow> {
184 const pinRank = (row: ThreadRelationshipWalkRow): number => {
185 if (isParentThreadRelationship(row.edge, input.currentThreadId)) return 0;
186 if (row.threadId === input.mergeTargetThreadId) return 1;
187 return 2;
188 };
189​
190 return [...input.rows].sort((left, right) => {
191 const rankDelta = pinRank(left) - pinRank(right);
192 if (rankDelta !== 0) return rankDelta;
193 const leftCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(left.threadId));
194 const rightCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(right.threadId));
195 if (leftCreatedAt !== rightCreatedAt) {
196 if (leftCreatedAt === null) return 1;
197 if (rightCreatedAt === null) return -1;
198 return rightCreatedAt - leftCreatedAt;
199 }
200 return left.threadId < right.threadId ? -1 : left.threadId > right.threadId ? 1 : 0;
201 });