Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions CLAUDE.md

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions docs/wiki/Mobile-Guide.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,22 @@ looks exactly like a dead button.
On phones this button replaces the desktop's **Run Shell** control; starting a shell moved
into the Run dropdown.

## Tapping, links and copying

- **Tap a link** in terminal output and it opens in a new tab. Same for a link in an agent's
answer in the response viewer — it opens a tab rather than navigating the dashboard away,
which on a phone would unload the whole session view.
- **Tap a file path** an agent printed and the file-preview overlay opens; a log path opens the
log viewer. Works in scrolled-up transcript too.
- A tap on the prose *beside* a link still places the cursor as usual, and a tap on a dialog's
numbered choice still answers the dialog even when the row contains a path — the dialog wins,
because on a phone it is the only interaction that matters.
- **Long-press to select text**, then drag, or tap the other end to extend the selection — no
hairline handles to grab. A small bar offers **Copy**, **Line** (the whole logical line,
wrapped rows included) and dismiss. Copy works on plain-HTTP installs too, where the browser
clipboard API is unavailable.
- A swipe is never mistaken for a long-press, and the keyboard stays down while you select.

## Scrolling and the keyboard

- The terminal and toolbar shift up when the keyboard opens, tracked through the browser's
Expand All@@ -97,6 +113,10 @@ into the Run dropdown.
keeps focus so you can place the caret.
- A scroll is never mistaken for a tap: travel is measured from the start of the gesture, and
multi-touch never counts.
- **A long prompt stays visible.** Once what you are typing wraps past the last visible row it
grows upward over the transcript instead of sliding under the keyboard, so the end of the
sentence — where the cursor is — is always on screen. A prompt taller than the visible strip
shows its tail.

## Voice

Expand Down
51 changes: 42 additions & 9 deletions packages/xterm-zerolag-input/src/overlay-renderer.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,38 +65,71 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
charTop,
charHeight,
promptRow,
totalRows,
font,
showCursor,
cursorColor,
terminal,
} = params;

// Position container at prompt row.
// ── Keep what is being typed ON SCREEN ────────────────────────────
//
// The overlay lays its wrapped lines out DOWNWARD from the prompt row, and
// nothing past the last terminal row is visible. On a phone the strip left
// above the on-screen keyboard is only a handful of rows, so a prompt long
// enough to wrap ran off the bottom and the user was typing blind — the tail
// of their own sentence, the part they are actually looking at, hidden behind
// the keyboard.
//
// So the composer grows UPWARD once it reaches the last row, exactly as a real
// terminal's does: every line div is opaque (see makeLine), so the lines cover
// transcript rows above instead of vanishing under the keyboard below, and the
// newest text stays where the eye is. A prompt taller than the whole viewport
// keeps its TAIL for the same reason.
//
// `startCol` indents only the line that begins at the prompt marker, so it is
// dropped along with that line when the tail is all that fits.
const rows = totalRows && totalRows > 0 ? totalRows : terminal?.rows;
let visibleLines = lines;
let keepsPromptLine = true;
let topRow = promptRow;
if (rows && rows > 0) {
if (lines.length > rows) {
visibleLines = lines.slice(lines.length - rows);
keepsPromptLine = false;
topRow = 0;
} else if (promptRow + lines.length > rows) {
topRow = rows - lines.length;
}
}
topRow = Math.max(0, topRow);

container.style.left = '0px';
container.style.top = promptRow * cellH + 'px';
container.style.top = topRow * cellH + 'px';

// Clear and rebuild (typically 1-3 line divs, negligible cost)
container.innerHTML = '';
const fullWidthPx = totalCols * cellW;

