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