The best way to control Claude Code, Codex and more from any computer or phone

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