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