diff --git a/CHANGELOG.md b/CHANGELOG.md index bb82d41..fd3cdf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,14 @@ Harness spec 3.7.0: one display in every client. answer for three situations; the spec now has one each — no page of the chat is open (and where to open it), the page did not answer, the run took too long. +- **Paste placeholders in the prompt box.** A paste of three lines or more, or of more than 150 + characters, shows as `[Pasted text 40 lines]` (or `[Pasted text 300 chars]`), and an image as + `[Image 1]`, `[Image 2]`…; what is sent is the text itself and the image. One backspace removes + a placeholder and what it stands for; pasting the same text again right after its placeholder + opens it. The transcript shows the placeholder; prompt history, `/undo` and copying from the box + give the text in full. `paste: full` in the config (or `/settings`) shows pastes whole, as + before. + ### Changed - **The terminal opened from the web UI or Desktop picks a shell that exists.** `$SHELL` when @@ -28,6 +36,9 @@ Harness spec 3.7.0: one display in every client. `cmd.exe` — started without `-l`, which none of them takes. (The runtime's pseudo-terminal is documented for Linux and macOS only, and there is no Windows build of the CLI yet: where a terminal cannot be opened, the refusal now says so in a sentence.) +- **Completing an `@file` or moving through the prompt box now counts columns as the box does**: + with a wide character (CJK, an emoji) before the cursor, the `@` list could replace the wrong + part of the line. - **Plainer refusals when a terminal or a folder cannot be used**: each says what to do — `lembas remote terminal on`, `lembas remote add `, close one of the open terminals. diff --git a/schema/config.schema.json b/schema/config.schema.json index fad792b..5ef3b0f 100644 --- a/schema/config.schema.json +++ b/schema/config.schema.json @@ -60,6 +60,14 @@ "description": "When a reply finishes, or the agent waits for you, while the terminal is not focused: ring the bell and ask the terminal for a desktop notification (OSC 9) naming the session — never what the reply says. Default true; false: neither.", "type": "boolean" }, + "paste": { + "description": "A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path.", + "type": "string", + "enum": [ + "placeholder", + "full" + ] + }, "icons": { "description": "emoji (default), or plain: one-column symbols for a terminal font that has no emoji.", "type": "string", diff --git a/src/config/schema.ts b/src/config/schema.ts index 174676f..06dd5a1 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -242,6 +242,7 @@ export const Config = z.strictObject({ busy_input: z.enum(["steer", "queue"]).optional().describe("A message sent while the agent works: steer (default) — it goes in at the next step, after the running tools finish, and the agent carries on with it; queue — it is sent as the next prompt once the task is done."), mouse: z.boolean().optional().describe("false: leave the mouse to the terminal — its own selection and Ctrl+Shift+C work without Shift, and the wheel no longer scrolls the transcript (pgup/pgdn do). Default true."), notify: z.boolean().optional().describe("When a reply finishes, or the agent waits for you, while the terminal is not focused: ring the bell and ask the terminal for a desktop notification (OSC 9) naming the session — never what the reply says. Default true; false: neither."), + paste: z.enum(["placeholder", "full"]).optional().describe("A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path."), icons: z.enum(["emoji", "plain"]).optional().describe("emoji (default), or plain: one-column symbols for a terminal font that has no emoji."), personality: z .enum(PERSONALITIES) diff --git a/src/config/settings.ts b/src/config/settings.ts index add67b6..d4621af 100644 --- a/src/config/settings.ts +++ b/src/config/settings.ts @@ -59,6 +59,7 @@ export const SETTINGS: SettingDef[] = [ { key: "theme", kind: "string", agent: true, scopes: USER, fallback: "moria" }, { key: "theme_background", kind: "enum", values: ["theme", "terminal"], agent: true, scopes: USER, fallback: "theme" }, { key: "busy_input", kind: "enum", values: ["steer", "queue"], agent: true, scopes: USER, fallback: "steer" }, + { key: "paste", kind: "enum", values: ["placeholder", "full"], agent: true, scopes: USER, fallback: "placeholder", hint: "a long paste or a pasted image in the prompt box: a placeholder, or shown in full" }, { key: "icons", kind: "enum", values: ["emoji", "plain"], agent: true, scopes: USER, fallback: "emoji" }, { key: "notify", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "bell and desktop notification when a reply finishes or the agent waits for you while the terminal is not focused" }, { key: "mouse", kind: "boolean", agent: true, scopes: ["global"], reload: true, fallback: "true" }, diff --git a/src/tui/app.tsx b/src/tui/app.tsx index 66e5ef3..041af38 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -18,7 +18,7 @@ import { JobView } from "./components/jobview.tsx" import { SubagentView } from "./components/subagent.tsx" import { Bus } from "../bus/index.ts" import { FocusWatch, noticeSequence, noticeText } from "./notify.ts" -import { Prompt, type PaletteEntry } from "./components/prompt.tsx" +import { Prompt, type PaletteEntry, type PromptHandle } from "./components/prompt.tsx" import { FileIndex } from "../project/files.ts" import { attachmentsFor } from "../project/attach.ts" import { customCommands, expandCommand, type CustomCommand } from "../project/commands.ts" @@ -112,6 +112,10 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => }) let scroll: ScrollBoxRenderable | undefined let input: TextareaRenderable | undefined + let box: PromptHandle | undefined + /** What is selected, as it is copied: a selection in the prompt box in full (a paste placeholder + * as what it stands for), anything else as it reads. */ + const selectedText = (visible: string) => (visible && input?.hasSelection() && input.getSelectedText() === visible ? (box?.expandedSelection() ?? visible) : visible) let quitArmed = 0 const dims = useTerminalDimensions() @@ -334,7 +338,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => if (!left.length) return reason const joined = left.join("\n\n") if (reason === "cancelled") { - const now = input?.plainText.trim() ?? "" + const now = (box?.expanded() ?? input?.plainText ?? "").trim() input?.setText(now ? `${joined}\n\n${now}` : joined) input?.gotoBufferEnd() view.info("stopped — what you sent meanwhile is back in the box") @@ -435,7 +439,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => } /** false: refused — the text stays in the box. */ - const submit = (text: string): boolean | void => { + const submit = (text: string, shown?: string): boolean | void => { const t = text.trim() // Inside a subagent, what is typed is for it; commands are still the session's. if (entered() && !t.startsWith("/")) return void sendToJob(t) @@ -467,7 +471,8 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => // While a task runs, a message joins it: at the next step, or after it (queue). if (app.turns.steer(t)) return if (busy()) return (view.info("still working — esc stops the current reply", "warn"), false) - void send(t) + // `shown`: the box as it looked, paste placeholders in place of what they stand for. + void send(t, shown?.trim() || t) } /** The messages waiting to go in, for ↑ in the box. */ @@ -563,7 +568,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => key.preventDefault() } else if (key.ctrl && key.name === "c" && (key.shift || renderer.hasSelection)) { // Ctrl+Shift+C (where the terminal passes it on), or Ctrl+C over a selection: copy it. - const sel = renderer.getSelection()?.getSelectedText() ?? "" + const sel = selectedText(renderer.getSelection()?.getSelectedText() ?? "") if (sel) copy(sel) else flash("nothing selected — drag over text, or /copy the last reply") renderer.clearSelection() @@ -620,7 +625,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => else flash(m.text) } const onSelection = (sel: { getSelectedText(): string } | null) => { - const text = sel?.getSelectedText() ?? "" + const text = selectedText(sel?.getSelectedText() ?? "") if (text.trim()) copy(text) } renderer.on("selection", onSelection) @@ -663,7 +668,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => - !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} /> + !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} handle={(h) => (box = h)} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} /> (rev(), share.label())} spend={spend} team={teamWord} /> diff --git a/src/tui/components/prompt.tsx b/src/tui/components/prompt.tsx index 02030fd..d90399d 100644 --- a/src/tui/components/prompt.tsx +++ b/src/tui/components/prompt.tsx @@ -1,14 +1,15 @@ -import type { PasteEvent, TextareaRenderable } from "@opentui/core" +import { RGBA, SyntaxStyle, type PasteEvent, type TextareaRenderable } from "@opentui/core" import { existsSync, mkdirSync } from "node:fs" import { join } from "node:path" import { paths } from "../../config/paths.ts" import { clipboardImage, isImage } from "../../project/image.ts" import { escapeMention } from "../../project/attach.ts" import fuzzysort from "fuzzysort" -import { createSignal, For, Show } from "solid-js" +import { createMemo, createSignal, For, onCleanup, Show } from "solid-js" import type { FileIndex } from "../../project/files.ts" import { useTui } from "../context.ts" import { History } from "../history.ts" +import { imageLabel, pasteLabel, Placeholders, type BoxSnapshot } from "../paste.ts" export interface PaletteEntry { name: string @@ -21,8 +22,28 @@ export interface PaletteEntry { interface Popup { kind: "command" | "file" items: { label: string; detail: string; value: string }[] - /** Where the replaced token starts in the text. */ - from: number + /** How many characters before the cursor the replaced token takes. */ + token: number +} + +/** What the app may ask of the box beyond its text. */ +export interface PromptHandle { + /** The box's text with every paste placeholder replaced by what it stands for. */ + expanded(): string + /** What is selected in the box, in full; undefined when the selection is not in the box. */ + expandedSelection(): string | undefined +} + +/** The offset (in the textarea's columns) at which the text before it is `index` characters long. */ +function offsetAt(area: TextareaRenderable, index: number): number { + let lo = 0 + let hi = area.cursorOffset + while (lo < hi) { + const mid = (lo + hi) >> 1 + if (area.getTextRange(0, mid).length < index) lo = mid + 1 + else hi = mid + } + return lo } /** The input: enter sends; shift+enter / alt+enter / ctrl+j add a line; ↑↓ on the edge lines walk @@ -33,9 +54,11 @@ export function Prompt(p: { busy: () => boolean commands: () => PaletteEntry[] files?: FileIndex - /** false: refused (busy, unknown command) — the text stays in the box. */ - onSubmit: (text: string) => boolean | void + /** false: refused (busy, unknown command) — the text stays in the box. `shown`: what the box + * said, when a paste placeholder made it differ from the text that is sent. */ + onSubmit: (text: string, shown?: string) => boolean | void ref?: (r: TextareaRenderable) => void + handle?: (h: PromptHandle) => void /** The messages waiting to go in: how many, take one out, put it back. */ queue?: { count(): number; take(index: number): string | undefined; putBack(index: number, text: string): void } /** A burst of ↑/↓ that was a mouse wheel: scroll the transcript `lines` up (-1) or down (1). */ @@ -44,9 +67,19 @@ export function Prompt(p: { * itself binds ctrl+b (move left) and would keep the key. */ onBackground?: () => void }) { - const { theme } = useTui() + const { theme, app } = useTui() const c = () => theme().colors const history = new History() + // How a paste placeholder looks: the theme's label colour, on the menu's background. + const style = createMemo((prev?: SyntaxStyle) => { + prev?.destroy() + return SyntaxStyle.fromStyles({ "extmark.paste": { fg: RGBA.fromHex(c().label), bg: RGBA.fromHex(c().menu) } }) + }) + onCleanup(() => style().destroy()) + let marks: Placeholders | undefined + /** The box's text as it is sent: placeholders replaced by what they stand for. */ + const full = () => marks?.expanded() ?? area?.plainText ?? "" + const pasteWhole = () => app.loaded.config.paste === "full" const [popup, setPopup] = createSignal() const [sel, setSel] = createSignal(0) let dismissedAt: string | undefined @@ -58,7 +91,7 @@ export function Prompt(p: { // held down, repeats 25 ms apart or more. A burst scrolls the transcript, and what its first // arrow did to the box is undone (otherwise the wheel walks the prompt history). const BURST_MS = 12 - let burst: { dir: "up" | "down"; at: number; undo?: { text: string; cursor: number; history: ReturnType; pulled: typeof pulled; queue?: () => void } } | undefined + let burst: { dir: "up" | "down"; at: number; undo?: { box: BoxSnapshot; history: ReturnType; pulled: typeof pulled; queue?: () => void } } | undefined /** ↑/↓ on an edge line: the waiting messages first (↑ newest to oldest), then history. */ const walk = (dir: "up" | "down", t: string): string | undefined => { @@ -89,21 +122,21 @@ export function Prompt(p: { const text = area.plainText if (text === dismissedAt) return setPopup(undefined) dismissedAt = undefined - const before = text.slice(0, area.cursorOffset) + const before = area.getTextRange(0, area.cursorOffset) if (/^\/[\w:-]*$/.test(text)) { const q = text.slice(1) const all = p.commands() const hits = q ? fuzzysort.go(q, all, { key: "name", limit: 8 }).map((h) => h.obj) : all.slice(0, 8) setPopup( hits.length - ? { kind: "command", from: 0, items: hits.map((cmd) => ({ label: `/${cmd.name}`, detail: `${cmd.args ? cmd.args + " " : ""}${cmd.description}${cmd.source && cmd.source !== "builtin" ? ` (${cmd.source})` : ""}`, value: cmd.name })) } + ? { kind: "command", token: text.length, items: hits.map((cmd) => ({ label: `/${cmd.name}`, detail: `${cmd.args ? cmd.args + " " : ""}${cmd.description}${cmd.source && cmd.source !== "builtin" ? ` (${cmd.source})` : ""}`, value: cmd.name })) } : undefined, ) } else { const m = p.files ? /(?:^|\s)@([^\s]*)$/.exec(before) : null if (m) { const hits = p.files!.search(m[1]!) - setPopup(hits.length ? { kind: "file", from: before.length - m[1]!.length, items: hits.map((f) => ({ label: f, detail: "", value: f })) } : undefined) + setPopup(hits.length ? { kind: "file", token: m[1]!.length, items: hits.map((f) => ({ label: f, detail: "", value: f })) } : undefined) } else setPopup(undefined) } setSel(0) @@ -122,24 +155,34 @@ export function Prompt(p: { setPopup(undefined) return run } - const text = area.plainText const cursor = area.cursorOffset // Escaped as the expander reads it back: a space or a # in a name. const insert = escapeMention(item.value) + (item.value.endsWith("/") ? "" : " ") - area.setText(text.slice(0, pop.from) + insert + text.slice(cursor)) - area.cursorOffset = pop.from + insert.length + // The token is replaced where it stands (not by setting the whole text, which would drop + // every paste placeholder in the box). + const from = offsetAt(area, area.getTextRange(0, cursor).length - pop.token) + if (from < cursor) area.setSelection(from, cursor) + area.insertText(insert) // A directory keeps the list open, one level down. queueMicrotask(compute) return false } - /** An image on the clipboard becomes an @reference to a saved copy. */ + /** An image file goes into the box as `[Image N]`; what is sent is its @reference. */ + const insertImage = (path: string) => { + if (!area || !marks) return + const ref = `@${escapeMention(path)}` + if (pasteWhole()) return area.insertText(`${ref} `) + marks.insert({ kind: "image", label: imageLabel(marks.nextImage()), content: ref }) + } + + /** An image on the clipboard becomes a saved copy and a placeholder for it. */ const pasteClipboardImage = (): boolean => { const dir = join(paths.state, "clipboard") mkdirSync(dir, { recursive: true }) const saved = clipboardImage(join(dir, `paste-${Date.now()}.png`)) if (!saved || !area) return false - area.insertText(`@${saved} `) + insertImage(saved) return true } @@ -165,7 +208,14 @@ export function Prompt(p: { } const img = imagePath(text) e.preventDefault() - area.insertText(img ? `@${img.includes(" ") ? img.replace(/ /g, "\\ ") : img} ` : text) + if (img) return insertImage(img) + // A long paste is a placeholder (`paste: full` shows it whole); the same paste again, right + // after its placeholder, opens it. + const content = text.replace(/\s+$/, "") + const label = pasteWhole() ? undefined : pasteLabel(content) + if (!label || !marks) return area.insertText(text) + if (marks.expandAtCursor(content)) return + marks.insert({ kind: "text", label, content }) } /** What undoes one ↑/↓ step through the queue: the message now in the box goes back, and the one @@ -178,16 +228,22 @@ export function Prompt(p: { const submit = () => { if (!area) return - const value = area.plainText + // What is sent is the text in full; what the transcript shows is what the box showed. + const value = full() + const shown = area.plainText if (!value.trim()) return + const box = marks?.snapshot() history.add(value) pulled = undefined area.setText("") + marks?.clear() setPopup(undefined) // Cleared first: a command may put text of its own there (/undo puts the prompt back). A - // refusal puts what was typed back, unless something else has been put there. - if (p.onSubmit(value) === false && !area.plainText) { - area.setText(value) + // refusal puts what was typed back — placeholders and all — unless something else has been + // put there. + if (p.onSubmit(value, shown !== value ? shown : undefined) === false && !area.plainText) { + if (box && marks) marks.restore(box) + else area.setText(value) area.gotoBufferEnd() } } @@ -211,13 +267,16 @@ export function Prompt(p: {