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

queuedMessageStore.ts

266 lines10.1 KB

1import type {
2 ModelSelection,
3 PreviewAnnotationPayload,
4 ProviderInteractionMode,
5 RuntimeMode,
6} from "@t3tools/contracts";
7import { create } from "zustand";
8​
9import type { LocalDispatchSnapshot } from "./components/ChatView.logic";
10import type { ComposerFileAttachment, ComposerImageAttachment } from "./composerDraftStore";
11import type { TerminalContextDraft } from "./lib/terminalContext";
12import { randomUUID } from "./lib/utils";
13import type { ReviewCommentContext } from "./reviewCommentContext";
14​
15/**
16 * The composer's model and modes when the message was queued. The send uses
17 * these instead of the live composer, so it can go out while the user is on
18 * another thread.
19 */
20export interface QueuedMessageSendSettings {
21 modelSelection: ModelSelection;
22 runtimeMode: RuntimeMode;
23 interactionMode: ProviderInteractionMode;
24 /** Effort written into the prompt text, for providers that read it there. */
25 promptEffort: string | null;
27​
28/**
29 * A composer submission held back while the thread's turn is running. It
30 * carries the full draft snapshot so the send path can dispatch it later with
31 * the same text, attachments, and contexts the user pressed Enter on.
32 */
33export interface QueuedComposerMessage {
34 id: string;
35 prompt: string;
36 images: ComposerImageAttachment[];
37 files: ComposerFileAttachment[];
38 terminalContexts: TerminalContextDraft[];
39 previewAnnotations: PreviewAnnotationPayload[];
40 reviewComments: ReviewCommentContext[];
41 sendSettings: QueuedMessageSendSettings;
42 /**
43 * The newest completed tool activity at queue time. A different id later
44 * means a tool call finished after the user queued, which is the boundary
45 * the message goes out on.
46 */
47 queuedAfterToolActivityId: string | null;
48 /**
49 * Set when the message was created by Stop or a failed restore, not by the
50 * user pressing send. It waits for Send now instead of leaving on its own.
51 */
52 holdUntilUserAction?: boolean;
53 /**
54 * Set while a send is under way; the row stays until it settles. Stop can
55 * still take a "preparing" message back (uploads, thread settings), but not
56 * a "dispatching" one, whose turn start is already on the wire.
57 */
58 sending?: "preparing" | "dispatching";
59 createdAt: string;
61​
62/**
63 * The thread as it was when its last queued turn start went out. The next
64 * message waits until the server has moved past it, so a send that starts a
65 * new turn and the message after it do not leave on one boundary.
66 */
67interface QueuedDispatch {
68 /** The message that went out, or null for a dispatch restored after a failure. */
69 messageId: string | null;
70 thread: LocalDispatchSnapshot;
71 /** The dispatch this one replaced. If this send fails, that one still counts. */
72 previous: LocalDispatchSnapshot | null;
74​
75interface QueuedMessageStoreState {
76 queuesByThreadKey: Record<string, QueuedComposerMessage[]>;
77 lastDispatchByThreadKey: Record<string, QueuedDispatch>;
78 enqueue: (threadKey: string, message: Omit<QueuedComposerMessage, "id">) => QueuedComposerMessage;
79 /**
80 * Marks one message as sending and returns it, or null when it is gone or
81 * the thread already has a send under way. The other messages are
82 * re-anchored to `toolActivityId` so only one leaves per tool boundary.
83 */
84 beginSend: (
85 threadKey: string,
86 id: string,
87 toolActivityId: string | null,
88 ) => QueuedComposerMessage | null;
89 /** The turn start is going out. False when Stop took the message back first. */
90 markDispatching: (threadKey: string, id: string, thread: LocalDispatchSnapshot) => boolean;
91 /** Drops a message whose send went out, or that had nothing left to send. */
92 finishSend: (threadKey: string, id: string) => void;
93 /**
94 * Moves a message whose send failed back to the head, held for user action.
95 * The queue keeps its order and nothing behind it overtakes. False when
96 * Stop already took the message back.
97 */
98 failSend: (threadKey: string, id: string) => boolean;
99 /** Removes one message without touching the others' anchors. Null when gone or sending. */
100 remove: (threadKey: string, id: string) => QueuedComposerMessage | null;
101 /** Removes and returns every message for the thread that is not already on the wire. */
102 drain: (threadKey: string) => QueuedComposerMessage[];
104​
105const EMPTY_QUEUE: QueuedComposerMessage[] = [];
106​
107type QueueState = Pick<QueuedMessageStoreState, "queuesByThreadKey" | "lastDispatchByThreadKey">;
108​
109/** Replaces one thread's queue. `lastDispatch` null forgets it; an empty queue always does. */
110function withQueue(
111 state: QueueState,
112 threadKey: string,
113 queue: QueuedComposerMessage[],
114 lastDispatch?: QueuedDispatch | null,
115): QueueState {
116 const queuesByThreadKey = { ...state.queuesByThreadKey, [threadKey]: queue };
117 const lastDispatchByThreadKey = { ...state.lastDispatchByThreadKey };
118 if (lastDispatch) lastDispatchByThreadKey[threadKey] = lastDispatch;
119 if (queue.length === 0) delete queuesByThreadKey[threadKey];
120 if (queue.length === 0 || lastDispatch === null) delete lastDispatchByThreadKey[threadKey];
121 return { queuesByThreadKey, lastDispatchByThreadKey };
123​
124/** In-memory only: a queued message is a live intent, not a draft worth persisting. */
125export const useQueuedMessageStore = create<QueuedMessageStoreState>()((set, get) => {
126 const queueOf = (threadKey: string) => get().queuesByThreadKey[threadKey] ?? EMPTY_QUEUE;
127 const update = (
128 threadKey: string,
129 queue: QueuedComposerMessage[],
130 lastDispatch?: QueuedDispatch | null,
131 ) => set((state) => withQueue(state, threadKey, queue, lastDispatch));
132 return {
133 queuesByThreadKey: {},
134 lastDispatchByThreadKey: {},
135 enqueue: (threadKey, message) => {
136 const entry: QueuedComposerMessage = { ...message, id: randomUUID() };
137 update(threadKey, [...queueOf(threadKey), entry]);
138 return entry;
139 },
140 beginSend: (threadKey, id, toolActivityId) => {
141 const queue = queueOf(threadKey);
142 const entry = queue.find((message) => message.id === id);
143 if (!entry || queue.some((message) => message.sending)) return null;
144 update(
145 threadKey,
146 queue.map((message) =>
147 message.id === id
148 ? { ...message, sending: "preparing" }
149 : message.queuedAfterToolActivityId === toolActivityId
150 ? message
151 : { ...message, queuedAfterToolActivityId: toolActivityId },
152 ),
153 );
154 return entry;
155 },
156 markDispatching: (threadKey, id, thread) => {
157 const queue = queueOf(threadKey);
158 if (!queue.some((message) => message.id === id && message.sending)) return false;
159 update(
160 threadKey,
161 queue.map((message) =>
162 message.id === id ? { ...message, sending: "dispatching" } : message,
163 ),
164 {
165 messageId: id,
166 thread,
167 previous: get().lastDispatchByThreadKey[threadKey]?.thread ?? null,
168 },
169 );
170 return true;
171 },
172 finishSend: (threadKey, id) => {
173 const queue = queueOf(threadKey);
174 if (!queue.some((message) => message.id === id)) return;
175 update(
176 threadKey,
177 queue.filter((message) => message.id !== id),
178 );
179 },
180 failSend: (threadKey, id) => {
181 const queue = queueOf(threadKey);
182 const entry = queue.find((message) => message.id === id);
183 if (!entry) return false;
184 const { sending: _sending, ...rest } = entry;
185 // This send never reached the server, so only an earlier one is worth
186 // waiting for.
187 const dispatch = get().lastDispatchByThreadKey[threadKey];
188 update(
189 threadKey,
190 [{ ...rest, holdUntilUserAction: true }, ...queue.filter((message) => message.id !== id)],
191 dispatch?.messageId !== id
192 ? undefined
193 : dispatch.previous && { messageId: null, thread: dispatch.previous, previous: null },
194 );
195 return true;
196 },
197 remove: (threadKey, id) => {
198 const queue = queueOf(threadKey);
199 const entry = queue.find((message) => message.id === id);
200 if (!entry || entry.sending) return null;
201 update(
202 threadKey,
203 queue.filter((message) => message.id !== id),
204 );
205 return entry;
206 },
207 drain: (threadKey) => {
208 const queue = queueOf(threadKey);
209 const drained = queue.filter((message) => message.sending !== "dispatching");
210 if (drained.length === 0) return EMPTY_QUEUE;
211 update(
212 threadKey,
213 queue.filter((message) => message.sending === "dispatching"),
214 );
215 return drained;
216 },
217 };
218});
219​
220/**
221 * The newest finished tool call. Its id changing is the boundary a queued
222 * message goes out on. Live arrays are sorted, but a snapshot loaded from the
223 * database is not, so pick by sequence rather than position.
224 */
225export function latestCompletedToolActivityId(
226 activities: ReadonlyArray<{
227 readonly id: string;
228 readonly kind: string;
229 readonly sequence?: number | undefined;
230 readonly createdAt: string;
231 }>,
232): string | null {
233 let latest: (typeof activities)[number] | null = null;
234 for (const activity of activities) {
235 if (activity.kind !== "tool.completed") continue;
236 if (
237 latest === null ||
238 (activity.sequence ?? -1) > (latest.sequence ?? -1) ||
239 ((activity.sequence ?? -1) === (latest.sequence ?? -1) &&
240 activity.createdAt > latest.createdAt)
241 ) {
242 latest = activity;
243 }
244 }
245 return latest?.id ?? null;
247​
248/**
249 * A queued message is due mid-turn once a tool call finished after it was
250 * queued, and as soon as the turn is over otherwise. "connecting" is the gap
251 * between a send and the provider picking it up, so nothing is due there.
252 */
253export function isQueuedMessageDue(input: {
254 message: Pick<QueuedComposerMessage, "queuedAfterToolActivityId" | "holdUntilUserAction">;
255 phase: "connecting" | "running" | "ready" | "disconnected";
256 latestToolActivityId: string | null;
257}): boolean {
258 if (input.message.holdUntilUserAction) return false;
259 if (input.phase === "connecting") return false;
260 if (input.phase !== "running") return true;
261 return input.latestToolActivityId !== input.message.queuedAfterToolActivityId;
263​
264export function useQueuedMessages(threadKey: string): QueuedComposerMessage[] {
265 return useQueuedMessageStore((state) => state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE);