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

thread-outbox-model.ts

291 lines10.3 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 projectTitle: Schema.optional(Schema.String),
39 projectCwd: Schema.optional(Schema.String),
40 workspaceMode: Schema.Literals(["local", "worktree"]),
41 branch: Schema.NullOr(Schema.String),
42 worktreePath: Schema.NullOr(Schema.String),
43 startFromOrigin: Schema.optional(Schema.Boolean),
44 pullRequestReference: Schema.optional(Schema.String),
45});
46​
47export const QueuedThreadMessageSchema = Schema.Struct({
48 schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION, 4]),
49 environmentId: EnvironmentId,
50 threadId: ThreadId,
51 messageId: MessageId,
52 commandId: CommandId,
53 text: Schema.String,
54 context: Schema.optional(OrchestrationMessageContext),
55 attachments: Schema.Array(DraftComposerAttachmentSchema),
56 modelSelection: Schema.optional(ModelSelection),
57 dispatchMode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
58 runtimeMode: Schema.optional(RuntimeMode),
59 interactionMode: Schema.optional(ProviderInteractionMode),
60 creation: Schema.optional(QueuedThreadCreationSchema),
61 createdAt: IsoDateTime,
62});
63​
64const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema);
65const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema);
66​
67export interface QueuedThreadCreation {
68 readonly projectId: ProjectIdType;
69 readonly projectTitle?: string;
70 readonly projectCwd?: string;
71 readonly workspaceMode: "local" | "worktree";
72 readonly branch: string | null;
73 readonly worktreePath: string | null;
74 readonly startFromOrigin?: boolean;
75 readonly pullRequestReference?: string;
77​
78export interface QueuedThreadMessage {
79 readonly environmentId: EnvironmentId;
80 readonly threadId: ThreadId;
81 readonly messageId: MessageId;
82 readonly commandId: CommandId;
83 readonly text: string;
84 readonly context?: OrchestrationMessageContext;
85 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
86 readonly modelSelection?: ModelSelectionType;
87 readonly runtimeMode?: RuntimeModeType;
88 readonly interactionMode?: ProviderInteractionModeType;
89 /**
90 * Captured at enqueue time because the drain can fire long after the tap.
91 */
92 readonly dispatchMode?: ComposerDispatchMode;
93 readonly creation?: QueuedThreadCreation;
94 readonly createdAt: string;
96​
97export interface ThreadSettingsSnapshot {
98 readonly modelSelection: ModelSelectionType;
99 readonly runtimeMode: RuntimeModeType;
100 readonly interactionMode: ProviderInteractionModeType;
102​
103export function resolveQueuedThreadSettings(
104 message: QueuedThreadMessage,
105 thread: ThreadSettingsSnapshot,
106 providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "showInteractionModeToggle">> = [],
107): ThreadSettingsSnapshot {
108 const modelSelection = message.modelSelection ?? thread.modelSelection;
109 const provider = providers.find(
110 (candidate) => candidate.instanceId === modelSelection.instanceId,
111 );
112 return {
113 modelSelection,
114 runtimeMode: message.runtimeMode ?? thread.runtimeMode,
115 interactionMode: resolveProviderInteractionMode(
116 provider,
117 message.interactionMode ?? thread.interactionMode,
118 ),
119 };
121​
122export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
123 return (
124 left.instanceId === right.instanceId &&
125 left.model === right.model &&
126 JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
127 );
129​
130export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
131 return encodeStoredQueuedThreadMessage({
132 schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
133 ...message,
134 });
136​
137export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage {
138 const { schemaVersion: _, ...message } = decodeStoredQueuedThreadMessage(value);
139 return message;
141​
142export function groupQueuedThreadMessages(
143 messages: ReadonlyArray<QueuedThreadMessage>,
144): Record<string, ReadonlyArray<QueuedThreadMessage>> {
145 const deduplicated = new Map<MessageId, QueuedThreadMessage>();
146 for (const message of messages) {
147 deduplicated.set(message.messageId, message);
148 }
149​
150 const grouped: Record<string, Array<QueuedThreadMessage>> = {};
151 for (const message of deduplicated.values()) {
152 const threadKey = scopedThreadKey(message.environmentId, message.threadId);
153 (grouped[threadKey] ??= []).push(message);
154 }
155 for (const queue of Object.values(grouped)) {
156 queue.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
157 }
158 return grouped;
160​
161export function flattenQueuedThreadMessages(
162 queues: Record<string, ReadonlyArray<QueuedThreadMessage>>,
163): ReadonlyArray<QueuedThreadMessage> {
164 return Object.values(queues).flat();
166​
167export function threadOutboxRetryDelayMs(attempt: number): number {
168 return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), THREAD_OUTBOX_MAX_RETRY_DELAY_MS);
170​
171export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send";
172​
173export function resolveThreadOutboxDeliveryAction(input: {
174 readonly isCreation: boolean;
175 readonly threadExists: boolean;
176 readonly shellStatus: EnvironmentShellStatus;
177 readonly environmentConnected: boolean;
178 readonly threadBusy: boolean;
179}): ThreadOutboxDeliveryAction {
180 if (input.isCreation) {
181 if (input.threadExists) {
182 return "remove";
183 }
184 // Wait for the shell to be live before sending: until the thread list has
185 // synchronized, a previously delivered creation whose cleanup failed would
186 // look missing and get re-issued, duplicating the thread.
187 return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
188 }
189 if (!input.threadExists) {
190 return input.shellStatus === "live" ? "remove" : "wait";
191 }
192 return input.environmentConnected ? "send" : "wait";
194​
195export type ThreadOutboxDispatchStep =
196 | { readonly step: "wait" }
197 | { readonly step: "remove" }
198 | { readonly step: "retry" }
199 | { readonly step: "restore"; readonly reason: string }
200 | { readonly step: "send" };
201​
202export function resolveThreadOutboxDispatchStep(input: {
203 readonly deliveryAction: ThreadOutboxDeliveryAction;
204 readonly fileAttachments: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
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​
229export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
230 if (!message.creation) {
231 return false;
232 }
233 const hasContent = message.text.trim().length > 0 || message.attachments.length > 0;
234 if (!hasContent || message.modelSelection === undefined) {
235 return false;
236 }
237 return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
239​
240function errorMessage(error: unknown): string | null {
241 if (error instanceof Error) {
242 return error.message;
243 }
244 if (typeof error === "object" && error !== null && "message" in error) {
245 return typeof error.message === "string" ? error.message : null;
246 }
247 return typeof error === "string" ? error : null;
249​
250/**
251 * Only a failure the server actually decided (`OrchestrationDispatchCommandError`,
252 * or an authorization rejection) means the payload itself is bad. The other typed
253 * failures a queued send can hit are transport-shaped: a socket that dropped
254 * mid-request (`RpcClientError` wrapping a Socket read/write/close reason), or an
255 * environment that is not connected or not registered.
256 */
257export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
258 if (typeof error === "object" && error !== null && "_tag" in error) {
259 switch (error._tag) {
260 case "OrchestrationDispatchCommandError":
261 case "EnvironmentAuthorizationError":
262 return false;
263 case "ConnectionTransientError":
264 case "RpcClientError":
265 case "EnvironmentRpcUnavailableError":
266 case "EnvironmentNotRegisteredError":
267 return true;
268 default:
269 break;
270 }
271 }
272 return isTransportConnectionErrorMessage(errorMessage(error));
274​
275export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
276export type ThreadOutboxFailureAction = "retry" | "restore";
277​
278export function resolveThreadOutboxFailureAction(input: {
279 readonly stage: ThreadOutboxCommandStage;
280 readonly error: unknown;
281 readonly interrupted: boolean;
282}): ThreadOutboxFailureAction {
283 if (
284 input.stage === "settings-sync" ||
285 input.interrupted ||
286 shouldRetryThreadOutboxDelivery(input.error)
287 ) {
288 return "retry";
289 }
290 return "restore";