diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.browser.test.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.browser.test.tsx new file mode 100644 index 0000000000000..05d3501f6eaa7 --- /dev/null +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.browser.test.tsx @@ -0,0 +1,141 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useState, type ComponentProps } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar"; +import type { ChatComposerHandle } from "./ChatComposer"; +import { useChatShortcuts } from "./useChatShortcuts"; + +type OnCite = ComponentProps["onCite"]; + +const threadRef = { + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread"), +}; + +// The chat's window capture listener runs before the toolbar's document listener, so +// type-to-focus sees every key first. The stand-in composer records what it receives. +function ChatShortcuts(props: { composerKeys: string[] }) { + useChatShortcuts({ + enabled: true, + keybindings: [], + scriptKeybindings: [], + getShortcutContext: () => ({ + terminalFocus: false, + terminalOpen: false, + previewFocus: false, + previewOpen: false, + isWeb: true, + isDesktop: false, + modelPickerOpen: false, + }), + threadFindActive: false, + composerRef: { + current: { + insertTextAtEnd: (key: string) => { + props.composerKeys.push(key); + return true; + }, + } as Partial as ChatComposerHandle, + }, + branchToolbarRef: { current: null }, + closeThreadFind: () => {}, + commands: {}, + fallback: () => undefined, + }); + return null; +} + +function Transcript(props: { onCite: OnCite; composerKeys?: string[] }) { + const [viewport, setViewport] = useState(null); + return ( + <> + {props.composerKeys ? : null} +
+
+

Render the citation chip

