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