diff --git a/docs/wiki/Working-With-Files.md b/docs/wiki/Working-With-Files.md index 10aeff5d..f2f2eff6 100644 --- a/docs/wiki/Working-With-Files.md +++ b/docs/wiki/Working-With-Files.md @@ -118,6 +118,11 @@ File paths in a session are links. That works in two places: render as underlined monospace links. A Markdown link whose target is a path (`[report](/tmp/run/report.json)`, the way Codex cites files) opens the same way. +Codex file links can open supported files in Codeman's preview. Use **Response files** to +browse files linked in the latest reply. A Codex sidebar file name also opens the preview +when it matches a single linked file. On a wide window with a single terminal, **Dock** +switches between a preview beside the terminal and a floating preview. + Clicking one opens it in the preview: images and PDFs render, video and audio play with a working scrub bar, documents convert, text shows inline, Markdown renders and HTML opens as a page. The exception is a plain text file (a log, `.txt`, `.json`, code) inside the workspace diff --git a/src/web/public/app.js b/src/web/public/app.js index a34b6cf4..6d4792d4 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -3211,9 +3211,11 @@ class CodemanApp { const backdrop = document.getElementById('responseViewerBackdrop'); viewer.classList.remove('visible'); if (backdrop) backdrop.classList.remove('visible'); - if (this.terminal) { + const terminal = this._responseViewerReturnTerminal; + this._responseViewerReturnTerminal = null; + if (terminal && terminal.element?.isConnected !== false && this._shouldFocusTerminalForTabSwitch()) { try { - this.terminal.focus(); + terminal.focus(); } catch { /* terminal may be detached mid-teardown */ } @@ -3221,14 +3223,35 @@ class CodemanApp { return true; } - _findCodexResponseFile(messages, label, session, sidebar = false) { + _supportsCodexResponseFiles(sessionId) { + const mode = this.sessions?.get(sessionId)?.mode; + return window.__codemanCliCatalog?.find((entry) => entry.id === mode)?.transcript === 'codex-rollout'; + } + + _findCodexResponseFile(messages, label, sessionId, sidebar = false) { const [prefix, suffix, ...extra] = sidebar ? label.split('…') : []; const abbreviated = Boolean(prefix && suffix && extra.length === 0); + const containsFilename = (text) => abbreviated ? text.includes(prefix) && text.includes(suffix) : text.includes(label); let match = null; for (const message of messages) { - if (message.role !== 'assistant' || typeof message.text !== 'string' || (!sidebar && !message.text.includes(label))) continue; + const { text } = message; + if (message.role !== 'assistant' || typeof text !== 'string') continue; + if (sidebar && !containsFilename(text)) { + // Markdown destinations can URI-encode the filename. Leave Markdown + // escapes and HTML entities to the renderer when present. + const decoded = text.replace(/(?:%[\da-f]{2})+/gi, (escapes) => { + try { + return decodeURIComponent(escapes); + } catch { + return escapes; + } + }); + if (!containsFilename(decoded) && !/\\[!-~]|&(?:#\w+|[a-z]+);/i.test(decoded)) continue; + } else if (!sidebar && !text.includes(label)) { + continue; + } const rendered = document.createElement('template'); - rendered.innerHTML = this._renderMarkdown(message.text, { localFileLinks: true }); + rendered.innerHTML = this._renderMarkdown(text, { localFileLinks: true }); const links = Array.from(rendered.content.querySelectorAll('a')).filter( (link) => sidebar || link.textContent.trim() === label ); @@ -3236,7 +3259,7 @@ class CodemanApp { this._linkifyFilePaths(rendered.content); for (const link of links) { - const path = resolveLinkedFilePath(link.dataset.path, session.workingDir); + const path = this._resolveLinkedFilePath(link.dataset.path, sessionId); if (sidebar) { const basename = path.split('/').pop(); // Codex preserves both ends of a filename when it shortens the tab. @@ -3257,11 +3280,12 @@ class CodemanApp { } _openResponseFile(path, sessionId) { - if (this.filePreviewEdit?.dirty && !confirm('Discard unsaved changes?')) return; + const discard = 'Discard unsaved changes?'; + if (this.filePreviewEdit?.dirty && !confirm(window.codemanT?.(discard) || discard)) return; return this.openFilePreview(path, sessionId, null, { dock: true }); } - _renderResponseFiles(body, responses, sessionId, session) { + _renderResponseFiles(body, responses, sessionId) { const list = document.createElement('ul'); const seen = new Set(); for (const response of responses) { @@ -3270,7 +3294,7 @@ class CodemanApp { this._linkifyFilePaths(rendered.content); for (const link of rendered.content.querySelectorAll('a.rv-path')) { if (link.dataset.folder) continue; - const path = resolveLinkedFilePath(link.dataset.path, session.workingDir); + const path = this._resolveLinkedFilePath(link.dataset.path, sessionId); if (!/^\/(?!\/)/.test(path) || !previewsInFileViewer(path) || seen.has(path)) continue; seen.add(path); const item = document.createElement('li'); @@ -3289,7 +3313,10 @@ class CodemanApp { } } if (seen.size) body.replaceChildren(list); - else body.textContent = 'No previewable files in the latest response.'; + else { + const empty = 'No previewable files in the latest response.'; + body.textContent = window.codemanT?.(empty) || empty; + } } async toggleResponseViewer(filesOnly = false) { @@ -3306,7 +3333,8 @@ class CodemanApp { if (!this.activeSessionId) return; const responseSessionId = this.activeSessionId; const session = this.sessions?.get?.(responseSessionId); - if (filesOnly && session?.mode !== 'codex') return; + if (filesOnly && !this._supportsCodexResponseFiles(responseSessionId)) return; + const returnTerminal = isOpen ? this._responseViewerReturnTerminal : this._focusedPane?.().terminal; const request = Symbol('response-viewer'); this._responseViewerRequest = request; try { @@ -3352,7 +3380,7 @@ class CodemanApp { const body = document.getElementById('responseViewerBody'); if (filesOnly) { const responses = turnMessages.length ? turnMessages.map((message) => message.text) : [lastResponse]; - this._renderResponseFiles(body, responses, responseSessionId, session); + this._renderResponseFiles(body, responses, responseSessionId); } else if (turnMessages.length > 0) { // The whole last turn, rendered exactly as the full view renders that // turn: one badge, then badge-less continuation segments. The same @@ -3383,13 +3411,14 @@ class CodemanApp { const title = document.getElementById('responseViewerTitle'); const moreBtn = document.getElementById('responseViewerMore'); viewer.dataset.filesOnly = String(filesOnly); - if (title) title.textContent = filesOnly ? 'Response files' : 'Last Response'; + const titleText = filesOnly ? 'Response files' : 'Last Response'; + if (title) title.textContent = window.codemanT?.(titleText) || titleText; if (moreBtn) { - moreBtn.style.display = data.hasContext ? '' : 'none'; - moreBtn.textContent = 'More'; + moreBtn.style.display = ''; + moreBtn.textContent = window.codemanT?.('More') || 'More'; } - // Last Response is a single rendered block, not a transcript — no filters here. + this._responseViewerReturnTerminal = returnTerminal; viewer.classList.add('visible'); backdrop.classList.add('visible'); // A multi-row turn opens at its NEWEST text, matching loadFullContext's @@ -3401,7 +3430,8 @@ class CodemanApp { } catch (err) { console.error('Failed to load response:', err); if (filesOnly && this._responseViewerRequest === request && this.activeSessionId === responseSessionId) { - this.showToast('Unable to load response files', 'error'); + const message = 'Unable to load response files'; + this.showToast(window.codemanT?.(message) || message, 'error'); } } } @@ -6572,7 +6602,7 @@ class CodemanApp { renderSessionTabs({ immediate = false } = {}) { const responseFilesButton = this.$('responseFilesBtn'); - if (responseFilesButton) responseFilesButton.hidden = this.sessions.get(this.activeSessionId)?.mode !== 'codex'; + if (responseFilesButton) responseFilesButton.hidden = !this._supportsCodexResponseFiles(this.activeSessionId); // Don't re-render while user is typing in the inline rename input if (this._inlineRenameActive) return; if (immediate) { diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 5b768a14..29b34076 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -244,6 +244,12 @@ 'No response yet — send a message in this session first.': '暂无回复,请先在此会话中发送一条消息。', 'No full conversation history available for this session': '此会话没有可显示的完整对话历史', 'Last Response': '最近一次回复', + 'Response files': '回复中的文件', + 'Open Codex response files': '打开 Codex 回复中的文件', + 'Dock preview': '停靠预览', + 'No previewable files in the latest response.': '最新回复中没有可预览的文件。', + 'Unable to load response files': '无法加载回复中的文件', + 'Discard unsaved changes?': '放弃未保存的更改?', More: '更多', 'Copy Markdown': '复制 Markdown', 'Copy response as Markdown': '将回复复制为 Markdown', diff --git a/src/web/public/panels-ui.js b/src/web/public/panels-ui.js index ad356c7a..04d25cf2 100644 --- a/src/web/public/panels-ui.js +++ b/src/web/public/panels-ui.js @@ -3762,10 +3762,16 @@ Object.assign(CodemanApp.prototype, { _setFilePreviewDocked(dock) { const overlay = this.$('filePreviewOverlay'); - if (!overlay || dock === overlay.classList.contains('is-docked')) return; + if (!overlay) return; + const terminalWrap = this.$('terminalContainer')?.closest('.terminal-wrap'); + dock = Boolean( + dock && + terminalWrap?.parentElement?.matches('.main:not(.tiles-active, .webview-active)') && + window.matchMedia?.('(min-width: 1180px)').matches + ); + if (dock === overlay.classList.contains('is-docked')) return; if (dock) { - const terminalWrap = this.$('terminalContainer')?.closest('.terminal-wrap'); - if (!terminalWrap || !overlay.parentElement) return; + if (!overlay.parentElement) return; this._filePreviewOverlayHome = overlay.parentElement; terminalWrap.after(overlay); } else { diff --git a/src/web/public/settings-ui.js b/src/web/public/settings-ui.js index 8a9f9c76..5d6d9c32 100644 --- a/src/web/public/settings-ui.js +++ b/src/web/public/settings-ui.js @@ -4179,8 +4179,7 @@ Object.assign(CodemanApp.prototype, { /** Keep the launch surfaces in sync with Settings mutations without a reload. */ _syncCliLaunchCatalog() { if (!Array.isArray(this._cliList) || this._cliList.length === 0) return; - // /api/clis rows carry no capabilities, so keep the served catalog's `external` - // (isExternalCliSession() reads it). A new custom CLI has none and falls back to `kind`. + // /api/clis rows carry no capabilities, so retain them from the served catalog. const previous = new Map( (Array.isArray(window.__codemanCliCatalog) ? window.__codemanCliCatalog : []).map((cli) => [cli.id, cli]) ); @@ -4191,6 +4190,7 @@ Object.assign(CodemanApp.prototype, { order: cli.order, kind: cli.kind, external: previous.get(cli.id)?.external, + transcript: previous.get(cli.id)?.transcript, enabled: cli.enabled, available: cli.kind === 'shell' || (cli.enabled && cli.installed), })); diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 836b81f7..8786ceb2 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -13647,7 +13647,7 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat } #responseFilesBtn[hidden], -.response-viewer[data-files-only='true'] :is(#responseViewerMore, #responseViewerCopy, #responseViewerCopyMarkdown) { +.response-viewer[data-files-only='true'] :is(#responseViewerMore, #responseViewerCopyMarkdown) { display: none !important; } diff --git a/src/web/public/terminal-split.js b/src/web/public/terminal-split.js index 2b41376f..f545ba9a 100644 --- a/src/web/public/terminal-split.js +++ b/src/web/public/terminal-split.js @@ -207,6 +207,7 @@ Object.assign(CodemanApp.prototype, { headerA.el.classList.add('terminal-pane-a-header'); this._splitHeaders = { a: headerA, b: headerB }; + this._setFilePreviewDocked?.(false); parent.insertBefore(container, wrap); wrap.insertBefore(headerA.el, wrap.firstChild); container.appendChild(wrap); diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 07eb7fe2..faf9c72f 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -2553,7 +2553,7 @@ Object.assign(CodemanApp.prototype, { } } - if (self.sessions?.get(getSessionId())?.mode === 'codex') { + if (self._supportsCodexResponseFiles?.(getSessionId())) { const sidebar = codexSidebarFileRow(terminal, bufferLineNumber - 1); if (sidebar) { const lineEnd = bufferLineNumber * terminal.cols + terminal.cols; @@ -6569,7 +6569,7 @@ Object.assign(CodemanApp.prototype, { return label && label.length <= 240 ? { label, row, start, end } : null; }, - async _openCodexTerminalResponseFile(terminal, sessionId, session, point, clicked, stillCurrent, forward) { + async _openCodexTerminalResponseFile(terminal, sessionId, point, clicked, stillCurrent, forward) { let path; try { const response = await fetch(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`, { @@ -6577,7 +6577,10 @@ Object.assign(CodemanApp.prototype, { }); if (response.ok) { const { data } = await response.json(); - if (Array.isArray(data?.messages)) path = this._findCodexResponseFile(data.messages, clicked.label, session, clicked.sidebar); + if (!stillCurrent()) return; + if (Array.isArray(data?.messages)) { + path = this._findCodexResponseFile(data.messages, clicked.label, sessionId, clicked.sidebar); + } } } catch { // Preserve the native click if the transcript cannot be resolved. @@ -6620,7 +6623,6 @@ Object.assign(CodemanApp.prototype, { if (performance.now() <= (this._trustedTapMouseSuppressUntil || 0)) return; if (!ev.target?.closest?.('.xterm-screen')) return; const sessionId = target.sessionId || this.activeSessionId; - const session = this.sessions?.get(sessionId); const { clientX, clientY } = ev; const forward = () => { if (this._shouldReportMouseToCli(sessionId)) this._sendSyntheticSgrTap(clientX, clientY, target); @@ -6628,7 +6630,7 @@ Object.assign(CodemanApp.prototype, { this._codexTerminalLinkClicks ??= new WeakMap(); const click = Symbol(); this._codexTerminalLinkClicks.set(terminal, click); - const link = session?.mode === 'codex' && this._codexTerminalLinkLabel(terminal, clientX, clientY); + const link = this._supportsCodexResponseFiles?.(sessionId) && this._codexTerminalLinkLabel(terminal, clientX, clientY); if (!link) { forward(); return; @@ -6637,7 +6639,7 @@ Object.assign(CodemanApp.prototype, { const stillCurrent = () => this._codexTerminalLinkClicks.get(terminal) === click && (target.sessionId ? terminal.element?.isConnected : this.activeSessionId === sessionId && this.terminal === terminal); - void this._openCodexTerminalResponseFile(terminal, sessionId, session, { clientX, clientY }, link, stillCurrent, forward) + void this._openCodexTerminalResponseFile(terminal, sessionId, { clientX, clientY }, link, stillCurrent, forward) .catch((error) => console.error('Unable to open Codex terminal response file:', error)); }, diff --git a/src/web/server.ts b/src/web/server.ts index 289a8a50..923741dd 100644 --- a/src/web/server.ts +++ b/src/web/server.ts @@ -2094,6 +2094,7 @@ export class WebServer extends EventEmitter { order: entry.order, kind: entry.kind, external: entry.capabilities.external, + transcript: entry.capabilities.transcript, enabled, available: enabled && installed, }; diff --git a/test/file-preview-window.test.ts b/test/file-preview-window.test.ts index d69a1cf0..b2a431f6 100644 --- a/test/file-preview-window.test.ts +++ b/test/file-preview-window.test.ts @@ -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(`
+
+
+ +
`); + 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); + }); +}); diff --git a/test/mobile-header-buttons-policy.test.ts b/test/mobile-header-buttons-policy.test.ts index 8ab13774..c114db36 100644 --- a/test/mobile-header-buttons-policy.test.ts +++ b/test/mobile-header-buttons-policy.test.ts @@ -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(['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); }); }); diff --git a/test/response-viewer-file-links.test.ts b/test/response-viewer-file-links.test.ts index 7b642932..36d0d41b 100644 --- a/test/response-viewer-file-links.test.ts +++ b/test/response-viewer-file-links.test.ts @@ -30,6 +30,8 @@ import { describe, expect, it, vi } from 'vitest'; const dom = new JSDOM(''); 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]()\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]().' }, - { 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]()` }; const near = { role: 'assistant', text: '[Wrong extension]()' }; 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 = `
+

+
`; + 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('#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('#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(); + }); +}); diff --git a/test/terminal-link-provider-target.test.ts b/test/terminal-link-provider-target.test.ts index ce70fbf2..230c43ce 100644 --- a/test/terminal-link-provider-target.test.ts +++ b/test/terminal-link-provider-target.test.ts @@ -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 = {}; 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(); + } + ); +});