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