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 /** Derived from the environment's configured scratch root, never persisted. */
26 readonly isScratch?: true;
27}
28
29/**
30 * A pristine V2 thread projection paired with the environment that produced it.
31 *
32 * The projection stays nested so the server projection and all structurally
33 * shared collections retain their identities. Rich consumers read V2 state
34 * directly instead of a second presentation-shaped thread graph.
35 */
36export interface EnvironmentThread {
37 readonly environmentId: EnvironmentId;
38 readonly projection: OrchestrationV2ThreadProjection;
39}
40
41export interface ThreadRunSummary {
42 readonly runId: RunId;
43 readonly status: OrchestrationV2RunStatus;
44 readonly requestedAt: string | null;
45 readonly startedAt: string | null;
46 readonly completedAt: string | null;
47 readonly assistantMessageId: MessageId | null;
48 readonly sourcePlanRef?: {
49 readonly threadId: ThreadId;
50 readonly planId: PlanId;
51 };
52}
53
54export interface ThreadRuntimeSummary {
55 readonly status: OrchestrationV2RunStatus | "idle";
56 readonly activeRunId: RunId | null;
57 readonly activityStartedAt?: string | null | undefined;
58 readonly providerInstanceId: ProviderInstanceId;
59 readonly providerName: string | null;
60 readonly lastError: string | null;
61 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
62 readonly usageLimitResetAt?: string | null;
63 readonly updatedAt: string;
64}
65
66export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
67 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
68}
69
70/** Archiving may discard queued work, but it must not detach a provider that
71 * is preparing, starting, or running a turn. */
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 latestUserMessageAt: string | null;
108 /** The last message the user wrote. `undefined` means the server predates it. */
109 readonly latestUserAuthoredMessageAt?: string | null;
110 readonly hasPendingApprovals: boolean;
111 readonly hasPendingUserInput: boolean;
112 readonly hasActionableProposedPlan: boolean;
113 readonly pendingBackgroundTasks: ReadonlyArray<
114 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
115 >;
116 /** Provider instances that have owned the root conversation, oldest first. */
117 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
118 /** Native `/goal` on the active provider thread. */
119 readonly goal: OrchestrationV2ProviderGoal | null;
120 readonly itemCount: number;
121 readonly visibleItemCount: number;
122 readonly createdAt: string;
123 readonly updatedAt: string;
124 readonly archivedAt: string | null;
125 readonly settledOverride: "settled" | "active" | null;
126 readonly settledAt: string | null;
127 readonly unsettledAt: string | null;
128 readonly snoozedUntil: string | null;
129 readonly snoozedAt: string | null;
130 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
131 readonly pinnedAt: string | null;
132 readonly autoSettleDisabledAt?: string | null;
133 /** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */
134 readonly pinOrderKey: string | null;
135 /** Slot in the user-arranged active order; null for keyless active threads. */
136 readonly activeOrderKey: string | null;
137 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
138 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
139 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
140 /**
141 * Server-tracked visited watermark. `undefined` means the environment's
142 * server predates visited tracking and clients should fall back to any
143 * local visited state they keep.
144 */
145 readonly lastVisitedAt?: string | null;
146 /** Pending title regeneration marker; null when no request is in flight. */
147 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
148 readonly deletedAt: string | null;
149 readonly source: OrchestrationV2ThreadShell;
150}
151
152function iso(value: DateTime.Utc): string {
153 return DateTime.formatIso(value);
154}
155
156function nullableIso(value: DateTime.Utc | null): string | null {
157 return value === null ? null : iso(value);
158}
159
160function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
161 return (
162 status === "completed" ||
163 status === "interrupted" ||
164 status === "failed" ||
165 status === "cancelled" ||
166 status === "rolled_back"
167 );
168}
169
170// Park runtime at idle when the post-settlement background roster holds the
171// run's completion, so #4415 waiting-presentation Waiting (session.idle) can
172// consume CTM runtime. Only work that wakes the agent holds it: commands it
173// left running, such as a dev server, present the run's own status (#14872).
174// The server suppresses the roster while an interruptible activity run exists,
175// so a remaining roster is stronger than checkpoint-oriented waiting.
176// latestRun keeps the latest run's status for history presentation.
177// A failed latest run outranks the roster, so the failure stays visible.
178function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
179 const parkAtIdle =
180 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
181 thread.status !== "failed";
182 // A pull request watch can hold a thread that never ran.
183 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
184 return null;
185 }
186 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
187 return {
188 status,
189 activeRunId: thread.activeRunId,
190 activityStartedAt:
191 thread.activityRunStartedAt === undefined
192 ? undefined
193 : nullableIso(thread.activityRunStartedAt),
194 providerInstanceId: thread.providerInstanceId,
195 providerName: null,
196 lastError: thread.lastError ?? null,
197 lastErrorClass: thread.lastErrorClass ?? null,
198 usageLimitResetAt: thread.usageLimitResetAt ?? null,
199 updatedAt: iso(thread.updatedAt),
200 };
201}
202
203export function scopeProject(
204 environmentId: EnvironmentId,
205 project: OrchestrationProjectShell,
206): EnvironmentProject {
207 return { ...project, environmentId };
208}
209
210export function presentThreadShell(
211 environmentId: EnvironmentId,
212 thread: OrchestrationV2ThreadShell,
213): EnvironmentThreadShell {
214 const updatedAt = iso(thread.updatedAt);
215 const latestRun =
216 thread.latestRunId === null
217 ? null
218 : ({
219 runId: thread.latestRunId,
220 status: thread.status === "idle" ? "completed" : thread.status,
221 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
222 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
223 completedAt:
224 thread.latestRunCompletedAt === undefined
225 ? thread.status === "idle" || terminalRunStatus(thread.status)
226 ? updatedAt
227 : null
228 : nullableIso(thread.latestRunCompletedAt),
229 assistantMessageId: null,
230 } satisfies ThreadRunSummary);
231 return {
232 environmentId,
233 id: thread.id,
234 projectId: thread.projectId,
235 title:
236 thread.lineage.relationshipToParent === "subagent"
237 ? formatSubagentDisplayTitle(thread.title)
238 : thread.title,
239 providerInstanceId: thread.providerInstanceId,
240 modelSelection: thread.modelSelection,
241 runtimeMode: thread.runtimeMode,
242 interactionMode: thread.interactionMode,
243 branch: thread.branch,
244 worktreePath: thread.worktreePath,
245 pullRequests: threadPullRequestsOf(thread),
246 linkedPullRequest: thread.linkedPullRequest ?? null,
247 branchPullRequest: thread.branchPullRequest ?? null,
248 lineage: thread.lineage,
249 forkedFrom: thread.forkedFrom,
250 activeProviderThreadId: thread.activeProviderThreadId,
251 latestRun,
252 runtime: shellRuntime(thread),
253 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
254 ...(thread.latestUserAuthoredMessageAt === undefined
255 ? {}
256 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
257 hasPendingApprovals:
258 thread.pendingRuntimeRequest !== null &&
259 thread.pendingRuntimeRequest.kind !== "user_input" &&
260 thread.pendingRuntimeRequest.kind !== "auth_refresh",
261 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
262 hasActionableProposedPlan: thread.hasActionableProposedPlan,
263 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
264 providerInstanceHistory: thread.providerInstanceHistory ?? [],
265 goal: thread.goal ?? null,
266 itemCount: thread.itemCount,
267 visibleItemCount: thread.visibleItemCount,
268 createdAt: iso(thread.createdAt),
269 updatedAt,
270 archivedAt: nullableIso(thread.archivedAt),
271 settledOverride: thread.settledOverride,
272 settledAt: nullableIso(thread.settledAt),
273 unsettledAt: nullableIso(thread.unsettledAt ?? null),
274 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
275 snoozedAt: nullableIso(thread.snoozedAt ?? null),
276 limitRecovery: thread.limitRecovery ?? null,
277 pinnedAt: nullableIso(thread.pinnedAt ?? null),
278 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
279 pinOrderKey: thread.pinOrderKey ?? null,
280 activeOrderKey: thread.activeOrderKey ?? null,
281 ...(thread.lastVisitedAt === undefined
282 ? {}
283 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
284 titleRegeneration:
285 thread.titleRegeneration == null
286 ? null
287 : {
288 requestId: thread.titleRegeneration.requestId,
289 startedAt: iso(thread.titleRegeneration.startedAt),
290 },
291 deletedAt: nullableIso(thread.deletedAt),
292 source: thread,
293 };
294}
295
296export function scopeThreadShell(
297 environmentId: EnvironmentId,
298 thread: OrchestrationV2ThreadShell,
299): EnvironmentThreadShell {
300 return presentThreadShell(environmentId, thread);
301}
302
303const THREAD_PROVIDER_STACK_LIMIT = 3;
304
305/**
306 * Provider instances to draw in a thread row's trailing stack, back to front:
307 * the current one is always last, earlier owners precede it oldest first.
308 * Newest history wins when the thread has been handed off more times than fit.
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 // Older servers can supply a timestamp only if the newest run owns the work.
333 const run = input.latestRun;
334 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
335 return valid(run.startedAt) ?? valid(run.requestedAt);
336 }
337 return null;
338}