Open History to see the last commit
1import type { PreviewAnnotationPayload } from "@t3tools/contracts";
2import { create } from "zustand";
3
4import type { ComposerSubmissionIntent } from "./composer-logic";
5import type { ComposerFileAttachment, ComposerImageAttachment } from "./composerDraftStore";
6import type { TerminalContextDraft } from "./lib/terminalContext";
7import { randomUUID } from "./lib/utils";
8import type { ReviewCommentContext } from "./reviewCommentContext";
9
10/**
11 * A composer submission held back while the thread's turn is running. It
12 * carries the full draft snapshot so the send path can dispatch it later with
13 * the same text, attachments, and contexts the user pressed Enter on.
14 */
15export interface QueuedComposerMessage {
16 id: string;
17 prompt: string;
18 images: ComposerImageAttachment[];
19 files: ComposerFileAttachment[];
20 terminalContexts: TerminalContextDraft[];
21 previewAnnotations: PreviewAnnotationPayload[];
22 reviewComments: ReviewCommentContext[];
23 submissionIntent: ComposerSubmissionIntent;
24 /**
25 * The newest completed tool activity at queue time. A different id later
26 * means a tool call finished after the user queued, which is the boundary
27 * the message goes out on.
28 */
29 queuedAfterToolActivityId: string | null;
30 /**
31 * Set when the message was created by Stop or a failed restore, not by the
32 * user pressing send. It waits for Send now instead of leaving on its own.
33 */
34 holdUntilUserAction?: boolean;
35 createdAt: string;
36}
37
38interface QueuedMessageStoreState {
39 queuesByThreadKey: Record<string, QueuedComposerMessage[]>;
40 /**
41 * Bumped by `drain`. A send that took a message before a drain and finishes
42 * its upload after it compares this to the value it captured and gives up,
43 * so Stop cannot be followed by a queued message starting a new turn.
44 */
45 drainGeneration: number;
46 enqueue: (threadKey: string, message: Omit<QueuedComposerMessage, "id">) => QueuedComposerMessage;
47 /**
48 * Removes one message and returns it, or null when another caller already
49 * took it. The remaining messages are re-anchored to `toolActivityId` so
50 * only one queued message leaves per tool boundary.
51 */
52 take: (
53 threadKey: string,
54 id: string,
55 toolActivityId: string | null,
56 ) => QueuedComposerMessage | null;
57 /** Removes one message without touching the others' anchors. Null when already gone. */
58 remove: (threadKey: string, id: string) => QueuedComposerMessage | null;
59 /**
60 * Puts a message back at the head, held for user action. Used when its
61 * send failed: the queue keeps its order and nothing behind it overtakes.
62 */
63 holdAtFront: (threadKey: string, message: QueuedComposerMessage) => void;
64 /** Removes and returns every queued message for the thread, oldest first. */
65 drain: (threadKey: string) => QueuedComposerMessage[];
66}
67
68const EMPTY_QUEUE: QueuedComposerMessage[] = [];
69
70/** In-memory only: a queued message is a live intent, not a draft worth persisting. */
71export const useQueuedMessageStore = create<QueuedMessageStoreState>()((set, get) => ({
72 queuesByThreadKey: {},
73 drainGeneration: 0,
74 enqueue: (threadKey, message) => {
75 const entry: QueuedComposerMessage = { ...message, id: randomUUID() };
76 set((state) => ({
77 queuesByThreadKey: {
78 ...state.queuesByThreadKey,
79 [threadKey]: [...(state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE), entry],
80 },
81 }));
82 return entry;
83 },
84 take: (threadKey, id, toolActivityId) => {
85 const queue = get().queuesByThreadKey[threadKey];
86 const entry = queue?.find((message) => message.id === id);
87 if (!queue || !entry) {
88 return null;
89 }
90 set((state) => {
91 const remaining = (state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE)
92 .filter((message) => message.id !== id)
93 .map((message) =>
94 message.queuedAfterToolActivityId === toolActivityId
95 ? message
96 : { ...message, queuedAfterToolActivityId: toolActivityId },
97 );
98 const queuesByThreadKey = { ...state.queuesByThreadKey };
99 if (remaining.length === 0) {
100 delete queuesByThreadKey[threadKey];
101 } else {
102 queuesByThreadKey[threadKey] = remaining;
103 }
104 return { queuesByThreadKey };
105 });
106 return entry;
107 },
108 remove: (threadKey, id) => {
109 const queue = get().queuesByThreadKey[threadKey];
110 const entry = queue?.find((message) => message.id === id);
111 if (!queue || !entry) {
112 return null;
113 }
114 set((state) => {
115 const remaining = (state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE).filter(
116 (message) => message.id !== id,
117 );
118 const queuesByThreadKey = { ...state.queuesByThreadKey };
119 if (remaining.length === 0) {
120 delete queuesByThreadKey[threadKey];
121 } else {
122 queuesByThreadKey[threadKey] = remaining;
123 }
124 return { queuesByThreadKey };
125 });
126 return entry;
127 },
128 holdAtFront: (threadKey, message) => {
129 set((state) => {
130 const rest = (state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE).filter(
131 (entry) => entry.id !== message.id,
132 );
133 return {
134 queuesByThreadKey: {
135 ...state.queuesByThreadKey,
136 [threadKey]: [{ ...message, holdUntilUserAction: true }, ...rest],
137 },
138 };
139 });
140 },
141 drain: (threadKey) => {
142 const queue = get().queuesByThreadKey[threadKey];
143 if (!queue || queue.length === 0) {
144 return EMPTY_QUEUE;
145 }
146 set((state) => {
147 const queuesByThreadKey = { ...state.queuesByThreadKey };
148 delete queuesByThreadKey[threadKey];
149 return { queuesByThreadKey, drainGeneration: state.drainGeneration + 1 };
150 });
151 return queue;
152 },
153}));
154
155/**
156 * The newest finished tool call. Its id changing is the boundary a queued
157 * message goes out on. Live arrays are sorted, but a snapshot loaded from the
158 * database is not, so pick by sequence rather than position.
159 */
160export function latestCompletedToolActivityId(
161 activities: ReadonlyArray<{
162 readonly id: string;
163 readonly kind: string;
164 readonly sequence?: number | undefined;
165 readonly createdAt: string;
166 }>,
167): string | null {
168 let latest: (typeof activities)[number] | null = null;
169 for (const activity of activities) {
170 if (activity.kind !== "tool.completed") continue;
171 if (
172 latest === null ||
173 (activity.sequence ?? -1) > (latest.sequence ?? -1) ||
174 ((activity.sequence ?? -1) === (latest.sequence ?? -1) &&
175 activity.createdAt > latest.createdAt)
176 ) {
177 latest = activity;
178 }
179 }
180 return latest?.id ?? null;
181}
182
183/**
184 * A queued message is due mid-turn once a tool call finished after it was
185 * queued, and as soon as the turn is over otherwise. "connecting" is the gap
186 * between a send and the provider picking it up, so nothing is due there.
187 */
188export function isQueuedMessageDue(input: {
189 message: Pick<QueuedComposerMessage, "queuedAfterToolActivityId" | "holdUntilUserAction">;
190 phase: "connecting" | "running" | "ready" | "disconnected";
191 latestToolActivityId: string | null;
192}): boolean {
193 if (input.message.holdUntilUserAction) return false;
194 if (input.phase === "connecting") return false;
195 if (input.phase !== "running") return true;
196 return input.latestToolActivityId !== input.message.queuedAfterToolActivityId;
197}
198
199export function useQueuedMessages(threadKey: string): QueuedComposerMessage[] {
200 return useQueuedMessageStore((state) => state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE);
201}