Paste placeholders in the prompt box
ci / check (push) Canceled after 0s

A paste of three lines or more, or over 150 characters, is shown as
[Pasted text N lines] / [Pasted text N chars]; an image as [Image N],
numbered after the highest in the box. They are OpenTUI extmarks over the
label; the content is kept beside them and sent in full (an image as its
@path). Deleting a placeholder removes its content; the same paste again
opens it. The transcript shows the box as it looked; history, /undo, a
refused send and a copy of a selection in the box use the full text.
paste: full shows pastes whole.

The box's offsets are columns: the @file list and the edge-line check now
take text by range instead of slicing by offset.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 09:50:14 +00:00
1 parent bba0428c3b
commit 4d14290cec
9 files changed
+507 -35

No files matched your search

+11
View File
@@ -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 <dir>`, close one of the open terminals.
+8
View File
@@ -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",
+1
View File
@@ -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)
+1
View File
@@ -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" },
+12 -7
View File
@@ -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: () =>
<Spinner />
</Show>
<Queued />
<Prompt focused={() => !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} />
<Prompt focused={() => !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} />
<StatusBar mode={mode} model={model} effort={effort} branch={branch()} voice={voiceStatus} flash={flashText} remote={() => (rev(), share.label())} spend={spend} team={teamWord} />
</box>
<Show when={dialog()}>
+86 -27
View File
@@ -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<Popup>()
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<History["mark"]>; pulled: typeof pulled; queue?: () => void } } | undefined
let burst: { dir: "up" | "down"; at: number; undo?: { box: BoxSnapshot; history: ReturnType<History["mark"]>; 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: {
<textarea
ref={(r: TextareaRenderable) => {
area = r
marks = new Placeholders(r, () => style().getStyleId("extmark.paste") ?? undefined)
p.ref?.(r)
p.handle?.({ expanded: full, expandedSelection: () => marks?.expandedSelection() })
}}
focused={p.focused()}
flexGrow={1}
minHeight={1}
maxHeight={8}
wrapMode="word"
syntaxStyle={style()}
textColor={c().prompt}
focusedTextColor={c().prompt}
cursorColor={c().accent}
@@ -260,7 +319,8 @@ export function Prompt(p: {
}
}
if (e.name !== "up" && e.name !== "down") return
const t = area.plainText
// In full: a draft with a placeholder in it comes back from history as its text.
const t = full()
const now = performance.now()
if (burst && burst.dir === e.name && now - burst.at < BURST_MS && p.onWheel) {
// The second arrow of a burst: it was the wheel. Undo the first, scroll for both.
@@ -270,8 +330,7 @@ export function Prompt(p: {
u.queue?.()
pulled = u.pulled
history.restore(u.history)
area.setText(u.text)
area.cursorOffset = u.cursor
marks!.restore(u.box)
burst.undo = undefined
lines = 2
}
@@ -279,10 +338,10 @@ export function Prompt(p: {
p.onWheel(e.name === "up" ? -1 : 1, lines)
return e.preventDefault()
}
const before = { text: t, cursor: area.cursorOffset, history: history.mark(), pulled: pulled && { ...pulled } }
const before = { box: marks!.snapshot(), history: history.mark(), pulled: pulled && { ...pulled } }
burst = { dir: e.name, at: now, undo: before }
const atFirst = !t.slice(0, area.cursorOffset).includes("\n")
const atLast = !t.slice(area.cursorOffset).includes("\n")
const atFirst = !area.getTextRange(0, area.cursorOffset).includes("\n")
const atLast = !area.getTextRange(area.cursorOffset, 0x3fffffff).includes("\n")
if ((e.name === "up" && atFirst) || (e.name === "down" && atLast)) {
const countBefore = p.queue?.count()
const next = walk(e.name, t)
+155
View File
@@ -0,0 +1,155 @@
// Paste placeholders in the prompt box. A long paste is shown as `[Pasted text 40 lines]` and an
// image as `[Image 2]`; what is sent is the text itself, or the `@path` of the saved image. The
// placeholder is an OpenTUI extmark over the label (virtual: the cursor steps over it and one
// backspace removes it whole), and the content is kept here, by the extmark's id.
//
// Offsets in the textarea are display columns, not string indices (a wide character is two), so
// nothing here slices `plainText` by an offset: text is taken with `getTextRange`.
import type { TextareaRenderable } from "@opentui/core"
/** A paste at least this many lines long is shown as a placeholder… */
export const PASTE_LINES = 3
/** …or longer than this many characters. */
export const PASTE_CHARS = 150
/** The placeholder a pasted text is shown as, or undefined when it is short enough to show whole. */
export function pasteLabel(text: string): string | undefined {
const lines = text.split("\n").length
if (lines >= PASTE_LINES) return `[Pasted text ${lines} lines]`
const chars = [...text].length
return chars > PASTE_CHARS ? `[Pasted text ${chars} chars]` : undefined
}
export const imageLabel = (n: number) => `[Image ${n}]`
/** The number the next image gets: one after the highest among `labels`. */
export function nextImageNumber(labels: string[]): number {
let max = 0
for (const l of labels) {
const m = /^\[Image (\d+)\]$/.exec(l)
if (m) max = Math.max(max, Number(m[1]))
}
return max + 1
}
export interface Placeholder {
label: string
/** What is sent in its place. */
content: string
kind: "text" | "image"
}
/** The box as it can be put back: its text, and where each placeholder was. */
export interface BoxSnapshot {
text: string
cursor: number
marks: { start: number; end: number; item: Placeholder }[]
}
type Area = Pick<TextareaRenderable, "plainText" | "cursorOffset" | "insertText" | "getTextRange" | "extmarks" | "setText" | "setSelection" | "getSelection" | "hasSelection">
/** Beyond any text a prompt box holds: `getTextRange` clamps it to the end. */
const END = 0x3fffffff
export class Placeholders {
private items = new Map<number, Placeholder>()
private typeId: number
constructor(
private area: Area,
private styleId?: () => number | undefined,
) {
this.typeId = area.extmarks.registerType("lembas-paste")
}
/** The placeholders in the box now, in order. One deleted is gone from here; an undo that
* brings its label back brings it back (the extmark returns under the same id). */
live(): { start: number; end: number; item: Placeholder }[] {
return this.area.extmarks
.getAllForTypeId(this.typeId)
.flatMap((m) => {
const item = this.items.get(m.id)
// A label that was edited into something else no longer stands for its content.
return item && this.area.getTextRange(m.start, m.end) === item.label ? [{ start: m.start, end: m.end, item }] : []
})
.sort((a, b) => a.start - b.start)
}
get any(): boolean {
return this.items.size > 0 && this.live().length > 0
}
/** Put a placeholder at the cursor, 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)
}
private mark(start: number, end: number, item: Placeholder) {
const id = this.area.extmarks.create({ start, end, virtual: true, typeId: this.typeId, ...(this.styleId?.() !== undefined ? { styleId: this.styleId!() } : {}) })
this.items.set(id, item)
}
/** The next image's number: after the highest in the box. */
nextImage(): number {
return nextImageNumber(this.live().map((m) => m.item.label))
}
/** The text between two offsets with every placeholder inside them replaced by its content. */
expandedRange(from: number, to: number): string {
let out = ""
let at = from
for (const m of this.live()) {
if (m.start < from || m.end > to) continue
out += this.area.getTextRange(at, m.start) + m.item.content
at = m.end
}
return out + this.area.getTextRange(at, to)
}
/** What the box says, in full: every placeholder replaced by its content. */
expanded(): string {
return this.items.size ? this.expandedRange(0, END) : this.area.plainText
}
/** What is selected in the box, in full — undefined when nothing in the box is selected. */
expandedSelection(): string | undefined {
if (!this.area.hasSelection()) return undefined
const sel = this.area.getSelection()
if (!sel || sel.start === sel.end) return undefined
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. */
expandAtCursor(content: string): boolean {
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))
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)
this.area.insertText(content)
return true
}
snapshot(): BoxSnapshot {
return { text: this.area.plainText, cursor: this.area.cursorOffset, marks: this.live() }
}
/** Put the box back as it was, placeholders and all. (`setText` drops every extmark.) */
restore(s: BoxSnapshot) {
this.area.setText(s.text)
this.items.clear()
for (const m of s.marks) this.mark(m.start, m.end, m.item)
this.area.cursorOffset = s.cursor
}
/** The box was emptied or given other text: nothing is a placeholder any more. */
clear() {
this.items.clear()
this.area.extmarks.clear()
}
}
+7 -1
View File
@@ -323,11 +323,17 @@ test("thinking stops the clock when the model starts a call, even if the call th
expect(await t.until("done")).toBe(true)
})
test("pasting an image's path (quoted, as a file manager does) inserts an @reference", async () => {
test("pasting an image's path (quoted, as a file manager does): [Image 1], or its @reference with paste: full", async () => {
t = await tui([])
await Bun.write(`${t.cwd}/my shot.png`, "x")
await t.input.pasteBracketedText(`'${t.cwd}/my shot.png'`)
await t.settle()
expect(t.frame()).toContain("❯ [Image 1]")
t.stop()
t = await tui([], undefined, "paste: full\n")
await Bun.write(`${t.cwd}/my shot.png`, "x")
await t.input.pasteBracketedText(`'${t.cwd}/my shot.png'`)
await t.settle()
expect(t.frame()).toContain(`@${t.cwd}/my\\ shot.png`)
})
+226
View File
@@ -0,0 +1,226 @@
// Paste placeholders in the prompt box (src/tui/paste.ts, prompt.tsx): a long paste and an image
// 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 { join } from "node:path"
import { paths } from "../../src/config/paths.ts"
import { nextImageNumber, pasteLabel } from "../../src/tui/paste.ts"
import { delta, usage } from "../fake-provider.ts"
import { tui } from "./harness.tsx"
let t: Awaited<ReturnType<typeof tui>> | undefined
afterEach(() => t?.stop())
const box = (n: any): TextareaRenderable => (n instanceof TextareaRenderable ? n : n.getChildren?.().map(box).find(Boolean))
const LONG = ["first line", "second line", "third line", "fourth line"].join("\n")
/** The last user message of request `i`, as JSON text. */
const sent = (i = 0) => JSON.stringify((t!.fake.requests[i]!.messages as { role: string; content: unknown }[]).filter((m) => m.role === "user").at(-1)!.content)
test("which pastes get a placeholder, and what it says", () => {
expect(pasteLabel("one\ntwo")).toBeUndefined()
expect(pasteLabel("one\ntwo\nthree")).toBe("[Pasted text 3 lines]")
expect(pasteLabel("x".repeat(150))).toBeUndefined()
expect(pasteLabel("x".repeat(151))).toBe("[Pasted text 151 chars]")
// Two long lines are still one long text, counted in characters (code points).
expect(pasteLabel(`${"é".repeat(100)}\n${"é".repeat(100)}`)).toBe("[Pasted text 201 chars]")
expect(nextImageNumber([])).toBe(1)
expect(nextImageNumber(["[Image 1]", "[Pasted text 3 lines]", "[Image 4]"])).toBe(5)
})
test("a long paste shows as a placeholder; the text itself is sent, and the transcript shows the placeholder", async () => {
t = await tui([{ chunks: [delta({ content: "Read it." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("look: ")
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe("look: [Pasted text 4 lines] ")
expect(t.frame()).toContain("look: [Pasted text 4 lines]")
await t.input.typeText("thanks")
t.input.pressEnter()
expect(await t.until("Read it.")).toBe(true)
expect(sent()).toContain("look: first line\\nsecond line\\nthird line\\nfourth line thanks")
expect(sent()).not.toContain("[Pasted text")
expect(t.frame()).toContain("┃ look: [Pasted text 4 lines] thanks")
expect(a.plainText).toBe("")
})
test("a short paste goes in as it is; text after wide characters keeps the placeholder in place", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText("just\ntwo")
await t.settle()
expect(a.plainText).toBe("just\ntwo")
a.setText("")
// Offsets in the box are columns: a wide character before the placeholder must not shift it.
a.insertText("日本語 🙂 ")
await t.input.pasteBracketedText(LONG)
await t.settle()
a.insertText("end")
expect(a.plainText).toBe("日本語 🙂 [Pasted text 4 lines] end")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toContain("日本語 🙂 first line\\nsecond line\\nthird line\\nfourth line end")
})
test("deleting the placeholder removes the content; undo in the box brings both back", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("a ")
await t.input.pasteBracketedText(LONG)
await t.settle()
t.input.pressBackspace() // the space after it
t.input.pressBackspace() // the placeholder, whole
await t.settle()
expect(a.plainText).toBe("a ")
a.undo()
await t.settle()
expect(a.plainText).toContain("[Pasted text 4 lines]")
a.gotoBufferEnd()
t.input.pressBackspace()
await t.settle()
expect(a.plainText).toBe("a ")
await t.input.typeText("b")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toStartWith('"a b\\n')
expect(sent()).not.toContain("first line")
})
test("the same paste again, right after its placeholder, opens it", async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe("[Pasted text 4 lines] ")
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe(LONG)
})
test("two pastes with the same label keep their own text; an @file completed beside them leaves them alone", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText("a1\na2\na3")
await t.input.pasteBracketedText("b1\nb2\nb3")
await t.settle()
expect(a.plainText).toBe("[Pasted text 3 lines] [Pasted text 3 lines] ")
await t.input.typeText("@hello")
expect(await t.until("hello.txt")).toBe(true)
t.input.pressTab()
await t.settle()
expect(a.plainText).toBe("[Pasted text 3 lines] [Pasted text 3 lines] @hello.txt ")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toContain("a1\\na2\\na3 b1\\nb2\\nb3 @hello.txt")
})
test("history and /undo give the text in full", async () => {
t = await tui([{ chunks: [delta({ content: "Answered." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("see ")
await t.input.pasteBracketedText(LONG)
await t.settle()
t.input.pressEnter()
expect(await t.until("Answered.")).toBe(true)
// History is the file other sessions read too: the text itself.
const history = readFileSync(join(paths.state, "history.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l) as string)
expect(history.at(-1)).toBe(`see ${LONG} `)
t.input.pressArrow("up")
await t.settle()
expect(a.plainText).toBe(`see ${LONG} `)
a.setText("")
await t.input.typeText("/undo")
t.input.pressEnter()
await t.settle(200)
expect(a.plainText).toContain(`see ${LONG}`)
})
test("a refused send puts the placeholder back, still standing for its text", async () => {
t = await tui([{ chunks: [delta({ content: "Slow" }), delta({ content: "ly" }), delta({ content: " done." }), usage(100, 5)], gapMs: 300 }, { chunks: [delta({ content: "Second." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("go")
t.input.pressEnter()
expect(await t.until("Slow")).toBe(true)
// Busy with a turn: a command that must wait is refused, and the box comes back whole.
await t.input.typeText("/compact ")
await t.input.pasteBracketedText(LONG)
await t.settle(20)
t.input.pressEnter()
await t.settle(20)
expect(t.frame()).toContain("wait for the reply to finish")
expect(a.plainText).toBe("/compact [Pasted text 4 lines] ")
expect(await t.until("ly done.")).toBe(true) // the notice above went in mid-reply
// Still a placeholder: sent now as a prompt, it is the text.
a.cursorOffset = 0
for (let k = 0; k < "/compact ".length; k++) a.deleteChar()
t.input.pressEnter()
expect(await t.until("Second.")).toBe(true)
expect(sent(1)).toContain("first line\\nsecond line")
})
test("copying a selection in the box copies the text in full", async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
await t.input.typeText("x ")
await t.input.pasteBracketedText(LONG)
await t.settle()
const copied: string[] = []
;(t.setup.renderer as any).copyToClipboardOSC52 = (s: string) => (copied.push(s), true)
// Drag across the box's one row.
const y = t.frame().split("\n").findIndex((l) => l.includes("[Pasted text 4 lines]"))
const x = t.frame().split("\n")[y]!.indexOf("x [Pasted")
await t.setup.mockMouse.drag(x, y, x + 30, y)
await t.settle()
expect(copied.at(-1)).toBe(`x ${LONG} `)
expect(a.plainText).toBe("x [Pasted text 4 lines] ")
})
test("paste: full shows the text itself", async () => {
t = await tui([], undefined, "paste: full\n")
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe(LONG)
})
test("a pasted path to an image is [Image N], numbered after the highest in the box, and sent as its @path", async () => {
t = await tui([{ chunks: [delta({ content: "Seen." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
// A 1×1 PNG.
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64")
const one = join(t.cwd, "shot one.png")
const two = join(t.cwd, "two.png")
writeFileSync(one, png)
writeFileSync(two, png)
await t.input.pasteBracketedText(`'${one}'`)
await t.input.pasteBracketedText(two)
await t.settle()
expect(a.plainText).toBe("[Image 1] [Image 2] ")
// The first one deleted: the next is numbered after the highest still there.
a.cursorOffset = "[Image 1] ".length
t.input.pressBackspace()
t.input.pressBackspace()
await t.settle()
expect(a.plainText).toBe("[Image 2] ")
a.gotoBufferEnd()
await t.input.pasteBracketedText(`file://${one.replace(/ /g, "%20")}`)
await t.settle()
expect(a.plainText).toBe("[Image 2] [Image 3] ")
t.input.pressEnter()
expect(await t.until("Seen.")).toBe(true)
expect(t.frame()).toContain("┃ [Image 2] [Image 3]")
expect(sent()).toContain(`@${two} @${one.replace(/ /g, "\\\\ ")}`)
expect(t.frame()).toContain("attached")
})
test("an @file completed after wide characters replaces its own token, nothing else", async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
a.insertText("日本語の説明 ")
await t.input.typeText("@hello")
expect(await t.until("hello.txt")).toBe(true)
t.input.pressTab()
await t.settle()
expect(a.plainText).toBe("日本語の説明 @hello.txt ")
})