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

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

No files matched your search

+1 -1
View File
@@ -1377,7 +1377,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
+9 -1
View File
@@ -63,11 +63,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
+8
View File
@@ -142,6 +142,14 @@ 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.
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
page. The exception is a plain text file (a log, `.txt`, `.json`, code) inside the workspace
+3 -1
View File
@@ -98,6 +98,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`).
+185 -13
View File
@@ -1427,6 +1427,7 @@ class CodemanApp {
// Escape - close panels and modals (different logic: no preventDefault, no return)
if (e.key === 'Escape') {
if (this._maybeCloseDockedFilePreviewOnEscape?.(e)) return;
// An open group menu (or a grouped-rail drag) owns this Escape: close
// just that, not every panel behind it.
if (this._tabGroupMenu && this._tabGroupMenuKeydown) {
@@ -2776,12 +2777,19 @@ class CodemanApp {
* newline is the agent's line break, wrong for a file (the File Viewer passes
* false), where a README hard-wrapped at 80 columns would break at every wrap.
*/
_renderMarkdown(text, { breaks = true } = {}) {
_renderMarkdown(text, { breaks = true, localFileLinks = false } = {}) {
const src = text || '';
if (typeof marked !== 'undefined' && marked.parse) {
try {
const prepared = this._preprocessAsciiArt(src);
let html = this._sanitizeHtml(marked.parse(prepared, { breaks, gfm: true }));
const options = { breaks, gfm: true };
if (localFileLinks) {
options.walkTokens = (token) => {
// Convert local URI destinations to inert path references before sanitizing.
if (token.type === 'link' && /^file:\/\/\/(?!\/)/i.test(token.href)) token.href = token.href.slice(7);
};
}
let html = this._sanitizeHtml(marked.parse(prepared, options));
// Wrap tables in a horizontal-scroll container so they overflow gracefully
// on mobile without collapsing into block-level cells.
html = html.replace(/<table>/g, '<div class="rv-table-wrap"><table>')
@@ -3228,19 +3236,166 @@ class CodemanApp {
: 'Claude';
}
async toggleResponseViewer() {
closeResponseViewer() {
this._responseViewerRequest = null;
const viewer = document.getElementById('responseViewer');
if (!viewer || !viewer.classList.contains('visible')) return false;
const backdrop = document.getElementById('responseViewerBackdrop');
viewer.classList.remove('visible');
if (backdrop) backdrop.classList.remove('visible');
const terminal = this._responseViewerReturnTerminal;
this._responseViewerReturnTerminal = null;
if (terminal && terminal.element?.isConnected !== false && this._shouldFocusTerminalForTabSwitch()) {
try {
terminal.focus();
} catch {
/* terminal may be detached mid-teardown */
}
}
return true;
}
_supportsCodexResponseFiles(sessionId) {
const mode = this.sessions?.get(sessionId)?.mode;
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);
const containsFilename = (text) => abbreviated ? text.includes(prefix) && text.includes(suffix) : text.includes(label);
let match = null;
for (const message of messages) {
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(text, { localFileLinks: true });
const links = Array.from(rendered.content.querySelectorAll('a')).filter(
(link) => sidebar || link.textContent.trim() === label
);
if (!links.length) continue;
this._linkifyFilePaths(rendered.content);
for (const link of links) {
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.
const matchesEnds =
abbreviated && basename.length > prefix.length + suffix.length &&
basename.startsWith(prefix) && basename.endsWith(suffix);
if (basename !== label && !matchesEnds) continue;
}
// Ambiguity includes web URLs and unsupported files with the same label.
if (!link.dataset.linkified || link.dataset.folder || !/^\/(?!\/)/.test(path) || !previewsInFileViewer(path)) {
return null;
}
if (match && match !== path) return null;
match = path;
}
}
return match;
}
_openResponseFile(path, sessionId) {
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) {
const list = document.createElement('ul');
list.className = 'response-files-list';
const seen = new Set();
for (const response of responses) {
const rendered = document.createElement('template');
rendered.innerHTML = this._renderMarkdown(response, { localFileLinks: true });
this._linkifyFilePaths(rendered.content);
for (const link of rendered.content.querySelectorAll('a.rv-path')) {
if (link.dataset.folder) continue;
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');
// A button, not <a href="#">: under <base href> 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) => {
event.preventDefault();
this.closeResponseViewer();
this._openResponseFile(path, sessionId);
});
item.appendChild(action);
list.appendChild(item);
}
}
if (seen.size) body.replaceChildren(list);
else {
const empty = 'No previewable files in the latest response.';
body.textContent = window.codemanT?.(empty) || empty;
}
}
async toggleResponseViewer(filesOnly = false) {
const viewer = document.getElementById('responseViewer');
const backdrop = document.getElementById('responseViewerBackdrop');
if (!viewer) return;
const isOpen = viewer.classList.contains('visible');
if (isOpen) {
viewer.classList.remove('visible');
backdrop.classList.remove('visible');
if (isOpen && (viewer.dataset.filesOnly === 'true') === filesOnly) {
this.closeResponseViewer();
return;
}
if (!this.activeSessionId) return;
const responseSessionId = this.activeSessionId;
const session = this.sessions?.get?.(responseSessionId);
if (filesOnly && !(this._codexFilePreviewsEnabled() && this._supportsCodexResponseFiles(responseSessionId))) return;
const returnTerminal = isOpen ? this._responseViewerReturnTerminal : this._focusedPane?.().terminal;
const request = Symbol('response-viewer');
this._responseViewerRequest = request;
try {
// Source 1: Transcript JSONL (best quality — clean structured text from Claude).
// `context=turn` asks for the last ANSWERED turn as messages: a Claude
@@ -3249,8 +3404,10 @@ class CodemanApp {
// rows before it. Readers that know no `turn` context (Codex, the pane
// parser, an older server) answer with `text` only, and that path is
// unchanged below.
const res = await fetch(`/api/sessions/${this.activeSessionId}/last-response?context=turn`);
const res = await fetch(`/api/sessions/${responseSessionId}/last-response?context=turn`);
if (filesOnly && !res.ok) throw new Error('Unable to load response files');
const data = (await res.json())?.data ?? {};
if (this._responseViewerRequest !== request || this.activeSessionId !== responseSessionId) return;
let lastResponse = data.text || '';
const turnMessages = (Array.isArray(data.messages) ? data.messages : []).filter(
(msg) => msg && msg.role === 'assistant' && typeof msg.text === 'string' && msg.text.trim()
@@ -3261,13 +3418,13 @@ class CodemanApp {
// shell sessions have no transcript source at all; for TUI modes
// (codex/opencode/gemini/antigravity) it yields repaint garbage, so a clear
// placeholder beats a messy screen dump there.
const sessionMode = this.sessions.get(this.activeSessionId)?.mode || 'claude';
const sessionMode = session?.mode || 'claude';
if (!lastResponse && (sessionMode === 'claude' || sessionMode === 'shell')) {
// The no-param form is capped only by `terminalBufferMaxBytes` (32MB by
// default), so it is the largest body the frontend asks for anywhere —
// it gets the full-history budget, not the tail one.
const termCapture = await this._fetchTerminalCapture(
`/api/sessions/${this.activeSessionId}/terminal`,
`/api/sessions/${responseSessionId}/terminal`,
{ full: true }
);
const termData = termCapture.json?.data ?? {};
@@ -3276,10 +3433,14 @@ class CodemanApp {
}
}
if (this._responseViewerRequest !== request || this.activeSessionId !== responseSessionId) return;
this._responseViewerMarkdown = this._responseViewerMarkdownFrom(turnMessages) || lastResponse;
const body = document.getElementById('responseViewerBody');
if (turnMessages.length > 0) {
if (filesOnly) {
const responses = turnMessages.length ? turnMessages.map((message) => message.text) : [lastResponse];
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
// numeric-`turn` gate as loadFullContext, never same-role adjacency.
@@ -3308,9 +3469,15 @@ class CodemanApp {
// Reset state for fresh open
const title = document.getElementById('responseViewerTitle');
const moreBtn = document.getElementById('responseViewerMore');
if (title) title.textContent = 'Last Response';
if (moreBtn) { moreBtn.style.display = ''; moreBtn.textContent = 'More'; }
viewer.dataset.filesOnly = String(filesOnly);
const titleText = filesOnly ? 'Response files' : 'Last Response';
if (title) title.textContent = window.codemanT?.(titleText) || titleText;
if (moreBtn) {
moreBtn.style.display = '';
moreBtn.textContent = window.codemanT?.('More') || 'More';
}
this._responseViewerReturnTerminal = returnTerminal;
viewer.classList.add('visible');
backdrop.classList.add('visible');
// A multi-row turn opens at its NEWEST text, matching loadFullContext's
@@ -3318,9 +3485,13 @@ class CodemanApp {
// brief view was a single card holding the last row; with the whole turn
// rendered, the top is the turn's first narration line and the answer the
// eye button exists to show can be several screens down.
body.scrollTop = turnMessages.length > 1 ? body.scrollHeight : 0;
body.scrollTop = !filesOnly && turnMessages.length > 1 ? body.scrollHeight : 0;
} catch (err) {
console.error('Failed to load response:', err);
if (filesOnly && this._responseViewerRequest === request && this.activeSessionId === responseSessionId) {
const message = 'Unable to load response files';
this.showToast(window.codemanT?.(message) || message, 'error');
}
}
}
@@ -6592,6 +6763,7 @@ class CodemanApp {
// ═══════════════════════════════════════════════════════════════
renderSessionTabs({ immediate = false } = {}) {
this._syncResponseFilesButton();
// Don't re-render while user is typing in the inline rename input
if (this._inlineRenameActive) return;
if (immediate) {
+9
View File
@@ -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',
@@ -481,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': '会话管理器按钮',
+6 -3
View File
@@ -206,6 +206,7 @@
</div>
<button class="btn-icon-header btn-redraw-terminal btn-redraw-terminal--hidden" onclick="app.restoreTerminalSize()" title="Redraw terminal to fit current screen (Ctrl+Shift+R)" aria-label="Redraw terminal"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><polyline points="23 20 23 14 17 14"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg></button>
<button class="btn-icon-header btn-response-viewer-header btn-response-viewer-header--hidden" onclick="app.toggleResponseViewer()" title="View last response" aria-label="View last response"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
<button id="responseFilesBtn" type="button" class="btn-icon-header btn-response-files btn-response-files--hidden" onclick="app.toggleResponseViewer(true)" title="Response files" aria-label="Open Codex response files" hidden><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8m-8 4h6"/></svg></button>
<button class="btn-icon-header btn-away-digest btn-away-digest--hidden" onclick="app.openAwayDigest()" title="Away Digest" aria-label="Open away digest"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg></button>
<button class="btn-icon-header btn-session-manager btn-session-manager--hidden" onclick="app.openSessionManager()" title="Session Manager" aria-label="Open session manager"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg></button>
<button class="btn-icon-header btn-approvals btn-approvals--hidden" id="approvalsBtn" onclick="app.toggleApprovalsInbox()" title="Approvals waiting on you" aria-label="Open approvals inbox" aria-expanded="false">
@@ -696,6 +697,7 @@
<button class="btn-icon-sm file-preview-edit-btn" id="filePreviewEditBtn" onclick="app.enterFilePreviewEdit()" title="Edit file" aria-label="Edit file" hidden><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z"/></svg></button>
<button class="btn-icon-sm" onclick="app.copyFilePreviewContent()" title="Copy content">&#x2398;</button>
<button class="btn-icon-sm" id="filePreviewDetachBtn" onclick="app.detachFilePreview()" title="Open in new tab" aria-label="Open in new tab" hidden><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></button>
<button type="button" class="btn-icon-sm" id="filePreviewDockBtn" hidden onclick="app.toggleFilePreviewDock()" title="Dock preview" aria-label="Dock preview" aria-pressed="false"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M15 4v16"/></svg></button>
<button class="btn-icon-sm" id="filePreviewExpandBtn" onclick="app.toggleFilePreviewExpanded()" title="Expand" aria-label="Expand" aria-pressed="false"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg></button>
<button class="btn-icon-sm" onclick="app.closeFilePreview()" title="Close">&times;</button>
</div>
@@ -735,12 +737,12 @@
<div class="response-viewer-actions">
<button class="response-viewer-more" id="responseViewerMore" onclick="app.loadFullContext()">More</button>
<button class="response-viewer-more response-viewer-copy-markdown" id="responseViewerCopyMarkdown" type="button" onclick="app.copyResponseViewerMarkdown()" title="Copy response as Markdown">Copy Markdown</button>
<button class="response-viewer-close" onclick="app.toggleResponseViewer()">&times;</button>
<button class="response-viewer-close" onclick="app.closeResponseViewer()">&times;</button>
</div>
</div>
<div class="response-viewer-body" id="responseViewerBody"></div>
</div>
<div class="response-viewer-backdrop" id="responseViewerBackdrop" onclick="app.toggleResponseViewer()"></div>
<div class="response-viewer-backdrop" id="responseViewerBackdrop" onclick="app.closeResponseViewer()"></div>
<!-- Bottom Toolbar -->
<footer class="toolbar">
@@ -2246,13 +2248,14 @@
<div class="set-group-head"><h4>Header buttons</h4><span class="set-scope">device</span></div>
<p class="set-group-hint">Tap to show a control in the header. Multi-monitor is the one entry here that syncs across devices.</p>
<div class="set-group-body">
<div class="set-chips" data-search="header buttons plan usage font stats lifecycle response file viewer attachments monitor session away cron redraw split tiles">
<div class="set-chips" data-search="header buttons plan usage font stats lifecycle response codex files file viewer attachments monitor session away cron redraw split tiles">
<label class="set-chip" data-preview="header" data-preview-order="1" data-preview-text="A+"><input type="checkbox" id="appSettingsShowFontControls"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 20 10 5l6 15"/><path d="M6.5 15h7"/><path d="M18 12h4M20 10v4"/></svg><span>Font Size</span></label>
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="CPU 12%"><input type="checkbox" id="appSettingsShowSystemStats" checked><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12h4l2.5-7 4 14L16 12h5"/></svg><span>System Stats</span></label>
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="GPU 8%"><input type="checkbox" id="appSettingsShowGpuStats"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="7" width="18" height="10" rx="2"/><path d="M7 21v-4M12 21v-4M17 21v-4M7 7V3M17 7V3"/></svg><span>GPU Stats</span></label>
<label class="set-chip" data-preview="header" data-preview-order="2" data-preview-text="3400 MHz"><input type="checkbox" id="appSettingsShowCpuMhz"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg><span>CPU MHz</span></label>
<label class="set-chip" data-preview="header" data-preview-order="3"><input type="checkbox" id="appSettingsShowRedrawButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><polyline points="23 20 23 14 17 14"/><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/></svg><span>Redraw Terminal</span></label>
<label class="set-chip" data-preview="header" data-preview-order="4"><input type="checkbox" id="appSettingsShowResponseViewer"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg><span>Response Viewer</span></label>
<label class="set-chip" data-search="codex files response files sidebar file tabs dock preview" data-preview="header" data-preview-order="4.5" title="Codex sessions: a Response files header button, Codex sidebar file tabs open in the preview, and a Dock control on file previews"><input type="checkbox" id="appSettingsCodexFilePreviews"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8m-8 4h6"/></svg><span>Codex files</span></label>
<label class="set-chip" data-preview="header" data-preview-order="5"><input type="checkbox" id="appSettingsShowAwayDigestButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg><span>Away Digest</span></label>
<label class="set-chip" data-preview="header" data-preview-order="6"><input type="checkbox" id="appSettingsShowSessionButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg><span>Session Manager</span></label>
<label class="set-chip" data-preview="header" data-preview-order="9"><input type="checkbox" id="appSettingsShowAttachmentsButton"><svg class="set-chip-ico" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg><span>Attachments</span></label>
+3
View File
@@ -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. */
+55
View File
@@ -4021,6 +4021,56 @@ Object.assign(CodemanApp.prototype, {
if (headerBtn) headerBtn.setAttribute('aria-expanded', 'false');
},
_setFilePreviewDocked(dock) {
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
);
if (dock === overlay.classList.contains('is-docked')) return;
if (dock) {
if (!overlay.parentElement) return;
this._filePreviewOverlayHome = overlay.parentElement;
terminalWrap.after(overlay);
} else {
this._filePreviewOverlayHome?.append(overlay);
this._filePreviewOverlayHome = null;
}
overlay.classList.toggle('is-docked', dock);
this.$('filePreviewDockBtn')?.setAttribute('aria-pressed', String(dock));
},
_isFilePreviewDocked() {
const overlay = this.$('filePreviewOverlay');
return (
overlay?.classList.contains('is-docked') &&
overlay.parentElement?.matches('.main:not(.tiles-active, .webview-active)') &&
window.matchMedia?.('(min-width: 1180px)').matches
);
},
toggleFilePreviewDock() {
const overlay = this.$('filePreviewOverlay');
if (!overlay?.classList.contains('visible')) return;
this._setFilePreviewDocked(!overlay.classList.contains('is-docked'));
},
_maybeCloseDockedFilePreviewOnEscape(event) {
const overlay = this.$('filePreviewOverlay');
if (!this._isFilePreviewDocked() || !overlay?.classList.contains('visible') || !overlay.contains(event.target)) return false;
event.preventDefault();
event.stopPropagation();
this.closeFilePreview();
if (!overlay.classList.contains('visible')) this.terminal?.focus();
return true;
},
/**
* Whether a path is absolute and provably OUTSIDE this session's workspace.
*
@@ -4127,6 +4177,9 @@ 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();
@@ -4657,6 +4710,7 @@ Object.assign(CodemanApp.prototype, {
if (ev.key !== 'ArrowLeft' && ev.key !== 'ArrowRight') return;
if (!this.$('filePreviewOverlay')?.classList.contains('visible')) return;
const t = ev.target;
if (this._isFilePreviewDocked?.() && !this.$('filePreviewOverlay')?.contains(t)) return;
if (t && (t.isContentEditable || (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) && !t.classList?.contains('xterm-helper-textarea')))) return;
// Swallowed even at the ends of the list: otherwise the terminal behind the overlay
// types it as word-left/right, and on a header button the browser's own Alt+← goes Back.
@@ -4787,6 +4841,7 @@ Object.assign(CodemanApp.prototype, {
const overlay = this.$('filePreviewOverlay');
if (overlay) {
overlay.classList.remove('visible');
this._setFilePreviewDocked?.(false);
}
// The overlay is hidden with display:none, which stops it being PAINTED and
// nothing else: a <video>/<audio> inside it keeps playing, keeps its audio
+13 -3
View File
@@ -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;
@@ -3165,6 +3167,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,
@@ -3485,6 +3488,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,
@@ -4184,8 +4189,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])
);
@@ -4196,6 +4200,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),
}));
@@ -4848,6 +4853,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');
@@ -5224,7 +5234,7 @@ Object.assign(CodemanApp.prototype, {
'terminalWheelLocalScrollback',
'historyReloadAction',
'autoCopySelection', 'copyStripMargin',
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
'showSessionButton', 'showAwayDigestButton', 'codexFilePreviewsEnabled', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
'showTabDetachButton',
'showTabNewButton',
'mobileOverviewEnabled',
+75
View File
@@ -11953,6 +11953,63 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
display: flex;
}
#filePreviewDockBtn {
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);
}
body:has(.main:not(.tiles-active, .webview-active) > .terminal-wrap) #filePreviewDockBtn {
display: inline-flex;
}
.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;
min-height: 0;
align-items: stretch;
background: transparent;
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked .file-preview-window {
width: 100% !important;
height: 100% !important;
min-width: 0;
min-height: 0;
max-height: none;
border-radius: 0;
resize: none;
}
.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked :is(#filePreviewExpandBtn, #filePreviewResize) {
display: none;
}
#filePreviewDockBtn[aria-pressed='true'] {
color: var(--accent);
}
body:has(.main:not(.tiles-active, .webview-active) > .file-preview-overlay.is-docked.visible) .attachment-card-stack {
right: calc(var(--file-preview-dock-width) + 18px);
}
}
/* Folder grid (panels-ui.js openFolderGrid): one step BELOW the file preview, so a
tile opens its preview on top and closing that preview lands back on the grid. */
.folder-grid-overlay {
@@ -13628,6 +13685,24 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
transform: translateY(0);
}
#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;
+1
View File
@@ -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);
+184 -3
View File
@@ -501,6 +501,79 @@
global.codemanCurrentSkinIsLight = currentSkinIsLight;
})(window);
// Codex's sidebar owns its tab bar and file picker. Their labels are UI
// chrome, so the ordinary path linkifier must never open a suffix of one.
function codexSidebarFileRow(terminal, row) {
const buffer = terminal.buffer.active;
const top = buffer.viewportY;
if (row < top) return null;
const line = buffer.getLine(row);
if (!line?.getCell) return null;
for (let headerRow = top; headerRow <= Math.min(row, top + 2); headerRow++) {
const header = buffer.getLine(headerRow);
if (!header?.translateToString(true).trimEnd().endsWith('+')) continue;
for (let divider = terminal.cols - 2; divider >= 0; divider--) {
if (header.getCell(divider)?.getChars() !== '│') continue;
if (buffer.getLine(headerRow + 1)?.getCell?.(divider)?.getChars() !== '│') continue;
const tabs = header.translateToString(true, divider + 1).trim();
if (tabs !== '+' && !tabs.endsWith('×') && !/×\s+\+$/.test(tabs)) continue;
if (row !== headerRow && line.getCell(divider)?.getChars() !== '│') continue;
const entries = [];
const addEntry = (from, to) => {
while (from < to && !line.getCell(from)?.getChars().trim()) from++;
while (to > from && !line.getCell(to - 1)?.getChars().trim()) {
if (line.getCell(to - 1)?.getWidth() === 0) break;
to--;
}
const label = line.translateToString(false, from, to).trim();
if (label && previewsInFileViewer(label)) entries.push({ label, start: from, end: to });
};
if (row === headerRow) {
let from = divider + 1;
for (let col = from; col < terminal.cols; col++) {
if (line.getCell(col)?.getChars() !== '×') continue;
addEntry(from, col);
from = col + 1;
}
return { divider, entries };
}
// The chooser can also be opened with a keyboard shortcut. Its file
// rows follow the heading and use either the normal or selected marker.
let inChooser = false;
for (let scan = headerRow + 1; scan < row; scan++) {
const text = buffer.getLine(scan)?.translateToString(true, divider + 1).trim();
if (text === 'Open in sidebar') inChooser = true;
if (inChooser && /^(?:Markdown files|Files)\s+\d+$/.test(text)) {
const file = line.translateToString(true, divider + 1);
const marker = file.match(/^\s*(?:›\s+)?·\s+/);
if (!marker) return null;
const from = divider + 1 + marker[0].length;
let end = terminal.cols;
// On wider panels Codex appends a styled directory after two spaces.
const titleCell = line.getCell(from);
for (let col = from + 1; col + 1 < terminal.cols; col++) {
const firstSpace = line.getCell(col);
const secondSpace = line.getCell(col + 1);
if (!firstSpace || !secondSpace || firstSpace.getChars().trim() || secondSpace.getChars().trim()) continue;
if (
firstSpace.getFgColor?.() !== titleCell?.getFgColor?.() ||
firstSpace.getFgColorMode?.() !== titleCell?.getFgColorMode?.() ||
firstSpace.isDim?.() !== titleCell?.isDim?.() ||
line.translateToString(true, col).trim() === 'Project root'
) {
end = col;
break;
}
}
addEntry(from, end);
return { divider, entries };
}
}
}
}
return null;
}
Object.assign(CodemanApp.prototype, {
// ═══════════════════════════════════════════════════════════════
// Terminal Setup — xterm.js config and input handling
@@ -2514,6 +2587,20 @@ Object.assign(CodemanApp.prototype, {
}
}
// 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;
const sidebarStart = bufferLineNumber * terminal.cols + sidebar.divider + 2;
for (let i = links.length - 1; i >= 0; i--) {
const { start, end } = links[i].range;
if (start.y * terminal.cols + start.x <= lineEnd && end.y * terminal.cols + end.x >= sidebarStart) links.splice(i, 1);
}
}
}
if (links.length > 0) {
console.debug(
'[LinkProvider] Found links:',
@@ -6613,9 +6700,83 @@ Object.assign(CodemanApp.prototype, {
}
},
_codexTerminalLinkLabel(terminal, clientX, clientY) {
const pos = this._clientPointToCell(clientX, clientY, terminal);
const buffer = terminal.buffer?.active;
if (!pos || !buffer) return null;
const row = pos.row + buffer.viewportY;
const line = buffer.getLine(row - 1);
if (!line) return null;
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;
}
if (line.isWrapped || buffer.getLine(row)?.isWrapped) return null;
const underlined = (index) => {
const cell = line.getCell(index);
return cell?.getWidth() === 0 || Boolean(cell?.isUnderline?.());
};
if (!underlined(col)) return null;
let start = col;
let end = col + 1;
while (start > 0 && underlined(start - 1)) start--;
while (end < terminal.cols && underlined(end)) end++;
const label = line.translateToString(false, start, end).trim();
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 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.
}
if (!stillCurrent()) return;
const current = this._codexTerminalLinkLabel(terminal, point.clientX, point.clientY);
if (!current || current.label !== clicked.label || current.row !== clicked.row ||
current.start !== clicked.start || current.end !== clicked.end || current.sidebar !== clicked.sidebar) return;
if (path) await this._openResponseFile(path, sessionId);
else forward();
},
// 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,
@@ -6637,12 +6798,32 @@ Object.assign(CodemanApp.prototype, {
if (ev.shiftKey || ev.altKey || ev.ctrlKey || ev.metaKey) return;
const mode = terminal.modes?.mouseTrackingMode;
if (mode && mode !== 'none') return;
if (!this._shouldReportMouseToCli(target.sessionId)) return;
if (terminal.hasSelection?.()) return;
if (target.linkHovered ?? this._linkHovered) return; // link provider hover/leave callbacks (registerFilePathLinkProvider)
if (performance.now() <= (this._trustedTapMouseSuppressUntil || 0)) return;
if (!ev.target?.closest?.('.xterm-screen')) return;
this._sendSyntheticSgrTap(ev.clientX, ev.clientY, target);
const sessionId = target.sessionId || this.activeSessionId;
const { clientX, clientY } = ev;
const forward = () => {
if (this._shouldReportMouseToCli(sessionId)) this._sendSyntheticSgrTap(clientX, clientY, target);
};
this._codexTerminalLinkClicks ??= new WeakMap();
const click = Symbol();
this._codexTerminalLinkClicks.set(terminal, click);
const link = this._supportsCodexResponseFiles?.(sessionId) && this._codexTerminalLinkLabel(terminal, clientX, clientY);
if (!link) {
forward();
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));
},
/**
+1
View File
@@ -2097,6 +2097,7 @@ export class WebServer extends EventEmitter {
order: entry.order,
kind: entry.kind,
external: entry.capabilities.external,
transcript: entry.capabilities.transcript,
enabled,
available: enabled && installed,
};
+167
View File
@@ -0,0 +1,167 @@
// test/codex-file-previews-setting.test.ts
// Port: none (static analysis plus vm-loaded modules, runs in CI, no browser/server).
//
// `codexFilePreviewsEnabled` (App Settings > Header buttons > Codex files) gates three
// behaviours together, per device, default OFF:
// 1. the Response files header button (never on phones, even when on),
// 2. taking a click on a file tab in Codex's own sidebar (and suppressing the
// ordinary linkifier on those rows),
// 3. the Dock control on file previews.
// With it off none of the three exists. Each surface's off-state behaviour is also
// pinned next to its own tests (response-viewer-file-links, terminal-link-provider-target,
// file-preview-window); this file pins the setting's own wiring and the off-state of all
// three through the real reader.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { performance } from 'node:perf_hooks';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const PUBLIC = join(HERE, '../src/web/public');
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
describe('codexFilePreviewsEnabled stays per-device: display key, stripped from the PUT, absent from the schema', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
it('is in the client-side displayKeys merge policy', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
expect(displayKeys).toContain("'codexFilePreviewsEnabled'");
});
it('is stripped out of the object saveAppSettings() PUTs and never declared in the .strict() schema', () => {
expect(settingsUi).toContain('codexFilePreviewsEnabled: _cfp,');
expect(schemas).not.toContain('codexFilePreviewsEnabled');
});
it('is loaded into and saved from its App Settings chip, default OFF', () => {
const index = read('index.html');
expect(index).toMatch(
/<label class="set-chip"[^>]*data-preview="header"[^>]*><input type="checkbox" id="appSettingsCodexFilePreviews">/
);
expect(settingsUi).toContain(
"document.getElementById('appSettingsCodexFilePreviews').checked = settings.codexFilePreviewsEnabled ?? defaults.codexFilePreviewsEnabled ?? false;"
);
expect(settingsUi).toContain(
"codexFilePreviewsEnabled: document.getElementById('appSettingsCodexFilePreviews').checked,"
);
});
});
describe('with the Codex files setting off (nothing stored), none of the three behaviours exists', () => {
function loadApp() {
const { window } = new JSDOM(`<!doctype html>
<button id="responseFilesBtn" class="btn-icon-header btn-response-files btn-response-files--hidden" hidden></button>
<main class="main"><div class="terminal-wrap"><div id="terminalContainer"></div></div></main>
<div id="filePreviewOverlay" class="visible"><button id="filePreviewDockBtn" hidden aria-pressed="false"></button></div>`);
const { document } = window;
const fetchSpy = vi.fn();
const context = vm.createContext({
console: { ...console, debug: vi.fn(), log: vi.fn() },
performance,
setInterval: vi.fn(),
clearInterval: vi.fn(),
setTimeout,
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
fetch: fetchSpy,
AbortSignal,
document,
NodeFilter: window.NodeFilter,
// Nothing stored on this device: the setting reads its default.
localStorage: { length: 0, key: vi.fn(), getItem: () => null, setItem: vi.fn(), removeItem: vi.fn() },
window: {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
matchMedia: () => ({ matches: true }), // a wide desktop: docking would otherwise apply
__codemanCliCatalog: [{ id: 'codex', transcript: 'codex-rollout' }],
},
MobileDetection: { isHandheldDevice: () => false, isTouchDevice: () => false, getDeviceType: () => 'desktop' },
});
const addEventListener = vi.spyOn(document, 'addEventListener').mockImplementation(() => {});
try {
vm.runInContext(
['constants.js', 'app.js', 'settings-ui.js', 'panels-ui.js', 'terminal-ui.js'].map(read).join('\n') +
'\nglobalThis.__CodemanApp = CodemanApp;',
context
);
} finally {
addEventListener.mockRestore();
}
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.assign(Object.create(CodemanApp.prototype), {
$: (id: string) => document.getElementById(id),
activeSessionId: 'codex-1',
sessions: new Map([['codex-1', { mode: 'codex' }]]),
});
return { app, document, fetchSpy };
}
it('reads OFF from the real device settings with nothing stored', () => {
const { app } = loadApp();
expect(app._codexFilePreviewsEnabled()).toBe(false);
});
it('1. keeps the Response files button hidden in a Codex session', () => {
const { app, document } = loadApp();
app._syncResponseFilesButton();
expect(document.getElementById('responseFilesBtn')!.classList.contains('btn-response-files--hidden')).toBe(true);
});
it('2. takes no click on a Codex sidebar file tab', () => {
const { app } = loadApp();
const cols = 80;
const lines = [' '.repeat(42) + '│ Brief.docx × +', ' '.repeat(42) + '│ body'];
const terminal = {
cols,
buffer: {
active: {
viewportY: 0,
length: lines.length,
getLine: (row: number) =>
lines[row] === undefined
? undefined
: {
isWrapped: false,
getCell: (col: number) => ({
getChars: () => lines[row][col] ?? ' ',
getWidth: () => 1,
isUnderline: () => false,
}),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const text = lines[row].padEnd(cols).slice(start, end);
return trim ? text.trimEnd() : text;
},
},
},
},
};
app._clientPointToCell = (col: number, row: number) => ({ col, row });
expect(app._codexTerminalLinkLabel(terminal, 46, 1)).toBeNull();
app._codexFilePreviewsEnabled = () => true; // the same click, setting on: taken
expect(app._codexTerminalLinkLabel(terminal, 46, 1)).toMatchObject({ label: 'Brief.docx', sidebar: true });
});
it('3. never docks a preview', () => {
const { app, document } = loadApp();
const overlay = document.getElementById('filePreviewOverlay')!;
app.toggleFilePreviewDock();
app._setFilePreviewDocked(true);
expect(overlay.classList.contains('is-docked')).toBe(false);
expect(overlay.parentElement).toBe(document.body);
app._codexFilePreviewsEnabled = () => true; // the same call, setting on: docks
app._setFilePreviewDocked(true);
expect(overlay.classList.contains('is-docked')).toBe(true);
});
it('keeps Response files off phones even with the setting on', () => {
const mobileCss = read('mobile.css');
const phoneBlock = mobileCss.slice(mobileCss.indexOf('@media (max-width: 599px)'));
expect(phoneBlock).toMatch(/\.btn-icon-header\.btn-response-files,[\s\S]*?display: none !important;/);
});
});
+131
View File
@@ -24,6 +24,7 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { describe, expect, it, vi } from 'vitest';
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
@@ -407,3 +408,133 @@ describe('file viewer on phones', () => {
expect(phone).toMatch(/#filePreviewExpandBtn,\s*\.file-preview-resize\s*\{\s*display: none;/);
});
});
describe('file preview dock lifecycle', () => {
function setup(layout: string, wide = true, codexFiles = true) {
const { window } = new JSDOM(`<!doctype html><main class="main ${layout}">
<div class="terminal-wrap"><div id="terminalContainer"></div></div>
</main><div id="filePreviewOverlay" class="visible">
<button id="filePreviewDockBtn" aria-pressed="false"></button>
</div>`);
const { document } = window;
const CodemanApp = function CodemanApp() {};
const context = vm.createContext({
CodemanApp,
document,
window: {
matchMedia: () => ({ matches: wide }),
innerWidth: 1400,
addEventListener: vi.fn(),
TerminalTile: class {
async connect() {}
destroy() {}
},
},
SPLIT_PANE_MIN_WIDTH: 1000,
});
vm.runInContext(panelsJs, context);
const splitJs = readFileSync(resolve(PUBLIC, 'terminal-split.js'), 'utf8');
vm.runInContext(splitJs, context);
const app = Object.assign(Object.create(CodemanApp.prototype), {
$: (id: string) => document.getElementById(id),
_resetFilePreviewEdit: vi.fn(),
_updateSplitButtonState: vi.fn(),
_buildSplitPaneHeader: () => ({ el: document.createElement('div') }),
_renderSplitChrome: vi.fn(),
_installSplitDividerDrag: vi.fn(),
activeSessionId: 'pane-a',
sessions: new Map([['pane-b', { pid: 1 }]]),
terminal: { focus: vi.fn() },
_codexFilePreviewsEnabled: () => codexFiles,
});
const overlay = document.getElementById('filePreviewOverlay')!;
const main = document.querySelector('.main')!;
const wrap = document.querySelector('.terminal-wrap')!;
const dockButton = document.getElementById('filePreviewDockBtn')!;
return { app, document, main, overlay, wrap, dockButton };
}
it('docks beside the terminal and returns to its original parent on close', () => {
const { app, document, main, overlay, wrap, dockButton } = setup('');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
expect(wrap.nextElementSibling).toBe(overlay);
expect(dockButton.getAttribute('aria-pressed')).toBe('true');
app.closeFilePreview();
expect(overlay.parentElement).toBe(document.body);
expect(overlay.classList.contains('visible')).toBe(false);
expect(dockButton.getAttribute('aria-pressed')).toBe('false');
});
it('handles Escape inside the dock and leaves terminal Escape alone', () => {
const { app, document, overlay, wrap, dockButton } = setup('');
app.toggleFilePreviewDock();
const escape = { target: wrap, preventDefault: vi.fn(), stopPropagation: vi.fn() };
expect(app._maybeCloseDockedFilePreviewOnEscape(escape)).toBe(false);
expect(escape.preventDefault).not.toHaveBeenCalled();
expect(overlay.classList.contains('visible')).toBe(true);
expect(app._maybeCloseDockedFilePreviewOnEscape({ ...escape, target: dockButton })).toBe(true);
expect(escape.preventDefault).toHaveBeenCalledOnce();
expect(escape.stopPropagation).toHaveBeenCalledOnce();
expect(app.terminal.focus).toHaveBeenCalledOnce();
expect(overlay.parentElement).toBe(document.body);
});
it('stays floating during a split and survives closing and reopening the preview', () => {
const { app, document, main, overlay } = setup('');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
app.openSplitPane('pane-b');
const split = document.querySelector('.terminal-split-container');
expect(split).not.toBeNull();
expect(overlay.parentElement).toBe(document.body);
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
app.closeSplitPane();
expect(split?.isConnected).toBe(false);
expect(overlay.isConnected).toBe(true);
app.closeFilePreview();
overlay.classList.add('visible');
app.toggleFilePreviewDock();
expect(overlay.parentElement).toBe(main);
});
it.each([
['', false],
['tiles-active', true],
['webview-active', true],
])('stays floating when docking is unavailable (layout %s, wide %s)', (layout, wide) => {
const { app, document, overlay } = setup(layout, wide);
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
expect(app._isFilePreviewDocked()).toBe(false);
});
it('never docks while the Codex files setting is off', () => {
const { app, document, overlay } = setup('', true, false);
app.toggleFilePreviewDock();
app._setFilePreviewDocked(true);
expect(overlay.parentElement).toBe(document.body);
expect(overlay.classList.contains('is-docked')).toBe(false);
expect(app._isFilePreviewDocked()).toBe(false);
});
it('sits in page flow when docked, under modals and the response viewer', () => {
// The floating overlay's z-index 5100 would put a docked pane above every
// modal backdrop (1000) and the response viewer sheet (5000).
const docked = stylesCss.match(
/\.main:not\(\.tiles-active, \.webview-active\) > \.file-preview-overlay\.is-docked \{([^}]*)\}/
);
expect(docked).not.toBeNull();
expect(docked![1]).toMatch(/z-index:\s*auto;/);
});
it('ships the Dock button hidden, and hidden means hidden at every width', () => {
expect(indexHtml).toMatch(/<button type="button" class="btn-icon-sm" id="filePreviewDockBtn" hidden/);
expect(stylesCss).toMatch(/#filePreviewDockBtn\[hidden\] \{\s*display: none !important;/);
expect(panelsJs).toContain('if (dockBtn) dockBtn.hidden = !this._codexFilePreviewsEnabled?.();');
});
});
+8 -1
View File
@@ -42,7 +42,14 @@ const MOBILE_VISIBLE_ALLOWLIST = new Set<string>(['btn-file-viewer']);
// it's excluded from the default-visible enumeration rather than mobile-hidden.
// The edit history button is opt-in the same way, but it IS here: its panel is
// desktop-sized, so it stays off phones even when the setting is on.
const KNOWN_PHONE_HIDDEN = ['btn-settings', 'btn-lifecycle-log', 'btn-session-manager', 'btn-edit-history'];
// Response files (Codex files setting) is opt-in too and likewise stays off phones.
const KNOWN_PHONE_HIDDEN = [
'btn-settings',
'btn-lifecycle-log',
'btn-session-manager',
'btn-edit-history',
'btn-response-files',
];
function attrOf(openTag: string, name: string): string {
const m = openTag.match(new RegExp(`${name}="([^"]*)"`));
+3 -1
View File
@@ -358,6 +358,7 @@ describe('WebServer.renderIndexHtml', () => {
order: number;
kind: string;
external: boolean;
transcript?: string;
enabled: boolean;
available: boolean;
}>;
@@ -366,6 +367,7 @@ describe('WebServer.renderIndexHtml', () => {
label: 'Codex',
kind: 'agent',
external: true,
transcript: 'codex-rollout',
});
// claude is `kind: 'agent'` too; `external` is what keeps its Respawn/Ralph options visible.
expect(catalog.find((entry) => entry.id === 'claude')).toMatchObject({ kind: 'agent', external: false });
@@ -373,7 +375,7 @@ describe('WebServer.renderIndexHtml', () => {
expect(
catalog.every((entry) =>
Object.keys(entry).every((key) =>
['id', 'label', 'shortBadge', 'order', 'kind', 'external', 'enabled', 'available'].includes(key)
['id', 'label', 'shortBadge', 'order', 'kind', 'external', 'transcript', 'enabled', 'available'].includes(key)
)
)
).toBe(true);
+244 -3
View File
@@ -30,6 +30,8 @@ import { describe, expect, it, vi } from 'vitest';
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
const { document, NodeFilter } = dom.window;
const fetchResponse = vi.fn();
function loadCodemanAppClass() {
const constants = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
@@ -42,14 +44,25 @@ function loadCodemanAppClass() {
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
fetch: vi.fn(),
fetch: fetchResponse,
document,
NodeFilter,
marked,
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
window: {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
__codemanCliCatalog: [{ id: 'custom-codex', transcript: 'codex-rollout' }],
},
MobileDetection: {},
});
vm.runInContext(`${constants}\n${source}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const terminalUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
const addEventListener = vi.spyOn(document, 'addEventListener').mockImplementation(() => {});
try {
vm.runInContext(`${constants}\n${source}\n${terminalUi}\nglobalThis.__CodemanApp = CodemanApp;`, context);
} finally {
addEventListener.mockRestore();
}
return (context as { __CodemanApp: { prototype: { _linkifyFilePaths(root: unknown): void } } }).__CodemanApp;
}
@@ -341,3 +354,231 @@ describe('response viewer file-path linkifier', () => {
expect(APP_SOURCE).toMatch(/openFilePreview\(target \|\| filePath, sessionId\)/);
});
});
describe('Codex response files', () => {
it('lists previewable files once and opens their encoded URI in the originating session', () => {
const app = Object.create(CodemanApp.prototype);
app._sanitizeHtml = (html: string) => html;
app.openFilePreview = vi.fn();
app.activeSessionId = 'another-session';
app.sessions = new Map([['codex-session', { workingDir: '/work/project', paneCwd: '/work/project/live' }]]);
const body = document.createElement('div');
app._renderResponseFiles(
body,
[
'[Word brief](</work/project/Brief %231.docx>)\n\n[Image](out/image.png)',
'[Duplicate](/work/project/live/out/image.png) [PDF](file:///work/project/Export%20one.pdf)',
'[Web](https://example.com/x.pdf) [Network](file://remote/share/x.pdf) [Code](src/app.ts)',
],
'codex-session'
);
const links = Array.from(body.querySelectorAll('button'));
expect(links.map((link) => link.textContent)).toEqual(['Word brief', 'Image', 'PDF']);
// Buttons, not <a href="#">: under <base href> a middle-click on "#" opened the app root.
expect(body.querySelector('a')).toBeNull();
expect(links.every((link) => link.type === 'button')).toBe(true);
expect(app.openFilePreview).not.toHaveBeenCalled();
for (const link of links) link.click();
expect(app.openFilePreview.mock.calls).toEqual([
['/work/project/Brief #1.docx', 'codex-session', null, { dock: true }],
['/work/project/live/out/image.png', 'codex-session', null, { dock: true }],
['/work/project/Export one.pdf', 'codex-session', null, { dock: true }],
]);
});
it('shows an empty state when the response contains no previewable files', () => {
const app = Object.create(CodemanApp.prototype);
app._renderMarkdown = renderChat;
const body = document.createElement('div');
app._renderResponseFiles(body, ['No files in this response.'], 'codex-session');
expect(body.textContent).toBe('No previewable files in the latest response.');
});
});
describe('Codex terminal response link matching', () => {
function appForTranscript() {
const app = Object.create(CodemanApp.prototype);
app._sanitizeHtml = (html: string) => html;
app.sessions = new Map([['codex-session', { workingDir: '/work/project', paneCwd: '/work/project/live' }]]);
return app;
}
it('uses the explicit destination behind an underlined label', () => {
const app = appForTranscript();
const session = 'codex-session';
expect(
app._findCodexResponseFile(
[
{ role: 'assistant', text: 'See [Word brief](<out/Word draft.docx>).' },
{ role: 'assistant', text: 'Repeated [Word brief](file:///work/project/live/out/Word%20draft.docx).' },
],
'Word brief',
session
)
).toBe('/work/project/live/out/Word draft.docx');
});
it('resolves a native sidebar filename only when its destination is unique', () => {
const app = appForTranscript();
const session = 'codex-session';
const message = { role: 'assistant', text: '[Preview image](file:///work/project/Image%20draft.png)' };
expect(app._findCodexResponseFile([message], 'Image draft.png', session, true)).toBe(
'/work/project/Image draft.png'
);
expect(
app._findCodexResponseFile(
[
message,
{
role: 'assistant',
text: '[Other](<out/Image draft.png>)',
},
],
'Image draft.png',
session,
true
)
).toBeNull();
});
it('renders only potential sidebar matches, including URI-encoded filenames', () => {
const app = appForTranscript();
const render = vi.spyOn(app, '_renderMarkdown');
const texts = [
'Unrelated message.',
'Only a prefix: Word',
'Only an extension: .docx',
'[Download](file:///work/Word%20draft.docx)',
];
const messages = texts.map((text) => ({ role: 'assistant', text }));
expect(app._findCodexResponseFile(messages, 'Word…draft.docx', 'codex-session', true)).toBe(
'/work/Word draft.docx'
);
expect(render).toHaveBeenCalledExactlyOnceWith(texts[3], { localFileLinks: true });
});
it('resolves an abbreviated native tab only when one path matches both visible ends', () => {
const app = appForTranscript();
const session = 'codex-session';
const name = 'Interview panel plan - requisition 2026943.docx';
const exact = { role: 'assistant', text: `[Download](<out/${name}>)` };
const near = { role: 'assistant', text: '[Wrong extension](<out/Interview draft 2026943.pdf>)' };
const label = 'Interview…26943.docx';
expect(app._findCodexResponseFile([exact, near], label, session, true)).toBe(`/work/project/live/out/${name}`);
expect(
app._findCodexResponseFile(
[
exact,
{
role: 'assistant',
text: '[Another draft](<other/Interview alternate 2026943.docx>)',
},
],
label,
session,
true
)
).toBeNull();
});
it.each([
'[Word brief](out/different.docx)',
'[Word brief](https://example.test/report.docx)',
'[Word brief](src/script.ts)',
])('declines an ambiguous label when another reference is %s', (other) => {
const app = appForTranscript();
expect(
app._findCodexResponseFile(
[
{ role: 'assistant', text: '[Word brief](out/report.docx)' },
{ role: 'assistant', text: other },
],
'Word brief',
'codex-session'
)
).toBeNull();
});
});
describe('response viewer modes', () => {
function setup(mode: string) {
document.body.innerHTML = `<div id="responseViewerBackdrop"></div><div id="responseViewer">
<h2 id="responseViewerTitle"></h2><button id="responseViewerMore" style="display:none"></button>
<div id="responseViewerBody"></div></div>`;
const app = Object.create(CodemanApp.prototype);
app.activeSessionId = 'session';
app.sessions = new Map([['session', { mode, workingDir: '/work', paneCwd: '/work/live' }]]);
app._sanitizeHtml = (html: string) => html;
app._buildResponseViewerMessage = () => document.createElement('div');
app._bindResponseViewerInteractions = vi.fn();
app.openFilePreview = vi.fn();
app.terminal = { focus: vi.fn() };
const focused = { focus: vi.fn() };
app._focusedPane = () => ({ terminal: focused });
app._shouldFocusTerminalForTabSwitch = () => true;
app._codexFilePreviewsEnabled = () => true;
fetchResponse.mockReset().mockResolvedValue({
ok: true,
json: async () => ({ data: { text: '[Plan](out/plan.docx)' } }),
});
return { app, focused };
}
it('restores More for a normal response without hasContext', async () => {
const { app } = setup('claude');
await app.toggleResponseViewer();
expect(document.querySelector<HTMLElement>('#responseViewerMore')?.style.display).toBe('');
});
it('opens the file picker for a registered rollout reader and returns focus to the originating pane', async () => {
const { app, focused } = setup('custom-codex');
await app.toggleResponseViewer(true);
expect(document.getElementById('responseViewer')?.dataset.filesOnly).toBe('true');
expect(document.getElementById('responseViewerTitle')?.textContent).toBe('Response files');
document.querySelector<HTMLButtonElement>('#responseViewerBody button')?.click();
expect(app.openFilePreview).toHaveBeenCalledWith('/work/live/out/plan.docx', 'session', null, { dock: true });
expect(focused.focus).toHaveBeenCalledOnce();
expect(app.terminal.focus).not.toHaveBeenCalled();
});
it('does not open the file picker while the Codex files setting is off', async () => {
const { app } = setup('custom-codex');
delete app._codexFilePreviewsEnabled; // the real reader: the device settings, default OFF
app.loadAppSettingsFromStorage = () => ({});
app.getDefaultSettings = () => ({});
expect(app._codexFilePreviewsEnabled()).toBe(false);
await app.toggleResponseViewer(true);
expect(fetchResponse).not.toHaveBeenCalled();
expect(document.getElementById('responseViewer')?.classList.contains('visible')).toBe(false);
});
it('hides the Response files button while the setting is off, even in a Codex session', () => {
const { app } = setup('custom-codex');
document.body.insertAdjacentHTML(
'beforeend',
'<button id="responseFilesBtn" class="btn-icon-header btn-response-files btn-response-files--hidden" hidden></button>'
);
const button = document.getElementById('responseFilesBtn')!;
app._codexFilePreviewsEnabled = () => false;
app._syncResponseFilesButton();
expect(button.classList.contains('btn-response-files--hidden')).toBe(true);
app._codexFilePreviewsEnabled = () => true;
app._syncResponseFilesButton();
expect(button.classList.contains('btn-response-files--hidden')).toBe(false);
expect(button.hidden).toBe(false);
app.activeSessionId = 'claude-session';
app._syncResponseFilesButton();
expect(button.hidden).toBe(true); // the setting alone never shows it outside a Codex session
});
it('closes the file picker without focusing an xterm when the keyboard is hidden', async () => {
const { app, focused } = setup('custom-codex');
app._shouldFocusTerminalForTabSwitch = () => false;
await app.toggleResponseViewer(true);
expect(app.closeResponseViewer()).toBe(true);
expect(focused.focus).not.toHaveBeenCalled();
expect(app.terminal.focus).not.toHaveBeenCalled();
});
});
+115 -4
View File
@@ -19,11 +19,13 @@ import { describe, expect, it, vi } from 'vitest';
type Link = { text: string; activate: (ev: unknown, text: string) => void; hover: () => void; leave: () => void };
type Provider = { provideLinks: (line: number, cb: (links: Link[] | undefined) => void) => void };
function loadHarness() {
function loadHarness(fetchResponse = vi.fn()) {
const CodemanApp = function CodemanApp(this: unknown) {};
const windowRef: Record<string, unknown> = {};
const context = vm.createContext({
window: windowRef,
AbortSignal,
fetch: fetchResponse,
document: {
body: { classList: { contains: () => false } },
activeElement: null,
@@ -48,20 +50,25 @@ function loadHarness() {
}
/** A one-screen xterm stand-in holding `lines`, recording every provider registered on it. */
function fakeTerminal(lines: string[]) {
function fakeTerminal(lines: string[], cols = 80) {
const providers: Provider[] = [];
return {
cols: 80,
cols,
providers,
registerLinkProvider: (p: Provider) => providers.push(p),
buffer: {
active: {
length: lines.length,
viewportY: 0,
getLine: (row: number) =>
row >= 0 && row < lines.length
? {
isWrapped: false,
translateToString: (trim?: boolean) => (trim === false ? lines[row].padEnd(80) : lines[row]),
getCell: (col: number) => ({ getChars: () => lines[row][col] ?? ' ', getWidth: () => 1 }),
translateToString: (trim?: boolean, start = 0, end = cols) => {
const text = lines[row].padEnd(cols).slice(start, end);
return trim ? text.trimEnd() : text;
},
}
: undefined,
},
@@ -146,3 +153,107 @@ describe('registerFilePathLinkProvider with a target (a second pane)', () => {
expect(app.openFilePreview).toHaveBeenCalledWith('/tmp/a.pdf', 'second');
});
});
describe('native Codex sidebar files', () => {
const left = 'wrote /tmp/keep.png'.padEnd(42);
const tab = ' Brief…26943.docx × +';
const picker = ' › · Word draft.docx Project root';
function setupSidebar() {
const app = makeApp();
app._supportsCodexResponseFiles = () => true;
app._codexFilePreviewsEnabled = () => true;
const terminal = fakeTerminal([
left + '│' + tab,
' '.repeat(42) + '│ Open in sidebar',
' '.repeat(42) + '│ Files 1',
' '.repeat(42) + '│' + picker,
' '.repeat(42) + '│ body /tmp/normal.png',
]);
app.terminal = terminal;
app._clientPointToCell = (col: number, row: number) => ({ col, row });
return { app, terminal };
}
it('finds a shortened tab and a picker entry without claiming the close button or directory suffix', () => {
const { app, terminal } = setupSidebar();
expect(app._codexTerminalLinkLabel(terminal, 47, 1)).toMatchObject({ label: 'Brief…26943.docx', sidebar: true });
expect(app._codexTerminalLinkLabel(terminal, 44 + tab.indexOf('×'), 1)).toBeNull();
expect(app._codexTerminalLinkLabel(terminal, 52, 4)).toMatchObject({ label: 'Word draft.docx', sidebar: true });
expect(app._codexTerminalLinkLabel(terminal, 44 + picker.indexOf('Project'), 4)).toBeNull();
});
it('suppresses generic sidebar suffixes and preserves ordinary paths beside and below them', () => {
const { app } = setupSidebar();
const provider = app.registerFilePathLinkProvider();
expect(linksOn(provider, 1).map(({ text }) => text)).toEqual(['/tmp/keep.png']);
expect(linksOn(provider, 4)).toEqual([]);
expect(linksOn(provider, 5).map(({ text }) => text)).toEqual(['/tmp/normal.png']);
app._supportsCodexResponseFiles = () => false;
expect(linksOn(provider, 4).map(({ text }) => text)).toContain('draft.docx');
});
it('leaves sidebar rows to Codex while the Codex files setting is off', () => {
const { app, terminal } = setupSidebar();
app._codexFilePreviewsEnabled = () => false;
// No sidebar label is taken, so the click is forwarded to Codex as before.
expect(app._codexTerminalLinkLabel(terminal, 47, 1)).toBeNull();
expect(app._codexTerminalLinkLabel(terminal, 52, 4)).toBeNull();
// And the row keeps the ordinary linkifier's links, exactly as on master.
const provider = app.registerFilePathLinkProvider();
expect(linksOn(provider, 4).map(({ text }) => text)).toContain('draft.docx');
});
it('caches the parsed conversation per session until its next turn', async () => {
const fetchResponse = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { messages: [] } }) });
const app = loadHarness(fetchResponse);
const session = { status: 'idle', lastSubmitAt: 1 };
app.sessions = new Map([['pane', session]]);
await app._codexResponseMessages('pane');
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(1);
session.lastSubmitAt = 2; // a new turn
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(2);
session.status = 'busy'; // a growing rollout is never served from the cache
await app._codexResponseMessages('pane');
await app._codexResponseMessages('pane');
expect(fetchResponse).toHaveBeenCalledTimes(4);
});
});
describe('Codex response click fallback', () => {
const clicked = { label: 'Word draft.docx', row: 1, start: 42, end: 57, sidebar: true };
const point = { clientX: 40, clientY: 10 };
it.each(['failed load', 'no match', 'superseded click', 'moved cell', 'matched file'])(
'handles %s',
async (outcome) => {
const fetchResponse = vi.fn();
const app = loadHarness(fetchResponse);
const forward = vi.fn();
const terminal = fakeTerminal([]);
const match = vi.fn(() => (outcome === 'no match' ? null : '/work/Word draft.docx'));
app._findCodexResponseFile = match;
app._codexTerminalLinkLabel = () => (outcome === 'moved cell' ? { ...clicked, row: 2 } : clicked);
app._openResponseFile = vi.fn();
if (outcome === 'failed load') fetchResponse.mockRejectedValue(new Error('offline'));
else fetchResponse.mockResolvedValue({ ok: true, json: async () => ({ data: { messages: [] } }) });
await app._openCodexTerminalResponseFile(
terminal,
'pane',
point,
clicked,
() => outcome !== 'superseded click',
forward
);
expect(forward).toHaveBeenCalledTimes(Number(outcome === 'failed load' || outcome === 'no match'));
if (outcome === 'matched file') {
expect(app._openResponseFile).toHaveBeenCalledWith('/work/Word draft.docx', 'pane');
} else {
expect(app._openResponseFile).not.toHaveBeenCalled();
}
if (outcome === 'superseded click') expect(match).not.toHaveBeenCalled();
}
);
});
+46
View File
@@ -493,6 +493,52 @@ describe('terminal touch tap mouse guard', () => {
expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[<0;21;6M\x1b[<0;21;6m' }]);
});
it('desktop click: resolves a Codex label from underlined cells before forwarding mouse input', () => {
const { app } = loadTerminalUiHarness();
const session = { mode: 'codex', cliMouseTracking: true };
app.activeSessionId = 'sess-1';
app.sessions = new Map([['sess-1', session]]);
app.terminal = createTerminalGrid(['• Word brief', '', '› '], 2);
const getLine = app.terminal.buffer.active.getLine;
app.terminal.buffer.active.getLine = (row: number) => {
const line = getLine(row);
if (row !== 0) return line;
return {
...line,
translateToString: (_trim: boolean, start: number, end: number) => '• Word brief'.slice(start, end),
getCell: (column: number) => ({ getWidth: () => 1, isUnderline: () => column >= 2 && column < 12 }),
};
};
app._supportsCodexResponseFiles = () => true;
app._openCodexTerminalResponseFile = vi.fn().mockResolvedValue(undefined);
app._sendSyntheticSgrTap = vi.fn();
app._handleDesktopTerminalClick({
isTrusted: true,
button: 0,
detail: 1,
clientX: 40,
clientY: 10,
target: { closest: () => ({}) },
});
expect(app._openCodexTerminalResponseFile).toHaveBeenCalledWith(
app.terminal,
'sess-1',
{ clientX: 40, clientY: 10 },
{ label: 'Word brief', row: 1, start: 2, end: 12 },
expect.any(Function),
expect.any(Function)
);
expect(app._sendSyntheticSgrTap).not.toHaveBeenCalled();
// A double-click selects the word: its second click returns before it can supersede
// this one, so the selection it leaves is what makes the pending lookup stale.
const stillCurrent = app._openCodexTerminalResponseFile.mock.calls[0][4];
expect(stillCurrent()).toBe(true);
app.terminal.hasSelection = () => true;
expect(stillCurrent()).toBe(false);
});
it('desktop click: skips clicks that already have a meaning elsewhere', () => {
const { app } = loadTerminalUiHarness();
const sent: string[] = [];