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

thread-outbox-model.ts

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