The best way to control Claude Code, Codex and more from any computer or phone

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