DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(web): re-send a refused answer instead of discarding it (#1273)
Bingxi Zhao (Frank)771174f49468
diff --git a/web/components/reading/workspace/ReadingComposer.tsx b/web/components/reading/workspace/ReadingComposer.tsxindex b86a77bfe..4ed6bc79f 100644--- a/web/components/reading/workspace/ReadingComposer.tsx+++ b/web/components/reading/workspace/ReadingComposer.tsx@@ -20,7 +20,10 @@ import StandaloneComposer, {} from "@/components/chat/home/StandaloneComposer";import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";-import { hasPendingAskUser, REPLY_NOT_DELIVERED } from "@/lib/ask-user-state";+import {+ hasPendingAskUser,+ REPLY_SENT_AS_NEW_MESSAGE,+} from "@/lib/ask-user-state";import { notify } from "@/lib/notifications";import { setReadingViewport } from "@/lib/reading-turn-state";@@ -62,48 +65,54 @@ export function ReadingComposer({const handleSubmit = useCallback((submission: StandaloneComposerSubmission) => {- // A turn paused on a question: what the user typed is their answer,- // not a new message. See page.tsx's handleSend for the same routing.- if (awaitingUserReply) {- if (submission.content.trim()) {- void submitUserReply({ text: submission.content }).then((sent) => {- if (!sent) notify(t(REPLY_NOT_DELIVERED), { tone: "error" });+ const sendAsNewMessage = () => {+ if (selection) {+ setReadingViewport({+ locator: selection.locator,+ selection: selection.quote,});}- return;- }- if (selection) {- setReadingViewport({- locator: selection.locator,- selection: selection.quote,+ // The composer's own "@ reference an earlier session" picker and this+ // surface's persistent linked-conversations list share one wire slot;+ // union them rather than letting either silently win.+ const historyReferences = Array.from(+ new Set([...linkedSessionIds, ...submission.historyReferences]),+ );+ sendMessage(+ submission.content,+ submission.attachments,+ // How many times the companion may consult the selected agent this+ // turn. Absent when no agent is picked, which is the ordinary case.+ submission.subagentBudget+ ? {+ ...(submission.config ?? {}),+ subagent_consult_budget: submission.subagentBudget,+ }+ : submission.config,+ submission.notebookReferences,+ historyReferences,+ { bookReferences: submission.bookReferences },+ submission.questionNotebookReferences,+ submission.persona ?? undefined,+ submission.memoryReferences,+ );+ onSent();+ window.setTimeout(() => setReadingViewport({ selection: "" }), 0);+ };++ // A turn paused on a question: what the reader typed is their answer,+ // not a new message. See ChatWorkspace's handleSend for the same routing+ // — including the fall-through on a refusal, which is what keeps a dead+ // question from swallowing the text they just wrote.+ if (awaitingUserReply && submission.content.trim()) {+ void submitUserReply({ text: submission.content }).then((sent) => {+ if (sent) return;+ notify(t(REPLY_SENT_AS_NEW_MESSAGE));+ sendAsNewMessage();});+ return;}- // The composer's own "@ reference an earlier session" picker and this- // surface's persistent linked-conversations list share one wire slot;- // union them rather than letting either silently win.- const historyReferences = Array.from(- new Set([...linkedSessionIds, ...submission.historyReferences]),- );- sendMessage(- submission.content,- submission.attachments,- // How many times the companion may consult the selected agent this- // turn. Absent when no agent is picked, which is the ordinary case.- submission.subagentBudget- ? {- ...(submission.config ?? {}),- subagent_consult_budget: submission.subagentBudget,- }- : submission.config,- submission.notebookReferences,- historyReferences,- { bookReferences: submission.bookReferences },- submission.questionNotebookReferences,- submission.persona ?? undefined,- submission.memoryReferences,- );- onSent();- window.setTimeout(() => setReadingViewport({ selection: "" }), 0);+ sendAsNewMessage();},[awaitingUserReply,diff --git a/web/components/space/learning/MasteryComposer.tsx b/web/components/space/learning/MasteryComposer.tsxindex e7c1fb718..5c073d723 100644--- a/web/components/space/learning/MasteryComposer.tsx+++ b/web/components/space/learning/MasteryComposer.tsx@@ -28,7 +28,10 @@ import { MASTERY_CAPABILITY_VALUE } from "@/features/capabilities/presentation";import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";import { useContextBudget } from "@/hooks/useContextBudget";import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";-import { hasPendingAskUser, REPLY_NOT_DELIVERED } from "@/lib/ask-user-state";+import {+ hasPendingAskUser,+ REPLY_SENT_AS_NEW_MESSAGE,+} from "@/lib/ask-user-state";import { notify } from "@/lib/notifications";export function MasteryComposer({@@ -74,36 +77,40 @@ export function MasteryComposer({const handleSubmit = useCallback((submission: StandaloneComposerSubmission) => {if (disabled) return;- // A turn paused on a question: what the user typed is their answer,- // not a new message. See page.tsx's handleSend for the same routing.- if (awaitingUserReply) {- if (submission.content.trim()) {- void submitUserReply({ text: submission.content }).then((sent) => {- // The composer already cleared what they typed, so a silent drop- // would look like the tutor simply never replied.- if (!sent) notify(t(REPLY_NOT_DELIVERED), { tone: "error" });- });- }+ const sendAsNewMessage = () =>+ sendMessage(+ submission.content,+ submission.attachments,+ // How many times the tutor may consult the selected agent this turn.+ // Absent when no agent is picked, which is the ordinary case.+ submission.subagentBudget+ ? {+ ...(submission.config ?? {}),+ subagent_consult_budget: submission.subagentBudget,+ }+ : submission.config,+ submission.notebookReferences,+ submission.historyReferences,+ { bookReferences: submission.bookReferences },+ submission.questionNotebookReferences,+ submission.persona ?? undefined,+ submission.memoryReferences,+ );++ // A turn paused on a question: what the learner typed is their answer,+ // not a new message. See ChatWorkspace's handleSend for the same routing+ // — including the fall-through, which is the part that matters: the+ // composer has already cleared the box, so stopping on a refusal+ // discarded what they wrote.+ if (awaitingUserReply && submission.content.trim()) {+ void submitUserReply({ text: submission.content }).then((sent) => {+ if (sent) return;+ notify(t(REPLY_SENT_AS_NEW_MESSAGE));+ sendAsNewMessage();+ });return;}- sendMessage(- submission.content,- submission.attachments,- // How many times the tutor may consult the selected agent this turn.- // Absent when no agent is picked, which is the ordinary case.- submission.subagentBudget- ? {- ...(submission.config ?? {}),- subagent_consult_budget: submission.subagentBudget,- }- : submission.config,- submission.notebookReferences,- submission.historyReferences,- { bookReferences: submission.bookReferences },- submission.questionNotebookReferences,- submission.persona ?? undefined,- submission.memoryReferences,- );+ sendAsNewMessage();},[awaitingUserReply, disabled, sendMessage, submitUserReply, t],);diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 1541c0a4b..01e102db2 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -75,7 +75,7 @@ import { useAttachmentLimits } from "@/lib/attachment-limits";import {hasPendingAskUser,hasPendingUserCard,- REPLY_NOT_DELIVERED,+ REPLY_SENT_AS_NEW_MESSAGE,} from "@/lib/ask-user-state";import { notify } from "@/lib/notifications";import { copyText } from "@/lib/clipboard";@@ -1772,13 +1772,14 @@ export default function ChatWorkspace() {// not the only one — and a card that never rendered no longer strands// the learner with a turn they can only cancel.if (awaitingUserReplyRef.current) {- if (content.trim()) {- const sent = await submitUserReply({ text: content });- // The composer already cleared what they typed, so a silent drop- // would look like the assistant simply never replied.- if (!sent) notify(t(REPLY_NOT_DELIVERED), { tone: "error" });- }- return;+ if (!content.trim()) return;+ if (await submitUserReply({ text: 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",+ // which is exactly what this branch was preventing them from doing.+ // Fall through and send it as one.+ notify(t(REPLY_SENT_AS_NEW_MESSAGE));}if ((!content &&diff --git a/web/lib/ask-user-state.ts b/web/lib/ask-user-state.tsindex 284205b45..26a022e02 100644--- a/web/lib/ask-user-state.ts+++ b/web/lib/ask-user-state.ts@@ -16,6 +16,21 @@ import { toolResultPayload } from "@/lib/tool-event";export const REPLY_NOT_DELIVERED ="This question is no longer active, so your answer could not be sent. Send a new message to continue.";+/**+ * Shown when a composer's reply was refused and re-sent as a new message.+ *+ * The composers used to raise {@link REPLY_NOT_DELIVERED} instead and stop,+ * which discarded what the user had typed — while telling them to do the one+ * thing the composer was refusing to do. They now fall through to an ordinary+ * message, so the honest report is that the text went somewhere, just not to+ * the question.+ *+ * The card keeps {@link REPLY_NOT_DELIVERED}: its own Submit really has+ * nowhere to send an answer, and it has no composer to fall through to.+ */+export const REPLY_SENT_AS_NEW_MESSAGE =+ "That question is no longer waiting for an answer, so this was sent as a new message.";+type MessageWithEvents = {events?: StreamEvent[];};diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 91a122860..98319f113 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3998,5 +3998,6 @@"Could not copy": "Could not copy","The clipboard is not available in this browser.": "The clipboard is not available in this browser.","attachments": "attachments",- "references": "references"+ "references": "references",+ "That question is no longer waiting for an answer, so this was sent as a new message.": "That question is no longer waiting for an answer, so this was sent as a new message."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 6f054b0cd..e53e8cae1 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3998,5 +3998,6 @@"Could not copy": "复制失败","The clipboard is not available in this browser.": "当前浏览器环境无法使用剪贴板。","attachments": "附件",- "references": "引用"+ "references": "引用",+ "That question is no longer waiting for an answer, so this was sent as a new message.": "这道题已经不再等待作答,所以这条内容作为新消息发送了。"}diff --git a/web/tests/composer-reply-fallthrough.spec.tsx b/web/tests/composer-reply-fallthrough.spec.tsxnew file mode 100644index 000000000..0e4d98909--- /dev/null+++ b/web/tests/composer-reply-fallthrough.spec.tsx@@ -0,0 +1,132 @@+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { initI18n } from "@/i18n/init";++initI18n("en");++/**+ * The composer under test only ever calls back into these two functions, so+ * the interesting behaviour is which one gets the text — and, when the reply+ * is refused, whether the text survives at all.+ */+const chat = vi.hoisted(() => ({+ sendMessage: vi.fn(),+ submitUserReply: vi.fn(async () => true),+ state: {+ messages: [+ {+ id: 1,+ role: "assistant" as const,+ content: "",+ parentMessageId: null,+ events: [+ {+ type: "tool_result",+ metadata: {+ tool_call_id: "call-1",+ tool_metadata: {+ ask_user: { questions: [{ id: "q", prompt: "Which one?" }] },+ },+ },+ },+ ],+ },+ ],+ knowledgeBases: [],+ llmSelection: null,+ personaSelection: null,+ isStreaming: false,+ },+}));++vi.mock("@/features/chat/ChatStateAdapter", () => ({+ useChatStateAdapter: () => ({+ state: chat.state,+ sendMessage: chat.sendMessage,+ submitUserReply: chat.submitUserReply,+ cancelStreamingTurn: () => undefined,+ setKBs: () => undefined,+ setLLMSelection: () => undefined,+ setPersonaSelection: () => undefined,+ }),+}));++vi.mock("@/hooks/useWorkspaceChatActions", () => ({+ useWorkspaceChatActions: () => ({+ capabilities: [],+ activeCapabilityValue: "",+ selectCapability: () => undefined,+ }),+}));++vi.mock("@/hooks/useContextBudget", () => ({+ useContextBudget: () => null,+}));++/** Stands in for the real composer: one button that submits fixed text. */+vi.mock("@/components/chat/home/StandaloneComposer", () => ({+ default: ({+ onSubmit,+ }: {+ onSubmit: (submission: Record<string, unknown>) => void;+ }) => (+ <button+ type="button"+ onClick={() =>+ onSubmit({+ content: "C",+ attachments: [],+ notebookReferences: [],+ historyReferences: [],+ bookReferences: [],+ questionNotebookReferences: [],+ memoryReferences: [],+ config: undefined,+ subagentBudget: undefined,+ persona: null,+ })+ }+ >+ send+ </button>+ ),+}));++const { MasteryComposer } = await import(+ "@/components/space/learning/MasteryComposer"+);++describe("composer routing while a question is open", () => {+ beforeEach(() => {+ chat.sendMessage.mockClear();+ chat.submitUserReply.mockClear();+ chat.submitUserReply.mockImplementation(async () => true);+ });++ it("routes the text to the open question when the turn accepts it", async () => {+ const user = userEvent.setup();+ render(<MasteryComposer placeholder="Ask" />);+ await user.click(screen.getByRole("button", { name: "send" }));+ await waitFor(() =>+ expect(chat.submitUserReply).toHaveBeenCalledWith({ text: "C" }),+ );+ expect(chat.sendMessage).not.toHaveBeenCalled();+ });++ /**+ * The #1273 shape. The backend refuses the reply because the turn that+ * asked is gone; the composer has already cleared the box. Returning here+ * discarded what the learner typed — while the error told them to send a+ * new message, which is the very thing this branch was intercepting.+ */+ it("re-sends as a new message when the reply is refused", async () => {+ chat.submitUserReply.mockImplementation(async () => false);+ const user = userEvent.setup();+ render(<MasteryComposer placeholder="Ask" />);+ await user.click(screen.getByRole("button", { name: "send" }));+ await waitFor(() => expect(chat.sendMessage).toHaveBeenCalled());+ expect(chat.sendMessage.mock.calls[0][0]).toBe("C");+ });+});