diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ccfd8f..9d55d20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,8 +24,8 @@ Harness spec 3.7.0: one display in every client. - **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 + a placeholder and what it stands for — cutting into one removes all of it; 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. @@ -36,8 +36,10 @@ Harness spec 3.7.0: one display in every client. - **Images over SSH.** A terminal cannot hand over the clipboard image of the machine you sit at, so: an image pasted as text — a `data:image/png;base64,…` URL, or the base64 itself — is recognised, saved and shown as `[Image N]`; with `ssh -X` the forwarded X clipboard is read; in - kitty the terminal itself is asked for its clipboard (its clipboard protocol, OSC 5522 — it asks - you once); and when nothing came through, one line names what works: the data URL, `@path` after + kitty, with `kitty_clipboard: true`, the terminal itself is asked for its clipboard (its + clipboard protocol, OSC 5522 — it asks you once). That one is off by default: on a connection + that stalls, part of the image can be lost on the way, and it is then refused with a line — + never saved broken, never typed into the box. And when nothing came through, one line names what works: the data URL, `@path` after copying the file over, or attaching it to the same chat in the web, Desktop or Android app. ### Changed @@ -66,6 +68,9 @@ Harness spec 3.7.0: one display in every client. - **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. +- **An approval card over the link names its tool** (`_meta.lembas.tool`); its title stays the + whole command, or the tool's name. +- **A duration just under a minute** is `1m 00s`, not `60.0s`. - **A refused tool call reaches a plain ACP client** (an editor): it was sent as an update of a call the client had never been told about, which a client drops; it is now announced as a failed call, with its title and the reason. diff --git a/harness/README.md b/harness/README.md index ba3550f..f6c6eb3 100644 --- a/harness/README.md +++ b/harness/README.md @@ -105,6 +105,8 @@ Written ahead of the implementations; the CLI carries it in the same round (`dis situations. `unavailable` is now only *no page of this chat is open* and says where to open it; `texts.no_answer` — a page is open but did not answer; `texts.timeout` — the run passed its `{{seconds}}`. Conformance area **`python`** (the server's). +- **The approval card keeps its own title** (`acp.md` `session/request_permission`): the whole + command, or the tool's name — not the short title — and `_meta.lembas.tool` names the tool. - Conformance area **`display`** (titles, durations, hunk counts, facts, the end line, drawn blocks); `progress` gains the `budget` stop. diff --git a/harness/acp.md b/harness/acp.md index 051b9fd..5fab0c2 100644 --- a/harness/acp.md +++ b/harness/acp.md @@ -258,7 +258,11 @@ named like any TUI command is not a command (the built-in wins in the TUI). An approval card. Params: ACP's `{ sessionId, toolCall: { toolCallId, title, kind, status: "pending", rawInput, content? }, options }` with options `once` (allow_once), `session` (allow_always, absent where "always" is never offered) -and `deny` (reject_once), and `_meta.lembas: { reason, purpose?, always?, patient?, job? }`. `patient`: a +and `deny` (reject_once), and `_meta.lembas: { tool, reason, purpose?, always?, patient?, job? }`. `tool` +(spec 3.7.0): the tool's name — `toolCall.title` here is **the whole command, or the tool's name where +the call has no command**, as before 3.7.0 (a card is read before it is answered; the call's short +title of `display.md` §1 is `tool_call`'s, not the card's), so a client that titles a card by the +command still has the tool to name. `patient`: a person may also answer at the terminal (a shared session), so the client does not time it out. `job` (capability `jobs`): `{ id, agent, description }` when a subagent running as a background job asks, so the card can say which — a background subagent may ask while the session itself is idle. `subagent` (capability `tree`, spec 3.4.0): diff --git a/harness/conformance/display.json b/harness/conformance/display.json index 371a03f..9dc0118 100644 --- a/harness/conformance/display.json +++ b/harness/conformance/display.json @@ -339,6 +339,24 @@ "duration": "59.9s" } }, + { + "about": "What would round to 60.0s is a minute.", + "show": "duration", + "state": "done", + "ms": 59960, + "expect": { + "duration": "1m 00s" + } + }, + { + "about": "The last tenth under a minute.", + "show": "duration", + "state": "done", + "ms": 59949, + "expect": { + "duration": "59.9s" + } + }, { "about": "From a minute: minutes and whole seconds.", "show": "duration", diff --git a/harness/display.md b/harness/display.md index 2b0286c..3fc661a 100644 --- a/harness/display.md +++ b/harness/display.md @@ -35,6 +35,11 @@ directory; a `bash` by its command, not its description; `phone_action` by its ` tool's own name (or the client's label for it — `Bash`, `Search files`; a client's own table) is drawn beside the title and is not part of it. +The short title is for a call **as it is listed**. The approval card (§5) is not titled by it: a +card shows what is asked in full — the whole command, the change — and names the tool +(`acp.md` `session/request_permission`: `toolCall.title` the whole command or the tool's name, +`_meta.lembas.tool` the tool). + A tool the spec marks `block: plan` or `block: hidden` is not drawn as a call at all (§3). ## 2. A call's states @@ -55,7 +60,8 @@ ended, the device went away), is drawn `failed` once that is known — never lef **The duration** of a finished call is the time from its start to its result, as the implementation that ran it measured it, written the one way (`display.duration`): under a minute -in seconds with one decimal (`0.4s`, `8.4s`); from a minute `1m 05s`; from an hour `2h 03m` — +in seconds with one decimal (`0.4s`, `8.4s`) — a time that would round to `60.0s` is a minute, +`1m 00s`; from a minute `1m 05s`; from an hour `2h 03m` — `progress.md`'s elapsed form with tenths under a minute. A duration is not a locale number (§6): it is written with `.` everywhere. A stored call whose duration was not kept shows none. diff --git a/schema/config.schema.json b/schema/config.schema.json index 5ef3b0f..7f0c37d 100644 --- a/schema/config.schema.json +++ b/schema/config.schema.json @@ -68,6 +68,10 @@ "full" ] }, + "kitty_clipboard": { + "description": "true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in.", + "type": "boolean" + }, "icons": { "description": "emoji (default), or plain: one-column symbols for a terminal font that has no emoji.", "type": "string", diff --git a/src/acp/agent.ts b/src/acp/agent.ts index 3e1d2cd..233be91 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -304,7 +304,9 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien sessionId, toolCall: { toolCallId: o.toolCallId ?? crypto.randomUUID(), - title: callTitle(req.args) ?? req.request.command ?? req.tool, + // The card's title is the whole command, or the tool's name: a card is read before it is + // answered. The call's short title (display.md §1) belongs on tool_call, not here. + title: req.request.command ?? req.tool, kind: toolKind(req.tool), status: "pending", rawInput: req.args, @@ -317,6 +319,7 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien ], _meta: { lembas: { + tool: req.tool, reason: req.decision.reason, purpose: req.purpose, always: req.decision.always ?? req.request.always, @@ -1453,7 +1456,6 @@ export class AcpAgent { content: [{ type: "content", content: { type: "text", text: e.result.output.slice(0, 20_000) } }], }) case "tool_denied": - // Refused, not run: `failed` to a plain ACP client, `denied` to one that reads _meta.lembas. // Refused, not run: `failed` to a plain ACP client, `denied` to one that reads _meta.lembas. // A refused call never started, so no tool_call announced it (the approval card, if one // was shown, has an id of its own): this is the call's first and only update, and an diff --git a/src/config/schema.ts b/src/config/schema.ts index 06dd5a1..6567845 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -243,6 +243,7 @@ export const Config = z.strictObject({ 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."), + kitty_clipboard: z.boolean().optional().describe("true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in."), 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 d4621af..4a57e67 100644 --- a/src/config/settings.ts +++ b/src/config/settings.ts @@ -60,6 +60,7 @@ export const SETTINGS: SettingDef[] = [ { 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: "kitty_clipboard", kind: "boolean", agent: false, scopes: USER, fallback: "false", hint: "over SSH in kitty, ctrl+v asks the terminal for the image on its clipboard" }, { 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/duration.ts b/src/duration.ts index a097848..9870030 100644 --- a/src/duration.ts +++ b/src/duration.ts @@ -1,7 +1,9 @@ /** Time as the eye reads it: 8.4s, 1m 05s, 2h 03m. `whole`: no tenths under a minute (8s) — for a * clock that ticks while you watch. */ export function duration(ms: number, whole = false): string { - const s = Math.max(0, ms) / 1000 + let s = Math.max(0, ms) / 1000 + // 59.96 s is a minute, not "60.0s": tenths are only written where they stay under one. + if (!whole && s >= 59.95 && s < 60) s = 60 if (s < 60) return whole ? `${Math.floor(s)}s` : `${s.toFixed(1)}s` const m = Math.floor(s / 60) if (m < 60) return `${m}m ${String(Math.floor(s % 60)).padStart(2, "0")}s` diff --git a/src/project/image.ts b/src/project/image.ts index d3e28bd..5910537 100644 --- a/src/project/image.ts +++ b/src/project/image.ts @@ -59,6 +59,31 @@ export function sniffImage(b: Uint8Array): (typeof CLIPBOARD_TYPES)[number] | un return undefined } +/** Whether these bytes are the whole of an image of this kind, by its own structure: a PNG's + * chunks run exactly to its IEND, a JPEG ends with its end marker, a GIF with its trailer, a + * WebP is as long as its header says. Bytes lost on the way (a transfer cut or missing a piece) + * fail it. */ +export function imageWhole(b: Uint8Array, mime: string): boolean { + const n = b.length + if (mime === "image/png") { + let at = 8 + let last = "" + while (at + 12 <= n) { + const len = ((b[at]! << 24) | (b[at + 1]! << 16) | (b[at + 2]! << 8) | b[at + 3]!) >>> 0 + last = String.fromCharCode(b[at + 4]!, b[at + 5]!, b[at + 6]!, b[at + 7]!) + at += 12 + len + } + return at === n && last === "IEND" + } + if (mime === "image/jpeg") return n >= 4 && b[n - 2] === 0xff && b[n - 1] === 0xd9 + if (mime === "image/gif") return n >= 14 && b[n - 1] === 0x3b + if (mime === "image/webp") { + const size = (b[4]! | (b[5]! << 8) | (b[6]! << 16) | (b[7]! << 24)) >>> 0 + return size + 8 === n || size + 9 === n + } + return false +} + let saved = 0 /** Save pasted image bytes under `dir` (made if missing), named by time and kind. */ export function savePastedImage(dir: string, bytes: Uint8Array, mime: string): string { @@ -70,8 +95,8 @@ export function savePastedImage(dir: string, bytes: Uint8Array, mime: string): s /** Pasted text that is an image: a `data:image/(png|jpeg|webp|gif);base64,…` URL, or bare base64 * that decodes to an image's signature — the way an image gets through a terminal that cannot - * hand over a clipboard image (over SSH). The bytes, a reason it is refused, or undefined when - * the text is not an image at all. */ + * hand over a clipboard image (over SSH). The bytes; a reason it is refused (too large); or + * undefined when the text does not decode to an image — it is then ordinary pasted text. */ export function imageFromText(text: string): { mime: string; bytes: Uint8Array } | { error: string } | undefined { let t = text.trim() if (t.length < 24) return undefined @@ -85,7 +110,9 @@ export function imageFromText(text: string): { mime: string; bytes: Uint8Array } if (Math.floor((t.length * 3) / 4) > MAX_PASTE_BYTES) return { error: `the pasted image is over ${MAX_PASTE_BYTES / 1e6} MB — copy the file over and use @path` } const bytes = new Uint8Array(Buffer.from(t, "base64")) const mime = sniffImage(bytes) - if (!mime) return url ? { error: "the pasted data URL is not a PNG, JPEG, WebP or GIF image" } : undefined + // Not an image after all (a data URL of something else, base64 that only began like one): it + // is text, and is pasted as text. + if (!mime) return undefined return { mime, bytes } } diff --git a/src/session/engine.ts b/src/session/engine.ts index 4599d6b..9789cea 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -28,18 +28,6 @@ import { callTitle } from "./display.ts" import type { Verdict } from "../team/delegation.ts" import { compactAsk, isNote, NO_CHANGING, noteFor, offeredFor, PREFIX_META, summaryOf, today, toldAt, unavailable, type Changing, type Kept, type Now, type Requirement, type Told } from "./prefix.ts" -/** A refused call's arguments and title, for those who draw it: the arguments as the model wrote - * them, when they are an object at all. */ -function deniedTitle(raw: string): { args?: unknown; title?: string } { - try { - const args: unknown = raw.trim() ? JSON.parse(raw) : {} - const title = callTitle(args) - return { args, ...(title ? { title } : {}) } - } catch { - return {} - } -} - export interface EngineOptions { bus: Bus asker: Asker @@ -226,8 +214,17 @@ export class Engine { o.bus.on((e) => { if (e.type === "error") failure = e.message if (e.type !== "done") return - if (this.o.store && this.sessionId) this.o.store.setMeta(this.sessionId, END_META, e.reason === "stop" ? null : { reason: e.reason, ...(e.reason === "error" && failure ? { error: failure } : {}) }) + const said = failure failure = undefined + const id = this.sessionId + if (!this.o.store || !id) return + if (e.reason === "stop") return this.o.store.setMeta(id, END_META, null) + // Written once the turn's last message is in: `at` ties the end to the conversation as it + // stood, so an /undo, a rewind or a compaction that takes the turn away takes its end too + // (and a /redo that brings the turn back brings it back). + queueMicrotask(() => { + if (this.sessionId === id) this.o.store?.setMeta(id, END_META, { reason: e.reason, at: this.messages.length, ...(e.reason === "error" && said ? { error: said } : {}) }) + }) }) this.mode = o.mode this._effort = o.effort @@ -377,11 +374,33 @@ export class Engine { return new ResultContext(this.o.store && sessionId ? this.o.store.results(sessionId) : memoryResults(), () => presentIds(this.messages)) } + /** A refused call's arguments and title, for those who draw it: the arguments as a call that + * runs gets them — the tool found under its former names, `purpose` taken off, parsed by the + * tool's schema (its defaults and conversions) — and as the model wrote them only when they do + * not parse. */ + private deniedTitle(call: ToolCallPart, toolMap: Map): { args?: unknown; title?: string } { + let args: unknown + try { + const written: unknown = call.args.trim() ? JSON.parse(call.args) : {} + const resolved = resolveCall(call.name, written) + const tool = toolMap.get(resolved.name) ?? toolMap.get(call.name) + const own = tool ? splitPurpose(tool, resolved.raw).args : resolved.raw + const parsed = tool?.schema.safeParse(own) + args = parsed?.success ? parsed.data : own + } catch { + return {} + } + const title = callTitle(args) + return { args, ...(title ? { title } : {}) } + } + /** How this session's last turn ended, when it did not finish — from the store. */ storedEnd(): { reason: string; error?: string } | undefined { if (!this.o.store || !this.sessionId) return undefined - const e = this.o.store.meta<{ reason?: unknown; error?: unknown } | null>(this.sessionId, END_META) - return e && typeof e.reason === "string" ? { reason: e.reason, ...(typeof e.error === "string" ? { error: e.error } : {}) } : undefined + const e = this.o.store.meta<{ reason?: unknown; error?: unknown; at?: unknown } | null>(this.sessionId, END_META) + // Only while the conversation still ends where that turn ended. + if (!e || typeof e.reason !== "string" || e.at !== this.messages.length) return undefined + return { reason: e.reason, ...(typeof e.error === "string" ? { error: e.error } : {}) } } /** The plan the store holds for this session, if any. */ @@ -874,7 +893,7 @@ export class Engine { const decided = await this.decide(call, toolMap, cut) if ("result" in decided) { results.set(call.id, decided.result) - if (decided.denied) bus.emit({ type: "tool_denied", id: call.id, name: call.name, reason: decided.result.output, ...deniedTitle(call.args) }) + if (decided.denied) bus.emit({ type: "tool_denied", id: call.id, name: call.name, reason: decided.result.output, ...this.deniedTitle(call, toolMap) }) } else { runnable.push({ call, ...decided }) argsOf.set(call.id, decided.args) diff --git a/src/tui/app.tsx b/src/tui/app.tsx index 89b24f7..a0b2b63 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -324,11 +324,14 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => * `attachFrom`: where @references are read from, when not all of `text` is the user's — an MCP * server's prompt or a skill must not attach ~/.ssh/… by naming it. `given`: a prompt from the web * UI, its attachments read already and its turn id its own. */ - const send = (text: string, shown = text, attachFrom = text, given?: Pick): Promise => { + const send = (text: string, shown = text, attachFrom = text, given?: Pick, drawn = shown): Promise => { voice.stopSpeaking() const atts = given ? [] : attachmentsFor(attachFrom, app.engine.o.toolCtx, app.engine.model.spec.vision === true) for (const a of atts) files.used(a.path) - view.user(shown) + // `drawn`: what this transcript shows — the box as it looked, a paste placeholder in place of + // its text. Only here: the session's title, the `prompt` event and everything a server + // mirrors get `shown`, which holds the words themselves. + view.user(drawn) if (atts.length) view.info(`attached ${atts.map((a) => (a.image ? `${a.path} (image)` : a.text.includes("not attached") ? `${a.path} (not attached: ${/not attached: ([^)]*)/.exec(a.text)?.[1]})` : a.path)).join(", ")}`) if (given?.attachments.length) view.info(`attached ${given.attachments.map((a) => a.name).join(", ")}`) scroll?.scrollTo(scroll.scrollHeight) @@ -479,8 +482,9 @@ 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) - // `shown`: the box as it looked, paste placeholders in place of what they stand for. - void send(t, shown?.trim() || t) + // `shown`: the box as it looked, paste placeholders in place of what they stand for — for + // this transcript alone. + void send(t, t, t, undefined, shown?.trim() || t) } /** The messages waiting to go in, for ↑ in the box. */ diff --git a/src/tui/components/prompt.tsx b/src/tui/components/prompt.tsx index 7fd0462..f2158ea 100644 --- a/src/tui/components/prompt.tsx +++ b/src/tui/components/prompt.tsx @@ -2,7 +2,7 @@ import { RGBA, SyntaxStyle, type PasteEvent, type TextareaRenderable } from "@op import { existsSync } from "node:fs" import { join } from "node:path" import { paths } from "../../config/paths.ts" -import { cleanPastedImages, clipboardImage, CLIPBOARD_TYPES, imageFromText, isImage, savePastedImage, type ClipboardImage } from "../../project/image.ts" +import { cleanPastedImages, clipboardImage, CLIPBOARD_TYPES, imageFromText, imageWhole, isImage, savePastedImage, sniffImage, type ClipboardImage } from "../../project/image.ts" import { kittyClipboardLikely, kittyReadImage, type KittyRead, type OscTerminal } from "../kitty-clipboard.ts" import { escapeMention } from "../../project/attach.ts" import fuzzysort from "fuzzysort" @@ -201,6 +201,17 @@ export function Prompt(p: { * `ssh -X` forwards, and a terminal that hands its clipboard over itself (kitty). When neither * does, one line says what does. */ let reading = false + // While the terminal sends its clipboard, nothing typed or pasted reaches the box: what would + // arrive is a reply that came apart on the way (kitty-clipboard.ts), and it is counted. + let held: number | undefined + const holdInput = () => { + held = 0 + return () => { + const n = held ?? 0 + held = undefined + return n + } + } const pasteClipboardImage = async () => { if (reading || !area) return reading = true @@ -209,11 +220,16 @@ export function Prompt(p: { let r: ClipboardImage | KittyRead = { status: "unsupported" } if (!remote) r = await clipboardImage() else if (process.env.DISPLAY) r = await clipboardImage({ env: { DISPLAY: process.env.DISPLAY } }) - if (r.status !== "read" && remote && p.terminal && kittyClipboardLikely()) { + // The terminal's own clipboard (kitty), only where it was turned on: see kitty-clipboard.ts. + if (r.status !== "read" && remote && p.terminal && app.loaded.config.kitty_clipboard === true && kittyClipboardLikely()) { p.note?.("asking the terminal for the image on its clipboard…") - r = await kittyReadImage(p.terminal, { types: CLIPBOARD_TYPES, password: CLIPBOARD_PASSWORD, name: "LLeMbas CLI" }) + r = await kittyReadImage( + { ...p.terminal, holdInput }, + { types: CLIPBOARD_TYPES, password: CLIPBOARD_PASSWORD, name: "LLeMbas CLI", whole: (bytes) => { const mime = sniffImage(bytes); return mime && imageWhole(bytes, mime) ? mime : undefined } }, + ) } if (r.status === "read") return insertImage(savePastedImage(CLIP_DIR, r.bytes, r.mime)) + if (r.status === "garbled") return p.note?.("the image did not arrive whole from the terminal (the connection stalled) — nothing was pasted; try again, or paste it as a data URL or use @path", true) if (r.status === "too-large") return p.note?.("the image on the clipboard is too large to paste — save it and use @path", true) if (r.status === "denied") return p.note?.("the terminal did not allow reading its clipboard", true) p.note?.(remote ? REMOTE_IMAGE_HINT : r.status === "unsupported" ? "no clipboard to read an image from here (install wl-clipboard or xclip), or use @path" : "no image on the clipboard") @@ -237,13 +253,19 @@ export function Prompt(p: { const onPaste = (e: PasteEvent) => { if (!area) return + if (held !== undefined) { + held++ + return e.preventDefault() + } const text = new TextDecoder().decode(e.bytes).replace(/\r\n/g, "\n").replace(/\r/g, "\n") - // Some terminals hand over an image-only clipboard as an empty bracketed paste. - if (!text.trim()) { + // Some terminals hand over an image-only clipboard as an empty bracketed paste. (A paste of + // white space — a newline — is a paste of white space.) + if (!text) { e.preventDefault() void pasteClipboardImage() return } + if (!text.trim()) return // An image pasted as text — a data URL, or base64 of one: the way through a terminal that // cannot hand over a clipboard image (over SSH). const data = imageFromText(text) @@ -275,6 +297,7 @@ export function Prompt(p: { const submit = () => { if (!area) return // What is sent is the text in full; what the transcript shows is what the box showed. + marks?.repair() const value = full() const shown = area.plainText if (!value.trim()) return @@ -334,12 +357,20 @@ export function Prompt(p: { { name: "return", meta: true, action: "newline" }, { name: "j", ctrl: true, action: "newline" }, ]} - onContentChange={compute} + onContentChange={() => { + // After this change has settled: a placeholder that lost part of its label goes whole. + queueMicrotask(() => marks?.repair()) + compute() + }} onCursorChange={compute} onSubmit={submit} onPaste={onPaste} onKeyDown={(e) => { if (!area) return + if (held !== undefined) { + held++ + return e.preventDefault() + } if (e.ctrl && e.name === "v" && !e.shift && !e.meta) { void pasteClipboardImage() return e.preventDefault() diff --git a/src/tui/kitty-clipboard.ts b/src/tui/kitty-clipboard.ts index 99c4fc0..7f9527d 100644 --- a/src/tui/kitty-clipboard.ts +++ b/src/tui/kitty-clipboard.ts @@ -11,6 +11,16 @@ // // The request "." lists the kinds on the clipboard and needs no permission; the read itself the // terminal asks the person about (once, when it remembers the password sent with it). +// +// What can go wrong on the way, and what is done about it. OpenTUI's input parser gives up on an +// escape sequence that stops arriving for about 20 ms and hands what it has on as typed keys. A +// reply that stalls inside a packet — an SSH connection does that — therefore loses that packet, +// and its base64 would be typed into the prompt box. So while a read is under way the box's input +// is held (`holdInput`): nothing of a reply reaches it, and any input that turned up during the +// read means a packet was lost — the read fails, said in a line, and nothing is saved. What +// arrives is also checked as an image by its own structure (the caller's `whole`). A read can +// therefore fail on a slow connection, but never saves a broken image or types into the box; +// because it can fail, the whole path is off unless `kitty_clipboard: true` is set. const OSC = "\x1b]5522;" const ST = "\x1b\\" @@ -19,6 +29,9 @@ export interface OscTerminal { write(data: string): void /** Every OSC sequence the terminal sends, whole. Returns what unsubscribes. */ subscribeOsc(handler: (sequence: string) => void): () => void + /** Hold the prompt box's input until the function returned is called; that call says how many + * inputs (keys, pastes) arrived meanwhile and were dropped. */ + holdInput?(): () => number } const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64") @@ -44,7 +57,8 @@ export function kittyClipboardLikely(env: Record = p return !!env.KITTY_WINDOW_ID || /kitty/i.test(env.TERM ?? "") } -export type KittyRead = { status: "read"; mime: string; bytes: Uint8Array } | { status: "unsupported" | "empty" | "denied" | "busy" | "too-large" | "timed-out" } +/** `garbled`: part of the reply was lost on the way, or what arrived is not a whole image. */ +export type KittyRead = { status: "read"; mime: string; bytes: Uint8Array } | { status: "unsupported" | "empty" | "denied" | "busy" | "too-large" | "timed-out" | "garbled" } interface ReadOptions { types: readonly string[] @@ -56,6 +70,9 @@ interface ReadOptions { /** Sent with the read so the terminal can remember the person's answer for this program. */ password?: string name?: string + /** The kind of image these bytes are when they are a whole one (project/image.ts `sniffImage` + * and `imageWhole`); undefined when they are not. What is read is believed only by this. */ + whole?: (bytes: Uint8Array) => string | undefined } /** One request and its replies: resolves with the data packets by kind, or how it failed. */ @@ -120,6 +137,18 @@ let serial = 0 * permission needed, and a terminal that does not answer does not speak the protocol), then the * first of `types` that is there is read. */ export async function kittyReadImage(term: OscTerminal, o: ReadOptions): Promise { + const release = term.holdInput?.() + let r: KittyRead + try { + r = await read(term, o) + } finally { + // Input during the read is a reply that came apart: whatever was put together is not trusted. + if ((release?.() ?? 0) > 0) return { status: "garbled" } + } + return r +} + +async function read(term: OscTerminal, o: ReadOptions): Promise { const maxBytes = o.maxBytes ?? 20_000_000 const id = `lembas${process.pid}.${++serial}` const listed = await request(term, "", ".", id, o.listTimeoutMs ?? 1500, 65_536) @@ -134,9 +163,13 @@ export async function kittyReadImage(term: OscTerminal, o: ReadOptions): Promise const type = o.types.find((t) => kinds.has(t)) if (!type) return { status: "empty" } const auth = o.password && o.name ? `:pw=${b64(o.password)}:name=${b64(o.name)}` : "" - const read = await request(term, auth, type, `${id}r`, o.readTimeoutMs ?? 60_000, maxBytes) - if (read.status !== "done") return { status: read.status } - const chunks = read.data.get(type) ?? [...read.data.values()][0] + const got = await request(term, auth, type, `${id}r`, o.readTimeoutMs ?? 30_000, maxBytes) + if (got.status !== "done") return { status: got.status } + const chunks = got.data.get(type) ?? [...got.data.values()][0] if (!chunks?.length) return { status: "empty" } - return { status: "read", mime: type, bytes: join(chunks) } + const bytes = join(chunks) + if (!o.whole) return { status: "read", mime: type, bytes } + // By its bytes, not by what it was asked for or called. + const mime = o.whole(bytes) + return mime ? { status: "read", mime, bytes } : { status: "garbled" } } diff --git a/src/tui/paste.ts b/src/tui/paste.ts index 671b71b..e0f9341 100644 --- a/src/tui/paste.ts +++ b/src/tui/paste.ts @@ -46,13 +46,14 @@ export interface BoxSnapshot { marks: { start: number; end: number; item: Placeholder }[] } -type Area = Pick +type Area = Pick /** Beyond any text a prompt box holds: `getTextRange` clamps it to the end. */ const END = 0x3fffffff export class Placeholders { private items = new Map() + private repairing = false private typeId: number constructor( @@ -79,12 +80,43 @@ export class Placeholders { return this.items.size > 0 && this.live().length > 0 } - /** Put a placeholder at the cursor, with a space after it. */ + /** Put a placeholder at the cursor — in place of what is selected — with a space after it. */ insert(item: Placeholder) { - const start = this.area.cursorOffset this.area.insertText(`${item.label} `) - // A label is ASCII: its width is its length. - this.mark(start, start + item.label.length, item) + // Where it went is read off the cursor after the insert, not before it: with a selection + // the text goes in at the selection's start, wherever the cursor was. A label is ASCII, so + // its width is its length. + const end = this.area.cursorOffset - 1 + this.mark(end - item.label.length, end, item) + } + + /** A placeholder is one thing: when part of its label has been deleted (a selection that cut + * into it, a kill to the end of the line), the rest of the label goes too — never a stump of + * it left as text, with what it stood for silently gone. Returns how many were removed. */ + repair(): number { + if (this.repairing || !this.items.size) return 0 + this.repairing = true + let removed = 0 + try { + // From the end, so removing one does not move those before it. + const broken = this.area.extmarks + .getAllForTypeId(this.typeId) + .filter((m) => this.items.has(m.id) && this.area.getTextRange(m.start, m.end) !== this.items.get(m.id)!.label) + .sort((a, b) => b.start - a.start) + for (const m of broken) { + const cursor = this.area.cursorOffset + this.area.extmarks.delete(m.id) + if (m.end > m.start) { + this.area.setSelection(m.start, m.end) + this.area.deleteSelection() + this.area.cursorOffset = cursor <= m.start ? cursor : Math.max(m.start, cursor - (m.end - m.start)) + } + removed++ + } + } finally { + this.repairing = false + } + return removed } private mark(start: number, end: number, item: Placeholder) { @@ -122,12 +154,14 @@ export class Placeholders { return this.expandedRange(Math.min(sel.start, sel.end), Math.max(sel.start, sel.end)) } - /** A placeholder that ends at the cursor (or one space before it) and stands for exactly - * `content` is replaced by the content itself — pasting the same thing again right after its - * placeholder shows it whole. */ + /** The one gesture that opens a placeholder: pasting the same text again with the cursor where + * the first paste left it — directly after the placeholder, or after the one space that was + * inserted with it — and nothing selected. The placeholder (and that space) becomes the text + * itself. Anywhere else, and after anything typed in between, the same paste is a second copy. */ expandAtCursor(content: string): boolean { + if (this.area.hasSelection()) return false const cursor = this.area.cursorOffset - const m = this.live().find((x) => x.item.kind === "text" && x.item.content === content && (x.end === cursor || x.end + 1 === cursor)) + const m = this.live().find((x) => x.item.kind === "text" && x.item.content === content && (x.end === cursor || (x.end + 1 === cursor && this.area.getTextRange(x.end, cursor) === " "))) if (!m) return false for (const e of this.area.extmarks.getAllForTypeId(this.typeId)) if (e.start === m.start && e.end === m.end) this.area.extmarks.delete(e.id) this.area.setSelection(m.start, cursor) diff --git a/src/tui/state.ts b/src/tui/state.ts index ea070d9..a50df1f 100644 --- a/src/tui/state.ts +++ b/src/tui/state.ts @@ -43,6 +43,8 @@ export type Item = facts?: string[] /** A failed call's error, or why a call was denied: its first line. */ note?: string + /** A `!` command the person ran themselves: not a call of the turn. */ + own?: boolean ms?: number output?: string diff?: string @@ -361,7 +363,8 @@ export function createView(bus: Bus) { s.preparing = undefined s.progress = undefined // A call still running when the turn ended never got its result: failed, not spinning. - for (const it of s.items) if (it.kind === "tool" && it.status === "running" && !it.jobId) it.status = "error" + // (Not the person's own `!command`, which is no part of the turn and runs on.) + for (const it of s.items) if (it.kind === "tool" && it.status === "running" && !it.jobId && !it.own) it.status = "error" const end = endItem(e.reason, failure) if (end) s.items.push(end) }), @@ -463,7 +466,7 @@ export function createView(bus: Bus) { /** A `!` command the user ran: shown like a tool call, without touching the phase. */ shellStart(command: string): string { const id = nextId() - set(produce((s) => void s.items.push({ kind: "tool", id, name: "bash", args: { command }, status: "running", title: `! ${command.split("\n")[0]}` }))) + set(produce((s) => void s.items.push({ kind: "tool", id, name: "bash", args: { command }, status: "running", title: `! ${command.split("\n")[0]}`, own: true }))) return id }, shellEnd(id: string, r: { output: string; title?: string; isError?: boolean; meta?: Record }, ms: number) { @@ -507,6 +510,7 @@ export function createView(bus: Bus) { load(messages: Message[], ended?: { reason: string; error?: string }) { const items: Item[] = [] const tools = new Map>() + const answered = new Set() for (const m of messages) { if (m.role === "user" && m.parts[0]?.type === "text" && m.parts[0].text === CONTINUE_PROMPT) items.push({ kind: "user", id: nextId(), text: "↻ continue" }) @@ -539,6 +543,7 @@ export function createView(bus: Bus) { } } else { const t = tools.get(m.callId) + answered.add(m.callId) if (t) { t.status = m.isError ? "error" : "done" t.output = m.content @@ -547,6 +552,9 @@ export function createView(bus: Bus) { } } } + // A stored call whose result never came (the turn was stopped, the process ended) failed: + // it is not drawn as done (display.md §2). + for (const [id, t] of tools) if (!answered.has(id)) t.status = "error" const end = ended ? endItem(ended.reason, ended.error) : undefined if (end) items.push(end) set({ items, usage: undefined, used: undefined }) diff --git a/tests/clipboard-image.test.ts b/tests/clipboard-image.test.ts index 247a5c0..879188c 100644 --- a/tests/clipboard-image.test.ts +++ b/tests/clipboard-image.test.ts @@ -5,7 +5,7 @@ import { expect, test } from "bun:test" import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" -import { cleanPastedImages, clipboardCommands, clipboardImage, imageFromText, MAX_PASTE_BYTES, savePastedImage, sniffImage } from "../src/project/image.ts" +import { cleanPastedImages, clipboardCommands, clipboardImage, imageFromText, imageWhole, MAX_PASTE_BYTES, savePastedImage, sniffImage } from "../src/project/image.ts" import { kittyClipboardLikely, kittyReadImage, parse5522, type OscTerminal } from "../src/tui/kitty-clipboard.ts" const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64") @@ -36,7 +36,7 @@ test("pasted text that is an image: a data URL, base64 with line breaks, bare ba expect(imageFromText(WEBP.toString("base64"))).toMatchObject({ mime: "image/webp" }) }) -test("pasted text that is not an image stays text; a data URL that is not one is refused in words", () => { +test("pasted text that is not an image stays text — a data URL of something else too; only one too large is refused", () => { expect(imageFromText("hello there, this is a perfectly ordinary sentence")).toBeUndefined() // Starts as a PNG would, but is prose. expect(imageFromText("iVBORw0KGgo is how a PNG starts in base64, did you know?")).toBeUndefined() @@ -44,7 +44,7 @@ test("pasted text that is not an image stays text; a data URL that is not one is expect(imageFromText(Buffer.from("just some bytes, nothing more than that").toString("base64"))).toBeUndefined() expect(imageFromText("data:text/plain;base64,aGVsbG8gd29ybGQsIGhlbGxvIHdvcmxk")).toBeUndefined() expect(imageFromText(`data:image/svg+xml;base64,${Buffer.from("".repeat(8)).toString("base64")}`)).toBeUndefined() - expect(imageFromText(`data:image/png;base64,${Buffer.from("not an image at all, only text").toString("base64")}`)).toEqual({ error: "the pasted data URL is not a PNG, JPEG, WebP or GIF image" }) + expect(imageFromText(`data:image/png;base64,${Buffer.from("not an image at all, only text").toString("base64")}`)).toBeUndefined() const huge = `data:image/png;base64,${"A".repeat(Math.ceil((MAX_PASTE_BYTES * 4) / 3) + 8)}` expect(imageFromText(huge)).toMatchObject({ error: expect.stringContaining("over 20 MB") }) }) @@ -196,6 +196,46 @@ test("kitty's clipboard protocol: a terminal that says nothing does not speak it expect(await kittyReadImage(other, { types: TYPES, listTimeoutMs: 80 })).toEqual({ status: "unsupported" }) }) +test("an image is whole by its own structure: a piece missing anywhere fails it", () => { + expect(imageWhole(PNG, "image/png")).toBe(true) + expect(imageWhole(PNG.subarray(0, PNG.length - 5), "image/png")).toBe(false) + // A piece lost from the middle: the chunks no longer run to IEND. + expect(imageWhole(Buffer.concat([PNG.subarray(0, 40), PNG.subarray(44)]), "image/png")).toBe(false) + expect(imageWhole(Buffer.concat([PNG, Buffer.from("x")]), "image/png")).toBe(false) + const jpeg = Buffer.concat([JPEG, Buffer.from([0xff, 0xd9])]) + expect(imageWhole(jpeg, "image/jpeg")).toBe(true) + expect(imageWhole(JPEG, "image/jpeg")).toBe(false) + expect(imageWhole(Buffer.concat([GIF, Buffer.from([0x3b])]), "image/gif")).toBe(true) + expect(imageWhole(GIF, "image/gif")).toBe(false) + const webp = Buffer.concat([Buffer.from("RIFF"), Buffer.from([16, 0, 0, 0]), Buffer.from("WEBPVP8 "), Buffer.alloc(8)]) + expect(imageWhole(webp, "image/webp")).toBe(true) + expect(imageWhole(webp.subarray(0, 20), "image/webp")).toBe(false) + expect(imageWhole(PNG, "text/plain")).toBe(false) +}) + +test("kitty's clipboard protocol: what arrives is believed by its bytes; input during the read means a lost packet", async () => { + const whole = (bytes: Uint8Array) => { + const mime = sniffImage(bytes) + return mime && imageWhole(bytes, mime) ? mime : undefined + } + // Asked for as PNG, a JPEG in fact: saved as what it is. + const jpeg = Buffer.concat([JPEG, Buffer.from([0xff, 0xd9])]) + expect(await kittyReadImage(kitty({ "image/png": jpeg }).term, { types: TYPES, whole })).toMatchObject({ status: "read", mime: "image/jpeg" }) + // Not an image at all, and an image missing its end: refused, never handed on. + expect(await kittyReadImage(kitty({ "image/png": Buffer.from("#!/bin/sh\necho not a picture\n") }).term, { types: TYPES, whole })).toEqual({ status: "garbled" }) + expect(await kittyReadImage(kitty({ "image/png": PNG.subarray(0, PNG.length - 6) }).term, { types: TYPES, whole })).toEqual({ status: "garbled" }) + // The box's input is held for the whole read and let go after it; keys that arrived meanwhile + // are a reply that came apart, so even a read that looks complete is not believed. + let holds = 0 + let released = 0 + const k = kitty({ "image/png": PNG }) + const quiet = { ...k.term, holdInput: () => (holds++, () => (released++, 0)) } + expect(await kittyReadImage(quiet, { types: TYPES, whole })).toMatchObject({ status: "read", mime: "image/png" }) + expect([holds, released]).toEqual([1, 1]) + const leaky = { ...kitty({ "image/png": PNG }).term, holdInput: () => () => 37 } + expect(await kittyReadImage(leaky, { types: TYPES, whole })).toEqual({ status: "garbled" }) +}) + test("which terminals are asked: kitty, also through ssh; never inside a multiplexer", () => { expect(kittyClipboardLikely({ TERM: "xterm-kitty" })).toBe(true) expect(kittyClipboardLikely({ TERM: "xterm-256color", KITTY_WINDOW_ID: "3" })).toBe(true) diff --git a/tests/display.test.ts b/tests/display.test.ts index 40f2443..148ff89 100644 --- a/tests/display.test.ts +++ b/tests/display.test.ts @@ -93,9 +93,14 @@ test("what a finished call adds after its title", () => { expect(resultFacts("tool", undefined, {})).toEqual([]) }) -test("over the link an approval's title is the call's title; how a turn ended, as the spec's progress", () => { +test("over the link an approval card keeps the whole command as its title and names the tool; how a turn ended, as the spec's progress", () => { const p = permissionParams("s1", { tool: "bash", args: { command: "rm -rf build\necho done", description: "Clean" }, request: { command: "rm -rf build\necho done", patterns: [] }, decision: { reason: "asks", always: [] } } as never) - expect(p.toolCall.title).toBe("rm -rf build") + // A card is read before it is answered: the whole command, not the call's short title. + expect(p.toolCall.title).toBe("rm -rf build\necho done") + expect(p._meta.lembas.tool).toBe("bash") + // No command: the tool's name, as before — and the name is in _meta.lembas either way. + const q = permissionParams("s1", { tool: "edit", args: { path: "a.txt", old: "a", new: "b" }, request: { patterns: ["a.txt"] }, decision: { reason: "asks", always: [] } } as never) + expect([q.toolCall.title, q._meta.lembas.tool]).toEqual(["edit", "edit"]) expect(endOf("stop")).toBeUndefined() expect(endOf("cancelled")).toEqual({ phase: "stopped", reason: "person" }) expect(endOf("steps")).toEqual({ phase: "stopped", reason: "steps" }) diff --git a/tests/tui/display.test.tsx b/tests/tui/display.test.tsx index 29abd7e..625db58 100644 --- a/tests/tui/display.test.tsx +++ b/tests/tui/display.test.tsx @@ -77,3 +77,75 @@ test("a session shown again from the store says how its last reply ended", async await t.settle() expect(t.frame()).toContain("■ Stopped: by you") }) + +// ---- found in review ---- + +test("the stored end belongs to its turn: /undo takes it away; a reply that finished is never drawn stopped", async () => { + t = await tui( + [{ chunks: [delta({ content: "Fine." }), usage(100, 5)] }, { chunks: [delta({ content: "Half" }), delta({ content: " more" }), delta({ content: " more" }), delta({ content: " more" })], gapMs: 400 }], + undefined, + "titles: prompt\n", // no second request for a title + { store: true }, + ) + await t.input.typeText("one") + t.input.pressEnter() + expect(await t.until("Fine.")).toBe(true) + await t.input.typeText("two") + t.input.pressEnter() + expect(await t.until("Half")).toBe(true) + t.input.pressEscape() + expect(await t.until("■ Stopped: by you")).toBe(true) + await t.settle() + expect(t.app.engine.storedEnd()).toEqual({ reason: "cancelled" }) + await t.input.typeText("/undo") + t.input.pressEnter() + await t.settle(300) + // The stopped turn is gone from the conversation: so is how it ended. + expect(t.app.engine.storedEnd()).toBeUndefined() + const id = t.app.engine.sessionId! + t.view.load(t.app.resume(id), t.app.engine.storedEnd()) + await t.settle() + expect(t.frame()).toContain("Fine.") + expect(t.frame()).not.toContain("Stopped") +}) + +test("a call whose result never came is drawn failed when the session is shown again; the person's own !command is not the turn's", async () => { + t = await tui([{ chunks: [delta({ content: "Slow" }), delta({ content: "ly" }), delta({ content: " said." }), usage(100, 5)], gapMs: 300 }]) + // A stored conversation that ends in a call with no result (the process went away mid-call). + t.view.load([ + { role: "user", parts: [{ type: "text", text: "run it" }] }, + { role: "assistant", parts: [{ type: "tool_call", id: "c1", name: "bash", args: '{"command":"make all"}' }, { type: "tool_call", id: "c2", name: "read", args: '{"path":"a.txt"}' }] }, + { role: "tool", callId: "c2", content: "1: hello", isError: false }, + ] as never) + await t.settle() + const items = t.view.state.items.filter((i) => i.kind === "tool") as { id: string; status: string; title?: string }[] + expect(items.map((i) => [i.id, i.status, i.title])).toEqual([ + ["c1", "error", "make all"], + ["c2", "done", "a.txt"], + ]) + expect(t.frame()).toMatch(/bash make all.*✗/) + // A `!` command still running when a turn ends stays running: it was never part of the turn. + const own = t.view.shellStart("sleep 30") + await t.input.typeText("go") + t.input.pressEnter() + expect(await t.until("ly said.")).toBe(true) + await t.settle() + const mine = t.view.state.items.find((i) => i.kind === "tool" && i.id === own) as { status: string } + expect(mine.status).toBe("running") +}) + +test("a refused call is titled from its arguments as a call that runs gets them, not the model's raw JSON", async () => { + t = await tui( + [{ chunks: [toolCall(0, "c1", "bash", '{"command":"git push origin main","purpose":"Publish the branch"}')] }, { chunks: [delta({ content: "Not pushed." }), usage(100, 5)] }], + undefined, + "mode: auto\npermission:\n bash:\n 'git push *': deny\n", + ) + const denied: { args?: unknown; title?: string }[] = [] + t.app.bus.on((e) => void (e.type === "tool_denied" && denied.push(e))) + await t.input.typeText("push") + t.input.pressEnter() + expect(await t.until("Not pushed.")).toBe(true) + expect(denied[0]!.title).toBe("git push origin main") + // `purpose` is the harness's own argument, taken off before the tool sees the call. + expect(denied[0]!.args).toEqual({ command: "git push origin main" }) +}) diff --git a/tests/tui/paste.test.tsx b/tests/tui/paste.test.tsx index 1564110..131b81f 100644 --- a/tests/tui/paste.test.tsx +++ b/tests/tui/paste.test.tsx @@ -2,7 +2,7 @@ // are shown as a placeholder and sent in full. import { afterEach, expect, test } from "bun:test" import { TextareaRenderable } from "@opentui/core" -import { readFileSync, writeFileSync } from "node:fs" +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs" import { join } from "node:path" import { paths } from "../../src/config/paths.ts" import { nextImageNumber, pasteLabel } from "../../src/tui/paste.ts" @@ -238,22 +238,29 @@ async function withEnv(vars: Record, fn: () => Promi } const NOT_REMOTE = { SSH_CONNECTION: undefined, SSH_TTY: undefined, SSH_CLIENT: undefined } -test("an image pasted as a data URL is saved and shown as [Image 1]; a broken one is said, not pasted", async () => { +test("an image pasted as a data URL is saved and shown as [Image 1]; a data URL that is no image is pasted as the text it is", async () => { t = await tui([{ chunks: [delta({ content: "Seen." }), usage(100, 5)] }]) const a = box(t.setup.renderer.root) await t.input.typeText("what is this ") await t.input.pasteBracketedText(`data:image/png;base64,${PNG_B64}`) await t.settle() expect(a.plainText).toBe("what is this [Image 1] ") - await t.input.pasteBracketedText(`data:image/png;base64,${Buffer.from("this is certainly not a picture").toString("base64")}`) + const notOne = `data:image/png;base64,${Buffer.from("this is certainly not a picture").toString("base64")}` + await t.input.pasteBracketedText(notOne) await t.settle() - expect(a.plainText).toBe("what is this [Image 1] ") - expect(t.frame()).toContain("not a PNG, JPEG, WebP or GIF image") + expect(a.plainText).toBe(`what is this [Image 1] ${notOne}`) + // A long one gets the placeholder any long text gets, and is sent as its text. + const long = `data:image/png;base64,${Buffer.from("not a picture either, ".repeat(12)).toString("base64")}` + a.insertText(" ") + await t.input.pasteBracketedText(long) + await t.settle() + expect(a.plainText).toBe(`what is this [Image 1] ${notOne} [Pasted text ${long.length} chars] `) t.input.pressEnter() expect(await t.until("Seen.")).toBe(true) // Sent as the @path of the copy kept under the state directory. const m = /@(\S+clipboard\/paste-[\w-]+\.png)/.exec(JSON.parse(sent()) as string) expect(m).not.toBeNull() + expect(JSON.parse(sent()) as string).toContain(long) expect(readFileSync(m![1]!).toString("base64")).toBe(PNG_B64) expect(m![1]!.startsWith(join(paths.state, "clipboard"))).toBe(true) }) @@ -282,7 +289,7 @@ test("ctrl+v with no image: said in a word, the box stays usable; over SSH one l test("over SSH in kitty: ctrl+v asks the terminal for its clipboard, and the image arrives as [Image 1]", async () => { await withEnv({ SSH_CONNECTION: "192.0.2.1 50000 192.0.2.2 22", DISPLAY: undefined, WAYLAND_DISPLAY: undefined, TERM: "xterm-kitty", TMUX: undefined, STY: undefined, ZELLIJ: undefined }, async () => { - t = await tui([]) + t = await tui([], undefined, "kitty_clipboard: true\n") const a = box(t.setup.renderer.root) const r = t.setup.renderer as any const b64 = (s: string) => Buffer.from(s).toString("base64") @@ -329,3 +336,171 @@ test("what is dictated is added after a placeholder, which still stands for its void stt.stop(true) } }) + +// ---- found in review ---- + +test("a paste over a selection: the placeholder goes where the text went, and still stands for it — text and image", async () => { + t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }, { chunks: [delta({ content: "ok2" }), usage(100, 5)] }]) + const a = box(t.setup.renderer.root) + // Shift+Right from the start: the cursor ends up after the selection, the text goes in before it. + await t.input.typeText("hello world") + a.cursorOffset = 0 + for (let i = 0; i < 5; i++) t.input.pressArrow("right", { shift: true }) + await t.settle() + expect(a.hasSelection()).toBe(true) + await t.input.pasteBracketedText(LONG) + await t.settle() + expect(a.plainText).toContain("[Pasted text 4 lines] ") + t.input.pressEnter() + expect(await t.until("ok")).toBe(true) + expect(sent()).toContain("first line\\nsecond line\\nthird line\\nfourth line") + expect(sent()).not.toContain("[Pasted text") + // A mouse drag over the box, then an image pasted in its place. + const png = join(t.cwd, "pic.png") + writeFileSync(png, Buffer.from(PNG_B64, "base64")) + await t.input.typeText("hello world") + await t.settle() + const lines = t.frame().split("\n") + const y = lines.findIndex((l) => l.includes("❯ hello world")) + const x = lines[y]!.indexOf("hello world") + await t.setup.mockMouse.drag(x, y, x + 5, y) + await t.settle() + expect(a.hasSelection()).toBe(true) + await t.input.pasteBracketedText(png) + await t.settle() + expect(a.plainText).toContain("[Image 1] ") + t.input.pressEnter() + expect(await t.until("ok2")).toBe(true) + expect(sent(1)).toContain(`@${png}`) + expect(sent(1)).not.toContain("[Image 1]") +}) + +test("the same paste twice is two copies unless it is the opening gesture: the cursor where the first paste left it", async () => { + t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }]) + const a = box(t.setup.renderer.root) + await t.input.pasteBracketedText(LONG) + await t.settle() + // Something typed in between — even in place of the space — and it is a second copy; the + // typed character stays. + t.input.pressBackspace() + await t.input.typeText("Q") + await t.input.pasteBracketedText(LONG) + await t.settle() + expect(a.plainText).toBe("[Pasted text 4 lines]Q[Pasted text 4 lines] ") + // Elsewhere in the box: a copy, not the gesture. + a.cursorOffset = 0 + await t.input.pasteBracketedText(LONG) + await t.settle() + expect(a.plainText).toBe("[Pasted text 4 lines] [Pasted text 4 lines]Q[Pasted text 4 lines] ") + t.input.pressEnter() + expect(await t.until("ok")).toBe(true) + expect(sent()).toStartWith(JSON.stringify(`${LONG} ${LONG}Q${LONG}`).slice(0, -1)) +}) + +test("a placeholder is one thing: cutting into it removes all of it, never a stump with its text silently gone", async () => { + t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }]) + const a = box(t.setup.renderer.root) + await t.input.typeText("pre ") + await t.input.pasteBracketedText(LONG) + await t.settle() + // A selection from inside "pre" into the middle of the label, deleted. + a.setSelection(2, 10) + await t.settle() + t.input.pressBackspace() + await t.settle() + expect(a.plainText).toBe("pr ") + // Undo brings the whole placeholder back, and it still stands for its text. + a.undo() + a.undo() + await t.settle() + if (!a.plainText.includes("[Pasted text 4 lines]")) a.undo() + await t.settle() + expect(a.plainText).toContain("[Pasted text 4 lines]") + // Kill to the end of the line from inside the text before it takes the placeholder whole. + a.setText("") + await t.input.typeText("one two ") + await t.input.pasteBracketedText(LONG) + await t.settle() + a.cursorOffset = 4 + t.input.pressKey("k", { ctrl: true }) + await t.settle() + expect(a.plainText).toBe("one ") + await t.input.typeText("three") + t.input.pressEnter() + expect(await t.until("ok")).toBe(true) + expect(sent()).toStartWith('"one three\\n') +}) + +test("a paste of white space is white space, not a clipboard read", async () => { + t = await tui([]) + const a = box(t.setup.renderer.root) + await t.input.typeText("x") + await t.input.pasteBracketedText("\n") + await t.settle(300) + expect(a.plainText).toBe("x\n") + expect(t.frame()).not.toMatch(/clipboard|no image/) +}) + +test("a session whose first prompt is a paste is titled by its words, and the prompt event carries them; only this transcript shows the label", async () => { + t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }], undefined, "titles: prompt\n", { store: true }) + const prompts: { text: string }[] = [] + t.app.bus.on((e) => void (e.type === "prompt" && prompts.push(e))) + const pasted = `Please review this function carefully and say what is wrong with it, in order of importance\nfunction a() {}\nfunction b() {}\nfunction c() {}` + await t.input.pasteBracketedText(pasted) + await t.settle() + t.input.pressEnter() + expect(await t.until("ok")).toBe(true) + await t.settle(200) + expect(t.frame()).toContain("┃ [Pasted text 4 lines]") + expect(prompts[0]!.text).toBe(pasted) + const title = t.app.store!.session(t.app.engine.sessionId!)!.title + expect(title).toStartWith("Please review this function carefully") + expect(title).not.toContain("[Pasted") + expect(title).not.toContain("function a") + expect(title.length).toBeLessThanOrEqual(80) +}) + +test("over SSH in kitty: off unless turned on; a reply that stalls inside a packet types nothing into the box and saves nothing", async () => { + const SSH = { SSH_CONNECTION: "192.0.2.1 50000 192.0.2.2 22", DISPLAY: undefined, WAYLAND_DISPLAY: undefined, TERM: "xterm-kitty", TMUX: undefined, STY: undefined, ZELLIJ: undefined } + const b64 = (s: string) => Buffer.from(s).toString("base64") + await withEnv(SSH, async () => { + // Off by default: the terminal is never asked, and the line says what works. + t = await tui([], { width: 220, height: 30 }) + let asked = 0 + ;(t.setup.renderer as any).writeOut = (seq: string) => void (seq.startsWith("\x1b]5522;") && asked++) + t.input.pressKey("v", { ctrl: true }) + expect(await t.until("no image reached this terminal over SSH")).toBe(true) + expect(asked).toBe(0) + t.stop() + + t = await tui([], { width: 220, height: 30 }, "kitty_clipboard: true\n") + const a = box(t.setup.renderer.root) + const r = t.setup.renderer as any + const before = existsSync(join(paths.state, "clipboard")) ? readdirSync(join(paths.state, "clipboard")).length : 0 + r.writeOut = (seq: string) => { + if (!seq.startsWith("\x1b]5522;")) return + const id = /id=([^:;]+)/.exec(seq)![1] + const want = Buffer.from(seq.slice(seq.lastIndexOf(";") + 1).replace("\x1b\\", ""), "base64").toString() + const emit = (s: string) => r.stdin.emit("data", Buffer.from(s)) + const reply = (meta: string, payload = "") => `\x1b]5522;type=read:status=${meta}:id=${id}${payload ? `;${payload}` : ""}\x1b\\` + setTimeout(async () => { + emit(reply("OK")) + if (want === ".") return void (emit(reply(`DATA:mime=${b64(".")}`, b64("text/plain image/png"))), emit(reply("DONE"))) + // The packet stops arriving half-way for longer than the input parser waits. + const whole = reply(`DATA:mime=${b64("image/png")}`, PNG_B64) + emit(whole.slice(0, 60)) + await Bun.sleep(80) + emit(whole.slice(60)) + emit(reply("DONE")) + }, 5) + } + await t.input.typeText("see ") + t.input.pressKey("v", { ctrl: true }) + expect(await t.until("did not arrive whole")).toBe(true) + expect(a.plainText).toBe("see ") + expect(existsSync(join(paths.state, "clipboard")) ? readdirSync(join(paths.state, "clipboard")).length : 0).toBe(before) + // The box takes input again once the read is over. + await t.input.typeText("now") + expect(a.plainText).toBe("see now") + }) +})