From e3c156e6e865441405754a6d48c1ade1b3e935d5 Mon Sep 17 00:00:00 2001 From: Aamer Akhter Date: Fri, 27 Nov 2026 12:58:48 -0500 Subject: [PATCH] fix(preview): COD-152 put Codex file extras behind a per-device setting The Response files header button, taking a click on a Codex sidebar file tab (and the link suppression on those rows) and the Dock control on file previews now sit behind one per-device setting, codexFilePreviewsEnabled (App Settings > Header buttons > Codex files), default off. With it off none of the three exists, and Response files stays off phones even with it on. Also from the second review: the docked preview is z-index auto so it sits under modals and the response viewer, a double-click no longer opens the preview, the parsed conversation is cached per idle session until its next turn, the Response files rows are buttons, and the two tests that failed at the previous head pass. Documented in Settings-Reference, Working-With-Files and src/web/CLAUDE.md. --- docs/architecture-invariants.md | 2 +- docs/wiki/Settings-Reference.md | 10 +- docs/wiki/Working-With-Files.md | 11 +- src/web/CLAUDE.md | 4 +- src/web/public/app.js | 38 ++++- src/web/public/i18n.js | 3 + src/web/public/index.html | 7 +- src/web/public/mobile.css | 3 + src/web/public/panels-ui.js | 5 + src/web/public/settings-ui.js | 12 +- src/web/public/styles.css | 22 +++ src/web/public/terminal-ui.js | 50 ++++-- test/codex-file-previews-setting.test.ts | 167 +++++++++++++++++++++ test/file-preview-window.test.ts | 28 +++- test/mobile-header-buttons-policy.test.ts | 12 +- test/render-index-html.test.ts | 4 +- test/response-viewer-file-links.test.ts | 38 ++++- test/terminal-link-provider-target.test.ts | 29 ++++ test/terminal-touch-tap.test.ts | 8 +- 19 files changed, 416 insertions(+), 37 deletions(-) create mode 100644 test/codex-file-previews-setting.test.ts diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index a10b1f72..e04abc10 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -1345,7 +1345,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u ### Z-index layers -**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the chat opened BEHIND the chat), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it). +**Z-index layers**: subagent windows (1000), split picker menu (1000, `.split-picker-menu`), Tiles count menu (1000, `.tile-count-menu`), the closing grid's still copy (`.tile-grid-ghosts`, z-index 3 inside `.main`, over the single view coming back; hidden under `.main.webview-active`), mobile/tablet fixed header (1200, `mobile.css`), modals on ≤768px (1300 — must beat the fixed header or the modal close button is buried), log viewers (2000), connection-loss overlay (2500, above the fixed header and modals), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, `#folderGridOverlay` — above the response viewer a folder link opens it from, below the file preview its tiles open, so a tile's preview and its ←/→ paging sit on top of the grid), file-preview overlay (5100 — must outrank the response viewer, which can launch it; at its old 2000 a path clicked in the chat opened BEHIND the chat; DOCKED beside the terminal (the Codex files setting) it is `z-index: auto`, page content, since with nothing above it making a stacking context its 5100 would sit over every modal backdrop and the response viewer sheet), toasts/path picker (10000+, deliberately above the preview), the custom-model center-status banner (10001, `.center-status-banner` — `[hidden]` must re-assert `display: none` over its own `display: flex`, same trap as `.home-sessions[hidden]`, or `dismiss()` leaves an invisible click-blocker dead centre on screen), the swap-confirm and context-warning modals (10010, `#customModelSwapConfirmModal`/`#customModelContextWarningModal` — must clear both the plain `.modal` z-index of 1000 and the center-status banner it can appear over), terminal touch-selection bar (900 — above terminal content and the local-echo overlay, deliberately BELOW floating agent windows so it can never cover their controls), local echo overlay (7), iOS IME composition preview (EFFECTIVE layer depends on its home: with local echo on it is part of the local echo overlay at 7, drawn by `setComposition()` as an underlined tail after the pending text; with local echo off it is a span at z-index 6 inside `.xterm-helpers`, but `.xterm-helpers` is its own z-index 5 stacking context, so the span's effective layer is 5. That is below the overlay's 7, which is why the span cannot be used while the overlay holds text: typed text never reaches the PTY before Enter, the PTY cursor that places the span stays at the prompt start, and the overlay's opaque line div covers it). ## Security layers diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 5bfd53a2..9870af96 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -62,11 +62,19 @@ non-updatable. See [Running As A Service](Running-As-A-Service). Chips for every optional header control, with a live preview of the resulting header: -Run, Font Size, System Stats, Redraw Terminal, Response Viewer, Away Digest, Session +Run, Font Size, System Stats, Redraw Terminal, Response Viewer, Codex files, Away Digest, Session Manager, Attachments, Edit history, File Viewer, Multi-monitor, Split, Tiles, Plan Usage, Lifecycle Log, Monitor, Project Insights, File Browser, Subagents, Approvals Inbox, Read My Mind, Ultracode Agents, Ultracode Windows, Cron. +**Codex files** (off by default, per device) switches on three extras for Codex sessions, together: +a **Response files** header button that lists the previewable files linked in the latest reply +(desktop only: phones keep File Viewer as their one header button, even with this on), a click on a +file name in Codex's own sidebar opening that file in the preview when it matches a single linked +file (off, the click goes to Codex), and a **Dock** button on file previews that, on a window 1180px +or wider with a single terminal, docks the preview beside the terminal. With it off none of the three +exists. Clicking a file name Codex underlined in the pane opens the preview either way. + **Host readings** (opt-in, both off by default and per device): **GPU Stats** adds three items after CPU and MEM: GPU load, graphics memory and the GPU clock, and **CPU MHz** adds the live CPU clock. Both sets of items live inside **System Stats**, so they show only while that chip is on, and nothing is fetched while it is off. An item appears only when the diff --git a/docs/wiki/Working-With-Files.md b/docs/wiki/Working-With-Files.md index f2f2eff6..6f716b6c 100644 --- a/docs/wiki/Working-With-Files.md +++ b/docs/wiki/Working-With-Files.md @@ -118,10 +118,13 @@ 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. +In a Codex session, clicking a file name Codex underlined opens it in Codeman's preview +when it names a single supported file from the conversation; anything else goes to Codex as +before. The **Codex files** setting (App Settings > Header buttons, per device, off by +default) adds three more: a **Response files** header button that lists the files linked in +the latest reply (desktop only), a file name in Codex's own sidebar opening the preview when it +matches a single linked file, and a **Dock** button that, on a wide window with a single +terminal, switches between a preview beside the terminal and a floating one. 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 diff --git a/src/web/CLAUDE.md b/src/web/CLAUDE.md index 5260666a..bf4e6fbe 100644 --- a/src/web/CLAUDE.md +++ b/src/web/CLAUDE.md @@ -94,6 +94,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L **SSE staleness watchdog** (`computeSseStale()` in constants.js, `_checkSseStale()` + a 5s interval in app.js): an `EventSource` can stop delivering without erroring, so the client forces a reconnect when nothing arrives. ⚠️ The server keepalive must stay the named `sse:heartbeat` event (`cleanupDeadClients()`, sse-stream-manager.ts), never an SSE comment, which `EventSource` cannot observe; its no-op client listener must stay registered. ⚠️ Judge staleness only while `connected` and online (the loop breaker). ⚠️ The liveness stamp lives inside `addListener`. ⚠️ Clear the interval only at the top of `connectSSE()`, or intervals stack. ⚠️ The watchdog cannot see an attempt that never OPENS (no response headers: no `open`, no `error`, never `connected`), so each attempt is bounded by `SSE_CONNECT_TIMEOUT_MS` (15s, `CodemanSseStale.CONNECT_TIMEOUT_MS`) and then retried through `_handleSseConnectionFailure()`, the same backoff `onerror` uses. Its timer is cleared at the top of `connectSSE()` BEFORE the offline early return, on `open`, and in `_handleSseConnectionFailure()`; the timer and the handler both ignore an `EventSource` that has been replaced. The window `offline` handler leaves it running on purpose (`navigator.onLine` can report offline on a working network). Tests: `test/sse-connect-timeout.test.ts`. → [architecture-invariants#sse-staleness-watchdog](../../docs/architecture-invariants.md#sse-staleness-watchdog) -**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers) +**Codex file previews** (`codexFilePreviewsEnabled`, App Settings > Header buttons > Codex files, per-device display key, absent from `SettingsUpdateSchema`, default OFF; `_codexFilePreviewsEnabled()` in app.js is the ONE reader): a session whose CLI publishes `transcript: 'codex-rollout'` opens the files Codex links in the file preview. The served CLI catalog (`window.__codemanCliCatalog`, server.ts) carries `transcript` for that check (`_supportsCodexResponseFiles()`), never a CLI id, and `_syncCliLaunchCatalog()` keeps it across a Settings refresh. A click on an underlined label in the pane is resolved against the conversation (`last-response?context=full`, cached per session while idle until the next `lastSubmitAt`, `_codexResponseMessages()`) and opens only a single, unambiguous, previewable file, else it is forwarded to Codex as before; this part is not behind the setting. Behind it are three things, all absent while it is off: the Response files header button (`toggleResponseViewer(true)`; marker `btn-response-files--hidden` for the setting, `hidden` for the capability, and `mobile.css` hides it on phones regardless, pinned by `test/mobile-header-buttons-policy.test.ts`), the Codex SIDEBAR file tabs (`codexSidebarFileRow()` in terminal-ui.js: with the setting on, `registerFilePathLinkProvider` drops its links on those rows, which are Codex chrome, and a click there is taken by `_codexTerminalLinkLabel()`; off, the row keeps its ordinary links and its click reaches Codex), and the Dock control. ⚠️ Docking MOVES `#filePreviewOverlay` out of its home and after `.terminal-wrap` (`_setFilePreviewDocked()`), only when the wrap is a direct child of `.main` without `.tiles-active`/`.webview-active` and the window is 1180px or wider; otherwise the preview floats. It moves back on close, on Escape inside it, when a split opens (`openSplitPane()` undocks first, or `closeSplitPane()` would remove the overlay with the split container) and when the setting is switched off. Tests: `test/codex-file-previews-setting.test.ts` (off-state of all three), `test/response-viewer-file-links.test.ts`, `test/terminal-link-provider-target.test.ts`, `test/terminal-touch-tap.test.ts`, `test/file-preview-window.test.ts`. + +**Z-index layers** (keep new overlays consistent with this stack): local echo overlay (7; with local echo on it also draws the iOS IME composition preview, as an underlined tail after its pending text via `setComposition`), iOS IME composition preview span when local echo is off (6 inside `.xterm-helpers`, whose own z-index 5 is its EFFECTIVE layer, so it sits UNDER the overlay and must never be used while the overlay shows text), terminal touch-selection bar (900, below floating agent windows), subagent windows + split picker menu + Tiles count menu (1000), mobile/tablet fixed header (1200), modals on ≤768px (1300, must beat the fixed header), log viewers (2000), connection-loss overlay (2500), image popups (3000), response viewer (5000, backdrop 4999), folder grid (5090, above the response viewer it opens from, below the file preview its tiles open), file-preview overlay (5100, must outrank the response viewer that launches it; DOCKED it is `z-index: auto`, page content beside the terminal, so it sits under every modal and the response viewer, pinned in `test/file-preview-window.test.ts`), toasts/path picker (10000+), custom-model center-status banner (10001; its `[hidden]` must re-assert `display: none` or `dismiss()` leaves an invisible click-blocker), custom-model swap-confirm/context-warning modals (10010). → [architecture-invariants#z-index-layers](../../docs/architecture-invariants.md#z-index-layers) **Keyboard shortcuts**: Escape (close), Ctrl+? (shortcut overlay), Ctrl/Cmd/Alt+K (session palette), Ctrl+Tab (next), Alt+[/] (prev/next tab), Alt+1-9 (switch tab), Ctrl+Shift+{/} (move tab left/right), Shift+Enter or Ctrl+Enter (newline), Ctrl+C (copy selection, else interrupt) / Ctrl+Shift+C (copy, never interrupts), Ctrl+L (clear), Ctrl+Shift+R (restore size), Ctrl+Shift+V (voice input), Ctrl/Cmd +/- (font), Shift+Wheel (local scrollback when mouse passthrough is active), Shift+drag (start a selection in a stripped-DECSET pane, where xterm's own Shift branch is unreachable and a Shift+drag used to select nothing; `_installShiftDragSelection`), right-click (copy the selection, the mintty/PuTTY convention, since xterm paints into a canvas and the native menu has no Copy for it; with nothing selected the native menu is left alone). Rebindable via the registry. ⚠️ **Ctrl+W is deliberately NOT bound** (owner decision): it is delete-word in every shell and agent CLI, and as Close Session it killed sessions with no confirm; `close-session` keeps `bindings: []` and stays bindable (`test/ctrl-w-never-closes.test.ts`). diff --git a/src/web/public/app.js b/src/web/public/app.js index 6d4792d4..5abd58bb 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -3228,6 +3228,31 @@ class CodemanApp { return window.__codemanCliCatalog?.find((entry) => entry.id === mode)?.transcript === 'codex-rollout'; } + /** + * Per-device opt-in (`codexFilePreviewsEnabled`, App Settings > Header buttons > Codex files), + * default OFF. It gates the three Codex file-preview extras together: the Response files header + * button, taking a click on a file tab in Codex's own sidebar (and the link suppression on those + * rows), and the Dock control on file previews. With it off none of them exists and sidebar clicks + * reach Codex as before. + */ + _codexFilePreviewsEnabled() { + const settings = this.loadAppSettingsFromStorage?.() || {}; + const defaults = this.getDefaultSettings?.() || {}; + return (settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false) === true; + } + + /** + * The Response files button shows only with the setting on (its --hidden marker; phones keep it + * hidden via mobile.css regardless) AND in a session whose CLI publishes a Codex rollout + * transcript (the `hidden` attribute). + */ + _syncResponseFilesButton() { + const button = document.getElementById('responseFilesBtn'); + if (!button) return; + button.classList.toggle('btn-response-files--hidden', !this._codexFilePreviewsEnabled()); + button.hidden = !this._supportsCodexResponseFiles(this.activeSessionId); + } + _findCodexResponseFile(messages, label, sessionId, sidebar = false) { const [prefix, suffix, ...extra] = sidebar ? label.split('…') : []; const abbreviated = Boolean(prefix && suffix && extra.length === 0); @@ -3287,6 +3312,7 @@ class CodemanApp { _renderResponseFiles(body, responses, sessionId) { const list = document.createElement('ul'); + list.className = 'response-files-list'; const seen = new Set(); for (const response of responses) { const rendered = document.createElement('template'); @@ -3298,9 +3324,10 @@ class CodemanApp { if (!/^\/(?!\/)/.test(path) || !previewsInFileViewer(path) || seen.has(path)) continue; seen.add(path); const item = document.createElement('li'); - const action = document.createElement('a'); - action.href = '#'; - action.className = 'rv-path rv-path-link'; + // A button, not : under a middle-click on "#" opens the app root. + const action = document.createElement('button'); + action.type = 'button'; + action.className = 'response-files-item'; action.textContent = link.textContent.trim() || path.split('/').pop(); action.title = path; action.addEventListener('click', (event) => { @@ -3333,7 +3360,7 @@ class CodemanApp { if (!this.activeSessionId) return; const responseSessionId = this.activeSessionId; const session = this.sessions?.get?.(responseSessionId); - if (filesOnly && !this._supportsCodexResponseFiles(responseSessionId)) return; + if (filesOnly && !(this._codexFilePreviewsEnabled() && this._supportsCodexResponseFiles(responseSessionId))) return; const returnTerminal = isOpen ? this._responseViewerReturnTerminal : this._focusedPane?.().terminal; const request = Symbol('response-viewer'); this._responseViewerRequest = request; @@ -6601,8 +6628,7 @@ class CodemanApp { // ═══════════════════════════════════════════════════════════════ renderSessionTabs({ immediate = false } = {}) { - const responseFilesButton = this.$('responseFilesBtn'); - if (responseFilesButton) responseFilesButton.hidden = !this._supportsCodexResponseFiles(this.activeSessionId); + this._syncResponseFilesButton(); // 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 29b34076..5434c95d 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -487,6 +487,9 @@ 'CPU MHz': 'CPU 频率', 'Lifecycle Log': '生命周期日志', 'Response Viewer': '回复查看器', + 'Codex files': 'Codex 文件', + 'Codex sessions: a Response files header button, Codex sidebar file tabs open in the preview, and a Dock control on file previews': + 'Codex 会话:标题栏的回复中的文件按钮、在预览中打开 Codex 侧边栏文件标签,以及文件预览上的停靠控件', 'Attachments Button': '附件按钮', 'Multi-monitor Button': '多显示器按钮', 'Session Manager Button': '会话管理器按钮', diff --git a/src/web/public/index.html b/src/web/public/index.html index ea33beb5..14fe1080 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -206,7 +206,7 @@ - + - + @@ -2241,13 +2241,14 @@

