fix(preview): COD-152 address upstream review

This commit is contained in:
Aamer Akhter committed 2026-11-23 18:06:30 -05:00
1 parent ac4ab8cf23
commit b02816c1cc
13 files changed
+368 -53

No files matched your search

+105
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,107 @@ 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) {
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() },
});
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);
});
});
+2 -4
View File
@@ -34,7 +34,7 @@ const PHONE_WIDTH = 393;
// Its per-device setting still defaults off on a handheld. With the blanket phone
// hide gone, that default and the startup hide are the whole lock, so both are
// pinned below ("File Viewer on a phone: off until it is switched on").
// Response files is available once Codex links a file, and its preview floats on phones.
// Response files is currently available in Codex sessions, and its preview floats on phones.
const MOBILE_VISIBLE_ALLOWLIST = new Set<string>(['btn-file-viewer', 'btn-response-files']);
// Buttons we expect to STAY hidden on phones — an explicit lock so a future edit
@@ -220,9 +220,7 @@ describe('File Viewer on a phone: off until it is switched on (#759)', () => {
if (decl.value.trim() === 'none' && decl.important) hidesAtStartup = true;
});
});
expect(hidesAtStartup, 'mobile.css must keep .btn-file-viewer in its html.mobile-init display:none rule').toBe(
true
);
expect(hidesAtStartup, 'mobile.css must keep .btn-file-viewer in its html.mobile-init display:none rule').toBe(true);
});
});
+94 -15
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,15 +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;
}
@@ -349,17 +361,17 @@ describe('Codex response files', () => {
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/out/image.png) [PDF](file:///work/project/Export%20one.pdf)',
'[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',
{ workingDir: '/work/project' }
'codex-session'
);
const links = Array.from(body.querySelectorAll('a'));
@@ -368,7 +380,7 @@ describe('Codex response files', () => {
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/out/image.png', '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 }],
]);
});
@@ -377,7 +389,7 @@ describe('Codex response 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', { workingDir: '/work' });
app._renderResponseFiles(body, ['No files in this response.'], 'codex-session');
expect(body.textContent).toBe('No previewable files in the latest response.');
});
});
@@ -386,27 +398,28 @@ 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 = { workingDir: '/work/project' };
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/out/Word%20draft.docx).' },
{ role: 'assistant', text: 'Repeated [Word brief](file:///work/project/live/out/Word%20draft.docx).' },
],
'Word brief',
session
)
).toBe('/work/project/out/Word draft.docx');
).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 = { workingDir: '/work/project' };
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'
@@ -427,14 +440,30 @@ describe('Codex terminal response link matching', () => {
).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 = { workingDir: '/work/project' };
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/out/${name}`);
expect(app._findCodexResponseFile([exact, near], label, session, true)).toBe(`/work/project/live/out/${name}`);
expect(
app._findCodexResponseFile(
[
@@ -464,8 +493,58 @@ describe('Codex terminal response link matching', () => {
{ role: 'assistant', text: other },
],
'Word brief',
{ workingDir: '/work/project' }
'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;
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<HTMLAnchorElement>('#responseViewerBody a')?.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('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();
});
});
+86 -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,78 @@ 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;
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');
});
});
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();
}
);
});