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