Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(chat): preserve pending ask_user turns

XZH6c6ef741d9ef
diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsx
index 033b7b8fa..8770a28ac 100644
--- a/web/features/chat/ChatStateAdapter.tsx
+++ b/web/features/chat/ChatStateAdapter.tsx
@@ -800,6 +800,13 @@ function reducer(state: ProviderState, action: Action): ProviderState {
messages[messages.length - 1] = { ...last, content: repaired };
return messages;
})();
+ const endedTurnId = action.turnId || ending?.activeTurnId || null;
+ // A completed turn can still own an unanswered card (for example, a
+ // replay/sentinel race). Keep its address so submit_user_reply can
+ // reach the backend waiter instead of failing the visible card.
+ const pendingAskUser =
+ action.status === "completed" &&
+ hasPendingAskUserInMessages(settled, endedTurnId);
return {
...state,
sessions: {
@@ -811,7 +818,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {
currentStage: "",
status: action.status ?? "completed",
activeTurnId:
- action.status === "running"
+ action.status === "running" || pendingAskUser
? action.turnId ||
state.sessions[action.key]?.activeTurnId ||
null
diff --git a/web/tests/ask-user-terminal-turn.spec.tsx b/web/tests/ask-user-terminal-turn.spec.tsx
new file mode 100644
index 000000000..ddb829482
--- /dev/null
+++ b/web/tests/ask-user-terminal-turn.spec.tsx
@@ -0,0 +1,143 @@
+import { useEffect } from "react";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ ChatStateAdapterProvider,
+ useChatStateAdapter,
+} from "@/features/chat/ChatStateAdapter";
+import { initI18n } from "@/i18n/init";
+
+initI18n("en");
+
+const transport = vi.hoisted(() => {
+ type MockEvent = Record<string, unknown>;
+ type EventListener = (event: MockEvent) => void;
+ const instances: MockUnifiedTurnClient[] = [];
+
+ class MockUnifiedTurnClient {
+ connected = false;
+ submitted: Array<Record<string, unknown>> = [];
+
+ constructor(
+ private readonly onEvent: EventListener,
+ private readonly onClose?: () => void,
+ ) {
+ instances.push(this);
+ }
+
+ connect(): void {
+ this.connected = true;
+ }
+
+ setResumeState(): void {}
+
+ disconnect(): void {
+ this.connected = false;
+ this.onClose?.();
+ }
+
+ send(message: Record<string, unknown>): void {
+ if (message.type !== "start_turn") return;
+ window.setTimeout(() => {
+ this.onEvent({
+ type: "tool_result",
+ source: "chat",
+ stage: "responding",
+ content: "",
+ metadata: {
+ tool_call_id: "call-1273",
+ tool_metadata: {
+ ask_user: {
+ questions: [{ id: "source", prompt: "Which source?" }],
+ },
+ },
+ },
+ turn_id: "turn-1273",
+ seq: 1,
+ timestamp: Date.now() / 1000,
+ });
+ }, 0);
+ window.setTimeout(() => {
+ this.onEvent({
+ type: "done",
+ source: "chat",
+ stage: "responding",
+ content: "",
+ metadata: { status: "completed" },
+ turn_id: "turn-1273",
+ seq: 2,
+ timestamp: Date.now() / 1000,
+ });
+ }, 0);
+ }
+
+ sendAwaitingAck(message: Record<string, unknown>): Promise<boolean> {
+ this.submitted.push(message);
+ return Promise.resolve(true);
+ }
+ }
+
+ return { MockUnifiedTurnClient, instances };
+});
+
+vi.mock("@/features/chat/transport/UnifiedTurnClient", () => ({
+ UnifiedTurnClient: transport.MockUnifiedTurnClient,
+}));
+
+function Harness() {
+ const chat = useChatStateAdapter();
+
+ useEffect(() => {
+ chat.newSession();
+ // Only initialize the draft once; the provider owns subsequent state.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return (
+ <div>
+ <span data-testid="streaming">{String(chat.state.isStreaming)}</span>
+ <button type="button" onClick={() => chat.sendMessage("hello")}>
+ Start turn
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ void chat.submitUserReply({
+ text: "Knowledge center",
+ answers: [{ questionId: "source", text: "Knowledge center" }],
+ });
+ }}
+ >
+ Submit answer
+ </button>
+ </div>
+ );
+}
+
+describe("ask_user terminal turn state", () => {
+ it("keeps the pending card addressable after a completed turn", async () => {
+ const user = userEvent.setup();
+ render(
+ <ChatStateAdapterProvider>
+ <Harness />
+ </ChatStateAdapterProvider>,
+ );
+
+ await user.click(screen.getByRole("button", { name: "Start turn" }));
+ await waitFor(() =>
+ expect(screen.getByTestId("streaming")).toHaveTextContent("false"),
+ );
+
+ await user.click(screen.getByRole("button", { name: "Submit answer" }));
+ await waitFor(() => {
+ const client = transport.instances.at(-1);
+ expect(client?.submitted.at(-1)).toMatchObject({
+ type: "submit_user_reply",
+ turn_id: "turn-1273",
+ text: "Knowledge center",
+ });
+ });
+ });
+});