Header buttons

device

Tap to show a control in the header. Multi-monitor is the one entry here that syncs across devices.

-
+
+ diff --git a/src/web/public/mobile.css b/src/web/public/mobile.css index c6e56676..15a14892 100644 --- a/src/web/public/mobile.css +++ b/src/web/public/mobile.css @@ -593,6 +593,9 @@ html.mobile-init .file-browser-panel { .btn-icon-header.btn-session-manager, /* Edit history: a desktop panel; phones never show the button (opt-in, default OFF anyway). */ .btn-icon-header.btn-edit-history, + /* Response files: the phone header keeps one opt-in button (File Viewer), so + this stays off phones even with the Codex files setting on. */ + .btn-icon-header.btn-response-files, /* Approvals bell: phones answer from the overview's NEEDS YOU rows instead (inline approve/deny in mobile-overview.js); the bell would only crowd the header it was designed to stay out of. */ diff --git a/src/web/public/panels-ui.js b/src/web/public/panels-ui.js index 04d25cf2..bb465d15 100644 --- a/src/web/public/panels-ui.js +++ b/src/web/public/panels-ui.js @@ -3764,8 +3764,11 @@ Object.assign(CodemanApp.prototype, { const overlay = this.$('filePreviewOverlay'); if (!overlay) return; const terminalWrap = this.$('terminalContainer')?.closest('.terminal-wrap'); + // Docking is one of the Codex files extras (_codexFilePreviewsEnabled, app.js): with the + // setting off a preview only ever floats. Undocking is always allowed. dock = Boolean( dock && + this._codexFilePreviewsEnabled?.() && terminalWrap?.parentElement?.matches('.main:not(.tiles-active, .webview-active)') && window.matchMedia?.('(min-width: 1180px)').matches ); @@ -3913,6 +3916,8 @@ Object.assign(CodemanApp.prototype, { if (!overlay || !bodyEl) return; + const dockBtn = this.$('filePreviewDockBtn'); + if (dockBtn) dockBtn.hidden = !this._codexFilePreviewsEnabled?.(); if (options.dock) this._setFilePreviewDocked?.(true); this._recordFilePreviewHistory(filePath, sessionId, attachmentId, options); this._bindFilePreviewChrome(); diff --git a/src/web/public/settings-ui.js b/src/web/public/settings-ui.js index 5d6d9c32..f27c6078 100644 --- a/src/web/public/settings-ui.js +++ b/src/web/public/settings-ui.js @@ -605,6 +605,8 @@ Object.assign(CodemanApp.prototype, { // in the template, so an unchecked box and a hidden button stay consistent). document.getElementById('appSettingsShowSessionButton').checked = settings.showSessionButton ?? defaults.showSessionButton ?? false; document.getElementById('appSettingsShowAwayDigestButton').checked = settings.showAwayDigestButton ?? defaults.showAwayDigestButton ?? false; + // Codex files (Response files button, sidebar file tabs, Dock): per-device, default OFF. + document.getElementById('appSettingsCodexFilePreviews').checked = settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false; document.getElementById('appSettingsShowCronButton').checked = settings.showCronButton ?? defaults.showCronButton ?? false; document.getElementById('appSettingsShowGitStatus').checked = settings.showGitStatus ?? defaults.showGitStatus ?? false; document.getElementById('appSettingsGitStatusTree').checked = settings.gitStatusTree ?? defaults.gitStatusTree ?? true; @@ -3163,6 +3165,7 @@ Object.assign(CodemanApp.prototype, { spawnedTabsFollowParent: document.getElementById('appSettingsSpawnedTabsFollowParent').checked, showSessionButton: document.getElementById('appSettingsShowSessionButton').checked, showAwayDigestButton: document.getElementById('appSettingsShowAwayDigestButton').checked, + codexFilePreviewsEnabled: document.getElementById('appSettingsCodexFilePreviews').checked, showCronButton: document.getElementById('appSettingsShowCronButton').checked, showGitStatus: document.getElementById('appSettingsShowGitStatus').checked, gitStatusTree: document.getElementById('appSettingsGitStatusTree').checked, @@ -3480,6 +3483,8 @@ Object.assign(CodemanApp.prototype, { // SettingsUpdateSchema (.strict()), so sending them would 400 the PUT. showSessionButton: _ssb, showAwayDigestButton: _adb, + // Codex files extras (app.js _codexFilePreviewsEnabled): per-device, absent from the .strict() schema. + codexFilePreviewsEnabled: _cfp, showCronButton: _crb, // Per-device bottom-bar indicator, absent from SettingsUpdateSchema (.strict()): it must not reach the PUT. showGitStatus: _sgs, @@ -4842,6 +4847,11 @@ Object.assign(CodemanApp.prototype, { awayDigestBtn.classList.toggle('btn-away-digest--hidden', !showAwayDigestButton); } + // Codex files (Response files button, sidebar file tabs, Dock) — opt-in, hidden by default. + // Switching it off takes a docked preview back to floating. + this._syncResponseFilesButton?.(); + if (!this._codexFilePreviewsEnabled?.()) this._setFilePreviewDocked?.(false); + // Cron button (footer toolbar) — opt-in, hidden by default. Same marker pattern. const showCronButton = settings.showCronButton ?? defaults.showCronButton ?? false; const cronBtn = document.querySelector('.btn-cron'); @@ -5217,7 +5227,7 @@ Object.assign(CodemanApp.prototype, { 'language', 'terminalWheelLocalScrollback', 'autoCopySelection', 'copyStripMargin', - 'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory', + 'showSessionButton', 'showAwayDigestButton', 'codexFilePreviewsEnabled', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory', 'showTabDetachButton', 'showTabNewButton', 'mobileOverviewEnabled', diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 8786ceb2..a1b24b95 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -11927,6 +11927,11 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat display: none; } +/* Hidden while the Codex files setting is off (panels-ui.js openFilePreview). */ +#filePreviewDockBtn[hidden] { + display: none !important; +} + @media (min-width: 1180px) { html { --file-preview-dock-width: clamp(400px, 35vw, 620px); @@ -11938,6 +11943,10 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat .main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked { position: relative; + /* The floating overlay's 5100 would, with nothing above it making a stacking + context, put a docked pane over every modal (1000+) and the response viewer + (5000). Docked, it is page content beside the terminal. */ + z-index: auto; inset: auto; flex: 0 0 var(--file-preview-dock-width); min-width: 0; @@ -13647,10 +13656,23 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat } #responseFilesBtn[hidden], +.btn-icon-header.btn-response-files--hidden, .response-viewer[data-files-only='true'] :is(#responseViewerMore, #responseViewerCopyMarkdown) { display: none !important; } +/* Response files rows: buttons (no href for a middle-click to open), drawn as links. */ +.response-files-list .response-files-item { + padding: 0; + border: 0; + background: none; + color: var(--accent); + font: inherit; + text-align: left; + text-decoration: underline; + cursor: pointer; +} + .response-viewer-header { display: flex; align-items: center; diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index faf9c72f..f18fba27 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -2553,7 +2553,9 @@ Object.assign(CodemanApp.prototype, { } } - if (self._supportsCodexResponseFiles?.(getSessionId())) { + // Sidebar file tabs belong to the Codex files setting (_codexFilePreviewsEnabled): off, + // the row keeps master's links and its clicks reach Codex untouched. + if (self._supportsCodexResponseFiles?.(getSessionId()) && self._codexFilePreviewsEnabled?.()) { const sidebar = codexSidebarFileRow(terminal, bufferLineNumber - 1); if (sidebar) { const lineEnd = bufferLineNumber * terminal.cols + terminal.cols; @@ -6552,6 +6554,8 @@ Object.assign(CodemanApp.prototype, { const col = pos.col - 1; const sidebar = codexSidebarFileRow(terminal, row - 1); if (sidebar && col > sidebar.divider) { + // A sidebar tab click is taken only with the Codex files setting on; off, it reaches Codex. + if (!this._codexFilePreviewsEnabled?.()) return null; const entry = sidebar.entries.find(({ start, end }) => col >= start && col < end); return entry ? { ...entry, row, sidebar: true } : null; } @@ -6569,19 +6573,33 @@ Object.assign(CodemanApp.prototype, { return label && label.length <= 240 ? { label, row, start, end } : null; }, + /** + * The parsed conversation behind a Codex click. `context=full` makes the server read and parse + * the whole rollout, so the messages are kept for the session until its next turn: one entry + * (the last session asked about), reused only while the session is idle and its `lastSubmitAt` + * is unchanged. A working session's rollout is still growing, so it is never cached. + */ + async _codexResponseMessages(sessionId) { + const session = this.sessions?.get?.(sessionId); + const key = session?.status === 'idle' ? `${session.lastSubmitAt || 0}` : null; + const cached = this._codexResponseMessagesCache; + if (key && cached?.sessionId === sessionId && cached.key === key) return cached.messages; + const response = await fetch(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`, { + signal: AbortSignal.timeout(3000), + }); + if (!response.ok) return null; + const { data } = await response.json(); + const messages = Array.isArray(data?.messages) ? data.messages : null; + this._codexResponseMessagesCache = key && messages ? { sessionId, key, messages } : null; + return messages; + }, + async _openCodexTerminalResponseFile(terminal, sessionId, point, clicked, stillCurrent, forward) { let path; try { - const response = await fetch(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`, { - signal: AbortSignal.timeout(3000), - }); - if (response.ok) { - const { data } = await response.json(); - if (!stillCurrent()) return; - if (Array.isArray(data?.messages)) { - path = this._findCodexResponseFile(data.messages, clicked.label, sessionId, clicked.sidebar); - } - } + const messages = await this._codexResponseMessages(sessionId); + if (!stillCurrent()) return; + if (messages) path = this._findCodexResponseFile(messages, clicked.label, sessionId, clicked.sidebar); } catch { // Preserve the native click if the transcript cannot be resolved. } @@ -6596,7 +6614,12 @@ Object.assign(CodemanApp.prototype, { // Desktop counterpart of the touchend tap branch: hand-encode an SGR report // for a plain left-click when the server strips mouse DECSETs (see - // _shouldReportMouseToCli). Every skip below is a click that already has + // _shouldReportMouseToCli). In a session whose CLI publishes a Codex rollout + // transcript, a plain click on an underlined label (or, with the Codex files + // setting on, on a sidebar file tab) is first resolved against the + // conversation (_openCodexTerminalResponseFile): a single previewable file + // opens in the preview, anything else is forwarded as the SGR report below + // once the lookup settles. Every skip below is a click that already has // a meaning elsewhere: synthetic/compat clicks after a touch tap (touchend // reported already), modified clicks (shift keeps xterm's selection // override), double/triple clicks (word/line selection), drag-selections, @@ -6636,8 +6659,11 @@ Object.assign(CodemanApp.prototype, { return; } + // A second click (a double-click selecting the word) supersedes this one through the + // selection it leaves: it returns at `ev.detail !== 1` before it can replace `click`. const stillCurrent = () => this._codexTerminalLinkClicks.get(terminal) === click && + !terminal.hasSelection?.() && (target.sessionId ? terminal.element?.isConnected : this.activeSessionId === sessionId && this.terminal === terminal); 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/test/codex-file-previews-setting.test.ts b/test/codex-file-previews-setting.test.ts new file mode 100644 index 00000000..b1198afd --- /dev/null +++ b/test/codex-file-previews-setting.test.ts @@ -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( + /
@@ -445,6 +445,7 @@ describe('file preview dock lifecycle', () => { 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')!; @@ -511,4 +512,29 @@ describe('file preview dock lifecycle', () => { 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(/' + ); + 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; diff --git a/test/terminal-link-provider-target.test.ts b/test/terminal-link-provider-target.test.ts index 230c43ce..06c5e969 100644 --- a/test/terminal-link-provider-target.test.ts +++ b/test/terminal-link-provider-target.test.ts @@ -162,6 +162,7 @@ describe('native Codex sidebar files', () => { function setupSidebar() { const app = makeApp(); app._supportsCodexResponseFiles = () => true; + app._codexFilePreviewsEnabled = () => true; const terminal = fakeTerminal([ left + '│' + tab, ' '.repeat(42) + '│ Open in sidebar', @@ -191,6 +192,34 @@ describe('native Codex sidebar files', () => { 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', () => { diff --git a/test/terminal-touch-tap.test.ts b/test/terminal-touch-tap.test.ts index b71e9268..dea7c773 100644 --- a/test/terminal-touch-tap.test.ts +++ b/test/terminal-touch-tap.test.ts @@ -509,6 +509,7 @@ describe('terminal touch tap mouse guard', () => { getCell: (column: number) => ({ getWidth: () => 1, isUnderline: () => column >= 2 && column < 12 }), }; }; + app._supportsCodexResponseFiles = () => true; app._openCodexTerminalResponseFile = vi.fn().mockResolvedValue(undefined); app._sendSyntheticSgrTap = vi.fn(); @@ -524,13 +525,18 @@ describe('terminal touch tap mouse guard', () => { expect(app._openCodexTerminalResponseFile).toHaveBeenCalledWith( app.terminal, 'sess-1', - session, { 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', () => {