Open History to see the last commit
1import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
2import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
3import {
4 CommandId,
5 EnvironmentId,
6 IsoDateTime,
7 MessageId,
8 ModelSelection,
9 ProjectId,
10 ProviderInteractionMode,
11 RuntimeMode,
12 ThreadId,
13 type ModelSelection as ModelSelectionType,
14 type ProjectId as ProjectIdType,
15 type ProviderInteractionMode as ProviderInteractionModeType,
16 type RuntimeMode as RuntimeModeType,
17} from "@t3tools/contracts";
18import * as Schema from "effect/Schema";
19
20import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
21import type { DraftComposerImageAttachment } from "../lib/composerImages";
22import { scopedThreadKey } from "../lib/scopedEntities";
23
24const THREAD_OUTBOX_SCHEMA_VERSION = 3;
25const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
26
27const QueuedThreadCreationSchema = Schema.Struct({
28 projectId: ProjectId,
29 // Snapshot of the project's display metadata so a pending task stays
30 // presentable in the thread list even when the project shell is not loaded.
31 projectTitle: Schema.optional(Schema.String),
32 projectCwd: Schema.optional(Schema.String),
33 workspaceMode: Schema.Literals(["local", "worktree"]),
34 branch: Schema.NullOr(Schema.String),
35 worktreePath: Schema.NullOr(Schema.String),
36 startFromOrigin: Schema.optional(Schema.Boolean),
37});
38
39export const QueuedThreadMessageSchema = Schema.Struct({
40 schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION]),
41 environmentId: EnvironmentId,
42 threadId: ThreadId,
43 messageId: MessageId,
44 commandId: CommandId,
45 text: Schema.String,
46 attachments: Schema.Array(DraftComposerImageAttachmentSchema),
47 modelSelection: Schema.optional(ModelSelection),
48 runtimeMode: Schema.optional(RuntimeMode),
49 interactionMode: Schema.optional(ProviderInteractionMode),
50 // Present when the queued item creates a brand-new thread (pending task)
51 // instead of appending a turn to an existing one.
52 creation: Schema.optional(QueuedThreadCreationSchema),
53 createdAt: IsoDateTime,
54});
55
56const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema);
57const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema);
58
59export interface QueuedThreadCreation {
60 readonly projectId: ProjectIdType;
61 readonly projectTitle?: string;
62 readonly projectCwd?: string;
63 readonly workspaceMode: "local" | "worktree";
64 readonly branch: string | null;
65 readonly worktreePath: string | null;
66 readonly startFromOrigin?: boolean;
67}
68
69export interface QueuedThreadMessage {
70 readonly environmentId: EnvironmentId;
71 readonly threadId: ThreadId;
72 readonly messageId: MessageId;
73 readonly commandId: CommandId;
74 readonly text: string;
75 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
76 readonly modelSelection?: ModelSelectionType;
77 readonly runtimeMode?: RuntimeModeType;
78 readonly interactionMode?: ProviderInteractionModeType;
79 readonly creation?: QueuedThreadCreation;
80 readonly createdAt: string;
81}
82
83export interface ThreadSettingsSnapshot {
84 readonly modelSelection: ModelSelectionType;
85 readonly runtimeMode: RuntimeModeType;
86 readonly interactionMode: ProviderInteractionModeType;
87}
88
89export function resolveQueuedThreadSettings(
90 message: QueuedThreadMessage,
91 thread: ThreadSettingsSnapshot,
92): ThreadSettingsSnapshot {
93 return {
94 modelSelection: message.modelSelection ?? thread.modelSelection,
95 runtimeMode: message.runtimeMode ?? thread.runtimeMode,
96 interactionMode: message.interactionMode ?? thread.interactionMode,
97 };
98}
99
100export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
101 return (
102 left.instanceId === right.instanceId &&
103 left.model === right.model &&
104 JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
105 );
106}
107
108export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
109 return encodeStoredQueuedThreadMessage({
110 schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
111 ...message,
112 });
113}
114
115export function decodeQueuedThreadMessage(value: unknown): QueuedThreadMessage {
116 const { schemaVersion: _, ...message } = decodeStoredQueuedThreadMessage(value);
117 return message;
118}
119
120export function groupQueuedThreadMessages(
121 messages: ReadonlyArray<QueuedThreadMessage>,
122): Record<string, ReadonlyArray<QueuedThreadMessage>> {
123 const deduplicated = new Map<MessageId, QueuedThreadMessage>();
124 for (const message of messages) {
125 deduplicated.set(message.messageId, message);
126 }
127
128 const grouped: Record<string, Array<QueuedThreadMessage>> = {};
129 for (const message of deduplicated.values()) {
130 const threadKey = scopedThreadKey(message.environmentId, message.threadId);
131 (grouped[threadKey] ??= []).push(message);
132 }
133 for (const queue of Object.values(grouped)) {
134 queue.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
135 }
136 return grouped;
137}
138
139export function flattenQueuedThreadMessages(
140 queues: Record<string, ReadonlyArray<QueuedThreadMessage>>,
141): ReadonlyArray<QueuedThreadMessage> {
142 return Object.values(queues).flat();
143}
144
145export function threadOutboxRetryDelayMs(attempt: number): number {
146 return Math.min(1_000 * 2 ** Math.max(0, attempt - 1), THREAD_OUTBOX_MAX_RETRY_DELAY_MS);
147}
148
149export type ThreadOutboxDeliveryAction = "wait" | "remove" | "send";
150
151export function resolveThreadOutboxDeliveryAction(input: {
152 readonly isCreation: boolean;
153 readonly threadExists: boolean;
154 readonly shellStatus: EnvironmentShellStatus;
155 readonly environmentConnected: boolean;
156 readonly threadBusy: boolean;
157}): ThreadOutboxDeliveryAction {
158 if (input.isCreation) {
159 // A pending task creates its thread on delivery. If the thread already
160 // exists the creation command went through and only cleanup remains.
161 if (input.threadExists) {
162 return "remove";
163 }
164 // Wait for the shell to be live before sending: until the thread list has
165 // synchronized, a previously delivered creation whose cleanup failed would
166 // look missing and get re-issued, duplicating the thread.
167 return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";
168 }
169 if (!input.threadExists) {
170 return input.shellStatus === "live" ? "remove" : "wait";
171 }
172 return input.environmentConnected ? "send" : "wait";
173}
174
175/**
176 * A queued creation can only be dispatched once its payload would pass server
177 * validation; incomplete payloads stay pending until the user edits them.
178 */
179export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
180 if (!message.creation) {
181 return false;
182 }
183 if (message.text.trim().length === 0 || message.modelSelection === undefined) {
184 return false;
185 }
186 return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
187}
188
189function errorMessage(error: unknown): string | null {
190 if (error instanceof Error) {
191 return error.message;
192 }
193 if (typeof error === "object" && error !== null && "message" in error) {
194 return typeof error.message === "string" ? error.message : null;
195 }
196 return typeof error === "string" ? error : null;
197}
198
199export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
200 if (
201 typeof error === "object" &&
202 error !== null &&
203 "_tag" in error &&
204 error._tag === "ConnectionTransientError"
205 ) {
206 return true;
207 }
208 return isTransportConnectionErrorMessage(errorMessage(error));
209}
210
211export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
212export type ThreadOutboxFailureAction = "retry" | "discard";
213
214export function resolveThreadOutboxFailureAction(input: {
215 readonly stage: ThreadOutboxCommandStage;
216 readonly error: unknown;
217 readonly interrupted: boolean;
218}): ThreadOutboxFailureAction {
219 if (
220 input.stage === "settings-sync" ||
221 input.interrupted ||
222 shouldRetryThreadOutboxDelivery(input.error)
223 ) {
224 return "retry";
225 }
226 return "discard";
227}