diff --git a/docs/reference.md b/docs/reference.md index c539eff..7585b05 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -78,6 +78,8 @@ Navigation: `ctrl+v` attaches the clipboard's image, or pastes its text when there is no image. Pasting or dropping the path of an image file (quoted, as a `file://` URL, or with `\ ` before spaces) attaches the file rather than typing the path. See [Attachments](#attachments). +Attachments and `@` files show in the box as chips, `[image 1]` or `@src/ui/App.tsx`, in the accent colour: the cursor steps over one in a single move and `backspace` deletes it whole. Deleting an attachment's chip removes the attachment. The text sent is what it was without chips: an attachment's chip is left out, and an `@` file goes as its markdown link. + With the box empty after an interrupted run (or one a usage limit stopped), `enter` continues where it left off and releases messages held in the queue. Typing a trigger opens a list of suggestions above the box: diff --git a/src/model/composerMenu.ts b/src/model/composerMenu.ts index 6c1f331..10d792b 100644 --- a/src/model/composerMenu.ts +++ b/src/model/composerMenu.ts @@ -23,6 +23,8 @@ export interface ComposerItem { readonly label: string; readonly description: string; readonly replacement: string | null; + /** What the composer shows in place of the replacement, as one chip; the replacement is still what's sent. */ + readonly chip?: string; /** A mention's record (a thread, or a pull request), sent with the message. */ readonly record?: ComposerContextRecord; readonly action?: "model"; @@ -138,14 +140,19 @@ export function pathItems(entries: readonly ProjectEntry[]): ComposerItem[] { label: `${entry.path.slice(slash + 1)}${entry.kind === "directory" ? "/" : ""}`, description: slash > 0 ? entry.path.slice(0, slash) : "", replacement: `${serializeComposerFileLink(entry.path)} `, + chip: `@${entry.path}${entry.kind === "directory" ? "/" : ""}`, }; }); } /** The text with the trigger replaced; a trailing space swallows one already there, as the web does. */ export function applyComposerItem(text: string, trigger: ComposerTrigger, replacement: string): { text: string; cursor: number } { - const end = replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd; - return replaceTextRange(text, trigger.rangeStart, end, replacement); + return replaceTextRange(text, trigger.rangeStart, composerItemEnd(text, trigger, replacement), replacement); +} + +/** Where the text a choice replaces ends: the trigger's range, and a space the replacement brings its own of. */ +export function composerItemEnd(text: string, trigger: ComposerTrigger, replacement: string): number { + return replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd; } /** The records for the mentions (threads, pull requests) still in the text, as the message's context. */ diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 47e47fd..c5c3851 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -48,9 +48,10 @@ import { SettingsView } from "./SettingsView.tsx"; import { useWorkspace } from "./useWorkspace.ts"; import { usePullRequests } from "./usePullRequests.ts"; import { rendererClipboard, type Clipboard } from "./clipboard.ts"; +import { composerText, useComposerChips } from "./useComposerChips.ts"; import { openInBrowser, screenTextAt } from "./links.ts"; import { desktopNotify, ring } from "./terminalOut.ts"; -import { colors, statusColor } from "./theme.ts"; +import { colors, statusColor, useMarkdownStyle } from "./theme.ts"; import { BAR, NO_BORDER } from "./edges.ts"; import { ThreadList } from "./ThreadList.tsx"; import { useTurns } from "./useTurns.ts"; @@ -114,6 +115,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const attached = attachThreadId !== undefined; const renderer = useRenderer(); const [clipboard] = useState(() => props.clipboard ?? rendererClipboard(renderer)); + const markdownStyle = useMarkdownStyle(); const { width, height } = useTerminalDimensions(); const [shell, setShell] = useState(session.getShell()); // Any thread, listed or not: subagents open here too. @@ -434,6 +436,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui confirm, say, }); + const chips = useComposerChips({ composerRef, composerKey, pending: attach.pending, remove: attach.remove }); const usage = useUsageSummary(session, settingsIndex !== null && live); const usageInfo = useMemo(() => usageLimits(serverConfig?.config ?? null, now), [serverConfig, now]); const spendResetCredit = (credit: (typeof usageInfo.credits)[number]) => @@ -563,7 +566,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const composer = composerRef.current; if (!composer) return; const key = composerKey; - const file = scratchFile(composer.plainText); + const file = scratchFile(composerText(composer)); showPane({ kind: "local", id: `message:${file.path}`, @@ -620,7 +623,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const putMessage = (key: string, text: string) => { const composer = composerRef.current; if (key !== activeComposerKey.current || !composer) return void drafts.current.set(key, text); - composer.setText(text); + chips.replaceText(composer, text); composer.gotoBufferEnd(); setComposerLines(composerLineCount(composer)); setComposerEmpty(text.trim() === ""); @@ -633,8 +636,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const restoreMessage = (key: string, text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[]) => { const composer = composerRef.current; if (key === activeComposerKey.current && composer) { - if (composer.plainText.trim()) return; - composer.setText(text); + if (composerText(composer).trim()) return; + chips.replaceText(composer, text); composer.gotoBufferEnd(); setComposerLines(composerLineCount(composer)); setComposerEmpty(text === ""); @@ -658,7 +661,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }; const clearComposer = () => { - composerRef.current?.setText(""); + if (composerRef.current) chips.replaceText(composerRef.current, ""); if (threadId) drafts.current.delete(threadId); composerMenu.forget(); setComposerLines(1); @@ -668,11 +671,11 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui /** Enter in the composer; `alternate` is alt+enter, which flips steer and queue. */ const submit = (alternate = false) => { const composer = composerRef.current; - const raw = composer?.plainText ?? ""; + const raw = composer ? composerText(composer) : ""; // A trailing backslash continues onto a new line, for terminals that can't send shift+enter. if (!alternate && config.sendShortcut === "enter" && composer && raw.endsWith("\\")) { - composer.setText(raw.slice(0, -1)); composer.gotoBufferEnd(); + composer.deleteCharBackward(); composer.newLine(); return; } @@ -727,10 +730,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const turns = useTurns({ session, threadId, projection, timeline: current, config: providerConfig, cwd: panel.cwd, ignoreWhitespace: config.diffIgnoreWhitespace, enabled: draft === null, diff, setDiff, scrollRef, confirm, say, showConversation: () => { setMode("nav"); setDetailsPrefState((value) => (width < MIN_CONVERSATION_WIDTH + DETAILS_WIDTH ? false : value)); }, restorePrompt: (id, text) => { - const previous = id === activeComposerKey.current ? composerRef.current?.plainText ?? "" : drafts.current.get(id) ?? ""; + const previous = id === activeComposerKey.current && composerRef.current ? composerText(composerRef.current) : drafts.current.get(id) ?? ""; const next = text ? previous ? `${previous}\n\n${text}` : text : previous; drafts.current.set(id, next); - if (id === activeComposerKey.current) { composerRef.current?.setText(next); setMode("input"); } + if (id === activeComposerKey.current && composerRef.current) { chips.replaceText(composerRef.current, next); setMode("input"); } }, }); @@ -1334,6 +1337,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui focusedBackgroundColor={colors.element} wrapMode="word" keyBindings={[...COMPOSER_KEYS[config.sendShortcut]]} + syntaxStyle={markdownStyle} onSubmit={() => submit()} onPaste={(event: PasteEvent) => { const text = decodePasteBytes(event.bytes); @@ -1347,8 +1351,9 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui onCursorChange={composerMenu.sync} onContentChange={() => { composerMenu.sync(); + chips.sync(); const composer = composerRef.current; - const text = composer?.plainText ?? ""; + const text = composer ? composerText(composer) : ""; if (text) drafts.current.set(composerKey, text); else drafts.current.delete(composerKey); // Wrapped lines count too, so a long paragraph grows the box. diff --git a/src/ui/theme.ts b/src/ui/theme.ts index e09a6fb..5f8bab4 100644 --- a/src/ui/theme.ts +++ b/src/ui/theme.ts @@ -183,6 +183,8 @@ export function useMarkdownStyle(): SyntaxStyle { "markup.quote": { fg: colors.muted, italic: true }, "markup.raw": { fg: colors.plan }, "markup.raw.block": { fg: colors.text }, + // Attachments and mentions in the message box. + "extmark.chip": { fg: colors.accent, bg: colors.element }, }, owner); markdownStyles.set(owner, style); return style; diff --git a/src/ui/useComposerChips.ts b/src/ui/useComposerChips.ts new file mode 100644 index 0000000..5b694e9 --- /dev/null +++ b/src/ui/useComposerChips.ts @@ -0,0 +1,135 @@ +import type { Extmark, TextareaRenderable } from "@opentui/core"; +import type { ChatAttachment } from "@t3tools/contracts"; +import { useEffect, useRef, useState, type RefObject } from "react"; + +/** What a chip stands for: an attachment, which the sent text leaves out, or a mention, sent as `sent`. */ +interface ChipData { + readonly attachmentId?: string; + readonly sent?: string; +} + +/** + * Makes `start`–`end` of the composer (in its cursor offsets) one chip: drawn in the accent + * colour, stepped over by the cursor and deleted whole by backspace. + */ +export function markChip(composer: TextareaRenderable, start: number, end: number, data: ChipData): void { + const extmarks = composer.extmarks; + const typeId = extmarks.getTypeId("chip") ?? extmarks.registerType("chip"); + const styleId = composer.syntaxStyle?.getStyleId("extmark.chip"); + extmarks.create({ start, end, virtual: true, typeId, data, ...(styleId ? { styleId } : {}) }); +} + +/** Inserts `label` at the cursor as a chip, apart from the words either side. */ +function insertChip(composer: TextareaRenderable, label: string, data: ChipData): void { + const before = composer.plainText[indexAtOffset(composer.plainText, composer.cursorOffset) - 1]; + if (before && !/\s/.test(before)) composer.insertText(" "); + const start = composer.cursorOffset; + composer.insertText(label); + markChip(composer, start, composer.cursorOffset, data); + composer.insertText(" "); +} + +function chipsOf(composer: TextareaRenderable): Extmark[] { + const typeId = composer.extmarks.getTypeId("chip"); + return typeId === null ? [] : composer.extmarks.getAllForTypeId(typeId); +} + +const attachmentChips = (composer: TextareaRenderable) => chipsOf(composer).filter((chip) => (chip.data as ChipData | undefined)?.attachmentId); + +/** The index in `text` of a cursor offset, which counts columns, and one for each line break. */ +function indexAtOffset(text: string, offset: number): number { + let column = 0; + let index = 0; + for (const char of text) { + if (column >= offset) break; + column += char === "\n" ? 1 : Bun.stringWidth(char); + index += char.length; + } + return index; +} + +/** The composer's text as it is sent and kept as a draft: mentions as they're sent, attachments (and the space after each) left out. */ +export function composerText(composer: TextareaRenderable): string { + const text = composer.plainText; + let kept = ""; + let from = 0; + for (const chip of chipsOf(composer).sort((a, b) => a.start - b.start)) { + const data = (chip.data ?? {}) as ChipData; + const start = indexAtOffset(text, chip.start); + let end = indexAtOffset(text, chip.end); + if (data.attachmentId && text[end] === " ") end++; + kept += text.slice(from, start) + (data.sent ?? ""); + from = end; + } + return kept + text.slice(from); +} + +/** + * The composer's attachments as chips, `[image 1]` or `[report.pdf]`: each pending one gets a + * chip at the cursor, removing an attachment takes its chip out, and deleting a chip removes + * its attachment. Replace the text through `replaceText`, so the old chips going with the old + * text doesn't count as deleting them. + */ +export function useComposerChips(deps: { + readonly composerRef: RefObject; + readonly composerKey: string; + readonly pending: readonly ChatAttachment[]; + readonly remove: (attachment: ChatAttachment) => void; +}) { + const { composerRef, composerKey, pending } = deps; + /** The attachments with a chip in the composer as it is now. */ + const shown = useRef(new Set()); + /** Bumped when the text is replaced, so the chips go back in. */ + const [replaced, setReplaced] = useState(0); + + // A new composer, new attachments or new text: each needs its chips. + useEffect(() => { + const composer = composerRef.current; + if (!composer) return; + const chips = attachmentChips(composer); + const present = new Set(chips.map((chip) => (chip.data as ChipData).attachmentId)); + for (const chip of chips) { + if (pending.some((attachment) => attachment.id === (chip.data as ChipData).attachmentId)) continue; + composer.extmarks.delete(chip.id); + removeRange(composer, chip.start, chip.end); + } + let images = 0; + for (const attachment of pending) { + if (attachment.type === "image") images++; + if (!present.has(attachment.id)) insertChip(composer, attachment.type === "image" ? `[image ${images}]` : `[${attachment.name}]`, { attachmentId: attachment.id }); + } + shown.current = new Set(pending.map((attachment) => attachment.id)); + }, [composerKey, pending, replaced]); + + return { + /** The text changed: an attachment whose chip was deleted goes too. */ + sync: () => { + const composer = composerRef.current; + if (!composer) return; + const present = new Set(attachmentChips(composer).map((chip) => (chip.data as ChipData).attachmentId)); + for (const attachment of pending) { + if (!shown.current.has(attachment.id) || present.has(attachment.id)) continue; + shown.current.delete(attachment.id); + deps.remove(attachment); + } + }, + /** Sets the composer's text, then puts the attachment chips back. */ + replaceText: (composer: TextareaRenderable, text: string) => { + shown.current.clear(); + composer.setText(text); + setReplaced((count) => count + 1); + }, + }; +} + +/** Deletes the text between two cursor offsets, and the space after it, keeping the cursor where it was. */ +function removeRange(composer: TextareaRenderable, start: number, end: number): void { + const cursor = composer.cursorOffset; + const stop = end + (composer.plainText[indexAtOffset(composer.plainText, end)] === " " ? 1 : 0); + composer.cursorOffset = start; + const from = composer.logicalCursor; + composer.cursorOffset = stop; + const to = composer.logicalCursor; + composer.deleteRange(from.row, from.col, to.row, to.col); + composer.cursorOffset = cursor >= stop ? cursor - (stop - start) : Math.min(cursor, start); +} diff --git a/src/ui/useComposerMenu.ts b/src/ui/useComposerMenu.ts index f02e05e..8105f10 100644 --- a/src/ui/useComposerMenu.ts +++ b/src/ui/useComposerMenu.ts @@ -3,8 +3,9 @@ import type { ComposerContextRecord, EnvironmentId, OrchestrationMessageContext, import { useEffect, useRef, useState, type RefObject } from "react"; import type { T3Session } from "../client/session.ts"; -import { applyComposerItem, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts"; +import { composerItemEnd, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts"; import { keys, type Binding } from "../model/keymap.ts"; +import { markChip } from "./useComposerChips.ts"; import { useComposerPullRequests } from "./usePullRequests.ts"; /** @@ -96,10 +97,17 @@ export function useComposerMenu(deps: { const choose = (item: ComposerItem | undefined) => { const composer = composerRef.current; if (!item || !trigger || !composer) return; - const next = applyComposerItem(state.text, trigger, item.replacement ?? ""); - composer.setText(next.text); - const at = cursorAtIndex(next.text, next.cursor); - composer.setCursor(at.row, at.col); + // An edit in place rather than new text, which would take the chips already there with it. + const replacement = item.replacement ?? ""; + const from = cursorAtIndex(state.text, trigger.rangeStart); + const to = cursorAtIndex(state.text, composerItemEnd(state.text, trigger, replacement)); + composer.deleteRange(from.row, from.col, to.row, to.col); + composer.setCursor(from.row, from.col); + const sent = replacement.trimEnd(); + const start = composer.cursorOffset; + composer.insertText(item.chip ?? sent); + if (item.chip) markChip(composer, start, composer.cursorOffset, { sent }); + composer.insertText(replacement.slice(sent.length)); if (item.record) { const records = mentions.current.get(composerKey) ?? new Map(); records.set(item.record.contextId, item.record); diff --git a/test/app/chips.test.tsx b/test/app/chips.test.tsx new file mode 100644 index 0000000..411d028 --- /dev/null +++ b/test/app/chips.test.tsx @@ -0,0 +1,123 @@ +import { afterEach, describe, expect, test } from "bun:test"; + +import { fakeSession, renderApp, v2ThreadId } from "./harness.tsx"; + +let app: Awaited> | null = null; +const open = async (...args: Parameters) => (app = await renderApp(...args)); +afterEach(() => { + app?.destroy(); + app = null; +}); + +const PNG = Uint8Array.from([0x89, 0x50, 0x4e, 0x47]); +const uploads = (...names: string[]) => { + let count = 0; + const session = fakeSession({ serverConfig: { providers: [], settings: {}, environment: { capabilities: { fileAttachments: { maxUploadBytes: 1 << 20 } } } } }); + // Each upload is a new attachment, as the server makes them. + const uploadAttachment = async (upload: { name: string; mimeType: string; sizeBytes: number }) => { + session.calls.push({ method: "uploadAttachment", args: [upload] }); + const name = names[count] ?? upload.name; + return { type: "image", id: `att-${++count}`, name, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes }; + }; + return { ...session, session: new Proxy(session.session, { get: (target, key) => (key === "uploadAttachment" ? uploadAttachment : Reflect.get(target, key)) }) }; +}; +/** The composer's text line: the row under the attachments line. */ +const composerLine = (frame: string) => frame.split("\n").find((line) => line.includes("┃ ") && /\[image|@src|look|draft/.test(line)) ?? ""; +const spanAt = (app: Awaited>, text: string) => { + const at = app.find(text); + const line = app.renderer.currentRenderBuffer.getSpanLines()[at.y] as unknown as { spans: { text: string; fg: { toString(): string }; bg: { toString(): string } }[] }; + return line.spans.find((span) => span.text.includes(text)); +}; + +describe("composer chips", () => { + test("a pasted image becomes an [image 1] chip, left out of the text that's sent", async () => { + const fake = uploads(); + const app = await open({ session: fake, clipboard: { image: { bytes: PNG, mimeType: "image/png" } } }); + await app.press("i"); + await app.type("look at "); + await app.press("v", { ctrl: true }); + await app.type("this"); + expect(composerLine(app.frame())).toContain("look at [image 1] this"); + await app.press("return"); + const [call] = app.calls("sendMessage"); + expect([call?.args[0], call?.args[1]]).toEqual([v2ThreadId, "look at this"]); + expect(call?.args[5]).toMatchObject([{ id: "att-1" }]); + }); + + test("the chip is drawn in the accent colour on the raised background", async () => { + const app = await open({ session: uploads(), clipboard: { image: { bytes: PNG, mimeType: "image/png" } } }); + await app.press("i"); + await app.press("v", { ctrl: true }); + const { colors } = await import("../../src/ui/theme.ts"); + const span = spanAt(app, "[image 1]"); + const hex = (color: { toString(): string } | undefined) => color?.toString(); + const { RGBA } = await import("@opentui/core"); + expect(hex(span?.fg)).toBe(RGBA.fromHex(colors.accent).toString()); + expect(hex(span?.bg)).toBe(RGBA.fromHex(colors.element).toString()); + }); + + test("backspace deletes a chip whole, and its attachment with it", async () => { + const app = await open({ session: uploads(), clipboard: { image: { bytes: PNG, mimeType: "image/png" } } }); + await app.press("i"); + await app.press("v", { ctrl: true }); + expect(app.frame()).toContain("pasted-image.png ✕"); + await app.press("backspace"); + await app.press("backspace"); + expect(app.frame()).not.toContain("[image"); + expect(app.frame()).not.toContain("pasted-image.png ✕"); + expect(app.calls("deleteAttachment").map((call) => call.args[0])).toEqual(["att-1"]); + }); + + test("removing an attachment takes its chip out, and the others keep theirs", async () => { + const app = await open({ session: uploads("one.png", "two.png"), clipboard: { image: { bytes: PNG, mimeType: "image/png" } } }); + await app.press("i"); + await app.press("v", { ctrl: true }); + await app.press("v", { ctrl: true }); + expect(composerLine(app.frame())).toContain("[image 1] [image 2]"); + const remove = app.find("one.png ✕"); + await app.click(remove.x + "one.png ".length, remove.y); + expect(app.frame()).not.toContain("[image 1]"); + expect(composerLine(app.frame())).toContain("[image 2]"); + }); + + test("a message that fails to send comes back with its chip, and isn't sent with the chip's text", async () => { + const fake = uploads(); + const failing = fakeSession({ failures: { sendMessage: "socket closed" } }); + const session = new Proxy(failing.session, { get: (target, key) => (key === "uploadAttachment" || key === "watchServerConfig" ? Reflect.get(fake.session, key) : Reflect.get(target, key)) }); + const app = await open({ session: { ...failing, session }, clipboard: { image: { bytes: PNG, mimeType: "image/png" } } }); + await app.press("i"); + await app.type("look"); + await app.press("v", { ctrl: true }); + await app.press("return"); + await app.settle(50); + expect(app.calls("sendMessage")[0]?.args[1]).toBe("look"); + expect(composerLine(app.frame())).toContain("look [image 1]"); + expect(app.frame()).toContain("pasted-image.png ✕"); + }); + + test("an @ file is a chip showing its path, and is sent as the link the web sends", async () => { + const app = await open({ session: fakeSession({ results: { searchEntries: [{ kind: "file", path: "src/ui/App.tsx" }] } }) }); + await app.press("i"); + await app.type("see @App"); + await app.settle(200); + expect(app.frame()).toContain("App.tsx"); + await app.press("tab"); + expect(composerLine(app.frame())).toContain("see @src/ui/App.tsx"); + await app.type("now"); + await app.press("return"); + expect(app.calls("sendMessage")[0]?.args[1]).toBe("see [App.tsx](src/ui/App.tsx) now"); + }); + + test("backspace over an @ chip deletes it whole", async () => { + const app = await open({ session: fakeSession({ results: { searchEntries: [{ kind: "file", path: "src/ui/App.tsx" }] } }) }); + await app.press("i"); + await app.type("see @App"); + await app.settle(200); + await app.press("tab"); + await app.press("backspace"); + await app.press("backspace"); + expect(composerLine(app.frame())).not.toContain("@src"); + await app.type("draft"); + expect(composerLine(app.frame())).toContain("see draft"); + }); +});