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