From d4d14d25e4e7697aeb30b1157731c62da57427ae Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sat, 3 Oct 2026 00:23:04 +0000 Subject: [PATCH 1/2] feat(chat): edit a question you asked and get a new answer POST /chats/{cid}/messages takes `edit`, the id of one of your earlier questions: it and everything after it are replaced by the edited question and its new answer. A conversation titled after the edited first question is retitled; a title you set is kept. In the chat page, each question has an Edit button (hidden while an answer is being written). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_012HJLUkBjcHPCPS9aGhPH2Y --- fastapi_backend/app/api/v1/routes/chats.py | 15 ++++- fastapi_backend/app/domain/chat.py | 9 +++ fastapi_backend/app/schemas/chats.py | 5 ++ fastapi_backend/tests/api/test_chats.py | 47 ++++++++++++++ nextjs-frontend/__tests__/chat.test.tsx | 33 +++++++++- nextjs-frontend/app/openapi-client/sdk.gen.ts | 3 + .../app/openapi-client/types.gen.ts | 6 ++ nextjs-frontend/components/chat/chat-app.tsx | 32 ++++----- .../components/chat/user-bubble.tsx | 65 +++++++++++++++++++ nextjs-frontend/openapi.json | 14 +++- 10 files changed, 210 insertions(+), 19 deletions(-) create mode 100644 nextjs-frontend/components/chat/user-bubble.tsx diff --git a/fastapi_backend/app/api/v1/routes/chats.py b/fastapi_backend/app/api/v1/routes/chats.py index 16436c4a8..f141f4a3d 100644 --- a/fastapi_backend/app/api/v1/routes/chats.py +++ b/fastapi_backend/app/api/v1/routes/chats.py @@ -157,7 +157,10 @@ def _ev(name: str, data: Any) -> str: ) async def send_message(cid: int, body: MessageCreate, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> StreamingResponse: """Ask a question. Streams events: step, approval, notice, passages, token (answer text), error, stopped (POST - /chats/{cid}/stop: what came before is saved, marked stopped), done (the saved message id).""" + /chats/{cid}/stop: what came before is saved, marked stopped), done (the saved message id). + + With `edit`, one of your earlier questions is edited: it and everything after it are replaced by this question and + its new answer (404 if it isn't a question in this conversation).""" c = await run_in_threadpool(_own_chat, db, cid, user) q = body.content.strip()[:4000] if not q: @@ -169,9 +172,17 @@ async def send_message(cid: int, body: MessageCreate, user: Writer, acl: Acl, db readable = set(acl.roles) def prepare() -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + title = c["title"] + if body.edit is not None: + try: + old = chat.rewind(db, cid, body.edit) + except KeyError: + raise HTTPException(404, "no such question in this conversation") from None + if title == old[:80]: # titled after the question being edited: retitle it after the edit + title = "New conversation" past = chat.history(db, cid) chat.add(db, cid, "user", q) - if not past and c["title"] == "New conversation": + if not past and title == "New conversation": db.q("UPDATE $r SET title = $t", r=R("chat", cid), t=q[:80]) return past, chat.retrieve(db, q, readable, c.get("scope"), cfg=cfg) diff --git a/fastapi_backend/app/domain/chat.py b/fastapi_backend/app/domain/chat.py index b294303d6..fd91c95a2 100644 --- a/fastapi_backend/app/domain/chat.py +++ b/fastapi_backend/app/domain/chat.py @@ -299,6 +299,15 @@ def add(db, cid, role, content, passages=None, stopped=False, steps=None, notice return mid +def rewind(db, cid, mid): + """Remove a question of yours and everything said after it, to ask it again as edited; returns its old text.""" + m = db.one("SELECT chat, role, content FROM $r", r=R("chat_message", mid)) + if not m or m["chat"] != cid or m["role"] != "user": + raise KeyError(mid) + db.q("DELETE chat_message WHERE chat = $c AND record::id(id) >= $m", c=cid, m=mid) + return m["content"] + + def model_choices(cfg): """The models people may pick: the configured one first, then llm.chat_models, or (when that's empty) whatever the model server lists. Just the configured one when the server's list can't be had.""" diff --git a/fastapi_backend/app/schemas/chats.py b/fastapi_backend/app/schemas/chats.py index 63f6840b3..c398c9cf3 100644 --- a/fastapi_backend/app/schemas/chats.py +++ b/fastapi_backend/app/schemas/chats.py @@ -116,6 +116,11 @@ class MessageCreate(RequestModel): model: str | None = Field( None, description="answer this one with another model (one of GET /chats/capabilities `models`), e.g. to retry" ) + edit: int | None = Field( + None, + description="edit one of your earlier questions (its message id): it and everything after it are replaced by this " + "question and a new answer", + ) class Approval(ResponseModel): diff --git a/fastapi_backend/tests/api/test_chats.py b/fastapi_backend/tests/api/test_chats.py index 57d90e97b..d44f0aa3f 100644 --- a/fastapi_backend/tests/api/test_chats.py +++ b/fastapi_backend/tests/api/test_chats.py @@ -389,3 +389,50 @@ def test_tools_stay_in_scope_and_say_what_is_missing(app, db, cfg, folder, new_c assert box.call("graph_neighbours", {})[1] == "graph_neighbours: give an entity_id or a speaker_id" assert box.call("propose_entity_change", {"action": "retype", "entity_id": 1})[1] == "propose_entity_change: retype needs new_type" assert box.approvals == [] + + +def test_editing_a_question(plain, client, new_client, db, cfg, folder, llm): + seed(db, cfg, folder) + make_user(db, "ed@x.io", "editor password 1", roles={"pods": "editor", "calls": "editor"}) + make_user(db, "vi@x.io", "viewer password 1", roles={"pods": "viewer"}) + h = login(client, "ed@x.io", "editor password 1") + other = new_client() + hv = login(other, "vi@x.io", "viewer password 1") + cid = client.post("/api/v1/chats", headers=h, json={}).json()["id"] + for q in ("When does the shipment leave?", "Who is shipping it?", "And where to?"): + sse(client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": q}).text) + msgs = client.get(f"/api/v1/chats/{cid}", headers=h).json()["messages"] + assert len(msgs) == 6 + second = msgs[2]["id"] + + # an answer, someone else's or another conversation's message isn't a question you can edit here + assert client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "x", "edit": msgs[1]["id"]}).status_code == 404 + assert client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "x", "edit": 999999}).status_code == 404 + assert other.post(f"/api/v1/chats/{cid}/messages", headers=hv, json={"content": "x", "edit": second}).status_code == 404 + elsewhere = client.post("/api/v1/chats", headers=h, json={}).json()["id"] + assert client.post(f"/api/v1/chats/{elsewhere}/messages", headers=h, json={"content": "x", "edit": second}).status_code == 404 + assert len(client.get(f"/api/v1/chats/{cid}", headers=h).json()["messages"]) == 6 # nothing was removed + + # editing the second question replaces it and everything after it; the model sees only what came before + llm.seen.clear() + ev = sse(client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "Who ships it, exactly?", "edit": second}).text) + assert ev["done"] + sent = [m["content"] for m in llm.seen[-1]["messages"] if m["role"] == "user"] + assert "When does the shipment leave?" in sent[0] and not any("Who is shipping it?" in s or "And where to?" in s for s in sent) + c = client.get(f"/api/v1/chats/{cid}", headers=h).json() + assert [m["content"] for m in c["messages"] if m["role"] == "user"] == ["When does the shipment leave?", "Who ships it, exactly?"] + assert [m["role"] for m in c["messages"]] == ["user", "assistant", "user", "assistant"] + assert c["title"] == "When does the shipment leave?" + + # editing the first question retitles a conversation titled after it, but keeps a title you set + first = c["messages"][0]["id"] + sse(client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "When is the Friday shipment?", "edit": first}).text) + c = client.get(f"/api/v1/chats/{cid}", headers=h).json() + assert ([m["content"] for m in c["messages"] if m["role"] == "user"], c["title"]) == ( + ["When is the Friday shipment?"], + "When is the Friday shipment?", + ) + assert client.patch(f"/api/v1/chats/{cid}", headers=h, json={"title": "Shipping"}).status_code == 200 + first = c["messages"][0]["id"] + sse(client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "When does it ship?", "edit": first}).text) + assert client.get(f"/api/v1/chats/{cid}", headers=h).json()["title"] == "Shipping" diff --git a/nextjs-frontend/__tests__/chat.test.tsx b/nextjs-frontend/__tests__/chat.test.tsx index 009cac44a..3e6664410 100644 --- a/nextjs-frontend/__tests__/chat.test.tsx +++ b/nextjs-frontend/__tests__/chat.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen } from "@testing-library/react"; import "@testing-library/jest-dom"; import { @@ -13,6 +13,8 @@ import { } from "@/components/chat/cite"; import { parseBlocks, RichText } from "@/components/chat/rich-text"; import { applyEvent, newTurn, savedSteps, stepCall } from "@/components/chat/stream"; +import { UserBubble } from "@/components/chat/user-bubble"; +import { TooltipProvider } from "@/components/ui/tooltip"; describe("citations", () => { it("splits [n], [n, m] and [n][m]", () => { @@ -169,3 +171,32 @@ describe("rich text", () => { expect(screen.getByText(/not html<\/b>/)).toBeInTheDocument(); }); }); + +describe("editing a question", () => { + it("edits in place and sends the new text, or cancels", () => { + const onEdit = jest.fn(); + render( + + + , + ); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + const box = screen.getByRole("textbox", { name: "Edit your question" }); + expect(box).toHaveValue("When does it ship?"); + fireEvent.change(box, { target: { value: " When does the Friday shipment leave? " } }); + fireEvent.keyDown(box, { key: "Enter" }); + expect(onEdit).toHaveBeenCalledWith("When does the Friday shipment leave?"); + expect(screen.queryByRole("textbox")).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + fireEvent.change(screen.getByRole("textbox"), { target: { value: "something else" } }); + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + expect(onEdit).toHaveBeenCalledTimes(1); + expect(screen.getByText("When does it ship?")).toBeInTheDocument(); + }); + + it("can't be edited without a handler, e.g. while an answer is written", () => { + render(); + expect(screen.queryByRole("button", { name: "Edit" })).not.toBeInTheDocument(); + }); +}); diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index ef1f2a063..03efc1007 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -4924,6 +4924,9 @@ export class Chats { * * Ask a question. Streams events: step, approval, notice, passages, token (answer text), error, stopped (POST * /chats/{cid}/stop: what came before is saved, marked stopped), done (the saved message id). + * + * With `edit`, one of your earlier questions is edited: it and everything after it are replaced by this question and + * its new answer (404 if it isn't a question in this conversation). */ public static sendMessage( options: Options, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 959104967..15b76d80b 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -4287,6 +4287,12 @@ export type MessageCreate = { * answer this one with another model (one of GET /chats/capabilities `models`), e.g. to retry */ model?: string | null; + /** + * Edit + * + * edit one of your earlier questions (its message id): it and everything after it are replaced by this question and a new answer + */ + edit?: number | null; }; /** diff --git a/nextjs-frontend/components/chat/chat-app.tsx b/nextjs-frontend/components/chat/chat-app.tsx index a1267e6b8..d2316b4af 100644 --- a/nextjs-frontend/components/chat/chat-app.tsx +++ b/nextjs-frontend/components/chat/chat-app.tsx @@ -8,7 +8,7 @@ import { useParams, useRouter, useSearchParams } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Chats } from "@/app/openapi-client"; -import type { AnswerCheck, Approval, ChatMessage, Estimate, Passage } from "@/app/openapi-client/types.gen"; +import type { AnswerCheck, Approval, Chat, ChatMessage, Estimate, Passage } from "@/app/openapi-client/types.gen"; import { Answer } from "@/components/chat/answer"; import { shortTitle } from "@/components/chat/cite"; import { Composer, ScopeBar } from "@/components/chat/composer"; @@ -18,6 +18,7 @@ import { EmptyChat } from "@/components/chat/empty"; import { fromApiScope, scopeFromParams, toApiScope, type Scope } from "@/components/chat/scope"; import { CitationSheet, SourcesPanel, SourcesSheet } from "@/components/chat/sources"; import { applyEvent, newTurn, savedSteps, type ToolStep, type TurnState } from "@/components/chat/stream"; +import { UserBubble } from "@/components/chat/user-bubble"; import { useRecordingIndex, useSpeakerDirectory } from "@/components/search/data"; import { Banner } from "@/components/ui/banner"; import { Button, IconButton } from "@/components/ui/button"; @@ -47,14 +48,6 @@ function pairs(msgs: ChatMessage[]): Pair[] { return out; } -function UserBubble({ text }: { text: string }) { - return ( -
- {text} -
- ); -} - function streamError(e: unknown): string { if (e instanceof SSEError) { if (e.status === 401) return "You were signed out. Sign in again and retry"; @@ -149,7 +142,11 @@ export function ChatApp() { ); const run = useCallback( - async (cid: number, question: string, model?: string) => { + async (cid: number, question: string, model?: string, edit?: number) => { + if (edit != null) + qc.setQueryData(["chat", cid], (c) => + c ? { ...c, messages: (c.messages ?? []).filter((m) => m.id < edit) } : c, + ); const ac = new AbortController(); abortRef.current = ac; let turn = newTurn(question); @@ -158,7 +155,7 @@ export function ChatApp() { try { for await (const msg of streamSSE(`/api/v1/chats/${cid}/messages`, { method: "POST", - body: { content: question, model }, + body: { content: question, model, edit }, accessToken: session?.accessToken, signal: ac.signal, })) { @@ -195,10 +192,10 @@ export function ChatApp() { ); const send = useCallback( - async (text?: string, model?: string) => { + async (text?: string, model?: string, edit?: number) => { const question = (text ?? draft).trim(); if (!question || streaming) return; - setDraft(""); + if (edit == null) setDraft(""); let cid = activeId; if (cid == null) { try { @@ -222,7 +219,7 @@ export function ChatApp() { return; } } - void run(cid, question, model); + void run(cid, question, model, edit); }, [activeId, client, draft, draftScope, draftModel, qc, router, run, streaming, toast], ); @@ -428,7 +425,12 @@ export function ChatApp() { const ex = it.a ? extras[it.a.id] : undefined; return (
- {it.q && } + {it.q && ( + send(t, undefined, it.q!.id) : undefined} + /> + )} {it.a ? ( void }) { + const [editing, setEditing] = useState(null); + const bubble = + "max-w-[520px] self-end rounded-[16px_16px_4px_16px] bg-surface-neutral px-4 py-3 text-[15px] leading-normal text-fg"; + if (editing != null && onEdit) { + const ready = editing.trim().length > 0; + const save = () => { + if (!ready) return; + setEditing(null); + if (editing.trim() !== text.trim()) onEdit(editing.trim()); + }; + return ( +
+