From 1eda79311412cf76355743acc1c7a05cd754121a Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Fri, 20 Nov 2026 13:50:46 -0800 Subject: [PATCH 1/2] feat(settings): edit base instructions with the shared editor Show the base prompt in a browsable list and put text editing and section actions together. Preserve source when the rich editor cannot round-trip it, and keep the last committed choices visible while a save is pending. Co-authored-by: Rizz <302abe414ca6e3134763d2539bfcf145aea2a63fe5f8455204ed602fd40cf381@feedback.communities.buzz.xyz> Co-authored-by: Carl Signed-off-by: Taylor Ho --- docs/buzz-help.md | 4 + src/app/AgentSettings.test.tsx | 24 +- .../agents/BaseInstructions.module.css | 60 + src/features/agents/BaseInstructions.test.tsx | 774 +++++++++---- src/features/agents/BaseInstructions.tsx | 1022 +++++++++++------ src/features/agents/prompt-sections.test.ts | 15 + src/features/agents/prompt-sections.ts | 4 +- .../messages/DocumentEditor.module.css | 29 + src/features/messages/DocumentEditor.tsx | 78 +- tests/browser/settings-layout.spec.mjs | 224 ++++ 10 files changed, 1574 insertions(+), 660 deletions(-) create mode 100644 src/features/agents/BaseInstructions.module.css diff --git a/docs/buzz-help.md b/docs/buzz-help.md index f74ba87c2d..16fa7bd411 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -141,6 +141,10 @@ if that desktop app is up and running. **Load earlier activity** to see more history. - **Instructions** change how an agent behaves. They don't give it new tools, accounts or permissions. +- **Settings → Agent setup → Base instructions** shows the instructions Buzz + gives agents on this device. Open a section to read it. For editable + sections, use **Save** or **Cancel**. **Options** lets you disable or enable + a section, or put the default text back in the editor for you to save. - **Sessions.** By default an agent starts a fresh conversation for each thread. Its settings can make it one per channel or one per community. - **While it works**, the agent shows typing dots, and you can stop it. If it diff --git a/src/app/AgentSettings.test.tsx b/src/app/AgentSettings.test.tsx index 76b0a4ec85..4e2bf03782 100644 --- a/src/app/AgentSettings.test.tsx +++ b/src/app/AgentSettings.test.tsx @@ -1,6 +1,13 @@ // @vitest-environment jsdom import "@testing-library/jest-dom/vitest"; -import { act, cleanup, render, screen, waitFor } from "@testing-library/react"; +import { + act, + cleanup, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, expect, it, vi } from "vitest"; import { ToastProvider } from "../shared/design-system/ui/Toast"; @@ -88,9 +95,18 @@ it("shows the base instructions, kept in the agents' storage", async () => { />, { wrapper: ToastProvider }, ); - await user.click(screen.getByRole("combobox", { name: "Progress" })); - await user.click(await screen.findByRole("option", { name: "Off" })); - await user.click(screen.getByRole("button", { name: "Save" })); + await user.click(screen.getByRole("button", { name: /^Show all \(\d+\)$/ })); + await user.click(screen.getByRole("button", { name: "Progress" })); + await user.click( + screen.getByRole("button", { name: "Options for Progress" }), + ); + await user.click(await screen.findByRole("menuitem", { name: "Disable" })); + const confirmation = screen.getByRole("alertdialog", { + name: "Save instruction change?", + }); + await user.click( + within(confirmation).getByRole("button", { name: "Disable" }), + ); await waitFor(() => expect(ownerChoices(storage)).toEqual({ progress: { mode: "off" } }), ); diff --git a/src/features/agents/BaseInstructions.module.css b/src/features/agents/BaseInstructions.module.css new file mode 100644 index 0000000000..25b7d0775b --- /dev/null +++ b/src/features/agents/BaseInstructions.module.css @@ -0,0 +1,60 @@ +.rowTitle { + opacity: 1; +} + +button[aria-expanded="true"] .rowTitle { + opacity: 0; +} + +@media (prefers-reduced-motion: no-preference) { + html:not([data-keyboard-input]) .rowTitle { + transition: opacity var(--duration-state) var(--easing-enter); + } +} + +.markdown > p:has(+ p) { + margin-block-end: var(--space-2); +} + +.markdown > p + p { + margin-block-start: var(--space-2); +} + +.sectionPreview > [data-layout="rows"] { + border-block-end-color: transparent; + border-end-start-radius: 0; + border-end-end-radius: 0; +} + +.sectionPreview:not(:has(:focus-visible, [aria-expanded="true"])) { + mask-image: linear-gradient( + to bottom, + black calc(100% - var(--space-16)), + calc(100% - var(--space-6)), + transparent + ); + + @media (prefers-reduced-transparency: reduce), (forced-colors: active) { + mask-image: none; + } +} + +.editor, +.readingArea { + --instruction-text-max-height: min(16rem, 32dvh); +} + +.editor { + --document-field-max-height: var(--instruction-text-max-height); +} + +.readingArea { + max-block-size: var(--instruction-text-max-height); + overflow-y: auto; +} + +html[data-keyboard-navigation] .readingArea:focus-visible { + mask-image: none; + outline: 2px solid var(--border-focus); + outline-offset: -2px; +} diff --git a/src/features/agents/BaseInstructions.test.tsx b/src/features/agents/BaseInstructions.test.tsx index 280206f39c..ce2bf0e923 100644 --- a/src/features/agents/BaseInstructions.test.tsx +++ b/src/features/agents/BaseInstructions.test.tsx @@ -1,7 +1,9 @@ // @vitest-environment jsdom import "@testing-library/jest-dom/vitest"; import { + act, cleanup, + fireEvent, render, screen, waitFor, @@ -11,6 +13,7 @@ import userEvent from "@testing-library/user-event"; import { afterEach, expect, it, vi } from "vitest"; import { SECTIONS } from "../agent-harness/sections"; import { SECTION_TEXT_BYTES } from "../agent-harness/sections/choices"; +import type { ComposerInputElement } from "../messages/composer-dom"; import { BaseInstructions } from "./BaseInstructions"; import { defaultHash, @@ -45,59 +48,141 @@ const memory = (global?: unknown) => { }; const defaultOf = (id: string) => String(SECTIONS.find((section) => section.id === id)?.text).trim(); -const choice = (title: string) => screen.getByRole("combobox", { name: title }); -const choose = async ( +const sectionActions = (title: string) => + screen.getByRole("button", { name: `Options for ${title}` }); +const chooseSectionAction = async ( user: ReturnType, title: string, - mode: string, + action: string, ) => { - await user.click(choice(title)); - await user.click(await screen.findByRole("option", { name: mode })); + await user.click(sectionActions(title)); + await user.click(await screen.findByRole("menuitem", { name: action })); +}; +const saveButton = () => screen.getByRole("button", { name: "Save" }); +const dialog = () => + screen.getByRole("alertdialog", { name: "Save instruction change?" }); +const notice = /^Older Codex conversations on this device start over once\./; +const sectionRow = (title: string) => + screen.getByRole("button", { name: title }); +const showAll = (count = SECTIONS.length) => sectionRow(`Show all (${count})`); +const openSection = async ( + user: ReturnType, + title: string, +) => { + if (!screen.queryByRole("button", { name: title })) { + await user.click(showAll()); + } + if (!screen.queryByRole("region", { name: title })) { + await user.click(sectionRow(title)); + } +}; +const disableSection = async ( + user: ReturnType, + title: string, +) => { + await openSection(user, title); + await chooseSectionAction(user, title, "Disable"); }; const editor = (title: string) => - screen.getByRole("textbox", { name: `Your text for ${title}` }); + screen.getByRole("textbox", { + name: `Your text for ${title}`, + }); +const editText = (title: string, text: string) => { + act(() => { + editor(title).value = text; + }); +}; -it("shows defaults read-only and keeps the custom draft when switching modes", async () => { +it("discloses the sections in prompt order and preserves an edit across collapse and section changes", async () => { const user = userEvent.setup(); const store = memory(); render(); - for (const section of SECTIONS.filter((section) => section.owner)) { - const preview = screen.getByRole("textbox", { - name: `Default text for ${section.title}`, - }); - expect(preview).toHaveValue(defaultOf(section.id)); - expect(preview).toHaveAttribute("readonly"); - expect(preview).toBeEnabled(); - expect(preview).toHaveAccessibleDescription("Choose Custom to edit."); - } - const preview = () => - screen.getByRole("textbox", { name: "Default text for Progress" }); - await user.click(preview()); - await user.keyboard("Changed"); - expect(preview()).toHaveValue(defaultOf("progress")); + const group = screen.getByRole("region", { name: "Base instructions" }); + const titles = SECTIONS.map((section) => section.title ?? "Opening lines"); + const collapsedRows = () => + within(group) + .getAllByRole("button", { expanded: false }) + .flatMap((row) => row.getAttribute("aria-label") ?? []); + expect(collapsedRows()).toEqual(titles.slice(0, 4)); expect( - screen.queryByRole("button", { name: "Save" }), + screen.queryByRole("button", { name: "Customize" }), ).not.toBeInTheDocument(); - await choose(user, "Progress", "Custom"); - expect(editor("Progress")).not.toHaveAttribute("readonly"); - await user.clear(editor("Progress")); - await user.type(editor("Progress"), "Report milestones."); - await choose(user, "Progress", "Default"); - expect(preview()).toHaveValue(defaultOf("progress")); - expect( - screen.queryByRole("button", { name: "Save" }), - ).not.toBeInTheDocument(); - await choose(user, "Progress", "Off"); + const first = sectionRow("Opening lines"); + first.focus(); + await user.keyboard("{Enter}"); + expect(screen.getByRole("region", { name: "Opening lines" })).toBeVisible(); + expect(first).toHaveFocus(); + expect(sectionRow("Show less")).toBeVisible(); + await user.keyboard("{Enter}"); + expect(collapsedRows()).toEqual(titles); + + sectionRow("Progress").focus(); + await user.keyboard("{Enter}"); + const panel = screen.getByRole("region", { name: "Progress" }); + expect(within(panel).getByRole("list")).toBeVisible(); + expect(within(panel).getByText("Work in the open.").tagName).toBe("STRONG"); + expect(sectionRow("Progress")).toHaveFocus(); + + await openSection(user, "Progress"); + expect(within(editor("Progress")).getByRole("list")).toBeVisible(); + editText("Progress", "Report milestones."); + expect(sectionRow("Progress")).not.toHaveTextContent("(Modified)"); + expect(within(sectionRow("Progress")).getByText("Edit")).toBeVisible(); + await user.click(sectionRow("Progress")); + expect(screen.queryByRole("region", { name: "Progress" })).toBeNull(); + await openSection(user, "Trust"); + await openSection(user, "Progress"); + expect(sectionRow("Trust")).toHaveAttribute("aria-expanded", "false"); + expect(editor("Progress")).toHaveTextContent("Report milestones."); + await user.click(screen.getByRole("button", { name: "Save" })); + await user.click(within(dialog()).getByRole("button", { name: "Save" })); + expect(sectionRow("Progress")).toHaveTextContent("Progress (Modified)"); + expect(sectionRow("Progress")).toHaveAccessibleDescription("Modified"); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + await disableSection(user, "Progress"); + const offRow = sectionRow("Progress"); + expect(offRow).toHaveAccessibleDescription("Disabled"); + expect(offRow).toHaveTextContent("Progress (Disabled)"); + const offTitle = within(offRow).getByText("Progress"); + expect(offTitle).toHaveClass("opacity-60"); + expect(offTitle).not.toHaveClass("line-through"); + expect(within(offRow).getByText("Edit")).toBeVisible(); + expect(within(editor("Progress")).getByRole("list")).toBeVisible(); + expect(editor("Progress")).toHaveAttribute("contenteditable", "false"); + expect(editor("Progress")).not.toHaveTextContent("Report milestones."); + expect(screen.queryByRole("button", { name: "Customize" })).toBeNull(); + expect(ownerChoices(store)).toEqual({ progress: { mode: "off" } }); +}); + +it("reveals the remaining rows with Show all and returns to the preview with Show less", async () => { + const user = userEvent.setup(); + render(); + const toggle = showAll(); + const firstRevealedTitle = SECTIONS[4]?.title ?? "Opening lines"; + expect(screen.queryByRole("button", { name: firstRevealedTitle })).toBeNull(); + toggle.focus(); + await user.keyboard("{Enter}"); + const firstRevealed = sectionRow(firstRevealedTitle); + expect(firstRevealed).toHaveFocus(); + expect(firstRevealed).toHaveAttribute("aria-expanded", "false"); + await user.keyboard("{Enter}"); expect( - screen.queryByRole("textbox", { name: /text for Progress/ }), - ).not.toBeInTheDocument(); - await choose(user, "Progress", "Custom"); - expect(editor("Progress")).toHaveValue("Report milestones."); - expect(ownerChoices(store)).toEqual({}); + screen.getByRole("region", { name: firstRevealedTitle }), + ).toBeVisible(); + const showLess = sectionRow("Show less"); + showLess.focus(); + await user.keyboard("{Enter}"); + expect(showAll()).toHaveFocus(); + expect(firstRevealed).not.toBeInTheDocument(); + await user.keyboard("{Enter}"); + expect(sectionRow(firstRevealedTitle)).toHaveAttribute( + "aria-expanded", + "false", + ); }); -it("offers Default, Off and Custom for each section the owner can configure", async () => { +it("opens an editor with a disabled Save for each section the owner can configure", async () => { const user = userEvent.setup(); render(); for (const title of [ @@ -107,20 +192,16 @@ it("offers Default, Off and Custom for each section the owner can configure", as "Agent Memory", "Commit identity", "Autonomy", - ]) - expect(choice(title)).toHaveTextContent("Default"); - expect( - screen.queryByRole("combobox", { name: "Trust" }), - ).not.toBeInTheDocument(); - await user.click(choice("Progress")); - expect( - (await screen.findAllByRole("option")).map((option) => option.textContent), - ).toEqual(["Default", "Off", "Custom"]); - await user.keyboard("{Escape}"); - // Nothing to save until a choice differs. - expect( - screen.queryByRole("button", { name: "Save" }), - ).not.toBeInTheDocument(); + ]) { + await openSection(user, title); + expect(editor(title)).toBeVisible(); + if (["Publishing", "Progress", "Etiquette", "Agent Memory"].includes(title)) + expect(within(editor(title)).getByRole("list")).toBeVisible(); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + } + await openSection(user, "Trust"); + expect(screen.queryByRole("textbox")).toBeNull(); + expect(screen.queryByRole("button", { name: "Save" })).toBeNull(); expect( screen.getByText( "Applies to each agent from its next turn. A session that is running a turn changes when the turn ends. Agents in the standalone agent host get a change when it next starts. Mesh agents do not get the base instructions.", @@ -128,92 +209,232 @@ it("offers Default, Off and Custom for each section the owner can configure", as ).toBeInTheDocument(); }); -it("saves a section turned off and one with the owner's text, only on Save", async () => { +it("saves each section independently and keeps other drafts", async () => { const user = userEvent.setup(); const store = memory(); render(); - await choose(user, "Progress", "Off"); - await choose(user, "Etiquette", "Custom"); - // Custom starts from the default text. - expect(editor("Etiquette")).toHaveValue(defaultOf("etiquette")); - await user.clear(editor("Etiquette")); - await user.type(editor("Etiquette"), "Be brief."); - expect(screen.getByText("9 of 4,096 bytes")).toBeInTheDocument(); - expect( - screen.getByText( - /^Older Codex conversations on this device start over once\./, - ), - ).toBeInTheDocument(); + await openSection(user, "Etiquette"); + expect(editor("Etiquette")).toHaveTextContent("Address people by the"); + expect(sectionRow("Etiquette")).toHaveFocus(); + editText("Etiquette", "Be brief."); + expect(screen.getByText("This instruction can be changed.")).toBeVisible(); + expect(editor("Etiquette")).toHaveAccessibleDescription( + "This instruction can be changed.", + ); + expect(screen.queryByText(/of 4,096 bytes/)).toBeNull(); + expect(screen.queryByText(notice)).toBeNull(); expect(ownerChoices(store)).toEqual({}); - + await disableSection(user, "Progress"); + expect(dialog()).toHaveAccessibleDescription(expect.stringMatching(notice)); + expect(ownerChoices(store)).toEqual({}); + await user.click(within(dialog()).getByRole("button", { name: "Cancel" })); + expect(ownerChoices(store)).toEqual({}); + expect(sectionRow("Progress")).not.toHaveAccessibleDescription(); + expect(sectionActions("Progress")).toHaveFocus(); + await chooseSectionAction(user, "Progress", "Disable"); + await user.click(within(dialog()).getByRole("button", { name: "Disable" })); + expect(ownerChoices(store)).toEqual({ progress: { mode: "off" } }); + expect(sectionRow("Progress")).toHaveAccessibleDescription("Disabled"); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + expect(sectionActions("Progress")).toHaveFocus(); + await user.click(screen.getByRole("button", { name: "Cancel" })); + expect(sectionRow("Progress")).toHaveAttribute("aria-expanded", "false"); + expect(sectionRow("Progress")).toHaveFocus(); + await openSection(user, "Etiquette"); + expect(editor("Etiquette")).toHaveTextContent("Be brief."); await user.click(screen.getByRole("button", { name: "Save" })); expect(ownerChoices(store)).toEqual({ progress: { mode: "off" }, etiquette: { mode: "custom", text: "Be brief." }, }); - expect( - screen.queryByRole("button", { name: "Save" }), - ).not.toBeInTheDocument(); - expect(choice("Progress")).toHaveTextContent("Off"); - expect(editor("Etiquette")).toHaveValue("Be brief."); - // Said once, with the first choice. - await choose(user, "Autonomy", "Off"); - expect( - screen.queryByText( - /^Older Codex conversations on this device start over once\./, - ), - ).not.toBeInTheDocument(); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + expect(screen.getByText("Be brief.")).toBeVisible(); + expect(saveButton()).toHaveFocus(); + expect(screen.queryByText(notice)).toBeNull(); +}); + +it("preserves Markdown when editing formatted text", async () => { + const user = userEvent.setup(); + const source = + "## Heading\n\n- **One**\n- `Two`\n\nKeep `this` literal."; + const store = memory({ + progress: { + mode: "custom", + text: source, + basedOn: ownerSectionsHash("progress"), + }, + }); + render(); + await openSection(user, "Progress"); + const input = editor("Progress"); + const position = input.value.indexOf("One") + 1; + expect(within(input).getByRole("list")).toBeVisible(); + expect(within(input).getByText("One").tagName).toBe("STRONG"); + expect(within(input).getByText("Two").tagName).toBe("CODE"); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + act(() => { + input.insertText( + "w", + undefined, + { start: position, end: position }, + undefined, + false, + ); + }); + await user.click(saveButton()); + expect(ownerChoices(store)).toEqual({ + progress: { mode: "custom", text: source.replace("One", "Owne") }, + }); +}); + +it("preserves noncanonical Markdown when editing source or cancelling a reset", async () => { + const user = userEvent.setup(); + const source = "Opening line.\nKeep this line break.\n\n* First\n* Second"; + const store = memory({ + etiquette: { + mode: "custom", + text: source, + basedOn: ownerSectionsHash("etiquette"), + }, + }); + render(); + await openSection(user, "Etiquette"); + expect(editor("Etiquette")).toHaveValue(source); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + await chooseSectionAction(user, "Etiquette", "Set to default instruction"); + await user.click(screen.getByRole("button", { name: "Cancel" })); + await openSection(user, "Etiquette"); + expect(editor("Etiquette")).toHaveValue(source); + expect(store.get(PROMPT_SECTIONS_KEY)).toContain(JSON.stringify(source)); + const changed = source.replace("Opening", "Edited"); + fireEvent.change(editor("Etiquette"), { target: { value: changed } }); + await user.click(saveButton()); + expect(ownerChoices(store)).toEqual({ + etiquette: { mode: "custom", text: changed }, + }); }); it("keeps a text that cannot be used out of the store", async () => { const user = userEvent.setup(); const store = memory(); render(); - await choose(user, "Etiquette", "Custom"); - await user.clear(editor("Etiquette")); + await openSection(user, "Etiquette"); + editText("Etiquette", ""); expect(screen.getByRole("alert")).toHaveTextContent( - "Enter the instructions, or choose Default or Off.", + "Enter the instructions.", ); - expect(screen.getByRole("button", { name: "Save" })).toBeDisabled(); - await user.click(editor("Etiquette")); - await user.paste("é".repeat(SECTION_TEXT_BYTES / 2 + 1)); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + editText("Etiquette", "x".repeat(3686)); + expect(screen.queryByText(/of 4,096 bytes/)).toBeNull(); + editText("Etiquette", "x".repeat(3687)); + expect(screen.getByText("3,687 of 4,096 bytes")).toBeVisible(); + expect(editor("Etiquette")).toHaveAccessibleDescription( + "This instruction can be changed. 3,687 of 4,096 bytes", + ); + editText("Etiquette", "é".repeat(SECTION_TEXT_BYTES / 2 + 1)); // The count stays in view when the text is too long. expect(screen.getByRole("alert")).toHaveTextContent( "Keep the instructions within 4 KiB. 4,098 of 4,096 bytes.", ); - expect(screen.getByRole("button", { name: "Save" })).toBeDisabled(); - await user.clear(editor("Etiquette")); - await user.type(editor("Etiquette"), "Short."); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + editText("Etiquette", "Short."); expect(screen.queryByRole("alert")).not.toBeInTheDocument(); expect(screen.getByRole("button", { name: "Save" })).toBeEnabled(); expect(ownerChoices(store)).toEqual({}); }); -it("returns a section to its default with Reset, and a draft with Cancel", async () => { +it("stages the default text until the user saves or cancels", async () => { const user = userEvent.setup(); const store = memory({ - progress: { mode: "off", basedOn: "x" }, - etiquette: { mode: "custom", text: "Be brief.", basedOn: "x" }, + etiquette: { + mode: "custom", + text: "Be brief.", + basedOn: ownerSectionsHash("etiquette"), + }, }); render(); - // Cancel drops the draft. - await user.clear(editor("Etiquette")); - await user.type(editor("Etiquette"), "Be long."); + await openSection(user, "Etiquette"); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + editText("Etiquette", "Be long."); + await chooseSectionAction(user, "Etiquette", "Set to default instruction"); + expect(editor("Etiquette")).toHaveTextContent("Address people by the"); + expect(ownerChoices(store)).toEqual({ + etiquette: { mode: "custom", text: "Be brief." }, + }); + expect(saveButton()).toBeEnabled(); await user.click(screen.getByRole("button", { name: "Cancel" })); - expect(editor("Etiquette")).toHaveValue("Be brief."); - // Reset to default removes the choice at Save. - const resets = screen.getAllByRole("button", { name: "Reset to default" }); - expect(resets).toHaveLength(2); - await user.click(resets[1] as HTMLElement); - expect(choice("Etiquette")).toHaveTextContent("Default"); - expect(ownerChoices(store)).toHaveProperty("etiquette"); - await user.click(screen.getByRole("button", { name: "Save" })); - expect(ownerChoices(store)).toEqual({ progress: { mode: "off" } }); - // Custom text that is the default text is the default. - await choose(user, "Etiquette", "Custom"); + expect(sectionRow("Etiquette")).toHaveAttribute("aria-expanded", "false"); + expect(sectionRow("Etiquette")).toHaveFocus(); + await openSection(user, "Etiquette"); + expect(editor("Etiquette")).toHaveTextContent("Be brief."); + await chooseSectionAction(user, "Etiquette", "Set to default instruction"); + await user.click(sectionActions("Etiquette")); expect( - screen.queryByRole("button", { name: "Save" }), - ).not.toBeInTheDocument(); + await screen.findByRole("menuitem", { + name: "Set to default instruction", + }), + ).not.toHaveAttribute("aria-disabled", "true"); + await user.keyboard("{Escape}"); + await user.click(saveButton()); + expect(ownerChoices(store)).toEqual({}); + expect(saveButton()).toHaveFocus(); + expect(editor("Etiquette")).toHaveTextContent("Address people by the"); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + await user.click(sectionActions("Etiquette")); + await screen.findByRole("menuitem", { name: "Disable" }); + expect( + screen.getByRole("menuitem", { + name: "Set to default instruction", + }), + ).toHaveAttribute("aria-disabled", "true"); +}); + +it("applies enable and disable immediately while preserving a text draft", async () => { + const user = userEvent.setup(); + const otherChoices = { publishing: { mode: "off" } } as const; + const store = memory({ + publishing: { + ...otherChoices.publishing, + basedOn: ownerSectionsHash("publishing"), + }, + progress: { mode: "off", basedOn: ownerSectionsHash("progress") }, + }); + render(); + await openSection(user, "Progress"); + expect(sectionRow("Progress")).toHaveAccessibleDescription("Disabled"); + expect(editor("Progress")).toHaveTextContent("Work in the open."); + expect(editor("Progress")).toHaveAttribute("aria-disabled", "true"); + expect(editor("Progress")).not.toHaveAccessibleDescription(); + await user.click(sectionActions("Progress")); + const enable = await screen.findByRole("menuitem", { name: "Enable" }); + expect( + screen.getByRole("menuitem", { + name: "Set to default instruction", + }), + ).toHaveAttribute("aria-disabled", "true"); + await user.click(enable); + expect(ownerChoices(store)).toEqual(otherChoices); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + editText("Progress", "Report milestones."); + await chooseSectionAction(user, "Progress", "Disable"); + expect(editor("Progress")).toHaveAttribute("aria-disabled", "true"); + expect(editor("Progress")).toHaveTextContent("Work in the open."); + expect(ownerChoices(store)).toEqual({ + ...otherChoices, + progress: { mode: "off" }, + }); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + await chooseSectionAction(user, "Progress", "Enable"); + expect(editor("Progress")).not.toHaveAttribute("aria-disabled"); + expect(editor("Progress")).toHaveTextContent("Report milestones."); + expect(saveButton()).toBeEnabled(); + expect(ownerChoices(store)).toEqual(otherChoices); + await user.click(screen.getByRole("button", { name: "Cancel" })); + await openSection(user, "Progress"); + expect(ownerChoices(store)).toEqual(otherChoices); + expect(sectionRow("Progress")).not.toHaveAccessibleDescription(); + expect(editor("Progress")).not.toHaveAttribute("aria-disabled"); + expect(editor("Progress")).toHaveTextContent("Work in the open."); }); it("says when a default changed after the owner's choice, until they keep theirs", async () => { @@ -227,22 +448,20 @@ it("says when a default changed after the owner's choice, until they keep theirs }, }); render(); - // Only the choice made on another default says so, with the default now. - expect(screen.getAllByText("Default changed")).toHaveLength(1); - expect(choice("Progress")).toHaveAccessibleDescription( - /^The default text changed after you made this choice\./, + await openSection(user, "Etiquette"); + expect(sectionActions("Etiquette")).not.toHaveAccessibleDescription(); + await openSection(user, "Progress"); + expect(sectionRow("Progress")).toHaveTextContent("Default changed"); + expect(sectionRow("Etiquette")).toHaveTextContent("Etiquette (Modified)"); + expect(sectionActions("Progress")).toHaveAccessibleDescription( + "The default text changed after you made this choice.", ); - expect(choice("Etiquette")).not.toHaveAccessibleDescription(); - expect( - screen.getByText("The default text changed after you made this choice.", { - exact: false, - }).parentElement, - ).toHaveTextContent(defaultOf("progress").slice(0, 40)); - await user.click(screen.getByRole("button", { name: "Keep mine" })); - expect(screen.queryByText("Default changed")).not.toBeInTheDocument(); - // The button left; its section's choice has the focus. - expect(choice("Progress")).toHaveFocus(); - await user.click(screen.getByRole("button", { name: "Save" })); + expect(editor("Progress")).toHaveTextContent("Work in the open."); + expect(editor("Progress")).toHaveAttribute("aria-disabled", "true"); + await chooseSectionAction(user, "Progress", "Keep mine"); + expect(sectionRow("Progress")).toHaveAccessibleDescription("Disabled"); + expect(sectionRow("Progress")).not.toHaveTextContent("Default changed"); + expect(sectionActions("Progress")).toHaveFocus(); // The choice stays; it is now based on the current default. expect(ownerSections(store).choices.progress).toEqual({ mode: "off", @@ -256,9 +475,9 @@ it("keeps the owner's own text when they keep theirs", async () => { etiquette: { mode: "custom", text: "Be brief.", basedOn: "an-older-one" }, }); render(); - await user.click(screen.getByRole("button", { name: "Keep mine" })); - expect(editor("Etiquette")).toHaveValue("Be brief."); - await user.click(screen.getByRole("button", { name: "Save" })); + await openSection(user, "Etiquette"); + await chooseSectionAction(user, "Etiquette", "Keep mine"); + expect(screen.getByText("Be brief.")).toBeVisible(); expect(ownerSections(store).choices.etiquette).toEqual({ mode: "custom", text: "Be brief.", @@ -276,29 +495,30 @@ it("keeps the owner's text when a later default is the same text, until they res }; const store = memory({ etiquette }); render(); - expect(screen.getByText("Default changed")).toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "Keep mine" })); - await user.click(screen.getByRole("button", { name: "Save" })); + await openSection(user, "Etiquette"); + expect(sectionRow("Etiquette")).toHaveTextContent("Default changed"); + await chooseSectionAction(user, "Etiquette", "Keep mine"); expect(ownerSections(store).choices.etiquette).toEqual({ ...etiquette, basedOn: ownerSectionsHash("etiquette"), }); // Saving another section keeps it too. - await choose(user, "Progress", "Off"); - await user.click(screen.getByRole("button", { name: "Save" })); + await disableSection(user, "Progress"); expect(ownerSections(store).choices.etiquette).toMatchObject({ mode: "custom", }); - await user.click( - within( - choice("Etiquette").closest("[data-section]") as HTMLElement, - ).getByRole("button", { name: "Reset to default" }), - ); - await user.click(screen.getByRole("button", { name: "Save" })); + await openSection(user, "Etiquette"); + expect(saveButton()).toHaveAttribute("aria-disabled", "true"); + await chooseSectionAction(user, "Etiquette", "Set to default instruction"); + expect(ownerSections(store).choices.etiquette).toMatchObject({ + mode: "custom", + }); + expect(saveButton()).toBeEnabled(); + await user.click(saveButton()); expect(ownerSections(store).choices.etiquette).toBeUndefined(); }); -it("lists every section's default text to read, and says who can change it", async () => { +it("lists every section's default text and shows plugin details inside the fixed section", async () => { const user = userEvent.setup(); render( (id === "working-location" ? ["Example Plugin"] : [])} />, ); - // A row's name says its title and what it is. - const row = (name: string) => screen.getByRole("button", { name }); - for (const name of [ - "Trust, Always on", - "Opening lines, Always on", - "Session Model, Set by Buzz", - "Routing, Always on", - "Progress, You can change this", - "Working location, Example Plugin can replace this in chats it manages.", - ]) - expect(row(name)).toHaveTextContent(name.replace(", ", "")); - await user.click(row("Trust, Always on")); + await user.click(showAll()); + for (const title of [ + "Trust", + "Opening lines", + "Session Model", + "Routing", + "Working location", + ]) { + const index = SECTIONS.findIndex( + (section) => (section.title ?? "Opening lines") === title, + ); + expect(sectionRow(title)).toHaveTextContent( + new RegExp(`^${index + 1}\\s*${title}$`), + ); + } + await user.click( + within(sectionRow("Progress")).getByText("Edit", { exact: true }), + ); + expect(editor("Progress")).toBeVisible(); + const pluginNote = "Example Plugin can replace this in chats it manages."; + expect(screen.queryByText(pluginNote)).not.toBeInTheDocument(); + await user.click(sectionRow("Trust")); expect( await screen.findByText(defaultOf("trust").slice(0, 60), { exact: false }), ).toBeInTheDocument(); - // Each row has text to read, also where Buzz picks it. - const rows = screen - .getAllByRole("button") - .filter((button) => button.getAttribute("aria-expanded") === "false"); - expect(rows).toHaveLength(SECTIONS.length - 1); - for (const closed of rows) await user.click(closed); - for (const closed of rows) - expect( - document.getElementById(closed.getAttribute("aria-controls") ?? ""), - ).not.toBeEmptyDOMElement(); + await openSection(user, "Session Model"); expect( - document.getElementById( - row("Session Model, Set by Buzz").getAttribute("aria-controls") ?? "", - ), + screen.getByRole("region", { name: "Session Model" }), ).toHaveTextContent("You are one session of your agent identity"); + await openSection(user, "Working location"); + expect( + within(screen.getByRole("region", { name: "Working location" })).getByText( + pluginNote, + ), + ).toBeVisible(); }); it("warns that the owner's choice also applies in the chats a plugin manages", async () => { @@ -350,19 +575,23 @@ it("warns that the owner's choice also applies in the chats a plugin manages", a ); const warning = "Your choice also applies in chats that Example Plugin and Other Plugin manage."; + await openSection(user, "Progress"); // The default text yields to a plugin: the row names the plugins. expect(screen.queryByText(warning, { exact: false })).not.toBeInTheDocument(); - expect(choice("Progress")).toHaveAccessibleDescription( + expect(sectionActions("Progress")).toHaveAccessibleDescription( "Example Plugin and Other Plugin can replace this in chats they manage.", ); - await choose(user, "Progress", "Off"); + await disableSection(user, "Progress"); + await user.click(within(dialog()).getByRole("button", { name: "Disable" })); expect(screen.getByText(warning, { exact: false })).toBeInTheDocument(); expect(screen.queryByText(/can replace this/)).not.toBeInTheDocument(); - expect(choice("Progress")).toHaveAccessibleDescription( + expect(sectionActions("Progress")).toHaveAccessibleDescription( expect.stringContaining(warning), ); - await choose(user, "Etiquette", "Off"); - expect(screen.getAllByText(/Your choice also applies/)).toHaveLength(1); + await user.click(sectionRow("Progress")); + expect(screen.queryByText(warning)).not.toBeInTheDocument(); + await openSection(user, "Progress"); + expect(screen.getByText(warning)).toBeVisible(); }); it("says when the saved choices cannot be read, and shows choices that are no longer used", async () => { @@ -379,6 +608,7 @@ it("says when the saved choices cannot be read, and shows choices that are no lo })} />, ); + await user.click(showAll(SECTIONS.length + 1)); const row = screen.getByRole("button", { name: "a-removed-section, no longer used", }); @@ -387,37 +617,54 @@ it("says when the saved choices cannot be read, and shows choices that are no lo expect(await screen.findByText("Mine.")).toBeInTheDocument(); }); -it("keeps the draft and says why when the save fails", async () => { +it("keeps a failed edit available for retry", async () => { const user = userEvent.setup(); const store = memory(); - const failing: AgentStore = { - ...store, - set: vi.fn(async () => { - throw new Error("The disk is full"); - }), - }; - render(); - await choose(user, "Progress", "Off"); - await user.click(screen.getByRole("button", { name: "Save" })); - expect(await screen.findByRole("alert")).toHaveTextContent( + const set = vi + .fn(store.set) + .mockRejectedValueOnce(new Error("The disk is full")); + render(); + await openSection(user, "Progress"); + editText("Progress", "Report milestones."); + const save = screen.getByRole("button", { name: "Save" }); + await user.click(save); + expect(dialog()).toHaveAccessibleDescription(expect.stringMatching(notice)); + expect(set).not.toHaveBeenCalled(); + await user.click(within(dialog()).getByRole("button", { name: "Cancel" })); + expect(editor("Progress")).toHaveTextContent("Report milestones."); + expect(save).toHaveFocus(); + await user.click(save); + const confirm = within(dialog()).getByRole("button", { name: "Save" }); + await user.click(confirm); + expect(await within(dialog()).findByRole("alert")).toHaveTextContent( "The disk is full", ); - expect(choice("Progress")).toHaveTextContent("Off"); - expect( - within(document.body).getByRole("button", { name: "Save" }), - ).toBeEnabled(); + expect(ownerChoices(store)).toEqual({}); + expect(confirm).toBeEnabled(); + await user.click(confirm); + expect(ownerChoices(store)).toEqual({ + progress: { mode: "custom", text: "Report milestones." }, + }); }); it("makes a new choice on the default as it is now", async () => { const user = userEvent.setup(); const store = memory({ - progress: { mode: "off", basedOn: "an-older-default" }, + progress: { + mode: "custom", + text: "An earlier edit.", + basedOn: "an-older-default", + }, }); render(); - await choose(user, "Progress", "Custom"); - expect(screen.queryByText("Default changed")).not.toBeInTheDocument(); - await user.clear(editor("Progress")); - await user.type(editor("Progress"), "Say little."); + await openSection(user, "Progress"); + editText("Progress", ""); + expect( + screen.queryByText("The default text changed after you made this choice.", { + exact: false, + }), + ).not.toBeInTheDocument(); + editText("Progress", "Say little."); await user.click(screen.getByRole("button", { name: "Save" })); expect(ownerSections(store).choices.progress).toEqual({ mode: "custom", @@ -426,24 +673,15 @@ it("makes a new choice on the default as it is now", async () => { }); }); -it("moves the focus to a choice when the action that had it leaves", async () => { - const user = userEvent.setup(); - render(); - await choose(user, "Etiquette", "Off"); - await user.click(screen.getByRole("button", { name: "Reset to default" })); - expect(choice("Etiquette")).toHaveFocus(); - await choose(user, "Etiquette", "Off"); - await user.click(screen.getByRole("button", { name: "Cancel" })); - expect(choice("Publishing")).toHaveFocus(); - await choose(user, "Etiquette", "Off"); - await user.click(screen.getByRole("button", { name: "Save" })); - await waitFor(() => expect(choice("Publishing")).toHaveFocus()); - expect(choice("Publishing")).toBeEnabled(); -}); - -it("holds the form while a save is in flight", async () => { +it("holds writes while a section save is in flight without moving focus when it finishes", async () => { const user = userEvent.setup(); - const store = memory(); + const original = { publishing: { mode: "off" } }; + const store = memory({ + publishing: { + ...original.publishing, + basedOn: ownerSectionsHash("publishing"), + }, + }); let finish = () => {}; const held: AgentStore = { ...store, @@ -455,68 +693,96 @@ it("holds the form while a save is in flight", async () => { }), }; render(); - await choose(user, "Etiquette", "Custom"); - await choose(user, "Progress", "Off"); + await openSection(user, "Progress"); + editText("Progress", "Report milestones."); await user.click(screen.getByRole("button", { name: "Save" })); try { await waitFor(() => expect(held.set).toHaveBeenCalledOnce()); - // Held, and able to take the focus when Save leaves: a disabled control - // is not, though jsdom lets one. - expect(choice("Progress")).toHaveAttribute("aria-readonly", "true"); - expect(choice("Progress")).toBeEnabled(); - expect(editor("Etiquette")).toBeDisabled(); - expect( - screen.getByRole("textbox", { name: "Default text for Publishing" }), - ).toBeEnabled(); - await user.click(choice("Progress")); - expect(screen.queryByRole("option")).not.toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled(); - expect(ownerChoices(store)).toEqual({}); + expect(editor("Progress")).toHaveAttribute("aria-disabled", "true"); + const cancel = screen.getByRole("button", { name: "Cancel" }); + expect(cancel).toBeEnabled(); + await user.click(cancel); + expect(sectionRow("Progress")).toHaveAttribute("aria-expanded", "false"); + expect(sectionRow("Progress")).toHaveFocus(); + expect(ownerChoices(store)).toEqual(original); + await openSection(user, "Etiquette"); + expect(sectionActions("Etiquette")).toHaveAttribute( + "aria-disabled", + "true", + ); + await user.click(sectionActions("Etiquette")); + expect(held.set).toHaveBeenCalledOnce(); + expect(sectionRow("Etiquette")).not.toHaveAccessibleDescription(); + sectionRow("Etiquette").focus(); } finally { finish(); } await waitFor(() => - expect( - screen.queryByRole("button", { name: "Save" }), - ).not.toBeInTheDocument(), + expect(sectionActions("Etiquette")).not.toHaveAttribute( + "aria-disabled", + "true", + ), ); - expect(ownerChoices(store)).toEqual({ progress: { mode: "off" } }); - expect(choice("Progress")).toBeEnabled(); -}); - -it("reopens on the saved choices while a save is in flight, and shows it failed", async () => { - const user = userEvent.setup(); - let fail = (_: Error) => {}; - let entered = () => {}; - const started = new Promise((resolve) => { - entered = resolve; - }); - // The device's file write is held, then fails: the store shows the value - // as soon as it is written, and puts the saved one back. - const store = fileStore(new Map(), async () => { - entered(); - await new Promise((_, reject) => { - fail = reject; - }); + expect(sectionRow("Etiquette")).toHaveFocus(); + expect(ownerChoices(store)).toEqual({ + ...original, + progress: { mode: "custom", text: "Report milestones." }, }); - const first = render(); - await choose(user, "Progress", "Off"); - await user.click(screen.getByRole("button", { name: "Save" })); - try { - await started; - first.unmount(); - render(); - expect(choice("Progress")).toHaveTextContent("Default"); - expect(choice("Progress")).toHaveAttribute("aria-readonly", "true"); - } finally { - fail(new Error("The disk is full")); - } - expect(await screen.findByText("The disk is full")).toBeInTheDocument(); - expect(choice("Progress")).toHaveTextContent("Default"); - expect(choice("Progress")).not.toHaveAttribute("aria-readonly", "true"); - expect(ownerChoices(store)).toEqual({}); }); +it.each(["succeeds", "fails"])( + "reopens with the saved instructions until a pending write %s", + async (result) => { + const user = userEvent.setup(); + let finish = (_error?: Error) => {}; + const write = vi.fn( + () => + new Promise((resolve, reject) => { + finish = (error) => { + if (error) reject(error); + else resolve(); + }; + }), + ); + const store = fileStore(new Map(), write); + const first = render(); + await disableSection(user, "Progress"); + await user.click(within(dialog()).getByRole("button", { name: "Disable" })); + + try { + await waitFor(() => expect(write).toHaveBeenCalledOnce()); + first.unmount(); + render(); + await openSection(user, "Progress"); + expect(sectionRow("Progress")).not.toHaveAccessibleDescription(); + expect(sectionActions("Progress")).toHaveAttribute( + "aria-disabled", + "true", + ); + expect(editor("Progress")).toHaveAttribute("aria-disabled", "true"); + } finally { + finish(result === "fails" ? new Error("The disk is full") : undefined); + } + + await waitFor(() => + expect(sectionActions("Progress")).not.toHaveAttribute( + "aria-disabled", + "true", + ), + ); + if (result === "fails") { + expect(screen.getByRole("alert")).toHaveTextContent("The disk is full"); + expect(sectionRow("Progress")).not.toHaveAccessibleDescription(); + expect(editor("Progress")).not.toHaveAttribute("aria-disabled", "true"); + expect(ownerChoices(store)).toEqual({}); + } else { + expect(sectionRow("Progress")).toHaveAccessibleDescription("Disabled"); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect(ownerChoices(store)).toEqual({ progress: { mode: "off" } }); + } + }, +); + function ownerSectionsHash(id: string) { const section = SECTIONS.find((candidate) => candidate.id === id); if (!section) throw new Error(id); diff --git a/src/features/agents/BaseInstructions.tsx b/src/features/agents/BaseInstructions.tsx index 3fb2987c12..d08867b814 100644 --- a/src/features/agents/BaseInstructions.tsx +++ b/src/features/agents/BaseInstructions.tsx @@ -1,47 +1,55 @@ // Settings → Agent setup → Base instructions: the owner's choice for each -// section of the base prompt they can configure, as a draft with an explicit -// Save, and every section's text to read. It applies to all the owner's -// agents on this device. +// section of the base prompt they can configure, and every section's text +// to read. Choices apply to all the owner's agents on this device. import { - useCallback, + memo, useEffect, useId, useLayoutEffect, useRef, useState, + type ReactNode, } from "react"; +import remarkGfm from "remark-gfm"; import { Accordion } from "../../shared/design-system/ui/Accordion"; +import { AlertDialog } from "../../shared/design-system/ui/AlertDialog"; import { Button } from "../../shared/design-system/ui/Button"; -import { Field } from "../../shared/design-system/ui/Field"; import { InlineHeader } from "../../shared/design-system/ui/Header"; -import { Select } from "../../shared/design-system/ui/Select"; +import { + MenuItem, + MenuPopup, + MenuRoot, + MenuTrigger, +} from "../../shared/design-system/ui/Menu"; import { SettingsGroup } from "../../shared/design-system/ui/SettingsGroup"; -import { Textarea } from "../../shared/design-system/ui/Textarea"; +import { Tooltip } from "../../shared/design-system/ui/Tooltip"; +import { useScrollEdges } from "../../shared/design-system/ui/useScrollEdges"; import { SECTIONS, type Section } from "../agent-harness/sections"; import { SECTION_TEXT_BYTES, textProblem, } from "../agent-harness/sections/choices"; +import { + MarkdownDocument, + MarkdownSource, + sharedComponents, +} from "../markdown/MarkdownDocument"; +import type { MarkdownProfile } from "../markdown/profiles"; +import { DocumentEditor } from "../messages/DocumentEditor"; +import { MAX_MARKDOWN_LENGTH, scanMarkdown } from "../relay/message-content"; import { committedOwnerSections, defaultHash, - type OwnerSections, ownerSections, + type SavedChoice, saveOwnerSections, } from "./prompt-sections"; import type { AgentStore } from "./store"; +import styles from "./BaseInstructions.module.css"; type Mode = "default" | "off" | "custom"; -/** One section's choice as it is being edited. `text` is kept while the - * mode is not Custom, so switching back shows it again. */ -type Draft = Readonly<{ mode: Mode; text: string; basedOn?: string }>; - -const MODES = [ - { value: "default", label: "Default" }, - { value: "off", label: "Off" }, - { value: "custom", label: "Custom" }, -] as const; -const CONFIGURABLE = SECTIONS.filter((section) => section.owner); +type SectionEdit = { text: string } | "default"; +const PREVIEW_SECTION_COUNT = 4; /** A section's default text; the one of a thread session in the agent's own * workspace where Buzz picks it. */ const defaultText = (section: Section) => @@ -51,63 +59,119 @@ const defaultText = (section: Section) => ).trim(); const bytes = (text: string) => new TextEncoder().encode(text.trim()).length; -const drafts = (saved: OwnerSections) => - Object.fromEntries( - CONFIGURABLE.map(({ id }): [string, Draft] => { - const choice = saved.choices[id]; - return [ - id, - choice - ? { - mode: choice.mode, - text: choice.mode === "custom" ? choice.text : "", - basedOn: choice.basedOn, - } - : { mode: "default", text: "" }, - ]; - }), - ); -/** What Save would keep for a draft. Custom text that is the default text - * is the default, unless it is the saved text: a later default can become - * the owner's text, which stays theirs until they reset it. */ -const kept = ( - section: Section, - { mode, text, basedOn }: Draft, - saved: OwnerSections["choices"], -) => { - const own = saved[section.id]; - return mode === "default" || - (mode === "custom" && - text.trim() === defaultText(section) && - !(own?.mode === "custom" && own.text === text.trim())) - ? undefined - : { - ...(mode === "custom" ? { mode, text: text.trim() } : { mode }), - ...(basedOn ? { basedOn } : {}), - }; +const firstChoiceNotice = + "Older Codex conversations on this device start over once. Older ones on another computer keep their instructions until you start a new session."; + +const PROFILE: MarkdownProfile = { + syntax: [remarkGfm], + transforms: [], + html: "literal", }; -/** What Save would keep for every section's draft. */ -const keptChoices = ( - all: Record, - saved: OwnerSections["choices"], -) => - Object.fromEntries( - CONFIGURABLE.flatMap((section) => { - const choice = kept(section, all[section.id] as Draft, saved); - return choice ? [[section.id, choice] as const] : []; - }), + +const InstructionText = memo(function InstructionText({ + text, +}: { + text: string; +}) { + const className = "min-w-0 select-text break-words text-message text-subtle"; + if (text.length > MAX_MARKDOWN_LENGTH || scanMarkdown(text).tooDeep) + return ; + return ( + ); +}); + +function InstructionReadingArea({ children }: { children: ReactNode }) { + const scrollRef = useScrollEdges("block"); + return ( +
+
{children}
+
+ ); +} -const prose = "m-0 whitespace-pre-wrap break-words text-body-sm text-subtle"; const names = new Intl.ListFormat("en", { type: "conjunction" }); const canReplace = (plugins: readonly string[]) => `${names.format(plugins)} can replace this in chats ${plugins.length > 1 ? "they manage" : "it manages"}.`; -/** The choice that takes focus when the control that has it leaves: its - * section's, or the first one for the form's own actions. */ -const choiceNear = (from: Element) => - ( - from.closest("[data-section]") ?? from.closest("form") - )?.querySelector('[role="combobox"]') ?? null; +const sectionTitle = (section: Section) => section.title ?? "Opening lines"; +const instructionStatus = (mode: Mode | undefined) => + mode === "custom" ? "Modified" : mode === "off" ? "Disabled" : undefined; + +function InstructionTitle({ + title, + mode, + changed, +}: { + title: string; + mode?: Mode | undefined; + changed?: boolean | undefined; +}) { + const status = instructionStatus(mode); + return ( + <> + {title} + {status && ( + + {` (${status})`} + + )} + {changed && ( + {" · Default changed"} + )} + + ); +} + +function InstructionRowTitle({ + title, + position, + mode, + changed, + retired, +}: { + title: string; + position: number; + mode?: Mode | undefined; + changed?: boolean; + retired?: boolean; +}) { + return ( + + + + {mode && Edit} + {retired && No longer used} + + ); +} +const defaultChanged = (section: Section, choice: SavedChoice | undefined) => + !!choice?.basedOn && choice.basedOn !== defaultHash(section); export function BaseInstructions({ store, @@ -118,346 +182,548 @@ export function BaseInstructions({ * chats they manage. */ replacedBy?: ((section: string) => readonly string[]) | undefined; }) { - // A save from a form closed since can still be in flight: this one - // starts from what is saved and holds until that save ends. const [start] = useState(() => committedOwnerSections(store)); const [saved, setSaved] = useState(start.sections); - const [draft, setDraft] = useState(() => drafts(saved)); - const [saving, setSaving] = useState(Boolean(start.writing)); - const [error, setError] = useState(""); + const [resumingSave, setResumingSave] = useState(!!start.writing); + const [edits, setEdits] = useState>({}); + const [editorRevisions, setEditorRevisions] = useState< + Record + >({}); + const [write, setWrite] = useState<{ + id: string; + enabledChanged: boolean; + } | null>(null); + const saving = write?.id ?? null; + const [error, setError] = useState<{ id?: string; message: string }>(); + const [confirmation, setConfirmation] = useState<{ + id: string; + choice: SavedChoice; + from?: HTMLElement | undefined; + }>(); + const [openRow, setOpenRow] = useState(null); + const [showAll, setShowAll] = useState(false); + const busy = saving !== null || resumingSave; + const noticeId = useId(); + const listId = useId(); + const listRef = useRef(null); + const focusRevealedRow = useRef(false); + const pendingFocus = useRef<{ id: string; from: HTMLElement }>(undefined); + const openSectionActions = () => + listRef.current?.querySelector( + ".buzz-accordion-item[data-open] [data-instruction-actions]", + ); useEffect(() => { + if (!start.writing) return; let live = true; - start.writing - ?.then( - () => "", - (reason: unknown) => - reason instanceof Error ? reason.message : String(reason), - ) - .then((failed) => { - if (!live) return; - const next = ownerSections(store); - setSaved(next); - setDraft(drafts(next)); - setError(failed); - setSaving(false); - }); + // The previous panel can still be writing to the optimistic store. + const settled = (failure?: { message: string }) => { + if (!live) return; + setSaved(ownerSections(store)); + setError(failure); + setResumingSave(false); + }; + void start.writing.then( + () => settled(), + (reason: unknown) => + settled({ + message: reason instanceof Error ? reason.message : String(reason), + }), + ); return () => { live = false; }; }, [start, store]); - const noticeId = useId(); - const pendingFocus = useRef(null); - const actionsRef = useCallback((node: HTMLDivElement | null) => { - if (!node) return; - // Capture focus before the conditional actions leave the DOM. - return () => { - if (node.contains(document.activeElement)) - pendingFocus.current = choiceNear(node); - }; - }, []); useLayoutEffect(() => { - // After the commit, when the control that had the focus has left. + if (focusRevealedRow.current) { + focusRevealedRow.current = false; + const rows = listRef.current?.querySelectorAll( + ".buzz-accordion-trigger", + ); + rows?.[PREVIEW_SECTION_COUNT]?.focus(); + } const target = pendingFocus.current; - pendingFocus.current = null; - if (target?.isConnected) target.focus(); + pendingFocus.current = undefined; + if (target?.id === openRow) { + const control = + target.from.isConnected && !target.from.closest("[inert], :disabled") + ? target.from + : openSectionActions(); + control?.focus(); + } }); - const change = (id: string, next: Partial) => { - setError(""); - setDraft((current) => ({ + const resetEditor = (id: string) => { + setEditorRevisions((current) => ({ ...current, - [id]: { ...(current[id] as Draft), ...next }, + [id]: (current[id] ?? 0) + 1, })); }; - const choices = keptChoices(draft, saved.choices); - const dirty = - JSON.stringify(choices) !== - JSON.stringify(keptChoices(drafts(saved), saved.choices)); - const invalid = CONFIGURABLE.some(({ id }) => { - const { mode, text } = draft[id] as Draft; - return mode === "custom" && textProblem(text); - }); - const save = async () => { - if (saving || !dirty || invalid) return; - setSaving(true); - setError(""); + const closeEdit = (id: string) => { + setEdits(({ [id]: _, ...remaining }) => remaining); + resetEditor(id); + setError((current) => (current?.id === id ? undefined : current)); + }; + const saveSection = async ( + id: string, + choice: SavedChoice | undefined, + from?: HTMLElement, + ) => { + if (busy) return false; + const choices = { ...ownerSections(store).choices }; + const hadChoice = !!choices[id]; + const enabledChanged = + (choices[id]?.mode === "off") !== (choice?.mode === "off"); + if (choice) choices[id] = choice; + else delete choices[id]; + setWrite({ id, enabledChanged }); + setError(undefined); try { - await saveOwnerSections(store, choices); - const next = ownerSections(store); - setSaved(next); - setDraft(drafts(next)); + if (choice || hadChoice) await saveOwnerSections(store, choices); + setSaved(ownerSections(store)); + if ( + from && + (document.activeElement === from || + document.activeElement === document.body) + ) { + pendingFocus.current = { id, from }; + } + if (enabledChanged) resetEditor(id); + else closeEdit(id); + return true; } catch (reason) { - setError(reason instanceof Error ? reason.message : String(reason)); + setError({ + id, + message: reason instanceof Error ? reason.message : String(reason), + }); + return false; } finally { - setSaving(false); + setWrite(null); + } + }; + const requestSectionSave = ( + id: string, + choice: SavedChoice | undefined, + from?: HTMLElement, + ) => { + if (busy) return; + if (choice && Object.keys(ownerSections(store).choices).length === 0) { + setError(undefined); + setConfirmation({ id, choice, from }); + } else { + void saveSection(id, choice, from); } }; /** The names of the plugins that can replace `section`. */ const plugins = (section: Section) => section.plugin ? (replacedBy?.(section.id) ?? []) : []; - /** What a section that the owner cannot configure is, in a few words. */ - const fixed = (section: Section) => { - const able = plugins(section); - if (able.length) return canReplace(able); - return typeof section.text === "string" ? "Always on" : "Set by Buzz"; - }; const unused = Object.entries(saved.unused); + const visibleSections = showAll + ? SECTIONS + : SECTIONS.slice(0, PREVIEW_SECTION_COUNT); + const toggleRow = (id: string, value: string[]) => { + const opening = value.length > 0; + if (opening) setShowAll(true); + setOpenRow(opening ? id : null); + }; - return ( - <> -
- - {saved.unreadable && ( -

- Your saved choices could not be read, so every section uses its - default text. Saving replaces them. + const renderEditor = (section: Section, defaultHasChanged: boolean) => { + const { id } = section; + const title = sectionTitle(section); + const choice = saved.choices[id]; + const savedMode = choice?.mode ?? "default"; + const content = edits[id]; + const resetting = content === "default"; + const enabled = savedMode !== "off"; + const mode = enabled && resetting ? "default" : savedMode; + const textEdit = resetting ? undefined : content; + const defaultSource = defaultText(section); + const savedSource = choice?.mode === "custom" ? choice.text : defaultSource; + const initialText = resetting ? defaultSource : savedSource; + const source = textEdit?.text ?? initialText; + const text = source.trim(); + const usesDefault = text === defaultSource; + const dirty = enabled && (mode !== savedMode || text !== savedSource); + const defaultSaved = savedMode === "default" && !dirty; + const defaultHint = defaultSaved + ? "Already set" + : enabled + ? undefined + : "Enable to edit"; + const savingText = saving === id && !write?.enabledChanged; + const problem = + dirty && mode !== "off" && !usesDefault ? textProblem(source) : undefined; + const byteCount = bytes(source); + const showCount = byteCount >= SECTION_TEXT_BYTES * 0.9; + const count = `${byteCount.toLocaleString("en")} of ${SECTION_TEXT_BYTES.toLocaleString("en")} bytes`; + const changed = !dirty && defaultHasChanged; + const basedOn = defaultHash(section); + const notice = `${noticeId}-${id}-default-changed`; + const details = `${noticeId}-${id}-editor-details`; + const able = plugins(section); + const pluginNote = !able.length + ? undefined + : mode === "default" && !dirty + ? canReplace(able) + : `Your choice also applies in chats that ${names.format(able)} ${able.length > 1 ? "manage" : "manages"}.`; + const pluginNoteId = `${noticeId}-${id}-plugin-note`; + const actionDescription = + [pluginNote && pluginNoteId, changed && notice] + .filter(Boolean) + .join(" ") || undefined; + const updateEdit = (next: SectionEdit) => { + if (next === "default") resetEditor(id); + setEdits((current) => ({ ...current, [id]: next })); + setError((current) => (current?.id === id ? undefined : current)); + }; + const defaultItem = ( + updateEdit("default")}> + Set to default instruction + + ); + return ( +

+

+ +

+
+ updateEdit({ text })} + /> + {changed && choice && ( +
+

+ The default text changed after you made this choice. + {mode === "custom" && " The default is now:"} +

+ {mode === "custom" && ( + + + + )} +
+ )} +
+ {pluginNote && ( +

+ {pluginNote}

)} - -
{ - event.preventDefault(); - void save(); - }} - > - {CONFIGURABLE.map((section) => { - const title = section.title ?? section.id; - const { mode, text, basedOn } = draft[section.id] as Draft; - const current = defaultHash(section); - // The default text is another one than when the owner chose. - const changed = - mode !== "default" && !!basedOn && basedOn !== current; - const problem = mode === "custom" ? textProblem(text) : undefined; - const count = `${bytes(text).toLocaleString("en")} of ${SECTION_TEXT_BYTES.toLocaleString("en")} bytes`; - const notice = `${noticeId}-${section.id}`; - const able = plugins(section); - const pluginNote = !able.length - ? undefined - : mode === "default" - ? canReplace(able) - : // The owner's choice wins over a plugin's text. - `Your choice also applies in chats that ${names.format(able)} ${able.length > 1 ? "manage" : "manages"}.`; - const pluginNoteId = `${notice}-plugins`; - return ( -
-