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