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