Skip to content

Commit 37ab796

Browse files
t3dotggclaude
andcommitted
fix(web): queued messages send while their thread is not open
Only the mounted ChatView drained the queue, and only one ChatView is mounted at a time. A message queued on thread A sat idle after switching to thread B, and went out only on return. A root-level QueuedMessageSender now watches every thread that has a queue and sends through one shared sendQueuedMessage, used by both the watcher and Send now. Queued messages carry the model and modes from queue time, so the send no longer reads the live composer. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent a21b42c commit 37ab796

11 files changed

Lines changed: 834 additions & 299 deletions

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 44 additions & 145 deletions
Large diffs are not rendered by default.
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
2+
import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
3+
import * as Cause from "effect/Cause";
4+
import { act, createElement } from "react";
5+
import { create, type ReactTestRenderer } from "react-test-renderer";
6+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7+
8+
import { useQueuedMessageStore, type QueuedComposerMessage } from "../queuedMessageStore";
9+
import { sendQueuedMessage } from "./chat/sendQueuedMessage";
10+
import { QueuedMessageSender } from "./QueuedMessageSender";
11+
12+
const io = vi.hoisted(() => ({
13+
run: vi.fn(),
14+
upload: vi.fn(),
15+
toast: vi.fn(),
16+
thread: null as unknown,
17+
shell: { runtimeMode: "full-access", interactionMode: "default" } as Record<string, unknown>,
18+
}));
19+
const config = {
20+
environment: { capabilities: { attachmentUploads: true, inlineMessageContext: true } },
21+
};
22+
vi.mock("@t3tools/client-runtime/state/runtime", async (load) => ({
23+
...(await load<typeof import("@t3tools/client-runtime/state/runtime")>()),
24+
runAtomCommand: (...args: unknown[]) => io.run(...args),
25+
}));
26+
vi.mock("../rpc/atomRegistry", () => ({
27+
appAtomRegistry: { get: () => new Map([["env-a", config]]) },
28+
}));
29+
vi.mock("../state/server", () => ({ environmentServerConfigsAtom: {} }));
30+
vi.mock("../state/threads", () => ({
31+
threadEnvironment: {
32+
updateMetadata: "metadata",
33+
setRuntimeMode: "runtime",
34+
setInteractionMode: "interaction",
35+
startTurn: "start",
36+
},
37+
}));
38+
vi.mock("../state/environments", () => ({
39+
useEnvironment: () => ({ connection: { phase: "connected" } }),
40+
}));
41+
vi.mock("../state/entities", () => ({
42+
useThread: () => io.thread,
43+
useThreadStatus: () => "live",
44+
useServerConfigs: () => new Map([["env-a", config]]),
45+
readThreadShell: () => io.shell,
46+
readThread: () => io.thread,
47+
}));
48+
vi.mock("./ui/toast", () => ({ toastManager: { add: (...args: unknown[]) => io.toast(...args) } }));
49+
vi.mock("../lib/attachmentUploadQueue", () => ({
50+
startAttachmentUpload: vi.fn(),
51+
awaitAttachmentUploads: (...args: unknown[]) => io.upload(...args),
52+
getUploadedAttachments: () => [
53+
{ type: "image", id: "uploaded", name: "a.png", mimeType: "image/png", sizeBytes: 4 },
54+
],
55+
releaseDraftAttachments: vi.fn(),
56+
}));
57+
58+
const threadRef = scopeThreadRef(EnvironmentId.make("env-a"), ThreadId.make("thread-a"));
59+
const threadKey = scopedThreadKey(threadRef);
60+
const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };
61+
62+
function enqueue(overrides: Partial<QueuedComposerMessage> = {}) {
63+
return useQueuedMessageStore.getState().enqueue(threadKey, {
64+
prompt: "follow up",
65+
images: [],
66+
files: [],
67+
terminalContexts: [],
68+
previewAnnotations: [],
69+
reviewComments: [],
70+
sendSettings: {
71+
modelSelection,
72+
runtimeMode: "full-access",
73+
interactionMode: "default",
74+
promptEffort: null,
75+
},
76+
queuedAfterToolActivityId: null,
77+
createdAt: "2026-09-25T00:00:00Z",
78+
...overrides,
79+
});
80+
}
81+
82+
const commandsRun = () => io.run.mock.calls.map((call) => call[1]);
83+
const queue = () => useQueuedMessageStore.getState().queuesByThreadKey[threadKey];
84+
85+
beforeEach(() => {
86+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
87+
useQueuedMessageStore.setState({ queuesByThreadKey: {}, lastDispatchByThreadKey: {} });
88+
io.thread = null;
89+
io.run.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
90+
io.upload.mockReset().mockResolvedValue(undefined);
91+
io.toast.mockReset();
92+
io.shell = {
93+
modelSelection,
94+
branch: null,
95+
runtimeMode: "full-access",
96+
interactionMode: "default",
97+
};
98+
});
99+
100+
afterEach(() => {
101+
vi.unstubAllGlobals();
102+
});
103+
104+
describe("QueuedMessageSender", () => {
105+
const thread = (
106+
status: string,
107+
{ toolActivityIds = [] as string[], userMessageIds = [] as string[] } = {},
108+
) => ({
109+
session: { status, activeTurnId: null, updatedAt: status },
110+
activities: toolActivityIds.map((id, index) => ({
111+
id,
112+
kind: "tool.completed",
113+
sequence: index,
114+
createdAt: "2026-09-25T00:00:01Z",
115+
})),
116+
messages: userMessageIds.map((id) => ({ id, role: "user" })),
117+
latestTurn: null,
118+
});
119+
let root: ReactTestRenderer | null = null;
120+
const render = () =>
121+
act(() => {
122+
if (root) root.update(createElement(QueuedMessageSender));
123+
else root = create(createElement(QueuedMessageSender));
124+
});
125+
afterEach(async () => {
126+
await act(() => root?.unmount());
127+
root = null;
128+
});
129+
130+
it("sends a queued message when the turn ends, with no chat view open", async () => {
131+
enqueue();
132+
io.thread = thread("running");
133+
await render();
134+
expect(commandsRun()).toEqual([]);
135+
136+
io.thread = thread("ready");
137+
await render();
138+
139+
expect(commandsRun()).toEqual(["start"]);
140+
expect(io.run.mock.calls[0]?.[2]).toMatchObject({
141+
environmentId: "env-a",
142+
input: { threadId: "thread-a", message: { text: "follow up" }, modelSelection },
143+
});
144+
expect(queue()).toBeUndefined();
145+
});
146+
147+
it("holds the next message until the server picks up the one before it", async () => {
148+
enqueue({ prompt: "first" });
149+
enqueue({ prompt: "second" });
150+
io.thread = thread("ready");
151+
await render();
152+
await render();
153+
expect(commandsRun()).toEqual(["start"]);
154+
155+
// The first message started a turn; the second waits for its next tool call.
156+
io.thread = thread("running", { userMessageIds: ["first"] });
157+
await render();
158+
expect(commandsRun()).toEqual(["start"]);
159+
io.thread = thread("running", { userMessageIds: ["first"], toolActivityIds: ["tool-1"] });
160+
await render();
161+
expect(commandsRun()).toEqual(["start", "start"]);
162+
});
163+
164+
it("moves on to the next message after a failed one is cancelled", async () => {
165+
io.run.mockResolvedValueOnce({ _tag: "Failure", cause: Cause.fail(new Error("offline")) });
166+
const first = enqueue({ prompt: "first" });
167+
enqueue({ prompt: "second" });
168+
io.thread = thread("ready");
169+
await render();
170+
expect(queue()?.[0]).toMatchObject({ prompt: "first", holdUntilUserAction: true });
171+
172+
await act(() => {
173+
useQueuedMessageStore.getState().remove(threadKey, first.id);
174+
});
175+
await render();
176+
177+
expect(commandsRun()).toEqual(["start", "start"]);
178+
expect(io.run.mock.calls[1]?.[2]).toMatchObject({ input: { message: { text: "second" } } });
179+
});
180+
});
181+
182+
describe("sendQueuedMessage", () => {
183+
it("saves a mode changed before queueing, then starts the turn", async () => {
184+
io.shell = { ...io.shell, runtimeMode: "approval-required" };
185+
const message = enqueue();
186+
187+
await sendQueuedMessage(threadRef, message.id);
188+
189+
expect(commandsRun()).toEqual(["runtime", "start"]);
190+
expect(io.run.mock.calls[1]?.[2]).toMatchObject({ input: { runtimeMode: "full-access" } });
191+
expect(queue()).toBeUndefined();
192+
});
193+
194+
it("gives a message back to Stop while its upload runs, without starting a turn", async () => {
195+
let finishUpload!: () => void;
196+
io.upload.mockReturnValue(new Promise<void>((resolve) => (finishUpload = resolve)));
197+
const image = {
198+
type: "image" as const,
199+
id: "image-1",
200+
name: "a.png",
201+
mimeType: "image/png",
202+
sizeBytes: 4,
203+
previewUrl: "data:image/png;base64,AAAA",
204+
file: new File(["AAAA"], "a.png", { type: "image/png" }),
205+
};
206+
const message = enqueue({ images: [image] });
207+
208+
const sending = sendQueuedMessage(threadRef, message.id);
209+
expect(useQueuedMessageStore.getState().drain(threadKey)).toHaveLength(1);
210+
finishUpload();
211+
await sending;
212+
213+
expect(commandsRun()).toEqual([]);
214+
expect(io.toast).not.toHaveBeenCalled();
215+
expect(queue()).toBeUndefined();
216+
});
217+
218+
it("holds a message at the head when the turn start fails", async () => {
219+
io.run.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("offline")) });
220+
enqueue({ prompt: "first" });
221+
const second = enqueue({ prompt: "second" });
222+
223+
await sendQueuedMessage(threadRef, second.id);
224+
225+
expect(queue()?.map((entry) => [entry.prompt, entry.holdUntilUserAction])).toEqual([
226+
["second", true],
227+
["first", undefined],
228+
]);
229+
expect(io.toast).toHaveBeenCalledWith(expect.objectContaining({ description: "offline" }));
230+
});
231+
});
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
2+
import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
3+
import { useEffect, useMemo } from "react";
4+
import { useShallow } from "zustand/react/shallow";
5+
6+
import { useComposerDraftStore } from "../composerDraftStore";
7+
import {
8+
isQueuedMessageDue,
9+
latestCompletedToolActivityId,
10+
useQueuedMessageStore,
11+
useQueuedMessages,
12+
} from "../queuedMessageStore";
13+
import { derivePhase } from "../session-logic";
14+
import { useServerConfigs, useThread, useThreadStatus } from "../state/entities";
15+
import { useEnvironment } from "../state/environments";
16+
import { hasServerAcknowledgedLocalDispatch, latestTurnStartFailureId } from "./ChatView.logic";
17+
import { sendQueuedMessage } from "./chat/sendQueuedMessage";
18+
19+
/**
20+
* Sends queued messages when they are due, for every thread with a queue,
21+
* whether or not the thread is on screen. Mounted once at the root.
22+
*/
23+
export function QueuedMessageSender() {
24+
const threadKeys = useQueuedMessageStore(
25+
useShallow((state) => Object.keys(state.queuesByThreadKey)),
26+
);
27+
return threadKeys.map((threadKey) => <ThreadQueueSender key={threadKey} threadKey={threadKey} />);
28+
}
29+
30+
/**
31+
* Watches one thread while it has queued messages. Reading the thread keeps
32+
* its detail subscribed, so tool boundaries and the end of the turn are
33+
* visible while the user is elsewhere.
34+
*/
35+
function ThreadQueueSender({ threadKey }: { threadKey: string }) {
36+
const threadRef = useMemo(() => parseScopedThreadKey(threadKey), [threadKey]);
37+
const thread = useThread(threadRef);
38+
const threadStatus = useThreadStatus(threadRef);
39+
const environmentId = threadRef?.environmentId ?? null;
40+
const environment = useEnvironment(environmentId);
41+
const serverConfigs = useServerConfigs();
42+
const serverConfigLoaded = environmentId !== null && serverConfigs.has(environmentId);
43+
const rewinding = useComposerDraftStore((store) => store.rewindingThreadKeys.has(threadKey));
44+
const queue = useQueuedMessages(threadKey);
45+
const next = queue[0];
46+
const sending = queue.some((message) => message.sending);
47+
const activities = thread?.activities;
48+
const latestToolActivityId = useMemo(
49+
() => latestCompletedToolActivityId(activities ?? []),
50+
[activities],
51+
);
52+
const pendingRequests = useMemo(() => derivePendingRequests(activities ?? []), [activities]);
53+
const phase = derivePhase(thread?.session ?? null);
54+
55+
// A send that starts a new turn leaves the thread idle until the server
56+
// picks it up. Hold the next message until then, as the composer does for
57+
// its own sends.
58+
const lastDispatch = useQueuedMessageStore(
59+
(state) => state.lastDispatchByThreadKey[threadKey] ?? null,
60+
);
61+
const latestUserMessageId = thread?.messages.findLast((m) => m.role === "user")?.id ?? null;
62+
const waitingForServer =
63+
lastDispatch !== null &&
64+
!hasServerAcknowledgedLocalDispatch({
65+
localDispatch: lastDispatch,
66+
phase,
67+
latestTurn: thread?.latestTurn ?? null,
68+
latestUserMessageId,
69+
session: thread?.session ?? null,
70+
hasPendingApproval: pendingRequests.approvals.length > 0,
71+
hasPendingUserInput: pendingRequests.userInputs.length > 0,
72+
latestTurnStartFailureId: latestTurnStartFailureId(thread ?? undefined, latestUserMessageId),
73+
threadError: null,
74+
});
75+
76+
// Approvals and questions block the agent; a steer landing on top of them
77+
// would answer nothing and confuse the turn, so the queue holds until the
78+
// user resolves them.
79+
const blocked =
80+
threadRef === null ||
81+
thread === null ||
82+
threadStatus !== "live" ||
83+
(environment !== null && environment.connection.phase !== "connected") ||
84+
!serverConfigLoaded ||
85+
rewinding ||
86+
sending ||
87+
waitingForServer ||
88+
pendingRequests.approvals.length > 0 ||
89+
pendingRequests.userInputs.length > 0;
90+
const due =
91+
next !== undefined &&
92+
!blocked &&
93+
isQueuedMessageDue({ message: next, phase, latestToolActivityId });
94+
const nextId = next?.id;
95+
useEffect(() => {
96+
if (!due || !threadRef || nextId === undefined) return;
97+
void sendQueuedMessage(threadRef, nextId);
98+
}, [due, nextId, threadRef]);
99+
return null;
100+
}

