Open History to see the last commit
1import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
2import {
3 clampFileAttachmentUploadBytes,
4 fileAttachmentTooLargeMessage,
5} from "@t3tools/client-runtime/state/attachments";
6import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
7import {
8 CommandId,
9 EnvironmentId,
10 IsoDateTime,
11 MessageId,
12 ModelSelection,
13 OrchestrationMessageContext,
14 ProjectId,
15 ProviderInteractionMode,
16 RuntimeMode,
17 ThreadId,
18 type ModelSelection as ModelSelectionType,
19 type ProjectId as ProjectIdType,
20 type ProviderInteractionMode as ProviderInteractionModeType,
21 type RuntimeMode as RuntimeModeType,
22 type ServerProvider,
23} from "@t3tools/contracts";
24import * as Schema from "effect/Schema";
25
26import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
27import type { DraftComposerAttachment } from "../lib/composerImages";
28import { scopedThreadKey } from "../lib/scopedEntities";
29import { resolveProviderInteractionMode } from "../features/threads/legacy-plan-mode";
30
31// Keep current writes until a compatible native baseline includes the v4 reader.
32const THREAD_OUTBOX_SCHEMA_VERSION = 3;
33const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
34
35const QueuedThreadCreationSchema = Schema.Struct({
36 projectId: ProjectId,
37 // Snapshot of the project's display metadata so a pending task stays
38 // presentable in the thread list even when the project shell is not loaded.
39 projectTitle: Schema.optional(Schema.String),
40 projectCwd: Schema.optional(Schema.String),
41 workspaceMode: Schema.Literals(["local", "worktree"]),
42 branch: Schema.NullOr(Schema.String),
43 worktreePath: Schema.NullOr(Schema.String),
44 startFromOrigin: Schema.optional(Schema.Boolean),
45});
46
47export const QueuedThreadMessageSchema = Schema.Struct({
48 schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION, 4]),
49 environmentId: EnvironmentId,
50 threadId: ThreadId,
51 messageId: MessageId,
52 commandId: CommandId,
53 text: Schema.String,
54 context: Schema.optional(OrchestrationMessageContext),
55 attachments: Schema.Array(DraftComposerAttachmentSchema),
56 modelSelection: Schema.optional(ModelSelection),
57 runtimeMode: Schema.optional(RuntimeMode),
58 interactionMode: Schema.optional(ProviderInteractionMode),
59 // Present when the queued item creates a brand-new thread (pending task)
60 // instead of appending a turn to an existing one.
61 creation: Schema.optional(QueuedThreadCreationSchema),
62 createdAt: IsoDateTime,
63});
64
65const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema);
66const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema);
67
68export interface QueuedThreadCreation {
69 readonly projectId: ProjectIdType;
70 readonly projectTitle?: string;
71 readonly projectCwd?: string;
72 readonly workspaceMode: "local" | "worktree";
73 readonly branch: string | null;
74 readonly worktreePath: string | null;
75 readonly startFromOrigin?: boolean;
76}
77
78export interface QueuedThreadMessage {
79 readonly environmentId: EnvironmentId;
80 readonly threadId: ThreadId;
81 readonly messageId: MessageId;
82 readonly commandId: CommandId;
83 readonly text: string;
84 readonly context?: OrchestrationMessageContext;
85 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
86 readonly modelSelection?: ModelSelectionType;
87 readonly runtimeMode?: RuntimeModeType;
88 readonly interactionMode?: ProviderInteractionModeType;
89 readonly creation?: QueuedThreadCreation;
90 readonly createdAt: string;
91}
92
93export interface ThreadSettingsSnapshot {
94 readonly modelSelection: ModelSelectionType;
95 readonly runtimeMode: RuntimeModeType;
96 readonly interactionMode: ProviderInteractionModeType;
97}
98
99export function resolveQueuedThreadSettings(
100 message: QueuedThreadMessage,
101 thread: ThreadSettingsSnapshot,
102 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "showInteractionModeToggle">> = [],
103): ThreadSettingsSnapshot {
104 const modelSelection = message.modelSelection ?? thread.modelSelection;
105 const provider = providers.find(
106 (candidate) => candidate.instanceId === modelSelection.instanceId,
107 );
108 return {
109 modelSelection,
110 runtimeMode: message.runtimeMode ?? thread.runtimeMode,
111 interactionMode: resolveProviderInteractionMode(
112 provider,
113 message.interactionMode ?? thread.interactionMode,
114 ),
115 };
116}
117
118export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
119 return (
120 left.instanceId === right.instanceId &&
121 left.model === right.model &&
122 JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
123 );
124}
125
126export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
127 return encodeStoredQueuedThreadMessage({
128 schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
129 ...message,
130 });
131}
132
133export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage {
134 const { schemaVersion: _, ...message } = decodeStoredQueuedThreadMessage(value);
135 return message;
136}
137
138export function groupQueuedThreadMessages(
139 messages: ReadonlyArray<QueuedThreadMessage>,
140): Record<string, ReadonlyArray<QueuedThreadMessage>> {
141 const deduplicated = new Map<MessageId, QueuedThreadMessage>();
142 for (const message of messages) {
143 deduplicated.set(message.messageId, message);
144 }
145
146 const grouped: Record<string, Array<QueuedThreadMessage>> = {};
147 for (const message of deduplicated.values()) {
148 const threadKey = scopedThreadKey(message.environmentId, message.threadId);
149 (grouped[threadKey] ??= []).push(message);
150 }
151 for (const queue of Object.values(grouped)) {
152 queue.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
153 }
154 return grouped;
155}
156
157export function flattenQueuedThreadMessages(
158 queues: Record<string, ReadonlyArray<QueuedThreadMessage>>,
159): ReadonlyArray<QueuedThreadMessage> {
160 return Object.values(queues).flat();
161}
162
163export function threadOutboxRetryDelayMs(attempt: number): number {
164 return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), THREAD_OUTBOX_MAX_RETRY_DELAY_MS);
165}
166
167export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send";
168
169export function resolveThreadOutboxDeliveryAction(input: {
170 readonly isCreation: boolean;
171 readonly threadExists: boolean;
172 readonly shellStatus: EnvironmentShellStatus;
173 readonly environmentConnected: boolean;
174 readonly threadBusy: boolean;
175}): ThreadOutboxDeliveryAction {
176 if (input.isCreation) {
177 // A pending task creates its thread on delivery. If the thread already
178 // exists the creation command went through and only cleanup remains.
179 if (input.threadExists) {
180 return "remove";
181 }
182 // Wait for the shell to be live before sending: until the thread list has
183 // synchronized, a previously delivered creation whose cleanup failed would
184 // look missing and get re-issued, duplicating the thread.
185 return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
186 }
187 if (!input.threadExists) {
188 return input.shellStatus === "live" ? "remove" : "wait";
189 }
190 return input.environmentConnected ? "send" : "wait";
191}
192
193export type ThreadOutboxDispatchStep =
194 | { readonly step: "wait" }
195 | { readonly step: "remove" }
196 | { readonly step: "retry" }
197 | { readonly step: "restore"; readonly reason: string }
198 | { readonly step: "send" };
199
200/**
201 * Wait for provider and file capabilities before sending. Cleanup does not
202 * need config: a creation whose thread exists, or a message whose thread is
203 * gone, can still be removed while config loads.
204 */
205export function resolveThreadOutboxDispatchStep(input: {
206 readonly deliveryAction: ThreadOutboxDeliveryAction;
207 readonly fileAttachments: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
208 /** Null while the environment's server config has not synced yet. */
209 readonly serverConfig: { readonly maxFileUploadBytes: number | undefined } | null;
210}): ThreadOutboxDispatchStep {
211 if (input.deliveryAction !== "send") {
212 return { step: input.deliveryAction };
213 }
214 if (input.serverConfig === null) {
215 return { step: "retry" };
216 }
217 if (input.fileAttachments.length === 0) {
218 return { step: "send" };
219 }
220 const maxBytes = input.serverConfig.maxFileUploadBytes;
221 if (maxBytes === undefined) {
222 return { step: "restore", reason: "This server does not support file attachments." };
223 }
224 const effectiveMaxBytes = clampFileAttachmentUploadBytes(maxBytes);
225 const oversized = input.fileAttachments.find(
226 (attachment) => attachment.sizeBytes > effectiveMaxBytes,
227 );
228 return oversized
229 ? { step: "restore", reason: fileAttachmentTooLargeMessage(oversized.name, effectiveMaxBytes) }
230 : { step: "send" };
231}
232
233/**
234 * A queued creation can only be dispatched once its payload would pass server
235 * validation; incomplete payloads stay pending until the user edits them.
236 */
237export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
238 if (!message.creation) {
239 return false;
240 }
241 if (message.text.trim().length === 0 || message.modelSelection === undefined) {
242 return false;
243 }
244 return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
245}
246
247function errorMessage(error: unknown): string | null {
248 if (error instanceof Error) {
249 return error.message;
250 }
251 if (typeof error === "object" && error !== null && "message" in error) {
252 return typeof error.message === "string" ? error.message : null;
253 }
254 return typeof error === "string" ? error : null;
255}
256
257/**
258 * Only a failure the server actually decided (`OrchestrationDispatchCommandError`,
259 * or an authorization rejection) means the payload itself is bad. The other
260 * typed failures a queued send can hit are transport-shaped: a socket that
261 * dropped mid-request (`RpcClientError` wrapping a Socket read/write/close
262 * reason), or an environment that is not connected or not registered. Those
263 * are matched by tag, not by message text, because a `SocketReadError` message
264 * is just "An error occurred during Read". A wrong answer here restores the
265 * pending task into a draft and it disappears from the list.
266 */
267export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
268 if (typeof error === "object" && error !== null && "_tag" in error) {
269 switch (error._tag) {
270 case "OrchestrationDispatchCommandError":
271 case "EnvironmentAuthorizationError":
272 return false;
273 case "ConnectionTransientError":
274 case "RpcClientError":
275 case "EnvironmentRpcUnavailableError":
276 case "EnvironmentNotRegisteredError":
277 return true;
278 default:
279 break;
280 }
281 }
282 return isTransportConnectionErrorMessage(errorMessage(error));
283}
284
285export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
286export type ThreadOutboxFailureAction = "retry" | "restore";
287
288export function resolveThreadOutboxFailureAction(input: {
289 readonly stage: ThreadOutboxCommandStage;
290 readonly error: unknown;
291 readonly interrupted: boolean;
292}): ThreadOutboxFailureAction {
293 if (
294 input.stage === "settings-sync" ||
295 input.interrupted ||
296 shouldRetryThreadOutboxDelivery(input.error)
297 ) {
298 return "retry";
299 }
300 return "restore";
301}