Merge #850: Open Codex file links in a docked preview (COD-152)

This commit is contained in:
Codeman maintainer committed 2026-12-03 10:15:14 +01:00
commit ab5f197dcc
21 files changed
+1267 -34

No files matched your search

+167
View File
@@ -0,0 +1,167 @@
// 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 buttons > Codex files) gates three
// 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.
// With it off none of the three 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 three 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('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;/);
});
});
+131
View File
@@ -24,6 +24,7 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { describe, expect, it, vi } from 'vitest';
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
@@ -407,3 +408,133 @@ describe('file viewer on phones', () => {
expect(phone).toMatch(/#filePreviewExpandBtn,\s*\.file-preview-resize\s*\{\s*display: none;/);
});
});
describe('file preview dock lifecycle', () => {
function setup(layout: string, wide = true, codexFiles = true) {
const { window } = new JSDOM(`<!doctype html><main class="main ${layout}">
<div class="terminal-wrap"><div id="terminalContainer"></div></div>
</main><div id="filePreviewOverlay" class="visible">
<button id="filePreviewDockBtn" aria-pressed="false"></button>
</div>`);
const { document } = window;
const CodemanApp = function CodemanApp() {};
const context = vm.createContext({
CodemanApp,
document,
window: {
matchMedia: () => ({ matches: wide }),
innerWidth: 1400,
addEventListener: vi.fn(),
TerminalTile: class {
async connect() {}
destroy() {}
},
},
SPLIT_PANE_MIN_WIDTH: 1000,
});
vm.runInContext(panelsJs, context);
const splitJs = readFileSync(resolve(PUBLIC, 'terminal-split.js'), 'utf8');
vm.runInContext(splitJs, context);
const app = Object.assign(Object.create(CodemanApp.prototype), {
$: (id: string) => document.getElementById(id),
_resetFilePreviewEdit: vi.fn(),
_updateSplitButtonState: vi.fn(),
_buildSplitPaneHeader: () => ({ el: document.createElement('div') }),
_renderSplitChrome: vi.fn(),
_installSplitDividerDrag: vi.fn(),
activeSessionId: 'pane-a',
sessions: new Map([['pane-b', { pid: 1 }]]),
terminal: { focus: vi.fn() },
_codexFilePreviewsEnabled: () => codexFiles,
});
const overlay = document.getElementById('filePreviewOverlay')!;
const main = document.querySelector('.main')!;
const wrap = document.querySelector('.terminal-wrap')!;
const dockButton = document.getElementById('filePreviewDockBtn')!;
return { app, document, main, overlay, wrap, dockButton };
}
it('docks beside the terminal and returns to its original parent on close', () => {
const { app, document, main, overlay, wrap, dockButton } = setup('');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
expect(wrap.nextElementSibling).toBe(overlay);
expect(dockButton.getAttribute('aria-pressed')).toBe('true');
app.closeFilePreview();
expect(overlay.parentElement).toBe(document.body);
expect(overlay.classList.contains('visible')).toBe(false);
expect(dockButton.getAttribute('aria-pressed')).toBe('false');
});
it('handles Escape inside the dock and leaves terminal Escape alone', () => {
const { app, document, overlay, wrap, dockButton } = setup('');
app.toggleFilePreviewDock();
const escape = { target: wrap, preventDefault: vi.fn(), stopPropagation: vi.fn() };
expect(app._maybeCloseDockedFilePreviewOnEscape(escape)).toBe(false);
expect(escape.preventDefault).not.toHaveBeenCalled();
expect(overlay.classList.contains('visible')).toBe(true);
expect(app._maybeCloseDockedFilePreviewOnEscape({ ...escape, target: dockButton })).toBe(true);
expect(escape.preventDefault).toHaveBeenCalledOnce();
expect(escape.stopPropagation).toHaveBeenCalledOnce();
expect(app.terminal.focus).toHaveBeenCalledOnce();
expect(overlay.parentElement).toBe(document.body);
});
it('stays floating during a split and survives closing and reopening the preview', () => {
const { app, document, main, overlay } = setup('');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
app.openSplitPane('pane-b');
const split = document.querySelector('.terminal-split-container');
expect(split).not.toBeNull();
expect(overlay.parentElement).toBe(document.body);
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
app.closeSplitPane();
expect(split?.isConnected).toBe(false);
expect(overlay.isConnected).toBe(true);
app.closeFilePreview();
overlay.classList.add('visible');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
});
it.each([
['', false],
['tiles-active', true],
['webview-active', true],
])('stays floating when docking is unavailable (layout %s, wide %s)', (layout, wide) => {
const { app, document, overlay } = setup(layout, wide);
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
expect(app._isFilePreviewDocked()).toBe(false);
});
it('never docks while the Codex files setting is off', () => {
const { app, document, overlay } = setup('', true, false);
app.toggleFilePreviewDock();
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
expect(overlay.classList.contains('is-docked')).toBe(false);
expect(app._isFilePreviewDocked()).toBe(false);
});
it('sits in page flow when docked, under modals and the response viewer', () => {
// The floating overlay's z-index 5100 would put a docked pane above every
// modal backdrop (1000) and the response viewer sheet (5000).
const docked = stylesCss.match(
/\.main:not\(\.tiles-active, \.webview-active\) > \.file-preview-overlay\.is-docked \{([^}]*)\}/
);
expect(docked).not.toBeNull();
expect(docked![1]).toMatch(/z-index:\s*auto;/);
});
it('ships the Dock button hidden, and hidden means hidden at every width', () => {
expect(indexHtml).toMatch(/<button type="button" class="btn-icon-sm" id="filePreviewDockBtn" hidden/);
expect(stylesCss).toMatch(/#filePreviewDockBtn\[hidden\] \{\s*display: none !important;/);
expect(panelsJs).toContain('if (dockBtn) dockBtn.hidden = !this._codexFilePreviewsEnabled?.();');
});
});
+8 -1
View File
@@ -42,7 +42,14 @@ const MOBILE_VISIBLE_ALLOWLIST = new Set<string>(['btn-file-viewer']);
// it's excluded from the default-visible enumeration rather than mobile-hidden.
// The edit history button is opt-in the same way, but it IS here: its panel is
// desktop-sized, so it stays off phones even when the setting is on.
const KNOWN_PHONE_HIDDEN = ['btn-settings', 'btn-lifecycle-log', 'btn-session-manager', 'btn-edit-history'];
// Response files (Codex files setting) is opt-in too and likewise stays off phones.
const KNOWN_PHONE_HIDDEN = [
'btn-settings',
'btn-lifecycle-log',
'btn-session-manager',
'btn-edit-history',
'btn-response-files',
];
function attrOf(openTag: string, name: string): string {
const m = openTag.match(new RegExp(`${name}="([^"]*)"`));
+3 -1
View File
@@ -358,6 +358,7 @@ describe('WebServer.renderIndexHtml', () => {
order: number;
kind: string;
external: boolean;
transcript?: string;
enabled: boolean;
available: boolean;
}>;
@@ -366,6 +367,7 @@ describe('WebServer.renderIndexHtml', () => {
label: 'Codex',
kind: 'agent',
external: true,
transcript: 'codex-rollout',
});
// claude is `kind: 'agent'` too; `external` is what keeps its Respawn/Ralph options visible.
expect(catalog.find((entry) => entry.id === 'claude')).toMatchObject({ kind: 'agent', external: false });
@@ -373,7 +375,7 @@ describe('WebServer.renderIndexHtml', () => {
expect(
catalog.every((entry) =>
Object.keys(entry).every((key) =>
['id', 'label', 'shortBadge', 'order', 'kind', 'external', 'enabled', 'available'].includes(key)
['id', 'label', 'shortBadge', 'order', 'kind', 'external', 'transcript', 'enabled', 'available'].includes(key)
)
)
).toBe(true);
+244 -3
View File
@@ -30,6 +30,8 @@ import { describe, expect, it, vi } from 'vitest';
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
const { document, NodeFilter } = dom.window;
const fetchResponse = vi.fn();
function loadCodemanAppClass() {
const constants = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
@@ -42,14 +44,25 @@ function loadCodemanAppClass() {
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
fetch: vi.fn(),
fetch: fetchResponse,
document,
NodeFilter,
marked,
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
window: {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
__codemanCliCatalog: [{ id: 'custom-codex', transcript: 'codex-rollout' }],
},
MobileDetection: {},
});
vm.runInContext(`${constants}\n${source}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const terminalUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
const addEventListener = vi.spyOn(document, 'addEventListener').mockImplementation(() => {});
try {
vm.runInContext(`${constants}\n${source}\n${terminalUi}\nglobalThis.__CodemanApp = CodemanApp;`, context);
} finally {
addEventListener.mockRestore();
}
return (context as { __CodemanApp: { prototype: { _linkifyFilePaths(root: unknown): void } } }).__CodemanApp;
}
@@ -341,3 +354,231 @@ describe('response viewer file-path linkifier', () => {
expect(APP_SOURCE).toMatch(/openFilePreview\(target \|\| filePath, sessionId\)/);
});
});
describe('Codex response files', () => {
it('lists previewable files once and opens their encoded URI in the originating session', () => {
const app = Object.create(CodemanApp.prototype);
app._sanitizeHtml = (html: string) => html;
app.openFilePreview = vi.fn();
app.activeSessionId = 'another-session';
app.sessions = new Map([['codex-session', { workingDir: '/work/project', paneCwd: '/work/project/live' }]]);
const body = document.createElement('div');
app._renderResponseFiles(
body,
[
'[Word brief](</work/project/Brief %231.docx>)\n\n[Image](out/image.png)',
'[Duplicate](/work/project/live/out/image.png) [PDF](file:///work/project/Export%20one.pdf)',
'[Web](https://example.com/x.pdf) [Network](file://remote/share/x.pdf) [Code](src/app.ts)',
],
'codex-session'
);
const links = Array.from(body.querySelectorAll('button'));
expect(links.map((link) => link.textContent)).toEqual(['Word brief', 'Image', 'PDF']);
// Buttons, not <a href="#">: under <base href> a middle-click on "#" opened the app root.
expect(body.querySelector('a')).toBeNull();
expect(links.every((link) => link.type === 'button')).toBe(true);
expect(app.openFilePreview).not.toHaveBeenCalled();
for (const link of links) link.click();
expect(app.openFilePreview.mock.calls).toEqual([
['/work/project/Brief #1.docx', 'codex-session', null, { dock: true }],
['/work/project/live/out/image.png', 'codex-session', null, { dock: true }],
['/work/project/Export one.pdf', 'codex-session', null, { dock: true }],
]);
});
it('shows an empty state when the response contains no previewable files', () => {
const app = Object.create(CodemanApp.prototype);
app._renderMarkdown = renderChat;
const body = document.createElement('div');
app._renderResponseFiles(body, ['No files in this response.'], 'codex-session');
expect(body.textContent).toBe('No previewable files in the latest response.');
});
});
describe('Codex terminal response link matching', () => {
function appForTranscript() {
const app = Object.create(CodemanApp.prototype);
app._sanitizeHtml = (html: string) => html;
app.sessions = new Map([['codex-session', { workingDir: '/work/project', paneCwd: '/work/project/live' }]]);
return app;
}
it('uses the explicit destination behind an underlined label', () => {
const app = appForTranscript();
const session = 'codex-session';
expect(
app._findCodexResponseFile(
[
{ role: 'assistant', text: 'See [Word brief](<out/Word draft.docx>).' },
{ role: 'assistant', text: 'Repeated [Word brief](file:///work/project/live/out/Word%20draft.docx).' },
],
'Word brief',
session
)
).toBe('/work/project/live/out/Word draft.docx');
});
it('resolves a native sidebar filename only when its destination is unique', () => {
const app = appForTranscript();
const session = 'codex-session';
const message = { role: 'assistant', text: '[Preview image](file:///work/project/Image%20draft.png)' };
expect(app._findCodexResponseFile([message], 'Image draft.png', session, true)).toBe(
'/work/project/Image draft.png'
);
expect(
app._findCodexResponseFile(
[
message,
{
role: 'assistant',
text: '[Other](<out/Image draft.png>)',
},
],
'Image draft.png',
session,
true
)
).toBeNull();
});
it('renders only potential sidebar matches, including URI-encoded filenames', () => {
const app = appForTranscript();
const render = vi.spyOn(app, '_renderMarkdown');
const texts = [
'Unrelated message.',
'Only a prefix: Word',
'Only an extension: .docx',
'[Download](file:///work/Word%20draft.docx)',
];
const messages = texts.map((text) => ({ role: 'assistant', text }));
expect(app._findCodexResponseFile(messages, 'Word…draft.docx', 'codex-session', true)).toBe(
'/work/Word draft.docx'
);
expect(render).toHaveBeenCalledExactlyOnceWith(texts[3], { localFileLinks: true });
});
it('resolves an abbreviated native tab only when one path matches both visible ends', () => {
const app = appForTranscript();
const session = 'codex-session';
const name = 'Interview panel plan - requisition 2026943.docx';
const exact = { role: 'assistant', text: `[Download](<out/${name}>)` };
const near = { role: 'assistant', text: '[Wrong extension](<out/Interview draft 2026943.pdf>)' };
const label = 'Interview…26943.docx';
expect(app._findCodexResponseFile([exact, near], label, session, true)).toBe(`/work/project/live/out/${name}`);
expect(
app._findCodexResponseFile(
[
exact,
{
role: 'assistant',
text: '[Another draft](<other/Interview alternate 2026943.docx>)',
},
],
label,
session,
true
)
).toBeNull();
});
it.each([
'[Word brief](out/different.docx)',
'[Word brief](https://example.test/report.docx)',
'[Word brief](src/script.ts)',
])('declines an ambiguous label when another reference is %s', (other) => {
const app = appForTranscript();
expect(
app._findCodexResponseFile(
[
{ role: 'assistant', text: '[Word brief](out/report.docx)' },
{ role: 'assistant', text: other },
],
'Word brief',
'codex-session'
)
).toBeNull();
});
});
describe('response viewer modes', () => {
function setup(mode: string) {
document.body.innerHTML = `<div id="responseViewerBackdrop"></div><div id="responseViewer">
<h2 id="responseViewerTitle"></h2><button id="responseViewerMore" style="display:none"></button>
<div id="responseViewerBody"></div></div>`;
const app = Object.create(CodemanApp.prototype);
app.activeSessionId = 'session';
app.sessions = new Map([['session', { mode, workingDir: '/work', paneCwd: '/work/live' }]]);
app._sanitizeHtml = (html: string) => html;
app._buildResponseViewerMessage = () => document.createElement('div');
app._bindResponseViewerInteractions = vi.fn();
app.openFilePreview = vi.fn();
app.terminal = { focus: vi.fn() };
const focused = { focus: vi.fn() };
app._focusedPane = () => ({ terminal: focused });
app._shouldFocusTerminalForTabSwitch = () => true;
app._codexFilePreviewsEnabled = () => true;
fetchResponse.mockReset().mockResolvedValue({
ok: true,
json: async () => ({ data: { text: '[Plan](out/plan.docx)' } }),
});
return { app, focused };
}
it('restores More for a normal response without hasContext', async () => {
const { app } = setup('claude');
await app.toggleResponseViewer();
expect(document.querySelector<HTMLElement>('#responseViewerMore')?.style.display).toBe('');
});
it('opens the file picker for a registered rollout reader and returns focus to the originating pane', async () => {
const { app, focused } = setup('custom-codex');
await app.toggleResponseViewer(true);
expect(document.getElementById('responseViewer')?.dataset.filesOnly).toBe('true');
expect(document.getElementById('responseViewerTitle')?.textContent).toBe('Response files');
document.querySelector<HTMLButtonElement>('#responseViewerBody button')?.click();
expect(app.openFilePreview).toHaveBeenCalledWith('/work/live/out/plan.docx', 'session', null, { dock: true });
expect(focused.focus).toHaveBeenCalledOnce();
expect(app.terminal.focus).not.toHaveBeenCalled();
});
it('does not open the file picker while the Codex files setting is off', async () => {
const { app } = setup('custom-codex');
delete app._codexFilePreviewsEnabled; // the real reader: the device settings, default OFF
app.loadAppSettingsFromStorage = () => ({});
app.getDefaultSettings = () => ({});
expect(app._codexFilePreviewsEnabled()).toBe(false);
await app.toggleResponseViewer(true);
expect(fetchResponse).not.toHaveBeenCalled();
expect(document.getElementById('responseViewer')?.classList.contains('visible')).toBe(false);
});
it('hides the Response files button while the setting is off, even in a Codex session', () => {
const { app } = setup('custom-codex');
document.body.insertAdjacentHTML(
'beforeend',
'<button id="responseFilesBtn" class="btn-icon-header btn-response-files btn-response-files--hidden" hidden></button>'
);
const button = document.getElementById('responseFilesBtn')!;
app._codexFilePreviewsEnabled = () => false;
app._syncResponseFilesButton();
expect(button.classList.contains('btn-response-files--hidden')).toBe(true);
app._codexFilePreviewsEnabled = () => true;
app._syncResponseFilesButton();
expect(button.classList.contains('btn-response-files--hidden')).toBe(false);
expect(button.hidden).toBe(false);
app.activeSessionId = 'claude-session';
app._syncResponseFilesButton();
expect(button.hidden).toBe(true); // the setting alone never shows it outside a Codex session
});
it('closes the file picker without focusing an xterm when the keyboard is hidden', async () => {
const { app, focused } = setup('custom-codex');
app._shouldFocusTerminalForTabSwitch = () => false;
await app.toggleResponseViewer(true);
expect(app.closeResponseViewer()).toBe(true);
expect(focused.focus).not.toHaveBeenCalled();
expect(app.terminal.focus).not.toHaveBeenCalled();
});
});
+115 -4
View File
@@ -19,11 +19,13 @@ import { describe, expect, it, vi } from 'vitest';
type Link = { text: string; activate: (ev: unknown, text: string) => void; hover: () => void; leave: () => void };
type Provider = { provideLinks: (line: number, cb: (links: Link[] | undefined) => void) => void };
function loadHarness() {
function loadHarness(fetchResponse = vi.fn()) {
const CodemanApp = function CodemanApp(this: unknown) {};
const windowRef: Record<string, unknown> = {};
const context = vm.createContext({
window: windowRef,
AbortSignal,
fetch: fetchResponse,
document: {
body: { classList: { contains: () => false } },
activeElement: null,
@@ -48,20 +50,25 @@ function loadHarness() {
}
/** A one-screen xterm stand-in holding `lines`, recording every provider registered on it. */
function fakeTerminal(lines: string[]) {
function fakeTerminal(lines: string[], cols = 80) {
const providers: Provider[] = [];
return {
cols: 80,
cols,
providers,
registerLinkProvider: (p: Provider) => providers.push(p),
buffer: {
active: {
length: lines.length,
viewportY: 0,
getLine: (row: number) =>
row >= 0 && row < lines.length
? {
isWrapped: false,
translateToString: (trim?: boolean) => (trim === false ? lines[row].padEnd(80) : lines[row]),
getCell: (col: number) => ({ getChars: () => lines[row][col] ?? ' ', getWidth: () => 1 }),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const text = lines[row].padEnd(cols).slice(start, end);
return trim ? text.trimEnd() : text;
},
}
: undefined,
},
@@ -146,3 +153,107 @@ describe('registerFilePathLinkProvider with a target (a second pane)', () => {
expect(app.openFilePreview).toHaveBeenCalledWith('/tmp/a.pdf', 'second');
});
});
describe('native Codex sidebar files', () => {
const left = 'wrote /tmp/keep.png'.padEnd(42);
const tab = ' Brief…26943.docx × +';
const picker = ' › · Word draft.docx Project root';
function setupSidebar() {
const app = makeApp();
app._supportsCodexResponseFiles = () => true;
app._codexFilePreviewsEnabled = () => true;
const terminal = fakeTerminal([
left + '│' + tab,
' '.repeat(42) + '│ Open in sidebar',
' '.repeat(42) + '│ Files 1',
' '.repeat(42) + '│' + picker,
' '.repeat(42) + '│ body /tmp/normal.png',
]);
app.terminal = terminal;
app._clientPointToCell = (col: number, row: number) => ({ col, row });
return { app, terminal };
}
it('finds a shortened tab and a picker entry without claiming the close button or directory suffix', () => {
const { app, terminal } = setupSidebar();
expect(app._codexTerminalLinkLabel(terminal, 47, 1)).toMatchObject({ label: 'Brief…26943.docx', sidebar: true });
expect(app._codexTerminalLinkLabel(terminal, 44 + tab.indexOf('×'), 1)).toBeNull();
expect(app._codexTerminalLinkLabel(terminal, 52, 4)).toMatchObject({ label: 'Word draft.docx', sidebar: true });
expect(app._codexTerminalLinkLabel(terminal, 44 + picker.indexOf('Project'), 4)).toBeNull();
});
it('suppresses generic sidebar suffixes and preserves ordinary paths beside and below them', () => {
const { app } = setupSidebar();
const provider = app.registerFilePathLinkProvider();
expect(linksOn(provider, 1).map(({ text }) => text)).toEqual(['/tmp/keep.png']);
expect(linksOn(provider, 4)).toEqual([]);
expect(linksOn(provider, 5).map(({ text }) => text)).toEqual(['/tmp/normal.png']);
app._supportsCodexResponseFiles = () => false;
expect(linksOn(provider, 4).map(({ text }) => text)).toContain('draft.docx');
});
it('leaves sidebar rows to Codex while the Codex files setting is off', () => {
const { app, terminal } = setupSidebar();
app._codexFilePreviewsEnabled = () => false;
// No sidebar label is taken, so the click is forwarded to Codex as before.
expect(app._codexTerminalLinkLabel(terminal, 47, 1)).toBeNull();
expect(app._codexTerminalLinkLabel(terminal, 52, 4)).toBeNull();
// And the row keeps the ordinary linkifier's links, exactly as on master.
const provider = app.registerFilePathLinkProvider();
expect(linksOn(provider, 4).map(({ text }) => text)).toContain('draft.docx');
});
it('caches the parsed conversation per session until its next turn', async () => {
const fetchResponse = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { messages: [] } }) });
const app = loadHarness(fetchResponse);
const session = { status: 'idle', lastSubmitAt: 1 };
app.sessions = new Map([['pane', session]]);
await app._codexResponseMessages('pane');
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(1);
session.lastSubmitAt = 2; // a new turn
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(2);
session.status = 'busy'; // a growing rollout is never served from the cache
await app._codexResponseMessages('pane');
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(4);
});
});
describe('Codex response click fallback', () => {
const clicked = { label: 'Word draft.docx', row: 1, start: 42, end: 57, sidebar: true };
const point = { clientX: 40, clientY: 10 };
it.each(['failed load', 'no match', 'superseded click', 'moved cell', 'matched file'])(
'handles %s',
async (outcome) => {
const fetchResponse = vi.fn();
const app = loadHarness(fetchResponse);
const forward = vi.fn();
const terminal = fakeTerminal([]);
const match = vi.fn(() => (outcome === 'no match' ? null : '/work/Word draft.docx'));
app._findCodexResponseFile = match;
app._codexTerminalLinkLabel = () => (outcome === 'moved cell' ? { ...clicked, row: 2 } : clicked);
app._openResponseFile = vi.fn();
if (outcome === 'failed load') fetchResponse.mockRejectedValue(new Error('offline'));
else fetchResponse.mockResolvedValue({ ok: true, json: async () => ({ data: { messages: [] } }) });
await app._openCodexTerminalResponseFile(
terminal,
'pane',
point,
clicked,
() => outcome !== 'superseded click',
forward
);
expect(forward).toHaveBeenCalledTimes(Number(outcome === 'failed load' || outcome === 'no match'));
if (outcome === 'matched file') {
expect(app._openResponseFile).toHaveBeenCalledWith('/work/Word draft.docx', 'pane');
} else {
expect(app._openResponseFile).not.toHaveBeenCalled();
}
if (outcome === 'superseded click') expect(match).not.toHaveBeenCalled();
}
);
});
+46
View File
@@ -493,6 +493,52 @@ describe('terminal touch tap mouse guard', () => {
expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[<0;21;6M\x1b[<0;21;6m' }]);
});
it('desktop click: resolves a Codex label from underlined cells before forwarding mouse input', () => {
const { app } = loadTerminalUiHarness();
const session = { mode: 'codex', cliMouseTracking: true };
app.activeSessionId = 'sess-1';
app.sessions = new Map([['sess-1', session]]);
app.terminal = createTerminalGrid(['• Word brief', '', '› '], 2);
const getLine = app.terminal.buffer.active.getLine;
app.terminal.buffer.active.getLine = (row: number) => {
const line = getLine(row);
if (row !== 0) return line;
return {
...line,
translateToString: (_trim: boolean, start: number, end: number) => '• Word brief'.slice(start, end),
getCell: (column: number) => ({ getWidth: () => 1, isUnderline: () => column >= 2 && column < 12 }),
};
};
app._supportsCodexResponseFiles = () => true;
app._openCodexTerminalResponseFile = vi.fn().mockResolvedValue(undefined);
app._sendSyntheticSgrTap = vi.fn();
app._handleDesktopTerminalClick({
isTrusted: true,
button: 0,
detail: 1,
clientX: 40,
clientY: 10,
target: { closest: () => ({}) },
});
expect(app._openCodexTerminalResponseFile).toHaveBeenCalledWith(
app.terminal,
'sess-1',
{ clientX: 40, clientY: 10 },
{ label: 'Word brief', row: 1, start: 2, end: 12 },
expect.any(Function),
expect.any(Function)
);
expect(app._sendSyntheticSgrTap).not.toHaveBeenCalled();
// A double-click selects the word: its second click returns before it can supersede
// this one, so the selection it leaves is what makes the pending lookup stale.
const stillCurrent = app._openCodexTerminalResponseFile.mock.calls[0][4];
expect(stillCurrent()).toBe(true);
app.terminal.hasSelection = () => true;
expect(stillCurrent()).toBe(false);
});
it('desktop click: skips clicks that already have a meaning elsewhere', () => {
const { app } = loadTerminalUiHarness();
const sent: string[] = [];