for (let i = 0; i < lines.length; i++) {
const leftPx = i === 0 ? startCol * cellW : 0;
const widthPx = i === 0 ? fullWidthPx - leftPx : fullWidthPx;
for (let i = 0; i < visibleLines.length; i++) {
const indents = i === 0 && keepsPromptLine;
const leftPx = indents ? startCol * cellW : 0;
const widthPx = indents ? fullWidthPx - leftPx : fullWidthPx;
const topPx = i * cellH;
const lineEl = makeLine(lines[i], leftPx, topPx, widthPx, cellH, cellW, charTop, charHeight, font, terminal);
const lineEl = makeLine(visibleLines[i], leftPx, topPx, widthPx, cellH, cellW, charTop, charHeight, font, terminal);
container.appendChild(lineEl);
}

// Block cursor at end of last line (use visual width for CJK support)
if (showCursor) {
const lastLine = lines[lines.length - 1];
const lastLineLeft = lines.length === 1 ? startCol : 0;
const lastLine = visibleLines[visibleLines.length - 1];
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine);
if (cursorCol < totalCols) {
const cursor = document.createElement('span');
cursor.style.cssText = 'position:absolute;display:inline-block';
cursor.style.left = cursorCol * cellW + 'px';
cursor.style.top = (lines.length - 1) * cellH + 'px';
cursor.style.top = (visibleLines.length - 1) * cellH + 'px';
cursor.style.width = cellW + 'px';
cursor.style.height = cellH + 'px';
cursor.style.backgroundColor = cursorColor;
Expand Down
7 changes: 7 additions & 0 deletions packages/xterm-zerolag-input/src/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -172,6 +172,13 @@ export interface RenderParams {
/** Height of the character rendering area (px). */
charHeight: number;
promptRow: number;
/**
* Visible terminal rows. When given, the overlay is kept ON SCREEN: it grows
* upward instead of running off the bottom edge, and a wrapped prompt taller
* than the viewport keeps its tail. Omit to lay out straight down from
* `promptRow` (the historical behaviour).
*/
totalRows?: number;
font: FontStyle;
showCursor: boolean;
cursorColor: string;
Expand Down
6 changes: 5 additions & 1 deletion packages/xterm-zerolag-input/src/zerolag-input-addon.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -565,7 +565,10 @@ export class ZerolagInputAddon implements XtermAddon {

// Skip redundant re-renders — include text content to detect
// same-length changes (e.g., setFlushed with different text)
const renderKey = `${displayText}:${startCol}:${activePrompt.row}:${activePrompt.col}:${totalCols}:${this._flushedOffset}`;
// `rows` is part of the key: the layout is clamped to the visible rows
// (see renderOverlay), so a keyboard opening — which changes rows without
// changing the text — must not be skipped as a redundant render.
const renderKey = `${displayText}:${startCol}:${activePrompt.row}:${activePrompt.col}:${totalCols}:${this._terminal.rows}:${this._flushedOffset}`;
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') return;
this._lastRenderKey = renderKey;

Expand DownExpand Up@@ -612,6 +615,7 @@ export class ZerolagInputAddon implements XtermAddon {
charTop,
charHeight,
promptRow: activePrompt.row,
totalRows: this._terminal.rows,
font: this._font,
showCursor: this._options.showCursor,
cursorColor,
Expand Down
85 changes: 85 additions & 0 deletions packages/xterm-zerolag-input/test/overlay-renderer.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -418,3 +418,88 @@ describe('stringCellWidth', () => {
expect(stringCellWidth(null, '')).toBe(0);
});
});

describe('renderOverlay — staying on screen (totalRows)', () => {
// A phone with the keyboard up leaves only a handful of terminal rows. The
// overlay lays its wrapped lines out downward from the prompt row, so a long
// prompt used to run off the bottom edge and the user typed blind, with the
// tail of their own sentence behind the keyboard. With totalRows known, the
// composer grows UPWARD instead — the line divs are opaque, so they cover
// transcript above rather than disappearing below.
const linesOf = (n: number) => Array.from({ length: n }, (_, i) => `line${i}`);
const lineDivs = (container: HTMLDivElement) =>
Array.from(container.children).filter((el) => el.tagName === 'DIV') as HTMLDivElement[];

it('lifts the block so its last line lands on the last visible row', () => {
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(5), promptRow: 10, totalRows: 12, cellH: 17 }));

// 10 + 5 would end on row 14 of a 12-row screen; the block starts at 7 instead.
expect(container.style.top).toBe(7 * 17 + 'px');
expect(lineDivs(container)).toHaveLength(5);
});

it('leaves the prompt row alone when the block already fits', () => {
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(3), promptRow: 5, totalRows: 24, cellH: 17 }));

expect(container.style.top).toBe(5 * 17 + 'px');
});

it('keeps the TAIL when the prompt is taller than the whole viewport', () => {
// The end is where the cursor is, and where the user is looking.
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(6), promptRow: 2, totalRows: 3, cellH: 20 }));

const divs = lineDivs(container);
expect(container.style.top).toBe('0px');
expect(divs).toHaveLength(3);
expect(divs.map((d) => d.textContent)).toEqual(['line3', 'line4', 'line5']);
});

