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 ProviderDriverKind,
16 ProviderInstanceId,
17 RunId,
18 ThreadId,
19} from "@t3tools/contracts";
20import * as DateTime from "effect/DateTime";
21import { mFallback, msg } from "gt-i18n";
22import type { MFunctionType } from "gt-i18n/types";
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;
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 readonly id: ThreadId;
188 readonly projectId: ProjectId;
189 readonly title: string;
190 readonly providerInstanceId: ProviderInstanceId;
191 readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"];
192 readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"];
193 readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"];
194 readonly branch: string | null;
195 readonly worktreePath: string | null;
196 readonly lineage: OrchestrationV2ThreadShell["lineage"];
197 readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];
198 readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null;
199 /** The thread in a linked environment that delegated this one, if one did. */
200 readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null;
201 /** A move to a linked environment: waiting, under way, done, or failed. */
202 readonly handoff: NonNullable<OrchestrationV2ThreadShell["handoff"]> | null;
203 /** The workflow run this thread is an agent step of, if it is one. */
204 readonly workflowRun: OrchestrationV2ThreadShell["workflowRun"] | null;
205 readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];
206 readonly latestRun: ThreadRunSummary | null;
207 readonly runtime: ThreadRuntimeSummary | null;
208 readonly blockedOnThreadWait?: boolean;
209 readonly latestUserMessageAt: string | null;
210 readonly latestUserAuthoredMessageAt?: string | null;
211 readonly hasPendingApprovals: boolean;
212 readonly hasPendingUserInput: boolean;
213 readonly pendingUserInputAt?: string | null;
214 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
215 /** Guest messages waiting for the owner to send or dismiss. */
216 readonly pendingGuestMessageCount?: number;
217 readonly hasActionableProposedPlan: boolean;
218 readonly pendingBackgroundTasks: ReadonlyArray<
219 NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
220 >;
221 readonly providerInstanceHistory: ReadonlyArray<ProviderInstanceId>;
222 readonly goal: OrchestrationV2ProviderGoal | null;
223 readonly itemCount: number;
224 readonly visibleItemCount: number;
225 readonly createdAt: string;
226 readonly updatedAt: string;
227 readonly archivedAt: string | null;
228 readonly settledOverride: "settled" | "active" | null;
229 readonly settledAt: string | null;
230 readonly unsettledAt: string | null;
231 readonly snoozedUntil: string | null;
232 readonly snoozedAt: string | null;
233 readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null;
234 readonly pinnedAt: string | null;
235 readonly autoSettleDisabledAt?: string | null;
236 readonly pinOrderKey: string | null;
237 readonly activeOrderKey: string | null;
238 readonly pullRequests: ReadonlyArray<import("@t3tools/contracts").ThreadPullRequestLink>;
239 readonly linkedPullRequest?: ThreadLinkedPullRequest | null;
240 readonly branchPullRequest?: ThreadLinkedPullRequest | null;
241 /** Absent from rows built before issue linking; the server sends an empty list. */
242 readonly issues?: ReadonlyArray<import("@t3tools/contracts").ThreadIssueLink>;
243 /**
244 * Server-tracked visited watermark. `undefined` means the environment's
245 * server predates visited tracking and clients should fall back to any
246 * local visited state they keep.
247 */
248 readonly lastVisitedAt?: string | null;
249 /** Server-tracked open history for search ranking. */
250 readonly opens?: import("@t3tools/contracts").OrchestrationV2ThreadOpens | null;
251 readonly titleRegeneration?: { readonly requestId: string; readonly startedAt: string } | null;
252 readonly deletedAt: string | null;
253 readonly source: OrchestrationV2ThreadShell;
254}
255
256function iso(value: DateTime.Utc): string {
257 return DateTime.formatIso(value);
258}
259
260function nullableIso(value: DateTime.Utc | null): string | null {
261 return value === null ? null : iso(value);
262}
263
264function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
265 return (
266 status === "completed" ||
267 status === "interrupted" ||
268 status === "failed" ||
269 status === "cancelled" ||
270 status === "rolled_back"
271 );
272}
273
274// Only work the agent waits on holds it: commands and monitors it left running
275// unmarked, such as a dev server, present the run's own status. The
276// server suppresses the roster while an interruptible activity run exists, so a
277// remaining roster is stronger than checkpoint-oriented waiting.
278function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
279 const parkAtIdle =
280 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
281 thread.status !== "failed";
282 if (thread.latestRunId === null && !parkAtIdle) {
283 return null;
284 }
285 const status = parkAtIdle ? "idle" : (thread.activityRunStatus ?? thread.status);
286 return {
287 status,
288 activeRunId: thread.activeRunId,
289 activityStartedAt:
290 thread.activityRunStartedAt === undefined
291 ? undefined
292 : nullableIso(thread.activityRunStartedAt),
293 providerInstanceId: thread.providerInstanceId,
294 providerName: null,
295 lastError: thread.lastError ?? null,
296 lastErrorClass: thread.lastErrorClass ?? null,
297 lastErrorCode: thread.lastErrorCode ?? null,
298 usageLimitResetAt: thread.usageLimitResetAt ?? null,
299 updatedAt: iso(thread.updatedAt),
300 };
301}
302
303export function scopeProject(
304 environmentId: EnvironmentId,
305 project: OrchestrationProjectShell,
306): EnvironmentProject {
307 return { ...project, environmentId };
308}
309
310export type PendingSubagentRequest = "approval" | "user_input";
311
312export function presentThreadShell(
313 environmentId: EnvironmentId,
314 thread: OrchestrationV2ThreadShell,
315 pendingSubagentRequest: PendingSubagentRequest | null = null,
316): EnvironmentThreadShell {
317 const updatedAt = iso(thread.updatedAt);
318 const latestRun =
319 thread.latestRunId === null
320 ? null
321 : ({
322 runId: thread.latestRunId,
323 status: thread.status === "idle" ? "completed" : thread.status,
324 requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
325 startedAt: nullableIso(thread.latestRunStartedAt ?? null),
326 completedAt:
327 thread.latestRunCompletedAt === undefined
328 ? thread.status === "idle" || terminalRunStatus(thread.status)
329 ? updatedAt
330 : null
331 : nullableIso(thread.latestRunCompletedAt),
332 assistantMessageId: null,
333 } satisfies ThreadRunSummary);
334 const runtime = shellRuntime(thread);
335 return {
336 environmentId,
337 id: thread.id,
338 projectId: thread.projectId,
339 title:
340 thread.lineage.relationshipToParent === "subagent"
341 ? formatSubagentDisplayTitle(thread.title)
342 : thread.title,
343 providerInstanceId: thread.providerInstanceId,
344 modelSelection: thread.modelSelection,
345 runtimeMode: thread.runtimeMode,
346 interactionMode: thread.interactionMode,
347 branch: thread.branch,
348 worktreePath: thread.worktreePath,
349 pullRequests: threadPullRequestsOf(thread),
350 linkedPullRequest: thread.linkedPullRequest ?? null,
351 branchPullRequest: thread.branchPullRequest ?? null,
352 issues: thread.issues ?? [],
353 lineage: thread.lineage,
354 forkedFrom: thread.forkedFrom,
355 linkOrigin: thread.linkOrigin ?? null,
356 delegatedFrom: thread.delegatedFrom ?? null,
357 handoff: thread.handoff ?? null,
358 workflowRun: thread.workflowRun ?? null,
359 activeProviderThreadId: thread.activeProviderThreadId,
360 latestRun,
361 runtime,
362 blockedOnThreadWait: thread.blockedOnThreadWait ?? false,
363 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
364 ...(thread.latestUserAuthoredMessageAt === undefined
365 ? {}
366 : { latestUserAuthoredMessageAt: nullableIso(thread.latestUserAuthoredMessageAt) }),
367 hasPendingApprovals:
368 thread.pendingRuntimeRequest !== null &&
369 thread.pendingRuntimeRequest.kind !== "user_input" &&
370 thread.pendingRuntimeRequest.kind !== "auth_refresh",
371 // Async questions count too, so a thread with any open question leaves Working.
372 hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
373 pendingUserInputAt:
374 thread.pendingRuntimeRequest?.kind === "user_input"
375 ? iso(thread.pendingRuntimeRequest.createdAt)
376 : null,
377 pendingSubagentRequest,
378 pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0,
379 hasActionableProposedPlan: thread.hasActionableProposedPlan,
380 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
381 providerInstanceHistory: thread.providerInstanceHistory ?? [],
382 goal: thread.goal ?? null,
383 itemCount: thread.itemCount,
384 visibleItemCount: thread.visibleItemCount,
385 createdAt: iso(thread.createdAt),
386 updatedAt,
387 archivedAt: nullableIso(thread.archivedAt),
388 settledOverride: thread.settledOverride,
389 settledAt: nullableIso(thread.settledAt),
390 unsettledAt: nullableIso(thread.unsettledAt ?? null),
391 snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
392 snoozedAt: nullableIso(thread.snoozedAt ?? null),
393 limitRecovery: thread.limitRecovery ?? null,
394 pinnedAt: nullableIso(thread.pinnedAt ?? null),
395 autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null),
396 pinOrderKey: thread.pinOrderKey ?? null,
397 activeOrderKey: thread.activeOrderKey ?? null,
398 ...(thread.lastVisitedAt === undefined
399 ? {}
400 : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
401 opens: thread.opens ?? null,
402 titleRegeneration:
403 thread.titleRegeneration == null
404 ? null
405 : {
406 requestId: thread.titleRegeneration.requestId,
407 startedAt: iso(thread.titleRegeneration.startedAt),
408 },
409 deletedAt: nullableIso(thread.deletedAt),
410 source: thread,
411 };
412}
413
414export function scopeThreadShell(
415 environmentId: EnvironmentId,
416 thread: OrchestrationV2ThreadShell,
417): EnvironmentThreadShell {
418 return presentThreadShell(environmentId, thread);
419}
420
421const THREAD_PROVIDER_STACK_LIMIT = 3;
422
423export function resolveThreadProviderStack(
424 thread: Pick<EnvironmentThreadShell, "providerInstanceHistory" | "modelSelection" | "runtime">,
425): ReadonlyArray<ProviderInstanceId> {
426 const current = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
427 const previous = thread.providerInstanceHistory.filter((instanceId) => instanceId !== current);
428 return [...previous.slice(-(THREAD_PROVIDER_STACK_LIMIT - 1)), current];
429}
430
431/**
432 * Both shell and detail timers count from the activity-owning run's work
433 * start, never last activity. A wake keeps the start of the work it continues.
434 */
435export function resolveThreadWorkingStartedAt(input: {
436 readonly latestRun: Pick<
437 ThreadRunSummary,
438 "runId" | "startedAt" | "requestedAt" | "completedAt"
439 > | null;
440 readonly runtime: Pick<ThreadRuntimeSummary, "activeRunId" | "activityStartedAt"> | null;
441}): string | null {
442 const valid = (value: string | null | undefined) =>
443 value != null && Number.isFinite(Date.parse(value)) ? value : null;
444 if (input.runtime?.activityStartedAt !== undefined) return valid(input.runtime.activityStartedAt);
445 const run = input.latestRun;
446 if (run?.completedAt === null && run.runId === input.runtime?.activeRunId) {
447 return valid(run.startedAt) ?? valid(run.requestedAt);
448 }
449 return null;
450}
451
452export function formatWorkingDurationLabel(
453 elapsedMs: number,
454 resolve: MFunctionType = mFallback,
455): string {
456 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
457 if (seconds < 60) return resolve(msg("{count}s", { count: seconds }));
458 const minutes = Math.floor(seconds / 60);
459 if (minutes < 60) return resolve(msg("{count}m", { count: minutes }));
460 return resolve(
461 msg("{hours}h {minutes}m", { hours: Math.floor(minutes / 60), minutes: minutes % 60 }),
462 );
463}