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 type { ThreadFamilyRead } from "@t3tools/client-runtime/state/threads";
8import {
9 CommandId,
10 EnvironmentId,
11 IsoDateTime,
12 MessageId,
13 ModelSelection,
14 OrchestrationMessageContext,
15 ProjectId,
16 ProviderInteractionMode,
17 RuntimeMode,
18 ThreadId,
19 type ModelSelection as ModelSelectionType,
20 type ProjectId as ProjectIdType,
21 type ProviderInteractionMode as ProviderInteractionModeType,
22 type RuntimeMode as RuntimeModeType,
23 type ServerProvider,
24} from "@t3tools/contracts";
25import * as Schema from "effect/Schema";
26
27import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
28import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
29import type { DraftComposerAttachment } from "../lib/composerImages";
30import { scopedThreadKey } from "../lib/scopedEntities";
31import { resolveProviderInteractionMode } from "./legacy-plan-mode";
32
33// Keep current writes until a compatible native baseline includes the v4 reader.
34const THREAD_OUTBOX_SCHEMA_VERSION = 3;
35const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
36
37const QueuedThreadCreationSchema = Schema.Struct({
38 projectId: ProjectId,
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 pullRequestReference: Schema.optional(Schema.String),
46});
47
48export const QueuedThreadMessageSchema = Schema.Struct({
49 schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION, 4]),
50 environmentId: EnvironmentId,
51 threadId: ThreadId,
52 messageId: MessageId,
53 commandId: CommandId,
54 text: Schema.String,
55 context: Schema.optional(OrchestrationMessageContext),
56 attachments: Schema.Array(DraftComposerAttachmentSchema),
57 modelSelection: Schema.optional(ModelSelection),
58 dispatchMode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
59 runtimeMode: Schema.optional(RuntimeMode),
60 interactionMode: Schema.optional(ProviderInteractionMode),
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 readonly pullRequestReference?: string;
77}
78
79export interface QueuedThreadMessage {
80 readonly environmentId: EnvironmentId;
81 readonly threadId: ThreadId;
82 readonly messageId: MessageId;
83 readonly commandId: CommandId;
84 readonly text: string;
85 readonly context?: OrchestrationMessageContext;
86 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
87 readonly modelSelection?: ModelSelectionType;
88 readonly runtimeMode?: RuntimeModeType;
89 readonly interactionMode?: ProviderInteractionModeType;
90 /** Captured at enqueue because draining may occur long after the tap. */
91 readonly dispatchMode?: ComposerDispatchMode;
92 readonly creation?: QueuedThreadCreation;
93 readonly createdAt: string;
94}
95
96export interface ThreadSettingsSnapshot {
97 readonly modelSelection: ModelSelectionType;
98 readonly runtimeMode: RuntimeModeType;
99 readonly interactionMode: ProviderInteractionModeType;
100}
101
102export function resolveQueuedThreadSettings(
103 message: QueuedThreadMessage,
104 thread: ThreadSettingsSnapshot,
105 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "showInteractionModeToggle">> = [],
106): ThreadSettingsSnapshot {
107 const modelSelection = message.modelSelection ?? thread.modelSelection;
108 const provider = providers.find(
109 (candidate) => candidate.instanceId === modelSelection.instanceId,
110 );
111 return {
112 modelSelection,
113 runtimeMode: message.runtimeMode ?? thread.runtimeMode,
114 interactionMode: resolveProviderInteractionMode(
115 provider,
116 message.interactionMode ?? thread.interactionMode,
117 ),
118 };
119}
120
121export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
122 return (
123 left.instanceId === right.instanceId &&
124 left.model === right.model &&
125 JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
126 );
127}
128
129export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
130 return encodeStoredQueuedThreadMessage({
131 schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
132 ...message,
133 });
134}
135
136export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage {
137 const { schemaVersion: _, ...message } = decodeStoredQueuedThreadMessage(value);
138 return message;
139}
140
141export function groupQueuedThreadMessages(
142 messages: ReadonlyArray<QueuedThreadMessage>,
143): Record<string, ReadonlyArray<QueuedThreadMessage>> {
144 const deduplicated = new Map<MessageId, QueuedThreadMessage>();
145 for (const message of messages) {
146 deduplicated.set(message.messageId, message);
147 }
148
149 const grouped: Record<string, Array<QueuedThreadMessage>> = {};
150 for (const message of deduplicated.values()) {
151 const threadKey = scopedThreadKey(message.environmentId, message.threadId);
152 (grouped[threadKey] ??= []).push(message);
153 }
154 for (const queue of Object.values(grouped)) {
155 queue.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
156 }
157 return grouped;
158}
159
160export function flattenQueuedThreadMessages(
161 queues: Record<string, ReadonlyArray<QueuedThreadMessage>>,
162): ReadonlyArray<QueuedThreadMessage> {
163 return Object.values(queues).flat();
164}
165
166export function threadOutboxRetryDelayMs(attempt: number): number {
167 return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), THREAD_OUTBOX_MAX_RETRY_DELAY_MS);
168}
169
170export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send";
171
172export function resolveThreadOutboxDeliveryAction(input: {
173 readonly isCreation: boolean;
174 readonly threadExists: boolean;
175 readonly shellStatus: EnvironmentShellStatus;
176 readonly environmentConnected: boolean;
177 /**
178 * Set when the shell can leave idle subagent children out: absence alone is not deletion there,
179 * only a settled family read without the row is.
180 */
181 readonly familyRead?: ThreadFamilyRead;
182}): ThreadOutboxDeliveryAction {
183 if (input.isCreation) {
184 if (input.threadExists) {
185 return "remove";
186 }
187 // Wait for live shells; an unsynchronized list can hide delivered creations and cause duplicate re-issuance.
188 return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
189 }
190 if (!input.threadExists) {
191 return input.shellStatus === "live" &&
192 (input.familyRead === undefined || input.familyRead === "settled")
193 ? "remove"
194 : "wait";
195 }
196 return input.environmentConnected ? "send" : "wait";
197}
198
199export type ThreadOutboxDispatchStep =
200 | { readonly step: "wait" }
201 | { readonly step: "remove" }
202 | { readonly step: "retry" }
203 | { readonly step: "restore"; readonly reason: string }
204 | { readonly step: "send" };
205
206export function resolveThreadOutboxDispatchStep(input: {
207 readonly deliveryAction: ThreadOutboxDeliveryAction;
208 readonly fileAttachments: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
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
233export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
234 if (!message.creation) {
235 return false;
236 }
237 const hasContent = message.text.trim().length > 0 || message.attachments.length > 0;
238 if (!hasContent || 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
254/** Dispatch/auth rejections invalidate payloads; other typed failures may be disconnected transports and must retry. */
255export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
256 if (typeof error === "object" && error !== null && "_tag" in error) {
257 switch (error._tag) {
258 case "OrchestrationDispatchCommandError":
259 case "EnvironmentAuthorizationError":
260 return false;
261 case "ConnectionTransientError":
262 case "RpcClientError":
263 case "EnvironmentRpcUnavailableError":
264 case "EnvironmentNotRegisteredError":
265 return true;
266 default:
267 break;
268 }
269 }
270 return isTransportConnectionErrorMessage(errorMessage(error));
271}
272
273export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
274export type ThreadOutboxFailureAction = "retry" | "restore";
275
276export function resolveThreadOutboxFailureAction(input: {
277 readonly stage: ThreadOutboxCommandStage;
278 readonly error: unknown;
279 readonly interrupted: boolean;
280}): ThreadOutboxFailureAction {
281 if (
282 input.stage === "settings-sync" ||
283 input.interrupted ||
284 shouldRetryThreadOutboxDelivery(input.error)
285 ) {
286 return "retry";
287 }
288 return "restore";
289}
290
291export type AcknowledgedThreadMessage = QueuedThreadMessage & {
292 /** The server sequence that committed the message; older servers do not report it. */
293 readonly sequence?: number;
294};