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 /** Editing replaces this message's content, so its id and context travel with the row. */
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}
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 return (
97 resolveActiveThreadRun(projection) === null &&
98 (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0)
99 );
100}
101
102/** Automatic completion/notification runs are not messages in the user's queue. */
103export function getUserQueuedThreadRuns(
104 projection: Pick<Projection, "runs" | "messages">,
105): ReadonlyArray<Run> {
106 const automaticCompletionMessageIds = new Set(
107 projection.messages
108 .filter(
109 (message) =>
110 message.delegatedCompletion !== undefined || message.notification !== undefined,
111 )
112 .map((message) => message.id),
113 );
114 return projection.runs.filter(
115 (run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
116 );
117}
118
119export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
120 const activeRun = resolveActiveThreadRun(projection);
121 const session = resolveThreadProviderSession(projection);
122 const capabilities = session?.capabilities.turns;
123 const hasSteerableProviderTurn =
124 activeRun?.status === "running" &&
125 activeRun.activeAttemptId !== null &&
126 projection.providerTurns.some(
127 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
128 );
129 const queuedRuns = copySorted(
130 getUserQueuedThreadRuns(projection),
131 (left, right) =>
132 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
133 left.ordinal - right.ordinal,
134 ).map((run) => {
135 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
136 return {
137 run,
138 text: message?.text ?? "Queued message",
139 attachments: message?.attachments ?? [],
140 messageId: run.userMessageId,
141 ...(message?.context ? { context: message.context } : {}),
142 };
143 });
144
145 return {
146 activeRun,
147 queuedRuns,
148 isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
149 canReorder: capabilities?.supportsQueuedMessages === true,
150 canPromoteToSteer:
151 hasSteerableProviderTurn &&
152 (capabilities?.supportsActiveSteering === true ||
153 capabilities?.supportsSteeringByInterruptRestart === true),
154 };
155}
156
157export function canForkProjectedAssistantItem(input: {
158 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
159 readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
160}): boolean {
161 const item = input.projectedItem.item;
162 if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
163 return false;
164 }
165 if (input.capabilities === undefined) {
166 // Historical and inherited rows may outlive their provider-session record.
167 // Keep the portable server-side fallback available when capability evidence
168 // is absent; a known incapable provider is rejected below.
169 return true;
170 }
171 const capabilities = input.capabilities;
172 const canForkNatively =
173 capabilities.threads.canForkThread &&
174 capabilities.threads.canForkFromTurn &&
175 capabilities.identity.nativeThreadIds === "strong";
176 return canForkNatively || capabilities.context.supportsFullThreadHandoff;
177}
178
179export function canDetachThreadProviderSession(projection: Projection): boolean {
180 const session = resolveThreadProviderSession(projection);
181 return session !== null && session.status !== "stopped" && session.status !== "error";
182}