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 pendingUserInputAt?: string | null;
162 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
163 /** Guest messages waiting for the owner to send or dismiss. */
164 readonly pendingGuestMessageCount?: number;
165 readonly hasActionableProposedPlan: boolean;
166 readonly pendingBackgroundTasks: ReadonlyArray<
167 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
168 >;
169 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
170 readonly goal: OrchestrationV2ProviderGoal | null;
171 readonly itemCount: number;
172 readonly visibleItemCount: number;
173 readonly createdAt: string;
174 readonly updatedAt: string;
175 readonly archivedAt: string | null;
176 readonly settledOverride: "settled" | "active" | null;
177 readonly settledAt: string | null;
178 readonly unsettledAt: string | null;
179 readonly snoozedUntil: string | null;
180 readonly snoozedAt: string | null;
181 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
182 readonly pinnedAt: string | null;
183 readonly autoSettleDisabledAt?: string | null;
184 readonly pinOrderKey: string | null;
185 readonly activeOrderKey: string | null;
186 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
187 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
188 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
189 /**
190 * Server-tracked visited watermark. `undefined` means the environment's
191 * server predates visited tracking and clients should fall back to any
192 * local visited state they keep.
193 */
194 readonly lastVisitedAt?: string | null;
195 /** Server-tracked open history for search ranking. */
196 readonly opens?: import("@t3tools/contracts").OrchestrationV2ThreadOpens | null;
197 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
198 readonly deletedAt: string | null;
199 readonly source: OrchestrationV2ThreadShell;
200}
201
202function iso(value: DateTime.Utc): string {
203 return DateTime.formatIso(value);
204}
205
206function nullableIso(value: DateTime.Utc | null): string | null {
207 return value === null ? null : iso(value);
208}
209
210function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
211 return (
212 status === "completed" ||
213 status === "interrupted" ||
214 status === "failed" ||
215 status === "cancelled" ||
216 status === "rolled_back"
217 );
218}
219
220// Only work the agent waits on holds it: commands and monitors it left running
221// unmarked, such as a dev server, present the run's own status. The
222// server suppresses the roster while an interruptible activity run exists, so a
223// remaining roster is stronger than checkpoint-oriented waiting.
224function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
225 const parkAtIdle =
226 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
227 thread.status !== "failed";
228 if (thread.latestRunId === null && thread.activeProviderThreadId === null && !parkAtIdle) {
229 return null;
230 }
231 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
232 return {
233 status,
234 activeRunId: thread.activeRunId,
235 activityStartedAt:
236 thread.activityRunStartedAt === undefined
237 ? undefined
238 : nullableIso(thread.activityRunStartedAt),
239 providerInstanceId: thread.providerInstanceId,
240 providerName: null,
241 lastError: thread.lastError ?? null,
242 lastErrorClass: thread.lastErrorClass ?? null,
243 lastErrorCode: thread.lastErrorCode ?? null,
244 usageLimitResetAt: thread.usageLimitResetAt ?? null,
245 updatedAt: iso(thread.updatedAt),
246 };
247}
248
249export function scopeProject(
250 environmentId: EnvironmentId,
251 project: OrchestrationProjectShell,
252): EnvironmentProject {
253 return { ...project, environmentId };
254}
255
256export type PendingSubagentRequest = "approval" | "user_input";
257
258export function presentThreadShell(
259 environmentId: EnvironmentId,
260 thread: OrchestrationV2ThreadShell,
261 pendingSubagentRequest: PendingSubagentRequest | null = null,
262): EnvironmentThreadShell {
263 const updatedAt = iso(thread.updatedAt);
264 const latestRun =
265 thread.latestRunId === null
266 ? null
267 : ({
268 runId: thread.latestRunId,
269 status: thread.status === "idle" ? "completed" : thread.status,
270 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
271 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
272 completedAt:
273 thread.latestRunCompletedAt === undefined
274 ? thread.status === "idle" || terminalRunStatus(thread.status)
275 ? updatedAt
276 : null
277 : nullableIso(thread.latestRunCompletedAt),
278 assistantMessageId: null,
279 } satisfies ThreadRunSummary);
280 const runtime = shellRuntime(thread);
281 return {
282 environmentId,
283 id: thread.id,
284 projectId: thread.projectId,
285 title:
286 thread.lineage.relationshipToParent === "subagent"
287 ? formatSubagentDisplayTitle(thread.title)
288 : thread.title,
289 providerInstanceId: thread.providerInstanceId,
290 modelSelection: thread.modelSelection,
291 runtimeMode: thread.runtimeMode,
292 interactionMode: thread.interactionMode,
293 branch: thread.branch,
294 worktreePath: thread.worktreePath,
295 pullRequests: threadPullRequestsOf(thread),
296 linkedPullRequest: thread.linkedPullRequest ?? null,
297 branchPullRequest: thread.branchPullRequest ?? null,
298 lineage: thread.lineage,
299 forkedFrom: thread.forkedFrom,
300 linkOrigin: thread.linkOrigin ?? null,
301 delegatedFrom: thread.delegatedFrom ?? null,
302 activeProviderThreadId: thread.activeProviderThreadId,
303 latestRun,
304 runtime,
305 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
306 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
307 ...(thread.latestUserAuthoredMessageAt === undefined
308 ? {}
309 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
310 hasPendingApprovals:
311 thread.pendingRuntimeRequest !== null &&
312 thread.pendingRuntimeRequest.kind !== "user_input" &&
313 thread.pendingRuntimeRequest.kind !== "auth_refresh",
314 // Async questions count too, so a thread with any open question leaves Working.
315 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
316 pendingUserInputAt:
317 thread.pendingRuntimeRequest?.kind === "user_input"
318 ? iso(thread.pendingRuntimeRequest.createdAt)
319 : null,
320 pendingSubagentRequest,
321 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
322 hasActionableProposedPlan: thread.hasActionableProposedPlan,
323 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
324 providerInstanceHistory: thread.providerInstanceHistory ?? [],
325 goal: thread.goal ?? null,
326 itemCount: thread.itemCount,
327 visibleItemCount: thread.visibleItemCount,
328 createdAt: iso(thread.createdAt),
329 updatedAt,
330 archivedAt: nullableIso(thread.archivedAt),
331 settledOverride: thread.settledOverride,
332 settledAt: nullableIso(thread.settledAt),
333 unsettledAt: nullableIso(thread.unsettledAt ?? null),
334 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
335 snoozedAt: nullableIso(thread.snoozedAt ?? null),
336 limitRecovery: thread.limitRecovery ?? null,
337 pinnedAt: nullableIso(thread.pinnedAt ?? null),
338 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
339 pinOrderKey: thread.pinOrderKey ?? null,
340 activeOrderKey: thread.activeOrderKey ?? null,
341 ...(thread.lastVisitedAt === undefined
342 ? {}
343 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
344 opens: thread.opens ?? null,
345 titleRegeneration:
346 thread.titleRegeneration == null
347 ? null
348 : {
349 requestId: thread.titleRegeneration.requestId,
350 startedAt: iso(thread.titleRegeneration.startedAt),
351 },
352 deletedAt: nullableIso(thread.deletedAt),
353 source: thread,
354 };
355}
356
357export function scopeThreadShell(
358 environmentId: EnvironmentId,
359 thread: OrchestrationV2ThreadShell,
360): EnvironmentThreadShell {
361 return presentThreadShell(environmentId, thread);
362}
363
364const THREAD_PROVIDER_STACK_LIMIT = 3;
365
366export function resolveThreadProviderStack(
367 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
368): ReadonlyArray<ProviderInstanceId> {
369 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
370 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
371 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
372}
373
374/**
375 * Both shell and detail timers count from the activity-owning run's work
376 * start, never last activity. A wake keeps the start of the work it continues.
377 */
378export function resolveThreadWorkingStartedAt(input: {
379 readonly latestRun: Pick<
380 ThreadRunSummary,
381 "runId" | "startedAt" | "requestedAt" | "completedAt"
382 > | null;
383 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
384}): string | null {
385 const valid = (value: string | null | undefined) =>
386 value != null && Number.isFinite(Date.parse(value)) ? value : null;
387 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
388 const run = input.latestRun;
389 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
390 return valid(run.startedAt) ?? valid(run.requestedAt);
391 }
392 return null;
393}
394
395export function formatWorkingDurationLabel(elapsedMs: number): string {
396 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
397 if (seconds < 60) return `${seconds}s`;
398 const minutes = Math.floor(seconds / 60);
399 if (minutes < 60) return `${minutes}m`;
400 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
401}