Open History to see the last commit
1import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2import { threadPullRequestsOf } from "../threadPullRequests.ts";
3import type {
4 ThreadLinkedPullRequest,
5 EnvironmentId,
6 MessageId,
7 OrchestrationProjectShell,
8 OrchestrationV2ProviderGoal,
9 OrchestrationV2RunStatus,
10 OrchestrationV2ProviderFailureClass,
11 OrchestrationV2ThreadProjection,
12 OrchestrationV2ThreadShell,
13 PlanId,
14 ProjectId,
15 ProviderInstanceId,
16 RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20
21import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";
22
23export interface EnvironmentProject extends OrchestrationProjectShell {
24 readonly environmentId: EnvironmentId;
25 readonly isScratch?: true;
26}
27
28/**
29 * The projection stays nested so the server projection and all structurally
30 * shared collections retain their identities.
31 */
32export interface EnvironmentThread {
33 readonly environmentId: EnvironmentId;
34 readonly projection: OrchestrationV2ThreadProjection;
35}
36
37type ProjectionTurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
38type StreamedProjectionTurnItem = Extract<
39 ProjectionTurnItem,
40 { readonly type: "assistant_message" | "reasoning" }
41>;
42
43/** A turn item without the fields that move while it streams. */
44export type ThreadStructureTurnItem =
45 | Exclude<ProjectionTurnItem, StreamedProjectionTurnItem>
46 | Omit<Extract<ProjectionTurnItem, { readonly type: "assistant_message" }>, "text" | "updatedAt">
47 | Omit<Extract<ProjectionTurnItem, { readonly type: "reasoning" }>, "text" | "updatedAt">;
48
49export type ThreadStructureVisibleTurnItem = Omit<
50 OrchestrationV2ThreadProjection["visibleTurnItems"][number],
51 "item"
52> & {
53 readonly item: ThreadStructureTurnItem;
54};
55
56/**
57 * A thread projection without the fields that move while a reply streams, so a
58 * reader of the quiet thread cannot depend on them and go stale. A full
59 * projection is assignable to it.
60 */
61export type ThreadStructureThread = Omit<
62 OrchestrationV2ThreadProjection["thread"],
63 "updatedAt" | "lastVisitedAt"
64>;
65
66export type ThreadStructure = Omit<
67 OrchestrationV2ThreadProjection,
68 "thread" | "turnItems" | "visibleTurnItems" | "updatedAt"
69> & {
70 readonly thread: ThreadStructureThread;
71 readonly turnItems: ReadonlyArray<ThreadStructureTurnItem>;
72 readonly visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>;
73};
74
75export interface EnvironmentThreadStructure {
76 readonly environmentId: EnvironmentId;
77 readonly projection: ThreadStructure;
78}
79
80export interface ThreadRunSummary {
81 readonly runId: RunId;
82 readonly status: OrchestrationV2RunStatus;
83 readonly requestedAt: string | null;
84 readonly startedAt: string | null;
85 readonly completedAt: string | null;
86 readonly assistantMessageId: MessageId | null;
87 /**
88 * The run is still open, but its provider turn already ended, so nothing is
89 * generating while the server settles it.
90 */
91 readonly turnEnded?: boolean;
92 readonly sourcePlanRef?: {
93 readonly threadId: ThreadId;
94 readonly planId: PlanId;
95 };
96}
97
98export interface ThreadRuntimeSummary {
99 readonly status: OrchestrationV2RunStatus | "idle";
100 readonly activeRunId: RunId | null;
101 readonly activityStartedAt?: string | null | undefined;
102 readonly providerInstanceId: ProviderInstanceId;
103 readonly providerName: string | null;
104 readonly lastError: string | null;
105 readonly lastErrorClass?: OrchestrationV2ProviderFailureClass | null;
106 readonly lastErrorCode?: string | null;
107 readonly usageLimitResetAt?: string | null;
108 readonly updatedAt: string;
109}
110
111/** The runtime summary a thread's structure determines; see ThreadStructure. */
112export type ThreadStructureRuntime = Omit<ThreadRuntimeSummary, "updatedAt">;
113
114export function threadRuntimeIsActive(runtime: ThreadStructureRuntime | null | undefined): boolean {
115 return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status);
116}
117
118export function threadRuntimeCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
119 if (runtime?.status === "queued") return runtime.activeRunId === null;
120 return (
121 runtime?.status !== "preparing" &&
122 runtime?.status !== "starting" &&
123 runtime?.status !== "running"
124 );
125}
126
127function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean {
128 return (
129 status === "preparing" ||
130 status === "queued" ||
131 status === "starting" ||
132 status === "running" ||
133 status === "waiting"
134 );
135}
136
137export interface EnvironmentThreadShell {
138 readonly environmentId: EnvironmentId;
139 readonly id: ThreadId;
140 readonly projectId: ProjectId;
141 readonly title: string;
142 readonly providerInstanceId: ProviderInstanceId;
143 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
144 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
145 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
146 readonly branch: string | null;
147 readonly worktreePath: string | null;
148 readonly lineage: OrchestrationV2ThreadShell["lineage"];
149 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
150 readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null;
151 /** The thread in a linked environment that delegated this one, if one did. */
152 readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null;
153 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
154 readonly latestRun: ThreadRunSummary | null;
155 readonly runtime: ThreadRuntimeSummary | null;
156 readonly blockedOnThreadWait?: boolean;
157 readonly latestUserMessageAt: string | null;
158 readonly latestUserAuthoredMessageAt?: string | null;
159 readonly hasPendingApprovals: boolean;
160 readonly hasPendingUserInput: boolean;
161 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
162 /** Guest messages waiting for the owner to send or dismiss. */
163 readonly pendingGuestMessageCount?: number;
164 readonly hasActionableProposedPlan: boolean;
165 readonly pendingBackgroundTasks: ReadonlyArray<
166 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
167 >;
168 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
169 readonly goal: OrchestrationV2ProviderGoal | null;
170 readonly itemCount: number;
171 readonly visibleItemCount: number;
172 readonly createdAt: string;
173 readonly updatedAt: string;
174 readonly archivedAt: string | null;
175 readonly settledOverride: "settled" | "active" | null;
176 readonly settledAt: string | null;
177 readonly unsettledAt: string | null;
178 readonly snoozedUntil: string | null;
179 readonly snoozedAt: string | null;
180 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
181 readonly pinnedAt: string | null;
182 readonly autoSettleDisabledAt?: string | null;
183 readonly pinOrderKey: string | null;
184 readonly activeOrderKey: string | null;
185 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
186 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
187 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
188 /**
189 * Server-tracked visited watermark. `undefined` means the environment's
190 * server predates visited tracking and clients should fall back to any
191 * local visited state they keep.
192 */
193 readonly lastVisitedAt?: string | null;
194 /** Server-tracked open history for search ranking. */
195 readonly opens?: import("@t3tools/contracts").OrchestrationV2ThreadOpens | null;
196 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
197 readonly deletedAt: string | null;
198 readonly source: OrchestrationV2ThreadShell;
199}
200
201function iso(value: DateTime.Utc): string {
202 return DateTime.formatIso(value);
203}
204
205function nullableIso(value: DateTime.Utc | null): string | null {
206 return value === null ? null : iso(value);
207}
208
209function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
210 return (
211 status === "completed" ||
212 status === "interrupted" ||
213 status === "failed" ||
214 status === "cancelled" ||
215 status === "rolled_back"
216 );
217}
218
219// Only work the agent waits on holds it: commands and monitors it left running
220// unmarked, such as a dev server, present the run's own status. The
221// server suppresses the roster while an interruptible activity run exists, so a
222// remaining roster is stronger than checkpoint-oriented waiting.
223function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
224 const parkAtIdle =
225 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
226 thread.status !== "failed";
227 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
228 return null;
229 }
230 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
231 return {
232 status,
233 activeRunId: thread.activeRunId,
234 activityStartedAt:
235 thread.activityRunStartedAt === undefined
236 ? undefined
237 : nullableIso(thread.activityRunStartedAt),
238 providerInstanceId: thread.providerInstanceId,
239 providerName: null,
240 lastError: thread.lastError ?? null,
241 lastErrorClass: thread.lastErrorClass ?? null,
242 lastErrorCode: thread.lastErrorCode ?? null,
243 usageLimitResetAt: thread.usageLimitResetAt ?? null,
244 updatedAt: iso(thread.updatedAt),
245 };
246}
247
248export function scopeProject(
249 environmentId: EnvironmentId,
250 project: OrchestrationProjectShell,
251): EnvironmentProject {
252 return { ...project, environmentId };
253}
254
255export type PendingSubagentRequest = "approval" | "user_input";
256
257export function presentThreadShell(
258 environmentId: EnvironmentId,
259 thread: OrchestrationV2ThreadShell,
260 pendingSubagentRequest: PendingSubagentRequest | null = null,
261): EnvironmentThreadShell {
262 const updatedAt = iso(thread.updatedAt);
263 const latestRun =
264 thread.latestRunId === null
265 ? null
266 : ({
267 runId: thread.latestRunId,
268 status: thread.status === "idle" ? "completed" : thread.status,
269 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
270 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
271 completedAt:
272 thread.latestRunCompletedAt === undefined
273 ? thread.status === "idle" || terminalRunStatus(thread.status)
274 ? updatedAt
275 : null
276 : nullableIso(thread.latestRunCompletedAt),
277 assistantMessageId: null,
278 } satisfies ThreadRunSummary);
279 const runtime = shellRuntime(thread);
280 // Waiting runs have ended their provider turn and are only draining effects.
281 const runtimeIsWorking =
282 runtime?.status === "preparing" ||
283 runtime?.status === "starting" ||
284 runtime?.status === "running";
285 return {
286 environmentId,
287 id: thread.id,
288 projectId: thread.projectId,
289 title:
290 thread.lineage.relationshipToParent === "subagent"
291 ? formatSubagentDisplayTitle(thread.title)
292 : thread.title,
293 providerInstanceId: thread.providerInstanceId,
294 modelSelection: thread.modelSelection,
295 runtimeMode: thread.runtimeMode,
296 interactionMode: thread.interactionMode,
297 branch: thread.branch,
298 worktreePath: thread.worktreePath,
299 pullRequests: threadPullRequestsOf(thread),
300 linkedPullRequest: thread.linkedPullRequest ?? null,
301 branchPullRequest: thread.branchPullRequest ?? null,
302 lineage: thread.lineage,
303 forkedFrom: thread.forkedFrom,
304 linkOrigin: thread.linkOrigin ?? null,
305 delegatedFrom: thread.delegatedFrom ?? null,
306 activeProviderThreadId: thread.activeProviderThreadId,
307 latestRun,
308 runtime,
309 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
310 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
311 ...(thread.latestUserAuthoredMessageAt === undefined
312 ? {}
313 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
314 hasPendingApprovals:
315 thread.pendingRuntimeRequest !== null &&
316 thread.pendingRuntimeRequest.kind !== "user_input" &&
317 thread.pendingRuntimeRequest.kind !== "auth_refresh",
318 hasPendingUserInput:
319 thread.pendingRuntimeRequest?.kind === "user_input" &&
320 (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
321 pendingSubagentRequest,
322 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
323 hasActionableProposedPlan: thread.hasActionableProposedPlan,
324 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
325 providerInstanceHistory: thread.providerInstanceHistory ?? [],
326 goal: thread.goal ?? null,
327 itemCount: thread.itemCount,
328 visibleItemCount: thread.visibleItemCount,
329 createdAt: iso(thread.createdAt),
330 updatedAt,
331 archivedAt: nullableIso(thread.archivedAt),
332 settledOverride: thread.settledOverride,
333 settledAt: nullableIso(thread.settledAt),
334 unsettledAt: nullableIso(thread.unsettledAt ?? null),
335 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
336 snoozedAt: nullableIso(thread.snoozedAt ?? null),
337 limitRecovery: thread.limitRecovery ?? null,
338 pinnedAt: nullableIso(thread.pinnedAt ?? null),
339 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
340 pinOrderKey: thread.pinOrderKey ?? null,
341 activeOrderKey: thread.activeOrderKey ?? null,
342 ...(thread.lastVisitedAt === undefined
343 ? {}
344 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
345 opens: thread.opens ?? null,
346 titleRegeneration:
347 thread.titleRegeneration == null
348 ? null
349 : {
350 requestId: thread.titleRegeneration.requestId,
351 startedAt: iso(thread.titleRegeneration.startedAt),
352 },
353 deletedAt: nullableIso(thread.deletedAt),
354 source: thread,
355 };
356}
357
358export function scopeThreadShell(
359 environmentId: EnvironmentId,
360 thread: OrchestrationV2ThreadShell,
361): EnvironmentThreadShell {
362 return presentThreadShell(environmentId, thread);
363}
364
365const THREAD_PROVIDER_STACK_LIMIT = 3;
366
367export function resolveThreadProviderStack(
368 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
369): ReadonlyArray<ProviderInstanceId> {
370 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
371 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
372 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
373}
374
375/**
376 * Both shell and detail timers count from the activity-owning run's work
377 * start, never last activity. A wake keeps the start of the work it continues.
378 */
379export function resolveThreadWorkingStartedAt(input: {
380 readonly latestRun: Pick<
381 ThreadRunSummary,
382 "runId" | "startedAt" | "requestedAt" | "completedAt"
383 > | null;
384 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
385}): string | null {
386 const valid = (value: string | null | undefined) =>
387 value != null && Number.isFinite(Date.parse(value)) ? value : null;
388 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
389 const run = input.latestRun;
390 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
391 return valid(run.startedAt) ?? valid(run.requestedAt);
392 }
393 return null;
394}
395
396export function formatWorkingDurationLabel(elapsedMs: number): string {
397 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
398 if (seconds < 60) return `${seconds}s`;
399 const minutes = Math.floor(seconds / 60);
400 if (minutes < 60) return `${minutes}m`;
401 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
402}