Open History to see the last commit
1import type {
2 ThreadLinkedPullRequest,
3 EnvironmentId,
4 MessageId,
5 OrchestrationProjectShell,
6 OrchestrationV2RunStatus,
7 OrchestrationV2ShellSnapshot,
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
60export function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
61 return (
62 status === "preparing" ||
63 status === "queued" ||
64 status === "starting" ||
65 status === "running" ||
66 status === "waiting"
67 );
68}
69
70export interface EnvironmentThreadShell {
71 readonly environmentId: EnvironmentId;
72 readonly id: ThreadId;
73 readonly projectId: ProjectId;
74 readonly title: string;
75 readonly providerInstanceId: ProviderInstanceId;
76 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
77 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
78 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
79 readonly branch: string | null;
80 readonly worktreePath: string | null;
81 readonly lineage: OrchestrationV2ThreadShell["lineage"];
82 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
83 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
84 readonly latestRun: ThreadRunSummary | null;
85 readonly runtime: ThreadRuntimeSummary | null;
86 readonly latestUserMessageAt: string | null;
87 readonly hasPendingApprovals: boolean;
88 readonly hasPendingUserInput: boolean;
89 readonly hasActionableProposedPlan: boolean;
90 readonly pendingBackgroundTasks: ReadonlyArray<
91 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
92 >;
93 readonly itemCount: number;
94 readonly visibleItemCount: number;
95 readonly createdAt: string;
96 readonly updatedAt: string;
97 readonly archivedAt: string | null;
98 readonly settledOverride: "settled" | "active" | null;
99 readonly settledAt: string | null;
100 readonly snoozedUntil: string | null;
101 readonly snoozedAt: string | null;
102 readonly pinnedAt: string | null;
103 /** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */
104 readonly pinOrderKey: string | null;
105 /**
106 * Pull request the user linked to the thread (#8160). The v2 server does not
107 * project this yet, so it stays undefined on v2 environments; UI treats
108 * undefined and null alike.
109 */
110 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
111 /**
112 * Server-tracked visited watermark. `undefined` means the environment's
113 * server predates visited tracking and clients should fall back to any
114 * local visited state they keep.
115 */
116 readonly lastVisitedAt?: string | null;
117 /** Pending title regeneration marker; null when no request is in flight. */
118 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
119 readonly deletedAt: string | null;
120 readonly source: OrchestrationV2ThreadShell;
121}
122
123function iso(value: DateTime.Utc): string {
124 return DateTime.formatIso(value);
125}
126
127function nullableIso(value: DateTime.Utc | null): string | null {
128 return value === null ? null : iso(value);
129}
130
131function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
132 return (
133 status === "completed" ||
134 status === "interrupted" ||
135 status === "failed" ||
136 status === "cancelled" ||
137 status === "rolled_back"
138 );
139}
140
141// Park runtime at idle when the post-settlement background roster is nonempty
142// so #4415 waiting-presentation Waiting (session.idle) can consume CTM runtime.
143// The server suppresses the roster while an interruptible activity run exists,
144// so a remaining roster is stronger than checkpoint-oriented waiting.
145// latestRun keeps the latest run's status for history presentation.
146function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
147 if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;
148 const hasPendingBackgroundTasks = (thread.pendingBackgroundTasks?.length ?? 0) > 0;
149 const status = hasPendingBackgroundTasks ? "idle" : (thread.activityRunStatus ?? thread.status);
150 return {
151 status,
152 activeRunId: thread.activeRunId,
153 providerInstanceId: thread.providerInstanceId,
154 providerName: null,
155 lastError: thread.lastError ?? null,
156 updatedAt: iso(thread.updatedAt),
157 };
158}
159
160export function scopeProject(
161 environmentId: EnvironmentId,
162 project: OrchestrationProjectShell,
163): EnvironmentProject {
164 return { ...project, environmentId };
165}
166
167export function presentThreadShell(
168 environmentId: EnvironmentId,
169 thread: OrchestrationV2ThreadShell,
170): EnvironmentThreadShell {
171 const updatedAt = iso(thread.updatedAt);
172 const latestRun =
173 thread.latestRunId === null
174 ? null
175 : ({
176 runId: thread.latestRunId,
177 status: thread.status === "idle" ? "completed" : thread.status,
178 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
179 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
180 completedAt:
181 thread.latestRunCompletedAt === undefined
182 ? thread.status === "idle" || terminalRunStatus(thread.status)
183 ? updatedAt
184 : null
185 : nullableIso(thread.latestRunCompletedAt),
186 assistantMessageId: null,
187 } satisfies ThreadRunSummary);
188 return {
189 environmentId,
190 id: thread.id,
191 projectId: thread.projectId,
192 title: thread.title,
193 providerInstanceId: thread.providerInstanceId,
194 modelSelection: thread.modelSelection,
195 runtimeMode: thread.runtimeMode,
196 interactionMode: thread.interactionMode,
197 branch: thread.branch,
198 worktreePath: thread.worktreePath,
199 linkedPullRequest: thread.linkedPullRequest ?? null,
200 lineage: thread.lineage,
201 forkedFrom: thread.forkedFrom,
202 activeProviderThreadId: thread.activeProviderThreadId,
203 latestRun,
204 runtime: shellRuntime(thread),
205 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
206 hasPendingApprovals:
207 thread.pendingRuntimeRequest !== null &&
208 thread.pendingRuntimeRequest.kind !== "user_input" &&
209 thread.pendingRuntimeRequest.kind !== "auth_refresh",
210 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
211 hasActionableProposedPlan: thread.hasActionableProposedPlan,
212 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
213 itemCount: thread.itemCount,
214 visibleItemCount: thread.visibleItemCount,
215 createdAt: iso(thread.createdAt),
216 updatedAt,
217 archivedAt: nullableIso(thread.archivedAt),
218 settledOverride: thread.settledOverride,
219 settledAt: nullableIso(thread.settledAt),
220 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
221 snoozedAt: nullableIso(thread.snoozedAt ?? null),
222 pinnedAt: nullableIso(thread.pinnedAt ?? null),
223 pinOrderKey: thread.pinOrderKey ?? null,
224 ...(thread.lastVisitedAt === undefined
225 ? {}
226 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
227 titleRegeneration:
228 thread.titleRegeneration == null
229 ? null
230 : {
231 requestId: thread.titleRegeneration.requestId,
232 startedAt: iso(thread.titleRegeneration.startedAt),
233 },
234 deletedAt: nullableIso(thread.deletedAt),
235 source: thread,
236 };
237}
238
239export const scopeThreadShell = presentThreadShell;
240
241export function selectEnvironmentThreadShell(
242 snapshot: OrchestrationV2ShellSnapshot | null,
243 environmentId: EnvironmentId,
244 threadId: ThreadId,
245): EnvironmentThreadShell | null {
246 const thread = snapshot?.threads.find((candidate) => candidate.id === threadId) ?? null;
247 return thread ? presentThreadShell(environmentId, thread) : null;
248}