8000 feat(cli): implement wmux read-screen (surface.read_text was a stub) by tawman · Pull Request #76 · amirlehmam/wmux · GitHub
[go: up one dir, main page]

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
6 changes: 2 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,16 +304,14 @@ The pipe server in `index.ts` handles V2 JSON-RPC methods. Most delegate to the
- `workspace.create`, `workspace.close`, `workspace.select`, `workspace.rename`, `workspace.list`
- `pane.split`, `pane.close`, `pane.focus`, `pane.zoom`, `pane.list`
- `surface.create`, `surface.close`, `surface.focus`, `surface.list`
- `surface.send_text`, `surface.send_key`, `surface.trigger_flash`
- `surface.send_text`, `surface.send_key`, `surface.read_text`, `surface.trigger_flash`
- `markdown.set_content`, `markdown.load_file`
- `notification.list`, `notification.clear`
- `sidebar.set_status`, `sidebar.set_progress`, `sidebar.log`, `sidebar.get_state`
- `browser.*` (via CDP bridge)
- `agent.spawn`, `agent.spawn_batch`, `agent.status`, `agent.list`, `agent.kill`
- `hook.event`, `diff.refresh`

**Partially implemented:** `surface.read_text` (stub — needs xterm serializer addon)

---

## wmux-orchestrator Plugin
Expand Down Expand Up @@ -363,7 +361,7 @@ wmux split [--down] [--type T] | close-pane | focus-pane | zoom-pane | list-pane

# Terminal I/O
wmux send <text> | send-key <key> [--ctrl] [--shift] [--alt]
wmux read-screen [--lines N] | trigger-flash
wmux read-screen [--lines N] [--surface <id>] | trigger-flash

