Python
feat(gui): keep unsent composer draft when changing conversation/page
cyureklib90c02d56104
diff --git a/surfaces/gui/src/components/Composer.draft.test.tsx b/surfaces/gui/src/components/Composer.draft.test.tsxnew file mode 100644index 00000000..87e0b99e--- /dev/null+++ b/surfaces/gui/src/components/Composer.draft.test.tsx@@ -0,0 +1,100 @@+// Composer draft persistence (UX: an unsent message survives switching conversations and+// navigating to another page/surface and back). See composerDraft.ts.+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { Composer } from "./Composer";+import { loadDraft, saveDraft } from "./composerDraft";++const props = (extra: Partial<Parameters<typeof Composer>[0]> = {}) => ({+ mode: "interactive",+ model: "gpt-5.6-sol",+ running: false,+ connected: true,+ sessionId: "s1",+ onSend: vi.fn(),+ onInterrupt: vi.fn(),+ onModeChange: vi.fn(),+ onModelChange: vi.fn(),+ ...extra,+});++const box = () => screen.getByPlaceholderText(/Ask the coworker/) as HTMLTextAreaElement;+const type = (text: string) => fireEvent.change(box(), { target: { value: text } });++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ localStorage.clear();+});++describe("Composer draft persistence", () => {+ it("keeps an unsent message when switching to another conversation and back", () => {+ const { rerender } = render(<Composer {...props({ sessionId: "s1", resetKey: "s1" })} />);+ type("write a script that copies invoices");+ expect(box().value).toBe("write a script that copies invoices");++ // Switch to another conversation (same mounted Composer, new resetKey).+ rerender(<Composer {...props({ sessionId: "s2", resetKey: "s2" })} />);+ expect(box().value).toBe(""); // new conversation starts empty++ // Come back to the original one.+ rerender(<Composer {...props({ sessionId: "s1", resetKey: "s1" })} />);+ expect(box().value).toBe("write a script that copies invoices");+ });++ it("restores a draft saved to localStorage on mount (page navigation round-trip)", () => {+ // Simulate navigating away: mount, type, then unmount (localStorage gets the draft).+ const { unmount } = render(<Composer {...props({ sessionId: "s1", resetKey: "s1" })} />);+ type("half a message for later");+ unmount();++ // Navigate back: a fresh Composer mount for the same session restores the draft.+ render(<Composer {...props({ sessionId: "s1", resetKey: "s1" })} />);+ expect(box().value).toBe("half a message for later");+ });++ it("does NOT restore a draft once the message was actually sent", () => {+ const onSend = vi.fn();+ const { rerender } = render(+ <Composer {...props({ sessionId: "s1", resetKey: "s1", onSend })} />,+ );+ type("this one gets sent");+ fireEvent.keyDown(box(), { key: "Enter" });+ expect(onSend).toHaveBeenCalledWith("this one gets sent", [], undefined);++ // Switch away and back: nothing should be restored.+ rerender(<Composer {...props({ sessionId: "s2", resetKey: "s2" })} />);+ rerender(<Composer {...props({ sessionId: "s1", resetKey: "s1" })} />);+ expect(box().value).toBe("");+ expect(loadDraft("s1")).toBeUndefined();+ });++ it("persists attachments and the picked skill through the store (serialization round-trip)", () => {+ const attachment = {+ kind: "pdf" as const,+ name: "brief.pdf",+ mime: "application/pdf",+ data_url: "data:application/pdf;base64,AAAA",+ };+ const skill = { name: "weekly-report", description: "Monday report", scope: "global" as const, enabled: true };+ saveDraft("s1", { text: "summarize the attached", attachments: [attachment], skill });++ const restored = loadDraft("s1");+ expect(restored?.text).toBe("summarize the attached");+ expect(restored?.attachments).toEqual([attachment]);+ expect(restored?.skill).toEqual(skill);++ // Empty drafts are pruned rather than left behind.+ saveDraft("s1", { text: " ", attachments: [], skill: null });+ expect(loadDraft("s1")).toBeUndefined();+ });++ it("leaves other sessions' drafts untouched while switching", () => {+ const { rerender } = render(<Composer {...props({ sessionId: "s1", resetKey: "s1" })} />);+ type("draft for session one");+ rerender(<Composer {...props({ sessionId: "s2", resetKey: "s2" })} />);+ type("draft for session two");+ rerender(<Composer {...props({ sessionId: "s1", resetKey: "s1" })} />);+ expect(box().value).toBe("draft for session one");+ });+});diff --git a/surfaces/gui/src/components/Composer.tsx b/surfaces/gui/src/components/Composer.tsxindex 5e4b0e1b..326f99e7 100644--- a/surfaces/gui/src/components/Composer.tsx+++ b/surfaces/gui/src/components/Composer.tsx@@ -5,6 +5,7 @@ import { isPdfFile, readFile } from "../attach";import { ProjectBindMenu } from "./ProjectBindMenu";import { getSettings, inspectPdf, sessionSkills, type SessionSkillRow } from "../api";import { formatTokens, totalTokens } from "../usage";+import { clearDraft, loadDraft, saveDraft, type ComposerDraft } from "./composerDraft";import { Dropdown, type Option } from "./Dropdown";import { Icon } from "./Icon";import { Toggle } from "./Toggle";@@ -207,6 +208,14 @@ export function Composer(props: Props) {const textareaRef = useRef<HTMLTextAreaElement | null>(null);const noticeTimer = useRef<number | null>(null);+ // Latest draft, mirrored each render so unmount/cleanup and the session-switch effect can+ // persist exactly what the user last typed, however state changes between renders.+ const draftRef = useRef<ComposerDraft>({ text: "", attachments: [], skill: null });+ draftRef.current = { text, attachments, skill: pendingSkill };+ // The resetKey this Composer last rendered with; lets the session-switch effect know the+ // session we're LEAVING in order to save its draft before restoring the incoming one.+ const prevResetKey = useRef<string | undefined>(props.resetKey);+// Rejected-attachment notice: visible ~8s, then clears (or on ✕).const showAttachNotice = (message: string) => {setAttachNotice(message);@@ -231,17 +240,35 @@ export function Composer(props: Props) {el.style.overflowY = el.scrollHeight > max ? "auto" : "hidden";}, [text]);- // Clear the draft when the conversation changes, so a half-typed message / picked file doesn't- // bleed from one session into another. Declared BEFORE the prefill effect: when both fire in- // the same render (the Skills doorway starts a new session AND prefills it), effects run in- // declaration order — clear first, then the prefill lands on the fresh session.+ // Persist the unsent draft per conversation: when the active session changes, save the+ // half-typed message / picked file under the session we're LEAVING, then restore whatever+ // draft is saved for the session we're ENTERING (rather than unconditionally wiping the box).+ // Declared BEFORE the prefill effect: when both fire in the same render (the Skills doorway+ // starts a new session AND prefills it), effects run in declaration order — the restore+ // runs first, so the prefill still lands on top of the fresh session.useEffect(() => {- setText("");- setAttachments([]);- setPendingSkill(null);+ const prev = prevResetKey.current;+ const next = props.resetKey;+ prevResetKey.current = next;+ // Save the outgoing draft so it isn't lost on a session switch (first mount: nothing to save).+ if (prev && prev !== next) saveDraft(prev, draftRef.current);+ // Restore the incoming session's saved draft (none → empty box).+ const restored = loadDraft(next);+ setText(restored?.text ?? "");+ setAttachments(restored?.attachments ?? []);+ setPendingSkill(restored?.skill ?? null);// eslint-disable-next-line react-hooks/exhaustive-deps}, [props.resetKey]);+ // Save the draft when the composer unmounts (e.g. navigating to Settings/Inbox or closing+ // the session view), so it survives leaving the page and is restored when you come back.+ useEffect(() => {+ return () => {+ if (prevResetKey.current) saveDraft(prevResetKey.current, draftRef.current);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+// Apply a prefill (text + attachments) pushed from outside, then focus the composer. Applied at// most once per nonce (a ref guards against StrictMode/re-render double-fires), and attachments// are de-duplicated so the same file never lands twice.@@ -401,6 +428,8 @@ export function Composer(props: Props) {setText("");setAttachments([]);setPendingSkill(null);+ // The message is away — drop the persisted draft so it isn't restored on a later visit.+ if (props.resetKey) clearDraft(props.resetKey);};const onKey = (e: React.KeyboardEvent) => {diff --git a/surfaces/gui/src/components/composerDraft.ts b/surfaces/gui/src/components/composerDraft.tsnew file mode 100644index 00000000..e91e831a--- /dev/null+++ b/surfaces/gui/src/components/composerDraft.ts@@ -0,0 +1,70 @@+// Unsent-draft persistence for the composer.+//+// UX: a half-typed message / picked file should survive navigation — switching to+// another conversation, or to Settings / Inbox / another surface and back — instead of+// being wiped the moment the active session changes. Without this, Composer.resetKey+// (= sessionId) cleared the box unconditionally and the draft was gone.+//+// The draft is keyed per session and lives in localStorage, so it also survives a reload+// and restoring an evicted run. It is cleared only once the message is actually sent.+// Mirrors the App.tsx localStorage conventions (best-effort, try/catch around JSON).+import type { Attachment } from "../types";+import type { SessionSkillRow } from "../api";++const DRAFT_KEY_PREFIX = "coworker:composer-draft:v1:";++export interface ComposerDraft {+ text: string;+ attachments: Attachment[];+ // The picked "/" force-run skill (SKILLS-SPEC §4.1 #3): the visible "/name " prefix is+ // UI state derived from this, so restoring it keeps the pending skill intact.+ skill: SessionSkillRow | null;+}++export function draftKey(sessionId: string): string {+ return DRAFT_KEY_PREFIX + sessionId;+}++/** Best-effort read of the saved draft for a session; undefined when none. */+export function loadDraft(sessionId: string | undefined): ComposerDraft | undefined {+ if (!sessionId) return undefined;+ try {+ const raw = localStorage.getItem(draftKey(sessionId));+ if (!raw) return undefined;+ const parsed = JSON.parse(raw) as ComposerDraft;+ // Defensive: only trust structurally-sane payloads.+ if (typeof parsed !== "object" || parsed === null || typeof parsed.text !== "string") {+ return undefined;+ }+ return {+ text: parsed.text,+ attachments: Array.isArray(parsed.attachments) ? parsed.attachments : [],+ skill: parsed.skill ?? null,+ };+ } catch {+ return undefined;+ }+}++/** Save the draft for a session. An empty draft is pruned rather than stored. */+export function saveDraft(sessionId: string, draft: ComposerDraft): void {+ try {+ const empty = !draft.text.trim() && draft.attachments.length === 0 && !draft.skill;+ if (empty) {+ localStorage.removeItem(draftKey(sessionId));+ return;+ }+ localStorage.setItem(draftKey(sessionId), JSON.stringify(draft));+ } catch {+ /* localStorage may be unavailable; draft persistence is best effort. */+ }+}++/** Drop the saved draft for a session (called after a successful send). */+export function clearDraft(sessionId: string): void {+ try {+ localStorage.removeItem(draftKey(sessionId));+ } catch {+ /* best effort */+ }+}