+
+
+ + + ); +} + +// router: false because the transcript never navigates. +const options = { router: false } as const; +const citeButton = page.getByRole("button", { name: "Cite selection in composer" }); + +async function selectAssistantText(container: HTMLElement) { + const text = container.querySelector("p")!.firstChild!; + window.getSelection()!.setBaseAndExtent(text, 7, text, 15); + await expect.element(citeButton).toBeVisible(); +} + +describe("AssistantSelectionToolbar", () => { + it.each(["r", "R"])("cites with %s instead of typing it into the composer", async (key) => { + const onCite = vi.fn(() => true); + const composerKeys: string[] = []; + await using screen = await render( + , + options, + ); + await selectAssistantText(screen.container); + + await userEvent.keyboard(key); + + expect(onCite).toHaveBeenCalledOnce(); + expect(onCite.mock.lastCall![0]).toMatchObject({ messageId: "message-1", text: "the cita" }); + expect(composerKeys).toEqual([]); + expect(window.getSelection()!.isCollapsed).toBe(true); + await expect.element(citeButton).not.toBeInTheDocument(); + }); + + it("types R into the composer when nothing is selected", async () => { + const onCite = vi.fn(() => true); + const composerKeys: string[] = []; + await using _screen = await render( + , + options, + ); + + await userEvent.keyboard("r"); + + expect(composerKeys).toEqual(["r"]); + expect(onCite).not.toHaveBeenCalled(); + }); + + // Dispatched rather than typed so a real Ctrl+R cannot reload the test page. + it.each([ + ["Cmd+R", { metaKey: true }], + ["Ctrl+R", { ctrlKey: true }], + ["Alt+R", { altKey: true }], + ])("leaves %s to the browser", async (_name, modifier) => { + const onCite = vi.fn(() => true); + await using screen = await render(, options); + await selectAssistantText(screen.container); + + const event = new KeyboardEvent("keydown", { + key: "r", + bubbles: true, + cancelable: true, + ...modifier, + }); + document.body.dispatchEvent(event); + + expect(event.defaultPrevented).toBe(false); + expect(onCite).not.toHaveBeenCalled(); + }); + + it("still focuses the Cite action on Tab", async () => { + const onCite = vi.fn(() => true); + await using screen = await render(, options); + await selectAssistantText(screen.container); + + await userEvent.keyboard("{Tab}"); + + await expect.element(citeButton).toHaveFocus(); + expect(onCite).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx index 0772a864c021e..28b9caac8b0e8 100644 --- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx @@ -19,7 +19,9 @@ import { type SelectionActionPoint, } from "~/lib/selectionActions"; import { Button } from "../ui/button"; +import { Kbd } from "../ui/kbd"; import { BackgroundThreadContext } from "./backgroundThread"; +import { isCiteSelectionShortcut } from "./composerFocusRedirect"; export function AssistantSelectionToolbar({ viewport, @@ -147,31 +149,34 @@ export function AssistantSelectionToolbar({ onDismiss: clear, }); actionsRef.current = actions; - const focusActions = (event: KeyboardEvent) => { + const handleShortcut = (event: KeyboardEvent) => { const toolbar = toolbarRef.current; if ( - event.key !== "Tab" || - event.shiftKey || + !toolbar || + toolbar.disabled || event.altKey || event.ctrlKey || event.metaKey || event.isComposing || - event.defaultPrevented || - !toolbar || - toolbar.contains(event.target as Node) + event.defaultPrevented ) { return; } - if (toolbar.disabled) return; - event.preventDefault(); - event.stopPropagation(); - toolbar.focus({ preventScroll: true }); + if (event.key === "Tab" && !event.shiftKey && !toolbar.contains(event.target as Node)) { + event.preventDefault(); + event.stopPropagation(); + toolbar.focus({ preventScroll: true }); + } else if (isCiteSelectionShortcut(event)) { + event.preventDefault(); + event.stopPropagation(); + toolbar.click(); + } }; - // Tab belongs to the foreground chat; a background timeline only follows its selection. - if (!backgroundThread) document.addEventListener("keydown", focusActions, true); + // Tab and R belong to the foreground chat; a background timeline only follows its selection. + if (!backgroundThread) document.addEventListener("keydown", handleShortcut, true); document.addEventListener("selectionchange", actions.selectionChanged); return () => { - document.removeEventListener("keydown", focusActions, true); + document.removeEventListener("keydown", handleShortcut, true); document.removeEventListener("selectionchange", actions.selectionChanged); actions.dispose(); actionsRef.current = null; @@ -180,6 +185,7 @@ export function AssistantSelectionToolbar({ if (!selection) return null; const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH; + const shortcut = !tooLong && !backgroundThread; const dismiss = () => { actionsRef.current?.cancel(); setSelection(null); @@ -198,6 +204,8 @@ export function AssistantSelectionToolbar({ variant="glass" disabled={tooLong} aria-label={tooLong ? gt("Selection is too long to cite") : gt("Cite selection in composer")} + aria-keyshortcuts={shortcut ? "R" : undefined} + data-cite-selection-action={shortcut ? "" : undefined} className="fixed z-50 max-w-[calc(100vw-1rem)]" style={{ left: selection.position.x, top: selection.position.y }} onPointerDown={(event) => event.preventDefault()} @@ -214,6 +222,7 @@ export function AssistantSelectionToolbar({ {tooLong ? gt("Shorten selection") : gt("Cite", { $context: "verb, button that quotes the selected text" })} + {shortcut ? R : null} , document.body, ); diff --git a/apps/web/src/components/chat/composerFocusRedirect.ts b/apps/web/src/components/chat/composerFocusRedirect.ts index cb187e73ea6a7..b43989a51b52a 100644 --- a/apps/web/src/components/chat/composerFocusRedirect.ts +++ b/apps/web/src/components/chat/composerFocusRedirect.ts @@ -82,6 +82,13 @@ export function shouldRedirectInputToComposer(event: Event): boolean { return true; } +export function isCiteSelectionShortcut(event: KeyboardEvent): boolean { + return ( + event.key.toLowerCase() === "r" && + document.querySelector("button[data-cite-selection-action]:enabled") !== null + ); +} + export function shouldTypeToFocusComposer(event: KeyboardEvent): boolean { if (event.isComposing) return false; if (event.metaKey || event.ctrlKey || event.altKey) return false; @@ -89,6 +96,7 @@ export function shouldTypeToFocusComposer(event: KeyboardEvent): boolean { if (!shouldRedirectInputToComposer(event)) return false; if (isSurfaceLauncherKey(event)) return false; if (isKeyClaimedInPath(event)) return false; + if (isCiteSelectionShortcut(event)) return false; return true; } diff --git a/docs/user/composer.md b/docs/user/composer.md index 53017052a2a01..e99533edb4bea 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -143,7 +143,7 @@ Leaving reasoning level or service tier unset uses the provider's own configurat ## Quote an assistant response On web and desktop, select text within one assistant response and choose -**Cite in composer**. You can add a comment about the quote and write instructions +**Cite**, or press `R`. You can add a comment about the quote and write instructions around it. Select the quote in a draft or sent message to return to its source. If the source