Open History to see the last commit
1import {
2 type ChatAttachment,
3 isCompactionCommandMessage,
4 type OrchestrationV2ProjectedTurnItem,
5 type OrchestrationV2ProviderCapabilities,
6} from "@t3tools/contracts";
7import { copySorted } from "@t3tools/shared/Array";
8
9import type { ThreadStructure } from "./models.ts";
10
11type Projection = ThreadStructure;
12type Run = Projection["runs"][number];
13type Message = Projection["messages"][number];
14type ProviderSession = Projection["providerSessions"][number];
15
16const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
17const MERGE_BACK_RUN_STATUSES = new Set<Run["status"]>(["waiting", "completed"]);
18const MERGE_BACK_BLOCKING_RUN_STATUSES = new Set<Run["status"]>([
19 "preparing",
20 "starting",
21 "running",
22]);
23
24export interface QueuedThreadRun {
25 readonly run: Run;
26 readonly text: string;
27 readonly attachments: ReadonlyArray<ChatAttachment>;
28 readonly messageId: Message["id"];
29 readonly context?: Message["context"];
30}
31
32export interface ThreadQueueWorkflowState {
33 readonly activeRun: Run | null;
34 readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
35 readonly isHeld: boolean;
36 readonly canPromoteToSteer: boolean;
37 /** The active run is a compaction, so promoting a queued message stops it instead of steering. */
38 readonly promoteSkipsCompaction: boolean;
39 readonly canSendNow: boolean;
40}
41
42export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
43 return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
44}
45
46/**
47 * A successfully finished provider turn remains in `waiting` while its
48 * checkpoint is captured. Keep that newest turn available for merge-back
49 * instead of falling through to an older fully checkpointed run.
50 */
51export function resolveLatestMergeBackRun(projection: Projection): Run | null {
52 const latestProviderFinishedRun = projection.runs.reduce<Run | null>(
53 (latest, run) =>
54 MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
55 ? run
56 : latest,
57 null,
58 );
59 if (latestProviderFinishedRun === null) return null;
60
61 const hasNewerActiveRun = projection.runs.some(
62 (run) =>
63 run.ordinal > latestProviderFinishedRun.ordinal &&
64 MERGE_BACK_BLOCKING_RUN_STATUSES.has(run.status),
65 );
66 return hasNewerActiveRun ? null : latestProviderFinishedRun;
67}
68
69function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
70 const activeRun = resolveActiveThreadRun(projection);
71 const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
72 const activeProviderThread =
73 providerThreadId === null
74 ? null
75 : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
76 const attachedProviderThread =
77 activeProviderThread ??
78 projection.providerThreads.find(
79 (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
80 ) ??
81 null;
82 const sessionId = attachedProviderThread?.providerSessionId ?? null;
83 if (sessionId !== null) {
84 return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
85 }
86 return (
87 projection.providerSessions.findLast(
88 (session) => session.status !== "stopped" && session.status !== "error",
89 ) ?? null
90 );
91}
92
93export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean {
94 if (projection == null) return false;
95 const session = resolveThreadProviderSession(projection);
96 if (session !== null) {
97 return session.capabilities.sessions.supportsProviderSwitchingViaHandoff;
98 }
99 if (resolveActiveThreadRun(projection) !== null) return false;
100 if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true;
101
102 // Detaching a stopped session removes it from the projection, but its native
103 // provider thread remains available for the next turn's portable handoff.
104 return projection.providerThreads.some(
105 (thread) =>
106 thread.id === projection.thread.activeProviderThreadId &&
107 thread.appThreadId === projection.thread.id &&
108 thread.providerInstanceId === projection.thread.modelSelection.instanceId &&
109 thread.nativeThreadRef !== null,
110 );
111}
112
113export function getUserQueuedThreadRuns(
114 projection: Pick<Projection, "runs" | "messages">,
115): ReadonlyArray<Run> {
116 const automaticCompletionMessageIds = new Set(
117 projection.messages
118 .filter(
119 (message) =>
120 message.delegatedCompletion !== undefined || message.notification !== undefined,
121 )
122 .map((message) => message.id),
123 );
124 return projection.runs.filter(
125 (run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
126 );
127}
128
129export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
130 const activeRun = resolveActiveThreadRun(projection);
131 const session = resolveThreadProviderSession(projection);
132 const capabilities = session?.capabilities.turns;
133 const activeMessage = projection.messages.find(
134 (message) => message.id === activeRun?.userMessageId,
135 );
136 const promoteSkipsCompaction =
137 activeMessage !== undefined && isCompactionCommandMessage(activeMessage);
138 const hasSteerableProviderTurn =
139 activeRun?.status === "running" &&
140 activeRun.activeAttemptId !== null &&
141 projection.providerTurns.some(
142 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
143 );
144 const queuedRuns = copySorted(
145 getUserQueuedThreadRuns(projection),
146 (left, right) =>
147 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
148 left.ordinal - right.ordinal,
149 ).map((run) => {
150 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
151 return {
152 run,
153 // A queued guest message shows the guest's words; the agent still gets the attributed text.
154 text: message?.context?.guest?.text ?? message?.text ?? "Queued message",
155 attachments: message?.attachments ?? [],
156 messageId: run.userMessageId,
157 ...(message?.context ? { context: message.context } : {}),
158 };
159 });
160
161 return {
162 activeRun,
163 queuedRuns,
164 isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
165 canSendNow:
166 activeRun === null &&
167 projection.thread.archivedAt == null &&
168 projection.thread.deletedAt == null,
169 canPromoteToSteer:
170 promoteSkipsCompaction ||
171 (hasSteerableProviderTurn &&
172 (capabilities?.supportsActiveSteering === true ||
173 capabilities?.supportsSteeringByInterruptRestart === true)),
174 promoteSkipsCompaction,
175 };
176}
177
178export function canForkProjectedAssistantItem(input: {
179 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
180 readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
181}): boolean {
182 const item = input.projectedItem.item;
183 if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
184 return false;
185 }
186 if (input.capabilities === undefined) {
187 // Historical and inherited rows may outlive their provider-session record.
188 // Keep the portable server-side fallback available when capability evidence
189 // is absent; a known incapable provider is rejected below.
190 return true;
191 }
192 const capabilities = input.capabilities;
193 const canForkNatively =
194 capabilities.threads.canForkThread &&
195 capabilities.threads.canForkFromTurn &&
196 capabilities.identity.nativeThreadIds === "strong";
197 return canForkNatively || capabilities.context.supportsFullThreadHandoff;
198}
199
200export function canDetachThreadProviderSession(projection: Projection): boolean {
201 const session = resolveThreadProviderSession(projection);
202 return session !== null && session.status !== "stopped" && session.status !== "error";
203}