diff --git a/e2e/agentMarkdown.spec.ts b/e2e/agentMarkdown.spec.ts index 774a1f02b..50cc7efdf 100644 --- a/e2e/agentMarkdown.spec.ts +++ b/e2e/agentMarkdown.spec.ts @@ -71,7 +71,14 @@ async function openReply(page: Page, text: string, imageData?: string, theme?: " [ task.id, [ - { type: "user", text: "Show Markdown", attachments: [], sentMs: 0, doneMs: 1, steered: false }, + { + type: "user", + text: "Show Markdown", + attachments: [], + sentMs: 0, + doneMs: 1, + steered: false, + }, { type: "agent", text }, ], ], @@ -111,7 +118,11 @@ test("scrolls a wide table inside the reply", async ({ page }) => { const reply = await openReply(page, REPLY); const sizes = await reply.evaluate((el) => { const table = el.querySelector("table")!; - return { reply: el.clientWidth, table: table.clientWidth, content: table.scrollWidth }; + return { + reply: el.clientWidth, + table: table.clientWidth, + content: table.scrollWidth, + }; }); expect(sizes.table).toBeLessThanOrEqual(sizes.reply); expect(sizes.content).toBeGreaterThan(sizes.table); @@ -148,7 +159,10 @@ test("loads local reply images, and web ones when asked", async ({ page }) => { let fetched = 0; await page.route("https://images.example.com/code.gif", (route) => { fetched++; - return route.fulfill({ contentType: "image/gif", body: Buffer.from(PIXEL.split(",")[1]!, "base64") }); + return route.fulfill({ + contentType: "image/gif", + body: Buffer.from(PIXEL.split(",")[1]!, "base64"), + }); }); const reply = await openReply( page, @@ -158,7 +172,9 @@ test("loads local reply images, and web ones when asked", async ({ page }) => { const width = (name: string) => reply.getByRole("img", { name, includeHidden: true }).evaluate((img: HTMLImageElement) => img.naturalWidth); await expect.poll(() => width("Local QR")).toBe(1); - const load = reply.getByRole("button", { name: "Load image from images.example.com" }); + const load = reply.getByRole("button", { + name: "Load image from images.example.com", + }); await expect(load).toBeVisible(); expect(fetched).toBe(0); await load.click(); @@ -203,12 +219,10 @@ test("keeps latest reply actions visible and quotes into the draft without shift await page.getByRole("button", { name: "Quote Reply", exact: true }).click(); const draft = page.getByRole("textbox", { name: "Message", exact: true }); await expect(draft).toBeFocused(); - await expect(draft).toHaveValue( - REPLY.trimEnd() - .split("\n") - .map((line) => (line ? `> ${line}` : ">")) - .join("\n") + "\n\n", - ); + // Quoted as `> ` lines, drawn as a block without their markers, an empty line to type in after it. + const quoted = REPLY.trimEnd().split("\n"); + await expect(draft.locator(".cm-line")).toHaveText([...quoted, "", ""]); + await expect(draft.locator(".cm-line[class*='_quoteLine_']")).toHaveCount(quoted.length); }); test("copies a mouse selection with Ctrl+C and pops up no Quote button", async ({ page, context }) => { @@ -231,7 +245,14 @@ test("keeps chat history readable and selections free of timestamps and status l await page.evaluate(async (task) => { const path = "/src/features/agents/store.ts"; const store = await import(path); - const user = (text: string) => ({ type: "user", text, attachments: [], sentMs: 1, doneMs: 5001, steered: false }); + const user = (text: string) => ({ + type: "user", + text, + attachments: [], + sentMs: 1, + doneMs: 5001, + steered: false, + }); store.useAgents.setState({ entries: new Map([ [ @@ -326,7 +347,9 @@ test("keeps hover actions reachable when the pointer leaves the message body", a const copy = page.getByRole("button", { name: "Copy Markdown", exact: true }); await reply.hover(); const box = await copy.boundingBox(); - await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2, { steps: 20 }); + await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2, { + steps: 20, + }); await expect(copy.locator("..")).toHaveCSS("opacity", "1"); await copy.click(); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("A short answer."); @@ -468,7 +491,10 @@ for (const theme of ["dark", "light"] as const) { const bar = document.getElementById(el.id.replace(/-text$/, ""))!; const fg = luminance(getComputedStyle(el).fill); const bg = luminance(getComputedStyle(bar).fill); - return { text: el.textContent, ratio: (Math.max(fg, bg) + 0.05) / (Math.min(fg, bg) + 0.05) }; + return { + text: el.textContent, + ratio: (Math.max(fg, bg) + 0.05) / (Math.min(fg, bg) + 0.05), + }; }); }); expect(contrasts).toHaveLength(4); @@ -480,7 +506,10 @@ test("draws a diagram without reaching the hosts its configuration names", async const asked: string[] = []; await page.route(/^https:\/\/([a-z\d-]+\.)*example\.com\//, (route) => { asked.push(new URL(route.request().url()).pathname); - return route.fulfill({ contentType: "image/gif", body: Buffer.from(PIXEL.split(",")[1]!, "base64") }); + return route.fulfill({ + contentType: "image/gif", + body: Buffer.from(PIXEL.split(",")[1]!, "base64"), + }); }); const at = (name: string) => `https://images.example.com/${name}`; const fence = (...lines: string[]) => ["```mermaid", ...lines, "```"].join("\n"); diff --git a/src/features/agents/Composer.module.css b/src/features/agents/Composer.module.css index 17f2d0ff6..cb108060b 100644 --- a/src/features/agents/Composer.module.css +++ b/src/features/agents/Composer.module.css @@ -22,58 +22,62 @@ inset 0 0 0 1px var(--focus-ring), 0 0 0 1px var(--focus-ring); } +/* The CodeMirror text field: the UI font, wrapping, growing with the text up to a limit. */ .field { position: relative; + min-width: 0; } -/* Tags under the transparent textarea: same font, metrics and padding, so the caret - and selection of the real textarea line up with the painted text. */ -.mirror { - position: absolute; - inset: 0; - overflow: hidden; - padding: 10px 12px 2px; - font: inherit; +.field :global(.cm-editor) { + background: transparent; + color: var(--fg-strong); font-size: var(--fs-ui); +} +.field :global(.cm-editor.cm-focused) { + outline: none; +} +.field :global(.cm-scroller) { + min-height: 44px; + max-height: 280px; + overflow-y: auto; + font-family: inherit; line-height: 1.5; +} +.field :global(.cm-content) { + padding: 10px 12px 2px; + caret-color: var(--fg-strong); white-space: pre-wrap; overflow-wrap: anywhere; - color: var(--fg-strong); - pointer-events: none; - -webkit-user-select: none; - user-select: none; } -.textarea { - position: relative; - z-index: 1; - display: block; - width: 100%; - min-height: 44px; - resize: none; - border: 0; - outline: none; - background: transparent; - color: transparent; - caret-color: var(--fg-strong); - font: inherit; - font-size: var(--fs-ui); - line-height: 1.5; - padding: 10px 12px 2px; - overflow-wrap: anywhere; - -webkit-user-select: text; - user-select: text; +.field :global(.cm-line) { + padding: 0; } -.textarea:focus-visible { - outline: none; +/* A wide card (a ``` block) takes the text's width, its code scrolling inside, rather than + widening the text past the box. */ +.field :global(.cm-content) { + min-width: 0; } -.textarea::placeholder { +.field :global(.cm-placeholder) { color: var(--fg-faint); } -/* The textarea's own glyphs are transparent so the mirror above shows the tags; the - selection would then paint an empty highlight. Paint the selected glyphs here instead — - the opaque selection background covers the mirror underneath. */ -.textarea::selection { +.field :global(.cm-cursor) { + border-left-color: var(--fg-strong); +} +.field ::selection { background: var(--bg-editor-selection); +} +/* A dragged file over the box: what dropping does. */ +.dropOverlay { + position: absolute; + z-index: 2; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + border-radius: inherit; + background: color-mix(in srgb, var(--bg-popup) 82%, transparent); color: var(--fg-strong); + pointer-events: none; } .bar { display: flex; @@ -347,17 +351,19 @@ color: var(--fg-subtle); } -.images { +/* Above the text: the current file to reference, attached files and images. */ +.context { display: flex; flex-wrap: wrap; + align-items: center; gap: 6px; padding: 8px 10px 0; cursor: default; } .image { position: relative; - width: 44px; - height: 44px; + width: 40px; + height: 40px; border-radius: var(--radius-small); box-shadow: inset 0 0 0 1px var(--border); overflow: hidden; @@ -393,21 +399,63 @@ opacity: 0; } .image:hover .removeImage, -.attachment:hover .removeImage, .removeImage:focus-visible { opacity: 1; } -.attachment { +/* Attached files and the current-file suggestion: one height, like the chips in the text. */ +.attachment, +.suggestion { position: relative; display: inline-flex; align-items: center; - gap: 6px; + gap: 5px; max-width: 240px; - height: 44px; - padding: 0 10px; - border-radius: var(--radius-small); + height: 24px; + padding: 0 4px 0 7px; + border-radius: var(--radius-control); box-shadow: inset 0 0 0 1px var(--border); + font-size: var(--fs-small); + color: var(--fg-strong); +} +.suggestion { + padding-right: 8px; + border: 0; + background: none; + box-shadow: none; + outline: 1px dashed var(--border-strong); + outline-offset: -1px; + color: var(--fg-muted); + cursor: pointer; + transition: + color var(--dur-fast) var(--ease), + background var(--dur-fast) var(--ease); +} +.suggestion:hover { + background: var(--bg-hover); + color: var(--fg-strong); +} +.suggestion:focus-visible { + outline: 2px solid var(--focus-ring); +} +.suggestionHint { + color: var(--fg-faint); +} +.removeChip { + display: grid; + place-items: center; + width: 16px; + height: 16px; + padding: 0; + border: 0; + border-radius: var(--radius-small); + background: none; + color: var(--fg-muted); + cursor: pointer; +} +.removeChip:hover { + background: var(--bg-hover); + color: var(--fg-strong); } .attachmentName { overflow: hidden; @@ -416,16 +464,6 @@ } /* `@` / `/` completion; Popup keeps the list within the viewport. */ -.caretMirror { - position: fixed; - top: 0; - left: 0; - box-sizing: border-box; - visibility: hidden; - pointer-events: none; - white-space: pre-wrap; - overflow-wrap: break-word; -} .popup { display: flex; flex-direction: column; @@ -453,3 +491,30 @@ text-overflow: ellipsis; color: var(--fg-subtle); } +.match { + background: none; + color: var(--fg-completion-match, var(--accent)); + font-weight: 600; +} +.popupFooter { + display: flex; + flex-wrap: wrap; + gap: 4px 14px; + padding: 5px 12px 6px; + border-top: 1px solid var(--border); + color: var(--fg-subtle); + font-size: var(--fs-small); +} +.popupFooter kbd { + display: inline-grid; + place-items: center; + min-width: 16px; + height: 16px; + margin-right: 2px; + padding: 0 3px; + border-radius: var(--radius-small); + background: var(--bg-hover); + color: var(--fg-muted); + font-family: var(--font-keys, inherit); + font-size: var(--fs-tiny, 11px); +} diff --git a/src/features/agents/Composer.tsx b/src/features/agents/Composer.tsx index 84e7682ec..1d2590cbd 100644 --- a/src/features/agents/Composer.tsx +++ b/src/features/agents/Composer.tsx @@ -1,34 +1,37 @@ /** * The message box of the New Task page and of sessions: `@` file and folder references - * (project index search), `/` agent commands, ↑ / ↓ history, pasted or dropped images, files dropped from - * outside the project as attachments, Shift+Tab to cycle - * the agent's mode. Its draft lives in the store under `id`. + * (project index search) shown as chips, `/` agent commands, `>` quotes as blocks, ↑ / ↓ + * history, pasted or dropped images, files dropped from outside the project as attachments, + * pasted project paths as references, Shift+Tab to cycle the agent's mode. Its draft lives + * in the store under `id`; the text there is what's sent (see `composerEditor`). */ -import { - Fragment, - useCallback, - useEffect, - useLayoutEffect, - useMemo, - useRef, - useState, - type KeyboardEvent, - type ReactNode, -} from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; import clsx from "clsx"; -import type { AgentCommand, AgentConfigOption, AgentImage, SendKey, WhileRunning } from "@/bindings"; +import type { VirtualElement } from "@floating-ui/react-dom"; +import { history, historyKeymap, insertNewline, standardKeymap } from "@codemirror/commands"; +import { Annotation, Compartment, EditorState, Prec } from "@codemirror/state"; +import { EditorView, keymap, placeholder as placeholderText, type ViewUpdate } from "@codemirror/view"; +import type { AgentCommand, AgentConfigOption, AgentImage, SendKey, SymbolMatch, WhileRunning } from "@/bindings"; +import { useEditorRegistry, openEditorPaths } from "@/editor/api"; import { call, commands, isTauri } from "@/platform/ipc"; import { nativeDropPoint } from "@/platform/nativeDrop"; import { invokeLocal } from "@/platform/tauriCore"; import { useTx } from "@/platform/i18n"; import { basename } from "@/platform/project"; import { isRemoteWindow } from "@/platform/remote"; -import { notifications, OWNS_FILE_DROP } from "@/workbench/contributions"; +import { registerKeyClaim } from "@/platform/keymap"; +import { isVirtualUri } from "@/platform/virtualDocs"; +import { copySourceOf } from "@/platform/clipboardSource"; +import { + getAgentContextSources, + notifications, + OWNS_FILE_DROP, + type AgentContextSource, +} from "@/workbench/contributions"; import { FILES_DRAG, Icon, IconButton, - InlineTag, List, Popup, firstSelectable, @@ -41,14 +44,19 @@ import { MAX_IMAGE_BYTES, applyCompletion, atEdgeLine, + isMentioned, isPathQuery, mergeMatches, resolveTyped, completionAt, + fenced, + LONG_PASTE_LINES, + looksLikeTrace, + pastedPaths, + placesInText, imageFromDataUrl, matchCommands, mentionOf, - messageTokens, modeOption, nextValue, recall, @@ -56,24 +64,57 @@ import { type Completion, type FileRef, } from "./composerModel"; +import { referenceExtensions, setReferences } from "./composerEditor"; +import { referenceHover } from "./ReferenceChip"; import { composerDraft, updateComposer, useAgents } from "./store"; import { ImagePreview, imageSrc } from "./ImagePreview"; -import { useCompletionAnchor } from "./useCompletionAnchor"; import { useAgentSettings } from "./agentSettings"; import styles from "./Composer.module.css"; import { isImeKey } from "@/platform/ime"; -import { isMacHost } from "@/platform/keymap"; -const MAX_PROMPT_HEIGHT = 280; const MAX_ITEMS = 12; +const MAX_OPEN_EDITORS = 5; + +type Section = "command" | "skill" | "open" | "project" | "context" | "files"; type Item = - | { kind: "file"; path: string; rel: string; dir?: boolean } + | { + kind: "file"; + path: string; + rel: string; + dir?: boolean; + indices?: readonly number[]; + } | { kind: "command"; command: AgentCommand } - | { kind: "section"; source: "command" | "skill" }; + | { kind: "context"; source: AgentContextSource } + | { kind: "symbol"; symbol: SymbolMatch; path: string } + | { kind: "section"; source: Section }; const isSection = (item: Item) => item.kind === "section"; +const SECTION_TITLES: Record = { + command: "Commands", + skill: "Skills", + open: "Open Editors", + project: "Project", + context: "Context", + files: "Files", +}; + +/** A change the store made (a quote, a reference sent from the editor): not written back. */ +const fromStore = Annotation.define(); + +/** `abs` relative to the first of `bases` it is under ("." for the base itself). */ +function relativeTo(bases: readonly string[], abs: string): string | null { + const source = resolveTyped("", abs.replace(/\\/g, "/")); + const base = bases + .filter(Boolean) + .map((path) => resolveTyped(path, ".")) + .find((path) => source === path || source.startsWith(`${path}/`)); + if (!base) return null; + return source === base ? "." : source.slice(base.length + 1); +} + export interface ComposerProps { /** Store key of the draft. */ id: string; @@ -105,7 +146,13 @@ export interface ComposerProps { * modifier, when Enter sends) the other way; without the send key, Enter is a new line. */ export function sendKeyAction( - e: { key: string; shiftKey: boolean; metaKey: boolean; ctrlKey: boolean; altKey?: boolean }, + e: { + key: string; + shiftKey: boolean; + metaKey: boolean; + ctrlKey: boolean; + altKey?: boolean; + }, sendWith: SendKey, whileRunning: WhileRunning, ): "queue" | "now" | null { @@ -122,64 +169,205 @@ export function sendKeyAction( return (whileRunning === "steer") !== other ? "now" : "queue"; } +/** Highlights the matched characters of `text` (`indices` counted from `offset`). */ +function Matched({ text, indices, offset = 0 }: { text: string; indices?: readonly number[]; offset?: number }) { + if (!indices?.length) return <>{text}; + const marked = new Set(indices.map((i) => i - offset)); + const out: ReactNode[] = []; + let run = ""; + let runMarked = false; + const flush = (key: number) => { + if (!run) return; + out.push( + runMarked ? ( + + {run} + + ) : ( + run + ), + ); + run = ""; + }; + [...text].forEach((ch, i) => { + const m = marked.has(i); + if (m !== runMarked) flush(i); + runMarked = m; + run += ch; + }); + flush(text.length); + return <>{out}; +} + export function Composer(props: ComposerProps) { const { id, root, projectRoot } = props; const tx = useTx(); const draft = useAgents((s) => s.composers.get(id)); const text = draft?.text ?? ""; const images = draft?.images ?? []; - const attached = useMemo(() => draft?.files.filter((f) => f.attached) ?? [], [draft?.files]); - const tokens = useMemo(() => messageTokens(text), [text]); + const draftFiles = draft?.files; + const attached = useMemo(() => draftFiles?.filter((f) => f.attached) ?? [], [draftFiles]); const [preview, setPreview] = useState(null); - const ref = useRef(null); - const mirrorRef = useRef(null); + const hostRef = useRef(null); + const viewRef = useRef(null); + // The same view, for rendering (the completion popup's anchor). + const [shownView, setShownView] = useState(null); const boxRef = useRef(null); const imageInput = useRef(null); + const placeholderSlot = useRef(new Compartment()); const [completion, setCompletion] = useState(null); const [files, setFiles] = useState([]); const [active, setActive] = useState(0); - const composing = useRef(false); - const recalled = useRef<{ index: number; stash: string }>({ index: -1, stash: "" }); + const recalled = useRef<{ index: number; stash: string }>({ + index: -1, + stash: "", + }); const { sendWith, whileRunning } = useAgentSettings(); + /** Replaces `from`–`to` with `insert` and puts the caret at `caret` (after the insert by default). */ + const replace = useCallback((from: number, to: number, insert: string, caret = from + insert.length) => { + const view = viewRef.current; + if (!view) return; + view.dispatch({ + changes: { from, to, insert }, + selection: { anchor: caret }, + userEvent: "input.complete", + }); + view.focus(); + }, []); + const setText = (value: string, caret = value.length) => { + const view = viewRef.current; + if (view) replace(0, view.state.doc.length, value, caret); + }; + + // Late-bound handlers: the editor is created once per draft, the props change every render. + const onKeyDownRef = useRef<(e: KeyboardEvent, view: EditorView) => boolean>(() => false); + const onPasteRef = useRef<(e: ClipboardEvent, view: EditorView) => boolean>(() => false); + const onUpdateRef = useRef<(u: ViewUpdate) => void>(() => {}); + + useLayoutEffect(() => { + const host = hostRef.current; + if (!host) return; + const view = new EditorView({ + parent: host, + state: EditorState.create({ + doc: composerDraft(id).text, + extensions: [ + history(), + EditorView.lineWrapping, + placeholderSlot.current.of([]), + EditorView.contentAttributes.of({ + "aria-multiline": "true", + spellcheck: "false", + autocorrect: "off", + autocapitalize: "off", + }), + Prec.highest( + EditorView.domEventHandlers({ + keydown: (e, v) => onKeyDownRef.current(e, v), + paste: (e, v) => onPasteRef.current(e, v), + }), + ), + referenceExtensions(), + keymap.of([ + { key: "Enter", run: insertNewline, shift: insertNewline }, + { key: "Mod-Enter", run: insertNewline }, + ]), + keymap.of([...standardKeymap, ...historyKeymap]), + EditorView.updateListener.of((u) => onUpdateRef.current(u)), + ], + }), + }); + view.dispatch({ effects: setReferences.of(composerDraft(id).files) }); + viewRef.current = view; + setShownView(view); + recalled.current = { index: -1, stash: "" }; + const disposeHover = referenceHover(host); + return () => { + disposeHover(); + viewRef.current = null; + setShownView(null); + view.destroy(); + }; + }, [id]); + + useLayoutEffect(() => { + viewRef.current?.dispatch({ + effects: placeholderSlot.current.reconfigure(placeholderText(tx(props.placeholder))), + }); + }, [props.placeholder, tx, id]); + + useLayoutEffect(() => { + viewRef.current?.contentDOM.setAttribute("aria-label", tx("Message")); + }, [tx, id]); + + // The store's text changed elsewhere (a quote, Send to Agent, a restored message). + useLayoutEffect(() => { + const view = viewRef.current; + if (!view || view.state.doc.toString() === text) return; + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: text }, + selection: { anchor: text.length }, + annotations: fromStore.of(true), + }); + }, [text, id]); + + useLayoutEffect(() => { + viewRef.current?.dispatch({ effects: setReferences.of(draftFiles ?? []) }); + }, [draftFiles, id]); + + const onUpdate = (u: ViewUpdate) => { + if (u.docChanged && !u.transactions.some((t) => t.annotation(fromStore))) { + updateComposer(id, { text: u.state.doc.toString() }); + } + if (u.focusChanged && !u.view.hasFocus) { + setCompletion(null); + return; + } + if (u.docChanged || u.selectionSet) { + const composing = u.view.composing || u.view.compositionStarted; + setCompletion(composing ? null : completionAt(u.state.doc.toString(), u.state.selection.main.head)); + if (u.docChanged) setActive(0); + } + }; + useEffect(() => { - if (props.autoFocus) ref.current?.focus(); - }, [props.autoFocus]); + if (props.autoFocus) viewRef.current?.focus(); + }, [props.autoFocus, id]); const focus = useAgents((s) => (s.focus?.key === id ? s.focus.seq : 0)); useEffect(() => { - const el = ref.current; - if (!focus || !el) return; - el.focus(); - el.setSelectionRange(el.value.length, el.value.length); - el.scrollTop = el.scrollHeight; + const view = viewRef.current; + if (!focus || !view) return; + view.focus(); + view.dispatch({ + selection: { anchor: view.state.doc.length }, + scrollIntoView: true, + }); }, [focus]); - // Grow with the text, up to a limit. - useLayoutEffect(() => { - const el = ref.current; - if (!el) return; - el.style.height = "auto"; - el.style.height = `${Math.min(el.scrollHeight, MAX_PROMPT_HEIGHT)}px`; - }, [text]); - - // A textarea that scrolls loses content width to its scrollbar: give the mirror the same - // width and offset, or a long prompt wraps a line earlier and the painted text drifts. - const syncMirror = useCallback(() => { - const el = ref.current; - const mirror = mirrorRef.current; - if (!el || !mirror) return; - mirror.style.right = `${el.offsetWidth - el.clientWidth}px`; - mirror.scrollTop = el.scrollTop; - }, []); - useLayoutEffect(syncMirror, [text, syncMirror]); - // `@` completion: project file search, mapped into the task's directory. useEffect(() => { if (completion?.kind !== "file") return; let alive = true; const query = completion.query; const timer = setTimeout(() => { + if (query.startsWith("#")) { + // `@#name`: a symbol, referenced by its file and line. + call(commands.findSymbols(query.slice(1), "all", MAX_ITEMS)) + .then((found) => { + if (!alive) return; + setFiles( + found.map((symbol) => ({ + kind: "symbol", + symbol, + path: root === projectRoot ? symbol.path : `${root}/${symbol.relPath}`, + })), + ); + }) + .catch(() => alive && setFiles([])); + return; + } if (isPathQuery(query)) { // Outside the index: list the directory typed so far. const typed = /(^|\/)\.\.?$/.test(query) ? `${query}/` : query; @@ -194,7 +382,12 @@ export function Composer(props: ComposerProps) { .slice(0, MAX_ITEMS) .map((f) => { const rel = `${dirPart}${f.name}`; - return { kind: "file", rel, dir: f.dir, path: resolveTyped(root, rel) }; + return { + kind: "file", + rel, + dir: f.dir, + path: resolveTyped(root, rel), + }; }), ); }) @@ -204,18 +397,28 @@ export function Composer(props: ComposerProps) { Promise.all([call(commands.findFiles(query, MAX_ITEMS)), call(commands.findDirs(query, MAX_ITEMS))]) .then(async ([found, dirs]) => { if (!alive) return; - // A bare `@`: the index has nothing to match on, so list the root instead of - // showing no popup at all. + // A bare `@`: the files open in editors, then the root (the index has nothing to + // match on). if (!query && found.length + dirs.length === 0) { + const open: Item[] = []; + for (const path of openEditorPaths()) { + const rel = isVirtualUri(path) ? null : relativeTo([projectRoot, root], path); + if (!rel || rel === "." || open.some((o) => o.kind === "file" && o.rel === rel)) continue; + open.push({ kind: "file", rel, path: resolveTyped(root, rel) }); + if (open.length >= MAX_OPEN_EDITORS) break; + } const top = await call(commands.pathCompletions(`${root}/_`, "")).catch(() => []); if (!alive) return; + const listed: Item[] = top.slice(0, MAX_ITEMS).map((f) => ({ + kind: "file", + rel: f.name, + dir: f.dir, + path: resolveTyped(root, f.name), + })); setFiles( - top.slice(0, MAX_ITEMS).map((f) => ({ - kind: "file", - rel: f.name, - dir: f.dir, - path: resolveTyped(root, f.name), - })), + open.length + ? [{ kind: "section", source: "open" }, ...open, { kind: "section", source: "project" }, ...listed] + : listed, ); return; } @@ -224,6 +427,7 @@ export function Composer(props: ComposerProps) { kind: "file", rel: f.rel, dir: f.dir, + indices: f.indices, path: root === projectRoot ? f.path : `${root}/${f.rel}`, })), ); @@ -238,7 +442,20 @@ export function Composer(props: ComposerProps) { const items: Item[] = useMemo(() => { if (!completion) return []; - if (completion.kind === "file") return files; + if (completion.kind === "file") { + const q = completion.query.toLowerCase(); + if (q.startsWith("#") || isPathQuery(q)) return files; + // `@problems`, `@terminal`, `@changes`…: what features offer, above the files. + const sources = getAgentContextSources().filter((s) => s.id.startsWith(q)); + if (!sources.length) return files; + const rest: Item[] = + files[0]?.kind === "section" || !files.length ? files : [{ kind: "section", source: "files" }, ...files]; + return [ + { kind: "section", source: "context" }, + ...sources.map((source) => ({ kind: "context" as const, source })), + ...rest, + ]; + } const out: Item[] = []; let source: "command" | "skill" | undefined; for (const command of matchCommands(props.commands, completion.query)) { @@ -252,41 +469,79 @@ export function Composer(props: ComposerProps) { return out; }, [completion, files, props.commands]); const activeIndex = items[active] && !isSection(items[active]!) ? active : firstSelectable(items, isSection); - const open = !!completion && items.length > 0; - const completionAnchor = useCompletionAnchor(ref, open ? completion.to : null, text); - - const setText = (value: string, caret?: number, restoreSelection = true) => { - updateComposer(id, { text: value }); - const c = caret ?? value.length; - setCompletion(composing.current ? null : completionAt(value, c)); - setActive(0); - if (caret !== undefined && restoreSelection) { - requestAnimationFrame(() => { - ref.current?.focus(); - ref.current?.setSelectionRange(caret, caret); - }); - } - }; + const open = !!completion && items.some((item) => !isSection(item)); + const anchorAt = open ? completion.to : null; + const completionAnchor = useMemo(() => { + const view = shownView; + if (anchorAt === null || !view) return null; + return { + contextElement: view.dom, + getBoundingClientRect: () => { + const at = view.coordsAtPos(Math.min(anchorAt, view.state.doc.length)); + if (!at) return view.contentDOM.getBoundingClientRect(); + return new DOMRect(at.left, at.top, 0, at.bottom - at.top); + }, + }; + }, [anchorAt, shownView]); /** Enter or a click references the item; Tab on a folder keeps completing inside it. */ const accept = (item: Item | undefined, descend = false) => { if (!item || item.kind === "section" || !completion) return; + const current = viewRef.current?.state.doc.toString() ?? text; + if (item.kind === "context") { + const view = viewRef.current; + const at = completion; + setCompletion(null); + if (!view) return; + void item.source.resolve().then( + (context) => { + if (!context) { + replace(at.from, at.to, ""); + notifications().notify({ + level: "info", + title: tx(item.source.title), + body: tx("Nothing to add right now"), + }); + } else if (context.kind === "block") { + insertBlock(view, at.from, at.to, context.info, context.text); + } else { + const refs = context.paths.flatMap((path) => { + const rel = relativeTo([root, projectRoot], path); + return rel && rel !== "." && !/\s/.test(rel) ? [{ path: resolveTyped(root, rel), rel }] : []; + }); + const known = new Set(composerDraft(id).files.map((f) => f.path)); + updateComposer(id, { files: [...composerDraft(id).files, ...refs.filter((r) => !known.has(r.path))] }); + replace(at.from, at.to, refs.length ? `${refs.map((r) => mentionOf(r.rel)).join(" ")} ` : ""); + } + }, + (error: unknown) => + notifications().notify({ level: "error", title: tx(item.source.title), body: String(error) }), + ); + return; + } + if (item.kind === "symbol") { + const rel = item.symbol.relPath; + const line = item.symbol.range.start.line + 1; + updateComposer(id, { files: [...composerDraft(id).files, { path: item.path, rel } satisfies FileRef] }); + const next = applyCompletion(current, completion, mentionOf(rel, { from: line, to: line })); + setText(next.text, next.caret); + setCompletion(null); + return; + } if (item.kind === "file") { const rel = item.dir ? `${item.rel}/` : item.rel; // A folder stays referenced while its `@folder/` is left as typed (`toPrompt`). - const current = composerDraft(id); - updateComposer(id, { files: [...current.files, { path: item.path, rel } satisfies FileRef] }); + updateComposer(id, { + files: [...composerDraft(id).files, { path: item.path, rel } satisfies FileRef], + }); if (item.dir && descend) { - const insert = mentionOf(rel); - setText(text.slice(0, completion.from) + insert + text.slice(completion.to), completion.from + insert.length); + replace(completion.from, completion.to, mentionOf(rel)); return; } - const next = applyCompletion(text, completion, mentionOf(rel)); + const next = applyCompletion(current, completion, mentionOf(rel)); setText(next.text, next.caret); } else { - // Inserted in place: the order of the message is kept, and the text is tagged - // where it stands (see the mirror below the textarea). - const next = applyCompletion(text, completion, `/${item.command.name}`); + const next = applyCompletion(current, completion, `/${item.command.name}`); setText(next.text, next.caret); } setCompletion(null); @@ -305,19 +560,18 @@ export function Composer(props: ComposerProps) { const files = current.files.filter((f) => known.has(f.path)); const refs: FileRef[] = []; for (const raw of paths) { - const source = resolveTyped("", raw.replace(/\\/g, "/")); - const base = [root, projectRoot] - .filter(Boolean) - .map((path) => resolveTyped(path, ".")) - .find((path) => source === path || source.startsWith(`${path}/`)); if (!/^(\/|[A-Za-z]:[\\/])/.test(raw)) continue; - if (!base) { + const rel = relativeTo([root, projectRoot], raw); + if (rel === null) { if (!attachOutside || isRemoteWindow() || known.has(raw)) continue; known.add(raw); - refs.push({ path: raw, rel: basename(source), attached: true }); + refs.push({ + path: raw, + rel: basename(resolveTyped("", raw.replace(/\\/g, "/"))), + attached: true, + }); continue; } - const rel = source === base ? "." : source.slice(base.length + 1); const path = resolveTyped(root, rel); if (known.has(path)) continue; known.add(path); @@ -341,7 +595,11 @@ export function Composer(props: ComposerProps) { const fitsLimit = (name: string, size: number) => { if (size <= MAX_IMAGE_BYTES) return true; - notifications().notify({ level: "warning", title: "Image too large", body: tx`${name} is over 5 MB.` }); + notifications().notify({ + level: "warning", + title: "Image too large", + body: tx`${name} is over 5 MB.`, + }); return false; }; @@ -363,6 +621,148 @@ export function Composer(props: ComposerProps) { if (image && fitsLimit("image", (image.data.length * 3) / 4)) addImages([image]); }; + /** + * Pasted paths of project files or folders (one per line, with `:10-20` lines, quoted or + * `file://`) go in as references when they all exist; anything else is pasted as text. + */ + const pastePath = (pasted: string, view: EditorView): boolean => { + const paths = pastedPaths(pasted); + const found = paths?.map((p) => ({ ...p, rel: relativeTo([root, projectRoot], p.path) })); + // A mention ends at whitespace: a path with a space stays text. + if (!found || found.some((p) => !p.rel || p.rel === "." || /\s/.test(p.rel))) return false; + const { from, to } = view.state.selection.main; + void Promise.all( + found.map(async (p) => { + const path = resolveTyped(root, p.rel!); + const kind = await call(commands.fsEntryKind(path)); + const dir = kind === "dir"; + return { path, rel: dir ? `${p.rel}/` : p.rel!, lines: dir ? undefined : p.lines }; + }), + ).then( + (refs) => { + const known = new Set(composerDraft(id).files.map((f) => f.path)); + const added = refs.filter((r) => !known.has(r.path)).map(({ path, rel }) => ({ path, rel }) satisfies FileRef); + updateComposer(id, { files: [...composerDraft(id).files, ...added] }); + const before = view.state.sliceDoc(Math.max(0, from - 1), from); + const glue = before && !/\s/.test(before) ? " " : ""; + replace(from, to, `${glue}${refs.map((r) => mentionOf(r.rel, r.lines)).join(" ")} `); + }, + () => replace(from, to, pasted), + ); + return true; + }; + + /** The project files `text` names at a line, as `@rel:line` (existing files only). */ + const projectPlaces = async (text: string): Promise => { + const found = await Promise.all( + placesInText(text).map(async ({ path, line }) => { + const absolute = /^(\/|[A-Za-z]:[\\/])/.test(path); + const rel = relativeTo([root, projectRoot], absolute ? path : resolveTyped(root, path.replace(/^\.\//, ""))); + if (!rel || rel === "." || /\s/.test(rel)) return null; + const kind = await call(commands.fsEntryKind(resolveTyped(root, rel))).catch(() => null); + return kind === "file" ? { rel, line } : null; + }), + ); + const refs = found.filter((r) => r !== null); + if (refs.length) { + const known = new Set(composerDraft(id).files.map((f) => f.rel)); + const added = [...new Set(refs.map((r) => r.rel))] + .filter((rel) => !known.has(rel)) + .map((rel) => ({ path: resolveTyped(root, rel), rel }) satisfies FileRef); + updateComposer(id, { files: [...composerDraft(id).files, ...added] }); + } + return refs.map((r) => mentionOf(r.rel, { from: r.line, to: r.line })); + }; + + /** + * `text` as a ``` block on its own lines in place of `from`–`to`; the project files it names + * at a line follow it as references once they are found. + */ + const insertBlock = (view: EditorView, start: number, to: number, info: string, text: string) => { + // The spaces before it on its line go: the block starts a line of its own. + const lineStart = view.state.doc.lineAt(start).from; + const from = lineStart + view.state.sliceDoc(lineStart, start).replace(/[ \t]+$/, "").length; + const before = view.state.sliceDoc(Math.max(0, from - 1), from); + const insert = `${before && before !== "\n" ? "\n" : ""}${fenced(text, info)}\n`; + replace(from, to, insert); + const end = from + insert.length; + const doc = view.state.doc; + void projectPlaces(text).then((mentions) => { + if (!mentions.length) return; + // Right after the block, unless the text changed meanwhile: then at the end. + const at = view.state.doc === doc ? end : view.state.doc.length; + replace(at, at, `${mentions.join(" ")} `); + }); + }; + + /** A stack trace, or text too long to read in the box, goes in as a block. */ + const pasteLong = (pasted: string, view: EditorView): boolean => { + const trace = looksLikeTrace(pasted); + if (!trace && pasted.split("\n").length < LONG_PASTE_LINES) return false; + const { from, to } = view.state.selection.main; + insertBlock(view, from, to, trace ? "trace" : "text", pasted); + return true; + }; + + /** + * Text copied in the IDE: an editor's lines become a reference to them (a ``` block when the + * file is outside the project), a terminal's output a terminal block. A single line from an + * editor is pasted as text. + */ + const pasteCopied = (pasted: string, view: EditorView): boolean => { + const source = copySourceOf(pasted); + if (!source) return false; + const { from, to } = view.state.selection.main; + const block = (info: string) => insertBlock(view, from, to, info, pasted); + if (source.kind === "terminal") { + block(`terminal ${source.title}`.trim()); + return true; + } + if (!pasted.replace(/\s+$/, "").includes("\n")) return false; + const rel = relativeTo([root, projectRoot], source.path); + if (!rel || rel === ".") { + const ext = /\.([\w+-]+)$/.exec(source.path)?.[1] ?? ""; + block(ext); + return true; + } + updateComposer(id, { files: [...composerDraft(id).files, { path: resolveTyped(root, rel), rel }] }); + const before = view.state.sliceDoc(Math.max(0, from - 1), from); + const glue = before && !/\s/.test(before) ? " " : ""; + replace(from, to, `${glue}${mentionOf(rel, { from: source.from, to: source.to })} `); + return true; + }; + + const onPaste = (e: ClipboardEvent, view: EditorView): boolean => { + const data = e.clipboardData; + if (!data) return false; + const pasted = [...data.files].filter((f) => f.type.startsWith("image/")); + if (pasted.length) { + e.preventDefault(); + readImageFiles(pasted); + return true; + } + if (isTauri() && !data.types.length) { + pasteClipboardImage().catch((error: unknown) => + notifications().notify({ + level: "error", + title: tx("Cannot insert image"), + body: String(error), + }), + ); + return false; + } + const plain = data.getData("text/plain"); + if (plain && pasteCopied(plain, view)) { + e.preventDefault(); + return true; + } + if (plain && (pastePath(plain, view) || pasteLong(plain, view))) { + e.preventDefault(); + return true; + } + return false; + }; + // Files dropped from the OS onto the box: images are inlined when they can be, other files // referenced, or attached by path when outside the project. useEffect(() => { @@ -427,73 +827,114 @@ export function Composer(props: ComposerProps) { }); }, [addPaths]); - const onKeyDown = (e: KeyboardEvent) => { - if (composing.current || isImeKey(e.nativeEvent)) return; + // The editor is a text field to the IDE keymap: plain keys type here, shortcuts stay global; + // the completion keeps Escape. + useEffect( + () => + registerKeyClaim((e, stroke) => { + const box = boxRef.current; + const target = e.target as Element | null; + if (!box || !target?.closest || !box.contains(target) || !target.closest(".cm-content")) return false; + if (stroke === "Escape" && box.hasAttribute("data-completing")) return true; + if ((e.key === "Backspace" || e.key === "Delete") && !e.shiftKey) return true; + return !(e.metaKey || e.ctrlKey || e.altKey) && !/^(Shift\+)?(F\d{1,2}|Escape)$/.test(stroke); + }), + [], + ); + + const onKeyDown = (e: KeyboardEvent, view: EditorView): boolean => { + // The input method's (the editor leaves them alone too). + if (view.composing || isImeKey(e)) return false; + const handled = () => { + e.preventDefault(); + return true; + }; if (open) { if (e.key === "ArrowDown" || e.key === "ArrowUp") { - e.preventDefault(); - const next = listNavigate(e.key, { items, active: activeIndex, isSection, wrap: true }); + const next = listNavigate(e.key, { + items, + active: activeIndex, + isSection, + wrap: true, + }); if (next !== null) setActive(next); - return; + return handled(); } if (e.key === "Enter" || e.key === "Tab") { - e.preventDefault(); accept(items[activeIndex], e.key === "Tab"); - return; + return handled(); } if (e.key === "Escape") { - e.preventDefault(); e.stopPropagation(); setCompletion(null); - return; + return handled(); } } const send = sendKeyAction(e, sendWith, whileRunning); if (send) { - e.preventDefault(); if (!props.disabled) props.onSubmit(send === "now"); recalled.current = { index: -1, stash: "" }; - return; - } - // macOS text boxes scroll on Home / End and leave the caret where it is. - if ((e.key === "Home" || e.key === "End") && !e.altKey && !e.ctrlKey && !e.metaKey && isMacHost()) { - e.preventDefault(); - getSelection()?.modify(e.shiftKey ? "extend" : "move", e.key === "Home" ? "backward" : "forward", "lineboundary"); - return; + return handled(); } if (e.key === "Tab" && e.shiftKey) { const mode = modeOption(props.config); const value = mode && nextValue(mode); if (mode && value && props.onConfig) { - e.preventDefault(); props.onConfig(mode.id, value); + return handled(); } - return; + return false; } - if ((e.key === "ArrowUp" || e.key === "ArrowDown") && !e.altKey && !e.metaKey) { + if ((e.key === "ArrowUp" || e.key === "ArrowDown") && !e.altKey && !e.metaKey && !e.shiftKey) { const dir = e.key === "ArrowUp" ? -1 : 1; - const el = e.currentTarget; + const current = view.state.doc.toString(); const r = recalled.current; // Only from an empty box or one showing a recalled message, with the caret on the edge line. - const fresh = r.index === -1 ? text === "" : text === props.history[r.index]; - if (!fresh || !atEdgeLine(text, el.selectionStart, dir)) return; + const fresh = r.index === -1 ? current === "" : current === props.history[r.index]; + if (!fresh || !atEdgeLine(current, view.state.selection.main.head, dir)) return false; const next = recall(props.history, r.index, dir); - if (next === null) return; - e.preventDefault(); - if (r.index === -1) r.stash = text; + if (next === null) return false; + if (r.index === -1) r.stash = current; r.index = next; const value = next === -1 ? r.stash : props.history[next]!; - setText(value, value.length); + setText(value); setCompletion(null); + return handled(); } + return false; }; + useLayoutEffect(() => { + onUpdateRef.current = onUpdate; + onPasteRef.current = onPaste; + onKeyDownRef.current = onKeyDown; + }); + + // The file in the focused editor, offered as a reference until the draft has it. + const activePath = useEditorRegistry((s) => s.active?.ctx.path ?? null); + const suggested = useMemo(() => { + if (!activePath || isVirtualUri(activePath)) return null; + const rel = relativeTo([projectRoot, root], activePath); + if (!rel || rel === "." || isMentioned(text, rel)) return null; + return { path: activePath, rel }; + }, [activePath, projectRoot, root, text]); + + const showContext = images.length > 0 || attached.length > 0 || !!suggested; + return (
ref.current?.focus()} + onMouseDown={(e) => { + // The padding around the text focuses it too. + const view = viewRef.current; + if (view && !view.dom.contains(e.target as Node) && !(e.target as Element).closest("button, input")) { + e.preventDefault(); + view.focus(); + } + }} > {open && completionAnchor && ( item.kind === "section" && tx(item.source === "skill" ? "Skills" : "Commands")} + renderSection={(item) => item.kind === "section" && tx(SECTION_TITLES[item.source])} activeIndex={activeIndex} onActiveChange={setActive} onActivate={(item) => accept(item)} @@ -525,39 +970,103 @@ export function Composer(props: ComposerProps) { hoverSelects aria-label={tx(completion.kind === "file" ? "Files" : "Commands")} className={styles.items} - renderItem={(item) => - item.kind === "section" ? null : item.kind === "file" ? ( + renderItem={(item) => { + if (item.kind === "section") return null; + if (item.kind === "context") + return ( + <> + + @{item.source.id} + {tx(item.source.description)} + + ); + if (item.kind === "symbol") + return ( + <> + + + + + + {item.symbol.container ? `${item.symbol.container} · ` : ""} + {item.symbol.relPath}:{item.symbol.range.start.line + 1} + + + ); + if (item.kind === "command") + return ( + <> + /{item.command.name} + {item.command.hint && {item.command.hint}} + {item.command.description} + + ); + const name = basename(item.rel); + const dir = item.rel.slice(0, item.rel.length - name.length).replace(/\/$/, ""); + return ( <> - + - {basename(item.rel)} + {item.dir && "/"} - {item.rel} + {dir} - ) : ( - <> - /{item.command.name} - {item.command.hint && {item.command.hint}} - {item.command.description} - - ) - } + ); + }} /> + )} - {(images.length > 0 || attached.length > 0) && ( -
e.stopPropagation()}> + {fileOver && ( + + )} + {showContext && ( +
e.stopPropagation()}> + {suggested && ( + + )} {attached.map((file) => ( - + {file.rel} @@ -582,62 +1095,8 @@ export function Composer(props: ComposerProps) { setPreview(null)} />
)} -
- {/* The text is painted here with `@file` / `/skill` tags; the textarea above it - keeps native editing, selection and the caret. */} - -