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

main
ts 421 lines 16.2 KB
Raw
1 import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2 import { threadPullRequestsOf } from "../threadPullRequests.ts";
3 import type {
4 ThreadLinkedPullRequest,
5 EnvironmentId,
6 MessageId,
7 OrchestrationProjectShell,
8 OrchestrationV2ProviderGoal,
9 OrchestrationV2RunStatus,
10 OrchestrationV2ProviderFailureClass,
11 OrchestrationV2ThreadProjection,
12 OrchestrationV2ThreadShell,
13 PlanId,
14 ProjectId,
15 ProviderInstanceId,
16 RunId,
17 ThreadId,
18 } from "@t3tools/contracts";
19 import * as DateTime from "effect/DateTime";
20 import { mFallback, msg } from "gt-i18n";
21 import type { MFunctionType } from "gt-i18n/types";
22
23 import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
24
25 export interface EnvironmentProject extends OrchestrationProjectShell {
26 readonly environmentId: EnvironmentId;
27 readonly isScratch?: true;
28 }
29
30 /**
31 * The projection stays nested so the server projection and all structurally
32 * shared collections retain their identities.
33 */
34 export interface EnvironmentThread {
35 readonly environmentId: EnvironmentId;
36 readonly projection: OrchestrationV2ThreadProjection;
37 }
38
39 type ProjectionTurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
40 type StreamedProjectionTurnItem = Extract<
41 ProjectionTurnItem,
42 { readonly type: "assistant_message" | "reasoning" }
43 >;
44
45 /** A turn item without the fields that move while it streams. */
46 export type ThreadStructureTurnItem =
47 | Exclude<ProjectionTurnItem, StreamedProjectionTurnItem>
48 | Omit<Extract<ProjectionTurnItem, { readonly type: "assistant_message" }>, "text" | "updatedAt">
49 | Omit<Extract<ProjectionTurnItem, { readonly type: "reasoning" }>, "text" | "updatedAt">;
50
51 export type ThreadStructureVisibleTurnItem = Omit<
52 OrchestrationV2ThreadProjection["visibleTurnItems"][number],
53 "item"
54 > & {
55 readonly item: ThreadStructureTurnItem;
56 };
57
58 /**
59 * A thread projection without the fields that move while a reply streams, so a
60 * reader of the quiet thread cannot depend on them and go stale. A full
61 * projection is assignable to it.
62 */
63 export type ThreadStructureThread = Omit<
64 OrchestrationV2ThreadProjection["thread"],
65 "updatedAt" | "lastVisitedAt"
66 >;
67
68 export type ThreadStructure = Omit<
69 OrchestrationV2ThreadProjection,
70 "thread" | "turnItems" | "visibleTurnItems" | "updatedAt"
71 > & {
72 readonly thread: ThreadStructureThread;
73 readonly turnItems: ReadonlyArray<ThreadStructureTurnItem>;
74 readonly visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>;
75 };
76
77 export interface EnvironmentThreadStructure {
78 readonly environmentId: EnvironmentId;
79 readonly projection: ThreadStructure;
80 }
81
82 export interface ThreadRunSummary {
83 readonly runId: RunId;
84 readonly status: OrchestrationV2RunStatus;
85 readonly requestedAt: string | null;
86 readonly startedAt: string | null;
87 readonly completedAt: string | null;
88 readonly assistantMessageId: MessageId | null;
89 /**
90 * The run is still open, but its provider turn already ended, so nothing is
91 * generating while the server settles it.
92 */
93 readonly turnEnded?: boolean;
94 /**
95 * Set while the run is open but its provider has not started a turn, so the
96 * provider is still launching and nothing is generating. Clients show it
97 * instead of "Thinking".
98 */
99 readonly providerStartingLabel?: string;
100 /** `providerStartingLabel` as a `msg()` string; display sites resolve this one. */
101 readonly providerStartingLabelMsg?: string;
102 readonly sourcePlanRef?: {
103 readonly threadId: ThreadId;
104 readonly planId: PlanId;
105 };
106 }
107
108 export interface ThreadRuntimeSummary {
109 readonly status: OrchestrationV2RunStatus | "idle";
110 readonly activeRunId: RunId | null;
111 readonly activityStartedAt?: string | null | undefined;
112 readonly providerInstanceId: ProviderInstanceId;
113 readonly providerName: string | null;
114 readonly lastError: string | null;
115 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
116 readonly lastErrorCode?: string | null;
117 /** The record `lastError` came from, with its change time so a repeated failure differs. */
118 readonly lastErrorSource?: string | null;
119 readonly usageLimitResetAt?: string | null;
120 readonly updatedAt: string;
121 }
122
123 /** The runtime summary a thread's structure determines; see ThreadStructure. */
124 export type ThreadStructureRuntime = Omit<ThreadRuntimeSummary, "updatedAt">;
125
126 export function threadRuntimeIsActive(runtime: ThreadStructureRuntime | null | undefined): boolean {
127 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
128 }
129
130 export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
131 if (runtime?.status === "queued") return runtime.activeRunId === null;
132 return (
133 runtime?.status !== "preparing" &&
134 runtime?.status !== "starting" &&
135 runtime?.status !== "running"
136 );
137 }
138
139 function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
140 return (
141 status === "preparing" ||
142 status === "queued" ||
143 status === "starting" ||
144 status === "running" ||
145 status === "waiting"
146 );
147 }
148
149 export interface EnvironmentThreadShell {
150 readonly environmentId: EnvironmentId;
151 readonly id: ThreadId;
152 readonly projectId: ProjectId;
153 readonly title: string;
154 readonly providerInstanceId: ProviderInstanceId;
155 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
156 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
157 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
158 readonly branch: string | null;
159 readonly worktreePath: string | null;
160 readonly lineage: OrchestrationV2ThreadShell["lineage"];
161 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
162 readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null;
163 /** The thread in a linked environment that delegated this one, if one did. */
164 readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null;
165 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
166 readonly latestRun: ThreadRunSummary | null;
167 readonly runtime: ThreadRuntimeSummary | null;
168 readonly blockedOnThreadWait?: boolean;
169 readonly latestUserMessageAt: string | null;
170 readonly latestUserAuthoredMessageAt?: string | null;
171 readonly hasPendingApprovals: boolean;
172 readonly hasPendingUserInput: boolean;
173 readonly pendingUserInputAt?: string | null;
174 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
175 /** Guest messages waiting for the owner to send or dismiss. */
176 readonly pendingGuestMessageCount?: number;
177 readonly hasActionableProposedPlan: boolean;
178 readonly pendingBackgroundTasks: ReadonlyArray<
179 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
180 >;
181 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
182 readonly goal: OrchestrationV2ProviderGoal | null;
183 readonly itemCount: number;
184 readonly visibleItemCount: number;
185 readonly createdAt: string;
186 readonly updatedAt: string;
187 readonly archivedAt: string | null;
188 readonly settledOverride: "settled" | "active" | null;
189 readonly settledAt: string | null;
190 readonly unsettledAt: string | null;
191 readonly snoozedUntil: string | null;
192 readonly snoozedAt: string | null;
193 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
194 readonly pinnedAt: string | null;
195 readonly autoSettleDisabledAt?: string | null;
196 readonly pinOrderKey: string | null;
197 readonly activeOrderKey: string | null;
198 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
199 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
200 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
201 /** Absent from rows built before issue linking; the server sends an empty list. */
202 readonly issues?: ReadonlyArray<import("@t3tools/contracts").ThreadIssueLink>;
203 /**
204 * Server-tracked visited watermark. `undefined` means the environment's
205 * server predates visited tracking and clients should fall back to any
206 * local visited state they keep.
207 */
208 readonly lastVisitedAt?: string | null;
209 /** Server-tracked open history for search ranking. */
210 readonly opens?: import("@t3tools/contracts").OrchestrationV2ThreadOpens | null;
211 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
212 readonly deletedAt: string | null;
213 readonly source: OrchestrationV2ThreadShell;
214 }
215
216 function iso(value: DateTime.Utc): string {
217 return DateTime.formatIso(value);
218 }
219
220 function nullableIso(value: DateTime.Utc | null): string | null {
221 return value === null ? null : iso(value);
222 }
223
224 function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
225 return (
226 status === "completed" ||
227 status === "interrupted" ||
228 status === "failed" ||
229 status === "cancelled" ||
230 status === "rolled_back"
231 );
232 }
233
234 // Only work the agent waits on holds it: commands and monitors it left running
235 // unmarked, such as a dev server, present the run's own status. The
236 // server suppresses the roster while an interruptible activity run exists, so a
237 // remaining roster is stronger than checkpoint-oriented waiting.
238 function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
239 const parkAtIdle =
240 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
241 thread.status !== "failed";
242 if (thread.latestRunId === null && !parkAtIdle) {
243 return null;
244 }
245 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
246 return {
247 status,
248 activeRunId: thread.activeRunId,
249 activityStartedAt:
250 thread.activityRunStartedAt === undefined
251 ? undefined
252 : nullableIso(thread.activityRunStartedAt),
253 providerInstanceId: thread.providerInstanceId,
254 providerName: null,
255 lastError: thread.lastError ?? null,
256 lastErrorClass: thread.lastErrorClass ?? null,
257 lastErrorCode: thread.lastErrorCode ?? null,
258 usageLimitResetAt: thread.usageLimitResetAt ?? null,
259 updatedAt: iso(thread.updatedAt),
260 };
261 }
262
263 export function scopeProject(
264 environmentId: EnvironmentId,
265 project: OrchestrationProjectShell,
266 ): EnvironmentProject {
267 return { ...project, environmentId };
268 }
269
270 export type PendingSubagentRequest = "approval" | "user_input";
271
272 export function presentThreadShell(
273 environmentId: EnvironmentId,
274 thread: OrchestrationV2ThreadShell,
275 pendingSubagentRequest: PendingSubagentRequest | null = null,
276 ): EnvironmentThreadShell {
277 const updatedAt = iso(thread.updatedAt);
278 const latestRun =
279 thread.latestRunId === null
280 ? null
281 : ({
282 runId: thread.latestRunId,
283 status: thread.status === "idle" ? "completed" : thread.status,
284 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
285 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
286 completedAt:
287 thread.latestRunCompletedAt === undefined
288 ? thread.status === "idle" || terminalRunStatus(thread.status)
289 ? updatedAt
290 : null
291 : nullableIso(thread.latestRunCompletedAt),
292 assistantMessageId: null,
293 } satisfies ThreadRunSummary);
294 const runtime = shellRuntime(thread);
295 return {
296 environmentId,
297 id: thread.id,
298 projectId: thread.projectId,
299 title:
300 thread.lineage.relationshipToParent === "subagent"
301 ? formatSubagentDisplayTitle(thread.title)
302 : thread.title,
303 providerInstanceId: thread.providerInstanceId,
304 modelSelection: thread.modelSelection,
305 runtimeMode: thread.runtimeMode,
306 interactionMode: thread.interactionMode,
307 branch: thread.branch,
308 worktreePath: thread.worktreePath,
309 pullRequests: threadPullRequestsOf(thread),
310 linkedPullRequest: thread.linkedPullRequest ?? null,
311 branchPullRequest: thread.branchPullRequest ?? null,
312 issues: thread.issues ?? [],
313 lineage: thread.lineage,
314 forkedFrom: thread.forkedFrom,
315 linkOrigin: thread.linkOrigin ?? null,
316 delegatedFrom: thread.delegatedFrom ?? null,
317 activeProviderThreadId: thread.activeProviderThreadId,
318 latestRun,
319 runtime,
320 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
321 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
322 ...(thread.latestUserAuthoredMessageAt === undefined
323 ? {}
324 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
325 hasPendingApprovals:
326 thread.pendingRuntimeRequest !== null &&
327 thread.pendingRuntimeRequest.kind !== "user_input" &&
328 thread.pendingRuntimeRequest.kind !== "auth_refresh",
329 // Async questions count too, so a thread with any open question leaves Working.
330 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
331 pendingUserInputAt:
332 thread.pendingRuntimeRequest?.kind === "user_input"
333 ? iso(thread.pendingRuntimeRequest.createdAt)
334 : null,
335 pendingSubagentRequest,
336 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
337 hasActionableProposedPlan: thread.hasActionableProposedPlan,
338 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
339 providerInstanceHistory: thread.providerInstanceHistory ?? [],
340 goal: thread.goal ?? null,
341 itemCount: thread.itemCount,
342 visibleItemCount: thread.visibleItemCount,
343 createdAt: iso(thread.createdAt),
344 updatedAt,
345 archivedAt: nullableIso(thread.archivedAt),
346 settledOverride: thread.settledOverride,
347 settledAt: nullableIso(thread.settledAt),
348 unsettledAt: nullableIso(thread.unsettledAt ?? null),
349 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
350 snoozedAt: nullableIso(thread.snoozedAt ?? null),
351 limitRecovery: thread.limitRecovery ?? null,
352 pinnedAt: nullableIso(thread.pinnedAt ?? null),
353 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
354 pinOrderKey: thread.pinOrderKey ?? null,
355 activeOrderKey: thread.activeOrderKey ?? null,
356 ...(thread.lastVisitedAt === undefined
357 ? {}
358 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
359 opens: thread.opens ?? null,
360 titleRegeneration:
361 thread.titleRegeneration == null
362 ? null
363 : {
364 requestId: thread.titleRegeneration.requestId,
365 startedAt: iso(thread.titleRegeneration.startedAt),
366 },
367 deletedAt: nullableIso(thread.deletedAt),
368 source: thread,
369 };
370 }
371
372 export function scopeThreadShell(
373 environmentId: EnvironmentId,
374 thread: OrchestrationV2ThreadShell,
375 ): EnvironmentThreadShell {
376 return presentThreadShell(environmentId, thread);
377 }
378
379 const THREAD_PROVIDER_STACK_LIMIT = 3;
380
381 export function resolveThreadProviderStack(
382 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
383 ): ReadonlyArray<ProviderInstanceId> {
384 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
385 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
386 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
387 }
388
389 /**
390 * Both shell and detail timers count from the activity-owning run's work
391 * start, never last activity. A wake keeps the start of the work it continues.
392 */
393 export function resolveThreadWorkingStartedAt(input: {
394 readonly latestRun: Pick<
395 ThreadRunSummary,
396 "runId" | "startedAt" | "requestedAt" | "completedAt"
397 > | null;
398 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
399 }): string | null {
400 const valid = (value: string | null | undefined) =>
401 value != null && Number.isFinite(Date.parse(value)) ? value : null;
402 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
403 const run = input.latestRun;
404 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
405 return valid(run.startedAt) ?? valid(run.requestedAt);
406 }
407 return null;
408 }
409
410 export function formatWorkingDurationLabel(
411 elapsedMs: number,
412 resolve: MFunctionType = mFallback,
413 ): string {
414 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
415 if (seconds < 60) return resolve(msg("{count}s", { count: seconds }));
416 const minutes = Math.floor(seconds / 60);
417 if (minutes < 60) return resolve(msg("{count}m", { count: minutes }));
418 return resolve(
419 msg("{hours}h {minutes}m", { hours: Math.floor(minutes / 60), minutes: minutes % 60 }),
420 );
421 }