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