Open History to see the last commit
1import { threadPullRequestsOf } from "@t3tools/shared/threadPullRequests";
2import type {
3 ThreadLinkedPullRequest,
4 EnvironmentId,
5 MessageId,
6 OrchestrationProjectShell,
7 OrchestrationV2RunStatus,
8 OrchestrationV2ProviderFailureClass,
9 OrchestrationV2ThreadProjection,
10 OrchestrationV2ThreadShell,
11 PlanId,
12 ProjectId,
13 ProviderInstanceId,
14 RunId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18
19import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
20
21export interface EnvironmentProject extends OrchestrationProjectShell {
22 readonly environmentId: EnvironmentId;
23}
24
25/**
26 * A pristine V2 thread projection paired with the environment that produced it.
27 *
28 * The projection stays nested so the server projection and all structurally
29 * shared collections retain their identities. Rich consumers read V2 state
30 * directly instead of a second presentation-shaped thread graph.
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
66/** Archiving may discard queued work, but it must not detach a provider that
67 * is preparing, starting, or running a turn. */
68export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
69 if (runtime?.status === "queued") return runtime.activeRunId === null;
70 return (
71 runtime?.status !== "preparing" &&
72 runtime?.status !== "starting" &&
73 runtime?.status !== "running"
74 );
75}
76
77function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
78 return (
79 status === "preparing" ||
80 status === "queued" ||
81 status === "starting" ||
82 status === "running" ||
83 status === "waiting"
84 );
85}
86
87export interface EnvironmentThreadShell {
88 readonly environmentId: EnvironmentId;
89 readonly id: ThreadId;
90 readonly projectId: ProjectId;
91 readonly title: string;
92 readonly providerInstanceId: ProviderInstanceId;
93 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
94 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
95 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
96 readonly branch: string | null;
97 readonly worktreePath: string | null;
98 readonly lineage: OrchestrationV2ThreadShell["lineage"];
99 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
100 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
101 readonly latestRun: ThreadRunSummary | null;
102 readonly runtime: ThreadRuntimeSummary | null;
103 readonly latestUserMessageAt: string | null;
104 readonly hasPendingApprovals: boolean;
105 readonly hasPendingUserInput: boolean;
106 readonly hasActionableProposedPlan: boolean;
107 readonly pendingBackgroundTasks: ReadonlyArray<
108 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
109 >;
110 /** Provider instances that have owned the root conversation, oldest first. */
111 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
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 /** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */
126 readonly pinOrderKey: string | null;
127 /** Slot in the user-arranged active order; null for keyless active threads. */
128 readonly activeOrderKey: string | null;
129 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
130 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
131 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
132 /**
133 * Server-tracked visited watermark. `undefined` means the environment's
134 * server predates visited tracking and clients should fall back to any
135 * local visited state they keep.
136 */
137 readonly lastVisitedAt?: string | null;
138 /** Pending title regeneration marker; null when no request is in flight. */
139 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
140 readonly deletedAt: string | null;
141 readonly source: OrchestrationV2ThreadShell;
142}
143
144function iso(value: DateTime.Utc): string {
145 return DateTime.formatIso(value);
146}
147
148function nullableIso(value: DateTime.Utc | null): string | null {
149 return value === null ? null : iso(value);
150}
151
152function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
153 return (
154 status === "completed" ||
155 status === "interrupted" ||
156 status === "failed" ||
157 status === "cancelled" ||
158 status === "rolled_back"
159 );
160}
161
162// Park runtime at idle when the post-settlement background roster is nonempty
163// so #4415 waiting-presentation Waiting (session.idle) can consume CTM runtime.
164// The server suppresses the roster while an interruptible activity run exists,
165// so a remaining roster is stronger than checkpoint-oriented waiting.
166// latestRun keeps the latest run's status for history presentation.
167function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
168 if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;
169 const hasPendingBackgroundTasks = (thread.pendingBackgroundTasks?.length ?? 0) > 0;
170 const status = hasPendingBackgroundTasks ? "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 function presentThreadShell(
195 environmentId: EnvironmentId,
196 thread: OrchestrationV2ThreadShell,
197): EnvironmentThreadShell {
198 const updatedAt = iso(thread.updatedAt);
199 const latestRun =
200 thread.latestRunId === null
201 ? null
202 : ({
203 runId: thread.latestRunId,
204 status: thread.status === "idle" ? "completed" : thread.status,
205 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
206 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
207 completedAt:
208 thread.latestRunCompletedAt === undefined
209 ? thread.status === "idle" || terminalRunStatus(thread.status)
210 ? updatedAt
211 : null
212 : nullableIso(thread.latestRunCompletedAt),
213 assistantMessageId: null,
214 } satisfies ThreadRunSummary);
215 return {
216 environmentId,
217 id: thread.id,
218 projectId: thread.projectId,
219 title:
220 thread.lineage.relationshipToParent === "subagent"
221 ? formatSubagentDisplayTitle(thread.title)
222 : thread.title,
223 providerInstanceId: thread.providerInstanceId,
224 modelSelection: thread.modelSelection,
225 runtimeMode: thread.runtimeMode,
226 interactionMode: thread.interactionMode,
227 branch: thread.branch,
228 worktreePath: thread.worktreePath,
229 pullRequests: threadPullRequestsOf(thread),
230 linkedPullRequest: thread.linkedPullRequest ?? null,
231 branchPullRequest: thread.branchPullRequest ?? null,
232 lineage: thread.lineage,
233 forkedFrom: thread.forkedFrom,
234 activeProviderThreadId: thread.activeProviderThreadId,
235 latestRun,
236 runtime: shellRuntime(thread),
237 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
238 hasPendingApprovals:
239 thread.pendingRuntimeRequest !== null &&
240 thread.pendingRuntimeRequest.kind !== "user_input" &&
241 thread.pendingRuntimeRequest.kind !== "auth_refresh",
242 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
243 hasActionableProposedPlan: thread.hasActionableProposedPlan,
244 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
245 providerInstanceHistory: thread.providerInstanceHistory ?? [],
246 itemCount: thread.itemCount,
247 visibleItemCount: thread.visibleItemCount,
248 createdAt: iso(thread.createdAt),
249 updatedAt,
250 archivedAt: nullableIso(thread.archivedAt),
251 settledOverride: thread.settledOverride,
252 settledAt: nullableIso(thread.settledAt),
253 unsettledAt: nullableIso(thread.unsettledAt ?? null),
254 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
255 snoozedAt: nullableIso(thread.snoozedAt ?? null),
256 limitRecovery: thread.limitRecovery ?? null,
257 pinnedAt: nullableIso(thread.pinnedAt ?? null),
258 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
259 pinOrderKey: thread.pinOrderKey ?? null,
260 activeOrderKey: thread.activeOrderKey ?? null,
261 ...(thread.lastVisitedAt === undefined
262 ? {}
263 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
264 titleRegeneration:
265 thread.titleRegeneration == null
266 ? null
267 : {
268 requestId: thread.titleRegeneration.requestId,
269 startedAt: iso(thread.titleRegeneration.startedAt),
270 },
271 deletedAt: nullableIso(thread.deletedAt),
272 source: thread,
273 };
274}
275
276export function scopeThreadShell(
277 environmentId: EnvironmentId,
278 thread: OrchestrationV2ThreadShell,
279): EnvironmentThreadShell {
280 return presentThreadShell(environmentId, thread);
281}
282
283const THREAD_PROVIDER_STACK_LIMIT = 3;
284
285/**
286 * Provider instances to draw in a thread row's trailing stack, back to front:
287 * the current one is always last, earlier owners precede it oldest first.
288 * Newest history wins when the thread has been handed off more times than fit.
289 */
290export function resolveThreadProviderStack(
291 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
292): ReadonlyArray<ProviderInstanceId> {
293 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
294 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
295 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
296}
297
298/** Both shell and detail timers use the activity-owning run, never last activity. */
299export function resolveThreadWorkingStartedAt(input: {
300 readonly latestRun: Pick<
301 ThreadRunSummary,
302 "runId" | "startedAt" | "requestedAt" | "completedAt"
303 > | null;
304 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
305}): string | null {
306 const valid = (value: string | null | undefined) =>
307 value != null && Number.isFinite(Date.parse(value)) ? value : null;
308 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
309 // Older servers can supply a timestamp only if the newest run owns the work.
310 const run = input.latestRun;
311 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
312 return valid(run.startedAt) ?? valid(run.requestedAt);
313 }
314 return null;
315}