fix(terminal): strip OSC 52 from replays and copy each clipboard write once

xterm parses write() data after chunkedTerminalWrite has already cleared
_isLoadingBuffer, so the main terminal's replay gate never held: a tab switch
or reconnect re-copied the newest OSC 52 in the replayed history. Strip every
OSC 52 from the replay beside the DEC 2026 markers (OSC52_STRIP_RE). Tiles
keep their own _bufferLoading gate, which holds there.

One Claude Code copy arrives up to three times (its own OSC 52, tmux
load-buffer -w, set-clipboard forwarding), so identical text within
OSC52_DEDUPE_MS is dropped. The manual-copy fallback opens only in the
focused tab, so a background tab on the same session stays quiet.

The replay tests now drive the real chunkedTerminalWrite into
@xterm/headless and fail without the strip. Test harnesses that supply
DEC_SYNC_STRIP_RE by hand get OSC52_STRIP_RE too, and CLAUDE.md records
the rules next to Auto Copy.
This commit is contained in:
Zoltan Zombory committed 2026-10-13 13:54:15 +02:00
1 parent 435a56be10
commit 4ecf7fa228
11 files changed
+127 -29

No files matched your search

+1
View File
@@ -39,6 +39,7 @@ function loadApp() {
setTimeout: () => 1,
MobileDetection: { isTouchDevice: () => false },
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
TERMINAL_CHUNK_SIZE: 32 * 1024,
});
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
+1
View File
@@ -57,6 +57,7 @@ function loadHarness() {
MobileDetection: { isTouchDevice: () => false },
KeyboardHandler: { keyboardVisible: false },
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
TERMINAL_CHUNK_SIZE: 32 * 1024,
});
+1
View File
@@ -61,6 +61,7 @@ function loadHarness(
MobileDetection: { isTouchDevice: () => false, getDeviceType: () => 'desktop' },
KeyboardHandler: { keyboardVisible: false },
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
TERMINAL_CHUNK_SIZE: 32 * 1024,
});
+1
View File
@@ -22,6 +22,7 @@ function loadTerminalUiHarness(mode: string) {
this.postMessage = () => {};
},
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
TERMINAL_CHUNK_SIZE: 32 * 1024,
});
@@ -38,6 +38,7 @@ function loadHarness() {
setTimeout: () => 1,
MobileDetection: { isTouchDevice: () => false },
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
TERMINAL_CHUNK_SIZE: 32 * 1024,
});
const read = (f: string) => readFileSync(resolve(import.meta.dirname, `../src/web/public/${f}`), 'utf8');
+90 -19
View File
@@ -5,33 +5,48 @@
* on, vim) set the clipboard this way. xterm.js registers no handler for 52,
* and a headless host has no OS clipboard, so without this handler every such
* copy was dropped. These tests pin the handler itself: decode, UTF-8, the
* read-query refusal, the replay gate, and the blocked-write fallback.
* read-query refusal, the replay gates, and the blocked-write fallback.
*
* Strategy: run terminal-ui.js in a vm with a stub CodemanApp (the harness
* shape test/terminal-copy-selection.test.ts uses) and a fake terminal whose
* parser records the registered handler. No DOM, no xterm.
* Strategy: run constants.js + terminal-ui.js in a vm with a stub CodemanApp
* (the harness shape test/terminal-copy-selection.test.ts uses). The handler
* tests use a fake terminal whose parser records the registered handler; the
* replay tests drive the REAL chunkedTerminalWrite into a real
* @xterm/headless terminal, because xterm parses write() data asynchronously
* and a synchronous stub hides exactly the ordering the replay gate depends on.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
import xtermHeadless from '@xterm/headless';
function loadHarness(copyResult = true) {
const { Terminal } = xtermHeadless as unknown as {
Terminal: new (opts: Record<string, unknown>) => { write(data: string, cb?: () => void): void };
};
const read = (rel: string) => readFileSync(resolve(import.meta.dirname, '..', rel), 'utf8');
function loadHarness(copyResult = true, focused = true) {
const CodemanApp = function CodemanApp(this: unknown) {};
const context = vm.createContext({
CodemanApp,
window: {},
document: { getElementById: () => null, querySelector: () => null },
globalThis: {},
document: { getElementById: () => null, querySelector: () => null, hasFocus: () => focused },
console,
MobileDetection: { isTouchDevice: () => false, getDeviceType: () => 'desktop' },
Object,
atob,
TextDecoder,
Uint8Array,
performance,
setTimeout,
clearTimeout,
requestAnimationFrame: (cb: () => void) => setTimeout(cb, 0),
});
const terminalUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
vm.runInContext(terminalUi, context, { filename: 'terminal-ui.js' });
vm.runInContext(read('src/web/public/constants.js'), context, { filename: 'constants.js' });
vm.runInContext(read('src/web/public/terminal-ui.js'), context, { filename: 'terminal-ui.js' });
const app = new (CodemanApp as unknown as new () => Record<string, any>)();
const copied: string[] = [];
@@ -43,6 +58,7 @@ function loadHarness(copyResult = true) {
};
app._showClipboardFallback = (text: string) => fallbacks.push(text);
app.showToast = (msg: string) => toasts.push(msg);
app._chunkedWriteGen = 0;
const handlers = new Map<number, (data: string) => boolean>();
const terminal = {
@@ -84,17 +100,6 @@ describe('OSC 52 clipboard handler', () => {
expect(h.copied).toEqual([]);
});
it('never copies during a buffer replay (main terminal flag)', async () => {
const h = loadHarness();
h.app._installOsc52Clipboard(h.terminal);
h.app._isLoadingBuffer = true;
h.handlers.get(52)!(`c;${b64('old')}`);
h.app._isLoadingBuffer = false;
h.handlers.get(52)!(`c;${b64('new')}`);
await flush();
expect(h.copied).toEqual(['new']);
});
it("uses the caller's replay check when one is given (TerminalTile)", async () => {
const h = loadHarness();
let tileLoading = true;
@@ -115,6 +120,29 @@ describe('OSC 52 clipboard handler', () => {
expect(h.toasts).toEqual([]);
});
it('copies one Claude Code copy once, though it arrives three times', async () => {
// What a single /copy in a Codeman tmux session actually delivers: Claude's
// own OSC 52 plus tmux forwarding it twice (captured from a live session).
const h = loadHarness();
h.app._installOsc52Clipboard(h.terminal);
const handler = h.handlers.get(52)!;
for (const data of [`;${b64('same')}`, `c;${b64('same')}`, `c;${b64('same')}`]) handler(data);
handler(`c;${b64('different')}`);
await flush();
expect(h.copied).toEqual(['same', 'different']);
expect(h.toasts).toHaveLength(2);
});
it('opens the manual-copy dialog only in the focused tab', async () => {
// Every tab watching the session receives the OSC 52; a background tab (a
// phone left on the session) must not pop a dialog for a copy made elsewhere.
const h = loadHarness(false, false);
h.app._installOsc52Clipboard(h.terminal);
h.handlers.get(52)!(`c;${b64('elsewhere')}`);
await flush();
expect(h.fallbacks).toEqual([]);
});
it('is wired into the main terminal and every TerminalTile', () => {
const read = (f: string) => readFileSync(resolve(import.meta.dirname, '../src/web/public', f), 'utf8');
expect(read('terminal-ui.js')).toContain('this._installOsc52Clipboard(this.terminal);');
@@ -123,3 +151,46 @@ describe('OSC 52 clipboard handler', () => {
);
});
});
describe('main-terminal replay over a real xterm', () => {
const osc52 = (text: string) => `\x1b]52;c;${b64(text)}\x07`;
async function replay(buffer: string) {
const h = loadHarness();
const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true, scrollback: 1000 });
h.app.terminal = term;
h.app._installOsc52Clipboard(term);
await h.app.chunkedTerminalWrite(buffer);
// Everything queued so far has been parsed once this callback fires.
await new Promise<void>((done) => term.write('', () => done()));
await flush();
return h;
}
it('does not re-copy an OSC 52 in a small (single-write) replay', async () => {
const h = await replay(`before\r\n${osc52('old copy')}after\r\n`);
expect(h.copied).toEqual([]);
});
it('does not re-copy an OSC 52 in the last chunk of a large replay', async () => {
const filler = 'x'.repeat(79) + '\r\n';
const history = filler.repeat(Math.ceil((100 * 1024) / filler.length));
const h = await replay(`${history}${osc52('recent copy')}tail\r\n`);
expect(h.copied).toEqual([]);
});
it('strips both BEL- and ST-terminated sequences and leaves the rest intact', () => {
const context = vm.createContext({ window: {}, globalThis: {} });
vm.runInContext(`${read('src/web/public/constants.js')}\nglobalThis.__re = OSC52_STRIP_RE;`, context);
const re = (context.globalThis as { __re: RegExp }).__re;
const input = `a\x1b]52;c;${b64('x')}\x07b\x1b]52;;${b64('y')}\x1b\\c\x1b]0;title\x07d`;
expect(input.replace(re, '')).toBe('abc\x1b]0;title\x07d');
});
it('still copies a live OSC 52 written after the replay', async () => {
const h = await replay('history\r\n');
await new Promise<void>((done) => h.app.terminal.write(osc52('live'), () => done()));
await flush();
expect(h.copied).toEqual(['live']);
});
});
+1
View File
@@ -40,6 +40,7 @@ function loadTerminalUiHarness() {
},
MobileDetection: { isTouchDevice: () => true },
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
TERMINAL_CHUNK_SIZE: 32 * 1024,
});
+1
View File
@@ -43,6 +43,7 @@ function loadTerminalUiHarness() {
},
},
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
OSC52_STRIP_RE: /\x1b\]52;[^\x07\x1b]*(?:\x07|\x1b\\)/g,
TERMINAL_CHUNK_SIZE: 32 * 1024,
});