diff --git a/docs/api.md b/docs/api.md index f1d7ec614..4281532ad 100644 --- a/docs/api.md +++ b/docs/api.md @@ -920,6 +920,9 @@ question can name another (`POST /chats/{cid}/messages {content, model}`, e.g. t a 400. Each answer records the `model` that wrote it. `POST /chats/{cid}/stop` stops the answer being written in your conversation after the piece or tool step it's on: the stream sends `stopped`, then `done` with the saved message, whose `stopped` is true and whose `content` is what came before (`(stopped)` when nothing had). `{stopping: false}` when nothing was being written. +`POST /chats/{cid}/messages {content, edit}` edits one of your earlier questions (`edit` is its message id): it and +everything after it are replaced by this question and its new answer; 404 when `edit` isn't a question in that +conversation. A conversation titled after the first question is retitled when that question is edited. A conversation's `scope` narrows what it draws on: `namespaces`, `recordings`, `collections`, `speakers`, `from` and `to`; every key narrows it further, and an empty scope is everything you can read. `collections` are ids of diff --git a/docs/assistant.md b/docs/assistant.md index d775d9c54..c59b7a63e 100644 --- a/docs/assistant.md +++ b/docs/assistant.md @@ -15,6 +15,8 @@ then. is writing it); what came before is saved, marked stopped. A model call already under way finishes first. - **Reopening:** a conversation's answers keep the tools the assistant used (and with what), any notice (the model couldn't use tools), the error when there was no answer, and their latest source check. +- **Editing a question:** Edit on a question you asked asks it again as edited; the answer and everything after it + are replaced (`POST /api/v1/chats//messages` with `edit`). - **Changed access:** old citations are filtered by the person's current access when a conversation is reopened. - **Choosing the model:** a conversation can use any model an admin offers (`llm.chat_models`, else whatever the model server lists); Try another model asks a question again with a different one. Each answer records the model that diff --git a/fastapi_backend/app/api/v1/routes/chats.py b/fastapi_backend/app/api/v1/routes/chats.py index 74e1f3dcd..972721ebb 100644 --- a/fastapi_backend/app/api/v1/routes/chats.py +++ b/fastapi_backend/app/api/v1/routes/chats.py @@ -176,7 +176,11 @@ def _ev(name: str, data: Any) -> str: async def send_message(cid: int, body: MessageCreate, user: Writer, acl: Acl, db: Db, cfg: Cfg, request: Request) -> StreamingResponse: """Ask a question, optionally from a page (`context`: the page, its text and any highlighted part, which the model reads with the 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). Without `context`, it keeps the page it was asked + from (where, and the highlighted text; not the page's text, which isn't kept).""" c = await run_in_threadpool(_own_chat, db, cid, user) q = body.content.strip()[:4000] files = await run_in_threadpool(_attachments, db, body.attachments, user) @@ -184,19 +188,30 @@ async def send_message(cid: int, body: MessageCreate, user: Writer, acl: Acl, db q = "I attached " + ("this file." if len(files) == 1 else "these files.") if not q: raise HTTPException(400, "ask something") - page = body.context.model_dump() if body.context else None - # what the model reads: the question with the page it was asked from, and the files it can import - asked = chat.with_context(q, page) + chat.attached_note(files) # this answer's model: the one asked for (400 if it isn't offered), else the conversation's while it's still offered model = await run_in_threadpool(_model, cfg, body.model) if body.model else c.get("model") if model and not body.model and model not in await run_in_threadpool(chat.model_choices, cfg): model = None + title = c["title"] + page = body.context.model_dump() if body.context else None + kept = chat.shared_context(page) # what the question keeps of the page + if body.edit is not None: # only after the question checks out, so a refused edit removes nothing + try: + old = await run_in_threadpool(chat.rewind, db, cid, body.edit) + except KeyError: + raise HTTPException(404, "no such question in this conversation") from None + if title == old["content"][:80]: # titled after the question being edited: retitle it after the edit + title = "New conversation" + if page is None and old.get("context"): + page = kept = old["context"] + # what the model reads: the question with the page it was asked from, and the files it can import + asked = chat.with_context(q, page) + chat.attached_note(files) readable = set(acl.roles) def prepare() -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: past = chat.history(db, cid) - chat.add(db, cid, "user", q, attachments=files, context=chat.shared_context(page)) - if not past and c["title"] == "New conversation": + chat.add(db, cid, "user", q, attachments=files, context=kept) + 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 d9b82f9ee..8c6943160 100644 --- a/fastapi_backend/app/domain/chat.py +++ b/fastapi_backend/app/domain/chat.py @@ -357,6 +357,16 @@ def add( return mid +def rewind(db, cid, mid): + """Remove a question of yours and everything said after it, to ask it again as edited; returns the old question + (its content and the page context it was asked with).""" + m = db.one("SELECT chat, role, content, context 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 + + 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 da3a4ac3d..b6a009a14 100644 --- a/fastapi_backend/app/schemas/chats.py +++ b/fastapi_backend/app/schemas/chats.py @@ -161,6 +161,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 af19233b9..d748b168f 100644 --- a/fastapi_backend/tests/api/test_chats.py +++ b/fastapi_backend/tests/api/test_chats.py @@ -391,6 +391,70 @@ def test_tools_stay_in_scope_and_say_what_is_missing(app, db, cfg, folder, new_c 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" + + # a refused edit (a model that isn't offered) removes nothing + n = len(client.get(f"/api/v1/chats/{cid}", headers=h).json()["messages"]) + assert ( + client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "x", "edit": first, "model": "gpt-9"}).status_code == 400 + ) + assert len(client.get(f"/api/v1/chats/{cid}", headers=h).json()["messages"]) == n + + # a question asked from a page keeps the page and the highlighted text when edited + page = {"url": "/library", "title": "Library", "text": "Shipment report", "selection": "Dyno shipment"} + sse(client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "When?", "context": page}).text) + asked = client.get(f"/api/v1/chats/{cid}", headers=h).json()["messages"][-2] + llm.seen.clear() + sse(client.post(f"/api/v1/chats/{cid}/messages", headers=h, json={"content": "When exactly?", "edit": asked["id"]}).text) + assert '"""\nDyno shipment\n"""' in llm.seen[-1]["messages"][-1]["content"] + edited = client.get(f"/api/v1/chats/{cid}", headers=h).json()["messages"][-2] + assert (edited["content"], edited["context"]) == ("When exactly?", asked["context"]) + + def test_asking_from_a_page(plain, client, db, cfg, folder, llm): """Chat on any page: the model reads the page and the highlighted part with the question; the question keeps where it was asked and what was highlighted, not the page's text.""" diff --git a/nextjs-frontend/__tests__/chat.test.tsx b/nextjs-frontend/__tests__/chat.test.tsx index 2ea7f01ef..bca2166ec 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 { @@ -14,6 +14,18 @@ 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"; + +jest.mock("@/components/chat/attachments", () => ({ + SentFiles: ({ files }: { files: { filename: string }[] }) => ( + + ), +})); +import { TooltipProvider } from "@/components/ui/tooltip"; describe("citations", () => { it("splits [n], [n, m] and [n][m]", () => { @@ -177,3 +189,49 @@ 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("re-sends a files-only question's files, with the text you add", () => { + const onEdit = jest.fn(); + render( + + + , + ); + expect(screen.queryByText("I attached this file.")).not.toBeInTheDocument(); + expect(screen.getByText("a.pdf")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + const box = screen.getByRole("textbox", { name: "Edit your question" }); + expect(box).toHaveValue(""); + fireEvent.change(box, { target: { value: "Summarise it" } }); + fireEvent.click(screen.getByRole("button", { name: "Send" })); + expect(onEdit).toHaveBeenCalledWith("Summarise it"); + }); + + 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 c56f69027..71b4e9651 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -5563,6 +5563,10 @@ export class Chats { * Ask a question, optionally from a page (`context`: the page, its text and any highlighted part, which the model * reads with the 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). Without `context`, it keeps the page it was asked + * from (where, and the highlighted text; not the page's text, which isn't kept). */ 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 dabe5b8e2..77c20743c 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -5357,6 +5357,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 416f28891..ec448f021 100644 --- a/nextjs-frontend/components/chat/chat-app.tsx +++ b/nextjs-frontend/components/chat/chat-app.tsx @@ -8,9 +8,9 @@ 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 { AttachmentChips, SentFiles, useAttachments } from "@/components/chat/attachments"; +import { AttachmentChips, useAttachments } from "@/components/chat/attachments"; import { shortTitle } from "@/components/chat/cite"; import { Composer, ScopeBar } from "@/components/chat/composer"; import { ConversationList } from "@/components/chat/conversations"; @@ -19,6 +19,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 { onlyFiles, UserBubble } from "@/components/chat/user-bubble"; import { SharedFrom } from "@/components/page-chat/page-chat"; import { useRecordingIndex, useSpeakerDirectory } from "@/components/search/data"; import { Banner } from "@/components/ui/banner"; @@ -36,7 +37,6 @@ type Live = { chatId: number; turn: TurnState; files: Sent[] }; type Queued = { key: number; text: string; files: Sent[] }; /** What a message with only files says (the server says the same when it gets none). */ -const onlyFiles = (n: number) => (n === 1 ? "I attached this file." : "I attached these files."); type Extra = { steps: ToolStep[]; notice: string | null; error: string | null }; type Pair = { key: string; q: ChatMessage | null; a: ChatMessage | null }; @@ -55,19 +55,6 @@ function pairs(msgs: ChatMessage[]): Pair[] { return out; } -function UserBubble({ text, files = [] }: { text: string; files?: { filename: string; size: number }[] }) { - return ( -
- - {!(files.length && text === onlyFiles(files.length)) && ( -
- {text} -
- )} -
- ); -} - function streamError(e: unknown): string { if (e instanceof SSEError) { if (e.status === 401) return "You were signed out. Sign in again and retry"; @@ -170,7 +157,11 @@ export function ChatApp() { ); const run = useCallback( - async (cid: number, question: string, model?: string, attached: Sent[] = []): Promise => { + async (cid: number, question: string, model?: string, attached: Sent[] = [], edit?: number): Promise => { + 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); @@ -180,7 +171,7 @@ export function ChatApp() { try { for await (const msg of streamSSE(`/api/v1/chats/${cid}/messages`, { method: "POST", - body: { content: question, model, attachments: attached.map((f) => f.id) }, + body: { content: question, model, attachments: attached.map((f) => f.id), edit }, accessToken: session?.accessToken, signal: ac.signal, })) { @@ -224,6 +215,7 @@ export function ChatApp() { model?: string, attached: Sent[] = [], kind: "chat" | "setup" = "chat", + edit?: number, ): Promise => { let cid = kind === "setup" ? null : activeId; if (cid == null) { @@ -248,7 +240,7 @@ export function ChatApp() { return null; } } - return run(cid, question, model, attached); + return run(cid, question, model, attached, edit); }, [activeId, client, draftScope, draftModel, qc, router, run, toast], ); @@ -276,6 +268,17 @@ export function ChatApp() { void dispatch(next.text, undefined, next.files); }, [live, queue, dispatch]); + // Editing a question asks it again (with the files it had): it and everything after it are replaced. + const editQuestion = useCallback( + (q: ChatMessage, text: string) => { + const attached: Sent[] = (q.attachments ?? []).map(({ id, filename, size }) => ({ id, filename, size })); + const question = text.trim() || (attached.length ? onlyFiles(attached.length) : ""); + if (!question || live) return; + void dispatch(question, undefined, attached, "chat", q.id); + }, + [dispatch, live], + ); + // Voice mode: hear a question, send it, read the answer aloud, listen again, until the mic is tapped off or // nothing is said twice in a row. /chat?voice=1 (the assistant home's mic) starts it at once. const voice = useVoice(); @@ -544,7 +547,11 @@ export function ChatApp() { {it.q && (
- + editQuestion(it.q!, t) : undefined} + />
)} {it.a ? ( diff --git a/nextjs-frontend/components/chat/user-bubble.tsx b/nextjs-frontend/components/chat/user-bubble.tsx new file mode 100644 index 000000000..79b140ed6 --- /dev/null +++ b/nextjs-frontend/components/chat/user-bubble.tsx @@ -0,0 +1,84 @@ +"use client"; + +import { Pencil } from "lucide-react"; +import { useState } from "react"; + +import { SentFiles } from "@/components/chat/attachments"; +import { Button, IconButton } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +/** What a question that only sends files says. */ +export const onlyFiles = (n: number) => (n === 1 ? "I attached this file." : "I attached these files."); + +/** A question you asked, with the files sent with it. With `onEdit` (not while an answer is being written) it can be edited, which asks it again: + * the answers and questions after it are replaced. */ +export function UserBubble({ + text, + files = [], + onEdit, +}: { + text: string; + files?: { filename: string; size: number }[]; + onEdit?: (text: string) => void; +}) { + const [editing, setEditing] = useState(null); + const filesOnly = files.length > 0 && text === onlyFiles(files.length); + 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 || files.length > 0; + const save = () => { + if (!ready) return; + setEditing(null); + if (editing.trim() !== (filesOnly ? "" : text.trim())) onEdit(editing.trim()); + }; + return ( +
+ +
+