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

thread-outbox-model.ts

231 lines8.0 KB

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 ThreadTurnDeliveryMode,
13 ThreadId,
14 type ModelSelection as ModelSelectionType,
15 type ProjectId as ProjectIdType,
16 type ProviderInteractionMode as ProviderInteractionModeType,
17 type RuntimeMode as RuntimeModeType,
18 type ThreadTurnDeliveryMode as ThreadTurnDeliveryModeType,
19} from "@t3tools/contracts";
20import * as Schema from "effect/Schema";
21​
22import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
23import type { DraftComposerImageAttachment } from "../lib/composerImages";
24import { scopedThreadKey } from "../lib/scopedEntities";
25​
26const THREAD_OUTBOX_SCHEMA_VERSION = 4;
27const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
28​
29const QueuedThreadCreationSchema = Schema.Struct({
30 projectId: ProjectId,
31 // Snapshot of the project's display metadata so a pending task stays
32 // presentable in the thread list even when the project shell is not loaded.
33 projectTitle: Schema.optional(Schema.String),
34 projectCwd: Schema.optional(Schema.String),
35 workspaceMode: Schema.Literals(["local", "worktree"]),
36 branch: Schema.NullOr(Schema.String),
37 worktreePath: Schema.NullOr(Schema.String),
38 startFromOrigin: Schema.optional(Schema.Boolean),
39});
40​
41export const QueuedThreadMessageSchema = Schema.Struct({
42 schemaVersion: Schema.Literals([1, 2, 3, THREAD_OUTBOX_SCHEMA_VERSION]),
43 environmentId: EnvironmentId,
44 threadId: ThreadId,
45 messageId: MessageId,
46 commandId: CommandId,
47 text: Schema.String,
48 attachments: Schema.Array(DraftComposerImageAttachmentSchema),
49 modelSelection: Schema.optional(ModelSelection),
50 runtimeMode: Schema.optional(RuntimeMode),
51 interactionMode: Schema.optional(ProviderInteractionMode),
52 deliveryMode: Schema.optional(ThreadTurnDeliveryMode),
53 // Present when the queued item creates a brand-new thread (pending task)
54 // instead of appending a turn to an existing one.
55 creation: Schema.optional(QueuedThreadCreationSchema),
56 createdAt: IsoDateTime,
57});
58​
59const decodeStoredQueuedThreadMessage = Schema.decodeUnknownSync(QueuedThreadMessageSchema);
60const encodeStoredQueuedThreadMessage = Schema.encodeUnknownSync(QueuedThreadMessageSchema);
61​
62export interface QueuedThreadCreation {
63 readonly projectId: ProjectIdType;
64 readonly projectTitle?: string;
65 readonly projectCwd?: string;
66 readonly workspaceMode: "local" | "worktree";
67 readonly branch: string | null;
68 readonly worktreePath: string | null;
69 readonly startFromOrigin?: boolean;
71​
72export interface QueuedThreadMessage {
73 readonly environmentId: EnvironmentId;
74 readonly threadId: ThreadId;
75 readonly messageId: MessageId;
76 readonly commandId: CommandId;
77 readonly text: string;
78 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
79 readonly modelSelection?: ModelSelectionType;
80 readonly runtimeMode?: RuntimeModeType;
81 readonly interactionMode?: ProviderInteractionModeType;
82 readonly deliveryMode?: ThreadTurnDeliveryModeType;
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​
179/**
180 * A queued creation can only be dispatched once its payload would pass server
181 * validation; incomplete payloads stay pending until the user edits them.
182 */
183export function isQueuedThreadCreationSendable(message: QueuedThreadMessage): boolean {
184 if (!message.creation) {
185 return false;
186 }
187 if (message.text.trim().length === 0 || message.modelSelection === undefined) {
188 return false;
189 }
190 return message.creation.workspaceMode !== "worktree" || Boolean(message.creation.branch);
192​
193function errorMessage(error: unknown): string | null {
194 if (error instanceof Error) {
195 return error.message;
196 }
197 if (typeof error === "object" && error !== null && "message" in error) {
198 return typeof error.message === "string" ? error.message : null;
199 }
200 return typeof error === "string" ? error : null;
202​
203export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
204 if (
205 typeof error === "object" &&
206 error !== null &&
207 "_tag" in error &&
208 error._tag === "ConnectionTransientError"
209 ) {
210 return true;
211 }
212 return isTransportConnectionErrorMessage(errorMessage(error));
214​
215export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
216export type ThreadOutboxFailureAction = "retry" | "discard";
217​
218export function resolveThreadOutboxFailureAction(input: {
219 readonly stage: ThreadOutboxCommandStage;
220 readonly error: unknown;
221 readonly interrupted: boolean;
222}): ThreadOutboxFailureAction {
223 if (
224 input.stage === "settings-sync" ||
225 input.interrupted ||
226 shouldRetryThreadOutboxDelivery(input.error)
227 ) {
228 return "retry";
229 }
230 return "discard";