it('drops the prompt indent once the prompt line is no longer shown', () => {
// startCol indents only the line that begins at the prompt marker.
const container = document.createElement('div');
renderOverlay(
container,
makeParams({ lines: linesOf(6), promptRow: 2, totalRows: 3, startCol: 5, cellW: 10, totalCols: 80 })
);

const first = lineDivs(container)[0];
expect(first.style.left).toBe('0px');
expect(first.style.width).toBe(80 * 10 + 'px');
});

it('rides the cursor on the last VISIBLE line', () => {
const container = document.createElement('div');
renderOverlay(
container,
makeParams({ lines: ['aaa', 'bbb', 'ccc', 'ddd'], promptRow: 9, totalRows: 3, cellH: 20, cellW: 10, startCol: 4 })
);

const cursor = Array.from(container.children).find((el) => el.tagName === 'SPAN') as HTMLSpanElement;
// Tail is the last 3 lines, so the cursor sits on row 2 (0-based) of the block…
expect(cursor.style.top).toBe(2 * 20 + 'px');
// …at column 3, NOT startCol + 3: the indented prompt line is not shown.
expect(cursor.style.left).toBe(3 * 10 + 'px');
});

it('lays out straight down when totalRows is absent (unchanged behaviour)', () => {
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(9), promptRow: 20, cellH: 17 }));

expect(container.style.top).toBe(20 * 17 + 'px');
expect(lineDivs(container)).toHaveLength(9);
});

it('falls back to the terminal row count when totalRows is not passed', () => {
// The addon passes totalRows, but a stale bundle / third-party caller may not.
const container = document.createElement('div');
renderOverlay(
container,
makeParams({ lines: linesOf(4), promptRow: 8, cellH: 17, terminal: { rows: 10, cols: 80 } as never })
);

expect(container.style.top).toBe(6 * 17 + 'px');
});
});
22 changes: 22 additions & 0 deletions src/web/public/app.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2053,6 +2053,28 @@ class CodemanApp {
wrap.appendChild(actions);
wrap.appendChild(pre);
});
// Links open in a NEW tab.
//
// marked emits a bare `<a href>` and the sanitizer's allowlist has no
// `target`, so a tap in the chat NAVIGATED THE APP AWAY: on a phone that
// unloads the whole dashboard — SSE, terminal buffers, unsent composer
// text — and the OS back gesture reloads it from scratch, which is what
// "links don't open" reads as on mobile, with no middle-click or
// open-in-new-tab affordance to work around it.
//
// This pass runs AFTER sanitizing, so it is the only source of these two
// attributes: whatever an agent wrote is already gone, and `rel` is set on
// the same element in the same breath, so no page Codeman opens ever gets
// a `window.opener` handle back (reverse tabnabbing).
//
// A fragment link stays in-page, and mailto:/tel: are handed to the OS —
// giving those a target just strands an empty tab.
tmpl.content.querySelectorAll('a[href]').forEach((a) => {
const href = a.getAttribute('href') || '';
if (!href || href.startsWith('#') || /^(?:mailto|tel):/i.test(href)) return;
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
});
return tmpl.innerHTML;
} catch { /* fall through */ }
}
Expand Down
105 changes: 105 additions & 0 deletions src/web/public/constants.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1035,7 +1035,112 @@ function previewsInFileViewer(filePath) {
return FILE_PREVIEW_EXTENSIONS.has(ext);
}