# Browser (CDP)
wmux browser open <url> | snapshot | click @eN | type @eN <text>
Expand Down
10 changes: 8 additions & 2 deletions src/cli/wmux.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,13 @@ const COMMANDS: Record<string, (args: string[]) => Promise<void> | void> = {
'send-key': cmdSendKey,
'read-screen': async (args) => {
const lines = args.find((a, i) => args[i - 1] === '--lines');
print(await sendV2('surface.read_text', { lines: lines ? parseInt(lines) : 50 }));
// Same targeting rule as send/send-key: inside a pane the caller's own
// surface is the default; cross-pane reads take --surface explicitly.
const surfaceId = getFlag(args, '--surface') || process.env.WMUX_SURFACE_ID;
print(await sendV2('surface.read_text', {
...(surfaceId ? { surfaceId } : {}),
lines: lines ? parseInt(lines) : 50,
}));
},
'trigger-flash': async (args) => print(await sendV2('surface.trigger_flash', { id: args[1] })),

Expand Down Expand Up @@ -438,7 +444,7 @@ Surface: new-surface [--type T] [--color-scheme NAME], close-surface, focus-s
Pane: split [--down] [--type T] [--color-scheme NAME], close-pane, focus-pane, zoom-pane, list-panes, tree
pane new|close|focus|list (verb form, mirrors issue #4 example)
Layout: layout grid --count <N> [--type terminal] [--anchor-surface <id>]
Terminal: send <text>, send-key <key>, read-screen, trigger-flash
Terminal: send <text>, send-key <key>, read-screen [--lines N] [--surface <id>], trigger-flash
Browser: browser open|snapshot|click|type|fill|screenshot|get-text|eval|wait|back|forward|reload
Agent: agent spawn|spawn-batch|status|list|kill
Markdown: markdown <file> (open a file in a new markdown view)
Expand Down
31 changes: 28 additions & 3 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -531,9 +531,34 @@ app.whenReady().then(() => {
break;
}
case 'surface.read_text': {
// Read screen content — not easily available from PTY buffer directly.
// Return a note that this requires xterm.js serializer addon in the renderer.
respond({ text: '', note: 'Screen reading requires renderer-side xterm serializer' });
// Screen content lives in the renderer (xterm owns the buffer), so
// delegate to the __wmux_readScreen bridge global. It reads the ACTIVE
// buffer — alt buffer included — so full-screen TUIs return what is
// actually visible, as plain text (no ANSI escapes).
(async () => {
try {
const surfaceId = await resolvePtySurface(request.params?.surfaceId || request.params?.id);
if (!surfaceId.ok) { respondError(-32000, surfaceId.error); return; }
const rawLines = Number(request.params?.lines);
const lines = Number.isFinite(rawLines)
? Math.min(Math.max(Math.floor(rawLines), 1), 10000)
: 50;
// The surface's terminal is mounted in exactly one window; probe
// each until one has it, keeping the first miss as the error.
let result: { text?: string; error?: string } | null = null;
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
const r = await win.webContents.executeJavaScript(
`window.__wmux_readScreen?.(${JSON.stringify(surfaceId.id)}, ${lines})`
);
if (r && !r.error) { result = r; break; }
if (r && !result) result = r;
}
if (!result) { respondError(-32000, 'No window'); return; }
if (result.error) { respondError(-32000, result.error); return; }
respond(result);
} catch (err: any) { respondError(-32000, err.message); }
})();
break;
}
case 'surface.trigger_flash': {
Expand Down
16 changes: 16 additions & 0 deletions src/renderer/hooks/useTerminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,13 @@ const surfaceMouseEnabled = new Map<string, boolean>();
const surfaceBufferCache = new Map<string, string>();
const MAX_BUFFER_CACHE = 32;

// Live xterm instances keyed by surfaceId, so the pipe bridge can read screen
// content (surface.read_text / `wmux read-screen`) from the active buffer.
// Module-level like surfaceMouseEnabled: survives remounts; entries are
// registered on mount and removed on unmount (guarded so a StrictMode
// setup→cleanup→setup sequence can't delete the replacement instance).
export const surfaceTerminalRegistry = new Map<string, Terminal>();

// Convert a wheel delta to a line count (sign preserved, magnitude ≥ 1).
function wheelDeltaToLines(ev: WheelEvent, rows: number): number {
let amount: number;
Expand Down Expand Up @@ -368,6 +375,8 @@ export function useTerminal({ surfaceId, shell, cwd, visible = true, focused = t
// Open terminal in the DOM
terminal.open(terminalRef.current);

if (surfaceId) surfaceTerminalRegistry.set(surfaceId, terminal);

// Restore a buffer snapshot captured before a previous unmount (issue #49).
// Written now — before the PTY reattaches below — so the restored scrollback
// lands ahead of any new PTY output. We snapshot the normal buffer only
Expand Down Expand Up @@ -808,6 +817,13 @@ export function useTerminal({ surfaceId, shell, cwd, visible = true, focused = t
}
}

// Drop the read-screen registry entry — but only if it still points at
// THIS terminal (StrictMode re-setup may already have registered the
// replacement instance under the same surfaceId).
if (surfaceId && surfaceTerminalRegistry.get(surfaceId) === terminal) {
surfaceTerminalRegistry.delete(surfaceId);
}

// Release the GPU renderer (and its WebGL budget slot) before disposing
rendererRef.current?.dispose();
rendererRef.current = null;
Expand Down
23 changes: 23 additions & 0 deletions src/renderer/pipe-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import { useStore } from './store';
import { splitNode, removeLeaf, getAllPaneIds, findLeaf, buildGridLayout } from './store/split-utils';
import { killSurfacePty } from './store/pty-teardown';
import { surfaceTerminalRegistry } from './hooks/useTerminal';
import { PaneId, SurfaceId, WorkspaceId, SurfaceType } from '../shared/types';
import { v4 as uuid } from 'uuid';

Expand Down Expand Up @@ -308,6 +309,28 @@ export function initPipeBridge(): void {
return leaf.surfaces[idx]?.id || null;
};

// Read a terminal's screen as plain text (surface.read_text / read-screen).
// Reads the ACTIVE xterm buffer — alt buffer included, so a full-screen TUI
// returns what is actually visible. `lines` counts back from the bottom of
// the buffer (scrollback included); trailing blank lines are trimmed.
w.__wmux_readScreen = (surfaceId?: string, lines?: number) => {
const id = surfaceId || w.__wmux_getActiveSurfaceId?.();
if (!id) return { error: 'No active surface' };
const terminal = surfaceTerminalRegistry.get(id);
if (!terminal) {
return { error: `no terminal for surface ${id} (markdown/browser pane, another window, or closed)` };
}
const buf = terminal.buffer.active;
const count = Math.min(Math.max(Math.floor(lines ?? 50), 1), 10000);
const end = buf.length;
const out: string[] = [];
for (let i = Math.max(0, end - count); i < end; i++) {
out.push(buf.getLine(i)?.translateToString(true) ?? '');
}
while (out.length && out[out.length - 1] === '') out.pop();
return { text: out.join('\n'), lines: out.length, surfaceId: id };
};

// ─── Markdown ───────────────────────────────────────────────────────────────

w.__wmux_setMarkdownContent = (surfaceId: string, markdown: string) => {
Expand Down
0