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

thread-outbox-model.ts

300 lines10.8 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 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 compactBeforeSend: Schema.optional(Schema.Boolean),
60 freshContext: Schema.optional(Schema.Boolean),
61 runtimeMode: Schema.optional(RuntimeMode),
62 interactionMode: Schema.optional(ProviderInteractionMode),
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;
78 readonly pullRequestReference?: string;
80​
81export interface QueuedThreadMessage {
82 readonly environmentId: EnvironmentId;
83 readonly threadId: ThreadId;
84 readonly messageId: MessageId;
85 readonly commandId: CommandId;
86 readonly text: string;
87 readonly context?: OrchestrationMessageContext;
88 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
89 readonly modelSelection?: ModelSelectionType;
90 readonly runtimeMode?: RuntimeModeType;
91 readonly interactionMode?: ProviderInteractionModeType;
92 /** Captured at enqueue because draining may occur long after the tap. */
93 readonly dispatchMode?: ComposerDispatchMode;
94 /** Sends "When you return"'s `/compact` ahead of the message, which queues behind it. */
95 readonly compactBeforeSend?: boolean;
96 /** Starts a new provider session (`/clear`). */
97 readonly freshContext?: boolean;
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 /**
184 * Set when the shell can leave idle subagent children out: absence alone is not deletion there,
185 * only a settled family read without the row is.
186 */
187 readonly familyRead?: ThreadFamilyRead;
188}): ThreadOutboxDeliveryAction {
189 if (input.isCreation) {
190 if (input.threadExists) {
191 return "remove";
192 }
193 // Wait for live shells; an unsynchronized list can hide delivered creations and cause duplicate re-issuance.
194 return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
195 }
196 if (!input.threadExists) {
197 return input.shellStatus === "live" &&
198 (input.familyRead === undefined || input.familyRead === "settled")
199 ? "remove"
200 : "wait";
201 }
202 return input.environmentConnected ? "send" : "wait";
204​
205export type ThreadOutboxDispatchStep =
206 | { readonly step: "wait" }
207 | { readonly step: "remove" }
208 | { readonly step: "retry" }
209 | { readonly step: "restore"; readonly reason: string }
210 | { readonly step: "send" };
211​
212export function resolveThreadOutboxDispatchStep(input: {
213 readonly deliveryAction: ThreadOutboxDeliveryAction;
214 readonly fileAttachments: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
215 readonly serverConfig: { readonly maxFileUploadBytes: number | undefined } | null;
216}): ThreadOutboxDispatchStep {
217 if (input.deliveryAction !== "send") {
218 return { step: input.deliveryAction };
219 }
220 if (input.serverConfig === null) {
221 return { step: "retry" };
222 }
223 if (input.fileAttachments.length === 0) {
224 return { step: "send" };
225 }
226 const maxBytes = input.serverConfig.maxFileUploadBytes;
227 if (maxBytes === undefined) {
228 return { step: "restore", reason: "This server does not support file attachments." };
229 }
230 const effectiveMaxBytes = clampFileAttachmentUploadBytes(maxBytes);
231 const oversized = input.fileAttachments.find(
232 (attachment) => attachment.sizeBytes > effectiveMaxBytes,
233 );
234 return oversized
235 ? { step: "restore", reason: fileAttachmentTooLargeMessage(oversized.name, effectiveMaxBytes) }
236 : { step: "send" };
238​
239export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
240 if (!message.creation) {
241 return false;
242 }
243 const hasContent = message.text.trim().length > 0 || message.attachments.length > 0;
244 if (!hasContent || message.modelSelection === undefined) {
245 return false;
246 }
247 return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
249​
250function errorMessage(error: unknown): string | null {
251 if (error instanceof Error) {
252 return error.message;
253 }
254 if (typeof error === "object" && error !== null && "message" in error) {
255 return typeof error.message === "string" ? error.message : null;
256 }
257 return typeof error === "string" ? error : null;
259​
260/** Dispatch/auth rejections invalidate payloads; other typed failures may be disconnected transports and must retry. */
261export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
262 if (typeof error === "object" && error !== null && "_tag" in error) {
263 switch (error._tag) {
264 case "OrchestrationDispatchCommandError":
265 case "EnvironmentAuthorizationError":
266 return false;
267 case "ConnectionTransientError":
268 case "RpcClientError":
269 case "EnvironmentRpcUnavailableError":
270 case "EnvironmentNotRegisteredError":
271 return true;
272 default:
273 break;
274 }
275 }
276 return isTransportConnectionErrorMessage(errorMessage(error));
278​
279export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
280export type ThreadOutboxFailureAction = "retry" | "restore";
281​
282export function resolveThreadOutboxFailureAction(input: {
283 readonly stage: ThreadOutboxCommandStage;
284 readonly error: unknown;
285 readonly interrupted: boolean;
286}): ThreadOutboxFailureAction {
287 if (
288 input.stage === "settings-sync" ||
289 input.interrupted ||
290 shouldRetryThreadOutboxDelivery(input.error)
291 ) {
292 return "retry";
293 }
294 return "restore";
296​
297export type AcknowledgedThreadMessage = QueuedThreadMessage & {
298 /** The server sequence that committed the message; older servers do not report it. */
299 readonly sequence?: number;
300};