Open History to see the last commit
1import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
3import 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";
19import * as DateTime from "effect/DateTime";
20
21import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
22
23export interface EnvironmentProject extends OrchestrationProjectShell {
24 readonly environmentId: EnvironmentId;
25 readonly isScratch?: true;
26}
27
28/**
29 * The projection stays nested so the server projection and all structurally
30 * shared collections retain their identities.
31 */
32export interface EnvironmentThread {
33 readonly environmentId: EnvironmentId;
34 readonly projection: OrchestrationV2ThreadProjection;
35}
36
37export interface ThreadRunSummary {
38 readonly runId: RunId;
39 readonly status: OrchestrationV2RunStatus;
40 readonly requestedAt: string | null;
41 readonly startedAt: string | null;
42 readonly completedAt: string | null;
43 readonly assistantMessageId: MessageId | null;
44 /**
45 * The run is still open, but its provider turn already ended, so nothing is
46 * generating while the server settles it.
47 */
48 readonly turnEnded?: boolean;
49 readonly sourcePlanRef?: {
50 readonly threadId: ThreadId;
51 readonly planId: PlanId;
52 };
53}
54
55export interface ThreadRuntimeSummary {
56 readonly status: OrchestrationV2RunStatus | "idle";
57 readonly activeRunId: RunId | null;
58 readonly activityStartedAt?: string | null | undefined;
59 readonly providerInstanceId: ProviderInstanceId;
60 readonly providerName: string | null;
61 readonly lastError: string | null;
62 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
63 readonly lastErrorCode?: string | null;
64 readonly usageLimitResetAt?: string | null;
65 readonly updatedAt: string;
66}
67
68export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
69 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
70}
71
72export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
73 if (runtime?.status === "queued") return runtime.activeRunId === null;
74 return (
75 runtime?.status !== "preparing" &&
76 runtime?.status !== "starting" &&
77 runtime?.status !== "running"
78 );
79}
80
81function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
82 return (
83 status === "preparing" ||
84 status === "queued" ||
85 status === "starting" ||
86 status === "running" ||
87 status === "waiting"
88 );
89}
90
91export interface EnvironmentThreadShell {
92 readonly environmentId: EnvironmentId;
93 readonly id: ThreadId;
94 readonly projectId: ProjectId;
95 readonly title: string;
96 readonly providerInstanceId: ProviderInstanceId;
97 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
98 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
99 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
100 readonly branch: string | null;
101 readonly worktreePath: string | null;
102 readonly lineage: OrchestrationV2ThreadShell["lineage"];
103 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
104 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
105 readonly latestRun: ThreadRunSummary | null;
106 readonly runtime: ThreadRuntimeSummary | null;
107 readonly blockedOnThreadWait?: boolean;
108 readonly latestUserMessageAt: string | null;
109 readonly latestUserAuthoredMessageAt?: string | null;
110 readonly hasPendingApprovals: boolean;
111 readonly hasPendingUserInput: boolean;
112 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
113 readonly hasActionableProposedPlan: boolean;
114 readonly pendingBackgroundTasks: ReadonlyArray<
115 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
116 >;
117 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
118 readonly goal: OrchestrationV2ProviderGoal | null;
119 readonly itemCount: number;
120 readonly visibleItemCount: number;
121 readonly createdAt: string;
122 readonly updatedAt: string;
123 readonly archivedAt: string | null;
124 readonly settledOverride: "settled" | "active" | null;
125 readonly settledAt: string | null;
126 readonly unsettledAt: string | null;
127 readonly snoozedUntil: string | null;
128 readonly snoozedAt: string | null;
129 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
130 readonly pinnedAt: string | null;
131 readonly autoSettleDisabledAt?: string | null;
132 readonly pinOrderKey: string | null;
133 readonly activeOrderKey: string | null;
134 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
135 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
136 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
137 /**
138 * Server-tracked visited watermark. `undefined` means the environment's
139 * server predates visited tracking and clients should fall back to any
140 * local visited state they keep.
141 */
142 readonly lastVisitedAt?: string | null;
143 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
144 readonly deletedAt: string | null;
145 readonly source: OrchestrationV2ThreadShell;
146}
147
148function iso(value: DateTime.Utc): string {
149 return DateTime.formatIso(value);
150}
151
152function nullableIso(value: DateTime.Utc | null): string | null {
153 return value === null ? null : iso(value);
154}
155
156function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
157 return (
158 status === "completed" ||
159 status === "interrupted" ||
160 status === "failed" ||
161 status === "cancelled" ||
162 status === "rolled_back"
163 );
164}
165
166// Only work that wakes the agent holds it: commands it left running, such as a
167// dev server, present the run's own status (#14872). The server suppresses the
168// roster while an interruptible activity run exists, so a remaining roster is
169// stronger than checkpoint-oriented waiting.
170function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
171 const parkAtIdle =
172 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
173 thread.status !== "failed";
174 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
175 return null;
176 }
177 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
178 return {
179 status,
180 activeRunId: thread.activeRunId,
181 activityStartedAt:
182 thread.activityRunStartedAt === undefined
183 ? undefined
184 : nullableIso(thread.activityRunStartedAt),
185 providerInstanceId: thread.providerInstanceId,
186 providerName: null,
187 lastError: thread.lastError ?? null,
188 lastErrorClass: thread.lastErrorClass ?? null,
189 lastErrorCode: thread.lastErrorCode ?? null,
190 usageLimitResetAt: thread.usageLimitResetAt ?? null,
191 updatedAt: iso(thread.updatedAt),
192 };
193}
194
195export function scopeProject(
196 environmentId: EnvironmentId,
197 project: OrchestrationProjectShell,
198): EnvironmentProject {
199 return { ...project, environmentId };
200}
201
202export type PendingSubagentRequest = "approval" | "user_input";
203
204export function presentThreadShell(
205 environmentId: EnvironmentId,
206 thread: OrchestrationV2ThreadShell,
207 pendingSubagentRequest: PendingSubagentRequest | null = null,
208): EnvironmentThreadShell {
209 const updatedAt = iso(thread.updatedAt);
210 const latestRun =
211 thread.latestRunId === null
212 ? null
213 : ({
214 runId: thread.latestRunId,
215 status: thread.status === "idle" ? "completed" : thread.status,
216 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
217 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
218 completedAt:
219 thread.latestRunCompletedAt === undefined
220 ? thread.status === "idle" || terminalRunStatus(thread.status)
221 ? updatedAt
222 : null
223 : nullableIso(thread.latestRunCompletedAt),
224 assistantMessageId: null,
225 } satisfies ThreadRunSummary);
226 const runtime = shellRuntime(thread);
227 // Waiting runs have ended their provider turn and are only draining effects.
228 const runtimeIsWorking =
229 runtime?.status === "preparing" ||
230 runtime?.status === "starting" ||
231 runtime?.status === "running";
232 return {
233 environmentId,
234 id: thread.id,
235 projectId: thread.projectId,
236 title:
237 thread.lineage.relationshipToParent === "subagent"
238 ? formatSubagentDisplayTitle(thread.title)
239 : thread.title,
240 providerInstanceId: thread.providerInstanceId,
241 modelSelection: thread.modelSelection,
242 runtimeMode: thread.runtimeMode,
243 interactionMode: thread.interactionMode,
244 branch: thread.branch,
245 worktreePath: thread.worktreePath,
246 pullRequests: threadPullRequestsOf(thread),
247 linkedPullRequest: thread.linkedPullRequest ?? null,
248 branchPullRequest: thread.branchPullRequest ?? null,
249 lineage: thread.lineage,
250 forkedFrom: thread.forkedFrom,
251 activeProviderThreadId: thread.activeProviderThreadId,
252 latestRun,
253 runtime,
254 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
255 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
256 ...(thread.latestUserAuthoredMessageAt === undefined
257 ? {}
258 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
259 hasPendingApprovals:
260 thread.pendingRuntimeRequest !== null &&
261 thread.pendingRuntimeRequest.kind !== "user_input" &&
262 thread.pendingRuntimeRequest.kind !== "auth_refresh",
263 hasPendingUserInput:
264 thread.pendingRuntimeRequest?.kind === "user_input" &&
265 (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
266 pendingSubagentRequest,
267 hasActionableProposedPlan: thread.hasActionableProposedPlan,
268 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
269 providerInstanceHistory: thread.providerInstanceHistory ?? [],
270 goal: thread.goal ?? null,
271 itemCount: thread.itemCount,
272 visibleItemCount: thread.visibleItemCount,
273 createdAt: iso(thread.createdAt),
274 updatedAt,
275 archivedAt: nullableIso(thread.archivedAt),
276 settledOverride: thread.settledOverride,
277 settledAt: nullableIso(thread.settledAt),
278 unsettledAt: nullableIso(thread.unsettledAt ?? null),
279 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
280 snoozedAt: nullableIso(thread.snoozedAt ?? null),
281 limitRecovery: thread.limitRecovery ?? null,
282 pinnedAt: nullableIso(thread.pinnedAt ?? null),
283 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
284 pinOrderKey: thread.pinOrderKey ?? null,
285 activeOrderKey: thread.activeOrderKey ?? null,
286 ...(thread.lastVisitedAt === undefined
287 ? {}
288 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
289 titleRegeneration:
290 thread.titleRegeneration == null
291 ? null
292 : {
293 requestId: thread.titleRegeneration.requestId,
294 startedAt: iso(thread.titleRegeneration.startedAt),
295 },
296 deletedAt: nullableIso(thread.deletedAt),
297 source: thread,
298 };
299}
300
301export function scopeThreadShell(
302 environmentId: EnvironmentId,
303 thread: OrchestrationV2ThreadShell,
304): EnvironmentThreadShell {
305 return presentThreadShell(environmentId, thread);
306}
307
308const THREAD_PROVIDER_STACK_LIMIT = 3;
309
310export function resolveThreadProviderStack(
311 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
312): ReadonlyArray<ProviderInstanceId> {
313 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
314 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
315 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
316}
317
318/**
319 * Both shell and detail timers count from the activity-owning run's work
320 * start, never last activity. A wake keeps the start of the work it continues.
321 */
322export function resolveThreadWorkingStartedAt(input: {
323 readonly latestRun: Pick<
324 ThreadRunSummary,
325 "runId" | "startedAt" | "requestedAt" | "completedAt"
326 > | null;
327 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
328}): string | null {
329 const valid = (value: string | null | undefined) =>
330 value != null && Number.isFinite(Date.parse(value)) ? value : null;
331 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
332 const run = input.latestRun;
333 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
334 return valid(run.startedAt) ?? valid(run.requestedAt);
335 }
336 return null;
337}
338
339export function formatWorkingDurationLabel(elapsedMs: number): string {
340 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
341 if (seconds < 60) return `${seconds}s`;
342 const minutes = Math.floor(seconds / 60);
343 if (minutes < 60) return `${minutes}m`;
344 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
345}