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

+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,
};