Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

thread-outbox-model.ts

310 lines11.5 KB

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