Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

models.ts

450 lines17.0 KB

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