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";
8import { mFallback, msg } from "gt-i18n";
9import type { MFunctionType } from "gt-i18n/types";
10
11import { compactionBlocksSteering } from "./composerDispatch.ts";
12import type { ThreadStructure } from "./models.ts";
13
14type Projection = ThreadStructure;
15type Run = Projection["runs"][number];
16type Message = Projection["messages"][number];
17type ProviderSession = Projection["providerSessions"][number];
18
19const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
20const MERGE_BACK_RUN_STATUSES = new Set<Run["status"]>(["waiting", "completed"]);
21const MERGE_BACK_BLOCKING_RUN_STATUSES = new Set<Run["status"]>([
22 "preparing",
23 "starting",
24 "running",
25]);
26
27export interface QueuedThreadRun {
28 readonly run: Run;
29 readonly text: string;
30 readonly attachments: ReadonlyArray<ChatAttachment>;
31 readonly messageId: Message["id"];
32 readonly context?: Message["context"];
33 /** Carries the attribution a sent message shows: automation, agent sender, or guest. */
34 readonly message?: Message;
35}
36
37export interface ThreadQueueWorkflowState {
38 readonly activeRun: Run | null;
39 readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
40 readonly isHeld: boolean;
41 readonly canPromoteToSteer: boolean;
42 /** The active run is a compaction, so promoting a queued message stops it instead of steering. */
43 readonly promoteSkipsCompaction: boolean;
44 readonly canSendNow: boolean;
45}
46
47export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
48 return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
49}
50
51/**
52 * A successfully finished provider turn remains in `waiting` while its
53 * checkpoint is captured. Keep that newest turn available for merge-back
54 * instead of falling through to an older fully checkpointed run.
55 */
56export function resolveLatestMergeBackRun(projection: Projection): Run | null {
57 const latestProviderFinishedRun = projection.runs.reduce<Run | null>(
58 (latest, run) =>
59 MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
60 ? run
61 : latest,
62 null,
63 );
64 if (latestProviderFinishedRun === null) return null;
65
66 const hasNewerActiveRun = projection.runs.some(
67 (run) =>
68 run.ordinal > latestProviderFinishedRun.ordinal &&
69 MERGE_BACK_BLOCKING_RUN_STATUSES.has(run.status),
70 );
71 return hasNewerActiveRun ? null : latestProviderFinishedRun;
72}
73
74function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
75 const activeRun = resolveActiveThreadRun(projection);
76 const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
77 const activeProviderThread =
78 providerThreadId === null
79 ? null
80 : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
81 const attachedProviderThread =
82 activeProviderThread ??
83 projection.providerThreads.find(
84 (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
85 ) ??
86 null;
87 const sessionId = attachedProviderThread?.providerSessionId ?? null;
88 if (sessionId !== null) {
89 return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
90 }
91 return (
92 projection.providerSessions.findLast(
93 (session) => session.status !== "stopped" && session.status !== "error",
94 ) ?? null
95 );
96}
97
98export function threadSteersDuringCompaction(projection: Projection | null | undefined): boolean {
99 if (projection == null) return false;
100 return (
101 resolveThreadProviderSession(projection)?.capabilities.turns.activeSteeringDuringCompaction ===
102 true
103 );
104}
105
106function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): boolean {
107 return (
108 turns.supportsActiveSteering ||
109 (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart)
110 );
111}
112
113export function threadCanSteer(
114 projection: Projection | null,
115 input: {
116 readonly compactCommandIsActive: boolean;
117 readonly compactionRunning: boolean;
118 readonly activeRunId: Run["id"] | null | undefined;
119 },
120): boolean {
121 const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns;
122 // A steer submitted before the session attaches can wait for its provider turn.
123 if (turns && !supportsSteering(turns)) return false;
124 return !compactionBlocksSteering({
125 compactCommandIsActive: input.compactCommandIsActive,
126 compactionRunning: input.compactionRunning,
127 steersDuringCompaction: turns?.activeSteeringDuringCompaction === true,
128 run: projection?.runs.find((run) => run.id === input.activeRunId),
129 messages: projection?.messages,
130 });
131}
132
133export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean {
134 if (projection == null) return false;
135 const session = resolveThreadProviderSession(projection);
136 if (session !== null) {
137 return session.capabilities.sessions.supportsProviderSwitchingViaHandoff;
138 }
139 if (resolveActiveThreadRun(projection) !== null) return false;
140 if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true;
141
142 // Detaching a stopped session removes it from the projection. The server still
143 // hands off from saved app history, which needs the source provider thread but
144 // not its native ref.
145 return projection.providerThreads.some(
146 (thread) =>
147 thread.id === projection.thread.activeProviderThreadId &&
148 thread.appThreadId === projection.thread.id &&
149 thread.providerInstanceId === projection.thread.modelSelection.instanceId,
150 );
151}
152
153export function getUserQueuedThreadRuns(
154 projection: Pick<Projection, "runs" | "messages">,
155): ReadonlyArray<Run> {
156 if (!projection.runs.some((run) => run.status === "queued")) return [];
157
158 const automaticCompletionMessageIds = new Set(
159 projection.messages
160 .filter(
161 (message) =>
162 message.delegatedCompletion !== undefined || message.notification !== undefined,
163 )
164 .map((message) => message.id),
165 );
166 return projection.runs.filter(
167 (run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
168 );
169}
170
171export function deriveThreadQueueWorkflowState(
172 projection: Projection,
173 resolve: MFunctionType = mFallback,
174): ThreadQueueWorkflowState {
175 const activeRun = resolveActiveThreadRun(projection);
176 const session = resolveThreadProviderSession(projection);
177 const capabilities = session?.capabilities.turns;
178 const canSteer = capabilities !== undefined && supportsSteering(capabilities);
179 const activeMessage = projection.messages.find(
180 (message) => message.id === activeRun?.userMessageId,
181 );
182 const promoteSkipsCompaction =
183 activeMessage !== undefined && isCompactionCommandMessage(activeMessage);
184 const hasSteerableProviderTurn =
185 activeRun?.status === "running" &&
186 activeRun.activeAttemptId !== null &&
187 projection.providerTurns.some(
188 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
189 );
190 const queuedRuns = copySorted(
191 getUserQueuedThreadRuns(projection),
192 (left, right) =>
193 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
194 left.ordinal - right.ordinal,
195 ).map((run) => {
196 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
197 return {
198 run,
199 // A queued guest message shows the guest's words; the agent still gets the attributed text.
200 text: message?.context?.guest?.text ?? message?.text ?? resolve(msg("Queued message")),
201 attachments: message?.attachments ?? [],
202 messageId: run.userMessageId,
203 ...(message?.context ? { context: message.context } : {}),
204 ...(message ? { message } : {}),
205 };
206 });
207
208 return {
209 activeRun,
210 queuedRuns,
211 isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
212 canSendNow:
213 activeRun === null &&
214 projection.thread.archivedAt == null &&
215 projection.thread.deletedAt == null,
216 canPromoteToSteer:
217 promoteSkipsCompaction ||
218 ((activeRun?.status === "preparing" || activeRun?.status === "starting") &&
219 (capabilities === undefined || canSteer)) ||
220 (hasSteerableProviderTurn && canSteer),
221 promoteSkipsCompaction,
222 };
223}
224
225export function canForkProjectedAssistantItem(input: {
226 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
227 readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
228}): boolean {
229 const item = input.projectedItem.item;
230 if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
231 return false;
232 }
233 if (input.capabilities === undefined) {
234 // Historical and inherited rows may outlive their provider-session record.
235 // Keep the portable server-side fallback available when capability evidence
236 // is absent; a known incapable provider is rejected below.
237 return true;
238 }
239 const capabilities = input.capabilities;
240 const canForkNatively =
241 capabilities.threads.canForkThread &&
242 capabilities.threads.canForkFromTurn &&
243 capabilities.identity.nativeThreadIds === "strong";
244 return canForkNatively || capabilities.context.supportsFullThreadHandoff;
245}
246
247export function canDetachThreadProviderSession(projection: Projection): boolean {
248 const session = resolveThreadProviderSession(projection);
249 return session !== null && session.status !== "stopped" && session.status !== "error";
250}