xonecas.io
64875
Mc

mini-coder / commit 8271267

Fix prompt paste handling

xonecas2026-03-08 8271267719bd2595aff5bab82f8d50d6279b3b1d parent 2dbe28d

3 files changed

TODO.md+0−9
@@ -2,15 +2,6 @@
22
33 ---
44
5-## Weird prompt behaviours related to paste
6-
7-- Weird whitepace when reaching max line length in the terminal
8-- `PASTE` word appears verbatim sometimes
9-- Extra spaces at the end of the line, pushing the cursor away from the text
10-- Pressing two keys simultaneously triggers the paste styling
11-
12----
13-
145 ## Subagents id/number/lane could be made more robust
156
167 - Currently we use an incremental integer for this, but in a long session with several conversations (user uses /new) it can become confusing (seeing subagent number 16 after /new). Let's think of a better way to id subagents and their lanes/worktrees. Maybe with a UUID?
src/cli/input.test.ts+86−1
@@ -1,5 +1,12 @@
11 import { describe, expect, test } from "bun:test";
2-import { getTurnControlAction, pasteLabel } from "./input.ts";
2+import {
3+ buildPromptDisplay,
4+ expandInputBuffer,
5+ getTurnControlAction,
6+ pasteLabel,
7+ pruneInputPasteTokens,
8+ renderInputBuffer,
9+} from "./input.ts";
310
411 describe("pasteLabel", () => {
512 test("single short line", () => {
@@ -27,6 +34,84 @@ describe("pasteLabel", () => {
2734 });
2835 });
2936
37+const PASTE_A = String.fromCharCode(0xe000);
38+const PASTE_B = String.fromCharCode(0xe001);
39+
40+describe("renderInputBuffer", () => {
41+ test("renders each paste token with its own label", () => {
42+ const pasteTokens = new Map<string, string>([
43+ [PASTE_A, "alpha"],
44+ [PASTE_B, "beta\ngamma"],
45+ ]);
46+
47+ expect(renderInputBuffer(`x${PASTE_A}y${PASTE_B}z`, pasteTokens)).toBe(
48+ 'x[pasted: "alpha"]y[pasted: "beta" +1 more line]z',
49+ );
50+ });
51+});
52+
53+describe("expandInputBuffer", () => {
54+ test("expands multiple paste tokens back to their original text", () => {
55+ const pasteTokens = new Map<string, string>([
56+ [PASTE_A, "alpha"],
57+ [PASTE_B, "beta\ngamma"],
58+ ]);
59+
60+ expect(expandInputBuffer(`x${PASTE_A}y${PASTE_B}z`, pasteTokens)).toBe(
61+ "xalphaybeta\ngammaz",
62+ );
63+ });
64+});
65+
66+describe("pruneInputPasteTokens", () => {
67+ test("removes a paste token after it has been deleted from all buffers", () => {
68+ const pasteTokens = new Map<string, string>([
69+ [PASTE_A, "alpha"],
70+ [PASTE_B, "beta"],
71+ ]);
72+
73+ expect(
74+ Array.from(pruneInputPasteTokens(pasteTokens, `x${PASTE_B}y`).entries()),
75+ ).toEqual([[PASTE_B, "beta"]]);
76+ });
77+
78+ test("keeps a paste token while it is still referenced by saved input", () => {
79+ const pasteTokens = new Map<string, string>([
80+ [PASTE_A, "alpha"],
81+ [PASTE_B, "beta"],
82+ ]);
83+
84+ expect(
85+ Array.from(
86+ pruneInputPasteTokens(
87+ pasteTokens,
88+ `x${PASTE_B}y`,
89+ `${PASTE_A}z`,
90+ ).entries(),
91+ ),
92+ ).toEqual([
93+ [PASTE_A, "alpha"],
94+ [PASTE_B, "beta"],
95+ ]);
96+ });
97+});
98+
99+describe("buildPromptDisplay", () => {
100+ test("keeps the cursor aligned with the visible tail of a long line", () => {
101+ expect(buildPromptDisplay("abcdefghijklmnopqrstuvwxyz", 26, 10)).toEqual({
102+ display: "…rstuvwxyz",
103+ cursor: 10,
104+ });
105+ });
106+
107+ test("shows ellipses on both sides when the cursor is in the middle", () => {
108+ expect(buildPromptDisplay("abcdefghijklmnopqrstuvwxyz", 15, 10)).toEqual({
109+ display: "…ghijklmn…",
110+ cursor: 10,
111+ });
112+ });
113+});
114+
30115 describe("getTurnControlAction", () => {
31116 test("treats ESC as cancel", () => {
32117 expect(getTurnControlAction(new Uint8Array([0x1b]))).toBe("cancel");
src/cli/input.ts+137−55
@@ -253,8 +253,19 @@ export function watchForCancel(abortController: AbortController): () => void {
253253
254254 // ─── Paste handling ───────────────────────────────────────────────────────────
255255
256-const PASTE_SENTINEL = "\x00PASTE\x00";
257-const PASTE_SENTINEL_LEN = PASTE_SENTINEL.length;
256+const PASTE_TOKEN_START = 0xe000;
257+const PASTE_TOKEN_END = 0xf8ff;
258+
259+function createPasteToken(
260+ buf: string,
261+ pasteTokens: ReadonlyMap<string, string>,
262+): string {
263+ for (let code = PASTE_TOKEN_START; code <= PASTE_TOKEN_END; code++) {
264+ const token = String.fromCharCode(code);
265+ if (!buf.includes(token) && !pasteTokens.has(token)) return token;
266+ }
267+ throw new Error("Too many pasted chunks in a single prompt");
268+}
258269
259270 export function pasteLabel(text: string): string {
260271 const lines = text.split("\n");
@@ -265,6 +276,81 @@ export function pasteLabel(text: string): string {
265276 return `[pasted: "${preview}"${more}]`;
266277 }
267278
279+export function renderInputBuffer(
280+ buf: string,
281+ pasteTokens: ReadonlyMap<string, string>,
282+): string {
283+ let out = "";
284+ for (let i = 0; i < buf.length; i++) {
285+ const ch = buf[i] ?? "";
286+ const pasted = pasteTokens.get(ch);
287+ out += pasted ? pasteLabel(pasted) : ch;
288+ }
289+ return out;
290+}
291+
292+export function expandInputBuffer(
293+ buf: string,
294+ pasteTokens: ReadonlyMap<string, string>,
295+): string {
296+ let out = "";
297+ for (let i = 0; i < buf.length; i++) {
298+ const ch = buf[i] ?? "";
299+ out += pasteTokens.get(ch) ?? ch;
300+ }
301+ return out;
302+}
303+
304+export function pruneInputPasteTokens(
305+ pasteTokens: ReadonlyMap<string, string>,
306+ ...buffers: readonly string[]
307+): Map<string, string> {
308+ const referenced = buffers.join("");
309+ const next = new Map<string, string>();
310+ for (const [token, text] of pasteTokens) {
311+ if (referenced.includes(token)) next.set(token, text);
312+ }
313+ return next;
314+}
315+
316+function getVisualCursor(
317+ buf: string,
318+ cursor: number,
319+ pasteTokens: ReadonlyMap<string, string>,
320+): number {
321+ let visual = 0;
322+ for (let i = 0; i < Math.min(cursor, buf.length); i++) {
323+ const ch = buf[i] ?? "";
324+ const pasted = pasteTokens.get(ch);
325+ visual += pasted ? pasteLabel(pasted).length : 1;
326+ }
327+ return visual;
328+}
329+
330+export function buildPromptDisplay(
331+ text: string,
332+ cursor: number,
333+ maxLen: number,
334+): { display: string; cursor: number } {
335+ const clampedCursor = Math.max(0, Math.min(cursor, text.length));
336+ if (maxLen <= 0) return { display: "", cursor: 0 };
337+ if (text.length <= maxLen) return { display: text, cursor: clampedCursor };
338+
339+ let start = Math.max(0, clampedCursor - maxLen);
340+ const end = Math.min(text.length, start + maxLen);
341+ if (end - start < maxLen) start = Math.max(0, end - maxLen);
342+
343+ let display = text.slice(start, end);
344+ if (start > 0 && display.length > 0) display = `…${display.slice(1)}`;
345+ if (end < text.length && display.length > 0)
346+ display = `${display.slice(0, -1)}…`;
347+
348+ return {
349+ display,
350+ cursor: Math.min(clampedCursor - start, display.length),
351+ };
352+}
353+
268354 // ─── Main readline function ───────────────────────────────────────────────────
269355
270356 const PROMPT = c.green("▶ ");
@@ -289,9 +375,26 @@ export async function readline(opts: {
289375 let savedInput = ""; // saved current line when navigating history
290376 let searchMode = false;
291377 let searchQuery = "";
292- let pasteBuffer: string | null = null; // full text of a pending paste
378+ const pasteTokens = new Map<string, string>();
293379 const imageAttachments: ImageAttachment[] = []; // images collected during this prompt
294380
381+ function prunePasteTokens(): void {
382+ const next = pruneInputPasteTokens(pasteTokens, buf, savedInput);
383+ pasteTokens.clear();
384+ for (const [token, text] of next) pasteTokens.set(token, text);
385+ }
386+
387+ function insertText(text: string): void {
388+ buf = buf.slice(0, cursor) + text + buf.slice(cursor);
389+ cursor += text.length;
390+ }
391+
392+ function insertPasteToken(text: string): void {
393+ const token = createPasteToken(buf, pasteTokens);
394+ pasteTokens.set(token, text);
395+ insertText(token);
396+ }
397+
295398 terminal.setRawMode(true);
296399 process.stdin.resume();
297400 process.stdout.write(BPASTE_ENABLE);
@@ -300,26 +403,13 @@ export async function readline(opts: {
300403
301404 function renderPrompt(): void {
302405 const cols = process.stdout.columns ?? 80;
303- // Replace paste sentinel and image labels with styled placeholders for display
304- const visualBuf = (
305- pasteBuffer
306- ? buf.replace(PASTE_SENTINEL, c.dim(pasteLabel(pasteBuffer)))
307- : buf
308- ).replace(/\[image: [^\]]+\]/g, (m) => c.dim(c.cyan(m)));
309-
310- // For cursor positioning we need the visual length without the sentinel substitution
311- const visualCursor = pasteBuffer
312- ? (() => {
313- const sentinelPos = buf.indexOf(PASTE_SENTINEL);
314- if (sentinelPos === -1 || cursor <= sentinelPos) return cursor;
315- // cursor is after the sentinel: shift by (label len - sentinel len)
316- return cursor - PASTE_SENTINEL_LEN + pasteLabel(pasteBuffer).length;
317- })()
318- : cursor;
319- const display =
320- visualBuf.length > cols - PROMPT_RAW_LEN - 2
321- ? `…${visualBuf.slice(-(cols - PROMPT_RAW_LEN - 3))}`
322- : visualBuf;
406+ const visualBuf = renderInputBuffer(buf, pasteTokens);
407+ const visualCursor = getVisualCursor(buf, cursor, pasteTokens);
408+ const { display, cursor: displayCursor } = buildPromptDisplay(
409+ visualBuf,
410+ visualCursor,
411+ Math.max(1, cols - PROMPT_RAW_LEN - 2),
412+ );
323413
324414 const prompt = opts.planMode
325415 ? PROMPT_PLAN
@@ -328,7 +418,7 @@ export async function readline(opts: {
328418 : PROMPT;
329419
330420 process.stdout.write(
331- `${CLEAR_LINE}${prompt}${display}${CSI}${PROMPT_RAW_LEN + visualCursor + 1}G`,
421+ `${CLEAR_LINE}${prompt}${display}${CSI}${PROMPT_RAW_LEN + displayCursor + 1}G`,
332422 );
333423 }
334424
@@ -343,6 +433,7 @@ export async function readline(opts: {
343433 buf = savedInput;
344434 }
345435 cursor = buf.length;
436+ prunePasteTokens();
346437 renderPrompt();
347438 }
348439
@@ -404,15 +495,12 @@ export async function readline(opts: {
404495 const imageResult = await tryExtractImageFromPaste(pasted, cwd);
405496 if (imageResult) {
406497 imageAttachments.push(imageResult.attachment);
407- buf = buf.slice(0, cursor) + imageResult.label + buf.slice(cursor);
408- cursor += imageResult.label.length;
498+ insertText(imageResult.label);
409499 renderPrompt();
410500 continue;
411501 }
412502
413- pasteBuffer = pasted;
414- buf = buf.slice(0, cursor) + PASTE_SENTINEL + buf.slice(cursor);
415- cursor += PASTE_SENTINEL_LEN;
503+ insertPasteToken(pasted);
416504 renderPrompt();
417505 continue;
418506 }
@@ -473,7 +561,7 @@ export async function readline(opts: {
473561 while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
474562 while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
475563 buf = buf.slice(0, cursor) + buf.slice(end);
476- if (pasteBuffer && !buf.includes(PASTE_SENTINEL)) pasteBuffer = null;
564+ prunePasteTokens();
477565 renderPrompt();
478566 continue;
479567 }
@@ -512,7 +600,7 @@ export async function readline(opts: {
512600 while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
513601 while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
514602 buf = buf.slice(0, cursor) + buf.slice(end);
515- if (pasteBuffer && !buf.includes(PASTE_SENTINEL)) pasteBuffer = null;
603+ prunePasteTokens();
516604 renderPrompt();
517605 continue;
518606 }
@@ -520,14 +608,14 @@ export async function readline(opts: {
520608 if (raw === CTRL_U) {
521609 buf = buf.slice(cursor);
522610 cursor = 0;
523- if (pasteBuffer && !buf.includes(PASTE_SENTINEL)) pasteBuffer = null;
611+ prunePasteTokens();
524612 renderPrompt();
525613 continue;
526614 }
527615
528616 if (raw === CTRL_K) {
529617 buf = buf.slice(0, cursor);
530- if (pasteBuffer && !buf.includes(PASTE_SENTINEL)) pasteBuffer = null;
618+ prunePasteTokens();
531619 renderPrompt();
532620 continue;
533621 }
@@ -549,7 +637,7 @@ export async function readline(opts: {
549637 if (cursor > 0) {
550638 buf = buf.slice(0, cursor - 1) + buf.slice(cursor);
551639 cursor--;
552- if (pasteBuffer && !buf.includes(PASTE_SENTINEL)) pasteBuffer = null;
640+ prunePasteTokens();
553641 renderPrompt();
554642 }
555643 continue;
@@ -580,11 +668,8 @@ export async function readline(opts: {
580668
581669 // ── Enter — submit ────────────────────────────────────────────────────
582670 if (raw === ENTER || raw === NEWLINE) {
583- // Expand paste sentinel before trimming/submitting
584- const expanded = pasteBuffer
585- ? buf.replace(PASTE_SENTINEL, pasteBuffer)
586- : buf;
587- pasteBuffer = null;
671+ const expanded = expandInputBuffer(buf, pasteTokens);
672+ pasteTokens.clear();
588673 const text = expanded.trim();
589674 process.stdout.write("\n");
590675 buf = "";
@@ -625,35 +710,32 @@ export async function readline(opts: {
625710 };
626711 }
627712
628- // ── Paste detection ───────────────────────────────────────────────────
629- // A chunk with more than one character that isn't an escape sequence is
630- // almost certainly a clipboard paste. Capture it and show a placeholder.
713+ // ── Multi-char chunks ──────────────────────────────────────────────────
714+ // Bracketed paste is handled above. Other multi-char chunks are usually
715+ // coalesced typing or a non-bracketed paste from a terminal that does not
716+ // support bracketed paste.
631717 if (raw.length > 1) {
632- // Strip trailing newline that some terminals append on paste
633- const pasted = raw.replace(/\r?\n$/, "");
634-
635- // Check if this is an image (data URL or image file path)
636- const imageResult = await tryExtractImageFromPaste(pasted, cwd);
718+ const chunk = raw.replace(/\r?\n$/, "");
719+ const imageResult = await tryExtractImageFromPaste(chunk, cwd);
637720 if (imageResult) {
638721 imageAttachments.push(imageResult.attachment);
639- // Insert the plain label into buf (no sentinel — nothing to expand at submit)
640- buf = buf.slice(0, cursor) + imageResult.label + buf.slice(cursor);
641- cursor += imageResult.label.length;
722+ insertText(imageResult.label);
642723 renderPrompt();
643724 continue;
644725 }
645726
646- pasteBuffer = pasted;
647- buf = buf.slice(0, cursor) + PASTE_SENTINEL + buf.slice(cursor);
648- cursor += PASTE_SENTINEL_LEN;
727+ if (chunk.includes("\n") || chunk.includes("\r")) {
728+ insertPasteToken(chunk);
729+ } else {
730+ insertText(chunk);
731+ }
649732 renderPrompt();
650733 continue;
651734 }
652735
653736 // ── Printable characters ──────────────────────────────────────────────
654737 if (raw >= " " || raw === "\t") {
655- buf = buf.slice(0, cursor) + raw + buf.slice(cursor);
656- cursor++;
738+ insertText(raw);
657739 renderPrompt();
658740 }
659741 }