Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

fix: hold a send while a turn is in flight instead of opening a second one

Khuram Niaz745b08bddff0
diff --git a/__tests__/AgentChatInput.spec.tsx b/__tests__/AgentChatInput.spec.tsx
index 2d03a0a..78ec2a1 100644
--- a/__tests__/AgentChatInput.spec.tsx
+++ b/__tests__/AgentChatInput.spec.tsx
@@ -8,6 +8,8 @@ const chat = {
stop: vi.fn(),
status: "ready" as string,
approvalPending: false,
+ queued: undefined as any,
+ clearQueued: vi.fn(),
error: undefined as Error | undefined,
clearError: vi.fn(),
preflight: { checked: true, ok: true } as any,
@@ -34,6 +36,7 @@ describe("AgentChatInput", () => {
vi.clearAllMocks();
chat.status = "ready";
chat.approvalPending = false;
+ chat.queued = undefined;
chat.error = undefined;
chat.preflight = { checked: true, ok: true };
chat.composerNonce = 0;
@@ -105,77 +108,62 @@ describe("AgentChatInput", () => {
expect(parts.some((p: any) => p.type === AGENT_PASTE_PART_TYPE)).toBe(true);
});
- it("queues rather than sends while an approval is pending", async () => {
+ // Whether a send waits — for an approval, or for a reply already streaming —
+ // is the provider's call, because it is the only place that sees all five
+ // senders. A composer that second-guesses it disagrees with the resume
+ // page's Review button. Holding is covered in AgentChatProvider.spec.
+ it("delegates every send to the provider, approval pending or not", async () => {
chat.approvalPending = true;
render(<AgentChatInput />);
await userEvent.type(screen.getByRole("textbox"), "the company is wrong");
await userEvent.click(screen.getByRole("button", { name: /send/i }));
- expect(chat.sendMessage).not.toHaveBeenCalled();
- expect(screen.getByText(/waiting on your approval/i)).toBeInTheDocument();
- expect(screen.getByText(/the company is wrong/)).toBeInTheDocument();
- });
-
- it("keeps a new paste out of messages while the card is open — the paste-drift invariant", async () => {
- chat.approvalPending = true;
- render(<AgentChatInput />);
- await paste(long);
- await userEvent.click(screen.getByRole("button", { name: /send/i }));
- expect(chat.sendMessage).not.toHaveBeenCalled();
- });
-
- it("dispatches the queued message once the approval resolves", async () => {
- chat.approvalPending = true;
- const { rerender } = render(<AgentChatInput />);
- await userEvent.type(screen.getByRole("textbox"), "the company is wrong");
- await userEvent.click(screen.getByRole("button", { name: /send/i }));
- chat.approvalPending = false;
- rerender(<AgentChatInput />);
- expect(chat.sendMessage).toHaveBeenCalled();
+ expect(chat.sendMessage).toHaveBeenCalledTimes(1);
expect(chat.sendMessage.mock.calls[0][0].parts[0].text).toBe(
"the company is wrong",
);
});
- it("holds the queued message while the approval's follow-up POST is streaming", async () => {
- // approvalPending clears at the same instant sendAutomaticallyWhen fires
- // the POST that executes the approved tool. Dispatching on that render
- // would race it — the queue waits for status to return to ready.
- chat.approvalPending = true;
+ it("shows a held message and says what it is waiting for", () => {
+ chat.queued = { parts: [{ type: "text", text: "the company is wrong" }] };
const { rerender } = render(<AgentChatInput />);
- await userEvent.type(screen.getByRole("textbox"), "the company is wrong");
- await userEvent.click(screen.getByRole("button", { name: /send/i }));
- chat.approvalPending = false;
- chat.status = "streaming";
- rerender(<AgentChatInput />);
- expect(chat.sendMessage).not.toHaveBeenCalled();
- chat.status = "ready";
+ expect(screen.getByText(/current reply finishes/i)).toBeInTheDocument();
+ expect(screen.getByText(/the company is wrong/)).toBeInTheDocument();
+ chat.approvalPending = true;
rerender(<AgentChatInput />);
- expect(chat.sendMessage).toHaveBeenCalledTimes(1);
+ expect(screen.getByText(/waiting on your approval/i)).toBeInTheDocument();
});
- it("lets the user discard a queued message", async () => {
- chat.approvalPending = true;
+ it("labels a held paste-only message with its chip", () => {
+ chat.queued = {
+ parts: [
+ {
+ type: AGENT_PASTE_PART_TYPE,
+ id: "p1",
+ data: { id: "p1", text: "x", chars: 1234, truncated: false },
+ },
+ ],
+ };
+ render(<AgentChatInput />);
+ expect(screen.getByText(/pasted posting · 1,234 chars/i)).toBeInTheDocument();
+ });
+
+ it("hands the discard back to the provider", async () => {
+ chat.queued = { parts: [{ type: "text", text: "never mind" }] };
render(<AgentChatInput />);
- await userEvent.type(screen.getByRole("textbox"), "never mind");
- await userEvent.click(screen.getByRole("button", { name: /send/i }));
await userEvent.click(
screen.getByRole("button", { name: /remove from queue/i }),
);
- chat.approvalPending = false;
- expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(chat.clearQueued).toHaveBeenCalled();
});
it("empties the composer when the conversation is cleared", async () => {
- chat.approvalPending = true;
const { rerender } = render(<AgentChatInput />);
await paste(long);
await userEvent.type(screen.getByRole("textbox"), "never mind");
- await userEvent.click(screen.getByRole("button", { name: /send/i }));
chat.composerNonce = 1;
rerender(<AgentChatInput />);
expect(screen.getByRole("textbox")).toHaveValue("");
expect(screen.queryByText(/pasted/i)).not.toBeInTheDocument();
- expect(screen.queryByText(/queued/i)).not.toBeInTheDocument();
});
it("swaps send for stop while streaming", async () => {
diff --git a/__tests__/AgentChatProvider.spec.tsx b/__tests__/AgentChatProvider.spec.tsx
index 829a4ee..22cc2dd 100644
--- a/__tests__/AgentChatProvider.spec.tsx
+++ b/__tests__/AgentChatProvider.spec.tsx
@@ -60,9 +60,17 @@ function Probe() {
<button onClick={c.close}>close</button>
<button onClick={c.clear}>clear</button>
<button onClick={() => void c.regenerate()}>regenerate</button>
- <button onClick={() => void c.sendMessage({ parts: [] } as any)}>
+ <button
+ onClick={() =>
+ void c.sendMessage({ parts: [{ type: "text", text: "hello" }] } as any)
+ }
+ >
sendMessage
</button>
+ <button onClick={c.clearQueued}>clearQueued</button>
+ <span data-testid="queued">
+ {c.queued ? (c.queued.parts[0] as any).text : ""}
+ </span>
<button onClick={c.togglePanelExpand}>togglePanelExpand</button>
<button onClick={toggle}>toggleSidebar</button>
<span data-testid="sidebar">{String(expanded)}</span>
@@ -160,13 +168,18 @@ describe("AgentChatProvider", () => {
// The interrupted notice describes a turn that is no longer interrupted the
// moment the user resumes it, so it must not outlive the reply it asked for.
+ // close() aborts through stop(), so the chat is idle by the time the user
+ // sees the Continue button — the rerender is what the real status callback
+ // does here.
it("clears the interrupted flag when the turn is resumed with Continue", async () => {
chat.status = "streaming";
- setup();
+ const { rerender } = setup();
await userEvent.click(screen.getByText("open"));
await userEvent.click(screen.getByText("close"));
expect(screen.getByTestId("state").textContent).toContain("|true|");
+ chat.status = "ready";
+ rerender(tree());
await userEvent.click(screen.getByText("regenerate"));
expect(chat.regenerate).toHaveBeenCalled();
expect(screen.getByTestId("state").textContent).toContain(
@@ -176,11 +189,13 @@ describe("AgentChatProvider", () => {
it("clears the interrupted flag when the user sends a new message instead", async () => {
chat.status = "streaming";
- setup();
+ const { rerender } = setup();
await userEvent.click(screen.getByText("open"));
await userEvent.click(screen.getByText("close"));
expect(screen.getByTestId("state").textContent).toContain("|true|");
+ chat.status = "ready";
+ rerender(tree());
await userEvent.click(screen.getByText("sendMessage"));
expect(chat.sendMessage).toHaveBeenCalled();
expect(screen.getByTestId("state").textContent).toContain(
@@ -188,6 +203,93 @@ describe("AgentChatProvider", () => {
);
});
+ // The duplicate-key bug: a send during a live turn opened a second request,
+ // useChat aborted neither, and the two streams took turns appending copies
+ // of each other's message under the same id.
+ it("holds a send instead of opening a second overlapping request", async () => {
+ chat.status = "streaming";
+ setup();
+ await userEvent.click(screen.getByText("sendMessage"));
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(screen.getByTestId("queued").textContent).toBe("hello");
+ });
+
+ it("dispatches the held message once the turn finishes", async () => {
+ chat.status = "streaming";
+ const { rerender } = setup();
+ await userEvent.click(screen.getByText("sendMessage"));
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+
+ chat.status = "ready";
+ await act(async () => {
+ rerender(tree());
+ });
+ expect(chat.sendMessage).toHaveBeenCalledTimes(1);
+ expect(chat.sendMessage.mock.calls[0][0].parts[0].text).toBe("hello");
+ expect(screen.getByTestId("queued").textContent).toBe("");
+ });
+
+ it("holds a send while an approval is pending", async () => {
+ chat.messages = [approvalMessage];
+ setup([approvalMessage]);
+ await userEvent.click(screen.getByText("sendMessage"));
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(screen.getByTestId("queued").textContent).toBe("hello");
+ });
+
+ // approvalPending clears at the same instant sendAutomaticallyWhen fires the
+ // POST that executes the approved tool. Releasing on that alone would race
+ // it and cut the tool off mid-execution server-side.
+ it("keeps holding while the approval's follow-up POST is streaming", async () => {
+ chat.messages = [approvalMessage];
+ const { rerender } = setup([approvalMessage]);
+ await userEvent.click(screen.getByText("sendMessage"));
+
+ chat.messages = [];
+ chat.status = "streaming";
+ await act(async () => {
+ rerender(tree());
+ });
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+
+ chat.status = "ready";
+ await act(async () => {
+ rerender(tree());
+ });
+ expect(chat.sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it("drops a held message when the conversation is cleared", async () => {
+ chat.status = "streaming";
+ const { rerender } = setup();
+ await userEvent.click(screen.getByText("sendMessage"));
+ await userEvent.click(screen.getByText("clear"));
+
+ chat.status = "ready";
+ await act(async () => {
+ rerender(tree());
+ });
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(screen.getByTestId("queued").textContent).toBe("");
+ });
+
+ it("lets the held message be discarded", async () => {
+ chat.status = "streaming";
+ setup();
+ await userEvent.click(screen.getByText("sendMessage"));
+ await userEvent.click(screen.getByText("clearQueued"));
+ expect(screen.getByTestId("queued").textContent).toBe("");
+ });
+
+ // Continue only renders while idle, so this is defence — but it is the same
+ // second-request hazard, and regenerate has no queue to fall back on.
+ it("ignores Continue while a turn is still streaming", async () => {
+ chat.status = "streaming";
+ setup();
+ await userEvent.click(screen.getByText("regenerate"));
+ expect(chat.regenerate).not.toHaveBeenCalled();
+ });
+
it("reports a pending approval from a rehydrated transcript", () => {
chat.messages = [approvalMessage];
setup([approvalMessage]);
diff --git a/src/components/agent/AgentChatInput.tsx b/src/components/agent/AgentChatInput.tsx
index a580a08..872e4d1 100644
--- a/src/components/agent/AgentChatInput.tsx
+++ b/src/components/agent/AgentChatInput.tsx
@@ -2,7 +2,7 @@
import { useCallback, useEffect, useState } from "react";
import { XIcon } from "lucide-react";
-import type { TextUIPart } from "ai";
+import type { TextUIPart, UIMessage } from "ai";
import {
Attachment,
AttachmentInfo,
@@ -60,7 +60,7 @@ function chipId(): string {
);
}
-function queuedText(parts: ComposerPart[]): string {
+function queuedText(parts: UIMessage["parts"]): string {
const text = parts.find((part) => part.type === "text");
const chip = parts.find(isAgentPastePart);
if (text?.type === "text" && text.text) return text.text;
@@ -73,6 +73,8 @@ export function AgentChatInput() {
stop,
status,
approvalPending,
+ queued,
+ clearQueued,
error,
clearError,
preflight,
@@ -81,7 +83,6 @@ export function AgentChatInput() {
const [text, setText] = useState("");
const [chip, setChip] = useState<AgentPastePartData | undefined>();
- const [queued, setQueued] = useState<ComposerPart[] | undefined>();
const onPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
const pasted = event.clipboardData.getData("text/plain");
@@ -116,34 +117,20 @@ export function AgentChatInput() {
: []),
];
if (parts.length === 0) return;
- if (approvalPending) {
- setQueued(parts); // client-only, never persisted
- } else {
- sendMessage({ parts });
- }
+ // Unconditional. Whether this goes out now or waits — for an approval, or
+ // for the reply already streaming — is the provider's call, because it is
+ // the only place that sees every sender.
+ sendMessage({ parts });
setText("");
setChip(undefined);
};
- // Dispatches once the approval resolves AND the follow-up POST that executes
- // the approved tool has finished. approvalPending flips false at the same
- // instant sendAutomaticallyWhen fires that POST — dispatching on that render
- // would race it, and if sendMessage interrupts the in-flight stream, the
- // approved tool can be cut off mid-execution server-side.
- useEffect(() => {
- if (!approvalPending && status === "ready" && queued) {
- sendMessage({ parts: queued });
- setQueued(undefined);
- }
- }, [approvalPending, status, queued, sendMessage]);
-
// Clearing the conversation clears the composer with it. The textarea empties
// by remounting on the same nonce below — nothing else resets it.
useEffect(() => {
if (!composerNonce) return;
setText("");
setChip(undefined);
- setQueued(undefined);
}, [composerNonce]);
const onStop = useCallback(() => {
@@ -177,14 +164,16 @@ export function AgentChatInput() {
<div className="flex items-start gap-2 rounded-md border bg-muted/30 p-2 text-sm">
<div className="min-w-0 flex-1">
<p className="text-xs text-muted-foreground">
- Queued — waiting on your approval above
+ {approvalPending
+ ? "Queued — waiting on your approval above"
+ : "Queued — sends when the current reply finishes"}
</p>
- <p className="truncate">{queuedText(queued)}</p>
+ <p className="truncate">{queuedText(queued.parts)}</p>
</div>
<Button
aria-label="Remove from queue"
className="size-6 shrink-0"
- onClick={() => setQueued(undefined)}
+ onClick={clearQueued}
size="icon"
type="button"
variant="ghost"
diff --git a/src/components/agent/AgentChatProvider.tsx b/src/components/agent/AgentChatProvider.tsx
index e90c9b0..849e1cf 100644
--- a/src/components/agent/AgentChatProvider.tsx
+++ b/src/components/agent/AgentChatProvider.tsx
@@ -45,6 +45,10 @@ type Preflight = {
model?: string;
};
+// Everything the five senders pass. Narrower than chat.sendMessage's union so
+// a held message can be re-dispatched and rendered without narrowing again.
+type QueuedMessage = { parts: UIMessage["parts"] };
+
type AgentChatValue = ReturnType<typeof useAgentChatValue>;
const AgentChatContext = createContext<AgentChatValue | null>(null);
@@ -230,6 +234,10 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
// remounting it on the nonce is the only thing that empties it.
const [composerNonce, setComposerNonce] = useState(0);
+ // At most one message waits here. A second send while one is already held
+ // replaces it, which is what the composer did before this moved up.
+ const [queued, setQueued] = useState<QueuedMessage | undefined>();
+
// stop() before the delete is load-bearing: the route skips its onFinish
// write when the turn was aborted, and that is what stops a late save from
// restoring the conversation this just deleted.
@@ -242,34 +250,62 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
setInterruptedTurn(false);
setComposerNonce((n) => n + 1);
setReviewStreams({});
+ setQueued(undefined);
// Clearing an idle conversation aborted nothing worth reporting.
if (wasStreaming) toastInfo("Conversation cleared and generation stopped.");
}, [chat]);
+ const approvalPending = useMemo(
+ () => hasPendingApproval(chat.messages),
+ [chat.messages],
+ );
+
// Resuming the turn is what ends the interruption — Continue, or simply
// typing the next message. Cleared here rather than on a status transition
// because close() flags the turn while stop() is still settling, and an
// effect watching status would race it back to false.
- const regenerate = useCallback<typeof chat.regenerate>(
- (...args) => {
+ const dispatch = useCallback(
+ (message: QueuedMessage) => {
setInterruptedTurn(false);
- return chat.regenerate(...args);
+ return chat.sendMessage(message);
},
[chat],
);
- const sendMessage = useCallback<typeof chat.sendMessage>(
- (...args) => {
- setInterruptedTurn(false);
- return chat.sendMessage(...args);
+ // Sending while a turn is in flight starts a SECOND request: useChat does
+ // not abort the first, and the two live streams then take turns appending
+ // copies of each other's message into one transcript — the same message.id
+ // in two slots, which is the duplicate-key crash. Every sender funnels
+ // through here, so the hold lives here and not in the composer, which the
+ // resume page's Review button never touches.
+ const sendMessage = useCallback(
+ (message: QueuedMessage) => {
+ if (streamingRef.current || approvalPending) {
+ setQueued(message);
+ return;
+ }
+ void dispatch(message);
},
- [chat],
+ [approvalPending, dispatch],
);
- const approvalPending = useMemo(
- () => hasPendingApproval(chat.messages),
- [chat.messages],
- );
+ // Both conditions are load-bearing. approvalPending flips false at the same
+ // instant sendAutomaticallyWhen fires the POST that executes the approved
+ // tool, so releasing on that alone would race it and cut the tool off
+ // mid-execution; status is what proves the connection is actually free.
+ useEffect(() => {
+ if (!queued || approvalPending || chat.status !== "ready") return;
+ setQueued(undefined);
+ void dispatch(queued);
+ }, [queued, approvalPending, chat.status, dispatch]);
+
+ const regenerate = useCallback(() => {
+ if (streamingRef.current) return;
+ setInterruptedTurn(false);
+ void chat.regenerate();
+ }, [chat]);
+
+ const clearQueued = useCallback(() => setQueued(undefined), []);
const dismissInterrupted = useCallback(() => setInterruptedTurn(false), []);
@@ -287,6 +323,8 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
regenerate,
addToolApprovalResponse: chat.addToolApprovalResponse,
approvalPending,
+ queued,
+ clearQueued,
interruptedTurn,
dismissInterrupted,
clear,