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