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