Answer hidden terminal queries from the model
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -87,9 +87,13 @@ ingestion and an async write; the decision must not be re-read at reply time):
|
||||
4. no remote view subscriber is attached to the PTY (runtime terminal-RPC
|
||||
subscriber records / `mobileSubscribers`): a mobile/web/remote-desktop
|
||||
xterm receiving the multiplexed stream answers with view authority, exactly
|
||||
like a visible local pane. Read-only consumers (CLI reads, automation
|
||||
observers) do not suppress — they also do not answer; that bounded
|
||||
no-reply case matches today's behavior.
|
||||
like a visible local pane. Legacy JSON `terminal.subscribe` streams **do**
|
||||
register as view subscribers and suppress, even when the consumer is a
|
||||
read-only watcher — deliberately conservative, because the stream may feed
|
||||
an older live xterm view and a withheld reply (the pre-Phase-5 status quo)
|
||||
is strictly safer than a double reply. Consumers that never register a
|
||||
stream (CLI `terminal.read`, automation observers) do not suppress — they
|
||||
also do not answer; that bounded no-reply case matches today's behavior.
|
||||
|
||||
Everything the emulator emits outside a forwarding window is discarded, which
|
||||
also swallows unsolicited core emissions (e.g. native 997 color-scheme pushes
|
||||
@@ -156,8 +160,11 @@ The provider kind is known main-side: mirror `isLocalNativeWindowsPty`
|
||||
provider, `win32`, not WSL). For such PTYs register a CSI `c` override on the
|
||||
emulator parser (the main-side twin of
|
||||
`installConptyDeviceAttributesHandler`) replying `CSI ?61;4c`, still gated by
|
||||
the forwarding predicate. ConPTY blocking on a missing DA1 is a spawn-time
|
||||
hazard; spawn-time ownership is deterministic (see races below).
|
||||
the forwarding predicate. The override is installed at emulator creation and
|
||||
retrofitted when the spawn mark lands (daemon stream data can create the
|
||||
emulator before the awaited spawn response marks the PTY). ConPTY blocking on
|
||||
a missing DA1 is a spawn-time hazard; see the races section for the
|
||||
hidden-at-spawn loss window that remains until Phase 6.
|
||||
|
||||
## Suppression: when main never replies
|
||||
|
||||
@@ -197,9 +204,14 @@ Safe-side rule per class: duplicates are structurally impossible (one decision
|
||||
point per chunk); where the race costs anything it costs a missing reply.
|
||||
That is acceptable for state queries (DSR/CPR/DECRPM — TUIs re-probe or
|
||||
tolerate silence, as they did for every hidden pane before this phase). The
|
||||
one blocking-on-no-reply sequence, ConPTY DA1, only fires at spawn, where
|
||||
ownership is deterministic: visible pane, startup window (renderer), or
|
||||
marked-at-spawn (main). It cannot land in the flip gap.
|
||||
one blocking-on-no-reply sequence, ConPTY DA1, only fires at spawn. A visible
|
||||
pane or an active codex startup window answers it from the renderer xterm.
|
||||
But a PTY spawned hidden **without** the startup window has no answerer until
|
||||
the renderer's hidden mark lands in main (one IPC hop after spawn): a DA1
|
||||
arriving in that pre-mark window is lost. That loss window is the pre-Phase-4
|
||||
hidden status quo and persists until Phase 6 marks hidden panes at spawn
|
||||
(spawn-record flag, below) — spawn-time ownership is not deterministic before
|
||||
then.
|
||||
|
||||
## Invariants
|
||||
|
||||
|
||||
@@ -290,6 +290,49 @@ describe('HeadlessEmulator', () => {
|
||||
expect(emulator.getSnapshot().modes.sgrMouseMode).toBe(false)
|
||||
})
|
||||
|
||||
it('tracks kitty keyboard flags for emulator re-seed parity', async () => {
|
||||
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
|
||||
expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(0)
|
||||
|
||||
await emulator.write('\x1b[=5;1u')
|
||||
expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(5)
|
||||
})
|
||||
|
||||
it('round-trips a pushed CSI > 1 u flag through the core-internals read path', async () => {
|
||||
// Why: getKittyKeyboardFlags reads _core.coreService.kittyKeyboard.flags,
|
||||
// a private xterm surface. If an xterm upgrade breaks that path this
|
||||
// must fail loudly instead of the responder silently answering ?0u.
|
||||
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
|
||||
|
||||
await emulator.write('\x1b[>1u')
|
||||
expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(1)
|
||||
})
|
||||
|
||||
it('snapshots the active-buffer kitty flags (alt screen keeps its own set)', async () => {
|
||||
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
|
||||
// Kitty flags are per screen buffer: entering the alt screen swaps to
|
||||
// its own (empty) flag set, exactly what a CSI ? u reply would report.
|
||||
await emulator.write('\x1b[=5;1u\x1b[?1049h')
|
||||
expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(0)
|
||||
|
||||
await emulator.write('\x1b[=3;1u')
|
||||
expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(3)
|
||||
|
||||
await emulator.write('\x1b[?1049l')
|
||||
expect(emulator.getSnapshot().modes.kittyKeyboardFlags).toBe(5)
|
||||
})
|
||||
|
||||
it('never pushes kitty flags into rehydrateSequences', async () => {
|
||||
// Why: POST_REPLAY_REATTACH_RESET's deliberate kitty reset must stay
|
||||
// authoritative for renderer replays (terminal-query-authority.md).
|
||||
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
|
||||
await emulator.write('\x1b[?1049h\x1b[=5;1u')
|
||||
|
||||
const snapshot = emulator.getSnapshot()
|
||||
expect(snapshot.modes.kittyKeyboardFlags).toBe(5)
|
||||
expect(snapshot.rehydrateSequences).not.toContain('u')
|
||||
})
|
||||
|
||||
it('tracks split SGR mouse reporting sequences', async () => {
|
||||
emulator = new HeadlessEmulator({ cols: 80, rows: 24 })
|
||||
|
||||
|
||||
@@ -2,12 +2,28 @@ import './xterm-env-polyfill'
|
||||
import { Terminal } from '@xterm/headless'
|
||||
import { SerializeAddon } from '@xterm/addon-serialize'
|
||||
import { extractLastOscTitle } from '../../shared/agent-detection'
|
||||
import { TerminalMouseModeMirror } from './terminal-mouse-mode-mirror'
|
||||
import type { TerminalSnapshot, TerminalModes } from './types'
|
||||
|
||||
export type HeadlessEmulatorOptions = {
|
||||
cols: number
|
||||
rows: number
|
||||
scrollback?: number
|
||||
/** Phase-5 model query responder sink (terminal-query-authority.md).
|
||||
* When set, xterm-core auto-replies generated while parsing a write
|
||||
* flagged `forwardQueryReplies` are forwarded here; all other emissions
|
||||
* (seeds, hydration, snapshot replay, unsolicited core pushes) are
|
||||
* discarded. The daemon Session must NEVER pass this — its emulator
|
||||
* stays write-only forever (contract invariant: the daemon never
|
||||
* answers). */
|
||||
onQueryReply?: (reply: string) => void
|
||||
}
|
||||
|
||||
export type HeadlessEmulatorWriteOptions = {
|
||||
/** Reply ownership captured at ingestion for this exact chunk. Default
|
||||
* false is the main-side replay guard (twin of the renderer's
|
||||
* replay-guard.ts): seed/hydration/snapshot writes never forward. */
|
||||
forwardQueryReplies?: boolean
|
||||
}
|
||||
|
||||
export type HeadlessSnapshotOptions = {
|
||||
@@ -17,15 +33,19 @@ export type HeadlessSnapshotOptions = {
|
||||
type TerminalWithSynchronousWrite = Terminal & {
|
||||
_core?: {
|
||||
writeSync?: (data: string) => void
|
||||
// Why: kitty keyboard flags are not on the public IModes; read the core
|
||||
// service state the CSI =/>/< u handlers mutate.
|
||||
coreService?: {
|
||||
kittyKeyboard?: { flags?: number }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_SCROLLBACK = 5000
|
||||
// Keep in sync with the renderer twin in terminal-conpty-device-attributes.ts
|
||||
// (main must not import renderer modules).
|
||||
const CONPTY_DA1_RESPONSE = '\x1b[?61;4c'
|
||||
const OSC_SCAN_TAIL_LIMIT = 4096
|
||||
// Why: PTY/SSH chunks can split a long combined DECSET before the final h/l.
|
||||
// Keep parser state far beyond normal mode lists while still bounding memory.
|
||||
const PRIVATE_MODE_SCAN_TAIL_LIMIT = 4096
|
||||
type MouseTrackingMode = NonNullable<TerminalModes['mouseTrackingMode']>
|
||||
|
||||
function parseFileUriPath(uri: string): string | null {
|
||||
try {
|
||||
@@ -61,11 +81,15 @@ export class HeadlessEmulator {
|
||||
private cwd: string | null = null
|
||||
private lastTitle: string | null = null
|
||||
private oscScanTail = ''
|
||||
private privateModeScanTail = ''
|
||||
private mouseTrackingMode: MouseTrackingMode = 'none'
|
||||
private sgrMouseMode = false
|
||||
private sgrMousePixelsMode = false
|
||||
private mouseModes = new TerminalMouseModeMirror()
|
||||
private disposed = false
|
||||
private onQueryReply: ((reply: string) => void) | null
|
||||
private conptyDa1OverrideInstalled = false
|
||||
// Why: replies must be scoped to the exact write that carried the query.
|
||||
// The window opens around the parse of a forward-flagged chunk and closes
|
||||
// with it, so seeds/snapshots and unsolicited core emissions (e.g. native
|
||||
// 997 pushes from option mutations) can never leak to the PTY.
|
||||
private queryReplyForwardingDepth = 0
|
||||
|
||||
constructor(opts: HeadlessEmulatorOptions) {
|
||||
this.terminal = new Terminal({
|
||||
@@ -73,26 +97,72 @@ export class HeadlessEmulator {
|
||||
rows: opts.rows,
|
||||
scrollback: opts.scrollback ?? DEFAULT_SCROLLBACK,
|
||||
allowProposedApi: true,
|
||||
logLevel: 'off'
|
||||
logLevel: 'off',
|
||||
// Why: parity with the renderer's buildDefaultTerminalOptions — parse
|
||||
// CSI =/>/< u pushes so CSI ? u answers with the flags the hidden app
|
||||
// actually pushed. Write-only daemon use is unaffected: keyboard state
|
||||
// never alters serialization (terminal-query-authority.md §kitty).
|
||||
vtExtensions: { kittyKeyboard: true }
|
||||
})
|
||||
|
||||
this.serializer = new SerializeAddon()
|
||||
this.terminal.loadAddon(this.serializer)
|
||||
|
||||
// Why no onData wiring: this emulator exists purely for state tracking
|
||||
// (snapshots, cwd, mode flags). It MUST NOT respond to terminal query
|
||||
// sequences (DA1/DA2, DSR, OSC 10/11/12, DECRPM). The emulator parses
|
||||
// data in-process synchronously before `handleSubprocessData` forwards
|
||||
// it to the renderer over IPC, so any reply it emits would land on the
|
||||
// shell's stdin ahead of the renderer's xterm reply and win the race.
|
||||
// The renderer is the authoritative responder (it has the real theme,
|
||||
// cursor position, and paste mode); a daemon-side reply would be a
|
||||
// double-reply with wrong values. OSC 11 was the visible casualty:
|
||||
// Claude Code's /theme auto always saw the emulator's default-black
|
||||
// background regardless of Orca's configured terminal theme.
|
||||
// Why onData is gated behind onQueryReply: by default this emulator is
|
||||
// pure state tracking and MUST NOT respond to terminal query sequences
|
||||
// (DA1/DA2, DSR, OSC 10/11/12, DECRPM). The daemon emulator parses data
|
||||
// in-process synchronously before `handleSubprocessData` forwards it to
|
||||
// the renderer over IPC, so any reply it emitted would land on the
|
||||
// shell's stdin ahead of the renderer's xterm reply and win the race —
|
||||
// a double-reply with default-xterm values (OSC 11 default-black was
|
||||
// the visible casualty). Only main's runtime per-PTY emulators pass a
|
||||
// sink, and even then replies flow only for chunks the hidden-delivery
|
||||
// gate DROPPED, where the renderer never sees the bytes and main is the
|
||||
// single answerer. See docs/reference/terminal-query-authority.md.
|
||||
this.onQueryReply = opts.onQueryReply ?? null
|
||||
if (this.onQueryReply) {
|
||||
this.terminal.onData((reply) => this.emitQueryReply(reply))
|
||||
}
|
||||
}
|
||||
|
||||
write(data: string): Promise<void> {
|
||||
/** Main-side twin of the renderer's terminal-conpty-device-attributes.ts:
|
||||
* ConPTY 1.22+ blocks at spawn waiting for a DA1 reply, and the override
|
||||
* variant (`CSI ?61;4c`) must win. Returning true consumes the query so
|
||||
* xterm core's default `?1;2c` cannot double-reply (custom CSI handlers
|
||||
* run before core's; false falls through). The reply still routes through
|
||||
* the forwarding window, so replayed/seeded bytes never answer. */
|
||||
installConptyPrimaryDeviceAttributesOverride(): void {
|
||||
// Why idempotent: the spawn mark can land after daemon stream data
|
||||
// already created the emulator, so the override is installed both at
|
||||
// creation and retrofitted at mark time — never stacked.
|
||||
if (this.conptyDa1OverrideInstalled) {
|
||||
return
|
||||
}
|
||||
this.conptyDa1OverrideInstalled = true
|
||||
this.terminal.parser.registerCsiHandler({ final: 'c' }, (params) => {
|
||||
const isPrimaryQuery = params.length === 0 || (params.length === 1 && params[0] === 0)
|
||||
if (!isPrimaryQuery) {
|
||||
return false
|
||||
}
|
||||
this.emitQueryReply(CONPTY_DA1_RESPONSE)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
private emitQueryReply(reply: string): void {
|
||||
if (this.queryReplyForwardingDepth > 0 && this.onQueryReply) {
|
||||
this.onQueryReply(reply)
|
||||
}
|
||||
}
|
||||
|
||||
/** Severs the reply sink at PTY teardown. Queued writeChain links may
|
||||
* still parse after dispose is requested, and daemon respawns reuse
|
||||
* session ids — a late reply must never reach a successor PTY. */
|
||||
disableQueryReplyForwarding(): void {
|
||||
this.onQueryReply = null
|
||||
}
|
||||
|
||||
write(data: string, opts: HeadlessEmulatorWriteOptions = {}): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
@@ -104,19 +174,43 @@ export class HeadlessEmulator {
|
||||
if (lastTitle !== null) {
|
||||
this.lastTitle = lastTitle
|
||||
}
|
||||
const forwardQueryReplies = opts.forwardQueryReplies === true
|
||||
const writeSync = (this.terminal as TerminalWithSynchronousWrite)._core?.writeSync
|
||||
if (typeof writeSync === 'function') {
|
||||
// Why: hidden renderer restore snapshots are requested immediately after
|
||||
// PTY bursts; queued headless writes can snapshot half-cleared TUI rows.
|
||||
writeSync.call((this.terminal as TerminalWithSynchronousWrite)._core, data)
|
||||
this.scanPrivateModes(data)
|
||||
if (forwardQueryReplies) {
|
||||
this.queryReplyForwardingDepth += 1
|
||||
}
|
||||
try {
|
||||
// Why: hidden renderer restore snapshots are requested immediately after
|
||||
// PTY bursts; queued headless writes can snapshot half-cleared TUI rows.
|
||||
writeSync.call((this.terminal as TerminalWithSynchronousWrite)._core, data)
|
||||
} finally {
|
||||
if (forwardQueryReplies) {
|
||||
this.queryReplyForwardingDepth -= 1
|
||||
}
|
||||
}
|
||||
this.mouseModes.scan(data)
|
||||
return Promise.resolve()
|
||||
}
|
||||
// Why the sentinel: xterm parses queued writes asynchronously, so opening
|
||||
// the window at enqueue time would leak it over earlier queued unflagged
|
||||
// chunks (seed/hydration bytes parsing while depth > 0). Write callbacks
|
||||
// fire in FIFO parse order, so a zero-byte write whose callback opens the
|
||||
// window brackets the parse of exactly this chunk; the data callback
|
||||
// closes it.
|
||||
if (forwardQueryReplies) {
|
||||
this.terminal.write('', () => {
|
||||
this.queryReplyForwardingDepth += 1
|
||||
})
|
||||
}
|
||||
return new Promise<void>((resolve) => {
|
||||
this.terminal.write(data, () => {
|
||||
if (forwardQueryReplies) {
|
||||
this.queryReplyForwardingDepth -= 1
|
||||
}
|
||||
// Why: snapshots combine serialized xterm state with mirrored mouse
|
||||
// modes. Commit the mirror only after xterm has parsed the same bytes.
|
||||
this.scanPrivateModes(data)
|
||||
this.mouseModes.scan(data)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
@@ -207,78 +301,6 @@ export class HeadlessEmulator {
|
||||
return suffix.slice(-OSC_SCAN_TAIL_LIMIT)
|
||||
}
|
||||
|
||||
private scanPrivateModes(data: string): void {
|
||||
const input = this.privateModeScanTail + data
|
||||
this.privateModeScanTail = this.extractPrivateModeScanTail(input)
|
||||
// oxlint-disable-next-line no-control-regex -- terminal escape sequences require control chars
|
||||
const privateModeRe = /\x1bc|\x1b\[\?([0-9;]+)([hl])|\x9b\?([0-9;]+)([hl])/g
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = privateModeRe.exec(input)) !== null) {
|
||||
if (match[0] === '\x1bc') {
|
||||
this.mouseTrackingMode = 'none'
|
||||
this.sgrMouseMode = false
|
||||
this.sgrMousePixelsMode = false
|
||||
continue
|
||||
}
|
||||
const params = match[1] ?? match[3]
|
||||
const enabled = (match[2] ?? match[4]) === 'h'
|
||||
for (const rawParam of params.split(';')) {
|
||||
if (rawParam === '') {
|
||||
continue
|
||||
}
|
||||
const param = Number(rawParam)
|
||||
if (!Number.isInteger(param)) {
|
||||
continue
|
||||
}
|
||||
if (param === 9) {
|
||||
this.mouseTrackingMode = enabled ? 'x10' : 'none'
|
||||
}
|
||||
if (param === 1000) {
|
||||
this.mouseTrackingMode = enabled ? 'vt200' : 'none'
|
||||
}
|
||||
if (param === 1002) {
|
||||
this.mouseTrackingMode = enabled ? 'drag' : 'none'
|
||||
}
|
||||
if (param === 1003) {
|
||||
this.mouseTrackingMode = enabled ? 'any' : 'none'
|
||||
}
|
||||
if (param === 1006) {
|
||||
this.sgrMouseMode = enabled
|
||||
this.sgrMousePixelsMode = false
|
||||
}
|
||||
if (param === 1016) {
|
||||
this.sgrMouseMode = false
|
||||
this.sgrMousePixelsMode = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extractPrivateModeScanTail(input: string): string {
|
||||
const start = Math.max(input.lastIndexOf('\x1b'), input.lastIndexOf('\x9b'))
|
||||
if (start === -1) {
|
||||
return ''
|
||||
}
|
||||
const tail = input.slice(start)
|
||||
if (tail.length > PRIVATE_MODE_SCAN_TAIL_LIMIT) {
|
||||
return ''
|
||||
}
|
||||
if (tail === '\x1b' || tail === '\x1b[' || tail === '\x9b') {
|
||||
return tail
|
||||
}
|
||||
if (tail.startsWith('\x1b[?')) {
|
||||
return this.isIncompletePrivateModeParams(tail.slice(3)) ? tail : ''
|
||||
}
|
||||
if (tail.startsWith('\x9b?')) {
|
||||
return this.isIncompletePrivateModeParams(tail.slice(2)) ? tail : ''
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
private isIncompletePrivateModeParams(params: string): boolean {
|
||||
return /^[0-9;]*$/.test(params)
|
||||
}
|
||||
|
||||
private normalizeSnapshotAnsiForModes(snapshotAnsi: string, modes: TerminalModes): string {
|
||||
if (!modes.alternateScreen) {
|
||||
return snapshotAnsi
|
||||
@@ -303,20 +325,32 @@ export class HeadlessEmulator {
|
||||
|
||||
private getModes(): TerminalModes {
|
||||
const buffer = this.terminal.buffer.active
|
||||
const mouseTrackingMode = this.mouseTrackingMode
|
||||
const mouseTrackingMode = this.mouseModes.mouseTrackingMode
|
||||
return {
|
||||
bracketedPaste: this.terminal.modes.bracketedPasteMode,
|
||||
mouseTracking: mouseTrackingMode !== 'none',
|
||||
mouseTrackingMode,
|
||||
sgrMouseMode: this.sgrMouseMode,
|
||||
sgrMousePixelsMode: this.sgrMousePixelsMode,
|
||||
sgrMouseMode: this.mouseModes.sgrMouseMode,
|
||||
sgrMousePixelsMode: this.mouseModes.sgrMousePixelsMode,
|
||||
applicationCursor:
|
||||
buffer.type === 'normal' ? this.terminal.modes.applicationCursorKeysMode : false,
|
||||
alternateScreen: buffer.type === 'alternate'
|
||||
alternateScreen: buffer.type === 'alternate',
|
||||
kittyKeyboardFlags: this.getKittyKeyboardFlags()
|
||||
}
|
||||
}
|
||||
|
||||
private getKittyKeyboardFlags(): number {
|
||||
const flags = (this.terminal as TerminalWithSynchronousWrite)._core?.coreService?.kittyKeyboard
|
||||
?.flags
|
||||
return typeof flags === 'number' ? flags : 0
|
||||
}
|
||||
|
||||
private buildRehydrateSequences(modes: TerminalModes): string {
|
||||
// Why no kitty flags here: rehydrateSequences feeds renderer xterms, and
|
||||
// POST_REPLAY_REATTACH_RESET's deliberate kitty reset (stale CSI-u Ctrl+C
|
||||
// hazard) must stay authoritative. modes.kittyKeyboardFlags exists for
|
||||
// emulator re-seed parity only; a re-seeded emulator answers ?0u and
|
||||
// protocol-conformant programs re-push.
|
||||
const seqs: string[] = []
|
||||
if (modes.alternateScreen) {
|
||||
seqs.push('\x1b[?1049h')
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { TerminalModes } from './types'
|
||||
|
||||
type MouseTrackingMode = NonNullable<TerminalModes['mouseTrackingMode']>
|
||||
|
||||
// Why: PTY/SSH chunks can split a long combined DECSET before the final h/l.
|
||||
// Keep parser state far beyond normal mode lists while still bounding memory.
|
||||
const PRIVATE_MODE_SCAN_TAIL_LIMIT = 4096
|
||||
|
||||
/**
|
||||
* Mirrors DECSET mouse-protocol/encoding state from the raw byte stream.
|
||||
* xterm's public modes API does not expose which mouse protocol is active,
|
||||
* so snapshots track it independently of the headless terminal; callers
|
||||
* must feed `scan()` the same bytes the terminal parsed, in order.
|
||||
*/
|
||||
export class TerminalMouseModeMirror {
|
||||
private scanTail = ''
|
||||
private trackingModeState: MouseTrackingMode = 'none'
|
||||
private sgrMouseModeState = false
|
||||
private sgrMousePixelsModeState = false
|
||||
|
||||
get mouseTrackingMode(): MouseTrackingMode {
|
||||
return this.trackingModeState
|
||||
}
|
||||
|
||||
get sgrMouseMode(): boolean {
|
||||
return this.sgrMouseModeState
|
||||
}
|
||||
|
||||
get sgrMousePixelsMode(): boolean {
|
||||
return this.sgrMousePixelsModeState
|
||||
}
|
||||
|
||||
scan(data: string): void {
|
||||
const input = this.scanTail + data
|
||||
this.scanTail = this.extractScanTail(input)
|
||||
// oxlint-disable-next-line no-control-regex -- terminal escape sequences require control chars
|
||||
const privateModeRe = /\x1bc|\x1b\[\?([0-9;]+)([hl])|\x9b\?([0-9;]+)([hl])/g
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = privateModeRe.exec(input)) !== null) {
|
||||
if (match[0] === '\x1bc') {
|
||||
this.trackingModeState = 'none'
|
||||
this.sgrMouseModeState = false
|
||||
this.sgrMousePixelsModeState = false
|
||||
continue
|
||||
}
|
||||
const params = match[1] ?? match[3]
|
||||
const enabled = (match[2] ?? match[4]) === 'h'
|
||||
for (const rawParam of params.split(';')) {
|
||||
if (rawParam === '') {
|
||||
continue
|
||||
}
|
||||
const param = Number(rawParam)
|
||||
if (!Number.isInteger(param)) {
|
||||
continue
|
||||
}
|
||||
if (param === 9) {
|
||||
this.trackingModeState = enabled ? 'x10' : 'none'
|
||||
}
|
||||
if (param === 1000) {
|
||||
this.trackingModeState = enabled ? 'vt200' : 'none'
|
||||
}
|
||||
if (param === 1002) {
|
||||
this.trackingModeState = enabled ? 'drag' : 'none'
|
||||
}
|
||||
if (param === 1003) {
|
||||
this.trackingModeState = enabled ? 'any' : 'none'
|
||||
}
|
||||
if (param === 1006) {
|
||||
this.sgrMouseModeState = enabled
|
||||
this.sgrMousePixelsModeState = false
|
||||
}
|
||||
if (param === 1016) {
|
||||
this.sgrMouseModeState = false
|
||||
this.sgrMousePixelsModeState = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extractScanTail(input: string): string {
|
||||
const start = Math.max(input.lastIndexOf('\x1b'), input.lastIndexOf('\x9b'))
|
||||
if (start === -1) {
|
||||
return ''
|
||||
}
|
||||
const tail = input.slice(start)
|
||||
if (tail.length > PRIVATE_MODE_SCAN_TAIL_LIMIT) {
|
||||
return ''
|
||||
}
|
||||
if (tail === '\x1b' || tail === '\x1b[' || tail === '\x9b') {
|
||||
return tail
|
||||
}
|
||||
if (tail.startsWith('\x1b[?')) {
|
||||
return this.isIncompleteParams(tail.slice(3)) ? tail : ''
|
||||
}
|
||||
if (tail.startsWith('\x9b?')) {
|
||||
return this.isIncompleteParams(tail.slice(2)) ? tail : ''
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
private isIncompleteParams(params: string): boolean {
|
||||
return /^[0-9;]*$/.test(params)
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,13 @@ export type TerminalModes = {
|
||||
sgrMousePixelsMode?: boolean
|
||||
applicationCursor: boolean
|
||||
alternateScreen: boolean
|
||||
/** Kitty keyboard protocol flags (CSI = u pushes) for emulator re-seed
|
||||
* parity ONLY. Produced but not yet consumed — the re-seed consumer is
|
||||
* slice-3 work; do not mistake this field for live snapshot parity.
|
||||
* rehydrateSequences must never push these into a renderer xterm —
|
||||
* POST_REPLAY_REATTACH_RESET's deliberate kitty reset stays authoritative
|
||||
* (terminal-query-authority.md §kitty). */
|
||||
kittyKeyboardFlags?: number
|
||||
}
|
||||
|
||||
// ─── NDJSON Protocol Messages ───────────────────────────────────────
|
||||
|
||||
@@ -73,6 +73,11 @@ import {
|
||||
shouldDropHiddenRendererPtyData,
|
||||
unmarkHiddenRendererPty
|
||||
} from './pty-hidden-delivery-gate'
|
||||
import {
|
||||
clearNativeWindowsConptyPty,
|
||||
isNativeWindowsLocalPtySpawn,
|
||||
markNativeWindowsConptyPty
|
||||
} from '../runtime/terminal-model-query-authority'
|
||||
import type { PtyModelRestoreReason } from '../../shared/pty-model-restore-marker'
|
||||
import type { CodexAccountSelectionTarget } from '../codex-accounts/runtime-selection'
|
||||
import { isHostCodexHomeForWsl, isWslCodexHomeForHost } from '../pty/codex-home-wsl-env'
|
||||
@@ -858,6 +863,8 @@ export function clearProviderPtyState(id: string): void {
|
||||
// shutdown, SSH exit/connection teardown) — hidden/interest gate bits must
|
||||
// not outlive the PTY or a reused map entry could silently gate a new one.
|
||||
clearHiddenRendererPtyDeliveryState(id)
|
||||
// Why: the Phase-5 ConPTY DA1 spawn record must not leak onto a reused id.
|
||||
clearNativeWindowsConptyPty(id)
|
||||
const paneKey = ptyPaneKey.get(id)
|
||||
const stillOwnsPaneKey = paneKey ? paneKeyPtyId.get(paneKey) === id : false
|
||||
// Why: drop the memory-collector registration so a dead PTY does not keep
|
||||
@@ -1905,6 +1912,18 @@ export function registerPtyHandlers(
|
||||
}
|
||||
}
|
||||
ptyOwnership.set(result.id, args.connectionId ?? null)
|
||||
// Why: Phase-5 ConPTY DA1 — record the native-Windows-local-PTY
|
||||
// determination from the spawn record before any byte reaches the
|
||||
// runtime emulator, so its DA1 override exists from byte zero.
|
||||
if (
|
||||
isNativeWindowsLocalPtySpawn({
|
||||
connectionId: args.connectionId,
|
||||
cwd: args.cwd,
|
||||
shellOverride: daemonShellOverride
|
||||
})
|
||||
) {
|
||||
markNativeWindowsConptyPty(result.id)
|
||||
}
|
||||
const relayResultId = getRelayPtyId(args.connectionId, result.id)
|
||||
const persistSshLease = (): void => {
|
||||
if (!store || !args.connectionId) {
|
||||
@@ -2540,6 +2559,18 @@ export function registerPtyHandlers(
|
||||
}
|
||||
}
|
||||
ptyOwnership.set(result.id, args.connectionId ?? null)
|
||||
// Why: Phase-5 ConPTY DA1 — record the native-Windows-local-PTY
|
||||
// determination from the spawn record before the headless seed below,
|
||||
// so the runtime emulator's DA1 override exists from byte zero.
|
||||
if (
|
||||
isNativeWindowsLocalPtySpawn({
|
||||
connectionId: args.connectionId,
|
||||
cwd: args.cwd,
|
||||
shellOverride: effectiveShellOverride
|
||||
})
|
||||
) {
|
||||
markNativeWindowsConptyPty(result.id)
|
||||
}
|
||||
const relayResultId = getRelayPtyId(args.connectionId, result.id)
|
||||
if (store && args.connectionId) {
|
||||
// Why: remote PTYs live in the SSH relay grace window after Orca
|
||||
|
||||
@@ -479,6 +479,11 @@ import {
|
||||
import { prefetchWorktreeCreateBase } from '../worktree-create-base-prefetch'
|
||||
import { invalidateAuthorizedRootsCache } from '../ipc/filesystem-auth'
|
||||
import { HeadlessEmulator } from '../daemon/headless-emulator'
|
||||
import {
|
||||
isNativeWindowsConptyPty,
|
||||
registerConptyDa1OverrideInstaller,
|
||||
shouldModelAnswerHiddenPtyQueries
|
||||
} from './terminal-model-query-authority'
|
||||
import { killAllProcessesForWorktree } from './worktree-teardown'
|
||||
import { MOBILE_SUBSCRIBE_SCROLLBACK_ROWS } from './scrollback-limits'
|
||||
import type { IFilesystemProvider, IPtyProvider } from '../providers/types'
|
||||
@@ -584,6 +589,11 @@ type RuntimeStore = {
|
||||
mobileEmulatorDefaultDeviceUdid?: string | null
|
||||
voice?: VoiceSettings
|
||||
claudeAgentTeamsMode?: GlobalSettings['claudeAgentTeamsMode']
|
||||
// Why: Phase-5 query responder kill switches — read per chunk in
|
||||
// onPtyData to capture reply ownership at ingestion.
|
||||
terminalMainSideEffectAuthority?: GlobalSettings['terminalMainSideEffectAuthority']
|
||||
terminalHiddenDeliveryGate?: GlobalSettings['terminalHiddenDeliveryGate']
|
||||
terminalModelQueryAuthority?: GlobalSettings['terminalModelQueryAuthority']
|
||||
}
|
||||
// Why: narrow to `unknown` return so test mocks can return void without
|
||||
// a cast. The runtime never reads the return value — the persisted value
|
||||
@@ -1477,6 +1487,14 @@ export class OrcaRuntimeService {
|
||||
>
|
||||
>()
|
||||
|
||||
// Why: Phase-5 query-responder suppression — a terminal-RPC subscribe
|
||||
// stream feeds a remote xterm view (mobile/web/remote desktop) that answers
|
||||
// queries with view authority, so main must yield while one is attached
|
||||
// (terminal-query-authority.md). Ref-counted per PTY because multiple
|
||||
// streams can attach concurrently; mobileSubscribers is consulted too so
|
||||
// grace-window mobile records keep suppressing.
|
||||
private remoteTerminalViewSubscriberCounts = new Map<string, number>()
|
||||
|
||||
// Why: per-PTY driver state. The "driver" is whoever currently owns the
|
||||
// input/resize floor. While `kind === 'mobile'` the desktop renderer drops
|
||||
// xterm.onData/onResize and shows the lock banner; `terminal.send` /
|
||||
@@ -1665,6 +1683,10 @@ export class OrcaRuntimeService {
|
||||
this.onPtyStopped = deps?.onPtyStopped ?? null
|
||||
this.onTerminalAgentStatus = deps?.onTerminalAgentStatus ?? null
|
||||
this.onTerminalSideEffects = deps?.onTerminalSideEffects ?? null
|
||||
// Why: the ConPTY spawn mark can land after daemon stream data already
|
||||
// created this PTY's emulator; the mark retrofits the DA1 override here
|
||||
// (terminal-query-authority.md §ConPTY DA1).
|
||||
registerConptyDa1OverrideInstaller((ptyId) => this.ensureNativeWindowsConptyDa1Override(ptyId))
|
||||
}
|
||||
|
||||
getLocalProvider(): IPtyProvider | null {
|
||||
@@ -3325,6 +3347,12 @@ export class OrcaRuntimeService {
|
||||
// panel can surface them in place of the kernel bind address.
|
||||
advertisedUrlWatcher.ingest(ptyId, data, at)
|
||||
serveSimStateWatcher.ingestPtyOutput(ptyId, data)
|
||||
// Why: reply ownership is captured per chunk, here at ingestion — the
|
||||
// same module state and tick as the hidden-gate drop sites — and rides
|
||||
// the writeChain link. A mark/setting/subscriber flip before the queued
|
||||
// emulator write runs must not change who answers (terminal-query-
|
||||
// authority.md invariant 1).
|
||||
const forwardQueryReplies = this.shouldAnswerQueriesForLiveChunk(ptyId)
|
||||
// Ordering invariant (DO NOT REORDER): maybeHydrateHeadlessFromRenderer
|
||||
// MUST run before trackHeadlessTerminalData so the eager-state pattern
|
||||
// (set headlessTerminals + writeChain head = seedPromise) is in place
|
||||
@@ -3333,7 +3361,7 @@ export class OrcaRuntimeService {
|
||||
// that the later seed-resolve would overwrite, dropping the live byte.
|
||||
// See docs/mobile-prefer-renderer-scrollback.md.
|
||||
this.maybeHydrateHeadlessFromRenderer(ptyId)
|
||||
this.trackHeadlessTerminalData(ptyId, data, outputSequence)
|
||||
this.trackHeadlessTerminalData(ptyId, data, outputSequence, forwardQueryReplies)
|
||||
|
||||
let normalizedData: string | null = null
|
||||
const getNormalizedData = (): string => {
|
||||
@@ -3884,6 +3912,37 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
}
|
||||
|
||||
/** Registered by terminal-RPC subscribe/multiplex streams: while a remote
|
||||
* view subscriber is attached its xterm answers queries with view
|
||||
* authority and the model responder must stay silent. Returns an
|
||||
* idempotent release. */
|
||||
registerRemoteTerminalViewSubscriber(ptyId: string): () => void {
|
||||
this.remoteTerminalViewSubscriberCounts.set(
|
||||
ptyId,
|
||||
(this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 0) + 1
|
||||
)
|
||||
let released = false
|
||||
return () => {
|
||||
if (released) {
|
||||
return
|
||||
}
|
||||
released = true
|
||||
const next = (this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 1) - 1
|
||||
if (next <= 0) {
|
||||
this.remoteTerminalViewSubscriberCounts.delete(ptyId)
|
||||
} else {
|
||||
this.remoteTerminalViewSubscriberCounts.set(ptyId, next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasRemoteTerminalViewSubscriber(ptyId: string): boolean {
|
||||
if ((this.remoteTerminalViewSubscriberCounts.get(ptyId) ?? 0) > 0) {
|
||||
return true
|
||||
}
|
||||
return (this.mobileSubscribers.get(ptyId)?.size ?? 0) > 0
|
||||
}
|
||||
|
||||
subscribeToFitOverrideChanges(
|
||||
ptyId: string,
|
||||
listener: (event: { mode: 'mobile-fit' | 'desktop-fit'; cols: number; rows: number }) => void
|
||||
@@ -4004,14 +4063,12 @@ export class OrcaRuntimeService {
|
||||
return
|
||||
}
|
||||
const dims = size ?? this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 }
|
||||
const state: RuntimeHeadlessTerminal = {
|
||||
emulator: new HeadlessEmulator({ cols: dims.cols, rows: dims.rows }),
|
||||
outputSequence: 0,
|
||||
writeChain: Promise.resolve()
|
||||
}
|
||||
const state = this.createPtyHeadlessTerminalState(ptyId, dims)
|
||||
this.headlessTerminals.set(ptyId, state)
|
||||
state.writeChain = state.writeChain
|
||||
.then(async () => {
|
||||
// Why: seed writes never set forwardQueryReplies — the main-side
|
||||
// replay guard. A snapshot containing old queries must answer no one.
|
||||
await state.emulator.write(data)
|
||||
if (metadata.cwd !== undefined) {
|
||||
state.emulator.setCwd(metadata.cwd)
|
||||
@@ -4050,11 +4107,9 @@ export class OrcaRuntimeService {
|
||||
|
||||
this.headlessHydrationState.set(ptyId, 'pending')
|
||||
const dims = this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 }
|
||||
const state: RuntimeHeadlessTerminal = {
|
||||
emulator: new HeadlessEmulator({ cols: dims.cols, rows: dims.rows }),
|
||||
outputSequence: 0,
|
||||
writeChain: Promise.resolve()
|
||||
}
|
||||
// Why: hydration writes below never set forwardQueryReplies (main-side
|
||||
// replay guard) — renderer-buffer snapshots can embed stale queries.
|
||||
const state = this.createPtyHeadlessTerminalState(ptyId, dims)
|
||||
this.headlessTerminals.set(ptyId, state)
|
||||
|
||||
// Why: append the seed work to writeChain so live writes queued by
|
||||
@@ -4127,11 +4182,28 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
}
|
||||
|
||||
private trackHeadlessTerminalData(ptyId: string, data: string, outputSequence: number): void {
|
||||
/** Per-chunk reply-ownership capture (Phase 5). Evaluated synchronously at
|
||||
* ingestion only — never re-read at reply time. */
|
||||
private shouldAnswerQueriesForLiveChunk(ptyId: string): boolean {
|
||||
return shouldModelAnswerHiddenPtyQueries({
|
||||
ptyId,
|
||||
settings: this.store?.getSettings(),
|
||||
hasRemoteViewSubscriber: this.hasRemoteTerminalViewSubscriber(ptyId)
|
||||
})
|
||||
}
|
||||
|
||||
private trackHeadlessTerminalData(
|
||||
ptyId: string,
|
||||
data: string,
|
||||
outputSequence: number,
|
||||
forwardQueryReplies = false
|
||||
): void {
|
||||
const state = this.getOrCreateHeadlessTerminal(ptyId)
|
||||
state.writeChain = state.writeChain
|
||||
.then(async () => {
|
||||
await state.emulator.write(data)
|
||||
// Why: the ingestion-time ownership decision is closed over this
|
||||
// chain link; async scheduling cannot retroactively change it.
|
||||
await state.emulator.write(data, { forwardQueryReplies })
|
||||
state.outputSequence = outputSequence
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -4140,17 +4212,53 @@ export class OrcaRuntimeService {
|
||||
})
|
||||
}
|
||||
|
||||
/** Shared factory for the per-PTY runtime emulators (seed, hydration, and
|
||||
* lazy live-byte creation): wires the Phase-5 query-reply sink and the
|
||||
* ConPTY DA1 override. The daemon emulator never goes through here. */
|
||||
private createPtyHeadlessTerminalState(
|
||||
ptyId: string,
|
||||
dims: { cols: number; rows: number }
|
||||
): RuntimeHeadlessTerminal {
|
||||
let state: RuntimeHeadlessTerminal | null = null
|
||||
const emulator = new HeadlessEmulator({
|
||||
cols: dims.cols,
|
||||
rows: dims.rows,
|
||||
// Why: replies take the provider input path (same entry as pty:write —
|
||||
// daemon shell-ready gating and the SSH relay write apply unchanged),
|
||||
// NOT writePtyInput, so renderer interactive-output metering never
|
||||
// counts responder traffic as user-input echo.
|
||||
onQueryReply: (reply) => {
|
||||
// Why the identity check: queued writeChain links can parse after
|
||||
// disposeHeadlessTerminal, and daemon respawns reuse session ids — a
|
||||
// stale link's reply must never reach a successor PTY under this id.
|
||||
if (state !== null && this.headlessTerminals.get(ptyId) === state) {
|
||||
this.ptyController?.write(ptyId, reply)
|
||||
}
|
||||
}
|
||||
})
|
||||
if (isNativeWindowsConptyPty(ptyId)) {
|
||||
emulator.installConptyPrimaryDeviceAttributesOverride()
|
||||
}
|
||||
state = { emulator, outputSequence: 0, writeChain: Promise.resolve() }
|
||||
return state
|
||||
}
|
||||
|
||||
/** Phase-5 ConPTY DA1 retrofit (terminal-query-authority.md): invoked via
|
||||
* markNativeWindowsConptyPty when the spawn mark lands after daemon stream
|
||||
* data already created this PTY's emulator. Idempotent emulator-side. */
|
||||
private ensureNativeWindowsConptyDa1Override(ptyId: string): void {
|
||||
if (isNativeWindowsConptyPty(ptyId)) {
|
||||
this.headlessTerminals.get(ptyId)?.emulator.installConptyPrimaryDeviceAttributesOverride()
|
||||
}
|
||||
}
|
||||
|
||||
private getOrCreateHeadlessTerminal(ptyId: string): RuntimeHeadlessTerminal {
|
||||
const existing = this.headlessTerminals.get(ptyId)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const size = this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 }
|
||||
const state: RuntimeHeadlessTerminal = {
|
||||
emulator: new HeadlessEmulator({ cols: size.cols, rows: size.rows }),
|
||||
outputSequence: 0,
|
||||
writeChain: Promise.resolve()
|
||||
}
|
||||
const state = this.createPtyHeadlessTerminalState(ptyId, size)
|
||||
this.headlessTerminals.set(ptyId, state)
|
||||
return state
|
||||
}
|
||||
@@ -4315,6 +4423,10 @@ export class OrcaRuntimeService {
|
||||
return
|
||||
}
|
||||
this.headlessTerminals.delete(ptyId)
|
||||
// Why: queued chain links still parse below before the emulator disposes;
|
||||
// sever the reply sink now so they cannot write to a respawned PTY that
|
||||
// reused this id (belt to the sink's state-identity check).
|
||||
state.emulator.disableQueryReplyForwarding()
|
||||
state.writeChain.finally(() => state.emulator.dispose()).catch(() => state.emulator.dispose())
|
||||
}
|
||||
|
||||
@@ -5013,6 +5125,7 @@ export class OrcaRuntimeService {
|
||||
serveSimStateWatcher.unbindPty(ptyId)
|
||||
// Clean up new mobile state for this PTY
|
||||
this.mobileSubscribers.delete(ptyId)
|
||||
this.remoteTerminalViewSubscriberCounts.delete(ptyId)
|
||||
this.mobileDisplayModes.delete(ptyId)
|
||||
this.resizeListeners.delete(ptyId)
|
||||
this.lastRendererSizes.delete(ptyId)
|
||||
|
||||
@@ -1319,6 +1319,16 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
emit({ type: 'end', streamId: request.streamId })
|
||||
return
|
||||
}
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
// Why: a competing subscribe for the same streamId can fully register
|
||||
// while this one awaited the PTY id above. Overwriting it in
|
||||
// `streams` would orphan its data/view-subscriber registrations — a
|
||||
// leaked view subscriber permanently silences the model query
|
||||
// responder (terminal-query-authority.md). Detach it so every
|
||||
// registration stays release-balanced.
|
||||
detachStream(request.streamId, false)
|
||||
|
||||
const ptyId = leaf.ptyId
|
||||
const stream: TerminalMultiplexStream = {
|
||||
@@ -1354,7 +1364,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
)
|
||||
|
||||
try {
|
||||
stream.unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data, meta) => {
|
||||
const unsubscribeStreamData = runtime.subscribeToTerminalData(ptyId, (data, meta) => {
|
||||
if (closed || streams.get(request.streamId) !== stream) {
|
||||
return
|
||||
}
|
||||
@@ -1364,6 +1374,15 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
}
|
||||
stream.outputBatcher.push(data, meta)
|
||||
})
|
||||
// Why: a multiplexed stream feeds a remote xterm view that answers
|
||||
// terminal queries with view authority; the main model responder
|
||||
// yields while it is attached (terminal-query-authority.md).
|
||||
// Wrapped into unsubscribeData so every detach path releases it.
|
||||
const releaseViewSubscriber = runtime.registerRemoteTerminalViewSubscriber(ptyId)
|
||||
stream.unsubscribeData = () => {
|
||||
releaseViewSubscriber()
|
||||
unsubscribeStreamData()
|
||||
}
|
||||
|
||||
if (isMobile && request.client?.id) {
|
||||
await runtime.handleMobileSubscribe(ptyId, request.client.id, request.viewport)
|
||||
@@ -1479,6 +1498,13 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
// Why the ownership check: a newer subscribe may own this streamId
|
||||
// now (it detached and released this stream on arrival). Detaching
|
||||
// or erroring the slot here would tear down the successor's live
|
||||
// registrations instead of this stream's.
|
||||
if (streams.get(request.streamId) !== stream) {
|
||||
return
|
||||
}
|
||||
detachStream(request.streamId, false)
|
||||
sendStreamError(request.streamId, error instanceof Error ? error.message : String(error))
|
||||
emit({ type: 'end', streamId: request.streamId })
|
||||
@@ -1578,9 +1604,19 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
const outputBatcher = createTerminalOutputBatcher((chunk) => {
|
||||
emit({ type: 'data', chunk })
|
||||
})
|
||||
const unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data) => {
|
||||
const unsubscribeStreamData = runtime.subscribeToTerminalData(ptyId, (data) => {
|
||||
outputBatcher.push(data)
|
||||
})
|
||||
// Why: this legacy JSON stream can feed a live xterm view too
|
||||
// (older web/desktop subscribers), so it conservatively registers
|
||||
// as a remote view subscriber. For read-only watchers the cost is
|
||||
// a withheld model reply — the pre-Phase-5 status quo — which is
|
||||
// strictly safer than a double reply under a view consumer.
|
||||
const releaseViewSubscriber = runtime.registerRemoteTerminalViewSubscriber(ptyId)
|
||||
const unsubscribeData = (): void => {
|
||||
releaseViewSubscriber()
|
||||
unsubscribeStreamData()
|
||||
}
|
||||
const unsubscribeFit = runtime.subscribeToFitOverrideChanges(ptyId, (event) => {
|
||||
outputBatcher.flush()
|
||||
emit({
|
||||
@@ -1718,7 +1754,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
return
|
||||
}
|
||||
|
||||
unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data, meta) => {
|
||||
const unsubscribeStreamData = runtime.subscribeToTerminalData(ptyId, (data, meta) => {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
@@ -1732,6 +1768,14 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
}
|
||||
outputBatcher?.push(data, meta)
|
||||
})
|
||||
// Why: binary subscribe streams feed remote xterm views (mobile and
|
||||
// binary-capable desktop clients) that answer queries with view
|
||||
// authority; the main model responder yields while attached.
|
||||
const releaseViewSubscriber = runtime.registerRemoteTerminalViewSubscriber(ptyId)
|
||||
unsubscribeData = () => {
|
||||
releaseViewSubscriber()
|
||||
unsubscribeStreamData()
|
||||
}
|
||||
|
||||
const read = await runtime.readTerminal(params.terminal)
|
||||
const serialized = await serializeBudgetedMobileSnapshot(runtime, ptyId, isMobile)
|
||||
|
||||
@@ -9,6 +9,9 @@ import type { RuntimeTerminalWait } from '../../../shared/runtime-types'
|
||||
function stubRuntime(overrides: Partial<OrcaRuntimeService> = {}): OrcaRuntimeService {
|
||||
return {
|
||||
getRuntimeId: () => 'test-runtime',
|
||||
// Why: subscribe streams register as remote view subscribers for Phase-5
|
||||
// query-authority suppression (terminal-query-authority.md).
|
||||
registerRemoteTerminalViewSubscriber: () => () => {},
|
||||
...overrides
|
||||
} as OrcaRuntimeService
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ import {
|
||||
function stubRuntime(overrides: Partial<OrcaRuntimeService> = {}): OrcaRuntimeService {
|
||||
return {
|
||||
getRuntimeId: () => 'test-runtime',
|
||||
// Why: every multiplex stream registers as a remote view subscriber for
|
||||
// Phase-5 query-authority suppression (terminal-query-authority.md).
|
||||
registerRemoteTerminalViewSubscriber: () => () => {},
|
||||
...overrides
|
||||
} as OrcaRuntimeService
|
||||
}
|
||||
@@ -1673,6 +1676,226 @@ describe('terminal multiplex RPC', () => {
|
||||
await dispatchPromise
|
||||
})
|
||||
|
||||
it('keeps view-subscriber releases balanced when a same-streamId subscribe overwrites a blocked one', async () => {
|
||||
const messages: string[] = []
|
||||
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
|
||||
const handlers = new Map<
|
||||
number,
|
||||
(frame: NonNullable<ReturnType<typeof decodeTerminalStreamFrame>>) => void
|
||||
>()
|
||||
const cleanups = new Map<string, () => void>()
|
||||
// Why: a leaked registration permanently suppresses the model query
|
||||
// responder (terminal-query-authority.md) — the count must return to 0.
|
||||
let viewSubscriberCount = 0
|
||||
let leafResolved = false
|
||||
let resolveFirstWait: (ptyId: string) => void = () => {}
|
||||
const runtime = stubRuntime({
|
||||
resolveLeafForHandle: vi.fn(() => (leafResolved ? { ptyId: 'pty-1' } : { ptyId: null })),
|
||||
waitForLeafPtyId: vi.fn(
|
||||
() =>
|
||||
new Promise<string>((resolve) => {
|
||||
resolveFirstWait = resolve
|
||||
})
|
||||
),
|
||||
registerRemoteTerminalViewSubscriber: vi.fn(() => {
|
||||
viewSubscriberCount += 1
|
||||
let released = false
|
||||
return () => {
|
||||
if (!released) {
|
||||
released = true
|
||||
viewSubscriberCount -= 1
|
||||
}
|
||||
}
|
||||
}),
|
||||
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
|
||||
serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snap', cols: 80, rows: 24 }),
|
||||
getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }),
|
||||
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
|
||||
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
|
||||
subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()),
|
||||
handleMobileSubscribe: vi.fn().mockResolvedValue(undefined),
|
||||
handleMobileUnsubscribe: vi.fn(),
|
||||
registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => {
|
||||
cleanups.set(id, cleanup)
|
||||
}),
|
||||
waitForTerminal: vi.fn(() => new Promise<RuntimeTerminalWait>(() => {}))
|
||||
})
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
|
||||
|
||||
const dispatchPromise = dispatcher.dispatchStreaming(
|
||||
makeRequest('terminal.multiplex', {}),
|
||||
(msg) => messages.push(msg),
|
||||
{
|
||||
connectionId: 'conn-overwrite',
|
||||
sendBinary: (bytes) => binaryFrames.push(bytes),
|
||||
registerBinaryStreamHandler: (streamId, handler) => {
|
||||
handlers.set(streamId, handler)
|
||||
return () => handlers.delete(streamId)
|
||||
}
|
||||
}
|
||||
)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true)
|
||||
)
|
||||
const sendSubscribe = (): void => {
|
||||
handlers.get(0)?.(
|
||||
decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Subscribe,
|
||||
streamId: 0,
|
||||
seq: 1,
|
||||
payload: encodeTerminalStreamJson({
|
||||
streamId: 7,
|
||||
terminal: 'terminal-1',
|
||||
client: { id: 'phone-1', type: 'mobile' }
|
||||
})
|
||||
})
|
||||
)!
|
||||
)
|
||||
}
|
||||
|
||||
// Subscribe A blocks in waitForLeafPtyId; subscribe B (same streamId)
|
||||
// then resolves the leaf directly and fully registers.
|
||||
sendSubscribe()
|
||||
await vi.waitFor(() => expect(runtime.waitForLeafPtyId).toHaveBeenCalled())
|
||||
leafResolved = true
|
||||
sendSubscribe()
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.filter((msg) => JSON.parse(msg).result?.type === 'subscribed')).toHaveLength(
|
||||
1
|
||||
)
|
||||
)
|
||||
|
||||
// A resumes and takes the slot; B's registration must be released, not
|
||||
// orphaned by the overwrite.
|
||||
resolveFirstWait('pty-1')
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.filter((msg) => JSON.parse(msg).result?.type === 'subscribed')).toHaveLength(
|
||||
2
|
||||
)
|
||||
)
|
||||
|
||||
handlers.get(7)?.(
|
||||
decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Unsubscribe,
|
||||
streamId: 7,
|
||||
seq: 2,
|
||||
payload: new Uint8Array()
|
||||
})
|
||||
)!
|
||||
)
|
||||
expect(viewSubscriberCount).toBe(0)
|
||||
|
||||
cleanups.get('terminal-multiplex:conn-overwrite')?.()
|
||||
await dispatchPromise
|
||||
})
|
||||
|
||||
it('keeps an evicted subscribe error from detaching the successor stream', async () => {
|
||||
const messages: string[] = []
|
||||
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
|
||||
const handlers = new Map<
|
||||
number,
|
||||
(frame: NonNullable<ReturnType<typeof decodeTerminalStreamFrame>>) => void
|
||||
>()
|
||||
const cleanups = new Map<string, () => void>()
|
||||
let viewSubscriberCount = 0
|
||||
const mobileSubscribeWaiters: {
|
||||
resolve: () => void
|
||||
reject: (error: Error) => void
|
||||
}[] = []
|
||||
const runtime = stubRuntime({
|
||||
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
|
||||
registerRemoteTerminalViewSubscriber: vi.fn(() => {
|
||||
viewSubscriberCount += 1
|
||||
let released = false
|
||||
return () => {
|
||||
if (!released) {
|
||||
released = true
|
||||
viewSubscriberCount -= 1
|
||||
}
|
||||
}
|
||||
}),
|
||||
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
|
||||
serializeTerminalBuffer: vi.fn().mockResolvedValue({ data: 'snap', cols: 80, rows: 24 }),
|
||||
getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }),
|
||||
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
|
||||
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
|
||||
subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()),
|
||||
handleMobileSubscribe: vi.fn(
|
||||
() =>
|
||||
new Promise<boolean>((resolve, reject) => {
|
||||
mobileSubscribeWaiters.push({ resolve: () => resolve(true), reject })
|
||||
})
|
||||
),
|
||||
handleMobileUnsubscribe: vi.fn(),
|
||||
registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => {
|
||||
cleanups.set(id, cleanup)
|
||||
}),
|
||||
waitForTerminal: vi.fn(() => new Promise<RuntimeTerminalWait>(() => {}))
|
||||
})
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
|
||||
|
||||
const dispatchPromise = dispatcher.dispatchStreaming(
|
||||
makeRequest('terminal.multiplex', {}),
|
||||
(msg) => messages.push(msg),
|
||||
{
|
||||
connectionId: 'conn-evicted-error',
|
||||
sendBinary: (bytes) => binaryFrames.push(bytes),
|
||||
registerBinaryStreamHandler: (streamId, handler) => {
|
||||
handlers.set(streamId, handler)
|
||||
return () => handlers.delete(streamId)
|
||||
}
|
||||
}
|
||||
)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true)
|
||||
)
|
||||
const sendSubscribe = (): void => {
|
||||
handlers.get(0)?.(
|
||||
decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Subscribe,
|
||||
streamId: 0,
|
||||
seq: 1,
|
||||
payload: encodeTerminalStreamJson({
|
||||
streamId: 9,
|
||||
terminal: 'terminal-1',
|
||||
client: { id: 'phone-1', type: 'mobile' }
|
||||
})
|
||||
})
|
||||
)!
|
||||
)
|
||||
}
|
||||
|
||||
// A registers, then blocks in handleMobileSubscribe. B (same streamId)
|
||||
// evicts A on arrival and completes its own registration.
|
||||
sendSubscribe()
|
||||
await vi.waitFor(() => expect(mobileSubscribeWaiters).toHaveLength(1))
|
||||
sendSubscribe()
|
||||
await vi.waitFor(() => expect(mobileSubscribeWaiters).toHaveLength(2))
|
||||
mobileSubscribeWaiters[1]!.resolve()
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.filter((msg) => JSON.parse(msg).result?.type === 'subscribed')).toHaveLength(
|
||||
1
|
||||
)
|
||||
)
|
||||
expect(viewSubscriberCount).toBe(1)
|
||||
|
||||
// A's pending await now rejects. The evicted stream must not detach the
|
||||
// successor that owns the slot.
|
||||
mobileSubscribeWaiters[0]!.reject(new Error('mobile_subscribe_failed'))
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
expect(viewSubscriberCount).toBe(1)
|
||||
|
||||
cleanups.get('terminal-multiplex:conn-evicted-error')?.()
|
||||
await dispatchPromise
|
||||
expect(viewSubscriberCount).toBe(0)
|
||||
})
|
||||
|
||||
it('bounds live output queued while a multiplex snapshot is loading', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,9 @@ import {
|
||||
function stubRuntime(overrides: Partial<OrcaRuntimeService> = {}): OrcaRuntimeService {
|
||||
return {
|
||||
getRuntimeId: () => 'test-runtime',
|
||||
// Why: subscribe streams register as remote view subscribers for Phase-5
|
||||
// query-authority suppression (terminal-query-authority.md).
|
||||
registerRemoteTerminalViewSubscriber: () => () => {},
|
||||
...overrides
|
||||
} as OrcaRuntimeService
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ import {
|
||||
function stubRuntime(overrides: Partial<OrcaRuntimeService> = {}): OrcaRuntimeService {
|
||||
return {
|
||||
getRuntimeId: () => 'test-runtime',
|
||||
// Why: subscribe streams register as remote view subscribers for Phase-5
|
||||
// query-authority suppression (terminal-query-authority.md).
|
||||
registerRemoteTerminalViewSubscriber: () => () => {},
|
||||
...overrides
|
||||
} as OrcaRuntimeService
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
_resetTerminalModelQueryAuthorityForTest,
|
||||
clearNativeWindowsConptyPty,
|
||||
isNativeWindowsConptyPty,
|
||||
isNativeWindowsLocalPtySpawn,
|
||||
isTerminalModelQueryAuthorityEnabled,
|
||||
markNativeWindowsConptyPty,
|
||||
shouldModelAnswerHiddenPtyQueries
|
||||
} from './terminal-model-query-authority'
|
||||
import {
|
||||
_resetHiddenRendererPtyDeliveryGateForTest,
|
||||
markHiddenRendererPty,
|
||||
setRendererPtyDeliveryInterest
|
||||
} from '../ipc/pty-hidden-delivery-gate'
|
||||
|
||||
const ALL_ON = {
|
||||
terminalMainSideEffectAuthority: true,
|
||||
terminalHiddenDeliveryGate: true,
|
||||
terminalModelQueryAuthority: true
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
_resetTerminalModelQueryAuthorityForTest()
|
||||
_resetHiddenRendererPtyDeliveryGateForTest()
|
||||
})
|
||||
|
||||
describe('isTerminalModelQueryAuthorityEnabled', () => {
|
||||
it('defaults on, including for absent settings', () => {
|
||||
expect(isTerminalModelQueryAuthorityEnabled(ALL_ON)).toBe(true)
|
||||
expect(isTerminalModelQueryAuthorityEnabled({})).toBe(true)
|
||||
expect(isTerminalModelQueryAuthorityEnabled(null)).toBe(true)
|
||||
expect(isTerminalModelQueryAuthorityEnabled(undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('is an independent off switch for the responder alone', () => {
|
||||
expect(
|
||||
isTerminalModelQueryAuthorityEnabled({ ...ALL_ON, terminalModelQueryAuthority: false })
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('requires both Phase-4 gate switches — no marks exist without them', () => {
|
||||
expect(
|
||||
isTerminalModelQueryAuthorityEnabled({ ...ALL_ON, terminalHiddenDeliveryGate: false })
|
||||
).toBe(false)
|
||||
expect(
|
||||
isTerminalModelQueryAuthorityEnabled({ ...ALL_ON, terminalMainSideEffectAuthority: false })
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldModelAnswerHiddenPtyQueries', () => {
|
||||
const answer = (ptyId: string, overrides: Record<string, boolean> = {}): boolean =>
|
||||
shouldModelAnswerHiddenPtyQueries({
|
||||
ptyId,
|
||||
settings: { ...ALL_ON, ...overrides },
|
||||
hasRemoteViewSubscriber: false
|
||||
})
|
||||
|
||||
it('answers only for hidden-marked PTYs (the delivery decision is the reply decision)', () => {
|
||||
expect(answer('pty-1')).toBe(false)
|
||||
markHiddenRendererPty('pty-1')
|
||||
expect(answer('pty-1')).toBe(true)
|
||||
expect(answer('pty-other')).toBe(false)
|
||||
})
|
||||
|
||||
it('yields to registered renderer delivery interest (chunk is delivered to a sidecar)', () => {
|
||||
markHiddenRendererPty('pty-1')
|
||||
setRendererPtyDeliveryInterest('pty-1', true)
|
||||
expect(answer('pty-1')).toBe(false)
|
||||
setRendererPtyDeliveryInterest('pty-1', false)
|
||||
expect(answer('pty-1')).toBe(true)
|
||||
})
|
||||
|
||||
it('yields while a remote view subscriber is attached', () => {
|
||||
markHiddenRendererPty('pty-1')
|
||||
expect(
|
||||
shouldModelAnswerHiddenPtyQueries({
|
||||
ptyId: 'pty-1',
|
||||
settings: ALL_ON,
|
||||
hasRemoteViewSubscriber: true
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('stays silent under any kill switch', () => {
|
||||
markHiddenRendererPty('pty-1')
|
||||
expect(answer('pty-1', { terminalModelQueryAuthority: false })).toBe(false)
|
||||
expect(answer('pty-1', { terminalHiddenDeliveryGate: false })).toBe(false)
|
||||
expect(answer('pty-1', { terminalMainSideEffectAuthority: false })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isNativeWindowsLocalPtySpawn (main-side mirror of isLocalNativeWindowsPty)', () => {
|
||||
const base = {
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: undefined,
|
||||
platform: 'win32' as NodeJS.Platform
|
||||
}
|
||||
|
||||
it('matches local native Windows spawns', () => {
|
||||
expect(isNativeWindowsLocalPtySpawn(base)).toBe(true)
|
||||
expect(isNativeWindowsLocalPtySpawn({ ...base, connectionId: undefined })).toBe(true)
|
||||
expect(
|
||||
isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'C:\\Tools\\powershell.exe' })
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects non-Windows hosts', () => {
|
||||
expect(isNativeWindowsLocalPtySpawn({ ...base, platform: 'darwin' })).toBe(false)
|
||||
expect(isNativeWindowsLocalPtySpawn({ ...base, platform: 'linux' })).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects SSH-backed spawns', () => {
|
||||
expect(isNativeWindowsLocalPtySpawn({ ...base, connectionId: 'ssh-1' })).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects WSL cwds and WSL shell overrides', () => {
|
||||
expect(
|
||||
isNativeWindowsLocalPtySpawn({ ...base, cwd: '\\\\wsl.localhost\\Ubuntu\\home\\me' })
|
||||
).toBe(false)
|
||||
expect(isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'wsl.exe' })).toBe(false)
|
||||
expect(
|
||||
isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'C:\\Windows\\System32\\wsl.exe' })
|
||||
).toBe(false)
|
||||
expect(isNativeWindowsLocalPtySpawn({ ...base, shellOverride: 'wsl' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('native-Windows ConPTY spawn record', () => {
|
||||
it('marks, reads, and clears per PTY', () => {
|
||||
expect(isNativeWindowsConptyPty('pty-1')).toBe(false)
|
||||
markNativeWindowsConptyPty('pty-1')
|
||||
expect(isNativeWindowsConptyPty('pty-1')).toBe(true)
|
||||
expect(isNativeWindowsConptyPty('pty-2')).toBe(false)
|
||||
clearNativeWindowsConptyPty('pty-1')
|
||||
expect(isNativeWindowsConptyPty('pty-1')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Phase 5 of the terminal model/view architecture: main-side terminal query
|
||||
* authority (docs/reference/terminal-query-authority.md).
|
||||
*
|
||||
* The delivery decision is the reply decision: main answers a query iff the
|
||||
* hidden-delivery gate dropped the chunk that carried it. This module owns
|
||||
* the responder kill-switch predicate and the main-side mirror of the
|
||||
* renderer's native-Windows-ConPTY determination, recorded per PTY at spawn
|
||||
* so the runtime emulator can register the DA1 override before byte zero.
|
||||
*/
|
||||
import type { GlobalSettings } from '../../shared/types'
|
||||
import { isWslUncPath } from '../../shared/wsl-paths'
|
||||
import {
|
||||
isHiddenPtyDeliveryGateEnabled,
|
||||
shouldDropHiddenRendererPtyData
|
||||
} from '../ipc/pty-hidden-delivery-gate'
|
||||
|
||||
export type TerminalModelQueryAuthoritySettings = Pick<
|
||||
GlobalSettings,
|
||||
'terminalMainSideEffectAuthority' | 'terminalHiddenDeliveryGate' | 'terminalModelQueryAuthority'
|
||||
>
|
||||
|
||||
/** Responder kill switch: requires BOTH Phase-4 gate switches (no marks/drops
|
||||
* exist without them) plus the Phase-5-specific independent off switch. */
|
||||
export function isTerminalModelQueryAuthorityEnabled(
|
||||
settings: TerminalModelQueryAuthoritySettings | null | undefined
|
||||
): boolean {
|
||||
return isHiddenPtyDeliveryGateEnabled(settings) && settings?.terminalModelQueryAuthority !== false
|
||||
}
|
||||
|
||||
/** Per-chunk reply-ownership predicate, evaluated once at ingestion in
|
||||
* OrcaRuntimeService.onPtyData — the same module state and tick as the
|
||||
* hidden-gate drop sites, so "chunk dropped" and "main answers" cannot
|
||||
* diverge for live chunks. Remote view subscribers (mobile/web/remote
|
||||
* desktop xterms on the multiplexed stream) keep view authority, so main
|
||||
* yields while one is attached. */
|
||||
export function shouldModelAnswerHiddenPtyQueries(opts: {
|
||||
ptyId: string
|
||||
settings: TerminalModelQueryAuthoritySettings | null | undefined
|
||||
hasRemoteViewSubscriber: boolean
|
||||
}): boolean {
|
||||
return (
|
||||
isTerminalModelQueryAuthorityEnabled(opts.settings) &&
|
||||
!opts.hasRemoteViewSubscriber &&
|
||||
shouldDropHiddenRendererPtyData(opts.ptyId, opts.settings)
|
||||
)
|
||||
}
|
||||
|
||||
/** Main-side mirror of the renderer's isLocalNativeWindowsPty
|
||||
* (windows-pty-compatibility.ts), computed from spawn-time facts: local or
|
||||
* daemon provider (no SSH connection), win32 host, and not a WSL shell. */
|
||||
export function isNativeWindowsLocalPtySpawn(opts: {
|
||||
connectionId: string | null | undefined
|
||||
cwd: string | null | undefined
|
||||
shellOverride: string | null | undefined
|
||||
platform?: NodeJS.Platform
|
||||
}): boolean {
|
||||
if ((opts.platform ?? process.platform) !== 'win32') {
|
||||
return false
|
||||
}
|
||||
if (opts.connectionId) {
|
||||
return false
|
||||
}
|
||||
if (isWslUncPath(opts.cwd ?? '')) {
|
||||
return false
|
||||
}
|
||||
if (/(?:^|[/\\])wsl(?:\.exe)?$/i.test(opts.shellOverride ?? '')) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Why module state (pattern of pty-hidden-delivery-gate.ts): pty.ts records
|
||||
// the determination at spawn, the runtime consults it at emulator creation.
|
||||
// Daemon-adopted PTYs from a previous app run carry no mark — acceptable:
|
||||
// ConPTY's blocking DA1 only fires at spawn, which happened in a prior life.
|
||||
const nativeWindowsConptyPtys = new Set<string>()
|
||||
|
||||
// Why installers: the mark lands after the awaited spawn response, but daemon
|
||||
// stream data (warm-reattach flush) can lazy-create the runtime emulator
|
||||
// first. The runtime registers an installer so marking retrofits the DA1
|
||||
// override onto an existing emulator; installation is idempotent emulator-side.
|
||||
type ConptyDa1OverrideInstaller = (ptyId: string) => void
|
||||
const conptyDa1OverrideInstallers = new Set<ConptyDa1OverrideInstaller>()
|
||||
|
||||
export function registerConptyDa1OverrideInstaller(installer: ConptyDa1OverrideInstaller): void {
|
||||
conptyDa1OverrideInstallers.add(installer)
|
||||
}
|
||||
|
||||
export function markNativeWindowsConptyPty(id: string): void {
|
||||
nativeWindowsConptyPtys.add(id)
|
||||
for (const installer of conptyDa1OverrideInstallers) {
|
||||
installer(id)
|
||||
}
|
||||
}
|
||||
|
||||
export function isNativeWindowsConptyPty(id: string): boolean {
|
||||
return nativeWindowsConptyPtys.has(id)
|
||||
}
|
||||
|
||||
/** Wired into clearProviderPtyState so every PTY teardown path releases the
|
||||
* spawn record. */
|
||||
export function clearNativeWindowsConptyPty(id: string): void {
|
||||
nativeWindowsConptyPtys.delete(id)
|
||||
}
|
||||
|
||||
/** Test seam: reset module state between tests. */
|
||||
export function _resetTerminalModelQueryAuthorityForTest(): void {
|
||||
nativeWindowsConptyPtys.clear()
|
||||
conptyDa1OverrideInstallers.clear()
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
/**
|
||||
* Phase 5 model query responder (docs/reference/terminal-query-authority.md):
|
||||
* reply parity through the runtime emulator, the per-chunk ownership matrix,
|
||||
* the main-side replay guard, and the ingestion-time capture race.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
import { HeadlessEmulator } from '../daemon/headless-emulator'
|
||||
import {
|
||||
_resetHiddenRendererPtyDeliveryGateForTest,
|
||||
markHiddenRendererPty,
|
||||
setRendererPtyDeliveryInterest,
|
||||
unmarkHiddenRendererPty
|
||||
} from '../ipc/pty-hidden-delivery-gate'
|
||||
import {
|
||||
_resetTerminalModelQueryAuthorityForTest,
|
||||
markNativeWindowsConptyPty
|
||||
} from './terminal-model-query-authority'
|
||||
|
||||
const settingsState = {
|
||||
terminalMainSideEffectAuthority: true as boolean,
|
||||
terminalHiddenDeliveryGate: true as boolean,
|
||||
terminalModelQueryAuthority: true as boolean
|
||||
}
|
||||
|
||||
const store = {
|
||||
getRepo: () => undefined,
|
||||
getRepos: () => [],
|
||||
addRepo: () => {},
|
||||
updateRepo: () => undefined as never,
|
||||
getAllWorktreeMeta: () => ({}),
|
||||
getWorktreeMeta: () => undefined,
|
||||
setWorktreeMeta: () => undefined as never,
|
||||
removeWorktreeMeta: () => {},
|
||||
getGitHubCache: () => ({ pr: {}, issue: {} }) as never,
|
||||
getSettings: () => ({
|
||||
workspaceDir: '/tmp/workspaces',
|
||||
nestWorkspaces: false,
|
||||
refreshLocalBaseRefOnWorktreeCreate: false,
|
||||
branchPrefix: 'none',
|
||||
branchPrefixCustom: '',
|
||||
terminalMainSideEffectAuthority: settingsState.terminalMainSideEffectAuthority,
|
||||
terminalHiddenDeliveryGate: settingsState.terminalHiddenDeliveryGate,
|
||||
terminalModelQueryAuthority: settingsState.terminalModelQueryAuthority
|
||||
})
|
||||
}
|
||||
|
||||
type RendererBufferStub = { data: string; cols: number; rows: number }
|
||||
|
||||
function createResponderRuntime(opts: { rendererBuffer?: RendererBufferStub } = {}) {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
const replies: { ptyId: string; data: string }[] = []
|
||||
runtime.setPtyController({
|
||||
write: (ptyId, data) => {
|
||||
replies.push({ ptyId, data })
|
||||
return true
|
||||
},
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null,
|
||||
getSize: () => ({ cols: 80, rows: 24 }),
|
||||
resize: () => true,
|
||||
...(opts.rendererBuffer
|
||||
? {
|
||||
hasRendererSerializer: () => true,
|
||||
serializeBuffer: async () => opts.rendererBuffer ?? null
|
||||
}
|
||||
: {})
|
||||
})
|
||||
return { runtime, replies }
|
||||
}
|
||||
|
||||
/** Awaits the per-PTY emulator writeChain so queued chunk links (and the
|
||||
* replies they forward) have settled. */
|
||||
async function settle(runtime: OrcaRuntimeService, ptyId: string): Promise<void> {
|
||||
await runtime.serializeMainTerminalBuffer(ptyId)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
_resetHiddenRendererPtyDeliveryGateForTest()
|
||||
_resetTerminalModelQueryAuthorityForTest()
|
||||
settingsState.terminalMainSideEffectAuthority = true
|
||||
settingsState.terminalHiddenDeliveryGate = true
|
||||
settingsState.terminalModelQueryAuthority = true
|
||||
})
|
||||
|
||||
describe('reply parity for hidden-dropped chunks', () => {
|
||||
// Expected replies pinned from the design doc and verified against the
|
||||
// bundled @xterm/headless build — the same core the renderer runs, so
|
||||
// parity is structural for static and model-state classes.
|
||||
it.each([
|
||||
['DA1 CSI c', '\x1b[c', ['\x1b[?1;2c']],
|
||||
['DA1 CSI 0 c variant', '\x1b[0c', ['\x1b[?1;2c']],
|
||||
['DA2', '\x1b[>c', ['\x1b[>0;276;0c']],
|
||||
['DSR 5n operating status', '\x1b[5n', ['\x1b[0n']],
|
||||
['CPR 6n at origin', '\x1b[6n', ['\x1b[1;1R']],
|
||||
['CPR 6n reports the model cursor position', 'hello\r\nworld\x1b[6n', ['\x1b[2;6R']],
|
||||
['DECXCPR ?6n', '\x1b[?6n', ['\x1b[?1;1R']],
|
||||
['DECRPM ?1 DECCKM default', '\x1b[?1$p', ['\x1b[?1;2$y']],
|
||||
['DECRPM ?6 DECOM default', '\x1b[?6$p', ['\x1b[?6;2$y']],
|
||||
['DECRPM ?7 DECAWM default', '\x1b[?7$p', ['\x1b[?7;1$y']],
|
||||
['DECRPM ?25 DECTCEM default', '\x1b[?25$p', ['\x1b[?25;1$y']],
|
||||
['DECRPM ?1004 focus events default', '\x1b[?1004$p', ['\x1b[?1004;2$y']],
|
||||
['DECRPM ?1006 SGR mouse default', '\x1b[?1006$p', ['\x1b[?1006;2$y']],
|
||||
['DECRPM ?1016 SGR pixels default', '\x1b[?1016$p', ['\x1b[?1016;2$y']],
|
||||
['DECRPM ?1049 alt screen default', '\x1b[?1049$p', ['\x1b[?1049;2$y']],
|
||||
['DECRPM ?2004 bracketed paste default', '\x1b[?2004$p', ['\x1b[?2004;2$y']],
|
||||
['DECRPM ?2026 synchronized output default', '\x1b[?2026$p', ['\x1b[?2026;2$y']],
|
||||
['DECRPM reports a set mode as enabled', '\x1b[?2004h\x1b[?2004$p', ['\x1b[?2004;1$y']],
|
||||
['DECRPM unknown mode reports 0', '\x1b[?12345$p', ['\x1b[?12345;0$y']],
|
||||
['DECRQM ANSI insert mode', '\x1b[4$p', ['\x1b[4;2$y']],
|
||||
['DECRQSS DECSTBM default margins', '\x1bP$qr\x1b\\', ['\x1bP1$r1;24r\x1b\\']],
|
||||
['DECRQSS DECSTBM after margin set', '\x1b[5;20r\x1bP$qr\x1b\\', ['\x1bP1$r5;20r\x1b\\']],
|
||||
['DECRQSS DECSCUSR default cursor', '\x1bP$q q\x1b\\', ['\x1bP1$r2 q\x1b\\']],
|
||||
['DECRQSS DECSCA', '\x1bP$q"q\x1b\\', ['\x1bP1$r0"q\x1b\\']],
|
||||
['DECRQSS SGR', '\x1bP$qm\x1b\\', ['\x1bP1$r0m\x1b\\']],
|
||||
['XTVERSION', '\x1b[>0q', ['\x1bP>|xterm.js(6.0.0)\x1b\\']],
|
||||
['kitty CSI ? u default flags', '\x1b[?u', ['\x1b[?0u']],
|
||||
['kitty CSI ? u reports pushed flags', '\x1b[=5;1u\x1b[?u', ['\x1b[?5u']]
|
||||
])('%s', async (_label, chunk, expectedReplies) => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-q')
|
||||
|
||||
runtime.onPtyData('pty-q', chunk, Date.now())
|
||||
await settle(runtime, 'pty-q')
|
||||
|
||||
expect(replies.map((reply) => reply.data)).toEqual(expectedReplies)
|
||||
expect(replies.every((reply) => reply.ptyId === 'pty-q')).toBe(true)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['XTWINOPS', '\x1b[14t'],
|
||||
['XTGETTCAP', '\x1bP+q544e\x1b\\'],
|
||||
['DSR ?15n printer status', '\x1b[?15n'],
|
||||
['DSR ?25n UDK status', '\x1b[?25n'],
|
||||
['DSR ?26n keyboard status', '\x1b[?26n'],
|
||||
['DSR ?53n locator status', '\x1b[?53n'],
|
||||
// View-attribute class: silent until the slice-2 renderer attribute push
|
||||
// — a fabricated default would resurrect the default-black OSC-11 bug.
|
||||
['OSC 10 foreground query', '\x1b]10;?\x07'],
|
||||
['OSC 11 background query', '\x1b]11;?\x07'],
|
||||
['OSC 12 cursor-color query', '\x1b]12;?\x1b\\'],
|
||||
['OSC 4 palette query', '\x1b]4;1;?\x07'],
|
||||
['DSR ?996n color-scheme query', '\x1b[?996n']
|
||||
])('stays silent for %s', async (_label, chunk) => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-q')
|
||||
|
||||
runtime.onPtyData('pty-q', chunk, Date.now())
|
||||
await settle(runtime, 'pty-q')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('reply ownership matrix', () => {
|
||||
const DA1 = '\x1b[c'
|
||||
|
||||
it('never answers delivered (unmarked) chunks — the visible xterm owns them', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
|
||||
runtime.onPtyData('pty-v', DA1, Date.now())
|
||||
await settle(runtime, 'pty-v')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
|
||||
it('never answers while renderer delivery interest holds the chunk delivered', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-i')
|
||||
setRendererPtyDeliveryInterest('pty-i', true)
|
||||
|
||||
runtime.onPtyData('pty-i', DA1, Date.now())
|
||||
await settle(runtime, 'pty-i')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['terminalModelQueryAuthority', () => (settingsState.terminalModelQueryAuthority = false)],
|
||||
['terminalHiddenDeliveryGate', () => (settingsState.terminalHiddenDeliveryGate = false)],
|
||||
[
|
||||
'terminalMainSideEffectAuthority',
|
||||
() => (settingsState.terminalMainSideEffectAuthority = false)
|
||||
]
|
||||
])('never answers with kill switch %s off', async (_label, flip) => {
|
||||
flip()
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-k')
|
||||
|
||||
runtime.onPtyData('pty-k', DA1, Date.now())
|
||||
await settle(runtime, 'pty-k')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
|
||||
it('yields while a remote view subscriber is attached and resumes on release', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-r')
|
||||
const release = runtime.registerRemoteTerminalViewSubscriber('pty-r')
|
||||
|
||||
runtime.onPtyData('pty-r', DA1, Date.now())
|
||||
await settle(runtime, 'pty-r')
|
||||
expect(replies).toEqual([])
|
||||
|
||||
release()
|
||||
// Releases are idempotent: a double release must not unbalance the count.
|
||||
release()
|
||||
runtime.onPtyData('pty-r', DA1, Date.now())
|
||||
await settle(runtime, 'pty-r')
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c'])
|
||||
})
|
||||
|
||||
it('counts overlapping remote view subscribers', () => {
|
||||
const { runtime } = createResponderRuntime()
|
||||
const releaseA = runtime.registerRemoteTerminalViewSubscriber('pty-m')
|
||||
const releaseB = runtime.registerRemoteTerminalViewSubscriber('pty-m')
|
||||
expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(true)
|
||||
releaseA()
|
||||
expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(true)
|
||||
releaseB()
|
||||
expect(runtime.hasRemoteTerminalViewSubscriber('pty-m')).toBe(false)
|
||||
})
|
||||
|
||||
it('treats mobile subscriber records as remote view subscribers', async () => {
|
||||
const { runtime } = createResponderRuntime()
|
||||
await runtime.handleMobileSubscribe('pty-mob', 'client-1', { cols: 40, rows: 20 })
|
||||
expect(runtime.hasRemoteTerminalViewSubscriber('pty-mob')).toBe(true)
|
||||
})
|
||||
|
||||
it('answers a dropped-chunk query exactly once', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-once')
|
||||
|
||||
runtime.onPtyData('pty-once', DA1, Date.now())
|
||||
await settle(runtime, 'pty-once')
|
||||
|
||||
expect(replies).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('main-side replay guard', () => {
|
||||
const DA1 = '\x1b[c'
|
||||
|
||||
it('never answers queries embedded in a seeded snapshot, then answers live bytes', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-seed')
|
||||
|
||||
runtime.seedHeadlessTerminal('pty-seed', `restored prompt${DA1}`)
|
||||
await settle(runtime, 'pty-seed')
|
||||
expect(replies).toEqual([])
|
||||
|
||||
runtime.onPtyData('pty-seed', DA1, Date.now())
|
||||
await settle(runtime, 'pty-seed')
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c'])
|
||||
})
|
||||
|
||||
it('never answers queries replayed by renderer-buffer hydration', async () => {
|
||||
const { runtime, replies } = createResponderRuntime({
|
||||
rendererBuffer: { data: `restored screen${DA1}`, cols: 80, rows: 24 }
|
||||
})
|
||||
markHiddenRendererPty('pty-hyd')
|
||||
|
||||
// First live byte triggers maybeHydrateHeadlessFromRenderer; the hydration
|
||||
// seed parses the embedded DA1 but must not forward its reply.
|
||||
runtime.onPtyData('pty-hyd', 'live output', Date.now())
|
||||
await settle(runtime, 'pty-hyd')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ingestion-time ownership capture', () => {
|
||||
const DA1 = '\x1b[c'
|
||||
|
||||
it('still answers when the hidden mark flips off between ingestion and the async write', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-race')
|
||||
|
||||
runtime.onPtyData('pty-race', DA1, Date.now())
|
||||
// Flip before the queued writeChain link runs: the captured decision wins.
|
||||
unmarkHiddenRendererPty('pty-race')
|
||||
await settle(runtime, 'pty-race')
|
||||
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?1;2c'])
|
||||
})
|
||||
|
||||
it('stays silent when the hidden mark lands after ingestion', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
|
||||
runtime.onPtyData('pty-race2', DA1, Date.now())
|
||||
markHiddenRendererPty('pty-race2')
|
||||
await settle(runtime, 'pty-race2')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('stale writeChain links after dispose', () => {
|
||||
const DA1 = '\x1b[c'
|
||||
|
||||
it('never forwards a queued reply once the PTY state is disposed', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-stale')
|
||||
|
||||
// Queue a forward-flagged chain link, then dispose before it runs.
|
||||
runtime.onPtyData('pty-stale', DA1, Date.now())
|
||||
runtime.onPtyExit('pty-stale', 0)
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
|
||||
it('never injects a stale reply into a successor PTY reusing the session id', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-reuse')
|
||||
|
||||
// Daemon respawns reuse session ids: dispose with the flagged link still
|
||||
// queued, then re-create the same id before the link runs.
|
||||
runtime.onPtyData('pty-reuse', DA1, Date.now())
|
||||
runtime.onPtyExit('pty-reuse', 0)
|
||||
runtime.onPtyData('pty-reuse', 'fresh shell banner', Date.now())
|
||||
await settle(runtime, 'pty-reuse')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ConPTY DA1 override', () => {
|
||||
it('retrofits the override when the spawn mark lands after data created the emulator', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markHiddenRendererPty('pty-win-late')
|
||||
|
||||
// Daemon warm-reattach flush: stream data creates the emulator before
|
||||
// the awaited spawn response marks the PTY native-Windows.
|
||||
runtime.onPtyData('pty-win-late', 'warm reattach flush', Date.now())
|
||||
markNativeWindowsConptyPty('pty-win-late')
|
||||
|
||||
runtime.onPtyData('pty-win-late', '\x1b[c', Date.now())
|
||||
await settle(runtime, 'pty-win-late')
|
||||
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?61;4c'])
|
||||
})
|
||||
|
||||
it('keeps the override single-reply when installed at creation and marked again', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markNativeWindowsConptyPty('pty-win-idem')
|
||||
markHiddenRendererPty('pty-win-idem')
|
||||
|
||||
runtime.onPtyData('pty-win-idem', 'boot output', Date.now())
|
||||
// A duplicate mark (e.g. respawn against a live emulator) must not stack
|
||||
// a second handler that double-replies.
|
||||
markNativeWindowsConptyPty('pty-win-idem')
|
||||
|
||||
runtime.onPtyData('pty-win-idem', '\x1b[c', Date.now())
|
||||
await settle(runtime, 'pty-win-idem')
|
||||
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?61;4c'])
|
||||
})
|
||||
|
||||
it('answers CSI ?61;4c for marked native-Windows PTYs, suppressing the core ?1;2c', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markNativeWindowsConptyPty('pty-win')
|
||||
markHiddenRendererPty('pty-win')
|
||||
|
||||
runtime.onPtyData('pty-win', '\x1b[c', Date.now())
|
||||
await settle(runtime, 'pty-win')
|
||||
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[?61;4c'])
|
||||
})
|
||||
|
||||
it('lets non-primary device-attribute queries fall through to the core', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markNativeWindowsConptyPty('pty-win2')
|
||||
markHiddenRendererPty('pty-win2')
|
||||
|
||||
runtime.onPtyData('pty-win2', '\x1b[>c', Date.now())
|
||||
await settle(runtime, 'pty-win2')
|
||||
|
||||
expect(replies.map((reply) => reply.data)).toEqual(['\x1b[>0;276;0c'])
|
||||
})
|
||||
|
||||
it('keeps the override silent for delivered chunks', async () => {
|
||||
const { runtime, replies } = createResponderRuntime()
|
||||
markNativeWindowsConptyPty('pty-win3')
|
||||
|
||||
runtime.onPtyData('pty-win3', '\x1b[c', Date.now())
|
||||
await settle(runtime, 'pty-win3')
|
||||
|
||||
expect(replies).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('HeadlessEmulator forwarding window', () => {
|
||||
it('forwards replies only for writes flagged forwardQueryReplies', async () => {
|
||||
const onQueryReply = vi.fn()
|
||||
const emulator = new HeadlessEmulator({ cols: 80, rows: 24, onQueryReply })
|
||||
try {
|
||||
await emulator.write('\x1b[c')
|
||||
expect(onQueryReply).not.toHaveBeenCalled()
|
||||
|
||||
await emulator.write('\x1b[c', { forwardQueryReplies: true })
|
||||
expect(onQueryReply).toHaveBeenCalledTimes(1)
|
||||
expect(onQueryReply).toHaveBeenCalledWith('\x1b[?1;2c')
|
||||
} finally {
|
||||
emulator.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('scopes the async-fallback forwarding window to the flagged chunk parse', async () => {
|
||||
const onQueryReply = vi.fn()
|
||||
const emulator = new HeadlessEmulator({ cols: 80, rows: 24, onQueryReply })
|
||||
// Force the async write path (xterm deprecates writeSync; the fallback
|
||||
// must stay structurally safe without writeChain serialization).
|
||||
const internals = emulator as unknown as { terminal: { _core: { writeSync?: unknown } } }
|
||||
internals.terminal._core.writeSync = undefined
|
||||
try {
|
||||
// Enqueue an unflagged seed carrying a query, then a flagged live
|
||||
// chunk, WITHOUT awaiting between them: both sit in xterm's write
|
||||
// queue together. The seed parse must not see an open window.
|
||||
const seed = emulator.write('seeded\x1b[c')
|
||||
const live = emulator.write('\x1b[5n', { forwardQueryReplies: true })
|
||||
await Promise.all([seed, live])
|
||||
|
||||
expect(onQueryReply.mock.calls.map((call) => call[0])).toEqual(['\x1b[0n'])
|
||||
} finally {
|
||||
emulator.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the ConPTY override inside the forwarding window', async () => {
|
||||
const onQueryReply = vi.fn()
|
||||
const emulator = new HeadlessEmulator({ cols: 80, rows: 24, onQueryReply })
|
||||
emulator.installConptyPrimaryDeviceAttributesOverride()
|
||||
try {
|
||||
// Unflagged (replayed/seeded) DA1 must answer no one even with the
|
||||
// override installed.
|
||||
await emulator.write('\x1b[c')
|
||||
expect(onQueryReply).not.toHaveBeenCalled()
|
||||
|
||||
await emulator.write('\x1b[c', { forwardQueryReplies: true })
|
||||
expect(onQueryReply).toHaveBeenCalledTimes(1)
|
||||
expect(onQueryReply).toHaveBeenCalledWith('\x1b[?61;4c')
|
||||
} finally {
|
||||
emulator.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -47,7 +47,10 @@ import {
|
||||
waitForTerminalOutputParsed,
|
||||
writeTerminalOutput
|
||||
} from '@/lib/pane-manager/pane-terminal-output-scheduler'
|
||||
import { isLocalNativeWindowsPty } from '@/lib/pane-manager/windows-pty-compatibility'
|
||||
import {
|
||||
isLocalNativeWindowsPty,
|
||||
resolveWindowsShellOverride
|
||||
} from '@/lib/pane-manager/windows-pty-compatibility'
|
||||
import { recordTerminalOutput, restoreScrollStateAfterLayout } from '@/lib/pane-manager/pane-scroll'
|
||||
import type { ScrollState } from '@/lib/pane-manager/pane-manager-types'
|
||||
import { makePaneKey } from '../../../../shared/stable-pane-id'
|
||||
@@ -1511,7 +1514,10 @@ export function connectPanePty(
|
||||
userAgent: navigator.userAgent,
|
||||
connectionId,
|
||||
cwd: deps.cwd,
|
||||
shellOverride
|
||||
// Why: main folds the global Windows shell into its spawn classification
|
||||
// (pty.ts effectiveShellOverride); fold it here too so both sides treat
|
||||
// a global-WSL default identically (terminal-query-authority.md ConPTY).
|
||||
shellOverride: resolveWindowsShellOverride(shellOverride, state.settings?.terminalWindowsShell)
|
||||
})
|
||||
const shouldApplyNativeWindowsRewriteRefresh = isNativeWindowsConpty
|
||||
const shouldProtectNativeWindowsSynchronizedOutput = isNativeWindowsConpty
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildWindowsPtyCompatibilityOptions,
|
||||
isLocalNativeWindowsPty
|
||||
isLocalNativeWindowsPty,
|
||||
resolveWindowsShellOverride
|
||||
} from './windows-pty-compatibility'
|
||||
|
||||
describe('buildWindowsPtyCompatibilityOptions', () => {
|
||||
@@ -88,6 +89,39 @@ describe('buildWindowsPtyCompatibilityOptions', () => {
|
||||
).toEqual({})
|
||||
})
|
||||
|
||||
it('classifies a global-WSL default shell as non-native, matching main', () => {
|
||||
// Why: main folds the global terminalWindowsShell into its spawn
|
||||
// classification (isNativeWindowsLocalPtySpawn). Without the fold the
|
||||
// renderer would call a tab with no override native-ConPTY while main
|
||||
// never marks it.
|
||||
const windowsUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
|
||||
expect(
|
||||
isLocalNativeWindowsPty({
|
||||
userAgent: windowsUserAgent,
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: resolveWindowsShellOverride(undefined, 'wsl.exe')
|
||||
})
|
||||
).toBe(false)
|
||||
// A tab-level override beats the global setting, both directions.
|
||||
expect(
|
||||
isLocalNativeWindowsPty({
|
||||
userAgent: windowsUserAgent,
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: resolveWindowsShellOverride('powershell.exe', 'wsl.exe')
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isLocalNativeWindowsPty({
|
||||
userAgent: windowsUserAgent,
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: resolveWindowsShellOverride('wsl.exe', 'powershell.exe')
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('exposes the same local native Windows predicate for related renderer workarounds', () => {
|
||||
expect(
|
||||
isLocalNativeWindowsPty({
|
||||
|
||||
@@ -45,6 +45,17 @@ export function buildWindowsPtyCompatibilityOptions(
|
||||
}
|
||||
}
|
||||
|
||||
/** Mirror of main's effectiveShellOverride fold (pty.ts spawn handlers): a
|
||||
* tab-level shell override wins, else the global Windows shell setting
|
||||
* applies — so renderer and main classify a global-WSL default identically
|
||||
* (the main-side twin is isNativeWindowsLocalPtySpawn). */
|
||||
export function resolveWindowsShellOverride(
|
||||
tabShellOverride: string | null | undefined,
|
||||
globalWindowsShell: string | null | undefined
|
||||
): string | undefined {
|
||||
return tabShellOverride ?? globalWindowsShell ?? undefined
|
||||
}
|
||||
|
||||
export function isLocalNativeWindowsPty(context: WindowsPtyCompatibilityContext): boolean {
|
||||
if (!isWindowsUserAgent(context.userAgent)) {
|
||||
return false
|
||||
|
||||
@@ -276,6 +276,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
|
||||
terminalHiddenViewParking: true,
|
||||
terminalMainSideEffectAuthority: true,
|
||||
terminalHiddenDeliveryGate: true,
|
||||
terminalModelQueryAuthority: true,
|
||||
defaultTuiAgent: null,
|
||||
disabledTuiAgents: [...DEFAULT_DISABLED_TUI_AGENTS],
|
||||
claudeAgentTeamsDefaultDisabledMigrated: true,
|
||||
|
||||
@@ -2207,6 +2207,12 @@ export type GlobalSettings = {
|
||||
* delivery to hidden renderer views after model ingestion; reveal restores
|
||||
* from the model snapshot. `false` restores hidden byte delivery. */
|
||||
terminalHiddenDeliveryGate?: boolean
|
||||
/** Kill switch for the main model query responder (Phase 5): when true
|
||||
* (default) AND both Phase-4 gate switches are on, main answers terminal
|
||||
* queries (DA1/CPR/DECRPM, …) embedded in hidden-dropped chunks from the
|
||||
* runtime emulator. `false` silences the responder without changing drops.
|
||||
* See docs/reference/terminal-query-authority.md. */
|
||||
terminalModelQueryAuthority?: boolean
|
||||
/** Which agent to pre-select in the new-workspace composer.
|
||||
* - null: auto (first detected agent)
|
||||
* - 'blank': blank terminal (no agent launched)
|
||||
|
||||
Reference in New Issue
Block a user