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 readonly threadBusy: boolean;
178 /**
179 * Set when the shell can leave idle subagent children out: absence alone is not deletion there,
180 * only a settled family read without the row is.
181 */
182 readonly familyRead?: ThreadFamilyRead;
183}): ThreadOutboxDeliveryAction {
184 if (input.isCreation) {
185 if (input.threadExists) {
186 return "remove";
187 }
188 // Wait for live shells; an unsynchronized list can hide delivered creations and cause duplicate re-issuance.
189 return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
190 }
191 if (!input.threadExists) {
192 return input.shellStatus === "live" &&
193 (input.familyRead === undefined || input.familyRead === "settled")
194 ? "remove"
195 : "wait";
196 }
197 return input.environmentConnected ? "send" : "wait";
198}
199
200export type ThreadOutboxDispatchStep =
201 | { readonly step: "wait" }
202 | { readonly step: "remove" }
203 | { readonly step: "retry" }
204 | { readonly step: "restore"; readonly reason: string }
205 | { readonly step: "send" };
206
207export function resolveThreadOutboxDispatchStep(input: {
208 readonly deliveryAction: ThreadOutboxDeliveryAction;
209 readonly fileAttachments: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
210 readonly serverConfig: { readonly maxFileUploadBytes: number | undefined } | null;
211}): ThreadOutboxDispatchStep {
212 if (input.deliveryAction !== "send") {
213 return { step: input.deliveryAction };
214 }
215 if (input.serverConfig === null) {
216 return { step: "retry" };
217 }
218 if (input.fileAttachments.length === 0) {
219 return { step: "send" };
220 }
221 const maxBytes = input.serverConfig.maxFileUploadBytes;
222 if (maxBytes === undefined) {
223 return { step: "restore", reason: "This server does not support file attachments." };
224 }
225 const effectiveMaxBytes = clampFileAttachmentUploadBytes(maxBytes);
226 const oversized = input.fileAttachments.find(
227 (attachment) => attachment.sizeBytes > effectiveMaxBytes,
228 );
229 return oversized
230 ? { step: "restore", reason: fileAttachmentTooLargeMessage(oversized.name, effectiveMaxBytes) }
231 : { step: "send" };
232}
233
234export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
235 if (!message.creation) {
236 return false;
237 }
238 const hasContent = message.text.trim().length > 0 || message.attachments.length > 0;
239 if (!hasContent || message.modelSelection === undefined) {
240 return false;
241 }
242 return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
243}
244
245function errorMessage(error: unknown): string | null {
246 if (error instanceof Error) {
247 return error.message;
248 }
249 if (typeof error === "object" && error !== null && "message" in error) {
250 return typeof error.message === "string" ? error.message : null;
251 }
252 return typeof error === "string" ? error : null;
253}
254
255/** Dispatch/auth rejections invalidate payloads; other typed failures may be disconnected transports and must retry. */
256export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
257 if (typeof error === "object" && error !== null && "_tag" in error) {
258 switch (error._tag) {
259 case "OrchestrationDispatchCommandError":
260 case "EnvironmentAuthorizationError":
261 return false;
262 case "ConnectionTransientError":
263 case "RpcClientError":
264 case "EnvironmentRpcUnavailableError":
265 case "EnvironmentNotRegisteredError":
266 return true;
267 default:
268 break;
269 }
270 }
271 return isTransportConnectionErrorMessage(errorMessage(error));
272}
273
274export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
275export type ThreadOutboxFailureAction = "retry" | "restore";
276
277export function resolveThreadOutboxFailureAction(input: {
278 readonly stage: ThreadOutboxCommandStage;
279 readonly error: unknown;
280 readonly interrupted: boolean;
281}): ThreadOutboxFailureAction {
282 if (
283 input.stage === "settings-sync" ||
284 input.interrupted ||
285 shouldRetryThreadOutboxDelivery(input.error)
286 ) {
287 return "retry";
288 }
289 return "restore";
290}