Open History to see the last commit
1import {
2 type ChatAttachment,
3 type OrchestrationV2ProjectedTurnItem,
4 type OrchestrationV2ProviderCapabilities,
5 orchestrationV2SteerRejectionReason,
6 isCompactionCommandMessage,
7 parseGoalCommand,
8} from "@t3tools/contracts";
9import { copySorted } from "@t3tools/shared/Array";
10
11import type { ThreadStructure } from "./models.ts";
12
13type Projection = ThreadStructure;
14type Run = Projection["runs"][number];
15type Message = Projection["messages"][number];
16type ProviderSession = Projection["providerSessions"][number];
17
18const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
19const MERGE_BACK_RUN_STATUSES = new Set<Run["status"]>(["waiting", "completed"]);
20const MERGE_BACK_BLOCKING_RUN_STATUSES = new Set<Run["status"]>([
21 "preparing",
22 "starting",
23 "running",
24]);
25
26export interface QueuedThreadRun {
27 readonly run: Run;
28 readonly text: string;
29 readonly attachments: ReadonlyArray<ChatAttachment>;
30 readonly messageId: Message["id"];
31 readonly context?: Message["context"];
32 /** Set when the server would reject promoting this run to a steer. */
33 readonly steerRejectionReason: string | null;
34 /** Carries the attribution a sent message shows: automation, agent sender, or guest. */
35 readonly message?: Message;
36}
37
38export interface ThreadQueueWorkflowState {
39 readonly activeRun: Run | null;
40 readonly queuedRuns: ReadonlyArray<QueuedThreadRun>;
41 readonly isHeld: boolean;
42 readonly canPromoteToSteer: boolean;
43 /** The active run is a compaction, so promoting a queued message stops it instead of steering. */
44 readonly promoteSkipsCompaction: boolean;
45 readonly canSendNow: boolean;
46}
47
48export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
49 return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
50}
51
52/**
53 * A successfully finished provider turn remains in `waiting` while its
54 * checkpoint is captured. Keep that newest turn available for merge-back
55 * instead of falling through to an older fully checkpointed run.
56 */
57export function resolveLatestMergeBackRun(projection: Projection): Run | null {
58 const latestProviderFinishedRun = projection.runs.reduce<Run | null>(
59 (latest, run) =>
60 MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
61 ? run
62 : latest,
63 null,
64 );
65 if (latestProviderFinishedRun === null) return null;
66
67 const hasNewerActiveRun = projection.runs.some(
68 (run) =>
69 run.ordinal > latestProviderFinishedRun.ordinal &&
70 MERGE_BACK_BLOCKING_RUN_STATUSES.has(run.status),
71 );
72 return hasNewerActiveRun ? null : latestProviderFinishedRun;
73}
74
75function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
76 const activeRun = resolveActiveThreadRun(projection);
77 const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
78 const activeProviderThread =
79 providerThreadId === null
80 ? null
81 : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
82 const attachedProviderThread =
83 activeProviderThread ??
84 projection.providerThreads.find(
85 (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
86 ) ??
87 null;
88 const sessionId = attachedProviderThread?.providerSessionId ?? null;
89 if (sessionId !== null) {
90 return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
91 }
92 return (
93 projection.providerSessions.findLast(
94 (session) => session.status !== "stopped" && session.status !== "error",
95 ) ?? null
96 );
97}
98
99export function threadSteersDuringCompaction(projection: Projection | null | undefined): boolean {
100 if (projection == null) return false;
101 return (
102 resolveThreadProviderSession(projection)?.capabilities.turns.activeSteeringDuringCompaction ===
103 true
104 );
105}
106
107export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean {
108 if (projection == null) return false;
109 const session = resolveThreadProviderSession(projection);
110 if (session !== null) {
111 return session.capabilities.sessions.supportsProviderSwitchingViaHandoff;
112 }
113 if (resolveActiveThreadRun(projection) !== null) return false;
114 if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true;
115
116 // Detaching a stopped session removes it from the projection. The server still
117 // hands off from saved app history, which needs the source provider thread but
118 // not its native ref.
119 return projection.providerThreads.some(
120 (thread) =>
121 thread.id === projection.thread.activeProviderThreadId &&
122 thread.appThreadId === projection.thread.id &&
123 thread.providerInstanceId === projection.thread.modelSelection.instanceId,
124 );
125}
126
127export function getUserQueuedThreadRuns(
128 projection: Pick<Projection, "runs" | "messages">,
129): ReadonlyArray<Run> {
130 const automaticCompletionMessageIds = new Set(
131 projection.messages
132 .filter(
133 (message) =>
134 message.delegatedCompletion !== undefined || message.notification !== undefined,
135 )
136 .map((message) => message.id),
137 );
138 return projection.runs.filter(
139 (run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
140 );
141}
142
143function steerRejectionReason(
144 message: { readonly text: string; readonly attachments: ReadonlyArray<ChatAttachment> },
145 runsNativeGoals: boolean,
146): string | null {
147 const reason = orchestrationV2SteerRejectionReason(message);
148 if (reason !== null || runsNativeGoals || parseGoalCommand(message) === null) return reason;
149 return "Goal commands must run as a separate turn.";
150}
151
152export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
153 const activeRun = resolveActiveThreadRun(projection);
154 const session = resolveThreadProviderSession(projection);
155 const capabilities = session?.capabilities.turns;
156 // Mirrors the server's goalDriverFor: elsewhere a goal cannot stop the turn, so it cannot steer.
157 const sessionRunsNativeGoals =
158 session === null ||
159 session.driver === "codex" ||
160 session.driver === "claudeAgent" ||
161 ((session.driver === "opencode" || session.driver === "antigravity") &&
162 capabilities?.supportsNativeGoals === true);
163 // The server checks the queued run's own provider; one the session does not show is left to it.
164 const runsNativeGoals = (run: Run) =>
165 sessionRunsNativeGoals ||
166 run.modelSelection?.instanceId !== session?.providerInstanceId ||
167 projection.thread.modelSelection?.instanceId !== session?.providerInstanceId;
168 const activeMessage = projection.messages.find(
169 (message) => message.id === activeRun?.userMessageId,
170 );
171 const promoteSkipsCompaction =
172 activeMessage !== undefined && isCompactionCommandMessage(activeMessage);
173 const hasSteerableProviderTurn =
174 activeRun?.status === "running" &&
175 activeRun.activeAttemptId !== null &&
176 projection.providerTurns.some(
177 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
178 );
179 const queuedRuns = copySorted(
180 getUserQueuedThreadRuns(projection),
181 (left, right) =>
182 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
183 left.ordinal - right.ordinal,
184 ).map((run) => {
185 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
186 return {
187 run,
188 // A queued guest message shows the guest's words; the agent still gets the attributed text.
189 text: message?.context?.guest?.text ?? message?.text ?? "Queued message",
190 attachments: message?.attachments ?? [],
191 steerRejectionReason:
192 message === undefined
193 ? "Queued message is still loading."
194 : steerRejectionReason(
195 { text: message.text, attachments: message.attachments ?? [] },
196 runsNativeGoals(run),
197 ),
198 messageId: run.userMessageId,
199 ...(message?.context ? { context: message.context } : {}),
200 ...(message ? { message } : {}),
201 };
202 });
203
204 return {
205 activeRun,
206 queuedRuns,
207 isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
208 canSendNow:
209 activeRun === null &&
210 projection.thread.archivedAt == null &&
211 projection.thread.deletedAt == null,
212 canPromoteToSteer:
213 promoteSkipsCompaction ||
214 ((activeRun?.status === "preparing" || activeRun?.status === "starting") &&
215 (capabilities === undefined ||
216 capabilities.supportsActiveSteering ||
217 capabilities.supportsSteeringByInterruptRestart)) ||
218 (hasSteerableProviderTurn &&
219 (capabilities?.supportsActiveSteering === true ||
220 capabilities?.supportsSteeringByInterruptRestart === true)),
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}