Open History to see the last commit
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;
26}
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 * Set when the message was created by Stop or a failed restore, not by the
44 * user pressing send. It waits for Send now instead of leaving on its own.
45 */
46 holdUntilUserAction?: boolean;
47 /**
48 * Set while a send is under way; the row stays until it settles. Stop can
49 * still take a "preparing" message back (uploads, thread settings), but not
50 * a "dispatching" one, whose turn start is already on the wire.
51 */
52 sending?: "preparing" | "dispatching";
53 createdAt: string;
54}
55
56/**
57 * The thread as it was when its last queued turn start went out. The next
58 * message waits until the server has moved past it, so a send that starts a
59 * new turn and the message after it do not leave on one boundary.
60 */
61interface QueuedDispatch {
62 /** The message that went out, or null for a dispatch restored after a failure. */
63 messageId: string | null;
64 thread: LocalDispatchSnapshot;
65 /** The dispatch this one replaced. If this send fails, that one still counts. */
66 previous: LocalDispatchSnapshot | null;
67}
68
69interface QueuedMessageStoreState {
70 queuesByThreadKey: Record<string, QueuedComposerMessage[]>;
71 lastDispatchByThreadKey: Record<string, QueuedDispatch>;
72 enqueue: (threadKey: string, message: Omit<QueuedComposerMessage, "id">) => QueuedComposerMessage;
73 /**
74 * Marks one message as sending and returns it, or null when it is gone or
75 * the thread already has a send under way.
76 */
77 beginSend: (threadKey: string, id: string) => QueuedComposerMessage | null;
78 /** The turn start is going out. False when Stop took the message back first. */
79 markDispatching: (threadKey: string, id: string, thread: LocalDispatchSnapshot) => boolean;
80 /** Drops a message whose send went out, or that had nothing left to send. */
81 finishSend: (threadKey: string, id: string) => void;
82 /**
83 * Moves a message whose send failed back to the head, held for user action.
84 * The queue keeps its order and nothing behind it overtakes. False when
85 * Stop already took the message back.
86 */
87 failSend: (threadKey: string, id: string) => boolean;
88 /** Removes one message without touching the others' anchors. Null when gone or sending. */
89 remove: (threadKey: string, id: string) => QueuedComposerMessage | null;
90 /** Removes and returns every message for the thread that is not already on the wire. */
91 drain: (threadKey: string) => QueuedComposerMessage[];
92}
93
94const EMPTY_QUEUE: QueuedComposerMessage[] = [];
95
96type QueueState = Pick<QueuedMessageStoreState, "queuesByThreadKey" | "lastDispatchByThreadKey">;
97
98/** Replaces one thread's queue. `lastDispatch` null forgets it; an empty queue always does. */
99function withQueue(
100 state: QueueState,
101 threadKey: string,
102 queue: QueuedComposerMessage[],
103 lastDispatch?: QueuedDispatch | null,
104): QueueState {
105 const queuesByThreadKey = { ...state.queuesByThreadKey, [threadKey]: queue };
106 const lastDispatchByThreadKey = { ...state.lastDispatchByThreadKey };
107 if (lastDispatch) lastDispatchByThreadKey[threadKey] = lastDispatch;
108 if (queue.length === 0) delete queuesByThreadKey[threadKey];
109 if (queue.length === 0 || lastDispatch === null) delete lastDispatchByThreadKey[threadKey];
110 return { queuesByThreadKey, lastDispatchByThreadKey };
111}
112
113/** In-memory only: a queued message is a live intent, not a draft worth persisting. */
114export const useQueuedMessageStore = create<QueuedMessageStoreState>()((set, get) => {
115 const queueOf = (threadKey: string) => get().queuesByThreadKey[threadKey] ?? EMPTY_QUEUE;
116 const update = (
117 threadKey: string,
118 queue: QueuedComposerMessage[],
119 lastDispatch?: QueuedDispatch | null,
120 ) => set((state) => withQueue(state, threadKey, queue, lastDispatch));
121 return {
122 queuesByThreadKey: {},
123 lastDispatchByThreadKey: {},
124 enqueue: (threadKey, message) => {
125 const entry: QueuedComposerMessage = { ...message, id: randomUUID() };
126 update(threadKey, [...queueOf(threadKey), entry]);
127 return entry;
128 },
129 beginSend: (threadKey, id) => {
130 const queue = queueOf(threadKey);
131 const entry = queue.find((message) => message.id === id);
132 if (!entry || queue.some((message) => message.sending)) return null;
133 update(
134 threadKey,
135 queue.map((message) =>
136 message.id === id ? { ...message, sending: "preparing" } : message,
137 ),
138 );
139 return entry;
140 },
141 markDispatching: (threadKey, id, thread) => {
142 const queue = queueOf(threadKey);
143 if (!queue.some((message) => message.id === id && message.sending)) return false;
144 update(
145 threadKey,
146 queue.map((message) =>
147 message.id === id ? { ...message, sending: "dispatching" } : message,
148 ),
149 {
150 messageId: id,
151 thread,
152 previous: get().lastDispatchByThreadKey[threadKey]?.thread ?? null,
153 },
154 );
155 return true;
156 },
157 finishSend: (threadKey, id) => {
158 const queue = queueOf(threadKey);
159 if (!queue.some((message) => message.id === id)) return;
160 update(
161 threadKey,
162 queue.filter((message) => message.id !== id),
163 );
164 },
165 failSend: (threadKey, id) => {
166 const queue = queueOf(threadKey);
167 const entry = queue.find((message) => message.id === id);
168 if (!entry) return false;
169 const { sending: _sending, ...rest } = entry;
170 // This send never reached the server, so only an earlier one is worth
171 // waiting for.
172 const dispatch = get().lastDispatchByThreadKey[threadKey];
173 update(
174 threadKey,
175 [{ ...rest, holdUntilUserAction: true }, ...queue.filter((message) => message.id !== id)],
176 dispatch?.messageId !== id
177 ? undefined
178 : dispatch.previous && { messageId: null, thread: dispatch.previous, previous: null },
179 );
180 return true;
181 },
182 remove: (threadKey, id) => {
183 const queue = queueOf(threadKey);
184 const entry = queue.find((message) => message.id === id);
185 if (!entry || entry.sending) return null;
186 update(
187 threadKey,
188 queue.filter((message) => message.id !== id),
189 );
190 return entry;
191 },
192 drain: (threadKey) => {
193 const queue = queueOf(threadKey);
194 const drained = queue.filter((message) => message.sending !== "dispatching");
195 if (drained.length === 0) return EMPTY_QUEUE;
196 update(
197 threadKey,
198 queue.filter((message) => message.sending === "dispatching"),
199 );
200 return drained;
201 },
202 };
203});
204
205/**
206 * Queued messages wait for the turn to end, then the oldest starts a new turn.
207 * "connecting" is the gap between a send and the provider picking it up, so
208 * nothing is due there either.
209 */
210export function isQueuedMessageDue(input: {
211 message: Pick<QueuedComposerMessage, "holdUntilUserAction">;
212 phase: "connecting" | "running" | "ready" | "disconnected";
213}): boolean {
214 return (
215 !input.message.holdUntilUserAction && input.phase !== "connecting" && input.phase !== "running"
216 );
217}
218
219export function useQueuedMessages(threadKey: string): QueuedComposerMessage[] {
220 return useQueuedMessageStore((state) => state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE);
221}