Open History to see the last commit
1import type {
2 EnvironmentId,
3 MessageId,
4 OrchestrationProjectShell,
5 OrchestrationV2RunStatus,
6 OrchestrationV2ShellSnapshot,
7 OrchestrationV2ThreadProjection,
8 OrchestrationV2ThreadShell,
9 PlanId,
10 ProjectId,
11 ProviderInstanceId,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16
17export interface EnvironmentProject extends OrchestrationProjectShell {
18 readonly environmentId: EnvironmentId;
19}
20
21/**
22 * A pristine V2 thread projection paired with the environment that produced it.
23 *
24 * The projection stays nested so the server projection and all structurally
25 * shared collections retain their identities. Rich consumers read V2 state
26 * directly instead of a second presentation-shaped thread graph.
27 */
28export interface EnvironmentThread {
29 readonly environmentId: EnvironmentId;
30 readonly projection: OrchestrationV2ThreadProjection;
31}
32
33export interface ThreadRunSummary {
34 readonly runId: RunId;
35 readonly status: OrchestrationV2RunStatus;
36 readonly requestedAt: string | null;
37 readonly startedAt: string | null;
38 readonly completedAt: string | null;
39 readonly assistantMessageId: MessageId | null;
40 readonly sourcePlanRef?: {
41 readonly threadId: ThreadId;
42 readonly planId: PlanId;
43 };
44}
45
46export interface ThreadRuntimeSummary {
47 readonly status: OrchestrationV2RunStatus | "idle";
48 readonly activeRunId: RunId | null;
49 readonly providerInstanceId: ProviderInstanceId;
50 readonly providerName: string | null;
51 readonly lastError: string | null;
52 readonly updatedAt: string;
53}
54
55export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
56 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
57}
58
59export function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
60 return (
61 status === "preparing" ||
62 status === "queued" ||
63 status === "starting" ||
64 status === "running" ||
65 status === "waiting"
66 );
67}
68
69export interface EnvironmentThreadShell {
70 readonly environmentId: EnvironmentId;
71 readonly id: ThreadId;
72 readonly projectId: ProjectId;
73 readonly title: string;
74 readonly providerInstanceId: ProviderInstanceId;
75 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
76 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
77 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
78 readonly branch: string | null;
79 readonly worktreePath: string | null;
80 readonly lineage: OrchestrationV2ThreadShell["lineage"];
81 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
82 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
83 readonly latestRun: ThreadRunSummary | null;
84 readonly runtime: ThreadRuntimeSummary | null;
85 readonly latestUserMessageAt: string | null;
86 readonly hasPendingApprovals: boolean;
87 readonly hasPendingUserInput: boolean;
88 readonly hasActionableProposedPlan: boolean;
89 readonly pendingBackgroundTasks: ReadonlyArray<
90 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
91 >;
92 readonly itemCount: number;
93 readonly visibleItemCount: number;
94 readonly createdAt: string;
95 readonly updatedAt: string;
96 readonly archivedAt: string | null;
97 readonly settledOverride: "settled" | "active" | null;
98 readonly settledAt: string | null;
99 readonly snoozedUntil: string | null;
100 readonly snoozedAt: string | null;
101 readonly pinnedAt: string | null;
102 /**
103 * Server-tracked visited watermark. `undefined` means the environment's
104 * server predates visited tracking and clients should fall back to any
105 * local visited state they keep.
106 */
107 readonly lastVisitedAt?: string | null;
108 /** Pending title regeneration marker; null when no request is in flight. */
109 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
110 readonly deletedAt: string | null;
111 readonly source: OrchestrationV2ThreadShell;
112}
113
114function iso(value: DateTime.Utc): string {
115 return DateTime.formatIso(value);
116}
117
118function nullableIso(value: DateTime.Utc | null): string | null {
119 return value === null ? null : iso(value);
120}
121
122function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
123 return (
124 status === "completed" ||
125 status === "interrupted" ||
126 status === "failed" ||
127 status === "cancelled" ||
128 status === "rolled_back"
129 );
130}
131
132// Park runtime at idle when the post-settlement background roster is nonempty
133// so #4415 waiting-presentation Waiting (session.idle) can consume CTM runtime.
134// The server suppresses the roster while an interruptible activity run exists,
135// so a remaining roster is stronger than checkpoint-oriented waiting.
136// latestRun keeps the latest run's status for history presentation.
137function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
138 if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;
139 const hasPendingBackgroundTasks = (thread.pendingBackgroundTasks?.length ?? 0) > 0;
140 const status = hasPendingBackgroundTasks ? "idle" : (thread.activityRunStatus ?? thread.status);
141 return {
142 status,
143 activeRunId: thread.activeRunId,
144 providerInstanceId: thread.providerInstanceId,
145 providerName: null,
146 lastError: thread.lastError ?? null,
147 updatedAt: iso(thread.updatedAt),
148 };
149}
150
151export function scopeProject(
152 environmentId: EnvironmentId,
153 project: OrchestrationProjectShell,
154): EnvironmentProject {
155 return { ...project, environmentId };
156}
157
158export function presentThreadShell(
159 environmentId: EnvironmentId,
160 thread: OrchestrationV2ThreadShell,
161): EnvironmentThreadShell {
162 const updatedAt = iso(thread.updatedAt);
163 const latestRun =
164 thread.latestRunId === null
165 ? null
166 : ({
167 runId: thread.latestRunId,
168 status: thread.status === "idle" ? "completed" : thread.status,
169 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
170 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
171 completedAt:
172 thread.latestRunCompletedAt === undefined
173 ? thread.status === "idle" || terminalRunStatus(thread.status)
174 ? updatedAt
175 : null
176 : nullableIso(thread.latestRunCompletedAt),
177 assistantMessageId: null,
178 } satisfies ThreadRunSummary);
179 return {
180 environmentId,
181 id: thread.id,
182 projectId: thread.projectId,
183 title: thread.title,
184 providerInstanceId: thread.providerInstanceId,
185 modelSelection: thread.modelSelection,
186 runtimeMode: thread.runtimeMode,
187 interactionMode: thread.interactionMode,
188 branch: thread.branch,
189 worktreePath: thread.worktreePath,
190 lineage: thread.lineage,
191 forkedFrom: thread.forkedFrom,
192 activeProviderThreadId: thread.activeProviderThreadId,
193 latestRun,
194 runtime: shellRuntime(thread),
195 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
196 hasPendingApprovals:
197 thread.pendingRuntimeRequest !== null &&
198 thread.pendingRuntimeRequest.kind !== "user_input" &&
199 thread.pendingRuntimeRequest.kind !== "auth_refresh",
200 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
201 hasActionableProposedPlan: thread.hasActionableProposedPlan,
202 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
203 itemCount: thread.itemCount,
204 visibleItemCount: thread.visibleItemCount,
205 createdAt: iso(thread.createdAt),
206 updatedAt,
207 archivedAt: nullableIso(thread.archivedAt),
208 settledOverride: thread.settledOverride,
209 settledAt: nullableIso(thread.settledAt),
210 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
211 snoozedAt: nullableIso(thread.snoozedAt ?? null),
212 pinnedAt: nullableIso(thread.pinnedAt ?? null),
213 ...(thread.lastVisitedAt === undefined
214 ? {}
215 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
216 titleRegeneration:
217 thread.titleRegeneration == null
218 ? null
219 : {
220 requestId: thread.titleRegeneration.requestId,
221 startedAt: iso(thread.titleRegeneration.startedAt),
222 },
223 deletedAt: nullableIso(thread.deletedAt),
224 source: thread,
225 };
226}
227
228export const scopeThreadShell = presentThreadShell;
229
230export function selectEnvironmentThreadShell(
231 snapshot: OrchestrationV2ShellSnapshot | null,
232 environmentId: EnvironmentId,
233 threadId: ThreadId,
234): EnvironmentThreadShell | null {
235 const thread = snapshot?.threads.find((candidate) => candidate.id === threadId) ?? null;
236 return thread ? presentThreadShell(environmentId, thread) : null;
237}