feat(preview): COD-152 open Codex files in a docked preview

This commit is contained in:
Aamer Akhter committed 2026-11-23 13:06:33 -05:00
1 parent 5548c17c4a
commit 6de846ba9a
7 files changed
+520 -17

No files matched your search

+120 -13
View File
@@ -1423,6 +1423,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) {
@@ -2744,12 +2745,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>')
@@ -3196,19 +3204,102 @@ 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');
if (this.terminal) {
try {
this.terminal.focus();
} catch {
/* terminal may be detached mid-teardown */
}
}
return true;
}
_findCodexResponseFile(messages, label, session, sidebar = false) {
let match = null;
for (const message of messages) {
if (message.role !== 'assistant' || typeof message.text !== 'string' || (!sidebar && !message.text.includes(label))) continue;
const rendered = document.createElement('template');
rendered.innerHTML = this._renderMarkdown(message.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 = resolveLinkedFilePath(link.dataset.path, session.workingDir);
if (sidebar && path.split('/').pop() !== label) 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) {
if (this.filePreviewEdit?.dirty && !confirm('Discard unsaved changes?')) return;
return this.openFilePreview(path, sessionId, null, { dock: true });
}
_renderResponseFiles(body, responses, sessionId, session) {
const list = document.createElement('ul');
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 = resolveLinkedFilePath(link.dataset.path, session.workingDir);
if (!/^\/(?!\/)/.test(path) || !previewsInFileViewer(path) || seen.has(path)) continue;
seen.add(path);
const item = document.createElement('li');
const action = document.createElement('a');
action.href = '#';
action.className = 'rv-path rv-path-link';
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 body.textContent = 'No previewable files in the latest response.';
}
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 && session?.mode !== 'codex') return;
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
@@ -3217,8 +3308,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()
@@ -3229,13 +3322,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 ?? {};
@@ -3244,10 +3337,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, session);
} 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.
@@ -3276,8 +3373,13 @@ 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);
if (title) title.textContent = filesOnly ? 'Response files' : 'Last Response';
if (moreBtn) {
moreBtn.style.display = data.hasContext ? '' : 'none';
moreBtn.textContent = 'More';
}
// Last Response is a single rendered block, not a transcript — no filters here.
viewer.classList.add('visible');
backdrop.classList.add('visible');
@@ -3286,9 +3388,12 @@ 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) {
this.showToast('Unable to load response files', 'error');
}
}
}
@@ -6457,6 +6562,8 @@ class CodemanApp {
// ═══════════════════════════════════════════════════════════════
renderSessionTabs({ immediate = false } = {}) {
const responseFilesButton = this.$('responseFilesBtn');
if (responseFilesButton) responseFilesButton.hidden = this.sessions.get(this.activeSessionId)?.mode !== 'codex';
// Don't re-render while user is typing in the inline rename input
if (this._inlineRenameActive) return;
if (immediate) {
+4 -2
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" 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" 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">
+44
View File
@@ -3760,6 +3760,47 @@ Object.assign(CodemanApp.prototype, {
if (headerBtn) headerBtn.setAttribute('aria-expanded', 'false');
},
_setFilePreviewDocked(dock) {
const overlay = this.$('filePreviewOverlay');
if (!overlay || dock === overlay.classList.contains('is-docked')) return;
if (dock) {
const terminalWrap = this.$('terminalContainer')?.closest('.terminal-wrap');
if (!terminalWrap || !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.
*
@@ -3866,6 +3907,7 @@ Object.assign(CodemanApp.prototype, {
if (!overlay || !bodyEl) return;
if (options.dock) this._setFilePreviewDocked?.(true);
this._recordFilePreviewHistory(filePath, sessionId, attachmentId, options);
this._bindFilePreviewChrome();
@@ -4396,6 +4438,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.
@@ -4526,6 +4569,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
+53
View File
@@ -11923,6 +11923,54 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
display: flex;
}
#filePreviewDockBtn {
display: none;
}
@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;
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 {
@@ -13598,6 +13646,11 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
transform: translateY(0);
}
#responseFilesBtn[hidden],
.response-viewer[data-files-only='true'] :is(#responseViewerMore, #responseViewerCopy, #responseViewerCopyMarkdown) {
display: none !important;
}
.response-viewer-header {
display: flex;
align-items: center;
+155 -2
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 && !label.includes('…') && 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
@@ -2480,6 +2553,18 @@ Object.assign(CodemanApp.prototype, {
}
}
if (self.sessions?.get(getSessionId())?.mode === 'codex') {
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:',
@@ -6456,6 +6541,56 @@ 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) {
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;
},
async _openCodexTerminalResponseFile(terminal, sessionId, session, point, clicked, stillCurrent, forward) {
let path;
try {
const response = await fetch(`/api/sessions/${encodeURIComponent(sessionId)}/last-response?context=full`, {
signal: AbortSignal.timeout(3000),
});
if (response.ok) {
const { data } = await response.json();
if (Array.isArray(data?.messages)) path = this._findCodexResponseFile(data.messages, clicked.label, session, 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
@@ -6480,12 +6615,30 @@ 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 session = this.sessions?.get(sessionId);
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 = session?.mode === 'codex' && this._codexTerminalLinkLabel(terminal, clientX, clientY);
if (!link) {
forward();
return;
}
const stillCurrent = () =>
this._codexTerminalLinkClicks.get(terminal) === click &&
(target.sessionId ? terminal.element?.isConnected : this.activeSessionId === sessionId && this.terminal === terminal);
void this._openCodexTerminalResponseFile(terminal, sessionId, session, { clientX, clientY }, link, stillCurrent, forward)
.catch((error) => console.error('Unable to open Codex terminal response file:', error));
},
/**