DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): distinguish unconfirmed replies from expired questions (#1648)
Bingxi Zhao (Frank)ed3f9e9b4e9b
diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsxindex 7ae30e3ad..236fa10df 100644--- a/web/components/chat/home/AskUserOptions.tsx+++ b/web/components/chat/home/AskUserOptions.tsx@@ -997,6 +997,7 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({const {sending: submitted,failed: submitFailed,+ failureMessage: submitFailureMessage,submit,} = useCardSubmission(onSubmit);// Same lock, two reasons: answers are in flight, or the question is not@@ -1193,7 +1194,7 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({: submitted? t("Sending your answers…"): submitFailed- ? t(REPLY_NOT_DELIVERED)+ ? t(submitFailureMessage ?? REPLY_NOT_DELIVERED): null;return (diff --git a/web/components/reading/workspace/ReadingComposer.tsx b/web/components/reading/workspace/ReadingComposer.tsxindex 6aea99c03..2f1e8e657 100644--- a/web/components/reading/workspace/ReadingComposer.tsx+++ b/web/components/reading/workspace/ReadingComposer.tsx@@ -12,7 +12,8 @@* before the message does, exactly like the retired bespoke textarea did.*/-import { useCallback } from "react";+import { useCallback, useRef } from "react";+import { COMMAND_CONFIRMATION_FAILED } from "@/features/chat/transport/command-delivery";import { X } from "lucide-react";import { useTranslation } from "react-i18next";@@ -68,6 +69,8 @@ export function ReadingComposer({const { capabilities, activeCapabilityValue, selectCapability } =useWorkspaceChatActions();const { t } = useTranslation();+ const fallbackInputRef = useRef<((text: string) => void) | null>(null);+ const replyInputRef = prefillInputRef ?? fallbackInputRef;const awaitingUserReply = hasPendingAskUser(state.messages[state.messages.length - 1]?.events,@@ -119,6 +122,9 @@ export function ReadingComposer({if (sent) return;notify(t(REPLY_SENT_AS_NEW_MESSAGE));sendAsNewMessage();+ }).catch(() => {+ notify(t(COMMAND_CONFIRMATION_FAILED), { tone: "error" });+ replyInputRef.current?.(submission.content);});return;}@@ -131,6 +137,7 @@ export function ReadingComposer({selection,sendMessage,submitUserReply,+ replyInputRef,t,],);@@ -165,7 +172,7 @@ export function ReadingComposer({/>) : null}- prefillInputRef={prefillInputRef}+ prefillInputRef={replyInputRef}/>);}diff --git a/web/components/space/learning/MasteryComposer.tsx b/web/components/space/learning/MasteryComposer.tsxindex 8fad34b92..f5179704e 100644--- a/web/components/space/learning/MasteryComposer.tsx+++ b/web/components/space/learning/MasteryComposer.tsx@@ -19,7 +19,8 @@* one. The action is now the screen itself.*/-import { useCallback } from "react";+import { useCallback, useRef } from "react";+import { COMMAND_CONFIRMATION_FAILED } from "@/features/chat/transport/command-delivery";import { useTranslation } from "react-i18next";import StandaloneComposer, {@@ -71,6 +72,8 @@ export function MasteryComposer({useWorkspaceChatActions({ pinnedCapability: MASTERY_CAPABILITY_VALUE });const contextBudget = useContextBudget(state.messages);const { t } = useTranslation();+ const fallbackInputRef = useRef<((text: string) => void) | null>(null);+ const replyInputRef = prefillInputRef ?? fallbackInputRef;// A turn paused on an ask_user card is still "streaming", but typing an// answer is exactly how it moves forward — the composer stays live.@@ -117,12 +120,15 @@ export function MasteryComposer({if (sent) return;notify(t(REPLY_SENT_AS_NEW_MESSAGE));sendAsNewMessage();+ }).catch(() => {+ notify(t(COMMAND_CONFIRMATION_FAILED), { tone: "error" });+ replyInputRef.current?.(submission.content);});return;}sendAsNewMessage();},- [awaitingUserReply, disabled, sendMessage, submitUserReply, t],+ [awaitingUserReply, disabled, sendMessage, submitUserReply, replyInputRef, t],);return (@@ -147,7 +153,7 @@ export function MasteryComposer({// question shows the learner a way in.inputPlaceholder={askHint || placeholder}inputPlaceholderCompletion={askHint}- prefillInputRef={prefillInputRef}+ prefillInputRef={replyInputRef}// A tutoring transcript fills a window faster than a chat one — a topic's// materials, the map, and the whole history of questions all ride along —// so the reading belongs here at least as much as on the chat page.diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex 1d57c61a4..d25840b3e 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -10,6 +10,7 @@ import {type FailedSubmissionRecord,} from "@/lib/failed-submissions";import { randomUuid } from "@/lib/random-uuid";+import { newCommandId } from "@/contracts/parse/turn-command";import React, {createContext,@@ -80,7 +81,7 @@ import {recomputeAnswerContent,shouldAppendEventContent,} from "@/lib/stream";-import { hasPendingAskUserInMessages } from "@/lib/ask-user-state";+import { hasPendingAskUserInMessages, pendingAskUserKeyInMessages } from "@/lib/ask-user-state";import { notify } from "@/lib/notifications";import { forwardReaderAction } from "@/lib/reading-reader-action";import {@@ -1800,6 +1801,7 @@ export function ChatStateAdapterProvider({{key: string;client: UnifiedTurnClient;+ replyCommand?: { fingerprint: string; commandId: string };}>>(new Map());@@ -2186,7 +2188,11 @@ export function ChatStateAdapterProvider({if (!existing.client.connected) existing.client.connect();return existing;}- const record = {+ const record: {+ key: string;+ client: UnifiedTurnClient;+ replyCommand?: { fingerprint: string; commandId: string };+ } = {key,client: new UnifiedTurnClient((event) => handleRunnerEvent(record.key, event),@@ -2245,6 +2251,11 @@ export function ChatStateAdapterProvider({return Promise.resolve(false);}const runner = ensureRunner(key);+ // The transport owns reconnection and queues durable replies. Local+ // connection retries must not end this already-running turn (#1648).+ if (options.awaitAck) {+ return runner.client.sendAwaitingAck(msg as ClientCommand);+ }if (!runner.client.connected) {if (attempt >= SUBMIT_CONNECT_RETRY_LIMIT) {console.error("WebSocket failed to connect after retries");@@ -2284,9 +2295,6 @@ export function ChatStateAdapterProvider({retryTimersRef.current.add(timerId);});}- if (options.awaitAck) {- return runner.client.sendAwaitingAck(msg as ClientCommand);- }runner.client.send(msg);return Promise.resolve(true);},@@ -3138,9 +3146,20 @@ export function ChatStateAdapterProvider({if (typeof reply.text === "string") message.text = reply.text;if (Array.isArray(reply.answers)) message.answers = reply.answers;}+ const runner = ensureRunner(key);+ const fingerprint = JSON.stringify([+ message, pendingAskUserKeyInMessages(session.messages, turnId),+ ]);+ // Retrying an unconfirmed answer reuses its idempotency key. The server+ // may already have accepted it even if its ACK was lost (#1648).+ const commandId = runner.replyCommand?.fingerprint === fingerprint+ ? runner.replyCommand.commandId+ : newCommandId();+ runner.replyCommand = { fingerprint, commandId };+ message.command_id = commandId;return sendThroughRunner(key, message, { awaitAck: true });},- [sendThroughRunner],+ [ensureRunner, sendThroughRunner],);const regenerateLastMessage = useCallback((replaySnapshot = false) => {diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 2aaaf2c89..97673f243 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -1,5 +1,7 @@"use client";+import { COMMAND_CONFIRMATION_FAILED } from "@/features/chat/transport/command-delivery";+import { ResourceReuseContext, useResourceReusePolicy } from "@/components/chat/home/ResourceReuse";import { retainedKnowledgeBases } from "@/lib/resource-reuse";import { knowledgeBaseRef } from "@/lib/knowledge-helpers";@@ -1910,7 +1912,13 @@ export default function ChatWorkspace({// the learner with a turn they can only cancel.if (awaitingUserReplyRef.current) {if (!content.trim()) return;- if (await submitUserReply({ text: content })) return;+ try {+ if (await submitUserReply({ text: content })) return;+ } catch {+ notify(t(COMMAND_CONFIRMATION_FAILED), { tone: "error" });+ prefillInputRef.current?.(content);+ return;+ }// Refused: the turn that asked is gone. Do NOT stop here. The// composer has already cleared the box, so returning discarded what// they typed — while the error told them to "send a new message",diff --git a/web/features/chat/transport/TurnRuntimeClient.ts b/web/features/chat/transport/TurnRuntimeClient.tsindex 69ab7cf3c..72e2e2300 100644--- a/web/features/chat/transport/TurnRuntimeClient.ts+++ b/web/features/chat/transport/TurnRuntimeClient.ts@@ -19,6 +19,7 @@ import {type TurnSocketFactory,} from "./socket";import { reconnectDelay, shouldReconnect } from "./reconnect-policy";+import { CommandDeliveryError } from "./command-delivery";export type RuntimeConnectionState =| "idle"@@ -39,6 +40,7 @@ export interface TurnRuntimeClientOptions {random?: () => number;maxBufferedGap?: number;replayProbeDelayMs?: number;+ commandAckTimeoutMs?: number;onEvent: (event: ServerEvent) => void;onStateChange?: (state: RuntimeConnectionState) => void;onDiagnostic?: (diagnostic: string) => void;@@ -53,6 +55,8 @@ interface PendingCommand {sentGeneration: number;/** Settled with the server's verdict, for callers that await one. */settle?: (accepted: boolean) => void;+ fail?: (error: Error) => void;+ timeoutHandle?: unknown;}const ACKNOWLEDGED_COMMAND_TYPES = new Set([@@ -97,6 +101,7 @@ export class TurnRuntimeClient {| "random"| "maxBufferedGap"| "replayProbeDelayMs"+ | "commandAckTimeoutMs">> &Omit<@@ -107,6 +112,7 @@ export class TurnRuntimeClient {| "random"| "maxBufferedGap"| "replayProbeDelayMs"+ | "commandAckTimeoutMs">;private socket: TurnSocket | null = null;private reconnectHandle: unknown = null;@@ -130,6 +136,7 @@ export class TurnRuntimeClient {random: Math.random,maxBufferedGap: 32,replayProbeDelayMs: 5_000,+ commandAckTimeoutMs: 30_000,...options,};}@@ -204,17 +211,31 @@ export class TurnRuntimeClient {* waiting, most often because the backend restarted since the question was* asked — is otherwise only a console diagnostic, which leaves whatever UI* is waiting on it pending forever. Resolves ``false`` for a rejection and- * for a client that stops before the acknowledgement arrives; a command+ * throws a delivery error when no acknowledgement arrives; a command* type the protocol never acknowledges resolves ``true`` on dispatch.*/sendAwaitingAck(command: ClientCommand): Promise<boolean> {- return new Promise<boolean>((resolve) => {- const pending = this.enqueue(command);- if (!pending.requiresAck) {- resolve(true);- return;+ return new Promise<boolean>((resolve, reject) => {+ const prepared = prepareCommand(command);+ const pending: PendingCommand = {+ ...prepared,+ acknowledgedAfter: this.lastSeq,+ sentGeneration: -1,+ settle: resolve,+ fail: reject,+ };+ if (pending.requiresAck) {+ // A live connection can still lose its ACK. Reopen the card without+ // declaring the server's question expired, and don't send a timed-out+ // answer later behind the learner's back (#1648).+ pending.timeoutHandle = this.options.scheduler.setTimeout(() => {+ this.pending = this.pending.filter((item) => item !== pending);+ reject(new CommandDeliveryError());+ }, this.options.commandAckTimeoutMs);}- pending.settle = resolve;+ this.pending.push(pending);+ this.flushPending();+ if (!pending.requiresAck) resolve(true);});}@@ -230,6 +251,12 @@ export class TurnRuntimeClient {return pending;}+ private clearCommandTimeout(pending: PendingCommand): void {+ if (pending.timeoutHandle === undefined) return;+ this.options.scheduler.clearTimeout(pending.timeoutHandle);+ pending.timeoutHandle = undefined;+ }+cancel(command: ClientCommand): void {this.send(command);}@@ -256,7 +283,10 @@ export class TurnRuntimeClient {socket?.close(1000, "client stopped");// Nobody is left to acknowledge these, so release their waiters rather// than leaving the UI that sent them pending forever.- for (const pending of this.pending) pending.settle?.(false);+ for (const pending of this.pending) {+ this.clearCommandTimeout(pending);+ pending.fail?.(new CommandDeliveryError());+ }this.pending = [];this.buffered.clear();this.setState("stopped");@@ -287,8 +317,10 @@ export class TurnRuntimeClient {if (event.type === "command_ack") {const remaining: PendingCommand[] = [];for (const item of this.pending) {- if (item.commandId === event.command_id) item.settle?.(event.accepted);- else remaining.push(item);+ if (item.commandId === event.command_id) {+ this.clearCommandTimeout(item);+ item.settle?.(event.accepted);+ } else remaining.push(item);}this.pending = remaining;if (!event.accepted) {diff --git a/web/features/chat/transport/command-delivery.ts b/web/features/chat/transport/command-delivery.tsnew file mode 100644index 000000000..e568b8b8b--- /dev/null+++ b/web/features/chat/transport/command-delivery.ts@@ -0,0 +1,10 @@+/** Local delivery uncertainty is not a server rejection (#1648). */+export const COMMAND_CONFIRMATION_FAILED =+ "Couldn't confirm your answer. Check your connection and retry.";++export class CommandDeliveryError extends Error {+ constructor() {+ super(COMMAND_CONFIRMATION_FAILED);+ this.name = "CommandDeliveryError";+ }+}diff --git a/web/hooks/use-card-submission.ts b/web/hooks/use-card-submission.tsindex bf370fc1b..5c2b818f1 100644--- a/web/hooks/use-card-submission.ts+++ b/web/hooks/use-card-submission.ts@@ -1,3 +1,4 @@+import { COMMAND_CONFIRMATION_FAILED } from "@/features/chat/transport/command-delivery";import { useCallback, useState } from "react";export interface UserReplyPayload {@@ -24,15 +25,18 @@ export type SubmitUserReply = (export function useCardSubmission(onSubmit: SubmitUserReply) {const [sending, setSending] = useState(false);const [failed, setFailed] = useState(false);+ const [failureMessage, setFailureMessage] = useState<string | null>(null);const submit = useCallback(async (payload: UserReplyPayload) => {setSending(true);setFailed(false);+ setFailureMessage(null);let accepted: void | boolean;try {accepted = await onSubmit(payload);} catch {+ setFailureMessage(COMMAND_CONFIRMATION_FAILED);accepted = false;}// ``undefined`` is a host that does not report a verdict; only an@@ -46,5 +50,5 @@ export function useCardSubmission(onSubmit: SubmitUserReply) {[onSubmit],);- return { sending, failed, submit };+ return { sending, failed, failureMessage, submit };}diff --git a/web/lib/ask-user-state.ts b/web/lib/ask-user-state.tsindex 26a022e02..56374bbfe 100644--- a/web/lib/ask-user-state.ts+++ b/web/lib/ask-user-state.ts@@ -83,7 +83,7 @@ function pendingCards(events: StreamEvent[] | undefined,turnId: string | null | undefined,includeMastery: boolean,-): number {+): Set<string> {const pending = new Set<string>();let anonymousCount = 0;@@ -121,7 +121,7 @@ function pendingCards(}}- return pending.size;+ return pending;}/**@@ -135,7 +135,7 @@ export function hasPendingAskUser(events: StreamEvent[] | undefined,turnId?: string | null,): boolean {- return pendingCards(events, turnId, false) > 0;+ return pendingCards(events, turnId, false).size > 0;}export function hasPendingAskUserInMessages(@@ -145,6 +145,16 @@ export function hasPendingAskUserInMessages(return messages.some((message) => hasPendingAskUser(message.events, turnId));}+/** Distinguish retries from a later question with the same answer (#1648). */+export function pendingAskUserKeyInMessages(+ messages: MessageWithEvents[],+ turnId?: string | null,+): string {+ return JSON.stringify(messages+ .map((message) => [...pendingCards(message.events, turnId, false)])+ .filter((keys) => keys.length > 0));+}+/*** Returns true when *any* card is still waiting on the user — a paused* `ask_user` or a mastery question that ended its turn.@@ -157,5 +167,5 @@ export function hasPendingUserCard(events: StreamEvent[] | undefined,turnId?: string | null,): boolean {- return pendingCards(events, turnId, true) > 0;+ return pendingCards(events, turnId, true).size > 0;}diff --git a/web/locales/de/app.json b/web/locales/de/app.jsonindex d2b01fde9..1553f1507 100644--- a/web/locales/de/app.json+++ b/web/locales/de/app.json@@ -5300,5 +5300,6 @@"Use main LLM (fallback)": "Hauptmodell verwenden (Standard)","Select a vision model for image descriptions in documents.": "Wähle ein Vision-Modell für Bildbeschreibungen in Dokumenten.","Failed to load image description models.": "Die Modelle für Bildbeschreibungen konnten nicht geladen werden.",- "Could not play this reply. Check Text-to-Speech in Settings.": "Diese Antwort konnte nicht vorgelesen werden. Prüfe Text-to-Speech in den Einstellungen."+ "Could not play this reply. Check Text-to-Speech in Settings.": "Diese Antwort konnte nicht vorgelesen werden. Prüfe Text-to-Speech in den Einstellungen.",+ "Couldn't confirm your answer. Check your connection and retry.": "Deine Antwort konnte nicht bestätigt werden. Prüfe die Verbindung und versuche es erneut."}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex ea18a5e6e..514a648b1 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -5300,5 +5300,6 @@"Image description model": "Image description model","Use main LLM (fallback)": "Use main LLM (fallback)","Failed to load image description models.": "Failed to load image description models.",- "Select a vision model for image descriptions in documents.": "Select a vision model for image descriptions in documents."+ "Select a vision model for image descriptions in documents.": "Select a vision model for image descriptions in documents.",+ "Couldn't confirm your answer. Check your connection and retry.": "Couldn't confirm your answer. Check your connection and retry."}diff --git a/web/locales/fr/app.json b/web/locales/fr/app.jsonindex fa80b82ee..3579dfc0d 100644--- a/web/locales/fr/app.json+++ b/web/locales/fr/app.json@@ -5743,5 +5743,6 @@"Use main LLM (fallback)": "Utiliser le modèle principal (par défaut)","Select a vision model for image descriptions in documents.": "Sélectionnez un modèle de vision pour décrire les images des documents.","Failed to load image description models.": "Impossible de charger les modèles de description des images.",- "Could not play this reply. Check Text-to-Speech in Settings.": "Impossible de lire cette réponse. Vérifiez la synthèse vocale dans les paramètres."+ "Could not play this reply. Check Text-to-Speech in Settings.": "Impossible de lire cette réponse. Vérifiez la synthèse vocale dans les paramètres.",+ "Couldn't confirm your answer. Check your connection and retry.": "Impossible de confirmer votre réponse. Vérifiez votre connexion et réessayez."}diff --git a/web/locales/pl/app.json b/web/locales/pl/app.jsonindex 09b7c0f22..68a31b611 100644--- a/web/locales/pl/app.json+++ b/web/locales/pl/app.json@@ -5316,5 +5316,6 @@"Use main LLM (fallback)": "Użyj głównego modelu językowego (domyślnie)","Select a vision model for image descriptions in documents.": "Wybierz model wizyjny do opisywania obrazów w dokumentach.","Failed to load image description models.": "Nie udało się wczytać modeli do opisywania obrazów.",- "Could not play this reply. Check Text-to-Speech in Settings.": "Nie udało się odczytać tej odpowiedzi. Sprawdź ustawienia syntezy mowy."+ "Could not play this reply. Check Text-to-Speech in Settings.": "Nie udało się odczytać tej odpowiedzi. Sprawdź ustawienia syntezy mowy.",+ "Couldn't confirm your answer. Check your connection and retry.": "Nie udało się potwierdzić odpowiedzi. Sprawdź połączenie i spróbuj ponownie."}diff --git a/web/locales/uk/app.json b/web/locales/uk/app.jsonindex 4162163fd..c39898b9d 100644--- a/web/locales/uk/app.json+++ b/web/locales/uk/app.json@@ -5316,5 +5316,6 @@"Use main LLM (fallback)": "Використовувати основну мовну модель (типово)","Select a vision model for image descriptions in documents.": "Виберіть модель зору для опису зображень у документах.","Failed to load image description models.": "Не вдалося завантажити моделі опису зображень.",- "Could not play this reply. Check Text-to-Speech in Settings.": "Не вдалося озвучити цю відповідь. Перевірте синтез мовлення в налаштуваннях."+ "Could not play this reply. Check Text-to-Speech in Settings.": "Не вдалося озвучити цю відповідь. Перевірте синтез мовлення в налаштуваннях.",+ "Couldn't confirm your answer. Check your connection and retry.": "Не вдалося підтвердити вашу відповідь. Перевірте з’єднання та спробуйте ще раз."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 21e2bf50a..001f02f07 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -5300,5 +5300,6 @@"Image description model": "图片描述模型","Use main LLM (fallback)": "使用主模型(默认)","Failed to load image description models.": "无法加载图片描述模型。",- "Select a vision model for image descriptions in documents.": "选择用于文档图片描述的视觉模型。"+ "Select a vision model for image descriptions in documents.": "选择用于文档图片描述的视觉模型。",+ "Couldn't confirm your answer. Check your connection and retry.": "无法确认你的答案是否已提交。请检查连接后重试。"}diff --git a/web/tests/ask-user-resume-cursor.spec.tsx b/web/tests/ask-user-resume-cursor.spec.tsxindex e898a6ae8..68599fb2a 100644--- a/web/tests/ask-user-resume-cursor.spec.tsx+++ b/web/tests/ask-user-resume-cursor.spec.tsx@@ -1,5 +1,5 @@import { useEffect } from "react";-import { act, render, screen, waitFor } from "@testing-library/react";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, expect, it, vi } from "vitest";@@ -79,16 +79,108 @@ function Harness() {<button onClick={() => chat.sendMessage("Quiz me")}>Start turn</button><span data-testid="streaming">{String(chat.state.isStreaming)}</span><span data-testid="answer">{last?.content}</span>- {card && <AskUserOptions data={card} onSubmit={chat.submitUserReply} />}+ {card && <AskUserOptions key={card.payload.questions[0]?.prompt} data={card} onSubmit={chat.submitUserReply} />}</>);}afterEach(() => {+ vi.useRealTimers();vi.unstubAllGlobals();TestSocket.instances = [];});+async function poseCard() {+ vi.stubGlobal("WebSocket", TestSocket);+ const user = userEvent.setup();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await user.click(screen.getByRole("button", { name: "Start turn" }));+ const socket = TestSocket.instances.at(-1)!;+ act(() => socket.open());+ await waitFor(() => expect(socket.sent.some((m) => m.type === "start_turn")).toBe(true));+ act(() => {+ socket.frame("turn-quiz", 1, "session");+ socket.frame("turn-quiz", 2, "tool_result", {+ tool_call_id: "call-quiz",+ tool_metadata: { ask_user: { questions: [+ { id: "q1", prompt: "Which update?", options: [{ label: "Overwrite" }] },+ ] } },+ });+ });+ await user.click(screen.getByRole("button", { name: /Overwrite/ }));+ vi.useFakeTimers();+ return socket;+}++function acknowledge(socket: TestSocket, commandId: unknown, accepted = true) {+ act(() => socket.dispatchEvent(new MessageEvent("message", {+ data: JSON.stringify({+ protocol_version: "2.0", type: "command_ack", command_type: "submit_user_reply",+ command_id: commandId, accepted, turn_id: "turn-quiz",+ }),+ })));+}++it("keeps a reply queued through a long reconnect without ending the turn (#1648)", async () => {+ const socket = await poseCard();+ act(() => socket.close());+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ await act(async () => { await vi.advanceTimersByTimeAsync(12_500); });+ expect(screen.getByText("Sending your answers…")).toBeVisible();+ expect(screen.getByTestId("streaming")).toHaveTextContent("true");+ const resumed = TestSocket.instances.at(-1)!;+ act(() => resumed.open());+ const reply = resumed.sent.find((m) => m.type === "submit_user_reply")!;+ expect(reply).toMatchObject({ turn_id: "turn-quiz", text: "Overwrite" });+ acknowledge(resumed, reply.command_id);+ await act(async () => { await vi.advanceTimersByTimeAsync(35_000); });+ expect(screen.queryByText(/Check your connection and retry/)).not.toBeInTheDocument();+});++it("allows an unconfirmed reply to retry with the same command id (#1648)", async () => {+ const socket = await poseCard();+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ const reply = socket.sent.find((m) => m.type === "submit_user_reply")!;+ await act(async () => { await vi.advanceTimersByTimeAsync(30_001); });+ expect(screen.getByText("Couldn't confirm your answer. Check your connection and retry.")).toBeVisible();+ expect(screen.queryByText(/This question is no longer active/)).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Overwrite/ })).toHaveAttribute("aria-pressed", "true");+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ const replies = socket.sent.filter((m) => m.type === "submit_user_reply");+ expect(replies).toHaveLength(2);+ expect(replies[1].command_id).toBe(reply.command_id);+ acknowledge(socket, reply.command_id, false);+ await act(async () => { await Promise.resolve(); });+ expect(screen.getByText(/This question is no longer active/)).toBeVisible();+});++it("uses a new command id for a later question with identical answers", async () => {+ const socket = await poseCard();+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ const first = socket.sent.find((m) => m.type === "submit_user_reply")!;+ acknowledge(socket, first.command_id);+ act(() => {+ socket.frame("turn-quiz", 3, "progress", {+ ask_user_resolved: true, ask_user_tool_call_id: "call-quiz",+ answers: [{ questionId: "q1", text: "Overwrite" }],+ });+ socket.frame("turn-quiz", 4, "tool_result", {+ tool_call_id: "call-quiz-2",+ tool_metadata: { ask_user: { questions: [+ { id: "q1", prompt: "Which update next?", options: [{ label: "Overwrite" }] },+ ] } },+ });+ });+ // The card may preserve the choice between identical question shapes.+ const option = screen.getByRole("button", { name: /Overwrite/ });+ if (option.getAttribute("aria-pressed") !== "true") fireEvent.click(option);+ fireEvent.click(screen.getByRole("button", { name: "Submit" }));+ const replies = socket.sent.filter((m) => m.type === "submit_user_reply");+ expect(replies).toHaveLength(2);+ expect(replies[1].command_id).not.toBe(first.command_id);+ acknowledge(socket, replies[1].command_id);+});+it("resumes an ask_user in a shorter second turn without skipping its reply or done", async () => {vi.stubGlobal("WebSocket", TestSocket);const user = userEvent.setup();diff --git a/web/tests/turn-runtime-client.test.ts b/web/tests/turn-runtime-client.test.tsindex 15779da3c..98835266d 100644--- a/web/tests/turn-runtime-client.test.ts+++ b/web/tests/turn-runtime-client.test.ts@@ -1,5 +1,6 @@import assert from "node:assert/strict";import test from "node:test";+import { CommandDeliveryError } from "../features/chat/transport/command-delivery";import {buildCancelTurn,@@ -385,7 +386,22 @@ test("stopping releases waiters that will never be acknowledged", async () => {);client.stop();- assert.equal(await verdict, false);+ await assert.rejects(verdict, CommandDeliveryError);+});++test("missing reply ACK times out without a false server rejection or delayed send", async () => {+ const { client, sockets, scheduler } = harness();+ client.connect();+ const verdict = client.sendAwaitingAck(+ buildSubmitUserReply({ turnId: "turn-1", text: "B", commandId: "unconfirmed" }),+ );+ const rejected = assert.rejects(verdict, CommandDeliveryError);+ scheduler.runNext();+ await rejected;+ sockets[0].open();+ assert.equal(sockets[0].sent.some((item) => item.type === "submit_user_reply"), false);+ client.stop();+ assert.equal(scheduler.tasks.length, 0);});