‎apps/web/src/components/chat/MessagesTimeline.logic.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1100,7 +1100,12 @@ describe("deriveMessagesTimelineRows", () => {
11001100
terminalContexts: [],
11011101
previewAnnotations: [],
11021102
reviewComments: [],
1103-
submissionIntent: "foreground" as const,
1103+
sendSettings: {
1104+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
1105+
runtimeMode: "full-access" as const,
1106+
interactionMode: "default" as const,
1107+
promptEffort: null,
1108+
},
11041109
queuedAfterToolActivityId: null,
11051110
createdAt: "2026-01-01T00:00:01Z",
11061111
});

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1788,11 +1788,14 @@ function QueuedMessageTimelineRow({
17881788
queuedMessage.previewAnnotations.length +
17891789
queuedMessage.reviewComments.length;
17901790
const text = queuedMessage.prompt.trim();
1791-
const statusLabel = queuedMessage.holdUntilUserAction
1792-
? "Waits for Send now"
1793-
: row.isNext
1794-
? "Sends after the next tool call or when the turn ends"
1795-
: "Sends after the messages above it";
1791+
const sending = queuedMessage.sending !== undefined;
1792+
const statusLabel = sending
1793+
? "Sending to the agent"
1794+
: queuedMessage.holdUntilUserAction
1795+
? "Waits for Send now"
1796+
: row.isNext
1797+
? "Sends after the next tool call or when the turn ends"
1798+
: "Sends after the messages above it";
17961799
return (
17971800
<div className="flex flex-col items-end" data-queued-message-id={queuedMessage.id}>
17981801
<div className="max-w-[80%] rounded-2xl border border-dashed border-border p-3 text-message-foreground/80">
@@ -1820,14 +1823,14 @@ function QueuedMessageTimelineRow({
18201823
<Tooltip>
18211824
<TooltipTrigger
18221825
render={<span className="inline-flex h-6 items-center gap-1" />}
1823-
aria-label={`Queued. ${statusLabel}.`}
1826+
aria-label={`${sending ? "Sending" : "Queued"}. ${statusLabel}.`}
18241827
>
18251828
<ClockIcon className="size-3.5" aria-hidden />
1826-
Queued
1829+
{sending ? "Sending" : "Queued"}
18271830
</TooltipTrigger>
18281831
<TooltipPopup side="bottom">{statusLabel}</TooltipPopup>
18291832
</Tooltip>
1830-
<div className="ml-auto flex items-center gap-0.5">
1833+
<div className={cn("ml-auto flex items-center gap-0.5", sending && "invisible")}>
18311834
<Tooltip>
18321835
<TooltipTrigger
18331836
render={

0 commit comments

Comments
 (0)