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

thread-outbox-model.ts

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