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
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 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
190 readonly deletedAt: string | null;
191 readonly source: OrchestrationV2ThreadShell;
192}
193
194function iso(value: DateTime.Utc): string {
195 return DateTime.formatIso(value);
196}
197
198function nullableIso(value: DateTime.Utc | null): string | null {
199 return value === null ? null : iso(value);
200}
201
202function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
203 return (
204 status === "completed" ||
205 status === "interrupted" ||
206 status === "failed" ||
207 status === "cancelled" ||
208 status === "rolled_back"
209 );
210}
211
212// Only work that wakes the agent holds it: commands it left running, such as a
213// dev server, present the run's own status (#14872). The server suppresses the
214// roster while an interruptible activity run exists, so a remaining roster is
215// stronger than checkpoint-oriented waiting.
216function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
217 const parkAtIdle =
218 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
219 thread.status !== "failed";
220 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
221 return null;
222 }
223 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
224 return {
225 status,
226 activeRunId: thread.activeRunId,
227 activityStartedAt:
228 thread.activityRunStartedAt === undefined
229 ? undefined
230 : nullableIso(thread.activityRunStartedAt),
231 providerInstanceId: thread.providerInstanceId,
232 providerName: null,
233 lastError: thread.lastError ?? null,
234 lastErrorClass: thread.lastErrorClass ?? null,
235 lastErrorCode: thread.lastErrorCode ?? null,
236 usageLimitResetAt: thread.usageLimitResetAt ?? null,
237 updatedAt: iso(thread.updatedAt),
238 };
239}
240
241export function scopeProject(
242 environmentId: EnvironmentId,
243 project: OrchestrationProjectShell,
244): EnvironmentProject {
245 return { ...project, environmentId };
246}
247
248export type PendingSubagentRequest = "approval" | "user_input";
249
250export function presentThreadShell(
251 environmentId: EnvironmentId,
252 thread: OrchestrationV2ThreadShell,
253 pendingSubagentRequest: PendingSubagentRequest | null = null,
254): EnvironmentThreadShell {
255 const updatedAt = iso(thread.updatedAt);
256 const latestRun =
257 thread.latestRunId === null
258 ? null
259 : ({
260 runId: thread.latestRunId,
261 status: thread.status === "idle" ? "completed" : thread.status,
262 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
263 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
264 completedAt:
265 thread.latestRunCompletedAt === undefined
266 ? thread.status === "idle" || terminalRunStatus(thread.status)
267 ? updatedAt
268 : null
269 : nullableIso(thread.latestRunCompletedAt),
270 assistantMessageId: null,
271 } satisfies ThreadRunSummary);
272 const runtime = shellRuntime(thread);
273 // Waiting runs have ended their provider turn and are only draining effects.
274 const runtimeIsWorking =
275 runtime?.status === "preparing" ||
276 runtime?.status === "starting" ||
277 runtime?.status === "running";
278 return {
279 environmentId,
280 id: thread.id,
281 projectId: thread.projectId,
282 title:
283 thread.lineage.relationshipToParent === "subagent"
284 ? formatSubagentDisplayTitle(thread.title)
285 : thread.title,
286 providerInstanceId: thread.providerInstanceId,
287 modelSelection: thread.modelSelection,
288 runtimeMode: thread.runtimeMode,
289 interactionMode: thread.interactionMode,
290 branch: thread.branch,
291 worktreePath: thread.worktreePath,
292 pullRequests: threadPullRequestsOf(thread),
293 linkedPullRequest: thread.linkedPullRequest ?? null,
294 branchPullRequest: thread.branchPullRequest ?? null,
295 lineage: thread.lineage,
296 forkedFrom: thread.forkedFrom,
297 activeProviderThreadId: thread.activeProviderThreadId,
298 latestRun,
299 runtime,
300 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
301 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
302 ...(thread.latestUserAuthoredMessageAt === undefined
303 ? {}
304 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
305 hasPendingApprovals:
306 thread.pendingRuntimeRequest !== null &&
307 thread.pendingRuntimeRequest.kind !== "user_input" &&
308 thread.pendingRuntimeRequest.kind !== "auth_refresh",
309 hasPendingUserInput:
310 thread.pendingRuntimeRequest?.kind === "user_input" &&
311 (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
312 pendingSubagentRequest,
313 hasActionableProposedPlan: thread.hasActionableProposedPlan,
314 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
315 providerInstanceHistory: thread.providerInstanceHistory ?? [],
316 goal: thread.goal ?? null,
317 itemCount: thread.itemCount,
318 visibleItemCount: thread.visibleItemCount,
319 createdAt: iso(thread.createdAt),
320 updatedAt,
321 archivedAt: nullableIso(thread.archivedAt),
322 settledOverride: thread.settledOverride,
323 settledAt: nullableIso(thread.settledAt),
324 unsettledAt: nullableIso(thread.unsettledAt ?? null),
325 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
326 snoozedAt: nullableIso(thread.snoozedAt ?? null),
327 limitRecovery: thread.limitRecovery ?? null,
328 pinnedAt: nullableIso(thread.pinnedAt ?? null),
329 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
330 pinOrderKey: thread.pinOrderKey ?? null,
331 activeOrderKey: thread.activeOrderKey ?? null,
332 ...(thread.lastVisitedAt === undefined
333 ? {}
334 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
335 titleRegeneration:
336 thread.titleRegeneration == null
337 ? null
338 : {
339 requestId: thread.titleRegeneration.requestId,
340 startedAt: iso(thread.titleRegeneration.startedAt),
341 },
342 deletedAt: nullableIso(thread.deletedAt),
343 source: thread,
344 };
345}
346
347export function scopeThreadShell(
348 environmentId: EnvironmentId,
349 thread: OrchestrationV2ThreadShell,
350): EnvironmentThreadShell {
351 return presentThreadShell(environmentId, thread);
352}
353
354const THREAD_PROVIDER_STACK_LIMIT = 3;
355
356export function resolveThreadProviderStack(
357 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
358): ReadonlyArray<ProviderInstanceId> {
359 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
360 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
361 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
362}
363
364/**
365 * Both shell and detail timers count from the activity-owning run's work
366 * start, never last activity. A wake keeps the start of the work it continues.
367 */
368export function resolveThreadWorkingStartedAt(input: {
369 readonly latestRun: Pick<
370 ThreadRunSummary,
371 "runId" | "startedAt" | "requestedAt" | "completedAt"
372 > | null;
373 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
374}): string | null {
375 const valid = (value: string | null | undefined) =>
376 value != null && Number.isFinite(Date.parse(value)) ? value : null;
377 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
378 const run = input.latestRun;
379 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
380 return valid(run.startedAt) ?? valid(run.requestedAt);
381 }
382 return null;
383}
384
385export function formatWorkingDurationLabel(elapsedMs: number): string {
386 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
387 if (seconds < 60) return `${seconds}s`;
388 const minutes = Math.floor(seconds / 60);
389 if (minutes < 60) return `${minutes}m`;
390 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
391}