/**
* The LOGICAL line a terminal row belongs to — the rows it spans, its text as one
* string, and a two-way map between that string and terminal cells.
*
* One definition, two consumers: the link provider matches its patterns over this
* text (`registerFilePathLinkProvider`) and touch selection measures words and
* whole lines with it (`_touchSelectionLogicalLine`). They MUST agree — a link that
* spans a wrap and a "Line" that stops at the screen edge is the same bug twice.
*
* Two kinds of continuation, and handling only the first is not enough:
*
* 1. **Soft wrap** — the emulator ran out of columns and flags the next row
* `isWrapped`. It inserts nothing, so the row's text is joined verbatim.
* 2. **Hard wrap** — the program wrapped the text itself and emitted a real
* newline, so nothing is flagged. A row that fills the last column is taken
* as continuing into the next; that is the only trace a hard wrap leaves.
*
* ⚠️ A hard-wrapped continuation may carry the program's own INDENT, and joining
* that verbatim puts whitespace in the middle of the token being stitched. That is
* why an agent's numbered list —
*
* 1. https://github.com/users/someone/packages/container/p
* ackage/thing
*
* — opened only `…/container/p`: the URL pattern stops at the space the indent
* contributed. So the leading whitespace of a HARD continuation is dropped, and
* `colStart` on that segment records how much, keeping the cell mapping exact. A
* soft continuation keeps its leading whitespace, since the terminal never adds
* any and it is therefore real content.
*
* ⚠️ Only the final row is trimmed. Continuation rows are read UNTRIMMED so each
* contributes exactly `cols` cells; trimming one would shift every later offset.
*
* The row span is bounded by `maxRows` (12 by default): this runs on every hover,
* and a screenful of full-width output would otherwise re-scan the viewport each
* time.
*
* @param {{getLine: (row: number) => any, length: number}} buffer xterm buffer.
* @param {number} row 0-based ABSOLUTE buffer row to expand around.
* @param {number} cols Terminal width.
* @param {number} [maxRows] Row-span bound.
* @returns {{startRow: number, endRow: number, text: string,
* offsetToCell: (offset: number) => {row: number, col: number},
* cellToOffset: (row: number, col: number) => number} | null}
* 0-based rows and columns throughout; null when the row does not exist.
*/
function terminalLogicalLine(buffer, row, cols, maxRows) {
if (!buffer || typeof buffer.getLine !== 'function') return null;
const width = Math.max(1, cols || 1);
const bound = Math.max(1, maxRows || 12);
const lineAt = (r) => (r >= 0 ? buffer.getLine(r) : undefined);
if (!lineAt(row)) return null;

const continuesPrevious = (r) => {
if (r <= 0) return false;
if (lineAt(r)?.isWrapped) return true;
const prev = lineAt(r - 1);
return !!prev && (prev.translateToString(true) || '').length >= width;
};

let startRow = row;
while (startRow > 0 && row - startRow < bound && continuesPrevious(startRow)) startRow--;
let endRow = row;
const length = Number.isFinite(buffer.length) ? buffer.length : endRow + 1;
while (endRow + 1 < length && endRow - startRow < bound && continuesPrevious(endRow + 1)) endRow++;

const segments = [];
let text = '';
for (let r = startRow; r <= endRow; r++) {
const line = lineAt(r);
if (!line) break;
let rowText = line.translateToString(r === endRow) || '';
let colStart = 0;
if (r > startRow && !line.isWrapped) {
const indent = rowText.length - rowText.replace(/^\s+/, '').length;
colStart = indent;
rowText = rowText.slice(indent);
}
segments.push({ row: r, textStart: text.length, colStart, length: rowText.length });
text += rowText;
}

const offsetToCell = (offset) => {
for (let i = segments.length - 1; i >= 0; i--) {
const seg = segments[i];
if (offset >= seg.textStart || i === 0) {
return { row: seg.row, col: seg.colStart + (offset - seg.textStart) };
}
}
return { row: startRow, col: offset };
};

const cellToOffset = (targetRow, targetCol) => {
for (const seg of segments) {
if (seg.row !== targetRow) continue;
return seg.textStart + Math.max(0, targetCol - seg.colStart);
}
return -1;
};

return { startRow, endRow, text, offsetToCell, cellToOffset };
}

if (typeof window !== 'undefined') {
window.CodemanHistoryFormat = { formatHistoryBytes, computeHistoryTruncationNotice, computeRewriteScrollLine };
window.CodemanFilePaths = { absoluteFilePathPattern, previewsInFileViewer, FILE_PREVIEW_EXTENSIONS };
window.CodemanTerminalLines = { terminalLogicalLine };
}
5 changes: 5 additions & 0 deletions src/web/public/i18n.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -500,6 +500,11 @@
'Respawn Blocked': '重生已阻止',
'Task Complete': '任务完成',
'Copied to clipboard': '已复制到剪贴板',
// Terminal touch-selection bar (long-press to select). The bar is a sibling of
// `.xterm`, not a descendant, so SKIP_SELECTOR does not cover it and these apply.
Copy: '复制',
Line: '整行',
'Clear selection': '清除选择',
'Failed to copy': '复制失败',
'Checking…': '正在检查…',
'Starting…': '正在启动…',
Expand Down
Loading