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