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