Files
Codeman/test/codex-file-previews-setting.test.ts
Codeman maintainer 5f4951884f fix(web): the Codex in-pane file click is behind the Codex files setting too
Owner decision for 1.52.1: #850 left a click on a file name Codex
underlined in the pane ungated, so it opened the preview for everyone.
_handleDesktopTerminalClick() now asks _codexFilePreviewsEnabled() first;
off, every click in a Codex pane goes on to Codex as before (main
terminal, split pane and tiles share that handler). The setting now
gates four behaviours: the chip's tooltip (and its zh-CN), the wiki,
src/web/CLAUDE.md and the off-state test say so. The new test fails
without the gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:55:34 +01:00

226 lines
10 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// test/codex-file-previews-setting.test.ts
// Port: none (static analysis plus vm-loaded modules, runs in CI, no browser/server).
//
// `codexFilePreviewsEnabled` (App Settings > Header & Panels > Codex files) gates four
// behaviours together, per device, default OFF:
// 1. the Response files header button (never on phones, even when on),
// 2. taking a click on a file tab in Codex's own sidebar (and suppressing the
// ordinary linkifier on those rows),
// 3. the Dock control on file previews,
// 4. taking a click on a file name Codex underlined in the pane (owner decision for 1.52.1).
// With it off none of the four exists. Each surface's off-state behaviour is also
// pinned next to its own tests (response-viewer-file-links, terminal-link-provider-target,
// file-preview-window); this file pins the setting's own wiring and the off-state of all
// three through the real reader.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { performance } from 'node:perf_hooks';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const PUBLIC = join(HERE, '../src/web/public');
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
describe('codexFilePreviewsEnabled stays per-device: display key, stripped from the PUT, absent from the schema', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
it('is in the client-side displayKeys merge policy', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
expect(displayKeys).toContain("'codexFilePreviewsEnabled'");
});
it('is stripped out of the object saveAppSettings() PUTs and never declared in the .strict() schema', () => {
expect(settingsUi).toContain('codexFilePreviewsEnabled: _cfp,');
expect(schemas).not.toContain('codexFilePreviewsEnabled');
});
it('is loaded into and saved from its App Settings chip, default OFF', () => {
const index = read('index.html');
expect(index).toMatch(
/<label class="set-chip"[^>]*data-preview="header"[^>]*><input type="checkbox" id="appSettingsCodexFilePreviews">/
);
expect(settingsUi).toContain(
"document.getElementById('appSettingsCodexFilePreviews').checked = settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false;"
);
expect(settingsUi).toContain(
"codexFilePreviewsEnabled: document.getElementById('appSettingsCodexFilePreviews').checked,"
);
});
});
describe('with the Codex files setting off (nothing stored), none of the four behaviours exists', () => {
function loadApp() {
const { window } = new JSDOM(`<!doctype html>
<button id="responseFilesBtn" class="btn-icon-header btn-response-files btn-response-files--hidden" hidden></button>
<main class="main"><div class="terminal-wrap"><div id="terminalContainer"></div></div></main>
<div id="filePreviewOverlay" class="visible"><button id="filePreviewDockBtn" hidden aria-pressed="false"></button></div>`);
const { document } = window;
const fetchSpy = vi.fn();
const context = vm.createContext({
console: { ...console, debug: vi.fn(), log: vi.fn() },
performance,
setInterval: vi.fn(),
clearInterval: vi.fn(),
setTimeout,
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
fetch: fetchSpy,
AbortSignal,
document,
NodeFilter: window.NodeFilter,
// Nothing stored on this device: the setting reads its default.
localStorage: { length: 0, key: vi.fn(), getItem: () => null, setItem: vi.fn(), removeItem: vi.fn() },
window: {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
matchMedia: () => ({ matches: true }), // a wide desktop: docking would otherwise apply
__codemanCliCatalog: [{ id: 'codex', transcript: 'codex-rollout' }],
},
MobileDetection: { isHandheldDevice: () => false, isTouchDevice: () => false, getDeviceType: () => 'desktop' },
});
const addEventListener = vi.spyOn(document, 'addEventListener').mockImplementation(() => {});
try {
vm.runInContext(
['constants.js', 'app.js', 'settings-ui.js', 'panels-ui.js', 'terminal-ui.js'].map(read).join('\n') +
'\nglobalThis.__CodemanApp = CodemanApp;',
context
);
} finally {
addEventListener.mockRestore();
}
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.assign(Object.create(CodemanApp.prototype), {
$: (id: string) => document.getElementById(id),
activeSessionId: 'codex-1',
sessions: new Map([['codex-1', { mode: 'codex' }]]),
});
return { app, document, fetchSpy };
}
it('reads OFF from the real device settings with nothing stored', () => {
const { app } = loadApp();
expect(app._codexFilePreviewsEnabled()).toBe(false);
});
it('1. keeps the Response files button hidden in a Codex session', () => {
const { app, document } = loadApp();
app._syncResponseFilesButton();
expect(document.getElementById('responseFilesBtn')!.classList.contains('btn-response-files--hidden')).toBe(true);
});
it('2. takes no click on a Codex sidebar file tab', () => {
const { app } = loadApp();
const cols = 80;
const lines = [' '.repeat(42) + '│ Brief.docx × +', ' '.repeat(42) + '│ body'];
const terminal = {
cols,
buffer: {
active: {
viewportY: 0,
length: lines.length,
getLine: (row: number) =>
lines[row] === undefined
? undefined
: {
isWrapped: false,
getCell: (col: number) => ({
getChars: () => lines[row][col] ?? ' ',
getWidth: () => 1,
isUnderline: () => false,
}),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const text = lines[row].padEnd(cols).slice(start, end);
return trim ? text.trimEnd() : text;
},
},
},
},
};
app._clientPointToCell = (col: number, row: number) => ({ col, row });
expect(app._codexTerminalLinkLabel(terminal, 46, 1)).toBeNull();
app._codexFilePreviewsEnabled = () => true; // the same click, setting on: taken
expect(app._codexTerminalLinkLabel(terminal, 46, 1)).toMatchObject({ label: 'Brief.docx', sidebar: true });
});
it('3. never docks a preview', () => {
const { app, document } = loadApp();
const overlay = document.getElementById('filePreviewOverlay')!;
app.toggleFilePreviewDock();
app._setFilePreviewDocked(true);
expect(overlay.classList.contains('is-docked')).toBe(false);
expect(overlay.parentElement).toBe(document.body);
app._codexFilePreviewsEnabled = () => true; // the same call, setting on: docks
app._setFilePreviewDocked(true);
expect(overlay.classList.contains('is-docked')).toBe(true);
});
it('4. passes a click on a file name Codex underlined in the pane on to Codex', () => {
const { app } = loadApp();
const cols = 40;
const text = '• Word brief';
const terminal = {
cols,
modes: { mouseTrackingMode: 'none' },
hasSelection: () => false,
buffer: {
active: {
viewportY: 0,
length: 2,
getLine: (row: number) =>
row > 1
? undefined
: {
isWrapped: false,
getCell: (col: number) => ({
getChars: () => (row === 0 ? (text[col] ?? ' ') : ' '),
getWidth: () => 1,
isUnderline: () => row === 0 && col >= 2 && col < 12,
}),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const line = (row === 0 ? text : '').padEnd(cols).slice(start, end);
return trim ? line.trimEnd() : line;
},
},
},
},
};
app.terminal = terminal;
app._clientPointToCell = () => ({ col: 5, row: 1 });
app._shouldReportMouseToCli = () => true;
app._sendSyntheticSgrTap = vi.fn();
app._openCodexTerminalResponseFile = vi.fn().mockResolvedValue(undefined);
const click = { isTrusted: true, button: 0, detail: 1, clientX: 50, clientY: 10, target: { closest: () => ({}) } };
app._handleDesktopTerminalClick(click);
expect(app._openCodexTerminalResponseFile).not.toHaveBeenCalled();
expect(app._sendSyntheticSgrTap).toHaveBeenCalledTimes(1);
app._codexFilePreviewsEnabled = () => true; // the same click, setting on: looked up first
app._handleDesktopTerminalClick(click);
expect(app._openCodexTerminalResponseFile).toHaveBeenCalledTimes(1);
expect(app._openCodexTerminalResponseFile.mock.calls[0][3]).toMatchObject({ label: 'Word brief' });
expect(app._sendSyntheticSgrTap).toHaveBeenCalledTimes(1);
});
it('flips the Dock button of an open preview when the setting changes, not only at the next open', () => {
const { app, document } = loadApp();
const dockBtn = document.getElementById('filePreviewDockBtn')!;
app._codexFilePreviewsEnabled = () => true;
app.applyHeaderVisibilitySettings();
expect(dockBtn.hidden).toBe(false);
app._codexFilePreviewsEnabled = () => false;
app.applyHeaderVisibilitySettings();
expect(dockBtn.hidden).toBe(true);
});
it('keeps Response files off phones even with the setting on', () => {
const mobileCss = read('mobile.css');
const phoneBlock = mobileCss.slice(mobileCss.indexOf('@media (max-width: 599px)'));
expect(phoneBlock).toMatch(/\.btn-icon-header\.btn-response-files,[\s\S]*?display: none !important;/);
});
});