Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(windows): session-host watch-attach, captureVisible and paneCwd verbs

review924f5b3ebc85
diff --git a/src/session-host/cwd-report.test.ts b/src/session-host/cwd-report.test.ts
new file mode 100644
index 000000000..4b9d9c924
--- /dev/null
+++ b/src/session-host/cwd-report.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+import { CWD_REPORT_MAX_CARRY, CwdReportScanner, parseCwdOsc } from './cwd-report'
+
+describe('parseCwdOsc', () => {
+ it('reads OSC 7 file URLs, percent-decoded, with a Windows drive path turned native', () => {
+ expect(parseCwdOsc('7;file://host/home/me/my%20dir')).toBe('/home/me/my dir')
+ expect(parseCwdOsc('7;file:///tmp')).toBe('/tmp')
+ expect(parseCwdOsc('7;file://PC/C:/Users/me/src')).toBe('C:\\Users\\me\\src')
+ expect(parseCwdOsc('7;file://PC/C:')).toBe('C:\\')
+ expect(parseCwdOsc('7;file://h/%E2%9C%93')).toBe('/✓')
+ })
+
+ it('reads OSC 9;9 with or without quotes', () => {
+ expect(parseCwdOsc('9;9;"C:\\Users\\me"')).toBe('C:\\Users\\me')
+ expect(parseCwdOsc('9;9;C:\\work')).toBe('C:\\work')
+ })
+
+ it("reads VS Code's 633;P;Cwd= with its own escaping", () => {
+ expect(parseCwdOsc('633;P;Cwd=C:\\\\a\\x3bb')).toBe('C:\\a;b')
+ expect(parseCwdOsc('633;P;Cwd=/srv/app')).toBe('/srv/app')
+ })
+
+ it('ignores everything that is not a cwd report, and garbage inside one', () => {
+ expect(parseCwdOsc('0;window title')).toBeNull()
+ expect(parseCwdOsc('52;c;aGVsbG8=')).toBeNull()
+ expect(parseCwdOsc('9;4;1;50')).toBeNull() // progress, not 9;9
+ expect(parseCwdOsc('7;http://host/x')).toBeNull()
+ expect(parseCwdOsc('7;file://host')).toBeNull()
+ expect(parseCwdOsc('9;9;')).toBeNull()
+ expect(parseCwdOsc('633;P;Cwd=a\x01b')).toBeNull()
+ expect(parseCwdOsc('7;file://h/%E2%9')).toBe('/%E2%9') // malformed escape: kept, never thrown
+ })
+})
+
+describe('CwdReportScanner', () => {
+ it('finds a report terminated by BEL or by ST, and returns the last one in a chunk', () => {
+ const s = new CwdReportScanner()
+ expect(s.push('plain output, nothing here')).toBeUndefined()
+ expect(s.push('a\x1b]7;file://h/one\x07b')).toBe('/one')
+ expect(s.push('\x1b]9;9;"C:\\x"\x1b\\ then \x1b]7;file://h/two\x1b\\')).toBe('/two')
+ })
+
+ it('carries a report split across chunks, including a split ESC and a split ST', () => {
+ const s = new CwdReportScanner()
+ expect(s.push('prompt\x1b')).toBeUndefined()
+ expect(s.push(']7;file://h/ho')).toBeUndefined()
+ expect(s.push('me/me\x1b')).toBeUndefined()
+ expect(s.push('\\$ ')).toBe('/home/me')
+ })
+
+ it('skips other OSCs (titles, clipboard) around a report', () => {
+ const s = new CwdReportScanner()
+ expect(s.push('\x1b]0;title\x07\x1b]7;file://h/w\x07\x1b]52;c;Zm9v\x07')).toBe('/w')
+ })
+
+ it('treats a new OSC before a terminator as abandoning the first', () => {
+ const s = new CwdReportScanner()
+ expect(s.push('\x1b]7;file://h/lost\x1b]7;file://h/kept\x07')).toBe('/kept')
+ })
+
+ it('drops an unterminated OSC that outgrows the carry cap instead of hoarding it', () => {
+ const s = new CwdReportScanner()
+ expect(s.push('\x1b]52;c;' + 'A'.repeat(CWD_REPORT_MAX_CARRY + 10))).toBeUndefined()
+ // The oversized partial was dropped: its eventual terminator cannot resurrect it, and a later
+ // report still parses.
+ expect(s.push('AAAA\x07\x1b]7;file://h/after\x07')).toBe('/after')
+ })
+})
diff --git a/src/session-host/cwd-report.ts b/src/session-host/cwd-report.ts
new file mode 100644
index 000000000..19e6ed1ec
--- /dev/null
+++ b/src/session-host/cwd-report.ts
@@ -0,0 +1,122 @@
+// The session host's answer to tmux's `#{pane_current_path}`: the working directory the pane's own
+// shell (or agent CLI) REPORTED in its output, parsed from the three escape sequences that carry one.
+//
+// OSC 7 ; file://<host>/<percent-encoded path> ST — the de-facto standard (VTE, iTerm2, WezTerm,
+// fish/zsh integrations, many agent CLIs)
+// OSC 9 ; 9 ; "<path>" ST — ConEmu / Windows Terminal's convention
+// OSC 633 ; P ; Cwd=<escaped path> ST — VS Code shell integration
+//
+// ST is BEL or ESC \. Pure, no Node imports: the host bundle and the unit tests share it.
+//
+// Why a reported cwd and not the process's: Windows has no portable way to read another process's
+// current directory (it lives in the target's PEB), and a pty's foreground process is not tracked by
+// the host the way a tmux pane's is. A shell that reports nothing leaves the answer null — the caller
+// already tried the node's LAUNCH cwd first, so null degrades to exactly the pre-feature behavior.
+// The spawn cwd is deliberately never used as a fallback answer for the same reason.
+
+const OSC_START = '\x1b]'
+/** Longest unterminated OSC carried to the next chunk. A real cwd report is a path plus a few bytes;
+ * anything longer is some other OSC (a 64 KB OSC 52 copy, a title) whose bytes we must not hoard. */
+export const CWD_REPORT_MAX_CARRY = 4096
+
+/** Decode `%XX` escapes as UTF-8. A malformed escape leaves the input as is (never throws). */
+function percentDecode(s: string): string {
+ try {
+ return decodeURIComponent(s)
+ } catch {
+ return s
+ }
+}
+
+/** `/C:/Users/x` (how a Windows path rides in a file URL) → `C:\Users\x`; anything else untouched. */
+function fromUrlPath(p: string): string {
+ const drive = /^\/([A-Za-z]):(\/.*)?$/.exec(p)
+ if (!drive) return p
+ return `${drive[1]}:${(drive[2] ?? '/').replace(/\//g, '\\')}`
+}
+
+/** VS Code's 633 value escaping: `\\` is a backslash, `\xHH` a byte (it escapes `;` as `\x3b`). */
+function decode633(v: string): string {
+ return v.replace(/\\(\\|x([0-9a-fA-F]{2}))/g, (_m, all: string, hex?: string) =>
+ hex ? String.fromCharCode(parseInt(hex, 16)) : all
+ )
+}
+
+/** A path we accept as a cwd: non-empty, single-line, no NUL. Anything else is ignored. */
+function plausible(p: string): string | null {
+ const t = p.trim()
+ // eslint-disable-next-line no-control-regex
+ if (!t || /[\x00-\x1f]/.test(t)) return null
+ return t
+}
+
+/** Parse ONE OSC payload (between `ESC ]` and its terminator). Null when it is not a cwd report. */
+export function parseCwdOsc(payload: string): string | null {
+ if (payload.startsWith('7;')) {
+ const url = payload.slice(2)
+ const m = /^file:\/\/[^/]*(\/.*)$/i.exec(url)
+ if (!m) return null
+ return plausible(fromUrlPath(percentDecode(m[1])))
+ }
+ if (payload.startsWith('9;9;')) {
+ let v = payload.slice(4)
+ if (v.length >= 2 && v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1)
+ return plausible(v)
+ }
+ if (payload.startsWith('633;P;Cwd=')) {
+ return plausible(decode633(payload.slice('633;P;Cwd='.length)))
+ }
+ return null
+}
+
+/**
+ * Stateful scanner over a pty's output. `push` returns the LAST cwd reported inside everything seen
+ * so far that completed in this chunk, or undefined when none did. An OSC split across chunks is
+ * carried (bounded by `CWD_REPORT_MAX_CARRY`) and parsed once its terminator arrives.
+ */
+export class CwdReportScanner {
+ private carry = ''
+
+ push(chunk: string): string | undefined {
+ // Fast path: nothing pending and no OSC (nor a trailing lone ESC that may start one) in sight.
+ if (!this.carry && !chunk.includes('\x1b')) return undefined
+ const data = this.carry + chunk
+ this.carry = ''
+ let found: string | undefined
+ let pos = 0
+ for (;;) {
+ const start = data.indexOf(OSC_START, pos)
+ if (start === -1) {
+ // A chunk can end exactly between ESC and `]`.
+ if (data.endsWith('\x1b')) this.carry = '\x1b'
+ return found
+ }
+ const body = start + OSC_START.length
+ const bel = data.indexOf('\x07', body)
+ const st = data.indexOf('\x1b\\', body)
+ // The earliest terminator wins; a NEW `ESC ]` before either means this OSC was abandoned.
+ let end = -1
+ let termLen = 0
+ if (bel !== -1 && (st === -1 || bel < st)) {
+ end = bel
+ termLen = 1
+ } else if (st !== -1) {
+ end = st
+ termLen = 2
+ }
+ const next = data.indexOf(OSC_START, body)
+ if (end === -1 || (next !== -1 && next < end)) {
+ if (next !== -1) {
+ pos = next
+ continue
+ }
+ const tail = data.slice(start)
+ if (tail.length <= CWD_REPORT_MAX_CARRY) this.carry = tail
+ return found
+ }
+ const cwd = parseCwdOsc(data.slice(body, end))
+ if (cwd !== null) found = cwd
+ pos = end + termLen
+ }
+ }
+}
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index a06d1a9d0..a5d1b77a8 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -29,6 +29,8 @@ import {
type HasSessionResult,
type PaneCommandResult,
type CaptureResult,
+ type CaptureVisibleResult,
+ type PaneCwdResult,
type KillSessionResult,
type ListSessionsResult,
type ShutdownResult
@@ -342,6 +344,10 @@ async function main(): Promise<void> {
* session and exit (issue #829): the command is destructive, so an app build that never asked
* for it can never trigger it by accident. */
const shutdownSockets = new WeakSet<net.Socket>()
+ /** Connections that negotiated `watch-attach`: only these may subscribe without a geometry claim.
+ * `captureVisible` / `paneCwd` are plain reads and need no per-socket gate — a client that did not
+ * negotiate them never sends them, and an older host answers `unknown command`. */
+ const watchSockets = new WeakSet<net.Socket>()
/** Set while a `shutdown` is ending sessions. New sessions (attach / attachExisting / launches)
* are refused for its duration; cleared again only if the shutdown could not end everything. */
let shuttingDown = false
@@ -379,6 +385,7 @@ async function main(): Promise<void> {
: []
if (features.includes('geometry')) geometrySockets.add(socket)
if (features.includes('shutdown')) shutdownSockets.add(socket)
+ if (features.includes('watch-attach')) watchSockets.add(socket)
return features.length > 0
? { protocolVersion: currentProtocolVersion(), features }
: { protocolVersion: currentProtocolVersion() }
@@ -464,6 +471,7 @@ async function main(): Promise<void> {
// node-pty may flush a queued data callback after its exit callback. Once endSession has
// disposed the emulator and broadcast exit, no data may touch or appear after that boundary.
if (session.exited) return
+ session.noteOutput(data)
// Trusted launch input is typed through the same ConPTY and therefore echoed by the shell.
// While HostSession verifies that echo, keep the entire chunk out of both renderer push
// frames and the reconstructable screen so executable/argv/prompt material stays core-only.
@@ -644,12 +652,13 @@ async function main(): Promise<void> {
if (req.expectedGeneration && req.expectedGeneration !== existing.generation) {
throw new Error(`session '${req.name}' was replaced by a different generation`)
}
- const attachment = await existing.prepareExistingAttachment(
- socket,
- req.paused === true,
- req.cols,
- req.rows
- )
+ if (req.watch === true && !watchSockets.has(socket)) {
+ throw new Error('watch attach requires the watch-attach feature negotiated at hello')
+ }
+ const attachment =
+ req.watch === true
+ ? await existing.prepareWatchAttachment(socket)
+ : await existing.prepareExistingAttachment(socket, req.paused === true, req.cols, req.rows)
try {
const screen = await existing.serialize()
if (!attachment.isCurrent()) {
@@ -662,7 +671,10 @@ async function main(): Promise<void> {
return RETRY_SESSION_GENERATION
}
if (!attachment.commit()) throw new Error('attachExisting cancelled before activation')
- log(`attach-existing name=${req.name} subscribers=${existing.subscribers.size}`)
+ log(
+ `attach-existing name=${req.name} subscribers=${existing.subscribers.size}` +
+ (req.watch === true ? ' watch' : '')
+ )
return {
fresh: false,
screen: screen || undefined,
@@ -942,6 +954,8 @@ async function main(): Promise<void> {
const s = sessions.get(req.name)
if (!s || s.exited) return { ok: false, error: 'no such session' }
if (!s.subscribers.has(socket)) return { ok: false, error: 'not attached to session' }
+ // A watch attachment (live link / relay viewer) is read-only end to end.
+ if (s.isWatching(socket)) return { ok: false, error: 'watch attachment is read-only' }
s.proc.write(req.data)
return { ok: true }
}
@@ -949,6 +963,8 @@ async function main(): Promise<void> {
const s = sessions.get(req.name)
if (!s || s.exited) return { ok: false, error: 'no such session' }
if (!s.subscribers.has(socket)) return { ok: false, error: 'not attached to session' }
+ // No claim to update, and a viewer must never acquire one (`watch-attach`).
+ if (s.isWatching(socket)) return { ok: false, error: 'watch attachment cannot resize' }
await s.resizeFor(socket, req.cols, req.rows)
return { ok: true }
}
@@ -1002,6 +1018,18 @@ async function main(): Promise<void> {
}
return { ok: true, result: { text } satisfies CaptureResult }
}
+ case 'captureVisible': {
+ const s = sessions.get(req.name)
+ if (!s || s.exited) return { ok: false, error: 'no such session' }
+ const result = await s.captureVisible()
+ if (s.exited || sessions.get(req.name) !== s) return { ok: false, error: 'no such session' }
+ return { ok: true, result: result satisfies CaptureVisibleResult }
+ }
+ case 'paneCwd': {
+ const s = sessions.get(req.name)
+ const cwd = s && !s.exited ? s.paneCwd : null
+ return { ok: true, result: { cwd } satisfies PaneCwdResult }
+ }
case 'executeLaunch': {
if (clientProtocolVersion === 1) {
return { ok: false, error: 'opaque launch requires session-host protocol v2' }
diff --git a/src/session-host/live-links-host.test.ts b/src/session-host/live-links-host.test.ts
new file mode 100644
index 000000000..22141f200
--- /dev/null
+++ b/src/session-host/live-links-host.test.ts
@@ -0,0 +1,289 @@
+// Live links on the session host: drives the REAL bundled host over its real socket protocol for the
+// three negotiated additions — `watch-attach` (a viewer subscribes with NO geometry claim and cannot
+// type or resize), `captureVisible` (the keyframe: visible rows + cursor + active buffer) and `paneCwd`
+// (the cwd the pane REPORTED, never the spawn cwd). The fake pty echoes every write back as output,
+// so a test types escape sequences in and reads what the host's emulator made of them.
+import { afterEach, describe, expect, it } from 'vitest'
+import { spawn, type ChildProcess } from 'child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'fs'
+import net, { type Socket } from 'net'
+import os from 'os'
+import path from 'path'
+import { build, type Plugin } from 'esbuild'
+import {
+ LineFramer,
+ SESSION_HOST_PROTOCOL_VERSION,
+ encodeFrame,
+ type SessionHostEvent,
+ type SessionHostFrame,
+ type SessionHostResponse,
+ type SessionHostSpawnOptions
+} from './protocol'
+import { sessionHostPaths, type SessionHostState } from './paths'
+
+function fakePtyPlugin(): Plugin {
+ return {
+ name: 'session-host-live-links-fake-pty',
+ setup(bundle) {
+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({ path: 'node-pty', namespace: 'geo' }))
+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'geo' }, () => ({
+ loader: 'js',
+ contents: `
+ export function spawn() {
+ let onExit
+ const onData = []
+ return {
+ pid: 4343,
+ onData(cb) { onData.push(cb) },
+ onExit(cb) { onExit = cb },
+ write(d) { setTimeout(() => { for (const cb of onData) cb(d) }, 0) },
+ resize() {},
+ pause() {},
+ resume() {},
+ kill() { setTimeout(() => onExit?.({ exitCode: 0 }), 20) }
+ }
+ }
+ `
+ }))
+ }
+ }
+}
+
+async function waitForIdentity(dataDir: string): Promise<{ state: SessionHostState; token: string }> {
+ const paths = sessionHostPaths(dataDir)
+ for (let attempt = 0; attempt < 200; attempt++) {
+ try {
+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8')) as SessionHostState
+ const token = readFileSync(paths.tokenPath, 'utf8').trim()
+ if (state.endpoint && token) return { state, token }
+ } catch {
+ /* publication is asynchronous by design; keep polling within the test bound */
+ }
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ }
+ throw new Error('session host did not publish its identity')
+}
+
+type Connection = {
+ socket: Socket
+ events: SessionHostEvent[]
+ request(frame: Record<string, unknown> & { id: number }): Promise<SessionHostResponse>
+}
+
+function connect(endpoint: string): Promise<Connection> {
+ return new Promise((resolve, reject) => {
+ const socket = net.connect(endpoint)
+ const framer = new LineFramer()
+ const events: SessionHostEvent[] = []
+ const waiters = new Map<number, (frame: SessionHostResponse) => void>()
+ socket.on('data', (chunk: Buffer) => {
+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {
+ if ('type' in frame) {
+ events.push(frame)
+ continue
+ }
+ waiters.get(frame.id)?.(frame)
+ waiters.delete(frame.id)
+ }
+ })
+ socket.once('error', reject)
+ socket.once('connect', () =>
+ resolve({
+ socket,
+ events,
+ request: (frame) =>
+ new Promise<SessionHostResponse>((done, fail) => {
+ const timer = setTimeout(() => fail(new Error(`timed out on ${frame.id}`)), 4_000)
+ waiters.set(frame.id, (response) => {
+ clearTimeout(timer)
+ done(response)
+ })
+ socket.write(encodeFrame(frame))
+ })
+ })
+ )
+ })
+}
+
+function waitForExit(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
+ return new Promise((resolve) => child.once('exit', () => resolve()))
+}
+
+const SPAWN: SessionHostSpawnOptions = {
+ cwd: '.',
+ shell: 'fake-shell',
+ args: [],
+ env: {},
+ cols: 80,
+ rows: 24
+}
+
+const cleanupPaths: string[] = []
+afterEach(() => {
+ for (const target of cleanupPaths.splice(0)) {
+ rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })
+ }
+})
+
+function geometryEvents(events: SessionHostEvent[]): Array<{ cols: number; rows: number }> {
+ return events.flatMap((event) =>
+ event.type === 'geometry' ? [{ cols: event.cols, rows: event.rows }] : []
+ )
+}
+
+
+async function until(check: () => boolean, label: string): Promise<void> {
+ const deadline = Date.now() + 4_000
+ while (!check()) {
+ if (Date.now() > deadline) throw new Error(`${label} never happened`)
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+}
+
+function dataSeen(events: SessionHostEvent[], marker: string): boolean {
+ return events.some((event) => event.type === 'data' && event.data.includes(marker))
+}
+
+describe('session-host live link features', () => {
+ it('watch-attach, captureVisible and paneCwd over the real protocol', async () => {
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-live-'))
+ cleanupPaths.push(fixtureDir)
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)
+ const bundlePath = path.join(fixtureDir, 'host.cjs')
+ await build({
+ absWorkingDir: process.cwd(),
+ entryPoints: ['src/session-host/host.ts'],
+ outfile: bundlePath,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ plugins: [fakePtyPlugin()],
+ logLevel: 'silent'
+ })
+ const child = spawn(process.execPath, [bundlePath, dataDir], {
+ cwd: process.cwd(),
+ stdio: 'ignore',
+ windowsHide: true
+ })
+ const sockets: Socket[] = []
+ try {
+ const { state, token } = await waitForIdentity(dataDir)
+ const owner = await connect(state.endpoint)
+ const viewer = await connect(state.endpoint)
+ const legacy = await connect(state.endpoint)
+ sockets.push(owner.socket, viewer.socket, legacy.socket)
+ const features = ['geometry', 'watch-attach', 'captureVisible', 'paneCwd']
+ for (const conn of [owner, viewer]) {
+ await expect(
+ conn.request({ id: 1, cmd: 'hello', token, protocolVersion: SESSION_HOST_PROTOCOL_VERSION, features })
+ ).resolves.toMatchObject({ ok: true, result: { features } })
+ }
+ await expect(
+ legacy.request({ id: 1, cmd: 'hello', token, protocolVersion: SESSION_HOST_PROTOCOL_VERSION })
+ ).resolves.toEqual({ id: 1, ok: true, result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION } })
+
+ await expect(
+ owner.request({ id: 2, cmd: 'attach', name: 'live', spawn: { ...SPAWN, cols: 100, rows: 30 }, scrollback: 100 })
+ ).resolves.toMatchObject({ ok: true, result: { fresh: true, geometry: { cols: 100, rows: 30 } } })
+
+ // A watch attach of a name that does not exist never spawns one.
+ const missing = await viewer.request({ id: 2, cmd: 'attachExisting', name: 'nope', watch: true })
+ expect(missing.ok).toBe(false)
+ await expect(viewer.request({ id: 3, cmd: 'hasSession', name: 'nope' })).resolves.toMatchObject({
+ ok: true,
+ result: { exists: false }
+ })
+
+ // The viewer joins with no geometry claim at all…
+ await expect(
+ viewer.request({ id: 4, cmd: 'attachExisting', name: 'live', watch: true })
+ ).resolves.toMatchObject({ ok: true, result: { fresh: false, geometry: { cols: 100, rows: 30 } } })
+ // …a connection that never negotiated the feature cannot do the same…
+ const refused = await legacy.request({ id: 2, cmd: 'attachExisting', name: 'live', watch: true })
+ expect(refused.ok).toBe(false)
+ // …and the owner's size alone decides the pty's: growing it is NOT capped by the viewer.
+ await expect(
+ owner.request({ id: 3, cmd: 'resize', name: 'live', cols: 120, rows: 40 })
+ ).resolves.toMatchObject({ ok: true })
+ await until(
+ () => viewer.events.some((e) => e.type === 'geometry' && e.cols === 120 && e.rows === 40),
+ 'the viewer learning the owner size'
+ )
+
+ // Read-only end to end: a watch connection can neither type nor resize.
+ await expect(viewer.request({ id: 5, cmd: 'write', name: 'live', data: 'x' })).resolves.toMatchObject({
+ ok: false,
+ error: 'watch attachment is read-only'
+ })
+ await expect(
+ viewer.request({ id: 6, cmd: 'resize', name: 'live', cols: 10, rows: 5 })
+ ).resolves.toMatchObject({ ok: false })
+ await expect(viewer.request({ id: 7, cmd: 'pause', name: 'live' })).resolves.toMatchObject({ ok: true })
+
+ // paneCwd: null until the pane REPORTS one (never the spawn cwd), then the reported path.
+ await expect(viewer.request({ id: 8, cmd: 'paneCwd', name: 'live' })).resolves.toMatchObject({
+ ok: true,
+ result: { cwd: null }
+ })
+ await owner.request({ id: 4, cmd: 'write', name: 'live', data: 'one\r\n\x1b]9;9;"C:\\work"\x07two\r\n' })
+ // The viewer's pause was ignored: output keeps flowing to it.
+ await until(() => dataSeen(viewer.events, 'two'), 'output reaching the viewer')
+ await expect(viewer.request({ id: 9, cmd: 'paneCwd', name: 'live' })).resolves.toMatchObject({
+ ok: true,
+ result: { cwd: 'C:\\work' }
+ })
+ await owner.request({ id: 5, cmd: 'write', name: 'live', data: '\x1b]7;file://pc/C:/Users/me\x1b\\' })
+ await until(() => dataSeen(viewer.events, 'file://pc'), 'the OSC 7 echo')
+ await expect(viewer.request({ id: 10, cmd: 'paneCwd', name: 'live' })).resolves.toMatchObject({
+ result: { cwd: 'C:\\Users\\me' }
+ })
+
+ // captureVisible: the visible rows + cursor, then the alternate screen alone.
+ const kf = (await viewer.request({ id: 11, cmd: 'captureVisible', name: 'live' })) as {
+ ok: true
+ result: { screen: string; cursor: { x: number; y: number }; altScreen: boolean }
+ }
+ expect(kf.ok).toBe(true)
+ expect(kf.result.altScreen).toBe(false)
+ expect(kf.result.screen).toContain('one\ntwo\n')
+ expect(kf.result.cursor).toEqual({ x: 0, y: 2 })
+ await owner.request({ id: 6, cmd: 'write', name: 'live', data: '\x1b[?1049h\x1b[HTUI' })
+ await until(() => dataSeen(viewer.events, 'TUI'), 'the alternate-screen echo')
+ const alt = (await viewer.request({ id: 12, cmd: 'captureVisible', name: 'live' })) as typeof kf
+ expect(alt.result.altScreen).toBe(true)
+ expect(alt.result.screen).toContain('TUI')
+ expect(alt.result.screen).not.toContain('one')
+ await expect(viewer.request({ id: 13, cmd: 'captureVisible', name: 'nope' })).resolves.toMatchObject({
+ ok: false
+ })
+
+ // The owner leaves: the viewer stays subscribed and the pty keeps the owner's last size.
+ const before = geometryEvents(viewer.events).length
+ await owner.request({ id: 7, cmd: 'detach', name: 'live' })
+ await expect(viewer.request({ id: 14, cmd: 'ping' })).resolves.toMatchObject({ ok: true })
+ expect(geometryEvents(viewer.events).length).toBe(before)
+
+ // A claim-carrying attach on the viewer's connection upgrades it; a watch attach withdraws it.
+ await expect(
+ viewer.request({ id: 15, cmd: 'attachExisting', name: 'live', cols: 90, rows: 20 })
+ ).resolves.toMatchObject({ ok: true, result: { geometry: { cols: 90, rows: 20 } } })
+ await expect(viewer.request({ id: 16, cmd: 'write', name: 'live', data: 'ok' })).resolves.toMatchObject({
+ ok: true
+ })
+ await expect(
+ viewer.request({ id: 17, cmd: 'attachExisting', name: 'live', watch: true })
+ ).resolves.toMatchObject({ ok: true, result: { geometry: { cols: 90, rows: 20 } } })
+ await expect(viewer.request({ id: 18, cmd: 'write', name: 'live', data: 'no' })).resolves.toMatchObject({
+ ok: false
+ })
+ } finally {
+ for (const socket of sockets) socket.destroy()
+ child.kill()
+ await waitForExit(child)
+ }
+ }, 30_000)
+})
diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.ts
index 5bdae9e02..e90d4082c 100644
--- a/src/session-host/protocol.ts
+++ b/src/session-host/protocol.ts
@@ -87,6 +87,11 @@ export type SessionHostRequest =
cols?: number
rows?: number
paused?: boolean
+ /** `watch-attach` feature only: subscribe this connection WITHOUT a geometry claim (a live
+ * link viewer / relay viewer's read-only view). Carries no cols/rows; never spawns. On a
+ * connection already attached it WITHDRAWS that connection's claim (its last voting
+ * subscriber left). A later claim-carrying attach upgrades it again. */
+ watch?: boolean
}
| { id: number; cmd: 'hasSession'; name: string }
| { id: number; cmd: 'write'; name: string; data: string }
@@ -99,6 +104,12 @@ export type SessionHostRequest =
| { id: number; cmd: 'messagePasteReadyV1'; name: string }
| { id: number; cmd: 'messageEnvelopeV1'; name: string; envelope: string; expected: PaneOwner }
| { id: number; cmd: 'capture'; name: string; full: boolean }
+ /** `captureVisible` feature only: the VISIBLE rows (no history) plus cursor + active buffer — a
+ * live link's keyframe. Never sent to a host that did not advertise it. */
+ | { id: number; cmd: 'captureVisible'; name: string }
+ /** `paneCwd` feature only: the last cwd the pane REPORTED (OSC 7 / 9;9 / 633), never the spawn
+ * cwd. */
+ | { id: number; cmd: 'paneCwd'; name: string }
| {
id: number
cmd: 'executeLaunch'
@@ -205,8 +216,14 @@ export interface AttachResult {
geometry?: { cols: number; rows: number }
}
/** Additive, independently negotiated capabilities (see the `hello` request). */
-export type SessionHostFeature = 'geometry' | 'shutdown'
-export const SESSION_HOST_FEATURES: readonly SessionHostFeature[] = ['geometry', 'shutdown']
+export type SessionHostFeature = 'geometry' | 'shutdown' | 'watch-attach' | 'captureVisible' | 'paneCwd'
+export const SESSION_HOST_FEATURES: readonly SessionHostFeature[] = [
+ 'geometry',
+ 'shutdown',
+ 'watch-attach',
+ 'captureVisible',
+ 'paneCwd'
+]
/** `result` of a successful `shutdown`: the session names whose process trees were ended. The
* host exits right after this reply is flushed. A shutdown that could not confirm every kill
@@ -241,6 +258,17 @@ export interface PaneCommandResult {
export interface CaptureResult {
text: string
}
+/** `result` of `captureVisible`. `screen` is one `\n`-terminated line per visible row with SGR (the
+ * shape `capture-pane -p -e` prints), '' for a session that never painted; `cursor` is 0-based and
+ * viewport-relative; `altScreen` is the emulator's ACTIVE buffer. A missing session is an error. */
+export interface CaptureVisibleResult {
+ screen: string
+ cursor: { x: number; y: number } | null
+ altScreen: boolean
+}
+export interface PaneCwdResult {
+ cwd: string | null
+}
export interface ListSessionsResult {
names: string[]
}
diff --git a/src/session-host/session-watch.test.ts b/src/session-host/session-watch.test.ts
new file mode 100644
index 000000000..29da27add
--- /dev/null
+++ b/src/session-host/session-watch.test.ts
@@ -0,0 +1,104 @@
+// HostSession's `watch-attach` transaction and its reported cwd, at unit level (the real-protocol
+// wiring is live-links-host.test.ts). A watch attachment must never contribute a geometry claim or
+// a pause ticket, and must give up any claim its connection held.
+import { describe, expect, it, vi } from 'vitest'
+import type { Socket } from 'net'
+import type { IPty } from 'node-pty'
+import { HostSession } from './session'
+import type { TerminalEmulator } from './terminal-emulator'
+import type { SessionHostSpawnOptions } from './protocol'
+
+const SPAWN: SessionHostSpawnOptions = { shell: 'unused', args: [], cwd: '.', env: {}, cols: 80, rows: 24 }
+
+function fixture(): { session: HostSession; resize: ReturnType<typeof vi.fn>; pause: ReturnType<typeof vi.fn> } {
+ const resize = vi.fn()
+ const pause = vi.fn()
+ const proc = { pid: 1, pause, resume: vi.fn(), resize } as unknown as IPty
+ const term = {
+ write: vi.fn(async () => {}),
+ serialize: vi.fn(() => ''),
+ resize: vi.fn(),
+ dispose: vi.fn()
+ } as unknown as TerminalEmulator
+ return { session: new HostSession('watch', SPAWN, 100, { proc, term }), resize, pause }
+}
+
+describe('HostSession watch attachments', () => {
+ it('casts no claim: the owner alone sizes the pty, up as well as down', async () => {
+ const { session, resize } = fixture()
+ const owner = {} as Socket
+ const viewer = {} as Socket
+ ;(await session.prepareAttachment(owner, 100, 30, false)).commit()
+ expect(resize).toHaveBeenLastCalledWith(100, 30)
+ const watch = await session.prepareWatchAttachment(viewer)
+ expect(watch.commit()).toBe(true)
+ expect(session.subscribers.has(viewer)).toBe(true)
+ expect(session.isWatching(viewer)).toBe(true)
+ await session.resizeFor(owner, 140, 50)
+ expect(resize).toHaveBeenLastCalledWith(140, 50)
+ // A viewer cannot resize, and never takes a pause ticket.
+ await expect(session.resizeFor(viewer, 10, 5)).rejects.toThrow(/watch attachment/)
+ session.pauseFor(viewer)
+ expect(session.geometry).toEqual({ cols: 140, rows: 50 })
+ })
+
+ it('withdraws the claim a connection held, and the pty keeps its size when no claim is left', async () => {
+ const { session, resize } = fixture()
+ const socket = {} as Socket
+ ;(await session.prepareAttachment(socket, 90, 20, false)).commit()
+ resize.mockClear()
+ ;(await session.prepareWatchAttachment(socket)).commit()
+ expect(session.isWatching(socket)).toBe(true)
+ expect(resize).not.toHaveBeenCalled()
+ expect(session.geometry).toEqual({ cols: 90, rows: 20 })
+ // A claim-carrying attach upgrades it again.
+ ;(await session.prepareAttachment(socket, 70, 20, false)).commit()
+ expect(session.isWatching(socket)).toBe(false)
+ expect(resize).toHaveBeenLastCalledWith(70, 20)
+ })
+
+ it('never holds a pause ticket, and returns one the connection held', async () => {
+ const { session, pause } = fixture()
+ const socket = {} as Socket
+ ;(await session.prepareAttachment(socket, 80, 24, true)).commit()
+ expect(pause).toHaveBeenCalledTimes(1)
+ const resume = (session.proc as unknown as { resume: ReturnType<typeof vi.fn> }).resume
+ ;(await session.prepareWatchAttachment(socket)).commit()
+ expect(resume).toHaveBeenCalledTimes(1)
+ })
+
+ it('a rolled-back watch attach restores the previous claim and mode exactly', async () => {
+ const { session, resize } = fixture()
+ const socket = {} as Socket
+ ;(await session.prepareAttachment(socket, 100, 40, false)).commit()
+ const watch = await session.prepareWatchAttachment(socket)
+ await watch.rollback()
+ expect(session.isWatching(socket)).toBe(false)
+ await session.resizeFor(socket, 110, 40)
+ expect(resize).toHaveBeenLastCalledWith(110, 40)
+ })
+
+ it('detach clears watch mode', async () => {
+ const { session } = fixture()
+ const socket = {} as Socket
+ ;(await session.prepareWatchAttachment(socket)).commit()
+ await session.detach(socket)
+ expect(session.isWatching(socket)).toBe(false)
+ expect(session.subscribers.has(socket)).toBe(false)
+ })
+})
+
+describe('HostSession reported cwd', () => {
+ it('is null until the pane reports one, then follows the latest report across chunks', () => {
+ const { session } = fixture()
+ expect(session.paneCwd).toBeNull()
+ session.noteOutput('PS> \x1b]9;9;"C:\\a"')
+ expect(session.paneCwd).toBeNull()
+ session.noteOutput('\x07')
+ expect(session.paneCwd).toBe('C:\\a')
+ session.noteOutput('\x1b]7;file://pc/C:/b\x1b\\')
+ expect(session.paneCwd).toBe('C:\\b')
+ session.noteOutput('plain output')
+ expect(session.paneCwd).toBe('C:\\b')
+ })
+})
diff --git a/src/session-host/session.ts b/src/session-host/session.ts
index 2a13a88d0..e64f7e2c0 100644
--- a/src/session-host/session.ts
+++ b/src/session-host/session.ts
@@ -2,7 +2,9 @@ import type { Socket } from 'net'
import { createHash, randomUUID } from 'crypto'
import * as pty from 'node-pty'
import { TerminalEmulator } from './terminal-emulator'
+import { CwdReportScanner } from './cwd-report'
import type {
+ CaptureVisibleResult,
ExecuteLaunchResult,
SessionHostShellDialect,
SessionHostSpawnOptions
@@ -91,6 +93,7 @@ interface AttachmentState {
geometry?: Geometry
explicitPaused: boolean
subscribed: boolean
+ watching: boolean
}
/** A warm attach must temporarily claim geometry and (on reconnect) restore its explicit pause
@@ -148,6 +151,14 @@ export class HostSession {
/** Each app connection contributes one componentwise geometry claim. The effective PTY size is
* the minimum across live claims so every viewer fits; removing the smallest claim grows it. */
private readonly geometryClaims = new Map<Socket, Geometry>()
+ /** Subscribed connections attached in `watch` mode (`watch-attach` feature): they receive output
+ * but hold NO geometry claim, so a live link / relay viewer can never size the pty. A claim-
+ * carrying attach on the same connection takes it out of this set again. */
+ private readonly watchers = new Set<Socket>()
+ /** The cwd the pane last REPORTED in its output (OSC 7 / 9;9 / 633 — see cwd-report.ts). Null
+ * until one arrives; deliberately never seeded with the spawn cwd. */
+ private reportedCwd: string | null = null
+ private readonly cwdScanner = new CwdReportScanner()
/** A detach/close increments the socket epoch before clearing state. A delayed prepare/rollback
* from the prior epoch can then observe cancellation instead of resurrecting a ghost socket. */
private readonly attachmentEpochs = new WeakMap<Socket, number>()
@@ -262,6 +273,29 @@ export class HostSession {
return settled
}
+ /** Scan one PTY-output chunk for a cwd report. Synchronous and independent of the emulator queue:
+ * it is called for every chunk, including private launch echo (a cwd is not launch material). */
+ noteOutput(data: string): void {
+ const cwd = this.cwdScanner.push(data)
+ if (cwd !== undefined) this.reportedCwd = cwd
+ }
+
+ /** `paneCwd`: the last REPORTED cwd, or null when the pane never reported one. */
+ get paneCwd(): string | null {
+ return this.reportedCwd
+ }
+
+ /** Is this connection subscribed in watch mode (no geometry claim)? */
+ isWatching(socket: Socket): boolean {
+ return this.watchers.has(socket)
+ }
+
+ /** The visible-screen keyframe, behind the same output barrier as `serialize`. */
+ async captureVisible(): Promise<CaptureVisibleResult> {
+ await this.outputTail
+ return this.term.captureVisible()
+ }
+
/** Wait until every PTY-output chunk observed before this call has reached xterm. */
settleOutput(): Promise<void> {
return this.outputTail
@@ -311,17 +345,36 @@ export class HostSession {
cols: number,
rows: number,
paused: boolean
+ ): Promise<PreparedHostAttachment> {
+ return this.stageAttachment(socket, normalizedGeometry(cols, rows), paused)
+ }
+
+ /** `watch-attach`: the same transaction with NO geometry claim. A connection that held one gives
+ * it up (its last voting subscriber left), and the pty's size is re-derived from the remaining
+ * claims — with none left it keeps the size it has. Never spawns: callers reach this only for an
+ * existing generation. Any explicit pause the connection held is returned. */
+ prepareWatchAttachment(socket: Socket): Promise<PreparedHostAttachment> {
+ // Never paused: a viewer holds no flow ticket on the shared pty (see `pauseFor`).
+ return this.stageAttachment(socket, null, false)
+ }
+
+ private async stageAttachment(
+ socket: Socket,
+ claim: Geometry | null,
+ paused: boolean
): Promise<PreparedHostAttachment> {
const epoch = (this.attachmentEpochs.get(socket) ?? 0) + 1
this.attachmentEpochs.set(socket, epoch)
const previous: AttachmentState = {
geometry: this.geometryClaims.get(socket),
explicitPaused: this.explicitPauseOwners.has(socket),
- subscribed: this.subscribers.has(socket)
+ subscribed: this.subscribers.has(socket),
+ watching: this.watchers.has(socket)
}
this.setSocketPauseOwner(this.explicitPauseOwners, socket, paused)
try {
- await this.setGeometryClaim(socket, cols, rows)
+ if (claim) await this.setGeometryClaim(socket, claim.cols, claim.rows)
+ else if (this.geometryClaims.delete(socket)) await this.applyEffectiveGeometry()
} catch (error) {
await this.restoreAttachment(socket, previous, epoch)
throw error
@@ -335,6 +388,8 @@ export class HostSession {
finished = true
if (this.attachmentEpochs.get(socket) !== epoch || socket.destroyed) return false
this.subscribers.add(socket)
+ if (claim) this.watchers.delete(socket)
+ else this.watchers.add(socket)
// A response written before this attach may already have filled the socket. The new
// session must inherit that socket-wide transport ticket before any live frame can add to
// the same queue.
@@ -368,11 +423,15 @@ export class HostSession {
/** Update only the requesting subscriber's geometry claim. */
async resizeFor(socket: Socket, cols: number, rows: number): Promise<void> {
if (!this.subscribers.has(socket)) return
+ // A watch-mode connection has no claim to update, and must never acquire one by resizing.
+ if (this.watchers.has(socket)) throw new Error('a watch attachment cannot resize the terminal')
await this.setGeometryClaim(socket, cols, rows)
}
pauseFor(socket: Socket): void {
if (!this.subscribers.has(socket)) return
+ // A viewer never slows the owner's terminal: a watch-mode connection takes no pause ticket.
+ if (this.watchers.has(socket)) return
this.setSocketPauseOwner(this.explicitPauseOwners, socket, true)
}
@@ -396,6 +455,7 @@ export class HostSession {
this.attachmentEpochs.set(socket, (this.attachmentEpochs.get(socket) ?? 0) + 1)
const wasPaused = this.hasPauseOwner()
this.subscribers.delete(socket)
+ this.watchers.delete(socket)
this.explicitPauseOwners.delete(socket)
this.transportPauseOwners.delete(socket)
this.reconcileProcFlow(wasPaused)
@@ -426,6 +486,7 @@ export class HostSession {
this.transportPauseOwners.clear()
this.emulatorPauseOwner = false
this.geometryClaims.clear()
+ this.watchers.clear()
this.term.dispose()
}
@@ -676,6 +737,8 @@ export class HostSession {
else this.explicitPauseOwners.delete(socket)
if (previous.subscribed) this.subscribers.add(socket)
else this.subscribers.delete(socket)
+ if (previous.watching) this.watchers.add(socket)
+ else this.watchers.delete(socket)
this.reconcileProcFlow(wasPaused)
if (previous.geometry) this.geometryClaims.set(socket, previous.geometry)
diff --git a/src/session-host/terminal-emulator.test.ts b/src/session-host/terminal-emulator.test.ts
new file mode 100644
index 000000000..4758b5169
--- /dev/null
+++ b/src/session-host/terminal-emulator.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { TerminalEmulator } from './terminal-emulator'
+
+const emulators: TerminalEmulator[] = []
+function emulator(cols = 20, rows = 4): TerminalEmulator {
+ const e = new TerminalEmulator({ cols, rows, scrollback: 1000 })
+ emulators.push(e)
+ return e
+}
+afterEach(() => {
+ for (const e of emulators.splice(0)) e.dispose()
+})
+
+/** The visible text of a keyframe, with SGR and cursor-move CSIs removed. */
+function text(screen: string): string {
+ // eslint-disable-next-line no-control-regex
+ return screen.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
+}
+
+describe('TerminalEmulator.captureVisible (live link keyframe)', () => {
+ it('returns exactly the visible rows — no history — with the cursor and SGR', async () => {
+ const e = emulator()
+ let data = ''
+ for (let i = 0; i < 300; i++) data += `line ${i}\r\n`
+ data += '\x1b[31mred\x1b[0m tail'
+ await e.write(data)
+ const cap = e.captureVisible()
+ expect(cap.altScreen).toBe(false)
+ expect(cap.screen.endsWith('\n')).toBe(true)
+ expect(cap.screen).toContain('\x1b[31mred')
+ expect(cap.screen).not.toContain('\r\n')
+ expect(text(cap.screen).split('\n').slice(0, 4)).toEqual([
+ 'line 297',
+ 'line 298',
+ 'line 299',
+ 'red tail'
+ ])
+ expect(cap.cursor).toEqual({ x: 8, y: 3 })
+ // The scrollback is still there for the warm-attach replay; the keyframe just never carries it.
+ expect(e.serialize()).toContain('line 0')
+ })
+
+ it('reports the cursor where the app moved it, viewport-relative', async () => {
+ const e = emulator()
+ await e.write('a\r\nb\r\nc\x1b[1;5H')
+ expect(e.captureVisible().cursor).toEqual({ x: 4, y: 0 })
+ })
+
+ it('captures the ALTERNATE screen alone, and says so', async () => {
+ const e = emulator()
+ await e.write('shell line\r\n$ vim\r\n')
+ await e.write('\x1b[?1049h\x1b[Hfull screen app\r\n~')
+ const cap = e.captureVisible()
+ expect(cap.altScreen).toBe(true)
+ expect(text(cap.screen)).toContain('full screen app')
+ expect(text(cap.screen)).not.toContain('shell line')
+ expect(cap.screen).not.toContain('\x1b[?1049h')
+ // Back on the normal screen, the keyframe is the shell's again.
+ await e.write('\x1b[?1049l')
+ const back = e.captureVisible()
+ expect(back.altScreen).toBe(false)
+ expect(text(back.screen)).toContain('shell line')
+ expect(text(back.screen)).not.toContain('full screen app')
+ })
+
+ it('keeps the private-mode tail a mid-stream viewer never saw', async () => {
+ const e = emulator()
+ await e.write('\x1b[?2004h\x1b[?1hprompt> ')
+ const cap = e.captureVisible()
+ expect(cap.screen).toContain('\x1b[?2004h')
+ expect(cap.screen).toContain('\x1b[?1h')
+ })
+
+ it('is empty for a session that never painted', () => {
+ expect(emulator().captureVisible()).toEqual({
+ screen: '',
+ cursor: { x: 0, y: 0 },
+ altScreen: false
+ })
+ })
+})
+
+describe('captureVisible tail', () => {
+ it("drops the serializer's relative cursor restore so the trailing newline cannot misplace it", async () => {
+ const e = emulator()
+ await e.write('one\r\ntwo\x1b[1;1H')
+ const cap = e.captureVisible()
+ expect(cap.screen).toBe('one\ntwo\n')
+ expect(cap.cursor).toEqual({ x: 0, y: 0 })
+ })
+})
diff --git a/src/session-host/terminal-emulator.ts b/src/session-host/terminal-emulator.ts
index 3f777e253..c786c43d6 100644
--- a/src/session-host/terminal-emulator.ts
+++ b/src/session-host/terminal-emulator.ts
@@ -74,6 +74,48 @@ export class TerminalEmulator {
return out
}
+ /**
+ * A live link's keyframe: the VISIBLE rows of the ACTIVE buffer only (never history), in the shape
+ * `capture-pane -p -e` prints — SGR, one `\n`-terminated line per row — plus the viewport-relative
+ * cursor and whether the alternate buffer is active.
+ *
+ * Built from `SerializeAddon` with `scrollback: 0` rather than by hand, so attributes, wide cells
+ * and soft wraps encode exactly as the warm-attach replay does. Adjustments:
+ * - the ALTERNATE buffer: `serialize` always writes the normal buffer first and the alternate one
+ * after `CSI ?1049h CSI H`; a keyframe is the active screen only (the viewer switches buffers
+ * itself from `altScreen` BEFORE painting), so only the part after that marker is kept;
+ * - row separators: the addon joins rows with `\r\n`; a keyframe's contract is `\n`.
+ * The private-mode tail (bracketed paste, application cursor keys, mouse) IS kept, after the last
+ * row: unlike a tmux client, a viewer joining a session-host stream mid-way never saw the app
+ * request them, and a Control viewer's keys encode by them. It is pure DECSET, so the viewer's
+ * reset + clear paint is unaffected. The addon's trailing relative cursor restore is dropped (the
+ * viewer places the cursor absolutely from `cursor`).
+ */
+ captureVisible(): { screen: string; cursor: { x: number; y: number }; altScreen: boolean } {
+ const buffer = this.term.buffer.active
+ const altScreen = buffer.type === 'alternate'
+ const bare = this.serializer.serialize({ scrollback: 0, excludeModes: true })
+ // `serialize` appends the mode tail LAST, so the difference of the two answers is exactly it.
+ const withModes = this.serialize(0)
+ const modes = withModes.startsWith(bare) ? withModes.slice(bare.length) : ''
+ const ALT = '\x1b[?1049h\x1b[H'
+ const altAt = bare.indexOf(ALT)
+ const screenPart = altScreen ? (altAt === -1 ? '' : bare.slice(altAt + ALT.length)) : altAt === -1 ? bare : bare.slice(0, altAt)
+ const body = screenPart
+ .replace(/\r\n/g, '\n')
+ // The addon's trailing RELATIVE cursor restore (CUU/CUD/CUF/CUB after the last row) is dropped:
+ // the keyframe carries the cursor absolutely, and a relative move followed by the row's `\n`
+ // could scroll the viewer. A row itself never ends in one (a gap is only emitted before a
+ // following character), so only the tail matches. The pen-style SGR after it is kept.
+ // eslint-disable-next-line no-control-regex
+ .replace(/(?:\x1b\[\d+[ABCD])+((?:\x1b\[[\d;]*m)?)$/, '$1')
+ return {
+ screen: body ? `${body}${modes}\n` : modes,
+ cursor: { x: buffer.cursorX, y: buffer.cursorY },
+ altScreen
+ }
+ }
+
/**
* Has the app running in this session REQUESTED bracketed paste (`CSI ?2004h`)?
*