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 canReorder: boolean;
35 readonly canPromoteToSteer: boolean;
36}
37
38export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
39 return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
40}
41
42/**
43 * A successfully finished provider turn remains in `waiting` while its
44 * checkpoint is captured. Keep that newest turn available for merge-back
45 * instead of falling through to an older fully checkpointed run.
46 */
47export function resolveLatestMergeBackRun(projection: Projection): Run | null {
48 const latestProviderFinishedRun = projection.runs.reduce<Run | null>(
49 (latest, run) =>
50 MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
51 ? run
52 : latest,
53 null,
54 );
55 if (latestProviderFinishedRun === null) return null;
56
57 const hasNewerActiveRun = projection.runs.some(
58 (run) =>
59 run.ordinal > latestProviderFinishedRun.ordinal &&
60 MERGE_BACK_BLOCKING_RUN_STATUSES.has(run.status),
61 );
62 return hasNewerActiveRun ? null : latestProviderFinishedRun;
63}
64
65export function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
66 const activeRun = resolveActiveThreadRun(projection);
67 const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
68 const activeProviderThread =
69 providerThreadId === null
70 ? null
71 : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
72 const attachedProviderThread =
73 activeProviderThread ??
74 projection.providerThreads.find(
75 (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
76 ) ??
77 null;
78 const sessionId = attachedProviderThread?.providerSessionId ?? null;
79 if (sessionId !== null) {
80 return projection.providerSessions.find((session) => session.id === sessionId) ?? null;
81 }
82 return (
83 projection.providerSessions.findLast(
84 (session) => session.status !== "stopped" && session.status !== "error",
85 ) ?? null
86 );
87}
88
89/** Automatic completion/notification runs are not messages in the user's queue. */
90export function getUserQueuedThreadRuns(
91 projection: Pick<Projection, "runs" | "messages">,
92): ReadonlyArray<Run> {
93 const automaticCompletionMessageIds = new Set(
94 projection.messages
95 .filter(
96 (message) =>
97 message.delegatedCompletion !== undefined || message.notification !== undefined,
98 )
99 .map((message) => message.id),
100 );
101 return projection.runs.filter(
102 (run) => run.status === "queued" && !automaticCompletionMessageIds.has(run.userMessageId),
103 );
104}
105
106export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQueueWorkflowState {
107 const activeRun = resolveActiveThreadRun(projection);
108 const session = resolveThreadProviderSession(projection);
109 const capabilities = session?.capabilities.turns;
110 const hasSteerableProviderTurn =
111 activeRun?.status === "running" &&
112 activeRun.activeAttemptId !== null &&
113 projection.providerTurns.some(
114 (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
115 );
116 const queuedRuns = copySorted(
117 getUserQueuedThreadRuns(projection),
118 (left, right) =>
119 (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
120 left.ordinal - right.ordinal,
121 ).map((run) => {
122 const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
123 return {
124 run,
125 text: message?.text ?? "Queued message",
126 attachments: message?.attachments ?? [],
127 messageId: run.userMessageId,
128 ...(message?.context ? { context: message.context } : {}),
129 };
130 });
131
132 return {
133 activeRun,
134 queuedRuns,
135 canReorder: capabilities?.supportsQueuedMessages === true,
136 canPromoteToSteer:
137 hasSteerableProviderTurn &&
138 (capabilities?.supportsActiveSteering === true ||
139 capabilities?.supportsSteeringByInterruptRestart === true),
140 };
141}
142
143export function canForkProjectedAssistantItem(input: {
144 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
145 readonly capabilities?: OrchestrationV2ProviderCapabilities | undefined;
146}): boolean {
147 const item = input.projectedItem.item;
148 if (item.type !== "assistant_message" || item.runId === null || item.status !== "completed") {
149 return false;
150 }
151 if (input.capabilities === undefined) {
152 // Historical and inherited rows may outlive their provider-session record.
153 // Keep the portable server-side fallback available when capability evidence
154 // is absent; a known incapable provider is rejected below.
155 return true;
156 }
157 const capabilities = input.capabilities;
158 const canForkNatively =
159 capabilities.threads.canForkThread &&
160 capabilities.threads.canForkFromTurn &&
161 capabilities.identity.nativeThreadIds === "strong";
162 return canForkNatively || capabilities.context.supportsFullThreadHandoff;
163}
164
165export function canDetachThreadProviderSession(projection: Projection): boolean {
166 const session = resolveThreadProviderSession(projection);
167 return session !== null && session.status !== "stopped" && session.status !== "error";
168}