The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Windows terminal host updates itself and takes over unnoticed (PTY rollover and delivery) (#1503)
0xken15151f8bb7cf61
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex d1a12504f..c99679691 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -83,6 +83,30 @@ jobs:if: ${{ !inputs.release }}working-directory: ptyrun: cargo test --locked --target ${{ matrix.target }}+ # The previous version of the host, for the specs of two real builds (the rollover, sub-project G): the same source+ # stamped older, built into the same target first and copied aside, with the ConPTY payload it loads from its own+ # folder. The release build below changes HARNESS_PTY_VERSION, which recompiles only the crate.+ - name: Build the previous host+ if: ${{ !inputs.release }}+ working-directory: pty+ shell: pwsh+ env:+ HARNESS_PTY_VERSION: '0.0.1'+ run: |+ cargo build --locked --release --target ${{ matrix.target }} --bin harness-pty+ if ($LASTEXITCODE -ne 0) { throw "cargo build exited $LASTEXITCODE" }+ $previous = "target/${{ matrix.target }}/previous"+ New-Item -ItemType Directory -Force $previous | Out-Null+ Copy-Item "target/${{ matrix.target }}/release/harness-pty.exe", "vendor/conpty/${{ matrix.arch }}/conpty.dll", "vendor/conpty/${{ matrix.arch }}/OpenConsole.exe" $previous+ & "$previous/harness-pty.exe" version+ # The Rust side of the two builds: both hosts serve one home side by side, each with its own discovery file+ # (pty/tests/control.rs). Set, HARNESS_PTY_BIN_OLD must name a file, or the test fails rather than skips.+ - name: 'Rust: two versions side by side'+ if: ${{ !inputs.release }}+ working-directory: pty+ env:+ HARNESS_PTY_BIN_OLD: ${{ github.workspace }}\pty\target\${{ matrix.target }}\previous\harness-pty.exe+ run: cargo test --locked --target ${{ matrix.target }} --test control two_versions_serve_side_by_side -- --nocapture# harness-serial (serial/, sub-project E): the dial's serial port. Tested on each architecture.- name: 'Serial: Rust tests'if: ${{ !inputs.release }}@@ -141,13 +165,26 @@ jobs:env:RUN_TERMINAL_CONTRACT: "1"HARNESS_PTY_BIN: ${{ github.workspace }}\pty\target\${{ matrix.target }}\release\harness-pty.exe- # installPs1.spec.ts runs the real harness.exe; a --target build is not where it looks by default.- HARNESS_EXE_BIN: ${{ github.workspace }}\pty\target\${{ matrix.target }}\release\harness.exe# serialWindows.spec.ts runs the real harness-serial.exe, placed beside the host by the payload step.HARNESS_SERIAL_BIN: ${{ github.workspace }}\pty\target\${{ matrix.target }}\release\harness-serial.exerun: |- $paths = @('src/lib/ptyHostBackend.contract.spec.ts', 'src/lib/ptyHost', 'src/lib/windows', 'src/scripts/installPs1.spec.ts', 'src/scripts/windowsCiChecks.spec.ts', 'src/lib/uninstall', 'src/engines/kit/hookRemoval.spec.ts', 'src/engines/kit/windowsHooks.spec.ts', 'src/engines/kit/windowsFiles.spec.ts', 'src/engines/kit/nativePaths.windows.spec.ts', 'src/engines/kit/launchExecutable.windows.spec.ts', 'src/engines/removeHooks.spec.ts', 'src/engines/windowsHomes.spec.ts', 'src/cable/windowsSerial.spec.ts', 'src/cable/serialWindows.spec.ts')+ $paths = @('src/lib/ptyHostBackend.contract.spec.ts', 'src/lib/ptyHost', 'src/lib/windows', 'src/scripts/windowsCiChecks.spec.ts', 'src/lib/uninstall', 'src/engines/kit/hookRemoval.spec.ts', 'src/engines/kit/windowsHooks.spec.ts', 'src/engines/kit/windowsFiles.spec.ts', 'src/engines/kit/nativePaths.windows.spec.ts', 'src/engines/kit/launchExecutable.windows.spec.ts', 'src/engines/removeHooks.spec.ts', 'src/engines/windowsHomes.spec.ts', 'src/cable/windowsSerial.spec.ts', 'src/cable/serialWindows.spec.ts')npx vitest run @paths --maxWorkers=1+ # Two real builds (sub-project G): the rollover from the previous host to this one (hostMove.real.spec.ts, and+ # drain.spec.ts's two-build case), and the payload install (the bin\ replacement, and install.ps1 in Windows+ # PowerShell 5.1). Verbose, so the log names each case that ran.+ - name: 'Two real builds: the pty host rollover and the payload install'+ if: ${{ !inputs.release }}+ working-directory: cli+ shell: pwsh+ env:+ HARNESS_PTY_BIN: ${{ github.workspace }}\pty\target\${{ matrix.target }}\release\harness-pty.exe+ HARNESS_PTY_BIN_PREV: ${{ github.workspace }}\pty\target\${{ matrix.target }}\previous\harness-pty.exe+ # installPs1.spec.ts runs the real harness.exe; a --target build is not where it looks by default.+ HARNESS_EXE_BIN: ${{ github.workspace }}\pty\target\${{ matrix.target }}\release\harness.exe+ run: |+ $paths = @('src/lib/hostMove/hostMove.real.spec.ts', 'src/lib/ptyHost/drain.spec.ts', 'src/lib/windows/ptyInstall.windows.real.spec.ts', 'src/scripts/installPs1.spec.ts')+ npx vitest run @paths --maxWorkers=1 --reporter=verbose- name: Collect the payloadshell: pwshrun: |@@ -312,7 +349,7 @@ jobs:run: |# Each tree under its own path below logs\ (the same file name is in more than one), as it is under the profile:# the master's and the core's cli\data\harness.log, harness-launch.exe's cli\data\logs\launch.log, the terminal- # host's pty\logs\pty-host.log, the dial's logs\dial-*.log. Every path starts with a dot, which upload-artifact+ # host's pty\logs\pty-host-<instance>.log, the dial's logs\dial-*.log. Every path starts with a dot, which upload-artifact# takes for hidden and leaves out unless include-hidden-files says otherwise: run 39083518767 uploaded nothing.# Each file copied is named here, so the job's own output says what the artifact holds.$logs = "$env:RUNNER_TEMP\logs"diff --git a/cli/README.md b/cli/README.mdindex e18dbd701..3af6c3f22 100644--- a/cli/README.md+++ b/cli/README.md@@ -224,7 +224,7 @@ claude under a terminal backend ──writes──▶ ~/.claude/projects/**.json- **Two backends: `tmux` and `ptyhost`.** tmux is the backend on macOS and Linux. `ptyhost` is theHarness PTY host (`pty/`, `harness-pty`), a long-lived process of its own with a ConPTY per pane: thebackend on Windows, and buildable on Unix for its tests. Its home is `HARNESS_PTY_DIR`- (`~/.harness/pty`), with its discovery file in `run/` and its log in `logs/pty-host.log`;+ (`~/.harness/pty`), with its discovery file in `run/` and its log in `logs/pty-host-<instance>.log` (one per host build);`HARNESS_PTY_BIN` overrides the host binary. The retired Herdr backend has been removed.`TERMINAL_BACKENDS=herdr` is not an error — it is dropped with a warning and the daemon runs on theplatform's default, because the CLI self-updates and a retired setting must not stop an unattendeddiff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex aab584fa4..864ca4b79 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -446,10 +446,11 @@ function readWindowsHookCredential(dataDir, file) {/*** A Harness pty host pane names itself `HARNESS_PANE=<instance>:%N` (pty/src/panes.rs), as a tmux pane has* `TMUX_PANE`. It is read only when there is no TMUX_PANE: a tmux pane inside a pty host pane is still the tmux pane.+ * The instance is `p<protocol>` or `p<protocol>-<build>`, as cli/src/lib/ptyHost/instance.ts `PTY_HOST_INSTANCE`.*/function ptyHostPane(environment = process.env) {if (environment.TMUX_PANE) return null- const match = /^(p\d{1,4}):(%\d{1,9})$/.exec(environment.HARNESS_PANE || '')+ const match = /^(p\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\d{1,9})$/.exec(environment.HARNESS_PANE || '')return match ? { instance: match[1], paneId: match[2] } : null}const PTY_PANE = ptyHostPane()diff --git a/cli/scripts/install.ps1 b/cli/scripts/install.ps1index 67e3a8f73..e6eadee49 100644--- a/cli/scripts/install.ps1+++ b/cli/scripts/install.ps1@@ -399,7 +399,13 @@ function Install-HarnessPty {Move-Item -LiteralPath $unpacked -Destination $target} finally { Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue }}- Write-HarnessPointer -Path (Join-Path $ptyRoot 'current-pty') -Value $version+ $pointer = Join-Path $ptyRoot 'current-pty'+ $before = ''+ if (Test-Path -LiteralPath $pointer -PathType Leaf) { $before = ([string](Get-Content -LiteralPath $pointer -TotalCount 1)).Trim() }+ Write-HarnessPointer -Path $pointer -Value $version+ # An explicit install supersedes a host the updater put on probation: left, its marker would let the next probation+ # roll this install back to the version before it (pty-pending.json, cli/src/lib/windows/ptyInstall.ts).+ if ($before -ne $version) { Remove-Item -LiteralPath (Join-Path $ptyRoot 'pty-pending.json') -Force -ErrorAction SilentlyContinue }$bin = Join-Path $Root 'bin'New-Item -ItemType Directory -Force -Path $bin | Out-NullCopy-HarnessFile -Source (Join-Path $target 'harness-launch.exe') -Destination (Join-Path $bin 'harness-launch.exe')@@ -518,20 +524,41 @@ function Read-HarnessCurrentCli {return ([string](Get-Content -LiteralPath $pointer -TotalCount 1)).Trim()}+function Read-HarnessCurrentPty {+ # The version runtime\pty\current-pty names, or '' before a first install. Read before the payload install moves+ # it, so Restart-HarnessDaemon can tell that only the terminal host changed.+ param([string]$Root)+ $pointer = Join-Path $Root 'runtime\pty\current-pty'+ if (-not (Test-Path -LiteralPath $pointer -PathType Leaf)) { return '' }+ return ([string](Get-Content -LiteralPath $pointer -TotalCount 1)).Trim()+}+function Restart-HarnessDaemon {# Run again over a live install, the installer moves the daemon to the new build. The master re-execs only before# a core starts, and nothing tells it that cli\current moved, so the daemon is restarted once: harness stop, then# harness start. Agents keep running: the terminal host is independent of the daemon, and the new core reattaches- # them. Nothing happens on the same version, on a first install, or when no daemon runs.- param([string]$Command, [string]$Before, [string]$After)- if (-not $Before -or $Before -eq $After) { return $false }+ # them. It also restarts when only the terminal host moved: a daemon holds on to the host it started with, so a new+ # host is used only after a restart. Nothing happens when neither version changed, on a first install, or when no+ # daemon runs. An explicit install installs: pty-rejected.json is the updater's back-off and is not read here.+ param([string]$Command, [string]$Before, [string]$After, [string]$PtyBefore, [string]$PtyAfter)+ $cliMoved = $Before -and $Before -ne $After+ $ptyMoved = $PtyBefore -and $PtyBefore -ne $PtyAfter+ if (-not $cliMoved -and -not $ptyMoved) { return $false }$statusLine = @(& $Command status) | Where-Object { $_ -match '^\s*status\s' } | Select-Object -First 1if ($LASTEXITCODE -ne 0 -or -not $statusLine -or $statusLine -match 'stopped|out of reach') { return $false }- Write-Host " Moving the running Harness from $Before to $After (your agents keep running)..."+ if ($cliMoved) {+ Write-Host " Moving the running Harness from $Before to $After (your agents keep running)..."+ } else {+ Write-Host " Moving the running Harness to terminal host $PtyAfter (your agents keep running)..."+ }& $Command stop | ForEach-Object { Write-Host " $_" }# A daemon that did not stop is still on the old build: nothing is started beside it, and no move is reported.if ($LASTEXITCODE -ne 0) {- Write-Host " Harness is still running version $Before; it moves to $After when it next restarts (harness stop, then harness start)."+ if ($cliMoved) {+ Write-Host " Harness is still running version $Before; it moves to $After when it next restarts (harness stop, then harness start)."+ } else {+ Write-Host " Harness is still running on terminal host $PtyBefore; it moves to $PtyAfter when it next restarts (harness stop, then harness start)."+ }return $false}# Not piped, and not left as the function's output (which a caller's `$null =` would capture through a pipe too):@@ -541,7 +568,10 @@ function Restart-HarnessDaemon {$start = Start-Process -FilePath $Command -ArgumentList 'start' -NoNewWindow -PassThru$null = $start.Handle$start.WaitForExit()- if ($start.ExitCode -ne 0) { Write-Host " Harness did not start again on version ${After}. Run 'harness start'." }+ if ($start.ExitCode -ne 0) {+ if ($cliMoved) { Write-Host " Harness did not start again on version ${After}. Run 'harness start'." }+ else { Write-Host " Harness did not start again on terminal host ${PtyAfter}. Run 'harness start'." }+ }return $true}@@ -567,11 +597,13 @@ function Install-Harness {$step = 'Installing the Harness CLI'# The version a running daemon may be on, read before the pointer moves (Restart-HarnessDaemon below).$before = Read-HarnessCurrentCli -Root $root+ $ptyBefore = Read-HarnessCurrentPty -Root $root$version = Install-HarnessCli -Root $root -Entry $sources.cli.entry -Source $sources.cli.source# The terminal host is installed in -Desktop mode too: the daemon the app starts runs its terminals on it.$step = 'Installing the terminal host'$ptyFolder = Install-HarnessPty -Root $root -Entry $sources.pty.entry -Source $sources.pty.source -Tar $tar$step = 'Installing the harness command'+ $ptyAfter = Split-Path -Leaf $ptyFolder$command = Install-HarnessCommand -Root $root -PtyFolder $ptyFolder$step = 'Adding Harness to your PATH'Add-HarnessPath -Root $root@@ -580,7 +612,7 @@ function Install-Harness {if ($LASTEXITCODE -ne 0 -or $said.Trim() -ne $version) { throw "harness version answered '$said' (exit code $LASTEXITCODE), not $version." }$step = 'Moving the running Harness to the new build'# $null: Install-Harness returns a single integer (the guard takes the last value).- $null = Restart-HarnessDaemon -Command $command -Before $before -After $version+ $null = Restart-HarnessDaemon -Command $command -Before $before -After $version -PtyBefore $ptyBefore -PtyAfter $ptyAfterif (-not $Desktop -and -not $NoService) {$step = 'Starting Harness when you sign in'Register-HarnessService -Command $commanddiff --git a/cli/scripts/windows-ci/check-install.ps1 b/cli/scripts/windows-ci/check-install.ps1index 310807a7d..4badea9fb 100644--- a/cli/scripts/windows-ci/check-install.ps1+++ b/cli/scripts/windows-ci/check-install.ps1@@ -44,7 +44,7 @@ function Show-Diagnosis {catch { Write-Host "$($found.Name): $($_.Exception.Message)" }}# The master and the core write cli\data\harness.log, harness-launch.exe cli\data\logs\launch.log, the host- # pty\logs\pty-host.log (pty/src/logfile.rs), the dial logs\dial-*.log.+ # pty\logs\pty-host-<instance>.log (pty/src/logfile.rs), the dial logs\dial-*.log.foreach ($tree in @('cli\data', 'pty\logs', 'logs')) {$dir = Join-Path $root $tree$files = @(Get-ChildItem $dir -Filter '*.log' -Recurse -File -Force -ErrorAction SilentlyContinue)diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex ac5399cea..a9b1286ad 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -745,9 +745,11 @@ export class BackendSocket {}/** The window's focused agent on this local connection — its terminal gets the short output window. */- setLocalTerminalFocus(connId: string, agentId: string | null): void {+ setLocalTerminalFocus(connId: string, agentId: string | null, visibleAgents?: readonly string[]): void {if (!this.localClients.has(connId)) returnthis.terminalStreams?.setFocusedAgent(connId, agentId)+ // Absent (an older desktop) stays null: that window keeps counting as looking.+ if (visibleAgents) this.terminalStreams?.setVisibleAgents(connId, visibleAgents)}/** Route an authenticated local terminal frame without applying cloud E2EE. */diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex a9d97514a..430450af8 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -77,6 +77,10 @@ import { startServiceProcess } from './serviceProcess.js'import { askDataFolderServer, isLocalSocketName, localSocketPath, refuseServedDataFolder, servedFolderDeps } from './lib/localSocket.js'import { legacyDaemonStatus, localDaemonCall, localDaemonStatus } from './lib/daemonEndpoint.js'import { PipeUnproven } from './lib/windows/pipeClient.js'+import { ptyManifestUrl, ptyPlatformKey, type PtyEntry } from './lib/windows/ptyPayload.js'+import { newerPtyForUpdate } from './lib/windows/ptyUpdateCommand.js'+import { runUpdateSteps } from './lib/updateCommand.js'+import { PTY_PROTOCOL } from './lib/ptyHost/protocol.js'import { runAutonomousDeviceCommand } from './lib/autonomous-device/command.js'import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'import { confirmsRemoval, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceHistory, formatDeviceList, logOrder, removeConfirmation } from './lib/e2ee/deviceDisplay.js'@@ -86,7 +90,7 @@ import { connectWithPassword, type PwConnectProgress } from './lib/e2ee/relayCliimport type { LinkedPeer } from './lib/e2ee/manager.js'import { DeviceLogStore } from './lib/e2ee/deviceLogStore.js'import { TrustGroupStore } from './lib/e2ee/trustGroup.js'-import { confirm as confirmUpdate, fetchManifest, downloadVerified, canary, stage, semverGt, isLocalDevBuild, type UpdateEntry } from './lib/selfUpdate.js'+import { fetchManifest, semverGt, isLocalDevBuild, type UpdateEntry } from './lib/selfUpdate.js'import { managedNodePath } from './lib/nodeRuntime.js'import { updateManagedTui } from './tui/manage.js'import { ensureHnLauncher, ensureLauncher } from './lib/launchers.js'@@ -1186,18 +1190,13 @@ async function resolveMachineIfUnknown(session: AuthSession): Promise<void> {}const RESOLVE_ON_START_TIMEOUT_MS = 10_000-/** Download + sha256-verify + canary the manifest's cli.js/notify.mjs, then atomically swap them into- * the installed CLI dir (dropping the .prev backups on success). The freshly-written cli.js is what the- * NEXT spawned daemon (`node cli.js __run`) executes — so staging here = "update, then run the new build".- * Runs in the short-lived CLI process, distinct from the daemon's own background `startSelfUpdater`. */-async function downloadCanaryStage(entry: UpdateEntry, dir: string, log: (m: string) => void): Promise<boolean> {- const cliBuf = await downloadVerified(entry.cli)- const notifyBuf = await downloadVerified(entry.notify)- if (!await canary(cliBuf, dir, entry.version)) { log(` ✗ the new build failed its self-check — keeping v${VERSION}`); return false }- // Asked for by name, so a version this machine once rolled back is installed and no longer rejected.- stage(dir, cliBuf, notifyBuf, entry.version)- confirmUpdate(dir) // canary passed + bytes already verified ⇒ drop the .prev backups- return true+/** The terminal host payload newer than the one installed under [rootDir], or null (also when this platform or the+ * update URL has none: the CLI's update goes on). */+async function newerPtyFor(rootDir: string): Promise<PtyEntry | null> {+ const key = ptyPlatformKey()+ let url: string+ try { url = ptyManifestUrl(env.ADAPTER_UPDATE_URL) } catch { return null }+ return key === null ? null : newerPtyForUpdate({ url, key, rootDir })}/** An explicit hn update manages only the installed bundle, never a checkout or a canary. */@@ -1215,6 +1214,10 @@ function isInstalledCli(): boolean {* its poller can't race our staging), swaps in the new bytes, then relaunches on them. No-op on a* dev/repo build, and leaves the daemon running-on-the-old-build untouched when already up to date.*+ * On Windows the terminal host's promoted payload counts too (lib/windows/ptyUpdateCommand.ts): a newer one is+ * installed under the same lock, before the CLI, and with the CLI current it is installed alone and the daemon+ * restarted. As for the CLI, a version this machine rolled back is installed anyway.+ ** On a LOCAL build (`install-cli.sh`) it stops and says so: the automatic paths leave those alone* (see {@link shouldAutoUpdate}), and a command that silently did the opposite would be the same* lost-work trap with a human's finger on it. [force] is that human saying it anyway. */@@ -1245,18 +1248,21 @@ async function updateCommand(force: boolean): Promise<void> {// level with — the check that keeps a release from stomping the build is also the check that would// make the deliberate swap a no-op.const replacingLocalBuild = force && isLocalDevBuild(VERSION)- if (!entry || !(semverGt(entry.version, VERSION) || replacingLocalBuild)) {+ const cliEntry = entry && (semverGt(entry.version, VERSION) || replacingLocalBuild) ? entry : null+ // Asked before anything stops: a host that is current must not cost the daemon a restart.+ const ptyRoot = process.platform === 'win32' ? dirname(resolve(env.ADAPTER_CLI_DIR)) : null+ const pty = ptyRoot === null ? null : await newerPtyFor(ptyRoot)+ if (!cliEntry && !pty) {console.log(`✓ Already on the latest version (v${VERSION}).`)process.exit(0)}- // A newer build exists. Stop the running daemon FIRST so its own background updater can't race our- // staging on the .prev/.tmp files, then swap the bytes and bring it back up on the new build.+ // A newer build or terminal host exists. Stop the running daemon FIRST so its own background updater can't+ // race our staging on the .prev/.tmp files, then swap the bytes and bring it back up on the new build.//// The whole stop → stage → relaunch sequence runs under the spawn lock. Between the stop and the// relaunch there is no pid file for several seconds, and anything that spawns `harness start` on// "no daemon" (the desktop app does, every few seconds) used to land a second child in that gap.- const staged = entryawait withSpawnLock('update', async () => {const running = readPid()const wasRunning = !!(running && isAlive(running))@@ -1266,17 +1272,24 @@ async function updateCommand(force: boolean): Promise<void> {}if (wasRunning) { console.log(' stopping the running adapter…'); await stopDaemonOrExit() }- console.log(`▸ Updating v${VERSION} → v${staged.version}…`)- let ok = false- try { ok = await downloadCanaryStage(staged, resolve(env.ADAPTER_CLI_DIR), (m) => console.log(m)) }- catch (e) { console.error(`✗ Update failed: ${e instanceof Error ? e.message : e}`); ok = false }- if (!ok) {- if (wasRunning) await relaunch() // staging failed → bring the OLD build back so `update` never leaves it down- process.exit(1)+ // Download, verify and canary the host and the build, then put them in, the host first (lib/updateCommand.ts). The+ // freshly-written cli.js is what the NEXT spawned daemon (`node cli.js __run`) executes — so staging here =+ // "update, then run the new build". An installed host is on probation, and the master the relaunch (or the next+ // `harness start`) brings up keeps it or rolls it back; with the build it was paired with, both.+ const done = await runUpdateSteps({ cliEntry, pty, cliDir: resolve(env.ADAPTER_CLI_DIR), ptyRoot, currentVersion: VERSION })+ // Nothing new went in: bring the OLD build back so `update` never leaves it down. A host only a newer build could+ // use, left out, is no failure: there was nothing this build could take.+ const nothing = done.cli === 'failed' || (done.cli === 'none' && done.pty !== 'installed')+ if (nothing) {+ const leftOut = done.cli === 'none' && done.pty === 'paired'+ if (leftOut) console.log(`✓ Already on the latest version (v${VERSION}).`)+ if (wasRunning) await relaunch()+ process.exit(leftOut ? 0 : 1)}- console.log(` ✓ installed v${staged.version}`)if (wasRunning) { await relaunch(); return }- console.log(`✓ Updated to v${staged.version}. Run \`harness start\` to connect.`)+ console.log(done.cli === 'installed'+ ? `✓ Updated to v${cliEntry?.version}. Run \`harness start\` to connect.`+ : `✓ Updated the terminal host to ${pty?.version}. Run \`harness start\` to connect.`)process.exit(0)}, {onWaiting: (owner) => console.log(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),@@ -2659,7 +2672,13 @@ function withoutFirst(argv: string[], token: string): string[] {if (cmd === 'help' && args[0] === 'agents') { console.log(agentsHelp()); process.exit(0) }if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') usage()-if (cmd === 'version' || cmd === '--version' || cmd === '-v') { console.log(VERSION); process.exit(0) }+// `--json` adds the terminal host protocol this build needs: the updater's canary reads it (lib/selfUpdate.ts+// `runCanary`) to hold a build back until a host of that protocol is installed. A build from before prints its+// version alone either way, which the canary reads as protocol 2.+if (cmd === 'version' || cmd === '--version' || cmd === '-v') {+ console.log(flags.includes('--json') ? JSON.stringify({ version: VERSION, ptyProtocol: PTY_PROTOCOL }) : VERSION)+ process.exit(0)+}switch (cmd) {diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.tsindex 9e7944557..2e1b4a9a6 100644--- a/cli/src/cliCommand.spec.ts+++ b/cli/src/cliCommand.spec.ts@@ -6,6 +6,7 @@ import { join } from 'path'import { fileURLToPath } from 'url'import { afterEach, describe, expect, it } from 'vitest'import { listenLocalSocket, localSocketPath } from './lib/localSocket.js'+import { PTY_PROTOCOL } from './lib/ptyHost/protocol.js'import { fakePlatform } from './testing/fakePlatform.js'import { alive, SpawnedRuns } from './testing/spawnedRuns.js'@@ -188,6 +189,16 @@ describe('CLI login/start command contract', () => {expect(result.stderr).toContain('Unknown command: analytics')}, ONE_RUN_TEST_MS)+ it('version --json prints the version and the pty protocol', async () => {+ // What the updater's canary reads (lib/selfUpdate.ts `runCanary`): the host protocol a build needs is the+ // protocol rule's input, learned before the build is staged. `harness version` alone prints what it always did.+ const [json, plain] = await Promise.all([run('version', '--json'), run('version')])+ expect(json.status).toBe(0)+ expect(plain.status).toBe(0)+ expect(plain.stdout.trim()).toMatch(/^\S+$/)+ expect(JSON.parse(json.stdout)).toEqual({ version: plain.stdout.trim(), ptyProtocol: PTY_PROTOCOL })+ }, ONE_RUN_TEST_MS)+it('returns a nonzero status for an unknown command', async () => {const result = await run('not-a-command')diff --git a/cli/src/cliStopFirst.spec.ts b/cli/src/cliStopFirst.spec.tsindex 31da3a719..bfda1ada1 100644--- a/cli/src/cliStopFirst.spec.ts+++ b/cli/src/cliStopFirst.spec.ts@@ -33,14 +33,14 @@ function at(text: string, call: string, after = 0): number {/** What changes the computer's state, or starts Harness: none of it may run before a stop's outcome is known. */const MUTATING = ['clearAdapterState(', 'clearAuthSession(', 'writeAuthSession(', 'saveAuthSession(', 'rmSync(', 'writeFileSync(', 'renameSync(',- 'launch(', 'relaunch(', 'passThroughToGridLogout(', 'downloadCanaryStage(', 'signIn(', 'resolveMachineIfUnknown(',+ 'launch(', 'relaunch(', 'passThroughToGridLogout(', 'runUpdateSteps(', 'signIn(', 'resolveMachineIfUnknown(',]describe('commands that stop Harness first (cli.ts)', () => {it.each([['resetCommand', ['clearAdapterState(', 'clearAuthSession(']],['logout', ['passThroughToGridLogout(', 'clearAuthSession(', 'launch(']],- ['updateCommand', ['downloadCanaryStage(', 'relaunch()']],+ ['updateCommand', ['runUpdateSteps(', 'relaunch()']],])('%s goes on only once Harness has stopped', (name, after) => {const text = body(name)const guard = at(text, 'stopDaemonOrExit(')diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex ea9b066d1..f1a2addfa 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -218,7 +218,7 @@ const fields = {// `harness.log` there is the daemon's console, and `harness reset` wipes it.HARNESS_LOGS_DIR: text(join(adapterRootDir, 'logs')),// The Harness PTY host's `--home` (the `ptyhost` terminal backend, pty/): it writes `run/` (its discovery- // file and endpoint) and `logs/pty-host.log` under it. Product-root state like the logs: the host outlives+ // file and endpoint) and `logs/pty-host-<instance>.log` under it. Product-root state like the logs: the host outlives// a daemon restart, and the next daemon finds it here.HARNESS_PTY_DIR: text(join(adapterRootDir, 'pty')),// The dials' own product-root state: `pets/` holds the custom pet packs and which pack stands for what.diff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.tsindex 462a2b66e..27bbe8571 100644--- a/cli/src/core/agents/discovery.spec.ts+++ b/cli/src/core/agents/discovery.spec.ts@@ -327,6 +327,41 @@ describe('discovery', () => {run.handlers.onTerminalAvailability(row(), false)expect(run.deps.announceSession).toHaveBeenCalledTimes(1)})++ describe('a shell row whose pane is live', () => {+ const shell = (over: Partial<RegisteredSession> = {}) => row({ engine: 'terminal', active: false, ...over } as Partial<RegisteredSession>)++ // A shell has no engine process, so no observation ever reactivates it after the core's start marks every row dormant:+ // its live pane, on whichever pty host serves it, is the only evidence there is.+ it('is active again, and announced as such', () => {+ const run = setup()+ const dormant = shell()+ run.rows.set(dormant.agentId, dormant)+ vi.mocked(run.deps.registry.terminalAvailable).mockReturnValue(true)+ run.handlers.onTerminalAvailability(dormant, true)+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)+ expect(run.deps.announceSession).toHaveBeenCalledTimes(1)+ })++ it('is left alone when already active, held or failed, or when its pane is not live', () => {+ const run = setup()+ for (const over of [{ active: true }, { launch: { state: 'held' } }, { launch: { state: 'failed' } }]) {+ const r = shell(over as Partial<RegisteredSession>)+ run.rows.set(r.agentId, r)+ run.handlers.onTerminalAvailability(r, true)+ }+ run.handlers.onTerminalAvailability(shell(), false)+ expect(run.deps.registry.setActive).not.toHaveBeenCalled()+ })++ it('is not reactivated for an engine row, which its process observation owns', () => {+ const run = setup()+ const engine = row({ active: false })+ run.rows.set(engine.agentId, engine)+ run.handlers.onTerminalAvailability(engine, true)+ expect(run.deps.registry.setActive).not.toHaveBeenCalled()+ })+ })})it('cannot promote an unadmitted external waiting pane into a live engine', async () => {diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.tsindex a00eb6c35..b4883080f 100644--- a/cli/src/core/agents/discovery.ts+++ b/cli/src/core/agents/discovery.ts@@ -235,7 +235,13 @@ export function createDiscoveryHandlers({const onTerminalAvailability = (agent: RegisteredSession, available: boolean): void => {const changed = registry.terminalAvailable(agent.agentId) !== availableregistry.setTerminalAvailable(agent.agentId, available)- if (available && changed) announceSession(agent)+ // A shell has no engine process to observe, so nothing else reactivates it after the core's start marked every row+ // dormant: its pane being live (on whichever pty host serves it) is all the evidence there is. Held and failed+ // launches are inactive on purpose.+ const revive = available && isTerminalEngine(agent.engine) && !agent.active+ && agent.launch?.state !== 'held' && agent.launch?.state !== 'failed'+ if (revive) registry.setActive(agent.agentId, true)+ if (available && (changed || revive)) announceSession(agent)}return { onDiscovered, onObserved, onDormant, onRemoved, onTerminalAvailability }}diff --git a/cli/src/core/agents/externalResume.spec.ts b/cli/src/core/agents/externalResume.spec.tsindex 55792512a..97209c7c8 100644--- a/cli/src/core/agents/externalResume.spec.ts+++ b/cli/src/core/agents/externalResume.spec.ts@@ -10,6 +10,7 @@ import type { ProcessView, RunningProcess } from '../../lib/sessionSearch/externimport { createExternalSessions } from '../../services/externalSessions.js'import { createExternalResumes, type ExternalResumeDeps } from './externalResume.js'import { stopExternalOwner } from './externalOwner.js'+import { moveHeldLine } from '../../lib/hostMove/moveAgent.js'vi.mock('./externalOwner.js', () => ({ stopExternalOwner: vi.fn(async () => false) }))const cwd = mkdtempSync(join(tmpdir(), 'external-resume-'))@@ -85,6 +86,20 @@ function setup() {return { deps, registry, rows, panes, inspect, create, killHeld, controller, stage, cancelWork: () => { cancelled = true } }}+it('opens no conversation of an agent a stopped move may still run beside, by its id or an alias the search names', async () => {+ for (const [asked, aliases] of [['conversation', []], ['other', ['conversation']]] as const) {+ const test = setup()+ test.deps.heldConversation = (sessionId) => sessionId === 'conversation' ? 'a1' : null+ test.inspect.mockImplementation(async (request) => ({ ...free(request), session: { ...fact, sessionId: request.sessionId, aliases: [...aliases] } }) as ExternalSessionAnswer)+ const warn = vi.mocked(console.warn)+ warn.mockClear()+ expect(await test.controller.create(input({ resumeSessionId: asked }))).toMatchObject({ ok: false, error: 'AGENT_BUSY' })+ expect(test.create).not.toHaveBeenCalled()+ expect(test.rows.size).toBe(0)+ expect(warn).toHaveBeenCalledWith(moveHeldLine('a1'))+ }+})+it('persists an inert held intent during search outage, then admits and launches the exact conversation', async () => {const test = setup(); test.inspect.mockResolvedValue(externalUnavailable('Reader unavailable.'))const id = await test.stage({ name: 'Mine', codexHome: '/fixture/profile' })diff --git a/cli/src/core/agents/externalResume.ts b/cli/src/core/agents/externalResume.tsindex 97ff9b65a..bc9c8adf1 100644--- a/cli/src/core/agents/externalResume.ts+++ b/cli/src/core/agents/externalResume.ts@@ -13,6 +13,7 @@ import { adoptionDecision } from './adopt.js'import { heldPaneArgv } from './heldLaunches.js'import { createExternalInspector } from './externalInspect.js'import { stopExternalOwner } from './externalOwner.js'+import { moveHeldLine } from '../../lib/hostMove/moveAgent.js'type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>type Owner = NonNullable<ExternalResumeIntent['owner']>@@ -43,6 +44,9 @@ export interface ExternalResumeDeps {launch(): voidforget(agentId: string): voidstopOwner?: typeof stopExternalOwner+ /** The agent whose conversation [sessionId] is, when a move a dead daemon left may still run its engine (main.ts+ * `moveHeld`): adopted, it would get a second engine beside that one. Null for any other. */+ heldConversation?: (sessionId: string) => string | null}export function createExternalResumes(deps: ExternalResumeDeps) {@@ -168,8 +172,18 @@ export function createExternalResumes(deps: ExternalResumeDeps) {if (!backend?.killHeld) return { ok: false, error: backend ? 'TMUX_UNAVAILABLE' : deps.noBackendCode ?? 'TMUX_UNAVAILABLE' }const request = externalSessionRequest({ sessionId: input.resumeSessionId, engine: input.engine })if (!request) return { ok: false, error: 'INVALID_SESSION' }+ const moveHeld = (ids: readonly string[]) => {+ const agentId = ids.map((id) => deps.heldConversation?.(id) ?? null).find((held) => held !== null)+ if (!agentId) return null+ console.warn(moveHeldLine(agentId))+ return { ok: false as const, error: 'AGENT_BUSY', detail: 'This conversation is held until the daemon restarts.' }+ }+ const heldBefore = moveHeld([request.sessionId])+ if (heldBefore) return heldBeforeconst answer = await inspect(request)if (stopped) return { ok: false, error: 'CORE_NOT_READY' }+ const heldAfter = answer.ok && answer.session ? moveHeld([answer.session.sessionId, ...answer.session.aliases ?? []]) : null+ if (heldAfter) return heldAfterconst decision = adoptionDecision(request.sessionId, request.engine, input.takeOver ?? null, answer, held)if (!decision.ok && decision.error !== 'SEARCH_UNAVAILABLE'&& !(decision.error === 'SESSION_BUSY_IN_TERMINAL' && activityUnknown(answer))) return decisiondiff --git a/cli/src/core/agents/hostMove.spec.ts b/cli/src/core/agents/hostMove.spec.tsnew file mode 100644index 000000000..17991fde1--- /dev/null+++ b/cli/src/core/agents/hostMove.spec.ts@@ -0,0 +1,340 @@+import { describe, expect, it, vi } from 'vitest'++vi.mock('../../lib/gatewayRuntime.js', async (real) => ({ ...await real<object>(), probeGatewayRuntime: vi.fn(async () => ({ kind: 'ori' })) }))+import type { RegisteredSession } from '../../lib/registry.js'+import type { RestartAgentDeps } from '../../lib/restartAgent.js'+import type { RestoreLaunch } from '../../lib/restoreAgents.js'+import type { TerminalBackend } from '../../lib/terminalBackend.js'+import type { ProcessIdentity, TerminalRuntimeRef } from '../../lib/terminalTypes.js'+import { terminalRouteKey } from '../../lib/terminalRuntime.js'+import { MoveGate } from '../../lib/hostMove/gate.js'+import { MOVE_MARKER_ENV } from '../../lib/hostMove/moveAgent.js'+import { SEED_HISTORY_LINES } from '../../lib/hostMove/seed.js'+import { createHostMove, hostMoveDeps, moveWaitingArgv, type HostMoveWiring } from './hostMove.js'++const OLD: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p2', paneId: '%1' }+const NEW: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p2-1.2.3', paneId: '%7' }+const OLD_ID: ProcessIdentity = { pid: 42, executable: 'claude', startMarker: 'old' }+const NEW_ID: ProcessIdentity = { pid: 43, executable: 'claude', startMarker: 'new' }++function session(): RegisteredSession {+ return {+ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/w', runtimes: [OLD], tmuxPane: '%1', registeredAt: 1,+ processIdentity: { ...OLD_ID }, permissionMode: null,+ } as unknown as RegisteredSession+}++const OVERRIDES = { env: { GRID: '1' }, extraArgs: ['--grid'], clearEnv: [] }+function deferredLaunch(prepare = vi.fn()): RestoreLaunch {+ return {+ argv: ['claude', '--resume', 's1'],+ paneLaunch: { afterExit: ['pwsh'], clearInherited: ['ANTHROPIC_API_KEY'] } as unknown as RestoreLaunch['paneLaunch'],+ deferred: { prepare, overrides: OVERRIDES, permission: { permissionMode: 'plan', bypassPermission: false } },+ }+}++function backend(): TerminalBackend & Record<string, ReturnType<typeof vi.fn>> {+ return {+ name: 'ptyhost',+ holdOpen: vi.fn(async () => ({ state: 'succeeded', dispatch: 'executed' })),+ respawn: vi.fn(async () => ({ state: 'succeeded', dispatch: 'executed' })),+ releaseHold: vi.fn(async () => {}),+ kill: vi.fn(async () => ({ state: 'succeeded', dispatch: 'executed' })),+ create: vi.fn(async () => ({ state: 'succeeded', dispatch: 'executed', runtime: NEW })),+ } as unknown as TerminalBackend & Record<string, ReturnType<typeof vi.fn>>+}++function wiring(overrides: Partial<HostMoveWiring> = {}) {+ const row = session()+ const old = backend()+ const target = backend()+ const swapDeps = {+ holdOpen: vi.fn(async () => ({ ok: true })),+ terminate: vi.fn(async () => 'terminated' as const),+ respawn: vi.fn(async () => ({ ok: true })),+ waitForProcess: vi.fn(async () => ({ ...OLD_ID, pid: 44 })),+ buildArgv: vi.fn(() => ['claude', '--resume', 's1']),+ prepareResume: vi.fn(),+ log: vi.fn(),+ } satisfies RestartAgentDeps+ const releases: Array<ReturnType<typeof vi.fn>> = []+ const w: HostMoveWiring = {+ registry: {+ byAgent: vi.fn(() => row),+ transaction: vi.fn(async (apply: () => unknown) => apply()) as unknown as HostMoveWiring['registry']['transaction'],+ updateRuntimes: vi.fn((_id: string, runtimes: readonly TerminalRuntimeRef[]) => { row.runtimes = [...runtimes]; return true }),+ updateProcessIdentity: vi.fn((_id: string, identity: ProcessIdentity) => { row.processIdentity = identity; return true }),+ setActive: vi.fn(() => true),+ },+ terminals: {+ backendFor: vi.fn((runtime: TerminalRuntimeRef) => terminalRouteKey(runtime) === terminalRouteKey(OLD) ? old : target),+ capture: vi.fn(async () => ({ state: 'succeeded' as const, value: 'history' })),+ },+ createBackend: () => target,+ restore: {+ respawn: vi.fn(async () => ({ ok: true })),+ probeProcess: vi.fn(async () => NEW_ID),+ },+ buildLaunch: vi.fn(async () => deferredLaunch()),+ paneSwapDeps: vi.fn(() => swapDeps) as unknown as HostMoveWiring['paneSwapDeps'],+ retarget: vi.fn(async () => {}),+ gate: new MoveGate(),+ eligible: vi.fn(() => true),+ holdRoute: vi.fn(() => { const release = vi.fn(); releases.push(release); return release }),+ announce: vi.fn(),+ refreshGridAssignment: vi.fn(),+ invalidateControl: vi.fn(),+ waitingArgv: () => ['wait'],+ log: vi.fn(),+ ...overrides,+ }+ return { w, row, old, target, swapDeps, releases }+}++describe('the move, wired to the core', () => {+ it('holds routes with the reconciler, with no auto-release, and hands back that hold\'s own release', () => {+ const { w, releases } = wiring()+ const deps = hostMoveDeps(session(), () => true, w)+ // The eligibility asked before the stop is the core's, of this agent.+ vi.mocked(w.eligible).mockReturnValueOnce(false)+ expect(deps.eligible()).toBe(false)+ expect(w.eligible).toHaveBeenCalledWith('a1')+ const release = deps.holdRoute(terminalRouteKey(OLD))+ expect(w.holdRoute).toHaveBeenCalledWith(terminalRouteKey(OLD), null)+ expect(release).toBe(releases[0])+ })++ it('captures the old pane with its history and colours, and opens the new pane waiting, marked and seeded', async () => {+ const { w, target } = wiring()+ const deps = hostMoveDeps(session(), () => true, w)+ expect(await deps.capture(session())).toBe('history')+ expect(w.terminals.capture).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1' }), { historyLines: SEED_HISTORY_LINES, ansi: true })+ expect(await deps.createSeeded(session(), 'seed')).toEqual({ ok: true, runtime: NEW })+ expect(target.create).toHaveBeenCalledWith(expect.objectContaining({+ command: ['wait'], cwd: '/w', env: { [MOVE_MARKER_ENV]: 'a1' }, seed: 'seed', current: expect.any(Function),+ }))+ })++ it('starts the engine in the new pane with the whole launch, its Windows pane launch included', async () => {+ const { w } = wiring()+ let live = true+ const deps = hostMoveDeps(session(), () => live, w)+ const launch = deferredLaunch()+ await deps.respawn(NEW, launch)+ expect(w.restore.respawn).toHaveBeenCalledWith(NEW, launch, { current: expect.any(Function) })+ const control = vi.mocked(w.restore.respawn).mock.calls[0]![2]!+ expect(control.current!()).toBe(true)+ live = false+ expect(control.current!()).toBe(false)+ })++ it('switches the row in one transaction, and an announce that fails after it is logged, not thrown', () => {+ const { w, row } = wiring({ announce: vi.fn(() => { throw new Error('socket closed') }) })+ const deps = hostMoveDeps(session(), () => true, w)+ expect(() => deps.swap('a1', NEW, NEW_ID)).not.toThrow()+ expect(row.runtimes).toEqual([NEW])+ expect(row.processIdentity).toEqual(NEW_ID)+ expect(w.registry.updateRuntimes).toHaveBeenCalledWith('a1', [NEW], terminalRouteKey(NEW))+ expect(w.invalidateControl).toHaveBeenCalledWith('a1')+ expect(vi.mocked(w.log).mock.calls.flat().join('\n')).toContain('[terminal] move a1: ')+ })++ it('throws when the row was not switched', () => {+ const { w } = wiring()+ vi.mocked(w.registry.updateRuntimes).mockReturnValue(false)+ const deps = hostMoveDeps(session(), () => true, w)+ expect(() => deps.swap('a1', NEW, NEW_ID)).toThrow()+ expect(w.registry.updateProcessIdentity).not.toHaveBeenCalled()+ expect(w.announce).not.toHaveBeenCalled()+ })++ it('stops the process the row recorded when the move began, keeping its pane', async () => {+ const { w, row, swapDeps, old } = wiring()+ const deps = hostMoveDeps(row, () => true, w)+ // Discovery records another process for the row after the move began: the move still targets the one it saw.+ row.processIdentity = { ...OLD_ID, pid: 99 }+ expect(await deps.stopEngine(row)).toBe('terminated')+ const [target, place] = vi.mocked(w.paneSwapDeps).mock.calls[0]!+ expect(target.processIdentity).toEqual(OLD_ID)+ expect(place).toEqual({ backend: old, runtime: OLD })+ expect(swapDeps.holdOpen).toHaveBeenCalled()+ expect(swapDeps.holdOpen.mock.invocationCallOrder[0]).toBeLessThan(swapDeps.terminate.mock.invocationCallOrder[0]!)+ })++ it('a pane that cannot be kept open is not stopped', async () => {+ const { w, swapDeps } = wiring()+ swapDeps.holdOpen.mockResolvedValue({ ok: false, reason: 'gone' } as never)+ const deps = hostMoveDeps(session(), () => true, w)+ expect(await deps.stopEngine(session())).toBe('failed')+ expect(swapDeps.terminate).not.toHaveBeenCalled()+ })++ it('prepares the conversation with what the launch was built with, without asking for overrides again', async () => {+ const prepare = vi.fn()+ const { w } = wiring({ buildLaunch: vi.fn(async () => deferredLaunch(prepare)) })+ const deps = hostMoveDeps(session(), () => true, w)+ await expect(deps.prepareResume(session())).rejects.toThrow()+ await deps.buildLaunch(session(), { resumeSessionId: 's1', current: () => true, prepare: false })+ await deps.prepareResume(session())+ expect(prepare).toHaveBeenCalledTimes(1)+ expect(w.buildLaunch).toHaveBeenCalledTimes(1)+ })++ it('relaunches in the old pane with the launch\'s own overrides, and the row keeps the old pane', async () => {+ const prepare = vi.fn()+ const { w, swapDeps, old, row } = wiring({ buildLaunch: vi.fn(async () => deferredLaunch(prepare)) })+ const deps = hostMoveDeps(row, () => true, w)+ // No launch yet: nothing to relaunch with.+ expect(await deps.relaunchOld(row)).toBe(false)+ await deps.buildLaunch(row, { resumeSessionId: 's1', current: () => true, prepare: false })+ await deps.prepareResume(row)+ expect(await deps.relaunchOld(row)).toBe(true)+ const [, place, overrides, permissionMode] = vi.mocked(w.paneSwapDeps).mock.calls.at(-1)!+ expect(place).toEqual({ backend: old, runtime: OLD })+ expect(overrides).toBe(OVERRIDES)+ expect(permissionMode).toBe('plan')+ expect(swapDeps.respawn).toHaveBeenCalled()+ // Prepared already, before the stop: not prepared twice.+ expect(prepare).toHaveBeenCalledTimes(1)+ expect(swapDeps.prepareResume).not.toHaveBeenCalled()+ // Committed as a restart commits (`commitRelaunchedEngine`): gateway, active, the pane released, announced, and+ // its grid assignment refreshed.+ expect(w.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', { ...OLD_ID, pid: 44 }, 'ori')+ expect(w.registry.setActive).toHaveBeenCalledWith('a1', true)+ expect(old.releaseHold).toHaveBeenCalledWith(OLD)+ expect(w.announce).toHaveBeenCalled()+ expect(w.refreshGridAssignment).toHaveBeenCalledWith(row)+ })++ it('a relaunch cancelled once the row has its engine still says the engine came back', async () => {+ const { w, old, row } = wiring()+ let live = true+ vi.mocked(old.releaseHold).mockImplementation(async () => { live = false })+ const deps = hostMoveDeps(row, () => live, w)+ await deps.buildLaunch(row, { resumeSessionId: 's1', current: () => true, prepare: false })+ expect(await deps.relaunchOld(row)).toBe(true)+ expect(w.registry.updateProcessIdentity).toHaveBeenCalled()+ expect(w.announce).not.toHaveBeenCalled()+ })++ it('a relaunch whose engine does not come back says so', async () => {+ const { w, swapDeps, row } = wiring()+ swapDeps.waitForProcess.mockResolvedValue(null as never)+ const deps = hostMoveDeps(row, () => true, w)+ await deps.buildLaunch(row, { resumeSessionId: 's1', current: () => true, prepare: false })+ expect(await deps.relaunchOld(row)).toBe(false)+ expect(w.registry.updateProcessIdentity).not.toHaveBeenCalled()+ })++ it('closes a pane on its own backend, and says whether it is gone', async () => {+ const { w, target } = wiring()+ const deps = hostMoveDeps(session(), () => true, w)+ expect(await deps.killPane(NEW)).toBe(true)+ vi.mocked(target.kill).mockResolvedValue({ state: 'failed', dispatch: 'rejected', reason: 'busy' })+ expect(await deps.killPane(NEW)).toBe(false)+ await deps.releaseHold(NEW)+ expect(target.releaseHold).toHaveBeenCalledWith(NEW)+ })++ it('the new pane waits printing nothing over its seed', () => {+ for (const platform of ['linux', 'darwin', 'win32'] as const) {+ const argv = moveWaitingArgv(platform)+ expect(argv.join(' '), platform).not.toMatch(/printf|stdout|echo/)+ }+ expect(moveWaitingArgv('win32')[1]).toBe('-e')+ })+})++describe('the move, wired to the core: the paths that do not go through', () => {+ it('reads no history from a pane that cannot be captured, and probes the new pane\'s engine', async () => {+ const { w } = wiring()+ vi.mocked(w.terminals.capture).mockResolvedValue({ state: 'failed', dispatch: 'rejected', reason: 'gone' } as never)+ const deps = hostMoveDeps(session(), () => true, w)+ expect(await deps.capture(session())).toBeNull()+ expect(await deps.probeProcess(NEW, 'claude')).toEqual(NEW_ID)+ expect(w.restore.probeProcess).toHaveBeenCalledWith(NEW, 'claude')+ await deps.retarget('a1', NEW)+ expect(w.retarget).toHaveBeenCalledWith('a1', NEW)+ deps.log('a line')+ expect(w.log).toHaveBeenCalledWith('a line')+ })++ it('opens no pane without a target host, and says why a host refused one', async () => {+ const none = wiring({ createBackend: () => null })+ expect(await hostMoveDeps(session(), () => true, none.w).createSeeded(session(), 'seed')).toEqual({ ok: false, reason: 'no target host' })+ const { w, target } = wiring()+ vi.mocked(target.create).mockResolvedValue({ state: 'failed', dispatch: 'rejected', reason: 'full' } as never)+ expect(await hostMoveDeps(session(), () => true, w).createSeeded(session(), 'seed')).toEqual({ ok: false, reason: 'full' })+ })++ it('does not stop an engine whose pane has no backend, and names a hold failure that gave no reason', async () => {+ const lost = wiring()+ vi.mocked(lost.w.terminals.backendFor).mockReturnValue(undefined as never)+ expect(await hostMoveDeps(session(), () => true, lost.w).stopEngine(session())).toBe('failed')+ expect(lost.w.paneSwapDeps).not.toHaveBeenCalled()+ const { w, swapDeps } = wiring()+ swapDeps.holdOpen.mockResolvedValue({ ok: false } as never)+ expect(await hostMoveDeps(session(), () => true, w).stopEngine(session())).toBe('failed')+ expect(vi.mocked(w.log).mock.calls.flat().join('\n')).toContain('(unknown reason)')+ })++ it('a switch whose save fails is logged, and a row gone after it or no grid refresh is not an error', async () => {+ for (const thrown of [new Error('disk full'), 'plain']) {+ const { w } = wiring({ registry: { ...wiring().w.registry, transaction: vi.fn(async () => { throw thrown }) as never } })+ expect(() => hostMoveDeps(session(), () => true, w).swap('a1', NEW, NEW_ID)).toThrow('the row is gone')+ await new Promise((done) => setImmediate(done))+ expect(vi.mocked(w.log).mock.calls.flat().join('\n')).toContain(`saving the switch failed: ${thrown instanceof Error ? thrown.message : thrown}`)+ }+ const gone = wiring()+ vi.mocked(gone.w.registry.byAgent).mockReturnValue(undefined)+ hostMoveDeps(session(), () => true, gone.w).swap('a1', NEW, NEW_ID)+ expect(gone.w.announce).not.toHaveBeenCalled()+ const plain = wiring({ refreshGridAssignment: undefined })+ hostMoveDeps(session(), () => true, plain.w).swap('a1', NEW, NEW_ID)+ expect(plain.w.announce).toHaveBeenCalled()+ })++ it('releases no hold on a pane with no backend', async () => {+ const { w } = wiring()+ vi.mocked(w.terminals.backendFor).mockReturnValue(undefined as never)+ const deps = hostMoveDeps(session(), () => true, w)+ await expect(deps.releaseHold(NEW)).rejects.toThrow('no backend for the new pane')+ expect(await deps.killPane(NEW)).toBe(false)+ })++ it('relaunches a resume-only, bypassing agent that was never prepared, and says when the relaunch fails or the row is gone', async () => {+ const prepare = vi.fn()+ const launch = deferredLaunch(prepare)+ launch.deferred!.permission = { bypassPermission: true } as never+ const row = { ...session(), resumeOnly: true } as RegisteredSession+ const { w, swapDeps } = wiring({ buildLaunch: vi.fn(async () => launch) })+ const deps = hostMoveDeps(row, () => true, w)+ await deps.buildLaunch(row, { resumeSessionId: 's1', current: () => true, prepare: false })+ // The row is gone once the engine is back: not a failure of the relaunch.+ vi.mocked(w.registry.byAgent).mockReturnValue(undefined)+ expect(await deps.relaunchOld(row)).toBe(false)+ expect(vi.mocked(w.paneSwapDeps).mock.calls[0]![3]).toBeNull()+ expect(prepare).toHaveBeenCalledTimes(1)+ // A relaunch cancelled before the row learned the engine.+ expect(await hostMoveDeps(row, () => false, w).relaunchOld(row)).toBe(false)+ expect(swapDeps.waitForProcess).toHaveBeenCalled()+ })++ it('has nothing to relaunch without a conversation, or for a pane with no backend', async () => {+ const bare = { ...session(), sessionId: undefined } as unknown as RegisteredSession+ const { w } = wiring()+ const deps = hostMoveDeps(bare, () => true, w)+ await deps.buildLaunch(bare, { resumeSessionId: 's1', current: () => true, prepare: false })+ expect(await deps.relaunchOld(bare)).toBe(false)+ const refused = wiring({ buildLaunch: vi.fn(async () => ({ error: 'no' }) as never) })+ const d2 = hostMoveDeps(session(), () => true, refused.w)+ expect(await d2.buildLaunch(session(), { resumeSessionId: 's1', current: () => true, prepare: false })).toEqual({ error: 'no' })+ expect(await d2.relaunchOld(session())).toBe(false)+ })++ it('createHostMove runs a move of a snapshot of the row, and a row with no conversation is not moved', async () => {+ const { w } = wiring()+ const bare = { ...session(), sessionId: undefined } as unknown as RegisteredSession+ expect(await createHostMove(w)(bare, () => true)).toEqual({ moved: false, reason: 'no conversation to resume', fellBack: false })+ })+})diff --git a/cli/src/core/agents/hostMove.ts b/cli/src/core/agents/hostMove.tsnew file mode 100644index 000000000..407551dca--- /dev/null+++ b/cli/src/core/agents/hostMove.ts@@ -0,0 +1,187 @@+/**+ * One move to the target pty host, wired to the core (hostMove/moveAgent.ts says what each step must do; this says+ * which core call does it). Every pane call reaches the pane's own backend; the new pane is made on the create+ * backend, the target's.+ *+ * The launch is built once, at step 2, without its preparation (`prepare: false`). What it was built with (the grid's+ * or the Store's overrides, the permission) is kept on it (`deferred`), and both the preparation and a fallback's+ * relaunch in the old pane use that: nothing is asked of the grid or the Store again while the agent's input is held.+ */+import { baseNode } from '../../harnessd/baseNode.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { ProcessIdentity, TerminalRuntimeRef } from '../../lib/terminalTypes.js'+import type { MoveGate } from '../../lib/hostMove/gate.js'+import { moveAgent, moveCreateRequest, type MoveAgentDeps, type MoveOutcome } from '../../lib/hostMove/moveAgent.js'+import { SEED_HISTORY_LINES } from '../../lib/hostMove/seed.js'+import { restartAgent } from '../../lib/restartAgent.js'+import type { RestoreAgentsDeps, RestoreLaunch } from '../../lib/restoreAgents.js'+import type { RestoreTerminals } from '../../lib/restoreTerminals.js'+import { restartTargetOf, type TerminalBackend } from '../../lib/terminalBackend.js'+import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'+import { terminalRouteKey } from '../../lib/terminalRuntime.js'+import { commitRelaunchedEngine } from './restart.js'+import type { PaneSwap } from './swap.js'++export interface HostMoveWiring {+ registry: {+ byAgent(agentId: string): RegisteredSession | undefined+ transaction<T>(apply: () => T | Promise<T>): Promise<T>+ updateRuntimes(agentId: string, runtimes: readonly TerminalRuntimeRef[], primaryRuntimeKey?: string): boolean+ updateProcessIdentity(agentId: string, identity: ProcessIdentity, gateway?: 'ori' | null): boolean+ setActive(agentId: string, active: boolean): boolean+ }+ terminals: Pick<TerminalBackendCoordinator, 'backendFor' | 'capture'>+ /** The backend new panes are made on: the target host's. */+ createBackend(): TerminalBackend | null+ /** Restore's own pane calls (lib/restoreTerminals.ts): its respawn spreads the launch's Windows pane launch. */+ restore: Pick<RestoreTerminals, 'respawn' | 'probeProcess'>+ /** Restore's launch (`createRestoreLaunch`), shared. */+ buildLaunch: RestoreAgentsDeps['buildLaunch']+ /** The pane-process swap's calls (core/agents/swap.ts): the stop of the recorded process, and a restart's relaunch. */+ paneSwapDeps: PaneSwap['paneSwapDeps']+ retarget(agentId: string, runtime: TerminalRuntimeRef): Promise<void>+ gate: MoveGate+ /** Whether [agentId] is still idle, quiet and not looked at, as the mover picked it: asked before the stop. */+ eligible(agentId: string): boolean+ /** `agentReconciler.holdRoute`, asked with no auto-release. */+ holdRoute(routeKey: string, autoReleaseMs: null): () => void+ announce(session: RegisteredSession): void+ /** A control lease taken on the old pane is not the new one's (core/terminals/control.ts). */+ invalidateControl(agentId: string): void+ refreshGridAssignment?(session: RegisteredSession): void+ /** The command the new pane waits in, with no engine, until the engine is started in it. */+ waitingArgv(): string[]+ log(message: string): void+}++/**+ * What the new pane runs until the engine is started in it: a process that waits and prints nothing, so the pane shows+ * the scrollback it was seeded with and no line of its own (restore's waiting pane, `heldPaneArgv`, says why it waits).+ * It ignores the interrupt keys, as that one does, so nothing typed ends it before the respawn replaces it.+ */+export function moveWaitingArgv(platform: NodeJS.Platform = process.platform): string[] {+ if (platform === 'win32') {+ return [baseNode(process.execPath), '-e', 'for(const s of ["SIGINT","SIGBREAK","SIGHUP"])process.on(s,()=>{});setInterval(()=>{},3600000)', 'harness-move']+ }+ return ['/bin/sh', '-c', 'trap "" INT QUIT TSTP; while :; do sleep 3600; done', 'harness-move']+}++const message = (error: unknown): string => error instanceof Error ? error.message : String(error)++/** The row as the move found it: what it stops is the process recorded then, never one recorded since. */+function snapshot(session: RegisteredSession): RegisteredSession {+ return { ...session, runtimes: [...session.runtimes], processIdentity: session.processIdentity && { ...session.processIdentity } }+}++/** [session]'s move, its cancellation read from [current] (`restartJobs.run`'s). */+export function hostMoveDeps(session: RegisteredSession, current: () => boolean, w: HostMoveWiring): MoveAgentDeps {+ const { agentId } = session+ const recorded = snapshot(session)+ /** The launch step 2 built, and whether its preparation has run. */+ let launch: RestoreLaunch | null = null+ let prepared = false+ const placeOf = (row: RegisteredSession) => restartTargetOf(row, (runtime) => w.terminals.backendFor(runtime))++ return {+ capture: async (row) => {+ const read = await w.terminals.capture(row, { historyLines: SEED_HISTORY_LINES, ansi: true })+ return read.state === 'succeeded' ? read.value : null+ },+ buildLaunch: async (row, opts) => {+ const built = await w.buildLaunch(row, opts)+ if ('argv' in built) launch = built+ return built+ },+ createSeeded: async (row, seed) => {+ const backend = w.createBackend()+ if (!backend) return { ok: false, reason: 'no target host' }+ const made = await backend.create({ ...moveCreateRequest(agentId, { seed, command: w.waitingArgv(), cwd: row.cwd }), current })+ return made.state === 'succeeded' ? { ok: true, runtime: made.runtime } : { ok: false, reason: made.reason }+ },+ respawn: (runtime, built) => w.restore.respawn(runtime, built, { current: () => current() && built.current?.() !== false }),+ prepareResume: async () => {+ const deferred = launch?.deferred+ if (!deferred) throw new Error('the launch was not built for a move')+ deferred.prepare()+ prepared = true+ },+ stopEngine: async () => {+ const place = placeOf(recorded)+ if (!place) return 'failed'+ // The pane is kept (`holdOpen`) before its engine is signalled: closed with it, nothing would be left to fall back+ // to. `terminate` signals the process the row recorded, checked against its start marker.+ const swap = w.paneSwapDeps(recorded, place, {}, recorded.permissionMode ?? null, current)+ const kept = await swap.holdOpen()+ if (!kept.ok) {+ w.log(`[terminal] move ${agentId}: could not keep the old pane open (${kept.reason ?? 'unknown reason'})`)+ return 'failed'+ }+ return swap.terminate()+ },+ probeProcess: (runtime, engine) => w.restore.probeProcess(runtime, engine),+ swap: (id, runtime, identity) => {+ // Synchronous: the transaction applies before it first awaits, so the row names the new pane on return.+ let switched = false+ void w.registry.transaction(() => {+ if (!w.registry.updateRuntimes(id, [runtime], terminalRouteKey(runtime))) return+ switched = true+ w.registry.updateProcessIdentity(id, identity)+ }).catch((error) => { w.log(`[terminal] move ${id}: saving the switch failed: ${message(error)}`) })+ if (!switched) throw new Error('the row is gone')+ // The row is switched: nothing after this may fail the move, which would relaunch the old engine beside the new.+ try {+ w.invalidateControl(id)+ const row = w.registry.byAgent(id)+ if (row) {+ w.announce(row)+ w.refreshGridAssignment?.(row)+ }+ } catch (error) {+ w.log(`[terminal] move ${id}: announcing the switch failed: ${message(error)}`)+ }+ },+ retarget: (id, runtime) => w.retarget(id, runtime),+ releaseHold: async (runtime) => {+ const backend = w.terminals.backendFor(runtime)+ if (!backend) throw new Error('no backend for the new pane')+ await backend.releaseHold(runtime)+ },+ killPane: async (runtime) => {+ const backend = w.terminals.backendFor(runtime)+ return !!backend && (await backend.kill(runtime)).state === 'succeeded'+ },+ relaunchOld: async (row) => {+ const deferred = launch?.deferred+ const place = placeOf(recorded)+ if (!deferred || !place || !recorded.sessionId) return false+ // A restart in the old pane, as `agent_restart` runs it, with the overrides and permission the move's launch was+ // built with. The conversation was prepared before the respawn when that step ran; otherwise here.+ const swap = w.paneSwapDeps(recorded, place, deferred.overrides, deferred.permission.permissionMode ?? null, current)+ const outcome = await restartAgent(+ { engine: recorded.engine, sessionId: recorded.sessionId, ...(recorded.resumeOnly ? { resumeOnly: true as const } : {}) },+ deferred.permission.bypassPermission === true,+ { ...swap, isCurrent: current, prepareResume: prepared ? undefined : () => deferred.prepare() },+ )+ if (!outcome.ok) {+ w.log(`[terminal] move ${agentId}: the relaunch in the old pane failed: ${outcome.detail}`)+ return false+ }+ // The row learns it as a restart's does (`commitRelaunchedEngine`, core/agents/restart.ts): shared, not copied.+ const committed = await commitRelaunchedEngine(+ { registry: w.registry, announceSession: w.announce, refreshGridAssignment: (refreshed) => w.refreshGridAssignment?.(refreshed) },+ row.agentId, outcome.processIdentity, place, current)+ // Cancelled once the row had the engine: it runs in the old pane all the same, which is what a fallback is.+ return typeof committed !== 'string' || committed === 'changed after commit'+ },+ gate: w.gate,+ holdRoute: (routeKey) => w.holdRoute(routeKey, null),+ current,+ eligible: () => w.eligible(agentId),+ log: (line) => w.log(line),+ }+}++/** Move [session] to the target host, as [current]'s lifecycle operation. */+export function createHostMove(w: HostMoveWiring): (session: RegisteredSession, current: () => boolean) => Promise<MoveOutcome> {+ return (session, current) => moveAgent(snapshot(session), hostMoveDeps(session, current, w))+}diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.tsindex 97ebbea42..b94d17743 100644--- a/cli/src/core/agents/lifecycle.spec.ts+++ b/cli/src/core/agents/lifecycle.spec.ts@@ -6,6 +6,7 @@ import { AgentStopError, createStopAgentService } from '../../lib/stopAgentServiimport { createAgentLifecycle, createPurgeRequest, createStopRequest, type LifecycleDeps } from './lifecycle.js'import { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'+import { moveHeldLine } from '../../lib/hostMove/moveAgent.js'vi.mock('../../lib/stopAgentService.js', async (real) => ({ ...await real<object>(), createStopAgentService: vi.fn(() => vi.fn(async () => {})) }))vi.mock('../../lib/resumeAgentService.js', async (real) => ({@@ -163,6 +164,24 @@ describe('stopping, purging and resuming an agent', () => {expect(vi.mocked(createResumeAgentService).mock.results.every((r) => !vi.mocked(r.value).mock.calls.length)).toBe(true)})+ it('starts no engine for an agent a stopped move may still run beside, stopped or running, this start', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const held = setup({ moveHeld: (id) => id === 'a1', stoppedAgents: { list: () => [], get: vi.fn(() => row()) } as never })+ expect(await held.lifecycle.resumeAgent('a1')).toMatchObject({ ok: false, error: 'AGENT_BUSY' })+ expect(vi.mocked(createResumeAgentService).mock.results.at(-1)!.value).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledWith(moveHeldLine('a1'))+ warn.mockRestore()+ })++ it('holds an id that no store knows by that id, as given', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const held = setup({ moveHeld: (id) => id === 'ghost', stoppedAgents: { list: () => [], get: vi.fn(() => undefined) } as never })+ vi.spyOn(held.deps.registry, 'byAgent').mockReturnValue(undefined)+ expect(await held.lifecycle.resumeAgent('ghost')).toMatchObject({ ok: false, error: 'AGENT_BUSY' })+ expect(warn).toHaveBeenCalledWith(moveHeldLine('ghost'))+ warn.mockRestore()+ })+it('waits while the agent is being purged, or while a purge holds its folder', async () => {const busy = setup()vi.spyOn(busy.lifecycle.purgeAgentService, 'busy').mockReturnValue(true)diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsindex 33b78cbfa..926e9dc3d 100644--- a/cli/src/core/agents/lifecycle.ts+++ b/cli/src/core/agents/lifecycle.ts@@ -8,6 +8,7 @@ import type { clearDeleted as clearDeletedFn, markDeleted as markDeletedFn } froimport { PurgeAgentService } from '../../lib/purgeAgentService.js'import type { registry, RegisteredSession } from '../../lib/registry.js'import { createResumeAgentService, type ResumeAgentServiceDeps } from '../../lib/resumeAgentService.js'+import { moveHeldLine } from '../../lib/hostMove/moveAgent.js'import type { SessionCheckpointStore } from '../../lib/sessionCheckpoint.js'import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'import { AgentStopError, createStopAgentService, type StopAgentServiceDeps } from '../../lib/stopAgentService.js'@@ -57,12 +58,14 @@ export interface LifecycleDeps {/** An agent was stopped: closed (`agent_close`), Stop Harness, or purged. The harnesses it started close with it* (services/agentCleanup.ts `closed`). */stopped?: (agentId: string) => void+ /** An agent a move a dead daemon left may still run beside (main.ts `moveHeld`): no engine of it starts this start. */+ moveHeld?: (agentId: string) => boolean}export function createAgentLifecycle({registry, stoppedAgents, restartJobs, createBackend, noBackendCode, backendFor, agentReconciler, forgetSession, markDeleted, clearDeleted, stopNative, settlePane, cancelExternal,sessionCheckpoints, mirror, sessionSearch, send, pinnedControls, retainExitedSession, announceSession,- relaunchOverrides, prepareSessionResume, refreshGridWebSearch, adoptSwarmSkill, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust, atEmptyComposer,+ relaunchOverrides, prepareSessionResume, refreshGridWebSearch, adoptSwarmSkill, attachDsh, attachSession, relaunchMarks, stopped, atFolderTrust, atEmptyComposer, moveHeld,}: LifecycleDeps) {/*** Stop Harness (`agent_delete`) archives its conversation and launch settings, removes the live@@ -101,7 +104,17 @@ export function createAgentLifecycle({retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume, adoptSwarmSkill,refreshGridWebSearch, clearDeleted, attachDsh, attachSession, relaunchMarks,})- const resumeAgent: ResumeAgent = (id, permissionMode) => (stoppedAgents.get(id) ?? registry.byAgent(id))?.guest+ const resumeAgent: ResumeAgent = (id, permissionMode) => {+ // A pane a stopped move left may still run this conversation's engine, which no record names (its pid was never+ // the row's), so a resume would find the engine gone and start a second one beside it: not this start.+ const heldId = (stoppedAgents.get(id) ?? registry.byAgent(id))?.agentId ?? id+ if (moveHeld?.(heldId)) {+ console.warn(moveHeldLine(heldId))+ return Promise.resolve({ ok: false, error: 'AGENT_BUSY', detail: 'This harness is held until the daemon restarts.' })+ }+ return resumeChecked(id, permissionMode)+ }+ const resumeChecked: ResumeAgent = (id, permissionMode) => (stoppedAgents.get(id) ?? registry.byAgent(id))?.guest? Promise.resolve(GUEST_HARNESS_REFUSAL): purgeAgentService.busy(id) || purgeAgentService.blocksFolder(stoppedAgents.get(id)?.cwd)? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode)diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.tsindex 82bdbec9f..527d976e4 100644--- a/cli/src/core/agents/restart.spec.ts+++ b/cli/src/core/agents/restart.spec.ts@@ -181,6 +181,18 @@ describe('restarting an agent', () => {expect(await setup(null).restart('a1')).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })})+ it('for an agent a stopped move may still run beside, held this start, with the move\'s line', async () => {+ const log = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const held = vi.fn(() => ({ ok: false, error: 'HELD' }))+ const run = setup(agent(), { moveHeld: (id) => id === 'a1', restartHeld: held as never })+ expect(await run.restart('a1')).toMatchObject({ ok: false, error: 'AGENT_BUSY' })+ // Neither a swap nor a held agent's launch runs: either would start a second engine on the conversation.+ expect(held).not.toHaveBeenCalled()+ expect(restartAgent).not.toHaveBeenCalled()+ expect(log).toHaveBeenCalledWith('[terminal] move a1: held until the next start: a pane its stopped move left was not confirmed closed')+ log.mockRestore()+ })+it('for a guest\'s harness, which a relaunch would run as the owner', async () => {const run = setup(agent({ guest: '[email protected]' }))expect(await run.restart('a1')).toEqual(GUEST_HARNESS_REFUSAL)diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.tsindex 3c19586a3..d8f52a6b0 100644--- a/cli/src/core/agents/restart.ts+++ b/cli/src/core/agents/restart.ts@@ -12,10 +12,10 @@ import { buildEngineLaunchArgv, commandAvailableInInteractiveShell } from '../..import { windowsPaneLaunch } from '../../lib/windows/engineStart.js'import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'import { sid } from '../../lib/log.js'-import type { registry, RegisteredSession } from '../../lib/registry.js'+import type { ProcessIdentity, registry, RegisteredSession } from '../../lib/registry.js'import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'-import { restartTargetOf } from '../../lib/terminalBackend.js'+import { restartTargetOf, type RestartTarget } from '../../lib/terminalBackend.js'import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'import { terminalRouteKey } from '../../lib/terminalRuntime.js'import type { HeldRestart } from './heldLaunches.js'@@ -23,6 +23,7 @@ import { workspaceMissing } from '../../lib/workspaceCheck.js'import type { createLaunchHelpers } from './launch.js'import type { RestartAgent } from './launches.js'import type { PaneSwap } from './swap.js'+import { moveHeldLine } from '../../lib/hostMove/moveAgent.js'import type { LaunchOverridesDeps } from '../../lib/launchOverrides.js'import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'@@ -48,6 +49,36 @@ async function engineInstalled(engine: AgentEngine): Promise<boolean | null> {type RestartAgentHandler = RestartAgent+export interface RelaunchCommitDeps {+ registry: Pick<typeof registry, 'updateProcessIdentity' | 'setActive' | 'byAgent'>+ announceSession: (session: RegisteredSession) => void+ refreshGridAssignment: (session: RegisteredSession) => void+}++/**+ * The row learns the engine a restart relaunched in [place] (restart, and a move's fallback to the old pane:+ * core/agents/hostMove.ts): its process and gateway, active again, the pane handed back to its backend's default+ * disposal, then announced. Gateway is a core process fact; optional grid metadata follows the committed binding in the+ * background, so an unavailable models service cannot hold this route. 'changed' when [current] went false before the+ * row learned the engine, 'changed after commit' once it had, 'vanished' when the row is gone.+ */+export async function commitRelaunchedEngine(+ deps: RelaunchCommitDeps, agentId: string, identity: ProcessIdentity, place: RestartTarget, current: () => boolean,+): Promise<RegisteredSession | 'changed' | 'changed after commit' | 'vanished'> {+ const gateway = await probeGatewayRuntime(identity)+ if (!current()) return 'changed'+ deps.registry.updateProcessIdentity(agentId, identity, gateway.kind)+ deps.registry.setActive(agentId, true)+ await place.backend.releaseHold(place.runtime)+ // The row has its new engine: cancelled from here on, the engine is still relaunched.+ if (!current()) return 'changed after commit'+ const refreshed = deps.registry.byAgent(agentId)+ if (!refreshed) return 'vanished'+ deps.announceSession(refreshed)+ deps.refreshGridAssignment(refreshed)+ return refreshed+}+export interface RestartDeps {adoptSwarmSkill?: AdoptSwarmSkillnative?: LaunchOverridesDeps['native']@@ -74,13 +105,15 @@ export interface RestartDeps {/** A held agent runs no engine to swap: its restart is its launch, now (core/agents/heldLaunches.ts). Null for* any other agent. */restartHeld: (agentId: string) => Promise<HeldRestart> | null+ /** An agent a move a dead daemon left may still run beside (main.ts `moveHeld`): no engine of it starts this start. */+ moveHeld?: (agentId: string) => boolean}export function createAgentRestarter({native: inspectNative, adoptSwarmSkill,restartJobs, registry, purgeBusy, stopJobs, pinnedControls, terminals, sameRestartTarget, agentReconciler,terminalHintMachineName, announceSession, refreshGridAssignment, relaunchOverrides, downgradedPermission, refreshGridWebSearch,- liveBypassPermission, paneSwapDeps, restartHeld,+ liveBypassPermission, paneSwapDeps, restartHeld, moveHeld,}: RestartDeps) {/*** Web or device restarted an agent (`agent_restart`): exit the live engine process and relaunch it in@@ -103,6 +136,13 @@ export function createAgentRestarter({*/const restartAgentHandler: RestartAgentHandler = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {if (purgeBusy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }+ // A pane a stopped move left may still run this conversation's engine: neither a swap nor a held launch starts+ // another beside it (core/main.ts, `removeOrphanMovePanes`).+ const heldId = registry.resolve(agentId)?.agentId ?? agentId+ if (moveHeld?.(heldId)) {+ console.warn(moveHeldLine(heldId))+ return { ok: false, error: 'AGENT_BUSY', detail: 'This harness is held until the daemon restarts.' }+ }let session = registry.resolve(agentId)if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }if (session.guest) return GUEST_HARNESS_REFUSAL@@ -206,18 +246,10 @@ export function createAgentRestarter({// Address the CANONICAL agentId from the resolved session, not the raw RPC input — `resolve()`// accepts either an agentId or a bare sessionId, but `setActive`/`byAgent` only ever key on the- // real agentId. Gateway is a core process fact; optional grid metadata follows the committed- // binding in the background, so an unavailable models service cannot hold this route.- const gateway = await probeGatewayRuntime(outcome.processIdentity)- if (!current()) return changed- registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind)- registry.setActive(session.agentId, true)- await backend.releaseHold(runtime)- if (!current()) return changed- const refreshed = registry.byAgent(session.agentId)- if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }- announceSession(refreshed)- refreshGridAssignment(refreshed)+ // real agentId.+ const refreshed = await commitRelaunchedEngine({ registry, announceSession, refreshGridAssignment }, session.agentId, outcome.processIdentity, place, current)+ if (refreshed === 'changed' || refreshed === 'changed after commit') return changed+ if (refreshed === 'vanished') return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }console.log(`[restart] ${sid(session.agentId)} ${engine} · ${outcome.resumed ? 'resumed' : 'fresh session'}`+ (session.gridLaunch ? ` · grid ${session.gridLaunch.networkName}` : ''))return { ok: true, session: refreshed, resumed: outcome.resumed }diff --git a/cli/src/core/agents/restoreLaunch.spec.ts b/cli/src/core/agents/restoreLaunch.spec.tsindex 8494c9634..fc0ed3a9e 100644--- a/cli/src/core/agents/restoreLaunch.spec.ts+++ b/cli/src/core/agents/restoreLaunch.spec.ts@@ -30,6 +30,41 @@ describe('a restore launch Windows refuses', () => {})})+describe('a launch built without preparation', () => {+ it('writes neither the conversation nor the row, and builds the same launch', async () => {+ const { deps, build } = setup()+ expect(await build(entry, { resumeSessionId: 'conversation', current: () => true, prepare: false })).toMatchObject({ argv: ['engine'] })+ expect(deps.prepareSessionResume).not.toHaveBeenCalled()+ expect(deps.refreshGridWebSearch).not.toHaveBeenCalled()+ expect(deps.launch).toHaveBeenCalledWith(entry, { resumeSessionId: 'conversation' }, built.overrides, { bypassPermission: false })+ const prepared = await build(entry, { resumeSessionId: 'conversation', current: () => true })+ expect(prepared).toEqual({ argv: ['engine'] })+ expect(deps.prepareSessionResume).toHaveBeenCalledWith(entry)+ expect(deps.refreshGridWebSearch).toHaveBeenCalledTimes(1)+ })++ it('hands back what it left out, run later with the overrides it was built with, never asked for again', async () => {+ const { deps, build } = setup()+ deps.downgradedPermission.mockResolvedValue({ bypassPermission: true, permissionMode: 'plan' } as never)+ const launch = await build(entry, { resumeSessionId: 'conversation', current: () => true, prepare: false })+ if (!('argv' in launch) || !launch.deferred) throw new Error('expected a deferred launch')+ expect(launch.deferred.overrides).toBe(built.overrides)+ expect(launch.deferred.permission).toEqual({ bypassPermission: true, permissionMode: 'plan' })+ launch.deferred.prepare()+ expect(deps.prepareSessionResume).toHaveBeenCalledWith(entry)+ expect(deps.refreshGridWebSearch).toHaveBeenCalledWith('agent', built.overrides)+ expect(deps.relaunchOverrides).toHaveBeenCalledTimes(1)+ // A preparation that fails says so to its caller, which falls back (hostMove/moveAgent.ts).+ deps.prepareSessionResume.mockImplementationOnce(() => { throw new Error('rollout unreadable') })+ expect(() => launch.deferred!.prepare()).toThrow('rollout unreadable')+ // Nothing to resume: nothing to prepare, only the grid's web search.+ const fresh = await build(entry, { current: () => true, prepare: false })+ if (!('argv' in fresh) || !fresh.deferred) throw new Error('expected a deferred launch')+ fresh.deferred.prepare()+ expect(deps.prepareSessionResume).toHaveBeenCalledTimes(2)+ })+})+describe('restore preparation keeps session authority in core', () => {it.each(['unknown flags', 'changed executable', 'ready'] as const)('preserves native preparation evidence through restore: %s', async stage => {const { deps, build } = setup()diff --git a/cli/src/core/agents/restoreLaunch.ts b/cli/src/core/agents/restoreLaunch.tsindex 9ac1249dc..afaf4ac37 100644--- a/cli/src/core/agents/restoreLaunch.ts+++ b/cli/src/core/agents/restoreLaunch.ts@@ -16,7 +16,7 @@ interface RestoreLaunchDeps {}export function createRestoreLaunch(deps: RestoreLaunchDeps): RestoreAgentsDeps['buildLaunch'] {- return async (entry, { current, ...opts }) => {+ return async (entry, { current, prepare, ...opts }) => {if (externalResumePending(entry.externalResume)) return { held: 'search', holdScope: 'workspace',detail: entry.launch?.state === 'held' ? entry.launch.detail : 'Waiting to verify this external conversation.' }const missing = deps.workspaceMissing(entry.cwd)@@ -31,19 +31,31 @@ export function createRestoreLaunch(deps: RestoreLaunchDeps): RestoreAgentsDeps[if (!current()) return { cancelled: true }if (permission.nativeHold) return { held: 'native', detail: permission.nativeHold }if (built.overrides.native?.current() === false) return { held: 'native', detail: 'Waiting for fresh executable and hook evidence.' }+ // A move builds its launch while the engine still runs (hostMove/moveAgent.ts): the conversation may only be+ // prepared, and the row written, once that engine has stopped. The move runs this itself then, and relaunches with+ // these same overrides if it falls back, so nothing is asked of the grid or the Store again while the agent's input+ // is held.+ const preparation = () => {+ if (opts.resumeSessionId) deps.prepareSessionResume(entry)+ deps.refreshGridWebSearch(entry.agentId, built.overrides)+ }// These writes are synchronous and belong to the core. Neither a stopped conversation's// transcript/tail nor a replacement binding's grid may be changed by an old Store answer.- if (opts.resumeSessionId) {- try { deps.prepareSessionResume(entry) } catch (error) {- return { error: 'RESUME_PREPARATION_FAILED', detail: error instanceof Error ? error.message : String(error) }+ if (prepare !== false) {+ if (opts.resumeSessionId) {+ try { deps.prepareSessionResume(entry) } catch (error) {+ return { error: 'RESUME_PREPARATION_FAILED', detail: error instanceof Error ? error.message : String(error) }+ }}+ deps.refreshGridWebSearch(entry.agentId, built.overrides)}- deps.refreshGridWebSearch(entry.agentId, built.overrides)// Windows refuses a batch-file engine whose arguments cmd.exe would read (lib/windows/launch.ts): this row fails// alone. Thrown, it ended the whole pass ("restore skipped") on every start.- try { return await deps.launch(entry, opts, built.overrides, permission) } catch (error) {+ let launched: RestoreLaunch+ try { launched = await deps.launch(entry, opts, built.overrides, permission) } catch (error) {const { error: code, detail } = windowsLaunchRefusal(error)return { error: code, detail }}+ return prepare === false ? { ...launched, deferred: { prepare: preparation, overrides: built.overrides, permission } } : launched}}diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex c9236860a..b975f76d2 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -126,6 +126,13 @@ describe('the session input controller\'s dependencies', () => {expect(await wired.beforeTeamWrite!(agents.get('a1')!)).toBeNull()})+ it('hands the controller the move gate when it was given one, and none otherwise', () => {+ const { deps: given } = deps()+ expect('moveGate' in sessionInputDeps(given, () => lock([]))).toBe(false)+ const moveGate = { held: () => false } as unknown as NonNullable<InputDeps['moveGate']>+ expect(sessionInputDeps({ ...given, moveGate }, () => lock([])).moveGate).toBe(moveGate)+ })+it('tells the device of a delivery first, then its caller; its caller alone without a device', () => {const one = deps()sessionInputDeps(one.deps, () => lock([])).onDelivery!(delivery('d1'))diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 8d2c27c93..42db338ee 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -17,6 +17,7 @@ import { adaptSlashCommand } from '../lib/goalCommand.js'import { sid } from '../lib/log.js'import type { LiveEvent } from '../engines/kit/events.js'import type { RegisteredSession } from '../lib/registry.js'+import type { MoveGate } from '../lib/hostMove/gate.js'import { SessionInputController, type MessageReceipt, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'import { passingHold } from '../lib/messageHolds.js'import type { ScreenReader } from '../lib/screenReader.js'@@ -58,6 +59,9 @@ export interface InputDeps {/** The person sent text to an agent from a window or the phone (a `message` frame, by agent or session id): one* another agent started is theirs from then on (services/agentCleanup.ts). */typed?: (id: string) => void+ /** While an agent changes host, its messages wait here and go to the pane it ends on (hostMove/gate.ts): the one+ * gate the terminal streams hold its keystrokes in too. */+ moveGate?: MoveGate}/**@@ -130,6 +134,7 @@ export function sessionInputDeps(? teamHold(session.engine, capture ?? '', screen.pane, screen.question, true) : screen.teamHold}return {+ ...(deps.moveGate ? { moveGate: deps.moveGate } : {}),readScreen: deps.readScreen,submission: deps.submission,getSession: (id) => resolve(id),diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 2180c3dc3..7327297ab 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -78,11 +78,16 @@ import { createHandoffDependencies } from './handoffDependencies.js'import { TmuxBackend } from '../lib/tmuxBackend.js'import { tmuxAvailableNow } from '../lib/tmuxOnPath.js'import { createTerminalBackendRecovery } from '../lib/terminalBackendRecovery.js'-import { isDrainBackend, ptyHostBackends, PtyHostDrain, rowsOnInstance } from '../lib/ptyHost/drain.js'-import { removeUnusedPtyVersions } from '../lib/ptyHost/launch.js'+import { isDrainBackend, ptyHostBackends, ptyHostOnProbation, PtyHostDrain, rowInstancesOf, rowsOnInstance, untilHostAttached, withoutCreateHost } from '../lib/ptyHost/drain.js'+import { removeUnusedPtyVersions, targetHost } from '../lib/ptyHost/launch.js'import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from '../lib/hostTheme.js'import { restoreAgents, type RestoreAgentsDeps, type RestoreSummary } from '../lib/restoreAgents.js'import { restoreTerminals } from '../lib/restoreTerminals.js'+import { acquireAfterHold, MoveGate } from '../lib/hostMove/gate.js'+import { HostMover, settleMovesForHandOver } from '../lib/hostMove/mover.js'+import { moveHeldLine, removeOrphanMovePanes, type MoveOutcome } from '../lib/hostMove/moveAgent.js'+import { QUIET_MS, QuietClock } from '../lib/hostMove/quiet.js'+import { resumesConversation } from '../lib/resumeCapability.js'import { createRetainExitedSession } from '../lib/retainExitedSession.js'import { createKeepAbandonedConversation } from '../lib/keepAbandonedConversation.js'import { RESUME_READINESS_BUDGET_MS } from '../lib/resumeStoppedAgent.js'@@ -171,6 +176,7 @@ import { createAgentForker } from './agents/fork.js'import { createPaneSwap } from './agents/swap.js'import { createAgentRetargeter } from './agents/retarget.js'import { createAgentRestarter } from './agents/restart.js'+import { createHostMove, moveWaitingArgv } from './agents/hostMove.js'import { createAgentLifecycle, createPurgeRequest, createStopRequest } from './agents/lifecycle.js'import { createAgentClosing, createCloseRequests } from './agents/close.js'import { answerConversationQuery, conversationReads } from './conversationQueries.js'@@ -483,7 +489,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {// (core/agents/heldLaunches.ts): the boot's restore of only those agents, set where tmux is there to restore into.const restorePanes = createPaneOperations()const restartJobs = new AgentRestartCoordinator()- const forgetRestartRevision = (agentId: string): void => restartJobs.forget(agentId)+ // Moving agents off a drained pty host (lib/hostMove/): how long each has been idle and untouched, the one gate an+ // agent's input waits in while it changes host, and the agents a move a dead daemon left may still run beside+ // (`removeOrphanMovePanes` below), held this start: neither restored, nor discovered, nor moved.+ const hostQuiet = new QuietClock({ now: Date.now })+ const moveGate = new MoveGate()+ const moveHeld = new Set<string>()+ /** The conversations of the agents in [moveHeld]: an adoption of one would start a second engine on it too. */+ const moveHeldConversations = new Map<string, string>()+ let hostMover: HostMover | null = null+ // Every removal of a row goes through here: its clocks go with it.+ const forgetRestartRevision = (agentId: string): void => { restartJobs.forget(agentId); hostQuiet.forget(agentId) }const restoreRevision = (agentId: string): number => restartJobs.revision(agentId)let externalResumes: ReturnType<typeof createExternalResumes> | null = nulllet searchGeneration = 0@@ -521,6 +537,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {probeMaster: () => probeStagedMaster((done) => execFile(managedNodePath(), [SCRIPT_PATH, PROBE_COMMAND], { encoding: 'utf8', env: harnessdEnv() }, (error, stdout) => done(error, stdout))),handOff: () => { startMasterHere(); process.exit(0) },log: (line) => console.log(line), error: (line) => console.error(line),+ // A move to another pty host that holds input: waited for, or its input written out, before the teardown closes the+ // pty host connection the held keystrokes would be written through (lib/hostMove/mover.ts).+ beforeTeardown: () => settleMovesForHandOver({ mover: hostMover, gate: moveGate, log: (line) => console.log(line) }),})// Another daemon serves this data folder: leave before reading or writing anything of its — its@@ -578,10 +597,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {const candidates: TerminalBackend[] = []const configuredTmux = terminalConfig.backends.includes('tmux') ? new TmuxBackend(() => hostTheme) : nullif (configuredTmux) candidates.push(configuredTmux)- // The Harness PTY host (pty/): reached, or started detached so its panes outlive this daemon. A host of the- // protocol before, still running from before an update, is a drain backend beside it (lib/ptyHost/drain.ts).+ // The Harness PTY host (pty/): reached, or started detached so its panes outlive this daemon. New panes go to the+ // target's host, the build this daemon would start; any other host, still running from before an update, is a+ // drain backend beside it (lib/ptyHost/drain.ts). The target is read here once, for this core's life: it runs the+ // binary (`harness-pty version`, up to 5 s), and an update that moves it starts a new core.+ const ptyTarget = terminalConfig.backends.includes('ptyhost') ? targetHost() : null+ if (terminalConfig.backends.includes('ptyhost')) {+ console.log(ptyTarget ? `[terminal] ptyhost: target ${ptyTarget.instance}` : '[terminal] ptyhost: target unknown')+ }const ptyHosts = terminalConfig.backends.includes('ptyhost')- ? ptyHostBackends(env.HARNESS_PTY_DIR, { rowsOn: (instanceId) => rowsOnInstance(registry.list(), instanceId) })+ ? ptyHostBackends(env.HARNESS_PTY_DIR, { target: ptyTarget, rowInstances: () => rowInstancesOf(registry.list()) }): nullconst ptyHostBackend = ptyHosts?.create ?? nullif (ptyHosts) candidates.push(ptyHosts.create, ...ptyHosts.drain)@@ -594,7 +619,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {const loginShellEnvPromise = warmLoginShellEnvironment()console.log(`[terminal] enabled backends: ${terminalConfig.backends.join(', ')}`)const prepared = await preparing- const terminalBackends = prepared.filter((p) => p.result.state === 'ready').map((p) => p.backend)+ const readyBackends = prepared.filter((p) => p.result.state === 'ready').map((p) => p.backend)+ // With no target, the create backend took whichever host answered, which a drain backend may be on too.+ const terminalBackends = ptyHosts ? withoutCreateHost(readyBackends, ptyHosts.create) : readyBackends// The first backend that could not be readied, and why, for the status's `discoveryError`.let terminalUnavailable: { backend: TerminalBackend['name']; reason: string; code: string } | null = prepared.flatMap(({ backend, result }) => result.state === 'unavailable'? [{ backend: backend.name, reason: result.reason, code: result.code }] : [])[0] ?? null@@ -632,6 +659,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {coordinator: terminals,inUse: (instanceId) => rowsOnInstance(registry.list(), instanceId),cleanup: () => { removeUnusedPtyVersions(env.HARNESS_PTY_DIR) },+ // An old host is not shut down while new panes have no host to go to: it may be the only one that serves.+ createAvailable: () => createBackend === ptyHosts.create && ptyHosts.create.attached,}): nullconst sqliteWarning = sqlitePreflightMessage()@@ -656,7 +685,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Reading and writing panes through control leases (core/terminals/control.ts).const terminalControl = createTerminalControl({ resolve: (target) => registry.resolve(target), terminals })const pinnedControls = terminalControl.pinnedControls- restoreCancelled = (agentId) => pinnedControls.has(agentId)+ restoreCancelled = (agentId) => pinnedControls.has(agentId) || moveHeld.has(agentId)const invalidateTerminalControl = terminalControl.invalidateTerminalControlconst captureTerminal = terminalControl.captureTerminalconst submitTerminal = terminalControl.submitTerminal@@ -773,7 +802,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Delivered turns (core/deliveries.ts): text a feature writes into an agent under a delivery id of its// own, and what becomes of each, told back to whoever made it, in this process or in its own.// A read-only view of agents' terminals for an experiment's viewers, told to its process (core/terminalWatch.ts).- const terminalWatch = createTerminalWatch({ terminals, resolve: (id) => registry.resolve(id), watchers: new Set(Object.keys(EXPERIMENTS)),+ const terminalWatch = createTerminalWatch({ terminals, resolve: (id) => registry.resolve(id), watchers: new Set(Object.keys(EXPERIMENTS)), moveGate,tell: (service, viewer, output) => serviceLinksRef?.notify(service, { type: 'service_event', payload: { kind: 'watch', viewer, output } }) ?? false })const deliveries = createDeliveries({submit: (agentId, text, deliveryId) => backendRef?.onMessage?.(agentId, text, deliveryId),@@ -1150,6 +1179,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// a sleeping grid starts that grid while the person types. Here, in the daemon's own input path, so// an older desktop and typing from a phone get it too; an agent on its own login has no `grid`.onInput: (agentId, typed, from) => {+ // What the person typed restarts the agent's quiet period: one in use is not moved to another host.+ if (typed) hostQuiet.noteInput(agentId)if (typed) browser.typed(agentId, from)if (typed) nativeTurns.typed(agentId, from.inputContext, from.submitted === true)const grid = registry.resolve(agentId)?.grid@@ -1157,6 +1188,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The person typing into a harness another agent started makes it theirs (services/agentCleanup.ts).if (typed) ports.agentCleanup?.typed(agentId)},+ moveGate,})backend.setTerminalStreamManager(terminalStreams)// What a harness's pane runs and where, and the desktop's pane colours (core/terminals/requests.ts). A@@ -1303,11 +1335,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {emit: (sessionId, events) => emitSessionEvents(sessionId, events),// Declared further down: read as a prompt is typed, never now.promptTyped: (session, capture, screen, inputContext) => {+ // A message typed into the pane, from any sender (`harness send`, Agent Messages, the Device): the agent is in use.+ hostQuiet.noteInput(session.agentId)nativeTurns.submitting(session.agentId, inputContext)if (session.sessionId) questionWatcher.notePrompt(session.sessionId, capture, screen.question)},// The person sent a harness text from a window or the phone (services/agentCleanup.ts).typed: (id) => ports.agentCleanup?.typed(id),+ moveGate,})const input = inputs.inputconst deviceInput = inputs.deviceInput@@ -1675,7 +1710,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {sendText: submitTerminal,sendLiteral: typeTerminal,sendKey: keyTerminal,- acquireInput: acquireTerminalControl,+ // The /model picker waits out a move to another host rather than answer BUSY (hostMove/gate.ts).+ acquireInput: (id) => acquireAfterHold(moveGate, registry.resolve(id)?.agentId ?? id, () => acquireTerminalControl(id)),})/*** Engine session id → the agent that owns it. The event stream speaks in ENGINE session ids while@@ -1740,6 +1776,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {startHeartbeat,questionWatcher,mirror,+ // A live turn, however short and with no input of its own (a /loop wake-up, a background notification), restarts+ // the agent's quiet period: the mover's ticks alone, seconds apart, would miss it.+ working: (agentId) => hostQuiet.noteActivity(agentId, 'working'),})// Cursor's Task hooks and the sub-agents they start (core/engines/cursorTasks.ts).const cursorTasks = createCursorTaskHooks({ emitSessionEvents, watcher, registry, cursorNormalizers })@@ -1864,6 +1903,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.error('[terminal] ptyhost: drain failed:', error instanceof Error ? error.message : error)})}+ // At most one idle, unwatched agent at a time moves off a drained host (lib/hostMove/mover.ts).+ void hostMover?.step().catch((error) => {+ console.error('[terminal] move: the mover failed:', error instanceof Error ? error.message : error)+ })},onProbeStatus: (status) => {discoveryReady = status.ready@@ -2361,6 +2404,59 @@ async function runForeground(session: AuthSession | null): Promise<void> {const saved = isTerminalEngine(entry.engine) ? stoppedAgents.get(entry.agentId) : nullif (saved && !isTerminalEngine(saved.engine)) retainExitedSession(entry, true)}+ // What restore asks of the terminals, each pane of its own backend, and the launch it builds (both shared with a move+ // to another pty host, core/agents/hostMove.ts). Every pane question asked of the pane's own backend, as every other+ // pane read is.+ const restoreOn = restoreTerminals({+ backendFor: (runtime) => terminals.backendFor(runtime),+ listTmuxPanes: () => listTmuxPanes(),+ cwd: homedir(),+ label: (engine) => buildHarnessSessionLabel(engine),+ })+ const restoreLaunch = createRestoreLaunch({+ workspaceMissing, relaunchOverrides, prepareSessionResume, refreshGridWebSearch,+ downgradedPermission: (entry, native) => downgradedPermission(entry, entry.bypassPermission === true, 'restore', native),+ launch: (entry, opts, overrides, permission) => {+ const { env: launchEnv, extraArgs, clearEnv } = overrides+ const argv = buildEngineLaunchArgv(entry.engine, {+ ...opts,+ ...(overrides.native ? { native: overrides.native } : {}),+ ...(entry.externalResume?.continue && entry.externalResume.signal === 'sent' && !entry.externalResume.dispatched && supportsFirstPrompt(entry.engine) ? { firstPrompt: 'continue' } : {}),+ bypassPermission: permission.bypassPermission === true,+ ...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),+ installIfMissing: enginePathOverride(entry.engine) ? undefined : engineInstallRecipe(entry.engine),+ ...(entry.cwd ? { cwd: entry.cwd } : {}),+ ...(extraArgs.length ? { extraArgs } : {}),+ ...(clearEnv.length ? { clearEnv } : {}),+ ...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),+ })+ // Windows: the variables the argv's `/usr/bin/env` prefix carries elsewhere, last (engineLaunchEnv).+ const paneEnv = { ...launchEnv, ...engineLaunchEnv(entry.engine, overrides.native) }+ return { argv, ...(overrides.native ? { nativeToken: overrides.native.token, current: overrides.native.current } : {}), ...(Object.keys(paneEnv).length ? { env: paneEnv } : {}),+ // Windows: the workspace to start in and the shell the pane becomes after the engine (lib/windows/engineStart.ts).+ paneLaunch: windowsPaneLaunch(entry.engine, { cwd: entry.cwd, clearEnv, native: overrides.native, held: isWindowsHeldPane(argv) }) }+ },+ })+ // A move a dead daemon left before its switch left a pane marked as that move's, which no row names: closed now,+ // before restore relaunches the row's own engine and discovery could mint that pane an agent beside it. One whose+ // close is not confirmed may still run an engine on the conversation: its agent is held this start (not restored,+ // not discovered, not moved), and so is the pane's route, until the next start closes it.+ if (ptyHosts) {+ const swept = await removeOrphanMovePanes(terminalBackends.filter((backend) => backend.name === 'ptyhost'), registry.list())+ .catch((error) => {+ console.warn(`[terminal] move: could not look for panes a stopped move left: ${error instanceof Error ? error.message : error}`)+ return { removed: 0, unconfirmed: [] as string[], keptPanes: [] }+ })+ if (swept.removed) console.log(`[terminal] move: closed ${swept.removed} pane(s) a stopped move left`)+ for (const pane of swept.keptPanes) agentReconciler.holdRoute(terminalRouteKey(pane), null)+ for (const agentId of swept.unconfirmed) {+ moveHeld.add(agentId)+ const conversation = registry.byAgent(agentId)?.sessionId ?? stoppedAgents.get(agentId)?.sessionId+ if (conversation) moveHeldConversations.set(conversation, agentId)+ for (const runtime of registry.byAgent(agentId)?.runtimes ?? []) agentReconciler.holdRoute(terminalRouteKey(runtime), null)+ console.warn(moveHeldLine(agentId))+ }+ }// Later passes over held agents (core/agents/heldLaunches.ts) wait for this one.await heldLaunches.boot(async (current) => {// Restore runs where a backend can rebuild and relaunch a pane in place (tmux, the pty host): each row on the@@ -2370,13 +2466,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// tiles, not the daemon. `restoreDegraded` then stops discovery retiring the rows whose panes// restore never got to, so the next daemon can put them back.try {- // Every pane question asked of the pane's own backend, as every other pane read is.- const restoreOn = restoreTerminals({- backendFor: (runtime) => terminals.backendFor(runtime),- listTmuxPanes: () => listTmuxPanes(),- cwd: homedir(),- label: (engine) => buildHarnessSessionLabel(engine),- })const restoreDeps: RestoreAgentsDeps = {cancelled: (agentId) => !current() || restoreCancelled(agentId),revision: (agentId) => restoreRevision(agentId),@@ -2395,30 +2484,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {restorable: restoreOn.restorable,waitingPane: restoreOn.waitingPane,liveProcess: restoreOn.liveProcess,- buildLaunch: createRestoreLaunch({- workspaceMissing, relaunchOverrides, prepareSessionResume, refreshGridWebSearch,- downgradedPermission: (entry, native) => downgradedPermission(entry, entry.bypassPermission === true, 'restore', native),- launch: (entry, opts, overrides, permission) => {- const { env: launchEnv, extraArgs, clearEnv } = overrides- const argv = buildEngineLaunchArgv(entry.engine, {- ...opts,- ...(overrides.native ? { native: overrides.native } : {}),- ...(entry.externalResume?.continue && entry.externalResume.signal === 'sent' && !entry.externalResume.dispatched && supportsFirstPrompt(entry.engine) ? { firstPrompt: 'continue' } : {}),- bypassPermission: permission.bypassPermission === true,- ...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),- installIfMissing: enginePathOverride(entry.engine) ? undefined : engineInstallRecipe(entry.engine),- ...(entry.cwd ? { cwd: entry.cwd } : {}),- ...(extraArgs.length ? { extraArgs } : {}),- ...(clearEnv.length ? { clearEnv } : {}),- ...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),- })- // Windows: the variables the argv's `/usr/bin/env` prefix carries elsewhere, last (engineLaunchEnv).- const paneEnv = { ...launchEnv, ...engineLaunchEnv(entry.engine, overrides.native) }- return { argv, ...(overrides.native ? { nativeToken: overrides.native.token, current: overrides.native.current } : {}), ...(Object.keys(paneEnv).length ? { env: paneEnv } : {}),- // Windows: the workspace to start in and the shell the pane becomes after the engine (lib/windows/engineStart.ts).- paneLaunch: windowsPaneLaunch(entry.engine, { cwd: entry.cwd, clearEnv, native: overrides.native, held: isWindowsHeldPane(argv) }) }- },- }),+ buildLaunch: restoreLaunch,createPane: restoreOn.createPane,respawn: restoreOn.respawn,probeProcess: restoreOn.probeProcess,@@ -2596,6 +2662,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {native: prepareNativeLaunch, hookPort, hooksDisabled: env.DISABLE_HOOK_INSTALL, installOpencodePlugin: installOpencodePluginBeforeSpawn }),announce: announceSession, launch: () => { void heldLaunches.restoreHeld('search') },forget: id => forgetSession(id, { force: true }),+ heldConversation: (sessionId) => moveHeldConversations.get(sessionId) ?? null,})// Creating an agent (core/agents/create.ts).@@ -2665,7 +2732,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend.onRetargetAgent = createAgentRetargeter({noBackendCode: createUnavailable,sessionTurnOpen,- purgeBusy: (agentId) => restorePanes.busy(agentId) || backend.purgeAgentService?.busy(agentId),+ // A retarget swaps the engine too: not of an agent a stopped move may still run beside (`moveHeld`).+ purgeBusy: (agentId) => restorePanes.busy(agentId) || backend.purgeAgentService?.busy(agentId) || moveHeld.has(registry.resolve(agentId)?.agentId ?? agentId),terminals,registry,runtimeProfiles,@@ -2719,10 +2787,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {relaunchMarks,// A harness closed or stopped: the harnesses it started close with it (services/agentCleanup.ts).stopped: (agentId) => ports.agentCleanup?.closed(agentId),+ moveHeld: (agentId) => moveHeld.has(agentId),})const stopJobs = lifecycle.stopJobslaunchCancelled = id => stopJobs.has(id)- restoreCancelled = (agentId) => stopJobs.has(agentId) || pinnedControls.has(agentId) || (restartJobs.operation(agentId) !== undefined && restartJobs.operation(agentId) !== 'restart')+ restoreCancelled = (agentId) => stopJobs.has(agentId) || pinnedControls.has(agentId) || moveHeld.has(agentId) || (restartJobs.operation(agentId) !== undefined && restartJobs.operation(agentId) !== 'restart')binding.whileChanging((agentId) => restorePanes.busy(agentId) || restartJobs.busy(agentId) || stopJobs.has(agentId))const stopAgent = lifecycle.stopAgentconst stopTerminalAgent = createStopRequest({ byAgent: (id) => registry.byAgent(id), stop: stopAgent })@@ -2772,7 +2841,68 @@ async function runForeground(session: AuthSession | null): Promise<void> {liveBypassPermission,paneSwapDeps,restartHeld: (agentId) => heldLaunches.restartHeld(agentId),- })+ moveHeld: (agentId) => moveHeld.has(agentId),+ })+ // Agents on a drained pty host move, one at a time and only while nobody uses them, to the target host once it can seed+ // a pane (lib/hostMove/mover.ts). Each move is the agent's lifecycle operation: a restart, stop or delete waits for it+ // or cancels it, as it would another restart.+ if (ptyHosts?.drain.length && ptyHostBackend) {+ const target = ptyHostBackend+ const moveActivity = (row: RegisteredSession) => activityFrameContextRef?.(row)?.state ?? 'unknown'+ const moveLookedAt = (agentId: string) => terminalStreams.isLookedAt(agentId) || terminalWatch.isWatched(agentId)+ const moveOne = createHostMove({+ registry, terminals, createBackend: () => createBackend,+ restore: restoreOn, buildLaunch: restoreLaunch, paneSwapDeps,+ // Every stream open to the agent follows it: the windows' and phones', and Share viewers'.+ retarget: async (agentId, runtime) => { await Promise.all([terminalStreams.retarget(agentId, runtime), terminalWatch.retarget(agentId, runtime)]) },+ gate: moveGate,+ // What the mover picked the agent for, asked again up to the old engine's stop: still idle, quiet, unwatched.+ eligible: (agentId) => {+ // Handing over: a move not yet past the old engine's stop cancels itself (`settleMovesForHandOver`).+ if (hostMover?.stopped) return false+ const row = registry.byAgent(agentId)+ return !!row && moveActivity(row) === 'idle' && hostQuiet.quietFor(agentId) >= QUIET_MS && !moveLookedAt(agentId)+ },+ holdRoute: (key, ms) => agentReconciler.holdRoute(key, ms),+ announce: announceSession,+ invalidateControl: invalidateTerminalControl,+ refreshGridAssignment: gridAssignments.refresh,+ waitingArgv: () => moveWaitingArgv(),+ log: (line) => console.log(line),+ })+ hostMover = new HostMover({+ list: () => registry.list(),+ isDrainRow: (row) => row.runtimes.some((runtime) => {+ const on = terminals.backendFor(runtime)+ return !!on && isDrainBackend(on)+ }),+ // Only while the target's host is the one new panes are made on, and it lists `seed`.+ targetCanSeed: () => createBackend === target && target.canSeed,+ target: ptyTarget?.instance ?? target.instanceId.replace(/^ptyhost:/, ''),+ resumesConversation,+ activity: moveActivity,+ quiet: hostQuiet,+ lookedAt: moveLookedAt,+ busy: (agentId) => restartJobs.busy(agentId) || stopJobs.has(agentId) || restorePanes.busy(agentId) || pinnedControls.has(agentId)+ || moveHeld.has(agentId),+ move: async (row) => {+ let outcome: MoveOutcome | null = null+ const reply = await restartJobs.run(row.agentId, async (current) => {+ outcome = await moveOne(row, current)+ return outcome.moved+ ? { ok: true, session: registry.byAgent(row.agentId) ?? row, resumed: outcome.resumed }+ : { ok: false, error: 'MOVE_FAILED', detail: outcome.reason }+ }, 'move')+ if (outcome) return outcome+ // Another lifecycle operation held the agent: nothing ran, so nothing failed. Anything else counts as a failure.+ const reason = reply.ok ? 'the move did not run' : reply.detail ?? reply.error+ return !reply.ok && reply.error === 'AGENT_BUSY'+ ? { moved: false, reason, fellBack: false, cancelled: true }+ : { moved: false, reason, fellBack: false }+ },+ log: (line) => console.log(line),+ })+ }const guestCreate = createGuestCreate({launch: (input) => (ports.sharedMachines ?? SHARED_MACHINES_OFF).guestLaunch(input),tmuxBackend: () => tmuxBackend, registry, announceSession, watchNewPane,@@ -3041,6 +3171,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {// answered now, in order, by the handlers meant to answer them (see BackendSocket.openRequests).// Only the end-to-end harness sets this: a start-up that hangs after binding, for the master's deadline.if (harnessd.HARNESSD_TEST_HOLD_READY === '1') await new Promise<never>(() => {})+ // A terminal host on probation is judged by this ready: a host whose version answers may still fail to serve (its+ // conpty.dll, its endpoint), and kept, every new pane would fail on it. Not ready until the create backend is attached+ // to the target's host; never, if it cannot be, and the master's ready timeout rolls the host back (lib/ptyHost/drain.ts).+ if (ptyHosts && coreLink.supervised && ptyHostOnProbation(env.ADAPTER_RUNTIME_DIR)) {+ const create = ptyHosts.create+ await untilHostAttached(() => ptyTarget !== null && createBackend === create && create.attached, ptyTarget?.instance ?? null, (line) => console.log(line))+ }backend.openRequests()daemonBoot.openRequests = nullcoreLink.ready()diff --git a/cli/src/core/terminalWatch.spec.ts b/cli/src/core/terminalWatch.spec.tsindex 14849d663..81a785b00 100644--- a/cli/src/core/terminalWatch.spec.ts+++ b/cli/src/core/terminalWatch.spec.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../lib/registry.js'import type { TerminalStreamSink } from '../lib/terminalTypes.js'import type { TerminalStreamManager } from '../lib/terminalStreamManager.js'+import { MoveGate } from '../lib/hostMove/gate.js'import { createTerminalWatch, KEPT_VIEWERS, type TerminalWatchDeps } from './terminalWatch.js'type Manager = ConstructorParameters<typeof TerminalStreamManager>[0]@@ -18,9 +19,12 @@ function manager() {handleFrame: vi.fn(async (viewer: string, type: string, payload: Record<string, unknown>) => { handled.push([viewer, type, payload]); return true }),closeConnection: vi.fn(async (viewer: string) => { closed.push(viewer) }),stop,+ isLookedAt: vi.fn(() => false),+ retarget: vi.fn(async (agentId: string, to: unknown) => { retargeted.push([agentId, to]) }),}}- return { built, handled, closed, stop, make }+ const retargeted: Array<[string, unknown]> = []+ return { built, handled, closed, stop, make, retargeted }}const setup = (over: Partial<TerminalWatchDeps> = {}) => {@@ -39,6 +43,29 @@ const setup = (over: Partial<TerminalWatchDeps> = {}) => {}describe('a read-only view of agents\' terminals', () => {+ it('says whether a viewer has an agent open, and no when nobody ever watched', async () => {+ const quiet = setup()+ expect(quiet.watch.isWatched('agent-1')).toBe(false)+ const lookedAt = vi.fn((id: string) => id === 'agent-1')+ const { watch } = setup({ manager: (() => ({ handleFrame: vi.fn(), closeConnection: vi.fn(), stop: vi.fn(), isLookedAt: lookedAt })) as never })+ await watch.watch.frame('observer:ken', 'terminal_open', { agentId: 'agent-1' })+ expect(watch.isWatched('agent-1')).toBe(true)+ expect(watch.isWatched('agent-2')).toBe(false)+ })++ it('holds its viewers through a move to another host, and moves their streams with the agent', async () => {+ const gate = new MoveGate()+ const { watch, m } = setup({ moveGate: gate })+ const pane = { backend: 'ptyhost', instance: 'p2-1.2.3', paneId: '%7' } as const+ // No viewer yet: nothing to move, and no manager built for it.+ await watch.retarget('agent-1', pane)+ expect(m.built).toHaveLength(0)+ await watch.watch.frame('observer:ken', 'terminal_open', { agentId: 'agent-1' })+ expect(m.built[0]!.moveGate).toBe(gate)+ await watch.retarget('agent-1', pane)+ expect(m.retargeted).toEqual([['agent-1', pane]])+ })+it('builds no stream manager until its first viewer, and a read-only one then', async () => {const { watch, m, agent } = setup()expect(m.built).toHaveLength(0)diff --git a/cli/src/core/terminalWatch.ts b/cli/src/core/terminalWatch.tsindex d0097b728..bb3157965 100644--- a/cli/src/core/terminalWatch.ts+++ b/cli/src/core/terminalWatch.ts@@ -10,8 +10,10 @@* process that sent the viewer's frames (`tell`). A terminal's bytes go as `binary`, base64 of the local* binary frame (lib/terminalBinary.ts `encodeTerminalLocal`), as Share already carried them to its observers.*/+import type { MoveGate } from '../lib/hostMove/gate.js'import type { RegisteredSession } from '../lib/registry.js'import type { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinator.js'+import type { TerminalRuntimeRef } from '../lib/terminalTypes.js'import { encodeTerminalLocal } from '../lib/terminalBinary.js'import { TerminalStreamManager } from '../lib/terminalStreamManager.js'import type { TerminalWatch, TerminalWatchOutput } from './api.js'@@ -28,10 +30,15 @@ export interface TerminalWatchDeps {tell: (service: string, viewer: string, output: TerminalWatchOutput) => boolean/** The processes that may watch: a viewer is only ever an experiment's. */watchers: ReadonlySet<string>+ /** The core's gate for an agent changing host (hostMove/gate.ts): a viewer that opens during a move counts as+ * someone using the agent, and its stream is moved with the agent's others (`retarget`). */+ moveGate?: MoveGate/** Swapped in tests for a manager they can drive. */- manager?: (deps: ConstructorParameters<typeof TerminalStreamManager>[0]) => Pick<TerminalStreamManager, 'handleFrame' | 'closeConnection' | 'stop'>+ manager?: (deps: ConstructorParameters<typeof TerminalStreamManager>[0]) => WatchManager}+type WatchManager = Pick<TerminalStreamManager, 'handleFrame' | 'closeConnection' | 'stop' | 'isLookedAt' | 'retarget'>+const text = (value: unknown): string => (typeof value === 'string' ? value : '')export function createTerminalWatch(deps: TerminalWatchDeps) {@@ -47,13 +54,14 @@ export function createTerminalWatch(deps: TerminalWatchDeps) {}return shown}- let manager: Pick<TerminalStreamManager, 'handleFrame' | 'closeConnection' | 'stop'> | null = null+ let manager: WatchManager | null = null/** Built at the first viewer: a daemon no one shares costs no stream manager. */const streams = () => manager ??= (deps.manager ?? ((d) => new TerminalStreamManager(d)))({readOnly: true,terminals: deps.terminals as TerminalBackendCoordinator,resolveAgent: deps.resolve,streamingAvailable: true,+ ...(deps.moveGate ? { moveGate: deps.moveGate } : {}),sendTarget: (viewer, type, payload) => show(viewer, { type, payload }),sendBinaryTarget: (viewer, frame) => {const bytes = encodeTerminalLocal(frame)@@ -77,6 +85,12 @@ export function createTerminalWatch(deps: TerminalWatchDeps) {/** The watch of the core's own `CoreApi`, for a feature in this process. */watch,+ /** Whether a Share viewer has this agent's terminal open (a viewer is a person, never a `watch: true` reader). */+ isWatched(agentId: string): boolean { return manager?.isLookedAt(agentId) ?? false },++ /** Move the viewers' streams of [agentId] to [to]: the agent changed host (`TerminalStreamManager.retarget`). */+ async retarget(agentId: string, to: TerminalRuntimeRef): Promise<void> { await manager?.retarget(agentId, to) },+/** A process's viewer's frame (`watch_frame`) or its end (`watch_close`): null for any other query. */async answer(service: string, query: string, payload: Payload): Promise<Payload | null> {if (query !== 'watch_frame' && query !== 'watch_close') return nulldiff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.tsindex 9277dd7ac..c45d5278f 100644--- a/cli/src/core/turns/funnel.spec.ts+++ b/cli/src/core/turns/funnel.spec.ts@@ -41,6 +41,19 @@ function setup(engine = 'claude', over: Partial<FunnelDeps> = {}) {describe('the event funnel', () => {afterEach(() => vi.restoreAllMocks())+ it('tells of an agent working on each live turn start and progress, never on its end or a re-read', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const working = vi.fn()+ const { funnel } = setup('claude', { working })+ funnel('s1', [started(), text()])+ expect(working.mock.calls).toEqual([['a1'], ['a1']])+ working.mockClear()+ funnel('s1', [ended()])+ funnel('s1', [started(), text(), ended()], { replay: true })+ funnel('s1', [started(), text(), ended()], { resumed: true })+ expect(working).not.toHaveBeenCalled()+ })+it('offers native observation after client dispatch without letting an observer break the turn', () => {vi.spyOn(console, 'log').mockImplementation(() => {})vi.spyOn(console, 'error').mockImplementation(() => {})diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.tsindex 92b8bfab7..4853f5e07 100644--- a/cli/src/core/turns/funnel.ts+++ b/cli/src/core/turns/funnel.ts@@ -24,7 +24,7 @@ import type { QuestionWatcher } from '../../lib/questionController.js'import type { RegisteredSession } from '../../lib/registry.js'import type { SessionInputController } from '../../lib/sessionInput.js'import { promptLine } from '../../lib/activitySummary.js'-import type { TurnActivity } from '../../lib/turnActivity.js'+import { isProgressEvent, type TurnActivity } from '../../lib/turnActivity.js'type Events = ReturnType<CursorNormalizer['ingest']>type EmitOptions = { resumed?: boolean; replay?: boolean }@@ -62,6 +62,9 @@ export interface FunnelDeps {nativeTurns?: { ingest(agentId: string, events: readonly Events[number][], replay: boolean): void }/** How a consumer outside the core is called ([outsideConsumers]). */outside?: OutsideConsumers+ /** The agent's engine is working now: a live turn start or its progress, never a re-read (the mover's quiet clock,+ * lib/hostMove/quiet.ts). */+ working?: (agentId: string) => void}type OutsideConsumers = (consumer: string, call: () => void) => void@@ -102,7 +105,7 @@ export function outsideConsumers(options: {/** The funnel itself, over what it feeds. */export function funnelFor({bySession, tokenUsage, agentIdFor, turnActivity, isSubagentSession, clients, search, turnStartedAt, prompts, input,- deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, nativeTurns, outside = outsideConsumers(),+ deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, nativeTurns, outside = outsideConsumers(), working,}: FunnelDeps) {return (sessionId: string, events: Events, opts?: EmitOptions): void => {if (!events.length || !bySession(sessionId)?.active) return@@ -112,6 +115,7 @@ export function funnelFor({const agentId = agentIdFor(sessionId)const replay = !!(opts?.resumed || opts?.replay)turnActivity.observe(sessionId, event.type, replay)+ if (!replay && isProgressEvent(event.type)) working?.(agentId)const frame = correlateAgentEvent({ ...event, payload: { ...event.payload, activity: turnActivity.snapshot(sessionId) } }, sessionId, agentId)// A `turn_started` that is not a turn starting NOW — a turn picked back up at attach, or a prompt// re-read from a transcript that was already on disk — says so in the clear, beside `agentId`diff --git a/cli/src/core/updateHandoff.spec.ts b/cli/src/core/updateHandoff.spec.tsindex deed5c0cd..b7402c555 100644--- a/cli/src/core/updateHandoff.spec.ts+++ b/cli/src/core/updateHandoff.spec.ts@@ -36,6 +36,27 @@ describe('the update handoff', () => {])})+ it('settles what must finish first before the teardown, outside its deadline, and goes on when that fails', async () => {+ vi.useFakeTimers()+ let settle!: () => void+ const { handoff, calls } = make({+ beforeTeardown: () => { calls.push('settle the moves'); return new Promise<void>((resolve) => { settle = resolve }) },+ teardownDeadlineMs: 1_000,+ })+ const done = handoff.restartForUpdate('2.0.0', [step(calls, 'the pty host connection')])+ // Longer than the teardown's deadline: that is counted from the teardown, not from here.+ await vi.advanceTimersByTimeAsync(5_000)+ expect(calls).toEqual(['[update] applying 1.0.0 → 2.0.0 — restarting daemon', 'settle the moves'])+ settle()+ await done+ expect(calls.slice(2)).toEqual(['release the pty host connection', '[update] handing 2.0.0 to harnessd', 'exit 75'])+ // Without a master too, after the probe; one that throws is said, and the teardown goes on.+ const other = make({ supervised: false, beforeTeardown: async () => { throw new Error('boom') } })+ await other.handoff.handOver([step(other.calls, 'the backend')])+ expect(other.calls).toContain('[update] the moves did not settle (boom) — handing over all the same')+ expect(other.calls.indexOf('release the backend')).toBeGreaterThan(other.calls.indexOf('probe the master'))+ })+it('under harnessd, tries every step when one throws, and exits for the update all the same (round 40)', async () => {const { handoff, calls } = make()await handoff.restartForUpdate('2.0.0', [diff --git a/cli/src/core/updateHandoff.ts b/cli/src/core/updateHandoff.tsindex 3b3c734d8..dfc8b8e80 100644--- a/cli/src/core/updateHandoff.ts+++ b/cli/src/core/updateHandoff.ts@@ -50,6 +50,10 @@ export interface UpdateHandoffDeps {log(line: string): voiderror(line: string): voidteardownDeadlineMs?: number+ /** What must finish before the teardown starts, outside its deadline and bounded by its own: a host move that holds+ * input, whose held keystrokes the teardown's closed connections would lose (lib/hostMove/mover.ts+ * `settleMovesForHandOver`). */+ beforeTeardown?: () => Promise<void>}export function createUpdateHandoff(deps: UpdateHandoffDeps) {@@ -60,6 +64,7 @@ export function createUpdateHandoff(deps: UpdateHandoffDeps) {/** Every step, in order, each failure said and passed; given up on, all the same, after the deadline. */const releaseAll = async (teardown: readonly TeardownStep[]): Promise<void> => {+ try { await deps.beforeTeardown?.() } catch (error) { deps.error(`[update] the moves did not settle (${message(error)}) — handing over all the same`) }let at = ''const steps = (async () => {for (const [name, release] of teardown) {diff --git a/cli/src/engines/__fixtures__/native-version.golden.json b/cli/src/engines/__fixtures__/native-version.golden.jsonindex da20bb088..3d9389836 100644--- a/cli/src/engines/__fixtures__/native-version.golden.json+++ b/cli/src/engines/__fixtures__/native-version.golden.json@@ -14,11 +14,11 @@"files": [{"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]},@@ -41,7 +41,7 @@},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]},@@ -60,11 +60,11 @@"files": [{"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]},@@ -76,11 +76,11 @@"files": [{"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]},@@ -99,11 +99,11 @@"files": [{"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]},@@ -126,7 +126,7 @@},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]},@@ -145,11 +145,11 @@"files": [{"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]},@@ -161,11 +161,11 @@"files": [{"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"},{"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]}diff --git a/cli/src/engines/__fixtures__/other-hooks.golden.json b/cli/src/engines/__fixtures__/other-hooks.golden.jsonindex 7290565ba..58b81cfa6 100644--- a/cli/src/engines/__fixtures__/other-hooks.golden.json+++ b/cli/src/engines/__fixtures__/other-hooks.golden.json@@ -14,11 +14,11 @@"8f5114f5734c2d24": "{\n \"version\": 1,\n \"note\": \"café ✓\",\n \"hooks\": {\n \"sessionStart\": [\n {\n \"command\": \"foreign-start\"\n },\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"afterFileEdit\": [\n {\n \"command\": \"foreign-edit\"\n }\n ],\n \"beforeSubmitPrompt\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"preToolUse\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"stop\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"sessionEnd\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ]\n }\n}\n","e161f02becaa47e8": "{\"hooks\":{\"sessionStart\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"beforeSubmitPrompt\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"preToolUse\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"stop\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"sessionEnd\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}]},\"version\":1}","d979437596e2baaf": "{\n \"version\": 1,\n \"note\": \"café ✓\",\n \"hooks\": {\n \"sessionStart\": [\n {\n \"command\": \"foreign-start\"\n }\n ],\n \"afterFileEdit\": [\n {\n \"command\": \"foreign-edit\"\n }\n ]\n }\n}\n",- "3e8a328cda5811b7": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.0.0.1:19473) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n",+ "8de376ba3baa5c8f": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.0.0.1:19473) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n","3cd1ae59e87ad8ec": "// someone else's plugin\nexport default {}\n",- "8756d502b15e2eec": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",- "7f06fa281974af31": "// session-register — auto-installed by the machine adapter. Binds this Kilo session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"kilo\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",- "9c54bea8a5b14730": "// session-register — auto-installed by the machine adapter. Binds this Pi session to the local\n// machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\n\nexport default function (pi: ExtensionAPI) {\n let announced = false; // posted at least once (the transcript may not exist yet)\n let registered = false; // posted with a real, on-disk transcript — nothing left to do\n\n const register = async (ctx: any) => {\n const pane = process.env.TMUX_PANE;\n const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\");\n let token = \"\";\n try { token = readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim(); } catch {}\n if ((!pane && !ptyPane) || !token) return;\n // Pi knows the session file path immediately but only WRITES it once the first assistant message\n // lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),\n // so announce without one first and attach the real path on a later turn.\n const file = ctx?.sessionManager?.getSessionFile?.() ?? null;\n const ready = !!file && existsSync(file);\n if (registered || (announced && !ready)) return;\n const sessionId = ctx?.sessionManager?.getSessionId?.();\n if (!sessionId) return;\n try {\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"pi\",\n pluginVersion: \"<version>\",\n sessionId,\n transcriptPath: ready ? file : undefined,\n cwd: ctx?.cwd ?? undefined,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n });\n if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn\n announced = true;\n if (ready) registered = true;\n } catch {}\n };\n\n // session_start fires before the transcript exists; the turn hooks catch it once it does.\n pi.on(\"session_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_end\", async (_event, ctx) => { await register(ctx); });\n}\n",+ "4bfbdceafa84276e": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",+ "8e291cfd70ebba26": "// session-register — auto-installed by the machine adapter. Binds this Kilo session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"kilo\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",+ "e3b07beb0331f78f": "// session-register — auto-installed by the machine adapter. Binds this Pi session to the local\n// machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\n\nexport default function (pi: ExtensionAPI) {\n let announced = false; // posted at least once (the transcript may not exist yet)\n let registered = false; // posted with a real, on-disk transcript — nothing left to do\n\n const register = async (ctx: any) => {\n const pane = process.env.TMUX_PANE;\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\");\n let token = \"\";\n try { token = readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim(); } catch {}\n if ((!pane && !ptyPane) || !token) return;\n // Pi knows the session file path immediately but only WRITES it once the first assistant message\n // lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),\n // so announce without one first and attach the real path on a later turn.\n const file = ctx?.sessionManager?.getSessionFile?.() ?? null;\n const ready = !!file && existsSync(file);\n if (registered || (announced && !ready)) return;\n const sessionId = ctx?.sessionManager?.getSessionId?.();\n if (!sessionId) return;\n try {\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"pi\",\n pluginVersion: \"<version>\",\n sessionId,\n transcriptPath: ready ? file : undefined,\n cwd: ctx?.cwd ?? undefined,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n });\n if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn\n announced = true;\n if (ready) registered = true;\n } catch {}\n };\n\n // session_start fires before the transcript exists; the turn hooks catch it once it does.\n pi.on(\"session_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_end\", async (_event, ctx) => { await register(ctx); });\n}\n","2351a62515202212": "// someone else's extension\nexport default function () {}\n","b97cffdaf15d26d4": "// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local\n// machine daemon (127.0.0.1:19473) and writes the transcript the daemon tails, because Amp keeps none\n// on disk. No-op outside tmux.\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport const description = 'Mirrors this Amp thread to the machine adapter (web + device)'\n\nconst SESSIONS_DIR = \"<root>/home/.harness/cli/data/amp-sessions\"\n\nexport default function (amp: any) {\n const pane = process.env.TMUX_PANE\n if (!pane) return\n\n // NOT `process.cwd()`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports\n // `<project>/.amp/plugins` (measured). `PWD` is inherited from the shell that launched plain Amp.\n const workdir = process.env.PWD || process.cwd()\n\n const emitted = new Set()\n // Turn ids already opened/closed. Amp re-dispatches a message it could not deliver, firing agent.start\n // a SECOND time for the same message id (measured: two identical turn_start records 61s apart, then a\n // turn_end 'done' and a turn_end 'error' for the one turn). Written straight through, that is two turns\n // on web and device and two user bubbles in history.\n const turnsStarted = new Set()\n const turnsEnded = new Set()\n // Tool ids already written, so a tool seen BOTH as an event and as a message block is written once.\n const toolCalls = new Set()\n const toolResults = new Set()\n let registered = false\n let file = ''\n let seeded = false\n\n const line = (record: any) => {\n try {\n mkdirSync(SESSIONS_DIR, { recursive: true, mode: 0o700 })\n appendFileSync(file, JSON.stringify(record) + '\\n')\n } catch {}\n }\n\n const open = (threadId: string) => {\n if (file) return\n file = join(SESSIONS_DIR, threadId + '.jsonl')\n // `cwd` on the first line is what lets the daemon re-find this session by directory after a restart,\n // the same way it reads claude's and pi's transcripts. It must be a top-level string field.\n line({ t: 'session', threadId, cwd: workdir, at: Date.now() })\n }\n\n const register = async (threadId: string) => {\n open(threadId)\n if (registered || !existsSync(file)) return\n try {\n const token = readFileSync(\"<root>/data/hook-credential\", 'utf8').trim()\n if (!token) return\n const res = await fetch('http://127.0.0.1:19473/api/hook/session-start', {\n method: 'POST',\n headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },\n body: JSON.stringify({\n engine: 'amp',\n pluginVersion: \"<version>\",\n sessionId: threadId,\n transcriptPath: file,\n cwd: workdir,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: 'tmux', paneId: pane }] : []),\n ],\n }),\n })\n if (res.ok) registered = true\n } catch {}\n }\n\n const resultId = (block: any) => String(block.toolUseID || block.tool_use_id || '')\n\n /**\n * Write everything in the thread that has not been written yet.\n *\n * This reads message BLOCKS rather than events, because the events do not cover the thread:\n *\n * - no event carries assistant text at all, and\n * - `tool.call`/`tool.result` only fire for tools the CLIENT executes. MEASURED: a `web_search`\n * turn produced no tool event and no tool lease in Amp's own log, yet the message plainly held a\n * `tool_use` block — Amp runs that tool on its server. Skipping blocks meant a search rendered as\n * nothing at all on web and device while the pane showed \"Explored 1 search\".\n *\n * `seed` marks what already exists WITHOUT writing it, for a thread that is being resumed: those\n * messages belong to earlier turns, and replaying them made a fresh turn open with an old answer in it.\n */\n const drain = async (ctx: any) => {\n let messages: any[] = []\n try { messages = await ctx.thread.messages({ from: 'end', limit: 20 }) } catch { return }\n // The FIRST drain of this plugin instance only claims what it finds; it writes nothing. That covers\n // both ways a plugin meets a thread that already has messages: a resumed thread, and a plugin reload\n // (Amp loads a plugin ONCE per process, so reload is how a running pane picks up a new build). Without\n // it, the next prompt replayed the whole recent history as if it had just happened.\n const seed = !seeded\n seeded = true\n // The seed pass would swallow the very prompt the turn needs to open on. Measured: `session.start`\n // does NOT fire when Amp launches — it fires on the first submit, and by then the thread already\n // holds one `user` message. So the seed has to tell history from the live prompt, and the test is\n // whether anything answered it: the LAST user text block with no assistant message after it is\n // waiting, not past. On a resumed thread the last message is an assistant one, so nothing opens.\n let liveUserId = ''\n for (const message of messages) {\n if (message.role === 'assistant') { liveUserId = ''; continue }\n const parts = Array.isArray(message.content) ? message.content : []\n const hasText = parts.some((b: any) => b && b.type === 'text' && typeof b.text === 'string' && b.text)\n if (hasText) liveUserId = String(message.id)\n }\n for (const message of messages) {\n const blocks = Array.isArray(message.content) ? message.content : []\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i]\n if (!block) continue\n if (block.type === 'text' || block.type === 'thinking') {\n const key = String(message.id) + '#' + i\n if (emitted.has(key)) continue\n const text = typeof block.text === 'string' ? block.text : block.thinking\n if (typeof text !== 'string' || !text) continue\n emitted.add(key)\n // A user TEXT block opens the turn.\n //\n // Amp used to announce that with an `agent.start` event, and the handler below wrote\n // `turn_start` from it. That event no longer fires — probed with a plugin that registered for\n // sixteen candidate names on amp 0.0.1786681855 and saw only `session.start`, `tool.call`,\n // `tool.result` and `agent.end`. The prompt now reaches a plugin no earlier than\n // `agent.end`, which is the END of the turn, far too late to open one.\n //\n // So it is taken from the thread instead, where drain was already reading it and dropping it:\n // measured at the first `tool.call` of a turn, `messages()` already returns the prompt, oldest\n // first. Without this the turn opens with an empty question on web and device, and the recap\n // loses what was asked.\n //\n // Only a TEXT block qualifies: a tool_result is also carried on a `user` message, so matching\n // the role alone would open a turn on every tool that returned.\n if (message.role !== 'assistant') {\n const turnId = String(message.id)\n if (turnsStarted.has(turnId)) continue\n turnsStarted.add(turnId)\n if (!seed || turnId === liveUserId) line({ t: 'turn_start', id: turnId, message: text, at: Date.now() })\n continue\n }\n if (!seed) line({ t: block.type, id: message.id, i, text })\n } else if (block.type === 'tool_use') {\n const id = String(block.id || '')\n if (!id || toolCalls.has(id)) continue\n toolCalls.add(id)\n if (!seed) line({ t: 'tool_call', id, tool: block.name, input: block.input })\n } else if (block.type === 'tool_result') {\n const id = resultId(block)\n if (!id || toolResults.has(id)) continue\n toolResults.add(id)\n // A server-run tool puts its payload under `run`; a client-run one under `content`/`output`.\n if (!seed) line({ t: 'tool_result', id, status: 'done', output: block.run ?? block.content ?? block.output })\n }\n }\n }\n }\n\n amp.on('session.start', async (event: any, ctx: any) => {\n await register(event.thread.id)\n await drain(ctx)\n })\n\n amp.on('agent.start', async (event: any, ctx: any) => {\n await register(event.thread.id)\n const id = String(event.id)\n if (!turnsStarted.has(id)) {\n turnsStarted.add(id)\n line({ t: 'turn_start', id: event.id, message: event.message, at: Date.now() })\n }\n await drain(ctx)\n })\n\n amp.on('tool.call', async (event: any, ctx: any) => {\n await register(event.thread.id)\n // CLAIM THE ID FIRST. `drain` runs before this card so a message's prose lands ahead of the tool it\n // called — but by then the tool_use block for THIS tool is already in the thread, so draining without\n // claiming wrote the card twice (measured: one Task turn produced two identical `skill` cards).\n toolCalls.add(String(event.toolUseID))\n await drain(ctx)\n line({ t: 'tool_call', id: event.toolUseID, tool: event.tool, input: event.input })\n })\n\n amp.on('tool.result', async (event: any, ctx: any) => {\n // Same rule as tool.call: claim before draining.\n toolResults.add(String(event.toolUseID))\n line({\n t: 'tool_result',\n id: event.toolUseID,\n tool: event.tool,\n status: event.status,\n output: event.output,\n })\n await drain(ctx)\n })\n\n amp.on('agent.end', async (event: any, ctx: any) => {\n await drain(ctx)\n // `message` is the prompt that STARTED this turn, and agent.end carries it even when\n // agent.start never fired (a prompt queued while Amp was connecting). Recording it here is what\n // lets history still show what was asked — see the replay branch in the normalizer.\n const id = String(event.id)\n if (turnsEnded.has(id)) return\n turnsEnded.add(id)\n line({ t: 'turn_end', id: event.id, status: event.status, message: event.message, at: Date.now() })\n })\n}\n","f2535bcde1fe8de5": "// someone else's plugin\nexport default function () {}\n",@@ -1037,7 +1037,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1077,7 +1077,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1117,7 +1117,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1157,7 +1157,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1197,7 +1197,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1237,7 +1237,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1277,7 +1277,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1317,7 +1317,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1357,7 +1357,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1397,7 +1397,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1437,7 +1437,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1477,7 +1477,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1517,7 +1517,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1557,7 +1557,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1597,7 +1597,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1636,7 +1636,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1676,7 +1676,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1716,7 +1716,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1756,7 +1756,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"},"elsewhere/real": {"type": "file",@@ -1804,7 +1804,7 @@"elsewhere/real": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1844,7 +1844,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1884,7 +1884,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1924,7 +1924,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -1963,7 +1963,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "444",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2003,7 +2003,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2116,7 +2116,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2159,7 +2159,7 @@"home/.config/opencode/plugins/launcher-register/tui.js.<pid>.tmp": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2199,7 +2199,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "600",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2238,7 +2238,7 @@"home/.config/opencode/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "8756d502b15e2eec"+ "text": "4bfbdceafa84276e"},"home/.config/opencode/plugins": {"type": "dir",@@ -2251,7 +2251,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2289,7 +2289,7 @@"home/.config/opencode/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "8756d502b15e2eec"+ "text": "4bfbdceafa84276e"},"home/.config/opencode/plugins": {"type": "dir",@@ -2302,7 +2302,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2342,7 +2342,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2387,7 +2387,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2436,7 +2436,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2486,7 +2486,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "3e8a328cda5811b7"+ "text": "8de376ba3baa5c8f"}}},@@ -2522,7 +2522,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2558,7 +2558,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2594,7 +2594,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2630,7 +2630,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2666,7 +2666,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2702,7 +2702,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2738,7 +2738,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2774,7 +2774,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2810,7 +2810,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2846,7 +2846,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2882,7 +2882,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2918,7 +2918,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2954,7 +2954,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -2990,7 +2990,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3026,7 +3026,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3061,7 +3061,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3097,7 +3097,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3133,7 +3133,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3169,7 +3169,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"},"elsewhere/real": {"type": "file",@@ -3213,7 +3213,7 @@"elsewhere/real": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3249,7 +3249,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3285,7 +3285,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3321,7 +3321,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3356,7 +3356,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "444",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3392,7 +3392,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3493,7 +3493,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3532,7 +3532,7 @@"home/.config/kilo/plugin/launcher-register.js.<pid>.tmp": {"type": "file","mode": "644",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3568,7 +3568,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "600",- "text": "7f06fa281974af31"+ "text": "8e291cfd70ebba26"}}},@@ -3604,7 +3604,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3640,7 +3640,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3676,7 +3676,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3712,7 +3712,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3748,7 +3748,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3784,7 +3784,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3820,7 +3820,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3856,7 +3856,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3892,7 +3892,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3928,7 +3928,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -3964,7 +3964,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4000,7 +4000,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4036,7 +4036,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4072,7 +4072,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4108,7 +4108,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4143,7 +4143,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4179,7 +4179,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4215,7 +4215,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4251,7 +4251,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"},"elsewhere/real": {"type": "file",@@ -4295,7 +4295,7 @@"elsewhere/real": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4331,7 +4331,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4367,7 +4367,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4403,7 +4403,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4438,7 +4438,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "444",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4474,7 +4474,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4575,7 +4575,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4614,7 +4614,7 @@"home/.pi/agent/extensions/launcher-register.ts.<pid>.tmp": {"type": "file","mode": "644",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},@@ -4650,7 +4650,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "600",- "text": "9c54bea8a5b14730"+ "text": "e3b07beb0331f78f"}}},diff --git a/cli/src/engines/kilo/contract.ts b/cli/src/engines/kilo/contract.tsindex 722622ade..5ef7a9723 100644--- a/cli/src/engines/kilo/contract.ts+++ b/cli/src/engines/kilo/contract.ts@@ -29,7 +29,7 @@ export const MachineRegister = async ({ directory, worktree, project, client })const post = async (sessionID) => {const pane = process.env.TMUX_PANE// A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.- const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "")+ const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "")const token = hookToken()if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) returnseen.add(sessionID)diff --git a/cli/src/engines/opencode/contract.ts b/cli/src/engines/opencode/contract.tsindex 495aecf62..89c4d9641 100644--- a/cli/src/engines/opencode/contract.ts+++ b/cli/src/engines/opencode/contract.ts@@ -69,7 +69,7 @@ export const MachineRegister = async ({ directory, worktree, project, client })const post = async (sessionID) => {const pane = process.env.TMUX_PANE// A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.- const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "")+ const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "")const token = hookToken()if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) returnseen.add(sessionID)@@ -138,7 +138,7 @@ export default {id: "harness-session-register",setup(ctx) {const pane = process.env.TMUX_PANE- const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "")+ const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "")const router = ctx && ctx.ui && ctx.ui.routerif ((!pane && !ptyPane) || !router || typeof router.current !== "function") returnconst posted = new Set()diff --git a/cli/src/engines/pi/contract.ts b/cli/src/engines/pi/contract.tsindex 5deadc2fd..c25a92b02 100644--- a/cli/src/engines/pi/contract.ts+++ b/cli/src/engines/pi/contract.ts@@ -35,7 +35,7 @@ export default function (pi: ExtensionAPI) {const register = async (ctx: any) => {const pane = process.env.TMUX_PANE;- const ptyPane = pane ? null : /^(p\\d{1,4}):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "");+ const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || "");let token = "";try { token = readFileSync(`,{ argument: 'credential' },diff --git a/cli/src/engines/pluginPaneHints.spec.ts b/cli/src/engines/pluginPaneHints.spec.tsindex 6961410bd..91830464d 100644--- a/cli/src/engines/pluginPaneHints.spec.ts+++ b/cli/src/engines/pluginPaneHints.spec.ts@@ -55,6 +55,32 @@ describe('a plugin in a Harness pty host pane (Windows)', () => {expect(posted()).toMatchObject({ sessionId: 'pi-1', runtimeHints: PTY_HINT })})+ it.each([+ [KILO_PLUGIN, 'kilo-v.mjs', 'p2-0.4.21-dev.win1'], [OPENCODE_LEGACY_PLUGIN, 'opencode-v.mjs', 'p2-h0123456789ab'],+ ] as const)('posts a versioned pty host\'s pane by HARNESS_PANE: %#', async (rule, name, instance) => {+ vi.stubEnv('HARNESS_PANE', `${instance}:%7`)+ const plugin = await load(rule, name)+ const hooks = await plugin.MachineRegister({ directory: '/work' })+ await hooks.event({ event: { type: 'session.created', properties: { info: { id: 'ses_v' } } } })+ expect(posted()).toMatchObject({ sessionId: 'ses_v', runtimeHints: [{ backend: 'ptyhost', instance, paneId: '%7' }] })+ })++ it('posts the OpenCode 2 TUI and Pi sessions of a versioned pty host\'s pane', async () => {+ vi.stubEnv('HARNESS_PANE', 'p2-0.4.21-dev.win1:%7')+ const hint = [{ backend: 'ptyhost', instance: 'p2-0.4.21-dev.win1', paneId: '%7' }]+ const tui = await load(OPENCODE_TUI_PLUGIN, 'tui-v.mjs')+ const stop = tui.default.setup({ ui: { router: { current: () => ({ type: 'session', sessionID: 'ses_4' }) } }, data: { session: { get: async () => ({}) } } })+ await vi.waitFor(() => expect(fetch).toHaveBeenCalled())+ stop?.()+ expect(posted()).toMatchObject({ sessionId: 'ses_4', runtimeHints: hint })+ fetch.mockClear()+ const pi = await load(PI_EXTENSION, 'pi-v.ts')+ const handlers: Record<string, (event: unknown, ctx: unknown) => Promise<void>> = {}+ pi.default({ on: (event: string, run: (event: unknown, ctx: unknown) => Promise<void>) => { handlers[event] = run } })+ await handlers.session_start({}, { sessionManager: { getSessionFile: () => null, getSessionId: () => 'pi-2' }, cwd: '/work' })+ expect(posted()).toMatchObject({ sessionId: 'pi-2', runtimeHints: hint })+ })+it('still posts a tmux pane by TMUX_PANE alone', async () => {vi.stubEnv('TMUX_PANE', '%7')const plugin = await load(KILO_PLUGIN, 'kilo-tmux.mjs')diff --git a/cli/src/harnessd/AGENTS.md b/cli/src/harnessd/AGENTS.mdindex 8fe3402b1..4f2720a36 100644--- a/cli/src/harnessd/AGENTS.md+++ b/cli/src/harnessd/AGENTS.md@@ -49,7 +49,10 @@ It keeps the core and the services running, and nothing else.9. **Updates are the master's to run, never the core's.** The updater runs in a process the master starts(`UPDATER_HOST`, `../services/updaterProcess.ts`): it downloads, verifies, canaries and stages a build,then says so (`harnessd:staged`); the master asks the core to hand over (`harnessd:update`) and judges- the new core on probation, as before. Only the updater's process (`UPDATER_PROCESS`) can start this, or+ the new core on probation, as before. On Windows it stages a terminal host payload too (`ptyVersion`,+ only under a master that sets `HARNESSD_JUDGES_PTY`), and the same probation rolls back or keeps both+ (`../lib/windows/ptyUpdate.ts`). A build that needs a host protocol above the installed host's is staged+ only with a payload of that protocol, the host first, in one handover (spec §5's protocol and pairing rules). Only the updater's process (`UPDATER_PROCESS`) can start this, orexit 75 to be restarted at once. From any other service, `harnessd:staged` is logged once and ignored,and exit 75 counts as a crash. The master itself still makes no network call. Every core thismaster starts hears `HARNESSD_UPDATES=master`; a core under a master from before that runs the updaterdiff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.tsindex d04172375..a7e75a6c9 100644--- a/cli/src/harnessd/master.spec.ts+++ b/cli/src/harnessd/master.spec.ts@@ -531,6 +531,7 @@ describe('runMaster', { timeout: 60_000 }, () => {process.send({ type: 'harnessd:bound', protocol: 3, port: 1 }); process.send({ type: 'harnessd:ready' })process.on('message', (message) => { if (message.type === 'harnessd:update') { say('asked for ' + message.version); process.exit(75) } })}+ if (role === 'service:updater') say('judges pty ' + process.env.HARNESSD_JUDGES_PTY)if (role === 'service:updater' && process.env.HARNESSD_RESTARTS === '0') setTimeout(() => process.send({ type: 'harnessd:staged', version: '9.9.9' }), 100)setInterval(() => process.send({ type: 'harnessd:heartbeat', rssBytes: 1, heapUsedBytes: 1, loopDelayMs: 0 }), 50)process.on('SIGTERM', () => process.exit(0))@@ -548,8 +549,10 @@ describe('runMaster', { timeout: 60_000 }, () => {})const said = (): Array<Record<string, string>> => jsonLines(seen)await until('the core to hand over and a new one to start', () => said().filter((line) => line.role === '__run' && line.what === 'started').length === 2)- expect(said().filter((line) => line.role.startsWith('service:')).map((line) => line.role)).toEqual(['service:updater'])+ expect(said().filter((line) => line.role.startsWith('service:') && line.what === 'started').map((line) => line.role)).toEqual(['service:updater'])expect(said()).toContainEqual({ role: '__run', what: 'asked for 9.9.9', restarts: '0' })+ // The updater hears that this master judges a terminal host it stages (Windows).+ expect(said()).toContainEqual({ role: 'service:updater', what: 'judges pty 1', restarts: '0' })expect(lines.some((line) => line.endsWith('[harnessd] the updater staged 9.9.9 — asking the core to hand over'))).toBe(true)expect(lines.some((line) => line.endsWith('[harnessd] core exited (code 75) for an update — restarting'))).toBe(true)signals.get('SIGTERM')!()diff --git a/cli/src/harnessd/master.ts b/cli/src/harnessd/master.tsindex 837ec6bde..951fccb67 100644--- a/cli/src/harnessd/master.ts+++ b/cli/src/harnessd/master.ts@@ -382,9 +382,11 @@ export function runMaster(config: MasterConfig): Supervisor {setTimer: (run, ms) => setTimeout(run, ms),clearTimer: (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),log,- // The updater staged a build: the core is asked to hand over for it, and the new core judged.- staged: (version) => supervisor?.updateStaged(version),- }, serviceOptions(env), { HARNESSD_SERVICE_TOKEN: token })+ // The updater staged a build, a terminal host or both: the core is asked to hand over, and the new core judged.+ staged: (staged) => supervisor?.updateStaged(staged),+ // HARNESSD_JUDGES_PTY: this master takes a terminal host's staging and judges it on its probation (Windows,+ // services/updaterProcess.ts). An updater under a master from before stages no host: no one would roll it back.+ }, serviceOptions(env), { HARNESSD_SERVICE_TOKEN: token, HARNESSD_JUDGES_PTY: '1' })// The pid file is this master's to remove as it ends: the supervisor says so once it claimed it, and so does a claim// as this master hands over (Windows), which the supervisor does not know of.let releaseOnExit = falsediff --git a/cli/src/harnessd/protocol.spec.ts b/cli/src/harnessd/protocol.spec.tsindex eb6e899e8..a0377592a 100644--- a/cli/src/harnessd/protocol.spec.ts+++ b/cli/src/harnessd/protocol.spec.ts@@ -47,8 +47,15 @@ describe('the spawn channel protocol', () => {it.each([[{ type: 'harnessd:staged', version: '1.2.3' }, true],+ [{ type: 'harnessd:staged', ptyVersion: '0.11.0' }, true],+ [{ type: 'harnessd:staged', version: '1.2.3', ptyVersion: '0.11.0' }, true],+ [{ type: 'harnessd:staged', version: '', ptyVersion: '0.11.0' }, true],+ [{ type: 'harnessd:staged' }, false],+ [{ type: 'harnessd:staged', version: '', ptyVersion: '' }, false],[{ type: 'harnessd:staged', version: '' }, false],[{ type: 'harnessd:staged', version: 3 }, false],+ [{ type: 'harnessd:staged', ptyVersion: 3 }, false],+ [{ type: 'harnessd:staged', version: 3, ptyVersion: '0.11.0' }, false],[{ type: 'harnessd:heartbeat', rssBytes: 1, heapUsedBytes: 1 }, false],[null, false],['harnessd:staged', false],diff --git a/cli/src/harnessd/protocol.ts b/cli/src/harnessd/protocol.tsindex 8c28971c2..795e07942 100644--- a/cli/src/harnessd/protocol.ts+++ b/cli/src/harnessd/protocol.ts@@ -89,8 +89,17 @@ export type MasterMessage =* from before ignores it, and is ended once its grace is over, as one that ignored SIGTERM was. */| { type: 'harnessd:shutdown' }-/** What the updater says to the master: it staged `version` on disk. */-export type UpdaterMessage = { type: 'harnessd:staged'; version: string }+/** What the updater says to the master: it staged CLI build `version`, terminal host `ptyVersion` (Windows), or both,+ * on disk, for one handover. At least one of the two is there. A master from before takes only `version`. */+export type UpdaterMessage = { type: 'harnessd:staged'; version?: string; ptyVersion?: string }++/** What one `harnessd:staged` staged, with each part there only when it was. */+export interface StagedUpdate { version?: string; ptyVersion?: string }++/** `9.9.9`, `terminal host 0.11.0`, or `9.9.9 and terminal host 0.11.0`: what a log line says was staged. */+export function describeStaged(staged: StagedUpdate): string {+ return [staged.version, staged.ptyVersion && `terminal host ${staged.ptyVersion}`].filter(Boolean).join(' and ')+}/** The exit code a service uses to be started again at once, on the bundle now on disk, without counting* as a crash: the updater, once it has staged a build, so that it next runs as that build. */@@ -99,7 +108,9 @@ export const SERVICE_EXIT_RESTART = 75export function isUpdaterMessage(value: unknown): value is UpdaterMessage {if (!value || typeof value !== 'object') return falseconst message = value as Record<string, unknown>- return message.type === 'harnessd:staged' && typeof message.version === 'string' && message.version.length > 0+ if (message.type !== 'harnessd:staged') return false+ const parts = [message.version, message.ptyVersion]+ return parts.every((part) => part === undefined || typeof part === 'string') && parts.some((part) => typeof part === 'string' && part.length > 0)}export function isCoreMessage(value: unknown): value is CoreMessage {diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.tsindex 939baaa79..d610414a4 100644--- a/cli/src/harnessd/services.spec.ts+++ b/cli/src/harnessd/services.spec.ts@@ -41,10 +41,10 @@ describe('ServiceSupervisor', () => {let children: FakeService[]let lines: string[]const latest = (name = 'search') => children.filter((child) => child.spec.name === name).at(-1)!- const staged: string[] = []+ const staged: Array<{ version?: string; ptyVersion?: string }> = []const make = (specs: ServiceSpec[] = [search], overrides: Partial<ServiceSupervisorOptions> = {}, env: Record<string, string> = {}, tell = true, more: Partial<ServiceSupervisorDeps> = {}) =>new ServiceSupervisor(specs, {- ...(tell ? { staged: (version: string) => { staged.push(version) } } : {}),+ ...(tell ? { staged: (what: { version?: string; ptyVersion?: string }) => { staged.push(what) } } : {}),spawnService: (spec, extra) => {const child = new FakeService(2000 + children.length, spec, extra)children.push(child)@@ -99,8 +99,15 @@ describe('ServiceSupervisor', () => {supervisor.start()latest('updater').beat()latest('updater').say({ type: 'harnessd:staged', version: '9.9.9' })- expect(staged).toEqual(['9.9.9'])+ expect(staged).toEqual([{ version: '9.9.9' }])expect(lines).toContain('[harnessd] service updater staged 9.9.9')+ // A terminal host (Windows), alone or with a build.+ latest('updater').say({ type: 'harnessd:staged', ptyVersion: '0.11.0' })+ latest('updater').say({ type: 'harnessd:staged', version: '9.9.9', ptyVersion: '0.11.0' })+ expect(staged.slice(1)).toEqual([{ ptyVersion: '0.11.0' }, { version: '9.9.9', ptyVersion: '0.11.0' }])+ expect(lines).toContain('[harnessd] service updater staged terminal host 0.11.0')+ expect(lines).toContain('[harnessd] service updater staged 9.9.9 and terminal host 0.11.0')+ staged.length = 1for (let i = 0; i < 3; i++) {latest('updater').exit(75)vi.advanceTimersByTime(0)@@ -117,7 +124,7 @@ describe('ServiceSupervisor', () => {const quiet = make([updater], {}, {}, false)quiet.start()latest('updater').say({ type: 'harnessd:staged', version: '9.9.10' })- expect(staged).toEqual(['9.9.9'])+ expect(staged).toEqual([{ version: '9.9.9' }])})it('takes a staged build, or a request to start again at once, from the updater alone', () => {diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 5c4150da6..4816bf9b9 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -12,7 +12,7 @@* bind and no update to prove; it beats, or it is restarted. Everything that touches the operating* system is injected, so every decision here is tested without one.*/-import { SERVICE_EXIT_RESTART, heartbeatGraceMs, isCoreMessage, isUpdaterMessage } from './protocol.js'+import { SERVICE_EXIT_RESTART, describeStaged, heartbeatGraceMs, isCoreMessage, isUpdaterMessage, type StagedUpdate } from './protocol.js'import { describeExit, type CoreHandle } from './supervisor.js'export interface ServiceSpec {@@ -42,8 +42,8 @@ export interface ServiceSupervisorDeps {setTimer(run: () => void, ms: number): unknownclearTimer(timer: unknown): voidlog(line: string): void- /** The updater staged `version` on disk (`harnessd:staged`): the core is to hand over for it. */- staged?(version: string): void+ /** The updater staged a CLI build, a terminal host or both on disk (`harnessd:staged`): the core is to hand over. */+ staged?(staged: StagedUpdate): void/** Stop a service with `harnessd:shutdown` rather than SIGTERM: Windows, where Node's `kill` is TerminateProcess* and the service's own stop never runs (./supervisor.ts `SupervisorDeps.stopByMessage`). */stopByMessage?: boolean@@ -190,9 +190,12 @@ class Service {private onMessage(child: CoreHandle, message: unknown): void {if (isUpdaterMessage(message)) {// It restarts the core: from any other service than the updater, a bug or worse, said once and ignored.- if (this.spec.name !== UPDATER_PROCESS) { if (!this.refusedStaged) this.deps.log(`[harnessd] service ${this.spec.name} said it staged ${message.version}, which only the updater may — ignored`); this.refusedStaged = true; return }- this.deps.log(`[harnessd] service ${this.spec.name} staged ${message.version}`)- this.deps.staged?.(message.version)+ const staged: StagedUpdate = {+ ...(message.version ? { version: message.version } : {}), ...(message.ptyVersion ? { ptyVersion: message.ptyVersion } : {}),+ }+ if (this.spec.name !== UPDATER_PROCESS) { if (!this.refusedStaged) this.deps.log(`[harnessd] service ${this.spec.name} said it staged ${describeStaged(staged)}, which only the updater may — ignored`); this.refusedStaged = true; return }+ this.deps.log(`[harnessd] service ${this.spec.name} staged ${describeStaged(staged)}`)+ this.deps.staged?.(staged)return}if (!isCoreMessage(message) || message.type !== 'harnessd:heartbeat') returndiff --git a/cli/src/harnessd/supervisor.spec.ts b/cli/src/harnessd/supervisor.spec.tsindex a2e0d0349..3417635e9 100644--- a/cli/src/harnessd/supervisor.spec.ts+++ b/cli/src/harnessd/supervisor.spec.ts@@ -4,6 +4,8 @@ import {DEFAULT_SUPERVISOR_OPTIONS, HAND_OVER_GRACE_MS, Supervisor, describeExit, namesTheDisk, type CoreHandle, type ReexecOutcome, type ResumeState, type SupervisorDeps, type SupervisorOptions,type SupervisorStatus,} from './supervisor.js'+import type { PtyRestore } from '../lib/windows/ptyInstall.js'+import { keepStaged, rollBackStaged } from '../lib/windows/ptyUpdate.js'const MIB = 1024 * 1024@@ -410,8 +412,8 @@ describe('Supervisor', () => {const supervisor = make()supervisor.start()core().up()- supervisor.updateStaged('9.9.9')- supervisor.updateStaged('9.9.9')+ supervisor.updateStaged({ version: '9.9.9' })+ supervisor.updateStaged({ version: '9.9.9' })expect(core().sent.filter((message) => message.type === 'harnessd:update')).toEqual([{ type: 'harnessd:update', version: '9.9.9' }])expect(lines.at(-1)).toBe('[harnessd] the updater staged 9.9.9 — asking the core to hand over')core().exit(CORE_EXIT_UPDATE)@@ -429,7 +431,7 @@ describe('Supervisor', () => {const supervisor = make()supervisor.start()core().up()- supervisor.updateStaged('9.9.9')+ supervisor.updateStaged({ version: '9.9.9' })live(HAND_OVER_GRACE_MS - 1_000)expect(core().kills).toEqual([])live(1_000)@@ -452,7 +454,7 @@ describe('Supervisor', () => {expect(core().env.HARNESSD_SAFE_MODE).toBe('crash-loop')core().exit(1)expect(supervisor.status().state).toBe('restarting')- supervisor.updateStaged('9.9.9')+ supervisor.updateStaged({ version: '9.9.9' })expect(lines.at(-1)).toBe('[harnessd] the updater staged 9.9.9 — the next core starts on it')vi.advanceTimersByTime(0)expect(core().env.HARNESSD_SAFE_MODE).toBeUndefined()@@ -465,7 +467,7 @@ describe('Supervisor', () => {it('judges the first core when a build is staged before the master starts one', () => {const supervisor = make()- supervisor.updateStaged('9.9.9')+ supervisor.updateStaged({ version: '9.9.9' })expect(cores).toHaveLength(0)supervisor.start()core().up()@@ -478,7 +480,7 @@ describe('Supervisor', () => {const supervisor = make({}, { reexec: (_state, proceed) => { deciding.push(proceed) } })supervisor.start()expect(cores).toHaveLength(0)- supervisor.updateStaged('9.9.9')+ supervisor.updateStaged({ version: '9.9.9' })expect(cores).toHaveLength(0)deciding[0]('kept')expect(cores).toHaveLength(1)@@ -488,9 +490,88 @@ describe('Supervisor', () => {expect(calls).toContain('restore')supervisor.stop('stopping')const before = lines.length- supervisor.updateStaged('9.9.10')+ supervisor.updateStaged({ version: '9.9.10' })expect(lines.length).toBe(before)})++ it('a PTY-only staging hands over and goes on probation', () => {+ const supervisor = make()+ supervisor.start()+ core().up()+ supervisor.updateStaged({ ptyVersion: '0.11.0' })+ // A core of any version hands over for it: the message names the host where a build would be.+ expect(core().sent.filter((message) => message.type === 'harnessd:update')).toEqual([{ type: 'harnessd:update', version: 'terminal host 0.11.0' }])+ expect(lines.at(-1)).toBe('[harnessd] the updater staged terminal host 0.11.0 — asking the core to hand over')+ core().exit(CORE_EXIT_UPDATE)+ vi.advanceTimersByTime(0)+ expect(cores).toHaveLength(2)+ core().up()+ core().exit(1)+ vi.advanceTimersByTime(0)+ expect(calls).toContain('restore')+ // Both, named in one line.+ make().updateStaged({ version: '9.9.9', ptyVersion: '0.11.0' })+ expect(lines.at(-1)).toBe('[harnessd] the updater staged 9.9.9 and terminal host 0.11.0 — the next core starts on it')+ })++ it('a PTY staged while a build is on probation supersedes it: neither is rolled back or kept yet', () => {+ const supervisor = make()+ supervisor.start()+ core().up()+ supervisor.updateStaged({ version: '9.9.9' })+ core().exit(CORE_EXIT_UPDATE)+ vi.advanceTimersByTime(0)+ core().up()+ // On probation, its updater (restarted on the new build) stages a host: the same bundle on disk.+ supervisor.updateStaged({ ptyVersion: '0.11.0' })+ live(options.updateProbationMs)+ expect(calls).not.toContain('confirm')+ core().exit(CORE_EXIT_UPDATE)+ vi.advanceTimersByTime(0)+ expect(calls).not.toContain('restore')+ expect(lines).toContain('[harnessd] the updated core staged a newer build before it was kept (code 75) — restarting onto that one')+ core().up()+ live(options.updateProbationMs)+ expect(calls.filter((call) => call === 'confirm')).toHaveLength(1)+ })++ describe('with the master\'s own rollback and keep (lib/windows/ptyUpdate.ts)', () => {+ const pending = { version: '0.11.0', previous: '0.10.0' }+ const restore = (restorePty: () => PtyRestore) => () => rollBackStaged({+ cliPending: () => false, restoreCli: () => calls.push('restore cli'), ptyRoot: '/root', log: (line) => lines.push(line),+ restorePty: () => { calls.push('restore pty'); return restorePty() }, readPending: () => pending,+ })++ it('a failed probation with only a PTY pending restores the PTY and not the CLI', () => {+ const supervisor = make({}, { restoreUpdate: restore(() => ({ found: true, pointer: true, restored: ['harness.exe', 'harness-launch.exe'], kept: [], missing: [] })) })+ supervisor.start()+ core().up()+ supervisor.updateStaged({ ptyVersion: '0.11.0' })+ core().exit(CORE_EXIT_UPDATE)+ vi.advanceTimersByTime(0)+ core().up()+ core().exit(1)+ vi.advanceTimersByTime(0)+ expect(calls).toContain('restore pty')+ expect(calls).not.toContain('restore cli')+ expect(lines).toContain('[harnessd] terminal host 0.11.0 did not come back healthy — back to 0.10.0')+ })++ it('a kept probation confirms both', () => {+ const supervisor = make({}, {+ confirmUpdate: () => keepStaged({ confirmCli: () => calls.push('confirm cli'), ptyRoot: '/root', confirmPty: () => { calls.push('confirm pty') } }),+ })+ supervisor.start()+ core().up()+ supervisor.updateStaged({ version: '9.9.9', ptyVersion: '0.11.0' })+ expect(core().sent.filter((message) => message.type === 'harnessd:update')).toEqual([{ type: 'harnessd:update', version: '9.9.9' }])+ core().exit(CORE_EXIT_UPDATE)+ vi.advanceTimersByTime(0)+ core().up()+ live(options.updateProbationMs)+ expect(calls.filter((call) => call.startsWith('confirm'))).toEqual(['confirm cli', 'confirm pty'])+ })+ })})it('stops the core and itself on request, and kills the core on a second request', () => {diff --git a/cli/src/harnessd/supervisor.ts b/cli/src/harnessd/supervisor.tsindex 371b1cc1c..86f55ba89 100644--- a/cli/src/harnessd/supervisor.ts+++ b/cli/src/harnessd/supervisor.ts@@ -14,10 +14,12 @@ import {CORE_EXIT_STOP,CORE_EXIT_UPDATE,HARNESSD_PROTOCOL,+ describeStaged,heartbeatGraceMs,isCoreMessage,type CoreMessage,type MasterMessage,+ type StagedUpdate,} from './protocol.js'export interface CoreHandle {@@ -264,6 +266,8 @@ export class Supervisor {private unproven = 0/** The bundle on disk when the running core was started (`deps.bundle`). */private spawnedOn: string | null = null+ /** The updater staged a terminal host while the running core ran (`updateStaged`). */+ private ptyStagedSinceSpawn = falseconstructor(private readonly deps: SupervisorDeps,@@ -341,27 +345,34 @@ export class Supervisor {}/**- * The updater (services/updaterProcess.ts) staged `version` on disk. The core used to stage it itself- * and exit 75; now the master asks it to (`harnessd:update`), and its exit is the update's, judged as- * before. A core that does not leave within `HAND_OVER_GRACE_MS` is stopped, and that exit counts as the- * update's too. With no core running (a restart's backoff, safe mode's), the next one starts on the new- * bundle at once, on probation, with a clean slate: whatever was crashing may be what it fixes.+ * The updater (services/updaterProcess.ts) staged a CLI build, a terminal host (Windows) or both on disk.+ * The core used to stage a build itself and exit 75; now the master asks it to (`harnessd:update`), and its+ * exit is the update's, judged as before: one probation for whatever was staged, which the master's own+ * rollback and keep cover both of (lib/windows/ptyUpdate.ts `rollBackStaged`, `keepStaged`). A core that+ * does not leave within `HAND_OVER_GRACE_MS` is stopped, and that exit counts as the update's too. With no+ * core running (a restart's backoff, safe mode's), the next one starts on the new bundle at once, on+ * probation, with a clean slate: whatever was crashing may be what it fixes.*/- updateStaged(version: string): void {+ updateStaged(staged: StagedUpdate): void {if (this.state === 'stopping' || this.state === 'stopped') return+ const what = describeStaged(staged)const core = this.coreif (!core) {this.update = 'pending'this.crashes = []this.safeMode = null- this.deps.log(`[harnessd] the updater staged ${version} — the next core starts on it`)+ this.deps.log(`[harnessd] the updater staged ${what} — the next core starts on it`)// Waiting out a backoff: no longer. Otherwise the next core is already being started (a// re-execution deciding), and starts on the bundle on disk.if (this.restartTimer !== null) this.scheduleSpawn(0)return}+ if (staged.ptyVersion) this.ptyStagedSinceSpawn = trueif (this.handOverTimer !== null) return- this.deps.log(`[harnessd] the updater staged ${version} — asking the core to hand over`)+ this.deps.log(`[harnessd] the updater staged ${what} — asking the core to hand over`)+ // A core of any version takes the message only with a version, which it says in its log: for a host alone, the+ // host's, named as one.+ const version = staged.version ?? whatcore.send({ type: 'harnessd:update', version })this.armTimer('handOverTimer', () => {this.handOverTimer = null@@ -418,6 +429,7 @@ export class Supervisor {if (this.lastExit) env.HARNESSD_LAST_EXIT = this.lastExitif (this.safeMode) env.HARNESSD_SAFE_MODE = this.safeModethis.spawnedOn = this.deps.bundle?.() ?? null+ this.ptyStagedSinceSpawn = falseconst core = this.deps.spawnCore(env)this.core = corecore.onMessage((message) => { if (this.core === core && isCoreMessage(message)) this.onMessage(core, message) })@@ -615,8 +627,10 @@ export class Supervisor {this.scheduleSpawn(delay)}- /** Whether the bundle on disk changed since the running core was started (`deps.bundle`). */+ /** Whether something newer was staged since the running core was started: the bundle on disk changed+ * (`deps.bundle`), or the updater staged a terminal host, which leaves the bundle as it was. */private stagedSinceSpawn(): boolean {+ if (this.ptyStagedSinceSpawn) return trueconst now = this.deps.bundle?.() ?? nullreturn now !== null && now !== this.spawnedOn}diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 926a5125d..ddfc8d28f 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -1914,6 +1914,12 @@ describe('hook notify in a Harness pty host pane (Windows)', () => {expect(requests[0].body.tmuxPane).toBeUndefined()})+ it.each(['p2-0.4.21-dev.win1', 'p2-h0123456789ab'])('names a versioned pty host\'s pane by HARNESS_PANE: %s', async (instance) => {+ const { port, requests } = await collect()+ await runHook({ port, env: { HARNESS_PANE: `${instance}:%7` }, input: sessionStart() })+ expect(requests[0].body.runtimeHints).toEqual([{ backend: 'ptyhost', instance, paneId: '%7' }])+ })+it('keeps naming a tmux pane by TMUX_PANE, and ignores a HARNESS_PANE that is not one', async () => {const { port, requests } = await collect()await runHook({ port, tmuxPane: '%42', env: { HARNESS_PANE: 'p3:%1007' }, input: sessionStart() })@@ -1921,6 +1927,9 @@ describe('hook notify in a Harness pty host pane (Windows)', () => {const bad = await collect()await runHook({ port: bad.port, env: { HARNESS_PANE: 'p3:1007' }, input: sessionStart() })expect(bad.requests).toEqual([])+ const odd = await collect()+ await runHook({ port: odd.port, env: { HARNESS_PANE: 'p2-0.4.21 x:%7' }, input: sessionStart() })+ expect(odd.requests).toEqual([])const empty = await collect()await runHook({ port: empty.port, env: { HARNESS_PANE: '' }, input: sessionStart() })expect(empty.requests).toEqual([])diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex daadb555d..b10883163 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -170,6 +170,17 @@ describe('process-owned hook server', () => {})})+ it.each(['p2-0.4.21-dev.win1', 'p2-h0123456789ab'])('resolves a hook from a versioned pty host\'s pane by its instance: %s', async (instance) => {+ const resolveHookAgent = vi.fn(async () => null)+ const { base, headers } = await start({ resolveHookAgent })+ const runtimeHints = [{ backend: 'ptyhost', instance, paneId: '%7' }]+ const response = await fetch(`${base}/api/hook/session-start`, {+ method: 'POST', headers, body: JSON.stringify({ engine: 'claude', sessionId: 'session-1', runtimeHints, callerPid: 4242 }),+ })+ expect(response.status).toBe(200)+ expect(resolveHookAgent).toHaveBeenCalledWith(expect.objectContaining({ runtimeHints }))+ })+it('answers a hook whose agent has yet to record its process before the wait, and only logs what the wait finds', async () => {// The engine's hook command gives up on a reply after 500ms and then writes the registry itself, as for// a daemon that is down (hook/notify.mjs, fallbackRegister): held for the wait, its own row took the@@ -269,6 +280,8 @@ describe('process-owned hook server', () => {[{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'tmux', paneId: '%1', extra: true }] }],[{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'ptyhost', instance: 'p1', paneId: '%1', extra: true }] }],[{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'ptyhost', instance: 'host', paneId: '%1' }] }],+ [{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'ptyhost', instance: 'p2-0.4.21 x', paneId: '%1' }] }],+ [{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'ptyhost', instance: 'p2-', paneId: '%1' }] }],[{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'ptyhost', instance: 'p1', paneId: '1' }] }],[{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'ptyhost', instance: 'p1' }] }],[{ engine: 'claude', sessionId: 'session-1', runtimeHints: [{ backend: 'ptyhost', instance: 1, paneId: '%1' }] }],diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex c07d99f77..276155e90 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -30,6 +30,7 @@ import type { HookTerminalHint } from './lib/terminalTypes.js'import { ENGINES, type AgentEngine } from './engines/types.js'import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'import { isTrustedLocal, listenLocalSocket, type LocalSocketServer } from './lib/localSocket.js'+import { PTY_HOST_INSTANCE } from './lib/ptyHost/instance.js'/*** Which agent does a hook belong to, given the two grades of evidence?@@ -269,7 +270,7 @@ function validHookBody(value: unknown): value is BoundHookBody {// A Harness pty host pane, as its shell names itself (`HARNESS_PANE=<instance>:%N`, hook/notify.mjs): the// instance and the pane, nothing else.if (Object.keys(hint).some((field) => !['backend', 'instance', 'paneId'].includes(field))- || typeof hint.instance !== 'string' || !/^p\d{1,4}$/.test(hint.instance)+ || typeof hint.instance !== 'string' || !PTY_HOST_INSTANCE.test(hint.instance)|| typeof hint.paneId !== 'string' || !/^%\d{1,9}$/.test(hint.paneId)) return false} else if (hint.backend === 'herdr') {// A hook script installed by an earlier build still sends these from inside a Herdr pane. The@@ -306,7 +307,7 @@ function normalizedRuntimeHints(body: RegisterInput): HookTerminalHint[] {if (Array.isArray(body.runtimeHints) && body.runtimeHints.length <= 4) {for (const hint of body.runtimeHints) {if (hint?.backend === 'tmux' && /^%\d+$/.test(hint.paneId)) hints.push({ backend: 'tmux', paneId: hint.paneId })- else if (hint?.backend === 'ptyhost' && /^p\d{1,4}$/.test(hint.instance) && /^%\d{1,9}$/.test(hint.paneId)) {+ else if (hint?.backend === 'ptyhost' && PTY_HOST_INSTANCE.test(hint.instance) && /^%\d{1,9}$/.test(hint.paneId)) {hints.push({ backend: 'ptyhost', instance: hint.instance, paneId: hint.paneId })}}diff --git a/cli/src/lib/daemonSpawnLock.spec.ts b/cli/src/lib/daemonSpawnLock.spec.tsindex 67ff01a49..fe91c6551 100644--- a/cli/src/lib/daemonSpawnLock.spec.ts+++ b/cli/src/lib/daemonSpawnLock.spec.ts@@ -111,6 +111,40 @@ describe('daemon spawn lock', () => {}})+ it('takes the lock synchronously for a caller that cannot wait on its event loop, re-entrant, and null while a live holder keeps it', async () => {+ const lock = await loadLock()+ const release = lock.tryAcquireSpawnLockSync('update', 100)+ expect(release).not.toBeNull()+ expect(lock.readSpawnLockOwner()).toMatchObject({ pid: process.pid, purpose: 'update' })+ // Inside another section of this process: a nested handle.+ const nested = lock.tryAcquireSpawnLockSync('update', 100)+ nested!()+ expect(existsSync(lockDir())).toBe(true)+ release!()+ expect(existsSync(lockDir())).toBe(false)++ const holder = sleeper()+ await waitFor(() => !!holder.pid)+ mkdirSync(lockDir(), { mode: 0o700 })+ writeFileSync(ownerFile(), JSON.stringify({ pid: holder.pid, startMarker: '', token: 't', purpose: 'start', since: Date.now() }), { mode: 0o600 })+ try {+ const started = Date.now()+ expect(lock.tryAcquireSpawnLockSync('update', 300)).toBeNull()+ expect(Date.now() - started).toBeGreaterThanOrEqual(250)+ expect(readFileSync(ownerFile(), 'utf8')).toContain('"token":"t"')+ } finally {+ holder.kill('SIGKILL')+ }+ // A dead holder's lock is reclaimed, as the asynchronous wait reclaims it.+ await waitFor(() => holder.exitCode !== null || holder.signalCode !== null)+ const reclaimed = lock.tryAcquireSpawnLockSync('update', 1000)+ expect(lock.readSpawnLockOwner()?.pid).toBe(process.pid)+ reclaimed!()+ // Something that is not a lock: null at once.+ writeFileSync(lockDir(), 'a file')+ expect(lock.tryAcquireSpawnLockSync('update', 1000)).toBeNull()+ })+it('reclaims a lock whose owner is dead', async () => {const lock = await loadLock()const dead = spawnSync(process.execPath, ['-e', 'process.exit(0)'])diff --git a/cli/src/lib/daemonSpawnLock.ts b/cli/src/lib/daemonSpawnLock.tsindex c8f3509bd..068311e34 100644--- a/cli/src/lib/daemonSpawnLock.ts+++ b/cli/src/lib/daemonSpawnLock.ts@@ -342,6 +342,41 @@ export async function acquireSpawnLock(}}+/** How long `tryAcquireSpawnLockSync` waits by default: a sweep, an install or a stage holds the lock for moments. */+export const SPAWN_LOCK_SYNC_WAIT_MS = 5_000++/**+ * `acquireSpawnLock` for the one caller that cannot wait asynchronously: harnessd's master, whose probation verdicts are+ * synchronous (harnessd/supervisor.ts `restoreUpdate`, `confirmUpdate`), the next core started right after. Re-entrant+ * as it is, and a dead holder's lock reclaimed as it is, but the wait blocks this process's event loop (`Atomics.wait`)+ * for at most [waitMs], so it stays short. The release, or null when a live holder keeps the lock that long or+ * something that is not a lock sits at its path: the caller decides whether to go on without it.+ */+export function tryAcquireSpawnLockSync(purpose: SpawnLockPurpose, waitMs: number = SPAWN_LOCK_SYNC_WAIT_MS): (() => void) | null {+ if (held) {+ held.depth += 1+ return release+ }+ const deadline = Date.now() + waitMs+ const pause = new Int32Array(new SharedArrayBuffer(4))+ for (;;) {+ try {+ const token = tryCreate(purpose)+ if (token) {+ held = { token, purpose, depth: 1 }+ installExitHook()+ return release+ }+ const owner = readSpawnLockOwner()+ if (owner ? reclaimIfStale(owner) : reclaimIfOwnerless()) continue+ } catch {+ return null+ }+ if (Date.now() >= deadline) return null+ Atomics.wait(pause, 0, 0, POLL_MS)+ }+}+function release(): void {if (!held) returnheld.depth -= 1diff --git a/cli/src/lib/hostMove/gate.spec.ts b/cli/src/lib/hostMove/gate.spec.tsnew file mode 100644index 000000000..8e21deaad--- /dev/null+++ b/cli/src/lib/hostMove/gate.spec.ts@@ -0,0 +1,130 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { acquireAfterHold, HOLD_WAIT_MS, MoveGate } from './gate.js'++describe('MoveGate', () => {+ it('input during a hold is delivered once, in order, after release', async () => {+ const gate = new MoveGate()+ const delivered: string[] = []+ gate.hold('a1')+ expect(gate.holding('a1')).toBe(true)+ gate.enqueue('a1', async () => { delivered.push('one') })+ gate.enqueue('a1', async () => { await Promise.resolve(); delivered.push('two') })+ gate.enqueue('a1', async () => { delivered.push('three') })+ await Promise.resolve()+ expect(delivered).toEqual([])+ await gate.release('a1')+ expect(delivered).toEqual(['one', 'two', 'three'])+ expect(gate.holding('a1')).toBe(false)+ await gate.release('a1')+ expect(delivered).toEqual(['one', 'two', 'three'])+ })++ it('keeps what arrives while the queue runs behind it, and lets go only after the last', async () => {+ const gate = new MoveGate()+ const delivered: string[] = []+ gate.hold('a1')+ gate.enqueue('a1', async () => {+ delivered.push('first')+ // Arrives mid-drain: still held, so it queues behind rather than overtaking.+ expect(gate.holding('a1')).toBe(true)+ gate.enqueue('a1', async () => { delivered.push('late') })+ })+ gate.enqueue('a1', async () => { throw new Error('a failed delivery does not stop the rest') })+ gate.enqueue('a1', async () => { expect(gate.holding('a1')).toBe(true); delivered.push('second') })+ await gate.release('a1')+ expect(delivered).toEqual(['first', 'second', 'late'])+ expect(gate.holding('a1')).toBe(false)+ })++ it('counts a held agent as touched from its first write or touch, and forgets it at release', async () => {+ const gate = new MoveGate()+ gate.touch('a1')+ expect(gate.touched('a1')).toBe(false)+ gate.hold('a1')+ expect(gate.touched('a1')).toBe(false)+ gate.touch('a1')+ expect(gate.touched('a1')).toBe(true)+ await gate.release('a1')+ expect(gate.touched('a1')).toBe(false)+ gate.hold('a1')+ expect(gate.touched('a1')).toBe(false)+ gate.enqueue('a1', async () => {})+ expect(gate.touched('a1')).toBe(true)+ await gate.release('a1')+ })++ it('nothing is held for other agents', async () => {+ const gate = new MoveGate()+ const delivered: string[] = []+ gate.hold('a1')+ expect(gate.holding('a2')).toBe(false)+ gate.enqueue('a2', async () => { delivered.push('a2') })+ await Promise.resolve()+ expect(delivered).toEqual(['a2'])+ expect(gate.touched('a2')).toBe(false)+ gate.enqueue('a1', async () => { delivered.push('a1') })+ await Promise.resolve()+ expect(delivered).toEqual(['a2'])+ await gate.release('a1')+ expect(delivered).toEqual(['a2', 'a1'])+ })+})++describe('MoveGate.releaseAll', () => {+ it('delivers what every held agent has waiting, in order, and lets all go; a hold already draining is waited for', async () => {+ const gate = new MoveGate()+ const written: string[] = []+ let unblock!: () => void+ gate.hold('a')+ gate.hold('b')+ gate.enqueue('a', async () => { written.push('a1') })+ gate.enqueue('b', async () => { await new Promise<void>((resolve) => { unblock = resolve }); written.push('b1') })+ gate.enqueue('b', async () => { written.push('b2') })+ expect(gate.held().sort()).toEqual(['a', 'b'])+ // b's own release is under way: releaseAll waits for it too.+ const draining = gate.release('b')+ let done = false+ const all = gate.releaseAll().then(() => { done = true })+ await new Promise((resolve) => setTimeout(resolve, 10))+ expect(written).toEqual(['a1'])+ expect(done).toBe(false)+ unblock()+ await all+ await draining+ expect(written).toEqual(['a1', 'b1', 'b2'])+ expect(gate.held()).toEqual([])+ })+})++describe('acquireAfterHold', () => {+ afterEach(() => { vi.useRealTimers() })++ it('a control refused while the agent changes host is asked again once the move lets it go', async () => {+ vi.useFakeTimers()+ const gate = new MoveGate()+ gate.hold('a1')+ const release = () => {}+ // Refused while held, as `acquireControl` refuses it; given once the hold ends.+ const acquire = vi.fn(() => gate.holding('a1') ? null : release)+ const got = acquireAfterHold(gate, 'a1', acquire)+ await vi.advanceTimersByTimeAsync(5_000)+ expect(acquire).toHaveBeenCalledTimes(1)+ await gate.release('a1')+ await vi.advanceTimersByTimeAsync(1_000)+ expect(await got).toBe(release)+ expect(acquire).toHaveBeenCalledTimes(2)+ })++ it('a refusal with no move in flight is answered at once, and a hold that never ends is waited out only so long', async () => {+ vi.useFakeTimers()+ const gate = new MoveGate()+ expect(await acquireAfterHold(gate, 'a1', () => null)).toBeNull()+ gate.hold('a1')+ let answered = false+ const got = acquireAfterHold(gate, 'a1', () => null).then((value) => { answered = true; return value })+ await vi.advanceTimersByTimeAsync(HOLD_WAIT_MS - 1_000)+ expect(answered).toBe(false)+ await vi.advanceTimersByTimeAsync(2_000)+ expect(await got).toBeNull()+ })+})diff --git a/cli/src/lib/hostMove/gate.ts b/cli/src/lib/hostMove/gate.tsnew file mode 100644index 000000000..7734d0324--- /dev/null+++ b/cli/src/lib/hostMove/gate.ts@@ -0,0 +1,117 @@+/**+ * Holds what reaches an agent while it changes host: its engine stops in the old pane and starts in a new one,+ * and input written in between would land in a pane that is going away. Nothing is refused or dropped: each+ * write waits here, in the order it arrived, and is delivered once the row points at the pane that stays (the+ * new one, or the old one when the move fell back).+ *+ * Only writes wait. A stream open is never held: a held open would stall every later frame of its connection+ * (frames are handled in order per connection), and the desktop gives up on an open after 4 s. It opens on the+ * pane the row names and is moved with the agent's other streams (`TerminalStreamManager.retarget`).+ */+interface Hold {+ queue: Array<() => Promise<void>>+ draining: boolean+ /** Whether input, a stream open or a message reached the agent during this hold: someone is using it. */+ touched: boolean+ /** Settles once the release that drains this hold has let the agent go. */+ done?: Promise<void>+}++export class MoveGate {+ private readonly holds = new Map<string, Hold>()++ /** Start holding [agentId]'s input. A second hold of an agent already held changes nothing. */+ hold(agentId: string): void {+ if (this.holds.has(agentId)) return+ this.holds.set(agentId, { queue: [], draining: false, touched: false })+ }++ /** True from `hold` until the last queued write after `release` has been delivered: a write that arrives+ * while the queue drains must queue behind it, or it would overtake input typed before it. */+ holding(agentId: string): boolean {+ return this.holds.has(agentId)+ }++ /** Queue [deliver] behind what is already held for [agentId], and count the agent as in use. An agent not+ * held is delivered at once. */+ enqueue(agentId: string, deliver: () => Promise<void>): void {+ const hold = this.holds.get(agentId)+ if (!hold) {+ void deliver().catch(() => { /* the deliverer reports its own failure */ })+ return+ }+ hold.touched = true+ hold.queue.push(deliver)+ }++ /** Count a held [agentId] as in use without queueing anything: a stream opened on it, or a write refused+ * for now (one whose caller asks again). Nothing for an agent not held. */+ touch(agentId: string): void {+ const hold = this.holds.get(agentId)+ if (hold) hold.touched = true+ }++ /** Whether anything reached [agentId] during the current hold. False once it is let go: the next hold+ * starts untouched. */+ touched(agentId: string): boolean {+ return this.holds.get(agentId)?.touched === true+ }++ /**+ * Deliver what was held, one write at a time in arrival order, then let [agentId] go. The mover calls this+ * after the row's runtime has switched (or fallen back) and its streams were retargeted, so each write+ * reaches the row's current pane when it runs. A write that fails is its deliverer's to report: the rest+ * still go. A second release while the first drains resolves at once; the first lets the agent go.+ */+ async release(agentId: string): Promise<void> {+ const hold = this.holds.get(agentId)+ if (!hold || hold.draining) return+ hold.draining = true+ let finished!: () => void+ hold.done = new Promise<void>((resolve) => { finished = resolve })+ for (let next = hold.queue.shift(); next; next = hold.queue.shift()) {+ try { await next() } catch { /* reported by the deliverer */ }+ }+ // No await between the empty queue and this: nothing can be queued that would then never run.+ this.holds.delete(agentId)+ finished()+ }++ /** The agents held now. */+ held(): string[] {+ return [...this.holds.keys()]+ }++ /**+ * Release every agent held, as `release` does each: what waits for it is written to the pane its row names now. For a+ * hand-over that cannot wait any longer for a move to finish (mover.ts `settleMovesForHandOver`): the connection the+ * deliveries are written through is about to close. Resolves once every agent is let go, a release already under way+ * (the move's own) included.+ */+ async releaseAll(): Promise<void> {+ await Promise.all([...this.holds].map(([agentId, hold]) => (hold.draining ? hold.done : this.release(agentId))))+ }+}++/** Longer than a move holds an agent (at most 75 s, moveAgent.ts), so a wait outlasts any hold that ends. */+export const HOLD_WAIT_MS = 90_000+const HOLD_POLL_MS = 100++/**+ * [acquire] (a control of the agent's pane, `acquireTerminalControl`), asked again once [agentId]'s move lets it go+ * when it was refused because a move holds it: the /model picker then waits out a move it never sees, rather than+ * answering BUSY. A refusal for any other reason is the answer at once. Nothing here touches the gate: [acquire] itself+ * counts a held agent as in use when it refuses it (lib/sessionInput.ts `acquireControl` calls `touch`), which cancels+ * a move that has not yet stopped the engine. Waits at most [boundMs].+ */+export async function acquireAfterHold<T>(gate: Pick<MoveGate, 'holding'>, agentId: string, acquire: () => T | null,+ boundMs = HOLD_WAIT_MS): Promise<T | null> {+ const first = acquire()+ if (first !== null || !gate.holding(agentId)) return first+ const deadline = Date.now() + boundMs+ while (gate.holding(agentId)) {+ if (Date.now() >= deadline) return null+ await new Promise((resolve) => setTimeout(resolve, HOLD_POLL_MS))+ }+ return acquire()+}diff --git a/cli/src/lib/hostMove/hostMove.real.spec.ts b/cli/src/lib/hostMove/hostMove.real.spec.tsnew file mode 100644index 000000000..e07d76e00--- /dev/null+++ b/cli/src/lib/hostMove/hostMove.real.spec.ts@@ -0,0 +1,421 @@+// The pty host rollover on two real builds (sub-project G): a host an older daemon started keeps its pane while new+// panes go to the installed build's host, an agent moves from one to the other with its scrollback and the input typed+// meanwhile, and the old host is shut down and its version folder removed once its last pane has gone.+//+// The move is the daemon's own (core/agents/hostMove.ts on lib/hostMove/moveAgent.ts), on real PtyHostBackends, a real+// coordinator, stream manager and move gate. Faked is only what needs a whole core: the registry (an in-memory row),+// the launch (a stand-in engine that prints its argv and waits for input, in place of a real engine's resume), the old+// engine's stop (the pane is kept, its process killed) and the probe of the new engine (the process the respawn put in+// the pane). Both builds come from the same source; the previous one is stamped with an older version:+// cd pty && HARNESS_PTY_VERSION=0.0.1 cargo +stable build && cp target/debug/harness-pty <scratch>/harness-pty-old && cargo +stable build+// cd cli && HARNESS_PTY_BIN=$(pwd)/../pty/target/debug/harness-pty HARNESS_PTY_BIN_PREV=<scratch>/harness-pty-old \+// npx vitest run src/lib/hostMove/hostMove.real.spec.ts+// The previous build's version names its folder under <runtime>/pty/, as an install's does: a number (VERSION_DIR).+import { spawn } from 'node:child_process'+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { createHostMove, moveWaitingArgv } from '../../core/agents/hostMove.js'+import type { PtyHostBackend } from '../ptyHostBackend.js'+import { PtyHostClient } from '../ptyHost/client.js'+import { ptyHostBackends, PtyHostDrain, rowsOnInstance } from '../ptyHost/drain.js'+import { binaryVersion, compareVersions, readInstanceDiscovery, removeUnusedPtyVersions, targetHost, VERSION_DIR, type PtyHostTarget } from '../ptyHost/launch.js'+import type { RegisteredSession } from '../registry.js'+import type { RestartAgentDeps } from '../restartAgent.js'+import { restoreTerminals } from '../restoreTerminals.js'+import { removeTree } from '../terminalBackend.contract.js'+import type { TerminalBackend } from '../terminalBackend.js'+import { TerminalBackendCoordinator } from '../terminalBackendCoordinator.js'+import { TerminalBinaryKind, type TerminalBinaryClear } from '../terminalBinary.js'+import { terminalRouteKey } from '../terminalRuntime.js'+import { TerminalStreamManager } from '../terminalStreamManager.js'+import type { ProcessIdentity, PtyRuntimeRef, TerminalRuntimeRef } from '../terminalTypes.js'+import { MoveGate } from './gate.js'+import type { MoveOutcome } from './moveAgent.js'++const realBinary = process.env.HARNESS_PTY_BIN+const previousBinary = process.env.HARNESS_PTY_BIN_PREV+const WINDOWS = process.platform === 'win32'+const CASE_TIMEOUT_MS = WINDOWS ? 90_000 : 30_000+const WAIT_MS = WINDOWS ? 20_000 : 8_000+const ENTER = WINDOWS ? '\r' : '\n'+const BINARY = WINDOWS ? 'harness-pty.exe' : 'harness-pty'+/** What the host loads from its own folder on Windows, as it ships in runtime\pty\<version>\ (windows.yml places them). */+const BESIDE = ['conpty.dll', 'OpenConsole.exe']+const OWNER = 'me'+const AGENT = 'agent-rollover'+const CONVERSATION = 'conv-rollover'+const OLD_LINES = 60++/**+ * The stand-in engine: prints its argv, a start prints [OLD_LINES] lines of history (more than a screen holds), then+ * it says it is ready and prints each line it is sent, until it is killed. Started as `--start <id>`, resumed as+ * `--resume <id>`, as an engine's resume names its conversation.+ */+const ENGINE = `+const args = process.argv.slice(2)+console.log('engine-argv ' + args.join(' '))+if (args[0] === '--start') for (let i = 1; i <= ${OLD_LINES}; i++) console.log('old-line-' + i)+console.log('engine-ready')+let buffered = ''+process.stdin.setEncoding('utf8')+process.stdin.on('data', (chunk) => {+ buffered += chunk+ for (let at = buffered.search(/[\\r\\n]/); at >= 0; at = buffered.search(/[\\r\\n]/)) {+ const line = buffered.slice(0, at)+ buffered = buffered.slice(at + 1)+ if (line) console.log('engine-got=' + line)+ }+})+`++const cleanup: Array<() => unknown> = []+afterEach(async () => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+ for (const step of cleanup.splice(0).reverse()) await step()+})++async function until<T>(read: () => Promise<T> | T, ok: (value: T) => boolean, ms = WAIT_MS): Promise<T> {+ const end = Date.now() + ms+ for (;;) {+ const value = await read()+ if (ok(value) || Date.now() > end) return value+ await new Promise((resolve) => setTimeout(resolve, 50))+ }+}++const alive = (pid: number) => { try { process.kill(pid, 0); return true } catch { return false } }+const killPid = (pid: number | undefined) => { if (pid) try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ } }+const count = (text: string, part: string) => text.split(part).length - 1++/** [binary] installed as `<runtime>/pty/<version>/`, with what it loads beside it. */+function install(runtimeDir: string, binary: string, version: string): string {+ const dir = path.join(runtimeDir, 'pty', version)+ mkdirSync(dir, { recursive: true })+ copyFileSync(binary, path.join(dir, BINARY))+ for (const name of BESIDE) {+ const file = path.join(path.dirname(binary), name)+ if (existsSync(file)) copyFileSync(file, path.join(dir, name))+ }+ return dir+}++interface Rollover {+ home: string+ runtimeDir: string+ oldDir: string+ newDir: string+ oldVersion: string+ target: PtyHostTarget+ oldPid: number+ oldPane: PtyRuntimeRef+ create: PtyHostBackend+ drain: PtyHostBackend+ backends: TerminalBackend[]+ terminals: TerminalBackendCoordinator+ rows: Map<string, RegisteredSession>+ gate: MoveGate+ manager: TerminalStreamManager+ engineArgv(...args: string[]): string[]+ screen(runtime: PtyRuntimeRef): Promise<string>+ /** A stream on the agent, as a window opens one: what it showed so far, and a keystroke line through it. */+ openStream(connId: string): Promise<{ output(): string; type(text: string): Promise<void> }>+}++/**+ * A home with both builds installed (`current-pty` naming the new one), the old build's host started as an older+ * daemon left it with the agent's pane, and this daemon's backends: the target's host (started from its installed+ * folder) and a drain backend on the old one.+ */+async function rollover(): Promise<Rollover> {+ // The drain's own lines (a backend that left, the old host's connection lost as it shuts down): the cases check+ // what they say happened.+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const home = mkdtempSync(path.join(tmpdir(), 'pty-rollover-'))+ cleanup.push(() => removeTree(home, 20_000))+ const runtimeDir = path.join(home, 'runtime')+ const newVersion = binaryVersion(realBinary!)?.version+ const oldVersion = binaryVersion(previousBinary!)?.version+ if (!newVersion || !oldVersion) throw new Error('a binary says no version')+ for (const version of [newVersion, oldVersion]) {+ if (!VERSION_DIR.test(version)) throw new Error(`${version} cannot name a version folder: build with a numeric HARNESS_PTY_VERSION`)+ }+ expect(compareVersions(oldVersion, newVersion)).toBeLessThan(0)+ const oldDir = install(runtimeDir, previousBinary!, oldVersion)+ const newDir = install(runtimeDir, realBinary!, newVersion)+ writeFileSync(path.join(runtimeDir, 'pty', 'current-pty'), `${newVersion}\n`)+ // The host this daemon starts is the installed one's: the create backend's launch resolves HARNESS_PTY_BIN first.+ vi.stubEnv('HARNESS_PTY_BIN', path.join(newDir, BINARY))+ const target = targetHost({ runtimeDir })+ if (!target) throw new Error('the installed build says no version')+ expect(target).toMatchObject({ version: newVersion, source: 'installed', features: expect.arrayContaining(['seed']) })+ const previous = targetHost({ runtimeDir, env: { HARNESS_PTY_BIN: path.join(oldDir, BINARY) } })!+ expect(previous.instance).not.toBe(target.instance)+ cleanup.push(() => { killPid(readInstanceDiscovery(home, previous.instance)?.pid); killPid(readInstanceDiscovery(home, target.instance)?.pid) })++ const script = path.join(home, 'engine.cjs')+ writeFileSync(script, ENGINE)+ const engineArgv = (...args: string[]) => [process.execPath, script, ...args]++ // The host an older daemon started from its own folder, with the agent's engine in a pane, held as every pane is.+ spawn(path.join(oldDir, BINARY), ['serve', '--home', home], { cwd: home, detached: true, stdio: 'ignore', windowsHide: true }).unref()+ const old = await until(() => readInstanceDiscovery(home, previous.instance), (found) => found !== null)+ if (!old) throw new Error('the old host published no discovery file')+ const before = await PtyHostClient.connect(old)+ if (!(before instanceof PtyHostClient)) throw new Error(JSON.stringify(before))+ const made = await before.call({ op: 'create', command: engineArgv('--start', CONVERSATION), cwd: home, cols: 80, rows: 24, owner: OWNER, hold: true })+ before.close()+ if (made.state !== 'ok') throw new Error(JSON.stringify(made))+ const oldPane: PtyRuntimeRef = { backend: 'ptyhost', instance: previous.instance, paneId: made.value.pane }++ // This daemon.+ const hosts = ptyHostBackends(home, { target, owner: () => OWNER })+ const [drain] = hosts.drain+ const create = hosts.create+ cleanup.push(() => { create.dispose(); drain?.dispose() })+ expect(hosts.drain.map((backend) => backend.instanceId)).toEqual([`ptyhost:${previous.instance}`])+ expect(await create.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ expect(await drain.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ expect(create.instanceId).toBe(`ptyhost:${target.instance}`)+ expect(create.canSeed).toBe(true)+ const backends: TerminalBackend[] = [create, drain]+ const terminals = new TerminalBackendCoordinator(backends, ['ptyhost'])++ const rows = new Map<string, RegisteredSession>([[AGENT, {+ schemaVersion: 2, agentId: AGENT, sessionId: CONVERSATION, engine: 'codex', active: true, boundAt: null, cwd: home,+ registeredAt: Date.now(), touchedAt: Date.now(), runtimes: [oldPane], primaryRuntimeKey: terminalRouteKey(oldPane),+ } as unknown as RegisteredSession]])+ const gate = new MoveGate()+ const binarySent: Array<{ connId: string; frame: TerminalBinaryClear }> = []+ const sent: Array<{ connId: string; type: string; payload: Record<string, unknown> }> = []+ const manager = new TerminalStreamManager({+ terminals,+ resolveAgent: (id) => rows.get(id),+ sendTarget: (connId, type, payload) => { sent.push({ connId, type, payload }); return true },+ sendBinaryTarget: (connId, frame) => { binarySent.push({ connId, frame }); return true },+ streamingAvailable: true,+ moveGate: gate,+ })+ cleanup.push(() => manager.stop())++ const screen = async (runtime: PtyRuntimeRef) => {+ const read = await terminals.backendFor(runtime)!.capture(runtime, { historyLines: 2000, ansi: false })+ return read.state === 'succeeded' ? read.value : ''+ }+ expect(await until(() => screen(oldPane), (text) => text.includes('engine-ready'))).toContain('engine-ready')++ const openStream = async (connId: string) => {+ await manager.handleFrame(connId, 'terminal_open', { requestId: `open-${connId}`, protocolVersion: 3, agentId: AGENT, cols: 100, rows: 30 })+ const ready = sent.findLast((frame) => frame.connId === connId && frame.type === 'terminal_ready')+ if (!ready) throw new Error(`no stream opened: ${JSON.stringify(sent.filter((frame) => frame.connId === connId))}`)+ const streamId = String(ready.payload.streamId)+ let seq = 0+ return {+ output: () => binarySent+ .filter((entry) => entry.connId === connId && entry.frame.streamId === streamId+ && (entry.frame.kind === TerminalBinaryKind.output || entry.frame.kind === TerminalBinaryKind.keyframe))+ .map((entry) => Buffer.from(entry.frame.bytes).toString('utf8')).join(''),+ type: (text: string) => manager.handleBinary(connId, { kind: TerminalBinaryKind.input, streamId, seq: seq++, bytes: Buffer.from(text), compressed: false }),+ }+ }++ return {+ home, runtimeDir, oldDir, newDir, oldVersion, target, oldPid: old.pid, oldPane, create, drain, backends, terminals,+ rows, gate, manager, engineArgv, screen, openStream,+ }+}++/**+ * The agent's move to the target's host, as the mover runs it (core/agents/hostMove.ts `createHostMove`). [duringStop]+ * runs as the old engine is about to be stopped, with the agent's input held: the swap is under way.+ */+async function move(rig: Rollover, duringStop: () => Promise<void> = async () => {}): Promise<{ outcome: MoveOutcome; lines: string[] }> {+ const { rows, terminals } = rig+ const lines: string[] = []+ const restore = restoreTerminals({+ backendFor: (runtime) => terminals.backendFor(runtime),+ listTmuxPanes: async () => ({ ok: false }),+ cwd: rig.home,+ label: () => 'rollover',+ })+ /** The waiting command each new pane ran before its respawn: the engine is the process that took its place. */+ const waiting = new Map<string, number>()+ const backendOf = (runtime: TerminalRuntimeRef) => terminals.backendFor(runtime) as PtyHostBackend+ const moveOne = createHostMove({+ registry: {+ byAgent: (id) => rows.get(id),+ transaction: async (apply) => apply(),+ updateRuntimes: (id, runtimes, primaryRuntimeKey) => {+ const row = rows.get(id)+ if (!row) return false+ rows.set(id, { ...row, runtimes: [...runtimes], ...(primaryRuntimeKey ? { primaryRuntimeKey } : {}) })+ return true+ },+ updateProcessIdentity: (id, identity) => {+ const row = rows.get(id)+ if (!row) return false+ rows.set(id, { ...row, processIdentity: identity })+ return true+ },+ setActive: () => true,+ },+ terminals,+ createBackend: () => rig.create,+ restore: {+ respawn: async (runtime, launch, control) => {+ const pid = await backendOf(runtime).rootProcess(runtime as PtyRuntimeRef)+ if (typeof pid === 'number') waiting.set(terminalRouteKey(runtime), pid)+ return restore.respawn(runtime, launch, control)+ },+ probeProcess: async (runtime) => {+ const pid = await backendOf(runtime).rootProcess(runtime as PtyRuntimeRef)+ if (typeof pid !== 'number' || pid === waiting.get(terminalRouteKey(runtime))) return null+ return { pid, executable: process.execPath, startMarker: `pid-${pid}` } satisfies ProcessIdentity+ },+ },+ buildLaunch: async (row, options) => ({+ argv: rig.engineArgv('--resume', options.resumeSessionId ?? row.sessionId),+ deferred: { prepare: () => {}, overrides: { env: {}, extraArgs: [], clearEnv: [] }, permission: {} },+ }),+ // The stop a restart makes: the pane is kept, then its engine ends. Nothing else of a swap is asked by a move.+ paneSwapDeps: (_session, { backend, runtime }) => ({+ holdOpen: async () => {+ const kept = await backend.holdOpen(runtime)+ return kept.state === 'succeeded' ? { ok: true } : { ok: false, reason: kept.reason }+ },+ terminate: async () => {+ await duringStop()+ const pid = await backend.rootProcess(runtime)+ if (typeof pid !== 'number') return 'failed'+ process.kill(pid, 'SIGKILL')+ const state = await until(() => backend.paneState(runtime), (read) => read !== 'unknown' && read !== 'gone' && read.dead)+ return state !== 'unknown' && state !== 'gone' && state.dead ? 'killed' : 'failed'+ },+ }) as unknown as RestartAgentDeps,+ retarget: (agentId, runtime) => rig.manager.retarget(agentId, runtime),+ gate: rig.gate,+ eligible: () => true,+ holdRoute: () => () => {},+ announce: () => {},+ invalidateControl: () => {},+ waitingArgv: () => moveWaitingArgv(),+ log: (line) => { lines.push(line) },+ })+ const outcome = await moveOne(rows.get(AGENT)!, () => true)+ return { outcome, lines }+}++/** The pane the agent's row names now. */+const rowPane = (rig: Rollover) => rig.rows.get(AGENT)!.runtimes[0] as PtyRuntimeRef++describe.runIf(!!realBinary && !!previousBinary)('the pty host rollover on two real builds', () => {+ it('a pane on the old host keeps streaming and taking input while a new pane opens on the new host', async () => {+ const rig = await rollover()+ const stream = await rig.openStream('window-1')+ await stream.type(`before-new-pane${ENTER}`)+ expect(await until(() => stream.output(), (text) => text.includes('engine-got=before-new-pane'))).toContain('engine-got=before-new-pane')++ const fresh = await rig.create.create({ command: rig.engineArgv('--start', 'conv-other'), cwd: rig.home })+ if (fresh.state !== 'succeeded') throw new Error(JSON.stringify(fresh))+ expect(fresh.runtime.instance).toBe(rig.target.instance)+ expect(rig.terminals.backendFor(fresh.runtime)).toBe(rig.create)+ expect(await until(() => rig.screen(fresh.runtime), (text) => text.includes('engine-ready'))).toContain('engine-argv --start conv-other')+ // The old host refuses new panes from this daemon: they go to the target's.+ expect(await rig.drain.create({ command: rig.engineArgv('--start', 'conv-refused') })).toMatchObject({ state: 'failed', dispatch: 'not_started' })++ await stream.type(`after-new-pane${ENTER}`)+ expect(await until(() => stream.output(), (text) => text.includes('engine-got=after-new-pane'))).toContain('engine-got=after-new-pane')+ expect(alive(rig.oldPid)).toBe(true)+ const oldListed = await rig.drain.inventory()+ expect(oldListed.state === 'available' && oldListed.roots.map((root) => root.runtime)).toEqual([rig.oldPane])+ const newListed = await rig.create.inventory()+ expect(newListed.state === 'available' && newListed.roots.map((root) => root.runtime)).toEqual([fresh.runtime])+ expect((await rig.create.kill(fresh.runtime)).state).toBe('succeeded')+ }, CASE_TIMEOUT_MS)++ it('a moved pane\'s history holds the old pane\'s lines', async () => {+ const rig = await rollover()+ const { outcome, lines } = await move(rig)+ expect(outcome, lines.join('\n')).toEqual({ moved: true, resumed: true })+ const moved = rowPane(rig)+ expect(moved.instance).toBe(rig.target.instance)+ expect(rig.terminals.backendFor(moved)).toBe(rig.create)+ const text = await until(() => rig.screen(moved), (value) => value.includes('engine-argv --resume'))+ // The old pane's whole scrollback, past one screen, then the resumed engine below it, naming the conversation.+ for (let line = 1; line <= OLD_LINES; line++) expect(text).toMatch(new RegExp(`^old-line-${line}$`, 'm'))+ expect(text.indexOf(`engine-argv --start ${CONVERSATION}`)).toBeGreaterThanOrEqual(0)+ expect(text.indexOf(`old-line-${OLD_LINES}`)).toBeLessThan(text.indexOf(`engine-argv --resume ${CONVERSATION}`))+ // The move closed the old pane.+ expect(await until(() => rig.drain.paneState(rig.oldPane), (state) => state === 'gone')).toBe('gone')+ }, CASE_TIMEOUT_MS)++ it('the old host shuts down after its last pane goes, and its version folder is removed', async () => {+ const rig = await rollover()+ const removed: string[] = []+ const drainer = new PtyHostDrain({+ drain: [rig.drain],+ backends: rig.backends,+ coordinator: rig.terminals,+ inUse: (instanceId) => rowsOnInstance([...rig.rows.values()], instanceId),+ cleanup: () => { removed.push(...removeUnusedPtyVersions(rig.home, rig.runtimeDir)) },+ })+ // While the old host runs, its folder stays: its version is a running host's.+ expect(removeUnusedPtyVersions(rig.home, rig.runtimeDir)).toEqual([])+ await drainer.step()+ await drainer.step()+ expect(rig.backends).toHaveLength(2)+ expect(existsSync(path.join(rig.oldDir, BINARY))).toBe(true)++ const { outcome, lines } = await move(rig)+ expect(outcome, lines.join('\n')).toEqual({ moved: true, resumed: true })+ // The move closed the old host's last pane: two empty passes later it is shut down, and its backend has left.+ await until(() => rig.drain.drainState(), (state) => state === 'empty')+ await drainer.step()+ expect(rig.backends).toHaveLength(2)+ await drainer.step()+ expect(rig.backends).toEqual([rig.create])+ expect(rig.terminals.instances()).toEqual([rig.create])+ expect(await until(() => alive(rig.oldPid), (up) => !up)).toBe(false)+ expect(readInstanceDiscovery(rig.home, rig.drain.instanceId.replace(/^ptyhost:/, ''))).toBeNull()+ // Its binaries are deleted with it; the installed build's stay, and its host runs the moved agent.+ // A folder that could not be removed (a file still locked on Windows) is said on console.error, stubbed here.+ const said = vi.mocked(console.error).mock.calls.map((call) => call.join(' ')).join('\n')+ expect(removed, said).toEqual([rig.oldVersion])+ expect(existsSync(rig.oldDir), said).toBe(false)+ expect(existsSync(path.join(rig.newDir, BINARY))).toBe(true)+ expect(await rig.create.paneState(rowPane(rig))).toMatchObject({ dead: false })+ }, CASE_TIMEOUT_MS)++ it('input sent during the swap arrives in the new pane', async () => {+ const rig = await rollover()+ const stream = await rig.openStream('window-1')+ expect(await until(() => stream.output(), (text) => text.includes('engine-ready'))).toContain('engine-ready')+ let held = false+ let oldScreen = ''+ const { outcome, lines } = await move(rig, async () => {+ // Typed as the old engine is about to stop, while it still runs: the gate holds it, and the old engine, given+ // the time to print it, never sees it.+ await stream.type(`typed-in-swap${ENTER}`)+ held = rig.gate.holding(AGENT)+ await new Promise((resolve) => setTimeout(resolve, 500))+ oldScreen = await rig.screen(rig.oldPane)+ })+ expect(outcome, lines.join('\n')).toEqual({ moved: true, resumed: true })+ expect(held).toBe(true)+ expect(oldScreen).toContain('engine-ready')+ expect(oldScreen).not.toContain('typed-in-swap')+ const moved = rowPane(rig)+ expect(moved.instance).toBe(rig.target.instance)+ const text = await until(() => rig.screen(moved), (value) => value.includes('engine-got=typed-in-swap'))+ // Delivered once, to the resumed engine.+ expect(count(text, 'engine-got=typed-in-swap')).toBe(1)+ expect(text.indexOf(`engine-argv --resume ${CONVERSATION}`)).toBeLessThan(text.indexOf('engine-got=typed-in-swap'))+ // The window's stream followed the agent: it shows the new pane, and what is typed now goes there.+ expect(await until(() => stream.output(), (value) => value.includes('engine-got=typed-in-swap'))).toContain('engine-got=typed-in-swap')+ await stream.type(`after-move${ENTER}`)+ expect(await until(() => rig.screen(moved), (value) => value.includes('engine-got=after-move'))).toContain('engine-got=after-move')+ }, CASE_TIMEOUT_MS)+})diff --git a/cli/src/lib/hostMove/moveAgent.spec.ts b/cli/src/lib/hostMove/moveAgent.spec.tsnew file mode 100644index 000000000..87f818b92--- /dev/null+++ b/cli/src/lib/hostMove/moveAgent.spec.ts@@ -0,0 +1,503 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../registry.js'+import type { TerminalBackend } from '../terminalBackend.js'+import type { ProcessIdentity, TerminalInventoryResult, TerminalRuntimeRef } from '../terminalTypes.js'+import { terminalRouteKey } from '../terminalRuntime.js'+import { MoveGate } from './gate.js'+import { MOVE_MARKER_ENV, moveAgent, moveCreateRequest, removeOrphanMovePanes, type MoveAgentDeps, type MoveOutcome } from './moveAgent.js'++const OLD: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p2', paneId: '%1' }+const NEW: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p2-1.2.3', paneId: '%7' }+const ID: ProcessIdentity = { pid: 42, executable: 'claude', startMarker: 'Mon Oct 20 10:00:00 2026' }+const LAUNCH = { argv: ['claude', '--resume', 's1'] }++function session(): RegisteredSession {+ return { agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/w', runtimes: [OLD], tmuxPane: '%1' } as unknown as RegisteredSession+}++const never = <T>() => new Promise<T>(() => { /* never settles */ })+const after = <T>(ms: number, value: T) => new Promise<T>((resolve) => setTimeout(() => resolve(value), ms))++/** Fakes for every step, recording the order of what changes anything, and a row that the swap switches. */+function harness(overrides: Partial<MoveAgentDeps> = {}) {+ const events: string[] = []+ const row = { runtime: OLD }+ const gate = new MoveGate()+ const hold = gate.hold.bind(gate)+ const release = gate.release.bind(gate)+ let heldAt: number | null = null+ let releasedAt: number | null = null+ gate.hold = (agentId) => { events.push('hold'); heldAt = Date.now(); hold(agentId) }+ gate.release = async (agentId) => { events.push('release'); releasedAt = Date.now(); await release(agentId) }+ // The reconciler's route holds, owner-scoped as `holdRoute(key, null)` is: a release lets go only of its own hold.+ const routes = new Map<string, symbol>()+ const holdRoute = vi.fn((key: string) => {+ const owner = Symbol('hold')+ routes.set(key, owner)+ return () => { if (routes.get(key) === owner) routes.delete(key) }+ })+ const deps: MoveAgentDeps = {+ capture: vi.fn(async () => { events.push('capture'); return 'line one\nline two\n' }),+ buildLaunch: vi.fn(async () => { events.push('buildLaunch'); return LAUNCH }),+ createSeeded: vi.fn(async () => { events.push('create'); return { ok: true as const, runtime: NEW } }),+ stopEngine: vi.fn(async () => { events.push('stop'); return 'terminated' as const }),+ prepareResume: vi.fn(async () => { events.push('prepare') }),+ respawn: vi.fn(async () => { events.push('respawn'); return { ok: true } }),+ probeProcess: vi.fn(async () => ID),+ swap: vi.fn((_agentId: string, runtime: TerminalRuntimeRef) => { events.push('swap'); row.runtime = runtime }),+ retarget: vi.fn(async (_agentId: string, to: TerminalRuntimeRef) => {+ events.push(row.runtime === to ? 'retarget(row names it)' : 'retarget(row names the old pane)')+ }),+ releaseHold: vi.fn(async (runtime: TerminalRuntimeRef) => { events.push(`releaseHold ${runtime.paneId}`) }),+ killPane: vi.fn(async (runtime: TerminalRuntimeRef) => { events.push(`kill ${runtime.paneId}`); return true }),+ relaunchOld: vi.fn(async () => { events.push('relaunchOld'); return true }),+ gate,+ holdRoute,+ current: () => true,+ eligible: () => true,+ log: vi.fn(),+ ...overrides,+ }+ return { deps, events, row, gate, holdRoute, routes, heldMs: () => heldAt === null || releasedAt === null ? null : releasedAt - heldAt }+}++let movedMs = 0+/** Runs the move to its end on the fake clock: the probe polls, and every bound is a timer. Sets `movedMs`. */+async function run(deps: MoveAgentDeps, row: RegisteredSession = session()): Promise<MoveOutcome> {+ const started = Date.now()+ const moved = moveAgent(row, deps).finally(() => { movedMs = Date.now() - started })+ await vi.advanceTimersByTimeAsync(300_000)+ return moved+}++beforeEach(() => { vi.useFakeTimers() })+afterEach(() => { vi.useRealTimers() })++describe('moveAgent', () => {+ it('moves an idle conversation agent and keeps its id', async () => {+ const h = harness()+ const outcome = await run(h.deps)+ expect(outcome).toEqual({ moved: true, resumed: true })+ expect(h.events).toEqual(['capture', 'buildLaunch', 'create', 'hold', 'stop', 'prepare', 'respawn', 'swap', 'retarget(row names it)', 'releaseHold %7', 'kill %1', 'release'])+ // The same agent id throughout: the row is switched to the new pane, never replaced.+ expect(h.deps.swap).toHaveBeenCalledWith('a1', NEW, ID)+ // Built while the old engine runs: without the writes a launch prepares, which wait for its stop.+ expect(h.deps.buildLaunch).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1' }), expect.objectContaining({ resumeSessionId: 's1', prepare: false }))+ // The new pane is seeded with the old one's scrollback, as the host's terminal expects it.+ expect(h.deps.createSeeded).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1' }), 'line one\r\nline two')+ expect(h.deps.respawn).toHaveBeenCalledWith(NEW, LAUNCH)+ expect(h.deps.relaunchOld).not.toHaveBeenCalled()+ expect(h.gate.holding('a1')).toBe(false)+ // Both routes, the new one from its create and the old one from the hold: the reconciler sees neither pane come+ // or go on its own. Both are let go at the end.+ expect(h.holdRoute.mock.calls.map(([key]) => key)).toEqual([terminalRouteKey(NEW), terminalRouteKey(OLD)])+ expect(h.routes.size).toBe(0)+ })++ it('delivers input typed during the move to the new pane, after the swap', async () => {+ const h = harness()+ const delivered: string[] = []+ h.deps.stopEngine = vi.fn(async () => {+ // Typed once the old engine is stopping: queued, not lost, and delivered where the row then points.+ h.gate.enqueue('a1', async () => { delivered.push(h.row.runtime.paneId) })+ return 'terminated' as const+ })+ expect(await run(h.deps)).toEqual({ moved: true, resumed: true })+ expect(delivered).toEqual(['%7'])+ })++ it('capture_failure_changes_nothing', async () => {+ for (const capture of [async () => null, async () => { throw new Error('no snapshot') }]) {+ const h = harness({ capture: vi.fn(capture) })+ const outcome = await run(h.deps)+ expect(outcome).toMatchObject({ moved: false, fellBack: false })+ expect(h.deps.createSeeded).not.toHaveBeenCalled()+ expect(h.deps.stopEngine).not.toHaveBeenCalled()+ expect(h.deps.killPane).not.toHaveBeenCalled()+ expect(h.events).not.toContain('hold')+ expect(h.holdRoute).not.toHaveBeenCalled()+ }+ })++ it('a refused create changes nothing', async () => {+ const h = harness({ createSeeded: vi.fn(async () => ({ ok: false as const, reason: 'this host cannot seed a pane' })) })+ const outcome = await run(h.deps)+ expect(outcome).toEqual({ moved: false, reason: expect.stringContaining('this host cannot seed a pane'), fellBack: false })+ expect(h.deps.stopEngine).not.toHaveBeenCalled()+ expect(h.deps.respawn).not.toHaveBeenCalled()+ expect(h.deps.killPane).not.toHaveBeenCalled()+ expect(h.deps.relaunchOld).not.toHaveBeenCalled()+ expect(h.events).not.toContain('hold')+ })++ it('a launch restore would not make changes nothing', async () => {+ const h = harness({ buildLaunch: vi.fn(async () => ({ error: 'WORKSPACE_MISSING', detail: 'The folder is gone.' })) })+ expect(await run(h.deps)).toEqual({ moved: false, reason: expect.stringContaining('The folder is gone.'), fellBack: false })+ expect(h.deps.createSeeded).not.toHaveBeenCalled()+ expect(h.events).not.toContain('hold')+ })++ it('a new engine that never appears falls back to the old pane', async () => {+ const h = harness({+ probeProcess: vi.fn(async () => null),+ // The old engine comes back before the gate lets held input through.+ relaunchOld: vi.fn(async () => { await after(2_000, null); h.events.push('relaunchOld (engine up)'); return true }),+ })+ const outcome = await run(h.deps)+ expect(outcome).toEqual({ moved: false, reason: expect.any(String), fellBack: true })+ expect(h.events).toEqual(['capture', 'buildLaunch', 'create', 'hold', 'stop', 'prepare', 'respawn', 'kill %7', 'relaunchOld (engine up)', 'release'])+ expect(h.deps.swap).not.toHaveBeenCalled()+ expect(h.row.runtime).toBe(OLD)+ expect(h.gate.holding('a1')).toBe(false)+ })++ it('an engine seen only once is not proven: one that exits at once falls back', async () => {+ let probes = 0+ const h = harness({ probeProcess: vi.fn(async () => (probes++ === 0 ? ID : null)) })+ expect(await run(h.deps)).toMatchObject({ moved: false, fellBack: true })+ expect(h.deps.swap).not.toHaveBeenCalled()+ })++ it('a failed relaunch in the old pane still lets the input go, and says it did not fall back', async () => {+ const h = harness()+ h.deps.respawn = vi.fn(async () => { h.events.push('respawn'); return { ok: false, reason: 'host refused' } })+ h.deps.relaunchOld = vi.fn(async () => { h.events.push('relaunchOld'); return false })+ expect(await run(h.deps)).toEqual({ moved: false, reason: expect.stringContaining('host refused'), fellBack: false })+ // Input then goes to the old pane, as it does after any failed restart.+ expect(h.events.slice(-4)).toEqual(['respawn', 'kill %7', 'relaunchOld', 'release'])+ expect(h.routes.size).toBe(0)+ expect(h.gate.holding('a1')).toBe(false)+ })++ it('never relaunches the old engine while the new pane may still run one', async () => {+ const h = harness({ probeProcess: vi.fn(async () => null), killPane: vi.fn(async () => false) })+ expect(await run(h.deps)).toMatchObject({ moved: false, fellBack: false })+ expect(h.deps.relaunchOld).not.toHaveBeenCalled()+ expect(h.events).toContain('release')+ // Its route stays held, so discovery never mints the pane a second agent; the old pane's is let go.+ expect([...h.routes.keys()]).toEqual([terminalRouteKey(NEW)])+ expect(h.deps.log).toHaveBeenCalledWith(expect.stringMatching(/warning: the new pane %7 was not confirmed closed/))+ })++ it('nothing after the switch relaunches the old engine', async () => {+ const h = harness({+ retarget: vi.fn(async () => { throw new Error('no stream') }),+ killPane: vi.fn(async () => { throw new Error('host gone') }),+ log: vi.fn(() => { throw new Error('no log') }),+ })+ expect(await run(h.deps)).toEqual({ moved: true, resumed: true })+ expect(h.deps.relaunchOld).not.toHaveBeenCalled()+ expect(h.row.runtime).toBe(NEW)+ expect(h.events.at(-1)).toBe('release')+ })++ it('open streams are retargeted after the swap, never before', async () => {+ const h = harness()+ await run(h.deps)+ expect(h.deps.retarget).toHaveBeenCalledTimes(1)+ expect(h.deps.retarget).toHaveBeenCalledWith('a1', NEW)+ expect(h.events).toContain('retarget(row names it)')+ expect(h.events).not.toContain('retarget(row names the old pane)')+ expect(h.events.indexOf('swap')).toBeLessThan(h.events.indexOf('retarget(row names it)'))+ expect(h.events.indexOf('retarget(row names it)')).toBeLessThan(h.events.indexOf('release'))++ // A move that falls back never points a stream anywhere: they stay on the old pane, which the row still names.+ const failed = harness({ probeProcess: vi.fn(async () => null) })+ await run(failed.deps)+ expect(failed.deps.retarget).not.toHaveBeenCalled()+ })++ it('the gate is released on every path', async () => {+ const boom = () => { throw new Error('boom') }+ const paths: Array<[string, Partial<MoveAgentDeps>]> = [+ ['capture fails', { capture: vi.fn(async () => null) }],+ ['buildLaunch throws', { buildLaunch: vi.fn(async () => boom()) }],+ ['create refused', { createSeeded: vi.fn(async () => ({ ok: false as const, reason: 'no' })) }],+ ['create throws', { createSeeded: vi.fn(async () => boom()) }],+ ['stop throws', { stopEngine: vi.fn(async () => boom()) }],+ ['stop unconfirmed', { stopEngine: vi.fn(async () => 'failed' as const) }],+ ['respawn refused', { respawn: vi.fn(async () => ({ ok: false, reason: 'no' })) }],+ ['respawn throws', { respawn: vi.fn(async () => boom()) }],+ ['probe throws', { probeProcess: vi.fn(async () => boom()) }],+ ['probe never proves', { probeProcess: vi.fn(async () => null) }],+ ['swap throws', { swap: vi.fn(() => boom()) }],+ ['retarget throws', { retarget: vi.fn(async () => boom()) }],+ ['kill throws', { killPane: vi.fn(async () => boom()) }],+ ['relaunch throws', { probeProcess: vi.fn(async () => null), relaunchOld: vi.fn(async () => boom()) }],+ ]+ for (const [name, overrides] of paths) {+ const h = harness(overrides)+ const delivered: string[] = []+ const outcome = await run(h.deps)+ expect(outcome, name).toHaveProperty('moved')+ if (h.events.includes('hold')) {+ expect(h.events.filter((event) => event === 'release'), name).toEqual(['release'])+ // Released last: nothing after it changes a pane.+ expect(h.events.at(-1), name).toBe('release')+ }+ h.gate.enqueue('a1', async () => { delivered.push('after') })+ await vi.advanceTimersByTimeAsync(0)+ expect(delivered, name).toEqual(['after'])+ expect(h.gate.holding('a1'), name).toBe(false)+ expect(h.routes.size, name).toBe(0)+ }+ })++ it('the hold, and the whole move, end well under two minutes when every step is slow or hangs', async () => {+ const slowest = harness({+ capture: vi.fn(() => after(4_000, 'old')),+ buildLaunch: vi.fn(() => after(9_000, LAUNCH)),+ createSeeded: vi.fn(() => after(4_000, { ok: true as const, runtime: NEW })),+ stopEngine: vi.fn(() => after(9_000, 'terminated' as const)),+ prepareResume: vi.fn(() => after(4_000, undefined)),+ respawn: vi.fn(() => after(4_000, { ok: true })),+ probeProcess: vi.fn(() => never<ProcessIdentity | null>()),+ killPane: vi.fn(() => after(4_000, true)),+ relaunchOld: vi.fn(() => never<boolean>()),+ })+ await run(slowest.deps)+ // Held: stop 9 + prepare 4 + respawn 4 + probe 30 + closing the new pane 4 + relaunch 20. Before it: 4 + 9 + 4.+ // Every bound was waited out, and no more.+ expect(slowest.heldMs()!).toBeGreaterThan(65_000)+ expect(slowest.heldMs()!).toBeLessThan(80_000)+ expect(movedMs).toBeGreaterThan(80_000)+ expect(movedMs).toBeLessThan(100_000)++ const hangs = harness({+ stopEngine: vi.fn(() => never<'terminated'>()),+ killPane: vi.fn(() => never<boolean>()),+ relaunchOld: vi.fn(() => never<boolean>()),+ })+ await run(hangs.deps)+ expect(hangs.heldMs()!).toBeLessThan(100_000)++ const movedButSlow = harness({+ retarget: vi.fn(() => never<void>()), releaseHold: vi.fn(() => never<void>()), killPane: vi.fn(() => never<boolean>()),+ })+ expect(await run(movedButSlow.deps)).toEqual({ moved: true, resumed: true })+ expect(movedButSlow.heldMs()!).toBeLessThan(100_000)+ })++ it('a launch that never comes ends the move with nothing changed and no route held', async () => {+ const h = harness({ buildLaunch: vi.fn(() => never<typeof LAUNCH>()) })+ expect(await run(h.deps)).toEqual({ moved: false, reason: expect.stringContaining('building the launch'), fellBack: false })+ expect(movedMs).toBeLessThan(120_000)+ expect(h.deps.createSeeded).not.toHaveBeenCalled()+ expect(h.deps.stopEngine).not.toHaveBeenCalled()+ expect(h.deps.killPane).not.toHaveBeenCalled()+ expect(h.events).not.toContain('hold')+ expect(h.holdRoute).not.toHaveBeenCalled()+ expect(h.routes.size).toBe(0)+ })++ it('a create answered after its bound closes the pane it made', async () => {+ const h = harness({ createSeeded: vi.fn(() => after(60_000, { ok: true as const, runtime: NEW })) })+ expect(await run(h.deps)).toMatchObject({ moved: false, fellBack: false })+ expect(h.deps.stopEngine).not.toHaveBeenCalled()+ expect(vi.mocked(h.deps.killPane).mock.calls.map(([runtime]) => runtime)).toEqual([NEW])+ expect(h.routes.size).toBe(0)+ })++ it('prepares the conversation only once the old engine is confirmed stopped', async () => {+ const h = harness()+ await run(h.deps)+ expect(h.events.indexOf('stop')).toBeLessThan(h.events.indexOf('prepare'))+ expect(h.events.indexOf('prepare')).toBeLessThan(h.events.indexOf('respawn'))+ expect(h.deps.prepareResume).toHaveBeenCalledTimes(1)++ for (const stopEngine of [async () => 'failed' as const, async () => 'not-ours' as const, () => never<'terminated'>()]) {+ const unconfirmed = harness({ stopEngine: vi.fn(stopEngine) })+ await run(unconfirmed.deps)+ expect(unconfirmed.deps.prepareResume).not.toHaveBeenCalled()+ expect(unconfirmed.deps.respawn).not.toHaveBeenCalled()+ }+ })++ it('a failed preparation falls back to the old pane', async () => {+ for (const prepareResume of [async () => { throw new Error('rollout repair failed') }, () => never<void>()]) {+ const h = harness({ prepareResume: vi.fn(prepareResume) })+ expect(await run(h.deps)).toEqual({ moved: false, reason: expect.any(String), fellBack: true })+ expect(h.deps.respawn).not.toHaveBeenCalled()+ expect(h.deps.swap).not.toHaveBeenCalled()+ expect(h.events.slice(-3)).toEqual(['kill %7', 'relaunchOld', 'release'])+ }+ })++ it('a route hold another owner took after the move\'s is not released by the move', async () => {+ const h = harness()+ let stopsHold: (() => void) | null = null+ // A Stop cancels the move while the old engine stops, and takes the old pane's route for its own retirement.+ let live = true+ h.deps.current = () => live+ h.deps.stopEngine = vi.fn(async () => {+ live = false+ stopsHold = h.deps.holdRoute(terminalRouteKey(OLD))+ return 'terminated' as const+ })+ expect(await run(h.deps)).toMatchObject({ moved: false })+ expect([...h.routes.keys()]).toEqual([terminalRouteKey(OLD)])+ stopsHold!()+ expect(h.routes.size).toBe(0)+ })++ it('a cancelled move (current() false) before step 5 changes nothing', async () => {+ // Each point the move can be cancelled at before the old engine is stopped, and whether a new pane exists then.+ const points: Array<[string, boolean]> = [['start', false], ['capture', false], ['buildLaunch', false], ['create', true], ['hold', true]]+ for (const [point, madePane] of points) {+ let live = point !== 'start'+ const h = harness()+ const inner = { ...h.deps }+ const cancelAt = <A extends unknown[], R>(name: string, step: (...args: A) => R) => (...args: A): R => {+ const result = step(...args)+ if (name === point) live = false+ return result+ }+ h.deps.current = () => live+ h.deps.capture = cancelAt('capture', inner.capture)+ h.deps.buildLaunch = cancelAt('buildLaunch', inner.buildLaunch)+ h.deps.createSeeded = cancelAt('create', inner.createSeeded)+ const gateHold = h.gate.hold+ h.gate.hold = cancelAt('hold', gateHold)+ const outcome = await run(h.deps)+ // Cancelled, not failed: the mover may try the agent again.+ expect(outcome, point).toMatchObject({ moved: false, fellBack: false, cancelled: true })+ expect(h.deps.stopEngine, point).not.toHaveBeenCalled()+ expect(h.deps.respawn, point).not.toHaveBeenCalled()+ expect(h.deps.swap, point).not.toHaveBeenCalled()+ expect(h.deps.relaunchOld, point).not.toHaveBeenCalled()+ // Only the pane the move made is closed; the old one is never touched.+ expect(vi.mocked(h.deps.killPane).mock.calls.map(([runtime]) => runtime), point).toEqual(madePane ? [NEW] : [])+ expect(h.gate.holding('a1'), point).toBe(false)+ expect(h.routes.size, point).toBe(0)+ }+ })++ it('input, a turn or a viewer during capture, launch or create cancels the move before the stop', async () => {+ // The agent stops being idle, quiet and unwatched while each step before the stop runs, and right before the stop.+ for (const point of ['capture', 'buildLaunch', 'create', 'hold'] as const) {+ let eligible = true+ const h = harness({ eligible: () => eligible })+ const inner = { ...h.deps }+ const at = <A extends unknown[], R>(name: string, step: (...args: A) => R) => (...args: A): R => {+ const result = step(...args)+ if (name === point) eligible = false+ return result+ }+ h.deps.capture = at('capture', inner.capture)+ h.deps.buildLaunch = at('buildLaunch', inner.buildLaunch)+ h.deps.createSeeded = at('create', inner.createSeeded)+ h.gate.hold = at('hold', h.gate.hold)+ const outcome = await run(h.deps)+ expect(outcome, point).toMatchObject({ moved: false, fellBack: false, cancelled: true })+ expect(h.deps.stopEngine, point).not.toHaveBeenCalled()+ expect(h.deps.prepareResume, point).not.toHaveBeenCalled()+ expect(h.deps.relaunchOld, point).not.toHaveBeenCalled()+ expect(vi.mocked(h.deps.killPane).mock.calls.map(([runtime]) => runtime), point).toEqual(point === 'capture' || point === 'buildLaunch' ? [] : [NEW])+ expect(h.gate.holding('a1'), point).toBe(false)+ expect(h.routes.size, point).toBe(0)+ }+ })++ it('once the old engine stopped, the agent becoming busy does not stop the move', async () => {+ let eligible = true+ const h = harness({ eligible: () => eligible, stopEngine: vi.fn(async () => { eligible = false; return 'terminated' as const }) })+ expect(await run(h.deps)).toEqual({ moved: true, resumed: true })+ })++ it('input that arrives once held, before the old engine stops, cancels the move and reaches the old pane', async () => {+ const h = harness()+ const delivered: string[] = []+ const hold = h.gate.hold+ h.gate.hold = (agentId) => {+ hold(agentId)+ h.gate.enqueue(agentId, async () => { delivered.push(h.row.runtime.paneId) })+ }+ expect(await run(h.deps)).toMatchObject({ moved: false, fellBack: false, cancelled: true })+ expect(h.deps.stopEngine).not.toHaveBeenCalled()+ expect(vi.mocked(h.deps.killPane).mock.calls.map(([runtime]) => runtime)).toEqual([NEW])+ expect(delivered).toEqual(['%1'])+ })++ it('a move cancelled once the old engine stopped leaves it stopped, for whoever cancelled it', async () => {+ let live = true+ const h = harness({ current: () => live, stopEngine: vi.fn(async () => { live = false; return 'terminated' as const }) })+ expect(await run(h.deps)).toMatchObject({ moved: false, fellBack: false, cancelled: true })+ expect(h.deps.respawn).not.toHaveBeenCalled()+ expect(h.deps.relaunchOld).not.toHaveBeenCalled()+ expect(vi.mocked(h.deps.killPane).mock.calls.map(([runtime]) => runtime)).toEqual([NEW])+ expect(h.events.at(-1)).toBe('release')+ })++ it('a pane with nothing to carry is created without a seed', async () => {+ const h = harness({ capture: vi.fn(async () => '') })+ expect(await run(h.deps)).toEqual({ moved: true, resumed: true })+ expect(h.deps.createSeeded).toHaveBeenCalledWith(expect.anything(), '')+ const request = moveCreateRequest('a1', { seed: '', command: ['sh'], cwd: '/w' })+ expect(request).not.toHaveProperty('seed')+ expect(moveCreateRequest('a1', { seed: 'x', command: ['sh'], cwd: '/w' })).toMatchObject({ seed: 'x' })+ })++ it('never moves an agent with no conversation to resume', async () => {+ const h = harness()+ const row = { ...session(), sessionId: '' } as RegisteredSession+ expect(await run(h.deps, row)).toMatchObject({ moved: false, fellBack: false })+ expect(h.deps.capture).not.toHaveBeenCalled()+ })+})++describe('moveCreateRequest', () => {+ it('opens the waiting shell in the row\'s folder, marked as the move of its agent', () => {+ expect(moveCreateRequest('a1', { seed: 'old\r\nlines', command: ['sh', '-c', 'wait'], cwd: '/w' })).toEqual({+ command: ['sh', '-c', 'wait'],+ cwd: '/w',+ env: { [MOVE_MARKER_ENV]: 'a1' },+ label: `${MOVE_MARKER_ENV}=a1`,+ seed: 'old\r\nlines',+ })+ expect(MOVE_MARKER_ENV).toBe('HARNESS_MOVE_OF')+ })+})++describe('removeOrphanMovePanes', () => {+ const backend = (inventory: TerminalInventoryResult) => {+ const kill = vi.fn(async (_runtime: TerminalRuntimeRef) => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))+ return { backend: { inventory: vi.fn(async () => inventory), kill } as unknown as TerminalBackend, kill }+ }+ const pane = (paneId: string, label?: string) => ({+ runtime: { backend: 'ptyhost' as const, instance: 'p2-1.2.3', paneId }, rootPid: 100, cwd: '/w', ...(label ? { label } : {}),+ })++ it('a_move_pane_left_by_a_dead_daemon_is_removed_before_discovery', async () => {+ const marker = moveCreateRequest('a1', { seed: '', command: ['sh'] }).label!+ const target = backend({+ state: 'available',+ roots: [+ // The daemon died mid-move: the row still names the old pane, and this one is no agent's.+ pane('%7', marker),+ // An earlier move that finished: its row names the pane, which keeps its label.+ pane('%9', moveCreateRequest('a2', { seed: '', command: ['sh'] }).label),+ // Any other pane is discovery's to judge.+ pane('%3'),+ ],+ })+ const unreachable = backend({ state: 'unavailable', reason: 'pty host is unavailable' })+ const rows = [+ { ...session(), runtimes: [OLD] },+ { ...session(), agentId: 'a2', runtimes: [{ backend: 'ptyhost', instance: 'p2-1.2.3', paneId: '%9' }] },+ ] as RegisteredSession[]+ expect(await removeOrphanMovePanes([target.backend, unreachable.backend], rows)).toEqual({ removed: 1, unconfirmed: [], keptPanes: [] })+ expect(target.kill.mock.calls.map(([runtime]) => runtime.paneId)).toEqual(['%7'])+ expect(unreachable.kill).not.toHaveBeenCalled()+ })++ it('names the agents whose orphan move pane could not be confirmed closed, for restore to hold', async () => {+ const refused = backend({ state: 'available', roots: [pane('%7', moveCreateRequest('a1', { seed: '', command: ['sh'] }).label)] })+ refused.kill.mockResolvedValue({ state: 'failed', dispatch: 'rejected', reason: 'busy' } as never)+ const throws = backend({ state: 'available', roots: [pane('%8', moveCreateRequest('a3', { seed: '', command: ['sh'] }).label)] })+ throws.kill.mockRejectedValue(new Error('host gone'))+ // And the panes themselves, whose routes restore holds so discovery never mints them an agent.+ expect(await removeOrphanMovePanes([refused.backend, throws.backend], [session()])).toEqual({+ removed: 0, unconfirmed: ['a1', 'a3'], keptPanes: [expect.objectContaining({ paneId: '%7' }), expect.objectContaining({ paneId: '%8' })],+ })+ })+})diff --git a/cli/src/lib/hostMove/moveAgent.ts b/cli/src/lib/hostMove/moveAgent.tsnew file mode 100644index 000000000..883fd7094--- /dev/null+++ b/cli/src/lib/hostMove/moveAgent.ts@@ -0,0 +1,384 @@+/**+ * Move one agent to another pty host (spec §4): its engine stops in the old pane and resumes its conversation in a+ * new pane seeded with the old one's scrollback, under the same agent id and row. When the new engine cannot be+ * proven in time, the engine comes back in the old pane, as a restart brings it back (`restartAgent.ts`).+ *+ * Dependency-injected like `restartAgent.ts`: the order of the steps, and what each failure undoes, is what this+ * file owns. The daemon's wiring (core/main.ts) supplies the backends, the registry and the reconciler.+ *+ * Two engines never hold one conversation at once: the new pane waits with no engine until the old engine is+ * confirmed stopped, and the old one is relaunched only once the new pane is confirmed closed.+ */++import type { AgentEngine } from '../../engines/types.js'+import type { TerminateOutcome } from '../deleteAgentFallback.js'+import type { RegisteredSession } from '../registry.js'+import { KILL_CONFIRMED } from '../restartAgent.js'+import type { RestoreAgentsDeps, RestoreLaunch } from '../restoreAgents.js'+import type { TerminalBackend } from '../terminalBackend.js'+import { sameProcessIdentity, terminalRouteKey } from '../terminalRuntime.js'+import type { ProcessIdentity, TerminalCreateRequest, TerminalRuntimeRef } from '../terminalTypes.js'+import type { MoveGate } from './gate.js'+import { seedFromCapture } from './seed.js'++/** Names a move's new pane after the agent it is for: in its environment, and as its label, which the host lists+ * back (`removeOrphanMovePanes`). */+export const MOVE_MARKER_ENV = 'HARNESS_MOVE_OF'++/** The new engine must be proven running within this, or the move falls back to the old pane. */+export const MOVE_TIMEOUT_MS = 30_000+/** How often the new pane is probed for its engine. An engine counts once two probes in a row see the same process:+ * a resume the engine refuses runs for an instant, as `paneSwapDeps`' `waitForProcess` settles for. */+export const MOVE_PROBE_INTERVAL_MS = 500++/**+ * Bounds on every step, so the whole move ends well under 120 s on every path: a mailbox message held longer is sent+ * again (gate.ts), and the routes the move holds have no auto-release. A step that overruns is abandoned and fails the+ * move as any failure there does.+ *+ * Before the hold: capture 5 + launch 10 + create 5 = 20 s. Held, on the longest path (a fallback whose every step+ * takes its whole bound): stop 10 + prepare 5 + respawn 5 + probe 30 + close the new pane 5 + relaunch 20 = 75 s.+ * Held, on the longest success: stop 10 + prepare 5 + respawn 5 + probe 30 + retarget 5 + release 5 + close the old+ * pane 5 = 65 s. At most 95 s in all.+ */+export const MOVE_CAPTURE_TIMEOUT_MS = 5_000+/** Restore's launch waits for the grid's or the Store's answer (`relaunchOverrides`) and the permission check. */+export const MOVE_LAUNCH_TIMEOUT_MS = 10_000+export const MOVE_CREATE_TIMEOUT_MS = 5_000+/** The old engine's stop: its native conversation released, then SIGTERM and, after a grace, SIGKILL. */+export const MOVE_STOP_TIMEOUT_MS = 10_000+/** Each single host or core call while held: preparing the conversation, respawn, retarget, release, a pane's close. */+export const MOVE_STEP_TIMEOUT_MS = 5_000+/** The old pane's relaunch: a restart's resume attempt and its fresh retry, each with its own wait for the engine. */+export const MOVE_RELAUNCH_TIMEOUT_MS = 20_000++/** `cancelled`: the move stopped because the agent was taken or used (a Stop, a delete, a replacement, input as the move+ * began), not because a step failed: the mover may try it again once it is quiet. */+export type MoveOutcome = { moved: true; resumed: boolean } | { moved: false; reason: string; fellBack: boolean; cancelled?: true }++export interface MoveAgentDeps {+ /** The old pane's scrollback (`capture` with `SEED_HISTORY_LINES`, ANSI kept); null when it could not be read. */+ capture(session: RegisteredSession): Promise<string | null>+ /** Open the new pane on the create backend, waiting with no engine: `moveCreateRequest` with a waiting command that+ * prints nothing over the seed (core/agents/hostMove.ts `moveWaitingArgv`). An empty [seed] means nothing to carry: no seed is sent. */+ createSeeded(session: RegisteredSession, seed: string): Promise<{ ok: true; runtime: TerminalRuntimeRef } | { ok: false; reason: string }>+ /** The backend's `respawn` of [runtime] with the launch's argv, cwd and env, as `restoreTerminals.ts` does: the+ * pane, and the scrollback it was seeded with, stay. */+ respawn(runtime: TerminalRuntimeRef, launch: RestoreLaunch): Promise<{ ok: boolean; reason?: string }>+ /** Restore's launch (`createRestoreLaunch`, core/agents/restoreLaunch.ts), shared and not copied. Asked with+ * `prepare: false`: it is built while the old engine still runs, so it must write neither the conversation nor the+ * row (`prepareResume` does, once that engine has stopped). */+ buildLaunch: RestoreAgentsDeps['buildLaunch']+ /** What `buildLaunch` leaves out with `prepare: false`, run once the old engine is confirmed stopped, as a restart+ * prepares after its kill: `prepareSessionResume` (the conversation's repair, a Pi session's copy) and+ * `refreshGridWebSearch`. Throws when the conversation could not be prepared. */+ prepareResume(session: RegisteredSession): Promise<void>+ /** Stop the old engine and keep its pane, as `paneSwapDeps`' `terminate` does after its `holdOpen` (core/agents/+ * swap.ts): a pane that is not held is closed with its process, and the fallback needs it. */+ stopEngine(session: RegisteredSession): Promise<TerminateOutcome>+ /** The engine process in [runtime], or null when none is found yet (`resolvePaneEngineProcess`). */+ probeProcess(runtime: TerminalRuntimeRef, engine: AgentEngine): Promise<ProcessIdentity | null>+ /** Point the row at [runtime], in one `registry.transaction`: `updateRuntimes(agentId, [runtime],+ * terminalRouteKey(runtime))` and `updateProcessIdentity`, then announce the session as a restart does. Throws+ * only when the row was not switched. */+ swap(agentId: string, runtime: TerminalRuntimeRef, identity: ProcessIdentity): void+ /** Move the agent's open streams to [runtime] (`TerminalStreamManager.retarget`). */+ retarget(agentId: string, runtime: TerminalRuntimeRef): Promise<void>+ /** Hand the new pane back to the backend's default disposal once it is the agent's, as a restart does+ * (`releaseHold`): it was created held. */+ releaseHold(runtime: TerminalRuntimeRef): Promise<void>+ /** Close [runtime]. True once the backend confirms it is gone. */+ killPane(runtime: TerminalRuntimeRef): Promise<boolean>+ /** Relaunch the engine in the old pane, with resume (`restartAgent`). True once it runs there. */+ relaunchOld(session: RegisteredSession): Promise<boolean>+ gate: MoveGate+ /** The reconciler's route hold (`agentReconciler.holdRoute(key, null)`), for the new pane from step 3 and the old+ * one from step 4: a pane seen mid-move would be read as an agent appearing or ending. Returns this hold's own+ * release, which lets go of the route only while this hold still owns it: a Stop or delete that cancelled the move+ * and took the route over keeps its hold. */+ holdRoute(routeKey: string): () => void+ /** False once the move is cancelled (Stop, delete, a replacement): `restartJobs.run`'s `current`. */+ current(): boolean+ /** Whether the agent still meets what the mover picked it for: idle, quiet, and nobody looking at it. Asked at every+ * point before the old engine stops, the last right before it: a person who types, a turn that starts or a viewer+ * who opens it in that window cancels the move with nothing changed. Never asked after the stop, where only+ * [current] counts: the engine is stopped by then, and the move ends one way or the other. */+ eligible(): boolean+ log(message: string): void+}++/** The new pane's create request: the waiting shell [command] in the row's folder, marked as [agentId]'s move. The pty+ * host holds every pane it creates (`hold: true`), which keeps the pane when the waiting shell is replaced. An empty+ * seed is left out: a pane seeded with nothing would start with a blank history line. */+export function moveCreateRequest(agentId: string, options: { seed: string; command: string[]; cwd?: string | null }): TerminalCreateRequest {+ return {+ command: options.command,+ ...(options.cwd ? { cwd: options.cwd } : {}),+ env: { [MOVE_MARKER_ENV]: agentId },+ label: moveLabel(agentId),+ ...(options.seed ? { seed: options.seed } : {}),+ }+}++function moveLabel(agentId: string): string {+ return `${MOVE_MARKER_ENV}=${agentId}`+}++/** The agent a pane labelled [label] was opened to move, or null for any other pane. */+export function moveMarkerOf(label: string | undefined): string | null {+ const prefix = `${MOVE_MARKER_ENV}=`+ return label?.startsWith(prefix) && label.length > prefix.length ? label.slice(prefix.length) : null+}++/**+ * Close every move pane no row names: a move a dead daemon left before its swap. The row still names the old pane,+ * which restore relaunches; this pane, possibly running an engine on the same conversation, would otherwise be minted+ * a second agent by discovery. Run once at core start, before restore and discovery. A pane a finished move made+ * keeps its label, and its row names it: it stays.+ *+ * Returns how many were closed, the agents whose orphan pane could not be confirmed closed, and those panes: restore+ * must hold those agents, or it would relaunch an engine beside the one that pane may still run, and the panes' routes,+ * or discovery would mint them an agent of their own.+ */+export async function removeOrphanMovePanes(+ backends: ReadonlyArray<Pick<TerminalBackend, 'inventory' | 'kill'>>,+ rows: ReadonlyArray<Pick<RegisteredSession, 'runtimes'>>,+): Promise<{ removed: number; unconfirmed: string[]; keptPanes: TerminalRuntimeRef[] }> {+ const named = new Set(rows.flatMap((row) => row.runtimes.map(terminalRouteKey)))+ let removed = 0+ const unconfirmed = new Set<string>()+ const keptPanes: TerminalRuntimeRef[] = []+ for (const backend of backends) {+ let inventory: Awaited<ReturnType<TerminalBackend['inventory']>>+ try { inventory = await backend.inventory() } catch { continue }+ // A host that cannot be listed keeps its panes: absence of an answer is not absence of a row.+ if (inventory.state !== 'available') continue+ for (const root of inventory.roots) {+ const agentId = moveMarkerOf(root.label)+ if (agentId === null || named.has(terminalRouteKey(root.runtime))) continue+ let closed = false+ try { closed = (await backend.kill(root.runtime)).state === 'succeeded' } catch { /* not confirmed */ }+ if (closed) removed+++ else { unconfirmed.add(agentId); keptPanes.push(root.runtime) }+ }+ }+ return { removed, unconfirmed: [...unconfirmed], keptPanes }+}++/** The line said of an agent `removeOrphanMovePanes` could not free, each time something would start its engine. */+export function moveHeldLine(agentId: string): string {+ return `[terminal] move ${agentId}: held until the next start: a pane its stopped move left was not confirmed closed`+}++type Bounded<T> = { done: true; value: T } | { done: false; reason: string }++/** [work], or why it did not finish within [ms]: thrown, or still running. A step that overruns is abandoned, not+ * stopped; what it may still do later is undone by the steps after it (the new pane is closed). */+async function bounded<T>(work: () => Promise<T>, ms: number, what: string): Promise<Bounded<T>> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race<Bounded<T>>([+ Promise.resolve().then(work).then((value) => ({ done: true as const, value })),+ new Promise<Bounded<T>>((resolve) => {+ timer = setTimeout(() => resolve({ done: false, reason: `${what} did not finish within ${ms / 1000} s` }), ms)+ }),+ ])+ } catch (error) {+ return { done: false, reason: `${what} failed: ${error instanceof Error ? error.message : String(error)}` }+ } finally {+ if (timer) clearTimeout(timer)+ }+}++const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))++/** The engine in [runtime], once two probes in a row see the same process, polled until `MOVE_TIMEOUT_MS`; null when+ * it is not proven by then, or the move was cancelled. */+async function proveEngine(deps: MoveAgentDeps, runtime: TerminalRuntimeRef, engine: AgentEngine): Promise<ProcessIdentity | null> {+ const deadline = Date.now() + MOVE_TIMEOUT_MS+ let previous: ProcessIdentity | null = null+ for (;;) {+ const left = deadline - Date.now()+ if (left <= 0) return null+ const probed = await bounded(() => deps.probeProcess(runtime, engine), left, 'the probe')+ const found = probed.done ? probed.value : null+ if (found && sameProcessIdentity(found, previous)) return found+ previous = found+ if (!deps.current()) return null+ const wait = Math.min(MOVE_PROBE_INTERVAL_MS, deadline - Date.now())+ if (wait <= 0) return null+ await sleep(wait)+ }+}++const CANCELLED = 'the move was cancelled'+const IN_USE = 'the agent was used as the move began'+const NOT_ELIGIBLE = 'the agent was used, started a turn or was looked at'++export async function moveAgent(session: RegisteredSession, deps: MoveAgentDeps): Promise<MoveOutcome> {+ const { agentId, engine } = session+ // A move restarts the engine: one with no conversation to resume would come back empty.+ if (!session.sessionId) return { moved: false, reason: 'no conversation to resume', fellBack: false }++ // A log line that throws must not turn a finished step into a failed one.+ const log = (message: string) => { try { deps.log(message) } catch { /* nothing to tell */ } }+ /** This move's own route holds, each with its owner-scoped release. */+ const routeHolds = new Map<string, () => void>()+ const holdRoute = (runtime: TerminalRuntimeRef) => {+ const key = terminalRouteKey(runtime)+ if (!routeHolds.has(key)) routeHolds.set(key, deps.holdRoute(key))+ }+ /** Routes the move must not let go of when it ends: a new pane that may still run, unclaimed by any row. */+ const keptRoutes = new Set<string>()+ /** The pane step 3 made; until the swap, the only pane a failure may close. */+ let created: TerminalRuntimeRef | null = null+ let holding = false+ /** Step 5 ran: the old engine may be stopped, and only `relaunchOld` brings it back. */+ let stopped = false+ /** Step 6 ran: the new pane may run an engine, so it must be confirmed closed before the old one is relaunched. */+ let respawned = false+ /** Step 8 ran: the row names the new pane, whose engine runs. Nothing after it may relaunch the old one. */+ let swapped = false++ /** Undo everything a failed or cancelled move did before its swap. The gate is released by the caller after it. */+ const recover = async (reason: string): Promise<MoveOutcome> => {+ const cancelled = reason === CANCELLED || reason === IN_USE || reason === NOT_ELIGIBLE+ const notMoved = (fellBack: boolean): MoveOutcome => ({ moved: false, reason, fellBack, ...(cancelled ? { cancelled: true as const } : {}) })+ if (swapped) {+ log(`[terminal] move ${agentId}: after the switch, ${reason}`)+ return { moved: true, resumed: true }+ }+ let newPaneClosed = true+ if (created) {+ const newPane = created+ const closed = await bounded(() => deps.killPane(newPane), MOVE_STEP_TIMEOUT_MS, 'closing the new pane')+ newPaneClosed = closed.done && closed.value+ if (!newPaneClosed) {+ // Its route stays held, so discovery never mints it a second agent, possibly beside the same conversation:+ // until the daemon restarts, whose start closes it (`removeOrphanMovePanes`), or a later close of it.+ keptRoutes.add(terminalRouteKey(newPane))+ log(`[terminal] move ${agentId}: warning: the new pane ${newPane.paneId} was not confirmed closed (${closed.done ? 'refused' : closed.reason}); its route stays held`)+ }+ }+ if (!stopped) return notMoved(false)+ // Cancelled by a Stop, a delete or a replacement: the engine stays stopped, for whoever cancelled the move.+ if (!deps.current()) return notMoved(false)+ if (respawned && !newPaneClosed) {+ // Relaunched now, the old engine could share its conversation with one still running in the new pane.+ log(`[terminal] move ${agentId}: not relaunched in the old pane while the new one may still run its engine`)+ return notMoved(false)+ }+ // The old pane's engine runs again before the gate opens, so held input reaches a live engine. When it does not+ // come back, the input still goes to the old pane, as it does after a failed restart.+ const relaunched = await bounded(() => deps.relaunchOld(session), MOVE_RELAUNCH_TIMEOUT_MS, 'the relaunch in the old pane')+ if (!relaunched.done) log(`[terminal] move ${agentId}: ${relaunched.reason}`)+ return notMoved(relaunched.done && relaunched.value)+ }++ /** Before the stop: why the move must not go on, or null. */+ const stale = (): string | null => !deps.current() ? CANCELLED : !deps.eligible() ? NOT_ELIGIBLE : null+ try {+ let reason = stale()+ if (reason) return await recover(reason)++ // Steps 1 to 3 write nothing: not the row, not the conversation, not the old pane. A failure or a cancel here+ // leaves the agent as it was, apart from the pane step 3 made.++ // 1. The old pane's scrollback.+ const capture = await bounded(() => deps.capture(session), MOVE_CAPTURE_TIMEOUT_MS, 'capturing the old pane')+ if (!capture.done || capture.value === null) return await recover(`could not capture the old pane${capture.done ? '' : `: ${capture.reason}`}`)+ if ((reason = stale())) return await recover(reason)+ const seed = seedFromCapture(capture.value)++ // 2. The launch, as restore builds it, resuming the row's conversation, without preparing it: the old engine still+ // runs, and the conversation is prepared once it has stopped (step 5).+ const built = await bounded(+ () => deps.buildLaunch(session, { resumeSessionId: session.sessionId, current: () => deps.current(), prepare: false }),+ MOVE_LAUNCH_TIMEOUT_MS, 'building the launch')+ if (!built.done) return await recover(built.reason)+ const launch = built.value+ if (!deps.current() || 'cancelled' in launch) return await recover(CANCELLED)+ if ('error' in launch) return await recover(`no launch: ${launch.detail}`)+ if ('held' in launch) return await recover(`the launch waits for ${launch.held}`)+ if ((reason = stale())) return await recover(reason)++ // 3. The new pane, waiting with no engine.+ const creating = Promise.resolve().then(() => deps.createSeeded(session, seed))+ const made = await bounded(() => creating, MOVE_CREATE_TIMEOUT_MS, 'opening the new pane')+ if (!made.done) {+ // A create answered after its bound made a pane nothing will use: close it then.+ void creating.then(async (late) => {+ if (late.ok && !(await deps.killPane(late.runtime))) log(`[terminal] move ${agentId}: warning: a late new pane ${late.runtime.paneId} was not confirmed closed`)+ }).catch(() => { /* the next core start closes it (`removeOrphanMovePanes`) */ })+ return await recover(made.reason)+ }+ if (!made.value.ok) return await recover(`could not open a pane on the new host: ${made.value.reason}`)+ created = made.value.runtime+ holdRoute(created)+ if ((reason = stale())) return await recover(reason)++ // 4. From here until release, what is typed or sent to the agent waits (gate.ts), and the old pane's route is+ // held: its engine is about to stop, which must not read as the agent ending.+ for (const runtime of session.runtimes) holdRoute(runtime)+ deps.gate.hold(agentId)+ holding = true+ if (!deps.current()) return await recover(CANCELLED)+ // Someone reached for the agent: nothing has changed yet, so give it back untouched.+ if (deps.gate.touched(agentId)) return await recover(IN_USE)+ // The last look before anything changes: a turn that began, or a viewer who opened it, since the pick.+ if ((reason = stale())) return await recover(reason)++ // 5. The old engine stops; its pane stays, for the fallback. Only then is the conversation prepared for its resume,+ // as a restart prepares after its kill.+ stopped = true+ const stop = await bounded(() => deps.stopEngine(session), MOVE_STOP_TIMEOUT_MS, `stopping ${engine}`)+ if (!stop.done) return await recover(stop.reason)+ if (!KILL_CONFIRMED.has(stop.value)) return await recover(`could not confirm the old ${engine} process stopped (${stop.value})`)+ if (!deps.current()) return await recover(CANCELLED)+ const prepared = await bounded(() => deps.prepareResume(session), MOVE_STEP_TIMEOUT_MS, `preparing the ${engine} conversation`)+ if (!prepared.done) return await recover(prepared.reason)+ if (!deps.current()) return await recover(CANCELLED)++ // 6. The engine resumes in the new pane, over its scrollback.+ respawned = true+ const newPane = created+ const spawn = await bounded(() => deps.respawn(newPane, launch), MOVE_STEP_TIMEOUT_MS, `starting ${engine} in the new pane`)+ if (!spawn.done) return await recover(spawn.reason)+ if (!spawn.value.ok) return await recover(`could not start ${engine} in the new pane: ${spawn.value.reason ?? 'unknown reason'}`)+ if (!deps.current()) return await recover(CANCELLED)++ // 7. Proven running there.+ const identity = await proveEngine(deps, newPane, engine)+ if (!deps.current()) return await recover(CANCELLED)+ if (!identity) return await recover(`${engine} was not proven running in the new pane within ${MOVE_TIMEOUT_MS / 1000} s`)++ // 8. The row names the new pane first, synchronously, and only then are the streams moved: a stream opened during+ // the hold opened on the pane the row named, and retarget moves it with the rest. Retargeted before the switch, a+ // stream opened in between would land on the old pane and stay there.+ try { deps.swap(agentId, newPane, identity) } catch (error) {+ return await recover(`could not switch the row: ${error instanceof Error ? error.message : String(error)}`)+ }+ swapped = true+ created = null+ const streams = await bounded(() => deps.retarget(agentId, newPane), MOVE_STEP_TIMEOUT_MS, 'moving open streams')+ if (!streams.done) log(`[terminal] move ${agentId}: ${streams.reason}`)+ const released = await bounded(() => deps.releaseHold(newPane), MOVE_STEP_TIMEOUT_MS, 'releasing the new pane')+ if (!released.done) log(`[terminal] move ${agentId}: ${released.reason}`)++ // 9. The old pane, which nothing names now.+ for (const old of session.runtimes) {+ const closed = await bounded(() => deps.killPane(old), MOVE_STEP_TIMEOUT_MS, 'closing the old pane')+ if (!closed.done || !closed.value) log(`[terminal] move ${agentId}: the old pane was not confirmed closed (${closed.done ? 'refused' : closed.reason})`)+ }+ return { moved: true, resumed: true }+ } catch (error) {+ return await recover(`the move failed: ${error instanceof Error ? error.message : String(error)}`)+ } finally {+ // 10. Held input goes to the pane the row names now: the new one, or the old one after a fallback.+ if (holding) await deps.gate.release(agentId).catch(() => { /* each delivery reports its own failure */ })+ for (const [key, release] of routeHolds) {+ if (keptRoutes.has(key)) continue+ try { release() } catch { /* the reconciler's own */ }+ }+ }+}diff --git a/cli/src/lib/hostMove/mover.spec.ts b/cli/src/lib/hostMove/mover.spec.tsnew file mode 100644index 000000000..5b36ec087--- /dev/null+++ b/cli/src/lib/hostMove/mover.spec.ts@@ -0,0 +1,370 @@+import { describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../registry.js'+import { resumesConversation } from '../resumeCapability.js'+import type { ActivityState } from '../turnActivity.js'+import type { TerminalRuntimeRef } from '../terminalTypes.js'+import { MoveGate } from './gate.js'+import { HAND_OVER_FLUSH_MS, HAND_OVER_MOVE_WAIT_MS, HostMover, settleMovesForHandOver, type HostMoverDeps } from './mover.js'+import type { MoveOutcome } from './moveAgent.js'+import { QUIET_MS, QuietClock } from './quiet.js'++const OLD_HOST = 'p2'+const TARGET = 'p2-1.2.3'++function row(agentId: string, fields: Partial<RegisteredSession> & { instance?: string } = {}): RegisteredSession {+ const { instance = OLD_HOST, ...rest } = fields+ const runtime: TerminalRuntimeRef = { backend: 'ptyhost', instance, paneId: `%${agentId}` }+ return {+ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w', runtimes: [runtime], tmuxPane: runtime.paneId,+ processIdentity: { pid: 42, executable: 'claude', startMarker: 'x' }, launch: { state: 'ready' },+ ...rest,+ } as unknown as RegisteredSession+}++/** A mover over [rows] on a fake clock, every agent idle, unwatched and free unless a test says otherwise. Agents+ * have been quiet for QUIET_MS once `settle()` has run one tick and advanced the clock. */+function harness(rows: RegisteredSession[], overrides: Partial<HostMoverDeps> = {}) {+ let clock = 1_000_000+ const now = () => clock+ const quiet = new QuietClock({ now })+ const activity = new Map<string, ActivityState>()+ const lookedAt = new Set<string>()+ const busy = new Set<string>()+ const drainHosts = new Set([OLD_HOST, 'p2-9.9.9'])+ let canSeed = true+ const moves: string[] = []+ let outcome: (agentId: string) => Promise<MoveOutcome> = async () => ({ moved: true, resumed: true })+ const log = vi.fn<(message: string) => void>()+ const deps: HostMoverDeps = {+ list: () => rows,+ isDrainRow: (r) => r.runtimes.some((runtime) => runtime.backend === 'ptyhost' && drainHosts.has(runtime.instance)),+ targetCanSeed: () => canSeed,+ target: TARGET,+ resumesConversation,+ activity: (r) => activity.get(r.agentId) ?? 'idle',+ quiet,+ lookedAt: (agentId) => lookedAt.has(agentId),+ busy: (agentId) => busy.has(agentId),+ // A moved agent's row names its pane on the target from then on, as the swap leaves it.+ move: async (r) => {+ moves.push(r.agentId)+ const result = await outcome(r.agentId)+ if (result.moved) r.runtimes = [{ backend: 'ptyhost', instance: TARGET, paneId: `%new-${r.agentId}` }]+ return result+ },+ log,+ ...overrides,+ }+ const mover = new HostMover(deps)+ return {+ mover, quiet, activity, lookedAt, busy, moves, log,+ lines: () => log.mock.calls.map(([line]) => line),+ advance: (ms: number) => { clock += ms },+ setCanSeed: (value: boolean) => { canSeed = value },+ setOutcome: (fn: (agentId: string) => Promise<MoveOutcome>) => { outcome = fn },+ /** One tick to start every clock, then enough time for each agent to count as quiet. */+ settle: async () => { await mover.step(); clock += QUIET_MS },+ }+}++describe('HostMover', () => {+ it('moves an idle, quiet, unwatched conversation agent on an old host', async () => {+ const h = harness([row('a1')])+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual(['a1'])+ expect(h.lines()).toContain('[terminal] move a1: moved (resumed)')+ })++ it('a working agent is not moved', async () => {+ const h = harness([row('a1')])+ h.activity.set('a1', 'working')+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move a1: skipped (working)')+ })++ it('unknown activity is not moved', async () => {+ const h = harness([row('a1')])+ h.activity.set('a1', 'unknown')+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move a1: skipped (activity unknown)')+ })++ it('input within QUIET_MS blocks', async () => {+ const h = harness([row('a1')])+ await h.mover.step()+ h.advance(QUIET_MS - 60_000)+ h.quiet.noteInput('a1')+ h.advance(60_000)+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move a1: skipped (not quiet yet)')+ // Quiet for the whole period since that input: now it moves.+ h.advance(QUIET_MS)+ await h.mover.step()+ expect(h.moves).toEqual(['a1'])+ })++ it('a looked-at agent is not moved', async () => {+ const h = harness([row('a1')])+ h.lookedAt.add('a1')+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move a1: skipped (looked at)')+ })++ it('a terminal is never moved', async () => {+ const h = harness([row('t1', { engine: 'terminal' as RegisteredSession['engine'], sessionId: undefined })])+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move t1: skipped (a terminal)')+ })++ it('a fresh engine is never moved', async () => {+ // An engine with no resume argv (resumeCapability.ts `fresh`): moved, it would come back in a new conversation.+ const fresh = vi.fn((engine: string, sessionId: string | null | undefined) => engine !== 'devin' && !!sessionId)+ const h = harness([row('d1', { engine: 'devin' as RegisteredSession['engine'] })], { resumesConversation: fresh })+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move d1: skipped (its engine cannot resume)')+ })++ it('no session id is never moved', async () => {+ const h = harness([row('a1', { sessionId: null as unknown as string })])+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move a1: skipped (no session id)')+ })++ it('a busy agent is not moved', async () => {+ const h = harness([row('a1')])+ h.busy.add('a1')+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move a1: skipped (busy)')+ h.busy.delete('a1')+ await h.mover.step()+ expect(h.moves).toEqual(['a1'])+ })++ it('one at a time', async () => {+ const h = harness([row('a1'), row('a2')])+ let finish!: (outcome: MoveOutcome) => void+ h.setOutcome(() => new Promise<MoveOutcome>((resolve) => { finish = resolve }))+ await h.settle()+ const first = h.mover.step()+ await h.mover.step()+ await h.mover.step()+ expect(h.moves).toHaveLength(1)+ finish({ moved: true, resumed: true })+ await first+ h.setOutcome(async () => ({ moved: true, resumed: true }))+ await h.mover.step()+ expect(h.moves).toHaveLength(2)+ expect(new Set(h.moves)).toEqual(new Set(['a1', 'a2']))+ })++ it('moves the agent quiet the longest first', async () => {+ const h = harness([row('a1'), row('a2')])+ await h.mover.step()+ h.advance(QUIET_MS)+ h.quiet.noteInput('a1')+ h.advance(QUIET_MS)+ await h.mover.step()+ expect(h.moves).toEqual(['a2'])+ })++ it('a failed agent is not retried until restart', async () => {+ const h = harness([row('a1')])+ h.setOutcome(async () => ({ moved: false, reason: 'the new engine was not proven', fellBack: true }))+ await h.settle()+ await h.mover.step()+ await h.mover.step()+ await h.mover.step()+ expect(h.moves).toEqual(['a1'])+ expect(h.lines()).toContain('[terminal] move a1: failed (the new engine was not proven)')+ expect(h.lines()).toContain('[terminal] move a1: skipped (a move failed this start)')+ // A move that throws counts as failed too.+ const t = harness([row('a2')])+ t.setOutcome(async () => { throw new Error('boom') })+ await t.settle()+ await t.mover.step()+ await t.mover.step()+ expect(t.moves).toEqual(['a2'])+ expect(t.lines()).toContain('[terminal] move a2: failed (boom)')+ })++ it('a cancelled move is not a failure: the agent may move later', async () => {+ const h = harness([row('a1')])+ h.setOutcome(async () => ({ moved: false, reason: 'the move was cancelled', fellBack: false, cancelled: true }))+ await h.settle()+ await h.mover.step()+ h.setOutcome(async () => ({ moved: true, resumed: true }))+ await h.mover.step()+ expect(h.moves).toEqual(['a1', 'a1'])+ expect(h.lines()).toContain('[terminal] move a1: skipped (the move was cancelled)')+ })++ it('an agent on the target host is never a candidate', async () => {+ const h = harness([row('a1', { instance: TARGET })])+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ // Not a drain host's agent: nothing to say about it.+ expect(h.lines().filter((line) => line.includes('a1'))).toEqual([])+ })++ it('nothing moves while the target cannot seed', async () => {+ const h = harness([row('a1')])+ h.setCanSeed(false)+ await h.settle()+ await h.mover.step()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toEqual([`[terminal] ptyhost: target ${TARGET} cannot seed; agents stay on their hosts`])+ })++ it('a turn that starts and ends between two ticks restarts the quiet period', async () => {+ const h = harness([row('a1')])+ await h.settle()+ // The funnel's live events (core/turns/funnel.ts `working`): a /loop wake-up, over before the next tick reads idle.+ h.quiet.noteActivity('a1', 'working')+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toContain('[terminal] move a1: skipped (not quiet yet)')+ h.advance(QUIET_MS)+ await h.mover.step()+ expect(h.moves).toEqual(['a1'])+ })++ it('says when a target that could not seed can, once', async () => {+ const h = harness([row('a1')])+ h.setCanSeed(false)+ await h.mover.step()+ h.setCanSeed(true)+ await h.settle()+ await h.mover.step()+ expect(h.lines().filter((line) => line.startsWith('[terminal] ptyhost:'))).toEqual([+ `[terminal] ptyhost: target ${TARGET} cannot seed; agents stay on their hosts`,+ `[terminal] ptyhost: target ${TARGET} can seed now; idle agents move to it`,+ ])+ expect(h.moves).toEqual(['a1'])+ })++ it('an agent on a newer host moves after a rollback', async () => {+ // The target went back to 1.2.3; a host of 9.9.9 is drained like any other.+ const h = harness([row('a1', { instance: 'p2-9.9.9' })])+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual(['a1'])+ })++ it('logs a skip once per reason change, not every tick', async () => {+ const h = harness([row('a1')])+ h.activity.set('a1', 'working')+ await h.mover.step()+ await h.mover.step()+ await h.mover.step()+ h.activity.set('a1', 'idle')+ await h.mover.step()+ await h.mover.step()+ expect(h.lines()).toEqual(['[terminal] move a1: skipped (working)', '[terminal] move a1: skipped (not quiet yet)'])+ })++ it('never moves a held, starting or guest agent, nor one with no engine process', async () => {+ const h = harness([+ row('h1', { launch: { state: 'held', service: 'models', detail: 'x' } }),+ row('s1', { launch: { state: 'starting' } }),+ row('g1', { guest: 'u1' }),+ row('p1', { processIdentity: null }),+ ])+ await h.settle()+ await h.mover.step()+ expect(h.moves).toEqual([])+ expect(h.lines()).toEqual(expect.arrayContaining([+ '[terminal] move h1: skipped (not launched)',+ '[terminal] move s1: skipped (not launched)',+ "[terminal] move g1: skipped (a guest's harness)",+ '[terminal] move p1: skipped (no engine process)',+ ]))+ })+})++describe('a hand-over while a move holds input', () => {+ /** A mover whose one move holds [gate] for a1 until the test lets it finish, then releases it as moveAgent does. */+ async function holding(gate: MoveGate) {+ const h = harness([row('a1'), row('a2')])+ let finish!: () => void+ h.setOutcome(async (agentId) => {+ gate.hold(agentId)+ await new Promise<void>((resolve) => { finish = resolve })+ await gate.release(agentId)+ return { moved: true, resumed: true }+ })+ await h.settle()+ const moving = h.mover.step()+ await vi.waitFor(() => expect(gate.holding('a1') || gate.holding('a2')).toBe(true))+ const held = gate.holding('a1') ? 'a1' : 'a2'+ return { h, moving, held, finish: () => finish() }+ }++ it('waits for the move to finish, and its own release delivers the held keystrokes; no move starts after', async () => {+ const gate = new MoveGate()+ const { h, moving, held, finish } = await holding(gate)+ const written: string[] = []+ gate.enqueue(held, async () => { written.push('k1') })+ gate.enqueue(held, async () => { written.push('k2') })+ const lines: string[] = []+ const settled = settleMovesForHandOver({ mover: h.mover, gate, log: (line) => lines.push(line) })+ await new Promise((resolve) => setTimeout(resolve, 20))+ expect(written).toEqual([])+ finish()+ await settled+ await moving+ expect(written).toEqual(['k1', 'k2'])+ expect(lines).toEqual([])+ // Stopped: the other agent, as eligible as before, does not move.+ expect(h.mover.stopped).toBe(true)+ await h.mover.step()+ expect(h.moves).toHaveLength(1)+ })++ it('past its bound, writes every held keystroke to the row\'s current pane before the hand-over goes on', async () => {+ const gate = new MoveGate()+ const { h, held, finish } = await holding(gate)+ const written: string[] = []+ gate.enqueue(held, async () => { written.push('k1') })+ gate.enqueue(held, async () => { written.push('k2') })+ const lines: string[] = []+ await settleMovesForHandOver({ mover: h.mover, gate, log: (line) => lines.push(line), waitMs: 30 })+ expect(written).toEqual(['k1', 'k2'])+ expect(gate.holding(held)).toBe(false)+ expect(lines).toEqual([`[terminal] move: a move still holds the input of ${held} after 0.03 s — delivering it to the pane the row names before handing over`])+ // The move's own release later finds nothing left.+ finish()+ expect(HAND_OVER_MOVE_WAIT_MS + HAND_OVER_FLUSH_MS).toBeLessThanOrEqual(25_000)+ })++ it('does not wait with nothing held, nor without a mover', async () => {+ const gate = new MoveGate()+ const h = harness([row('a1')])+ let started = false+ h.setOutcome(async () => { started = true; return new Promise<MoveOutcome>(() => {}) })+ await h.settle()+ void h.mover.step()+ await vi.waitFor(() => expect(started).toBe(true))+ const before = Date.now()+ await settleMovesForHandOver({ mover: h.mover, gate, log: () => {} })+ await settleMovesForHandOver({ mover: null, gate, log: () => {} })+ expect(Date.now() - before).toBeLessThan(1_000)+ })+})diff --git a/cli/src/lib/hostMove/mover.ts b/cli/src/lib/hostMove/mover.tsnew file mode 100644index 000000000..cc515a71a--- /dev/null+++ b/cli/src/lib/hostMove/mover.ts@@ -0,0 +1,190 @@+/**+ * Which agent moves to the target pty host, and when (spec §4). After each reconcile pass (core/main.ts+ * `onReconciled`) the mover looks at the agents on the hosts being drained, keeps each one's quiet clock, and moves at+ * most one: the one quiet the longest among those that meet every condition. How a move happens is moveAgent.ts.+ *+ * Moving restarts the engine, so only an agent nobody is using moves: idle (never working, never unknown: a question+ * waiting for its answer reads as working, and the gate's refusal of an answer during a hold relies on that), with no+ * input for `QUIET_MS`, not looked at, and with no restart, stop, restore or held control in flight. An agent that+ * never meets them stays on its old host until it ends.+ */+import { isTerminalEngine, type AgentEngine } from '../../engines/types.js'+import type { RegisteredSession } from '../registry.js'+import type { ActivityState } from '../turnActivity.js'+import type { MoveGate } from './gate.js'+import type { MoveOutcome } from './moveAgent.js'+import { QUIET_MS, type QuietClock } from './quiet.js'++/** How long a hand-over waits for a move that holds input to finish (`settleMovesForHandOver`). */+export const HAND_OVER_MOVE_WAIT_MS = 20_000+/** How long it then gives the held input to be written, when it could not wait the move out. */+export const HAND_OVER_FLUSH_MS = 5_000++export interface HostMoverDeps {+ /** The registry's rows, read on each step. */+ list(): readonly RegisteredSession[]+ /** Whether [row]'s pane is on a drain backend's host: an older one, or a newer one after a downgrade or rollback. */+ isDrainRow(row: RegisteredSession): boolean+ /** Whether the target host can seed a pane (`PtyHostBackend.canSeed`): a pre-G target gets no moves. */+ targetCanSeed(): boolean+ /** The target host's instance, for the line that says it cannot seed. */+ target: string+ /** `resumesConversation` (resumeCapability.ts): the engine has a resume argv and the row a session id. */+ resumesConversation(engine: AgentEngine, sessionId: string | null | undefined): boolean+ /** The agent's working state as the windows are told it (`activityFrame`). */+ activity(row: RegisteredSession): ActivityState+ quiet: QuietClock+ /** A person can see its terminal (`TerminalStreamManager.isLookedAt`, a Share viewer's stream). */+ lookedAt(agentId: string): boolean+ /** A restart, stop, restore or held control owns the agent now. */+ busy(agentId: string): boolean+ /** One move (moveAgent.ts), run as the agent's lifecycle operation. */+ move(row: RegisteredSession): Promise<MoveOutcome>+ log(message: string): void+}++export class HostMover {+ private moving = false+ /** The move in flight, settled once it has ended (its gate released). */+ private inFlight: Promise<void> | null = null+ private halted = false+ /** Agents whose move failed since this core started: not tried again until the next start (spec §4). */+ private readonly failed = new Set<string>()+ /** The reason each agent was last said to be skipped, so a skip is logged once per change, not every tick. */+ private readonly skipped = new Map<string, string>()+ private toldCannotSeed = false+ private toldCanSeed = false++ constructor(private readonly deps: HostMoverDeps) {}++ /** No move starts from now on: the core is handing over (`settleMovesForHandOver`). One in flight goes on. */+ stop(): void {+ this.halted = true+ }++ get stopped(): boolean {+ return this.halted+ }++ /** Settles once the move in flight, if any, has ended. */+ settled(): Promise<void> {+ return this.inFlight ?? Promise.resolve()+ }++ async step(): Promise<void> {+ if (this.halted) return+ if (!this.deps.targetCanSeed()) {+ if (!this.toldCannotSeed) {+ this.toldCannotSeed = true+ this.deps.log(`[terminal] ptyhost: target ${this.deps.target} cannot seed; agents stay on their hosts`)+ }+ return+ }+ // A target attached after the first tick (or reconnected to a newer build) may seed after all: say so once.+ if (this.toldCannotSeed && !this.toldCanSeed) {+ this.toldCanSeed = true+ this.deps.log(`[terminal] ptyhost: target ${this.deps.target} can seed now; idle agents move to it`)+ }+ const rows = this.deps.list().filter((row) => this.deps.isDrainRow(row))+ // Each tick reads every drain agent's state, a move in flight or not: the quiet clock starts at the first idle.+ for (const row of rows) this.deps.quiet.noteActivity(row.agentId, this.deps.activity(row))+ const present = new Set(rows.map((row) => row.agentId))+ for (const agentId of this.skipped.keys()) if (!present.has(agentId)) this.skipped.delete(agentId)+ if (this.moving) return++ let pick: { row: RegisteredSession; quietFor: number } | null = null+ for (const row of rows) {+ const reason = this.refusal(row)+ if (reason) { this.skip(row.agentId, reason); continue }+ const quietFor = this.deps.quiet.quietFor(row.agentId)+ if (!pick || quietFor > pick.quietFor) pick = { row, quietFor }+ }+ if (!pick) return+ const { row } = pick+ this.skipped.delete(row.agentId)+ this.moving = true+ let ended!: () => void+ this.inFlight = new Promise<void>((resolve) => { ended = resolve })+ try {+ let outcome: MoveOutcome+ try { outcome = await this.deps.move(row) } catch (error) {+ outcome = { moved: false, reason: error instanceof Error ? error.message : String(error), fellBack: false }+ }+ if (outcome.moved) {+ this.deps.log(`[terminal] move ${row.agentId}: moved (${outcome.resumed ? 'resumed' : 'fresh'})`)+ } else if (outcome.cancelled) {+ // Someone reached for the agent, or a Stop or delete took it: nothing failed, and once it is quiet again it+ // may move.+ this.skip(row.agentId, outcome.reason)+ } else {+ this.failed.add(row.agentId)+ this.deps.log(`[terminal] move ${row.agentId}: failed (${outcome.reason})`)+ }+ } finally {+ this.moving = false+ this.inFlight = null+ ended()+ }+ }++ /** Why [row] may not move now, or null when it may. Permanent reasons first, then the ones a tick can change. */+ private refusal(row: RegisteredSession): string | null {+ if (isTerminalEngine(row.engine)) return 'a terminal'+ if (!row.sessionId) return 'no session id'+ if (!this.deps.resumesConversation(row.engine, row.sessionId)) return 'its engine cannot resume'+ // A guest's harness runs as the guest's own user; relaunched here it would run as the owner (restoreAgents.ts).+ if (row.guest) return "a guest's harness"+ if (this.failed.has(row.agentId)) return 'a move failed this start'+ // Held, starting or failed: no engine of its own runs in the pane to move.+ if (row.launch && row.launch.state !== 'ready') return 'not launched'+ if (!row.processIdentity) return 'no engine process'+ const activity = this.deps.activity(row)+ if (activity === 'working') return 'working'+ if (activity !== 'idle') return 'activity unknown'+ if (this.deps.quiet.quietFor(row.agentId) < QUIET_MS) return 'not quiet yet'+ if (this.deps.lookedAt(row.agentId)) return 'looked at'+ if (this.deps.busy(row.agentId)) return 'busy'+ return null+ }++ private skip(agentId: string, reason: string): void {+ if (this.skipped.get(agentId) === reason) return+ this.skipped.set(agentId, reason)+ this.deps.log(`[terminal] move ${agentId}: skipped (${reason})`)+ }+}++/**+ * What a hand-over does first, before its teardown closes the connections held input would be written through: no move+ * starts any more ([mover] stopped: one not yet past its old engine's stop cancels itself there, core/main.ts+ * `eligible`), and a move that holds input is waited for, at most [waitMs]: its own release then writes what was held+ * to the pane that stays. Past the bound, every held input is written to the pane each row names now (`releaseAll`),+ * within [flushMs], and the hand-over goes on. Nothing held: nothing to wait for. Both bounds and the teardown's own+ * (core/updateHandoff.ts `TEARDOWN_DEADLINE_MS`) fit in the master's hand-over grace (harnessd/supervisor.ts).+ */+export async function settleMovesForHandOver(o: {+ mover: Pick<HostMover, 'stop' | 'settled'> | null+ gate: Pick<MoveGate, 'held' | 'releaseAll'>+ log: (line: string) => void+ waitMs?: number+ flushMs?: number+}): Promise<void> {+ o.mover?.stop()+ if (o.gate.held().length === 0) return+ const waitMs = o.waitMs ?? HAND_OVER_MOVE_WAIT_MS+ if (o.mover) await within(o.mover.settled(), waitMs)+ const held = o.gate.held()+ if (held.length === 0) return+ o.log(`[terminal] move: a move still holds the input of ${held.join(', ')} after ${waitMs / 1000} s — delivering it to the pane the row names before handing over`)+ await within(o.gate.releaseAll(), o.flushMs ?? HAND_OVER_FLUSH_MS)+}++/** [work], or nothing once [ms] have passed. */+async function within(work: Promise<void>, ms: number): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ await Promise.race([work, new Promise<void>((resolve) => { timer = setTimeout(resolve, ms) })])+ } finally {+ clearTimeout(timer)+ }+}diff --git a/cli/src/lib/hostMove/quiet.spec.ts b/cli/src/lib/hostMove/quiet.spec.tsnew file mode 100644index 000000000..c57a8e28c--- /dev/null+++ b/cli/src/lib/hostMove/quiet.spec.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from 'vitest'+import { QUIET_MS, QuietClock } from './quiet.js'++function setup() {+ let t = 1_000_000+ const clock = new QuietClock({ now: () => t })+ return { clock, advance: (ms: number) => { t += ms } }+}++describe('QuietClock', () => {+ it('idle without input for QUIET_MS is quiet', () => {+ const { clock, advance } = setup()+ clock.noteActivity('a', 'idle')+ advance(QUIET_MS)+ expect(clock.quietFor('a')).toBeGreaterThanOrEqual(QUIET_MS)+ })++ it('input resets quiet', () => {+ const { clock, advance } = setup()+ clock.noteActivity('a', 'idle')+ advance(QUIET_MS)+ clock.noteInput('a')+ expect(clock.quietFor('a')).toBe(0)+ advance(1000)+ expect(clock.quietFor('a')).toBe(1000)+ })++ it('working or unknown is never quiet', () => {+ const { clock, advance } = setup()+ clock.noteActivity('a', 'working')+ advance(QUIET_MS * 2)+ expect(clock.quietFor('a')).toBe(0)+ clock.noteActivity('a', 'unknown')+ advance(QUIET_MS * 2)+ expect(clock.quietFor('a')).toBe(0)+ expect(clock.quietFor('never-seen')).toBe(0)+ })++ it('idle seen again after working restarts the clock', () => {+ const { clock, advance } = setup()+ clock.noteActivity('a', 'idle')+ advance(QUIET_MS)+ clock.noteActivity('a', 'working')+ advance(5000)+ clock.noteActivity('a', 'idle')+ expect(clock.quietFor('a')).toBe(0)+ advance(2000)+ expect(clock.quietFor('a')).toBe(2000)+ })++ it('repeated idle does not restart the clock; forget clears', () => {+ const { clock, advance } = setup()+ clock.noteActivity('a', 'idle')+ advance(1000)+ clock.noteActivity('a', 'idle')+ expect(clock.quietFor('a')).toBe(1000)+ clock.forget('a')+ expect(clock.quietFor('a')).toBe(0)+ })+})diff --git a/cli/src/lib/hostMove/quiet.ts b/cli/src/lib/hostMove/quiet.tsnew file mode 100644index 000000000..406154bbb--- /dev/null+++ b/cli/src/lib/hostMove/quiet.ts@@ -0,0 +1,53 @@+import type { ActivityState } from '../turnActivity.js'++/** Idle with no input for this long before an agent may be moved to a new host. */+export const QUIET_MS = 300_000++interface Entry {+ idleSince: number | null+ lastInput: number | null+}++/**+ * Tracks how long an agent has been idle and untouched. Moving an engine+ * restarts it, so the mover only acts on agents nobody is using.+ */+export class QuietClock {+ private readonly entries = new Map<string, Entry>()++ constructor(private readonly deps: { now: () => number }) {}++ private entry(agentId: string): Entry {+ let e = this.entries.get(agentId)+ if (!e) {+ e = { idleSince: null, lastInput: null }+ this.entries.set(agentId, e)+ }+ return e+ }++ noteInput(agentId: string): void {+ this.entry(agentId).lastInput = this.deps.now()+ }++ noteActivity(agentId: string, state: ActivityState): void {+ const e = this.entry(agentId)+ if (state === 'idle') {+ // Only the first idle after anything else starts the clock; polling+ // every tick must not keep restarting it.+ if (e.idleSince === null) e.idleSince = this.deps.now()+ } else {+ e.idleSince = null+ }+ }++ quietFor(agentId: string): number {+ const e = this.entries.get(agentId)+ if (!e || e.idleSince === null) return 0+ return Math.max(0, this.deps.now() - Math.max(e.idleSince, e.lastInput ?? 0))+ }++ forget(agentId: string): void {+ this.entries.delete(agentId)+ }+}diff --git a/cli/src/lib/hostMove/seed.spec.ts b/cli/src/lib/hostMove/seed.spec.tsnew file mode 100644index 000000000..45dfaae3e--- /dev/null+++ b/cli/src/lib/hostMove/seed.spec.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest'+import { MAX_FRAME } from '../ptyHost/protocol.js'+import { seedFromCapture, SEED_HISTORY_LINES, SEED_MAX_BYTES } from './seed.js'++describe('seedFromCapture', () => {+ it('keeps every line under the cap', () => {+ expect(seedFromCapture('a\nb\nc')).toBe('a\r\nb\r\nc')+ expect(SEED_MAX_BYTES).toBe(4 * 1024 * 1024)+ expect(SEED_HISTORY_LINES).toBe(2000)+ const text = Array.from({ length: 500 }, () => 'x'.repeat(99)).join('\n')+ expect(Buffer.byteLength(seedFromCapture(text, 1000))).toBeLessThanOrEqual(1000)+ })++ it('drops the oldest lines first', () => {+ // Each break costs four: `\r\n` as the create request's JSON writes it.+ expect(seedFromCapture('one\ntwo\nthree\nfour', 13)).toBe('three\r\nfour')+ expect(seedFromCapture('one\ntwo\nthree\nfour', 12)).toBe('four')+ expect(seedFromCapture('one\ntwo\nthree', 3)).toBe('')+ })++ it('caps the seed as the create request carries it: JSON, where each ESC is six bytes', () => {+ // 3 MB of colour codes: under the cap raw, but escaped as `\u001b` six times that, past the host's 8 MB frame.+ const line = '\x1b[31mx\x1b[0m'.repeat(100)+ const text = Array.from({ length: 3 * 1024 * 1024 / line.length }, () => line).join('\n')+ const seed = seedFromCapture(text)+ expect(seed.length).toBeGreaterThan(0)+ expect(Buffer.byteLength(JSON.stringify(seed))).toBeLessThanOrEqual(SEED_MAX_BYTES + 2)+ expect(SEED_MAX_BYTES).toBeLessThanOrEqual(MAX_FRAME / 2)+ // Non-ASCII text is its UTF-8 bytes in JSON too.+ expect(seedFromCapture('\u00e9\u00e9\n\u00e9', 2)).toBe('\u00e9')+ })++ it('uses CRLF', () => {+ expect(seedFromCapture('a\r\nb\nc\r\n')).toBe('a\r\nb\r\nc')+ })+})diff --git a/cli/src/lib/hostMove/seed.ts b/cli/src/lib/hostMove/seed.tsnew file mode 100644index 000000000..7baf631f8--- /dev/null+++ b/cli/src/lib/hostMove/seed.ts@@ -0,0 +1,34 @@+/**+ * The most scrollback a moved pane is seeded with, as the create request carries it: JSON-encoded, where each ESC of a+ * colour code is six bytes (`\u001b`) and each line break four (`\r\n`). Half the host's frame limit (`MAX_FRAME`,+ * 8 MiB), so a seed never comes near it whatever the scrollback holds. The oldest lines are dropped first.+ */+export const SEED_MAX_BYTES = 4 * 1024 * 1024++/** How many history lines the old pane is captured with (`capture(..., { historyLines, ansi: true })`). */+export const SEED_HISTORY_LINES = 2000++/** What [line] costs in the create request's JSON: its escaped UTF-8 bytes, without the quotes. */+const encodedBytes = (line: string): number => Buffer.byteLength(JSON.stringify(line)) - 2+/** `\r\n` escaped. */+const BREAK_BYTES = 4++/**+ * A capture as the seed a new pty pane starts with: lines ending in `\r\n`, as the host's terminal expects, cut from the+ * top by whole lines until the text, JSON-encoded, fits `maxBytes`. A cut mid-line would start the pane on a torn escape+ * or a torn character. A single last line over the cap leaves an empty seed.+ */+export function seedFromCapture(text: string, maxBytes: number = SEED_MAX_BYTES): string {+ const lines = text.split(/\r?\n/)+ // A capture ends with a line break; the host drops one trailing break itself, so this one is not a line.+ if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()+ let bytes = 0+ let start = lines.length+ while (start > 0) {+ const cost = encodedBytes(lines[start - 1]!) + (start < lines.length ? BREAK_BYTES : 0)+ if (bytes + cost > maxBytes) break+ bytes += cost+ start--+ }+ return lines.slice(start).join('\r\n')+}diff --git a/cli/src/lib/ptyHost/client.spec.ts b/cli/src/lib/ptyHost/client.spec.tsindex c1a87579d..2d159c1c8 100644--- a/cli/src/lib/ptyHost/client.spec.ts+++ b/cli/src/lib/ptyHost/client.spec.ts@@ -24,6 +24,8 @@ interface FakeHostOptions {* one made with a guessed token.*/proof?: 'right' | 'none' | 'reflect' | 'fromAuth' | 'guess'+ /** The hello reply's `features`: absent (a host from before them) unless given. */+ features?: unknown}interface FakeHost {discovery: PtyHostDiscovery@@ -79,7 +81,8 @@ async function fakeHost(options: FakeHostOptions = {}): Promise<FakeHost> {: options.proof === 'fromAuth' ? { proof: helloProof(sent, nonce) }: options.proof === 'guess' ? { proof: helloProof('tok-guess', nonce) }: { proof: helloProof(token, nonce) }- const ok = Buffer.from(`${JSON.stringify({ hello: { ok: true, instance: 'p1', version: 'test', pid: 1, ...proof } })}\n`)+ const features = options.features === undefined ? {} : { features: options.features }+ const ok = Buffer.from(`${JSON.stringify({ hello: { ok: true, instance: 'p1', version: 'test', pid: 1, ...features, ...proof } })}\n`)socket.write(role === 'stream' && options.streamGreeting ? Buffer.concat([ok, options.streamGreeting]) : ok)continue}@@ -150,6 +153,15 @@ describe('PtyHostClient.connect', () => {expect(fake.hellos).toHaveLength(2)})+ it('features come from the hello reply, empty when absent', async () => {+ expect((await connected({ features: ['seed'] })).client.features).toEqual(['seed'])+ // A host from before features lists none.+ expect((await connected()).client.features).toEqual([])+ // Only names: anything else in the list, or a list that is not one, is no feature.+ expect((await connected({ features: ['seed', 7, null, 'later'] })).client.features).toEqual(['seed', 'later'])+ expect((await connected({ features: 'seed' })).client.features).toEqual([])+ })+it('refuses a host whose hello names another pid than its discovery file', async () => {const fake = await fakeHost()cleanup.push(() => fake.close())diff --git a/cli/src/lib/ptyHost/client.ts b/cli/src/lib/ptyHost/client.tsindex a95eac246..1e68dabc2 100644--- a/cli/src/lib/ptyHost/client.ts+++ b/cli/src/lib/ptyHost/client.ts@@ -22,7 +22,10 @@ import {type PtyResponse,} from './protocol.js'-/** `<home>/run/pty-host-<protocol>.json`, as the host writes it (pty/src/discovery.rs). */+/**+ * `<home>/run/pty-host-<instance>.json` (a legacy `p<n>`'s `pty-host-<n>.json`), as the host writes it+ * (pty/src/discovery.rs).+ */export interface PtyHostDiscovery {protocol: numberinstance: string@@ -76,7 +79,7 @@ class LineSplitter {}type HelloOutcome =- | { state: 'ok'; socket: net.Socket; instance: string; rest: Buffer }+ | { state: 'ok'; socket: net.Socket; instance: string; features: string[]; rest: Buffer }| { state: 'incompatible'; reason: string }| { state: 'unreachable' }@@ -156,7 +159,9 @@ function hello(discovery: PtyHostDiscovery, role: HelloRole, timeoutMs: number):} else if (reply.ok === true) {// The lines after the hello's are not split here: they belong to whoever reads next.const after = chunk.subarray(chunk.indexOf(0x0a) + 1)- finish({ state: 'ok', socket, instance: String(reply.instance), rest: Buffer.from(after) })+ // A host from before features sends none: it has none. Only names count.+ const features = Array.isArray(reply.features) ? reply.features.filter((name): name is string => typeof name === 'string') : []+ finish({ state: 'ok', socket, instance: String(reply.instance), features, rest: Buffer.from(after) })} else {finish({ state: 'incompatible', reason: `${reply.code ?? 'incompatible'}: ${reply.reason ?? 'refused'}` })}@@ -194,10 +199,12 @@ export class PtyHostClient {const outcome = await hello(discovery, 'control', timeoutMs)if (outcome.state === 'unreachable') return nullif (outcome.state === 'incompatible') return { incompatible: outcome.reason }- return new PtyHostClient(discovery, outcome.socket, outcome.instance, outcome.rest)+ return new PtyHostClient(discovery, outcome.socket, outcome.instance, outcome.features, outcome.rest)}readonly instance: string+ /** What the host says it can do beyond its protocol (protocol.ts `SEED_FEATURE`), from its hello; `[]` when none. */+ readonly features: readonly string[]/** The protocol this connection speaks: the host's own, which gates the ops added since (protocol.ts). */get protocol(): number {return this.discovery.protocol@@ -229,9 +236,11 @@ export class PtyHostClient {private readonly discovery: PtyHostDiscovery,private readonly socket: net.Socket,instance: string,+ features: readonly string[],rest: Buffer,) {this.instance = instance+ this.features = Object.freeze([...features])socket.on('data', chunk => this.onData(chunk))socket.on('error', () => { /* 'close' follows */ })socket.on('close', () => this.onEnded())diff --git a/cli/src/lib/ptyHost/drain.spec.ts b/cli/src/lib/ptyHost/drain.spec.tsindex a1736eb16..6b3848bc6 100644--- a/cli/src/lib/ptyHost/drain.spec.ts+++ b/cli/src/lib/ptyHost/drain.spec.ts@@ -1,6 +1,6 @@-import { spawn } from 'node:child_process'+import { spawn, spawnSync } from 'node:child_process'import { once } from 'node:events'-import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import net from 'node:net'import { tmpdir } from 'node:os'import path from 'node:path'@@ -13,7 +13,8 @@ import { terminalRouteKey } from '../terminalRuntime.js'import type { ProcessRow } from '../processTable.js'import type { PtyRuntimeRef, TerminalInventoryResult } from '../terminalTypes.js'import { PtyHostClient } from './client.js'-import type { ReachPtyHostResult } from './launch.js'+import { discoveryFileName } from './instance.js'+import type { PtyHostTarget, ReachPtyHostResult } from './launch.js'import { helloProof, PTY_PROTOCOL, SHUTDOWN_PROTOCOL, type PtyEvent, type PtyOp } from './protocol.js'// The Windows seams, watched: a drain backend must never install them (they are the create backend's).@@ -23,8 +24,8 @@ vi.mock('../processTable.js', async (importOriginal) => {})const { PtyHostBackend } = await import('../ptyHostBackend.js')-const { EMPTY_PASSES, isDrainBackend, ptyHostBackends, PtyHostDrain, rowsOnInstance } = await import('./drain.js')-const { readDiscovery } = await import('./launch.js')+const { EMPTY_PASSES, isDrainBackend, ptyHostBackends, ptyHostOnProbation, PtyHostDrain, rowInstancesOf, rowsOnInstance, untilHostAttached, withoutCreateHost } = await import('./drain.js')+const { listDiscoveries, readInstanceDiscovery, removeUnusedPtyVersions, targetHost } = await import('./launch.js')const { setProcessTableSource } = await import('../processTable.js')const OLD = PTY_PROTOCOL - 1@@ -52,10 +53,16 @@ const endpointIn = (dir: string, name: string) => process.platform === 'win32'? `\\\\.\\pipe\\pty-drain-${path.basename(dir)}-${name}`: path.join(dir, `${name}.sock`)-/** A stand-in host in this process: it proves its token, says hello as `p<protocol>`, and lists [panes]. */-async function fakeHostAt(endpoint: string, panes: unknown[] = []) {+/**+ * A stand-in host in this process: it proves its token, says hello as [instance] (`p<protocol>` by default) with+ * [pid] (this process's by default), lists [panes], and records every op it is asked; a `shutdown` is granted, and+ * [onShutdown] told.+ */+async function fakeHostAt(endpoint: string, panes: unknown[] = [], options: { instance?: string; pid?: number; onShutdown?: () => void } = {}) {const token = `tok-${path.basename(endpoint)}`const hellos: number[] = []+ const ops: string[] = []+ const pid = options.pid ?? process.pidconst server = net.createServer(socket => {socket.on('error', () => {})let pending = ''@@ -67,24 +74,36 @@ async function fakeHostAt(endpoint: string, panes: unknown[] = []) {const value = JSON.parse(pending.slice(0, at))pending = pending.slice(at + 1)if (said) {- socket.write(`${JSON.stringify(value.op === 'inventory' ? { id: value.id, ok: true, panes } : { id: value.id, ok: true })}\n`)+ ops.push(value.op)+ if (value.op === 'shutdown') options.onShutdown?.()+ socket.write(`${JSON.stringify(value.op === 'inventory' ? { id: value.id, ok: true, panes } : value.op === 'create' ? { id: value.id, ok: true, pane: '%9' } : { id: value.id, ok: true })}\n`)continue}said = truehellos.push(value.hello.protocol)- socket.write(`${JSON.stringify({ hello: { ok: true, instance: `p${value.hello.protocol}`, version: '0.1.0', pid: process.pid, proof: helloProof(token, value.hello.nonce) } })}\n`)+ socket.write(`${JSON.stringify({ hello: { ok: true, instance: options.instance ?? `p${value.hello.protocol}`, version: '0.1.0', pid, proof: helloProof(token, value.hello.nonce) } })}\n`)}})})server.listen(endpoint)await once(server, 'listening')cleanup.push(() => new Promise(resolve => server.close(resolve)))- return { endpoint, token, pid: process.pid, hellos }+ return { endpoint, token, pid, hellos, ops }}-function writeDiscovery(home: string, value: { protocol: number; instance: string; endpoint: string; token: string; pid: number }) {+function writeDiscovery(home: string, value: { protocol: number; instance: string; endpoint: string; token: string; pid: number; version?: string }) {mkdirSync(path.join(home, 'run'), { recursive: true })- writeFileSync(path.join(home, 'run', `pty-host-${value.protocol}.json`), JSON.stringify({ version: '0.1.0', ...value }))+ writeFileSync(path.join(home, 'run', discoveryFileName(value.instance)!), JSON.stringify({ version: '0.1.0', ...value }))+}++/** A target of [version] (`p<PTY_PROTOCOL>-<version>`), from [source]. */+const targetOf = (version: string, source: PtyHostTarget['source'] = 'installed', instance = `p${PTY_PROTOCOL}-${version}`): PtyHostTarget =>+ ({ protocol: PTY_PROTOCOL, version, instance, features: ['seed'], source })++/** A pid no process has any more: a child's that has exited. */+function deadPid(): number {+ const child = spawnSync(process.execPath, ['-e', ''])+ return child.pid!}/** A stub client of a host with [pid] speaking [protocol]: [replies] by op name, `ok {}` for the rest. */@@ -127,7 +146,7 @@ function drainBackend(results: Array<StubClient | ReachPtyHostResult>, options:const tables = vi.fn(options.rows ?? (async () => [row(10)]))const backend = new PtyHostBackend({home: options.home ?? '/tmp/none',- protocol: OLD,+ instance: `p${OLD}`,launch,owner: () => 'me',platform: options.platform ?? 'linux',@@ -138,49 +157,200 @@ function drainBackend(results: Array<StubClient | ReachPtyHostResult>, options:const OLD_PANE: PtyRuntimeRef = { backend: 'ptyhost', instance: `p${OLD}`, paneId: '%3' }+const P = PTY_PROTOCOL+const PANE_ROW = { pane: '%3', rootPid: 7, cwd: '/w', title: '', dead: false, owner: 'me', label: null }++/**+ * [home] with the target's host (`p<P>-0.2.0`, this process's pid) and another of [version] of the same protocol, with+ * [panes]: its pid is one no process has, and the `hostProcess` seam says it runs until it is asked to shut down.+ * The runtime has `pty/0.1.0`, `pty/0.2.0` (`current-pty`) and `pty/0.3.0`.+ */+async function twoVersions(version: string, panes: unknown[] = []) {+ const home = tmpHome()+ const runtime = tmpHome()+ for (const name of ['0.1.0', '0.2.0', '0.3.0']) mkdirSync(path.join(runtime, 'pty', name), { recursive: true })+ writeFileSync(path.join(runtime, 'pty', 'current-pty'), '0.2.0')+ const pid = deadPid()+ let exited = false+ const other = await fakeHostAt(endpointIn(home, 'other'), panes, { instance: `p${P}-${version}`, pid, onShutdown: () => { exited = true } })+ const target = await fakeHostAt(endpointIn(home, 'target'), [], { instance: `p${P}-0.2.0` })+ writeDiscovery(home, { protocol: P, instance: `p${P}-${version}`, version, endpoint: other.endpoint, token: other.token, pid })+ writeDiscovery(home, { protocol: P, instance: `p${P}-0.2.0`, version: '0.2.0', endpoint: target.endpoint, token: target.token, pid: target.pid })+ const hostProcess = { alive: (candidate: number) => candidate !== pid || !exited, rows: async () => [] }+ return { home, runtime, other, target, hostProcess }+}++/** The create and drain backends of [home] under [target], prepared, and a drain over them. */+async function drained(home: string, target: PtyHostTarget | null, options: { hostProcess?: { alive: (pid: number) => boolean; rows: () => Promise<ProcessRow[] | null> }; inUse?: () => boolean; cleanup?: () => void } = {}) {+ const { create, drain } = ptyHostBackends(home, { target, owner: () => 'me', platform: 'linux', ...(options.hostProcess ? { hostProcess: options.hostProcess } : {}) })+ cleanup.push(() => { create.dispose(); for (const backend of drain) backend.dispose() })+ expect(await create.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ for (const backend of drain) expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ const backends: TerminalBackend[] = [create, ...drain]+ const drainer = new PtyHostDrain({ drain, backends, coordinator: { replaceBackends: () => {} }, inUse: options.inUse ?? (() => false), cleanup: options.cleanup })+ return { create, drain, backends, drainer }+}+describe.runIf(PTY_PROTOCOL >= 2)('ptyHostBackends', () => {- it('creates on the newest host and keeps older panes on the old one', async () => {+ it('creates on the target host and keeps older protocol panes on the old one', async () => {+ quiet()const home = tmpHome()- const oldHost = await fakeHostAt(endpointIn(home, 'old'), [{ pane: '%3', rootPid: 7, cwd: '/w', title: '', dead: false, owner: 'me', label: null }])+ const oldHost = await fakeHostAt(endpointIn(home, 'old'), [PANE_ROW])const newHost = await fakeHostAt(endpointIn(home, 'new'))writeDiscovery(home, { protocol: OLD, instance: `p${OLD}`, ...oldHost })- writeDiscovery(home, { protocol: PTY_PROTOCOL, instance: `p${PTY_PROTOCOL}`, ...newHost })- const { create, drain } = ptyHostBackends(home, { owner: () => 'me', platform: 'linux' })+ writeDiscovery(home, { protocol: P, instance: `p${P}`, ...newHost })+ // A pre-G binary's target: its host is the legacy `p<P>`.+ const { create, drain } = ptyHostBackends(home, { target: targetOf('0.1.0', 'binary', `p${P}`), owner: () => 'me', platform: 'linux' })cleanup.push(() => { create.dispose(); for (const backend of drain) backend.dispose() })expect(await create.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })for (const backend of drain) expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })- expect(create.instanceId).toBe(`ptyhost:p${PTY_PROTOCOL}`)+ expect(create.instanceId).toBe(`ptyhost:p${P}`)expect(drain.map((b) => b.instanceId)).toEqual([`ptyhost:p${OLD}`])// Each is spoken to in its own protocol.- expect([oldHost.hellos, newHost.hellos]).toEqual([[OLD], [PTY_PROTOCOL]])+ expect([oldHost.hellos, newHost.hellos]).toEqual([[OLD], [P]])expect([isDrainBackend(create), isDrainBackend(drain[0])]).toEqual([false, true])// The old pane is listed on its own instance, and the route keys of both instances reach their own backend.expect(await drain[0].inventory()).toEqual({ state: 'available', roots: [{ runtime: OLD_PANE, rootPid: 7, cwd: '/w' }] })const created = await create.create({ command: ['sh'] })if (created.state !== 'succeeded') throw new Error(JSON.stringify(created))- expect(created.runtime.instance).toBe(`p${PTY_PROTOCOL}`)+ expect(created.runtime.instance).toBe(`p${P}`)const terminals = new TerminalBackendCoordinator([create, ...drain], ['ptyhost'])expect(terminals.backendFor(OLD_PANE)).toBe(drain[0])expect(terminals.backendFor(created.runtime)).toBe(create)- expect(terminalRouteKey(OLD_PANE)).not.toBe(terminalRouteKey({ ...OLD_PANE, instance: `p${PTY_PROTOCOL}` }))+ expect(terminalRouteKey(OLD_PANE)).not.toBe(terminalRouteKey({ ...OLD_PANE, instance: `p${P}` }))// A drain backend never makes a pane.expect(await drain[0].create({ command: ['sh'] })).toMatchObject({ state: 'failed', dispatch: 'not_started', reason: expect.stringContaining('draining') })})- it('makes a drain backend for an older protocol only with its discovery file, or rows still on it', () => {+ it('an older version\'s host of the same protocol drains', async () => {+ quiet()+ const { home, other, target, hostProcess } = await twoVersions('0.1.0', [PANE_ROW])+ for (const source of ['installed', 'binary'] as const) {+ const { create, drain } = await drained(home, targetOf('0.2.0', source), { hostProcess })+ expect(drain.map((b) => [b.instanceId, b.draining, b.mayShutDown])).toEqual([[`ptyhost:p${P}-0.1.0`, true, true]])+ expect(create.instanceId).toBe(`ptyhost:p${P}-0.2.0`)+ const created = await create.create({ command: ['sh'] })+ expect(created).toMatchObject({ state: 'succeeded', runtime: { instance: `p${P}-0.2.0` } })+ expect(await drain[0].inventory()).toEqual({ state: 'available', roots: [{ runtime: { backend: 'ptyhost', instance: `p${P}-0.1.0`, paneId: '%3' }, rootPid: 7, cwd: '/w' }] })+ expect(await drain[0].create({ command: ['sh'] })).toMatchObject({ state: 'failed', dispatch: 'not_started', reason: expect.stringContaining('draining') })+ }+ // New panes went to the target alone.+ expect([other.ops.includes('create'), target.ops.filter((op) => op === 'create').length]).toEqual([false, 2])+ })++ it('a legacy p2 host drains', async () => {+ quiet()const home = tmpHome()- expect(ptyHostBackends(home).drain).toEqual([])- const onOld = ptyHostBackends(home, { rowsOn: (id) => id === `ptyhost:p${OLD}` })- expect(onOld.drain.map((b) => [b.instanceId, b.protocol, b.draining])).toEqual([[`ptyhost:p${OLD}`, OLD, true]])- expect([onOld.create.protocol, onOld.create.draining]).toEqual([PTY_PROTOCOL, false])- writeDiscovery(home, { protocol: OLD, instance: `p${OLD}`, endpoint: '/x', token: 't', pid: 1 })- expect(ptyHostBackends(home).drain).toHaveLength(1)+ const legacy = await fakeHostAt(endpointIn(home, 'legacy'), [PANE_ROW])+ const target = await fakeHostAt(endpointIn(home, 'target'), [], { instance: `p${P}-0.2.0` })+ writeDiscovery(home, { protocol: P, instance: `p${P}`, endpoint: legacy.endpoint, token: legacy.token, pid: legacy.pid })+ writeDiscovery(home, { protocol: P, instance: `p${P}-0.2.0`, version: '0.2.0', endpoint: target.endpoint, token: target.token, pid: target.pid })+ const { create, drain } = await drained(home, targetOf('0.2.0'))+ expect([create.instanceId, drain.map((b) => [b.instanceId, b.mayShutDown])]).toEqual([`ptyhost:p${P}-0.2.0`, [[`ptyhost:p${P}`, true]]])+ expect(await drain[0].inventory()).toMatchObject({ state: 'available', roots: [{ runtime: { instance: `p${P}`, paneId: '%3' } }] })+ expect(await create.create({ command: ['sh'] })).toMatchObject({ state: 'succeeded', runtime: { instance: `p${P}-0.2.0` } })+ expect(legacy.ops).not.toContain('create')+ })++ it('a newer host drains and shuts down under an installed target', async () => {+ quiet()+ const { home, other, hostProcess } = await twoVersions('0.3.0')+ const { create, drain, backends, drainer } = await drained(home, targetOf('0.2.0', 'installed'), { hostProcess })+ expect(drain.map((b) => [b.instanceId, b.mayShutDown])).toEqual([[`ptyhost:p${P}-0.3.0`, true]])+ for (let pass = 0; pass < EMPTY_PASSES; pass++) await drainer.step()+ expect(other.ops).toContain('shutdown')+ expect(drain[0].hostGone).toContain('shut down')+ expect(backends).toEqual([create])+ })++ it('a newer host is reached but never shut down under a binary target', async () => {+ quiet()+ const { home, other, hostProcess } = await twoVersions('0.3.0')+ let rows = true+ const { create, drain, backends, drainer } = await drained(home, targetOf('0.2.0', 'binary'), { hostProcess, inUse: () => rows })+ expect(drain.map((b) => [b.instanceId, b.mayShutDown])).toEqual([[`ptyhost:p${P}-0.3.0`, false]])+ expect(other.hellos).toEqual([P])+ for (let pass = 0; pass < EMPTY_PASSES + 2; pass++) await drainer.step()+ // Rows still name it: reached, listed, kept.+ expect(backends).toEqual([create, drain[0]])+ expect(await drain[0].inventory()).toEqual({ state: 'available', roots: [] })+ rows = false+ await drainer.step()+ // Its backend leaves; the host is never asked to go.+ expect(backends).toEqual([create])+ expect(other.ops).not.toContain('shutdown')+ expect(drain[0].hostGone).toBeNull()+ })++ it('a drain backend never shuts its host down when there is no target', async () => {+ quiet()+ const { home, other, hostProcess } = await twoVersions('0.1.0')+ const { drain } = ptyHostBackends(home, { target: null, owner: () => 'me', platform: 'linux', hostProcess })+ expect(drain.map((b) => [b.instanceId, b.mayShutDown])).toEqual([[`ptyhost:p${P}-0.1.0`, false], [`ptyhost:p${P}-0.2.0`, false]])+ expect(other.ops).toEqual([])+ })++ it('with no target, the drain backend of the host the create backend took leaves', async () => {+ quiet()+ const { home, hostProcess } = await twoVersions('0.1.0')+ const { create, drain } = ptyHostBackends(home, { target: null, owner: () => 'me', platform: 'linux', hostProcess })+ cleanup.push(() => { create.dispose(); for (const backend of drain) backend.dispose() })+ for (const backend of [create, ...drain]) expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ // The newest host answered the create backend.+ expect(create.instanceId).toBe(`ptyhost:p${P}-0.2.0`)+ const disposed = vi.spyOn(drain[1], 'dispose')+ const kept = withoutCreateHost([create, ...drain], create)+ expect(kept).toEqual([create, drain[0]])+ expect(disposed).toHaveBeenCalledTimes(1)+ expect(withoutCreateHost(kept, create)).toEqual(kept)+ })++ it('rows on an instance with no discovery get a drain backend', () => {+ const home = tmpHome()+ expect(ptyHostBackends(home, { target: targetOf('0.2.0') }).drain).toEqual([])+ writeDiscovery(home, { protocol: P, instance: `p${P}-0.1.0`, version: '0.1.0', endpoint: '/x', token: 't', pid: 1 })+ const rows = [`ptyhost:p${P}-0.0.9`, `ptyhost:p${OLD}`, `ptyhost:p${P}-0.1.0`, `ptyhost:p${P}-0.2.0`, 'ptyhost:p9-1.0', 'ptyhost:../x', `ptyhost:p${OLD}`]+ const { create, drain } = ptyHostBackends(home, { target: targetOf('0.2.0'), rowInstances: () => rows })+ // The discovered one, then those only rows name: never the target's, an unsupported protocol's or a non-instance.+ expect(drain.map((b) => [b.instanceId, b.draining])).toEqual([[`ptyhost:p${P}-0.1.0`, true], [`ptyhost:p${P}-0.0.9`, true], [`ptyhost:p${OLD}`, true]])+ expect([create.instanceId, create.draining]).toEqual(['ptyhost:unprepared', false])+ })++ it('rowInstancesOf: the pty host instances rows name, once each', () => {+ const rows = [+ { runtimes: [OLD_PANE, { ...OLD_PANE, paneId: '%4' }] },+ { runtimes: [{ backend: 'tmux' as const, instance: 'default', paneId: '%1' }, { backend: 'ptyhost' as const, instance: `p${P}-0.1.0`, paneId: '%1' }] },+ ]+ expect(rowInstancesOf(rows)).toEqual([`ptyhost:p${OLD}`, `ptyhost:p${P}-0.1.0`])+ })++ it('an empty older host is shut down after EMPTY_PASSES and its folder removed', async () => {+ quiet()+ const { home, runtime, other, hostProcess } = await twoVersions('0.1.0')+ const { create, backends, drainer } = await drained(home, targetOf('0.2.0'), { hostProcess, cleanup: () => { removeUnusedPtyVersions(home, runtime) } })+ await drainer.step()+ expect(other.ops).not.toContain('shutdown')+ await drainer.step()+ expect(other.ops).toContain('shutdown')+ expect(backends).toEqual([create])+ expect(readInstanceDiscovery(home, `p${P}-0.1.0`)).toBeNull()+ expect(['0.1.0', '0.2.0', '0.3.0'].map((name) => existsSync(path.join(runtime, 'pty', name)))).toEqual([false, true, true])+ })++ it('a newer host\'s folder is never removed', async () => {+ quiet()+ const { home, runtime, other, hostProcess } = await twoVersions('0.3.0')+ const { create, backends, drainer } = await drained(home, targetOf('0.2.0'), { hostProcess, cleanup: () => { removeUnusedPtyVersions(home, runtime) } })+ for (let pass = 0; pass < EMPTY_PASSES; pass++) await drainer.step()+ // Shut down (a rollback), and gone: still its folder stays, newer than `current-pty`.+ expect([other.ops.includes('shutdown'), backends]).toEqual([true, [create]])+ expect(['0.1.0', '0.2.0', '0.3.0'].map((name) => existsSync(path.join(runtime, 'pty', name)))).toEqual([false, true, true])})it('rowsOnInstance: whether a row has a runtime on the instance', () => {const rows = [{ runtimes: [OLD_PANE] }, { runtimes: [{ backend: 'tmux' as const, instance: 'default', paneId: '%1' }] }]expect(rowsOnInstance(rows, `ptyhost:p${OLD}`)).toBe(true)- expect(rowsOnInstance(rows, `ptyhost:p${PTY_PROTOCOL}`)).toBe(false)+ expect(rowsOnInstance(rows, `ptyhost:p${P}`)).toBe(false)})})@@ -350,12 +520,13 @@ describe.runIf(PTY_PROTOCOL >= 2)('a drain backend', () => {})/** Drain backends stubbed by state, and a drain over them. */-function drainFixture(options: { oldPanes?: unknown[]; inUse?: () => boolean } = {}) {- type Stub = { instanceId: string; draining: true; hostGone: string | null; shutdownCalled: boolean; disposed: boolean; panes: unknown[]; refuse: boolean; unknown: boolean+function drainFixture(options: { oldPanes?: unknown[]; inUse?: () => boolean; createAvailable?: () => boolean } = {}) {+ type Stub = { instanceId: string; draining: true; mayShutDown: boolean; hostGone: string | null; shutdownCalled: boolean; disposed: boolean; panes: unknown[]; refuse: boolean; unknown: booleandrainState(): Promise<string>; shutdownHost(): Promise<string>; dispose(): void }const stub: Stub = {instanceId: `ptyhost:p${OLD}`,draining: true,+ mayShutDown: true,hostGone: null,shutdownCalled: false,disposed: false,@@ -381,10 +552,45 @@ function drainFixture(options: { oldPanes?: unknown[]; inUse?: () => boolean } =coordinator: { replaceBackends: (list) => { replaced.push([...list]) } },inUse: options.inUse ?? (() => false),cleanup: cleaned,+ ...(options.createAvailable ? { createAvailable: options.createAvailable } : {}),})return { drain: [stub], drainer, step: () => drainer.step(), backends, create, replaced, cleaned }}+describe('a host on probation', () => {+ it('is one with a pty-pending.json', () => {+ const runtime = mkdtempSync(path.join(tmpdir(), 'probation-'))+ try {+ expect(ptyHostOnProbation(runtime)).toBe(false)+ mkdirSync(path.join(runtime, 'pty'))+ writeFileSync(path.join(runtime, 'pty', 'pty-pending.json'), '{}')+ expect(ptyHostOnProbation(runtime)).toBe(true)+ } finally { rmSync(runtime, { recursive: true, force: true }) }+ })++ it('makes the core wait to be ready until the create backend is attached to it, said once, and forever when it never is', async () => {+ vi.useFakeTimers()+ try {+ const lines: string[] = []+ let attached = false+ let ready = false+ void untilHostAttached(() => attached, 'p2-0.11.0', (line) => lines.push(line)).then(() => { ready = true })+ await vi.advanceTimersByTimeAsync(10_000)+ expect(ready).toBe(false)+ expect(lines).toEqual(['[terminal] ptyhost: the host on probation (p2-0.11.0) is not attached — not ready until it is; the master rolls it back if it never is'])+ attached = true+ await vi.advanceTimersByTimeAsync(250)+ expect(ready).toBe(true)+ expect(lines).toHaveLength(2)+ expect(lines[1]).toBe('[terminal] ptyhost: the host on probation (p2-0.11.0) is attached')+ // Attached from the start: ready at once, nothing said.+ const quietLines: string[] = []+ await untilHostAttached(() => true, null, (line) => quietLines.push(line))+ expect(quietLines).toEqual([])+ } finally { vi.useRealTimers() }+ })+})+describe('PtyHostDrain', () => {it('shuts a drained host down after two empty passes', async () => {quiet()@@ -425,6 +631,32 @@ describe('PtyHostDrain', () => {expect(client.closed).toBe(true)})+ it('never asks a host it may not shut down: it stays running, and its backend leaves once no row names it', async () => {+ quiet()+ let rows = true+ const { drain, step, backends } = drainFixture({ inUse: () => rows })+ drain[0].mayShutDown = false+ for (let pass = 0; pass < EMPTY_PASSES + 1; pass++) await step()+ expect([drain[0].shutdownCalled, backends.length]).toEqual([false, 2])+ rows = false+ await step()+ expect([drain[0].shutdownCalled, backends.length, drain[0].hostGone]).toEqual([false, 1, null])+ })++ it('never shuts an old host down while the create backend is unavailable: it may be the only host that serves', async () => {+ quiet()+ let available = false+ const { drain, step, backends } = drainFixture({ createAvailable: () => available })+ for (let pass = 0; pass < EMPTY_PASSES + 2; pass++) await step()+ expect([drain[0].shutdownCalled, backends.length]).toEqual([false, 2])+ // Counted afresh once it is back: two empty passes with a create backend to go to.+ available = true+ await step()+ expect(drain[0].shutdownCalled).toBe(false)+ await step()+ expect(drain[0].shutdownCalled).toBe(true)+ })+it('counts empty passes in a row: a pass with a pane, or one that could not ask, starts again', async () => {quiet()const { drain, step } = drainFixture({ oldPanes: [{ pane: '%1' }] })@@ -534,10 +766,13 @@ const computed = (word: string) => process.platform === 'win32' ? `echo "${word}describe.runIf(!!realBinary)('shutdown on the real host', () => {it('is refused while the host has a pane; granted, the host exits and takes its discovery file down', async () => {const home = tmpHome()- const { create } = ptyHostBackends(home, { owner: () => 'me' })- cleanup.push(() => { create.dispose(); killPid(readDiscovery(home, PTY_PROTOCOL)?.pid) })+ const target = targetHost({ runtimeDir: home })+ if (!target) throw new Error('HARNESS_PTY_BIN says no version')+ const { create } = ptyHostBackends(home, { target, owner: () => 'me' })+ cleanup.push(() => { create.dispose(); killPid(readInstanceDiscovery(home, target.instance)?.pid) })expect(await create.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })- const discovery = readDiscovery(home, PTY_PROTOCOL)!+ expect(create.instanceId).toBe(`ptyhost:${target.instance}`)+ const discovery = readInstanceDiscovery(home, target.instance)!const client = await PtyHostClient.connect(discovery)if (!(client instanceof PtyHostClient)) throw new Error(JSON.stringify(client))cleanup.push(() => client.close())@@ -548,20 +783,24 @@ describe.runIf(!!realBinary)('shutdown on the real host', () => {expect((await create.kill(pane.runtime)).state).toBe('succeeded')expect(await client.call({ op: 'shutdown' })).toEqual({ state: 'ok', value: {} })expect(await until(() => alive(discovery.pid), (up) => !up)).toBe(false)- expect(existsSync(path.join(home, 'run', `pty-host-${PTY_PROTOCOL}.json`))).toBe(false)+ expect(listDiscoveries(home).some((found) => found.pid === discovery.pid)).toBe(false)}, CASE_TIMEOUT_MS)})-// A protocol bump with real hosts: HARNESS_PTY_BIN_PREV is a build of the protocol before (the commit before the bump,-// built apart), HARNESS_PTY_BIN this one's.-describe.runIf(!!realBinary && !!previousBinary && PTY_PROTOCOL >= 2)('a protocol bump with the real hosts', () => {- it('streams the old host\'s pane, makes new panes on the new host, and lets the old one go once its pane closes', async () => {+// Two builds of one protocol with real hosts: HARNESS_PTY_BIN_PREV is the previous version, the same source built+// with `HARNESS_PTY_VERSION=0.0.1` and copied aside first (as windows.yml builds it), HARNESS_PTY_BIN this one's.+describe.runIf(!!realBinary && !!previousBinary)('a previous version with the real hosts', () => {+ it('streams the old host\'s pane, makes new panes on the target, and shuts the old one down once its pane closes', async () => {quiet()const home = tmpHome()- cleanup.push(() => { killPid(readDiscovery(home, OLD)?.pid); killPid(readDiscovery(home, PTY_PROTOCOL)?.pid) })+ const target = targetHost({ runtimeDir: home })+ const previous = targetHost({ runtimeDir: home, env: { HARNESS_PTY_BIN: previousBinary } })+ if (!target || !previous) throw new Error('a binary says no version')+ expect(previous.instance).not.toBe(target.instance)+ cleanup.push(() => { killPid(readInstanceDiscovery(home, previous.instance)?.pid); killPid(readInstanceDiscovery(home, target.instance)?.pid) })// The host an older daemon started, with a shell pane in it.spawn(previousBinary!, ['serve', '--home', home], { cwd: home, detached: true, stdio: 'ignore', windowsHide: true }).unref()- const old = await until(() => readDiscovery(home, OLD), (found) => found !== null)+ const old = await until(() => readInstanceDiscovery(home, previous.instance), (found) => found !== null)if (!old) throw new Error('the previous host published no discovery file')const oldPid = old.pidconst before = await PtyHostClient.connect(old)@@ -569,15 +808,15 @@ describe.runIf(!!realBinary && !!previousBinary && PTY_PROTOCOL >= 2)('a protococonst made = await before.call({ op: 'create', command: SHELL, cols: 80, rows: 24, owner: 'me', hold: true })before.close()if (made.state !== 'ok') throw new Error(JSON.stringify(made))- const oldPane: PtyRuntimeRef = { backend: 'ptyhost', instance: `p${OLD}`, paneId: made.value.pane }+ const oldPane: PtyRuntimeRef = { backend: 'ptyhost', instance: previous.instance, paneId: made.value.pane }- // This daemon: the new protocol's host is started, the old one drained.- const { create, drain } = ptyHostBackends(home, { owner: () => 'me' })+ // This daemon: the target's host is started beside it, the old one drained.+ const { create, drain } = ptyHostBackends(home, { target, owner: () => 'me' })cleanup.push(() => { create.dispose(); for (const backend of drain) backend.dispose() })- expect(drain).toHaveLength(1)+ expect(drain.map((backend) => [backend.instanceId, backend.mayShutDown])).toEqual([[`ptyhost:${previous.instance}`, true]])expect(await create.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })expect(await drain[0].prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })- expect([create.instanceId, drain[0].instanceId]).toEqual([`ptyhost:p${PTY_PROTOCOL}`, `ptyhost:p${OLD}`])+ expect(create.instanceId).toBe(`ptyhost:${target.instance}`)const backends: TerminalBackend[] = [create, drain[0]]const terminals = new TerminalBackendCoordinator(backends, ['ptyhost'])expect(terminals.backendFor(oldPane)).toBe(drain[0])@@ -595,14 +834,13 @@ describe.runIf(!!realBinary && !!previousBinary && PTY_PROTOCOL >= 2)('a protocoexpect(await until(() => output, (text) => text.includes('drained-42'))).toContain('drained-42')await opened.value.close()- // New panes land on the new host.+ // New panes land on the target's host.const fresh = await create.create({ command: SHELL })if (fresh.state !== 'succeeded') throw new Error(JSON.stringify(fresh))- expect(fresh.runtime.instance).toBe(`p${PTY_PROTOCOL}`)+ expect(fresh.runtime.instance).toBe(target.instance)expect(terminals.backendFor(fresh.runtime)).toBe(create)- // The old pane closes: two empty passes later its backend has left. The protocol 1 host has no `shutdown` and- // is never signalled: it stays running, idle.+ // The old pane closes: two empty passes later the old host is shut down and its backend has left.const drainer = new PtyHostDrain({ drain, backends, coordinator: terminals, inUse: () => false })await drainer.step()expect(backends).toHaveLength(2)@@ -613,10 +851,9 @@ describe.runIf(!!realBinary && !!previousBinary && PTY_PROTOCOL >= 2)('a protocoawait drainer.step()expect(backends).toEqual([create])expect(terminals.instances()).toEqual([create])- await new Promise((resolve) => setTimeout(resolve, 300))- expect(alive(oldPid)).toBe(true)- expect(readDiscovery(home, OLD)?.pid).toBe(oldPid)- // The new host and its pane are untouched.+ expect(await until(() => alive(oldPid), (up) => !up)).toBe(false)+ expect(readInstanceDiscovery(home, previous.instance)).toBeNull()+ // The target's host and its pane are untouched.const remaining: TerminalInventoryResult = await create.inventory()expect(remaining.state === 'available' && remaining.roots.map((root) => root.runtime)).toEqual([fresh.runtime])expect((await create.kill(fresh.runtime)).state).toBe('succeeded')diff --git a/cli/src/lib/ptyHost/drain.ts b/cli/src/lib/ptyHost/drain.tsindex c1a20dcbe..44190422d 100644--- a/cli/src/lib/ptyHost/drain.ts+++ b/cli/src/lib/ptyHost/drain.ts@@ -1,56 +1,101 @@/**- * Hosts across a protocol bump: the newest protocol's host makes new panes, and the one before drains.+ * The hosts of one home: the target's makes new panes, and every other drains.*- * A host's protocol is fixed at its build (pty/src/protocol.rs `PROTOCOL`), and each protocol is its own instance,- * `p<protocol>`: its own discovery file, endpoint, lock and pane ids. An update that bumps the protocol leaves the old- * host running with the person's panes in it, as a tmux server of an older tmux keeps running. This daemon reaches- * it too, as a drain backend (ptyHostBackend.ts): its panes are listed, streamed and controlled, their registry rows- * keep their `ptyhost:p<old>` runtimes, and the route keys name the instance, so both hosts' panes are reached at- * once. Nothing new goes to it. Once it has no pane on two reconcile passes in a row it is shut down (protocol 2 on;- * an older host, which has no `shutdown`, is left running idle, ptyHostBackend.ts `shutdownHost`), and the backend- * leaves the daemon's backends (`TerminalBackendCoordinator.replaceBackends`). A drain host proven to have exited (the- * process table) is gone, its panes with it: its inventory is then empty for certain, so the reconciler counts its- * rows' runtimes missing, and the backend leaves once no row names its instance. Then the runtime's host binaries no- * running host uses are deleted (launch.ts `removeUnusedPtyVersions`).+ * Each host build is its own instance (`p<protocol>-<version>`, or `p<protocol>` for a host from before that,+ * instance.ts): its own discovery file, endpoint, lock and pane ids. The target is the build this daemon would start+ * (launch.ts `targetHost`, read once as the core starts). An update leaves the previous build's host running with the+ * person's panes in it, as a tmux server of an older tmux keeps running. This daemon reaches it too, as a drain+ * backend (ptyHostBackend.ts): its panes are listed, streamed and controlled, their registry rows keep their+ * `ptyhost:<instance>` runtimes, and the route keys name the instance, so every host's panes are reached at once.+ * Nothing new goes to it. Once it has no pane on two reconcile passes in a row it is shut down (protocol 2 on, and only+ * when `mayShutDown`: never a host newer than a dev build's target, nor any with no target; an older protocol's host,+ * which has no `shutdown`, is left running idle, ptyHostBackend.ts `shutdownHost`), and the backend leaves the daemon's+ * backends (`TerminalBackendCoordinator.replaceBackends`). A drain host proven to have exited (the process table) is+ * gone, its panes with it: its inventory is then empty for certain, so the reconciler counts its rows' runtimes+ * missing, and the backend leaves once no row names its instance. Then the runtime's host binaries no running host+ * uses are deleted (launch.ts `removeUnusedPtyVersions`, which keeps every folder newer than `current-pty`). No drain+ * host is shut down while the create backend has no host of its own (`createAvailable`): it may be the only one left.+ *+ * While a host is on probation (`ptyHostOnProbation`), the core is ready only once the create backend is attached to it+ * (`untilHostAttached`): the master's probation judges the core's ready, and so the host's.*/+import { existsSync } from 'node:fs'+import path from 'node:path'import type { TerminalBackend } from '../terminalBackend.js'import { terminalInstanceId } from '../terminalRuntime.js'import type { TerminalRuntimeRef } from '../terminalTypes.js'import { PtyHostBackend, type PtyHostBackendOptions } from '../ptyHostBackend.js'-import { readDiscovery } from './launch.js'-import { PTY_PROTOCOL, SUPPORTED_PTY_PROTOCOLS } from './protocol.js'+import { instanceProtocol } from './instance.js'+import { listDiscoveries, type PtyHostTarget } from './launch.js'+import { SUPPORTED_PTY_PROTOCOLS } from './protocol.js'/** How many reconcile passes in a row must find a drain host with no pane before it is shut down. */export const EMPTY_PASSES = 2export interface PtyHostBackends {- /** This daemon's protocol's host: new panes go there, and it is started when there is none. */+ /** The target's host: new panes go there, and it is started when there is none. */create: PtyHostBackend- /** Older protocols' hosts, oldest first. */+ /** Every other host's, oldest first, then those only registry rows name. */drain: PtyHostBackend[]}-export interface PtyHostBackendsOptions extends Omit<PtyHostBackendOptions, 'home' | 'protocol'> {- /** Whether a registry row has a runtime on [instanceId] (`ptyhost:p<protocol>`): a drain backend is made for- * an older protocol with no discovery file too, so those rows go gone rather than stay on no backend. */- rowsOn?: (instanceId: string) => boolean+export interface PtyHostBackendsOptions extends Omit<PtyHostBackendOptions, 'home' | 'instance' | 'target'> {+ /** The daemon's target host (`targetHost`); null when it cannot be known. */+ target?: PtyHostTarget | null+ /**+ * The `ptyhost:<instance>` instances registry rows name (`rowInstancesOf`): a drain backend is made for one with no+ * discovery file too, so those rows go gone rather than stay on no backend.+ */+ rowInstances?: () => string[]+}++const PTYHOST = 'ptyhost:'++/** Whether [instance] is a host instance of a protocol this daemon speaks. */+function supported(instance: string): boolean {+ const protocol = instanceProtocol(instance)+ return protocol !== null && SUPPORTED_PTY_PROTOCOLS.includes(protocol)}/**- * One backend per host instance of [home]: the create backend for `PTY_PROTOCOL`, and a drain backend for each- * older supported protocol that has a discovery file, or rows still on it.+ * One backend per host instance of [home]: the create backend for the target, and a drain backend for each other+ * instance of a supported protocol that has a discovery file, or rows still on it. With no target, every discovered+ * host is a drain backend's, including the one the create backend will take (`withoutCreateHost` drops that one once+ * they are prepared).*/export function ptyHostBackends(home: string, options: PtyHostBackendsOptions = {}): PtyHostBackends {- const { rowsOn, ...backendOptions } = options- const drain = SUPPORTED_PTY_PROTOCOLS- .filter((protocol) => protocol < PTY_PROTOCOL)- .filter((protocol) => readDiscovery(home, protocol) !== null || rowsOn?.(`ptyhost:p${protocol}`) === true)- .map((protocol) => new PtyHostBackend({ ...backendOptions, home, protocol }))- return { create: new PtyHostBackend({ ...backendOptions, home }), drain }+ const { target = null, rowInstances, ...backendOptions } = options+ const discovered = listDiscoveries(home).map((discovery) => discovery.instance)+ const named = (rowInstances?.() ?? []).flatMap((id) => id.startsWith(PTYHOST) ? [id.slice(PTYHOST.length)] : [])+ // By instance, never by version: a folder `current-pty` names may hold a binary stamped otherwise, and the instance+ // is the name its host publishes (launch.ts `targetHost`).+ const instances = [...new Set([...discovered, ...named])].filter((instance) => supported(instance) && instance !== target?.instance)+ const drain = instances.map((instance) => new PtyHostBackend({ ...backendOptions, home, instance, target }))+ return { create: new PtyHostBackend({ ...backendOptions, home, target }), drain }+}++/** The `ptyhost:<instance>` instances [rows] have runtimes on, once each. */+export function rowInstancesOf(rows: ReadonlyArray<{ runtimes: readonly TerminalRuntimeRef[] }>): string[] {+ const instances = rows.flatMap((row) => row.runtimes.filter((runtime) => runtime.backend === 'ptyhost').map(terminalInstanceId))+ return [...new Set(instances)]+}++/**+ * [backends] without a drain backend on the host [create] reached, which is disposed (its connection only). Only with+ * no target can there be one: the create backend then took whichever host of `PTY_PROTOCOL` answered, which was a+ * drain backend's too. Two backends of one instance would list its panes twice, and the coordinator would route them to+ * the later one.+ */+export function withoutCreateHost(backends: readonly TerminalBackend[], create: PtyHostBackend): TerminalBackend[] {+ return backends.filter((backend) => {+ if (!isDrainBackend(backend) || backend.instanceId !== create.instanceId) return true+ backend.dispose()+ return false+ })}/** Whether [backend] is a drain backend: never the one new panes are made on (main.ts `createBackend`). */-export function isDrainBackend(backend: TerminalBackend): boolean {+export function isDrainBackend(backend: TerminalBackend): backend is PtyHostBackend {return backend instanceof PtyHostBackend && backend.draining}@@ -69,6 +114,9 @@ export interface PtyHostDrainDeps {inUse: (instanceId: string) => boolean/** After a drained host has gone and its backend left: `removeUnusedPtyVersions`. */cleanup?: () => void+ /** Whether the create backend is attached to its host. While it is not, no drain host is shut down: new panes have+ * nowhere else to go, and a probation that rolls the target back needs a host to come back to. Left out, always. */+ createAvailable?: () => boolean}/** The drain, one `step` after each reconcile pass (main.ts `onReconciled`). */@@ -91,7 +139,7 @@ export class PtyHostDrain {/*** One pass's look at each drain host. An empty one (no pane of any owner) on `EMPTY_PASSES` passes in a row is* shut down; a host that refuses (a pane came meanwhile) starts the count again. One of a protocol without- * `shutdown` stays running, idle, and only its backend leaves. A backend leaves once no row names its instance: a+ * `shutdown`, or one it may not shut down (`mayShutDown`), stays running, idle, and only its backend leaves. A backend leaves once no row names its instance: a* gone host's rows go gone through the reconciler first, which a backend taken out early would strand on no* backend. A step while one runs is skipped: the count is of passes.*/@@ -111,10 +159,16 @@ export class PtyHostDrain {this.empty.delete(backend)return}+ if (state === 'empty' && this.deps.createAvailable && !this.deps.createAvailable()) {+ this.empty.delete(backend)+ return+ }const passes = (this.empty.get(backend) ?? 0) + 1this.empty.set(backend, passes)if (passes < EMPTY_PASSES) return- if (state === 'empty') {+ // A host it may not shut down (`mayShutDown`) stays running, as one without `shutdown` does; its backend leaves+ // all the same once no row names it.+ if (state === 'empty' && backend.mayShutDown) {const shutdown = await backend.shutdownHost().catch(() => 'failed' as const)if (shutdown === 'refused') this.empty.delete(backend)// `unsupported`: the host stays, never signalled; its backend leaves all the same.@@ -144,3 +198,22 @@ export class PtyHostDrain {for (const backend of this.draining) backend.dispose()}}++/** A host is on probation: `<runtime>/pty/pty-pending.json` (lib/windows/ptyInstall.ts `PTY_PENDING`) exists. */+export function ptyHostOnProbation(runtimeDir: string): boolean {+ return existsSync(path.join(runtimeDir, 'pty', 'pty-pending.json'))+}++/**+ * Wait until [attached] (the create backend reached the target's host, [instance]; null when there is no target), polled+ * every [pollMs]: how a core whose host is on probation holds back its ready (core/main.ts). The master judges the host+ * by that ready, and a version that says it runs proves nothing about serving. One that never attaches keeps the core+ * not ready for good: the master's ready timeout ends it, and its probation rolls the host back. Said once, if it waits.+ */+export async function untilHostAttached(attached: () => boolean, instance: string | null, log: (line: string) => void, pollMs = 250): Promise<void> {+ if (attached()) return+ const host = instance ?? 'no target'+ log(`[terminal] ptyhost: the host on probation (${host}) is not attached — not ready until it is; the master rolls it back if it never is`)+ while (!attached()) await new Promise((resolve) => setTimeout(resolve, pollMs))+ log(`[terminal] ptyhost: the host on probation (${host}) is attached`)+}diff --git a/cli/src/lib/ptyHost/instance.spec.ts b/cli/src/lib/ptyHost/instance.spec.tsnew file mode 100644index 000000000..f1e92127a--- /dev/null+++ b/cli/src/lib/ptyHost/instance.spec.ts@@ -0,0 +1,44 @@+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { describe, expect, it } from 'vitest'+import { discoveryFileName, hostInstanceName, instanceProtocol, PTY_HOST_INSTANCE, PTY_HOST_PANE } from './instance.js'++describe('hostInstanceName', () => {+ it('names follow the host\'s shared vectors', () => {+ // The host's own test reads the same file (pty/src/instance.rs): both sides name one build alike.+ const file = path.join(import.meta.dirname, '..', '..', '..', '..', 'pty', 'tests', 'fixtures', 'instances.json')+ const vectors = JSON.parse(readFileSync(file, 'utf8')) as Array<{ protocol: number; version: string; instance: string }>+ expect(vectors.length).toBeGreaterThanOrEqual(6)+ for (const vector of vectors) {+ expect(hostInstanceName(vector.protocol, vector.version), JSON.stringify(vector)).toBe(vector.instance)+ expect(PTY_HOST_INSTANCE.test(vector.instance)).toBe(true)+ }+ })+})++describe('PTY_HOST_INSTANCE', () => {+ it('takes a legacy p<protocol>, a version tag and a hash tag, and nothing else', () => {+ for (const good of ['p1', 'p2', 'p2-0.4.21-dev.win1', 'p2-h0123456789ab', 'p9999-1']) expect(PTY_HOST_INSTANCE.test(good), good).toBe(true)+ for (const bad of ['', 'p', 'P2', 'p12345', 'p2-', 'p2-a/b', 'p2-a b', 'p2-0.4.21+meta', `p2-${'1'.repeat(33)}`, 'p2:%1', '../p2']) {+ expect(PTY_HOST_INSTANCE.test(bad), bad).toBe(false)+ }+ })++ it('makes the HARNESS_PANE pattern: <instance>:%N', () => {+ expect(PTY_HOST_PANE.exec('p2-0.4.21-dev.win1:%7')?.slice(1)).toEqual(['p2-0.4.21-dev.win1', '%7'])+ expect(PTY_HOST_PANE.exec('p2-h0123456789ab:%7')?.slice(1)).toEqual(['p2-h0123456789ab', '%7'])+ expect(PTY_HOST_PANE.exec('p1:%3')?.slice(1)).toEqual(['p1', '%3'])+ for (const bad of ['%7', 'p2-0.4.21:7', 'p2-0.4.21:%7; calc', 'p2-0.4.21:%1234567890']) expect(PTY_HOST_PANE.test(bad), bad).toBe(false)+ })+})++describe('instance files', () => {+ it('a legacy instance keeps its protocol-named file; a versioned one is named by its instance', () => {+ expect(discoveryFileName('p2')).toBe('pty-host-2.json')+ expect(discoveryFileName('p2-0.4.20')).toBe('pty-host-p2-0.4.20.json')+ expect(discoveryFileName('p2/../x')).toBeNull()+ expect(instanceProtocol('p2-0.4.20')).toBe(2)+ expect(instanceProtocol('p13')).toBe(13)+ expect(instanceProtocol('q2')).toBeNull()+ })+})diff --git a/cli/src/lib/ptyHost/instance.ts b/cli/src/lib/ptyHost/instance.tsnew file mode 100644index 000000000..f8c1d8758--- /dev/null+++ b/cli/src/lib/ptyHost/instance.ts@@ -0,0 +1,44 @@+/**+ * A host's instance name, one per build: `p<protocol>-<tag>` (pty/src/instance.rs). Two builds of one protocol run+ * side by side in one home, so the build is part of the name that keys the discovery file, lock, pane ids, socket,+ * pipe suffix, log and `HARNESS_PANE`. A host from before this (pre-G) is `p<protocol>`, in `pty-host-<protocol>.json`;+ * it is still found, as an instance of its own.+ */+import { createHash } from 'node:crypto'++/**+ * An instance, unanchored, for the patterns built on it. Hook scripts and engine plugins cannot import it and carry+ * it written out (hook/notify.mjs, engines/{kilo,opencode,pi}/contract.ts): change those with it.+ */+export const PTY_HOST_INSTANCE_SOURCE = String.raw`p\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?`+/** A pty host instance: a legacy `p<protocol>`, or `p<protocol>-<version or hash>`. */+export const PTY_HOST_INSTANCE = new RegExp(`^${PTY_HOST_INSTANCE_SOURCE}$`)+/** A pty host pane as its shell names itself: `HARNESS_PANE`, `<instance>:%N`. */+export const PTY_HOST_PANE = new RegExp(`^(${PTY_HOST_INSTANCE_SOURCE}):(%\\d{1,9})$`)++const PLAIN_TAG = /^[0-9A-Za-z.-]{1,32}$/+const LEGACY = /^p(\d{1,4})$/++/**+ * The instance a host of [protocol] built as [version] runs as: the version itself when it is safe in a file name, a+ * pipe name and a socket path, else `h` and the first 12 hex digits of its SHA-256 (build metadata, spaces, length).+ */+export function hostInstanceName(protocol: number, version: string): string {+ const tag = PLAIN_TAG.test(version) ? version : `h${createHash('sha256').update(version, 'utf8').digest('hex').slice(0, 12)}`+ return `p${protocol}-${tag}`+}++/** The protocol an instance is of, or null for anything that is not one. */+export function instanceProtocol(instance: string): number | null {+ return PTY_HOST_INSTANCE.test(instance) ? Number(/^p(\d+)/.exec(instance)![1]) : null+}++/**+ * The name of [instance]'s discovery file in `<home>/run/`, or null for anything that is not an instance (it is never+ * a path): a legacy `p<n>`'s is `pty-host-<n>.json`, as hosts from before instances wrote it.+ */+export function discoveryFileName(instance: string): string | null {+ if (!PTY_HOST_INSTANCE.test(instance)) return null+ const legacy = LEGACY.exec(instance)+ return `pty-host-${legacy ? legacy[1] : instance}.json`+}diff --git a/cli/src/lib/ptyHost/launch.spec.ts b/cli/src/lib/ptyHost/launch.spec.tsindex ad1bfbefb..0c4681ceb 100644--- a/cli/src/lib/ptyHost/launch.spec.ts+++ b/cli/src/lib/ptyHost/launch.spec.ts@@ -1,13 +1,14 @@import { once } from 'node:events'import { spawnSync } from 'node:child_process'-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'import net from 'node:net'import { tmpdir } from 'node:os'import path from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import { removeTree } from '../terminalBackend.contract.js'import { PtyHostClient } from './client.js'-import { currentPtyVersion, discoveredHostDead, discoverHosts, ensurePtyHost, forgetExitedHost, ptyHostBinary, reachable, reachPtyHost, readDiscovery, removeUnusedPtyVersions, startMarkerMs } from './launch.js'+import { binaryVersion, currentPtyVersion, discoveredHostDead, ensurePtyHost, forgetExitedHost, listDiscoveries, ptyHostBinary, reachable, reachPtyHost, readInstanceDiscovery, removeUnusedPtyVersions, startMarkerMs, targetHost } from './launch.js'+import { discoveryFileName } from './instance.js'import { helloProof, PTY_PROTOCOL, SUPPORTED_PTY_PROTOCOLS } from './protocol.js'const exe = process.platform === 'win32' ? 'harness-pty.exe' : 'harness-pty'@@ -29,6 +30,8 @@ function executable(file: string, body = ''): string {return file}+/** The instance a host from before versioned instances has: `p<protocol>`, in `pty-host-<protocol>.json`. */+const LEGACY = `p${PTY_PROTOCOL}`const discoveryFile = (home: string) => path.join(home, 'run', `pty-host-${PTY_PROTOCOL}.json`)function writeDiscovery(home: string, value: unknown): void {mkdirSync(path.join(home, 'run'), { recursive: true })@@ -95,27 +98,58 @@ describe('ptyHostBinary', () => {})})-describe('readDiscovery', () => {- const valid = { protocol: PTY_PROTOCOL, instance: 'p1', endpoint: '/x.sock', pid: 7, version: '0.1.0', token: 't' }+describe('readInstanceDiscovery', () => {+ const valid = { protocol: PTY_PROTOCOL, instance: LEGACY, endpoint: '/x.sock', pid: 7, version: '0.1.0', token: 't' }- it('reads <home>/run/pty-host-<protocol>.json', () => {+ it('reads a legacy p<n> from <home>/run/pty-host-<n>.json, and a versioned one from pty-host-<instance>.json', () => {const home = tempDir('h-')writeDiscovery(home, valid)- expect(readDiscovery(home, PTY_PROTOCOL)).toEqual(valid)+ expect(readInstanceDiscovery(home, LEGACY)).toEqual(valid)+ const versioned = { ...valid, instance: `p${PTY_PROTOCOL}-0.4.21`, version: '0.4.21' }+ writeFileSync(path.join(home, 'run', `pty-host-p${PTY_PROTOCOL}-0.4.21.json`), JSON.stringify(versioned))+ expect(readInstanceDiscovery(home, versioned.instance)).toEqual(versioned)+ // Each instance its own file.+ expect(readInstanceDiscovery(home, LEGACY)).toEqual(valid)})- it('gives null for a missing, unreadable or malformed file, or another protocol', () => {+ it('gives null for a missing, unreadable or malformed file, another protocol or another instance', () => {const home = tempDir('h-')- expect(readDiscovery(home, PTY_PROTOCOL)).toBeNull()+ expect(readInstanceDiscovery(home, LEGACY)).toBeNull()mkdirSync(path.join(home, 'run'))writeFileSync(discoveryFile(home), '{"protocol":')- expect(readDiscovery(home, PTY_PROTOCOL)).toBeNull()+ expect(readInstanceDiscovery(home, LEGACY)).toBeNull()writeDiscovery(home, { ...valid, pid: '7' })- expect(readDiscovery(home, PTY_PROTOCOL)).toBeNull()+ expect(readInstanceDiscovery(home, LEGACY)).toBeNull()writeDiscovery(home, null)- expect(readDiscovery(home, PTY_PROTOCOL)).toBeNull()+ expect(readInstanceDiscovery(home, LEGACY)).toBeNull()writeDiscovery(home, { ...valid, protocol: PTY_PROTOCOL + 1 })- expect(readDiscovery(home, PTY_PROTOCOL)).toBeNull()+ expect(readInstanceDiscovery(home, LEGACY)).toBeNull()+ writeDiscovery(home, { ...valid, instance: `p${PTY_PROTOCOL}-0.4.21` })+ expect(readInstanceDiscovery(home, LEGACY)).toBeNull()+ // Not an instance: never a path.+ expect(readInstanceDiscovery(home, '../run/pty-host-2')).toBeNull()+ })+})++describe('listDiscoveries', () => {+ it('listDiscoveries finds legacy and versioned hosts, oldest first', () => {+ const dir = tempDir('h-')+ expect(listDiscoveries(dir)).toEqual([])+ expect(listDiscoveries(path.join(dir, 'none'))).toEqual([])+ writeDiscoveryOf(dir, 2, { endpoint: '/b', pid: 2, version: '0.4.21' }, 'p2-0.4.21')+ writeDiscoveryOf(dir, 3, { endpoint: '/e', pid: 5, version: '0.1.0' }, 'p3-0.1.0')+ writeDiscoveryOf(dir, 2, { endpoint: '/a', pid: 1, version: '0.4.20' }, 'p2-0.4.20')+ writeDiscoveryOf(dir, 2, { endpoint: '/l', pid: 9, version: '0.4.19' })+ writeDiscoveryOf(dir, 2, { endpoint: '/d', pid: 3, version: '0.4.21-dev.win1' }, 'p2-0.4.21-dev.win1')+ writeDiscoveryOf(dir, 1, { endpoint: '/o', pid: 4, version: '0.3.0' })+ // Not discovery files: the wrong shape, an instance another file is named for, a protocol its instance is not of.+ writeFileSync(path.join(dir, 'run', 'pty-host-junk.json'), JSON.stringify({ protocol: 2, instance: 'junk', endpoint: '/j', pid: 6, version: 'x', token: 't' }))+ writeFileSync(path.join(dir, 'run', 'pty-host-p2-9.json'), JSON.stringify({ protocol: 2, instance: 'p2-0.4.20', endpoint: '/j', pid: 6, version: 'x', token: 't' }))+ writeFileSync(path.join(dir, 'run', 'pty-host-p2-8.json'), JSON.stringify({ protocol: 1, instance: 'p2-8', endpoint: '/j', pid: 6, version: 'x', token: 't' }))+ writeFileSync(path.join(dir, 'run', 'pty-host-p2-7.json'), '{"protocol":')+ writeFileSync(path.join(dir, 'run', 'pty-host-p2-0.4.20.lock'), '')+ expect(listDiscoveries(dir).map(host => host.instance)).toEqual(['p1', 'p2', 'p2-0.4.20', 'p2-0.4.21-dev.win1', 'p2-0.4.21', 'p3-0.1.0'])+ expect(listDiscoveries(dir)[2]).toEqual({ protocol: 2, instance: 'p2-0.4.20', endpoint: '/a', pid: 1, version: '0.4.20', token: 't' })})})@@ -124,13 +158,19 @@ describe('readDiscovery', () => {* `<home>/spawns`, then serves (writing its discovery file once it listens), fails, or exits* at once as a host that found another one serving does.*/-function fakeBinary(mode: 'serve' | 'fail' | 'quiet' | 'deaf'): string {- const dir = tempDir('bin-')- return executable(path.join(dir, exe), `#!${process.execPath}+function fakeBinary(mode: 'serve' | 'fail' | 'quiet' | 'deaf', options: { instance?: string; versionLine?: string; file?: string } = {}): string {+ const instance = options.instance ?? LEGACY+ const name = discoveryFileName(instance)!+ return executable(options.file ?? path.join(tempDir('bin-'), exe), `#!${process.execPath}import crypto from 'node:crypto'import fs from 'node:fs'import net from 'node:net'import path from 'node:path'+if (process.argv[2] === 'version') {+ if (process.env.FAKE_PTY_RUNS) fs.appendFileSync(process.env.FAKE_PTY_RUNS, 'version\\n')+ process.stdout.write(${JSON.stringify(`${options.versionLine ?? ''}\n`)})+ process.exit(0)+}const home = process.argv[process.argv.indexOf('--home') + 1]const run = path.join(home, 'run')fs.mkdirSync(run, { recursive: true })@@ -144,8 +184,8 @@ const endpoint = path.join(run, 'h.sock')fs.rmSync(endpoint, { force: true })if (${JSON.stringify(mode)} === 'deaf') {// A discovery file naming an endpoint nothing listens at, from a host that then stays up.- const file = path.join(run, 'pty-host-${PTY_PROTOCOL}.json')- fs.writeFileSync(file, JSON.stringify({ protocol: ${PTY_PROTOCOL}, instance: 'p1', endpoint, pid: process.pid, version: 'fake', token: 'fake-token' }))+ const file = path.join(run, ${JSON.stringify(name)})+ fs.writeFileSync(file, JSON.stringify({ protocol: ${PTY_PROTOCOL}, instance: ${JSON.stringify(instance)}, endpoint, pid: process.pid, version: 'fake', token: 'fake-token' }))setInterval(() => {}, 1000)} else {const server = net.createServer(socket => {@@ -161,7 +201,7 @@ const server = net.createServer(socket => {if (!said) {said = trueconst proof = crypto.createHash('sha256').update('fake-token').update('\\0').update(String(value.hello.nonce)).digest('hex')- socket.write(JSON.stringify({ hello: { ok: true, instance: 'p1', version: 'fake', pid: process.pid, proof } }) + '\\n')+ socket.write(JSON.stringify({ hello: { ok: true, instance: ${JSON.stringify(instance)}, version: 'fake', pid: process.pid, proof } }) + '\\n')continue}socket.write(JSON.stringify(value.op === 'inventory' ? { id: value.id, ok: true, panes: [] } : { id: value.id, ok: true }) + '\\n')@@ -169,8 +209,8 @@ const server = net.createServer(socket => {})})server.listen(endpoint, () => {- const file = path.join(run, 'pty-host-${PTY_PROTOCOL}.json')- fs.writeFileSync(file + '.tmp', JSON.stringify({ protocol: ${PTY_PROTOCOL}, instance: 'p1', endpoint, pid: process.pid, version: 'fake', token: 'fake-token' }))+ const file = path.join(run, ${JSON.stringify(name)})+ fs.writeFileSync(file + '.tmp', JSON.stringify({ protocol: ${PTY_PROTOCOL}, instance: ${JSON.stringify(instance)}, endpoint, pid: process.pid, version: 'fake', token: 'fake-token' }))fs.renameSync(file + '.tmp', file)})}@@ -204,9 +244,9 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {it('connects to the host the discovery file names, without starting one', async () => {const dir = home()const binary = fakeBinary('serve')- const first = await clientOf(await ensurePtyHost(dir, { binary }))+ const first = await clientOf(await ensurePtyHost(dir, { target: null, binary }))expect(spawnCount(dir)).toBe(1)- const second = await clientOf(await ensurePtyHost(dir, { binary: null }))+ const second = await clientOf(await ensurePtyHost(dir, { target: null, binary: null }))expect(second).not.toBe(first)expect(await second.call({ op: 'inventory' })).toEqual({ state: 'ok', value: { panes: [] } })expect(spawnCount(dir)).toBe(1)@@ -218,7 +258,7 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {vi.stubEnv('PTY_LAUNCH_KEPT', 'yes')try {const dir = home()- await clientOf(await ensurePtyHost(dir, { binary: fakeBinary('serve') }))+ await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve') }))expect(JSON.parse(readFileSync(path.join(dir, 'env.json'), 'utf8'))).toEqual({ TMUX: null, TMUX_PANE: null, KEPT: 'yes' })expect(process.env.TMUX_PANE).toBe('%42')} finally { vi.unstubAllEnvs() }@@ -226,7 +266,7 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {it('starts the host in its home, not in the daemon\'s directory', async () => {const dir = home()- await clientOf(await ensurePtyHost(dir, { binary: fakeBinary('serve') }))+ await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve') }))expect(readFileSync(path.join(dir, 'cwd'), 'utf8')).toBe(realpathSync(dir))expect(realpathSync(process.cwd())).not.toBe(realpathSync(dir))})@@ -234,64 +274,73 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {it('starts the host in a home that does not exist yet, making it', async () => {const parent = home()const dir = path.join(parent, 'not', 'yet')- const client = await clientOf(await ensurePtyHost(dir, { binary: fakeBinary('serve') }))+ const client = await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve') }))cleanup.push(() => {- const pid = readDiscovery(dir, PTY_PROTOCOL)?.pid+ const pid = readInstanceDiscovery(dir, LEGACY)?.pidif (pid) try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }})- expect(client.instance).toBe('p1')+ expect(client.instance).toBe(LEGACY)expect(readFileSync(path.join(dir, 'cwd'), 'utf8')).toBe(realpathSync(dir))expect(statSync(dir).mode & 0o777).toBe(0o700)})it('starts a host when there is no discovery file, and waits for it', async () => {const dir = home()- const client = await clientOf(await ensurePtyHost(dir, { binary: fakeBinary('serve') }))- expect(client.instance).toBe('p1')- expect(readDiscovery(dir, PTY_PROTOCOL)?.pid).toBe(Number(readFileSync(path.join(dir, 'spawns'), 'utf8').trim()))+ const client = await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve') }))+ expect(client.instance).toBe(LEGACY)+ expect(readInstanceDiscovery(dir, LEGACY)?.pid).toBe(Number(readFileSync(path.join(dir, 'spawns'), 'utf8').trim()))})it('starts a host when the endpoint in the discovery file refuses', async () => {const dir = home()- writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: 'p1', endpoint: path.join(dir, 'gone.sock'), pid: 999_999, version: 'old', token: 't' })- const client = await clientOf(await ensurePtyHost(dir, { binary: fakeBinary('serve') }))+ writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: LEGACY, endpoint: path.join(dir, 'gone.sock'), pid: 999_999, version: 'old', token: 't' })+ const client = await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve') }))expect(await client.call({ op: 'inventory' })).toMatchObject({ state: 'ok' })- expect(readDiscovery(dir, PTY_PROTOCOL)?.version).toBe('fake')+ expect(readInstanceDiscovery(dir, LEGACY)?.version).toBe('fake')+ })++ it('without a target, waits for whichever host of this protocol the binary starts: a versioned one too', async () => {+ const dir = home()+ // A legacy host that has exited is no host.+ writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: LEGACY, endpoint: path.join(dir, 'gone.sock'), pid: deadPid(), version: 'old', token: 't' })+ const client = await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve', { instance: `p${PTY_PROTOCOL}-0.4.21` }) }))+ expect(client.instance).toBe(`p${PTY_PROTOCOL}-0.4.21`)+ expect(spawnCount(dir)).toBe(1)})it('starts one host for concurrent calls', async () => {const dir = home()const binary = fakeBinary('serve')- const results = await Promise.all([ensurePtyHost(dir, { binary }), ensurePtyHost(dir, { binary }), ensurePtyHost(dir, { binary })])+ const results = await Promise.all([ensurePtyHost(dir, { target: null, binary }), ensurePtyHost(dir, { target: null, binary }), ensurePtyHost(dir, { target: null, binary })])for (const result of results) await clientOf(result)expect(spawnCount(dir)).toBe(1)})it('is unavailable when there is no binary', async () => {- expect(await ensurePtyHost(home(), { binary: null })).toEqual({+ expect(await ensurePtyHost(home(), { target: null, binary: null })).toEqual({unavailable: expect.stringContaining('harness-pty'), code: 'PTY_HOST_UNAVAILABLE',})})it('is unavailable when the binary cannot be started', async () => {- const result = await ensurePtyHost(home(), { binary: path.join(tempDir('bin-'), 'missing') })+ const result = await ensurePtyHost(home(), { target: null, binary: path.join(tempDir('bin-'), 'missing') })expect(result).toEqual({ unavailable: expect.stringContaining('could not start'), code: 'PTY_HOST_UNAVAILABLE' })})it('is unavailable at once when the host exits with an error', async () => {const started = Date.now()- const result = await ensurePtyHost(home(), { binary: fakeBinary('fail'), waitMs: 5_000 })+ const result = await ensurePtyHost(home(), { target: null, binary: fakeBinary('fail'), waitMs: 5_000 })expect(result).toEqual({ unavailable: expect.stringContaining('exited with code 4'), code: 'PTY_HOST_UNAVAILABLE' })expect(Date.now() - started).toBeLessThan(4_000)})it('is unavailable when no discovery file appears in time', async () => {- const result = await ensurePtyHost(home(), { binary: fakeBinary('quiet'), waitMs: 300 })+ const result = await ensurePtyHost(home(), { target: null, binary: fakeBinary('quiet'), waitMs: 300 })expect(result).toEqual({ unavailable: expect.stringContaining('300 ms'), code: 'PTY_HOST_UNAVAILABLE' })})it('is unavailable, saying so, when the endpoint a new discovery file names refuses connections', async () => {- const result = await ensurePtyHost(home(), { binary: fakeBinary('deaf') })+ const result = await ensurePtyHost(home(), { target: null, binary: fakeBinary('deaf') })expect(result).toEqual({unavailable: 'no harness-pty answers at the endpoint its discovery file names', code: 'PTY_HOST_UNAVAILABLE',})@@ -309,8 +358,8 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {server.listen(endpoint)await once(server, 'listening')cleanup.push(() => new Promise(resolve => server.close(resolve)))- writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: 'p1', endpoint, pid: 1, version: 'v', token: 'stale' })- expect(await ensurePtyHost(dir, { binary: fakeBinary('serve') })).toEqual({ incompatible: 'incompatible: wrong token' })+ writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: LEGACY, endpoint, pid: 1, version: 'v', token: 'stale' })+ expect(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve') })).toEqual({ incompatible: 'incompatible: wrong token' })expect(spawnCount(dir)).toBe(0)})@@ -326,8 +375,8 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {squatter.listen(endpoint)await once(squatter, 'listening')cleanup.push(() => new Promise(resolve => squatter.close(resolve)))- writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: 'p1', endpoint, pid: deadPid(), version: 'v', token: 'stale' })- const client = await clientOf(await ensurePtyHost(dir, { binary: fakeBinary('serve') }))+ writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: LEGACY, endpoint, pid: deadPid(), version: 'v', token: 'stale' })+ const client = await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve') }))expect(await client.call({ op: 'inventory' })).toMatchObject({ state: 'ok' })expect(spawnCount(dir)).toBe(1)expect(dialled).toBe(0)@@ -345,7 +394,7 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {server.listen(endpoint)await once(server, 'listening')cleanup.push(() => new Promise(resolve => server.close(resolve)))- writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: 'p1', endpoint, pid: process.pid, version: 'v', token: 'stale' })+ writeDiscovery(dir, { protocol: PTY_PROTOCOL, instance: LEGACY, endpoint, pid: process.pid, version: 'v', token: 'stale' })// The host that wrote the file started before it; this one after: not it.// (The host started in its place is listed too, as having started before its own file.)const started = () => existsSync(path.join(dir, 'spawns'))@@ -354,13 +403,13 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {{ pid: process.pid, executable: 'x', startMarker: filetime(Date.now() + 60_000) },...started().map(pid => ({ pid, executable: 'harness-pty', startMarker: filetime(Date.now() - 60_000) })),] }- expect(await clientOf(await ensurePtyHost(dir, { binary: fakeBinary('serve'), liveness: later }))).toBeTruthy()+ expect(await clientOf(await ensurePtyHost(dir, { target: null, binary: fakeBinary('serve'), liveness: later }))).toBeTruthy()expect(dialled).toBe(0)// The process that wrote it, still running and refusing: an error, and no other host is started.const other = home()- writeDiscovery(other, { protocol: PTY_PROTOCOL, instance: 'p1', endpoint, pid: process.pid, version: 'v', token: 'stale' })+ writeDiscovery(other, { protocol: PTY_PROTOCOL, instance: LEGACY, endpoint, pid: process.pid, version: 'v', token: 'stale' })const earlier = { alive: () => true, rows: async () => [{ pid: process.pid, executable: 'x', startMarker: filetime(Date.now() - 60_000) }] }- expect(await ensurePtyHost(other, { binary: fakeBinary('serve'), liveness: earlier })).toEqual({ incompatible: 'incompatible: wrong token' })+ expect(await ensurePtyHost(other, { target: null, binary: fakeBinary('serve'), liveness: earlier })).toEqual({ incompatible: 'incompatible: wrong token' })expect(dialled).toBe(1)expect(spawnCount(other)).toBe(0)})@@ -368,8 +417,8 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {it('tries again once when the discovery file changed during a refused hello', async () => {const dir = home()const binary = fakeBinary('serve')- await clientOf(await ensurePtyHost(dir, { binary }))- const live = readDiscovery(dir, PTY_PROTOCOL)!+ await clientOf(await ensurePtyHost(dir, { target: null, binary }))+ const live = readInstanceDiscovery(dir, LEGACY)!// A host that just restarted: the file still names the old token while the new host answers.const endpoint = path.join(dir, 'r.sock')const server = net.createServer(socket => {@@ -383,7 +432,7 @@ describe.skipIf(process.platform === 'win32')('ensurePtyHost', () => {await once(server, 'listening')cleanup.push(() => new Promise(resolve => server.close(resolve)))writeDiscovery(dir, { ...live, endpoint, token: 'old', pid: 1 })- const client = await clientOf(await ensurePtyHost(dir, { binary: null }))+ const client = await clientOf(await ensurePtyHost(dir, { target: null, binary: null }))expect(await client.call({ op: 'inventory' })).toMatchObject({ state: 'ok' })})})@@ -393,8 +442,11 @@ const endpointIn = (dir: string, name: string) => process.platform === 'win32'? `\\\\.\\pipe\\pty-launch-${path.basename(dir)}-${name}`: path.join(dir, `${name}.sock`)-/** A host stand-in in this process that proves [token] and answers every request `ok`; the protocols said hello in. */-async function answeringHost(endpoint: string, token: string): Promise<number[]> {+/**+ * A host stand-in in this process that proves [token] and answers every request `ok`, saying hello as [instance]+ * (`p<protocol>` by default); the protocols said hello in.+ */+async function answeringHost(endpoint: string, token: string, instance?: string): Promise<number[]> {const protocols: number[] = []const server = net.createServer(socket => {socket.on('error', () => {})@@ -409,7 +461,7 @@ async function answeringHost(endpoint: string, token: string): Promise<number[]>if (said) { socket.write(`${JSON.stringify({ id: value.id, ok: true })}\n`); continue }said = trueprotocols.push(value.hello.protocol)- socket.write(`${JSON.stringify({ hello: { ok: true, instance: `p${value.hello.protocol}`, version: 'v', pid: process.pid, proof: helloProof(token, value.hello.nonce) } })}\n`)+ socket.write(`${JSON.stringify({ hello: { ok: true, instance: instance ?? `p${value.hello.protocol}`, version: 'v', pid: process.pid, proof: helloProof(token, value.hello.nonce) } })}\n`)}})})@@ -419,9 +471,10 @@ async function answeringHost(endpoint: string, token: string): Promise<number[]>return protocols}-const writeDiscoveryOf = (home: string, protocol: number, value: Record<string, unknown>) => {+/** [instance]'s discovery file (a legacy `p<protocol>` by default), in the file it is read from. */+const writeDiscoveryOf = (home: string, protocol: number, value: Record<string, unknown>, instance = `p${protocol}`) => {mkdirSync(path.join(home, 'run'), { recursive: true })- writeFileSync(path.join(home, 'run', `pty-host-${protocol}.json`), JSON.stringify({ protocol, instance: `p${protocol}`, version: '0.1.0', token: 't', ...value }))+ writeFileSync(path.join(home, 'run', discoveryFileName(instance)!), JSON.stringify({ protocol, instance, version: '0.1.0', token: 't', ...value }))}/** A pid no process has: a child that has exited. */function deadPid(): number {@@ -442,7 +495,7 @@ describe('discoveredHostDead', () => {it('is proven only by a pid that runs nothing, a table without it, or a process that started after the file', async () => {const dir = tempDir('h-')writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: '/x', pid: 42 })- const discovery = { protocol: PTY_PROTOCOL, pid: 42 }+ const discovery = { instance: `p${PTY_PROTOCOL}`, pid: 42 }const row = (startMarker: string) => ({ pid: 42, executable: 'harness-pty.exe', startMarker })expect(await discoveredHostDead(dir, discovery, { alive: () => false })).toBe(true)// The pid alone, alive: no proof.@@ -457,30 +510,34 @@ describe('discoveredHostDead', () => {expect(await discoveredHostDead(dir, discovery, { alive: () => true, rows: async () => { throw new Error('ps') } })).toBe(false)expect(await discoveredHostDead(dir, discovery, { alive: () => true, rows: async () => [row('soon')] })).toBe(false)expect(await discoveredHostDead(tempDir('h-'), discovery, { alive: () => true, rows: async () => [row(filetime(Date.now() + 60_000))] })).toBe(false)+ // A versioned instance is judged against its own file: another instance's says nothing of it.+ const versioned = { instance: `p${PTY_PROTOCOL}-0.4.21`, pid: 42 }+ expect(await discoveredHostDead(dir, versioned, { alive: () => true, rows: async () => [row(filetime(Date.now() + 60_000))] })).toBe(false)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: '/x', pid: 42 }, versioned.instance)+ expect(await discoveredHostDead(dir, versioned, { alive: () => true, rows: async () => [row(filetime(Date.now() + 60_000))] })).toBe(true)})})-describe('discoverHosts', () => {- it('reads every supported protocol\'s discovery file, oldest first, and nothing else', () => {- const dir = tempDir('h-')- expect(discoverHosts(dir)).toEqual([])- for (const protocol of [...SUPPORTED_PTY_PROTOCOLS, PTY_PROTOCOL + 1]) writeDiscoveryOf(dir, protocol, { endpoint: `/e${protocol}`, pid: protocol })- expect(discoverHosts(dir).map(host => host.protocol)).toEqual([...SUPPORTED_PTY_PROTOCOLS])- expect(SUPPORTED_PTY_PROTOCOLS).toEqual([PTY_PROTOCOL - 1, PTY_PROTOCOL].filter(p => p >= 1))- })-})describe('reachPtyHost', () => {- it('connects to the host of the protocol asked, in its own protocol, and never starts one', async () => {+ it('connects to the host of the instance asked, in its own protocol, and never starts one', async () => {const dir = tempDir('h-')const protocol = SUPPORTED_PTY_PROTOCOLS[0]const endpoint = endpointIn(dir, 'old')const protocols = await answeringHost(endpoint, 't')writeDiscoveryOf(dir, protocol, { endpoint, pid: process.pid })- const result = await reachPtyHost(dir, protocol)+ const result = await reachPtyHost(dir, `p${protocol}`)const client = await clientOf(result as Awaited<ReturnType<typeof ensurePtyHost>>)expect(client.protocol).toBe(protocol)expect(protocols).toEqual([protocol])+ // A versioned instance, from its own file.+ const versioned = endpointIn(dir, 'versioned')+ const heard = await answeringHost(versioned, 't', `p${PTY_PROTOCOL}-0.4.21`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: versioned, pid: process.pid }, `p${PTY_PROTOCOL}-0.4.21`)+ const other = await clientOf(await reachPtyHost(dir, `p${PTY_PROTOCOL}-0.4.21`) as Awaited<ReturnType<typeof ensurePtyHost>>)+ expect(other.instance).toBe(`p${PTY_PROTOCOL}-0.4.21`)+ expect(heard).toEqual([PTY_PROTOCOL])+ expect(protocols).toEqual([protocol])})it('never dials a dead host\'s endpoint, even when something answers there', async () => {@@ -490,19 +547,20 @@ describe('reachPtyHost', () => {const protocols = await answeringHost(endpoint, 't')const dead = deadPid()writeDiscoveryOf(dir, protocol, { endpoint, pid: dead })- expect(await reachPtyHost(dir, protocol)).toEqual({ unavailable: expect.stringContaining(`pid ${dead}`), code: 'PTY_HOST_UNAVAILABLE', pid: dead, missing: false })+ expect(await reachPtyHost(dir, `p${protocol}`)).toEqual({ unavailable: expect.stringContaining(`pid ${dead}`), code: 'PTY_HOST_UNAVAILABLE', pid: dead, missing: false })expect(protocols).toEqual([])})it('says what the file named when nothing answers, and never that the host has gone', async () => {const dir = tempDir('h-')- expect(await reachPtyHost(dir, 1)).toEqual({ unavailable: 'there is no pty-host-1.json', code: 'PTY_HOST_UNAVAILABLE', pid: null, missing: true })+ expect(await reachPtyHost(dir, 'p1')).toEqual({ unavailable: 'there is no pty-host-1.json', code: 'PTY_HOST_UNAVAILABLE', pid: null, missing: true })+ expect(await reachPtyHost(dir, 'p2-0.4.21')).toEqual({ unavailable: 'there is no pty-host-p2-0.4.21.json', code: 'PTY_HOST_UNAVAILABLE', pid: null, missing: true })mkdirSync(path.join(dir, 'run'), { recursive: true })writeFileSync(path.join(dir, 'run', 'pty-host-1.json'), '{"protocol":')- expect(await reachPtyHost(dir, 1)).toEqual({ unavailable: 'pty-host-1.json cannot be read', code: 'PTY_HOST_UNAVAILABLE', pid: null, missing: false })+ expect(await reachPtyHost(dir, 'p1')).toEqual({ unavailable: 'pty-host-1.json cannot be read', code: 'PTY_HOST_UNAVAILABLE', pid: null, missing: false })const dead = deadPid()writeDiscoveryOf(dir, 1, { endpoint: endpointIn(dir, 'none'), pid: dead })- expect(await reachPtyHost(dir, 1)).toEqual({ unavailable: expect.stringContaining(`pid ${dead}`), code: 'PTY_HOST_UNAVAILABLE', pid: dead, missing: false })+ expect(await reachPtyHost(dir, 'p1')).toEqual({ unavailable: expect.stringContaining(`pid ${dead}`), code: 'PTY_HOST_UNAVAILABLE', pid: dead, missing: false })})})@@ -515,17 +573,185 @@ describe('forgetExitedHost', () => {writeDiscoveryOf(dir, 1, { endpoint: socket, pid: dead })writeFileSync(socket, '')// Another pid's file (a host that took its place), or a live one: kept.- forgetExitedHost(dir, 1, dead + 1)+ forgetExitedHost(dir, 'p1', dead + 1)expect(existsSync(file)).toBe(true)writeDiscoveryOf(dir, 1, { endpoint: socket, pid: process.pid })- forgetExitedHost(dir, 1, process.pid)+ forgetExitedHost(dir, 'p1', process.pid)expect(existsSync(file)).toBe(true)writeDiscoveryOf(dir, 1, { endpoint: socket, pid: dead })- forgetExitedHost(dir, 1, dead)+ forgetExitedHost(dir, 'p1', dead)expect(existsSync(file)).toBe(false)expect(existsSync(socket)).toBe(process.platform === 'win32')// Nothing there: nothing to do.- forgetExitedHost(dir, 1, dead)+ forgetExitedHost(dir, 'p1', dead)+ // A versioned instance's own file, and never another instance's.+ const instance = `p${PTY_PROTOCOL}-0.4.21`+ const own = path.join(dir, 'run', `pty-host-${instance}.json`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: socket, pid: dead }, instance)+ writeDiscoveryOf(dir, 1, { endpoint: socket, pid: dead })+ forgetExitedHost(dir, instance, dead)+ expect([existsSync(own), existsSync(file)]).toEqual([false, true])+ })++ it('takes the lock and pane-id files of the exited instance with it, and never while the host runs or another instance\'s', () => {+ const dir = tempDir('h-')+ const instance = `p${PTY_PROTOCOL}-0.4.21`+ const other = `p${PTY_PROTOCOL}-0.4.22`+ const run = path.join(dir, 'run')+ const files = (name: string) => ['json', 'lock', 'panes'].map((ext) => path.join(run, `pty-host-${name}.${ext}`))+ const dead = deadPid()+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: path.join(run, 'x.sock'), pid: process.pid }, instance)+ for (const file of [...files(instance).slice(1), ...files(other)]) writeFileSync(file, '1')+ // A live host keeps all of them.+ forgetExitedHost(dir, instance, process.pid)+ expect(files(instance).map((file) => existsSync(file))).toEqual([true, true, true])+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: path.join(run, 'x.sock'), pid: dead }, instance)+ forgetExitedHost(dir, instance, dead)+ expect(files(instance).map((file) => existsSync(file))).toEqual([false, false, false])+ expect(files(other).map((file) => existsSync(file))).toEqual([true, true, true])+ })++ it('goes on when a lock file cannot be removed', () => {+ const dir = tempDir('h-')+ const instance = `p${PTY_PROTOCOL}-0.4.23`+ const run = path.join(dir, 'run')+ const dead = deadPid()+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: path.join(run, 'x.sock'), pid: dead }, instance)+ // A directory in the lock's place cannot be removed as a file, as a lock a scanner still holds on Windows.+ mkdirSync(path.join(run, `pty-host-${instance}.lock`))+ writeFileSync(path.join(run, `pty-host-${instance}.panes`), '1')+ forgetExitedHost(dir, instance, dead)+ expect([existsSync(path.join(run, `pty-host-${instance}.json`)), existsSync(path.join(run, `pty-host-${instance}.panes`))]).toEqual([false, false])+ })+})++const SEED_LINE = (version: string) => JSON.stringify({ version, protocol: PTY_PROTOCOL, features: ['seed'] })++// The fake binary is a script with a shebang, which Windows cannot run.+describe.skipIf(process.platform === 'win32')('targetHost', () => {+ it('targetHost reads current-pty, and is installed', () => {+ const runtime = tempDir('rt-')+ // The binary says another version than its folder: the installed CLI's pointer names the version.+ fakeBinary('serve', { file: path.join(runtime, 'pty', '0.4.21', exe), versionLine: SEED_LINE('0.4.21') })+ writeFileSync(path.join(runtime, 'pty', 'current-pty'), '0.4.21\n')+ expect(targetHost({ env: {}, runtimeDir: runtime, besideDir: '/nowhere' })).toEqual({+ protocol: PTY_PROTOCOL, version: '0.4.21', instance: `p${PTY_PROTOCOL}-0.4.21`, features: ['seed'], source: 'installed',+ })+ // HARNESS_PTY_BIN naming that very binary is still the installed one.+ expect(targetHost({ env: { HARNESS_PTY_BIN: path.join(runtime, 'pty', '0.4.21', exe) }, runtimeDir: runtime, besideDir: '/nowhere' })?.source).toBe('installed')+ })++ it('targetHost asks a dev binary its version, and is binary', () => {+ const runtime = tempDir('rt-')+ const binary = fakeBinary('serve', { versionLine: SEED_LINE('9.9.9') })+ expect(targetHost({ env: { HARNESS_PTY_BIN: binary }, runtimeDir: runtime, besideDir: '/nowhere' })).toEqual({+ protocol: PTY_PROTOCOL, version: '9.9.9', instance: `p${PTY_PROTOCOL}-9.9.9`, features: ['seed'], source: 'binary',+ })+ // No current-pty: the binary beside the bundle, asked.+ const besideDir = tempDir('dist-')+ fakeBinary('serve', { file: path.join(besideDir, 'pty', exe), versionLine: SEED_LINE('0.4.21-dev.win1') })+ expect(targetHost({ env: {}, runtimeDir: runtime, besideDir })).toMatchObject({ version: '0.4.21-dev.win1', instance: `p${PTY_PROTOCOL}-0.4.21-dev.win1`, source: 'binary' })+ // A host from before versioned instances lists no features, and is still `p<protocol>`.+ const old = fakeBinary('serve', { versionLine: JSON.stringify({ version: '0.4.19', protocol: PTY_PROTOCOL }) })+ expect(targetHost({ env: { HARNESS_PTY_BIN: old }, runtimeDir: runtime, besideDir: '/nowhere' })).toEqual({+ protocol: PTY_PROTOCOL, version: '0.4.19', instance: LEGACY, features: [], source: 'binary',+ })+ })++ it('targetHost is null when neither is known', () => {+ const runtime = tempDir('rt-')+ expect(targetHost({ env: {}, runtimeDir: runtime, besideDir: '/nowhere' })).toBeNull()+ for (const line of ['', 'harness-pty 0.4.21', '{"version":"","protocol":2}', '{"version":"1","protocol":"2"}', '{"version":"1","protocol":2,"features":"seed"}']) {+ const binary = fakeBinary('serve', { versionLine: line })+ expect(targetHost({ env: { HARNESS_PTY_BIN: binary }, runtimeDir: runtime, besideDir: '/nowhere' }), line).toBeNull()+ }+ // A binary that is not there.+ expect(targetHost({ env: { HARNESS_PTY_BIN: path.join(runtime, 'missing') }, runtimeDir: runtime, besideDir: '/nowhere' })).toBeNull()+ })++ it('targetHost is unknown, said once, for a host of a protocol this daemon does not speak: the newest supported host is used', () => {+ const runtime = tempDir('rt-')+ // A paired host left in current-pty without its CLI build: above this daemon's protocol, or below every supported one.+ fakeBinary('serve', { file: path.join(runtime, 'pty', '0.5.0', exe), versionLine: JSON.stringify({ version: '0.5.0', protocol: PTY_PROTOCOL + 1, features: ['seed'] }) })+ writeFileSync(path.join(runtime, 'pty', 'current-pty'), '0.5.0\n')+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ expect(targetHost({ env: {}, runtimeDir: runtime, besideDir: '/nowhere' })).toBeNull()+ expect(targetHost({ env: {}, runtimeDir: runtime, besideDir: '/nowhere' })).toBeNull()+ const said = error.mock.calls.map((call) => String(call[0])).filter((line) => line.includes('0.5.0'))+ expect(said).toEqual([`[terminal] ptyhost: the host 0.5.0 speaks protocol ${PTY_PROTOCOL + 1}, which this daemon does not (it speaks ${SUPPORTED_PTY_PROTOCOLS.join(' and ')}): target unknown, the newest running host of protocol ${PTY_PROTOCOL} is used`])+ const old = fakeBinary('serve', { versionLine: JSON.stringify({ version: '0.0.9', protocol: 0, features: [] }) })+ expect(targetHost({ env: { HARNESS_PTY_BIN: old }, runtimeDir: runtime, besideDir: '/nowhere' })).toBeNull()+ } finally { error.mockRestore() }+ })++ it('binaryVersion runs the binary once per build: cached by its path and mtime', () => {+ const runs = path.join(tempDir('runs-'), 'runs')+ vi.stubEnv('FAKE_PTY_RUNS', runs)+ try {+ const binary = fakeBinary('serve', { versionLine: SEED_LINE('1.2.3') })+ expect(binaryVersion(binary)).toEqual({ version: '1.2.3', protocol: PTY_PROTOCOL, features: ['seed'] })+ expect(binaryVersion(binary)).toEqual({ version: '1.2.3', protocol: PTY_PROTOCOL, features: ['seed'] })+ expect(readFileSync(runs, 'utf8').split('\n').filter(Boolean)).toHaveLength(1)+ // A new build at the same path is asked again.+ fakeBinary('serve', { file: binary, versionLine: SEED_LINE('1.2.4') })+ utimesSync(binary, new Date(), new Date(Date.now() + 10_000))+ expect(binaryVersion(binary)?.version).toBe('1.2.4')+ expect(readFileSync(runs, 'utf8').split('\n').filter(Boolean)).toHaveLength(2)+ } finally { vi.unstubAllEnvs() }+ })+})++/** A target for [version] of this protocol, as `targetHost` gives it. */+const targetOf = (version: string) => ({+ protocol: PTY_PROTOCOL, version, instance: `p${PTY_PROTOCOL}-${version}`, features: ['seed'], source: 'binary' as const,+})++describe('ensurePtyHost by instance', () => {+ it('ensurePtyHost with a target never connects to another version\'s host', async () => {+ const dir = tempDir('h-')+ const older = await answeringHost(endpointIn(dir, 'older'), 't', `p${PTY_PROTOCOL}-0.4.20`)+ const newer = await answeringHost(endpointIn(dir, 'newer'), 't', `p${PTY_PROTOCOL}-0.4.21`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: endpointIn(dir, 'older'), pid: process.pid, version: '0.4.20' }, `p${PTY_PROTOCOL}-0.4.20`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: endpointIn(dir, 'newer'), pid: process.pid, version: '0.4.21' }, `p${PTY_PROTOCOL}-0.4.21`)+ // The older one is the target: never the newer, though it runs too.+ const client = await clientOf(await ensurePtyHost(dir, { target: targetOf('0.4.20'), binary: null }))+ expect(client.instance).toBe(`p${PTY_PROTOCOL}-0.4.20`)+ expect([older, newer]).toEqual([[PTY_PROTOCOL], []])+ // A target with no host: started (here there is no binary), and neither running host is dialled.+ expect(await ensurePtyHost(dir, { target: targetOf('0.5.0'), binary: null })).toEqual({+ unavailable: expect.stringContaining('harness-pty'), code: 'PTY_HOST_UNAVAILABLE',+ })+ expect([older, newer]).toEqual([[PTY_PROTOCOL], []])+ })++ it('ensurePtyHost without a target connects to the newest running host', async () => {+ const dir = tempDir('h-')+ const legacy = await answeringHost(endpointIn(dir, 'legacy'), 't')+ const older = await answeringHost(endpointIn(dir, 'older'), 't', `p${PTY_PROTOCOL}-0.4.20`)+ const newer = await answeringHost(endpointIn(dir, 'newer'), 't', `p${PTY_PROTOCOL}-0.4.21`)+ const squatted = await answeringHost(endpointIn(dir, 'squatted'), 't', `p${PTY_PROTOCOL}-0.4.22`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: endpointIn(dir, 'legacy'), pid: process.pid, version: '0.4.19' })+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: endpointIn(dir, 'older'), pid: process.pid, version: '0.4.20' }, `p${PTY_PROTOCOL}-0.4.20`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: endpointIn(dir, 'newer'), pid: process.pid, version: '0.4.21' }, `p${PTY_PROTOCOL}-0.4.21`)+ // Newest of all, but its host has exited: its endpoint is never dialled.+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: endpointIn(dir, 'squatted'), pid: deadPid(), version: '0.4.22' }, `p${PTY_PROTOCOL}-0.4.22`)+ const client = await clientOf(await ensurePtyHost(dir, { target: null, binary: null }))+ expect(client.instance).toBe(`p${PTY_PROTOCOL}-0.4.21`)+ expect([legacy, older, newer, squatted]).toEqual([[], [], [PTY_PROTOCOL], []])+ })++ it.skipIf(process.platform === 'win32')('ensurePtyHost with a target starts its binary beside another version\'s host, once for concurrent calls', async () => {+ const dir = home()+ const older = await answeringHost(endpointIn(dir, 'older'), 't', `p${PTY_PROTOCOL}-0.4.20`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: endpointIn(dir, 'older'), pid: process.pid, version: '0.4.20' }, `p${PTY_PROTOCOL}-0.4.20`)+ const target = targetOf('0.4.21')+ const binary = fakeBinary('serve', { instance: target.instance })+ const results = await Promise.all([ensurePtyHost(dir, { target, binary }), ensurePtyHost(dir, { target, binary })])+ for (const result of results) expect((await clientOf(result)).instance).toBe(target.instance)+ expect(spawnCount(dir)).toBe(1)+ expect(readInstanceDiscovery(dir, target.instance)?.pid).toBe(Number(readFileSync(path.join(dir, 'spawns'), 'utf8').trim()))+ expect(older).toEqual([])})})@@ -547,6 +773,32 @@ describe('removeUnusedPtyVersions', () => {// No runtime directory at all.expect(removeUnusedPtyVersions(dir, path.join(runtime, 'none'))).toEqual([])})++ it('removeUnusedPtyVersions keeps a folder a versioned host runs from', () => {+ const runtime = tempDir('rt-')+ const dir = tempDir('h-')+ for (const version of ['0.4.19', '0.4.20', '0.4.21', '0.4.22']) executable(path.join(runtime, 'pty', version, exe))+ writeFileSync(path.join(runtime, 'pty', 'current-pty'), '0.4.21')+ // Two hosts of one protocol, side by side: 0.4.20's runs, 0.4.19's has exited.+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: '/a', pid: process.pid, version: '0.4.20' }, `p${PTY_PROTOCOL}-0.4.20`)+ writeDiscoveryOf(dir, PTY_PROTOCOL, { endpoint: '/b', pid: deadPid(), version: '0.4.19' }, `p${PTY_PROTOCOL}-0.4.19`)+ expect(removeUnusedPtyVersions(dir, runtime)).toEqual(['0.4.19'])+ // Newer than current-pty stays, as before.+ expect(readdirSync(path.join(runtime, 'pty')).sort()).toEqual(['0.4.20', '0.4.21', '0.4.22', 'current-pty'])+ })++ it('removeUnusedPtyVersions keeps the version a host on probation would roll back to', () => {+ const runtime = tempDir('rt-')+ const dir = tempDir('h-')+ for (const version of ['0.4.19', '0.4.20', '0.4.21']) executable(path.join(runtime, 'pty', version, exe))+ writeFileSync(path.join(runtime, 'pty', 'current-pty'), '0.4.21')+ // 0.4.21 is on probation (lib/windows/ptyInstall.ts): no host runs from 0.4.20, and it is the rollback target.+ writeFileSync(path.join(runtime, 'pty', 'pty-pending.json'), JSON.stringify({ version: '0.4.21', previous: '0.4.20' }))+ expect(removeUnusedPtyVersions(dir, runtime)).toEqual(['0.4.19'])+ // Once it is kept, the marker goes, and so may the folder.+ rmSync(path.join(runtime, 'pty', 'pty-pending.json'))+ expect(removeUnusedPtyVersions(dir, runtime)).toEqual(['0.4.20'])+ })})describe('reachable', () => {@@ -579,12 +831,15 @@ describe('reachable', () => {describe.skipIf(!process.env.HARNESS_PTY_BIN)('ensurePtyHost with the real harness-pty', () => {it('starts the host in a temporary home, lists no panes, and reports a pane\'s exit after its create', async () => {const dir = tempDir('h-')+ const target = targetHost({ runtimeDir: tempDir('rt-') })+ if (!target) throw new Error('the real harness-pty did not say its version')cleanup.push(() => {- const pid = readDiscovery(dir, PTY_PROTOCOL)?.pid+ const pid = readInstanceDiscovery(dir, target.instance)?.pidif (pid) try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }})- const client = await clientOf(await ensurePtyHost(dir))- expect(client.instance).toBe(`p${PTY_PROTOCOL}`)+ const client = await clientOf(await ensurePtyHost(dir, { target }))+ expect(client.instance).toBe(target.instance)+ expect(client.features).toEqual(target.features)expect(await client.call({ op: 'inventory' })).toEqual({ state: 'ok', value: { panes: [] } })// A command that exits at once: its exit notice may overtake the create reply.diff --git a/cli/src/lib/ptyHost/launch.ts b/cli/src/lib/ptyHost/launch.tsindex eff136dbc..88dc71e30 100644--- a/cli/src/lib/ptyHost/launch.ts+++ b/cli/src/lib/ptyHost/launch.ts@@ -1,9 +1,9 @@/**- * Finding `harness-pty`, finding the host it started (its discovery file), and starting one when- * there is none. In production harnessd keeps the host running (sub-project B); this is how the+ * Finding `harness-pty` and the host build it is (the target), finding hosts by their instance (their discovery files),+ * and starting one when there is none. In production harnessd keeps the host running (sub-project B); this is how the* daemon gets one without it, in development and tests.*/-import { spawn } from 'node:child_process'+import { execFileSync, spawn } from 'node:child_process'import { accessSync, constants, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'import net from 'node:net'import path from 'node:path'@@ -11,6 +11,7 @@ import { fileURLToPath } from 'node:url'import { env } from '../../config/env.js'import { scrubTerminalContext } from '../terminalEnvironment.js'import { PtyHostClient, type PtyHostDiscovery } from './client.js'+import { discoveryFileName, hostInstanceName, instanceProtocol } from './instance.js'import { PTY_PROTOCOL, SUPPORTED_PTY_PROTOCOLS } from './protocol.js'import { pidAlive, recordedProcessDead, startMarkerMs, type HostLiveness, type HostProcessRow } from '../processProof.js'@@ -23,6 +24,8 @@ const START_WAIT_MS = 5_000const POLL_MS = 25/** How long a connection may take to be accepted: as long as `PtyHostClient.connect` gives a hello. */const CONNECT_TIMEOUT_MS = 5_000+/** How long `harness-pty version` may take. */+const VERSION_TIMEOUT_MS = 5_000function runnable(file: string): boolean {try {@@ -33,17 +36,35 @@ function runnable(file: string): boolean {}}-const VERSION_DIR = /^\d+(\.\d+)*$/+export const VERSION_DIR = /^\d+(\.\d+)*$/+/**+ * Orders two versions: their dotted numbers first, then a pre-release (`-dev.win1`) before its release, as semver+ * does, and build metadata (`+…`) not at all. A host's version is any build string (a dev build's is not a plain+ * number), so a part that is not a number counts as 0. The order is total: two versions that differ only in how they+ * are written are told apart by that, so readdir's order never picks.+ */export function compareVersions(a: string, b: string): number {- const pa = a.split('.').map(Number)- const pb = b.split('.').map(Number)- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {- const d = (pa[i] ?? 0) - (pb[i] ?? 0)+ const va = versionParts(a)+ const vb = versionParts(b)+ for (let i = 0; i < Math.max(va.core.length, vb.core.length); i++) {+ const d = (va.core[i] ?? 0) - (vb.core[i] ?? 0)if (d !== 0) return d}+ if (va.pre !== vb.pre) {+ if (va.pre === null) return 1+ if (vb.pre === null) return -1+ return va.pre < vb.pre ? -1 : 1+ }// `1.0` and `1.0.0` are the same version; order them anyway so readdir's order cannot pick.- return a.length - b.length+ return a.length - b.length || (a < b ? -1 : a > b ? 1 : 0)+}++function versionParts(version: string): { core: number[]; pre: string | null } {+ const plain = version.split('+')[0]+ const dash = plain.indexOf('-')+ const core = (dash < 0 ? plain : plain.slice(0, dash)).split('.').map((part) => Number(part) || 0)+ return { core, pre: dash < 0 ? null : plain.slice(dash + 1) }}export interface PtyHostBinaryOptions {@@ -90,20 +111,31 @@ export function ptyHostBinary(options: PtyHostBinaryOptions = {}): string | nullreturn runnable(beside) ? beside : null}-/** `<home>/run/pty-host-<protocol>.json`, or null when it is missing or not a discovery file. */-export function readDiscovery(home: string, protocol: number): PtyHostDiscovery | null {+/** `<home>/run/<instance's discovery file>`, or null for anything that is not an instance. */+function discoveryPath(home: string, instance: string): string | null {+ const name = discoveryFileName(instance)+ return name ? path.join(home, 'run', name) : null+}++/**+ * The discovery file named [name] in [home]'s run directory, or null when it is missing or not one. A file's own+ * `instance` and `protocol` must be well formed and agree with each other and with the file's name: a copy under+ * another name, or a file that names another instance, is not that instance's.+ */+function readDiscoveryFile(home: string, name: string): PtyHostDiscovery | null {try {- const value = JSON.parse(readFileSync(path.join(home, 'run', `pty-host-${protocol}.json`), 'utf8'))+ const value = JSON.parse(readFileSync(path.join(home, 'run', name), 'utf8'))if (value && typeof value === 'object'- && value.protocol === protocol&& typeof value.instance === 'string'+ && discoveryFileName(value.instance) === name+ && value.protocol === instanceProtocol(value.instance)&& typeof value.endpoint === 'string'&& typeof value.pid === 'number'&& typeof value.version === 'string'&& typeof value.token === 'string') {- const { instance, endpoint, pid, version, token } = value+ const { protocol, instance, endpoint, pid, version, token } = valuereturn { protocol, instance, endpoint, pid, version, token }}} catch {@@ -112,9 +144,161 @@ export function readDiscovery(home: string, protocol: number): PtyHostDiscoveryreturn null}-/** Every supported protocol's discovery file in [home], oldest protocol first (SUPPORTED_PTY_PROTOCOLS). */-export function discoverHosts(home: string): PtyHostDiscovery[] {- return SUPPORTED_PTY_PROTOCOLS.flatMap((protocol) => readDiscovery(home, protocol) ?? [])+/** [instance]'s discovery file (a legacy `p<n>` from `pty-host-<n>.json`), or null when it is missing or not one. */+export function readInstanceDiscovery(home: string, instance: string): PtyHostDiscovery | null {+ const name = discoveryFileName(instance)+ return name ? readDiscoveryFile(home, name) : null+}++const DISCOVERY_FILE = /^pty-host-.+\.json$/++/**+ * Every host discovery file in [home]: legacy (`pty-host-<n>.json`) and versioned, of every protocol, supported or+ * not. Oldest first: by protocol, then by version (`compareVersions`).+ */+export function listDiscoveries(home: string): PtyHostDiscovery[] {+ let names: string[]+ try {+ names = readdirSync(path.join(home, 'run'))+ } catch {+ return []+ }+ return names+ .filter((name) => DISCOVERY_FILE.test(name))+ .flatMap((name) => readDiscoveryFile(home, name) ?? [])+ .sort((a, b) => a.protocol - b.protocol || compareVersions(a.version, b.version) || (a.instance < b.instance ? -1 : 1))+}++/** What `harness-pty version` says of its build. */+export interface PtyHostBinaryVersion { version: string; protocol: number; features: string[] }++/** `binaryVersion`'s, with whether the build is from before features (and so before versioned instances). */+type ReadVersion = PtyHostBinaryVersion & { legacy: boolean }++/** `binaryVersion`'s answers, by path: kept while the file's mtime is the same, so each build is run once. */+const versions = new Map<string, { mtimeMs: number; value: ReadVersion }>()++function readBinaryVersion(binary: string): ReadVersion | null {+ const key = path.resolve(binary)+ let mtimeMs: number+ try {+ mtimeMs = statSync(key).mtimeMs+ } catch {+ return null+ }+ const known = versions.get(key)+ if (known && known.mtimeMs === mtimeMs) return known.value+ let value: ReadVersion | null = null+ try {+ // Synchronous: once per build.+ const parsed = JSON.parse(runVersionCommand(binary).trim()) as Record<string, unknown> | null+ const features = parsed?.features+ if (+ parsed && typeof parsed === 'object'+ && typeof parsed.version === 'string' && parsed.version !== ''+ && Number.isSafeInteger(parsed.protocol) && (parsed.protocol as number) >= 1+ && (features === undefined || (Array.isArray(features) && features.every((name) => typeof name === 'string')))+ ) {+ value = {+ version: parsed.version, protocol: parsed.protocol as number,+ features: features === undefined ? [] : [...features as string[]], legacy: features === undefined,+ }+ }+ } catch {+ // Did not run, timed out, or said something else: no version. Asked again next time.+ }+ if (value) versions.set(key, { mtimeMs, value })+ return value+}++/**+ * How this CLI asks a PTY build what it is: `<binary> version`, an argument array so no shell reads the path, hidden+ * so no console flashes on Windows, within 5 s. One definition for `runVersionCommand` here (synchronous, the daemon's+ * `binaryVersion`) and the payload canary's asynchronous run (lib/windows/ptyPayload.ts `probeVersionLine`), which must+ * never block the updater's event loop.+ */+export const VERSION_COMMAND = {+ args: ['version'] as readonly string[],+ options: { encoding: 'utf8', timeout: VERSION_TIMEOUT_MS, windowsHide: true } as const,+}++/** What `<binary> version` prints, or a throw when it fails to run, exits non-zero or takes longer than 5 s. */+export function runVersionCommand(binary: string): string {+ return execFileSync(binary, [...VERSION_COMMAND.args], { ...VERSION_COMMAND.options, stdio: ['ignore', 'pipe', 'ignore'] })+}++/**+ * What [binary] says it is (`harness-pty version`: `{"version","protocol","features"}`), or null when it cannot be+ * run or says something else. A build from before features lists none: `[]`. Run with a 5 s timeout, hidden, and+ * cached by path and mtime.+ */+export function binaryVersion(binary: string): PtyHostBinaryVersion | null {+ const read = readBinaryVersion(binary)+ return read ? { version: read.version, protocol: read.protocol, features: [...read.features] } : null+}++/**+ * `previous` of `pty-pending.json` (lib/windows/ptyInstall.ts `PTY_PENDING`), or null with no marker. Read here rather+ * than imported: ptyInstall.ts imports this module.+ */+function probationPrevious(ptyRoot: string): string | null {+ try {+ const previous: unknown = JSON.parse(readFileSync(path.join(ptyRoot, 'pty-pending.json'), 'utf8'))?.previous+ return typeof previous === 'string' && previous !== '' ? previous : null+ } catch {+ return null+ }+}++/** The builds `targetHost` said it would not target, by path and version: said once each. */+const toldUnsupported = new Set<string>()++/** The host build new panes go to: the one this daemon would start. */+export interface PtyHostTarget {+ protocol: number+ version: string+ instance: string+ features: readonly string[]+ /** `installed`: the version is the one `current-pty` names (the binary is that folder's); `binary`: it said so. */+ source: 'installed' | 'binary'+}++/**+ * The target host: the build `ptyHostBinary()` resolves. Its version is the one `current-pty` names when the binary+ * is that folder's, else the binary's own (a dev build's `HARNESS_PTY_BIN`, the bundle's). Its protocol and features+ * are always the binary's (`binaryVersion`). Null when there is no binary or it cannot say what it is: the version,+ * or the protocol, is then unknown, and the caller does what it did before targets.+ *+ * The instance is the one the host will publish: named from the binary's own version (instance.rs names it so), and+ * `p<protocol>` for a build from before features, which predates versioned instances too.+ *+ * A build of a protocol outside `SUPPORTED_PTY_PROTOCOLS` is no target either (said once per binary): a paired host left+ * in `current-pty` without the CLI build that needs it (spec §5, the pairing rule), which `ensurePtyHost` would only+ * find incompatible. Unknown, the daemon takes the newest running host it speaks, as it did before targets.+ */+export function targetHost(options: PtyHostBinaryOptions = {}): PtyHostTarget | null {+ const binary = ptyHostBinary(options)+ if (!binary) return null+ const read = readBinaryVersion(binary)+ if (!read) return null+ if (!SUPPORTED_PTY_PROTOCOLS.includes(read.protocol)) {+ const key = `${path.resolve(binary)}\u0000${read.version}`+ if (!toldUnsupported.has(key)) {+ toldUnsupported.add(key)+ console.error(`[terminal] ptyhost: the host ${read.version} speaks protocol ${read.protocol}, which this daemon does not (it speaks ${SUPPORTED_PTY_PROTOCOLS.join(' and ')}): target unknown, the newest running host of protocol ${PTY_PROTOCOL} is used`)+ }+ return null+ }+ const runtimeDir = options.runtimeDir ?? env.ADAPTER_RUNTIME_DIR+ const current = currentPtyVersion(runtimeDir)+ const installed = current !== null && path.resolve(binary) === path.resolve(runtimeDir, 'pty', current, BINARY)+ return {+ protocol: read.protocol,+ version: installed ? current : read.version,+ instance: read.legacy ? `p${read.protocol}` : hostInstanceName(read.protocol, read.version),+ features: [...read.features],+ source: installed ? 'installed' : 'binary',+ }}const DEFAULT_LIVENESS: HostLiveness = { alive: (pid) => pidAlive(pid) }@@ -129,16 +313,24 @@ const DEFAULT_LIVENESS: HostLiveness = { alive: (pid) => pidAlive(pid) }*/export async function discoveredHostDead(home: string,- discovery: Pick<PtyHostDiscovery, 'protocol' | 'pid'>,+ discovery: Pick<PtyHostDiscovery, 'instance' | 'pid'>,liveness: HostLiveness = DEFAULT_LIVENESS,): Promise<boolean> {- return recordedProcessDead(path.join(home, 'run', `pty-host-${discovery.protocol}.json`), discovery.pid, liveness)+ const file = discoveryPath(home, discovery.instance)+ // Not an instance: no file to judge it by, so no proof.+ if (!file) return false+ return recordedProcessDead(file, discovery.pid, liveness)}export type PtyHostUnavailable = { unavailable: string; code: 'PTY_HOST_UNAVAILABLE' }export type EnsurePtyHostResult = { client: PtyHostClient } | PtyHostUnavailable | { incompatible: string }export interface EnsurePtyHostOptions {+ /**+ * The host new panes go to (`targetHost`): only its instance is connected to, and the binary is started for it.+ * Null when the target is unknown: the newest running host of `PTY_PROTOCOL`, whatever its build, as before targets.+ */+ target: PtyHostTarget | null/** The binary to start; `null` means there is none. Defaults to `ptyHostBinary()`. */binary?: string | null/** How long a started host has to publish its discovery file. */@@ -149,16 +341,14 @@ export interface EnsurePtyHostOptions {const unavailable = (reason: string): PtyHostUnavailable => ({ unavailable: reason, code: 'PTY_HOST_UNAVAILABLE' })+type Connected = { client: PtyHostClient } | { incompatible: string } | null+/**- * The host the discovery file names: a client, `{ incompatible }` when it answers but refuses this+ * The host [instance]'s discovery file names: a client, `{ incompatible }` when it answers but refuses this* daemon, or null when nothing answers there (or there is no file).*/-async function connectExisting(- home: string,- protocol = PTY_PROTOCOL,- liveness: HostLiveness = DEFAULT_LIVENESS,-): Promise<{ client: PtyHostClient } | { incompatible: string } | null> {- const discovery = readDiscovery(home, protocol)+async function connectInstance(home: string, instance: string, liveness: HostLiveness): Promise<Connected> {+ const discovery = readInstanceDiscovery(home, instance)if (!discovery) return null// A dead host's endpoint is never dialled: no host, so the caller starts one (a drain backend's judges it gone).if (await discoveredHostDead(home, discovery, liveness)) return null@@ -166,7 +356,7 @@ async function connectExisting(if (result instanceof PtyHostClient) return { client: result }if (result === null) return null// A host that restarted between our read and our hello has a new token: read the file again.- const again = readDiscovery(home, protocol)+ const again = readInstanceDiscovery(home, instance)if (again && (again.token !== discovery.token || again.endpoint !== discovery.endpoint)) {if (await discoveredHostDead(home, again, liveness)) return nullconst retried = await PtyHostClient.connect(again)@@ -177,6 +367,30 @@ async function connectExisting(return { incompatible: result.incompatible }}+/** The hosts a start for [instance] (null: any build of `PTY_PROTOCOL`) waits for or finds, oldest first. */+function hostsFor(home: string, instance: string | null): PtyHostDiscovery[] {+ if (instance !== null) {+ const discovery = readInstanceDiscovery(home, instance)+ return discovery ? [discovery] : []+ }+ return listDiscoveries(home).filter((discovery) => discovery.protocol === PTY_PROTOCOL)+}++/**+ * [instance]'s host; with null, the newest host of `PTY_PROTOCOL` that answers, else the first refusal. A dead host's+ * endpoint is never dialled (`connectInstance`).+ */+async function connectExisting(home: string, instance: string | null, liveness: HostLiveness): Promise<Connected> {+ if (instance !== null) return connectInstance(home, instance, liveness)+ let refused: Connected = null+ for (const discovery of hostsFor(home, null).reverse()) {+ const result = await connectInstance(home, discovery.instance, liveness)+ if (result && 'client' in result) return result+ refused ??= result+ }+ return refused+}+/*** Whether something accepts a connection at `endpoint` within `timeoutMs` (the hello's own limit); it is closed* without a hello. A connection never accepted (a stopped host's full backlog) counts as nothing there, and must not@@ -196,26 +410,35 @@ export function reachable(endpoint: string, timeoutMs = CONNECT_TIMEOUT_MS): Pro})}-/** One start per home at a time in this process; concurrent callers share it. */+/** One start per home and instance at a time in this process; concurrent callers share it. */const starting = new Map<string, Promise<PtyHostUnavailable | null>>()-function startHost(home: string, binary: string | null, waitMs: number, liveness: HostLiveness): Promise<PtyHostUnavailable | null> {- const key = path.resolve(home)+function startHost(home: string, instance: string | null, binary: string | null, waitMs: number, liveness: HostLiveness): Promise<PtyHostUnavailable | null> {+ const key = `${path.resolve(home)}\u0000${instance ?? ''}`let start = starting.get(key)if (!start) {- start = spawnAndWait(home, binary, waitMs, liveness).finally(() => starting.delete(key))+ start = spawnAndWait(home, instance, binary, waitMs, liveness).finally(() => starting.delete(key))starting.set(key, start)}return start}-/** Start `binary serve --home <home>` and wait for a discovery file naming another pid. */-async function spawnAndWait(home: string, binary: string | null, waitMs: number, liveness: HostLiveness): Promise<PtyHostUnavailable | null> {- const before = readDiscovery(home, PTY_PROTOCOL)+/**+ * Start `binary serve --home <home>` and wait for a discovery file of [instance] (null: of any build of+ * `PTY_PROTOCOL`) that was not there before, or names another pid.+ */+async function spawnAndWait(home: string, instance: string | null, binary: string | null, waitMs: number, liveness: HostLiveness): Promise<PtyHostUnavailable | null> {+ const seen = (discovery: PtyHostDiscovery) => `${discovery.instance}\u0000${discovery.pid}`+ const before = hostsFor(home, instance)+ const known = new Set(before.map(seen))// A caller that found no host may arrive just after another caller's start finished. Not a dead host's endpoint:// something else may have taken its name (`discoveredHostDead`).const live = (discovery: PtyHostDiscovery) => discoveredHostDead(home, discovery, liveness).then((dead) => !dead)- if (before && await live(before) && await reachable(before.endpoint)) return null+ const answering = async (discoveries: PtyHostDiscovery[]) => {+ for (const discovery of discoveries) if (await live(discovery) && await reachable(discovery.endpoint)) return true+ return false+ }+ if (await answering(before)) return nullif (!binary) return unavailable('harness-pty is not installed')let failed: string | null = nulllet exitedCleanly = false@@ -244,27 +467,29 @@ async function spawnAndWait(home: string, binary: string | null, waitMs: number,while (Date.now() < deadline) {await new Promise(resolve => setTimeout(resolve, POLL_MS))if (failed) return unavailable(failed)- const now = readDiscovery(home, PTY_PROTOCOL)- if (now && now.pid !== before?.pid) return null- if (exitedCleanly && now && await live(now) && await reachable(now.endpoint)) return null+ const now = hostsFor(home, instance)+ if (now.some((discovery) => !known.has(seen(discovery)))) return null+ if (exitedCleanly && await answering(now)) return null}return unavailable(`harness-pty did not publish its discovery file within ${waitMs} ms`)}/**- * A client of the host serving `home`, starting the host first when nothing answers at the- * endpoint its discovery file names. `incompatible` is a host that answers and refuses this- * daemon; starting another would not replace it.+ * A client of the host serving `home` that new panes go to, starting the host first when nothing answers at the+ * endpoint its discovery file names. With a target, that is the target's instance alone: a host of another build is+ * never connected to, though it runs. Without one (null), the newest running host of `PTY_PROTOCOL`. `incompatible`+ * is a host that answers and refuses this daemon; starting another would not replace it.*/-export async function ensurePtyHost(home: string, options: EnsurePtyHostOptions = {}): Promise<EnsurePtyHostResult> {+export async function ensurePtyHost(home: string, options: EnsurePtyHostOptions): Promise<EnsurePtyHostResult> {const liveness = options.liveness ?? DEFAULT_LIVENESS- const existing = await connectExisting(home, PTY_PROTOCOL, liveness)+ const instance = options.target?.instance ?? null+ const existing = await connectExisting(home, instance, liveness)if (existing) return existingconst binary = options.binary !== undefined ? options.binary : ptyHostBinary()- const failed = await startHost(home, binary, options.waitMs ?? START_WAIT_MS, liveness)+ const failed = await startHost(home, instance, binary, options.waitMs ?? START_WAIT_MS, liveness)if (failed) return failed// The host this start found or made published a discovery file, but nothing answers where it says.- return (await connectExisting(home, PTY_PROTOCOL, liveness)) ?? unavailable('no harness-pty answers at the endpoint its discovery file names')+ return (await connectExisting(home, instance, liveness)) ?? unavailable('no harness-pty answers at the endpoint its discovery file names')}/**@@ -276,31 +501,41 @@ export type PtyHostUnreached = PtyHostUnavailable & { pid: number | null; missinexport type ReachPtyHostResult = { client: PtyHostClient } | { incompatible: string } | PtyHostUnreached/**- * A client of the [protocol] host serving `home`, never starting one: how a drain backend reaches a host of the- * protocol before this daemon's (ptyHost/drain.ts). Whether a host that does not answer has gone is not decided- * here: a file that could not be read, or a pid that runs, is no proof either way.+ * A client of [instance]'s host serving `home`, never starting one: how a drain backend reaches a host that new panes+ * no longer go to (ptyHost/drain.ts). Whether a host that does not answer has gone is not decided here: a file that+ * could not be read, or a pid that runs, is no proof either way.*/-export async function reachPtyHost(home: string, protocol: number, liveness: HostLiveness = DEFAULT_LIVENESS): Promise<ReachPtyHostResult> {- const file = path.join(home, 'run', `pty-host-${protocol}.json`)- const discovery = readDiscovery(home, protocol)+export async function reachPtyHost(home: string, instance: string, liveness: HostLiveness = DEFAULT_LIVENESS): Promise<ReachPtyHostResult> {+ const name = discoveryFileName(instance)+ // Not an instance: there is no file it could have.+ if (!name) return { ...unavailable(`${JSON.stringify(instance)} is not a pty host instance`), pid: null, missing: true }+ const discovery = readInstanceDiscovery(home, instance)if (!discovery) {- const missing = !existsSync(file)- return { ...unavailable(missing ? `there is no pty-host-${protocol}.json` : `pty-host-${protocol}.json cannot be read`), pid: null, missing }+ const missing = !existsSync(path.join(home, 'run', name))+ return { ...unavailable(missing ? `there is no ${name}` : `${name} cannot be read`), pid: null, missing }}- const existing = await connectExisting(home, protocol, liveness)+ const existing = await connectInstance(home, instance, liveness)if (existing) return existing- return { ...unavailable(`nothing answers for the protocol ${protocol} host (pid ${discovery.pid})`), pid: discovery.pid, missing: false }+ return { ...unavailable(`nothing answers for the ${instance} host (pid ${discovery.pid})`), pid: discovery.pid, missing: false }}/**- * Take down what a host of [protocol] that has exited left published: its discovery file, and its socket file on+ * Take down what [instance]'s host that has exited left published: its discovery file, and its socket file on* Unix. Only while the file still names [pid] and that process is gone: a host that took its place keeps its own.* A host that shut down (protocol 2 on) has removed them itself; a protocol 1 host ended by its pid leaves them.*/-export function forgetExitedHost(home: string, protocol: number, pid: number): void {- const discovery = readDiscovery(home, protocol)- if (!discovery || discovery.pid !== pid || pidAlive(pid)) return- rmSync(path.join(home, 'run', `pty-host-${protocol}.json`), { force: true })+export function forgetExitedHost(home: string, instance: string, pid: number): void {+ const discovery = readInstanceDiscovery(home, instance)+ const file = discoveryPath(home, instance)+ if (!discovery || !file || discovery.pid !== pid || pidAlive(pid)) return+ rmSync(file, { force: true })+ // The host's lock and pane-id counter sit beside its discovery file under the same name. The host cannot delete the+ // lock itself: removing it before the lock is released lets a host starting meanwhile lock an unlinked file while+ // another makes a new one. Here the host is proven gone, so no one holds either; one a scanner still holds stays+ // for the next time.+ for (const ext of ['lock', 'panes']) {+ try { rmSync(file.replace(/\.json$/, `.${ext}`), { force: true }) } catch { /* held for now */ }+ }if (process.platform !== 'win32' && path.isAbsolute(discovery.endpoint)&& path.dirname(discovery.endpoint) === path.join(home, 'run')) rmSync(discovery.endpoint, { force: true })}@@ -308,8 +543,9 @@ export function forgetExitedHost(home: string, protocol: number, pid: number): v/*** Delete the `<runtime>/pty/<version>/` directories no host runs from any more, after a drained host has gone: every* version older than the one `current-pty` names (the installed CLI's) whose version no running host of [home] has- * (its discovery file's `version`, its pid alive). The current one, newer ones (another install's, perhaps not- * finished), and anything that is not a version directory stay. Nothing goes without a `current-pty`: with no+ * (any instance's discovery file, legacy or versioned: its `version`, its pid alive). The current one, newer ones (another install's, perhaps not+ * finished), the one a version on probation would roll back to (`pty-pending.json`'s `previous`), and anything that+ * is not a version directory stay. Nothing goes without a `current-pty`: with no* installed CLI's word, no version is known to be old. A directory that cannot be removed (a running .exe on* Windows, of some other home's host) stays for the next time. Returns the versions removed.*/@@ -317,7 +553,10 @@ export function removeUnusedPtyVersions(home: string, runtimeDir: string = env.Aconst current = currentPtyVersion(runtimeDir)if (!current) return []const root = path.join(runtimeDir, 'pty')- const running = new Set(discoverHosts(home).filter((host) => pidAlive(host.pid)).map((host) => host.version))+ const running = new Set(listDiscoveries(home).filter((host) => pidAlive(host.pid)).map((host) => host.version))+ // While a version is on probation, the one it replaced is what a rollback puts back, host or not.+ const rollback = probationPrevious(root)+ if (rollback) running.add(rollback)let names: string[]try {names = readdirSync(root)diff --git a/cli/src/lib/ptyHost/protocol.spec.ts b/cli/src/lib/ptyHost/protocol.spec.tsindex 62d6e00aa..95366fdfd 100644--- a/cli/src/lib/ptyHost/protocol.spec.ts+++ b/cli/src/lib/ptyHost/protocol.spec.ts@@ -8,16 +8,19 @@ import {helloProof,MAX_FRAME,PTY_PROTOCOL,+ SUPPORTED_PTY_PROTOCOLS,type HelloLine,type PtyOp,type PtyOpOf,} from './protocol.js'-// Installed Windows hosts are replaced only by install.ps1, never by the CLI's self-update, so a CLI that raised the-// protocol would reach Windows machines whose host cannot speak it, and no new pane would open. Bump it only once the-// host is updated with the CLI (the PTY host rollover, not yet built).-it('keeps the protocol that installed Windows hosts speak', () => {- expect(PTY_PROTOCOL).toBe(2)+// A bump no longer needs a pin here: the updater holds a CLI whose `PTY_PROTOCOL` is above the installed host's back+// until a payload of that protocol goes in first, in the same handover (lib/selfUpdate.ts `installedPtyProtocol`; the+// delivery rule is tested in selfUpdate.spec.ts, "a build needing a newer pty protocol waits, then stages once the host+// has it", and the pair in windows/ptyUpdate.spec.ts). What still holds is that the daemon reaches the hosts of its own+// protocol.+it('a CLI needing a protocol above the installed host\'s waits (the delivery rule replaces the pin)', () => {+ expect(SUPPORTED_PTY_PROTOCOLS).toContain(PTY_PROTOCOL)})describe('ptyHost protocol framing', () => {@@ -144,7 +147,7 @@ describe('ptyHost protocol messages', () => {type FieldType = 'string' | 'number' | 'boolean' | 'string[]' | 'env' | 'afterExit'type OpFields = { [K in PtyOp['op']]: { [F in keyof Omit<PtyOpOf<K>, 'op'>]-?: FieldType } }const OP_FIELDS: OpFields = {- create: { command: 'string[]', cwd: 'string', env: 'env', cols: 'number', rows: 'number', owner: 'string', label: 'string', hold: 'boolean', afterExit: 'afterExit', clearInherited: 'string[]' },+ create: { command: 'string[]', cwd: 'string', env: 'env', cols: 'number', rows: 'number', owner: 'string', label: 'string', hold: 'boolean', afterExit: 'afterExit', clearInherited: 'string[]', seed: 'string' },kill: { pane: 'string', graceMs: 'number' },inventory: {},titles: {},diff --git a/cli/src/lib/ptyHost/protocol.ts b/cli/src/lib/ptyHost/protocol.tsindex 2884c4525..3263ad00c 100644--- a/cli/src/lib/ptyHost/protocol.ts+++ b/cli/src/lib/ptyHost/protocol.ts@@ -2,8 +2,8 @@import { createHash } from 'node:crypto'/**- * The protocol this daemon's host speaks (protocol.rs `PROTOCOL`), and the instance its panes are made on- * (`p<protocol>`).+ * The protocol this daemon's host speaks (protocol.rs `PROTOCOL`). A host's instance is `p<protocol>-<version>`, so+ * hosts of one protocol and different builds run side by side (instance.ts); one from before that is `p<protocol>`.** - 2: the `shutdown` op, for draining a host of the protocol before.* - 1: the first.@@ -18,6 +18,11 @@ export const PTY_PROTOCOL = 2export const SUPPORTED_PTY_PROTOCOLS: readonly number[] = [PTY_PROTOCOL - 1, PTY_PROTOCOL].filter((p) => p >= 1)/** The first protocol with the `shutdown` op. */export const SHUTDOWN_PROTOCOL = 2+/**+ * The feature a host lists (its hello reply's and `harness-pty version`'s `features`) when its `create` takes a+ * `seed`: added within protocol 2, so a host's protocol does not say it. A host that lists no features has none.+ */+export const SEED_FEATURE = 'seed'export const MAX_FRAME = 8 * 1024 * 1024export enum FrameKind {@@ -133,7 +138,7 @@ export interface HelloLine {hello: { auth: string; nonce: string; protocol: number; role: HelloRole; clientId: string }}export type HelloReply =- | { hello: { ok: true; instance: string; version: string; pid: number; proof: string } }+ | { hello: { ok: true; instance: string; version: string; pid: number; features?: string[]; proof: string } }| { hello: { ok: false; code: string; reason: string } }const tokenDigest = (token: string, separator: string, nonce: string) =>@@ -190,7 +195,7 @@ export interface PtyAfterExit {}export type PtyOp =- | { op: 'create'; command: string[]; cwd?: string; env?: Record<string, string>; cols: number; rows: number; owner: string; label?: string; hold: boolean; afterExit?: PtyAfterExit; clearInherited?: string[] }+ | { op: 'create'; command: string[]; cwd?: string; env?: Record<string, string>; cols: number; rows: number; owner: string; label?: string; hold: boolean; afterExit?: PtyAfterExit; clearInherited?: string[]; /** Scrollback the pane starts with: lines separated by \n or \r\n. Send only to a host listing the `seed` feature. */ seed?: string }| { op: 'kill'; pane: string; graceMs?: number }| { op: 'inventory' }| { op: 'titles' }diff --git a/cli/src/lib/ptyHost/stream.spec.ts b/cli/src/lib/ptyHost/stream.spec.tsindex 804412673..2eda511a8 100644--- a/cli/src/lib/ptyHost/stream.spec.ts+++ b/cli/src/lib/ptyHost/stream.spec.ts@@ -8,7 +8,7 @@ import { rewrapTmuxHistory } from '../historyRewrap.js'import { removeTree, SHELL, WAIT_MS } from '../terminalBackend.contract.js'import { KEYFRAME_MAX_BYTES, type PtyRuntimeRef, type TerminalStreamSnapshot } from '../terminalTypes.js'import { CONVERSATION_HISTORY_LINES, SNAPSHOT_HISTORY_LINES, tmuxKeyframe, type PaneMeta } from '../tmuxStream.js'-import { readDiscovery } from './launch.js'+import { listDiscoveries } from './launch.js'import { encodeFrame, FrameKind, FrameReader, PTY_PROTOCOL, type PtyPaneMeta, type StreamSnapshotRequest } from './protocol.js'import { PtyHostStream, type PtyHostStreamOptions } from './stream.js'@@ -534,7 +534,7 @@ describe.skipIf(!process.env.HARNESS_PTY_BIN)('PtyHostStream with the real harnelet home: string | null = nullafterEach(async () => {if (!home) return- const pid = readDiscovery(home, PTY_PROTOCOL)?.pid+ const pid = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)?.pidif (pid) try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }const dir = homehome = nulldiff --git a/cli/src/lib/ptyHostBackend.contract.spec.ts b/cli/src/lib/ptyHostBackend.contract.spec.tsindex fa5ff5b8b..82c1d0847 100644--- a/cli/src/lib/ptyHostBackend.contract.spec.ts+++ b/cli/src/lib/ptyHostBackend.contract.spec.ts@@ -6,7 +6,8 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it } from 'vitest'import { PtyHostBackend } from './ptyHostBackend.js'-import { readDiscovery } from './ptyHost/launch.js'+import { PTY_HOST_INSTANCE, PTY_HOST_INSTANCE_SOURCE } from './ptyHost/instance.js'+import { listDiscoveries } from './ptyHost/launch.js'import { PTY_PROTOCOL } from './ptyHost/protocol.js'import { removeTree, runTerminalBackendContract, SHELL } from './terminalBackend.contract.js'import type { TerminalInventoryResult } from './terminalTypes.js'@@ -19,7 +20,7 @@ const freshHome = (prefix: string) => mkdtempSync(join(tmpdir(), prefix))/** Stop the host serving [home] (its panes go with it) and remove the home. */async function stopHost(home: string): Promise<void> {- const pid = readDiscovery(home, PTY_PROTOCOL)?.pid+ const pid = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)?.pidif (pid) {try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }}@@ -66,7 +67,7 @@ async function readyBackend(home: string): Promise<PtyHostBackend> {backend.onHostReplaced = () => replaced.push(Date.now())const created = await backend.create({ command: SHELL })if (created.state !== 'succeeded') throw new Error(`create failed: ${JSON.stringify(created)}`)- const before = readDiscovery(home, PTY_PROTOCOL)!+ const before = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)!process.kill(before.pid, 'SIGKILL')await new Promise((resolve) => setTimeout(resolve, 300))// Disconnected: unavailable, never an empty listing (which would read as every pane gone).@@ -74,12 +75,16 @@ async function readyBackend(home: string): Promise<PtyHostBackend> {// The reconnect, 1 s after the loss, starts a new host: it has no panes.const inventory = await until<TerminalInventoryResult>(() => backend.inventory(), (inv) => inv.state === 'available')expect(inventory).toEqual({ state: 'available', roots: [] })- const after = readDiscovery(home, PTY_PROTOCOL)!+ const after = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)!expect(after.pid).not.toBe(before.pid)// A Windows host draws a new pipe name each start; the reconnect followed the discovery file to it.if (process.platform === 'win32') {expect(after.endpoint).not.toBe(before.endpoint)- expect(after.endpoint).toMatch(/^\\\\\.\\pipe\\harness-pty-[0-9a-f]{16}-[0-9a-f]{16}-p\d+$/)+ // `harness-pty-<16 hex of the user and home>-<16 random hex>-<instance>` (pty/src/transport/windows.rs): the+ // instance is the host's own, `p<protocol>-<version>`, dashes and all.+ expect(after.instance).toMatch(PTY_HOST_INSTANCE)+ expect(after.endpoint).toMatch(new RegExp(String.raw`^\\\\\.\\pipe\\harness-pty-[0-9a-f]{16}-[0-9a-f]{16}-${PTY_HOST_INSTANCE_SOURCE}$`))+ expect(after.endpoint.endsWith(`-${after.instance}`)).toBe(true)}expect(replaced).toHaveLength(1)expect(await backend.paneState(created.runtime)).toBe('gone')diff --git a/cli/src/lib/ptyHostBackend.restart.spec.ts b/cli/src/lib/ptyHostBackend.restart.spec.tsindex 3c301b5bf..5639706e6 100644--- a/cli/src/lib/ptyHostBackend.restart.spec.ts+++ b/cli/src/lib/ptyHostBackend.restart.spec.ts@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it, vi } from 'vitest'import { PtyHostBackend } from './ptyHostBackend.js'-import { readDiscovery } from './ptyHost/launch.js'+import { listDiscoveries } from './ptyHost/launch.js'import { PTY_PROTOCOL } from './ptyHost/protocol.js'import { canRestart } from './terminalBackend.js'import { removeTree, SHELL } from './terminalBackend.contract.js'@@ -69,7 +69,7 @@ async function withHost(run: (backend: PtyHostBackend) => Promise<void>): Promisthrow error} finally {backend.dispose()- const pid = readDiscovery(home, PTY_PROTOCOL)?.pid+ const pid = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)?.pidif (pid) {try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }}diff --git a/cli/src/lib/ptyHostBackend.spec.ts b/cli/src/lib/ptyHostBackend.spec.tsindex 53c4f3ee6..1ab384f98 100644--- a/cli/src/lib/ptyHostBackend.spec.ts+++ b/cli/src/lib/ptyHostBackend.spec.ts@@ -1,7 +1,12 @@+import { once } from 'node:events'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import net from 'node:net'+import { tmpdir } from 'node:os'+import path from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { PtyEvent, PtyOp } from './ptyHost/protocol.js'import type { PtyHostClient } from './ptyHost/client.js'-import type { EnsurePtyHostResult } from './ptyHost/launch.js'+import type { EnsurePtyHostResult, PtyHostTarget } from './ptyHost/launch.js'import type { PtyRuntimeRef } from './terminalTypes.js'// validate's branches, not the process table: the same narrow mock tmuxBackendValidate.spec.ts uses.@@ -25,6 +30,8 @@ const { PtyHostBackend } = await import('./ptyHostBackend.js')const { defaultWindowsShell } = await import('./windows/shell.js')const { processRows, setProcessTableSource } = await import('./processTable.js')const { setAgentSignaller, signalAgentProcess } = await import('./processSignals.js')+const { helloProof, PTY_PROTOCOL } = await import('./ptyHost/protocol.js')+const { discoveryFileName } = await import('./ptyHost/instance.js')type Reply = unknown | ((op: PtyOp) => unknown)@@ -33,6 +40,7 @@ interface BackendOptions {owner?: stringstream?: () => Promise<unknown>platform?: NodeJS.Platform+ features?: string[]endTree?: (pid: number) => Promise<'sent' | 'gone' | 'failed'>}@@ -41,6 +49,7 @@ function backendWith(replies: Record<string, Reply>, options: BackendOptions = {const listeners = new Set<(event: PtyEvent) => void>()const client = {instance: 'p1',+ features: options.features ?? [],call: async (op: PtyOp) => {calls.push(op)const reply = replies[op.op]@@ -90,6 +99,7 @@ describe('PtyHostBackend prepare', () => {expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'unavailable', code: 'PTY_HOST_UNAVAILABLE', reason: 'harness-pty is not installed' })expect(await backend.inventory()).toEqual({ state: 'unavailable', reason: 'pty host is unavailable' })+ expect(backend.attached).toBe(false)expect(await backend.create({ command: ['/bin/sh'] })).toMatchObject({ state: 'failed', dispatch: 'not_started' })})@@ -102,6 +112,26 @@ describe('PtyHostBackend prepare', () => {})describe('PtyHostBackend create', () => {+ it('create passes the seed to a host with the seed feature', async () => {+ const { backend, calls } = await ready({ create: { state: 'ok', value: { pane: '%4' } } }, { features: ['seed'] })+ expect(backend.canSeed).toBe(true)+ // Attached to its host, until the connection is let go.+ expect(backend.attached).toBe(true)+ await backend.create({ command: ['claude'], seed: 'a\r\nb' })+ expect(calls[0]).toMatchObject({ op: 'create', seed: 'a\r\nb' })+ backend.dispose()+ expect(backend.attached).toBe(false)+ })++ it('create refuses a seed for a host without it', async () => {+ const { backend, calls } = await ready({ create: { state: 'ok', value: { pane: '%4' } } })+ expect(backend.canSeed).toBe(false)+ expect(await backend.create({ command: ['claude'], seed: 'a' })).toMatchObject({ state: 'failed', dispatch: 'not_started', reason: 'this host cannot seed a pane' })+ expect(calls.some((call) => call.op === 'create')).toBe(false)+ // No seed: a pre-G host still creates.+ expect(await backend.create({ command: ['claude'] })).toMatchObject({ state: 'succeeded' })+ })+it('asks for a held 200x50 pane owned by this daemon', async () => {const { backend, calls } = await ready({ create: { state: 'ok', value: { pane: '%4' } } })const result = await backend.create({ command: ['claude'], cwd: '/w', label: 'harness-claude-1', env: { K: 'v' } })@@ -256,6 +286,20 @@ describe('PtyHostBackend inventory and titles', () => {})})+ it('lists the label a pane was created with, which tells a move pane (hostMove/moveAgent.ts)', async () => {+ const row = (pane: string, label: string | null) => ({ pane, rootPid: 11, cwd: '/w', title: '', dead: false, owner: 'me', label })+ const { backend } = await ready({+ inventory: { state: 'ok', value: { panes: [row('%1', 'HARNESS_MOVE_OF=a1'), row('%2', null)] } },+ })+ expect(await backend.inventory()).toEqual({+ state: 'available',+ roots: [+ { runtime: { backend: 'ptyhost', instance: 'p1', paneId: '%1' }, rootPid: 11, cwd: '/w', label: 'HARNESS_MOVE_OF=a1' },+ { runtime: { backend: 'ptyhost', instance: 'p1', paneId: '%2' }, rootPid: 11, cwd: '/w' },+ ],+ })+ })+it('keys titles by route', async () => {const { backend } = await ready({ titles: { state: 'ok', value: { titles: { '%1': 'one' } } } })const titles = await backend.titles()@@ -350,6 +394,18 @@ describe('PtyHostBackend input', () => {expect(calls).toEqual([{ op: 'paste', pane: '%1', text: 'héllo', bracketed: false }])})+ it('writeInput sends the bytes as they are, through the host\'s raw write', async () => {+ const { backend, calls } = await ready()+ expect(await backend.writeInput(PANE, Uint8Array.of(0x1b, 0x5b, 0x41, 0x0d))).toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(calls).toEqual([{ op: 'write', pane: '%1', data: Buffer.from([0x1b, 0x5b, 0x41, 0x0d]).toString('base64') }])+ })++ it('pasteInput pastes as a stream\'s paste frame does', async () => {+ const { backend, calls } = await ready()+ expect(await backend.pasteInput(PANE, 'a\nb')).toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(calls).toEqual([{ op: 'paste', pane: '%1', text: 'a\nb', bracketed: true }])+ })+it('sendKey sends the tmux name of the key', async () => {const { backend, calls } = await ready()await backend.sendKey(PANE, 'backtab')@@ -964,3 +1020,242 @@ describe('PtyHostBackend host connection', () => {expect(connected.events.size + connected.closes.size).toBe(0)})})++describe('PtyHostBackend hosts by instance', () => {+ const P = PTY_PROTOCOL+ const homes: string[] = []+ const servers: Array<{ stop(): Promise<void> }> = []+ afterEach(async () => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+ for (const server of servers.splice(0)) await server.stop()+ for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })+ })++ const tmpHome = () => {+ const home = mkdtempSync(path.join(tmpdir(), 'pty-backend-'))+ homes.push(home)+ return home+ }++ /**+ * A stand-in host of [instance] in [home], in this process: its discovery file, a hello that proves its token, and+ * `ok` to every op (a `create` makes `%9`). `stop` ends it and every connection to it; `start` serves again. [pid]+ * is the one its file and hello name (this process's by default).+ */+ async function hostIn(home: string, instance: string, version: string, pid = process.pid) {+ const endpoint = process.platform === 'win32' ? `\\\\.\\pipe\\pty-backend-${path.basename(home)}-${instance}` : path.join(home, `${instance}.sock`)+ const token = `tok-${instance}`+ const hellos: string[] = []+ const ops: string[] = []+ const sockets = new Set<net.Socket>()+ let server: net.Server | null = null+ const serve = (socket: net.Socket) => {+ sockets.add(socket)+ socket.on('close', () => sockets.delete(socket))+ socket.on('error', () => {})+ let pending = ''+ let said = false+ socket.on('data', (chunk) => {+ pending += chunk+ let at+ while ((at = pending.indexOf('\n')) >= 0) {+ const value = JSON.parse(pending.slice(0, at))+ pending = pending.slice(at + 1)+ if (said) {+ ops.push(value.op)+ socket.write(`${JSON.stringify(value.op === 'inventory' ? { id: value.id, ok: true, panes: [] } : value.op === 'create' ? { id: value.id, ok: true, pane: '%9' } : { id: value.id, ok: true })}\n`)+ continue+ }+ said = true+ hellos.push(instance)+ socket.write(`${JSON.stringify({ hello: { ok: true, instance, version, pid, proof: helloProof(token, value.hello.nonce) } })}\n`)+ }+ })+ }+ const host = {+ hellos,+ ops,+ async start() {+ server = net.createServer(serve)+ server.listen(endpoint)+ await once(server, 'listening')+ },+ async stop() {+ const closing = server+ server = null+ if (!closing) return+ for (const socket of sockets) socket.destroy()+ await new Promise((resolve) => closing.close(resolve))+ },+ }+ await host.start()+ servers.push(host)+ mkdirSync(path.join(home, 'run'), { recursive: true })+ writeFileSync(path.join(home, 'run', discoveryFileName(instance)!), JSON.stringify({ protocol: P, instance, endpoint, pid, version, token }))+ return host+ }++ const target = (version: string): PtyHostTarget => ({ protocol: P, version, instance: `p${P}-${version}`, features: ['seed'], source: 'installed' })+ const quiet = () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ }++ it('the create backend never makes a pane on a non-target host', async () => {+ quiet()+ // No host binary to start: a missing target's host is not made, and nothing else stands in for it.+ vi.stubEnv('HARNESS_PTY_BIN', path.join(tmpdir(), 'no-such-harness-pty'))+ const home = tmpHome()+ const other = await hostIn(home, `p${P}-0.1.0`, '0.1.0')+ const lonely = new PtyHostBackend({ home, target: target('0.2.0'), owner: () => 'me', platform: 'linux' })+ expect(await lonely.prepare({ ownedPanes: new Map() })).toMatchObject({ state: 'unavailable' })+ expect(await lonely.create({ command: ['sh'] })).toMatchObject({ state: 'failed', dispatch: 'not_started' })+ lonely.dispose()+ // With the target's host running too, panes go there alone.+ const own = await hostIn(home, `p${P}-0.2.0`, '0.2.0')+ const backend = new PtyHostBackend({ home, target: target('0.2.0'), owner: () => 'me', platform: 'linux' })+ expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ expect(await backend.create({ command: ['sh'] })).toMatchObject({ state: 'succeeded', runtime: { instance: `p${P}-0.2.0`, paneId: '%9' } })+ backend.dispose()+ expect([other.hellos, other.ops, own.ops.filter((op) => op === 'create')]).toEqual([[], [], ['create']])+ expect(backend.mayShutDown).toBe(false)+ })++ it('a drain backend refuses create', async () => {+ const calls: string[] = []+ const client = {+ instance: `p${P}-0.1.0`, pid: 10, protocol: P,+ call: async (op: PtyOp) => { calls.push(op.op); return op.op === 'inventory' ? { state: 'ok', value: { panes: [] } } : { state: 'ok', value: {} } },+ onEvent: () => () => {}, onClose: () => () => {}, close() {},+ }+ const backend = new PtyHostBackend({+ home: '/tmp/h', instance: `p${P}-0.1.0`, target: target('0.2.0'), owner: () => 'me', platform: 'linux',+ launch: async () => ({ client: client as unknown as PtyHostClient }), hostProcess: { alive: () => true, rows: async () => null },+ })+ // Its instance is known before its host is reached: rows name it.+ expect([backend.instanceId, backend.draining]).toEqual([`ptyhost:p${P}-0.1.0`, true])+ vi.spyOn(console, 'log').mockImplementation(() => {})+ expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ expect(await backend.create({ command: ['sh'] })).toMatchObject({ state: 'failed', dispatch: 'not_started', reason: expect.stringContaining('draining') })+ expect(calls).not.toContain('create')+ backend.dispose()+ })++ it('with no target, a reconnect stays on the instance it was attached to', async () => {+ quiet()+ vi.stubEnv('HARNESS_PTY_BIN', path.join(tmpdir(), 'no-such-harness-pty'))+ const home = tmpHome()+ const older = await hostIn(home, `p${P}-0.1.0`, '0.1.0')+ const newer = await hostIn(home, `p${P}-0.2.0`, '0.2.0')+ const backend = new PtyHostBackend({ home, target: null, owner: () => 'me', platform: 'linux' })+ const replaced = vi.fn()+ backend.onHostReplaced = replaced+ expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ expect(backend.instanceId).toBe(`ptyhost:p${P}-0.2.0`)+ // The newest host stops answering for a while: the older one is never taken in its place.+ await newer.stop()+ await vi.waitFor(async () => expect(await backend.inventory()).toMatchObject({ state: 'unavailable' }))+ await new Promise((resolve) => setTimeout(resolve, 1_500))+ expect(older.hellos).toEqual([])+ await newer.start()+ await vi.waitFor(async () => expect(await backend.inventory()).toEqual({ state: 'available', roots: [] }), { timeout: 5_000, interval: 100 })+ expect(backend.instanceId).toBe(`ptyhost:p${P}-0.2.0`)+ expect(older.hellos).toEqual([])+ expect(replaced).not.toHaveBeenCalled()+ backend.dispose()+ }, 15_000)++ /** A pid no host has: the stand-in host given it is dead once the test says so (`hostProcess`). */+ const GONE_PID = 2_000_000_001++ it('with no target, a host proven dead gives way to the newest one that answers', async () => {+ quiet()+ vi.stubEnv('HARNESS_PTY_BIN', path.join(tmpdir(), 'no-such-harness-pty'))+ const home = tmpHome()+ const older = await hostIn(home, `p${P}-0.1.0`, '0.1.0')+ const newer = await hostIn(home, `p${P}-0.2.0`, '0.2.0', GONE_PID)+ let dead = false+ const hostProcess = { alive: (pid: number) => pid !== GONE_PID || !dead, rows: async () => null }+ const backend = new PtyHostBackend({ home, target: null, owner: () => 'me', platform: 'linux', hostProcess })+ const replaced = vi.fn()+ backend.onHostReplaced = replaced+ expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ expect(backend.instanceId).toBe(`ptyhost:p${P}-0.2.0`)+ // The newest host exits for good: its panes are gone, and new ones go to the host that answers.+ dead = true+ await newer.stop()+ await vi.waitFor(() => expect(replaced).toHaveBeenCalledTimes(1), { timeout: 5_000, interval: 50 })+ expect(backend.instanceId).toBe(`ptyhost:p${P}-0.1.0`)+ expect(await backend.create({ command: ['sh'] })).toMatchObject({ state: 'succeeded', runtime: { instance: `p${P}-0.1.0` } })+ expect(older.ops).toContain('create')+ backend.dispose()+ }, 15_000)++ // A stand-in binary is a script run by its shebang: not on Windows.+ it.runIf(process.platform !== 'win32')('with a target, a dead host is started again from the binary, and only the target\'s instance is waited on', async () => {+ quiet()+ const home = tmpHome()+ const instance = `p${P}-0.2.0`+ const binary = path.join(home, 'harness-pty-stub')+ // `serve --home <home>`: says how it was started, then serves as [instance] (hello, `ok` to every op) and+ // publishes its discovery file. It ends itself after 30 s if nothing kills it.+ writeFileSync(binary, `#!${process.execPath}+const { createHash } = require('node:crypto')+const fs = require('node:fs')+const net = require('node:net')+const path = require('node:path')+const home = process.argv[process.argv.indexOf('--home') + 1]+fs.appendFileSync(path.join(home, 'started'), process.argv.slice(2).join(' ') + '\\n')+const endpoint = path.join(home, 'stub.sock')+const token = 'stub-token'+const proof = (nonce) => createHash('sha256').update(token).update('\\0').update(nonce).digest('hex')+const server = net.createServer((socket) => {+ socket.on('error', () => {})+ let pending = ''+ let said = false+ socket.on('data', (chunk) => {+ pending += chunk+ let at+ while ((at = pending.indexOf('\\n')) >= 0) {+ const value = JSON.parse(pending.slice(0, at))+ pending = pending.slice(at + 1)+ if (said) {+ socket.write(JSON.stringify(value.op === 'inventory' ? { id: value.id, ok: true, panes: [] } : value.op === 'create' ? { id: value.id, ok: true, pane: '%5' } : { id: value.id, ok: true }) + '\\n')+ continue+ }+ said = true+ socket.write(JSON.stringify({ hello: { ok: true, instance: ${JSON.stringify(instance)}, version: '0.2.0', pid: process.pid, proof: proof(value.hello.nonce) } }) + '\\n')+ }+ })+})+server.listen(endpoint, () => {+ fs.writeFileSync(path.join(home, 'run', ${JSON.stringify(discoveryFileName(instance))}), JSON.stringify({ protocol: ${P}, instance: ${JSON.stringify(instance)}, endpoint, pid: process.pid, version: '0.2.0', token }))+})+setTimeout(() => process.exit(0), 30000)+`, { mode: 0o755 })+ vi.stubEnv('HARNESS_PTY_BIN', binary)+ const own = await hostIn(home, instance, '0.2.0', GONE_PID)+ const other = await hostIn(home, `p${P}-0.3.0`, '0.3.0')+ let dead = false+ const hostProcess = { alive: (pid: number) => pid !== GONE_PID || !dead, rows: async () => null }+ const backend = new PtyHostBackend({ home, target: target('0.2.0'), owner: () => 'me', platform: 'linux', hostProcess })+ const replaced = vi.fn()+ backend.onHostReplaced = replaced+ expect(await backend.prepare({ ownedPanes: new Map() })).toEqual({ state: 'ready' })+ dead = true+ await own.stop()+ try {+ await vi.waitFor(() => expect(replaced).toHaveBeenCalledTimes(1), { timeout: 8_000, interval: 50 })+ expect(readFileSync(path.join(home, 'started'), 'utf8')).toBe(`serve --home ${home}\n`)+ expect(backend.instanceId).toBe(`ptyhost:${instance}`)+ expect(await backend.create({ command: ['sh'] })).toMatchObject({ state: 'succeeded', runtime: { instance, paneId: '%5' } })+ // Another build's host, though it answers, is never taken.+ expect(other.hellos).toEqual([])+ } finally {+ backend.dispose()+ const stub = JSON.parse(readFileSync(path.join(home, 'run', discoveryFileName(instance)!), 'utf8')) as { pid: number }+ if (stub.pid !== GONE_PID) try { process.kill(stub.pid, 'SIGKILL') } catch { /* already gone */ }+ }+ }, 20_000)+})diff --git a/cli/src/lib/ptyHostBackend.ts b/cli/src/lib/ptyHostBackend.tsindex 04b92583d..95eace369 100644--- a/cli/src/lib/ptyHostBackend.ts+++ b/cli/src/lib/ptyHostBackend.ts@@ -11,12 +11,16 @@* apart; the delays start again from 1 s only for a connection that had stayed up 30 s. A host with another pid is another host: its predecessor's panes are gone, and `onHostReplaced` says so,* so the reconciler sees them absent and the resume path takes over. `dispose` drops the connection alone.*- * One backend per host instance (`p<protocol>`, ptyHost/drain.ts). The one for this daemon's protocol makes new panes,- * and starts its host when there is none. One for the protocol before is a drain backend: it reaches the host still- * running from before an update and never starts one, lists, streams and controls its panes, refuses `create`, and- * shuts the host down once it has none (`shutdownHost`). A drain host that exits is gone for good (`hostGone`): its- * inventory is then authoritative and empty, so its panes' runtimes go gone through the reconciler's normal misses.+ * One backend per host instance (ptyHost/instance.ts, ptyHost/drain.ts). The create backend makes new panes on the+ * target's host (launch.ts `targetHost`: the build this daemon would start), and starts it when there is none; it is+ * never connected to another build's host. With no target it takes the newest running host of `PTY_PROTOCOL` and stays+ * on that instance until that host is proven dead. Every other host is a drain backend's: it reaches a host still running from before an update and+ * never starts one, lists, streams and controls its panes, refuses `create`, and shuts the host down once it has none+ * (`shutdownHost`) when it may (`mayShutDown`). A drain host that exits is gone for good (`hostGone`): its inventory is+ * then authoritative and empty, so its panes' runtimes go gone through the reconciler's normal misses.*/+import { existsSync } from 'node:fs'+import path from 'node:path'import { env } from '../config/env.js'import type { AgentEngine } from '../engines/types.js'import { harnessPaneOwner } from './harnessSessionLabel.js'@@ -25,8 +29,12 @@ import { lookupPaneEngineProcess } from './paneEngineProcess.js'import { comparableStartMarker, processRows, setProcessTableSource, type ProcessRow } from './processTable.js'import { setAgentSignaller, type AgentSignal } from './processSignals.js'import type { PtyHostCallResult, PtyHostClient } from './ptyHost/client.js'-import { ensurePtyHost, forgetExitedHost, pidAlive, reachPtyHost, type EnsurePtyHostResult, type HostLiveness, type PtyHostUnavailable, type PtyHostUnreached, type ReachPtyHostResult } from './ptyHost/launch.js'-import { PTY_PROTOCOL, SHUTDOWN_PROTOCOL, type PtyEvent } from './ptyHost/protocol.js'+import { discoveryFileName, instanceProtocol } from './ptyHost/instance.js'+import {+ compareVersions, discoveredHostDead, ensurePtyHost, forgetExitedHost, pidAlive, reachPtyHost, readInstanceDiscovery,+ type EnsurePtyHostResult, type HostLiveness, type PtyHostTarget, type PtyHostUnavailable, type PtyHostUnreached, type ReachPtyHostResult,+} from './ptyHost/launch.js'+import { PTY_PROTOCOL, SEED_FEATURE, SHUTDOWN_PROTOCOL, type PtyEvent } from './ptyHost/protocol.js'import { PtyHostStream } from './ptyHost/stream.js'import { submitContent, submitSettleMs } from './submitTiming.js'import type { TerminalBackend, TerminalBackendPrepared } from './terminalBackend.js'@@ -80,11 +88,13 @@ const HOST_EXIT_WAIT_MS = 3_000export interface PtyHostBackendOptions {/** The host's `--home` (`HARNESS_PTY_DIR`): its discovery file and logs live there. */home: string+ /** A drain backend's host instance (`p2-0.4.20`, a legacy `p1`): set, the backend is a drain backend. */+ instance?: string/**- * The host's protocol (`PTY_PROTOCOL` by default): this daemon's own makes new panes; an older one's is a drain- * backend (the module comment).+ * The daemon's target host (`targetHost`, read once as the core starts). A create backend makes panes on its+ * instance alone; a drain backend weighs its own host's version against it (`mayShutDown`). Null or absent: unknown.*/- protocol?: number+ target?: PtyHostTarget | null/** Reach or start the host (`ensurePtyHost`; a drain backend's only reaches it, `reachPtyHost`); a seam for tests. */launch?: (home: string) => Promise<EnsurePtyHostResult | ReachPtyHostResult>/** Whether a pid runs (`pidAlive`), and the process table (`processRows`) a drain host's death is proven in; a seam@@ -141,12 +151,13 @@ export type PtyHostDrainState = 'gone' | 'empty' | 'busy' | 'unknown'export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {readonly name = 'ptyhost' as const- /** The protocol of the host this backend reaches. */- readonly protocol: number- /** A backend for a host of an older protocol: never made new panes on, shut down once it has none. */+ /** A backend for a host other than the target's: never made new panes on, shut down once it has none. */readonly draining: booleanprivate readonly home: string+ private readonly target: PtyHostTarget | null+ /** A drain host's version, from its discovery file, once read. */+ private hostVersion: string | null = nullprivate readonly launch: (home: string) => Promise<EnsurePtyHostResult | ReachPtyHostResult>private readonly hostProcess: { alive: (pid: number) => boolean; rows: () => Promise<ProcessRow[] | null> }/** A drain backend's host has exited, and why: its panes are gone and nothing starts it again. */@@ -179,11 +190,11 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {constructor(options: PtyHostBackendOptions) {this.home = options.home- this.protocol = options.protocol ?? PTY_PROTOCOL- this.draining = this.protocol < PTY_PROTOCOL+ this.target = options.target ?? null+ this.draining = options.instance !== undefined// A drain backend's instance is known before its host is reached: when it has gone, the rows still name it.- if (this.draining) this.instance = `p${this.protocol}`- const protocol = this.protocol+ const drainInstance = options.instance+ if (drainInstance !== undefined) this.instance = drainInstancethis.hostProcess = options.hostProcess ?? { alive: pidAlive, rows: processRows }this.owner = options.owner ?? (() => harnessPaneOwner(env.ADAPTER_DATA_DIR))this.platform = options.platform ?? process.platform@@ -193,13 +204,53 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {const liveness: HostLiveness = this.platform === 'win32'? { alive: (pid) => this.hostProcess.alive(pid), rows: () => this.hostProcess.rows() }: { alive: (pid) => this.hostProcess.alive(pid) }- this.launch = options.launch ?? (this.draining- ? ((home) => reachPtyHost(home, protocol, liveness))- : ((home) => ensurePtyHost(home, { liveness })))+ this.launch = options.launch ?? (drainInstance !== undefined+ ? ((home) => reachPtyHost(home, drainInstance, liveness))+ : (async (home) => ensurePtyHost(home, { target: await this.pinnedTarget(liveness), liveness })))this.endTree = options.endTree ?? ((pid) => this.endTreeOf(pid))}- /** `ptyhost:<instance>`, the instance being the host's (`p<protocol>`), known once `prepare` reached it. */+ /**+ * The host the create backend reaches: the target's; with none, once it has been attached, the instance it took,+ * while that host is not proven dead. A reconnect while it only does not answer must not take another build's host+ * instead: that host's pid would read as a replaced host, and every pane of the one it was on as gone. Once it is+ * proven dead (its discovery file gone, or `discoveredHostDead`), its panes are gone anyway, and the reconnect takes+ * the newest host that answers or the one the binary starts, as with no pin; `onHostReplaced` then says so. The pin+ * names only the instance, which is all `ensurePtyHost` matches on.+ */+ private async pinnedTarget(liveness: HostLiveness): Promise<PtyHostTarget | null> {+ if (this.target || this.instance === null) return this.target+ const pin: PtyHostTarget = { protocol: instanceProtocol(this.instance) ?? PTY_PROTOCOL, version: '', instance: this.instance, features: [], source: 'binary' }+ const discovery = readInstanceDiscovery(this.home, this.instance)+ if (!discovery) {+ // A file caught mid-write is still there: no proof. A host takes its file down only as it exits.+ const file = discoveryFileName(this.instance)+ return file && existsSync(path.join(this.home, 'run', file)) ? pin : null+ }+ return await discoveredHostDead(this.home, discovery, liveness) ? null : pin+ }++ /**+ * Whether the drain may shut this backend's host down once it is empty (ptyHost/drain.ts). Never with no target:+ * the host may be the one the create backend took. Never for a host newer than a target the binary named (a dev+ * build's `HARNESS_PTY_BIN`): that newer host is the installed one's, and stays for its daemon. A newer host under an+ * installed target is a downgrade or a rollback, and goes like any other. A host whose version cannot be read is+ * not known to be older, so it stays too. Always false for the create backend.+ */+ get mayShutDown(): boolean {+ if (!this.draining || !this.target) return false+ if (this.target.source === 'installed') return true+ const version = this.drainHostVersion()+ return version !== null && compareVersions(version, this.target.version) <= 0+ }++ /** The drain host's version, from its discovery file: an instance is one build, so once read it is kept. */+ private drainHostVersion(): string | null {+ if (this.hostVersion === null && this.instance !== null) this.hostVersion = readInstanceDiscovery(this.home, this.instance)?.version ?? null+ return this.hostVersion+ }++ /** `ptyhost:<instance>`, the instance being the host's (ptyHost/instance.ts), known once `prepare` reached it. */get instanceId(): string {return `ptyhost:${this.instance ?? 'unprepared'}`}@@ -274,9 +325,9 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {const rows = await this.hostProcess.rows().catch(() => null)if (!rows) return nullconst row = rows.find((candidate) => candidate.pid === pid)- if (!row) return `the protocol ${this.protocol} host (pid ${pid}) has exited`+ if (!row) return `the ${this.instance} host (pid ${pid}) has exited`if (this.hostIdentity && this.hostIdentity.pid === pid && !sameProcessIdentity(row, this.hostIdentity)) {- return `the protocol ${this.protocol} host (pid ${pid}) has exited; another process has its pid`+ return `the ${this.instance} host (pid ${pid}) has exited; another process has its pid`}return null}@@ -329,7 +380,7 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {console.error(`[terminal] ptyhost: the drained ${this.instance} host (pid ${pid}) has not exited`)return 'failed'}- forgetExitedHost(this.home, this.protocol, pid)+ if (this.instance !== null) forgetExitedHost(this.home, this.instance, pid)this.markGone(`shut down with no panes left (pid ${pid})`)return 'exited'}@@ -424,6 +475,8 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {if (this.draining) {if (this.hostIdentity?.pid !== client.pid) this.hostIdentity = nullvoid this.recordHostIdentity(client)+ // Read while its discovery file is surely there: the host that file names has just answered.+ this.drainHostVersion()}return replaced}@@ -458,7 +511,10 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {this.reconnectTimer = null}- /** One attempt: the host this home has, started again if it is not running (`ensurePtyHost`). */+ /**+ * One attempt: the host this backend is on, started again if it is not running (`ensurePtyHost`, pinned to the+ * instance by `pinnedTarget`; a drain backend's only reaches it).+ */private async reconnect(): Promise<void> {let reached: EnsurePtyHostResult | ReachPtyHostResulttry {@@ -515,10 +571,23 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {return { sessionEnv: true }}+ /** Whether a host is attached now: false before `prepare` reached one, while a lost connection is reconnecting, and+ * once disposed. With a target, the create backend attaches to the target's host alone. */+ get attached(): boolean {+ return this.client !== null && !this.disposed+ }++ /** Whether the host attached now lists `seed`; read live, as the client is replaced on reconnect. False when unattached. */+ get canSeed(): boolean {+ return this.client?.features.includes(SEED_FEATURE) ?? false+ }+async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<PtyRuntimeRef>> {- if (this.draining) return terminalActionNotStarted(`the protocol ${this.protocol} pty host is draining: new panes go to the newest host`)+ if (this.draining) return terminalActionNotStarted(`the ${this.instance} pty host is draining: new panes go to the target host`)const client = this.clientif (!client) return terminalActionNotStarted(UNAVAILABLE)+ // A pre-G host drops `seed` silently, which would look like a pane that kept its scrollback: refuse instead.+ if (request.seed !== undefined && !client.features.includes(SEED_FEATURE)) return terminalActionNotStarted('this host cannot seed a pane')if (request.current?.() === false) return terminalActionNotStarted('The harness changed before pane dispatch')request.onDispatch?.()// Held from the start, as tmux's remain-on-exit at create: an engine that exits at once still leaves@@ -533,6 +602,7 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {owner: this.owner(),...(request.label ? { label: request.label } : {}),hold: true,+ ...(request.seed !== undefined ? { seed: request.seed } : {}),// Windows: the shell the pane becomes when its engine exits, made by the host (lib/windows/engineStart.ts)....(request.afterExit ? { afterExit: { command: request.afterExit.command, ...(request.afterExit.env ? { env: request.afterExit.env } : {}) } } : {}),// Windows: what the pane must not inherit from the host's environment (a grid launch's provider keys).@@ -580,6 +650,7 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {runtime: { backend: 'ptyhost' as const, instance, paneId: pane.pane },rootPid: pane.rootPid!,cwd: pane.cwd,+ ...(pane.label ? { label: pane.label } : {}),})),}}@@ -675,6 +746,21 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {return actionOf(await client.call({ op: 'key', pane: runtime.paneId, key: 'Enter' }))}+ /** The host's raw `write`: the bytes a stream's input frame carries, sent as they are. */+ async writeInput(runtime: PtyRuntimeRef, bytes: Uint8Array): Promise<TerminalActionResult> {+ const client = this.clientFor(runtime)+ if (!client) return terminalActionNotStarted(UNAVAILABLE)+ return actionOf(await client.call({ op: 'write', pane: runtime.paneId, data: Buffer.from(bytes).toString('base64') }))+ }++ /** The host's bracketed `paste`, which brackets only when the program asked for it: what a stream's Paste+ * frame writes (pty/src/stream.rs). */+ async pasteInput(runtime: PtyRuntimeRef, text: string): Promise<TerminalActionResult> {+ const client = this.clientFor(runtime)+ if (!client) return terminalActionNotStarted(UNAVAILABLE)+ return actionOf(await client.call({ op: 'paste', pane: runtime.paneId, text, bracketed: true }))+ }+async sendKey(runtime: PtyRuntimeRef, key: TerminalLogicalKey): Promise<TerminalActionResult> {const client = this.clientFor(runtime)if (!client) return terminalActionNotStarted(UNAVAILABLE)diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex 62948bc8f..565ba2244 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -539,6 +539,10 @@ describe('registry remote display names', () => {const { validTerminalRuntime } = await loadRegistryModule()expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p3', paneId: '%0' })).toBe(true)expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p12345', paneId: '%0' })).toBe(false)+ // A versioned host's: two builds of one protocol run side by side.+ expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p2-0.4.21-dev.win1', paneId: '%7' })).toBe(true)+ expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p2-h0123456789ab', paneId: '%7' })).toBe(true)+ expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p2-0.4.21/x', paneId: '%7' })).toBe(false)expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'default', paneId: '%0' })).toBe(false)expect(validTerminalRuntime({ backend: 'ptyhost', paneId: '%0' })).toBe(false)expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p3', paneId: 'w1:p1' })).toBe(false)diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex b05877f08..8baf16ed8 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -59,6 +59,7 @@ import { mergeTerminalRuntimes, primaryRuntime, processIdentityKey, sameProcessIimport type { HookTerminalHint, ProcessIdentity, TerminalRuntimeRef } from './terminalTypes.js'import { externalReservations, externalResumePending, externalResumeIds, parseExternalResume, type ExternalResumeIntent } from './externalResume.js'import type { StartedBy } from './agentAttribution.js'+import { PTY_HOST_INSTANCE } from './ptyHost/instance.js'import { isKittyGraphicsCommand } from './terminalTitle.js'export type { ProcessIdentity } from './terminalTypes.js'@@ -360,8 +361,8 @@ const PRE_V2_BACKUP_FILE = join(env.ADAPTER_DATA_DIR, 'registry.pre-v2.json')const NAME_OVERRIDES = new Map<string, string>()const PANE_RE = /^%\d+$/-/** A pty host instance: `p` and its protocol version (`PtyRuntimeRef.instance`). */-const PTY_INSTANCE_RE = /^p\d{1,4}$/+/** A pty host instance (`PtyRuntimeRef.instance`): `p<protocol>`, or `p<protocol>-<build>` (ptyHost/instance.ts). */+const PTY_INSTANCE_RE = PTY_HOST_INSTANCEconst GROK_SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iconst AGENT_ENGINES: ReadonlySet<string> = new Set(ENGINES)diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.tsindex 88eb7963a..9be0cc90a 100644--- a/cli/src/lib/restartAgent.ts+++ b/cli/src/lib/restartAgent.ts@@ -111,9 +111,10 @@ export interface RestartAgentDeps {keepAbandoned?: () => void}-/** Outcomes that mean the old process is confirmed gone — safe to respawn over the pane. `not-ours` and- * `failed` are NOT here on purpose: never respawn over a target the kill sequence could not confirm. */-const KILL_CONFIRMED: ReadonlySet<TerminateOutcome> = new Set(['gone', 'terminated', 'killed'])+/** Outcomes that mean the old process is confirmed gone — safe to respawn over the pane (or, for a move, to start+ * the engine in another one: hostMove/moveAgent.ts). `not-ours` and `failed` are NOT here on purpose: never+ * respawn over a target the kill sequence could not confirm. */+export const KILL_CONFIRMED: ReadonlySet<TerminateOutcome> = new Set(['gone', 'terminated', 'killed'])export async function restartAgent(session: { engine: AgentEngine; sessionId: string; resumeOnly?: true },diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.tsindex 760b6e196..7c3125579 100644--- a/cli/src/lib/restoreAgents.ts+++ b/cli/src/lib/restoreAgents.ts@@ -37,6 +37,7 @@*/import { isTerminalEngine, type AgentEngine } from '../engines/types.js'+import type { LaunchOverrides } from './launchOverrides.js'import type { AgentLaunch, ProcessIdentity, RegisteredSession } from './registry.js'import type { TerminalDispatchControl, TerminalRuntimeRef } from './terminalTypes.js'import type { WindowsPaneLaunch } from './windows/engineStart.js'@@ -51,6 +52,19 @@ export interface RestoreLaunch {/** Windows: the folder the engine starts in and the shell its pane becomes after it (lib/windows/engineStart.ts* `windowsPaneLaunch`); elsewhere the launch script enters the folder and hands the pane on itself. */paneLaunch?: WindowsPaneLaunch+ /** Built with `prepare: false` (a move, hostMove/moveAgent.ts): what the build left out, and what it was built with,+ * so the caller prepares and relaunches with the same overrides once the engine has stopped, without asking the+ * grid or the Store again. */+ deferred?: DeferredLaunch+}++export interface DeferredLaunch {+ /** The conversation's resume preparation, when it resumes one, and the row's grid web search. Throws when the+ * conversation could not be prepared. */+ prepare(): void+ /** The overrides (`relaunchOverrides`) and the permission (`downgradedPermission`) the launch was built with. */+ overrides: LaunchOverrides+ permission: { permissionMode?: string | null; bypassPermission?: boolean }}/** The launch, why there is none, or the service its launch asks that could not be asked (`held`). */@@ -111,7 +125,10 @@ export interface RestoreAgentsDeps {liveProcess: (entry: RegisteredSession, runtime: TerminalRuntimeRef) => Promise<ProcessIdentity | null | 'unknown'>/** The pane's launch — engine argv plus whatever puts it back on its grid / profile. A grid the* machine cannot honour (unsupported engine, tmux too old, config dir unwritable) is a refusal. */- buildLaunch: (entry: RegisteredSession, opts: { resumeSessionId?: string; current(): boolean }) => Promise<RestoreLaunchResult>+ /** [opts.prepare] false builds the launch without the writes it makes for it (the conversation's resume preparation,+ * the row's grid web search): a caller that builds it while the engine still runs does them itself once it has+ * stopped (hostMove/moveAgent.ts). */+ buildLaunch: (entry: RegisteredSession, opts: { resumeSessionId?: string; current(): boolean; prepare?: false }) => Promise<RestoreLaunchResult>createPane: (entry: RegisteredSession, launch: RestoreLaunch, control?: TerminalDispatchControl) => Promise<| { ok: true; runtime: TerminalRuntimeRef }| { ok: false; reason: string }diff --git a/cli/src/lib/runtimeControl.ts b/cli/src/lib/runtimeControl.tsindex bc69ac6ec..c937d48eb 100644--- a/cli/src/lib/runtimeControl.ts+++ b/cli/src/lib/runtimeControl.ts@@ -44,7 +44,9 @@ export interface RuntimeProfileControllerDeps {/** Type without submitting. */sendLiteral: (terminalTarget: string, text: string) => Promise<boolean>sendKey: (terminalTarget: string, key: string) => Promise<boolean>- acquireInput: (sessionId: string) => (() => void) | null+ /** The pane's control, or null when it is busy. May wait: while the agent changes host, the daemon's waits for the+ * move to end rather than refuse (hostMove/gate.ts `acquireAfterHold`). */+ acquireInput: (sessionId: string) => (() => void) | null | Promise<(() => void) | null>}export interface CursorParameterRow {@@ -151,7 +153,7 @@ export class RuntimeProfileController {// The other engines' pane drivers read the pane with their engine's own code, loaded in this process: without// it the switch is refused before any key is sent.if (!native && isOtherEngine(session.engine) && !await loadEngine(session.engine)) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')- const release = this.deps.acquireInput(session.agentId)+ const release = await this.deps.acquireInput(session.agentId)if (!release) throw new RuntimeProfileControlError('BUSY')let controlStarted = falselet pickerOpen = falsediff --git a/cli/src/lib/selfUpdate.spec.ts b/cli/src/lib/selfUpdate.spec.tsindex b845fe3bc..25042482e 100644--- a/cli/src/lib/selfUpdate.spec.ts+++ b/cli/src/lib/selfUpdate.spec.ts@@ -9,6 +9,7 @@ import {startSelfUpdater as startSelfUpdaterOn, unjudgedUpdate,} from './selfUpdate.js'import { SpawnLockBusyError } from './daemonSpawnLock.js'+import { PTY_PROTOCOL } from './ptyHost/protocol.js'import { versionsOnDisk } from './windows/cliVersions.js'// The pointer file's writer (B1), with a switch to make it fail.@@ -168,6 +169,34 @@ describe('startSelfUpdater', () => {expect(events).toEqual(['lock', 'staged:9.9.9', 'handoff-done', 'unlock'])})+ it('beforeStage runs under the lock before stage, and its version reaches onStaged', async () => {+ serveUpdate()+ const dir = tempDir()+ const events: string[] = []+ let locked = false+ const staged: Array<[string, string | null]> = []+ const poller = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 20,+ withLock: async (fn) => { locked = true; try { return await fn() } finally { locked = false } },+ // The terminal host goes first, in the same lock hold: the CLI is not on disk yet.+ beforeStage: async () => { events.push(`before ${locked ? 'locked' : 'unlocked'} ${existsSync(join(dir, 'cli.js')) ? 'staged' : 'unstaged'}`); return { version: '0.11.0', protocol: 2 } },+ onStaged: (version, ptyVersion) => { staged.push([version, ptyVersion]) },+ })+ await vi.waitFor(() => expect(staged).toEqual([['9.9.9', '0.11.0']]), { timeout: 5_000 })+ poller.stop()+ expect(events).toEqual(['before locked unstaged'])+ // Without one, the second argument is null.+ serveUpdate()+ const other = tempDir()+ const alone: Array<[string, string | null]> = []+ const plain = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: other, intervalMs: 20,+ onStaged: (version, ptyVersion) => { alone.push([version, ptyVersion]) },+ })+ await vi.waitFor(() => expect(alone).toEqual([['9.9.9', null]]), { timeout: 5_000 })+ plain.stop()+ })+it('stopped while a check is under way, swaps nothing and hands nothing over', async () => {// A daemon shutting down (`harness stop`, a sign-out) while the updater waits on a download or a// canary. Here the canary: the build answers after a moment, and the stop lands before it does.@@ -632,8 +661,8 @@ describe('the canary\'s verdicts', () => {it('tells a build that failed or names another version from a canary that could not be written', async () => {const dir = tempDir()- expect(await runCanary(Buffer.from('console.log("9.9.9")\n'), dir, '9.9.9')).toEqual({ ok: true })- expect(await runCanary(Buffer.from('console.log("loading…"); console.log("9.9.9")\n'), dir, '9.9.9')).toEqual({ ok: true })+ expect(await runCanary(Buffer.from('console.log("9.9.9")\n'), dir, '9.9.9')).toEqual({ ok: true, ptyProtocol: 2 })+ expect(await runCanary(Buffer.from('console.log("loading…"); console.log("9.9.9")\n'), dir, '9.9.9')).toEqual({ ok: true, ptyProtocol: 2 })expect(await runCanary(Buffer.from('console.log("9.9.8")\n'), dir, '9.9.9')).toEqual({ ok: false, problem: 'wrong-version', detail: 'it says it is 9.9.8' })expect(await runCanary(Buffer.from(''), dir, '9.9.9')).toEqual({ ok: false, problem: 'wrong-version', detail: 'it says it is nothing' })expect(await runCanary(Buffer.from('process.exit(3)\n'), dir, '9.9.9')).toEqual({ ok: false, problem: 'failed', detail: 'exit 3' })@@ -652,7 +681,7 @@ describe('the canary\'s verdicts', () => {let ticks = 0const timer = setInterval(() => { ticks++ }, 20)try {- expect(await runCanary(Buffer.from('setTimeout(() => console.log("9.9.9"), 600)\n'), tempDir(), '9.9.9')).toEqual({ ok: true })+ expect(await runCanary(Buffer.from('setTimeout(() => console.log("9.9.9"), 600)\n'), tempDir(), '9.9.9')).toEqual({ ok: true, ptyProtocol: 2 })} finally { clearInterval(timer) }expect(ticks).toBeGreaterThan(10)})@@ -685,6 +714,213 @@ describe('the canary\'s verdicts', () => {})})+describe('the terminal host protocol a build needs (spec §5, the protocol rule)', () => {+ const sha = (b: Buffer): string => createHash('sha256').update(b).digest('hex')+ const notify = Buffer.from('export {}\n')+ afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true })+ dirs = []+ })++ /** A build that answers `version --json` as a G build does, and plain `version` as every build does. */+ const build = (version: string, ptyProtocol: number): Buffer => Buffer.from(+ `console.log(process.argv.includes('--json') ? JSON.stringify({ version: ${JSON.stringify(version)}, ptyProtocol: ${ptyProtocol} }) : ${JSON.stringify(version)})\n`,+ )++ it('plain version output counts as protocol 2', async () => {+ const dir = tempDir()+ // A build from before G prints its version alone, `--json` or not.+ expect(await runCanary(Buffer.from('console.log("9.9.9")\n'), dir, '9.9.9')).toEqual({ ok: true, ptyProtocol: 2 })+ expect(await runCanary(Buffer.from('console.log("{not json")\n'), dir)).toEqual({ ok: true, ptyProtocol: 2 })+ // One that is not the JSON a G build prints is read as plain output too.+ expect(await runCanary(Buffer.from('console.log(JSON.stringify({ version: "9.9.9" }))\n'), dir)).toEqual({ ok: true, ptyProtocol: 2 })+ // A G build says its protocol; its JSON version is the one checked.+ expect(await runCanary(build('9.9.9', 3), dir, '9.9.9')).toEqual({ ok: true, ptyProtocol: 3 })+ expect(await runCanary(build('9.9.8', 3), dir, '9.9.9')).toEqual({ ok: false, problem: 'wrong-version', detail: 'it says it is 9.9.8' })+ expect(readdirSync(dir), 'the canary cleans up after itself').toEqual([])+ })++ it('a build needing a newer pty protocol waits, then stages once the host has it', async () => {+ const cli = build('9.9.9', 3)+ let downloads = 0+ vi.stubGlobal('fetch', async (url: string) => {+ if (url.endsWith('/metadata.json')) {+ return new Response(JSON.stringify({ adapter: {+ version: '9.9.9',+ cli: { url: 'https://updates.test/cli.js', sha256: sha(cli) },+ notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notify) },+ } }))+ }+ if (url.endsWith('cli.js')) downloads+++ return new Response(url.endsWith('cli.js') ? cli : notify)+ })+ const logs: string[] = []+ vi.spyOn(console, 'log').mockImplementation((line: string) => { logs.push(String(line)) })+ const errors: string[] = []+ vi.spyOn(console, 'error').mockImplementation((line: string) => { errors.push(String(line)) })+ let host: number | null = 2+ const dir = tempDir()+ const staged: string[] = []+ const poller = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 10,+ installedPtyProtocol: () => host,+ onStaged: (version) => { staged.push(version) },+ })+ const waiting = "[update] 9.9.9 needs pty protocol 3; this machine's host speaks 2 — waiting for its payload"+ try {+ await vi.waitFor(() => expect(logs).toContain(waiting), { timeout: 5_000 })+ await new Promise((resolve) => setTimeout(resolve, 80))+ expect(staged).toEqual([])+ expect(existsSync(join(dir, 'cli.js')), 'nothing is staged').toBe(false)+ expect(logs.filter((line) => line === waiting), 'said once').toHaveLength(1)+ expect(downloads, 'the bytes stay verified for the next tick').toBe(1)+ expect(errors).toEqual([])+ // The payload arrives (the PTY check, or install.ps1): the build goes ahead with the bytes it already has.+ host = 3+ await vi.waitFor(() => expect(staged).toEqual(['9.9.9']), { timeout: 5_000 })+ expect(downloads).toBe(1)+ expect(readFileSync(join(dir, 'cli.js'))).toEqual(cli)+ } finally { poller.stop() }+ // A host whose protocol cannot be read holds nothing back, and neither does a build at the host's protocol.+ for (const [needs, speaks] of [[3, null], [2, 2]] as const) {+ const other = tempDir()+ const at = build('9.9.9', needs)+ vi.stubGlobal('fetch', async (url: string) => {+ if (url.endsWith('/metadata.json')) {+ return new Response(JSON.stringify({ adapter: {+ version: '9.9.9',+ cli: { url: 'https://updates.test/cli.js', sha256: sha(at) },+ notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notify) },+ } }))+ }+ return new Response(url.endsWith('cli.js') ? at : notify)+ })+ const done: string[] = []+ const plain = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: other, intervalMs: 10,+ installedPtyProtocol: () => speaks,+ onStaged: (version) => { done.push(version) },+ })+ try {+ await vi.waitFor(() => expect(done).toEqual(['9.9.9']), { timeout: 5_000 })+ } finally { plain.stop() }+ }+ })++ /** A manifest naming [cli] as 9.9.9. */+ function serve(cli: Buffer): void {+ vi.stubGlobal('fetch', async (url: string) => {+ if (url.endsWith('/metadata.json')) {+ return new Response(JSON.stringify({ adapter: {+ version: '9.9.9',+ cli: { url: 'https://updates.test/cli.js', sha256: sha(cli) },+ notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notify) },+ } }))+ }+ return new Response(url.endsWith('cli.js') ? cli : notify)+ })+ }++ it('on Windows, a host whose protocol cannot be read counts as this CLI\'s own: a build that raises it waits', async () => {+ // No current-pty, or a `harness-pty.exe version` that failed or timed out: unknown must not mean "anything goes".+ serve(build('9.9.9', PTY_PROTOCOL + 1))+ const logs: string[] = []+ vi.spyOn(console, 'log').mockImplementation((line: string) => { logs.push(String(line)) })+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const staged: string[] = []+ const poller = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: tempDir(), intervalMs: 10, platform: 'win32',+ installedPtyProtocol: () => null,+ onStaged: (version) => { staged.push(version) },+ })+ try {+ await vi.waitFor(() => expect(logs).toContain(`[update] 9.9.9 needs pty protocol ${PTY_PROTOCOL + 1}; this machine's host speaks ${PTY_PROTOCOL} — waiting for its payload`), { timeout: 5_000 })+ await new Promise((resolve) => setTimeout(resolve, 60))+ expect(staged).toEqual([])+ } finally { poller.stop() }+ })++ it('asks the rule again under the lock, after beforeStage: a host that went back meanwhile holds the build', async () => {+ serve(build('9.9.9', 3))+ const logs: string[] = []+ vi.spyOn(console, 'log').mockImplementation((line: string) => { logs.push(String(line)) })+ vi.spyOn(console, 'error').mockImplementation(() => {})+ let locked = false+ const asked: string[] = []+ const staged: string[] = []+ const needs: number[] = []+ const dir = tempDir()+ const poller = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 10,+ withLock: async (fn) => { locked = true; try { return await fn() } finally { locked = false } },+ // Protocol 3 when the check asks; 2 under the lock, as after a rollback that landed in between.+ installedPtyProtocol: () => { asked.push(locked ? 'locked' : 'unlocked'); return locked ? 2 : 3 },+ beforeStage: async (protocol) => { needs.push(protocol); return null },+ onStaged: (version) => { staged.push(version) },+ })+ try {+ await vi.waitFor(() => expect(logs).toContain("[update] 9.9.9 needs pty protocol 3; this machine's host speaks 2 — waiting for its payload"), { timeout: 5_000 })+ await new Promise((resolve) => setTimeout(resolve, 60))+ expect(staged).toEqual([])+ expect(existsSync(join(dir, 'cli.js'))).toBe(false)+ expect(asked.slice(0, 2)).toEqual(['unlocked', 'locked'])+ // beforeStage hears the protocol the build needs: a paired host goes in only for that one.+ expect(needs[0]).toBe(3)+ } finally { poller.stop() }+ })++ it('under the lock, trusts the protocol of the host that just went in from its canary, not a fresh read of it', async () => {+ // A just-installed harness-pty.exe whose `version` fails or times out reads as null, which on Windows counts as 2:+ // re-read, it would hold back the very build the paired host came for, with the host already in.+ serve(build('9.9.9', 3))+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const staged: Array<[string, string | null]> = []+ const poller = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir: tempDir(), intervalMs: 10,+ installedPtyProtocol: () => 2,+ readyPtyProtocol: () => 3,+ beforeStage: async () => ({ version: '0.11.0', protocol: 3 }),+ onStaged: (version, ptyVersion) => { staged.push([version, ptyVersion]) },+ })+ try {+ await vi.waitFor(() => expect(staged).toEqual([['9.9.9', '0.11.0']]), { timeout: 5_000 })+ } finally { poller.stop() }+ })++ it('a paired host of the protocol the build needs lets it go ahead, the host first in the same lock hold', async () => {+ serve(build('9.9.9', 3))+ vi.spyOn(console, 'log').mockImplementation(() => {})+ let host = 2+ let ready: number | null = 2+ const order: string[] = []+ const staged: Array<[string, string | null]> = []+ const dir = tempDir()+ const poller = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 10,+ installedPtyProtocol: () => host,+ // A payload of another protocol is no help; once one of protocol 3 is ready, it goes in first.+ readyPtyProtocol: () => ready,+ beforeStage: async (protocol) => {+ if (ready !== protocol) return null+ order.push(`host ${existsSync(join(dir, 'cli.js')) ? 'after' : 'before'} the build`)+ host = 3+ ready = null+ return { version: '0.11.0', protocol: 3 }+ },+ onStaged: (version, ptyVersion) => { staged.push([version, ptyVersion]) },+ })+ try {+ await new Promise((resolve) => setTimeout(resolve, 200))+ expect(staged).toEqual([])+ ready = 3+ await vi.waitFor(() => expect(staged).toEqual([['9.9.9', '0.11.0']]), { timeout: 5_000 })+ expect(order).toEqual(['host before the build'])+ } finally { poller.stop() }+ })+})+describe('a build that fails on its own merits (e2e/updateHostile.e2e.ts)', () => {const sha = (b: Buffer): string => createHash('sha256').update(b).digest('hex')const notify = Buffer.from('export {}\n')diff --git a/cli/src/lib/selfUpdate.ts b/cli/src/lib/selfUpdate.tsindex fc57038a9..84777e397 100644--- a/cli/src/lib/selfUpdate.ts+++ b/cli/src/lib/selfUpdate.ts@@ -20,6 +20,7 @@ import { dirname, join } from 'path'import { SpawnLockBusyError, describeSpawnLockFailure } from './daemonSpawnLock.js'import { managedNodePath } from './nodeRuntime.js'import { patientDeadline } from './patientExec.js'+import { PTY_PROTOCOL } from './ptyHost/protocol.js'import { currentCli } from './windows/installLayout.js'import { isVersionFolder, retireUnused, switchTo, versionsOnDisk, writeVersionFolder, type RetireDeps } from './windows/cliVersions.js'@@ -91,7 +92,8 @@ const liveSha256 = (dir: string, platform: NodeJS.Platform): string | null => {return file === null ? null : fileSha256(file)}-function pendingVersion(dir: string): string | null {+/** The version of a staged build not yet kept or rolled back (its pending note), or null when there is none. */+export function pendingVersion(dir: string): string | null {return readPending(dir)?.version ?? null}@@ -186,7 +188,7 @@ export const RUNTIME_DOWNLOAD_LIMITS: TransferLimits = { idleMs: 300_000, deadliexport class TransferStalledError extends Error {}/** GET `url` whole within `limits`: the status, and the body once it has all arrived. */-async function fetchWithin(url: string, limits: TransferLimits, expectedBytes?: number): Promise<{ ok: boolean; status: number; body: Buffer }> {+export async function fetchWithin(url: string, limits: TransferLimits, expectedBytes?: number): Promise<{ ok: boolean; status: number; body: Buffer }> {const controller = new AbortController()let stalled!: (error: TransferStalledError) => voidconst gaveUp = new Promise<never>((_, reject) => { stalled = reject })@@ -272,9 +274,26 @@ export async function downloadVerified(ref: FileRef, limits: TransferLimits = DO/*** What the canary found. `unwritable`: it could not be set up (a full disk, a folder it may not write),* which says nothing about the build; `failed`: the build ran and failed; `wrong-version`: it ran and- * said it is another version than the manifest names.+ * said it is another version than the manifest names. A build that ran says which terminal host protocol it+ * needs (`ptyProtocol`, its `PTY_PROTOCOL`): the updater's protocol rule (`installedPtyProtocol`).*/-export type CanaryResult = { ok: true } | { ok: false; problem: 'unwritable' | 'failed' | 'wrong-version'; detail: string }+export type CanaryResult = { ok: true; ptyProtocol: number } | { ok: false; problem: 'unwritable' | 'failed' | 'wrong-version'; detail: string }++/** The protocol a build that prints only its version speaks: every build from before `version --json`. */+const PLAIN_VERSION_PTY_PROTOCOL = 2++/** What a build's last `version --json` line says: a G build's `{"version","ptyProtocol"}`, or, for any other line (a+ * build from before, which ignores the flag and prints its version alone), that line as its version, at protocol 2. */+function readVersionAnswer(line: string): { version: string; ptyProtocol: number } {+ try {+ const parsed: unknown = JSON.parse(line)+ const { version, ptyProtocol } = (parsed ?? {}) as { version?: unknown; ptyProtocol?: unknown }+ if (typeof version === 'string' && Number.isSafeInteger(ptyProtocol) && (ptyProtocol as number) >= 1) {+ return { version, ptyProtocol: ptyProtocol as number }+ }+ } catch { /* plain output */ }+ return { version: line, ptyProtocol: PLAIN_VERSION_PTY_PROTOCOL }+}/** How long the canary may take to answer. */export const CANARY_TIMEOUT_MS = 15_000@@ -282,7 +301,8 @@ export const CANARY_TIMEOUT_MS = 15_000export const CANARY_KILL_GRACE_MS = 2_000/** Cheap runnability check: write the new bundle into a temp install-shaped dir and run- * `node cli.js version`. This catches broken ESM/CJS packaging before the live install is touched.+ * `node cli.js version --json`. This catches broken ESM/CJS packaging before the live install is touched,+ * and learns the terminal host protocol the build needs without staging it (spec §5, the protocol rule).** Given the version the manifest names, the build must also say it is that version. A manifest that* named an older build's bytes under a newer version (published by mistake, e2e/updateHostile.e2e.ts)@@ -313,7 +333,7 @@ export async function runCanary(cliBuf: Buffer, dir: string, version?: string, tlet timedOut = falselet grace: ReturnType<typeof setTimeout> | undefinedlet cancel = (): void => {}- const child = execFile(managedNodePath(), [tmpCli, 'version'], { encoding: 'utf8' }, (error, stdout) => {+ const child = execFile(managedNodePath(), [tmpCli, 'version', '--json'], { encoding: 'utf8' }, (error, stdout) => {cancel()clearTimeout(grace)// An answer is an answer, even one that raced the kill.@@ -335,9 +355,9 @@ export async function runCanary(cliBuf: Buffer, dir: string, version?: string, t})if (r.failure !== null) return { ok: false, problem: 'failed', detail: r.failure }const lines = r.stdout.trim().split('\n')- const said = lines[lines.length - 1]- if (version !== undefined && said !== version) return { ok: false, problem: 'wrong-version', detail: `it says it is ${said || 'nothing'}` }- return { ok: true }+ const said = readVersionAnswer(lines[lines.length - 1].trim())+ if (version !== undefined && said.version !== version) return { ok: false, problem: 'wrong-version', detail: `it says it is ${said.version || 'nothing'}` }+ return { ok: true, ptyProtocol: said.ptyProtocol }} finally {try { rmSync(tmpDir, { recursive: true, force: true }) } catch { /* ignore */ }}@@ -561,7 +581,7 @@ export function msUntilSlot(nowMs: number, slotSecond: number | undefined, inter/*** Poll on an interval; on the first build {@link shouldAutoUpdate} allows that also verifies and- * passes its canary, STAGE it and call `onStaged(version)` exactly once, then stop polling (the+ * passes its canary, STAGE it and call `onStaged(version, ptyVersion)` exactly once, then stop polling (the* caller restarts immediately). Every failure* (fetch/parse/sha/canary/disk) is swallowed and simply retried next tick — the daemon never crashes* on a bad update.@@ -590,8 +610,14 @@ export function startSelfUpdater(opts: {/** The clock (tests). */now?: () => number/** Awaited: the section from the byte swap through whatever `onStaged` does (the daemon's restart- * handoff) is ONE critical section, and the lock `withLock` takes must outlive all of it. */- onStaged: (version: string) => void | Promise<void>+ * handoff) is ONE critical section, and the lock `withLock` takes must outlive all of it. `ptyVersion`: the+ * terminal host `beforeStage` installed into the same handover, or null. */+ onStaged: (version: string, ptyVersion: string | null) => void | Promise<void>+ /** Called under the lock right before `stage`: what else goes into this handover, first (Windows: a terminal host+ * payload already prepared, ./windows/ptyUpdate.ts `readyToStage`). Its version reaches `onStaged`. It hears the+ * host protocol the build needs, so a paired host goes in only with the build that needs it, and says the protocol+ * of a host it installed (from that host's canary), which the rule then trusts. */+ beforeStage?: (ptyProtocol: number) => Promise<{ version: string; protocol: number } | null>/** Wrap the swap + `onStaged` in a mutual exclusion with every other process that writes the* bundle or spawns the daemon. Default: none (tests, and callers that hold their own). */withLock?: <T>(fn: () => Promise<T>) => Promise<T>@@ -608,6 +634,18 @@ export function startSelfUpdater(opts: {stageWhileJudged?: boolean/** Whose layout `dir` has; this process's when left out. */platform?: NodeJS.Platform+ /**+ * Windows: the protocol of the terminal host `current-pty` names (lib/windows/ptyUpdate.ts `installedPtyProtocol`).+ * A build whose canary says it needs a higher one is not staged: it would come up with no host it can open a pane+ * on. It waits, verified, until a payload of that protocol is installed (install.ps1), or is ready to go in first+ * (`readyPtyProtocol`). On Windows a host that cannot be read (no pointer, a `version` that failed or timed out)+ * counts as this CLI's own `PTY_PROTOCOL`: unknown must not let a build that raises it through. Left out (macOS and+ * Linux), nothing is held back.+ */+ installedPtyProtocol?: () => number | null+ /** The protocol of a terminal host payload prepared and waiting to go into this handover first (`beforeStage`), or+ * null. A build that needs exactly that protocol goes ahead with it, as one pair. */+ readyPtyProtocol?: () => number | null}): Poller {let checking = falselet done = false@@ -617,12 +655,24 @@ export function startSelfUpdater(opts: {// they passed their canary: when the lock was busy (a `harness start` or `harness update`// mid-flight), or the canary could not be written, the next tick should try again from there, not// from the whole download.- let verified: { entry: string; version: string; cliBuf: Buffer; notifyBuf: Buffer; canaried: boolean } | null = null+ let verified: { entry: string; version: string; cliBuf: Buffer; notifyBuf: Buffer; canaried: boolean; ptyProtocol: number } | null = null// The manifest's build, when it failed in a way it would fail again, and when it may be tried again.let refused: { entry: string; tries: number; until: number } | null = null// Said once per version: the check repeats every interval.let toldRejected: string | null = nulllet toldWaiting: string | null = null+ let toldProtocol: string | null = null+ /** What the protocol rule says of a build that needs host protocol [needs]: null when it may be staged, else the+ * protocol the installed host speaks. */+ const hostShortOf = (needs: number): number | null => {+ if (!opts.installedPtyProtocol) return null+ const host = opts.installedPtyProtocol() ?? (platform === 'win32' ? PTY_PROTOCOL : null)+ return host !== null && needs > host ? host : null+ }+ const waitForHost = (version: string, needs: number, host: number): void => {+ if (toldProtocol !== version) console.log(`[update] ${version} needs pty protocol ${needs}; this machine's host speaks ${host} — waiting for its payload`)+ toldProtocol = version+ }const now = opts.now ?? Date.nowconst platform = opts.platform ?? process.platform@@ -690,7 +740,7 @@ export function startSelfUpdater(opts: {refuse(`does not match its manifest (${error.message})`)return}- verified = { entry: key, version: entry.version, cliBuf, notifyBuf, canaried: false }+ verified = { entry: key, version: entry.version, cliBuf, notifyBuf, canaried: false, ptyProtocol: PLAIN_VERSION_PTY_PROTOCOL }}if (halted) returnif (!verified.canaried) {@@ -702,8 +752,14 @@ export function startSelfUpdater(opts: {}if (!result.ok) { refuse(`failed its canary (${result.detail})`); return }verified.canaried = true+ verified.ptyProtocol = result.ptyProtocol}const ready = verified+ // The protocol rule: no CLI that no installed host can serve. Asked at every check, with the bytes kept, so the+ // build goes ahead at the first check after its payload is installed, or once one of that protocol is ready to go+ // in first, in this handover (the pairing rule).+ const short = hostShortOf(ready.ptyProtocol)+ if (short !== null && opts.readyPtyProtocol?.() !== ready.ptyProtocol) { waitForHost(ready.version, ready.ptyProtocol, short); return }if (opts.stageWhileJudged === false && unjudgedUpdate(opts.dir, liveSha256(opts.dir, platform))) {if (toldWaiting !== ready.version) console.log(`[update] ${ready.version} is ready — waiting for this build to be kept before staging it`)toldWaiting = ready.version@@ -721,11 +777,19 @@ export function startSelfUpdater(opts: {console.log(`[update] ${ready.version} is no longer an update: the installed build is now ${pointedNow}. Nothing was staged.`)return}+ // The terminal host first, in this same lock hold and handover (spec §5): one restart for both.+ const host = opts.beforeStage ? await opts.beforeStage(ready.ptyProtocol) : null+ const ptyVersion = host?.version ?? null+ // Asked again with the host this build would come up on: the paired one may have failed to go in, or a rollback+ // may have moved the pointer since the check. A host that just went in is known from its canary: its binary,+ // read again now, could fail and count as this CLI's protocol. One that went in is the caller's (`withLock`).+ const shortNow = host ? (ready.ptyProtocol > host.protocol ? host.protocol : null) : hostShortOf(ready.ptyProtocol)+ if (shortNow !== null) { waitForHost(ready.version, ready.ptyProtocol, shortNow); return }stage(opts.dir, ready.cliBuf, ready.notifyBuf, ready.version, platform)done = truestop()console.log(`[update] staged ${ready.version} — restarting now`)- await opts.onStaged(ready.version)+ await opts.onStaged(ready.version, ptyVersion)}).catch((err: unknown) => {// A busy lock is not a failed check: the bytes are good and waiting, and the next tick tries// the swap again. Say so, or a minute of "check failed" reads as the updater being broken.diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex c58819ea7..5d4514a74 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'import { afterEach, describe, expect, it, vi } from 'vitest'import { SessionInputController } from './sessionInput.js'+import { MoveGate } from './hostMove/gate.js'import type { RegisteredSession } from './registry.js'import { TERMINAL_LEASE_REFUSED, type ProcessIdentity, type TerminalActionResult } from './terminalTypes.js'import { createScreens } from '../core/engines/screens.js'@@ -1832,3 +1833,104 @@ describe('what became of a person\'s message, for its measurement', () => {controller.forget('s1')})})++describe('while the agent changes host', () => {+ const controllerWith = (gate: MoveGate, inject: (target: string, content: string) => Promise<boolean>) =>+ new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: (id) => id === 's1' ? session() : id === 's2' ? { ...session(), sessionId: 's2', agentId: 'h2' } : undefined,+ validateRuntime: async () => true, inject, sendKey: async () => true,+ capture: async () => codexComposer(''), onError: vi.fn(), moveGate: gate })++ it('a harness send during a hold is delivered after release', async () => {+ const gate = new MoveGate()+ const injected: string[] = []+ const controller = controllerWith(gate, async (_target, content) => { injected.push(content); return true })+ gate.hold('h1')+ controller.submit('s1', 'sent while it moves')+ await new Promise((resolve) => setTimeout(resolve, 5))+ expect(injected).toEqual([])+ await gate.release('h1')+ await vi.waitFor(() => expect(injected).toEqual(['sent while it moves']))+ controller.forget('s1')+ })++ it('a held message can be cancelled, and nothing is typed at release', async () => {+ const gate = new MoveGate()+ const injected: string[] = []+ const onDelivery = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(), validateRuntime: async () => true,+ inject: async (_target, content) => { injected.push(content); return true }, sendKey: async () => true,+ capture: async () => codexComposer(''), onError: vi.fn(), onDelivery, beforeTeamWrite: async () => null, moveGate: gate })+ gate.hold('h1')+ controller.submit('s1', 'retired before it was typed', 'team:d1')+ expect(controller.cancelDelivery('team:d1')).toBe(true)+ expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'team:d1', state: 'rejected', reason: 'cancelled' })+ await gate.release('h1')+ await new Promise((resolve) => setTimeout(resolve, 5))+ expect(injected).toEqual([])+ expect(controller.cancelDelivery('team:d1')).toBe(false)+ controller.forget('s1')+ })++ it('held messages count against the queue\'s limits', async () => {+ const gate = new MoveGate()+ const onError = vi.fn()+ const injected: string[] = []+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(), validateRuntime: async () => true,+ inject: async (_target, content) => { injected.push(content); return true }, sendKey: async () => true,+ capture: async () => codexComposer(''), onError, moveGate: gate })+ gate.hold('h1')+ const outcomes: string[] = []+ for (let i = 0; i < 9; i++) controller.submit('s1', `m${i}`, undefined, undefined, (o) => { outcomes.push(o) })+ expect(outcomes).toEqual(['queue_full'])+ expect(onError).toHaveBeenCalledWith('s1', 'This agent already has too many queued messages. Try again after the current operation finishes.')+ controller.forget('s1')+ })++ it('held keystrokes behind a held message land after its Enter', async () => {+ const gate = new MoveGate()+ const order: string[] = []+ const controller = controllerWith(gate, async (_target, content) => {+ order.push(`paste:${content}`)+ await new Promise((resolve) => setTimeout(resolve, 10))+ order.push('enter')+ return true+ })+ gate.hold('h1')+ controller.submit('s1', 'the message')+ // A keystroke typed into the agent's stream after the message, held by the same gate.+ gate.enqueue('h1', async () => { order.push('key') })+ await gate.release('h1')+ expect(order).toEqual(['paste:the message', 'enter', 'key'])+ controller.forget('s1')+ })++ it('control is never handed out onto the pane being replaced, and is given again after the move', async () => {+ const gate = new MoveGate()+ const controller = controllerWith(gate, async () => true)+ gate.hold('h1')+ // Refused as a busy pane is: device input asks again every 100 ms, so its write waits rather than+ // reaching the old pane.+ expect(controller.acquireControl('s1')).toBeNull()+ expect(controller.acquireControl('s1', { forAnswer: true })).toBeNull()+ expect(gate.touched('h1')).toBe(true)+ await gate.release('h1')+ const release = controller.acquireControl('s1')+ expect(release).toBeTypeOf('function')+ release!()+ controller.forget('s1')+ })++ it('nothing is held for other agents', async () => {+ const gate = new MoveGate()+ const injected: string[] = []+ const controller = controllerWith(gate, async (_target, content) => { injected.push(content); return true })+ gate.hold('h1')+ controller.submit('s2', 'to the other agent')+ await vi.waitFor(() => expect(injected).toEqual(['to the other agent']))+ controller.forget('s1')+ controller.forget('s2')+ })+})diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 84a0d38a0..d21dd39bb 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -6,6 +6,7 @@ import { launchBound } from '../core/engines/sessionBinding.js'import type { RegisteredSession } from './registry.js'import { sid } from './log.js'import { isMessageHold, messageHoldText, messageWithheldText, passingHold, type MessageHold } from './messageHolds.js'+import type { MoveGate } from './hostMove/gate.js'import { enterWithheldReason, TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'const MAX_QUEUE_ITEMS = 8@@ -104,6 +105,13 @@ interface QueuedInput {expiresAt: number}+/** A message held while its agent changes host (`MoveGate`): submitted as itself at release, unless cancelled. */+interface HeldInput {+ deliveryId?: string+ bytes: number+ cancelled: boolean+}+interface InputState {/** The writes this agent's messages are making, one after another in the order they arrived. */writes?: Promise<void>@@ -123,6 +131,9 @@ interface InputState {controlLocked: booleansettling: booleanqueue: QueuedInput[]+ /** The messages the move gate holds for this agent, in arrival order. Counted against the queue's limits,+ * and cancellable as queued ones are. */+ held: HeldInput[]timer: NodeJS.Timeout | nullsettleTimer: NodeJS.Timeout | nullretries: number@@ -156,6 +167,9 @@ export interface SessionInputDeps {/** Clock and timer for the lease wait; real ones by default. */now?: () => numbersleep?: (ms: number) => Promise<void>+ /** While an agent changes host, its messages wait here and are typed into the pane it ends on. Absent: none+ * is ever held. */+ moveGate?: MoveGate}/** A message not typed because of what the pane showed (messageHold.ts): nothing was written. */@@ -252,6 +266,7 @@ export class SessionInputController {controlLocked: false,settling: false,queue: [],+ held: [],timer: null,settleTimer: null,retries: 0,@@ -288,6 +303,13 @@ export class SessionInputController {/** Revoke queued work only; a paste already in progress cannot be recalled. */cancelDelivery(deliveryId: string): boolean {for (const [sessionId, state] of this.states) {+ const held = state.held.findIndex((item) => item.deliveryId === deliveryId)+ if (held >= 0) {+ state.held[held].cancelled = true+ state.held.splice(held, 1)+ this.delivery(sessionId, deliveryId, 'rejected', 'cancelled')+ return true+ }const index = state.queue.findIndex((item) => item.deliveryId === deliveryId)if (index >= 0) {state.queue.splice(index, 1)@@ -306,12 +328,39 @@ export class SessionInputController {/** [receipt]: what became of a person's message (one with no [deliveryId]), for its measurement. */submit(sessionId: string, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void {const said = sayOnce(receipt)+ // An agent changing host has no pane to type into until the move ends: the message waits, as itself, and+ // is submitted then, through every check `submitNow` makes, into the pane the row then names.+ const agentId = this.controlSession(sessionId)?.agentId+ const gate = this.deps.moveGate+ if (agentId && gate?.holding(agentId)) {+ const state = this.state(sessionId)+ const bytes = Buffer.byteLength(content, 'utf8')+ if (this.refusedFull(sessionId, state, bytes, deliveryId, said)) return+ console.log(`[inject] ${sid(sessionId)} held · the agent is changing host · depth=${state.held.length + 1}`)+ const item: HeldInput = { deliveryId, bytes, cancelled: false }+ state.held.push(item)+ gate.enqueue(agentId, async () => {+ const at = state.held.indexOf(item)+ if (at >= 0) state.held.splice(at, 1)+ if (!item.cancelled) await this.submitNow(sessionId, content, deliveryId, inputContext, said)+ })+ return+ }+ void this.submitNow(sessionId, content, deliveryId, inputContext, said)+ }++ /**+ * `submit` past the move gate. Resolves once this message's write is done, or at once when it is queued+ * here or refused: the gate delivers what it held one at a time, and a keystroke held behind this message+ * must not land between its paste and its Enter.+ */+ private submitNow(sessionId: string, content: string, deliveryId?: string, inputContext?: string, said?: MessageReceipt): Promise<void> {const session = this.controlSession(sessionId)if (!session) {said?.('agent_gone')this.delivery(sessionId, deliveryId, 'rejected', 'agent_gone')if (!deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This harness is no longer available.')- return+ return Promise.resolve()}const state = this.state(sessionId)this.dropExpired(sessionId, state)@@ -324,7 +373,7 @@ export class SessionInputController {this.enqueue(sessionId, state, content, deliveryId, inputContext, said)if (this.swarmTypesWhileBusy(session.engine, deliveryId) && state.turnOpen&& !state.deliveryId && state.awaitingFingerprint && !state.timer) this.armSubmitCheck(sessionId, session, state)- return+ return Promise.resolve()}this.delivery(sessionId, deliveryId, 'queued')// One write at a time per agent, in the order the messages arrived. Claude Code and Codex take@@ -335,10 +384,10 @@ export class SessionInputController {// agent as it is by then, which a restart in between may have changed.// With nothing in flight the write starts at once, so a cancel or a control request that follows// the submit sees it, as before.- this.scheduleWrite(sessionId, session, content, deliveryId, inputContext, said)+ return this.scheduleWrite(sessionId, session, content, deliveryId, inputContext, said)}- private scheduleWrite(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void {+ private scheduleWrite(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): Promise<void> {const state = this.state(sessionId)const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, inputContext, receipt)const running = state.writes ? state.writes.then(write, write) : write()@@ -348,6 +397,7 @@ export class SessionInputController {if (this.states.get(sessionId) === state && state.queue[0]?.deliveryId?.startsWith('team:service:superTabs:')) this.drainOne(sessionId, state)})state.writes = settled+ return settled}/** Reserve this pane for a short native control interaction such as `/model`. */@@ -366,6 +416,13 @@ export class SessionInputController {acquireControl(sessionId: string, opts?: { forAnswer?: boolean }): (() => void) | null {const session = this.controlSession(sessionId)if (!session) return null+ // Not while the agent changes host: what the holder typed would reach the pane being replaced. Refused+ // as a busy pane is, so the caller asks again (device input every 100 ms) and gets it after the move.+ const gate = this.deps.moveGate+ if (gate?.holding(session.agentId)) {+ gate.touch(session.agentId)+ return null+ }const state = this.state(sessionId)this.dropExpired(sessionId, state)const turnBlocks = state.turnOpen && !opts?.forAnswer@@ -1045,6 +1102,17 @@ export class SessionInputController {}private drainOne(sessionId: string, state: InputState): void {+ // A queued message whose turn is due while the agent changes host goes behind what the gate holds.+ const agentId = this.controlSession(sessionId)?.agentId+ const gate = this.deps.moveGate+ if (agentId && gate?.holding(agentId)) {+ gate.enqueue(agentId, async () => { const current = this.states.get(sessionId); if (current) await this.drainNow(sessionId, current) })+ return+ }+ void this.drainNow(sessionId, state)+ }++ private async drainNow(sessionId: string, state: InputState): Promise<void> {this.dropExpired(sessionId, state)const current = this.controlSession(sessionId)const busySwarm = !!current && this.swarmTypesWhileBusy(current.engine, state.queue[0]?.deliveryId)@@ -1062,23 +1130,28 @@ export class SessionInputController {if (!next.deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This harness is no longer available.')return}- if (busySwarm) this.scheduleWrite(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)- else void this.inject(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)+ if (busySwarm) await this.scheduleWrite(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)+ else await this.inject(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)}private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void {const bytes = Buffer.byteLength(content, 'utf8')- const queuedBytes = state.queue.reduce((sum, item) => sum + item.bytes, 0)- if (state.queue.length >= MAX_QUEUE_ITEMS || queuedBytes + bytes > MAX_QUEUE_BYTES) {- this.delivery(sessionId, deliveryId, 'rejected', 'queue_full')- receipt?.('queue_full')- if (!deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This agent already has too many queued messages. Try again after the current operation finishes.')- return- }+ if (this.refusedFull(sessionId, state, bytes, deliveryId, receipt)) returnstate.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS, deliveryId, inputContext, ...(receipt ? { receipt } : {}) })this.delivery(sessionId, deliveryId, 'queued')}+ /** Refuse a message of [bytes] when the agent's queued and held messages are at their limits. */+ private refusedFull(sessionId: string, state: InputState, bytes: number, deliveryId?: string, receipt?: MessageReceipt): boolean {+ const waiting = [...state.queue, ...state.held]+ const waitingBytes = waiting.reduce((sum, item) => sum + item.bytes, 0)+ if (waiting.length < MAX_QUEUE_ITEMS && waitingBytes + bytes <= MAX_QUEUE_BYTES) return false+ this.delivery(sessionId, deliveryId, 'rejected', 'queue_full')+ receipt?.('queue_full')+ if (!deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This agent already has too many queued messages. Try again after the current operation finishes.')+ return true+ }+private dropExpired(sessionId: string, state: InputState): void {const now = Date.now()const expiredLocalInput = state.queue.some(item => item.expiresAt <= now && !item.deliveryId?.startsWith('team:'))diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.tsindex 2e5845ead..bcd2b3152 100644--- a/cli/src/lib/terminalAgentReconciler.spec.ts+++ b/cli/src/lib/terminalAgentReconciler.spec.ts@@ -167,6 +167,27 @@ describe('composite terminal reconciliation', () => {expect(onTerminalAvailability).toHaveBeenCalledWith(current, true)})+ it('verifies a shell row on a drain host\'s pane, by that host\'s instance and not the target\'s', async () => {+ const old: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p2-0.4.901', paneId: '%1' }+ // The target's host has a pane of the same id: only the row's own instance may answer for it.+ const target: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p2-0.4.902', paneId: '%1' }+ const current = { ...session([old]), engine: 'terminal' as const, active: false, processIdentity: null }+ const onTerminalAvailability = vi.fn()+ const reconciler = new TerminalAgentReconciler({+ current: () => [current], backends: [], backendOrder: ['ptyhost'],+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),+ onTerminalAvailability,+ probe: async () => probe([+ { instanceId: 'ptyhost:p2-0.4.902', result: { state: 'available', roots: [{ runtime: target, rootPid: 1, cwd: '/work' }] } },+ { instanceId: 'ptyhost:p2-0.4.901', result: { state: 'available', roots: [{ runtime: old, rootPid: 2, cwd: '/work' }] } },+ ]),+ })++ await reconciler.trigger()++ expect(onTerminalAvailability).toHaveBeenCalledWith(current, true)+ })+it('still verifies retained panes when the process table is unavailable', async () => {const current = { ...session([tmux]), active: false }const onTerminalAvailability = vi.fn()diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.tsindex fa4be858f..ed55aa5a8 100644--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@ -46,6 +46,13 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimtypeLiteral(runtime: Ref, text: string): Promise<TerminalActionResult>submitText(runtime: Ref, text: string, options?: SubmitOptions): Promise<TerminalActionResult>sendKey(runtime: Ref, key: TerminalLogicalKey): Promise<TerminalActionResult>+ /** Raw bytes into the pane, as a stream's input frame writes them, with no stream open: what was typed while+ * the agent changed host, delivered to the pane it ended on (hostMove/gate.ts). Optional: only the pty host+ * moves panes. */+ writeInput?(runtime: Ref, bytes: Uint8Array): Promise<TerminalActionResult>+ /** A paste into the pane, as a stream's paste frame makes it (bracketed when the program asked for that),+ * with no stream open: `writeInput`'s companion for a held paste. */+ pasteInput?(runtime: Ref, text: string): Promise<TerminalActionResult>setTitle(runtime: Ref, title: string): Promise<TerminalActionResult>notify(runtime: Ref, title: string, body: string): Promise<TerminalActionResult>diff --git a/cli/src/lib/terminalHandoff.spec.ts b/cli/src/lib/terminalHandoff.spec.tsindex 478a64540..834317233 100644--- a/cli/src/lib/terminalHandoff.spec.ts+++ b/cli/src/lib/terminalHandoff.spec.ts@@ -17,6 +17,10 @@ describe('the tile `harness remote` was typed in', () => {expect(handoffAgentId(rows, 'p1:%3')).toBe('a')expect(handoffAgentId(rows, 'p2:%3')).toBe('b')expect(handoffAgentId(rows, 'p3:%3')).toBeNull()+ // A versioned host's, beside the legacy one of its protocol.+ const versioned = [...rows, pty('dev', 'p2-0.4.21-dev.win1', '%7'), pty('hashed', 'p2-h0123456789ab', '%7')]+ expect(handoffAgentId(versioned, 'p2-0.4.21-dev.win1:%7')).toBe('dev')+ expect(handoffAgentId(versioned, 'p2-h0123456789ab:%7')).toBe('hashed')})it('never by the bare primary pane alone: a row without that runtime is not it', () => {@@ -25,6 +29,7 @@ describe('the tile `harness remote` was typed in', () => {it('accepts either form on the wire, and nothing else', () => {expect(terminalHandoffRequest({ tmuxPane: 'p1:%3', machineId: 'm', agentId: 'a' })).toEqual({ tmuxPane: 'p1:%3', machineId: 'm', agentId: 'a' })- for (const pane of ['p1:3', 'x1:%3', 'p1:%', ':%3', 'p12345:%3']) expect(terminalHandoffRequest({ tmuxPane: pane, machineId: 'm', agentId: 'a' })).toBeNull()+ for (const pane of ['p2-0.4.21-dev.win1:%7', 'p2-h0123456789ab:%7']) expect(terminalHandoffRequest({ tmuxPane: pane, machineId: 'm', agentId: 'a' })?.tmuxPane).toBe(pane)+ for (const pane of ['p1:3', 'x1:%3', 'p1:%', ':%3', 'p12345:%3', 'p2-:%3', 'p2-a/b:%3']) expect(terminalHandoffRequest({ tmuxPane: pane, machineId: 'm', agentId: 'a' })).toBeNull()})})diff --git a/cli/src/lib/terminalHandoff.ts b/cli/src/lib/terminalHandoff.tsindex 6464537aa..f004f60e1 100644--- a/cli/src/lib/terminalHandoff.ts+++ b/cli/src/lib/terminalHandoff.ts@@ -8,6 +8,7 @@* terminal streams' and never reach the RPC switch.)*/+import { PTY_HOST_INSTANCE_SOURCE } from './ptyHost/instance.js'import { sessionForPaneId } from './terminalRuntime.js'import type { TerminalRuntimeRef } from './terminalTypes.js'@@ -22,7 +23,7 @@ export interface TerminalHandoffRequest {export const TMUX_PANE_RE = /^%\d{1,9}$//** What the daemon accepts as the handoff's pane: tmux's `%N`, or a pty host pane's `<instance>:%N`. */-const HANDOFF_PANE_RE = /^(?:p\d{1,4}:)?%\d{1,9}$/+const HANDOFF_PANE_RE = new RegExp(`^(?:${PTY_HOST_INSTANCE_SOURCE}:)?%\\d{1,9}$`)const ID_RE = /^[A-Za-z0-9_-]{1,128}$//** The request as the wire may carry it — bounded, printable ids, a real pane id — or null. */diff --git a/cli/src/lib/terminalRuntime.spec.ts b/cli/src/lib/terminalRuntime.spec.tsindex f50b6f857..92348d069 100644--- a/cli/src/lib/terminalRuntime.spec.ts+++ b/cli/src/lib/terminalRuntime.spec.ts@@ -6,6 +6,7 @@ import {processIdentityOf,primaryRuntime,sameProcessIdentity,+ sessionForPaneId,terminalInstanceId,terminalPlacementKey,terminalRouteKey,@@ -36,6 +37,17 @@ describe('terminal runtime identity', () => {expect(() => terminalRouteKey({ ...r, instance: '' })).toThrow('invalid pty host instance')})+ it('sessionForPaneId accepts p2-0.4.21-dev.win1:%7 and p2-h0123456789ab:%7', () => {+ const row = (agentId: string, instance: string) => ({ agentId, runtimes: [{ backend: 'ptyhost' as const, instance, paneId: '%7' }] })+ // Two builds of one protocol side by side: each pane is its own host's.+ const rows = [row('legacy', 'p2'), row('dev', 'p2-0.4.21-dev.win1'), row('hashed', 'p2-h0123456789ab'), { agentId: 'tmux', runtimes: [{ backend: 'tmux' as const, paneId: '%7' }] }]+ expect(sessionForPaneId(rows, 'p2-0.4.21-dev.win1:%7')?.agentId).toBe('dev')+ expect(sessionForPaneId(rows, 'p2-h0123456789ab:%7')?.agentId).toBe('hashed')+ expect(sessionForPaneId(rows, 'p2:%7')?.agentId).toBe('legacy')+ expect(sessionForPaneId(rows, '%7')?.agentId).toBe('tmux')+ expect(sessionForPaneId(rows, 'p2-0.4.22:%7')).toBeUndefined()+ })+it('takes a session\'s first runtime as its primary, whatever its backend', () => {const ptyhost = { backend: 'ptyhost' as const, instance: 'p1', paneId: '%4' }expect(primaryRuntime({ runtimes: [ptyhost, tmux] })).toBe(ptyhost)diff --git a/cli/src/lib/terminalRuntime.ts b/cli/src/lib/terminalRuntime.tsindex 1b9033411..758093f75 100644--- a/cli/src/lib/terminalRuntime.ts+++ b/cli/src/lib/terminalRuntime.ts@@ -1,4 +1,5 @@import type { AgentEngine } from '../engines/types.js'+import { PTY_HOST_PANE } from './ptyHost/instance.js'import type { ProcessIdentity, TerminalBackendName, TerminalRuntimeRef } from './terminalTypes.js'const SEP = '\u0000'@@ -50,9 +51,6 @@ export function primaryRuntime(session: { readonly runtimes: readonly TerminalRureturn session.runtimes[0]}-/** A pty host pane as its shell names itself: `HARNESS_PANE`, `<instance>:%N`. */-const PTY_HOST_PANE = /^(p\d{1,4}):(%\d{1,9})$/-/*** The row a shell's own word about its pane names (`harness remote`, `harness send`). A bare `%N` is `$TMUX_PANE`,* so a tmux pane and nothing else: a pty host's `%N` is another pane, which only its own `<instance>:%N`diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.tsindex 5726943b8..0cbc92a3e 100644--- a/cli/src/lib/terminalStreamManager.spec.ts+++ b/cli/src/lib/terminalStreamManager.spec.ts@@ -13,6 +13,7 @@ import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.jsimport { TerminalBinaryKind, TERMINAL_LOCAL_IMAGE_PASTE_MAX_PAYLOAD_BYTES, type TerminalBinaryClear } from './terminalBinary.js'import { writeImageToOsClipboard, type OsClipboardImageResult } from './osClipboard.js'import { writePasteDropFile, writePasteImageFile } from './pasteDropFiles.js'+import { MoveGate } from './hostMove/gate.js'vi.mock('./osClipboard.js', () => ({ writeImageToOsClipboard: vi.fn() }))vi.mock('./pasteDropFiles.js', () => ({ writePasteImageFile: vi.fn(), writePasteDropFile: vi.fn() }))@@ -45,8 +46,11 @@ class FakeStream implements TerminalStreamHandle {/** When set, every writeRaw parks on it instead of answering at once — a tmux that is slow to `%end`. */pendingWrites: Array<(result: TerminalActionResult) => void> = []holdWrites = false+ /** Every write and paste, in the order they reached the pane. */+ order: string[] = []async writeRaw(bytes: Uint8Array): Promise<TerminalActionResult> {this.writes.push(bytes)+ this.order.push(`raw:${Buffer.from(bytes).toString()}`)if (!this.holdWrites) return TERMINAL_ACTION_SUCCEEDEDreturn new Promise((resolve) => { this.pendingWrites.push(resolve) })}@@ -54,6 +58,7 @@ class FakeStream implements TerminalStreamHandle {pasteLands: ((allowed: (() => boolean) | undefined) => Promise<TerminalActionResult>) | null = nullasync pasteRaw(text: string, allowed?: () => boolean) {this.pastes.push(text)+ this.order.push(`paste:${text}`)return this.pasteLands ? this.pasteLands(allowed) : TERMINAL_ACTION_SUCCEEDED}async resize(size: { cols: number; rows: number }) { this.sizes.push(size); return TERMINAL_ACTION_SUCCEEDED }@@ -1696,4 +1701,330 @@ describe('TerminalStreamManager', () => {await vi.advanceTimersByTimeAsync(2)expect(binarySent.length).toBe(afterLeadingEdge + 1)})++ describe('who is looking', () => {+ const open = (connId: string, extra: Record<string, unknown> = {}) =>+ manager.handleFrame(connId, 'terminal_open', {+ requestId: `open-${connId}`, protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30, ...extra,+ })+ beforeEach(async () => {+ await manager.stop()+ manager = newManager({ isLoopback: (connId) => connId.startsWith('local:') })+ })++ it('a loopback stream whose window lists other agents is not looked at', async () => {+ await open('local:desktop')+ manager.setVisibleAgents('local:desktop', ['agent-other'])+ expect(manager.isLookedAt('agent-1')).toBe(false)+ manager.setVisibleAgents('local:desktop', ['agent-1'])+ expect(manager.isLookedAt('agent-1')).toBe(true)+ })++ it('a loopback stream whose window never sent a list is looked at', async () => {+ await open('local:desktop')+ expect(manager.isLookedAt('agent-1')).toBe(true)+ manager.setVisibleAgents('local:desktop', null)+ expect(manager.isLookedAt('agent-1')).toBe(true)+ })++ it('a mobile or web stream is looked at, a takeover:false one included', async () => {+ await open('web-1')+ await open('web-2', { takeover: false })+ expect(manager.isLookedAt('agent-1')).toBe(true)+ await manager.closeConnection('web-1')+ expect(manager.isLookedAt('agent-1')).toBe(true)+ await manager.closeConnection('web-2')+ expect(manager.isLookedAt('agent-1')).toBe(false)+ })++ it('a watch:true stream is never looked at', async () => {+ await open('web-1', { watch: true })+ await open('local:desktop', { watch: true })+ expect(manager.isLookedAt('agent-1')).toBe(false)+ })++ it('a Share observer on a read-only manager counts even when it asks for watch:true', async () => {+ await manager.stop()+ manager = newManager({ readOnly: true })+ await open('observer:ken', { watch: true })+ expect(manager.isLookedAt('agent-1')).toBe(true)+ })++ it('a minimized window\'s empty list frees its agents', async () => {+ await open('local:desktop')+ manager.setVisibleAgents('local:desktop', [])+ expect(manager.isLookedAt('agent-1')).toBe(false)+ })++ it('closing the connection forgets its list', async () => {+ await open('local:desktop')+ manager.setVisibleAgents('local:desktop', [])+ await manager.closeConnection('local:desktop')+ await open('local:desktop')+ expect(manager.isLookedAt('agent-1')).toBe(true)+ })+ })++ describe('while an agent changes host', () => {+ const oldPane = { backend: 'ptyhost' as const, instance: 'p2', paneId: '%1' }+ const newPane = { backend: 'ptyhost' as const, instance: 'p2-0.5.0', paneId: '%7' }+ let gate: MoveGate+ let opens: Array<{ runtimes: unknown; size: unknown; readOnly: boolean; sink: TerminalStreamSink; stream: FakeStream }>+ let rawWrites: Array<{ runtime: unknown; bytes: string }>+ let duringOpen: (() => void) | null+ const paste = (connId: string, streamId: string, text: string) => manager.handleBinary(connId, {+ kind: TerminalBinaryKind.paste, streamId, seq: 0, bytes: Buffer.from(text), compressed: false,+ })+ /** What the mover does at the swap: the row names the new pane, and the agent's streams follow it. */+ const swap = async () => {+ agents.set('agent-1', row('agent-1', newPane))+ await manager.retarget('agent-1', newPane)+ }+ const row = (agentId: string, runtime: typeof oldPane) => ({+ ...session('codex', agentId), runtimes: [runtime], primaryRuntimeKey: `ptyhost:${runtime.instance}:${runtime.paneId}`,+ } as unknown as RegisteredSession)+ const openFrame = (connId: string, agentId = 'agent-1') => manager.handleFrame(connId, 'terminal_open', {+ requestId: `open-${connId}`, protocolVersion: 3, agentId, cols: 100, rows: 30,+ })+ const readyFor = (connId: string) => String(sent.findLast((f) => f.connId === connId && f.type === 'terminal_ready')!.payload.streamId)+ const input = (connId: string, streamId: string, seq: number, text: string) => manager.handleBinary(connId, {+ kind: TerminalBinaryKind.input, streamId, seq, bytes: Buffer.from(text), compressed: false,+ })++ beforeEach(async () => {+ await manager.stop()+ gate = new MoveGate()+ opens = []+ rawWrites = []+ agents = new Map([['agent-1', row('agent-1', oldPane)], ['agent-2', row('agent-2', { ...oldPane, paneId: '%2' })]])+ duringOpen = null+ terminals = {+ openStream: async (opened: RegisteredSession, size: unknown, nextSink: TerminalStreamSink, readOnly = false) => {+ const next = new FakeStream()+ opens.push({ runtimes: opened.runtimes, size, readOnly, sink: nextSink, stream: next })+ duringOpen?.()+ return { state: 'succeeded' as const, value: next }+ },+ backendFor: () => ({+ writeInput: async (runtime: unknown, bytes: Uint8Array) => {+ rawWrites.push({ runtime, bytes: Buffer.from(bytes).toString() })+ return TERMINAL_ACTION_SUCCEEDED+ },+ pasteInput: async (runtime: unknown, text: string) => {+ rawWrites.push({ runtime, bytes: `paste:${text}` })+ return TERMINAL_ACTION_SUCCEEDED+ },+ }),+ } as unknown as TerminalBackendCoordinator+ manager = newManager({ moveGate: gate, isLoopback: (connId) => connId.startsWith('local:') })+ })++ it('input during a hold is delivered once, in order, after release', async () => {+ const onInput = vi.fn()+ await manager.stop()+ manager = newManager({ moveGate: gate, onInput })+ await openFrame('web-1')+ const streamId = readyFor('web-1')+ gate.hold('agent-1')+ await input('web-1', streamId, 0, 'a')+ await input('web-1', streamId, 1, 'b')+ await input('web-1', streamId, 2, 'c')+ // Taken as input at once (the prewarm, the quiet clock), but nothing reaches a pane yet.+ expect(onInput).toHaveBeenCalledTimes(3)+ expect(opens[0].stream.writes).toEqual([])+ await swap()+ expect(opens[1].stream.writes).toEqual([])+ await gate.release('agent-1')+ // Through the retargeted stream, onto the new pane; never the old one.+ expect(opens[1].stream.order).toEqual(['raw:a', 'raw:b', 'raw:c'])+ expect(opens[0].stream.writes).toEqual([])+ expect(rawWrites).toEqual([])+ expect(sent.filter((f) => f.type === 'terminal_error')).toEqual([])+ })++ it('held input whose stream closed during the move still reaches the row\'s pane', async () => {+ await openFrame('web-1')+ const streamId = readyFor('web-1')+ gate.hold('agent-1')+ await input('web-1', streamId, 0, 'a')+ await paste('web-1', streamId, 'P')+ await manager.closeConnection('web-1')+ agents.set('agent-1', row('agent-1', newPane))+ await gate.release('agent-1')+ expect(rawWrites).toEqual([{ runtime: newPane, bytes: 'a' }, { runtime: newPane, bytes: 'paste:P' }])+ expect(opens[0].stream.writes).toEqual([])+ })++ it('a paste during a hold is delivered after release, in order with keystrokes', async () => {+ await openFrame('web-1')+ const streamId = readyFor('web-1')+ gate.hold('agent-1')+ await input('web-1', streamId, 0, 'a')+ await paste('web-1', streamId, 'P')+ await input('web-1', streamId, 1, 'b')+ expect(opens[0].stream.order).toEqual([])+ await swap()+ await gate.release('agent-1')+ expect(opens[1].stream.order).toEqual(['raw:a', 'paste:P', 'raw:b'])+ expect(opens[0].stream.order).toEqual([])+ })++ it('an image paste during a hold is delivered after release, in order with keystrokes', async () => {+ await openFrame('web-1')+ const streamId = readyFor('web-1')+ gate.hold('agent-1')+ const png = Uint8Array.of(0x89, 0x50, 0x4e, 0x47)+ await input('web-1', streamId, 0, 'a')+ await manager.handleFrame('web-1', 'terminal_chunked_upload_begin', { streamId, uploadKind: 'image', totalBytes: png.length })+ await manager.handleBinary('web-1', { kind: TerminalBinaryKind.imagePaste, streamId, seq: 0, compressed: false, bytes: png })+ await input('web-1', streamId, 1, 'b')+ expect(writeImageToOsClipboard).not.toHaveBeenCalled()+ expect(opens[0].stream.order).toEqual([])+ await swap()+ await gate.release('agent-1')+ expect(writeImageToOsClipboard).toHaveBeenCalledTimes(1)+ expect(opens[1].stream.order).toEqual(['raw:a', 'raw:\u0016', 'raw:b'])+ expect(sent.findLast((f) => f.type === 'terminal_paste_image_result')?.payload).toMatchObject({ streamId, outcome: 'clipboard' })+ })++ it('a held agent counts as looked at from the moment input or an open arrives, until it is let go', async () => {+ await openFrame('local:desktop')+ manager.setVisibleAgents('local:desktop', ['agent-other'])+ gate.hold('agent-1')+ expect(manager.isLookedAt('agent-1')).toBe(false)+ await input('local:desktop', readyFor('local:desktop'), 0, 'x')+ expect(manager.isLookedAt('agent-1')).toBe(true)+ await gate.release('agent-1')+ expect(manager.isLookedAt('agent-1')).toBe(false)+ // The next hold starts untouched.+ gate.hold('agent-1')+ expect(manager.isLookedAt('agent-1')).toBe(false)+ await gate.release('agent-1')++ manager.setVisibleAgents('local:other', ['agent-other'])+ gate.hold('agent-2')+ await openFrame('local:other', 'agent-2')+ expect(manager.isLookedAt('agent-2')).toBe(true)+ await gate.release('agent-2')+ expect(manager.isLookedAt('agent-2')).toBe(false)+ })++ it('an open during a hold returns at once on the current runtime, and is moved by the retarget at swap', async () => {+ gate.hold('agent-1')+ await openFrame('web-1')+ const streamId = readyFor('web-1')+ expect(opens.map((o) => o.runtimes)).toEqual([[oldPane]])+ await swap()+ expect(opens.map((o) => o.runtimes)).toEqual([[oldPane], [newPane]])+ expect(opens[0].stream.closed).toBe(true)+ await gate.release('agent-1')+ expect(sent.filter((f) => f.type === 'terminal_closed' || f.type === 'terminal_error')).toEqual([])+ await input('web-1', streamId, 0, 'typed')+ expect(opens[1].stream.order).toEqual(['raw:typed'])+ })++ it('an open the swap overtook follows the row on its own', async () => {+ gate.hold('agent-1')+ // The mover switches the row and retargets while this open is still reaching the old pane: the+ // retarget finds no stream to move, so the open has to notice.+ duringOpen = () => {+ duringOpen = null+ agents.set('agent-1', row('agent-1', newPane))+ void manager.retarget('agent-1', newPane)+ }+ await openFrame('web-1')+ expect(opens.map((o) => o.runtimes)).toEqual([[oldPane], [newPane]])+ expect(opens[0].stream.closed).toBe(true)+ expect(sent.filter((f) => f.type === 'terminal_closed' || f.type === 'terminal_error')).toEqual([])+ await gate.release('agent-1')+ })++ it('a retarget opens the new pane at the size the client last asked for, even one the old pane refused', async () => {+ await openFrame('web-1')+ const streamId = readyFor('web-1')+ opens[0].stream.resize = async () => ({ state: 'failed', dispatch: 'rejected', reason: 'no' })+ await manager.handleFrame('web-1', 'terminal_resize', { streamId, resizeSeq: 1, cols: 90, rows: 20 })+ await swap()+ expect(opens[1].size).toEqual({ cols: 90, rows: 20 })+ })++ it('an open stream follows a retarget with no close, and gets the new pane\'s output', async () => {+ await openFrame('web-1')+ await openFrame('web-2')+ const watcherOpen = manager.handleFrame('web-3', 'terminal_open', {+ requestId: 'watch', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24, watch: true,+ })+ await watcherOpen+ const streamId = readyFor('web-2')+ await manager.handleFrame('web-2', 'terminal_resize', { streamId, resizeSeq: 1, cols: 120, rows: 40 })+ const [, before, watcher] = opens+ before.stream.snapshotBytes = Buffer.from('old pane')+ const framesBefore = binarySent.length+ sent = []++ await manager.retarget('agent-1', newPane)++ // Every open stream of the agent was re-subscribed on the new pane, at its own size and mode.+ expect(opens.slice(3).map((o) => [o.runtimes, o.size, o.readOnly])).toEqual([+ [[newPane], { cols: 120, rows: 40 }, false],+ [[newPane], { cols: 80, rows: 24 }, true],+ ])+ expect(before.stream.closed).toBe(true)+ expect(watcher.stream.closed).toBe(true)+ expect(sent.filter((f) => f.type === 'terminal_closed' || f.type === 'terminal_error')).toEqual([])+ const after = opens[3]+ // The client's screen is reset through the keyframe it already knows, on its own stream id.+ expect(after.stream.snapshots).toBe(1)+ const keyframe = binarySent.slice(framesBefore).find((f) => f.connId === 'web-2' && f.frame.kind === TerminalBinaryKind.keyframe)+ expect(keyframe?.frame.streamId).toBe(streamId)++ // The old pane's late output is dropped; the new pane's reaches the same stream.+ const sentNow = binarySent.length+ before.sink.onData(Buffer.from('late old output'))+ before.sink.onClose('old pane gone')+ after.sink.onData(Buffer.from('new pane output'))+ await vi.advanceTimersByTimeAsync(20)+ const outputs = binarySent.slice(sentNow).filter((f) => f.connId === 'web-2' && f.frame.kind === TerminalBinaryKind.output)+ expect(outputs.map((f) => [f.frame.streamId, Buffer.from(f.frame.bytes).toString()])).toEqual([[streamId, 'new pane output']])+ expect(sent.filter((f) => f.type === 'terminal_closed')).toEqual([])++ // Input on the same stream now goes to the new pane.+ await input('web-2', streamId, 0, 'typed')+ expect(after.stream.writes.map((b) => Buffer.from(b).toString())).toEqual(['typed'])+ expect(before.stream.writes).toEqual([])+ })++ it('a keyframe being taken of the old pane when the stream moves is taken again of the new one', async () => {+ await openFrame('web-1')+ const streamId = readyFor('web-1')+ const before = opens[0].stream+ let finishOld!: () => void+ before.snapshot = () => new Promise((resolve) => {+ finishOld = () => resolve({ state: 'succeeded', value: { bytes: Buffer.from('old pane'), cols: 100, rows: 30 } })+ })+ const resync = manager.handleFrame('web-1', 'terminal_resync', { streamId })+ await vi.advanceTimersByTimeAsync(0)+ const framesBefore = binarySent.length+ await manager.retarget('agent-1', newPane)+ const after = opens[1].stream+ after.snapshotBytes = Buffer.from('new pane')+ finishOld()+ await resync+ const keyframes = binarySent.slice(framesBefore).filter((f) => f.frame.kind === TerminalBinaryKind.keyframe)+ expect(keyframes.map((f) => [f.frame.streamId, Buffer.from(f.frame.bytes).toString()])).toEqual([[streamId, 'new pane']])+ expect(after.snapshotBegins).toBe(after.snapshotEnds)+ expect(sent.filter((f) => f.type === 'terminal_closed' || f.type === 'terminal_error')).toEqual([])+ })++ it('nothing is held for other agents', async () => {+ await openFrame('web-1', 'agent-2')+ const streamId = readyFor('web-1')+ gate.hold('agent-1')+ await input('web-1', streamId, 0, 'free')+ expect(opens[0].stream.writes.map((b) => Buffer.from(b).toString())).toEqual(['free'])+ await openFrame('web-2', 'agent-2')+ expect(opens).toHaveLength(2)+ expect(rawWrites).toEqual([])+ })+ })})diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsindex 48d245902..3f742923d 100644--- a/cli/src/lib/terminalStreamManager.ts+++ b/cli/src/lib/terminalStreamManager.ts@@ -10,8 +10,17 @@ import { writeImageToOsClipboard } from './osClipboard.js'import { sleptFor } from './sleepAware.js'import { writePasteDropFile, writePasteImageFile } from './pasteDropFiles.js'import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'+import type { TerminalBackend } from './terminalBackend.js'import { terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'-import { KEYFRAME_MAX_BYTES, type TerminalStreamHandle, type TerminalStreamSize } from './terminalTypes.js'+import {+ KEYFRAME_MAX_BYTES,+ terminalActionNotStarted,+ type TerminalActionResult,+ type TerminalRuntimeRef,+ type TerminalStreamHandle,+ type TerminalStreamSize,+} from './terminalTypes.js'+import type { MoveGate } from './hostMove/gate.js'import {TerminalBinaryKind,TERMINAL_LOCAL_IMAGE_PASTE_MAX_PAYLOAD_BYTES,@@ -138,6 +147,13 @@ interface ActiveStream {engineId: stringplacementKey: stringhandle: TerminalStreamHandle+ /** Which of the stream's subscriptions `handle` is: 0 for the one it opened with, then one more for each+ * `retarget`. A sink answers only while it is the current one, so a pane left behind can neither write+ * to the stream nor close it. `subscriptions` is the last one handed out. */+ subscription: number+ subscriptions: number+ /** The size the stream last asked its pane for (open, then each resize): a retarget opens the new pane at it. */+ size: TerminalStreamSizecompression: 'none' | 'zlib'/** Whether this stream serves the desktop on this computer (see `TerminalStreamManagerDeps.isLoopback`). */loopback: boolean@@ -216,11 +232,24 @@ export interface TerminalStreamManagerDeps {* pane opens can go to the phone the person is typing on (core/terminals/browser.ts).*/onInput?: (agentId: string, typed: boolean, from: { connId: string, kind: string | null; inputContext?: string; submitted?: boolean }) => void+ /** While an agent changes host, every write to its terminal waits here, and goes to the pane it ends on;+ * its streams follow it through `retarget`. Absent: nothing is ever held. */+ moveGate?: MoveGate/** Set only while keystrokes are traced (`TYPING_TRACE`): one line per keystroke held, released, and echoed.* Numbers and timings only, never the bytes. */typingTrace?: (line: string) => void}+/** The row's primary pane, on whichever backend holds it (tmux or the PTY host). */+function primaryRuntimeOf(session: RegisteredSession): TerminalRuntimeRef | undefined {+ return session.runtimes.find((runtime) => terminalRouteKey(runtime) === session.primaryRuntimeKey) ?? session.runtimes[0]+}++/** [session] as the coordinator reads it, naming only [runtime]: the open path's own call, on that pane. */+function rowOn(session: RegisteredSession, runtime: TerminalRuntimeRef): RegisteredSession {+ return { ...session, runtimes: [runtime], primaryRuntimeKey: terminalRouteKey(runtime) }+}+function sizeFrom(payload: FramePayload): TerminalStreamSize | null {const cols = Number(payload.cols)const rows = Number(payload.rows)@@ -260,6 +289,9 @@ export class TerminalStreamManager {// The agent each loopback window last said it has focused (`app_focus`), null for none. A window that// never said is absent, and all its terminals keep the short window, as before focus was followed.private readonly focusByConn = new Map<string, string | null>()+ // The agents whose tiles each loopback window shows (`app_focus.visibleAgents`). A window that never+ // sent a list is absent, and counts as looking at everything it streams (older desktops).+ private readonly visibleByConn = new Map<string, ReadonlySet<string>>()private readonly now: () => numberprivate readonly expiryTimer: ReturnType<typeof setInterval>private lastSweepAt: number@@ -469,14 +501,16 @@ export class TerminalStreamManager {this.sendError(connId, 'TERMINAL_AGENT_NOT_FOUND', { requestId })return}+ // An agent changing host is opened at once, on the pane its row names now (the old one is kept until its+ // streams are retargeted): waiting here would hold every later frame of this connection. The open counts+ // as someone using the agent.+ this.deps.moveGate?.touch(session.agentId)if (!TERMINAL_ENGINES.has(session.engine)) {this.sendError(connId, 'TERMINAL_ENGINE_UNSUPPORTED', { requestId })return}- // The agent's primary pane, on whichever backend holds it (tmux or the PTY host): the coordinator opens the- // stream through that backend.- const streamRuntime = session.runtimes.find((runtime) => terminalRouteKey(runtime) === session.primaryRuntimeKey)- ?? session.runtimes[0]+ // The agent's primary pane: the coordinator opens the stream through the backend that holds it.+ const streamRuntime = primaryRuntimeOf(session)if (!streamRuntime) {this.sendError(connId, 'TERMINAL_RUNTIME_UNAVAILABLE', { requestId })return@@ -545,12 +579,13 @@ export class TerminalStreamManager {let opened: Awaited<ReturnType<TerminalBackendCoordinator['openStream']>>try {opened = await this.deps.terminals.openStream(session, size, {+ // Subscription 0: once a retarget has moved the stream to another pane, this one is ignored.onData: (bytes) => {- if (state) this.onOutput(state, bytes)- else buffered.push(Buffer.from(bytes))+ if (!state) buffered.push(Buffer.from(bytes))+ else if (state.subscription === 0) this.onOutput(state, bytes)},onClose: (reason) => {- if (state) void this.closeStream(state, reason, true)+ if (state?.subscription === 0) void this.closeStream(state, reason, true)},}, this.deps.readOnly || watching)} catch {@@ -600,6 +635,9 @@ export class TerminalStreamManager {engineId: session.engine,placementKey,handle: opened.value,+ subscription: 0,+ subscriptions: 0,+ size,compression: wantsZlib ? 'zlib' : 'none',loopback,flushMs: this.flushWindow(connId, session.agentId, loopback),@@ -657,9 +695,20 @@ export class TerminalStreamManager {// Whether it holds the terminal: who resized an agent is read from here.this.diagnostic(state, 'opened', { cols: size.cols, rows: size.rows, compression: state.compression, watching, ...(watchOnly ? { watchOnly } : {}) })await this.sendKeyframe(state, 'open')+ // A move that swapped the row's pane while this open was in flight retargeted the streams it found, and+ // this one may not have been among them: it follows on its own.+ if (this.deps.moveGate) await this.followRow(state, streamRuntime)})}+ /** Retarget [state] to its row's primary pane when that is no longer [openedOn]. */+ private async followRow(state: ActiveStream, openedOn: TerminalRuntimeRef): Promise<void> {+ const row = this.deps.resolveAgent(state.agentId)+ const current = row ? primaryRuntimeOf(row) : undefined+ if (state.closing || !row || !current || terminalRouteKey(current) === terminalRouteKey(openedOn)) return+ await this.retargetStream(state, rowOn(row, current))+ }+private streamFor(connId: string, payload: FramePayload): ActiveStream | null {const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''const state = this.streams.get(streamId)@@ -805,13 +854,26 @@ export class TerminalStreamManager {if (this.deps.typingTrace) state.echoProbe = { seq: inputSeq, at: this.now() }state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MSthis.tookInput(state, typedByPerson(bytes), nativeSubmitKey(bytes))+ // The agent is changing host: the pane this stream writes to is going away. The keystrokes wait, in order+ // with every other write to the agent, and are written once the move ends. The seq is spent either way.+ const gate = this.heldGate(state)+ if (gate) {+ const held = Uint8Array.from(bytes)+ gate.enqueue(state.agentId, () => this.reportInput(state, this.writeRawTo(state, held, true)))+ return+ }// Not awaited. `writeRaw` hands its `send-keys` to the control client's FIFO synchronously, so// keystroke order is already fixed by the time it returns its promise — and the seq above is// spent, so the next frame cannot race this one. Awaiting the reply held the whole local// socket (localWsServer.ts serialises every message behind this call) for one tmux round-trip// per keystroke; now the round-trips overlap, which is what ControlCommandQueue pipelines for.// The result still matters, only later: a failure is reported when tmux says so.- void state.handle.writeRaw(bytes).then(+ void this.reportInput(state, state.handle.writeRaw(bytes))+ }++ /** A keystroke write's outcome, told to the client when it failed. */+ private reportInput(state: ActiveStream, write: Promise<TerminalActionResult>): Promise<void> {+ return write.then((result) => {if (state.closing || result.state === 'succeeded') returnthis.sendError(state.connId, 'TERMINAL_INPUT_FAILED', { streamId: state.streamId, message: result.reason })@@ -831,6 +893,40 @@ export class TerminalStreamManager {})}+ /** The gate, when [state]'s agent is changing host: then every write from the stream waits on it. */+ private heldGate(state: ActiveStream): MoveGate | null {+ const gate = this.deps.moveGate+ return gate?.holding(state.agentId) ? gate : null+ }++ /**+ * Raw bytes into [state]'s pane: the stream's own pane, retargeted to the row's by the time held input is+ * delivered. [held] input whose stream closed during the move goes to the row's pane through its backend:+ * the stream is gone, and the input is still the person's.+ */+ private writeRawTo(state: ActiveStream, bytes: Uint8Array, held = false): Promise<TerminalActionResult> {+ if (!held || !state.closing) return state.handle.writeRaw(bytes)+ return this.writeToRow(state, (backend, runtime) => backend.writeInput?.(runtime, bytes))+ }++ /** A paste into [state]'s pane, as `writeRawTo` writes raw bytes. */+ private pasteRawTo(state: ActiveStream, text: string, held = false): Promise<TerminalActionResult> {+ // Asked again as it lands (main's guard): a paste takes two tmux processes, and its stream may close meanwhile.+ if (!held || !state.closing) return state.handle.pasteRaw(text, () => !state.closing)+ return this.writeToRow(state, (backend, runtime) => backend.pasteInput?.(runtime, text))+ }++ private async writeToRow(+ state: ActiveStream,+ write: (backend: TerminalBackend, runtime: TerminalRuntimeRef) => Promise<TerminalActionResult> | undefined,+ ): Promise<TerminalActionResult> {+ const row = this.deps.resolveAgent(state.agentId)+ const runtime = row ? primaryRuntimeOf(row) : undefined+ const backend = runtime ? this.deps.terminals.backendFor(runtime) : undefined+ const result = runtime && backend ? write(backend, runtime) : undefined+ return result ?? terminalActionNotStarted('the agent has no pane to write to')+ }+/** See `TerminalStreamManagerDeps.onInput`. A listener's failure is its own: input is never held by it. */private tookInput(state: ActiveStream, typed: boolean, submitted = false): void {try { this.deps.onInput?.(state.agentId, typed, { connId: state.connId, kind: state.client?.kind ?? null,@@ -847,6 +943,8 @@ export class TerminalStreamManager {if (!Number.isSafeInteger(resizeSeq) || resizeSeq <= state.lastResizeSeq || !size) returnstate.lastResizeSeq = resizeSeqstate.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS+ // The size the client asked for, kept even when this pane refuses it: a retarget opens the new pane at it.+ state.size = sizeconst result = await state.handle.resize(size)if (result.state !== 'succeeded') {this.sendError(connId, 'TERMINAL_RESIZE_FAILED', { streamId: state.streamId, message: result.reason })@@ -880,9 +978,17 @@ export class TerminalStreamManager {}state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MSthis.tookInput(state, true)- // Asked again as it lands: a paste takes two tmux processes, and its stream may be closed or taken over- // meanwhile (its close does not wait in the input lane the paste holds). Gone, it has nobody to tell.- const result = await state.handle.pasteRaw(text, () => !state.closing)+ // Held while the agent changes host, in order with its keystrokes (see `input`).+ const gate = this.heldGate(state)+ if (gate) {+ gate.enqueue(state.agentId, () => this.deliverPaste(state, text, true))+ return+ }+ await this.deliverPaste(state, text)+ }++ private async deliverPaste(state: ActiveStream, text: string, held = false): Promise<void> {+ const result = await this.pasteRawTo(state, text, held)if (state.closing) returnif (result.state !== 'succeeded') {this.sendError(state.connId, 'TERMINAL_PASTE_FAILED', { streamId: state.streamId, message: result.reason })@@ -905,7 +1011,7 @@ export class TerminalStreamManager {* the OS clipboard. The client is told which happened (`terminal_paste_image_result`) so it can* show the right feedback instead of a silent difference in behavior.*/- private async pasteImage(state: ActiveStream, bytes: Uint8Array): Promise<void> {+ private async pasteImage(state: ActiveStream, bytes: Uint8Array, held = false): Promise<void> {if (bytes.length === 0) returnstate.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MSlet path: string@@ -922,7 +1028,7 @@ export class TerminalStreamManager {if (clipboard.state === 'written') {// The OS clipboard now owns the bytes — the file was only a hand-off.void unlink(path).catch(() => { /* best effort */ })- const result = await state.handle.writeRaw(CTRL_V_BYTE)+ const result = await this.writeRawTo(state, CTRL_V_BYTE, held)if (result.state !== 'succeeded') {this.sendError(state.connId, 'TERMINAL_PASTE_IMAGE_FAILED', { streamId: state.streamId, message: result.reason })if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state, 'input')@@ -941,9 +1047,7 @@ export class TerminalStreamManager {// still needs the image. Hard-failing here used to freeze the whole session over what is, from// the engine's perspective, just a degraded paste. Fall back to the file's path as ordinary// text, and keep the file: it has to keep resolving after this call returns.- // Asked again as it lands: a paste takes two tmux processes, and its stream may be closed or taken over- // meanwhile (its close does not wait in the input lane the paste holds). Gone, it has nobody to tell.- const result = await state.handle.pasteRaw(path, () => !state.closing)+ const result = await this.pasteRawTo(state, path, held)if (state.closing) returnif (result.state !== 'succeeded') {this.sendError(state.connId, 'TERMINAL_PASTE_IMAGE_FAILED', { streamId: state.streamId, message: result.reason })@@ -966,7 +1070,7 @@ export class TerminalStreamManager {* sends this at all for a genuinely REMOTE pane (a local one pastes its own already-valid path* without ever reaching the wire), so there is no local/remote branch to make here either.*/- private async pasteFile(state: ActiveStream, filename: string, bytes: Uint8Array): Promise<void> {+ private async pasteFile(state: ActiveStream, filename: string, bytes: Uint8Array, held = false): Promise<void> {state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MSlet path: stringtry {@@ -978,9 +1082,7 @@ export class TerminalStreamManager {})return}- // Asked again as it lands: a paste takes two tmux processes, and its stream may be closed or taken over- // meanwhile (its close does not wait in the input lane the paste holds). Gone, it has nobody to tell.- const result = await state.handle.pasteRaw(path, () => !state.closing)+ const result = await this.pasteRawTo(state, path, held)if (state.closing) returnif (result.state !== 'succeeded') {this.sendError(state.connId, 'TERMINAL_PASTE_FILE_FAILED', { streamId: state.streamId, message: result.reason })@@ -1115,11 +1217,13 @@ export class TerminalStreamManager {// always was, and callers/tests comparing against a Uint8Array must not have to know this// path happens to assemble through Buffer internally.const assembled = new Uint8Array(Buffer.concat(pending.chunks.filter((chunk): chunk is Buffer => chunk !== undefined)))- if (kind === TerminalBinaryKind.imagePaste) {- await this.pasteImage(state, assembled)- } else {- await this.pasteFile(state, pending.filename!, assembled)- }+ const deliver = (held: boolean): Promise<void> => kind === TerminalBinaryKind.imagePaste+ ? this.pasteImage(state, assembled, held)+ : this.pasteFile(state, pending.filename!, assembled, held)+ // Held while the agent changes host, in order with its keystrokes (see `input`).+ const gate = this.heldGate(state)+ if (gate) gate.enqueue(state.agentId, () => deliver(true))+ else await deliver(false)}/** Scroll gestures arrive stream-scoped, same as resize — no ordering/seq guard needed since,@@ -1137,10 +1241,18 @@ export class TerminalStreamManager {return}state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS- const result = await state.handle.scroll(direction, lines)- if (result.state !== 'succeeded') {- this.sendError(connId, 'TERMINAL_SCROLL_FAILED', { streamId: state.streamId, message: result.reason })+ const deliver = async (): Promise<void> => {+ // A scroll moves this view's pane only: one whose stream closed during a move has nothing to scroll.+ if (state.closing) return+ const result = await state.handle.scroll(direction, lines)+ if (result.state !== 'succeeded') {+ this.sendError(connId, 'TERMINAL_SCROLL_FAILED', { streamId: state.streamId, message: result.reason })+ }}+ // A scroll writes keys into the pane (PageUp/PageDown), so it waits with the agent's other writes.+ const gate = this.heldGate(state)+ if (gate) gate.enqueue(state.agentId, deliver)+ else await deliver()}private async resyncRequested(connId: string, payload: FramePayload): Promise<void> {@@ -1289,13 +1401,23 @@ export class TerminalStreamManager {* which the snapshot then waits out, or `ended`.*/private async sendKeyframe(- state: ActiveStream, reason: 'open' | 'resize' | 'resync' | 'input' | 'repaint', print?: 'printing' | 'ended',+ state: ActiveStream, reason: 'open' | 'resize' | 'resync' | 'input' | 'repaint' | 'retarget', print?: 'printing' | 'ended',): Promise<void> {if (state.closing || state.resyncing) returnconst startedAt = this.now()+ // The pane this keyframe is taken from. A retarget while it is taken moves the stream to another pane: what+ // this one shows is then not the stream's, and the keyframe is taken again from the new one (`moved`).+ const handle = state.handle+ const moved = (): boolean => {+ if (state.handle === handle) return false+ handle.endSnapshot()+ state.snapshotting = false+ state.resyncing = false+ return true+ }state.resyncing = truestate.snapshotting = true- state.handle.beginSnapshot()+ handle.beginSnapshot()state.output = []state.outputBytes = 0if (state.outputPaused) {@@ -1304,13 +1426,14 @@ export class TerminalStreamManager {state.pausedAt = nullif (state.stallTimer) clearTimeout(state.stallTimer)state.stallTimer = null- const resumed = await state.handle.resumeOutput().catch(() => ({+ const resumed = await handle.resumeOutput().catch(() => ({state: 'failed' as const,dispatch: 'not_started' as const,reason: 'resume failed',}))+ if (moved()) return this.sendKeyframe(state, 'retarget')if (resumed.state !== 'succeeded') {- state.handle.endSnapshot()+ handle.endSnapshot()state.snapshotting = falsestate.resyncing = falsethis.sendError(state.connId, 'TERMINAL_BACKPRESSURE_FAILED', {@@ -1340,7 +1463,7 @@ export class TerminalStreamManager {state.repaintWatchUntil = this.now() + REPAINT_GUARD_MSstate.repaintTail = Buffer.alloc(0)}- snapshot = await state.handle.snapshot(+ snapshot = await handle.snapshot(state.engineId === 'grok' ? { tuiOwnsScrollback: true }: screen ? { conversationHistory: true, ...(repaint ? { repaint } : {}) }: undefined,@@ -1348,8 +1471,9 @@ export class TerminalStreamManager {} catch (error) {snapshot = { state: 'failed', reason: error instanceof Error ? error.message : 'tmux snapshot failed' }}+ if (moved()) return this.sendKeyframe(state, 'retarget')if (snapshot.state !== 'succeeded') {- state.handle.endSnapshot()+ handle.endSnapshot()state.snapshotting = falsestate.resyncing = falsethis.diagnostic(state, 'snapshot_failed', { reason: snapshot.reason })@@ -1358,7 +1482,7 @@ export class TerminalStreamManager {return}if (snapshot.value.bytes.length > KEYFRAME_MAX_BYTES) {- state.handle.endSnapshot()+ handle.endSnapshot()state.snapshotting = falsestate.resyncing = falsethis.diagnostic(state, 'snapshot_too_large', { plainBytes: snapshot.value.bytes.length })@@ -1381,7 +1505,7 @@ export class TerminalStreamManager {bytes: body.bytes,})if (!sent) {- state.handle.endSnapshot()+ handle.endSnapshot()state.snapshotting = falsestate.resyncing = falseawait this.closeStream(state, 'backend disconnected', false)@@ -1410,7 +1534,7 @@ export class TerminalStreamManager {// the viewer while the keyframe was still marked as being taken. The print's keyframe can begin from it here.state.snapshotting = falsestate.resyncing = false- state.handle.endSnapshot()+ handle.endSnapshot()this.flushOutput(state)if (state.pendingBytes > PAUSE_HIGH_WATERMARK_BYTES && !state.outputPaused) void this.pauseOutput(state)}@@ -1584,6 +1708,102 @@ export class TerminalStreamManager {}}+ /**+ * The agents the loopback window on `connId` has on screen; null when it never sent a list (it then+ * counts as looking at all its streams). `[]` is a minimized or tray-hidden window.+ */+ setVisibleAgents(connId: string, agentIds: readonly string[] | null): void {+ if (agentIds === null) this.visibleByConn.delete(connId)+ else this.visibleByConn.set(connId, new Set(agentIds))+ }++ /**+ * Whether a person can see this agent's terminal right now. A `watch: true` stream never counts (no+ * person behind it). A phone or web stream does, including a `takeover: false` neighbour. A loopback+ * window counts when it lists the agent, or never listed anything.+ */+ isLookedAt(agentId: string): boolean {+ // A held agent someone typed into or opened is in use, whether or not a window lists it: the mover reads+ // this on its next tick, and stops before a swap it has not yet begun. The gate forgets it at release.+ if (this.deps.moveGate?.touched(agentId)) return true+ for (const state of this.streams.values()) {+ if (state.agentId !== agentId || state.closing || state.watchOnly) continue+ if (!state.loopback) return true+ const visible = this.visibleByConn.get(state.connId)+ if (!visible || visible.has(agentId)) return true+ }+ return false+ }++ /**+ * Move every open stream of [agentId], of any kind, to the pane [to]: the agent changed host. Each stream is+ * subscribed on `to` through the same coordinator call an open makes, at its own size and mode, and keeps its+ * connection, stream id, lease and seq. The client sees only frames it already knows: a keyframe of the new+ * pane in place of the old one, then the new pane's output. No close, and no new frame type. A stream that+ * cannot follow is closed as a stream whose pane went away is, and its client opens it again.+ */+ async retarget(agentId: string, to: TerminalRuntimeRef): Promise<void> {+ const streams = [...this.streams.values()].filter((state) => state.agentId === agentId && !state.closing)+ if (streams.length === 0) return+ const session = this.deps.resolveAgent(agentId)+ const target = session ? rowOn(session, to) : null+ await Promise.all(streams.map((state) => this.retargetStream(state, target)))+ }++ private async retargetStream(state: ActiveStream, target: RegisteredSession | null): Promise<void> {+ if (!target) {+ await this.closeStream(state, 'the agent is no longer registered', true)+ return+ }+ const subscription = ++state.subscriptions+ let opened: Awaited<ReturnType<TerminalBackendCoordinator['openStream']>>+ try {+ opened = await this.deps.terminals.openStream(target, state.size, {+ onData: (bytes) => { if (state.subscription === subscription) this.onOutput(state, bytes) },+ onClose: (reason) => { if (state.subscription === subscription) void this.closeStream(state, reason, true) },+ }, this.deps.readOnly === true || state.watching)+ } catch (error) {+ opened = { state: 'failed', reason: error instanceof Error ? error.message : String(error) }+ }+ // Closed while the new pane was being opened, or moved again past this one by a later retarget.+ if (state.closing || state.subscription > subscription) {+ if (opened.state === 'succeeded') await opened.value.close().catch(() => { /* best effort */ })+ return+ }+ if (opened.state !== 'succeeded') {+ this.diagnostic(state, 'retarget_failed', { reason: opened.reason })+ await this.closeStream(state, opened.reason, true)+ return+ }+ const previous = state.handle+ const previousPaused = state.outputPaused+ state.subscription = subscription+ state.handle = opened.value+ const placementKey = terminalPlacementKey(opened.value.runtime)+ if (placementKey !== state.placementKey) {+ if (this.controllerByPlacement.get(state.placementKey) === state.ownerId) {+ this.controllerByPlacement.delete(state.placementKey)+ this.controllerByPlacement.set(placementKey, state.ownerId)+ }+ state.placementKey = placementKey+ }+ // The new pane was never paused, and no print after a resize is awaited from it.+ if (state.outputPaused) {+ state.outputPaused = false+ if (state.pausedAt != null) state.pausedMs += Math.max(0, this.now() - state.pausedAt)+ state.pausedAt = null+ if (state.stallTimer) clearTimeout(state.stallTimer)+ state.stallTimer = null+ }+ state.repaintWatchUntil = 0+ state.repaintTail = Buffer.alloc(0)+ this.diagnostic(state, 'retargeted', { watching: state.watching })+ if (previousPaused) await previous.resumeOutput().catch(() => { /* best effort */ })+ await previous.close().catch(() => { /* best effort */ })+ // What the client shows is the old pane's: the keyframe replaces it, and the new pane's output follows it.+ await this.sendKeyframe(state, 'retarget')+ }+private flushWindow(connId: string, agentId: string, loopback: boolean): number {if (!loopback) return OUTPUT_FLUSH_MSconst focused = this.focusByConn.get(connId)@@ -1592,6 +1812,7 @@ export class TerminalStreamManager {async closeConnection(connId: string, reason = 'connection closed', notify = false): Promise<void> {this.focusByConn.delete(connId)+ this.visibleByConn.delete(connId)const states = [...this.streams.values()].filter((state) => state.connId === connId)await Promise.all(states.map((state) => this.closeStream(state, reason, notify)))}@@ -1613,6 +1834,7 @@ export class TerminalStreamManager {async stop(): Promise<void> {clearInterval(this.expiryTimer)this.focusByConn.clear()+ this.visibleByConn.clear()await this.closeAll('terminal manager stopped')}}diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex c50572b03..e5955d552 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -40,6 +40,9 @@ export interface TerminalRootObservation {cwd: string/** Route aliases reported by the backend; never treated as process identity. */aliases?: readonly string[]+ /** The label the pane was created with, where the backend keeps one (the pty host): a move's new pane is told by+ * it (hostMove/moveAgent.ts `removeOrphanMovePanes`). */+ label?: string}export type TerminalInventoryResult =@@ -118,6 +121,9 @@ export interface TerminalCreateRequest extends TerminalDispatchControl {env?: Record<string, string>/** What the pane runs when `command` exits by itself (`TerminalAfterExit`); the pty host's alone. */afterExit?: TerminalAfterExit+ /** Scrollback the new pane starts with (hostMove/seed.ts); the pty host's alone, and only one that lists the `seed`+ * feature: the tmux backend ignores it. */+ seed?: string/** Names this process, and its `afterExit` shell, do not get from the backend's own environment (a grid launch's* provider keys, on Windows: lib/windows/engineStart.ts); the pty host's alone, whose panes inherit the host's* environment. Per launch: the next respawn sends its own. */diff --git a/cli/src/lib/turnActivity.ts b/cli/src/lib/turnActivity.tsindex 721fdb9d2..815ec54cd 100644--- a/cli/src/lib/turnActivity.ts+++ b/cli/src/lib/turnActivity.ts@@ -22,6 +22,10 @@ interface Entry {export const WORK_EVIDENCE_MS = 30_000export const WORK_HEARTBEAT_LEASE_MS = WORK_EVIDENCE_MSconst PROGRESS = new Set(['turn_started', 'text_delta', 'thinking_delta', 'thinking_title', 'tool_start', 'tool_end', 'subagent_finished'])+/** Whether a live event of [type] says the engine is working: a turn starting, or one making progress. */+export function isProgressEvent(type: string): boolean {+ return PROGRESS.has(type)+}export class TurnActivity {private readonly entries = new Map<string, Entry>()diff --git a/cli/src/lib/uninstall/ptyHosts.spec.ts b/cli/src/lib/uninstall/ptyHosts.spec.tsindex 34ef17f31..3a0b2a3f3 100644--- a/cli/src/lib/uninstall/ptyHosts.spec.ts+++ b/cli/src/lib/uninstall/ptyHosts.spec.ts@@ -5,10 +5,10 @@ import { describe, expect, it } from 'vitest'import type { PtyHostDiscovery } from '../ptyHost/client.js'import { endPtyHosts, HOST_EXIT_WAIT_MS, PANE_GRACE_MS, ptyHostsDeps, type HostClient, type PtyHostsDeps } from './ptyHosts.js'-const discovery = (pid: number, protocol = 2): PtyHostDiscovery => ({ protocol, instance: `p${protocol}`, endpoint: 'e', pid, version: '0.5.0', token: 't' })+const discovery = (pid: number, protocol = 2, instance = `p${protocol}`): PtyHostDiscovery => ({ protocol, instance, endpoint: 'e', pid, version: '0.5.0', token: 't' })/** When the record was written, as it was read: after both rows' start markers below. */const WRITTEN = Date.parse('Sun Oct 18 10:00:00 2026')-const rec = (pid: number, protocol = 2, written: number | null = WRITTEN) => ({ discovery: discovery(pid, protocol), written })+const rec = (pid: number, protocol = 2, written: number | null = WRITTEN, instance = `p${protocol}`) => ({ discovery: discovery(pid, protocol, instance), written })const filetime = (ms: number) => `w:${(BigInt(ms) + 11_644_473_600_000n) * 10_000n}`const WIN_HOME = 'C:\\Users\\u\\.harness\\adapters\\pty'@@ -228,7 +228,50 @@ describe('endPtyHosts', () => {})})+describe('endPtyHosts, several instances', () => {+ it('ends a legacy and two versioned hosts of one protocol in one home', async () => {+ const instances = new Map([[101, 'p2'], [102, 'p2-1.0.0'], [103, 'p2-1.1.0']])+ const up = new Set(instances.keys())+ const reached: string[] = []+ const shut: number[] = []+ const t = deps(null, {+ discover: () => [...instances].map(([pid, instance]) => rec(pid, 2, WRITTEN, instance)),+ alive: (pid) => up.has(pid),+ reach: async (instance) => {+ reached.push(instance)+ const pid = [...instances].find(([, name]) => name === instance)![0]+ const h = host([])+ const call = h.client.call+ h.client.call = (async (op: { op: string }) => { if (op.op === 'shutdown') { up.delete(pid); shut.push(pid) } return call(op as never) }) as typeof call+ return { client: h.client }+ },+ })+ expect(await endPtyHosts(t.deps)).toEqual([101, 102, 103].map((pid) => ({ pid, protocol: 2, panes: 0, how: 'shut down' })))+ expect(reached).toEqual(['p2', 'p2-1.0.0', 'p2-1.1.0'])+ expect(shut).toEqual([101, 102, 103])+ })+})+describe('ptyHostsDeps', () => {+ it('lists every instance with its own record time, legacy and versioned', () => {+ const home = mkdtempSync(path.join(tmpdir(), 'pty-hosts-'))+ try {+ mkdirSync(path.join(home, 'run'))+ const names = ['p2', 'p2-1.0.0', 'p2-1.1.0']+ names.forEach((instance, i) => {+ const file = path.join(home, 'run', instance === 'p2' ? 'pty-host-2.json' : `pty-host-${instance}.json`)+ writeFileSync(file, JSON.stringify(discovery(100 + i, 2, instance)))+ const at = new Date(WRITTEN - (i + 1) * 60_000)+ utimesSync(file, at, at)+ })+ const found = ptyHostsDeps(home).discover()+ expect(found.map((r) => r.discovery.instance).sort()).toEqual([...names].sort())+ for (const r of found) expect(r.written).toBe(WRITTEN - (names.indexOf(r.discovery.instance) + 1) * 60_000)+ } finally {+ rmSync(home, { recursive: true, force: true })+ }+ })+it("takes each record's time as it reads the record, so a host that removes its record while it exits is still judged", async () => {const home = mkdtempSync(path.join(tmpdir(), 'pty-hosts-'))try {diff --git a/cli/src/lib/uninstall/ptyHosts.ts b/cli/src/lib/uninstall/ptyHosts.tsindex 38ea839d7..67ad3c1c8 100644--- a/cli/src/lib/uninstall/ptyHosts.ts+++ b/cli/src/lib/uninstall/ptyHosts.ts@@ -14,7 +14,8 @@ import { statSync } from 'node:fs'import path from 'node:path'import { env } from '../../config/env.js'import type { PtyHostClient, PtyHostDiscovery } from '../ptyHost/client.js'-import { discoverHosts, discoveredHostDead, pidAlive, reachPtyHost, type HostLiveness } from '../ptyHost/launch.js'+import { discoveryFileName } from '../ptyHost/instance.js'+import { discoveredHostDead, listDiscoveries, pidAlive, reachPtyHost, type HostLiveness } from '../ptyHost/launch.js'import { SHUTDOWN_PROTOCOL, SUPPORTED_PTY_PROTOCOLS } from '../ptyHost/protocol.js'import { startedNoLaterThan, startMarkerMs } from '../processProof.js'import { argvTokens, processRows, type ProcessRow } from '../processTable.js'@@ -35,7 +36,7 @@ export interface PtyHostsDeps {/** This home's discovery records, each with when it was written as it was read (null when that could not be read):* a host that agreed to shut down removes its record before it exits, and is still judged against it. */discover(): RecordedHost[]- reach(protocol: number): Promise<{ client: HostClient } | { unreachable: string }>+ reach(instance: string): Promise<{ client: HostClient } | { unreachable: string }>alive(pid: number): boolean/** A's proof that the discovery file's host has gone (its pid now belongs to a later process). */dead(discovery: PtyHostDiscovery): Promise<boolean>@@ -65,7 +66,7 @@ export async function endPtyHosts(deps: PtyHostsDeps): Promise<PtyHostEnd[]> {if (!deps.alive(pid) || await deps.dead(discovery)) { ended.push({ pid, protocol, panes: 0, how: 'gone' }); continue }let panes = 0let why: string- const reached = await deps.reach(protocol)+ const reached = await deps.reach(discovery.instance)if ('client' in reached) {const client = reached.clientlet agreed = false@@ -193,12 +194,15 @@ export function ptyHostsDeps(home: string = env.HARNESS_PTY_DIR): PtyHostsDeps {home,discover: () => {// Each record's time before the records: one rewritten in between is judged against the older time, which a- // later host fails, so the error is on the side of leaving it.- const written = new Map(SUPPORTED_PTY_PROTOCOLS.map((protocol) => [protocol, writtenAt(path.join(home, 'run', `pty-host-${protocol}.json`))]))- return discoverHosts(home).map((discovery) => ({ discovery, written: written.get(discovery.protocol) ?? null }))+ // later host fails, so the error is on the side of leaving it. Keyed by instance: a legacy `p2` and any number+ // of versioned `p2-<tag>` hosts of one protocol each have their own record.+ const written = new Map(listDiscoveries(home).map((found) => [found.instance, writtenAt(path.join(home, 'run', discoveryFileName(found.instance) ?? ''))]))+ return listDiscoveries(home)+ .filter((discovery) => SUPPORTED_PTY_PROTOCOLS.includes(discovery.protocol))+ .map((discovery) => ({ discovery, written: written.get(discovery.instance) ?? null }))},- reach: async (protocol) => {- const result = await reachPtyHost(home, protocol, liveness)+ reach: async (instance) => {+ const result = await reachPtyHost(home, instance, liveness)return 'client' in result ? { client: result.client } : { unreachable: 'incompatible' in result ? result.incompatible : result.unavailable }},alive: pidAlive,diff --git a/cli/src/lib/updateCommand.spec.ts b/cli/src/lib/updateCommand.spec.tsnew file mode 100644index 000000000..4dc159380--- /dev/null+++ b/cli/src/lib/updateCommand.spec.ts@@ -0,0 +1,189 @@+/**+ * `harness update`'s steps once the daemon is stopped (./updateCommand.ts `runUpdateSteps`): the terminal host and the+ * CLI, on a temp install root with the real install, canary and staging. The command itself lives in cli.ts and runs as+ * a process that refuses to update from a source checkout, so the order it takes them in is asserted on its source, as+ * cliStopFirst.spec.ts does.+ */+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { PTY_PROTOCOL } from './ptyHost/protocol.js'+import { confirm, stage, type UpdateEntry } from './selfUpdate.js'+import { installPreparedPty, rejectedPtyVersions } from './windows/ptyInstall.js'+import { PTY_PAYLOAD_FILES, type PreparedPty, type PtyEntry } from './windows/ptyPayload.js'+import { runUpdateSteps, type UpdateStepsDeps } from './updateCommand.js'++let root: string+let ptyRoot: string+let bin: string+let cliDir: string+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'update-command-'))+ ptyRoot = join(root, 'runtime', 'pty')+ bin = join(root, 'bin')+ cliDir = join(root, 'cli')+ // The machine as install.ps1 leaves it: host 0.10.0 in use, its two bin files copied out of its folder; CLI 1.0.0.+ mkdirSync(join(ptyRoot, '0.10.0'), { recursive: true })+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.10.0', name), `old ${name}`)+ writeFileSync(join(ptyRoot, 'current-pty'), '0.10.0\r\n')+ mkdirSync(bin)+ for (const name of ['harness.exe', 'harness-launch.exe']) writeFileSync(join(bin, name), `old ${name}`)+ mkdirSync(cliDir)+ writeFileSync(join(cliDir, 'cli.js'), 'console.log("1.0.0")\n')+})+afterEach(() => { rmSync(root, { recursive: true, force: true }) })++const above = PTY_PROTOCOL + 1+const ptyEntry: PtyEntry = { version: '0.11.0', url: 'https://cdn.test/pty.zip', sha256: 'a'.repeat(64), size: 10 }+const cliEntry: UpdateEntry = {+ version: '9.9.9', cli: { url: 'https://cdn.test/cli.js', sha256: 'b'.repeat(64) }, notify: { url: 'https://cdn.test/notify.mjs', sha256: 'c'.repeat(64) },+}+/** A CLI build that needs host protocol [needs], as its `version --json` says through the real canary. */+const cliNeeding = (needs: number) => Buffer.from(+ `console.log(process.argv.includes('--json') ? JSON.stringify({ version: '9.9.9', ptyProtocol: ${needs} }) : '9.9.9')\n`,+)+const pointer = () => readFileSync(join(ptyRoot, 'current-pty'), 'utf8').trim()+const cliOnDisk = () => readFileSync(join(cliDir, 'cli.js'), 'utf8')++/** The steps on the temp root: the downloads in the test's hands, the rest real (macOS's in-place CLI layout). */+function steps(o: { cli?: Buffer | null; hostProtocol?: number; hostReads?: (version: string) => number | null; stage?: UpdateStepsDeps['stage'] } = {}) {+ const lines: string[] = []+ const order: string[] = []+ const hostProtocol = o.hostProtocol ?? 2+ const deps: Partial<UpdateStepsDeps> = {+ downloadCli: async () => ({ cliBuf: o.cli ?? cliNeeding(2), notifyBuf: Buffer.from('export {}\n') }),+ stage: o.stage ?? ((dir, cliBuf, notifyBuf, version) => { order.push('stage cli'); stage(dir, cliBuf, notifyBuf, version, 'darwin') }),+ confirm: (dir) => { order.push('confirm cli'); confirm(dir) },+ // The installed host's `version`: the new folder speaks [hostProtocol], the old one 2.+ readHostProtocol: (binary) => (o.hostReads ? o.hostReads(binary) : binary.includes('0.11.0') ? hostProtocol : 2),+ pty: {+ fetchEntry: async () => ptyEntry,+ prepare: async (entry) => {+ const staging = join(ptyRoot, `.staging-1-${Date.now()}`)+ mkdirSync(staging, { recursive: true })+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(staging, name), `new ${name}`)+ return { version: entry.version, staging, protocol: hostProtocol, features: ['seed'], paired: hostProtocol > PTY_PROTOCOL } satisfies PreparedPty+ },+ install: (prepared, rootDir) => { order.push('install host'); return installPreparedPty(prepared, rootDir) },+ },+ log: (line) => lines.push(line),+ }+ const run = (want: { cli: UpdateEntry | null; pty: PtyEntry | null }) =>+ runUpdateSteps({ cliEntry: want.cli, pty: want.pty, cliDir, ptyRoot: root, currentVersion: '1.0.0', deps })+ return { run, lines, order }+}++/** cli.ts with its comments blanked, and `updateCommand`'s body. */+function updateCommandSource(): string {+ const source = readFileSync(join(import.meta.dirname, '..', 'cli.ts'), 'utf-8')+ .replace(/\/\*[\s\S]*?\*\//g, (match) => ' '.repeat(match.length))+ .replace(/(^|[^:])\/\/[^\n]*/gm, (match, lead: string) => lead + ' '.repeat(match.length - lead.length))+ const from = source.indexOf('async function updateCommand(')+ expect(from).toBeGreaterThan(-1)+ return source.slice(from, source.indexOf('\n}\n', from))+}++describe('harness update', () => {+ it('harness update installs a newer pty payload when the CLI is current', async () => {+ const m = steps()+ expect(await m.run({ cli: null, pty: ptyEntry })).toEqual({ cli: 'none', pty: 'installed' })+ expect(pointer()).toBe('0.11.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ // On the master's probation, as an update the updater staged: the restarted daemon's master judges it.+ expect(JSON.parse(readFileSync(join(ptyRoot, 'pty-pending.json'), 'utf8'))).toEqual({ version: '0.11.0', previous: '0.10.0' })+ expect(m.lines).toEqual(['▸ Updating the terminal host 0.10.0 → 0.11.0…', ' ✓ installed terminal host 0.11.0'])++ // cli.ts: the host is asked about before "Already on the latest version", which a newer host does not reach, and+ // the steps run under the lock, after the stop.+ const text = updateCommandSource()+ const asked = text.indexOf('newerPtyFor(') // cli.ts's wrapper around newerPtyForUpdate, with the manifest url and key+ const latest = text.indexOf('Already on the latest version')+ expect(asked).toBeGreaterThan(-1)+ expect(asked).toBeLessThan(latest)+ expect(text.slice(asked, latest)).toMatch(/if \(!cliEntry && !pty\)/)+ const stop = text.indexOf('stopDaemonOrExit(')+ expect(text.indexOf('runUpdateSteps(')).toBeGreaterThan(stop)+ expect(text.indexOf('withSpawnLock(')).toBeLessThan(stop)+ })++ it('harness update installs a rejected pty version anyway', async () => {+ // The background updater never tries 0.11.0 again on this machine; a person asking by name gets it, as for the CLI.+ writeFileSync(join(ptyRoot, 'pty-rejected.json'), '["0.11.0"]')+ expect(await steps().run({ cli: null, pty: ptyEntry })).toEqual({ cli: 'none', pty: 'installed' })+ expect(pointer()).toBe('0.11.0')+ })++ it('installs the host first, then the CLI, and keeps the CLI build at once when it is not part of a pair', async () => {+ const m = steps()+ expect(await m.run({ cli: cliEntry, pty: ptyEntry })).toEqual({ cli: 'installed', pty: 'installed' })+ expect(m.order).toEqual(['install host', 'stage cli', 'confirm cli'])+ expect(cliOnDisk()).toContain('9.9.9')+ expect(existsSync(join(cliDir, 'update-pending.json'))).toBe(false)+ })++ it('refuses a CLI build that needs a host protocol this machine does not have, and says so', async () => {+ const m = steps({ cli: cliNeeding(above) })+ expect(await m.run({ cli: cliEntry, pty: null })).toEqual({ cli: 'failed', pty: 'none' })+ expect(m.lines).toContain(` ✗ v9.9.9 needs terminal host protocol ${above}; this machine's host speaks 2 — keeping v1.0.0`)+ expect(m.order).toEqual([])+ expect(cliOnDisk()).toContain('1.0.0')+ })++ it('reads a host whose protocol cannot be read as this CLI\'s own, so a build that raises it is refused', async () => {+ // A `harness-pty.exe version` that failed or timed out.+ const m = steps({ cli: cliNeeding(above), hostReads: () => null })+ expect(await m.run({ cli: cliEntry, pty: null })).toEqual({ cli: 'failed', pty: 'none' })+ expect(m.lines).toContain(` ✗ v9.9.9 needs terminal host protocol ${above}; this machine's host speaks ${PTY_PROTOCOL} — keeping v1.0.0`)+ // And with no current-pty at all.+ rmSync(join(ptyRoot, 'current-pty'))+ expect(await steps({ cli: cliNeeding(above) }).run({ cli: cliEntry, pty: null })).toEqual({ cli: 'failed', pty: 'none' })+ })++ it('installs a paired host with the CLI build that needs it, host first, and leaves both on probation', async () => {+ const m = steps({ cli: cliNeeding(above), hostProtocol: above })+ expect(await m.run({ cli: cliEntry, pty: ptyEntry })).toEqual({ cli: 'installed', pty: 'installed' })+ expect(m.order).toEqual(['install host', 'stage cli'])+ expect(pointer()).toBe('0.11.0')+ expect(cliOnDisk()).toContain('9.9.9')+ // Not kept on the spot: the next master judges the pair, and its rollback restores both.+ expect(JSON.parse(readFileSync(join(cliDir, 'update-pending.json'), 'utf8'))).toMatchObject({ version: '9.9.9' })+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(true)+ })++ it('leaves a paired host out when no CLI build being installed needs it', async () => {+ for (const cli of [null, cliEntry]) {+ const m = steps({ cli: cliNeeding(2), hostProtocol: above })+ expect(await m.run({ cli, pty: ptyEntry })).toEqual({ cli: cli ? 'installed' : 'none', pty: 'paired' })+ expect(m.lines).toContain(` terminal host 0.11.0 speaks protocol ${above}, above this CLI's ${PTY_PROTOCOL} — it goes in only with a CLI build that needs it`)+ expect(m.order).not.toContain('install host')+ expect(pointer()).toBe('0.10.0')+ expect(rejectedPtyVersions(root)).toEqual([])+ }+ })++ it('takes a paired host back out when the CLI build it came with cannot be staged', async () => {+ const m = steps({ cli: cliNeeding(above), hostProtocol: above, stage: () => { throw new Error('ENOSPC: no space left on device') } })+ expect(await m.run({ cli: cliEntry, pty: ptyEntry })).toEqual({ cli: 'failed', pty: 'none' })+ expect(pointer()).toBe('0.10.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('old harness.exe')+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ // Nothing was wrong with the host: it is not remembered as rolled back, and pairs with the next build.+ expect(rejectedPtyVersions(root)).toEqual([])+ expect(m.lines).toContain(' ✗ Update failed: ENOSPC: no space left on device')+ expect(m.lines).toContain(' terminal host 0.11.0 taken back out with the build it came with — back to 0.10.0')+ })++ it('off Windows there is no host, and no protocol rule', async () => {+ const lines: string[] = []+ const result = await runUpdateSteps({+ cliEntry, pty: null, cliDir, ptyRoot: null, currentVersion: '1.0.0',+ deps: {+ downloadCli: async () => ({ cliBuf: cliNeeding(above), notifyBuf: Buffer.from('export {}\n') }),+ stage: (dir, cliBuf, notifyBuf, version) => stage(dir, cliBuf, notifyBuf, version, 'darwin'),+ log: (line) => lines.push(line),+ },+ })+ expect(result).toEqual({ cli: 'installed', pty: 'none' })+ })+})diff --git a/cli/src/lib/updateCommand.ts b/cli/src/lib/updateCommand.tsnew file mode 100644index 000000000..7651de04c--- /dev/null+++ b/cli/src/lib/updateCommand.ts@@ -0,0 +1,130 @@+/**+ * `harness update`'s steps once cli.ts has stopped the daemon, under the spawn lock it holds: the terminal host+ * (Windows) and the CLI build, in that order, and under the rules the background updater keeps (spec §5).+ *+ * - The host is downloaded and canaried first, then the CLI build, and only then is anything installed: a paired host+ * (one of a protocol above this CLI's, ./windows/ptyPayload.ts `PreparedPty.paired`) goes in only when the build+ * being installed needs exactly its protocol, which only that build's canary says.+ * - The protocol rule (Windows): a build that needs a host protocol above the one installed, read after the host step+ * so a host that went in now counts, is refused. A person asking by name does not override it, as they do a+ * rolled-back version: the build would come up with no host to open a pane on. A host that cannot be read counts as+ * this CLI's own protocol.+ * - A pair is judged as one: the CLI build is left on probation beside the host (no `confirm`), so the next master+ * keeps or rolls back both. A paired host whose build then fails to go in is taken back out before the relaunch.+ */+import { join } from 'node:path'+import { binaryVersion } from './ptyHost/launch.js'+import { PTY_PROTOCOL } from './ptyHost/protocol.js'+import { confirm, downloadVerified, runCanary, stage, type CanaryResult, type UpdateEntry } from './selfUpdate.js'+import type { PreparedPty, PtyEntry } from './windows/ptyPayload.js'+import { installedPtyProtocol } from './windows/ptyUpdate.js'+import {+ installPtyForUpdate, preparePtyForUpdate, takeBackPtyForUpdate, type PtyUpdateCommandDeps,+} from './windows/ptyUpdateCommand.js'++export interface UpdateStepsDeps {+ downloadCli: (entry: UpdateEntry) => Promise<{ cliBuf: Buffer; notifyBuf: Buffer }>+ canary: (cliBuf: Buffer, dir: string, version: string) => Promise<CanaryResult>+ stage: (dir: string, cliBuf: Buffer, notifyBuf: Buffer, version: string) => void+ /** Keep the build at once (drop its backups): for a build not paired with a host. */+ confirm: (dir: string) => void+ /** `harness-pty.exe version`'s protocol, or null when it cannot be read. */+ readHostProtocol: (binary: string) => number | null+ pty: Partial<PtyUpdateCommandDeps>+ log: (line: string) => void+}++const DEFAULT_DEPS: UpdateStepsDeps = {+ downloadCli: async (entry) => ({ cliBuf: await downloadVerified(entry.cli), notifyBuf: await downloadVerified(entry.notify) }),+ canary: (cliBuf, dir, version) => runCanary(cliBuf, dir, version),+ stage: (dir, cliBuf, notifyBuf, version) => stage(dir, cliBuf, notifyBuf, version),+ confirm: (dir) => confirm(dir),+ readHostProtocol: (binary) => binaryVersion(binary)?.protocol ?? null,+ pty: {},+ log: (line) => console.log(line),+}++export interface UpdateStepsResult {+ cli: 'installed' | 'failed' | 'none'+ /** `paired`: a host only a newer build could use, left out. */+ pty: 'installed' | 'paired' | 'failed' | 'none'+}++const message = (error: unknown): string => (error instanceof Error ? error.message : String(error))++export async function runUpdateSteps(o: {+ /** The newer CLI build, or null when the CLI is current. */+ cliEntry: UpdateEntry | null+ /** The newer host payload (Windows), or null. */+ pty: PtyEntry | null+ cliDir: string+ /** The install root on Windows (`bin\`, `runtime\pty\`); null elsewhere, where there is no host and no rule. */+ ptyRoot: string | null+ /** The build this command runs as, which a failure keeps. */+ currentVersion: string+ deps?: Partial<UpdateStepsDeps>+}): Promise<UpdateStepsResult> {+ const d: UpdateStepsDeps = { ...DEFAULT_DEPS, ...o.deps }+ const ptyDeps: Partial<PtyUpdateCommandDeps> = { ...d.pty, log: d.log }+ const result: UpdateStepsResult = { cli: o.cliEntry ? 'failed' : 'none', pty: 'none' }++ // 1. The host, downloaded and canaried: not installed yet, as a paired one waits for the build's canary.+ let prepared: PreparedPty | null = null+ if (o.pty && o.ptyRoot !== null) {+ prepared = await preparePtyForUpdate(o.pty, { rootDir: o.ptyRoot, deps: ptyDeps })+ if (!prepared) result.pty = 'failed'+ }++ // 2. The CLI build, downloaded and canaried: its canary says the host protocol it needs.+ let build: { entry: UpdateEntry; cliBuf: Buffer; notifyBuf: Buffer; ptyProtocol: number } | null = null+ if (o.cliEntry) {+ d.log(`▸ Updating v${o.currentVersion} → v${o.cliEntry.version}…`)+ try {+ const { cliBuf, notifyBuf } = await d.downloadCli(o.cliEntry)+ const canaried = await d.canary(cliBuf, o.cliDir, o.cliEntry.version)+ if (canaried.ok) build = { entry: o.cliEntry, cliBuf, notifyBuf, ptyProtocol: canaried.ptyProtocol }+ else d.log(` ✗ the new build failed its self-check — keeping v${o.currentVersion}`)+ } catch (error) {+ d.log(` ✗ Update failed: ${message(error)}`)+ }+ }++ // 3. The host goes in first; a paired one only for the build that needs it.+ if (prepared && o.ptyRoot !== null) {+ result.pty = installPtyForUpdate(prepared, { rootDir: o.ptyRoot, cliPtyProtocol: build?.ptyProtocol ?? null, deps: ptyDeps })+ }+ const pairedIn = result.pty === 'installed' && prepared?.paired === true++ // 4. The protocol rule, against the host this build would come up on.+ if (build && o.ptyRoot !== null) {+ const host = installedPtyProtocol(o.ptyRoot, (binary) => {+ const protocol = d.readHostProtocol(binary)+ return protocol === null ? null : { protocol }+ }) ?? PTY_PROTOCOL+ if (build.ptyProtocol > host) {+ d.log(` ✗ v${build.entry.version} needs terminal host protocol ${build.ptyProtocol}; this machine's host speaks ${host} — keeping v${o.currentVersion}`)+ build = null+ }+ }++ // 5. The build. Asked for by name, so a version this machine once rolled back is installed and no longer rejected.+ if (build) {+ try {+ d.stage(o.cliDir, build.cliBuf, build.notifyBuf, build.entry.version)+ // Canary passed and bytes verified: drop the backups, unless it came with a host the next master must judge+ // with it, whose rollback needs them.+ if (!pairedIn) d.confirm(o.cliDir)+ d.log(` ✓ installed v${build.entry.version}`)+ result.cli = 'installed'+ } catch (error) {+ d.log(` ✗ Update failed: ${message(error)}`)+ }+ }++ // 6. A paired host whose build did not go in: the old build relaunched could not use it.+ if (result.cli === 'failed' && pairedIn && o.ptyRoot !== null) {+ takeBackPtyForUpdate(o.ptyRoot, d.log)+ result.pty = 'none'+ }+ return result+}diff --git a/cli/src/lib/windows/engineStart.real.spec.ts b/cli/src/lib/windows/engineStart.real.spec.tsindex ac91cbf16..1cb5156d3 100644--- a/cli/src/lib/windows/engineStart.real.spec.ts+++ b/cli/src/lib/windows/engineStart.real.spec.ts@@ -14,7 +14,7 @@ import { captureLaunchExecutable } from '../../engines/kit/launchExecutable.js'import { inspectNativeLaunch } from '../../engines/nativeLaunch.js'import type { AgentEngine } from '../../engines/types.js'import { PtyHostBackend } from '../ptyHostBackend.js'-import { readDiscovery } from '../ptyHost/launch.js'+import { listDiscoveries } from '../ptyHost/launch.js'import { PTY_PROTOCOL } from '../ptyHost/protocol.js'import { processRows } from '../processTable.js'import { registry, type RegisteredSession } from '../registry.js'@@ -43,7 +43,7 @@ async function withBackend(run: (backend: PtyHostBackend) => Promise<void>): Proif (prepared.state !== 'ready') throw new Error(`the pty host is unavailable: ${prepared.reason}`)await run(backend)} finally {- const discovery = readDiscovery(home, PTY_PROTOCOL)+ const discovery = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)backend.dispose()if (discovery) try { process.kill(discovery.pid) } catch { /* gone */ }removeTree(home)diff --git a/cli/src/lib/windows/launch.real.spec.ts b/cli/src/lib/windows/launch.real.spec.tsindex 0f19c34d9..72cfd4053 100644--- a/cli/src/lib/windows/launch.real.spec.ts+++ b/cli/src/lib/windows/launch.real.spec.ts@@ -7,7 +7,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it } from 'vitest'import { PtyHostBackend } from '../ptyHostBackend.js'-import { readDiscovery } from '../ptyHost/launch.js'+import { listDiscoveries } from '../ptyHost/launch.js'import { PTY_PROTOCOL } from '../ptyHost/protocol.js'import { processRows } from '../processTable.js'import { removeTree } from '../terminalBackend.contract.js'@@ -34,7 +34,7 @@ async function withBackend(run: (backend: PtyHostBackend, scratch: string) => Prif (prepared.state !== 'ready') throw new Error(`the pty host is unavailable: ${prepared.reason}`)await run(backend, scratch)} finally {- const discovery = readDiscovery(home, PTY_PROTOCOL)+ const discovery = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)backend.dispose()if (discovery) try { process.kill(discovery.pid) } catch { /* gone */ }removeTree(home)diff --git a/cli/src/lib/windows/processControl.real.spec.ts b/cli/src/lib/windows/processControl.real.spec.tsindex 5334584ea..d18d72d4c 100644--- a/cli/src/lib/windows/processControl.real.spec.ts+++ b/cli/src/lib/windows/processControl.real.spec.ts@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it } from 'vitest'import { PtyHostBackend } from '../ptyHostBackend.js'-import { readDiscovery } from '../ptyHost/launch.js'+import { listDiscoveries } from '../ptyHost/launch.js'import { PTY_PROTOCOL } from '../ptyHost/protocol.js'import { processRows } from '../processTable.js'import { signalAgentProcess } from '../processSignals.js'@@ -80,7 +80,7 @@ const running = (pid: number): boolean => {} finally {foreign?.kill()backend.dispose()- const pid = readDiscovery(home, PTY_PROTOCOL)?.pid+ const pid = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)?.pidif (pid) {try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }}@@ -124,7 +124,7 @@ const running = (pid: number): boolean => {expect((await backend.kill(pane)).state).toBe('succeeded')} finally {backend.dispose()- const pid = readDiscovery(home, PTY_PROTOCOL)?.pid+ const pid = listDiscoveries(home).findLast((found) => found.protocol === PTY_PROTOCOL)?.pidif (pid) {try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }}diff --git a/cli/src/lib/windows/ptyInstall.spec.ts b/cli/src/lib/windows/ptyInstall.spec.tsnew file mode 100644index 000000000..11125c5b2--- /dev/null+++ b/cli/src/lib/windows/ptyInstall.spec.ts@@ -0,0 +1,495 @@+import { copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { basename, dirname, join } from 'path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { readPointer } from './installLayout.js'+import { PTY_PAYLOAD_FILES, PtyPayloadRefused, type PreparedPty } from './ptyPayload.js'+import {+ confirmPty, installPreparedPty, rejectedPtyVersions, restorePty, sweepAsideFiles, type PtyInstallFs,+} from './ptyInstall.js'++let root: string+let ptyRoot: string+let bin: string+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'pty-install-'))+ ptyRoot = join(root, 'runtime', 'pty')+ bin = join(root, 'bin')+ // The machine as install.ps1 leaves it: 0.10.0 in use, its two bin files copied out of its folder.+ mkdirSync(join(ptyRoot, '0.10.0'), { recursive: true })+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.10.0', name), `old ${name}`)+ writeFileSync(join(ptyRoot, 'current-pty'), '0.10.0\r\n')+ mkdirSync(bin)+ for (const name of ['harness.exe', 'harness-launch.exe']) writeFileSync(join(bin, name), `old ${name}`)+})+afterEach(() => { rmSync(root, { recursive: true, force: true }) })++/** A staging folder as preparePtyPayload leaves it, holding [prefix] in front of each file name. */+function staged(prefix = 'new', version = '0.11.0'): PreparedPty {+ const staging = join(ptyRoot, `.staging-1-${Math.random().toString(36).slice(2)}`)+ mkdirSync(staging)+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(staging, name), `${prefix} ${name}`)+ return { version, staging, protocol: 2, features: ['seed'] }+}++/** Every file under bin\ with its bytes, the marker, the pointer and the pty folder's entries. With [ignoreAside],+ * the `.old-` files are left out: an undo while a new file runs leaves it aside, for the sweep. */+function snapshot(ignoreAside = false) {+ return {+ bin: Object.fromEntries(readdirSync(bin).filter((n) => !ignoreAside || !n.includes('.old-')).sort()+ .map((n) => [n, readFileSync(join(bin, n), 'utf8')])),+ marker: existsSync(join(ptyRoot, 'pty-pending.json')),+ pointer: readFileSync(join(ptyRoot, 'current-pty'), 'utf8'),+ pty: readdirSync(ptyRoot).sort(),+ }+}++const realFs: PtyInstallFs = { rename: renameSync, link: linkSync, copyFile: copyFileSync, writeFile: writeFileSync, rm: rmSync, sleep: () => {} }+const err = (code: string, message = `injected ${code}`) => Object.assign(new Error(message), { code })++/** The calls made, by kind, and the calls that change files, numbered. [failAt] (from 1) throws EIO instead. */+function faulty(failAt: number, base: PtyInstallFs = realFs) {+ let calls = 0+ const log: string[] = []+ // A call that throws is logged with " !failed" after it.+ const step = (entry: string, call: () => void) => {+ log.push(entry)+ try {+ if (++calls === failAt) throw err('EIO', `injected failure at call ${failAt}`)+ call()+ } catch (error) {+ log[log.length - 1] += ' !failed'+ throw error+ }+ }+ const rel = (p: string) => p.slice(root.length + 1)+ const fs: PtyInstallFs = {+ ...base,+ rename: (a, b) => step(`rename ${rel(a)} -> ${rel(b)}`, () => base.rename(a, b)),+ link: (a, b) => step(`link ${rel(a)} -> ${rel(b)}`, () => base.link(a, b)),+ copyFile: (a, b) => step(`copy ${rel(a)} -> ${rel(b)}`, () => base.copyFile(a, b)),+ writeFile: (p, d) => step(`write ${rel(p)}`, () => base.writeFile(p, d)),+ rm: (p, o) => { log.push(`rm ${rel(p)}`); base.rm(p, o) },+ sleep: (ms) => { log.push(`sleep ${ms}`); base.sleep(ms) },+ }+ return { fs, calls: () => calls, log }+}++/** As Windows behaves while every bin file runs: nothing can be renamed over it, though it can be renamed. */+const running: PtyInstallFs = {+ ...realFs,+ rename: (a, b) => {+ if (dirname(b) === bin && existsSync(b)) throw err('EPERM', 'in use')+ renameSync(a, b)+ },+}++/** Each rename of a bin file aside that succeeded is followed at once by a rename in of its replacement (which may+ * fail), with no other call and no sleep between them. */+function expectPairsAdjacent(log: string[]): void {+ log.forEach((entry, i) => {+ const aside = /^rename (bin[\\/][^ ]+) -> bin[\\/][^ ]+\.old-\d+-\d+$/.exec(entry)+ if (!aside) return+ expect(log[i + 1], `after "${entry}"`).toMatch(new RegExp(`^rename .+ -> ${aside[1].replace(/[\\.]/g, '\\$&')}( !failed)?$`))+ })+}++/** The calls a successful install makes when nothing runs, in order; [fatal] says whether a failure there aborts. */+const STEPS: Array<[string, boolean]> = [+ ['rename the staging folder to the version folder', true],+ ['copy harness.exe to its temporary name', true],+ ['link the old harness.exe aside', false],+ ['rename the new harness.exe over it', true],+ ['copy harness-launch.exe to its temporary name', true],+ ['link the old harness-launch.exe aside', false],+ ['rename the new harness-launch.exe over it', true],+ ['write the marker to its temporary name', true],+ ['rename the marker into place', true],+ ['rename current-pty into place', true],+]++describe('installPreparedPty', () => {+ it('installs: folder, bin files, marker, pointer', () => {+ const prepared = staged()+ expect(installPreparedPty(prepared, root, realFs)).toBe(true)+ expect(existsSync(prepared.staging)).toBe(false)+ for (const name of PTY_PAYLOAD_FILES) expect(readFileSync(join(ptyRoot, '0.11.0', name), 'utf8')).toBe(`new ${name}`)+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ expect(readFileSync(join(bin, 'harness-launch.exe'), 'utf8')).toBe('new harness-launch.exe')+ const aside = readdirSync(bin).filter((n) => n !== 'harness.exe' && n !== 'harness-launch.exe').sort()+ expect(aside).toHaveLength(2)+ expect(aside[0]).toMatch(new RegExp(`^harness-launch\\.exe\\.old-${process.pid}-\\d+$`))+ expect(aside[1]).toMatch(new RegExp(`^harness\\.exe\\.old-${process.pid}-\\d+$`))+ expect(JSON.parse(readFileSync(join(ptyRoot, 'pty-pending.json'), 'utf8'))).toEqual({ version: '0.11.0', previous: '0.10.0' })+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.11.0')+ // No temporary file is left behind.+ expect(readdirSync(ptyRoot).sort()).toEqual(['0.10.0', '0.11.0', 'current-pty', 'pty-pending.json'])+ })++ it('puts a bin file in even when there was none before', () => {+ rmSync(join(bin, 'harness.exe'))+ installPreparedPty(staged(), root, realFs)+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ })++ it('makes exactly the calls the failure cases below cover', () => {+ const counter = faulty(0)+ installPreparedPty(staged(), root, counter.fs)+ expect(counter.calls()).toBe(STEPS.length)+ })++ describe('a failure at each step leaves the bin files, the marker and the pointer as they were', () => {+ it.each(STEPS.map(([name, fatal], i) => [i + 1, name, fatal] as const).filter(([, , fatal]) => fatal))(+ 'call %i: %s', (failAt) => {+ const before = snapshot()+ const prepared = staged()+ const error = (() => { try { installPreparedPty(prepared, root, faulty(failAt).fs) } catch (e) { return e } })()+ // An fs failure is rethrown as it was, not as a refusal: it is not the payload's fault.+ expect(error).toMatchObject({ code: 'EIO' })+ expect(error).not.toBeInstanceOf(PtyPayloadRefused)+ expect(snapshot()).toEqual(before)+ expect(existsSync(prepared.staging)).toBe(false)+ },+ )+ })++ it('a link that fails (FAT, or a running image) falls back to the rename-aside pair', () => {+ for (const failAt of [3, 6]) {+ rmSync(join(ptyRoot, '0.11.0'), { recursive: true, force: true })+ rmSync(join(ptyRoot, 'pty-pending.json'), { force: true })+ writeFileSync(join(ptyRoot, 'current-pty'), '0.10.0\r\n')+ const counter = faulty(failAt)+ expect(installPreparedPty(staged(), root, counter.fs)).toBe(true)+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ expect(readFileSync(join(bin, 'harness-launch.exe'), 'utf8')).toBe('new harness-launch.exe')+ expectPairsAdjacent(counter.log)+ expect(counter.log.some((e) => /^rename bin.harness(-launch)?\.exe -> .+\.old-/.test(e))).toBe(true)+ }+ })++ describe('while the old bin files run, Windows-style', () => {+ /** Each bin file now takes copy, link, a refused rename over it, a rename aside and a rename in. */+ const FALLBACK_STEPS: Array<[string, 'fatal' | 'falls back' | 'refused']> = [+ ['rename the staging folder to the version folder', 'fatal'],+ ['copy harness.exe', 'fatal'], ['link harness.exe aside', 'falls back'], ['rename over harness.exe', 'refused'],+ ['rename harness.exe aside', 'fatal'], ['rename harness.exe in', 'fatal'],+ ['copy harness-launch.exe', 'fatal'], ['link harness-launch.exe aside', 'falls back'],+ ['rename over harness-launch.exe', 'refused'], ['rename harness-launch.exe aside', 'fatal'],+ ['rename harness-launch.exe in', 'fatal'],+ ['write the marker', 'fatal'], ['rename the marker', 'fatal'], ['rename current-pty', 'fatal'],+ ]++ it('renames the old files aside instead, as adjacent pairs, and the install completes', () => {+ const counter = faulty(0, running)+ installPreparedPty(staged(), root, counter.fs)+ expect(counter.calls()).toBe(FALLBACK_STEPS.length)+ expectPairsAdjacent(counter.log)+ expect(counter.log.some((e) => e.startsWith('sleep'))).toBe(false)+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ expect(readFileSync(join(bin, 'harness-launch.exe'), 'utf8')).toBe('new harness-launch.exe')+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.11.0')+ // The extra links went; one aside file per bin file holds the old bytes.+ const aside = readdirSync(bin).filter((n) => n.includes('.old-')).map((n) => readFileSync(join(bin, n), 'utf8')).sort()+ expect(aside).toEqual(['old harness-launch.exe', 'old harness.exe'])+ })++ it.each(FALLBACK_STEPS.map(([name, kind], i) => [i + 1, name, kind] as const).filter(([, , kind]) => kind === 'fatal'))(+ 'a failure at call %i (%s) is undone, the undo going through the same pairs', (failAt) => {+ const before = snapshot()+ const counter = faulty(failAt, running)+ expect(() => installPreparedPty(staged(), root, counter.fs)).toThrow('injected failure')+ expect(snapshot(true)).toEqual(before)+ expectPairsAdjacent(counter.log)+ },+ )++ it('a rename-in refused for a moment puts the old file back, waits with it in place, and tries the pair again', () => {+ let refusals = 1+ const fs: PtyInstallFs = {+ ...running,+ rename: (a, b) => {+ if (basename(a).includes('.new-') && basename(b) === 'harness.exe' && !existsSync(b) && refusals-- > 0) {+ throw err('EBUSY', 'held by a scan')+ }+ running.rename(a, b)+ },+ }+ const counter = faulty(0, fs)+ installPreparedPty(staged(), root, counter.fs)+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ const firstAside = counter.log.findIndex((e) => /^rename bin.harness\.exe -> .+\.old-/.test(e))+ // aside, refused rename-in, put back, sleep, then the pair again.+ expect(counter.log.slice(firstAside + 2, firstAside + 4)).toEqual([+ expect.stringMatching(/^rename .+\.old-\d+-\d+ -> bin.harness\.exe$/), expect.stringMatching(/^sleep /),+ ])+ expectPairsAdjacent(counter.log)+ })++ it('a put-back that fails once is retried, and the path is never left missing', () => {+ let putBackFailures = 1+ const fs: PtyInstallFs = {+ ...running,+ rename: (a, b) => {+ if (basename(a).includes('.new-') && basename(b) === 'harness.exe' && !existsSync(b)) throw err('EIO', 'disk error')+ if (basename(a).startsWith('harness.exe.old-') && putBackFailures-- > 0) throw err('EBUSY', 'held')+ running.rename(a, b)+ },+ }+ const before = snapshot()+ expect(() => installPreparedPty(staged(), root, fs)).toThrow('disk error')+ expect(snapshot(true)).toEqual(before)+ })++ it('a put-back that keeps failing leaves the undo to restore the file', () => {+ let putBackFailures = 5+ const fs: PtyInstallFs = {+ ...running,+ rename: (a, b) => {+ if (basename(a).includes('.new-') && basename(b) === 'harness-launch.exe' && !existsSync(b)) throw err('EIO', 'disk error')+ if (basename(a).startsWith('harness-launch.exe.old-') && putBackFailures-- > 0) throw err('EBUSY', 'held')+ running.rename(a, b)+ },+ }+ const before = snapshot()+ const error = (() => { try { installPreparedPty(staged(), root, fs) } catch (e) { return e } })()+ // The put-back failure is thrown, with the rename-in failure behind it.+ expect(error).toMatchObject({ code: 'EBUSY', message: 'held', cause: { code: 'EIO', message: 'disk error' } })+ expect(snapshot(true)).toEqual(before)+ })++ /** During a restore: harness.exe's rename-in fails, and the next [putBackFailures] renames of its aside file too. */+ function restoreFailing(putBackFailures: number): PtyInstallFs {+ return {+ ...running,+ rename: (a, b) => {+ if (basename(a).includes('.new-') && basename(b) === 'harness.exe' && !existsSync(b)) throw err('EIO', 'disk error')+ if (basename(a).startsWith('harness.exe.old-') && basename(b) === 'harness.exe' && putBackFailures-- > 0) throw err('EBUSY', 'held')+ running.rename(a, b)+ },+ }+ }++ it('a restore whose rename-in and every put-back fail has the undo put the current file back, and says kept', () => {+ installPreparedPty(staged(), root, running)+ // putBack's five attempts all fail; the undo's rename then succeeds.+ expect(restorePty(root, restoreFailing(5))).toEqual({ found: true, pointer: true, restored: ['harness-launch.exe'], kept: ['harness.exe'], missing: [] })+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ expect(readFileSync(join(bin, 'harness-launch.exe'), 'utf8')).toBe('old harness-launch.exe')+ })++ it('a restore that can put nothing back reports the path missing, not kept', () => {+ installPreparedPty(staged(), root, running)+ expect(restorePty(root, restoreFailing(Infinity))).toEqual({ found: true, pointer: true, restored: ['harness-launch.exe'], kept: [], missing: ['harness.exe'] })+ expect(existsSync(join(bin, 'harness.exe'))).toBe(false)+ // Its bytes are still there, under an aside name.+ expect(readdirSync(bin).some((n) => n.startsWith('harness.exe.old-') && readFileSync(join(bin, n), 'utf8') === 'new harness.exe')).toBe(true)+ })++ it('restorePty puts the old files back the same way', () => {+ installPreparedPty(staged(), root, running)+ expect(restorePty(root, running)).toEqual({ found: true, pointer: true, restored: ['harness.exe', 'harness-launch.exe'], kept: [], missing: [] })+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('old harness.exe')+ expect(readFileSync(join(bin, 'harness-launch.exe'), 'utf8')).toBe('old harness-launch.exe')+ })+ })++ it('an existing version folder is reused only when it matches', () => {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.11.0', name), `new ${name}`)+ const prepared = staged()+ expect(installPreparedPty(prepared, root, realFs)).toBe(true)+ expect(existsSync(prepared.staging)).toBe(false)+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.11.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ })++ it('a reused version folder survives a later failure', () => {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.11.0', name), `new ${name}`)+ const before = snapshot()+ // The reuse makes no rename, so the last call (the pointer) is one earlier.+ expect(() => installPreparedPty(staged(), root, faulty(STEPS.length - 1).fs)).toThrow('injected failure')+ expect(snapshot()).toEqual(before)+ expect(readdirSync(join(ptyRoot, '0.11.0')).sort()).toEqual([...PTY_PAYLOAD_FILES].sort())+ })++ it('refused when it differs', () => {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.11.0', name), `other ${name}`)+ const before = snapshot()+ const prepared = staged()+ expect(() => installPreparedPty(prepared, root, realFs)).toThrow(PtyPayloadRefused)+ expect(snapshot()).toEqual(before)+ expect(existsSync(prepared.staging)).toBe(false)+ expect(readFileSync(join(ptyRoot, '0.11.0', 'harness.exe'), 'utf8')).toBe('other harness.exe')+ })++ it('refused when the existing folder lacks a file', () => {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES.slice(1)) writeFileSync(join(ptyRoot, '0.11.0', name), `new ${name}`)+ expect(() => installPreparedPty(staged(), root, realFs)).toThrow(PtyPayloadRefused)+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.10.0')+ })++ it('refuses a version launch.ts could not read', () => {+ for (const version of ['0.11.0-beta', 'v0.11.0', '..', '']) {+ const before = snapshot()+ expect(() => installPreparedPty(staged('new', version), root, realFs)).toThrow(PtyPayloadRefused)+ expect(snapshot()).toEqual(before)+ }+ })++ it('a plain error, not a refusal, with no installed version to roll back to', () => {+ rmSync(join(ptyRoot, 'current-pty'))+ const prepared = staged()+ const error = (() => { try { installPreparedPty(prepared, root, realFs) } catch (e) { return e } })()+ expect(error).toBeInstanceOf(Error)+ expect(error).not.toBeInstanceOf(PtyPayloadRefused)+ expect(existsSync(join(ptyRoot, 'current-pty'))).toBe(false)+ expect(existsSync(join(ptyRoot, '0.11.0'))).toBe(false)+ expect(existsSync(prepared.staging)).toBe(false)+ })++ it('a plain error, changing nothing, while a version is still on probation', () => {+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.10.0', previous: '0.9.0' }))+ const before = snapshot()+ const error = (() => { try { installPreparedPty(staged(), root, realFs) } catch (e) { return e } })()+ expect(error).toBeInstanceOf(Error)+ expect(error).not.toBeInstanceOf(PtyPayloadRefused)+ expect(snapshot()).toEqual(before)+ })++ it('returns false and only drops the staging folder when current-pty already names the version', () => {+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0\r\n')+ const before = snapshot()+ const prepared = staged()+ expect(installPreparedPty(prepared, root, realFs)).toBe(false)+ expect(snapshot()).toEqual(before)+ expect(existsSync(prepared.staging)).toBe(false)+ })++ it('a staging folder that will not delete does not replace the real error', () => {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.11.0', name), `other ${name}`)+ const fs: PtyInstallFs = { ...realFs, rm: (p, o) => { if (p.includes('.staging-')) throw err('EBUSY'); rmSync(p, o) } }+ expect(() => installPreparedPty(staged(), root, fs)).toThrow(PtyPayloadRefused)+ })+})++describe('restorePty', () => {+ it('restorePty puts the pointer and the bin files back, rejects the version, and keeps the folder', () => {+ installPreparedPty(staged(), root, realFs)+ expect(restorePty(root)).toEqual({ found: true, pointer: true, restored: ['harness.exe', 'harness-launch.exe'], kept: [], missing: [] })+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.10.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('old harness.exe')+ expect(readFileSync(join(bin, 'harness-launch.exe'), 'utf8')).toBe('old harness-launch.exe')+ expect(rejectedPtyVersions(root)).toEqual(['0.11.0'])+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(readdirSync(join(ptyRoot, '0.11.0')).sort()).toEqual([...PTY_PAYLOAD_FILES].sort())+ })++ it('keeps the current bin file for one the previous version lacks', () => {+ installPreparedPty(staged(), root, realFs)+ rmSync(join(ptyRoot, '0.10.0', 'harness-launch.exe'))+ expect(restorePty(root)).toEqual({ found: true, pointer: true, restored: ['harness.exe'], kept: ['harness-launch.exe'], missing: [] })+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.10.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('old harness.exe')+ expect(readFileSync(join(bin, 'harness-launch.exe'), 'utf8')).toBe('new harness-launch.exe')+ expect(rejectedPtyVersions(root)).toEqual(['0.11.0'])+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ })++ it('with the previous folder gone, rejects the version and leaves the pointer and bin files', () => {+ installPreparedPty(staged(), root, realFs)+ rmSync(join(ptyRoot, '0.10.0'), { recursive: true })+ expect(restorePty(root)).toEqual({ found: true, pointer: false, restored: [], kept: ['harness.exe', 'harness-launch.exe'], missing: [] })+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.11.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ expect(rejectedPtyVersions(root)).toEqual(['0.11.0'])+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ // Nothing is left to try again.+ expect(restorePty(root).found).toBe(false)+ })++ it('records the rejection before it touches the bin files', () => {+ installPreparedPty(staged(), root, realFs)+ const counter = faulty(0)+ restorePty(root, counter.fs)+ const record = counter.log.findIndex((e) => e.includes('pty-rejected.json'))+ const firstBin = counter.log.findIndex((e) => /bin[\\/]/.test(e))+ expect(record).toBeGreaterThanOrEqual(0)+ expect(record).toBeLessThan(firstBin)+ })++ it('a bin file Windows will not take is kept, and the restore still completes', () => {+ installPreparedPty(staged(), root, realFs)+ const fs: PtyInstallFs = { ...realFs, copyFile: () => { throw err('EIO') } }+ expect(restorePty(root, fs)).toEqual({ found: true, pointer: true, restored: [], kept: ['harness.exe', 'harness-launch.exe'], missing: [] })+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ })++ it('adds to the rejected list without repeating a version', () => {+ writeFileSync(join(ptyRoot, 'pty-rejected.json'), JSON.stringify(['0.9.0', '0.11.0']))+ installPreparedPty(staged(), root, realFs)+ restorePty(root)+ expect(rejectedPtyVersions(root)).toEqual(['0.9.0', '0.11.0'])+ })++ it('restorePty with no marker changes nothing', () => {+ const before = snapshot()+ expect(restorePty(root).found).toBe(false)+ expect(snapshot()).toEqual(before)+ expect(rejectedPtyVersions(root)).toEqual([])+ })++ it('a marker that names a path outside pty\\ restores nothing', () => {+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '..' }))+ const before = snapshot()+ expect(restorePty(root).found).toBe(false)+ expect(snapshot()).toEqual(before)+ })+})++describe('confirmPty', () => {+ it('confirmPty removes the marker', () => {+ installPreparedPty(staged(), root, realFs)+ confirmPty(root)+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(readPointer(ptyRoot, 'current-pty')).toBe('0.11.0')+ expect(restorePty(root).found).toBe(false)+ })+})++describe('rejectedPtyVersions', () => {+ it('is empty when the file is missing or malformed', () => {+ expect(rejectedPtyVersions(root)).toEqual([])+ writeFileSync(join(ptyRoot, 'pty-rejected.json'), '{not json')+ expect(rejectedPtyVersions(root)).toEqual([])+ writeFileSync(join(ptyRoot, 'pty-rejected.json'), JSON.stringify(['0.9.0', 7]))+ expect(rejectedPtyVersions(root)).toEqual(['0.9.0'])+ })+})++describe('sweepAsideFiles', () => {+ it('sweepAsideFiles deletes what it can', () => {+ const leftovers = ['harness.exe.old-1-1', 'harness-launch.exe.old-1-2', '.harness.exe.old-3-4', '.harness.exe.new-5-6', 'harness.exe~RF1a2b.TMP']+ for (const n of leftovers) writeFileSync(join(bin, n), n)+ // A file still running cannot be deleted on Windows; the injected rm stands in for that here.+ const fs: PtyInstallFs = {+ ...realFs,+ rm: (p, o) => {+ if (p.endsWith('harness-launch.exe.old-1-2')) throw err('EPERM', 'busy')+ rmSync(p, o)+ },+ }+ expect(sweepAsideFiles(root, fs)).toBe(1)+ expect(readdirSync(bin).sort()).toEqual(['harness-launch.exe', 'harness-launch.exe.old-1-2', 'harness.exe'])+ expect(sweepAsideFiles(root)).toBe(0)+ expect(readdirSync(bin).sort()).toEqual(['harness-launch.exe', 'harness.exe'])+ })++ it('is zero with no bin folder', () => {+ rmSync(bin, { recursive: true })+ expect(sweepAsideFiles(root)).toBe(0)+ })+})diff --git a/cli/src/lib/windows/ptyInstall.ts b/cli/src/lib/windows/ptyInstall.tsnew file mode 100644index 000000000..b2981b5c5--- /dev/null+++ b/cli/src/lib/windows/ptyInstall.ts@@ -0,0 +1,398 @@+/**+ * Putting a prepared PTY payload (ptyPayload.ts) in use, and taking it back out (spec §3, "How a payload is+ * installed" and "Rollback"). The layout is installLayout.ts's:+ *+ * <root>\bin\harness.exe, harness-launch.exe copies out of the version folder in use+ * <root>\runtime\pty\<version>\ the six payload files, never replaced once complete+ * <root>\runtime\pty\current-pty the version in use (ptyHost/launch.ts currentPtyVersion)+ * <root>\runtime\pty\pty-pending.json { version, previous } while the new version is on probation+ * <root>\runtime\pty\pty-rejected.json versions rolled back on this machine, never tried again+ *+ * Windows cannot overwrite or delete a running .exe, but it can rename one. So a bin file is never written in place:+ * the old one is kept aside as `<name>.old-<pid>-<ms>` and the new one is renamed in (putInPlace); the aside files+ * are swept once nothing runs them. Nothing here calls a Windows API, so it is tested on every OS.+ */+import { copyFileSync, existsSync, linkSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { basename, dirname, join } from 'node:path'+import { VERSION_DIR } from '../ptyHost/launch.js'+import { isSingleSegment, readPointer, writePointer } from './installLayout.js'+import { PTY_PAYLOAD_FILES, PtyPayloadRefused, type PreparedPty } from './ptyPayload.js'++export const PTY_POINTER = 'current-pty'+export const PTY_PENDING = 'pty-pending.json'+export const PTY_REJECTED = 'pty-rejected.json'+/** The bin files that come out of the payload, in the order they are replaced. */+export const BIN_FILES = ['harness.exe', 'harness-launch.exe'] as const+/** What a sweep of bin\ removes: our aside files and install.ps1's (`.<name>.old-*`), our temporary copies, and the+ * `<name>~RF<hex>.TMP` backups that File.Replace leaves when install.ps1 replaces a running program. */+const SWEPT = [/\.old-/, /^\..+\.new-\d+-\d+$/, /~RF.*\.TMP$/i]++/** The calls that change files, so the tests can make any one of them fail. */+export interface PtyInstallFs {+ rename: (from: string, to: string) => void+ link: (existing: string, newPath: string) => void+ copyFile: (from: string, to: string) => void+ writeFile: (path: string, data: string) => void+ rm: (path: string, options?: { recursive?: boolean; force?: boolean }) => void+ sleep: (ms: number) => void+}++export const defaultPtyInstallFs: PtyInstallFs = {+ rename: renameSync,+ link: linkSync,+ copyFile: copyFileSync,+ writeFile: writeFileSync,+ rm: rmSync,+ // Synchronous on purpose, as in installLayout.ts: the caller holds the spawn lock and is synchronous.+ sleep: (ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) },+}++/**+ * The codes Windows gives while a file is held: by an antivirus scan or the indexer for a moment, or, for a rename+ * over a program, for as long as it runs. Waiting can fix those, and nothing else.+ */+const RETRIED = new Set(['EPERM', 'EBUSY', 'EACCES'])+const ATTEMPTS = 5+const codeOf = (error: unknown) => (error as NodeJS.ErrnoException)?.code ?? ''+const backoff = (attempt: number) => 25 * 2 ** (attempt - 1)++function renameRetrying(fs: PtyInstallFs, from: string, to: string): void {+ for (let attempt = 1; ; attempt++) {+ try {+ fs.rename(from, to)+ return+ } catch (error) {+ if (!RETRIED.has(codeOf(error)) || attempt >= ATTEMPTS) throw error+ fs.sleep(backoff(attempt))+ }+ }+}++function tryRm(fs: PtyInstallFs, path: string, options: { recursive?: boolean; force?: boolean } = { force: true }): void {+ try { fs.rm(path, options) } catch { /* a running file on Windows: swept later */ }+}++const ptyRootOf = (rootDir: string) => join(rootDir, 'runtime', 'pty')++/** `<dir>\<stem>-<pid>-<ms>`, not taken yet: two replacements of one file within a millisecond must not meet. */+function freshName(dir: string, stem: string): string {+ for (let ms = Date.now(); ; ms++) {+ const candidate = join(dir, `${stem}-${process.pid}-${ms}`)+ if (!existsSync(candidate)) return candidate+ }+}++/** What [putInPlace] did, so it can be undone: where the old file went (null when there was none). */+interface Replaced { target: string; aside: string | null }++/**+ * After a failed rename-in, the old file goes straight back. Any error is retried here (bounded): a target left+ * missing while its bytes sit under an `.old-` name is the one outcome that is not allowed.+ */+function putBack(fs: PtyInstallFs, aside: string, target: string): void {+ for (let attempt = 1; ; attempt++) {+ try {+ fs.rename(aside, target)+ return+ } catch (error) {+ if (attempt >= ATTEMPTS) throw error+ fs.sleep(backoff(attempt))+ }+ }+}++/**+ * Rename the old [target] aside and [ready] in, as one unit: nothing runs between the two renames, so the path is+ * missing only for that moment. A failed rename-in puts the old file back at once; any wait happens with it in+ * place, and then the pair is tried again. The entry is in [done] across the gap, so if even the put-back fails,+ * the caller's undo still knows where the old file is.+ */+function swapPair(fs: PtyInstallFs, ready: string, target: string, aside: string, done: Replaced[]): void {+ for (let attempt = 1; ; attempt++) {+ try {+ fs.rename(target, aside)+ } catch (error) {+ if (!RETRIED.has(codeOf(error)) || attempt >= ATTEMPTS) throw error+ fs.sleep(backoff(attempt))+ continue+ }+ const entry: Replaced = { target, aside }+ done.push(entry)+ try {+ fs.rename(ready, target)+ return+ } catch (error) {+ try {+ putBack(fs, aside, target)+ } catch (putBackError) {+ // The put-back failure is what is thrown; the rename-in failure that led to it stays readable.+ throw Object.assign(putBackError as Error, { cause: error })+ }+ done.splice(done.indexOf(entry), 1)+ if (!RETRIED.has(codeOf(error)) || attempt >= ATTEMPTS) throw error+ fs.sleep(backoff(attempt))+ }+ }+}++/**+ * Put [ready] (a file already in bin\) at `<bin>\<name>`. When there is no old file, a plain rename. Otherwise one+ * rename over the old file first, which keeps the path answering throughout; with [keepOld] the old file first gets+ * a second name (a hard link, the aside file the undo needs). Windows refuses that rename while the old file runs,+ * and a link fails on FAT or for a running image: then [swapPair].+ */+function putInPlace(fs: PtyInstallFs, ready: string, bin: string, name: string, done: Replaced[], keepOld: boolean): void {+ const target = join(bin, name)+ if (!existsSync(target)) {+ renameRetrying(fs, ready, target)+ done.push({ target, aside: null })+ return+ }+ if (keepOld) {+ const link = freshName(bin, `${name}.old`)+ let linked = false+ try {+ fs.link(target, link)+ linked = true+ } catch { /* no second name here; the pair keeps the old file instead */ }+ if (linked) {+ try {+ fs.rename(ready, target)+ done.push({ target, aside: link })+ return+ } catch (error) {+ tryRm(fs, link)+ if (!RETRIED.has(codeOf(error))) throw error+ }+ }+ } else {+ try {+ fs.rename(ready, target)+ return+ } catch (error) {+ if (!RETRIED.has(codeOf(error))) throw error+ }+ }+ swapPair(fs, ready, target, freshName(bin, `${name}.old`), done)+}++/** Copy [source] to a temporary name in bin\ (before any rename touches the path), then [putInPlace]. */+function replaceBinFile(fs: PtyInstallFs, source: string, bin: string, name: string, done: Replaced[]): void {+ const temporary = freshName(bin, `.${name}.new`)+ try {+ fs.copyFile(source, temporary)+ putInPlace(fs, temporary, bin, name, done, true)+ } finally {+ tryRm(fs, temporary)+ }+}++/** Undo one [putInPlace]: the old file goes back the same way the new one came in, since the new one may run now. */+function undoReplaced(fs: PtyInstallFs, { target, aside }: Replaced): void {+ const bin = dirname(target)+ if (aside) return putInPlace(fs, aside, bin, basename(target), [], false)+ try {+ fs.rm(target, { force: true })+ } catch {+ // A new file someone already runs cannot be deleted on Windows; moved aside, it is swept later.+ fs.rename(target, freshName(bin, `${basename(target)}.old`))+ }+}++/** Write [path] whole or not at all: a reader never sees half a marker. */+function writeJson(fs: PtyInstallFs, path: string, value: unknown): void {+ const temporary = freshName(dirname(path), `.${basename(path)}.tmp`)+ try {+ fs.writeFile(temporary, JSON.stringify(value))+ renameRetrying(fs, temporary, path)+ } finally {+ tryRm(fs, temporary)+ }+}++function sameFiles(a: string, b: string): boolean {+ return PTY_PAYLOAD_FILES.every((name) => {+ try {+ return readFileSync(join(a, name)).equals(readFileSync(join(b, name)))+ } catch {+ return false+ }+ })+}++/** Run every undo step, even after one fails: each one left undone is a file out of place. */+function undoAll(steps: Array<() => void>): void {+ for (const step of [...steps].reverse()) {+ try { step() } catch { /* best effort; the original failure is what the caller hears */ }+ }+}++/**+ * Put [prepared] in use. The caller holds the daemon spawn lock. In order: the staging folder becomes+ * `<runtime>\pty\<version>\`; `bin\harness.exe` then `bin\harness-launch.exe` are replaced; `pty-pending.json`+ * records `{ version, previous }`; `current-pty` names the new version. A failure at any step undoes the steps+ * before it (the old bin files go back, the marker goes, the pointer is never moved) and is rethrown as it was.+ * Only content is refused ([PtyPayloadRefused]): a version launch.ts cannot read, or an existing version folder+ * with other files. Returns false, having done nothing, when `current-pty` already names the version (another+ * installer got there first). The staging folder is gone afterwards, whatever happened.+ */+export function installPreparedPty(prepared: PreparedPty, rootDir: string, fs: PtyInstallFs = defaultPtyInstallFs): boolean {+ const ptyRoot = ptyRootOf(rootDir)+ const bin = join(rootDir, 'bin')+ const { version, staging } = prepared+ const versionDir = join(ptyRoot, version)+ const undo: Array<() => void> = []+ try {+ if (!VERSION_DIR.test(version)) throw new PtyPayloadRefused(`version ${JSON.stringify(version)} is not a version folder name`)+ // A version still on probation must be confirmed or rolled back first: its marker names the one to go back to.+ if (existsSync(join(ptyRoot, PTY_PENDING))) throw new Error(`a pty version is still on probation (${PTY_PENDING})`)+ // Without a version to go back to, probation could not roll the new one back.+ const previous = readPointer(ptyRoot, PTY_POINTER)+ if (previous === null) throw new Error('no installed pty version to roll back to')+ if (previous === version) return false++ // 1. The version folder. A complete one is never replaced: a host may run from it.+ if (existsSync(versionDir)) {+ if (!sameFiles(versionDir, staging)) throw new PtyPayloadRefused(`${versionDir} exists with other files`)+ } else {+ renameRetrying(fs, staging, versionDir)+ // Back to the staging name first, so a folder that half fails to delete is never taken for a complete one.+ undo.push(() => { fs.rename(versionDir, staging) })+ }++ // 2. The bin files.+ const replaced: Replaced[] = []+ undo.push(() => { undoAll(replaced.map((entry) => () => undoReplaced(fs, entry))) })+ for (const name of BIN_FILES) replaceBinFile(fs, join(versionDir, name), bin, name, replaced)++ // 3. The probation marker.+ const marker = join(ptyRoot, PTY_PENDING)+ undo.push(() => { fs.rm(marker, { force: true }) })+ writeJson(fs, marker, { version, previous })++ // 4. The pointer, last: it is what makes the version the one in use.+ writePointer(ptyRoot, PTY_POINTER, version, { rename: fs.rename, sleep: fs.sleep })+ return true+ } catch (error) {+ undoAll(undo)+ throw error+ } finally {+ // A just-run canary can hold a file for a moment; a failed delete must not replace the real outcome.+ tryRm(fs, staging, { recursive: true, force: true })+ }+}++export interface PtyPending { version: string; previous: string }+type Pending = PtyPending++/** The version on probation and the one it replaced, or null when none is (or its marker cannot be read). */+export function readPtyPending(rootDir: string): PtyPending | null {+ return readPending(ptyRootOf(rootDir))+}++function readPending(ptyRoot: string): Pending | null {+ try {+ const value = JSON.parse(readFileSync(join(ptyRoot, PTY_PENDING), 'utf8')) as Partial<Pending>+ if (typeof value?.version !== 'string' || !isSingleSegment(value.version)) return null+ if (typeof value.previous !== 'string' || !isSingleSegment(value.previous)) return null+ return { version: value.version, previous: value.previous }+ } catch {+ return null+ }+}++export interface PtyRestore {+ /** There was a version on probation, and it is now rejected and its marker gone. */+ found: boolean+ /** `current-pty` names the previous version again. */+ pointer: boolean+ /** The bin files copied back from the previous version. */+ restored: string[]+ /** The bin files left as they were: missing from the previous version, or a copy back that failed and was undone. */+ kept: string[]+ /** The bin files whose copy back failed and whose undo failed too: the path is missing, and its last bytes sit in+ * a `bin\<name>.old-*` file. The caller must put one back before a sweep. */+ missing: string[]+}++/**+ * Roll a version on probation back. The rejection is recorded first. `current-pty` names `previous` again when its+ * host is still there, and each bin file `previous` still has is copied back the rename-aside way; a missing one+ * keeps the current file. The version folder stays; a host may still run from it (spec §3 removes it later). Only a+ * failed pointer or record write throws, and a retry repeats nothing that took: a restore never sticks on a+ * version folder that is gone or incomplete.+ */+export function restorePty(rootDir: string, fs: PtyInstallFs = defaultPtyInstallFs): PtyRestore {+ const ptyRoot = ptyRootOf(rootDir)+ const result: PtyRestore = { found: false, pointer: false, restored: [], kept: [], missing: [] }+ const pending = readPending(ptyRoot)+ if (!pending) return result+ const previousDir = join(ptyRoot, pending.previous)+ const has = (name: string) => existsSync(join(previousDir, name))++ const rejected = rejectedPtyVersions(rootDir)+ if (!rejected.includes(pending.version)) writeJson(fs, join(ptyRoot, PTY_REJECTED), [...rejected, pending.version])++ if (has('harness-pty.exe')) {+ writePointer(ptyRoot, PTY_POINTER, pending.previous, { rename: fs.rename, sleep: fs.sleep })+ result.pointer = true+ }+ const bin = join(rootDir, 'bin')+ for (const name of BIN_FILES) {+ if (!has(name)) { result.kept.push(name); continue }+ const done: Replaced[] = []+ try {+ replaceBinFile(fs, join(previousDir, name), bin, name, done)+ result.restored.push(name)+ } catch {+ // Swallowed so a restore never sticks, but only once the current file is back where it was, if it can be.+ undoAll(done.map((entry) => () => undoReplaced(fs, entry)))+ ;(existsSync(join(bin, name)) ? result.kept : result.missing).push(name)+ }+ }+ fs.rm(join(ptyRoot, PTY_PENDING), { force: true })+ result.found = true+ return result+}++/** The version on probation came back healthy: it stays. */+export function confirmPty(rootDir: string, fs: PtyInstallFs = defaultPtyInstallFs): void {+ fs.rm(join(ptyRootOf(rootDir), PTY_PENDING), { force: true })+}++/** The versions rolled back on this machine. A missing or unreadable list is empty. */+export function rejectedPtyVersions(rootDir: string): string[] {+ try {+ const value: unknown = JSON.parse(readFileSync(join(ptyRootOf(rootDir), PTY_REJECTED), 'utf8'))+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []+ } catch {+ return []+ }+}++/**+ * Delete the leftovers in bin\: `*.old-*` aside files (ours and install.ps1's `.<name>.old-*`), `.<name>.new-*`+ * temporary copies of an interrupted install, and install.ps1's `*~RF*.TMP`. One that is still running cannot be+ * deleted on Windows and is left for the next sweep. Returns how many are left. The caller holds the daemon spawn+ * lock: an install's `.new-*` copy and, mid-pair, its `.old-*` aside file are the only copies of their bytes, so a+ * sweep outside the lock can break a concurrent install or lose a path while it is renamed aside.+ */+export function sweepAsideFiles(rootDir: string, fs: PtyInstallFs = defaultPtyInstallFs): number {+ const bin = join(rootDir, 'bin')+ let names: string[]+ try {+ names = readdirSync(bin)+ } catch {+ return 0+ }+ let left = 0+ for (const name of names.filter((n) => SWEPT.some((pattern) => pattern.test(n)))) {+ try {+ fs.rm(join(bin, name))+ } catch (error) {+ // Gone already (another sweep) is as good as deleted.+ if (codeOf(error) !== 'ENOENT') left+++ }+ }+ return left+}diff --git a/cli/src/lib/windows/ptyInstall.windows.real.spec.ts b/cli/src/lib/windows/ptyInstall.windows.real.spec.tsnew file mode 100644index 000000000..d13147222--- /dev/null+++ b/cli/src/lib/windows/ptyInstall.windows.real.spec.ts@@ -0,0 +1,162 @@+// The bin\ replacement on real Windows (spec §3): a running .exe cannot be overwritten or deleted there, only renamed,+// which is what installPreparedPty relies on. With Node's fs the path can be missing for the moment between two+// adjacent renames in bin\ (the rename aside and the rename in), and never longer. This checks that bar from the+// calls themselves: which branch ran, that nothing comes between the two renames of a pair, and that the path is+// there after every pair and at the end. A poller measures misses too, and reports them; the Windows timer's+// ~15.6 ms granularity means its count proves little either way. Windows only; it runs on Windows CI. Everything lives in its own+// temporary root: the "harness.exe" here is a copy of this Node, so it runs and can be held open with no real+// install behind it.+// cd cli && npx vitest run src/lib/windows/ptyInstall.windows.real.spec.ts+import { spawn, type ChildProcess } from 'node:child_process'+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { Worker } from 'node:worker_threads'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { PTY_PAYLOAD_FILES } from './ptyPayload.js'+import { defaultPtyInstallFs, installPreparedPty, sweepAsideFiles, type PtyInstallFs } from './ptyInstall.js'++const BIN_FILES = ['harness.exe', 'harness-launch.exe']++/** Polls each path every millisecond until told to stop. Shared counters: [stop, polls, missing]. */+const POLLER = `+const { workerData, parentPort } = require('node:worker_threads')+const { existsSync } = require('node:fs')+const flags = new Int32Array(workerData.shared)+const pause = new Int32Array(new SharedArrayBuffer(4))+while (Atomics.load(flags, 0) === 0) {+ for (const path of workerData.paths) if (!existsSync(path)) Atomics.add(flags, 2, 1)+ Atomics.add(flags, 1, 1)+ Atomics.wait(pause, 0, 0, 1)+}+parentPort.postMessage('stopped')+`++const tick = () => new Promise((resolve) => setTimeout(resolve, 1))++describe.runIf(process.platform === 'win32')('ptyInstall on real Windows', () => {+ let root: string+ let children: ChildProcess[] = []+ beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'pty-install-real-')) })+ afterEach(async () => {+ await Promise.all(children.map((child) => new Promise<void>((resolve) => {+ if (child.exitCode !== null || child.signalCode !== null) return resolve()+ child.once('exit', () => resolve())+ child.kill()+ })))+ children = []+ rmSync(root, { recursive: true, force: true })+ })++ /** A program file: this Node, with [tag] appended so each version's bytes differ (Windows ignores the overlay). */+ function program(path: string, tag: string): void {+ writeFileSync(path, Buffer.concat([readFileSync(process.execPath), Buffer.from(tag)]))+ }++ function payload(dir: string, tag: string): void {+ mkdirSync(dir, { recursive: true })+ for (const name of PTY_PAYLOAD_FILES) {+ if (BIN_FILES.includes(name)) program(join(dir, name), tag)+ else writeFileSync(join(dir, name), `${tag} ${name}`)+ }+ }++ async function started(file: string): Promise<ChildProcess> {+ const child = spawn(file, ['-e', 'setInterval(() => {}, 1 << 30)'], { stdio: 'ignore', windowsHide: true })+ children.push(child)+ await new Promise<void>((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject) })+ return child+ }++ it('bin files are replaced while copies of them run, and the path is missing at most between the two renames of a pair', async () => {+ const ptyRoot = join(root, 'runtime', 'pty')+ const bin = join(root, 'bin')+ payload(join(ptyRoot, '0.10.0'), 'old')+ writeFileSync(join(ptyRoot, 'current-pty'), '0.10.0\r\n')+ mkdirSync(bin)+ for (const name of BIN_FILES) copyFileSync(join(ptyRoot, '0.10.0', name), join(bin, name))+ const staging = join(ptyRoot, `.staging-${process.pid}-${Date.now()}`)+ payload(staging, 'new')++ // 1. Copies of both bin files run, so neither can be overwritten or deleted.+ const running = await Promise.all(BIN_FILES.map((name) => started(join(bin, name))))++ // 2. The real calls, recorded: every call in order, whether a rename over a bin file was refused, and whether+ // the path was there right after each pair's rename in.+ const calls: string[] = []+ const presentAfterPair: boolean[] = []+ let refusedOver = 0+ let awaitingPutBack: string | null = null+ const isBinFile = (p: string) => BIN_FILES.some((name) => p === join(bin, name))+ const fs: PtyInstallFs = {+ ...defaultPtyInstallFs,+ rename: (from, to) => {+ // A pair ends with its rename in, or, when that fails, with the old file's rename back.+ const pairIn = isBinFile(to) && (calls.at(-1)?.startsWith(`aside ${to}`) ?? false)+ const putBack = to === awaitingPutBack+ calls.push(isBinFile(from) && to.includes('.old-') ? `aside ${from}` : isBinFile(to) ? `in ${to}` : `rename ${to}`)+ try {+ defaultPtyInstallFs.rename(from, to)+ } catch (error) {+ calls[calls.length - 1] += ' !failed'+ if (pairIn) awaitingPutBack = to+ else if (isBinFile(to) && !putBack) refusedOver+++ throw error+ }+ if (pairIn || putBack) {+ presentAfterPair.push(existsSync(to))+ awaitingPutBack = null+ }+ },+ link: (a, b) => { calls.push(`link ${b}`); defaultPtyInstallFs.link(a, b) },+ copyFile: (a, b) => { calls.push(`copy ${b}`); defaultPtyInstallFs.copyFile(a, b) },+ writeFile: (p, d) => { calls.push(`write ${p}`); defaultPtyInstallFs.writeFile(p, d) },+ rm: (p, o) => { calls.push(`rm ${p}`); defaultPtyInstallFs.rm(p, o) },+ sleep: (ms) => { calls.push(`sleep ${ms}`); defaultPtyInstallFs.sleep(ms) },+ }++ // 3. Another thread looks for the paths every millisecond, from before the install to after it.+ const shared = new SharedArrayBuffer(12)+ const flags = new Int32Array(shared)+ const poller = new Worker(POLLER, { eval: true, workerData: { shared, paths: BIN_FILES.map((n) => join(bin, n)) } })+ const stopped = new Promise((resolve) => poller.once('message', resolve))+ while (Atomics.load(flags, 1) < 5) await tick()+ expect(installPreparedPty({ version: '0.11.0', staging, protocol: 2, features: ['seed'] }, root, fs)).toBe(true)+ const after = Atomics.load(flags, 1)+ while (Atomics.load(flags, 1) < after + 5) await tick()+ Atomics.store(flags, 0, 1)+ await stopped+ await poller.terminate()+ const pairs = presentAfterPair.length+ console.log(`[ptyInstall real] branch: ${pairs > 0 ? 'rename-aside pairs' : 'rename over'}; renames over refused: ${refusedOver}; `+ + `pairs: ${pairs}; polls: ${Atomics.load(flags, 1)}; polls that found a path missing: ${Atomics.load(flags, 2)}`)++ // Each successful rename aside is followed at once by its rename in: no other call and no sleep between.+ calls.forEach((call, i) => {+ if (!call.startsWith('aside ') || call.endsWith('!failed')) return+ expect(calls[i + 1], `after "${call}"`).toMatch(new RegExp(`^in ${call.slice('aside '.length).replace(/[\\.]/g, '\\$&')}`))+ })+ // The path is there after every pair, and at the end.+ expect(presentAfterPair.every(Boolean)).toBe(true)+ for (const name of BIN_FILES) expect(existsSync(join(bin, name))).toBe(true)++ // 4. The new bytes are in place, and the running copies were kept aside rather than lost.+ for (const name of BIN_FILES) expect(readFileSync(join(bin, name)).equals(readFileSync(join(ptyRoot, '0.11.0', name)))).toBe(true)+ const aside = () => readdirSync(bin).filter((n) => n.includes('.old-'))+ for (const name of BIN_FILES) {+ const old = readFileSync(join(ptyRoot, '0.10.0', name))+ expect(aside().some((n) => n.startsWith(`${name}.old-`) && readFileSync(join(bin, n)).equals(old))).toBe(true)+ }++ // 5. The aside files go once the copies have exited.+ await Promise.all(running.map((child) => new Promise<void>((resolve) => { child.once('exit', () => resolve()); child.kill() })))+ // Windows releases an image a moment after the process is reported gone.+ let left = sweepAsideFiles(root)+ for (let attempt = 0; left > 0 && attempt < 100; attempt++) {+ await new Promise((resolve) => setTimeout(resolve, 20))+ left = sweepAsideFiles(root)+ }+ expect(left).toBe(0)+ expect(aside()).toEqual([])+ }, 120_000)+})diff --git a/cli/src/lib/windows/ptyPayload.spec.ts b/cli/src/lib/windows/ptyPayload.spec.tsnew file mode 100644index 000000000..3a0d2b085--- /dev/null+++ b/cli/src/lib/windows/ptyPayload.spec.ts@@ -0,0 +1,349 @@+import { execFileSync } from 'child_process'+import { chmodSync, existsSync, realpathSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { PTY_PROTOCOL } from '../ptyHost/protocol.js'+import { DigestMismatchError } from '../selfUpdate.js'+import {+ PTY_PAYLOAD_FILES, PtyPayloadRefused, PtyPayloadUnpackFailed, CANARY_HOME_STALE_MS, SERVE_CANARY_BOUND_MS, fetchPtyEntry, preparePtyPayload, ptyManifestUrl, ptyPlatformKey,+ probeVersionLine, processesInFolder, ptyUpdateWanted, serveCanary, sweepCanaryHomes, sweepStagingFolders, type PtyEntry,+} from './ptyPayload.js'++let tmp: string+beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), 'pty-payload-')) })+afterEach(() => { vi.useRealTimers(); rmSync(tmp, { recursive: true, force: true }) })++function zipOf(names: readonly string[]): Buffer {+ const src = join(tmp, 'src'); rmSync(src, { recursive: true, force: true }); mkdirSync(src)+ for (const n of names) writeFileSync(join(src, n), n)+ const out = join(tmp, 'p.zip'); rmSync(out, { force: true })+ // Windows has no `zip`: its own bsdtar writes one (`-a` picks the format from the .zip suffix), and the payload's+ // default unzip there is that same tar.exe, so these cases go through the real Windows unpack.+ if (process.platform === 'win32') {+ execFileSync(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe'), ['-a', '-c', '-f', out, ...names], { cwd: src, windowsHide: true })+ } else {+ execFileSync('zip', ['-q', '-j', out, ...names.map((n) => join(src, n))])+ }+ return readFileSync(out)+}++const entry: PtyEntry = { version: '0.11.0', url: 'https://cdn.example/p.zip', sha256: 'a'.repeat(64), size: 10 }+const goodProbe = (host: object = {}, serial: object = {}) => async (bin: string) =>+ bin.endsWith('harness-pty.exe')+ ? { version: '0.11.0', protocol: 2, features: ['seed'], ...host }+ : { version: '0.11.0', ...serial }+const run = (deps: Parameters<typeof preparePtyPayload>[2], files: readonly string[] = PTY_PAYLOAD_FILES) =>+ preparePtyPayload(entry, tmp + '/rt', { download: async () => zipOf(files), probe: goodProbe(), serve: async () => {}, ...deps })+const leftovers = () => (existsSync(join(tmp, 'rt', 'pty')) ? readdirSync(join(tmp, 'rt', 'pty')) : [])++describe('ptyManifestUrl', () => {+ it('swaps the last two segments', () => {+ expect(ptyManifestUrl('https://x.example/a/cli/metadata.json')).toBe('https://x.example/a/pty/metadata.json')+ })+ it('throws on any other url', () => {+ expect(() => ptyManifestUrl('https://x.example/a/other.json')).toThrow()+ })+})++describe('ptyPlatformKey', () => {+ it('maps x64 and arm64, and nothing else', () => {+ expect(ptyPlatformKey('x64')).toBe('win32-x64')+ expect(ptyPlatformKey('arm64')).toBe('win32-arm64')+ expect(ptyPlatformKey('ia32')).toBeNull()+ })+})++describe('ptyUpdateWanted', () => {+ const cli = '1.2.3'+ it('newer is wanted', () => expect(ptyUpdateWanted(entry, { pty: '0.10.0', cli }, [])).toBe(true))+ it('same and older are not', () => {+ expect(ptyUpdateWanted(entry, { pty: '0.11.0', cli }, [])).toBe(false)+ expect(ptyUpdateWanted(entry, { pty: '0.12.0', cli }, [])).toBe(false)+ })+ it('a dev CLI never updates', () => expect(ptyUpdateWanted(entry, { pty: '0.10.0', cli: '1.2.3-dev.abc' }, [])).toBe(false))+ it('a rejected version is not', () => expect(ptyUpdateWanted(entry, { pty: '0.10.0', cli }, ['0.11.0'])).toBe(false))+ // Without a current-pty there is no previous version for probation to roll back to (install.ps1 installs the first).+ it('no installed pty wants none', () => expect(ptyUpdateWanted(entry, { pty: null, cli }, [])).toBe(false))+})++describe('preparePtyPayload', () => {+ it('a good zip is unpacked into a staging folder', async () => {+ const p = await run({})+ expect(p).toMatchObject({ version: '0.11.0', protocol: 2, features: ['seed'] })+ expect(p.staging.startsWith(join(tmp, 'rt', 'pty', '.staging-'))).toBe(true)+ expect(readdirSync(p.staging).sort()).toEqual([...PTY_PAYLOAD_FILES].sort())+ })+ it('a digest mismatch is refused and leaves nothing', async () => {+ await expect(run({ download: async () => { throw new DigestMismatchError('bad') } })).rejects.toBeInstanceOf(PtyPayloadRefused)+ expect(leftovers()).toEqual([])+ })+ it('a missing or extra file is refused', async () => {+ await expect(run({}, PTY_PAYLOAD_FILES.slice(1))).rejects.toThrow(/expected/)+ await expect(run({}, [...PTY_PAYLOAD_FILES, 'extra.dll'])).rejects.toThrow(/expected/)+ expect(leftovers()).toEqual([])+ })+ it('a host that names another version is refused', async () => {+ await expect(run({ probe: goodProbe({ version: '0.9.0' }) })).rejects.toThrow(/harness-pty reports version 0.9.0/)+ expect(leftovers()).toEqual([])+ })+ it('a protocol this CLI does not support is refused when it is below, and paired when it is above', async () => {+ // Supported: installed on its own, with any CLI build.+ const supported = await run({})+ expect(supported.paired).toBe(false)+ rmSync(supported.staging, { recursive: true, force: true })+ // Above: a host for a CLI build that needs it (spec §5, the pairing rule), canaried like any other and installed+ // only in that build's handover.+ const above = await run({ probe: goodProbe({ protocol: PTY_PROTOCOL + 1 }) })+ expect(above).toMatchObject({ version: '0.11.0', protocol: PTY_PROTOCOL + 1, paired: true })+ expect(readdirSync(above.staging).sort()).toEqual([...PTY_PAYLOAD_FILES].sort())+ rmSync(above.staging, { recursive: true, force: true })+ await expect(run({ probe: goodProbe({ protocol: PTY_PROTOCOL + 1 }, { version: '0.9.0' }) })).rejects.toThrow(/harness-serial reports version 0.9.0/)+ await expect(run({ probe: goodProbe({ protocol: PTY_PROTOCOL + 1, features: 'seed' }) })).rejects.toThrow(/features/)+ // Below every supported one, or not a protocol: no CLI will ever need it.+ await expect(run({ probe: goodProbe({ protocol: 0 }) })).rejects.toThrow(/protocol 0/)+ await expect(run({ probe: goodProbe({ protocol: 2.5 }) })).rejects.toThrow(/protocol 2.5/)+ expect(leftovers()).toEqual([])+ })+ it('a serial binary that names another version is refused', async () => {+ await expect(run({ probe: goodProbe({}, { version: '0.9.0' }) })).rejects.toThrow(/harness-serial reports version 0.9.0/)+ expect(leftovers()).toEqual([])+ })+ it('a canary that hangs past 5 s is refused', async () => {+ // Only the timers are faked: unzip is a real process and needs real time to finish.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ let started = false+ const p = run({ probe: () => { started = true; return new Promise(() => {}) } })+ const assertion = expect(p).rejects.toThrow(/no answer within 5000 ms/)+ while (!started) await new Promise((r) => setImmediate(r))+ await vi.advanceTimersByTimeAsync(5_000)+ await assertion+ expect(leftovers()).toEqual([])+ })+})++describe('preparePtyPayload failure kinds', () => {+ it('a network error from the download is rethrown as it is, leaving no staging', async () => {+ const boom = new Error('ECONNRESET')+ const err = await run({ download: async () => { throw boom } }).catch((e) => e)+ expect(err).toBe(boom)+ expect(err).not.toBeInstanceOf(PtyPayloadRefused)+ expect(leftovers()).toEqual([])+ })+ it('an unzip that fails is no refusal: it carries the verified bytes, which a later prepare unpacks without a download', async () => {+ const zip = zipOf(PTY_PAYLOAD_FILES)+ let downloads = 0+ const err = await run({ download: async () => { downloads++; return zip }, unzip: async () => { throw new Error('spawn unzip ENOENT') } }).catch((e) => e)+ expect(err).toBeInstanceOf(PtyPayloadUnpackFailed)+ expect(err).not.toBeInstanceOf(PtyPayloadRefused)+ expect(err.reason).toBe('spawn unzip ENOENT')+ expect(err.zip).toBe(zip)+ expect(leftovers()).toEqual([])+ const again = await preparePtyPayload(entry, tmp + '/rt', { download: async () => { downloads++; return zip }, probe: goodProbe(), serve: async () => {} }, err.zip)+ expect(downloads).toBe(1)+ expect(readdirSync(again.staging).sort()).toEqual([...PTY_PAYLOAD_FILES].sort())+ })+ it('a probe that rejects is a refusal', async () => {+ await expect(run({ probe: async () => { throw new Error('exit 1') } })).rejects.toBeInstanceOf(PtyPayloadRefused)+ expect(leftovers()).toEqual([])+ })+})++describe('the serve canary', () => {+ it('runs after the version checks, on the staged host with its protocol and version, and its failure is a refusal', async () => {+ const asked: Array<{ binary: string; protocol: number; version: string }> = []+ const p = await run({ serve: async (binary, host) => { asked.push({ binary, ...host }) } })+ expect(asked).toEqual([{ binary: join(p.staging, 'harness-pty.exe'), protocol: 2, version: '0.11.0' }])+ rmSync(p.staging, { recursive: true, force: true })+ // Not reached for a payload a version check refused.+ asked.length = 0+ await expect(run({ probe: goodProbe({}, { version: '0.9.0' }), serve: async (binary, host) => { asked.push({ binary, ...host }) } })).rejects.toThrow(/harness-serial/)+ expect(asked).toEqual([])+ const err = await run({ serve: async () => { throw new Error('its create failed (spawn_failed: conpty.dll not found)') } }).catch((e) => e)+ expect(err).toBeInstanceOf(PtyPayloadRefused)+ expect(err.reason).toBe('harness-pty serve failed: its create failed (spawn_failed: conpty.dll not found)')+ expect(leftovers()).toEqual([])+ })++ it('a serve canary that never ends is refused at its bound', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ let started = false+ const p = run({ serve: () => { started = true; return new Promise(() => {}) } })+ const assertion = expect(p).rejects.toThrow(/harness-pty serve failed: no answer within/)+ while (!started) await new Promise((r) => setImmediate(r))+ await vi.advanceTimersByTimeAsync(SERVE_CANARY_BOUND_MS)+ await assertion+ expect(leftovers()).toEqual([])+ // Cleanup included, under the updater's 30 s heartbeat timeout (harnessd/services.ts).+ expect(SERVE_CANARY_BOUND_MS).toBeLessThanOrEqual(20_000)+ })+})++describe.skipIf(process.platform === 'win32')('serveCanary, against stand-in binaries', () => {+ function script(name: string, body: string): string {+ const file = join(tmp, name)+ writeFileSync(file, `#!/bin/sh\n${body}\n`)+ chmodSync(file, 0o755)+ return file+ }+ const canaryHomes = (dir: string) => readdirSync(dir).filter((n) => n.startsWith('harness-pty-canary-'))++ it('a host that exits before it publishes is a failure, and its temporary home is gone', async () => {+ const homes = join(tmp, 'homes'); mkdirSync(homes)+ await expect(serveCanary(script('exits', 'exit 3'), { protocol: 2, version: '0.11.0' }, { tmpRoot: homes }))+ .rejects.toThrow(/exited with code 3 before it published its discovery file/)+ expect(canaryHomes(homes)).toEqual([])+ })++ it('a host that hangs is killed at the bound, and its temporary home is gone', async () => {+ const homes = join(tmp, 'homes'); mkdirSync(homes)+ const pidFile = join(tmp, 'pid')+ const binary = script('hangs', `echo $$ > '${pidFile}'\nexec sleep 30`)+ await expect(serveCanary(binary, { protocol: 2, version: '0.11.0' }, { tmpRoot: homes, timeoutMs: 3_000 })).rejects.toThrow(/no answer within 3000 ms/)+ const pid = Number(readFileSync(pidFile, 'utf8'))+ expect(() => process.kill(pid, 0)).toThrow()+ expect(canaryHomes(homes)).toEqual([])+ })++ it('runs the host outside its home, so a host or pane that lingers does not hold the folder', async () => {+ const homes = join(tmp, 'homes'); mkdirSync(homes)+ const cwdFile = join(tmp, 'cwd')+ await expect(serveCanary(script('cwd', `pwd -P > '${cwdFile}'\nexit 3`), { protocol: 2, version: '0.11.0' }, { tmpRoot: homes })).rejects.toThrow(/code 3/)+ expect(readFileSync(cwdFile, 'utf8').trim()).toBe(realpathSync(homes))+ })++ it('a home it cannot remove is left, and swept once stale, never while fresh', async () => {+ const homes = join(tmp, 'homes'); mkdirSync(homes)+ await expect(serveCanary(script('exits', 'exit 3'), { protocol: 2, version: '0.11.0' }, {+ tmpRoot: homes, remove: () => { throw Object.assign(new Error('EBUSY: resource busy or locked'), { code: 'EBUSY' }) },+ })).rejects.toThrow(/exited with code 3/)+ const left = canaryHomes(homes)+ expect(left).toHaveLength(1)+ // A canary may be running in a fresh one.+ expect(sweepCanaryHomes(homes)).toBe(0)+ expect(canaryHomes(homes)).toEqual(left)+ // Other folders are never touched.+ mkdirSync(join(homes, 'something-else'))+ expect(sweepCanaryHomes(homes, CANARY_HOME_STALE_MS, Date.now() + CANARY_HOME_STALE_MS + 1_000)).toBe(1)+ expect(readdirSync(homes)).toEqual(['something-else'])+ expect(sweepCanaryHomes(join(tmp, 'no-such-folder'))).toBe(0)+ })+})++// The real host (`cd pty && cargo build`, then HARNESS_PTY_BIN=<that harness-pty>): start, hello, one pane that exits, shutdown.+const realHost = process.env.HARNESS_PTY_BIN+describe.runIf(realHost)('serveCanary, against the real host', () => {+ // Short off Windows: the host's Unix socket is in its home, and a macOS temporary folder is half a socket path already.+ let homes: string+ beforeEach(() => { homes = mkdtempSync(process.platform === 'win32' ? join(tmpdir(), 'hpc-') : '/tmp/hpc-') })+ afterEach(() => { rmSync(homes, { recursive: true, force: true }) })++ // Windows: the host's console process (OpenConsole.exe) must not outlive the canary, or the folder it started in+ // cannot be removed (and, staged, cannot be renamed). A leftover is named in the message.+ async function expectNoneLeft(): Promise<void> {+ if (process.platform !== 'win32') return+ const left = await processesInFolder(realHost!)+ expect(left, `processes still running from ${realHost}: ${JSON.stringify(left)}`).toEqual([])+ rmSync(homes, { recursive: true, maxRetries: 0 })+ }++ it('passes, and leaves no host and no home behind', async () => {+ const said = await probeVersionLine(realHost!) as { version: string; protocol: number }+ await serveCanary(realHost!, { protocol: said.protocol, version: said.version }, { tmpRoot: homes })+ expect(readdirSync(homes)).toEqual([])+ await expectNoneLeft()+ }, 30_000)++ it('a host that cannot start a pane fails it', async () => {+ const said = await probeVersionLine(realHost!) as { version: string; protocol: number }+ await expect(serveCanary(realHost!, { protocol: said.protocol, version: said.version }, { tmpRoot: homes, command: [join(tmp, 'no-such-shell')] }))+ .rejects.toThrow(/its create failed|its pane exited with/)+ expect(readdirSync(homes)).toEqual([])+ await expectNoneLeft()+ }, 30_000)+})++describe('probeVersionLine', () => {+ // The same `<bin> version` run as ptyHost/launch.ts binaryVersion's (one implementation, 5 s, hidden).+ it.skipIf(process.platform === 'win32')('parses the last line a binary prints, and rejects one that fails', async () => {+ const good = join(tmp, 'good')+ writeFileSync(good, '#!/bin/sh\necho "starting"\necho \'{"version":"0.11.0"}\'\n', { mode: 0o755 })+ await expect(probeVersionLine(good)).resolves.toEqual({ version: '0.11.0' })+ const bad = join(tmp, 'bad')+ writeFileSync(bad, '#!/bin/sh\nexit 3\n', { mode: 0o755 })+ await expect(probeVersionLine(bad)).rejects.toThrow()+ })++ // A binary whose child holds its output open: a synchronous run outlived its timeout with it, and the updater's event+ // loop with it. The default canary refuses it within 5 s, and the loop runs meanwhile.+ it.skipIf(process.platform === 'win32')('a default probe that never answers is refused within the timeout, the event loop running', async () => {+ const unzip = async (_zip: Buffer, dest: string) => {+ for (const name of PTY_PAYLOAD_FILES) if (name !== 'harness-pty.exe') writeFileSync(join(dest, name), name)+ // Its child keeps stdout open after the shell is killed at the timeout.+ writeFileSync(join(dest, 'harness-pty.exe'), '#!/bin/sh\n(sleep 8)\n', { mode: 0o755 })+ }+ let beats = 0+ const beat = setInterval(() => { beats++ }, 100)+ const started = Date.now()+ try {+ const err = await preparePtyPayload(entry, join(tmp, 'rt'), { download: async () => Buffer.from('zip'), unzip }).catch((e) => e)+ expect(err).toBeInstanceOf(PtyPayloadRefused)+ expect((err as PtyPayloadRefused).reason).toMatch(/no answer within 5000 ms/)+ expect(Date.now() - started).toBeLessThan(7_000)+ expect(beats).toBeGreaterThan(20)+ } finally { clearInterval(beat) }+ expect(leftovers()).toEqual([])+ }, 15_000)+})++describe('sweepStagingFolders', () => {+ it('removes stale staging folders and nothing else', () => {+ const root = join(tmp, 'rt', 'pty')+ mkdirSync(join(root, '.staging-1-2'), { recursive: true })+ mkdirSync(join(root, '.staging-3-4'), { recursive: true })+ mkdirSync(join(root, '0.10.0'), { recursive: true })+ expect(sweepStagingFolders(join(tmp, 'rt'))).toBe(2)+ expect(readdirSync(root)).toEqual(['0.10.0'])+ expect(sweepStagingFolders(join(tmp, 'nothing'))).toBe(0)+ })+})++describe('fetchPtyEntry', () => {+ const good = { version: '0.11.0', url: 'https://cdn.example/p.zip', sha256: 'b'.repeat(64), size: 10 }+ const serve = (body: string, status = 200) => vi.stubGlobal('fetch', async () => new Response(body, { status }))+ const manifest = (e: object) => JSON.stringify({ pty: { 'win32-x64': e, 'win32-arm64': { ...good, version: '0.12.0' } } })+ afterEach(() => vi.unstubAllGlobals())++ it('reads the entry of the platform from the published shape', async () => {+ serve(manifest(good))+ expect(await fetchPtyEntry('https://m.example/pty/metadata.json', 'win32-x64')).toEqual(good)+ expect((await fetchPtyEntry('https://m.example/pty/metadata.json', 'win32-arm64'))?.version).toBe('0.12.0')+ })+ it('an absent platform is null', async () => {+ serve(JSON.stringify({ pty: { 'win32-arm64': good } }))+ expect(await fetchPtyEntry('https://m.example/m.json', 'win32-x64')).toBeNull()+ })+ it('a top-level entry (not the published shape) is null', async () => {+ serve(JSON.stringify({ 'win32-x64': good }))+ expect(await fetchPtyEntry('https://m.example/m.json', 'win32-x64')).toBeNull()+ })+ it.each([+ ['an http url', { url: 'http://cdn.example/p.zip' }],+ ['a 63-char sha', { sha256: 'b'.repeat(63) }],+ ['a non-hex sha', { sha256: 'z'.repeat(64) }],+ ['size 0', { size: 0 }],+ ['size 1.5', { size: 1.5 }],+ ['size "10"', { size: '10' }],+ ])('%s is null', async (_n, bad) => {+ serve(manifest({ ...good, ...bad }))+ expect(await fetchPtyEntry('https://m.example/m.json', 'win32-x64')).toBeNull()+ })+ it('a non-2xx response is null', async () => {+ serve(manifest(good), 404)+ expect(await fetchPtyEntry('https://m.example/m.json', 'win32-x64')).toBeNull()+ })+ it('malformed JSON is null', async () => {+ serve('{nope')+ expect(await fetchPtyEntry('https://m.example/m.json', 'win32-x64')).toBeNull()+ })+})diff --git a/cli/src/lib/windows/ptyPayload.ts b/cli/src/lib/windows/ptyPayload.tsnew file mode 100644index 000000000..fd987ed05--- /dev/null+++ b/cli/src/lib/windows/ptyPayload.ts@@ -0,0 +1,444 @@+/**+ * Delivery of a promoted PTY payload (six files in one zip): decide whether one is wanted, download and+ * verify it, unpack it beside the live install and prove it runs: each binary says its version, and the host serves+ * one pane (`serveCanary`). Nothing here calls a Windows API, so it is tested on every OS; only the default unzip tool+ * and the canary pane's command differ by platform.+ */+import { execFile, spawn, type ChildProcess } from 'child_process'+import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { dirname, join } from 'path'+import { PtyHostClient } from '../ptyHost/client.js'+import { hostInstanceName } from '../ptyHost/instance.js'+import { VERSION_COMMAND, readInstanceDiscovery } from '../ptyHost/launch.js'+import { PTY_PROTOCOL, SHUTDOWN_PROTOCOL, SUPPORTED_PTY_PROTOCOLS } from '../ptyHost/protocol.js'+import { windowsProcessRows } from './processTable.js'+import { scrubTerminalContext } from '../terminalEnvironment.js'+import {+ DigestMismatchError, MANIFEST_LIMITS, downloadVerified, fetchWithin, isLocalDevBuild, semverGt,+ type FileRef, type TransferLimits,+} from '../selfUpdate.js'++/** The files a payload carries, and the only ones it may carry. */+export const PTY_PAYLOAD_FILES: readonly string[] = [+ 'harness-pty.exe', 'harness-launch.exe', 'harness.exe', 'conpty.dll', 'OpenConsole.exe', 'harness-serial.exe',+]++/** Each canary run must answer within this; a hung binary must not hold the updater. */+const CANARY_TIMEOUT_MS = 5_000+/**+ * The serve canary's work (`serveCanary`): its start and discovery file, the hello, one pane's create and exit, and the+ * shutdown. With its cleanup (`SERVE_CANARY_CLEANUP_MS`) at most 20 s, under the updater's 30 s heartbeat timeout+ * (harnessd/services.ts), though the canary is asynchronous and the heartbeat goes on beside it.+ */+export const SERVE_CANARY_TIMEOUT_MS = 10_000+/** Cleanup, step 1: how long the host gets to end itself on `shutdown`, so it closes its consoles as it exits. */+const SERVE_CANARY_ASK_MS = 2_000+/** Cleanup, step 2: how long a killed host gets to exit before its temporary home is removed: on Windows a file a process+ * still holds, or a folder that is a process's working directory, cannot be removed. */+const SERVE_CANARY_EXIT_WAIT_MS = 2_000+/** Cleanup, step 3 (Windows): how long a console process the host started (OpenConsole.exe) gets to follow the host+ * out before it is ended; then the same again, after the ending, to see it gone. */+const SERVE_CANARY_IMAGES_WAIT_MS = 3_000+const SERVE_CANARY_IMAGES_ENDED_MS = 1_000+/** The cleanup's whole bound: ask 2 s + exit wait 2 s + images 3 s + 1 s, then the removal's retries (`removeCanaryHome`, 2 s). */+const SERVE_CANARY_CLEANUP_MS = 10_000+/** The serve canary from start to cleanup: what `preparePtyPayload` waits for it at most. */+export const SERVE_CANARY_BOUND_MS = SERVE_CANARY_TIMEOUT_MS + SERVE_CANARY_CLEANUP_MS+/** The canary's temporary homes: `<temporary folder>/harness-pty-canary-*`. */+const CANARY_HOME_PREFIX = 'harness-pty-canary-'+/** A canary home this old is left over from one whose removal failed (`sweepCanaryHomes`): no canary runs this long. */+export const CANARY_HOME_STALE_MS = 10 * 60_000++/** Where canary homes are made: the OS's temporary folder; off Windows (the tests) `/tmp`, as the host's endpoint is a+ * Unix socket in the home, whose path must fit in about 100 bytes, and a macOS temporary folder alone takes half. */+export function canaryTempRoot(): string {+ return process.platform === 'win32' ? tmpdir() : '/tmp'+}++/** Remove a canary home, retrying while Windows still reports it held (a process that has just exited). */+function removeCanaryHome(dir: string): void {+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 })+}++/**+ * Remove the canary homes in [root] older than [maxAgeMs]: those whose removal failed (a file still held as the canary+ * ended), left for this sweep, which the updater runs as it starts (./ptyUpdate.ts `sweepPtyLeftovers`). A fresh one may+ * be a canary running now, and stays; so does one that still cannot be removed. Returns how many were removed.+ */+export function sweepCanaryHomes(root: string = canaryTempRoot(), maxAgeMs: number = CANARY_HOME_STALE_MS, now: number = Date.now()): number {+ let names: string[]+ try { names = readdirSync(root) } catch { return 0 }+ let removed = 0+ for (const name of names) {+ if (!name.startsWith(CANARY_HOME_PREFIX)) continue+ const dir = join(root, name)+ try {+ const info = statSync(dir)+ if (!info.isDirectory() || now - info.mtimeMs < maxAgeMs) continue+ removeCanaryHome(dir)+ removed+++ } catch { /* held still, or gone meanwhile: the next sweep's */ }+ }+ return removed+}++export interface PtyEntry { version: string; url: string; sha256: string; size: number }++/** The payload manifest sits beside the CLI one, so both follow the same override of the update URL. */+export function ptyManifestUrl(cliManifestUrl: string): string {+ const tail = 'cli/metadata.json'+ if (!cliManifestUrl.endsWith(`/${tail}`)) throw new Error(`not a CLI manifest url: ${cliManifestUrl}`)+ return `${cliManifestUrl.slice(0, -tail.length)}pty/metadata.json`+}++export function ptyPlatformKey(arch: string = process.arch): 'win32-x64' | 'win32-arm64' | null {+ if (arch === 'x64') return 'win32-x64'+ if (arch === 'arm64') return 'win32-arm64'+ return null+}++/** Fetch the manifest `{ "pty": { "<platform key>": entry } }` and return this platform's entry, or null+ * when the response is not 2xx, the JSON is malformed, or the entry is absent or invalid: an https url, a+ * 64-digit sha256 hex digest and a positive integer size. */+export async function fetchPtyEntry(url: string, key: string, limits: TransferLimits = MANIFEST_LIMITS): Promise<PtyEntry | null> {+ const res = await fetchWithin(url, limits)+ if (!res.ok) return null+ let json: unknown+ try { json = JSON.parse(res.body.toString('utf8')) } catch { return null }+ const platforms = (json as { pty?: unknown } | null)?.pty+ if (!platforms || typeof platforms !== 'object') return null+ const e = (platforms as Record<string, unknown>)[key] as Partial<PtyEntry> | undefined+ if (!e || typeof e.version !== 'string' || !e.version) return null+ if (typeof e.url !== 'string' || !/^https:\/\//.test(e.url)) return null+ if (typeof e.sha256 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(e.sha256)) return null+ if (typeof e.size !== 'number' || !Number.isInteger(e.size) || e.size <= 0) return null+ return { version: e.version, url: e.url, sha256: e.sha256, size: e.size }+}++/** Only over an installed host: with no `current-pty` there is no version for probation to roll back to, and the+ * first host is install.ps1's to put in. A dev CLI never updates, as for the CLI itself. */+export function ptyUpdateWanted(entry: PtyEntry, installed: { pty: string | null; cli: string }, rejected: readonly string[]): boolean {+ if (isLocalDevBuild(installed.cli)) return false+ if (rejected.includes(entry.version)) return false+ return installed.pty !== null && semverGt(entry.version, installed.pty)+}++export interface PreparedPty {+ version: string+ staging: string+ protocol: number+ features: string[]+ /** Its host speaks a protocol above this CLI's (spec §5, the pairing rule): no daemon of this build could open a pane+ * on it, so it is installed only with a CLI build that needs exactly that protocol, in that build's handover. */+ paired?: boolean+}++export class PtyPayloadRefused extends Error {+ constructor(readonly reason: string) { super(`pty payload refused: ${reason}`) }+}++/**+ * A payload downloaded and verified that could not be unpacked (a tool that failed, a full disk, a scan holding a+ * file): transient, as a network failure is, but its bytes are good. The poller keeps [zip] and hands it to the next+ * check's prepare, which unpacks it again rather than download it again, as the CLI's updater keeps its `verified`.+ */+export class PtyPayloadUnpackFailed extends Error {+ readonly reason: string+ constructor(readonly zip: Buffer, cause: unknown) {+ const reason = cause instanceof Error ? cause.message : String(cause)+ super(`pty payload not unpacked: ${reason}`)+ this.reason = reason+ }+}++export interface PreparePtyDeps {+ download: (ref: FileRef) => Promise<Buffer>+ unzip: (zip: Buffer, dest: string) => Promise<void>+ /** Run `<binary> version` and return its one parsed JSON line. */+ probe: (binary: string) => Promise<unknown>+ /** Prove the staged host serves (`serveCanary`); throws why not. */+ serve: (binary: string, host: { protocol: number; version: string }) => Promise<void>+}++/** `tar.exe` is the bsdtar Windows ships (install.ps1's Expand-HarnessZip falls back to it too); `unzip`+ * stands in elsewhere so the tests can run. tar.exe reads its arguments in the ANSI code page, so a profile+ * path outside it (CJK on a Western Windows) breaks extraction: as install.ps1 does, run it in the staging+ * folder with an ASCII relative zip name. The zip is removed after. */+async function unzipWithTool(zip: Buffer, dest: string): Promise<void> {+ const name = 'payload.zip'+ writeFileSync(join(dest, name), zip)+ const [cmd, args] = process.platform === 'win32'+ ? [join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe'), ['-xf', name]] as const+ : ['unzip', ['-q', '-o', name]] as const+ try {+ await new Promise<void>((resolve, reject) => {+ execFile(cmd, [...args], { cwd: dest, windowsHide: true, timeout: 60_000 }, (err) => (err ? reject(err) : resolve()))+ })+ } finally {+ rmSync(join(dest, name), { force: true })+ }+}++/** The last line a binary prints for `version`, parsed: ptyHost/launch.ts `VERSION_COMMAND`, the run `binaryVersion`+ * makes, but asynchronous. A binary whose child holds its output open past the timeout keeps a synchronous run going+ * with it, the updater's event loop blocked and the process killed as hung; here `canary`'s own timer ends the wait. */+export function probeVersionLine(binary: string): Promise<unknown> {+ return new Promise((resolve, reject) => {+ execFile(binary, [...VERSION_COMMAND.args], VERSION_COMMAND.options, (err, stdout) => {+ if (err) return reject(err)+ try { resolve(JSON.parse(String(stdout).trim().split(/\r?\n/).filter(Boolean).pop() ?? '')) } catch (e) { reject(e) }+ })+ })+}++const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))+const reasonOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))++/** The canary pane's command: one that exits at once, with 0. */+const CANARY_COMMAND = process.platform === 'win32' ? ['cmd.exe', '/d', '/c', 'exit 0'] : ['/bin/sh', '-c', 'exit 0']++/** Processes (pid, image) alive whose executable sits in [dir], or null when the table cannot be read. This scan's own+ * child (`harness-pty ps`, from the same folder) is left out. */+export async function processesInFolder(binary: string): Promise<{ pid: number; image: string }[] | null> {+ const rows = await windowsProcessRows(null, { binary: () => binary })+ const dir = dirname(binary)+ if (!rows) return null+ const prefix = dir.replace(/[\\/]+$/, '').toLowerCase().replace(/\//g, '\\') + '\\'+ return rows+ .filter((row) => row.parentPid !== process.pid && row.imagePath && row.imagePath.toLowerCase().replace(/\//g, '\\').startsWith(prefix))+ .map((row) => ({ pid: row.pid, image: row.imagePath! }))+}++/** After the host is gone, no process of ours may keep running from the binary's folder: an OpenConsole.exe there would+ * hold the canary's working folder and, in production, block the rename of the staging folder. Wait for them to end,+ * then end what is left (their image is in our staging folder, so they are ours). */+async function endBinaryProcesses(binary: string): Promise<void> {+ const waitUntilNone = async (ms: number): Promise<{ pid: number; image: string }[]> => {+ const until = Date.now() + ms+ for (;;) {+ const left = await processesInFolder(binary)+ if (!left?.length || Date.now() >= until) return left ?? []+ await sleep(100)+ }+ }+ const left = await waitUntilNone(SERVE_CANARY_IMAGES_WAIT_MS)+ if (!left.length) return+ await Promise.all(left.map((p) => new Promise<void>((resolve) => {+ execFile('taskkill', ['/PID', String(p.pid), '/T', '/F'], { windowsHide: true, timeout: 2_000 }, () => resolve())+ })))+ await waitUntilNone(SERVE_CANARY_IMAGES_ENDED_MS)+}++/**+ * Prove a staged host serves, which `harness-pty version` does not: that never loads conpty.dll, never binds an+ * endpoint and never starts a pane. `<binary> serve --home <a fresh temporary home> --no-reexec` (no copy outside a job,+ * so the process started is the host), hidden; its discovery file; the hello; one pane running [command] (a shell that+ * exits 0) and its exit; `shutdown`, and the process gone. A host of a protocol above this CLI's (a paired one) cannot+ * be spoken to by any client here: for it the canary ends at the discovery file. Within [timeoutMs]; on every path the+ * host is killed if it still runs, its exit waited for, and the temporary home removed; a home that cannot be removed+ * even so is left for `sweepCanaryHomes`. Neither the host nor its pane runs in the home: on Windows a folder that is a+ * process's working directory cannot be removed while it runs, and a pane's console may outlive the host a moment.+ * Throws why it did not pass.+ */+export async function serveCanary(binary: string, host: { protocol: number; version: string }, options: {+ timeoutMs?: number+ /** Where the temporary home is made: `canaryTempRoot()` unless a test names one. */+ tmpRoot?: string+ command?: string[]+ /** How the home is removed (`removeCanaryHome`); a test's may fail. */+ remove?: (dir: string) => void+} = {}): Promise<void> {+ const timeoutMs = options.timeoutMs ?? SERVE_CANARY_TIMEOUT_MS+ const root = options.tmpRoot ?? canaryTempRoot()+ const home = mkdtempSync(join(root, CANARY_HOME_PREFIX))+ const instance = hostInstanceName(host.protocol, host.version)+ let child: ChildProcess | null = null+ let client: PtyHostClient | null = null+ let ended: string | null = null+ let done = false+ const work = async (): Promise<void> => {+ const started = spawn(binary, ['serve', '--home', home, '--no-reexec'], {+ cwd: root, windowsHide: true, stdio: 'ignore', env: scrubTerminalContext({ ...process.env }),+ })+ child = started+ started.once('error', (error) => { ended ??= `could not start (${error.message})` })+ started.once('exit', (code, signal) => { ended ??= `exited with ${code === null ? `signal ${signal}` : `code ${code}`}` })+ let discovery = readInstanceDiscovery(home, instance)+ while (!discovery) {+ if (ended) throw new Error(`it ${ended} before it published its discovery file`)+ await sleep(25)+ if (done) return+ discovery = readInstanceDiscovery(home, instance)+ }+ if (!SUPPORTED_PTY_PROTOCOLS.includes(host.protocol)) return+ const connected = await PtyHostClient.connect(discovery)+ if (!(connected instanceof PtyHostClient)) throw new Error(connected ? `its hello was refused (${connected.incompatible})` : 'nothing answers at the endpoint it published')+ client = connected+ const exits = new Map<string, number | null>()+ let wake: (() => void) | null = null+ connected.onEvent((event) => {+ if (event.event !== 'exit') return+ exits.set(event.pane, event.status)+ wake?.()+ })+ const created = await connected.call({ op: 'create', command: options.command ?? CANARY_COMMAND, cwd: root, cols: 80, rows: 24, owner: 'harness-pty-canary', hold: false })+ if (created.state !== 'ok') throw new Error(`its create failed (${created.state === 'failed' ? `${created.code}: ${created.reason}` : created.reason})`)+ const pane = created.value.pane+ while (!exits.has(pane)) {+ await new Promise<void>((resolve) => { wake = resolve; setTimeout(resolve, 100) })+ if (done) return+ }+ const status = exits.get(pane)!+ if (status !== null && status !== 0) throw new Error(`its pane exited with ${status}`)+ // A host from before `shutdown` is ended by the cleanup, as the drain ends one.+ if (connected.protocol < SHUTDOWN_PROTOCOL) return+ const down = await connected.call({ op: 'shutdown' })+ if (down.state !== 'ok') throw new Error(`its shutdown failed (${down.state === 'failed' ? `${down.code}: ${down.reason}` : down.reason})`)+ while (!ended) {+ await sleep(25)+ if (done) return+ }+ }+ let timer: NodeJS.Timeout | undefined+ try {+ await Promise.race([+ work(),+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`no answer within ${timeoutMs} ms`)), timeoutMs) }),+ ])+ } finally {+ done = true+ clearTimeout(timer)+ const askedClient = client as PtyHostClient | null+ const running = child as ChildProcess | null+ const open = () => !!running && running.exitCode === null && running.signalCode === null+ if (running && open()) {+ const gone = new Promise<void>((resolve) => { running.once('exit', () => resolve()); running.once('error', () => resolve()) })+ // Ask first: a host ended by TerminateProcess never closes its pseudoconsoles, and the console process behind each+ // (OpenConsole.exe) may outlive it holding the folder it started in. `shutdown` succeeds when no pane is left.+ if (askedClient && askedClient.protocol >= SHUTDOWN_PROTOCOL) {+ await Promise.race([askedClient.call({ op: 'shutdown' }).then(() => gone, () => undefined), sleep(SERVE_CANARY_ASK_MS)])+ }+ if (open()) {+ try { running.kill('SIGKILL') } catch { /* gone meanwhile */ }+ await Promise.race([gone, sleep(SERVE_CANARY_EXIT_WAIT_MS)])+ }+ }+ askedClient?.close()+ if (process.platform === 'win32') await endBinaryProcesses(binary)+ try { (options.remove ?? removeCanaryHome)(home) } catch { /* still held: the updater's next start sweeps it (`sweepCanaryHomes`) */ }+ }+}++const DEFAULT_DEPS: PreparePtyDeps = {+ download: (ref) => downloadVerified(ref), unzip: unzipWithTool, probe: probeVersionLine, serve: (binary, host) => serveCanary(binary, host),+}++/** A probe that never answers must not stall the updater, whatever the injected probe does. */+async function canary(probe: PreparePtyDeps['probe'], binary: string): Promise<unknown> {+ let timer: NodeJS.Timeout | undefined+ const hung = new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error(`no answer within ${CANARY_TIMEOUT_MS} ms`)), CANARY_TIMEOUT_MS)+ })+ try {+ return await Promise.race([probe(binary), hung])+ } catch (e) {+ throw new PtyPayloadRefused(`${binary.split(/[\\/]/).pop()} version failed: ${e instanceof Error ? e.message : String(e)}`)+ } finally {+ clearTimeout(timer)+ }+}++/** [serve], bounded as `canary` bounds a probe (`serveCanary` bounds itself and cleans up; this is for any other), and+ * its failure a refusal. */+async function serves(serve: PreparePtyDeps['serve'], binary: string, host: { protocol: number; version: string }): Promise<void> {+ let timer: NodeJS.Timeout | undefined+ const bound = SERVE_CANARY_BOUND_MS+ try {+ await Promise.race([+ serve(binary, host),+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`no answer within ${bound} ms`)), bound) }),+ ])+ } catch (e) {+ throw new PtyPayloadRefused(`harness-pty serve failed: ${reasonOf(e)}`)+ } finally {+ clearTimeout(timer)+ }+}++/** Download, verify, unpack and canary a payload; [verified]: its bytes from an earlier check, verified then, which are+ * unpacked without a download. A failure to unpack them is `PtyPayloadUnpackFailed`, which carries them. On any+ * failure the staging folder is removed. */+export async function preparePtyPayload(entry: PtyEntry, runtimeDir: string, deps: Partial<PreparePtyDeps> = {}, verified?: Buffer): Promise<PreparedPty> {+ const d = { ...DEFAULT_DEPS, ...deps }+ const staging = join(runtimeDir, 'pty', `.staging-${process.pid}-${Date.now()}`)+ try {+ let zip: Buffer+ if (verified) zip = verified+ else {+ try {+ zip = await d.download({ url: entry.url, sha256: entry.sha256, size: entry.size })+ } catch (e) {+ if (e instanceof DigestMismatchError) throw new PtyPayloadRefused(`digest mismatch: ${e.message}`)+ throw e+ }+ }+ try {+ mkdirSync(staging, { recursive: true })+ await d.unzip(zip, staging)+ } catch (e) {+ throw new PtyPayloadUnpackFailed(zip, e)+ }+ const found = readdirSync(staging).sort()+ const want = [...PTY_PAYLOAD_FILES].sort()+ if (found.length !== want.length || found.some((f, i) => f !== want[i])) {+ throw new PtyPayloadRefused(`payload holds [${found.join(', ')}], expected [${want.join(', ')}]`)+ }+ const host = await canary(d.probe, join(staging, 'harness-pty.exe'))+ if (!host || typeof host !== 'object') throw new PtyPayloadRefused('harness-pty version is not a JSON object')+ const h = host as { version?: unknown; protocol?: unknown; features?: unknown }+ if (h.version !== entry.version) throw new PtyPayloadRefused(`harness-pty reports version ${String(h.version)}, expected ${entry.version}`)+ // Above this CLI's: the host of a protocol bump, kept for the CLI build that needs it. Below every supported one+ // (or not a protocol at all): no build will ever need it.+ const paired = Number.isSafeInteger(h.protocol) && (h.protocol as number) > PTY_PROTOCOL+ if (typeof h.protocol !== 'number' || (!paired && !SUPPORTED_PTY_PROTOCOLS.includes(h.protocol))) {+ throw new PtyPayloadRefused(`harness-pty speaks unsupported protocol ${String(h.protocol)}`)+ }+ if (!Array.isArray(h.features) || !h.features.every((f) => typeof f === 'string')) {+ throw new PtyPayloadRefused('harness-pty reports no features array')+ }+ const serial = await canary(d.probe, join(staging, 'harness-serial.exe'))+ const sv = (serial as { version?: unknown } | null)?.version+ if (sv !== entry.version) throw new PtyPayloadRefused(`harness-serial reports version ${String(sv)}, expected ${entry.version}`)+ // A version is no proof the host serves: one whose conpty.dll does not load, or that cannot bind or start a pane,+ // would be kept by a probation that judges the core, and every new pane would fail on it.+ await serves(d.serve, join(staging, 'harness-pty.exe'), { protocol: h.protocol, version: entry.version })+ return { version: entry.version, staging, protocol: h.protocol, features: h.features as string[], paired }+ } catch (e) {+ removeFolder(staging)+ // Content failures are refusals (the caller backs off); anything else (network, disk, a missing unzip+ // tool) is transient and rethrown as it is, so the next check retries, as selfUpdate's refuse vs rethrow.+ throw e+ }+}++/** Deleting a just-run exe on Windows often fails EBUSY/EPERM; that must not replace the real error. */+function removeFolder(dir: string): boolean {+ try {+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 })+ return true+ } catch {+ return false+ }+}++/** Delete stale `<runtime>/pty/.staging-*` folders left by an interrupted run; those still locked stay for+ * the next sweep. Returns how many were removed. */+export function sweepStagingFolders(runtimeDir: string): number {+ const root = join(runtimeDir, 'pty')+ let names: string[]+ try { names = readdirSync(root) } catch { return 0 }+ let removed = 0+ for (const n of names) if (n.startsWith('.staging-') && removeFolder(join(root, n))) removed+++ return removed+}diff --git a/cli/src/lib/windows/ptyUpdate.spec.ts b/cli/src/lib/windows/ptyUpdate.spec.tsnew file mode 100644index 000000000..694c3fad8--- /dev/null+++ b/cli/src/lib/windows/ptyUpdate.spec.ts@@ -0,0 +1,655 @@+import { createHash } from 'crypto'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { SpawnLockBusyError } from '../daemonSpawnLock.js'+import { PTY_PROTOCOL } from '../ptyHost/protocol.js'+import { restore as restoreCli, startSelfUpdater } from '../selfUpdate.js'+import { installPreparedPty, rejectedPtyVersions } from './ptyInstall.js'+import { PTY_PAYLOAD_FILES, PtyPayloadRefused, PtyPayloadUnpackFailed, type PreparedPty, type PtyEntry } from './ptyPayload.js'+import {+ installedPtyProtocol, keepStaged, ptyOnProbation, ptyUnjudged, rollBackStaged, startPtyUpdater, sweepPtyLeftovers, takeBackPty,+ type PtyPoller, type PtyUpdaterDeps,+} from './ptyUpdate.js'++let root: string+let ptyRoot: string+let bin: string+const pollers: PtyPoller[] = []+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'pty-update-'))+ ptyRoot = join(root, 'runtime', 'pty')+ bin = join(root, 'bin')+ // The machine as install.ps1 leaves it: 0.10.0 in use, its two bin files copied out of its folder.+ mkdirSync(join(ptyRoot, '0.10.0'), { recursive: true })+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.10.0', name), `old ${name}`)+ writeFileSync(join(ptyRoot, 'current-pty'), '0.10.0\r\n')+ mkdirSync(bin)+ for (const name of ['harness.exe', 'harness-launch.exe']) writeFileSync(join(bin, name), `old ${name}`)+})+afterEach(() => {+ for (const poller of pollers.splice(0)) poller.stop()+ vi.useRealTimers()+ rmSync(root, { recursive: true, force: true })+})++const entryOf = (version = '0.11.0', sha = 'a'): PtyEntry => ({ version, url: 'https://cdn.test/pty.zip', sha256: sha.repeat(64), size: 10 })+const pointer = () => readFileSync(join(ptyRoot, 'current-pty'), 'utf8').trim()+const waitTicks = (n: number) => new Promise((resolve) => setTimeout(resolve, 20 * n + 10))++/** A staging folder as preparePtyPayload leaves it; [protocol] above this CLI's makes it a paired payload. */+function stagingFor(version: string, protocol = 2): PreparedPty {+ const staging = join(ptyRoot, `.staging-1-${Math.random().toString(36).slice(2)}`)+ mkdirSync(staging, { recursive: true })+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(staging, name), `new ${name}`)+ return { version, staging, protocol, features: ['seed'], paired: protocol > PTY_PROTOCOL }+}++/** A poller over the temp root, with the lock, the manifest and the download in the test's hands. */+function harness(over: {+ entry?: () => PtyEntry | null+ prepare?: PtyUpdaterDeps['prepare']+ withLock?: <T>(fn: () => Promise<T>) => Promise<T>+ intervalMs?: number+ deps?: Partial<PtyUpdaterDeps>+} = {}) {+ const events: string[] = []+ const lines: string[] = []+ const staged: string[] = []+ let held = false+ const lock = over.withLock ?? (async <T>(fn: () => Promise<T>): Promise<T> => {+ held = true+ try { return await fn() } finally { held = false }+ })+ const poller = startPtyUpdater({+ url: 'https://cdn.test/pty/metadata.json', key: 'win32-x64', rootDir: root, intervalMs: over.intervalMs ?? 20,+ installedCli: () => '1.2.3',+ withLock: lock,+ onStaged: (version) => { events.push(`staged ${version} ${held ? 'locked' : 'unlocked'}`); staged.push(version) },+ deps: {+ fetchEntry: async () => { events.push('fetch'); return over.entry ? over.entry() : entryOf() },+ prepare: over.prepare ?? (async (entry) => { events.push(`prepare ${entry.version} ${held ? 'locked' : 'unlocked'}`); return stagingFor(entry.version) }),+ log: (line) => lines.push(line),+ error: (line) => lines.push(line),+ ...over.deps,+ },+ })+ pollers.push(poller)+ return { poller, events, lines, staged }+}++describe('startPtyUpdater', () => {+ it('a newer entry is installed under the lock and onStaged gets its version', async () => {+ const h = harness()+ await vi.waitFor(() => expect(h.staged).toEqual(['0.11.0']), { timeout: 2_000 })+ // Downloaded outside the lock; installed and handed over inside it.+ expect(h.events.filter((e) => !e.startsWith('fetch'))).toEqual(['prepare 0.11.0 unlocked', 'staged 0.11.0 locked'])+ expect(pointer()).toBe('0.11.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ expect(JSON.parse(readFileSync(join(ptyRoot, 'pty-pending.json'), 'utf8'))).toEqual({ version: '0.11.0', previous: '0.10.0' })+ expect(h.lines).toContain('[update] newer terminal host available: 0.10.0 → 0.11.0')+ expect(h.lines).toContain('[update] staged terminal host 0.11.0 — handing over')+ // Once staged, it stops: the process is restarted onto what it staged.+ const fetched = h.events.filter((e) => e === 'fetch').length+ await waitTicks(3)+ expect(h.events.filter((e) => e === 'fetch').length).toBe(fetched)+ })++ it('a pointer that moved past it while downloading stages nothing', async () => {+ const h = harness({+ prepare: async (entry) => {+ // install.ps1 put a newer host in while this one downloaded.+ writeFileSync(join(ptyRoot, 'current-pty'), '0.12.0')+ return stagingFor(entry.version)+ },+ })+ await vi.waitFor(() => expect(h.lines.some((l) => l.includes('no longer an update'))).toBe(true), { timeout: 2_000 })+ await waitTicks(3)+ expect(h.staged).toEqual([])+ expect(pointer()).toBe('0.12.0')+ expect(existsSync(join(ptyRoot, '0.11.0'))).toBe(false)+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(readdirSync(ptyRoot).filter((n) => n.startsWith('.staging-'))).toEqual([])+ expect(h.lines.filter((l) => l.includes('no longer an update'))).toHaveLength(1)+ })++ it('a refused payload backs off', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })+ let sha = 'a'+ const prepared: string[] = []+ const h = harness({+ intervalMs: 1_000,+ entry: () => entryOf('0.11.0', sha),+ prepare: async (entry) => {+ prepared.push(entry.sha256[0])+ if (entry.sha256[0] === 'a') throw new PtyPayloadRefused('digest mismatch: nope')+ return stagingFor(entry.version)+ },+ })+ await vi.advanceTimersByTimeAsync(1_000)+ expect(prepared).toEqual(['a'])+ expect(h.lines).toContain('[update] terminal host 0.11.0 was refused (digest mismatch: nope) — not trying it again for 2 s')+ // Two intervals before it is tried again: the check between downloads nothing.+ await vi.advanceTimersByTimeAsync(1_000)+ expect(prepared).toEqual(['a'])+ await vi.advanceTimersByTimeAsync(1_000)+ expect(prepared).toEqual(['a', 'a'])+ // Said once for the version, whatever the back-off.+ expect(h.lines.filter((l) => l.includes('not trying it again'))).toHaveLength(1)+ // A new entry for it is tried at once.+ sha = 'b'+ await vi.advanceTimersByTimeAsync(1_000)+ expect(prepared).toEqual(['a', 'a', 'b'])+ await vi.advanceTimersByTimeAsync(1_000)+ expect(h.staged).toEqual(['0.11.0'])+ })++ it('a transient failure is retried next check with no back-off', async () => {+ let prepared = 0+ const h = harness({ prepare: async (entry) => { prepared++; if (prepared === 1) throw new Error('ECONNRESET'); return stagingFor(entry.version) } })+ await vi.waitFor(() => expect(h.staged).toEqual(['0.11.0']), { timeout: 2_000 })+ expect(h.lines.some((l) => l.includes('check failed') && l.includes('ECONNRESET'))).toBe(true)+ expect(h.lines.some((l) => l.includes('not trying it again'))).toBe(false)+ })++ it('a payload verified but not unpacked is unpacked again next check from the bytes kept, not downloaded again', async () => {+ const zip = Buffer.from('verified zip')+ const given: Array<Buffer | undefined> = []+ let sha = 'a'+ const h = harness({+ entry: () => entryOf('0.11.0', sha),+ prepare: async (entry, _runtimeDir, verified) => {+ given.push(verified)+ if (given.length === 1) throw new PtyPayloadUnpackFailed(zip, new Error('tar exited 1'))+ if (given.length === 3) throw new PtyPayloadUnpackFailed(Buffer.from('other zip'), new Error('EBUSY'))+ return stagingFor(entry.version)+ },+ withLock: async (fn) => { if (given.length >= 2 && sha === 'a') throw new SpawnLockBusyError(null); return fn() },+ })+ await vi.waitFor(() => expect(given).toHaveLength(2), { timeout: 2_000 })+ expect(given[0]).toBeUndefined()+ expect(given[1]).toBe(zip)+ expect(h.lines).toContain('[update] terminal host 0.11.0 was downloaded but could not be unpacked (tar exited 1) — unpacking it again next check, from the bytes already verified')+ expect(h.lines.some((l) => l.includes('not trying it again'))).toBe(false)+ // Another entry's bytes are never handed to it.+ sha = 'b'+ await vi.waitFor(() => expect(given).toHaveLength(4), { timeout: 2_000 })+ expect(given[2]).toBeUndefined()+ expect(given[3]?.toString()).toBe('other zip')+ await vi.waitFor(() => expect(h.staged).toEqual(['0.11.0']), { timeout: 2_000 })+ })++ it('a busy lock retries the install next tick without downloading again', async () => {+ let busy = 0+ const h = harness({+ withLock: async (fn) => {+ // Busy once, for the install (the start sweep before it gets the lock).+ if (h.events.some((e) => e.startsWith('prepare')) && busy++ === 0) throw new SpawnLockBusyError(null)+ return fn()+ },+ })+ await vi.waitFor(() => expect(h.staged).toEqual(['0.11.0']), { timeout: 2_000 })+ expect(busy).toBe(2)+ expect(h.events.filter((e) => e.startsWith('prepare'))).toHaveLength(1)+ expect(h.lines.filter((l) => l.includes('terminal host 0.11.0 is ready but the daemon spawn lock is'))).toHaveLength(1)+ })++ it('readyToStage installs a prepared payload, and returns null when there is none', async () => {+ // A lock that never lets the poller in on its own: only the CLI's handover (which holds it) installs.+ const h = harness({ withLock: async () => { throw new SpawnLockBusyError(null) } })+ expect(await h.poller.readyToStage()).toBeNull()+ await vi.waitFor(() => expect(h.events).toContain('prepare 0.11.0 unlocked'), { timeout: 2_000 })+ expect(await h.poller.readyToStage()).toEqual({ version: '0.11.0', protocol: 2, paired: false })+ expect(pointer()).toBe('0.11.0')+ // Taken into the CLI's handover: the poller stages nothing more, on its own or for the CLI.+ expect(h.staged).toEqual([])+ expect(await h.poller.readyToStage()).toBeNull()+ })++ it('a payload the manifest withdraws, or moves back from, is never installed by the next CLI stage', async () => {+ for (const after of [null, entryOf('0.10.0'), entryOf('0.11.0', 'b')]) {+ let offered: PtyEntry | null = entryOf()+ // Never in on its own: only the CLI's handover could install it.+ const h = harness({ entry: () => offered, withLock: async () => { throw new SpawnLockBusyError(null) } })+ await vi.waitFor(() => expect(h.events).toContain('prepare 0.11.0 unlocked'), { timeout: 2_000 })+ offered = after+ const fetched = h.events.filter((e) => e === 'fetch').length+ await vi.waitFor(() => expect(h.events.filter((e) => e === 'fetch').length).toBeGreaterThan(fetched), { timeout: 2_000 })+ if (after?.sha256.startsWith('b')) {+ // Replaced by other bytes: the new ones are prepared, never the old.+ await vi.waitFor(() => expect(h.events.filter((e) => e === 'prepare 0.11.0 unlocked')).toHaveLength(2), { timeout: 2_000 })+ h.poller.stop()+ continue+ }+ expect(await h.poller.readyToStage()).toBeNull()+ expect(pointer()).toBe('0.10.0')+ expect(readdirSync(ptyRoot).filter((n) => n.startsWith('.staging-'))).toEqual([])+ h.poller.stop()+ }+ })++ it('readyToStage never holds the CLI up: an install that fails is said and is null', async () => {+ const h = harness({+ withLock: async () => { throw new SpawnLockBusyError(null) },+ deps: { install: () => { throw new Error('EIO: disk gone') } },+ })+ await vi.waitFor(() => expect(h.events).toContain('prepare 0.11.0 unlocked'), { timeout: 2_000 })+ expect(await h.poller.readyToStage()).toBeNull()+ expect(h.lines.some((l) => l.includes('terminal host 0.11.0') && l.includes('EIO: disk gone'))).toBe(true)+ })++ it('a host on probation is nothing to do: no download, no back-off', async () => {+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.10.0', previous: '0.9.0' }))+ const h = harness()+ await waitTicks(4)+ expect(h.events).toEqual([])+ expect(h.staged).toEqual([])+ expect(h.lines.some((l) => l.includes('not trying it again'))).toBe(false)+ })++ it('a machine with no installed host, a dev CLI or a rejected version takes nothing', async () => {+ writeFileSync(join(ptyRoot, 'pty-rejected.json'), JSON.stringify(['0.11.0']))+ const h = harness()+ await waitTicks(4)+ expect(h.events.filter((e) => e !== 'fetch')).toEqual([])+ })++ it('stopped, stages nothing', async () => {+ const h = harness({ prepare: async (entry) => { h.poller.stop(); return stagingFor(entry.version) } })+ await waitTicks(4)+ expect(h.staged).toEqual([])+ expect(pointer()).toBe('0.10.0')+ expect(readdirSync(ptyRoot).filter((n) => n.startsWith('.staging-'))).toEqual([])+ })+})++describe('a host for a CLI build that needs it (the pairing rule)', () => {+ const above = PTY_PROTOCOL + 1++ it('host-3 alone is never installed: not by its own check, nor for a CLI build that does not need it', async () => {+ const h = harness({ prepare: async (entry) => { h.events.push(`prepare ${entry.version}`); return stagingFor(entry.version, above) } })+ await vi.waitFor(() => expect(h.events).toContain('prepare 0.11.0'), { timeout: 2_000 })+ await waitTicks(5)+ expect(h.staged).toEqual([])+ expect(pointer()).toBe('0.10.0')+ expect(h.lines.filter((l) => l === `[update] terminal host 0.11.0 speaks protocol ${above}, above this CLI's ${PTY_PROTOCOL} — it goes in only with a CLI build that needs it`)).toHaveLength(1)+ // Kept, prepared, for the build that needs it: downloaded once.+ expect(h.events.filter((e) => e.startsWith('prepare'))).toHaveLength(1)+ expect(h.poller.readyProtocol()).toBe(above)+ expect(await h.poller.readyToStage()).toBeNull()+ expect(await h.poller.readyToStage(PTY_PROTOCOL)).toBeNull()+ expect(pointer()).toBe('0.10.0')+ expect(await h.poller.readyToStage(above)).toEqual({ version: '0.11.0', protocol: above, paired: true })+ expect(pointer()).toBe('0.11.0')+ expect(h.poller.readyProtocol()).toBeNull()+ })++ it('a host taken back out after its build failed to stage is prepared again once the back-off has passed', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })+ const h = harness({ intervalMs: 1_000, prepare: async (entry) => { h.events.push(`prepare ${entry.version}`); return stagingFor(entry.version, above) } })+ await vi.advanceTimersByTimeAsync(1_000)+ expect(await h.poller.readyToStage(above)).toEqual({ version: '0.11.0', protocol: above, paired: true })+ // The CLI build did not stage: the host goes back out (services/updaterProcess.ts), and the poller is told.+ takeBackPty(root, () => {}, '[update] ')+ expect(pointer()).toBe('0.10.0')+ h.poller.takenBack()+ expect(h.lines).toContain('[update] terminal host 0.11.0 was taken back out with the build it came with — preparing it again in 2 s')+ await vi.advanceTimersByTimeAsync(1_000)+ expect(h.events.filter((e) => e.startsWith('prepare'))).toHaveLength(1)+ await vi.advanceTimersByTimeAsync(1_000)+ expect(h.events.filter((e) => e.startsWith('prepare'))).toHaveLength(2)+ expect(h.poller.readyProtocol()).toBe(above)+ // Taken back again: the back-off doubles, as a refusal's does.+ expect(await h.poller.readyToStage(above)).not.toBeNull()+ takeBackPty(root, () => {}, '[update] ')+ h.poller.takenBack()+ expect(h.lines).toContain('[update] terminal host 0.11.0 was taken back out with the build it came with — preparing it again in 4 s')+ // Nothing to re-arm once stopped, or with nothing installed.+ h.poller.stop()+ h.poller.takenBack()+ await vi.advanceTimersByTimeAsync(10_000)+ expect(h.events.filter((e) => e.startsWith('prepare'))).toHaveLength(2)+ const fresh = harness({ intervalMs: 1_000 })+ fresh.poller.takenBack()+ expect(fresh.lines.filter((l) => l.includes('taken back'))).toEqual([])+ })++ it('a supported payload says its protocol too, and goes in with any build', async () => {+ const h = harness({ withLock: async () => { throw new SpawnLockBusyError(null) } })+ expect(h.poller.readyProtocol()).toBeNull()+ await vi.waitFor(() => expect(h.events).toContain('prepare 0.11.0 unlocked'), { timeout: 2_000 })+ expect(h.poller.readyProtocol()).toBe(2)+ expect(await h.poller.readyToStage(above)).toEqual({ version: '0.11.0', protocol: 2, paired: false })+ })++ describe('with the CLI updater beside it', () => {+ const sha = (b: Buffer): string => createHash('sha256').update(b).digest('hex')+ const notify = Buffer.from('export {}\n')+ const oldCli = Buffer.from('console.log("1.0.0")\n')+ /** A CLI build that needs host protocol [needs]: what its `version --json` says, through the canary. */+ const cliNeeding = (needs: number) => Buffer.from(+ `console.log(process.argv.includes('--json') ? JSON.stringify({ version: '9.9.9', ptyProtocol: ${needs} }) : '9.9.9')\n`,+ )+ const stops: Array<() => void> = []+ afterEach(() => { for (const stop of stops.splice(0)) stop(); vi.unstubAllGlobals(); vi.restoreAllMocks() })++ /** Both pollers as the updater process runs them: one lock, the host first in the CLI's handover. */+ function both(o: { cli: Buffer; hostProtocol: number }) {+ const events: string[] = []+ const handovers: Array<{ version?: string; ptyVersion?: string }> = []+ vi.stubGlobal('fetch', async (url: string) => {+ if (url.endsWith('/metadata.json')) {+ return new Response(JSON.stringify({ adapter: {+ version: '9.9.9', cli: { url: 'https://updates.test/cli.js', sha256: sha(o.cli) }, notify: { url: 'https://updates.test/notify.mjs', sha256: sha(notify) },+ } }))+ }+ return new Response(url.endsWith('cli.js') ? o.cli : notify)+ })+ vi.spyOn(console, 'log').mockImplementation((line: string) => { events.push(String(line)) })+ vi.spyOn(console, 'error').mockImplementation((line: string) => { events.push(String(line)) })+ const dir = join(root, 'cli')+ mkdirSync(dir)+ writeFileSync(join(dir, 'cli.js'), oldCli)+ const pty = startPtyUpdater({+ url: 'https://cdn.test/pty/metadata.json', key: 'win32-x64', rootDir: root, intervalMs: 20, installedCli: () => '1.0.0',+ withLock: (fn) => fn(),+ onStaged: (ptyVersion) => { handovers.push({ ptyVersion }) },+ deps: {+ fetchEntry: async () => entryOf(),+ prepare: async (entry) => stagingFor(entry.version, o.hostProtocol),+ install: (prepared, rootDir) => { events.push(`install host ${prepared.version}`); return installPreparedPty(prepared, rootDir) },+ log: (line) => events.push(line), error: (line) => events.push(line),+ },+ })+ pollers.push(pty)+ const cli = startSelfUpdater({+ currentVersion: '1.0.0', url: 'https://updates.test/metadata.json', key: 'adapter', dir, intervalMs: 20, platform: 'darwin',+ // The host's own `version`: the installed folder's protocol.+ installedPtyProtocol: () => installedPtyProtocol(root, (binary) => ({ protocol: binary.includes('0.11.0') ? o.hostProtocol : 2 })),+ readyPtyProtocol: () => pty.readyProtocol(),+ beforeStage: (needs) => pty.readyToStage(needs),+ onStaged: (version, ptyVersion) => {+ events.push(`stage cli ${readFileSync(join(dir, 'cli.js')).equals(o.cli) ? 'done' : 'not done'}`)+ handovers.push({ version, ...(ptyVersion ? { ptyVersion } : {}) })+ },+ })+ stops.push(() => cli.stop())+ return { dir, events, handovers }+ }++ it('a protocol-2 updater with host-3 payload and CLI-3 build ready installs both in one handover, host first', async () => {+ const m = both({ cli: cliNeeding(above), hostProtocol: above })+ await vi.waitFor(() => expect(m.handovers).toEqual([{ version: '9.9.9', ptyVersion: '0.11.0' }]), { timeout: 5_000 })+ expect(pointer()).toBe('0.11.0')+ const order = m.events.filter((e) => e.startsWith('install host') || e.startsWith('stage cli'))+ expect(order).toEqual(['install host 0.11.0', 'stage cli done'])++ // One probation for the pair: the new core failed, and the master's rollback puts both back.+ rollBackStaged({+ cliPending: () => existsSync(join(m.dir, 'update-pending.json')),+ restoreCli: () => restoreCli(m.dir, 'darwin'),+ ptyRoot: root, log: () => {},+ })+ expect(pointer()).toBe('0.10.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('old harness.exe')+ expect(readFileSync(join(m.dir, 'cli.js'))).toEqual(oldCli)+ expect(rejectedPtyVersions(root)).toEqual(['0.11.0'])+ })++ it('CLI-3 alone waits: with no host payload, or one of another protocol', async () => {+ const m = both({ cli: cliNeeding(above), hostProtocol: 2 })+ const waiting = `[update] 9.9.9 needs pty protocol ${above}; this machine's host speaks 2 — waiting for its payload`+ await vi.waitFor(() => expect(m.events).toContain(waiting), { timeout: 5_000 })+ await waitTicks(5)+ // The protocol-2 host goes in on its own, as any supported one; the CLI build still waits for protocol 3.+ expect(m.handovers).toEqual([{ ptyVersion: '0.11.0' }])+ expect(readFileSync(join(m.dir, 'cli.js'))).toEqual(oldCli)+ })+ })+})++describe('the start sweep', () => {+ it('removes staging folders and aside files under the lock before the first check', async () => {+ mkdirSync(join(ptyRoot, '.staging-9-9'))+ writeFileSync(join(bin, 'harness.exe.old-9-9'), 'stale')+ let held = false+ const order: string[] = []+ const h = harness({+ withLock: async (fn) => { held = true; try { return await fn() } finally { held = false } },+ deps: { sweep: (rootDir, log) => { order.push(`sweep ${held ? 'locked' : 'unlocked'}`); sweepPtyLeftovers(rootDir, log) } },+ })+ await vi.waitFor(() => expect(h.events).toContain('fetch'), { timeout: 2_000 })+ expect(order).toEqual(['sweep locked'])+ expect(existsSync(join(ptyRoot, '.staging-9-9'))).toBe(false)+ expect(existsSync(join(bin, 'harness.exe.old-9-9'))).toBe(false)+ })++ it('puts a missing bin file back from its newest aside file, and sweeps nothing while one stays missing', () => {+ rmSync(join(bin, 'harness.exe'))+ writeFileSync(join(bin, 'harness.exe.old-5-100'), 'older')+ writeFileSync(join(bin, 'harness.exe.old-4-200'), 'newest')+ const lines: string[] = []+ sweepPtyLeftovers(root, (line) => lines.push(line))+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('newest')+ expect(lines).toContain('[update] put bin\\harness.exe back from harness.exe.old-4-200')+ // Back in place: the rest is swept.+ expect(readdirSync(bin).sort()).toEqual(['harness-launch.exe', 'harness.exe'])++ // A path missing whose aside file cannot be put back: nothing is swept, its bytes stay.+ rmSync(join(bin, 'harness.exe'))+ writeFileSync(join(bin, 'harness.exe.old-1-1'), 'aside')+ writeFileSync(join(bin, 'harness-launch.exe.old-1-1'), 'aside')+ const failed: string[] = []+ const fs = { rename: () => { throw Object.assign(new Error('held'), { code: 'EBUSY' }) } }+ sweepPtyLeftovers(root, (line) => failed.push(line), fs)+ expect(existsSync(join(bin, 'harness-launch.exe.old-1-1'))).toBe(true)+ expect(existsSync(join(bin, 'harness.exe.old-1-1'))).toBe(true)+ expect(failed).toEqual(['[update] bin\\harness.exe is missing and harness.exe.old-1-1 could not be put back (held) — nothing is swept until it is'])+ })+})++describe("the master's rollback and keep", () => {+ /** 0.11.0 installed over 0.10.0 and on probation. */+ function onProbation(): void {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.11.0', name), `new ${name}`)+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '0.10.0' }))+ for (const name of ['harness.exe', 'harness-launch.exe']) writeFileSync(join(bin, name), `new ${name}`)+ }++ it('rolls back the host on probation, and the CLI only when a CLI build is pending', () => {+ onProbation()+ const calls: string[] = []+ const lines: string[] = []+ rollBackStaged({ cliPending: () => false, restoreCli: () => calls.push('restore cli'), ptyRoot: root, log: (l) => lines.push(l) })+ expect(calls).toEqual([])+ expect(pointer()).toBe('0.10.0')+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('old harness.exe')+ expect(rejectedPtyVersions(root)).toEqual(['0.11.0'])+ expect(lines).toEqual(['[harnessd] terminal host 0.11.0 did not come back healthy — back to 0.10.0'])+ // Nothing on probation now: a second rollback is the CLI's alone.+ rollBackStaged({ cliPending: () => true, restoreCli: () => calls.push('restore cli'), ptyRoot: root, log: (l) => lines.push(l) })+ expect(calls).toEqual(['restore cli'])+ expect(lines).toHaveLength(1)+ // Off Windows there is no host payload, and the CLI is restored as it always was.+ rollBackStaged({ cliPending: () => false, restoreCli: () => calls.push('restore cli'), ptyRoot: null, log: (l) => lines.push(l) })+ expect(calls).toEqual(['restore cli', 'restore cli'])+ })++ it('puts a bin file the restore left missing back from its aside file', () => {+ onProbation()+ const lines: string[] = []+ // The copy back of harness.exe failed and so did its undo: the path is missing, its last bytes aside.+ const restorePty = () => {+ renameSync(join(bin, 'harness.exe'), join(bin, 'harness.exe.old-7-123'))+ return { found: true, pointer: true, restored: ['harness-launch.exe'], kept: [], missing: ['harness.exe'] }+ }+ rollBackStaged({ cliPending: () => false, restoreCli: () => {}, ptyRoot: root, log: (l) => lines.push(l), restorePty })+ expect(readFileSync(join(bin, 'harness.exe'), 'utf8')).toBe('new harness.exe')+ expect(lines).toEqual([+ '[harnessd] terminal host 0.11.0 did not come back healthy — back to 0.10.0',+ '[harnessd] put bin\\harness.exe back from harness.exe.old-7-123',+ ])+ })++ it('says a host it could not keep, whose marker then holds host updates back until a start judges it again', () => {+ onProbation()+ const lines: string[] = []+ keepStaged({ confirmCli: () => {}, ptyRoot: root, log: (l) => lines.push(l), confirmPty: () => { throw new Error('EPERM') } })+ expect(lines).toEqual(['[harnessd] could not keep terminal host 0.11.0 (EPERM) — judged again at the next start'])+ expect(ptyOnProbation(root)).toBe('terminal host 0.11.0')+ })++ it('a corrupt marker is judged at a start and cleared by the rollback, the host in use staying', () => {+ writeFileSync(join(ptyRoot, 'pty-pending.json'), '{ not json')+ expect(ptyOnProbation(root)).toBe('terminal host (unreadable marker)')+ const lines: string[] = []+ rollBackStaged({ cliPending: () => false, restoreCli: () => {}, ptyRoot: root, log: (l) => lines.push(l) })+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(pointer()).toBe('0.10.0')+ expect(lines).toEqual(['[harnessd] removed an unreadable terminal host probation marker — the host in use stays'])+ expect(ptyOnProbation(root)).toBeNull()+ })++ it('rolls back and keeps the host under the spawn lock, taken only while a host is on probation', () => {+ const calls: string[] = []+ const lock = () => { calls.push('lock'); return () => calls.push('release') }+ const restorePty = (rootDir: string) => { calls.push('restore pty'); return { found: false, pointer: false, restored: [], kept: [], missing: [], rootDir } }+ rollBackStaged({ cliPending: () => true, restoreCli: () => calls.push('restore cli'), ptyRoot: root, log: () => {}, lock, restorePty })+ expect(calls).toEqual(['restore cli'])+ onProbation()+ calls.length = 0+ rollBackStaged({ cliPending: () => true, restoreCli: () => calls.push('restore cli'), ptyRoot: root, log: () => {}, lock, restorePty })+ expect(calls).toEqual(['lock', 'restore pty', 'release', 'restore cli'])+ calls.length = 0+ keepStaged({ confirmCli: () => calls.push('confirm cli'), ptyRoot: root, lock, confirmPty: () => calls.push('confirm pty') })+ expect(calls).toEqual(['confirm cli', 'lock', 'confirm pty', 'release'])+ // A lock that stays busy: said, and the host judged all the same, as before the lock.+ const lines: string[] = []+ calls.length = 0+ keepStaged({ confirmCli: () => {}, ptyRoot: root, lock: () => null, log: (l) => lines.push(l), confirmPty: () => calls.push('confirm pty') })+ rollBackStaged({ cliPending: () => false, restoreCli: () => {}, ptyRoot: root, log: (l) => lines.push(l), lock: () => null, restorePty })+ expect(calls).toEqual(['confirm pty', 'restore pty'])+ expect(lines).toEqual([+ '[harnessd] the daemon spawn lock is busy — keeping terminal host 0.11.0 without it',+ '[harnessd] the daemon spawn lock is busy — rolling terminal host 0.11.0 back without it',+ ])+ // A keep with nothing on probation takes no lock.+ calls.length = 0+ rmSync(join(ptyRoot, 'pty-pending.json'))+ keepStaged({ confirmCli: () => {}, ptyRoot: root, lock, confirmPty: () => calls.push('confirm pty') })+ expect(calls).toEqual(['confirm pty'])+ })++ it('keeps both', () => {+ onProbation()+ const calls: string[] = []+ keepStaged({ confirmCli: () => calls.push('confirm cli'), ptyRoot: root })+ expect(calls).toEqual(['confirm cli'])+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(pointer()).toBe('0.11.0')+ })+})++describe('takeBackPty', () => {+ /** A paired 0.11.0 installed over 0.10.0, as `readyToStage` leaves it, and rejected nowhere yet. */+ function pairedIn(): void {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.11.0', name), `new ${name}`)+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '0.10.0' }))+ }++ it('puts the previous host back, takes back the rejection the restore records, and says so', () => {+ pairedIn()+ const lines: string[] = []+ takeBackPty(root, (l) => lines.push(l), '[update] ')+ expect(pointer()).toBe('0.10.0')+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(rejectedPtyVersions(root)).toEqual([])+ expect(lines).toEqual(['[update] terminal host 0.11.0 taken back out with the build it came with — back to 0.10.0'])+ })++ it('says the host stays when the version before it is no longer there to go back to', () => {+ pairedIn()+ rmSync(join(ptyRoot, '0.10.0'), { recursive: true })+ const lines: string[] = []+ takeBackPty(root, (l) => lines.push(l), ' ', ' ✗ ')+ expect(pointer()).toBe('0.11.0')+ expect(lines).toEqual([' ✗ terminal host 0.11.0 could not be taken back out: 0.10.0 is no longer there to go back to — it stays'])+ })++ it('on a failure, says the marker stays for the next master, which may keep it', () => {+ pairedIn()+ // The rejection the restore records first cannot be written: a folder stands where it goes.+ mkdirSync(join(ptyRoot, 'pty-rejected.json'))+ const lines: string[] = []+ takeBackPty(root, (l) => lines.push(l), ' ', ' ✗ ')+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(true)+ expect(lines).toHaveLength(1)+ expect(lines[0]).toMatch(/^ {2}✗ could not take terminal host 0\.11\.0 back out \(.+\) — it stays on probation: the next master takes it back out, or judges it and may keep it$/)+ })+})++describe("a master's start: a host this build cannot speak on probation (ptyUnjudged)", () => {+ function onProbation(): void {+ mkdirSync(join(ptyRoot, '0.11.0'))+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.11.0', name), `new ${name}`)+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '0.10.0' }))+ }+ const speaks = (protocol: number | null) => () => protocol++ it('takes back a host of a protocol it does not support, with no CLI build pending, instead of judging it', () => {+ onProbation()+ const lines: string[] = []+ const calls: string[] = []+ const lock = () => { calls.push('lock'); return () => calls.push('release') }+ expect(ptyUnjudged(root, { cliPending: false, log: (l) => lines.push(l), protocol: speaks(PTY_PROTOCOL + 1), lock })).toBeNull()+ expect(calls).toEqual(['lock', 'release'])+ expect(pointer()).toBe('0.10.0')+ expect(rejectedPtyVersions(root)).toEqual([])+ expect(lines).toEqual([+ `[harnessd] terminal host 0.11.0 is on probation with no CLI build, and speaks protocol ${PTY_PROTOCOL + 1}, which this build does not — taking it back out rather than judging it`,+ '[harnessd] terminal host 0.11.0 taken back out with the build it came with — back to 0.10.0',+ ])+ })++ it('judges it as before when it speaks a supported protocol, a CLI build is pending, its protocol cannot be read, or the take-back fails', () => {+ onProbation()+ const lines: string[] = []+ expect(ptyUnjudged(root, { cliPending: false, log: (l) => lines.push(l), protocol: speaks(PTY_PROTOCOL), lock: () => () => {} })).toBe('terminal host 0.11.0')+ expect(ptyUnjudged(root, { cliPending: true, log: (l) => lines.push(l), protocol: speaks(PTY_PROTOCOL + 1), lock: () => () => {} })).toBe('terminal host 0.11.0')+ expect(ptyUnjudged(root, { cliPending: false, log: (l) => lines.push(l), protocol: speaks(null), lock: () => () => {} })).toBe('terminal host 0.11.0')+ expect(lines).toEqual([])+ mkdirSync(join(ptyRoot, 'pty-rejected.json'))+ expect(ptyUnjudged(root, { cliPending: false, log: (l) => lines.push(l), protocol: speaks(PTY_PROTOCOL + 1), lock: () => null })).toBe('terminal host 0.11.0')+ expect(lines[0]).toBe('[harnessd] the daemon spawn lock is busy — taking terminal host 0.11.0 back out without it')+ expect(lines.at(-1)).toMatch(/could not take terminal host 0\.11\.0 back out/)+ expect(pointer()).toBe('0.11.0')+ })++ it('takes no lock and reads nothing with no host on probation', () => {+ const calls: string[] = []+ expect(ptyUnjudged(root, { cliPending: false, log: () => {}, protocol: () => { calls.push('protocol'); return 3 }, lock: () => { calls.push('lock'); return null } })).toBeNull()+ expect(calls).toEqual([])+ writeFileSync(join(ptyRoot, 'pty-pending.json'), '{ not json')+ expect(ptyUnjudged(root, { cliPending: false, log: () => {}, protocol: () => { calls.push('protocol'); return 3 } , lock: () => { calls.push('lock'); return () => {} } })).toBe('terminal host (unreadable marker)')+ expect(calls).toEqual([])+ })+})++describe('installedPtyProtocol', () => {+ it('is the protocol of the host current-pty names, or null when there is none to read', () => {+ const asked: string[] = []+ const version = (binary: string) => { asked.push(binary); return binary.includes('0.10.0') ? { protocol: 2 } : null }+ expect(installedPtyProtocol(root, version)).toBe(2)+ expect(asked).toEqual([join(ptyRoot, '0.10.0', 'harness-pty.exe')])+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ expect(installedPtyProtocol(root, version)).toBeNull()+ rmSync(join(ptyRoot, 'current-pty'))+ expect(installedPtyProtocol(root, version)).toBeNull()+ })+})diff --git a/cli/src/lib/windows/ptyUpdate.ts b/cli/src/lib/windows/ptyUpdate.tsnew file mode 100644index 000000000..d0cf3fce2--- /dev/null+++ b/cli/src/lib/windows/ptyUpdate.ts@@ -0,0 +1,503 @@+/**+ * The terminal host's self-update on Windows (spec §5): the updater process (services/updaterProcess.ts) polls the PTY+ * manifest beside the CLI's, downloads and canaries a promoted payload outside the lock (./ptyPayload.ts), installs it+ * under the daemon spawn lock (./ptyInstall.ts) and tells harnessd's master, which hands over to a new core and judges+ * it on the CLI's probation. When both have an update, the CLI's poller takes the prepared payload into its own lock+ * hold and handover, first (`readyToStage`), so the daemon restarts once.+ *+ * A payload whose host speaks a protocol above this CLI's (a protocol bump's) is canaried like any other but never+ * installed on its own: no daemon of this build could open a pane on it. It waits, prepared, for the CLI build whose+ * `version --json` needs exactly that protocol, and goes into that build's handover, first; one probation judges the+ * pair (spec §5, the pairing rule beside the protocol rule).+ *+ * Also the master's half: what its probation runs when the new core fails (`rollBackStaged`) or stays up+ * (`keepStaged`), for the CLI build and the host alike, and the start-of-updater sweep of what installs leave behind.+ * Nothing here calls a Windows API, so it is tested on every OS.+ */+import { existsSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { SpawnLockBusyError, describeSpawnLockFailure } from '../daemonSpawnLock.js'+import { binaryVersion, currentPtyVersion } from '../ptyHost/launch.js'+import { PTY_PROTOCOL, SUPPORTED_PTY_PROTOCOLS } from '../ptyHost/protocol.js'+import { REFUSED_RETRY_MAX_MS, msUntilSlot, type Poller } from '../selfUpdate.js'+import {+ BIN_FILES, PTY_PENDING, PTY_REJECTED, confirmPty, defaultPtyInstallFs, installPreparedPty, readPtyPending, rejectedPtyVersions, restorePty,+ sweepAsideFiles, type PtyInstallFs, type PtyPending, type PtyRestore,+} from './ptyInstall.js'+import {+ PtyPayloadRefused, PtyPayloadUnpackFailed, fetchPtyEntry, preparePtyPayload, ptyUpdateWanted, sweepCanaryHomes, sweepStagingFolders,+ type PreparedPty,+ type PtyEntry,+} from './ptyPayload.js'++export interface PtyUpdaterDeps {+ fetchEntry: (url: string, key: string) => Promise<PtyEntry | null>+ /** [verified]: the entry's bytes, downloaded and verified at an earlier check whose unpack failed+ * (`PtyPayloadUnpackFailed`): unpacked again, not downloaded again. */+ prepare: (entry: PtyEntry, runtimeDir: string, verified?: Buffer) => Promise<PreparedPty>+ install: (prepared: PreparedPty, rootDir: string) => boolean+ /** Remove the staging folder of a payload that will not be installed. */+ discard: (prepared: PreparedPty) => void+ /** What the poller runs once, under the lock, before its first check. */+ sweep: (rootDir: string, log: (line: string) => void) => void+ now: () => number+ log: (line: string) => void+ error: (line: string) => void+}++const DEFAULT_DEPS: PtyUpdaterDeps = {+ fetchEntry: (url, key) => fetchPtyEntry(url, key),+ prepare: (entry, runtimeDir, verified) => preparePtyPayload(entry, runtimeDir, {}, verified),+ install: (prepared, rootDir) => installPreparedPty(prepared, rootDir),+ discard: (prepared) => {+ // A just-run canary can hold a file a moment; what is left is the next start's sweep's.+ try { rmSync(prepared.staging, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }) } catch { /* swept later */ }+ },+ sweep: (rootDir, log) => sweepPtyLeftovers(rootDir, log),+ now: () => Date.now(),+ log: (line) => console.log(line),+ error: (line) => console.error(line),+}++/** A host `readyToStage` installed: its protocol, from its canary, and whether it was a paired one. */+export interface StagedHost { version: string; protocol: number; paired: boolean }++export type PtyPoller = Poller & {+ /** Under a lock the caller already holds: install the payload already prepared and return its version, or null+ * when there is none (or it can no longer be installed). [forPtyProtocol]: the host protocol the CLI build being+ * staged needs; a paired payload (./ptyPayload.ts `PreparedPty.paired`) goes in only for a build that needs exactly+ * its protocol. Never throws: the CLI's stage goes on either way, under the protocol rule. */+ readyToStage(forPtyProtocol?: number): Promise<StagedHost | null>+ /** The protocol of the payload prepared and waiting, or null: what lets a CLI build that needs it go ahead+ * (lib/selfUpdate.ts `readyPtyProtocol`), with it first. */+ readyProtocol(): number | null+ /** The host `readyToStage` installed was taken back out (`takeBackPty`: its CLI build did not stage). The poller,+ * finished by that install, checks again, the payload backed off as a refused one is: the next updater start is+ * otherwise the first to prepare it for the next build. Nothing once stopped, or with nothing installed. */+ takenBack(): void+}++const message = (error: unknown): string => (error instanceof Error ? error.message : String(error))++/**+ * Poll on the CLI's schedule (scheduled ticks on the same slot), for a payload newer than `current-pty`. A download+ * outside the lock; a refused payload backed off as the CLI's (`refuse` in lib/selfUpdate.ts `startSelfUpdater`),+ * a transient failure retried at the next check; under the lock, asked again whether `current-pty` is still older+ * (install.ps1 or `harness update` may have moved it), then installed and handed over (`onStaged`, awaited inside the+ * lock). Nothing is checked while a version is on probation: the master keeps it or rolls it back first.+ *+ * A payload prepared at a check is installed on its own at the next one, not at once: the CLI's check runs on the same+ * slot, and when it stages a build too it takes the payload into its handover (`readyToStage`), so the daemon restarts+ * once for both, the host first. Each log line is said once per version.+ */+export function startPtyUpdater(opts: {+ url: string+ key: string+ /** The install root: `bin\` and `runtime\pty\` are in it. */+ rootDir: string+ intervalMs: number+ /** Wall-clock second the ticks land on, as the CLI's; omit or negative for a plain interval. */+ slotSecond?: number+ /** The CLI build installed: a development one never takes an update (lib/selfUpdate.ts `isLocalDevBuild`). */+ installedCli: () => string+ /** The daemon spawn lock, around the install and `onStaged`. */+ withLock: <T>(fn: () => Promise<T>) => Promise<T>+ onStaged: (ptyVersion: string) => void | Promise<void>+ deps?: Partial<PtyUpdaterDeps>+}): PtyPoller {+ const d: PtyUpdaterDeps = { ...DEFAULT_DEPS, ...opts.deps }+ const runtimeDir = join(opts.rootDir, 'runtime')+ const marker = join(runtimeDir, 'pty', PTY_PENDING)+ let timer: NodeJS.Timeout | null = null+ let checking = false+ let halted = false+ // Downloaded, verified and canaried, waiting for the lock. `fresh`: prepared at this check, left for the CLI's.+ let ready: { key: string; entry: PtyEntry; prepared: PreparedPty; fresh: boolean } | null = null+ let refused: { key: string; tries: number; until: number } | null = null+ // The bytes of an entry downloaded and verified whose unpack failed: the next check unpacks them, and downloads nothing.+ let verified: { key: string; zip: Buffer } | null = null+ // What `installReady` installed last, for `takenBack`.+ let installedLast: { key: string; version: string } | null = null+ let stopped = false+ const told = new Map<string, string>()+ const once = (kind: string, version: string, say: () => void): void => {+ if (told.get(kind) === version) return+ told.set(kind, version)+ say()+ }++ const stop = (): void => { if (timer) { clearTimeout(timer); timer = null } }+ const schedule = (): void => {+ stop()+ timer = setTimeout(() => void tick(), msUntilSlot(d.now(), opts.slotSecond, opts.intervalMs))+ timer.unref?.()+ }+ const finish = (): void => { halted = true; stop() }++ const drop = (): void => {+ if (ready) d.discard(ready.prepared)+ ready = null+ }+ /** Hold [key] back, as the CLI's refusal does: twice as long each time in a row, up to `REFUSED_RETRY_MAX_MS`. */+ const backOff = (key: string): string => {+ const tries = refused?.key === key ? refused.tries + 1 : 1+ const wait = Math.min(opts.intervalMs * 2 ** tries, REFUSED_RETRY_MAX_MS)+ refused = { key, tries, until: d.now() + wait }+ return wait >= 1000 ? `${Math.round(wait / 1000)} s` : `${wait} ms`+ }+ const refuse = (key: string, version: string, reason: string): void => {+ const wait = backOff(key)+ once('refused', version, () => d.error(`[update] terminal host ${version} was refused (${reason}) — not trying it again for ${wait}`))+ }+ /** Whether [entry] is still an update over what is installed now; said once when it no longer is. */+ const wanted = (entry: PtyEntry): boolean => {+ const installed = currentPtyVersion(runtimeDir)+ if (ptyUpdateWanted(entry, { pty: installed, cli: opts.installedCli() }, rejectedPtyVersions(opts.rootDir))) return true+ if (ready?.entry.version === entry.version) {+ drop()+ once('gone', entry.version, () => d.log(`[update] terminal host ${entry.version} is no longer an update: the installed host is now ${installed ?? 'none'}. Nothing was staged.`))+ }+ return false+ }++ /** Under the lock: install what is ready. Null when nothing was installed. A paired payload only for a CLI build that+ * needs its protocol ([forPtyProtocol]), never on its own: it stays ready for that build. */+ const installReady = (forPtyProtocol?: number): StagedHost | null => {+ if (halted || !ready) return null+ const { key, entry, prepared } = ready+ if (prepared.paired && forPtyProtocol !== prepared.protocol) return null+ // Another installer may have moved the pointer, or put a version on probation, since the download began.+ if (!wanted(entry)) return null+ if (existsSync(marker)) { drop(); return null }+ // The install owns the staging folder from here, whatever happens to it.+ ready = null+ let installed: boolean+ try {+ installed = d.install(prepared, opts.rootDir)+ } catch (error) {+ d.discard(prepared)+ if (error instanceof PtyPayloadRefused) { refuse(key, entry.version, error.reason); return null }+ throw error+ }+ if (!installed) return null+ finish()+ installedLast = { key, version: entry.version }+ d.log(`[update] staged terminal host ${entry.version} — handing over`)+ return { version: entry.version, protocol: prepared.protocol, paired: prepared.paired === true }+ }++ // At the updater's start, before any check prepares a staging folder the sweep would take for a stale one.+ const swept = opts.withLock(async () => { d.sweep(opts.rootDir, d.log) })+ .catch((error: unknown) => d.error(`[update] could not sweep the terminal host's leftovers (${message(error)}) — the next start tries again`))++ const tick = async (): Promise<void> => {+ // Booked first, from the clock, as the CLI's: a slow download neither drifts the slot nor ends the chain.+ schedule()+ if (checking) return+ checking = true+ try {+ await swept+ if (halted) return+ if (existsSync(marker)) return+ const entry = await d.fetchEntry(opts.url, opts.key)+ if (halted) return+ // What was prepared is installed only while the manifest still offers it: one withdrawn, replaced or moved back+ // goes, before the CLI's next stage could take it into its handover (`readyToStage`).+ const key = entry ? `${entry.version} ${entry.sha256}` : null+ if (ready && ready.key !== key) drop()+ if (verified && verified.key !== key) verified = null+ if (!entry || key === null || !wanted(entry)) return+ if (!ready) {+ if (refused?.key === key && d.now() < refused.until) return+ once('available', entry.version, () => d.log(`[update] newer terminal host available: ${currentPtyVersion(runtimeDir)} → ${entry.version}`))+ let prepared: PreparedPty+ try {+ prepared = await d.prepare(entry, runtimeDir, verified?.key === key ? verified.zip : undefined)+ } catch (error) {+ if (error instanceof PtyPayloadUnpackFailed) {+ verified = { key, zip: error.zip }+ d.error(`[update] terminal host ${entry.version} was downloaded but could not be unpacked (${error.reason}) — unpacking it again next check, from the bytes already verified`)+ return+ }+ verified = null+ if (!(error instanceof PtyPayloadRefused)) throw error+ refuse(key, entry.version, error.reason)+ return+ }+ verified = null+ ready = { key, entry, prepared, fresh: true }+ if (halted) { drop(); return }+ }+ if (ready.prepared.paired) {+ const { version, protocol } = ready.prepared+ once('paired', version, () => d.log(`[update] terminal host ${version} speaks protocol ${protocol}, above this CLI's ${PTY_PROTOCOL} — it goes in only with a CLI build that needs it`))+ return+ }+ if (ready.fresh) { ready.fresh = false; return }+ const version = ready.entry.version+ await opts.withLock(async () => {+ const staged = installReady()+ // From the marker's write to the master hearing `harnessd:staged` is one IPC send: an updater killed in that+ // window leaves a host on probation this master never judges, until a master's start does (`unjudgedUpdate`).+ if (staged !== null) await opts.onStaged(staged.version)+ }).catch((error: unknown) => {+ // A busy lock is no failed check: the payload is good and waiting, and the next tick tries again.+ if (!(error instanceof SpawnLockBusyError)) throw error+ once('busy', version, () => d.log(`[update] terminal host ${version} is ready but the daemon spawn lock is ${describeSpawnLockFailure(error)} — trying again next check`))+ })+ } catch (error) {+ d.error(`[update] terminal host check failed (will retry): ${message(error)}`)+ } finally {+ checking = false+ }+ }++ schedule()+ return {+ stop: () => {+ stopped = true+ finish()+ // A download under way finds `halted` and discards what it prepared; one already waiting goes now.+ if (!checking) drop()+ },+ takenBack: () => {+ if (stopped || !installedLast) return+ const { key, version } = installedLast+ installedLast = null+ halted = false+ const wait = backOff(key)+ d.log(`[update] terminal host ${version} was taken back out with the build it came with — preparing it again in ${wait}`)+ schedule()+ },+ readyProtocol: () => ready?.prepared.protocol ?? null,+ readyToStage: async (forPtyProtocol?: number) => {+ const version = ready?.entry.version+ try {+ return installReady(forPtyProtocol)+ } catch (error) {+ d.error(`[update] terminal host ${version} could not be installed (${message(error)}) — trying again next check`)+ return null+ }+ },+ }+}++/**+ * The protocol the host `current-pty` names speaks (`harness-pty.exe version`, run once per build: ptyHost/launch.ts+ * `binaryVersion`), or null when there is no pointer or the host cannot be read. The CLI's updater holds back a build+ * that needs more (lib/selfUpdate.ts `installedPtyProtocol`, spec §5's protocol rule).+ */+export function installedPtyProtocol(rootDir: string, version: (binary: string) => { protocol: number } | null = binaryVersion): number | null {+ const runtimeDir = join(rootDir, 'runtime')+ const current = currentPtyVersion(runtimeDir)+ return current === null ? null : version(join(runtimeDir, 'pty', current, 'harness-pty.exe'))?.protocol ?? null+}++/** The aside files (`<name>.old-<pid>-<ms>`) of bin\[name], newest first. */+function asideFiles(bin: string, name: string): string[] {+ const pattern = new RegExp(`^${name.replace(/[.]/g, '\\.')}\\.old-(\\d+)-(\\d+)$`)+ let names: string[]+ try { names = readdirSync(bin) } catch { return [] }+ return names.map((n) => ({ n, m: pattern.exec(n) })).filter((x) => x.m)+ .sort((a, b) => Number(b.m![2]) - Number(a.m![2]) || Number(b.m![1]) - Number(a.m![1])).map((x) => x.n)+}++interface PutBack { restored: Array<{ name: string; from: string }>; failed: Array<{ name: string; from: string; error: unknown }> }++/**+ * Put bin\[name] back from its newest aside file, for each of [names] that is missing and has one: a rollback whose+ * copy back failed, undo and all, leaves the path missing and its last bytes aside (./ptyInstall.ts `PtyRestore`).+ */+export function putBackAside(rootDir: string, names: readonly string[], fs: Pick<PtyInstallFs, 'rename'> = defaultPtyInstallFs): PutBack {+ const bin = join(rootDir, 'bin')+ const result: PutBack = { restored: [], failed: [] }+ for (const name of names) {+ if (existsSync(join(bin, name))) continue+ const from = asideFiles(bin, name)[0]+ if (!from) continue+ try {+ fs.rename(join(bin, from), join(bin, name))+ result.restored.push({ name, from })+ } catch (error) {+ result.failed.push({ name, from, error })+ }+ }+ return result+}++/**+ * What an updater sweeps as it starts, under the lock: staging folders an interrupted check left, stale serve canary homes+ * in the temporary folder (./ptyPayload.ts `sweepCanaryHomes`), and bin\'s aside and temporary files (./ptyInstall.ts+ * `sweepAsideFiles`). A bin file that is missing is put back from its aside file first; while one cannot be, nothing in+ * bin\ is swept, as its aside file holds the only copy of its bytes.+ */+export function sweepPtyLeftovers(rootDir: string, log: (line: string) => void, fs: Partial<PtyInstallFs> = {}): void {+ const all: PtyInstallFs = { ...defaultPtyInstallFs, ...fs }+ sweepStagingFolders(join(rootDir, 'runtime'))+ // A serve canary's temporary home whose removal failed (./ptyPayload.ts `serveCanary`).+ sweepCanaryHomes()+ const put = putBackAside(rootDir, BIN_FILES, all)+ for (const { name, from } of put.restored) log(`[update] put bin\\${name} back from ${from}`)+ for (const { name, from, error } of put.failed) {+ log(`[update] bin\\${name} is missing and ${from} could not be put back (${message(error)}) — nothing is swept until it is`)+ }+ if (put.failed.length === 0) sweepAsideFiles(rootDir, all)+}++/**+ * The master's rollback (its probation's `restoreUpdate`): the CLI build only when one is pending (Windows; off it+ * there is no host payload, and the CLI is restored as it always was), and the host whenever `pty-pending.json`+ * exists. Never throws: the supervisor calls it on its way to the next core.+ */+export function rollBackStaged(o: {+ cliPending: () => boolean+ restoreCli: () => void+ /** The install root on Windows; null elsewhere. */+ ptyRoot: string | null+ log: (line: string) => void+ restorePty?: (rootDir: string) => PtyRestore+ readPending?: (rootDir: string) => PtyPending | null+ /** The daemon spawn lock, around the host's restore: the updater sweeps bin\'s aside files under it, and one of them+ * may hold the only copy of a path this restore puts back. Left out, none. */+ lock?: SyncSpawnLock+}): void {+ if (o.ptyRoot !== null) {+ const root = o.ptyRoot+ const pending = (o.readPending ?? readPtyPending)(root)+ if (pending || existsSync(join(root, 'runtime', 'pty', PTY_PENDING))) underLock(o.lock, o.log, `rolling terminal host ${pending?.version ?? '(unreadable marker)'} back`, () => {+ try {+ const result = (o.restorePty ?? restorePty)(root)+ if (pending && result.found) {+ o.log(result.pointer+ ? `[harnessd] terminal host ${pending.version} did not come back healthy — back to ${pending.previous}`+ : `[harnessd] terminal host ${pending.version} did not come back healthy — rejected, but ${pending.previous} is no longer there to go back to`)+ }+ // Before anything sweeps: the aside file is the only copy of that path's bytes.+ const put = putBackAside(root, result.missing)+ for (const { name, from } of put.restored) o.log(`[harnessd] put bin\\${name} back from ${from}`)+ for (const { name, from, error } of put.failed) {+ o.log(`[harnessd] bin\\${name} is missing and ${from} could not be put back (${message(error)}) — the updater sweeps nothing until it is`)+ }+ // A marker no one can read names nothing to go back to; left, it would hold every host update back for good.+ if (!pending) {+ rmSync(join(root, 'runtime', 'pty', PTY_PENDING), { force: true })+ o.log('[harnessd] removed an unreadable terminal host probation marker — the host in use stays')+ }+ } catch (error) {+ o.log(`[harnessd] could not roll terminal host ${pending?.version ?? '(unreadable marker)'} back (${message(error)}) — the next probation tries again`)+ }+ })+ }+ if (o.ptyRoot === null || o.cliPending()) o.restoreCli()+}++/** What a master's start finds on probation for the host (masterProcess.ts `unjudgedUpdate`): `terminal host <v>`, or+ * the same with an unreadable marker, which the rollback clears; null with no marker. */+export function ptyOnProbation(rootDir: string): string | null {+ const pending = readPtyPending(rootDir)+ if (pending) return `terminal host ${pending.version}`+ return existsSync(join(rootDir, 'runtime', 'pty', PTY_PENDING)) ? 'terminal host (unreadable marker)' : null+}++/**+ * Take a paired host back out whose CLI build did not go in with it (spec §5, the pairing rule): left in, the daemon this+ * build runs could open no pane on it, and a master judging it with this build's core would likely keep it. The host+ * goes back as a probation rollback puts it (./ptyInstall.ts `restorePty`, with any missing bin path put back from its+ * aside file), but nothing was wrong with it, so the rejection that rollback records is taken back: it pairs with the+ * next build. Under the lock the install held. Never throws; each line starts with [prefix], or [failedPrefix] when it+ * says what did not happen (`harness update` marks those ✗).+ */+export function takeBackPty(rootDir: string, log: (line: string) => void, prefix: string, failedPrefix: string = prefix): void {+ const pending = readPtyPending(rootDir)+ // Only the rejection this restore adds is taken back: one from before (a version installed anyway, by name) stays.+ const rejectedBefore = rejectedPtyVersions(rootDir)+ try {+ const result = restorePty(rootDir)+ // Before anything sweeps: the aside file is the only copy of that path's bytes.+ const put = putBackAside(rootDir, result.missing)+ for (const { name, from, error } of put.failed) log(`${failedPrefix}bin\\${name} is missing and ${from} could not be put back (${message(error)})`)+ if (!pending) return+ const rejected = rejectedPtyVersions(rootDir)+ if (!rejectedBefore.includes(pending.version) && rejected.includes(pending.version)) {+ const file = join(rootDir, 'runtime', 'pty', PTY_REJECTED)+ const temporary = `${file}.tmp-${process.pid}`+ writeFileSync(temporary, JSON.stringify(rejected.filter((version) => version !== pending.version)))+ renameSync(temporary, file)+ }+ log(result.pointer+ ? `${prefix}terminal host ${pending.version} taken back out with the build it came with — back to ${pending.previous}`+ : `${failedPrefix}terminal host ${pending.version} could not be taken back out: ${pending.previous} is no longer there to go back to — it stays`)+ } catch (error) {+ // The marker stays: a master's start takes a host it cannot speak back out (`ptyUnjudged`), and failing that judges it.+ log(`${failedPrefix}could not take terminal host ${pending?.version ?? '(unreadable marker)'} back out (${message(error)}) — it stays on probation: the next master takes it back out, or judges it and may keep it`)+ }+}++/** The daemon spawn lock for a synchronous caller (lib/daemonSpawnLock.ts `tryAcquireSpawnLockSync`): its release, or null+ * while it stays busy. */+export type SyncSpawnLock = () => (() => void) | null++/** [fn] under [lock] when one is given. A lock that stays busy is said ([busy]), and [fn] runs all the same, as it ran+ * before the lock: the probation's verdict, or the next core's start, must not wait on it. */+function underLock<T>(lock: SyncSpawnLock | undefined, log: ((line: string) => void) | undefined, busy: string, fn: () => T): T {+ if (!lock) return fn()+ const release = lock()+ if (!release) log?.(`[harnessd] the daemon spawn lock is busy — ${busy} without it`)+ try {+ return fn()+ } finally {+ release?.()+ }+}++/**+ * What a master's start judges for the host (masterProcess.ts `unjudgedUpdate`), as `ptyOnProbation`, after one case+ * is put right first, under the spawn lock: a host on probation with no CLI build pending ([cliPending]) whose protocol+ * ([protocol], the host `current-pty` names) is outside this build's `SUPPORTED_PTY_PROTOCOLS` is a paired host whose+ * build never went in (a take-back that failed, or a kill between the paired install and the build's stage). Judged+ * with this build's core, which opens no pane on it, it would roll back as a failure, or worse be kept: it is taken back+ * out (`takeBackPty`, no rejection) and nothing is judged. When that fails, its marker stays and it is judged as before.+ */+export function ptyUnjudged(rootDir: string, o: {+ cliPending: boolean+ log: (line: string) => void+ protocol?: (rootDir: string) => number | null+ lock?: SyncSpawnLock+}): string | null {+ const pending = o.cliPending ? null : readPtyPending(rootDir)+ if (!pending) return ptyOnProbation(rootDir)+ const protocol = (o.protocol ?? ((root: string) => installedPtyProtocol(root)))(rootDir)+ if (protocol === null || SUPPORTED_PTY_PROTOCOLS.includes(protocol)) return ptyOnProbation(rootDir)+ return underLock(o.lock, o.log, `taking terminal host ${pending.version} back out`, () => {+ o.log(`[harnessd] terminal host ${pending.version} is on probation with no CLI build, and speaks protocol ${protocol}, which this build does not — taking it back out rather than judging it`)+ takeBackPty(rootDir, o.log, '[harnessd] ')+ return ptyOnProbation(rootDir)+ })+}++/** The master's keep (its probation's `confirmUpdate`): the CLI build and the host both stay. */+export function keepStaged(o: {+ confirmCli: () => void+ ptyRoot: string | null+ confirmPty?: (rootDir: string) => void+ /** Where a host that could not be kept is said. Left out, nowhere. */+ log?: (line: string) => void+ readPending?: (rootDir: string) => PtyPending | null+ /** The daemon spawn lock, around the host's keep, as around its rollback (`rollBackStaged`). Left out, none. */+ lock?: SyncSpawnLock+}): void {+ o.confirmCli()+ if (o.ptyRoot === null) return+ const root = o.ptyRoot+ // Nothing on probation: no lock to wait for.+ const lock = existsSync(join(root, 'runtime', 'pty', PTY_PENDING)) ? o.lock : undefined+ const pending = (o.readPending ?? readPtyPending)(root)+ underLock(lock, o.log, `keeping terminal host ${pending?.version ?? '(unreadable marker)'}`, () => {+ try {+ (o.confirmPty ?? confirmPty)(root)+ } catch (error) {+ // The marker stays, and the poller checks nothing while it does: said, as host updates wait on the next start.+ o.log?.(`[harnessd] could not keep terminal host ${pending?.version ?? '(unreadable marker)'} (${message(error)}) — judged again at the next start`)+ }+ })+}diff --git a/cli/src/lib/windows/ptyUpdateCommand.spec.ts b/cli/src/lib/windows/ptyUpdateCommand.spec.tsnew file mode 100644index 000000000..a5370eecf--- /dev/null+++ b/cli/src/lib/windows/ptyUpdateCommand.spec.ts@@ -0,0 +1,90 @@+/**+ * `harness update`'s terminal host helpers (./ptyUpdateCommand.ts), on a temp install root. The steps the command+ * takes with them, the CLI's included, are tested in ../updateCommand.spec.ts.+ */+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { PTY_PAYLOAD_FILES, type PtyEntry } from './ptyPayload.js'+import { newerPtyForUpdate, preparePtyForUpdate, takeBackPtyForUpdate, type PtyUpdateCommandDeps } from './ptyUpdateCommand.js'++let root: string+let ptyRoot: string+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'pty-update-command-'))+ ptyRoot = join(root, 'runtime', 'pty')+ mkdirSync(join(ptyRoot, '0.10.0'), { recursive: true })+ for (const name of PTY_PAYLOAD_FILES) writeFileSync(join(ptyRoot, '0.10.0', name), `old ${name}`)+ writeFileSync(join(ptyRoot, 'current-pty'), '0.10.0\r\n')+})+afterEach(() => { rmSync(root, { recursive: true, force: true }) })++const entryOf = (version = '0.11.0'): PtyEntry => ({ version, url: 'https://cdn.test/pty.zip', sha256: 'a'.repeat(64), size: 10 })+const pointer = () => readFileSync(join(ptyRoot, 'current-pty'), 'utf8').trim()++function deps(entry: PtyEntry | null | Error = entryOf()) {+ const lines: string[] = []+ const prepared: string[] = []+ const d: Partial<PtyUpdateCommandDeps> = {+ fetchEntry: async () => { if (entry instanceof Error) throw entry; return entry },+ prepare: async (e) => { prepared.push(e.version); throw new Error('not reached') },+ log: (line) => lines.push(line),+ }+ return { d, lines, prepared }+}+const ask = (d: Partial<PtyUpdateCommandDeps>) => newerPtyForUpdate({ url: 'https://cdn.test/pty/metadata.json', key: 'win32-x64', rootDir: root, deps: d })++describe('harness update, for the terminal host (Windows)', () => {+ it('installs no pty while one is on probation, says so, and lets the CLI go on', async () => {+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.10.0', previous: '0.9.0' }))+ const said = ' terminal host 0.10.0 is still on probation, so 0.11.0 is not installed now: run `harness update` again once the daemon has kept it or rolled it back'+ const { d, lines, prepared } = deps()+ expect(await ask(d)).toBeNull()+ expect(lines).toEqual([said])+ // One that appears between the check and the lock: refused there the same way, with nothing downloaded.+ lines.length = 0+ expect(await preparePtyForUpdate(entryOf(), { rootDir: root, deps: d })).toBeNull()+ expect(lines).toEqual([said])+ expect(prepared).toEqual([])+ expect(pointer()).toBe('0.10.0')+ })++ it('wants nothing that is not newer, over no installed host, or from a manifest it cannot read', async () => {+ expect(await ask(deps(entryOf('0.10.0')).d)).toBeNull()+ expect(await ask(deps(null).d)).toBeNull()+ const unreachable = deps(new Error('ECONNRESET'))+ expect(await ask(unreachable.d)).toBeNull()+ expect(unreachable.lines).toEqual([' could not check for a terminal host update (ECONNRESET); continuing with the CLI'])+ // The first host is install.ps1's to put in: with no current-pty there is nothing for probation to go back to.+ rmSync(join(ptyRoot, 'current-pty'))+ expect(await ask(deps().d)).toBeNull()+ })++ it('a payload that fails its canary is reported, and nothing is installed', async () => {+ const { d, lines } = deps()+ d.prepare = async () => { throw new Error('pty payload refused: harness-pty reports version 0.9.9, expected 0.11.0') }+ expect(await preparePtyForUpdate(entryOf(), { rootDir: root, deps: d })).toBeNull()+ expect(lines).toEqual([+ '▸ Updating the terminal host 0.10.0 → 0.11.0…',+ ' ✗ terminal host 0.11.0 was not installed (pty payload refused: harness-pty reports version 0.9.9, expected 0.11.0) — keeping 0.10.0',+ ])+ expect(pointer()).toBe('0.10.0')+ })++ it('takes a paired host back out after its build failed to go in, marking with ✗ what did not happen', () => {+ mkdirSync(join(ptyRoot, '0.11.0'))+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '0.10.0' }))+ // The rejection the restore records first cannot be written.+ mkdirSync(join(ptyRoot, 'pty-rejected.json'))+ const lines: string[] = []+ takeBackPtyForUpdate(root, (line) => lines.push(line))+ expect(lines).toHaveLength(1)+ expect(lines[0]).toMatch(/^ {2}✗ could not take terminal host 0\.11\.0 back out/)+ rmSync(join(ptyRoot, 'pty-rejected.json'), { recursive: true })+ takeBackPtyForUpdate(root, (line) => lines.push(line))+ expect(lines[1]).toBe(' terminal host 0.11.0 taken back out with the build it came with — back to 0.10.0')+ expect(pointer()).toBe('0.10.0')+ })+})diff --git a/cli/src/lib/windows/ptyUpdateCommand.ts b/cli/src/lib/windows/ptyUpdateCommand.tsnew file mode 100644index 000000000..2f06c6073--- /dev/null+++ b/cli/src/lib/windows/ptyUpdateCommand.ts@@ -0,0 +1,123 @@+/**+ * `harness update`'s half for the terminal host on Windows (spec §5): the command a person runs to take an update now+ * also installs a newer promoted PTY payload, under the same spawn lock and before the CLI, and with the CLI already+ * current it installs the host alone and restarts the daemon (../updateCommand.ts `runUpdateSteps`, from cli.ts).+ *+ * The same download, canary and install as the background updater's (./ptyPayload.ts, ./ptyInstall.ts), with the+ * differences a person asking by name makes, as for the CLI: the versions this machine rolled back+ * (`pty-rejected.json`) are installed anyway, and nothing is backed off. What it does not override is a version still+ * on probation: its marker names the version to go back to, and only the master's probation may settle it. Nor the+ * pairing rule: a host of a protocol above this CLI's goes in only with the CLI build that needs it.+ */+import { rmSync } from 'node:fs'+import { join } from 'node:path'+import { currentPtyVersion } from '../ptyHost/launch.js'+import { PTY_PROTOCOL } from '../ptyHost/protocol.js'+import { semverGt } from '../selfUpdate.js'+import { installPreparedPty, readPtyPending, type PtyPending } from './ptyInstall.js'+import { fetchPtyEntry, preparePtyPayload, type PreparedPty, type PtyEntry } from './ptyPayload.js'+import { takeBackPty } from './ptyUpdate.js'++export interface PtyUpdateCommandDeps {+ fetchEntry: (url: string, key: string) => Promise<PtyEntry | null>+ prepare: (entry: PtyEntry, runtimeDir: string) => Promise<PreparedPty>+ install: (prepared: PreparedPty, rootDir: string) => boolean+ log: (line: string) => void+}++const DEFAULT_DEPS: PtyUpdateCommandDeps = {+ fetchEntry: (url, key) => fetchPtyEntry(url, key),+ prepare: (entry, runtimeDir) => preparePtyPayload(entry, runtimeDir),+ install: (prepared, rootDir) => installPreparedPty(prepared, rootDir),+ log: (line) => console.log(line),+}++const message = (error: unknown): string => (error instanceof Error ? error.message : String(error))+const runtimeOf = (rootDir: string): string => join(rootDir, 'runtime')++const onProbation = (pending: PtyPending, entry: PtyEntry): string =>+ ` terminal host ${pending.version} is still on probation, so ${entry.version} is not installed now: run \`harness update\` again once the daemon has kept it or rolled it back`++/**+ * Asked before anything is stopped: the promoted payload when it is newer than the host `current-pty` names, or null.+ * Null too with no installed host (the first one is install.ps1's), a manifest that cannot be read (said: the CLI's+ * update goes on), and a version still on probation (said once, here).+ */+export async function newerPtyForUpdate(o: {+ url: string+ key: string+ /** The install root: `bin\` and `runtime\pty\` are in it. */+ rootDir: string+ deps?: Partial<PtyUpdateCommandDeps>+}): Promise<PtyEntry | null> {+ const d: PtyUpdateCommandDeps = { ...DEFAULT_DEPS, ...o.deps }+ let entry: PtyEntry | null+ try {+ entry = await d.fetchEntry(o.url, o.key)+ } catch (error) {+ d.log(` could not check for a terminal host update (${message(error)}); continuing with the CLI`)+ return null+ }+ const installed = currentPtyVersion(runtimeOf(o.rootDir))+ if (!entry || installed === null || !semverGt(entry.version, installed)) return null+ const pending = readPtyPending(o.rootDir)+ if (pending) { d.log(onProbation(pending, entry)); return null }+ return entry+}++/**+ * Under the spawn lock the command holds, with the daemon stopped: download, verify and canary [entry], ready to+ * install. Null when it cannot be (said): a version on probation since the check, or a payload that failed. Never+ * throws: the CLI's update goes on.+ */+export async function preparePtyForUpdate(entry: PtyEntry, o: { rootDir: string; deps?: Partial<PtyUpdateCommandDeps> }): Promise<PreparedPty | null> {+ const d: PtyUpdateCommandDeps = { ...DEFAULT_DEPS, ...o.deps }+ // A marker that appeared since the check (an updater's install before the stop): refused before any download.+ const pending = readPtyPending(o.rootDir)+ if (pending) { d.log(onProbation(pending, entry)); return null }+ const installed = currentPtyVersion(runtimeOf(o.rootDir))+ d.log(`▸ Updating the terminal host ${installed} → ${entry.version}…`)+ try {+ return await d.prepare(entry, runtimeOf(o.rootDir))+ } catch (error) {+ d.log(` ✗ terminal host ${entry.version} was not installed (${message(error)}) — keeping ${installed}`)+ return null+ }+}++/**+ * Install [prepared], or leave a paired one out unless the CLI build being installed needs exactly its protocol+ * ([cliPtyProtocol], null with none). `installed` is on probation for the next master to judge, as one the updater+ * staged; `paired` was left out (its staging folder removed). Never throws.+ */+export function installPtyForUpdate(+ prepared: PreparedPty,+ o: { rootDir: string; cliPtyProtocol: number | null; deps?: Partial<PtyUpdateCommandDeps> },+): 'installed' | 'paired' | 'failed' {+ const d: PtyUpdateCommandDeps = { ...DEFAULT_DEPS, ...o.deps }+ if (prepared.paired && o.cliPtyProtocol !== prepared.protocol) {+ // A just-run canary can hold a file a moment; what is left is the updater's start sweep's.+ try { rmSync(prepared.staging, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }) } catch { /* swept later */ }+ d.log(` terminal host ${prepared.version} speaks protocol ${prepared.protocol}, above this CLI's ${PTY_PROTOCOL} — it goes in only with a CLI build that needs it`)+ return 'paired'+ }+ const installed = currentPtyVersion(runtimeOf(o.rootDir))+ try {+ // False: another installer put this very version in since the check, which is as good.+ if (d.install(prepared, o.rootDir)) d.log(` ✓ installed terminal host ${prepared.version}`)+ else d.log(` terminal host ${prepared.version} is already installed`)+ return 'installed'+ } catch (error) {+ d.log(` ✗ terminal host ${prepared.version} was not installed (${message(error)}) — keeping ${installed}`)+ return 'failed'+ }+}++/**+ * A paired host whose CLI build then failed to go in: taken back out before the old build is relaunched, which could+ * not open a pane on it, and not remembered as rolled back (./ptyUpdate.ts `takeBackPty`). Never throws.+ */+export function takeBackPtyForUpdate(rootDir: string, log: (line: string) => void): void {+ // What did not happen is marked ✗, as every other failure `harness update` reports.+ takeBackPty(rootDir, log, ' ', ' ✗ ')+}diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex 124907642..91c342bbe 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -42,8 +42,10 @@ class FakeBackend implements LocalWsBackend {async handleLocalBinary(_connId: string, frame: TerminalBinaryClear): Promise<void> {this.binaries.push(frame)}- setLocalTerminalFocus(connId: string, agentId: string | null): void {+ visibles: Array<[string, readonly string[] | undefined]> = []+ setLocalTerminalFocus(connId: string, agentId: string | null, visibleAgents?: readonly string[]): void {this.focuses.push([connId, agentId])+ this.visibles.push([connId, visibleAgents])}observed: Array<[string, unknown]> = []observeProduct(connId: string, payload: unknown): void {@@ -873,6 +875,26 @@ describe('local CLI WebSocket', () => {ws.close()})+ it('app_focus with visibleAgents reaches setLocalTerminalFocus', async () => {+ const backend = new FakeBackend()+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })+ local = attachLocalWsServer(server, { machineId, backend })+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))+ const ws = new WebSocket(`ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`)+ await onceOpen(ws)+ const connected = onceMessage(ws)+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))+ await connected++ ws.send(JSON.stringify({ type: 'app_focus', payload: { agentId: 'a', visibleAgents: ['a', 'b', 7, ''] } }))+ ws.send(JSON.stringify({ type: 'app_focus', payload: { agentId: null, visibleAgents: [] } }))+ // An older desktop sends no list: it must stay undefined so the window keeps counting as looking.+ ws.send(JSON.stringify({ type: 'app_focus', payload: { agentId: 'a' } }))+ await vi.waitFor(() => expect(backend.visibles).toHaveLength(3))+ expect(backend.visibles.map(([, list]) => list)).toEqual([['a', 'b'], [], undefined])+ ws.close()+ })+it('reports only explicit voice focus and clears by originating connection', async () => {const backend = new FakeBackend()const states: Array<{ machine: string; agent: string | null; conn: string }> = []diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 5201b85ea..c9e83c9ae 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -43,7 +43,7 @@ export interface LocalWsBackend {handleLocalFrame: (connId: string, frame: Frame) => voidhandleLocalBinary: (connId: string, frame: TerminalBinaryClear) => Promise<void>/** The agent this window has focused, or null — which of its terminals gets the short output window. */- setLocalTerminalFocus?: (connId: string, agentId: string | null) => void+ setLocalTerminalFocus?: (connId: string, agentId: string | null, visibleAgents?: readonly string[]) => void/** hn's `product_observe`, from a connection on this computer's own socket bound to this machine. */observeProduct?: (connId: string, payload: unknown) => void}@@ -760,7 +760,11 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO// Ahead of the dial's revision check below: that gate is about which agent the voice// follows, and a stale one says nothing about which terminal is in front of the person.// Only this daemon's own streams — a relayed machine's live on that machine's daemon.- if (!relay && boundMachineId === options.machineId) options.backend.setLocalTerminalFocus?.(connId, agentId)+ if (!relay && boundMachineId === options.machineId) {+ const listed = (parsed.payload as Record<string, unknown>)?.visibleAgents+ const visible = Array.isArray(listed) ? listed.filter((id): id is string => typeof id === 'string' && !!id) : undefined+ options.backend.setLocalTerminalFocus?.(connId, agentId, visible)+ }const revision = (parsed.payload as Record<string, unknown>)?.focusRevisionif (options.onAppFocusState?.(boundMachineId, agentId, connId,typeof revision === 'string' ? revision : undefined) === false) returndiff --git a/cli/src/masterProcess.spec.ts b/cli/src/masterProcess.spec.tsindex 47b4cce36..5d4fb6070 100644--- a/cli/src/masterProcess.spec.ts+++ b/cli/src/masterProcess.spec.ts@@ -1,25 +1,33 @@import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { dirname, join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { env } from './config/env.js'import { PROBE_ANSWER } from './harnessd/reexec.js'import { LEAN_ENTRY, leanFingerprint, type LeanBundle } from './harnessd/leanBundle.js'import { DAEMON_LOG_FILE, PID_FILE } from './lib/daemonState.js'import { launchDetached } from './lib/windows/launcher.js'+import { PTY_PROTOCOL } from './lib/ptyHost/protocol.js'import type { WindowsMasterDeps } from './masterProcess.js'const runMaster = vi.hoisted(() => vi.fn((_config: Record<string, unknown>) => 'supervisor'))vi.mock('./harnessd/master.js', async (real) => ({ ...await real<object>(), runMaster }))const leanBundle = vi.hoisted(() => ({ read: vi.fn((_bundle: Buffer): LeanBundle | null => null) }))vi.mock('./harnessd/leanBundle.js', async (real) => ({ ...await real<object>(), readLeanBundle: (bundle: Buffer) => leanBundle.read(bundle) }))-const spawnLock = vi.hoisted(() => ({ acquire: vi.fn(async (..._args: unknown[]): Promise<() => void> => () => {}) }))+const spawnLock = vi.hoisted(() => ({+ acquire: vi.fn(async (..._args: unknown[]): Promise<() => void> => () => {}),+ sync: vi.fn((..._args: unknown[]): (() => void) | null => () => {}),+}))const socket = vi.hoisted(() => ({ none: false }))vi.mock('./lib/localSocket.js', async (real) => {const actual = await real<typeof import('./lib/localSocket.js')>()return { ...actual, unixSocketPath: (...args: Parameters<typeof actual.unixSocketPath>) => socket.none ? null : actual.unixSocketPath(...args) }})-vi.mock('./lib/daemonSpawnLock.js', async (real) => ({ ...await real<object>(), acquireSpawnLock: (...args: unknown[]) => spawnLock.acquire(...args) }))+vi.mock('./lib/daemonSpawnLock.js', async (real) => ({+ ...await real<object>(),+ acquireSpawnLock: (...args: unknown[]) => spawnLock.acquire(...args),+ tryAcquireSpawnLockSync: (...args: unknown[]) => spawnLock.sync(...args),+}))const {BUNDLE_ENV, BUNDLE_SHA256_ENV, HANDOVER_LAUNCH_TIMEOUT_MS, HANDOVER_LOCK_WAIT_MS, LEAN_DIR, LEAN_FINGERPRINT_ENV, LEAN_OFF_FILE, handoverAlive, masterEnv, probeLean,@@ -420,6 +428,77 @@ describe('starting the master', () => {expect(LEAN_OFF_FILE).toMatch(/[\\/]lean-off$/)})+ it('on Windows, judges a terminal host on probation with the build: unjudged at start, rolled back, kept', () => {+ // The suite's own home (config/testIsolation.ts): the install root the CLI folder sits in.+ const root = dirname(env.ADAPTER_CLI_DIR)+ const ptyRoot = join(root, 'runtime', 'pty')+ try {+ mkdirSync(join(ptyRoot, '0.10.0'), { recursive: true })+ writeFileSync(join(ptyRoot, '0.10.0', 'harness-pty.exe'), 'old')+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '0.10.0' }))+ runMaster.mockClear()+ startMaster({ scriptPath: '/cli/cli.js' }, () => {}, 'win32', () => ({}))+ const config = runMaster.mock.calls[0][0] as { restoreUpdate(): void; confirmUpdate(): void; unjudgedUpdate(bundle: string | null): string | null }+ expect(config.unjudgedUpdate(null)).toBe('terminal host 0.11.0')+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ try { config.restoreUpdate() } finally { log.mockRestore() }+ expect(readFileSync(join(ptyRoot, 'current-pty'), 'utf8').trim()).toBe('0.10.0')+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(JSON.parse(readFileSync(join(ptyRoot, 'pty-rejected.json'), 'utf8'))).toEqual(['0.11.0'])+ expect(config.unjudgedUpdate(null)).toBeNull()+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.12.0', previous: '0.10.0' }))+ config.confirmUpdate()+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ // A corrupt marker, which the poller waits on as on any: judged at the start, and the rollback clears it.+ writeFileSync(join(ptyRoot, 'pty-pending.json'), '{ not json')+ expect(config.unjudgedUpdate(null)).toBe('terminal host (unreadable marker)')+ const quiet = vi.spyOn(console, 'log').mockImplementation(() => {})+ try { config.restoreUpdate() } finally { quiet.mockRestore() }+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(readFileSync(join(ptyRoot, 'current-pty'), 'utf8').trim()).toBe('0.10.0')+ } finally { rmSync(join(root, 'runtime', 'pty'), { recursive: true, force: true }) }+ })++ // The stand-in host is a shell script: what `harness-pty.exe version` prints, off Windows.+ it.skipIf(process.platform === 'win32')('on Windows, judges and keeps the terminal host under the spawn lock, and takes back at start a host it cannot speak', () => {+ const root = dirname(env.ADAPTER_CLI_DIR)+ const ptyRoot = join(root, 'runtime', 'pty')+ const events: string[] = []+ spawnLock.sync.mockImplementation((purpose: unknown) => { events.push(`lock ${String(purpose)}`); return () => { events.push('release') } })+ const log = vi.spyOn(console, 'log').mockImplementation((line: string) => { events.push(String(line)) })+ try {+ mkdirSync(join(ptyRoot, '0.10.0'), { recursive: true })+ writeFileSync(join(ptyRoot, '0.10.0', 'harness-pty.exe'), 'old')+ // A paired host whose CLI build never went in: it says it speaks a protocol above this build's.+ mkdirSync(join(ptyRoot, '0.11.0'), { recursive: true })+ const host = join(ptyRoot, '0.11.0', 'harness-pty.exe')+ writeFileSync(host, `#!/bin/sh\necho '{"version":"0.11.0","protocol":${PTY_PROTOCOL + 1},"features":["seed"]}'\n`, { mode: 0o755 })+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '0.10.0' }))+ runMaster.mockClear()+ startMaster({ scriptPath: '/cli/cli.js' }, () => {}, 'win32', () => ({}))+ const config = runMaster.mock.calls[0][0] as { restoreUpdate(): void; confirmUpdate(): void; unjudgedUpdate(bundle: string | null): string | null }+ expect(config.unjudgedUpdate(null)).toBeNull()+ expect(readFileSync(join(ptyRoot, 'current-pty'), 'utf8').trim()).toBe('0.10.0')+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ expect(events.filter((e) => e.startsWith('lock') || e === 'release')).toEqual(['lock update', 'release'])+ expect(events.some((e) => e.includes(`speaks protocol ${PTY_PROTOCOL + 1}, which this build does not — taking it back out rather than judging it`))).toBe(true)+ // A rollback and a keep: each under the lock.+ events.length = 0+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.12.0', previous: '0.10.0' }))+ config.restoreUpdate()+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.12.0', previous: '0.10.0' }))+ config.confirmUpdate()+ expect(events.filter((e) => e.startsWith('lock') || e === 'release')).toEqual(['lock update', 'release', 'lock update', 'release'])+ } finally {+ log.mockRestore()+ spawnLock.sync.mockReset()+ spawnLock.sync.mockImplementation(() => () => {})+ rmSync(join(root, 'runtime', 'pty'), { recursive: true, force: true })+ }+ })+it('keeps the services in the core when the core will have no local socket for them to reach it by', () => {const given = { HOME: '/home/someone' }const logs: string[] = []diff --git a/cli/src/masterProcess.ts b/cli/src/masterProcess.tsindex 101d32994..b344d3b87 100644--- a/cli/src/masterProcess.ts+++ b/cli/src/masterProcess.ts@@ -20,7 +20,7 @@ import { baseNode, namedNode } from './harnessd/processName.js'import { PROBE_ANSWER, PROBE_TIMEOUT_MS } from './harnessd/reexec.js'import { dropAgentSessionEnv } from './lib/agentSessionEnv.js'import { ensureUtf8Locale } from './lib/childLocale.js'-import { acquireSpawnLock } from './lib/daemonSpawnLock.js'+import { acquireSpawnLock, tryAcquireSpawnLockSync } from './lib/daemonSpawnLock.js'import { DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, PID_FILE } from './lib/daemonState.js'import { isInstalledCopy } from './lib/installedCopy.js'import { unixSocketPath } from './lib/localSocket.js'@@ -28,7 +28,8 @@ import { currentCli, harnessLaunchPath } from './lib/windows/installLayout.js'import { launchDetached } from './lib/windows/launcher.js'import { leanFingerprint, readLeanBundle, releaseLeanClaim, writeLeanBundle, type LeanBundle } from './harnessd/leanBundle.js'import { ts } from './lib/log.js'-import { confirm as confirmUpdate, restore as restoreUpdate, unjudgedUpdate } from './lib/selfUpdate.js'+import { confirm as confirmUpdate, pendingVersion, restore as restoreUpdate, unjudgedUpdate } from './lib/selfUpdate.js'+import { keepStaged, ptyUnjudged, rollBackStaged } from './lib/windows/ptyUpdate.js'import { VERSION } from './version.js'/** Where a master re-executing on a new bundle leaves word of it, until that master's core is up. */@@ -241,6 +242,12 @@ export function startMaster(// Windows, before the master says anything: harness-launch.exe gave it no output, and its console is the daemon's log// from here on, `masterEnv`'s line among the rest.const windowsConfig = platform === 'win32' ? windows() : {}+ // The install root a terminal host payload is installed in (lib/windows/ptyInstall.ts); none elsewhere.+ const ptyRoot = platform === 'win32' ? dirname(env.ADAPTER_CLI_DIR) : null+ // What the master does to the host, it does under the daemon spawn lock: the updater sweeps bin\'s aside files under it,+ // and an aside file may hold the only copy of a path a rollback puts back. Taken only while a host is on probation.+ const lock = () => tryAcquireSpawnLockSync('update')+ const masterLog = (line: string) => console.log(`${ts()} ${line}`)return runMaster({env: masterEnv(process.env, unixSocketPath(env.ADAPTER_DATA_DIR, env.PORT), undefined, platform),nodePath: baseNode(process.execPath),@@ -251,11 +258,19 @@ export function startMaster(pidFile: PID_FILE,statusFile: HARNESSD_STATUS_FILE,logFile: DAEMON_LOG_FILE,- restoreUpdate: () => restoreUpdate(env.ADAPTER_CLI_DIR),- confirmUpdate: () => confirmUpdate(env.ADAPTER_CLI_DIR),+ // One probation for whatever the updater staged: the CLI build, the terminal host (Windows), or both.+ restoreUpdate: () => rollBackStaged({+ cliPending: () => pendingVersion(env.ADAPTER_CLI_DIR) !== null, restoreCli: () => restoreUpdate(env.ADAPTER_CLI_DIR),+ ptyRoot, log: masterLog, lock,+ }),+ confirmUpdate: () => keepStaged({ confirmCli: () => confirmUpdate(env.ADAPTER_CLI_DIR), ptyRoot, log: masterLog, lock }),version: VERSION,reexecMarkerFile: HARNESSD_REEXEC_FILE,- unjudgedUpdate: (bundle) => unjudgedUpdate(env.ADAPTER_CLI_DIR, bundle),+ // A host still on probation when the master judging it died (a power cut) is judged by the first core too: left+ // unjudged, its marker would hold every later host update back. One of a protocol this build cannot speak, with no+ // CLI build pending, is a paired host whose build never went in: taken back out instead (`ptyUnjudged`).+ unjudgedUpdate: (bundle) => unjudgedUpdate(env.ADAPTER_CLI_DIR, bundle)+ ?? (ptyRoot === null ? null : ptyUnjudged(ptyRoot, { cliPending: pendingVersion(env.ADAPTER_CLI_DIR) !== null, log: masterLog, lock })),// The updater runs for the installed copy alone (lib/installedCopy.ts), beside the core, never in it.updater: !env.ADAPTER_UPDATE_DISABLE && isInstalledCopy(start.scriptPath, env.ADAPTER_CLI_DIR),// A master that ends cleanly gives up its claim on its lean bundle, so the next one to start candiff --git a/cli/src/messages/command.spec.ts b/cli/src/messages/command.spec.tsindex 25c709b2e..6438174e4 100644--- a/cli/src/messages/command.spec.ts+++ b/cli/src/messages/command.spec.ts@@ -140,6 +140,9 @@ describe('what harness send prints', () => {expect(sendPane({ HARNESS_PANE: 'p1:%3' })).toBe('p1:%3')expect(sendPane({ TMUX_PANE: '%4', HARNESS_PANE: 'p1:%3' })).toBe('%4')expect(sendPane({ HARNESS_PANE: 'p1:%3; calc' })).toBeUndefined()+ expect(sendPane({ HARNESS_PANE: 'p2-0.4.21-dev.win1:%7' })).toBe('p2-0.4.21-dev.win1:%7')+ expect(sendPane({ HARNESS_PANE: 'p2-h0123456789ab:%7' })).toBe('p2-h0123456789ab:%7')+ expect(sendPane({ HARNESS_PANE: 'p2-0.4.21 calc:%7' })).toBeUndefined()expect(sendPane({})).toBeUndefined()expect(paneOwner('p1:%3', () => { throw new Error('tmux was asked about a pty host pane') })).toBeNull()})diff --git a/cli/src/messages/command.ts b/cli/src/messages/command.tsindex 07305c2d9..960f4ac94 100644--- a/cli/src/messages/command.ts+++ b/cli/src/messages/command.ts@@ -18,6 +18,7 @@ import { readAuthSession } from '../lib/authSession.js'import { HARNESS_OWNER_OPTION } from '../lib/harnessSessionLabel.js'import { MessageError } from './model.js'import { messagesRpc, type Rpc } from './rpc.js'+import { PTY_HOST_PANE } from '../lib/ptyHost/instance.js'export const SEND_USAGE = `harness send — message your teammates in this tab@@ -95,7 +96,7 @@ export function paneOwner(pane: string, tmux: (args: string[]) => string = (args* which has no TMUX_PANE (messages/service.ts takes both). */export function sendPane(vars: NodeJS.ProcessEnv): string | undefined {if (vars.TMUX_PANE) return vars.TMUX_PANE- return /^p\d{1,4}:%\d{1,9}$/.test(vars.HARNESS_PANE ?? '') ? vars.HARNESS_PANE : undefined+ return PTY_HOST_PANE.test(vars.HARNESS_PANE ?? '') ? vars.HARNESS_PANE : undefined}/** How many tasks `harness send` alone lists: a short section, the windows show the rest. */diff --git a/cli/src/messages/inbox.spec.ts b/cli/src/messages/inbox.spec.tsindex 3c21bc8db..64a247c8a 100644--- a/cli/src/messages/inbox.spec.ts+++ b/cli/src/messages/inbox.spec.ts@@ -51,6 +51,18 @@ describe('a pane inbox', () => {expect(inbox.waiting(tmux, 'k')).toBe(false)})+ it('keys a versioned pty host\'s pane by its instance: p2-0.4.21-dev.win1:%7 and p2-h0123456789ab:%7', () => {+ const dev = 'ptyhost\u0000p2-0.4.21-dev.win1\u0000%7', hashed = 'ptyhost\u0000p2-h0123456789ab\u0000%7', legacy = 'ptyhost\u0000p2\u0000%7'+ expect(inbox.paneDir(dev)).toBe(paneDir('ptyhost.p2-0.4.21-dev.win1.7'))+ expect(inbox.paneDir(hashed)).toBe(paneDir('ptyhost.p2-h0123456789ab.7'))+ for (const bad of ['ptyhost\u0000p2-\u0000%7', 'ptyhost\u0000p2-a/b\u0000%7', 'ptyhost\u0000p2-0.4.21\u00007']) expect(inbox.paneDir(bad), bad).toBeNull()+ // A delivery key has a `-` in it, as a versioned instance does: the folder still reads back as its pane.+ for (const pane of [dev, hashed, legacy]) inbox.put(pane, 'm0000001-aaaa', { session: '', text: pane })+ expect(inbox.entries().map((e) => [e.pane, e.key]).sort()).toEqual([dev, hashed, legacy].map((pane) => [pane, 'm0000001-aaaa']).sort())+ for (const pane of [dev, hashed, legacy]) expect(inbox.reclaim(pane, 'm0000001-aaaa')).toBe(true)+ expect(inbox.reclaimed().sort()).toEqual([dev, hashed, legacy].map((pane) => [pane, 'm0000001-aaaa']).sort())+ })+it('refuses what is not a pane or a key', () => {expect(() => inbox.put('x', 'k', { session: '', text: 't' })).toThrow(/not a terminal pane/)expect(() => inbox.put('%1', '../escape', { session: '', text: 't' })).toThrow(/invalid inbox key/)diff --git a/cli/src/messages/inbox.ts b/cli/src/messages/inbox.tsindex b1d54219d..21af469c6 100644--- a/cli/src/messages/inbox.ts+++ b/cli/src/messages/inbox.ts@@ -17,6 +17,7 @@*/import { chmodSync, mkdirSync, readdirSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from 'node:fs'import { join } from 'node:path'+import { PTY_HOST_INSTANCE_SOURCE } from '../lib/ptyHost/instance.js'/** What one inbox file holds: the text, and the engine conversation it is for. A hook in any other conversation* (a Codex sub-agent runs its hooks from its parent's pane) leaves it. `notice` is the line the pane shows the@@ -25,11 +26,17 @@ export interface InboxItem { session: string; text: string; notice?: string }const LEGACY_PANE = /^%(\d{1,9})$/const TMUX_PANE = /^tmux\u0000%(\d{1,9})$/-const PTY_PANE = /^ptyhost\u0000(p\d{1,4})\u0000%(\d{1,9})$/+const PTY_PANE = new RegExp(`^ptyhost\\u0000(${PTY_HOST_INSTANCE_SOURCE})\\u0000%(\\d{1,9})$`)const KEY = /^[0-9a-z._-]{1,120}$//** What a folder name (or a typing/claimed name's prefix) says the pane is: a tmux pane's number, or a pty host's. */const TMUX_FOLDER = /^(\d{1,9})$/-const PTY_FOLDER = /^ptyhost\.(p\d{1,4})\.(\d{1,9})$/+// A versioned instance has dots of its own (`p2-0.4.21`): the pane is the number after the last one.+const PTY_FOLDER = new RegExp(`^ptyhost\\.(${PTY_HOST_INSTANCE_SOURCE})\\.(\\d{1,9})$`)+/**+ * A reclaimed item's name, `<pane folder>-<key>`. An instance may have a `-` in it, as a key does: the folder ends at+ * the last `.<pane number>-`, since no key (a message id and a hash, or `0note-<hash>`) has a `.` in it.+ */+const RECLAIMED = new RegExp(`^(\\d{1,9}|ptyhost\\.${PTY_HOST_INSTANCE_SOURCE}\\.\\d{1,9})-(.+)\\.json$`)/** A pane as Agent Messages keys it: its route key, with a legacy bare `%N` read as the tmux pane it was. */export function inboxPaneKey(pane: string): string {@@ -169,7 +176,7 @@ export class PaneInbox {let names: string[] = []try { names = readdirSync(this.dir('typing')) } catch { /* nothing reclaimed */ }return names.flatMap((name) => {- const match = /^(\d{1,9}|ptyhost\.p\d{1,4}\.\d{1,9})-(.+)\.json$/.exec(name)+ const match = RECLAIMED.exec(name)return match ? [[paneOfFolder(match[1])!, match[2]] as [string, string]] : []})}diff --git a/cli/src/messages/service.spec.ts b/cli/src/messages/service.spec.tsindex 3e5f156ce..9ad643e4c 100644--- a/cli/src/messages/service.spec.ts+++ b/cli/src/messages/service.spec.ts@@ -29,8 +29,8 @@ const OWNER_REMOTE = { local: false, owner: true }const session = (agentId: string, pane: string, engine = 'claude', cwd = `/work/${agentId}`) =>({ agentId, sessionId: `s-${agentId}`, engine, cwd, tmuxPane: pane, runtimes: [{ backend: 'tmux', paneId: pane }], active: true, title: agentId }) as unknown as RegisteredSession/** A harness in a pty host pane: its `tmuxPane` is that pane's id, which a tmux pane may also have. */-const ptySession = (agentId: string, pane: string, engine = 'claude') =>- ({ ...session(agentId, pane, engine), runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: pane }] }) as unknown as RegisteredSession+const ptySession = (agentId: string, pane: string, engine = 'claude', instance = 'p1') =>+ ({ ...session(agentId, pane, engine), runtimes: [{ backend: 'ptyhost', instance, paneId: pane }] }) as unknown as RegisteredSessioninterface Setup {tabs?: Array<{ id: string; name: string; panes: Array<{ machineId: string; agentId: string }>; leader?: { machineId: string; agentId: string } | null }>@@ -734,6 +734,14 @@ describe('the roster note and the directory', () => {expect((await t.ask({ action: 'send', pane: 'p2:%5', to: 'b', text: 'hi' })).error).toBe('NOT_A_HARNESS')})+ it('names a versioned pty host\'s pane by its own instance: p2-0.4.21-dev.win1:%7 and p2-h0123456789ab:%7', async () => {+ const tabs = [{ id: 'app', name: 'app', panes: ['a', 'b', 'c'].map((agentId) => ({ machineId: 'm1', agentId })) }]+ const t = setup({ tabs, agents: [ptySession('a', '%7', 'claude', 'p2-0.4.21-dev.win1'), ptySession('b', '%7', 'claude', 'p2-h0123456789ab'), session('c', '%6')] })+ expect((await t.ask({ action: 'send', pane: 'p2-0.4.21-dev.win1:%7', to: 'c', text: 'hi' })).recipients).toEqual([{ name: 'c', state: 'queued' }])+ expect((await t.ask({ action: 'send', pane: 'p2-h0123456789ab:%7', to: 'c', text: 'hi' })).recipients).toEqual([{ name: 'c', state: 'queued' }])+ expect((await t.ask({ action: 'send', pane: 'p2-0.4.22:%7', to: 'c', text: 'hi' })).error).toBe('NOT_A_HARNESS')+ })+it('keeps the notes it put in the store, withdraws a gone harness\'s, and sweeps old files nothing waits on', async () => {vi.useFakeTimers()const t = setup()diff --git a/cli/src/messages/service.ts b/cli/src/messages/service.tsindex 058a4afbe..91201b0e9 100644--- a/cli/src/messages/service.ts+++ b/cli/src/messages/service.ts@@ -59,6 +59,7 @@ import { cleanSummary } from '../lib/activitySummary.js'import { VERSION } from '../version.js'import { createTaskReader, type TaskReader, type TaskResult } from './tasks.js'import { MessageStore, type Entry, type LocalDelivery, type Outgoing } from './store.js'+import { PTY_HOST_INSTANCE_SOURCE } from '../lib/ptyHost/instance.js'export interface MessagesOptions {/** Where its history and waiting deliveries are kept; an isolated fixture's own. */@@ -140,7 +141,7 @@ export const MESSAGES_OFF_TEXT = 'Agent Messages are off. The person turns on "A/** How long the windows' `shared_tabs_changed` waits for more of the same change. */export const SHARES_COALESCE_MS = 250/** `harness send`'s pane: `$TMUX_PANE` (`%N`, a tmux pane only) or a pty host pane's `<instance>:%N` (`$HARNESS_PANE`). */-const PANE = /^(?:p\d{1,4}:)?%\d{1,9}$/+const PANE = new RegExp(`^(?:${PTY_HOST_INSTANCE_SOURCE}:)?%\\d{1,9}$`)/** The most messages `harness send` alone gives an agent at once, unread ones first. */const UNREAD_MAX = 20/** Whether `wanted` is the whole of a name the engine cut short: Codex titles its terminal with the folder cut to fitdiff --git a/cli/src/scripts/installPs1.spec.ts b/cli/src/scripts/installPs1.spec.tsindex d21dfe7ed..fc04c6efa 100644--- a/cli/src/scripts/installPs1.spec.ts+++ b/cli/src/scripts/installPs1.spec.ts@@ -73,7 +73,15 @@ describe('install.ps1, as written', () => {it('moves a running daemon to the new build when it is run again over an install', () => {expect(source).toContain('$before = Read-HarnessCurrentCli -Root $root')- expect(source).toContain('$null = Restart-HarnessDaemon -Command $command -Before $before -After $version')+ expect(source).toContain('$ptyBefore = Read-HarnessCurrentPty -Root $root')+ expect(source).toContain('$null = Restart-HarnessDaemon -Command $command -Before $before -After $version -PtyBefore $ptyBefore -PtyAfter $ptyAfter')+ })++ it('clears a terminal host probation when it moves current-pty, and names the host when a host-only move does not start', () => {+ const pty = source.match(/^function Install-HarnessPty[\s\S]*?^}\r?$/m)?.[0] ?? ''+ expect(pty).toContain("if ($before -ne $version) { Remove-Item -LiteralPath (Join-Path $ptyRoot 'pty-pending.json') -Force -ErrorAction SilentlyContinue }")+ expect(pty.indexOf('Write-HarnessPointer -Path $pointer -Value $version')).toBeLessThan(pty.indexOf("'pty-pending.json'"))+ expect(source).toContain(`Write-Host " Harness did not start again on terminal host \${PtyAfter}. Run 'harness start'."`)})it('keeps exactly one app-default line off in the CLI source', () => {@@ -584,6 +592,50 @@ describe.runIf(windows)('install.ps1, run again over a live install', { timeout:expect(stopped.calls()).toEqual(['status'])})+ it('names the terminal host when Harness does not start again after a host-only move', () => {+ const harness = fakeHarness('running - backend connected', ['if "%1"=="start" exit /b 3'])+ const run = ps(`Restart-HarnessDaemon -Command '${harness.command}' -Before '1.0.1' -After '1.0.1' -PtyBefore '2.0.0' -PtyAfter '2.0.1'`)+ expect(last(run.stdout), run.stderr).toBe('True')+ expect(run.stdout).toContain("Harness did not start again on terminal host 2.0.1. Run 'harness start'.")+ })++ it('removes a terminal host probation marker when it moves current-pty, and keeps it when the pointer stays', () => {+ const root = mkdtempSync(join(tmpdir(), 'harness-ps1-pending-'))+ scratch.push(root)+ const ptyRoot = join(root, 'runtime', 'pty')+ for (const version of ['1.0.0', '2.0.0']) {+ mkdirSync(join(ptyRoot, version), { recursive: true })+ for (const name of ['harness-pty.exe', 'harness-launch.exe', 'harness.exe', 'conpty.dll', 'OpenConsole.exe', 'harness-serial.exe']) writeFileSync(join(ptyRoot, version, name), name)+ }+ const marker = join(ptyRoot, 'pty-pending.json')+ writeFileSync(join(ptyRoot, 'current-pty'), '1.0.0\r\n')+ writeFileSync(marker, JSON.stringify({ version: '1.0.0', previous: '0.9.0' }))+ const moved = ps(`$null = Install-HarnessPty -Root '${root}' -Entry @{ version = '2.0.0' } -Source '' -Tar ''`)+ expect(moved.status, moved.stderr).toBe(0)+ expect(readFileSync(join(ptyRoot, 'current-pty'), 'utf8')).toBe('2.0.0\r\n')+ expect(existsSync(marker)).toBe(false)+ writeFileSync(marker, JSON.stringify({ version: '2.0.0', previous: '1.0.0' }))+ const same = ps(`$null = Install-HarnessPty -Root '${root}' -Entry @{ version = '2.0.0' } -Source '' -Tar ''`)+ expect(same.status, same.stderr).toBe(0)+ expect(existsSync(marker)).toBe(true)+ })++ it('restarts the daemon when only the terminal host moved', () => {+ const harness = fakeHarness('running - backend connected')+ const run = ps(`Restart-HarnessDaemon -Command '${harness.command}' -Before '1.0.1' -After '1.0.1' -PtyBefore '2.0.0' -PtyAfter '2.0.1'`)+ expect(last(run.stdout), run.stderr).toBe('True')+ expect(run.stdout).toContain('Moving the running Harness to terminal host 2.0.1 (your agents keep running)...')+ expect(harness.calls()).toEqual(['status', 'stop', 'start'])+ })++ it('does not restart the daemon when neither the CLI nor the terminal host changed', () => {+ const harness = fakeHarness('running - backend connected')+ expect(ps(`Restart-HarnessDaemon -Command '${harness.command}' -Before '1.0.1' -After '1.0.1' -PtyBefore '2.0.1' -PtyAfter '2.0.1'`).stdout).toBe('False')+ // A first terminal host install has nothing running to move.+ expect(ps(`Restart-HarnessDaemon -Command '${harness.command}' -Before '1.0.1' -After '1.0.1' -PtyBefore '' -PtyAfter '2.0.1'`).stdout).toBe('False')+ expect(harness.calls()).toEqual([])+ })+it('closes without the setup steps when this computer is signed in and Harness runs', () => {// With a line on stderr, as a sign-in refresh warning would be: it must not reach the closing text.const ready = fakeHarness('running - backend connected', ['if "%1"=="auth" echo refreshing the sign-in 1>&2', 'if "%1"=="auth" echo {"loggedIn":true}'])diff --git a/cli/src/scripts/windowsWorkflows.spec.ts b/cli/src/scripts/windowsWorkflows.spec.tsindex 125d9fb0d..c6495a336 100644--- a/cli/src/scripts/windowsWorkflows.spec.ts+++ b/cli/src/scripts/windowsWorkflows.spec.ts@@ -17,6 +17,16 @@ describe('the Windows release workflows', () => {expect(pty).toContain('HARNESS_EXE_BIN:')})+ it('runs the rollover and payload-install specs against two real builds of the host', () => {+ const pty = read('windows.yml')+ // The previous build: a numeric version, as an install's folder under runtime\pty\ is named.+ expect(pty).toMatch(/- name: Build the previous host\n\s+if: \$\{\{ !inputs\.release \}\}\n[\s\S]*?HARNESS_PTY_VERSION: '0\.0\.1'\n/)+ expect(pty).toContain('HARNESS_PTY_BIN_PREV: ${{ github.workspace }}\\pty\\target\\${{ matrix.target }}\\previous\\harness-pty.exe')+ // The Rust two-build test runs on that build too: without HARNESS_PTY_BIN_OLD it returns at once.+ expect(pty).toMatch(/- name: 'Rust: two versions side by side'\n\s+if: \$\{\{ !inputs\.release \}\}\n[\s\S]*?HARNESS_PTY_BIN_OLD: \$\{\{ github\.workspace \}\}\\pty\\target\\\$\{\{ matrix\.target \}\}\\previous\\harness-pty\.exe\n\s+run: cargo test --locked --target \$\{\{ matrix\.target \}\} --test control two_versions_serve_side_by_side -- --nocapture\n/)+ for (const spec of ['src/lib/hostMove/hostMove.real.spec.ts', 'src/lib/ptyHost/drain.spec.ts', 'src/lib/windows/ptyInstall.windows.real.spec.ts']) expect(pty).toContain(spec)+ })+it('publishes the Windows bits to staging only, beside a CLI publish that never waits for them', () => {const release = read('release.yml')expect(release).toContain('uses: ./.github/workflows/windows.yml')diff --git a/cli/src/services/updaterProcess.spec.ts b/cli/src/services/updaterProcess.spec.tsindex 5b7d34f4c..1f88afdde 100644--- a/cli/src/services/updaterProcess.spec.ts+++ b/cli/src/services/updaterProcess.spec.ts@@ -1,39 +1,84 @@-import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import { SERVICE_EXIT_RESTART, type UpdaterMessage } from '../harnessd/protocol.js'import type { startSelfUpdater } from '../lib/selfUpdate.js'+import type { startPtyUpdater } from '../lib/windows/ptyUpdate.js'import type { startTuiUpdater } from '../tui/update.js'import { VERSION } from '../version.js'import { processUpdaterDeps, runUpdaterService, type UpdaterServiceDeps } from './updaterProcess.js'// A lock someone else holds a moment: what the updater says while it waits for it.const locked = vi.hoisted(() => [] as string[])+/** What the next lock sections throw instead of running (each once). */+const lockFails = vi.hoisted(() => [] as unknown[])+/** Replacements for the terminal host payload's functions, left to the real ones when unset. */+const payload = vi.hoisted(() => ({} as {+ manifestUrl?: (url: string) => string+ platformKey?: () => string | null+ prepare?: (...args: unknown[]) => Promise<unknown>+}))+const downloaded = vi.hoisted(() => ({ ref: undefined as unknown, limits: undefined as unknown }))vi.mock('../lib/daemonSpawnLock.js', async (real) => ({...await real<object>(),withSpawnLock: async (purpose: string, fn: () => Promise<unknown>, opts: { onWaiting?: (owner: object) => void } = {}) => {locked.push(purpose)+ if (lockFails.length) throw lockFails.shift()opts.onWaiting?.({ pid: 4242, purpose: 'start', since: Date.now(), startMarker: 'x', token: 't' })return fn()},}))+vi.mock('../lib/windows/ptyPayload.js', async (real) => {+ const actual = await real<typeof import('../lib/windows/ptyPayload.js')>()+ return {+ ...actual,+ ptyManifestUrl: (url: string) => (payload.manifestUrl ?? actual.ptyManifestUrl)(url),+ ptyPlatformKey: () => (payload.platformKey ? payload.platformKey() : actual.ptyPlatformKey()),+ preparePtyPayload: (...args: Parameters<typeof actual.preparePtyPayload>) => (payload.prepare ?? actual.preparePtyPayload)(...args),+ }+})+vi.mock('../lib/selfUpdate.js', async (real) => {+ const actual = await real<typeof import('../lib/selfUpdate.js')>()+ return {+ ...actual,+ downloadVerified: async (ref: unknown, limits: unknown) => { downloaded.ref = ref; downloaded.limits = limits; return Buffer.from('zip') },+ }+})+// No process runs from any build: the retirement's table, the same on every host.vi.mock('../lib/windows/processTable.js', () => ({ windowsProcessRows: async () => [] }))type CliOptions = Parameters<typeof startSelfUpdater>[0]type HnOptions = Parameters<typeof startTuiUpdater>[0]+type PtyOptions = Parameters<typeof startPtyUpdater>[0]++/** Run [fn] under a master that judges a terminal host it staged (harnessd/master.ts). */+async function judgingPty(fn: () => Promise<void> | void): Promise<void> {+ const saved = process.env.HARNESSD_JUDGES_PTY+ process.env.HARNESSD_JUDGES_PTY = '1'+ try { await fn() } finally {+ if (saved === undefined) delete process.env.HARNESSD_JUDGES_PTY+ else process.env.HARNESSD_JUDGES_PTY = saved+ }+}describe('the updater in its own process', () => {- afterEach(() => { vi.restoreAllMocks() })+ afterEach(() => {+ vi.restoreAllMocks()+ lockFails.length = 0+ for (const k of Object.keys(payload)) delete (payload as Record<string, unknown>)[k]+ })const make = () => {const calls: string[] = []const told: UpdaterMessage[] = []let cli: CliOptions | null = nulllet hn: HnOptions | null = null+ let pty: PtyOptions | null = nulllet sent: (() => void) | null = null+ const ready = { pty: null as string | null, paired: false }const deps: UpdaterServiceDeps = {tell: (message, done) => { told.push(message); sent = done },exit: (code) => { calls.push(`exit ${code}`) },@@ -41,7 +86,25 @@ describe('the updater in its own process', () => {startHn: (options) => { hn = options; return { stop: () => calls.push('stop hn') } },log: (line) => calls.push(line),}- return { deps, calls, told, cli: () => cli!, hn: () => hn!, sent: () => sent! }+ // Windows: the terminal host's poller beside them, in the install root the CLI folder sits in.+ const windows: Partial<UpdaterServiceDeps> = {+ ptyRootDir: join(tmpdir(), 'updater-pty-root'),+ startPty: (options) => {+ pty = options+ return {+ stop: () => calls.push('stop pty'),+ readyToStage: async (forPtyProtocol?: number) => {+ calls.push(`ready for ${forPtyProtocol}`)+ const version = ready.pty+ ready.pty = null+ return version === null ? null : { version, protocol: ready.paired ? 3 : 2, paired: ready.paired }+ },+ readyProtocol: () => (ready.pty ? (ready.paired ? 3 : 2) : null),+ takenBack: () => { calls.push('pty taken back') },+ }+ },+ }+ return { deps, windows, calls, told, ready, cli: () => cli!, hn: () => hn!, pty: () => pty, sent: () => sent! }}it('checks for this build\'s successor, and hn\'s, on the installed copy, and stops both', () => {@@ -88,7 +151,7 @@ describe('the updater in its own process', () => {it('tells the master what it staged, and only once that has left asks to be started again as the new build', async () => {const m = make()runUpdaterService(undefined, m.deps)- const staged = m.cli().onStaged('9.9.9') as Promise<void>+ const staged = m.cli().onStaged('9.9.9', null) as Promise<void>expect(m.told).toEqual([{ type: 'harnessd:staged', version: '9.9.9' }])expect(m.calls).not.toContain(`exit ${SERVICE_EXIT_RESTART}`)m.sent()()@@ -96,6 +159,194 @@ describe('the updater in its own process', () => {expect(m.calls).toContain(`exit ${SERVICE_EXIT_RESTART}`)})+ it('a PTY-only staging tells the master ptyVersion alone, and the next run checks the CLI', () => judgingPty(async () => {+ const m = make()+ const service = runUpdaterService(undefined, { ...m.deps, ...m.windows })+ expect(m.pty()).toMatchObject({ rootDir: m.windows.ptyRootDir, url: expect.stringMatching(/\/pty\/metadata\.json$/) })+ expect(m.pty()!.key).toMatch(/^win32-(x64|arm64)$/)+ const staged = m.pty()!.onStaged('0.11.0') as Promise<void>+ expect(m.told).toEqual([{ type: 'harnessd:staged', ptyVersion: '0.11.0' }])+ expect(m.calls).not.toContain(`exit ${SERVICE_EXIT_RESTART}`)+ m.sent()()+ await staged+ expect(m.calls).toContain(`exit ${SERVICE_EXIT_RESTART}`)+ service.stop()+ expect(m.calls.slice(-3)).toEqual(['stop cli', 'stop hn', 'stop pty'])+ // The master starts it again at once: that run checks the CLI, and the host, again.+ const next = make()+ runUpdaterService(undefined, { ...next.deps, ...next.windows }).stop()+ expect(next.cli()).toMatchObject({ currentVersion: VERSION })+ expect(next.pty()).not.toBeNull()+ }))++ it('CLI and PTY in one check send one message with both', () => judgingPty(async () => {+ const m = make()+ runUpdaterService(undefined, { ...m.deps, ...m.windows })+ m.ready.pty = '0.11.0'+ // The CLI poller's handover (lib/selfUpdate.ts): under its lock, the host first, then the CLI.+ await m.cli().withLock!(async () => {+ const host = await m.cli().beforeStage!(2)+ const staged = m.cli().onStaged('9.9.9', host?.version ?? null) as Promise<void>+ m.sent()()+ await staged+ })+ expect(m.told).toEqual([{ type: 'harnessd:staged', version: '9.9.9', ptyVersion: '0.11.0' }])+ expect(m.calls.filter((line) => line === `exit ${SERVICE_EXIT_RESTART}`)).toHaveLength(1)+ }))++ it('a host taken into a CLI handover that then fails is still handed over, alone', () => judgingPty(async () => {+ const m = make()+ runUpdaterService(undefined, { ...m.deps, ...m.windows })+ m.ready.pty = '0.11.0'+ const handover = m.cli().withLock!(async () => {+ await m.cli().beforeStage!(2)+ throw new Error('ENOSPC')+ })+ await vi.waitFor(() => expect(m.told).toEqual([{ type: 'harnessd:staged', ptyVersion: '0.11.0' }]))+ m.sent()()+ await expect(handover).rejects.toThrow('ENOSPC')+ expect(m.calls).toContain(`exit ${SERVICE_EXIT_RESTART}`)+ }))++ it('on Windows, sweeps what installs leave under the lock as it starts, with no terminal host poller too', async () => {+ const root = mkdtempSync(join(tmpdir(), 'updater-sweep-'))+ try {+ mkdirSync(join(root, 'bin'))+ mkdirSync(join(root, 'runtime', 'pty', '.staging-1-1'), { recursive: true })+ for (const name of ['harness.exe', 'harness-launch.exe', 'harness.exe.old-1-1']) writeFileSync(join(root, 'bin', name), name)+ // No HARNESSD_JUDGES_PTY: no poller, the sweep all the same.+ const m = make()+ locked.length = 0+ runUpdaterService(undefined, { ...m.deps, ...m.windows, ptyRootDir: root }).stop()+ expect(m.pty()).toBeNull()+ await vi.waitFor(() => expect(readdirSync(join(root, 'bin')).sort()).toEqual(['harness-launch.exe', 'harness.exe']))+ expect(readdirSync(join(root, 'runtime', 'pty'))).toEqual([])+ expect(locked).toContain('handoff')+ // A bin file missing whose aside file cannot be told from a stale one is put back, never swept.+ rmSync(join(root, 'bin', 'harness.exe'))+ writeFileSync(join(root, 'bin', 'harness.exe.old-2-2'), 'last bytes')+ const again = make()+ runUpdaterService(undefined, { ...again.deps, ...again.windows, ptyRootDir: root }).stop()+ await vi.waitFor(() => expect(readFileSync(join(root, 'bin', 'harness.exe'), 'utf8')).toBe('last bytes'))+ expect(again.calls).toContain('[update] put bin\\harness.exe back from harness.exe.old-2-2')+ } finally { rmSync(root, { recursive: true, force: true }) }+ })++ it('says when the sweep of the terminal host\'s leftovers cannot run, whatever was thrown', async () => {+ for (const thrown of [new Error('locked'), 'plain']) {+ lockFails.push(thrown)+ const m = make()+ runUpdaterService(undefined, { ...m.deps, ...m.windows }).stop()+ await vi.waitFor(() => expect(m.calls).toContain(`[update] could not sweep the terminal host's leftovers (${thrown instanceof Error ? thrown.message : thrown}) — the next start tries again`))+ }+ })++ it('runs no terminal host poller when the manifest url or the platform has none, and says why for the url', () => judgingPty(() => {+ for (const thrown of [new Error('not a CLI manifest url: x'), 'odd']) {+ payload.manifestUrl = () => { throw thrown }+ const m = make()+ runUpdaterService(undefined, { ...m.deps, ...m.windows }).stop()+ expect(m.pty()).toBeNull()+ expect(m.calls).toContain(`[update] no terminal host updates: ${thrown instanceof Error ? thrown.message : thrown}`)+ }+ delete payload.manifestUrl+ payload.platformKey = () => null+ const other = make()+ runUpdaterService(undefined, { ...other.deps, ...other.windows }).stop()+ expect(other.pty()).toBeNull()+ }))++ it('names the installed build to the host poller, and downloads a host payload with this process\'s limits', () => judgingPty(async () => {+ const plain = make()+ runUpdaterService(undefined, { ...plain.deps, ...plain.windows }).stop()+ expect(plain.pty()!.installedCli()).toBe(VERSION)+ const named = make()+ runUpdaterService(undefined, { ...named.deps, ...named.windows, installedVersion: () => '7.7.7' }).stop()+ expect(named.pty()!.installedCli()).toBe('7.7.7')+ const calls: unknown[][] = []+ payload.prepare = async (...args) => { calls.push(args); await (args[2] as { download(ref: unknown): Promise<unknown> }).download({ url: 'u' }); return 'prepared' }+ const entry = { url: 'https://x/pty.zip', sha256: 'a'.repeat(64), size: 1 } as never+ await expect(named.pty()!.deps!.prepare!(entry, 'runtime-dir', Buffer.from('v'))).resolves.toBe('prepared')+ expect(calls[0]!.slice(0, 2)).toEqual([entry, 'runtime-dir'])+ expect(calls[0]![3]).toEqual(Buffer.from('v'))+ expect(downloaded.ref).toEqual({ url: 'u' })+ expect(downloaded.limits).toMatchObject({ floorBytesPerSecond: expect.any(Number) })+ }))++ it('runs no terminal host poller off Windows, or under a master that would not judge it', async () => {+ const plain = make()+ runUpdaterService(undefined, { ...plain.deps, ...plain.windows }).stop()+ expect(plain.pty()).toBeNull()+ expect(plain.cli().beforeStage).toBeUndefined()+ await judgingPty(() => {+ const linux = make()+ runUpdaterService(undefined, linux.deps).stop()+ expect(linux.cli().beforeStage).toBeUndefined()+ })+ expect(processUpdaterDeps('linux').startPty).toBeUndefined()+ expect(processUpdaterDeps('win32', join(tmpdir(), 'x', 'cli')).ptyRootDir).toBe(join(tmpdir(), 'x'))+ })++ it('a paired host whose build then fails to stage is taken back out, and nothing is handed over', () => judgingPty(async () => {+ // Handed over alone, a CLI-2 master would judge host 3 with a CLI-2 core, likely keep it, and no pane could open.+ const root = mkdtempSync(join(tmpdir(), 'updater-paired-'))+ try {+ const ptyRoot = join(root, 'runtime', 'pty')+ // As readyToStage(3) leaves it: 0.11.0 (protocol 3) in use and on probation, 0.10.0 to go back to.+ for (const version of ['0.10.0', '0.11.0']) {+ mkdirSync(join(ptyRoot, version), { recursive: true })+ for (const name of ['harness-pty.exe', 'harness.exe', 'harness-launch.exe']) writeFileSync(join(ptyRoot, version, name), `${version} ${name}`)+ }+ writeFileSync(join(ptyRoot, 'current-pty'), '0.11.0')+ writeFileSync(join(ptyRoot, 'pty-pending.json'), JSON.stringify({ version: '0.11.0', previous: '0.10.0' }))+ mkdirSync(join(root, 'bin'))+ for (const name of ['harness.exe', 'harness-launch.exe']) writeFileSync(join(root, 'bin', name), `0.11.0 ${name}`)+ const m = make()+ runUpdaterService(undefined, { ...m.deps, ...m.windows, ptyRootDir: root })+ m.ready.pty = '0.11.0'+ m.ready.paired = true+ await expect(m.cli().withLock!(async () => {+ await m.cli().beforeStage!(3)+ throw new Error('ENOSPC')+ })).rejects.toThrow('ENOSPC')+ expect(m.told).toEqual([])+ expect(m.calls).not.toContain(`exit ${SERVICE_EXIT_RESTART}`)+ expect(readFileSync(join(ptyRoot, 'current-pty'), 'utf8').trim()).toBe('0.10.0')+ expect(readFileSync(join(root, 'bin', 'harness.exe'), 'utf8')).toBe('0.10.0 harness.exe')+ expect(existsSync(join(ptyRoot, 'pty-pending.json'))).toBe(false)+ // Nothing was wrong with the host: it pairs with the next build.+ expect(existsSync(join(ptyRoot, 'pty-rejected.json')) ? JSON.parse(readFileSync(join(ptyRoot, 'pty-rejected.json'), 'utf8')) : []).toEqual([])+ expect(m.calls).toContain('[update] terminal host 0.11.0 taken back out with the build it came with — back to 0.10.0')+ // And its poller, finished by that install, checks again (backed off) rather than wait for the next updater start.+ expect(m.calls.indexOf('pty taken back')).toBeGreaterThan(m.calls.indexOf('[update] terminal host 0.11.0 taken back out with the build it came with — back to 0.10.0'))+ } finally { rmSync(root, { recursive: true, force: true }) }+ }))++ it('tells the host poller the protocol the build needs, and the CLI\'s rule what is ready to go in first', () => judgingPty(async () => {+ const m = make()+ runUpdaterService(undefined, { ...m.deps, ...m.windows })+ expect(m.cli().readyPtyProtocol?.()).toBeNull()+ m.ready.pty = '0.11.0'+ m.ready.paired = true+ expect(m.cli().readyPtyProtocol?.()).toBe(3)+ expect(await m.cli().beforeStage?.(3)).toEqual({ version: '0.11.0', protocol: 3 })+ expect(m.calls).toContain('ready for 3')+ }))++ it('holds a CLI build back by the installed host\'s protocol on Windows, whatever the master, and nowhere else', () => {+ // Not gated on HARNESSD_JUDGES_PTY: a build with no host to open a pane on is no fix under any master.+ const win = make()+ runUpdaterService(undefined, { ...win.deps, installedPtyProtocol: () => 2 }).stop()+ expect(win.cli().installedPtyProtocol?.()).toBe(2)+ const linux = make()+ runUpdaterService(undefined, linux.deps).stop()+ expect(linux.cli().installedPtyProtocol).toBeUndefined()+ expect(processUpdaterDeps('linux').installedPtyProtocol).toBeUndefined()+ // No current-pty in this root: nothing to read. The CLI's updater (lib/selfUpdate.ts) counts that as this CLI's own+ // PTY_PROTOCOL on Windows, so a build that needs more is still held back.+ expect(processUpdaterDeps('win32', join(tmpdir(), 'no-such-install', 'cli')).installedPtyProtocol!()).toBeNull()+ })+it('stages under the spawn lock, saying who holds it while it waits', async () => {const m = make()runUpdaterService(undefined, m.deps)diff --git a/cli/src/services/updaterProcess.ts b/cli/src/services/updaterProcess.tsindex 1fa9ffe38..73a90fd61 100644--- a/cli/src/services/updaterProcess.ts+++ b/cli/src/services/updaterProcess.ts@@ -12,13 +12,22 @@** Once it has staged a build it exits with `SERVICE_EXIT_RESTART`, and the master starts it again at once:* a staging is the updater's last act on the bundle it runs, and the next check is the new build's.+ *+ * On Windows it checks the terminal host's payload too (lib/windows/ptyUpdate.ts), under a master that judges one+ * (`HARNESSD_JUDGES_PTY`). A host alone is staged and told as `ptyVersion`; a host and a build found at one check go+ * in one lock hold and one message, the host first. Either staging ends this process the same way, and the next run+ * checks both again. A host of a protocol above this build's (a paired one) goes in only with the build that needs it;+ * if that build then fails to stage, the host is taken back out and nothing is told (lib/windows/ptyUpdate.ts+ * `takeBackPty`).*/import { env } from '../config/env.js'-import { SERVICE_EXIT_RESTART, type UpdaterMessage } from '../harnessd/protocol.js'+import { SERVICE_EXIT_RESTART, type StagedUpdate, type UpdaterMessage } from '../harnessd/protocol.js'import { describeSpawnLockOwner, withSpawnLock } from '../lib/daemonSpawnLock.js'-import { DOWNLOAD_LIMITS, isLocalDevBuild, retireCliVersions, startSelfUpdater } from '../lib/selfUpdate.js'+import { DOWNLOAD_LIMITS, downloadVerified, isLocalDevBuild, retireCliVersions, startSelfUpdater } from '../lib/selfUpdate.js'import { currentCli } from '../lib/windows/installLayout.js'import { processRetireDeps } from '../lib/windows/cliVersions.js'+import { preparePtyPayload, ptyManifestUrl, ptyPlatformKey } from '../lib/windows/ptyPayload.js'+import { installedPtyProtocol, startPtyUpdater, sweepPtyLeftovers, takeBackPty, type StagedHost } from '../lib/windows/ptyUpdate.js'import { startTuiUpdater } from '../tui/update.js'import { VERSION } from '../version.js'import { harnessdEnv } from '../lib/harnessdEnv.js'@@ -38,6 +47,13 @@ export interface UpdaterServiceDeps {/** The build that is installed, which the start line names: on Windows the one `cli\current` points to, which after a* rollback is not the build this process runs from. This process's VERSION when left out. */installedVersion?: () => string+ /** Windows: the terminal host's poller, and the install root it works in (`bin\`, `runtime\pty\`). Left out+ * elsewhere. */+ startPty?: typeof startPtyUpdater+ ptyRootDir?: string+ /** Windows: the protocol of the installed host, which a CLI build must not need more than (lib/selfUpdate.ts+ * `installedPtyProtocol`). Left out elsewhere. */+ installedPtyProtocol?: () => number | null}/** [cliDir]: the CLI folder the retirement looks at, this user's own unless a test names one of its own. */@@ -56,12 +72,48 @@ export const processUpdaterDeps = (platform: NodeJS.Platform = process.platform,...(platform === 'win32' ? {retire: () => withSpawnLock('update', () => retireCliVersions(cliDir, processRetireDeps())),installedVersion: () => currentCli(dirname(cliDir))?.version ?? VERSION,+ startPty: startPtyUpdater,+ ptyRootDir: dirname(cliDir),+ installedPtyProtocol: () => installedPtyProtocol(dirname(cliDir)),} : {}),})export function runUpdaterService(_options?: unknown, deps: UpdaterServiceDeps = processUpdaterDeps()): ServiceProcess {// What its master, or the core it runs beside, said: held out of process.env (lib/harnessdEnv.ts).const harnessd = harnessdEnv()+ const installed = deps.installedVersion?.() ?? VERSION+ const limits = { idleMs: env.ADAPTER_UPDATE_IDLE_MS, deadlineMs: env.ADAPTER_UPDATE_DEADLINE_MS, floorBytesPerSecond: DOWNLOAD_LIMITS.floorBytesPerSecond }+ // One lock section at a time in this process. The spawn lock is re-entrant, so it does not keep this process's two+ // pollers apart: a host installed while the CLI's handover is under way would be told in a second message.+ let section: Promise<unknown> = Promise.resolve()+ const oneAtATime = <T>(fn: () => Promise<T>): Promise<T> => {+ const run = section.then(fn, fn)+ section = run.catch(() => {})+ return run+ }+ // The lock spans the byte swap and the word to the master: a `harness start` or `harness update` that+ // lands between them would stage over the backup this one just made.+ const withLock = <T>(fn: () => Promise<T>): Promise<T> => oneAtATime(() => withSpawnLock('handoff', fn, {+ onWaiting: (owner) => deps.log(`[update] waiting — the daemon is ${describeSpawnLockOwner(owner)}`),+ }))+ const handOver = (staged: StagedUpdate): Promise<void> => new Promise<void>((done) => {+ deps.tell({ type: 'harnessd:staged', ...staged }, () => {+ done()+ deps.exit(SERVICE_EXIT_RESTART)+ })+ })+ const pty = startPty(deps, harnessd, installed, limits, withLock, handOver)+ // Windows: what installs leave in bin\ and runtime\pty\ is swept at every start, under the lock; the poller does+ // that itself before its first check, and without one (a master from before, an unusable manifest URL) it is done+ // here. A bin file missing whose aside file holds its bytes is put back first, and while one is not, nothing goes.+ if (!pty && deps.ptyRootDir !== undefined) {+ const root = deps.ptyRootDir+ void withLock(async () => { sweepPtyLeftovers(root, deps.log) })+ .catch((error: unknown) => deps.log(`[update] could not sweep the terminal host's leftovers (${error instanceof Error ? error.message : String(error)}) — the next start tries again`))+ }+ // A host the CLI's handover took (`beforeStage`) and has not told yet: if that stage fails, a supported one is told on+ // its own, and a paired one taken back out.+ let ptyTaken: StagedHost | null = nullconst cli = deps.startCli({currentVersion: VERSION,url: env.ADAPTER_UPDATE_URL,@@ -69,18 +121,39 @@ export function runUpdaterService(_options?: unknown, deps: UpdaterServiceDeps =dir: env.ADAPTER_CLI_DIR,intervalMs: env.ADAPTER_UPDATE_CHECK_MS,slotSecond: env.ADAPTER_UPDATE_SLOT_SEC,- // The lock spans the byte swap and the word to the master: a `harness start` or `harness update` that- // lands between them would stage over the backup this one just made.- withLock: (fn) => withSpawnLock('handoff', fn, {- onWaiting: (owner) => deps.log(`[update] waiting — the daemon is ${describeSpawnLockOwner(owner)}`),+ withLock: (fn) => withLock(async () => {+ try {+ return await fn()+ } finally {+ // Installed for this handover and then the build's stage failed. A supported host is on disk, on probation, and+ // must still be handed over, or no master would judge it. A paired one would come up under this build, which+ // cannot open a pane on it, and a master judging it with this build's core would likely keep it: it is taken+ // back out, and nothing is handed over; its poller, finished by that install, checks again, backed off as a+ // refused payload is, and prepares it again for the build after.+ const taken = ptyTaken+ ptyTaken = null+ if (taken?.paired && deps.ptyRootDir !== undefined) {+ takeBackPty(deps.ptyRootDir, deps.log, '[update] ')+ pty?.takenBack()+ } else if (taken !== null) await handOver({ ptyVersion: taken.version })+ }}),- onStaged: (version) => new Promise<void>((done) => {- deps.tell({ type: 'harnessd:staged', version }, () => {- done()- deps.exit(SERVICE_EXIT_RESTART)- })- }),- limits: { idleMs: env.ADAPTER_UPDATE_IDLE_MS, deadlineMs: env.ADAPTER_UPDATE_DEADLINE_MS, floorBytesPerSecond: DOWNLOAD_LIMITS.floorBytesPerSecond },+ // A paired host (one of a protocol above this build's) goes in only for the build that needs it: the poller is told+ // which protocol that is, and the CLI's protocol rule hears what is ready to go in first.+ ...(pty ? {+ beforeStage: async (ptyProtocol: number) => {+ ptyTaken = await pty.readyToStage(ptyProtocol)+ return ptyTaken && { version: ptyTaken.version, protocol: ptyTaken.protocol }+ },+ readyPtyProtocol: () => pty.readyProtocol(),+ } : {}),+ onStaged: (version, ptyVersion) => {+ ptyTaken = null+ return handOver({ version, ...(ptyVersion ? { ptyVersion } : {}) })+ },+ limits,+ // Under any master: a build that needs a host this machine does not have would open no pane, whoever judged it.+ ...(deps.installedPtyProtocol ? { installedPtyProtocol: deps.installedPtyProtocol } : {}),// A master judges a build staged while the one before is on probation (#807). Beside a core, under a// master too old to run the updater (core/updaterBeside.ts), only one that says so: one from before// rolled the newer build back with the one it judged.@@ -97,9 +170,37 @@ export function runUpdaterService(_options?: unknown, deps: UpdaterServiceDeps =// Never in the way of the update itself: a pass that fails is the next start's to repeat.void deps.retire?.().catch((error: unknown) => deps.log(`[update] retiring older CLI builds failed: ${error instanceof Error ? error.message : String(error)}`))// A development build is never replaced (lib/selfUpdate.ts isLocalDevBuild): it said "on" and polled in silence (G5).- const installed = deps.installedVersion?.() ?? VERSIONdeps.log(isLocalDevBuild(installed)? `[update] self-update off · v${installed} is a development build, which never takes an update`: `[update] self-update on · v${installed} · every ${Math.round(env.ADAPTER_UPDATE_CHECK_MS / 1000)}s`)- return { stop: () => { cli.stop(); hn.stop() } }+ return { stop: () => { cli.stop(); hn.stop(); pty?.stop() } }+}++/** Windows, under a master that judges a host: the terminal host's poller (lib/windows/ptyUpdate.ts). Null otherwise. */+function startPty(+ deps: UpdaterServiceDeps, harnessd: NodeJS.ProcessEnv, installed: string, limits: typeof DOWNLOAD_LIMITS,+ withLock: <T>(fn: () => Promise<T>) => Promise<T>, handOver: (staged: StagedUpdate) => Promise<void>,+): ReturnType<typeof startPtyUpdater> | null {+ if (!deps.startPty || deps.ptyRootDir === undefined) return null+ // Under a master from before, a host staged would be told to no one who rolls it back: it waits for the master to+ // be replaced by one that does (the next CLI update).+ if (harnessd.HARNESSD_JUDGES_PTY !== '1') return null+ const key = ptyPlatformKey()+ let url: string+ try {+ url = ptyManifestUrl(env.ADAPTER_UPDATE_URL)+ } catch (error) {+ deps.log(`[update] no terminal host updates: ${error instanceof Error ? error.message : String(error)}`)+ return null+ }+ if (key === null) return null+ return deps.startPty({+ url, key, rootDir: deps.ptyRootDir,+ intervalMs: env.ADAPTER_UPDATE_CHECK_MS,+ slotSecond: env.ADAPTER_UPDATE_SLOT_SEC,+ installedCli: () => deps.installedVersion?.() ?? installed,+ withLock,+ onStaged: (ptyVersion) => handOver({ ptyVersion }),+ deps: { prepare: (entry, runtimeDir, verified) => preparePtyPayload(entry, runtimeDir, { download: (ref) => downloadVerified(ref, limits) }, verified) },+ })}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 0822abec3..cc3088588 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -961,6 +961,9 @@ class AppNotifier extends ChangeNotifier {if (_disposed) return;final wasForeground = foreground.value;foreground.value = state == null || state == AppLifecycleState.resumed;+ // Every transition, not only the three the listener has callbacks for: hidden -> inactive fires+ // onShow, and a window shown again without focus must not keep telling the daemon it shows nothing.+ _announceVisibleAgents();if (wasForeground && !foreground.value) {_awaySince = phoneOfferClock();_missedWhileAway = null;@@ -4945,7 +4948,9 @@ class AppNotifier extends ChangeNotifier {// restarted — has never been told what is on the grid. Without this// the dial goes back to beeping about tiles in plain sight until the// next time a pane happens to change.+ _announcedVisible.remove(machineId);_announceOpenPanesToDial();+ _announceVisibleAgents();_announceUnreadToDial();// ...nor which tile this window is looking at. The daemon repeats that to the dial after every// list push, which is what keeps the two screens from drifting apart — but it can only repeat@@ -5006,7 +5011,71 @@ class AppNotifier extends ChangeNotifier {if (previousMachineId != null && previousMachineId != machineId) {_sendAppFocus(previousMachineId, null);}+ _announcedFocusAgentId = machineId == null ? null : agentId;if (machineId != null) _sendAppFocus(machineId, agentId);+ // The selected pane moved with a tab switch or a close, and the tiles on screen moved with it.+ _announceVisibleAgents();+ }++ String? _announcedFocusAgentId;++ /// The signature of the `visibleAgents` last sent to each machine's daemon, so a change in what is+ /// on screen is sent once and a repeat is not. Forgotten on (re)connect: a new daemon has no list.+ final Map<String, String> _announcedVisible = {};++ /// Whether the super tab [swarmId] shows its terminal canvas (it hides it behind chat or the+ /// member list, with the panes still mounted `Offstage`). Only the workspace knows.+ String? _superTerminalsShownSwarm;++ void setSuperTabTerminalsShown(String swarmId, bool shown) {+ final next = shown ? swarmId : null;+ if (_superTerminalsShownSwarm == next ||+ (!shown && _superTerminalsShownSwarm != swarmId)) {+ return;+ }+ _superTerminalsShownSwarm = next;+ _announceVisibleAgents();+ }++ /// The agents on [machineId] whose tiles a person can see in this window right now: the active+ /// tab's mounted, non-`Offstage` tiles (the zoomed one alone while zoomed), and none while the+ /// window is minimized or hidden to the tray. A window that is merely behind another app still+ /// shows its tiles, so it still lists them; only hidden/paused/detached empty the list.+ List<String> visibleAgentIds(String machineId) {+ switch (lifecycle()) {+ case AppLifecycleState.hidden:+ case AppLifecycleState.paused:+ case AppLifecycleState.detached:+ return const [];+ case AppLifecycleState.resumed:+ case AppLifecycleState.inactive:+ case null:+ break;+ }+ final tab = activeSwarm;+ if (tab.isStore || tab.isOrchestrator) return const [];+ if (tab.isSuperTab && _superTerminalsShownSwarm != tab.id) return const [];+ return [+ for (final pane in tab.panes)+ if (pane.machineId == machineId &&+ (tab.zoomedPaneId == null || pane.id == tab.zoomedPaneId))+ ?pane.agentId,+ ];+ }++ /// Tell each daemon on this computer which terminals are on screen, when that changed.+ void _announceVisibleAgents() {+ final pool = _pool;+ if (pool == null) return;+ for (final machineId in pool.machineIds) {+ final list = visibleAgentIds(machineId);+ if (_announcedVisible[machineId] == list.join(',')) continue;+ if (_deskConnection(machineId) == null) continue;+ _sendAppFocus(+ machineId,+ machineId == _announcedFocusMachineId ? _announcedFocusAgentId : null,+ );+ }}/// The socket [machineId]'s desk frames ride — `app_focus`, `app_panes`, `app_swarms`, `app_unread`,@@ -5023,10 +5092,15 @@ class AppNotifier extends ChangeNotifier {// Never create a socket just to move focus, and never queue stale focus// across a reconnect. The connected callback reasserts the current pane.final send = focusFrameSenderForTest;+ final visible = visibleAgentIds(machineId);+ _announcedVisible[machineId] = visible.join(',');final pending = send != null? send(machineId, agentId): _deskConnection(machineId)?.sendTerminalFrame('app_focus', {'agentId': agentId,+ // Every terminal of this machine that is on screen; [] for a hidden window. An older+ // daemon ignores it.+ 'visibleAgents': visible,if (_deviceFocusRevision != null)'focusRevision': _deviceFocusRevision,});@@ -5127,7 +5201,10 @@ class AppNotifier extends ChangeNotifier {/// Re-send the tile roster because the WINDOW moved, not because the tiles/// did. Public so the lifecycle listener can say so; the roster itself is/// unchanged and the `foreground` flag riding with it is the point.- void announceWindowForeground() => _announceOpenPanesToDial();+ void announceWindowForeground() {+ _announceOpenPanesToDial();+ _announceVisibleAgents();+ }bool _announceFromDevice = false;int _devicePick = 0;@@ -18054,6 +18131,7 @@ class AppNotifier extends ChangeNotifier {if (id == null || panes.length < 2) return;zoomedPaneId = zoomedPaneId == id ? null : id;_persistLayout();+ _announceVisibleAgents();notifyListeners();}@@ -19026,6 +19104,7 @@ class AppNotifier extends ChangeNotifier {});_layoutRevision++;_announceOpenPanesToDial();+ _announceVisibleAgents();_freezeDeskLayouts();_deskQueueDiff();final saved = swarms.where((swarm) => !isDraftSwarm(swarm.id)).toList();diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex f9ed37b7d..19180b0e2 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -401,6 +401,10 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {_readyRequest == _terminalRequest &&agents.isNotEmpty &&tab.panes.isNotEmpty;+ // The terminal canvas is mounted either way; whether a person can see it is this.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) app.setSuperTabTerminalsShown(tab.id, showTerminal);+ });final lead = controller.snapshot?.agents.where((a) => controller.snapshot!.isLead(a.id)).firstOrNull;diff --git a/desktop/test/app_focus_visible_agents_test.dart b/desktop/test/app_focus_visible_agents_test.dartnew file mode 100644index 000000000..777990a7f--- /dev/null+++ b/desktop/test/app_focus_visible_agents_test.dart@@ -0,0 +1,123 @@+// `app_focus.visibleAgents`: which terminals a person can see in this window, so the daemon can tell+// "someone is looking at this agent" from "it is mounted somewhere nobody sees".+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show createApp;++class _Conn extends WsConn {+ _Conn()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ transportKind: WsTransportKind.localPlaintext,+ localWsUri: Uri.parse('ws://127.0.0.1:1/ws'),+ );++ final sent = <Map<String, dynamic>>[];++ @override+ Future<bool> sendTerminalFrame(+ String type,+ Map<String, dynamic> payload,+ ) async {+ if (type == 'app_focus') sent.add(payload);+ return true;+ }+}++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late AppNotifier app;+ late _Conn conn;+ var lifecycleState = AppLifecycleState.resumed;++ TerminalPane tile(int id, String agentId) =>+ TerminalPane(id: id, machineId: 'm', agentId: agentId);++ List<String>? lastList() =>+ (conn.sent.last['visibleAgents'] as List?)?.cast<String>();++ setUp(() async {+ lifecycleState = AppLifecycleState.resumed;+ conn = _Conn();+ app = createApp(connectionForTest: (_) => conn, connected: true)+ ..lifecycle = () => lifecycleState;+ addTearDown(app.dispose);+ app.adoptPoolConnectionForTest('m', conn);+ final first = app.activeSwarm;+ first.panes.addAll([tile(1, 'a1'), tile(2, 'a2')]);+ app.newSwarm(name: 'Second');+ app.activeSwarm.panes.addAll([tile(3, 'b1'), tile(4, 'b2')]);+ app.selectSwarm(first.id);+ conn.sent.clear();+ });++ test('app_focus carries the on-screen tiles', () {+ final first = app.swarms.first.id;+ final second = app.swarms.last.id;+ app.selectSwarm(second);+ expect(lastList(), ['b1', 'b2']);+ app.selectSwarm(first);+ expect(lastList(), ['a1', 'a2']);+ });++ test('a zoomed tile is the only one on screen', () {+ app.focusPane(1);+ app.toggleZoomPane();+ expect(lastList(), ['a1']);+ });++ test('minimizing sends an empty list, restoring sends the tiles back', () {+ lifecycleState = AppLifecycleState.hidden;+ app.announceWindowForeground();+ expect(lastList(), isEmpty);+ // Behind another app is still on screen.+ lifecycleState = AppLifecycleState.inactive;+ app.announceWindowForeground();+ expect(lastList(), ['a1', 'a2']);+ });++ test('the real lifecycle path re-announces on every state change', () {+ final binding = TestWidgetsFlutterBinding.instance;+ final listener = AppLifecycleListener(+ onStateChange: app.appLifecycleChanged,+ );+ addTearDown(listener.dispose);+ app.lifecycle = () => binding.lifecycleState;+ binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ expect(lastList(), isEmpty);+ // hidden -> inactive fires onShow, not onInactive: a window brought back without focus.+ binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ expect(lastList(), ['a1', 'a2']);+ binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ });++ test('a repeat of the same list is not sent again', () {+ app.announceWindowForeground();+ app.announceWindowForeground();+ expect(conn.sent, isEmpty);+ });++ test('a super tab whose terminal canvas is not shown lists nothing', () {+ final superTab = Swarm(id: 'st', name: 'Super', kind: 'superTab')+ ..superTabId = 'st-remote'+ ..panes.add(tile(5, 's1'));+ app.swarms.add(superTab);+ app.selectSwarm('st');+ expect(lastList(), isEmpty);+ app.setSuperTabTerminalsShown('st', true);+ expect(lastList(), ['s1']);+ app.setSuperTabTerminalsShown('st', false);+ expect(lastList(), isEmpty);+ });+}diff --git a/docs/superpowers/plans/2026-10-20-pty-host-rollover.md b/docs/superpowers/plans/2026-10-20-pty-host-rollover.mdnew file mode 100644index 000000000..8ea7d9d9e--- /dev/null+++ b/docs/superpowers/plans/2026-10-20-pty-host-rollover.md@@ -0,0 +1,964 @@+# PTY Host Rollover and Delivery (sub-project G) Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** A PTY payload the owner promotes reaches every Windows machine through the self-update. New panes run the new+host and old hosts drain away. Running agents move to the new host by themselves while idle and off screen, unnoticed.++**Architecture:**+- **One host per build.** The host's instance name becomes `p<protocol>-<version tag>`, and every file the instance+ keys follows it, so two builds of protocol 2 run side by side in one home. A seeded `create` is an optional+ protocol-2 feature that the host advertises; `PTY_PROTOCOL` stays 2.+- **Create and drain.** The daemon computes its target instance from the binary it would start. That host is the+ create backend; every other host is a drain backend, reusing today's drain.+- **Delivery.** A PTY poller beside the CLI and hn pollers in the updater process reads the production+ `pty/metadata.json`. It downloads, verifies, canaries and installs a newer payload beside the old one, replaces+ `bin\harness.exe` and `bin\harness-launch.exe` by rename-aside, moves `current-pty`, and tells the master, whose+ probation covers the PTY as it covers the CLI.+- **The mover.** A daemon service moves one idle, quiet, unwatched `conversation` agent at a time onto a host that+ can seed. It captures the old pane, opens a seeded pane on the new host, relaunches the engine with its resume argv,+ swaps the row's runtime, moves open streams, and closes the old pane. On failure it relaunches in the old pane.+- **On screen.** The desktop reports which tiles are on screen through its existing `app_focus` message.++**Tech Stack:**+- Rust 2024 (`pty/`, alacritty_terminal).+- TypeScript (Node 22) in `cli/`, vitest. PowerShell 5.1 in `cli/scripts/install.ps1`.+- Flutter/Dart in `desktop/`, one message field.+- GitHub Actions `windows.yml` (on demand) and `ci.yml`.++**Spec:** `docs/superpowers/specs/2026-10-20-pty-host-rollover-design.md`. Read it first: its Anti-goals are the+acceptance bar.++**Where and when.**+- Branch `feat/windows-pty-rollover`, recreated from current `main`. The old branch (from before the Windows merge)+ is replaced: its history holds commits from before the public-data cleanup. Force-pushing it needs the owner's OK.+- The worktree is `~/harnesses/worktrees/openharness/windows-pty-rollover`.+- First commit: this plan and the spec (`docs: PTY host rollover and delivery spec and plan`).+- Commits and pushes of `feat/windows-pty-rollover` are authorized once it is recreated. Never push `main`; no other+ force-push.+- It ships as its own PR to `main`, opened only when the owner asks.++## Global Constraints++**Platform and behaviour**+- Per user, with no administrator rights and no UAC prompt.+- Scope is Windows, where the PTY host is the terminal backend. tmux is not touched.+- No UI on any client, and no new frame type from the daemon to clients. The only new client signal is+ `app_focus.visibleAgents`, from the desktop to the daemon.+- Never interrupt a turn, and never end a terminal or an engine that cannot resume. Never lose input. Never give an+ agent a new id.++**The host**+- `PTY_PROTOCOL` stays `2` (Rust `pty/src/protocol.rs`, TS `cli/src/lib/ptyHost/protocol.ts`).+ `SUPPORTED_PTY_PROTOCOLS` stays `[1, 2]`.+ - The `protocol.spec.ts` test "keeps the protocol that installed Windows hosts speak" stays until G3.4, which+ replaces it with the CLI protocol rule.+- **Features:**+ - a G host lists `"features":["seed"]` in its hello reply and in its `version` line. A pre-G host lists none; an+ absent field means `[]`;+ - TS `SEED_FEATURE = 'seed'`.+- **Instance name:** `p<protocol>-<tag>`.+ - `<tag>` is the version when it matches `^[0-9A-Za-z.-]{1,32}$`.+ - Otherwise `<tag>` is `h` followed by the first 12 hex digits of SHA-256(version).+ - Pre-G hosts keep `p<protocol>`.+- **Files, all in `<home>/run/`:**+ - `pty-host-<instance>.json` (discovery);+ - `.lock`, `.panes` and `.sock`, with the same stem;+ - when `<home>/run/pty-host-<instance>.sock` would be longer than 100 bytes, the socket is+ `pty-host-s<12 hex of SHA-256(instance)>.sock`;+ - the Windows pipe suffix is `-<instance>`;+ - the host log is `<home>/logs/pty-host-<instance>.log`.+ - Legacy names (`pty-host-<protocol>.json`) are still read.++**Delivery**+- Manifest: `ADAPTER_UPDATE_URL` with its trailing `cli/metadata.json` replaced by `pty/metadata.json`, key `pty`.+ - The entry key is `win32-x64` when `process.arch` is `x64`, and `win32-arm64` when it is `arm64`. The installed+ Node is the machine's native one, as `install.ps1` picks it.+- `PTY_PAYLOAD_FILES`: `harness-pty.exe`, `harness-launch.exe`, `harness.exe`, `conpty.dll`, `OpenConsole.exe`,+ `harness-serial.exe`.+- Under `<runtime>/pty/`:+ - the staging folder is `.staging-<pid>-<ms>`;+ - the probation marker is `pty-pending.json`, `{ "version": s, "previous": s }`;+ - the rejected list is `pty-rejected.json`, a JSON array of versions.+- Renamed-aside files are `bin\<name>.old-<pid>-<ms>`. They are deleted at each updater start, and whenever deletion+ fails (still running), they are left for the next one.+- Canary:+ - `harness-pty.exe version` must print JSON whose `version` is the entry's, whose `protocol` is in+ `SUPPORTED_PTY_PROTOCOLS`, and whose `features` is an array;+ - `harness-serial.exe version`'s `version` must be the entry's;+ - each run has a 5 s timeout, with `windowsHide: true`.+- The CLI's host protocol: a G build answers `cli.js version --json` with `{"version":s,"ptyProtocol":n}`. Output that+ is not that JSON means protocol 2.+- Updater message: `{ type: 'harnessd:staged', version?: string, ptyVersion?: string }`, with at least one of the two.+- The same refusal back-off as the CLI's (`refuse` in `startSelfUpdater`). The same dev-build rule+ (`isLocalDevBuild` of the installed CLI).++**The mover**+- `QUIET_MS = 300_000`: idle with no input for this long.+- `MOVE_TIMEOUT_MS = 30_000`: the new engine must be proven within this.+- `SEED_MAX_BYTES = 4 * 1024 * 1024`: the oldest lines are dropped first.+- `SEED_HISTORY_LINES = 2000`.+- One move at a time per daemon. It runs as `restartJobs.run(agentId, fn, 'move')`.+- A move's target must list `seed`. With a pre-G target, nothing moves.++**Testing and safety**+- Never against the developer's own `~/.harness`, the daemon on 18473, engine homes or tmux.+- No production publish. A staging publish needs the owner's OK. The E2E serves its manifests from the fake HTTPS+ CDN (`fake-cdn.sh`).+- On the ARM64 VM, never touch `C:\work\e2e` or the admin profile's engine settings. On the x64 test PC, touch only+ what G installs, and clean up.+- The repo is public: no addresses, account names, ids, serials or passwords in committed evidence.+- Docs, comments and commit messages are in English. Comments say why.+- Never bare `git stash`, never `git clean -fdx`.+- Conventional commits ending with the engine's `Co-Authored-By` line.++## Review Focus++1. **`bin\harness.exe` is running when the payload lands** (a hook, a `harness send`): the rename-aside leaves the+ path answering at every moment, and the aside file goes once it exits. Pinned by G3.2's Windows real test.+2. **A PTY-only update on a machine whose CLI is current**: the master hands over with `ptyVersion` alone, the new+ core targets the new host, and the updater's next run still checks the CLI. Pinned by G3.3+ `a PTY-only staging tells the master ptyVersion alone, and the next run checks the CLI`.+3. **`<runtime>/pty/<version>/` already exists** (an `install.ps1` that put it there, or a rolled-back version's+ folder kept by §3): it is reused only when its six files match the zip byte for byte, else the payload is+ refused. Pinned by G3.2 `an existing version folder is reused only when it matches`.+4. **The daemon killed mid-move**, after the old engine stopped and before the swap.+ - After restart the row still names the old pane, which the existing restore relaunches.+ - The new pane carries `HARNESS_MOVE_OF=<agentId>`; it is killed at start before discovery, so the reconciler+ never mints a second agent for it.+ - Pinned by G4.5 `a_move_pane_left_by_a_dead_daemon_is_removed_before_discovery`.+5. **Someone arrives during the swap.**+ - Keystrokes, a paste, or a `harness send` are delivered once, in order, to the new pane.+ - A stream opened then opens on the new pane, and one already open follows it.+ - Pinned by G4.4.++## File map++| File | Task | Responsibility |+|---|---|---|+| `pty/src/instance.rs` (new), `discovery.rs`, `host_lock.rs`, `pane_ids.rs`, `transport/{unix,windows}.rs`, `logfile.rs`, `cli.rs` | G1.1 | Instance per build; every keyed file |+| `pty/tests/fixtures/instances.json` (new), `pty/tests/common/mod.rs`, `pty/tests/control.rs` | G1.1 | Shared vectors; tests that hard-code names |+| `pty/src/protocol.rs`, `cli.rs`, `server.rs` (hello reply), `panes.rs`, `pane.rs`, `pty/tests/fixtures/ops.json`, `pty/tests/stream.rs` | G1.2 | `features`; `create.seed` |+| `cli/src/lib/ptyHost/instance.ts` (new), `launch.ts`, `protocol.ts`, `client.ts`, `cli/src/lib/terminalRuntime.ts`, every `HARNESS_PANE` parser | G2.1 | Discovery by instance; the target; names; features |+| `cli/src/lib/ptyHostBackend.ts`, `cli/src/lib/ptyHost/drain.ts`, `cli/src/core/main.ts` | G2.2 | Create and drain per instance |+| `cli/src/lib/uninstall/ptyHosts.ts` | G2.3 | Uninstall ends every instance |+| `cli/src/lib/windows/ptyPayload.ts` (new) | G3.1 | Check, download, verify, unpack, canary |+| `cli/src/lib/windows/ptyInstall.ts` (new) | G3.2 | Install under the lock, undo, aside files, probation marker, rollback |+| `cli/src/lib/windows/ptyUpdate.ts` (new), `cli/src/services/updaterProcess.ts`, `cli/src/harnessd/{protocol,supervisor,masterProcess}.ts`, `cli/src/lib/selfUpdate.ts` | G3.3 | The poller; one handover; probation and rollback |+| `cli/src/cli.ts` (`version --json`, `harness update`), `selfUpdate.ts` (canary), `protocol.spec.ts`, B spec | G3.4 | The protocol rule; `harness update` |+| `cli/scripts/install.ps1`, `cli/src/scripts/installPs1.spec.ts` | G3.5 | Restart when only the PTY moved |+| `desktop/lib/state/app_state.dart`, `desktop/lib/super_tabs/workspace.dart`, `cli/src/localWsServer.ts`, `cli/src/backendSocket.ts`, `cli/src/lib/terminalStreamManager.ts`, `cli/src/core/terminalWatch.ts` | G4.1 | Who is looking |+| `cli/src/lib/hostMove/quiet.ts` (new) | G4.2 | Idle and input clocks |+| `cli/src/lib/terminalTypes.ts`, `ptyHostBackend.ts`, `cli/src/lib/hostMove/seed.ts` (new) | G4.3 | Seeded create; seed from capture |+| `cli/src/lib/hostMove/gate.ts` (new), `terminalStreamManager.ts`, `cli/src/lib/sessionInput.ts` | G4.4 | Hold input; move open streams |+| `cli/src/lib/hostMove/moveAgent.ts` (new) | G4.5 | One move, with its fallback |+| `cli/src/lib/hostMove/mover.ts` (new), `cli/src/core/main.ts` | G4.6 | Which agent, when; wiring |+| `cli/src/lib/hostMove/hostMove.real.spec.ts` (new), `.github/workflows/windows.yml` | G5.1 | Two real builds |+| `docs/testing/pty-rollover-e2e.md` (new), the spec | G5.2 | The VM and the x64 PC; status |++---++## Phase G1: The host++### Task G1.1: One instance per host build++**Files:** `pty/src/instance.rs` (new). Modify `pty/src/{lib.rs,discovery.rs,host_lock.rs,pane_ids.rs,cli.rs,+logfile.rs}`, `pty/src/transport/{unix.rs,windows.rs}`. Tests: in-file, `pty/tests/fixtures/instances.json`+(new), `pty/tests/common/mod.rs`, `pty/tests/control.rs`.++**Interfaces:**+- Produces (Rust):+ - `pub fn instance_name(protocol: u32, version: &str) -> String`;+ - `pub fn current() -> String` (`instance_name(PROTOCOL, VERSION)`);+ - `pub fn run_file(run_dir: &Path, instance: &str, ext: &str) -> PathBuf` (`pty-host-<instance>.<ext>`);+ - `pub fn socket_path(run_dir: &Path, instance: &str) -> PathBuf`, with the 100-byte rule;+ - `pub fn log_path(home: &Path, instance: &str) -> PathBuf`.+ - `discovery::instance()` is removed; callers use `instance::current()`.+- Produces (shared): `pty/tests/fixtures/instances.json`, an array of `{ "protocol": n, "version": s, "instance": s }`.+ It covers:+ - `0.4.20`;+ - `0.4.21-dev.win1`;+ - `0.1.0`;+ - `0.4.21+meta`, `1 2` and a 40-character version, all hash form.++- [ ] **Step 1: Write the failing tests.**+ - `instance.rs`:+ - `names_follow_the_shared_vectors` reads `../tests/fixtures/instances.json` and asserts each entry.+ - `a_long_home_uses_the_hashed_socket_name`: a run dir of 90 bytes gives `pty-host-s<12hex>.sock`, and a short+ one gives `pty-host-<instance>.sock`.+ - `two_builds_have_different_files`: `run_file` differs for `0.4.20` and `0.4.21`.+ - `tests/control.rs`, a new `two_versions_serve_side_by_side`, run only when `HARNESS_PTY_BIN_OLD` names a build+ of this source with another `HARNESS_PTY_VERSION` (built as in G5.1):+ 1. start it and `CARGO_BIN_EXE_harness-pty` on one home;+ 2. both publish their own discovery files and both answer hello, with different instances.+ - Update `discovery_names_the_host`, `children_see_harness_pane` and every hard-coded `pty-host-{PROTOCOL}` or+ `p{PROTOCOL}` in `tests/control.rs` and `tests/common/mod.rs` (`grep -n 'pty-host-\|"p{' pty/tests`) to go+ through `instance::current()` and `run_file`.+- [ ] **Step 2: Run them and see them fail.**+ - Run: `cd pty && cargo test --locked instance`.+ - Expected: FAIL; `instance` is not found.+- [ ] **Step 3: Implement.**+ - `instance.rs` per the Global Constraints (SHA-256 via the existing `sha2` dependency).+ - Rewrite `PROTOCOL`'s doc comment "Each value is its own host instance" to "each (protocol, version) is its own+ instance". The value stays 2.+ - Route `discovery::file_path`, the `.tmp` name, `host_lock::file_path`, `pane_ids::file_path`,+ `transport::unix::socket_path`, `set_discovery_aside`, the Windows `pipe_name` suffix, `logfile` and+ `Panes::child_env`'s instance through `instance::current()` and `run_file`.+ - The log rotation stays lock-holder-only, now per instance.+- [ ] **Step 4: Run.**+ - Run: `cd pty && cargo test --locked`.+ - Expected: PASS, every unit and integration test. Windows runs it in `windows.yml` (G5.1); Linux in `ci.yml`.+- [ ] **Step 5: Commit** `feat(pty): one host instance per build, so two versions run side by side`.++### Task G1.2: Features, and a pane created with a seed++**Files:**+- Modify: `pty/src/protocol.rs` (`Op::Create`; a `FEATURES` constant), `pty/src/cli.rs` (`version_line`), the hello+ reply's writer (`grep -n '"proof"' pty/src`), `pty/src/panes.rs`, `pty/src/pane.rs` (`PaneSpec`, `Pane::spawn`).+- Tests: `pty/tests/fixtures/ops.json`, `pty/tests/ops_fixture.rs`, `pty/tests/stream.rs`, `parses_every_op` in+ `protocol.rs`, `version_line_is_json_with_protocol` in `cli.rs`.++**Interfaces:**+- Produces:+ - `pub const FEATURES: &[&str] = &["seed"]`. The hello reply carries `"features": FEATURES`, and `version_line()`+ prints `{"version":…,"protocol":2,"features":["seed"]}`.+ - `Op::Create { …, seed: Option<String> }`. The JSON field is `"seed"` and its default is absent. Its text is the+ `capture`/`history` style: SGR-only ANSI, one line per row.+ - `PaneSpec.seed: Option<Vec<u8>>`.++- [ ] **Step 1: Write the failing tests.**+ - `version_line_is_json_with_protocol` also asserts `v["features"] == ["seed"]`. A hello test in+ `tests/control.rs` asserts the reply's `features`.+ - `ops.json` gains `"seed": "a\r\nb"` on its `create` entry.+ - `tests/stream.rs` gains `a_seeded_pane_starts_with_its_seed_in_history`:+ 1. create with `seed = "one\r\ntwo\r\n\x1b[31mthree\x1b[0m"`, `rows = 10`, and a command that sleeps before it+ prints;+ 2. take the snapshot before any output: `history` ends with the three lines in order, colour kept, and+ `capture` is blank with the cursor at 0,0;+ 3. after the child prints `ready`, `capture`'s first line is `ready`.+ - `a_create_without_seed_is_unchanged`: today's snapshot is unchanged.+- [ ] **Step 2: Run.**+ - Run: `cd pty && cargo test --locked seed ops_fixture version_line hello`.+ - Expected: FAIL. `features` is missing, `seed` is an unknown field in the fixture check, and the test is missing.+- [ ] **Step 3: Implement.**+ - In `Pane::spawn`, between `Term::new` and `attach`:+ 1. advance the seed bytes;+ 2. then advance `"\r\n"` repeated `rows` times and `"\x1b[H"`, so the seed sits wholly in scrollback and the+ live screen is blank;+ 3. bump `seq` once.+ - `draw_from_host`'s `cfg` gate does not apply here: this is spawn's own code path.+ - Update the TS `PtyOp` create type and the hello reply type in the same commit, so the `ops.json` check in+ `cli/src/lib/ptyHost/protocol.spec.ts` stays green.+- [ ] **Step 4: Run.**+ - Run: `cd pty && cargo test --locked` and `cd cli && npx vitest run src/lib/ptyHost/protocol.spec.ts`.+ - Expected: PASS.+- [ ] **Step 5: Commit** `feat(pty): advertise features, and create a pane seeded with another pane's scrollback`.++---++## Phase G2: The daemon finds hosts by instance++### Task G2.1: Instances, discovery, features and the target++**Files:**+- Create: `cli/src/lib/ptyHost/instance.ts`.+- Modify: `cli/src/lib/ptyHost/{launch.ts,protocol.ts,client.ts}`, `cli/src/lib/terminalRuntime.ts`, and every+ `HARNESS_PANE` parser. Find them with+ `grep -rn "HARNESS_PANE\|p\\\\d{1,4}" cli/src cli/hook --include=*.ts --include=*.mjs`; today that includes+ `terminalRuntime.ts` `PTY_HOST_PANE`, `hook/notify.mjs`, `messages/command.ts` and `remoteCommand.ts`.+- Tests: `instance.spec.ts` (new), `launch.spec.ts`, `client.spec.ts`, `terminalRuntime.spec.ts`.++**Interfaces:**+- Produces:+ - `hostInstanceName(protocol: number, version: string): string`, held to `pty/tests/fixtures/instances.json`.+ - `PTY_HOST_INSTANCE: RegExp`, which is `^p\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?$`, used by every+ `HARNESS_PANE` parser as `^(<instance>):(%\d{1,9})$`.+ - `SEED_FEATURE = 'seed'` in `protocol.ts`. `PtyHostClient.features: readonly string[]`, from the hello reply,+ `[]` when absent.+ - `interface PtyHostTarget { protocol: number; version: string; instance: string; features: readonly string[];+ source: 'installed' | 'binary' }`. `installed` means the version came from `current-pty`.+ - `listDiscoveries(home: string): PtyHostDiscovery[]`. It reads every `run/pty-host-*.json`, legacy included,+ keeps only files whose own `protocol` and `instance` fields are well formed, and sorts by protocol, then+ `compareVersions`.+ - `readInstanceDiscovery(home: string, instance: string): PtyHostDiscovery | null`. It reads legacy `p<n>` from+ `pty-host-<n>.json`.+ - `binaryVersion(binary: string): { version: string; protocol: number; features: string[] } | null`. It runs+ `binary version` with a 5 s timeout, `windowsHide: true`, and an argument array, and is cached by path and mtime.+ G3.1 and G3.4 use it too.+ - `targetHost(options?: PtyHostBinaryOptions): PtyHostTarget | null`. The binary is `ptyHostBinary()`; the+ version is `currentPtyVersion()` when the binary is that folder's (`source: 'installed'`), else+ `binaryVersion()` (`source: 'binary'`). The protocol and features always come from `binaryVersion()`. It is null+ when the version is unknown.+ - `ensurePtyHost(home, options & { target: PtyHostTarget | null })`.+ - With a target, it connects only to that instance's host, else starts the binary.+ - With `null`, it does what it does today: the newest running `PTY_PROTOCOL` host, else start.+ - `startHost` dedupes by home and instance.+ - `reachPtyHost(home: string, instance: string, liveness?)`.+ - `forgetExitedHost(home: string, instance: string, pid: number)`.+ - `discoveredHostDead(home, discovery: Pick<PtyHostDiscovery, 'instance' | 'pid'>, liveness?)`.+ - `discoverHosts(home)` becomes `listDiscoveries`. Its old protocol-only callers go through it.+ - `removeUnusedPtyVersions(home, runtimeDir?)`. Its running set comes from `listDiscoveries`, so every instance+ counts. Its rule is otherwise unchanged: only versions older than `current-pty`; newer folders stay.++- [ ] **Step 1: Write the failing tests.**+ - `instance.spec.ts`: `names follow the host's shared vectors`, which reads `../pty/tests/fixtures/instances.json`.+ - `client.spec.ts`: `features come from the hello reply, empty when absent`.+ - `launch.spec.ts`. Extend the helper `writeDiscoveryOf(home, protocol, value)` with an instance and file name.+ - `listDiscoveries finds legacy and versioned hosts, oldest first`.+ - `targetHost reads current-pty, and is installed`.+ - `targetHost asks a dev binary its version, and is binary` (a fake binary printing+ `{"version":"9.9.9","protocol":2,"features":["seed"]}`).+ - `targetHost is null when neither is known`.+ - `ensurePtyHost with a target never connects to another version's host` (two fake answering hosts).+ - `ensurePtyHost without a target connects to the newest running host`.+ - `removeUnusedPtyVersions keeps a folder a versioned host runs from`.+ - Update the existing `readDiscovery`, `reachPtyHost`, `forgetExitedHost` and `removeUnusedPtyVersions` cases to+ the instance signatures.+ - `terminalRuntime.spec.ts`: `sessionForPaneId accepts p2-0.4.21-dev.win1:%7 and p2-h0123456789ab:%7`.+ - Add the same case to each other parser's spec.+- [ ] **Step 2: Run.**+ - Run: `cd cli && npx vitest run src/lib/ptyHost src/lib/terminalRuntime.spec.ts`.+ - Expected: FAIL on the new cases.+- [ ] **Step 3: Implement** to the signatures above. `client.ts` keeps speaking the protocol its discovery file names.+- [ ] **Step 4: Run.**+ - Run the same command, plus `npx tsc --noEmit -p .`.+ - Expected: PASS. Fix every type error the signature changes cause in their callers (G2.2 and G2.3 own the+ behaviour; here only compile).+- [ ] **Step 5: Commit** `feat(cli): find pty hosts by instance and pick the installed build as the target`.++### Task G2.2: Create on the target, drain the rest++**Files:**+- Modify: `cli/src/lib/ptyHostBackend.ts`, `cli/src/lib/ptyHost/drain.ts`, `cli/src/core/main.ts` (around+ `prepareTerminalBackends`).+- Tests: `drain.spec.ts`, `ptyHostBackend.spec.ts`.++**Interfaces:**+- Consumes: G2.1.+- Produces:+ - `PtyHostBackendOptions` gains `instance?: string` (a drain backend's host) and `target?: PtyHostTarget | null`+ (the create backend's). `protocol` goes.+ - `draining` is `instance !== undefined`.+ - The drain backend's `instance` is set from the option before it is reached, as `p${protocol}` is today.+ - `PtyHostBackend.mayShutDown: boolean`. It is false when there is no target, or when the drain host's discovery+ `version` is newer than the target's (`compareVersions > 0`) and the target's `source` is `binary`. A newer host+ with an `installed` target is a downgrade or a rollback (spec §2): it drains and shuts down like any other.+ - `ptyHostBackends(home, { target, rowsOn, rowInstances })`:+ - the create backend is the target's;+ - there is one drain backend per discovered instance other than the target, with a supported protocol;+ - there is also one per `rowInstances()` instance with no discovery file, so its rows go gone as today.+ - `rowInstances: () => string[]` returns the `ptyhost:` instances named by registry rows.+ - `PtyHostDrain.step()` skips `shutdownHost` for a backend whose `mayShutDown` is false. Its panes stay reachable.+- Main: the target is computed when the core starts (`targetHost()`), and logged as+ `[terminal] ptyhost: target <instance>` or `[terminal] ptyhost: target unknown`.++- [ ] **Step 1: Write the failing tests.**+ - `drain.spec.ts`:+ - `an older version's host of the same protocol drains`.+ - `a legacy p2 host drains`.+ - `a newer host drains and shuts down under an installed target` (a rollback).+ - `a newer host is reached but never shut down under a binary target`.+ - `rows on an instance with no discovery get a drain backend`.+ - `an empty older host is shut down after EMPTY_PASSES and its folder removed`.+ - `a newer host's folder is never removed`.+ - `ptyHostBackend.spec.ts`:+ - `the create backend never makes a pane on a non-target host`.+ - `a drain backend refuses create`, which is today's behaviour, now by instance.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/ptyHost src/lib/ptyHostBackend.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement.** In `main.ts`, pass `target` and `rowInstances`. Everything else around+ `prepareTerminalBackends` is unchanged.+- [ ] **Step 4: Run.**+ - Unit: the same command.+ - Real: `cd pty && cargo +stable build`, then+ `cd cli && HARNESS_PTY_BIN=$(pwd)/../pty/target/debug/harness-pty npx vitest run src/lib/ptyHost/drain.spec.ts src/lib/ptyHostBackend.restart.spec.ts`.+ The drain spec's `HARNESS_PTY_BIN_PREV` case now means "the previous version", built as in G5.1.+ - Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): new panes go to the installed pty host build; others drain`.++### Task G2.3: Uninstall ends every instance++**Files:** `cli/src/lib/uninstall/ptyHosts.ts`, `ptyHosts.spec.ts`.++**Interfaces:**+- Consumes: G2.1's `listDiscoveries`, `reachPtyHost(home, instance)` and `discoveredHostDead`.+- Produces: `PtyHostEnd` keyed by `instance`; `deps.reach(instance)`; `written` keyed by instance.++- [ ] **Step 1: Write the failing test.** `ends a legacy and two versioned hosts of one protocol in one home`: three+ fake discoveries; each is reached and ended once.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/uninstall/ptyHosts.spec.ts`. Expected: FAIL. Two hosts of one+ protocol collide.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command. Expected: PASS.+- [ ] **Step 5: Commit** `fix(cli): uninstall ends every pty host instance`.++---++## Phase G3: Delivery (spec §5)++### Task G3.1: Check, download, verify, unpack, canary++**Files:** Create `cli/src/lib/windows/ptyPayload.ts`, `ptyPayload.spec.ts`. Tested on every OS; nothing in it calls a+Windows API.++**Interfaces:**+- Consumes: `fetchManifest`, `downloadVerified`, `shouldAutoUpdate`, `isLocalDevBuild`, `DigestMismatchError` and the+ limits from `selfUpdate.ts`; `binaryVersion` from G2.1; `currentPtyVersion` from `launch.ts`.+- Produces:+ - `ptyManifestUrl(cliManifestUrl: string): string`. It throws when the URL does not end in `cli/metadata.json`.+ - `ptyPlatformKey(arch: string = process.arch): 'win32-x64' | 'win32-arm64' | null`.+ - `PTY_PAYLOAD_FILES: readonly string[]`.+ - `interface PtyEntry { version: string; url: string; sha256: string; size: number }`.+ - `fetchPtyEntry(url: string, key: string, limits?): Promise<PtyEntry | null>`.+ - `ptyUpdateWanted(entry: PtyEntry, installed: { pty: string | null; cli: string }, rejected: readonly string[]):+ boolean`. It is false for a dev CLI, a version not newer than `pty`, or a rejected one. A missing `pty` counts as+ older than anything.+ - `interface PreparedPty { version: string; staging: string; protocol: number; features: string[] }`.+ - `preparePtyPayload(entry: PtyEntry, runtimeDir: string, deps?: { download; unzip; probe }):+ Promise<PreparedPty>`. Steps:+ 1. download and verify;+ 2. unzip into `<runtimeDir>/pty/.staging-<pid>-<ms>`;+ 3. require exactly the six files;+ 4. run the canary of the Global Constraints.++ Any failure removes the staging folder and throws `PtyPayloadRefused` with a reason. A digest mismatch is wrapped+ too.+ - `unzip` on Windows is `tar.exe -xf` (the bsdtar Windows ships), as `install.ps1`'s `Expand-HarnessZip` falls back+ to; elsewhere `unzip -q`, for tests.++- [ ] **Step 1: Write the failing tests.** Use a zip built in the test from fake files, a fake `download`, and a+ fake `probe` that returns the version lines.+ - `ptyManifestUrl swaps the last two segments`, and `throws on any other url`.+ - `ptyPlatformKey maps x64 and arm64, and nothing else`.+ - `ptyUpdateWanted`: `newer is wanted`; `same and older are not`; `a dev CLI never updates`;+ `a rejected version is not`; `no installed pty wants any`.+ - `preparePtyPayload`:+ - `a good zip is unpacked into a staging folder`;+ - `a digest mismatch is refused and leaves nothing`;+ - `a missing or extra file is refused`;+ - `a host that names another version is refused`;+ - `an unsupported protocol is refused`;+ - `a serial binary that names another version is refused`;+ - `a canary that hangs past 5 s is refused`.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/windows/ptyPayload.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command. Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): fetch, verify and canary a promoted pty payload`.++### Task G3.2: Install under the lock, undo, and roll back++**Files:** Create `cli/src/lib/windows/ptyInstall.ts`, `ptyInstall.spec.ts`, `ptyInstall.windows.real.spec.ts`.++**Interfaces:**+- Consumes: G3.1's `PreparedPty`; `writePointer`, `readPointer` and `harnessLaunchPath` from `installLayout.ts`.+- Produces:+ - `installPreparedPty(prepared: PreparedPty, rootDir: string, fs?: PtyInstallFs): void`. The caller holds the+ spawn lock. In order:+ 1. rename the staging folder to `<runtime>/pty/<version>/`. If that folder exists, compare its six files byte for+ byte with the staging folder's. Equal: delete the staging folder and use it. Different: throw+ `PtyPayloadRefused`;+ 2. for `harness.exe`, then `harness-launch.exe`, in `<root>\bin\`: rename the old one aside, copy the new one in+ through a temporary name and a rename, so the path never stands empty;+ 3. write `pty-pending.json` `{ version, previous }`;+ 4. `writePointer(<runtime>/pty, 'current-pty', version)`.++ A failure at any step undoes the ones before it: the aside files go back, `pty-pending.json` is removed, and the+ pointer is left as it was. Then it throws.+ - `restorePty(rootDir: string): boolean`. With a `pty-pending.json`:+ - point `current-pty` back at `previous`;+ - copy `previous`'s `harness.exe` and `harness-launch.exe` back into `bin\`, the same rename-aside way;+ - add `version` to `pty-rejected.json` and remove the marker.++ It returns whether it restored anything. The version folder stays (spec §3).+ - `confirmPty(rootDir: string): void`. It removes `pty-pending.json`.+ - `rejectedPtyVersions(rootDir: string): string[]`.+ - `sweepAsideFiles(rootDir: string): number`. It deletes `bin\*.old-*` files it can, and returns how many are left.++- [ ] **Step 1: Write the failing tests.**+ - `ptyInstall.spec.ts`, with a temp root and an injectable `fs` for the failure cases:+ - `installs: folder, bin files, marker, pointer`;+ - `a failure at each step leaves the bin files, the marker and the pointer as they were`, one case per step;+ - `an existing version folder is reused only when it matches`, and `refused when it differs`;+ - `restorePty puts the pointer and the bin files back, rejects the version, and keeps the folder`;+ - `restorePty with no marker changes nothing`;+ - `confirmPty removes the marker`;+ - `sweepAsideFiles deletes what it can`.+ - `ptyInstall.windows.real.spec.ts`, run only on win32:+ - `bin files are replaced while copies of them run, and a reader never finds the path missing`:+ 1. start a copy of `bin\harness.exe` that waits;+ 2. poll the path every millisecond on another worker during the install;+ 3. check the poll never saw it missing;+ 4. check the new bytes are in place;+ 5. check `sweepAsideFiles` deletes the aside file once the copy exits.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/windows/ptyInstall.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command. Expected: PASS. The real spec runs on Windows CI in G5.1.+- [ ] **Step 5: Commit** `feat(cli): install a pty payload beside the old one, undoably, and roll it back`.++### Task G3.3: The poller, one handover, probation++**Files:**+- Create: `cli/src/lib/windows/ptyUpdate.ts`, `ptyUpdate.spec.ts`.+- Modify:+ - `cli/src/services/updaterProcess.ts`;+ - `cli/src/harnessd/protocol.ts` (`UpdaterMessage` and its guard);+ - `cli/src/harnessd/supervisor.ts` (`updateStaged`);+ - the master's `restoreUpdate` and confirm wiring (`grep -n 'restoreUpdate\|confirm(' cli/src/harnessd`);+ - `cli/src/lib/selfUpdate.ts` (`startSelfUpdater` gains `beforeStage`).+- Tests: `ptyUpdate.spec.ts`, `updaterProcess.spec.ts`, `protocol.spec.ts` (harnessd), `supervisor.spec.ts`,+ `selfUpdate.spec.ts`.++**Interfaces:**+- Consumes: G3.1, G3.2; `withSpawnLock`, `SpawnLockBusyError`.+- Produces:+ - `startPtyUpdater(opts: { url: string; key: string; rootDir: string; intervalMs: number; slotSecond?: number;+ installedCli: () => string; withLock; onStaged: (ptyVersion: string) => void | Promise<void>; deps? }): Poller &+ { readyToStage(): Promise<string | null> }`.+ - It has the CLI poller's shape: scheduled ticks, a download outside the lock, `refuse` back-off, and a re-check+ under the lock that `current-pty` is still older (another installer may have moved it).+ - On its own it installs under the lock and calls `onStaged(version)`.+ - `readyToStage()`, under a lock the caller already holds, installs a payload already prepared and returns its+ version, or returns null. That is how the CLI poller takes the PTY first in one handover.+ - `startSelfUpdater` gains `beforeStage?: () => Promise<string | null>`, called under the lock right before `stage`.+ `onStaged` gains a second argument `ptyVersion: string | null`.+ - `UpdaterMessage` becomes `{ type: 'harnessd:staged'; version?: string; ptyVersion?: string }`. The guard+ accepts any message with at least one non-empty string.+ - `Supervisor.updateStaged(staged: { version?: string; ptyVersion?: string })`. The same hand-over and probation;+ the log line names both.+ - The master's restore runs `selfUpdate.restore` only when a CLI build is pending, and `restorePty` whenever+ `pty-pending.json` exists. Its keep runs `confirm` and `confirmPty`.+ - `updaterProcess.ts`, on win32 only: `sweepAsideFiles` at start, and the PTY poller beside `startCli` and+ `startHn`. A staging of either exits with `SERVICE_EXIT_RESTART`, as today. The next run checks both again.+ - Log lines, in the CLI's words (`[update]`), each said once per version:+ - `[update] newer terminal host available: <a> → <b>`;+ - `[update] staged terminal host <b> — handing over`;+ - `[update] terminal host <b> <reason> — not trying it again for <wait>`.++ The master logs a rollback as `[harnessd] terminal host <b> did not come back healthy — back to <a>`. Nothing+ reaches any client.++- [ ] **Step 1: Write the failing tests.**+ - `ptyUpdate.spec.ts`:+ - `a newer entry is installed under the lock and onStaged gets its version`;+ - `a pointer that moved past it while downloading stages nothing`;+ - `a refused payload backs off`;+ - `a busy lock retries the install next tick without downloading again`;+ - `readyToStage installs a prepared payload, and returns null when there is none`.+ - `selfUpdate.spec.ts`: `beforeStage runs under the lock before stage, and its version reaches onStaged`.+ - `updaterProcess.spec.ts`:+ - `a PTY-only staging tells the master ptyVersion alone, and the next run checks the CLI`;+ - `CLI and PTY in one check send one message with both`.+ - harnessd `protocol.spec.ts`: the guard accepts `{ptyVersion}`, `{version}` and both; it refuses neither.+ - `supervisor.spec.ts`:+ - `a PTY-only staging hands over and goes on probation`;+ - `a failed probation with only a PTY pending restores the PTY and not the CLI`;+ - `a kept probation confirms both`.+- [ ] **Step 2: Run.**+ - Run: `cd cli && npx vitest run src/lib/windows/ptyUpdate.spec.ts src/lib/selfUpdate.spec.ts src/services/updaterProcess.spec.ts src/harnessd`.+ - Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command and `npx tsc --noEmit -p .`. Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): the Windows updater installs promoted pty payloads, on the master's probation`.++### Task G3.4: The protocol rule, and `harness update`++**Files:**+- Modify: `cli/src/cli.ts` (`version --json`; the `update` command), `cli/src/lib/selfUpdate.ts` (`runCanary`,+ `startSelfUpdater`).+- Modify: `cli/src/lib/ptyHost/protocol.spec.ts`, `docs/superpowers/specs/2026-10-16-windows-native-cli-design.md`+ (self-update item 6).+- Tests: `selfUpdate.spec.ts`, `cliCommand.spec.ts` (or the spec that covers `version`), an update-command spec+ (`grep -ln "Already on the latest" cli/src`).++**Interfaces:**+- Produces:+ - `harness version --json` prints `{"version":VERSION,"ptyProtocol":PTY_PROTOCOL}`. `harness version` is unchanged.+ - `CanaryResult` gains `ptyProtocol: number`. The canary runs `cli.js version --json` and reads plain output as+ protocol 2.+ - `startSelfUpdater` gains `installedPtyProtocol?: () => number | null` (win32: `binaryVersion` of the+ `current-pty` host). A canaried build whose `ptyProtocol` is above it is not staged, and the updater logs once+ per version: `[update] <v> needs pty protocol <n>; this machine's host speaks <m> — waiting for its payload`.+ The bytes stay verified for the next tick.+ - `harness update` on win32:+ - also installs a newer promoted payload (G3.1, G3.2) under its lock, before the CLI;+ - with the CLI current and only the PTY newer, it installs the PTY and restarts the daemon instead of+ "Already on the latest version";+ - it ignores `pty-rejected.json`, as it ignores the CLI's rejected versions.++- [ ] **Step 1: Write the failing tests.**+ - `version --json prints the version and the pty protocol`.+ - `selfUpdate.spec.ts`:+ - `a build needing a newer pty protocol waits, then stages once the host has it`;+ - `plain version output counts as protocol 2`.+ - The update-command spec:+ - `harness update installs a newer pty payload when the CLI is current`;+ - `harness update installs a rejected pty version anyway`.+ - `protocol.spec.ts`: replace "keeps the protocol that installed Windows hosts speak" with+ `a CLI needing a protocol above the installed host's waits (the delivery rule replaces the pin)`, a pointer test+ to the `selfUpdate.spec.ts` case above that asserts `PTY_PROTOCOL` is in `SUPPORTED_PTY_PROTOCOLS`.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/selfUpdate.spec.ts src/lib/ptyHost/protocol.spec.ts` and+ the update and version specs. Expected: FAIL.+- [ ] **Step 3: Implement.** Update item 6 of the B spec: the payload now updates with the CLI (G), and a protocol+ bump is safe under the delivery rule.+- [ ] **Step 4: Run.** The same commands and `npx tsc --noEmit -p .`. Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): a CLI waits for the pty protocol it needs, and harness update installs the payload`.++### Task G3.5: `install.ps1` restarts when only the PTY moved++**Files:** `cli/scripts/install.ps1` (`Restart-HarnessDaemon` and its caller), `cli/src/scripts/installPs1.spec.ts`.++**Interfaces:**+- `Restart-HarnessDaemon` gains `-PtyBefore` and `-PtyAfter`. It restarts when the CLI version or the+ `current-pty` version changed. Its line reads `Moving the running Harness to terminal host <PtyAfter> (your agents+ keep running)...` when only the PTY changed.+- **Ruling against spec §5 "Other installers":** `install.ps1` does not take the daemon spawn lock. The lock's+ liveness proof (`processLiveness.ts`) is Node-only. The race is covered by both sides instead:+ - `install.ps1` already unpacks into its own staging folder and moves the pointer atomically;+ - the updater re-reads `current-pty` under its lock before it installs (G3.3);+ - an existing version folder is reused only when it matches (G3.2).++ The cost if wrong: an `install.ps1` run and an updater install in the same second could both restart the daemon.+- `install.ps1` does not read `pty-rejected.json`: an explicit install installs.++- [ ] **Step 1: Write the failing test** in `installPs1.spec.ts`, in the existing restart cases' style:+ `a PTY-only change restarts the daemon`, and `no change in either does not`.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/scripts/installPs1.spec.ts`. Expected: FAIL. On macOS the+ PowerShell cases run under `pwsh` when it is present, as today.+- [ ] **Step 3: Implement.** The script stays pure ASCII.+- [ ] **Step 4: Run.** The same command. Expected: PASS. Windows CI runs it in G5.1.+- [ ] **Step 5: Commit** `fix(windows): install.ps1 restarts the daemon when only the terminal host changed`.++---++## Phase G4: Moving agents unnoticed++### Task G4.1: Who is looking++**Files:**+- Modify: `desktop/lib/state/app_state.dart` (the `app_focus` send), `desktop/lib/super_tabs/workspace.dart`.+- Modify: `cli/src/localWsServer.ts` (the `app_focus` handler), `cli/src/backendSocket.ts` (`setLocalTerminalFocus`),+ `cli/src/lib/terminalStreamManager.ts`, `cli/src/core/terminalWatch.ts`.+- Tests: `desktop/test/app_focus_visible_agents_test.dart` (new), `cli/src/lib/terminalStreamManager.spec.ts`,+ `cli/src/localWsServer.spec.ts`.++**Interfaces:**+- Produces (wire): the `app_focus` payload gains `visibleAgents?: string[]`.+ - It holds the ids of every agent whose tile is on screen in that window.+ - It is `[]` while the window is minimized or hidden to the tray.+ - The desktop sends it whenever the set changes: tab switch, layout change, minimize, restore, hide or show.+- Produces (TS):+ - `TerminalStreamManager.setVisibleAgents(connId: string, agentIds: readonly string[] | null): void`, where null+ means the window has never sent the list.+ - `TerminalStreamManager.isLookedAt(agentId: string): boolean`. A stream opened with `watch: true` (`watchOnly`)+ never counts. Otherwise it is true when any non-closing stream for the agent is:+ - from a loopback connection whose visible list is null;+ - from a loopback connection whose visible list contains the agent;+ - from any non-loopback connection, the phone pager's `takeover: false` neighbours included.+ - `TerminalWatch.isWatched(agentId: string): boolean`, for Share viewers.+ - `BackendSocket.setLocalTerminalFocus(connId, agentId, visibleAgents?)`.+- Consumes: the existing `app_focus` handling and `setFocusedAgent`. Those stay as they are.++- [ ] **Step 1: Write the failing tests.**+ - TS:+ - `a loopback stream whose window lists other agents is not looked at`.+ - `a loopback stream whose window never sent a list is looked at`.+ - `a mobile or web stream is looked at, a takeover:false one included`.+ - `a watch:true stream is never looked at`.+ - `a minimized window's empty list frees its agents`.+ - `closing the connection forgets its list`.+ - In `localWsServer`: `app_focus with visibleAgents reaches setLocalTerminalFocus`.+ - Desktop:+ - `app_focus carries the on-screen tiles`: two super tabs, only the active tab's tiles are listed.+ - `minimizing sends an empty list`.+- [ ] **Step 2: Run.**+ - Run: `cd cli && npx vitest run src/lib/terminalStreamManager.spec.ts src/localWsServer.spec.ts`, and+ `cd desktop && flutter test test/app_focus_visible_agents_test.dart`.+ - Expected: FAIL.+- [ ] **Step 3: Implement.** The desktop derives the list from the active super tab's mounted, non-`Offstage` tiles+ and the window's visibility state.+- [ ] **Step 4: Run.** The same commands. Expected: PASS.+- [ ] **Step 5: Commit** `feat: the desktop tells its daemon which terminals are on screen`.++### Task G4.2: Quiet clocks++**Files:** `cli/src/lib/hostMove/quiet.ts` (new), `quiet.spec.ts`. Wire it in G4.6.++**Interfaces:**+- Produces `class QuietClock`, constructed with `{ now: () => number }`:+ - `noteInput(agentId: string): void`.+ - `noteActivity(agentId: string, state: ActivityState): void`. It records `idleSince` the first time it sees `idle`+ after anything else, and clears it on `working` or `unknown`.+ - `quietFor(agentId: string): number`. It is `now - max(idleSince, lastInput)`, or 0 when not idle.+ - `forget(agentId: string): void`.+- Fed from:+ - the core's `onInput` (`grep -n 'onInput' cli/src/core/main.ts`);+ - the `SessionInputController` submit paths (a `harness send` is input);+ - the mover's own tick, which reads `turnActivity.snapshot(sessionId)`.++- [ ] **Step 1: Write the failing tests.**+ - `idle without input for QUIET_MS is quiet`.+ - `input resets quiet`.+ - `working or unknown is never quiet`.+ - `idle seen again after working restarts the clock`.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/hostMove/quiet.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command. Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): track how long an agent has been idle and untouched`.++### Task G4.3: Seeded create, and a seed from a capture++**Files:** `cli/src/lib/terminalTypes.ts`, `cli/src/lib/ptyHostBackend.ts` (`create`), `cli/src/lib/hostMove/seed.ts`+(new). Tests: `seed.spec.ts`, `ptyHostBackend.spec.ts`.++**Interfaces:**+- Produces:+ - `TerminalCreateRequest.seed?: string`. Only the ptyhost backend uses it; tmux ignores it.+ - `PtyHostBackend.create` sends `seed` when `client.features` includes `SEED_FEATURE`. It refuses with+ `not_started` ("this host cannot seed a pane") when a seed is given to a host without it.+ - `PtyHostBackend.canSeed: boolean`, from the connected host's features.+ - `seedFromCapture(text: string, maxBytes = SEED_MAX_BYTES): string`. It normalises line ends to `\r\n` and drops+ whole lines from the top until it fits.+- Consumes: the coordinator's `capture(session, { historyLines: SEED_HISTORY_LINES, ansi: true })` on the old pane.++- [ ] **Step 1: Write the failing tests.**+ - `seed.spec.ts`:+ - `keeps every line under the cap`.+ - `drops the oldest lines first`.+ - `uses CRLF`.+ - `ptyHostBackend.spec.ts`:+ - `create passes the seed to a host with the seed feature`.+ - `create refuses a seed for a host without it`.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/hostMove/seed.spec.ts src/lib/ptyHostBackend.spec.ts`. Expected:+ FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command. Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): open a pty pane seeded with another pane's scrollback`.++### Task G4.4: The move gate, and streams that follow++**Files:**+- Create: `cli/src/lib/hostMove/gate.ts`.+- Modify: `cli/src/lib/terminalStreamManager.ts` (the input frame path that ends in `tookInput`; stream open; stream+ retarget), `cli/src/lib/sessionInput.ts` (`SessionInputController` submit paths).+- Tests: `gate.spec.ts`, `terminalStreamManager.spec.ts`, `sessionInput.spec.ts`.++**Interfaces:**+- Produces `class MoveGate`:+ - `hold(agentId: string): void`.+ - `holding(agentId: string): boolean`.+ - `enqueue(agentId: string, deliver: () => Promise<void>): void`. It queues in arrival order.+ - `whenOpen(agentId: string): Promise<void>`. It resolves at release.+ - `release(agentId: string): Promise<void>`. It runs the queue in order, after the row's runtime has switched (or+ fallen back), so each `deliver` reaches the row's current pane.+- Produces `TerminalStreamManager.retarget(agentId: string, to: TerminalRuntimeRef): Promise<void>`.+ - Every open stream of the agent, of any kind, is re-subscribed on `to` on the daemon's side. The client's+ connection and stream id stay.+ - What the client receives next uses the existing frames: the new pane's output, and the stream's existing resync+ path if the frame sequence needs one.+ - No new frame type, and no close.+- Behaviour:+ - While the gate holds an agent, a stream input frame for it becomes an `enqueue` of a raw write to the row's+ runtime. That uses the backend's raw input op: ptyhost `write`, adding `TerminalBackend.writeInput?(runtime,+ bytes)` if no such method exists.+ - A `SessionInputController` submission is enqueued as itself.+ - A stream open waits `whenOpen`, then opens on the row's current runtime.+ - A held agent counts as looked at from the moment input or an open arrives. The mover reads that through+ `isLookedAt` on its next tick; it does not cancel a swap already past the stop of the old engine.++- [ ] **Step 1: Write the failing tests.**+ - `input during a hold is delivered once, in order, after release`.+ - `a harness send during a hold is delivered after release`.+ - `a stream opened during a hold opens on the new runtime`.+ - `an open stream follows a retarget with no close, and gets the new pane's output`.+ - `nothing is held for other agents`.+- [ ] **Step 2: Run.**+ - Run: `cd cli && npx vitest run src/lib/hostMove/gate.spec.ts src/lib/terminalStreamManager.spec.ts src/lib/sessionInput.spec.ts`.+ - Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command. Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): hold an agent's input while it changes host, and move its open streams`.++### Task G4.5: One move++**Files:** `cli/src/lib/hostMove/moveAgent.ts` (new), `moveAgent.spec.ts`. Dependency-injected like `restartAgent.ts`.++**Interfaces:**+- Produces:+ - `type MoveOutcome = { moved: true; resumed: boolean } | { moved: false; reason: string; fellBack: boolean }`.+ - `moveAgent(session: RegisteredSession, deps: MoveAgentDeps): Promise<MoveOutcome>`.+ - `MOVE_MARKER_ENV = 'HARNESS_MOVE_OF'`.+ - `removeOrphanMovePanes(backends: TerminalBackend[], rows: RegisteredSession[]): Promise<number>`, run once at+ core start, before discovery.+- `MoveAgentDeps`:+ - `capture(session): Promise<string | null>`;+ - `createSeeded(session, seed: string): Promise<{ ok: true; runtime } | { ok: false; reason }>`. It calls the create+ backend's `create` with `seed`, `hold: true`, the waiting-shell argv restore uses (`waitingLaunch` in+ `core/main.ts`), the row's cwd, and `HARNESS_MOVE_OF=<agentId>`;+ - `respawn(runtime, launch: RestoreLaunch): Promise<{ ok: boolean; reason?: string }>`. It is the backend's+ `respawn` with the launch's argv, cwd and env, as `restoreTerminals.ts` does, and keeps the pane's scrollback;+ - `buildLaunch: RestoreAgentsDeps['buildLaunch']`, from `core/agents/restoreLaunch.ts` `createRestoreLaunch`,+ shared and not copied;+ - `stopEngine(session): Promise<TerminateOutcome>`; the old pane is kept, as `paneSwapDeps` `terminate` does+ (`core/agents/swap.ts`);+ - `probeProcess(runtime, engine): Promise<ProcessIdentity | null>`, polled until `MOVE_TIMEOUT_MS`;+ - `swap(agentId, runtime, identity): void`. In one `registry.transaction` it calls+ `updateRuntimes(agentId, [runtime], terminalRouteKey(runtime))` and `updateProcessIdentity`, then announces the+ session as a restart does;+ - `retarget(agentId, runtime)`: G4.4's;+ - `killPane(runtime)`;+ - `relaunchOld(session): Promise<boolean>`; `restartAgent` in the old pane, with resume;+ - `gate: MoveGate`;+ - `holdRoute` and `releaseRoute`, for both routes for the whole move;+ - `current(): boolean`;+ - `log(message)`.+- Order (spec §4). Two engines never hold one conversation at once:+ 1. capture;+ 2. buildLaunch;+ 3. createSeeded (the new pane waits, with no engine);+ 4. `gate.hold`;+ 5. stopEngine (old);+ 6. respawn (new) with the launch;+ 7. probe (new);+ 8. swap, then retarget;+ 9. killPane (old);+ 10. `gate.release`.++ A failure at 1–3 changes nothing, apart from killing a pane step 3 made. From step 4 on, a failure kills the new+ pane, runs `relaunchOld` if step 5 ran, and then releases the gate.++- [ ] **Step 1: Write the failing tests.**+ - `moves an idle conversation agent and keeps its id`.+ - `capture_failure_changes_nothing`.+ - `a refused create changes nothing`.+ - `a new engine that never appears falls back to the old pane`.+ - `open streams are retargeted after the swap, never before`.+ - `the gate is released on every path`.+ - `a_move_pane_left_by_a_dead_daemon_is_removed_before_discovery`.+ - `a cancelled move (current() false) before step 5 changes nothing`.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/hostMove/moveAgent.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run.** The same command. Expected: PASS.+- [ ] **Step 5: Commit** `feat(cli): move one agent to another pty host, falling back to its old pane`.++### Task G4.6: The mover, and the wiring++**Files:**+- Create: `cli/src/lib/hostMove/mover.ts`.+- Modify `cli/src/core/main.ts`:+ - after `ptyDrain.step()` in `onReconciled`;+ - the `onInput`;+ - before restore and discovery at start, for `removeOrphanMovePanes`.+- Tests: `mover.spec.ts`.++**Interfaces:**+- Produces `class HostMover`, built with+ `{ list, isDrainRow(row), targetCanSeed(), resumesConversation, activity(row), quiet: QuietClock, lookedAt(agentId),+ busy(agentId), move(row), now, log }`:+ - `step(): Promise<void>`. It does nothing while `targetCanSeed()` is false. At most one move is in flight. It picks+ the oldest-quiet candidate that meets every condition in spec §4.+ - Each row has at most one failed move per core start (`failed: Set<string>`).+- Wiring:+ - `busy` is `restartJobs.busy(id) || stopJobs.has(id) || restorePanes.busy(id) || pinnedControls.has(id)`.+ - `move` runs inside `restartJobs.run(agentId, …, 'move')`.+ - `lookedAt` is `terminalStreams.isLookedAt(id) || terminalWatch.isWatched(id)`.+ - `isDrainRow` is true when the row's runtime instance is a drain backend's: older hosts, and a newer one after a+ downgrade or rollback.+ - `targetCanSeed` is the create backend's `canSeed`.+- Logs: `[terminal] move <agentId>: moved (resumed|fresh)`, `skipped (<reason>)` and `failed (<reason>)`. The skipped+ line is logged once per reason change, not every tick. One line, once per core start, when the target cannot seed:+ `[terminal] ptyhost: target <instance> cannot seed; agents stay on their hosts`.++- [ ] **Step 1: Write the failing tests.** One per condition:+ - `a working agent is not moved`.+ - `unknown activity is not moved`.+ - `input within QUIET_MS blocks`.+ - `a looked-at agent is not moved`.+ - `a terminal is never moved`.+ - `a fresh engine is never moved`.+ - `no session id is never moved`.+ - `a busy agent is not moved`.+ - `one at a time`.+ - `a failed agent is not retried until restart`.+ - `an agent on the target host is never a candidate`.+ - `nothing moves while the target cannot seed`.+ - `an agent on a newer host moves after a rollback`.+- [ ] **Step 2: Run.** `cd cli && npx vitest run src/lib/hostMove/mover.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement, and wire it in `main.ts`.**+- [ ] **Step 4: Run.**+ - Run: `cd cli && npx vitest run src/lib/hostMove src/lib/ptyHost src/lib/windows src/lib/terminalStreamManager.spec.ts src/lib/sessionInput.spec.ts && npx tsc --noEmit -p .`.+ - Run the coverage gates the change touches (AGENTS.md): `npm run test:core`, `npm run test:resume`,+ `npm run test:harnessd`.+ - Expected: PASS. A red test in a suite with known base failures is compared by name against a clean worktree of+ `main`. The documented base failures are 3 `searchProcess` tests in `test:core` and 2 `sessionRepair` tests in+ `test:resume`.+- [ ] **Step 5: Commit** `feat(cli): move idle, unwatched agents to the installed pty host`.++---++## Phase G5: Proof++### Task G5.1: Two real builds on Windows CI++**Files:** `cli/src/lib/hostMove/hostMove.real.spec.ts` (new), `.github/workflows/windows.yml`.++**Interfaces:**+- Consumes everything above.+- `HARNESS_PTY_BIN` is the new build. The old build is the same source built with `HARNESS_PTY_VERSION=0.0.1`: a+ number, because it names its version folder under `<runtime>/pty/` as an install's does (`VERSION_DIR`). The TS+ specs read it as `HARNESS_PTY_BIN_PREV` (the drain spec's name), the Rust `two_versions_serve_side_by_side` as+ `HARNESS_PTY_BIN_OLD`. Build the old one first, copy it aside, then build the new one: the env change recompiles+ only the crate.++- [ ] **Step 1: Write the real spec**, run only when both env vars are set. Use a temp home and a stand-in engine+ that resumes: a script that prints its argv and waits for input. Cases:+ - `a pane on the old host keeps streaming and taking input while a new pane opens on the new host`;+ - `a moved pane's history holds the old pane's lines`;+ - `the old host shuts down after its last pane goes, and its version folder is removed`;+ - `input sent during the swap arrives in the new pane`.+- [ ] **Step 2: Run locally first** (the fast loop; Windows CI is the proof).+ - Run: `cd pty && HARNESS_PTY_VERSION=0.0.1 cargo +stable build && cp target/debug/harness-pty <scratch>/harness-pty-old && cargo +stable build`.+ - Then: `cd cli && HARNESS_PTY_BIN=$(pwd)/../pty/target/debug/harness-pty HARNESS_PTY_BIN_PREV=<the copy> npx vitest run src/lib/hostMove/hostMove.real.spec.ts src/lib/ptyHost/drain.spec.ts`.+ - Expected: PASS.+- [ ] **Step 3: Windows CI.**+ - In `windows.yml`'s `windows-pty` job, after the Rust tests:+ - add the old build to the same target, run `two_versions_serve_side_by_side` with it (`HARNESS_PTY_BIN_OLD`),+ and run the real spec with both binaries;+ - run `src/lib/windows/ptyInstall.windows.real.spec.ts` and `src/scripts/installPs1.spec.ts`.+ - `windows.yml` runs on demand: push the branch once, then `gh workflow run windows.yml --ref feat/windows-pty-rollover`+ with `release=false`. Watch it on x64 and arm64: `gh run watch <run> --exit-status`.+ - Expected: both pass, and the vitest output names the real cases (not skipped).+- [ ] **Step 4: Commit** `test(windows): pty host rollover and payload install against real builds`, and record the+ run link in the ledger.++### Task G5.2: The VM and the x64 PC, the way a person updates; status++**Files:** `docs/testing/pty-rollover-e2e.md` (new), the spec's status line and Known limits.++- [ ] **Step 1: Delivery, on the ARM64 VM and on the x64 test PC,** with the owner's OK and only when each is free.+ Use a throwaway standard user on the VM; on the PC, touch only what G installs.+ 1. Build N and N+1 of the branch: CLI and PTY payload, non-dev versions (`0.4.<n>-e2e.1`).+ 2. Serve N from the fake HTTPS CDN (`fake-cdn.sh` + `vm-cdn.ps1`, as B5.13 did) and install it with `install.ps1`.+ 3. Serve a PTY manifest naming N+1. Check that within one update check, with no `install.ps1`:+ - `current-pty` names N+1;+ - `bin\harness.exe` and `bin\harness-launch.exe` are N+1's;+ - the daemon log shows the handover.+ 4. On the x64 PC: the dial on COM3 is found through N+1's `harness-serial.exe`.+ 5. Serve an N+2 payload with a wrong digest: it is refused, and nothing changes.+ 6. Serve a CLI N+2 that needs protocol 3 (a test build with `PTY_PROTOCOL` raised): it waits, and the daemon log+ says so.+- [ ] **Step 2: Rollover, on the ARM64 VM.** These are the spec's Testing steps:+ 1. on N, start a claude agent, a codex agent and a terminal;+ 2. let the updater install N+1's payload;+ 3. check that a new agent opens on the new host;+ 4. keep one tile on screen, put one in another super tab, and minimize;+ 5. wait out `QUIET_MS`. Check that:+ - the off-screen agents moved, with the same ids, their scrollback and resumed conversations;+ - the on-screen one did not move;+ - the terminal was not touched;+ 6. close the terminal. Check that the old host exits and its folder is deleted;+ 7. repeat steps 2–3 once with an `install.ps1` update instead of the updater.+- [ ] **Step 3: Record** each item as passed, failed, or not run with the reason, in+ `docs/testing/pty-rollover-e2e.md`. Leave no addresses, account names or ids in it.+- [ ] **Step 4: Clean up** the throwaway user, the fake CDN settings and everything G installed, on both machines.+- [ ] **Step 5: Update the spec:** `Status: implemented on feat/windows-pty-rollover; E2E in+ docs/testing/pty-rollover-e2e.md`, and one Known limits line for each limit found and not fixed.+- [ ] **Step 6: Commit** `docs: PTY host rollover and delivery E2E and status`.diff --git a/docs/superpowers/specs/2026-10-16-windows-native-cli-design.md b/docs/superpowers/specs/2026-10-16-windows-native-cli-design.mdindex 577ee17d1..52c074d99 100644--- a/docs/superpowers/specs/2026-10-16-windows-native-cli-design.md+++ b/docs/superpowers/specs/2026-10-16-windows-native-cli-design.md@@ -230,7 +230,7 @@ process names stay `node` (`processName.ts` already does that).### Self-update and rollback1. The updater downloads the CLI into `cli\<version>\`, verifies it, and canaries it- (`node cli.js version` in a temp folder).+ (`node cli.js version --json` in a temp folder, which also says the host protocol it needs).2. It writes `cli\current` and refreshes the stable `cli\notify.mjs` (temp file and rename, retried ifa running hook holds it), then says `harnessd:staged`.3. The handoff is the Mac's: the core exits 75, the master starts the new core from the new folder and@@ -239,10 +239,13 @@ process names stay `node` (`processName.ts` already does that).folders are removed once no live process runs from them, retried later when removal fails.5. A Node runtime update installs a new `runtime\node-…` folder and pointer; the next master and coreuse it; the old folder is retired when nothing runs it.-6. The terminal host payload (`runtime\pty\<version>`, `current-pty`) is not part of self-update: only- `install.ps1` writes it. Until the host is updated with the CLI (PTY host rollover, parked), a CLI release- must not raise `PTY_PROTOCOL`, and fixes to `harness-pty.exe`, `harness-launch.exe` or `harness-serial.exe`- reach a machine only when `install.ps1` runs again.+6. The terminal host payload (`runtime\pty\<version>`, `current-pty`) now updates with the CLI (sub-project G,+ [the PTY host rollover](2026-10-20-pty-host-rollover-design.md) §5). The updater installs a promoted payload+ beside the CLI's check, under the same lock and handover, and the master's probation judges both;+ `harness update` installs one too. Fixes to `harness-pty.exe`, `harness-launch.exe` or `harness-serial.exe`+ no longer wait for `install.ps1` to run again. A CLI release may raise `PTY_PROTOCOL`: the updater stages+ a build whose `version --json` names a protocol above the installed host's only together with a promoted+ payload of exactly that protocol, the host first, in one handover and one probation.The Mac's rules stay: a dev build is never replaced, updates only move forward, rejected versions areremembered. Agents survive because the pty host is independent of the daemon (A).diff --git a/docs/superpowers/specs/2026-10-20-pty-host-rollover-design.md b/docs/superpowers/specs/2026-10-20-pty-host-rollover-design.mdnew file mode 100644index 000000000..64e692740--- /dev/null+++ b/docs/superpowers/specs/2026-10-20-pty-host-rollover-design.md@@ -0,0 +1,504 @@+# PTY host updates while agents run (sub-project G)++Date: 2026-10-20, delivery added 2026-10-21+Status: implemented on feat/windows-pty-rollover; E2E in docs/testing/pty-rollover-e2e.md++## Why++On Windows every agent and terminal runs in a pane of the Harness PTY host, `harness-pty.exe`. Two things keep new+PTY code from reaching a person's machine today.++**The payload never arrives by itself.** Only `install.ps1` installs the PTY payload (the host, `harness-launch.exe`,+the `harness.exe` command, ConPTY and `harness-serial.exe`). The CLI's self-update downloads `cli.js` only. A machine+updates its CLI on every release and keeps the PTY payload it was installed with, until someone runs `install.ps1`+again. On the x64 test PC on 2026-10-21, the CLI and app were current and the PTY was a build too old to carry+`harness-serial.exe`. The dial on COM3 was never found.++**A payload that arrives never runs while its host does.** A PTY update with the same wire protocol never takes+effect while that host runs. It was measured in C5.2 on the ARM64 VM:+- `install.ps1` put PTY 0.4.19 in place and moved `current-pty` to it;+- the host still running was 0.4.18, with seven agents in it;+- the restarted daemon reconnected to that host, and new panes opened on it too.++The new host code (fixes included) runs only after every pane has gone and the host has exited. In practice that+means a reboot. Stopping the host to force the update would kill the person's agents.++A protocol bump already handles this well (`cli/src/lib/ptyHost/drain.ts`):+- the new protocol's host makes the new panes;+- the old host keeps its panes and is shut down once it has none;+- then its version folder is deleted.++G closes both gaps:+- the self-update installs a newly promoted PTY payload, as it installs a new CLI (§5);+- the new host takes the new panes, the same rule a protocol bump follows, applied to every host version (§1–§3);+- running agents move onto the new host by themselves, at moments no one is using them (§4).++The person never sees any of this: no notice, no button, no choice to make.++## Goals++0. **A promoted payload reaches every machine by itself.**+ - Within one update check of the owner promoting a PTY payload to production, a running Windows install+ downloads it, verifies it and installs it beside the one in use.+ - No one runs `install.ps1` again.+1. **New panes run the new code.** After a PTY update, every new agent or terminal opens on a host of the installed+ version.+2. **Running agents are never interrupted by an update.**+ - An agent or terminal on the old host keeps running, streaming and taking input, exactly as now.+ - It stays there until it ends, or until the daemon moves it unnoticed (§4).+3. **Old hosts go away by themselves.**+ - A host of an old version is shut down once it has no pane, and its version folder is deleted, as the drain+ does today.+ - A host of an old version that has no pane when the daemon starts is shut down then, without waiting for a pane.+4. **Running agents move to the new version by themselves, unnoticed.**+ - The daemon moves an agent to the new host only while it is idle and no one is looking at it.+ - A moved agent keeps its agent id, its scrollback and its engine conversation. The next time the person opens+ it, they find the same agent and the same conversation, with the scrollback above it as before.+5. **Nothing to see.** There is no notice, dialog, badge, setting or button for any of this, on any client. The+ update is visible only in the daemon's log.++## Non-goals++- Changing how a payload is released. Every CLI release still builds a PTY payload stamped with its version and+ publishes it to staging. The owner still promotes one to production by hand (`promote-pty-payload.sh`), only when+ its PTY code is worth shipping. The machines follow the production manifest. They never follow staging, and never+ a CLI release that was not promoted.+- Moving a running process to the new host without restarting it: handing ConPTY handles and screen state from one+ host to another. ConPTY's internals are not documented, and a failure loses the person's agent. Rejected.+- tmux. Scope is Windows only, where the PTY host is the terminal backend.+- Any UI for the rollover, on any client.+- Moving terminals (plain shells): a shell has nothing to resume. A terminal stays on its host until the person+ closes it.+- Moving engines that cannot resume (`fresh` in `resumeCapability.ts`, e.g. `devin`): moving one would lose its+ conversation. It stays on its host until it ends.++## Anti-goals: a failure even if it works++- The person notices the move:+ - an agent interrupted mid-turn;+ - a screen that went blank or lost its scrollback;+ - a tile that flickered or reloaded while they watched;+ - keystrokes lost while they typed;+ - any message about it.+- An update ends a terminal, or an agent that cannot resume.+- A moved agent loses its conversation.+- A moved agent comes back with a new agent id: its tile, links and history break.+- A failed move leaves an agent worse off than if it had not been moved.+- Two hosts left running for good, one of them with no pane.+- A pane that is listed, streams, or takes input on the wrong host, or is listed twice.+- A version folder deleted while a host still runs from it.+- A half-installed payload in use: `current-pty` naming a folder that is missing a file, or holding a file that does+ not match the manifest.+- `bin\harness.exe` or `bin\harness-launch.exe` missing, even for a moment, so that a `harness` command or a pane+ launch fails during an update.+- A CLI update that leaves the machine with no host its daemon can speak to.+- An update that downgrades the PTY, or moves to a dev or staging build.++## Current state (as of `feat/windows-desktop` at `8fb220f15`; Windows merged to main as #1470, `8eb94821d`)++- **The host** (`pty/src`) has one instance per protocol, `p<PROTOCOL>` (`discovery.rs` `instance()`). That name keys+ its discovery file `<home>/run/pty-host-<protocol>.json`, its lock (`host_lock.rs`), its pane-id counter+ (`pane_ids.rs`, `pty-host-<protocol>.panes`), its Unix socket (`pty-host-<protocol>.sock`) and the+ `HARNESS_PANE=<instance>:%N` its children see. The Windows pipe name is random on each start+ (`transport/windows.rs` `pipe_name_for`, suffix `-p<protocol>`); the lock is what keeps one host per protocol per+ home. The host log `<home>/logs/pty-host.log` is per home, and only the lock holder rotates it (`logfile.rs`).+ The version is any non-empty build string (`cli.rs` `release_version`), unvalidated. The discovery+ file already carries the host's `version` (`cli.rs` `publish_and_serve`). A release stamps that version with the+ CLI's version (`HARNESS_PTY_VERSION`), so every CLI release ships a host with a new version.+- **The daemon** (`cli/src/lib/ptyHost/`):+ - `ensurePtyHost` connects to any running host of `PTY_PROTOCOL`, whatever its version, and starts one only+ when there is none.+ - `ptyHostBackends` makes one create backend (`PTY_PROTOCOL`) and one drain backend for each older supported+ protocol with a discovery file or registry rows.+ - The drain shuts an empty old host down after `EMPTY_PASSES` reconcile passes (`shutdownHost`; protocol 2 has+ the `shutdown` op; a protocol 1 host is left idle).+ - Then `removeUnusedPtyVersions` deletes the version folders older than `current-pty` that no running host+ uses. Newer folders always stay (another install's, perhaps not finished).+ - Uninstall (`uninstall/ptyHosts.ts`) and `discoverHosts` find hosts only through `pty-host-<protocol>.json`.+ - Registry rows name their host by runtime instance (`ptyhost:<instance>`, `terminalRuntime.ts`). The instance is+ an opaque string to everything above `ptyHost/`.+- **Updates on Windows.**+ - Only `install.ps1` writes `<runtime>/pty/current-pty`.+ - It reads `pty/metadata.json`, takes the `win32-x64` or `win32-arm64` entry for the machine's native+ architecture (`Get-HarnessPlatform`), and unpacks it into `<runtime>/pty/<version>/`.+ - It copies `harness.exe` and `harness-launch.exe` from there into `bin\`.+ - `install.ps1` then restarts the daemon once (`Restart-HarnessDaemon`: `harness stop`, then start).+ - The CLI's self-update (`selfUpdate.ts` `startSelfUpdater`) does not change the PTY.+ - It reads `cli/metadata.json` on a schedule, downloads and verifies `cli.js` and `notify.mjs`, and runs a canary+ (`node cli.js version`).+ - Under the daemon spawn lock it stages the build into `cli\<version>\`, moves `cli\current`, and restarts the+ daemon (`onStaged`).+ - Dev builds never update themselves (`isLocalDevBuild`).+ - `harness.exe` (`pty/src/command.rs`) and `harness-launch.exe` (`pty/src/launcher.rs`) are short-lived: each+ resolves the pointers, starts `node.exe` and exits. Either may be running at any moment a command or a pane+ starts.+ - The production manifest `pty/metadata.json` changes only when the owner promotes a payload+ (`promote-pty-payload.sh`). Its entries' `url`s point at the immutable staging objects of that release.+ - The CLI and the host meet on `PTY_PROTOCOL` (2 today). `protocol.spec.ts` pins it, because no update path+ brings a new host to an installed machine. G's delivery is that path.+- **Restarting agents.**+ - `restartAgent.ts` relaunches an agent's engine in the same pane, on the same host.+ - `restoreAgents.ts` (after a reboot) makes a new pane for a row whose pane is gone, and relaunches the engine+ there with its resume argv. It keeps the same agent id.+ - `resumeCapability.ts` says per engine whether a conversation comes back (`conversation`), a shell is relaunched+ (`shell`), or only a fresh session is possible (`fresh`).++## Design++### 1. One host instance per host build++- A host's instance name is derived from both its protocol and its version. It is unique for each (protocol,+ version) pair, and stable across restarts of the same build.+- Everything the instance keys today is keyed by the new name, so two hosts of the same protocol and different+ versions can run side by side in one home:+ - the discovery file, the lock and the pane-id counter;+ - the Unix socket, and the Windows pipe's suffix (its name is already random per start);+ - `HARNESS_PANE`'s instance;+ - the host log, so two hosts never rotate one file.+- The exact format is the builder's. The version is unvalidated, so the name must be made safe from it (a+ sanitised form or a short hash) for a file name, a Windows pipe name and a Unix socket path. The socket path must+ stay inside `sun_path` (104 bytes on macOS), which nothing guards today.+- **Hosts already running** (written by today's builds as `pty-host-<protocol>.json`, instance `p<protocol>`) are+ found and treated as instances of their own. Their panes, rows and routes keep working, and they are drained like+ any old host.++### 2. Which host gets new panes++- The daemon's **target host** is the one it would start: `PTY_PROTOCOL`, and the version of the binary+ `ptyHostBinary()` resolves. On Windows that is the folder `current-pty` names. In a dev build it is whatever+ `HARNESS_PTY_BIN` points to, read with `harness-pty version`.+- The daemon looks at every host discovery file in the home, not only those of the supported protocols.+ - The host matching the target becomes the create backend. It is started when there is none.+ - Every other running host of a supported protocol becomes a drain backend.+ - Hosts of unsupported protocols are reported as they are today.+- When the target version cannot be known (no `current-pty` and no readable binary version), the daemon behaves as+ it does today: it creates on any running host of `PTY_PROTOCOL`.+- **When this is decided:** when a core starts, as the backends are built today (`core/main.ts`). G makes every PTY+ update start a new core:+ - the self-update hands over through the harnessd master (§5);+ - `install.ps1`'s `Restart-HarnessDaemon` restarts the daemon only when the CLI version changed+ (`$Before -eq $After` returns early). G makes it restart when `current-pty` moved too.++ When that restart fails, new panes move to the new host at the next restart, and `install.ps1` already says so.+- A downgrade (an older version installed) or a §5 rollback rolls the same way: the target is whatever is+ installed.+ - The newer host is drained like any other: listed, streamed, given nothing new.+ - Its agents are moved to the target under §4.+ - It is shut down once it has no pane.+ - Its version folder is kept, as `removeUnusedPtyVersions` keeps newer folders today.++### 3. Old hosts++- The drain is unchanged: listed, streamed and controlled panes; nothing new; shutdown after `EMPTY_PASSES` empty+ passes; then `removeUnusedPtyVersions`.+- `removeUnusedPtyVersions` must never delete a folder a running host (any instance) was started from. Its rule+ otherwise stays: only folders older than `current-pty` go, and newer ones stay, after a downgrade too.+- Uninstall (`uninstall/ptyHosts.ts`) finds and ends every instance's host, legacy and versioned.+- **More than one daemon on one PTY home** (another data folder, or an older daemon whose stop failed) needs no+ coordination, under two rules:+ - a host is shut down only when it has no pane of any owner, as `drainState` already counts;+ - a daemon never deletes the folder of a host newer than its own target.+ - It drains and shuts down a newer host only when its own install has gone back below it, by a downgrade or a+ rollback. That is, `current-pty` names an older version than that host's. A daemon whose install is still the+ older one, beside a newer one, leaves the newer host alone.+- An old host that has no pane when the daemon starts is shut down on the first passes, as the drain already does.+ Nothing waits for a pane to end.++### 4. Moving running agents, unnoticed++**When an agent is moved.** The daemon moves an agent on an old host only when all of these hold:+- its engine can resume (`conversation` in `resumeCapability.ts`) and its row has a recorded session id;+- its activity is `idle` (`turnActivity.ts`). Never on `working`, and never on `unknown`;+- it has been idle, with no input sent to it, for a quiet period. Five minutes is the starting value (builder may+ tune, see below);+- no one is looking at it (below);+- no other move, restart, stop or delete is in flight for it.++**Who is looking.** An agent counts as looked at when any of these holds:+- a desktop window shows its tile on screen. The desktop already tells the daemon which agent its window focuses+ (`setLocalTerminalFocus`, `TerminalStreamManager.setFocusedAgent`). G widens that local message to carry every+ agent whose tile is on screen in that window. The list is empty while the window is minimized or hidden to the+ tray. A tile kept mounted off screen (another super tab, `Offstage`) is not looked at, even though its stream stays+ open;+- a mobile or web client, or a Share viewer (`terminalWatch.ts`), has a stream open to it. That includes the phone+ pager's streams to the agents one swipe away (`takeover: false`), which the person can reach in a moment;+- a desktop window that has not sent the list (an older desktop) has a stream open to it. That is the safe default:+ fewer moves, never a visible one.++What does not count: a `watch: true` stream held for a desktop window that has been closed+(`terminalStreamManager.ts`). Nothing shows it. Neither does a tile kept mounted off screen, as above.++**Streams across the swap.** A stream still open to the agent when it moves (an off-screen tile, a closed window's+watch, a prefetched neighbour) is moved to the new pane by the daemon. The client is not asked to reconnect. The+client sees what the resumed engine draws, as it would see any redraw. It gets no new frame type and no reload.++This is a client-to-daemon signal only. Clients still get nothing new, and nothing changes on screen.++Agents are moved one at a time. When a move starts, its conditions are checked again. Anything that breaks them+before the switch (input, a viewer subscribing, a turn starting) cancels the move, and the agent is left untouched.+An agent that never meets the conditions simply stays on the old host until it ends.++**How a move happens.**+1. The old pane's scrollback is captured from the old host. It already answers `Snapshot`, within that op's limits:+ `historyLines` and the frame size.+2. A pane is opened on the target host, seeded with that scrollback. The host has no way to seed a pane today: G adds+ one, **without raising `PTY_PROTOCOL`** (below). The old host only needs to answer `Snapshot`, as it does now.+ - The bar is: the scrollback above reads as before, and the live screen is whatever the resumed engine draws.+ `claude --resume` and `codex resume` clear and redraw their screen with the conversation, so the visible screen+ cannot be pixel-identical. It does not need to be.+3. The engine in the old pane is stopped. The old pane is kept, not closed.+4. The engine is relaunched in the new pane with its resume argv, keeping the same agent id and row.+ - It builds the launch as `restoreAgents.ts` does (`buildLaunch`, the resume argv, grid launches). That code is+ shared, not copied.+ - The route handling is the move's own: restore commits a route before launch and goes through+ `launch: starting`, which clients see. A move prepares the new pane off to the side, then swaps.+5. Once the engine is proven running in the new pane, the row's runtime switches to it, and the old pane is closed.+ The switch is atomic for clients: none sees the agent twice, or with no pane.+ - Input that arrives between step 3 and the switch is held, and delivered to the new pane once the engine there+ is ready. It is never dropped. The window is seconds.++**When a move fails.** If the relaunch on the new host fails, or is not proven in time:+- the engine is relaunched in the **old** pane, as `restartAgent.ts` does;+- the new pane is closed;+- the agent is marked so it is not tried again until the next daemon start.++To the person, the agent is where it was, with its conversation.++**What is never moved:** terminals, engines that cannot resume, agents with no session id, and grid agents whose row+cannot be relaunched as `restoreAgents.ts` already defines. They stay until they end.++**Logs only.** Every move, skip and failure is logged by the daemon, with the agent id and the reason. Clients get no+new frame for it.++**The seed op stays on protocol 2.** Machines today run protocol-2 payloads, and only `install.ps1` replaces them.+Every CLI release reaches production, while a payload waits for its promotion. The first G CLI therefore lands on+machines whose host is a pre-G protocol-2 build, under updaters that know nothing of §5's protocol rule. A protocol+bump there would leave the G daemon with no host it can speak to. So:+- the seed op is added to protocol 2 as an optional op. A G daemon learns whether a host has it: from the host's+ `version` output or its hello, or by an `unsupported` answer to the op;+- a G daemon creates panes on a pre-G protocol-2 host as today's daemons do, and moves nothing to it;+- moves start once the target host is a G build, which §5 brings within one check of its promotion.++Raising `PTY_PROTOCOL` later stays possible: once G's updaters are on the machines, §5's protocol rule holds a+protocol-bumped CLI back until its payload is promoted, and its pairing rule then delivers the two together.++### 5. The self-update installs a promoted payload++**When.** The Windows self-update also reads the production `pty/metadata.json`, from the same base as the CLI+manifest it reads, on each of its checks. It installs the machine's entry when all of these hold:+- the entry's `version` is newer than the version `current-pty` names. It is never older and never the same, and+ the same version rule as the CLI's applies (`shouldAutoUpdate`);+- the installed build is not a dev build (`isLocalDevBuild`), as for the CLI;+- that version was not rolled back or refused on this machine (below).++The entry is `win32-x64` or `win32-arm64` for the machine's native architecture, the same choice `install.ps1`+makes. The PTY check and the CLI check are independent:+- a promoted payload is installed on a machine whose CLI is already current;+- a CLI update goes ahead with the PTY in place, under the protocol rule below.++**How a payload is installed.**+1. Download the zip, outside any lock, within the self-update's transfer limits. Check its `sha256` and `size`+ against the entry. A mismatch is refused, as for the CLI, and backed off before it is tried again.+2. Unpack it into a temporary folder beside `<runtime>/pty/`. Check that all six files are there: `harness-pty.exe`,+ `harness-launch.exe`, `harness.exe`, `conpty.dll`, `OpenConsole.exe`, `harness-serial.exe`.+3. Run a canary: the new `harness-pty.exe version` (and `harness-serial.exe version`) must answer with the entry's+ version. A payload that fails is refused. A host whose protocol the installed CLI supports+ (`SUPPORTED_PTY_PROTOCOLS`) is installed as below. A host whose protocol is above the running CLI's+ (`PTY_PROTOCOL`), the host of a protocol bump, is canaried the same way but kept *paired*: it is never installed+ on its own, only under the pairing rule below. A host below every supported protocol is refused.+4. Under the daemon spawn lock, the one the CLI update holds:+ - rename the temporary folder to `<runtime>/pty/<version>/`;+ - replace `bin\harness.exe` and `bin\harness-launch.exe`. A running executable cannot be overwritten on Windows,+ but it can be renamed. So each old file is renamed aside first, and the new file is put in its place. At every+ moment one of the two answers at the path, never neither. The renamed-aside files are deleted at a later check,+ once nothing runs them;+ - move `current-pty` with `writePointer`;+ - hand over to a new core, as a CLI update does. The updater runs in its own process+ (`services/updaterProcess.ts`): it tells the harnessd master `harnessd:staged` and exits. The master asks the+ core to hand over and puts the build on probation (`harnessd/supervisor.ts` `updateStaged`). G gives that+ message a PTY version beside the CLI one (either may be absent), and the master's probation covers both. From+ then on §2 applies: the new core builds its backends, new panes open on the new host, and §3 and §4 take care+ of the old one.++ If any step under the lock fails, the steps before it are undone: the two `bin\` files are put back and+ `current-pty` is left alone. The payload is refused like a failed canary.+5. When the CLI and the PTY both have an update on one check, both are installed under one lock hold and one+ handover. The PTY goes first. The updater stops after one staging today (`done`). After a PTY-only handover it+ must come back to check the CLI, and the reverse.++**The protocol rule.**+- A CLI build is not staged when it needs a host protocol that no installed payload offers. That is, `PTY_PROTOCOL`+ of the new build is above the protocol of the host `current-pty` names.+- The CLI waits, with a log line once per version, until a payload with that protocol is ready to go in with it+ (the pairing rule below), or `install.ps1` has installed one. Then it updates. A host whose protocol cannot be read+ (no `current-pty`, or a `version` that fails or times out) counts as the running CLI's own `PTY_PROTOCOL`.+- **The pairing rule.** A payload whose host protocol is above the running CLI's goes in only in the same lock hold+ and the same handover (`harnessd:staged` with both versions) as a canaried CLI build that needs exactly that+ protocol, the host first, and one probation judges the pair: a failure rolls both back. If the build does not go+ in after the host did, the host is taken back out (not recorded as rejected) and nothing is handed over.+- `harness update` follows the same rules: it installs a paired host only with the build that needs it, refuses a+ build that needs a protocol above the host's (read after its host step), leaves a pair on probation for the next+ master, and takes a paired host back out when its build fails to go in.+- The owner's order stays the one `desktop/RELEASE.md` gives. If a protocol bump's CLI is released before its payload+ is promoted, machines keep the older CLI until the promotion. They never get a CLI with no host to talk to.+- How the updater learns a new build's protocol (from its canary's `version` output, or from the CLI manifest+ entry) is the builder's. It must not need the build to be staged first.+- Once G ships, the `protocol.spec.ts` pin and the B spec's item 6 ("must not be raised until the rollover lands")+ are replaced by this rule.++**Rollback.** A payload whose new core does not come back healthy is rolled back by the master's probation, as it+rolls back a CLI build today (`restore()`, which G extends to the PTY):+- `current-pty` goes back to the previous version, and the two `bin\` files are restored;+- the version is recorded as rejected on this machine, and not tried again until a newer one is promoted.+- The new version folder stays until no host runs from it, under §3's rules.++The probation's signal and its window are the CLI's where they can be shared. Their exact shape is the builder's.++**Other installers.** `install.ps1` keeps installing the payload as it does today. It and the self-update take the+same lock and write the same pointer, so whichever comes second sees the other's version and does nothing.+`harness update` installs a newer promoted payload too, as it installs a newer CLI.++**Logs only.** A found, installed, refused or rolled-back payload is one line in the daemon log, as a CLI update is.+Nothing reaches any client.++## Constraints++- No administrator rights, no UAC prompt, per user. These are the same as A, B and C.+- Scope is Windows. tmux is not touched.+- Seeding a pane (§4) is an optional op on protocol 2, not a protocol bump. Any later bump follows+ `ptyHost/protocol.ts`'s rule (the daemon keeps a client for the protocol before it), §5's protocol rule, and §5's+ pairing rule (the bumped host goes in only with the CLI build that needs it, in one handover and one probation).+- Hosts and daemons of today's builds keep working: a G daemon drains a `p<protocol>` host. A pre-G daemon still+ running beside a G host (its stop failed during an update) keeps its own `p<protocol>` host; that is accepted.+- Never test against the developer's own machine: the real `~/.harness`, the daemon on 18473, the engine homes,+ tmux.+- The repo is public: no addresses, account names, ids or passwords in committed evidence.+- Docs, comments and commit messages in English.++## Testing++- **Unit (every OS):**+ - instance naming;+ - discovery of every instance in a home, including legacy `pty-host-<protocol>.json`;+ - target choice (installed version, unknown version, downgrade);+ - create and drain backends per host;+ - `removeUnusedPtyVersions` with two running versions;+ - the move's conditions: each one alone blocks a move, and breaking one mid-move cancels it;+ - the move's outcomes: moved; failed and back in the old pane; never-moved kinds left alone.+- **Real host (Mac, and Windows CI x64 and arm64):** two host builds with different `HARNESS_PTY_VERSION`, as in+ `ptyHostBackend.restart.spec.ts`:+ - a pane on the old host keeps streaming and taking input while new panes open on the new host;+ - a pane seeded from an old pane's snapshot shows the same screen and scrollback;+ - the old host is shut down after its last pane ends;+ - its folder is then deleted.+- **Unit, delivery (§5):**+ - the PTY check: newer, same, older, dev build, rejected version, missing entry for this architecture;+ - a zip that fails its digest, its size, the file list, or the canary is refused and leaves everything as it was;+ - a failure at each step under the lock is undone: the `bin\` files are back and `current-pty` is unchanged;+ - the protocol rule: a CLI needing a newer protocol waits, then updates once the payload lands;+ - CLI and PTY in one check: one lock hold and one handover, PTY first;+ - rollback after an unhealthy restart.+- **Windows CI (x64 and arm64), real files:** replace `bin\harness.exe` and `bin\harness-launch.exe` while copies of+ each are running, and check that the path answers at every moment, and that the renamed-aside files are deleted+ once they exit.+- **On the ARM64 VM and the x64 test PC, delivery the way a person gets it:**+ - install release N with `install.ps1` from the fake HTTPS CDN (`fake-cdn.sh`, as B5.13 did, so the build is+ not a dev build);+ - serve a PTY manifest naming N+1, and check that the next update check installs it with no `install.ps1`, moves+ `current-pty`, replaces the two `bin\` files and restarts the daemon;+ - on the x64 test PC, check that the dial on COM3 is found through the new payload's `harness-serial.exe`;+ - serve a payload with a wrong digest and check that it is refused and nothing changes;+ - serve a CLI N+1 that needs a protocol the installed payload lacks, and check that it waits, then updates once+ the payload is served.+- **On the ARM64 VM, the way a person updates:**+ - install a release;+ - start a claude agent, a codex agent and a terminal;+ - let the self-update install the next build's payload (§5). Then check the same steps after an `install.ps1`+ update;+ - check that a new agent opens on the new host while the three keep running;+ - close every client and wait out the quiet period. Check that each agent moved one at a time, with the same+ agent id, its scrollback as before and its conversation resumed. Check that the terminal was not touched;+ - with the desktop open, check that an agent whose tile is on screen is not moved, and that one in another super+ tab is;+ - minimize the desktop and check that the agents move;+ - close the terminal and check that the old host exits and its folder is deleted.++## Where and when++- The Windows PR (#1470) has merged and shipped. G is now its own branch, cut from current `main`+ (`feat/windows-pty-rollover`, rebased), and its own PR to `main`. Delivery (§5) and the rollover (§1–§4) ship+ together: either one alone leaves a new payload unused or unreachable.+- It touches:+ - the PTY host (`pty/src`);+ - the daemon's `ptyHost/`;+ - the self-update (`selfUpdate.ts` and its Windows layout code, `windows/installLayout.ts`);+ - agent-restore, stream and input code;+ - the desktop's local focus message.++ It does not touch the cable or serial code, or `harness-install.exe`. `install.ps1` changes only where it must+ share the lock or the rejected-version record with the self-update, and to restart the daemon when `current-pty`+ moved (§2).+- The release flow does not change. Once G ships, the owner promotes a payload when its PTY code is worth shipping,+ and every machine picks it up.++## Left to the builder++- The instance name's format, within §1's rules.+- How the daemon reads the target version where `current-pty` is absent (dev builds).+- The seed op's shape (a snapshot passed at create, or a separate op before the first output), and whether the+ host keeps the seeded scrollback within `--history-limit`.+- The quiet period's exact value and the move timeout, from measurements. Five minutes is the starting value.+- Whether the PTY check runs in the CLI's poller or beside it, and how they share the lock and the one handover.+- How the updater learns a new CLI build's host protocol, within §5's rule.+- The PTY probation's signal and window, shared with the CLI's where possible.+- When the renamed-aside `bin\` files are deleted, and their names.++## Calls made in this design++The owner decided:+- the rollover is invisible to the person, with no UI;+- the product decides when to move;+- a promoted PTY payload reaches machines through the self-update, with no `install.ps1` run (2026-10-21);+- promotion to production stays by hand (`promote-pty-payload.sh`), not on every CLI release (2026-10-21).++These calls are this design's, not yet confirmed by the owner:+- **The host rolls on every version change**, not only when its code changes. Every CLI release stamps a new host+ version, so after each update a second host runs until the old one's panes end or move. This costs one extra+ host process for that time, and keeps one predictable rule.+- **The target is decided at daemon start**, not before each new pane: on Windows an update always restarts the+ daemon.+- **"Looked at" means on screen.** The desktop reports its on-screen tiles through its existing focus message;+ mobile, web and Share count by open stream; an older desktop counts by open stream.+- **Moves wait for idle, unwatched and quiet.** An agent that is never left alone stays on the old host until it+ ends; that is accepted over interrupting the person.+- **Terminals and engines that cannot resume are never moved.** They hold the old host until they end.+- **The screen bar is the scrollback and the conversation**, not a pixel-identical screen.+- **The move shares restore's launch building** but has its own prepare-then-swap route handling.+- **Input during the swap is held and delivered**, never dropped.+- **Several daemons on one PTY home need no coordination**, under §3's two rules.+- **A downgrade keeps the newer version folder**, as today.+- **`bin\` files are replaced by rename-aside**, never by overwrite. A path always answers.+- **A failed download, digest, canary or step is refused and retried later**, with everything left as it was.+- **A CLI that needs a newer host protocol waits for the payload**, instead of installing with no host to speak to.+- **A payload that does not come back healthy is rolled back** and its version rejected on that machine, as a CLI+ build is.+- **PTY and CLI updates in one check share one handover**, PTY first.+- **Delivery is in G's spec and ships with the rollover**, not as a separate project.+- **The seed op is optional on protocol 2**, so the first G CLI works on machines with today's payload. Moves begin+ once a G payload is promoted.+- **Open streams follow a moved agent on the daemon's side**: no reconnect, no reload.+- **The phone's prefetched neighbours count as looked at; a closed window's watch does not.**+- **After a downgrade or rollback the newer host is drained and its agents moved back**, its folder kept.+- **`install.ps1` restarts the daemon when only the PTY changed.**++## Known limits++Found by the ARM64 VM end to end ([results](../../testing/pty-rollover-e2e.md)) and not fixed.++- **An agent with no session id never moves and keeps its old host alive** until its pane ends (by design: it cannot+ resume). On the VM an engine at its sign-in screen was such a pane. The same holds for the shell an exited engine+ leaves in its pane (on Windows the host's `afterExit` shell): it becomes a terminal row on that host, and a terminal+ never moves.+- **The moves of idle agents and the desktop-only cases are unproven on a real machine**: they need a signed-in+ engine and the desktop UI. The protocol rule's "updates once the payload lands" half needs a host build of+ protocol 3.diff --git a/docs/testing/pty-rollover-e2e.md b/docs/testing/pty-rollover-e2e.mdnew file mode 100644index 000000000..76994adad--- /dev/null+++ b/docs/testing/pty-rollover-e2e.md@@ -0,0 +1,114 @@+# PTY host rollover and delivery: end-to-end results++Date: 2026-10-21. Branch `feat/windows-pty-rollover` at `90e426cdd`. This is Task G5.2; the spec's testing section is+[Testing in the design](../superpowers/specs/2026-10-20-pty-host-rollover-design.md#testing). Machine: the Windows 11+ARM64 VM only. The owner decided to skip the x64 test PC, so the dial on COM3 is not covered.++## What was built++- **Terminal host payloads (arm64)** from the Windows workflow on the branch, `release=true` (payload only, the+ tests are not run; the same `cargo build --release` as the full run). One run per version, because the workflow's+ concurrency group is per ref and a second run cancels the first:+ - 0.4.901: [run 39575143666](https://github.com/autonomous-ai/openharness/actions/runs/39575143666);+ - 0.4.902: [run 39575521100](https://github.com/autonomous-ai/openharness/actions/runs/39575521100);+ - 0.4.904: [run 39578332728](https://github.com/autonomous-ai/openharness/actions/runs/39578332728).+ - 0.4.903 reused 0.4.902's bytes under a manifest with a wrong sha256.+- **CLI bundles** built locally from this tree, non-dev: `0.4.40-e2e.1` (N), `0.4.41-e2e.1`, and `0.4.42-e2e.1` with+ the `version --json` answer patched to `"ptyProtocol":3` in the bundle (the only change).++## How it was driven++A throwaway standard user (not in Administrators) was created on the VM and reached over SSH by key. The Mac served a+fake HTTPS CDN (`fake-cdn.sh` with `vm-cdn.ps1`, as in the [Windows CLI run](windows-cli-e2e.md)); the user's+`ADAPTER_UPDATE_URL` pointed at its staging manifest and `NODE_EXTRA_CA_CERTS` at its CA (`vm-cdn-user.ps1`), so the+daemon's updater fetched manifests and zips over HTTPS exactly as a person's would. The release was installed with the+real `irm .../install.ps1 | iex` line. The PTY driver (`cli/scripts/windows-pty-e2e`, bundled to the user's folder)+used the user's own loopback port. Codex was installed with npm; it was not signed in. Claude Code was not installed+(its installer downloads from a host the fake CDN answers for). The VM's `C:\work\e2e` and the admin profile were not+used. Only the arm64 platform is in the manifests.++## Summary++| # | Item | Result |+|---|---|---|+| 1 | Install N (CLI 0.4.40, host 0.4.901) with `install.ps1` from the fake CDN | Passed |+| 2 | Manifest names host 0.4.902: `current-pty`, both `bin\` files and the log, with no `install.ps1` | Passed |+| 3 | Host 0.4.903 with a wrong digest: refused, nothing changes | Passed |+| 4a | CLI needing protocol 3 waits, the log says so | Passed |+| 4b | ... and updates once a protocol-3 payload is served | Not run: no protocol-3 host build exists |+| 5 | After the updater's payload update: a new pane opens on the new host, old panes keep running | Passed |+| 6 | After an `install.ps1` update (CLI 0.4.41, host 0.4.904): same | Passed |+| 7 | Idle agent moves after `QUIET_MS` (same id, scrollback, conversation resumed) | Not run: no signed-in engine (see below) |+| 8 | The terminal is not touched by the mover | Passed |+| 9 | Closing the last pane: the old host exits and its folder goes | Passed, after a held pane was killed (see Findings) |+| 10 | Claude agent | Not run: not installed (installer blocked by the fake CDN names; not signed in anyway) |+| 11 | A tile on screen not moved; another super tab moved; minimize/tray | Not run: needs the desktop UI |+| 12 | Dial on COM3 through the new `harness-serial.exe` | Not run: the owner skipped the x64 PC |++## Results++**1. Install N.** The `irm` line took about 20 s, printed `OK Harness 0.4.40-e2e.1` and `OK terminal host 0.4.901`.+`harness start` brought the daemon up (not signed in, serving this computer only). The daemon log:+`ptyhost: target p2-0.4.901`. A terminal and a Codex agent were created (panes on host 0.4.901).++**2. Payload update.** The manifest was switched to 0.4.902 with no other action. The log:+`newer terminal host available: 0.4.901 -> 0.4.902` (44 s later, the next tick), then `staged terminal host 0.4.902 -+handing over` 60 s after that, `service updater asked to start again`, `core started`, and `the update stayed up -+keeping it` 34 s later. `current-pty` read 0.4.902 and `bin\harness.exe` and `bin\harness-launch.exe` hashed equal to+the 0.4.902 payload's files (and differed from 0.4.901's); both version folders were on disk. The check is two ticks by+design: the first prepares and verifies the payload, the next installs it (`ptyUpdate.ts`, `ready.fresh`). Total from+serving to kept: 2 min 18 s.++**3. Wrong digest.** With 0.4.903 served: `terminal host 0.4.903 was refused (digest mismatch: sha256 mismatch ...)`,+the version folders, `current-pty` and the `bin\` hashes were byte-for-byte as before (the diff of the two snapshots+differed only by the finished probation marker `pty-pending.json`).++**4a. Protocol wait.** With `0.4.42-e2e.1` (protocol 3) served: `newer build available: 0.4.40-e2e.1 -> 0.4.42-e2e.1`+and `0.4.42-e2e.1 needs pty protocol 3; this machine's host speaks 2 - waiting for its payload`. `harness version` still+read 0.4.40-e2e.1. The manifest was put back afterwards.++**5. New pane on the new host.** After step 2 the daemon log read `ptyhost: available (p2-0.4.901, draining)` and+`available (p2-0.4.902)`. Input typed into the pane that was opened before the update was echoed by its shell; a+terminal created after the update was a child of the 0.4.902 host process, the older panes children of the 0.4.901 one+(process tree from a toolhelp snapshot, since WMI refuses a standard user's SSH logon).++**6. After `install.ps1`.** With CLI 0.4.41 and host 0.4.904 served, the same `irm` line printed `Moving the running+Harness from 0.4.40-e2e.1 to 0.4.41-e2e.1 (your agents keep running)...`; afterwards `current-pty` was 0.4.904, the log+read `target p2-0.4.904`, `available (p2-0.4.902, draining)`, and a pane created after it was a child of the 0.4.904+host while the pane opened before (host 0.4.902) still took input.++**7 and 8. The mover.** The Codex agent was at its sign-in screen: it has no session id, so the mover logged+`move <agent>: skipped (no session id)` and the terminal `skipped (a terminal)` at the handover. The agents were idle+with no client attached for more than 300 s (log read 7 minutes after the handover): no move was attempted, the agent+kept its id and pane, and the terminal was untouched. The agent move itself needs a signed-in engine and was not run.++**9. Old host exit.** The old terminal was closed; the host stayed (the Codex pane was still on it, correct). The Codex+pane could not be closed through `agent_delete` (`IDENTITY_UNAVAILABLE ... the native ps probe did not complete`, the+same WMI limit of an SSH logon); it was ended with Ctrl+C instead. Opening the stopped row then started a shell under+the old host with no row of its own, which kept it alive for 5 more minutes. After that process was killed, the host+logged `draining p2-0.4.901 has gone (shut down with no panes left)`, exited, and its version folder was deleted within+the 10 s poll. `.lock` and `.panes` of that instance stayed in `run\`.++## Findings (limits, not fixed)++1. A terminal's row reads `offline` after a payload handover though its shell answers (`list-after`); seen before as G3+ of the Windows CLI run on a CLI-only update.+2. An agent with no session id never moves and keeps its host alive until closed (by design).+3. Opening a stopped agent row put a shell pane under the draining host with no row; not root-caused.+4. A drained host leaves `.lock` and `.panes` in `run\`.++These are in the spec's Known limits.++Fixed after the run: 1 (fdd4129a4: nothing reactivated a shell row after the core marked every row dormant, on any+host), 4 (455b0a2c1: the daemon removes the lock and pane counter with the discovery file). 3 was not a pane made on the+draining host: it was the `afterExit` shell of the Codex pane that was ended with Ctrl+C, kept as a terminal row+(`94184a03`, which the log shows as `move ...: skipped (a terminal)`); no code change, the spec's note on terminals+that never move covers it.++## Clean-up++Done: the user's scheduled tasks, every process of the user, the fake CDN lines in the hosts file (byte-identical to+before: same sha256), the fake CA in `LocalMachine\Root`, the Mac's fake CDN server, the staged files on the VM, the+user's account, and everything under the user's profile except its registry hive files (a loaded hive that Windows had+not released; it goes at the next sign-out or reboot). `C:\work\e2e` was not touched (its `state.json` keeps its+October 15 date).diff --git a/pty/src/cli.rs b/pty/src/cli.rsindex ba1001c8e..43140a660 100644--- a/pty/src/cli.rs+++ b/pty/src/cli.rs@@ -4,7 +4,7 @@use std::path::{Path, PathBuf};-use crate::protocol::PROTOCOL;+use crate::protocol::{FEATURES, PROTOCOL};/// How many random pipe names a Windows host tries before it gives up.#[cfg(windows)]@@ -29,11 +29,7 @@ pub const fn release_version(given: Option<&'static str>) -> &'static str {}pub fn version_line() -> String {- format!(- "{{\"version\":\"{}\",\"protocol\":{}}}",- VERSION,- PROTOCOL- )+ serde_json::json!({"version": VERSION, "protocol": PROTOCOL, "features": FEATURES}).to_string()}#[derive(Debug, PartialEq, Eq)]@@ -231,7 +227,7 @@ pub fn serve(home: &Path, history_limit: usize, reexec: bool) -> std::io::Result}}-/// Move `pty-host-<P>.json` to `pty-host-<P>.json.stale`, when there is one.+/// Move this build's `pty-host-<instance>.json` to `.json.stale`, when there is one.fn set_discovery_aside(run: &Path) {let file = crate::discovery::file_path(run);let mut aside = file.clone().into_os_string();@@ -276,7 +272,7 @@ fn publish_and_serve<L: crate::transport::Listener>() -> std::io::Result<()> {let info = crate::server::HostInfo {token: uuid::Uuid::new_v4().to_string(),- instance: crate::discovery::instance(),+ instance: crate::instance::current(),version: VERSION.to_owned(),pid: std::process::id(),};@@ -329,6 +325,7 @@ mod tests {let v: serde_json::Value = serde_json::from_str(&version_line()).unwrap();assert_eq!(v["version"], VERSION);assert_eq!(v["protocol"], PROTOCOL);+ assert_eq!(v["features"], serde_json::json!(["seed"]));}#[test]diff --git a/pty/src/discovery.rs b/pty/src/discovery.rsindex 3f4f6283c..b635de590 100644--- a/pty/src/discovery.rs+++ b/pty/src/discovery.rs@@ -1,12 +1,10 @@-//! `<home>/run/pty-host-<protocol>.json`: how a client finds and proves itself to the host.+//! `<home>/run/pty-host-<instance>.json`: how a client finds and proves itself to the host.use std::io;use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};-use crate::protocol::PROTOCOL;-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Discovery {pub protocol: u32,@@ -18,13 +16,7 @@ pub struct Discovery {}pub fn file_path(run_dir: &Path) -> PathBuf {- run_dir.join(format!("pty-host-{PROTOCOL}.json"))-}--/// The host's instance name: one host per protocol (`p1`), so a protocol bump drains into a-/// new instance.-pub fn instance() -> String {- format!("p{PROTOCOL}")+ crate::instance::run_file(run_dir, &crate::instance::current(), "json")}/// Write the discovery file atomically: a reader sees the old file or the whole new one, never a@@ -32,10 +24,9 @@ pub fn instance() -> String {/// on Unix, on Windows the pipe's DACL `D:P(A;;GA;;;<user SID>)` (`files::replace_private`).pub fn write(run_dir: &Path, discovery: &Discovery) -> io::Result<PathBuf> {let path = file_path(run_dir);- let tmp = run_dir.join(format!(- "pty-host-{PROTOCOL}.json.{}.tmp",- std::process::id()- ));+ let mut tmp = path.clone().into_os_string();+ tmp.push(format!(".{}.tmp", std::process::id()));+ let tmp = PathBuf::from(tmp);let body = serde_json::to_vec(discovery).map_err(io::Error::other)?;crate::files::replace_private(&tmp, &path, &body)?;Ok(path)@@ -44,11 +35,12 @@ pub fn write(run_dir: &Path, discovery: &Discovery) -> io::Result<PathBuf> {#[cfg(test)]mod tests {use super::*;+ use crate::protocol::PROTOCOL;fn sample(token: &str) -> Discovery {Discovery {protocol: PROTOCOL,- instance: instance(),+ instance: crate::instance::current(),endpoint: "/x.sock".into(),pid: 7,version: "0.1.0".into(),@@ -60,13 +52,13 @@ mod tests {fn writes_and_replaces_the_file() {let dir = tempfile::tempdir().unwrap();let path = write(dir.path(), &sample("a")).unwrap();- assert_eq!(path, dir.path().join(format!("pty-host-{PROTOCOL}.json")));+ assert_eq!(path, crate::instance::run_file(dir.path(), &crate::instance::current(), "json"));write(dir.path(), &sample("b")).unwrap();let read: Discovery = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();assert_eq!(read, sample("b"));let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();assert_eq!(v["protocol"], PROTOCOL);- assert_eq!(v["instance"], format!("p{PROTOCOL}"));+ assert_eq!(v["instance"], crate::instance::current());// No temporary file is left behind.assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);}diff --git a/pty/src/host_lock.rs b/pty/src/host_lock.rsindex 67142f759..d03eae36f 100644--- a/pty/src/host_lock.rs+++ b/pty/src/host_lock.rs@@ -1,4 +1,4 @@-//! `<home>/run/pty-host-<protocol>.lock`: one host per home.+//! `<home>/run/pty-host-<instance>.lock`: one host per home.//!//! A host takes the lock before it binds its endpoint or reserves pane ids, and holds it for its//! life; a host that cannot take it exits as one that found another host serving. Without it, two@@ -13,10 +13,9 @@ use std::fs::File;use std::io;use std::path::{Path, PathBuf};-use crate::protocol::PROTOCOL;pub fn file_path(run_dir: &Path) -> PathBuf {- run_dir.join(format!("pty-host-{PROTOCOL}.lock"))+ crate::instance::run_file(run_dir, &crate::instance::current(), "lock")}/// The lock, held while this lives.diff --git a/pty/src/instance.rs b/pty/src/instance.rsnew file mode 100644index 000000000..7e08a18aa--- /dev/null+++ b/pty/src/instance.rs@@ -0,0 +1,122 @@+//! The host's instance name, one per (protocol, version): `p<protocol>-<tag>`.+//!+//! Two builds of one protocol must be able to run side by side in one home, so the build is part of+//! the name that keys the discovery file, lock, pane-id counter, socket, pipe suffix, log and+//! `HARNESS_PANE`. Pre-G hosts used `p<protocol>`; this build never does.++use std::path::{Path, PathBuf};++use sha2::{Digest, Sha256};++use crate::cli::VERSION;+use crate::protocol::PROTOCOL;++/// The longest socket path in bytes. `sockaddr_un.sun_path` is 104 bytes on macOS and 108 on+/// Linux, so 100 leaves room for the terminating NUL on both.+const MAX_SOCKET_BYTES: usize = 100;++fn hex12(input: &str) -> String {+ Sha256::digest(input.as_bytes())[..6]+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect()+}++/// `p<protocol>-<version>` when the version is safe to put in a file name (`[0-9A-Za-z.-]{1,32}`),+/// otherwise `p<protocol>-h<12 hex of SHA-256(version)>`: a hash keeps odd or long versions+/// (build metadata, spaces) out of paths, and still gives each its own instance.+pub fn instance_name(protocol: u32, version: &str) -> String {+ let plain = (1..=32).contains(&version.len())+ && version+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-');+ if plain {+ format!("p{protocol}-{version}")+ } else {+ format!("p{protocol}-h{}", hex12(version))+ }+}++/// This build's instance.+pub fn current() -> String {+ instance_name(PROTOCOL, VERSION)+}++/// `<run_dir>/pty-host-<instance>.<ext>`.+pub fn run_file(run_dir: &Path, instance: &str, ext: &str) -> PathBuf {+ run_dir.join(format!("pty-host-{instance}.{ext}"))+}++/// The Unix socket path. A long home would push the plain name past the OS limit on `sun_path`+/// (the bind then fails), so past 100 bytes the name is a hash of the instance instead.+pub fn socket_path(run_dir: &Path, instance: &str) -> PathBuf {+ let plain = run_file(run_dir, instance, "sock");+ if plain.as_os_str().len() <= MAX_SOCKET_BYTES {+ return plain;+ }+ run_dir.join(format!("pty-host-s{}.sock", hex12(instance)))+}++/// `<home>/logs/pty-host-<instance>.log`.+pub fn log_path(home: &Path, instance: &str) -> PathBuf {+ home.join("logs").join(format!("pty-host-{instance}.log"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_follow_the_shared_vectors() {+ let text = std::fs::read_to_string(concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/tests/fixtures/instances.json"+ ))+ .unwrap();+ let vectors: Vec<serde_json::Value> = serde_json::from_str(&text).unwrap();+ assert!(vectors.len() >= 6);+ for v in vectors {+ assert_eq!(+ instance_name(v["protocol"].as_u64().unwrap() as u32, v["version"].as_str().unwrap()),+ v["instance"].as_str().unwrap(),+ "{v}"+ );+ }+ }++ #[test]+ fn current_is_this_builds_instance() {+ assert_eq!(current(), instance_name(PROTOCOL, VERSION));+ }++ #[test]+ fn a_long_home_uses_the_hashed_socket_name() {+ let instance = "p2-0.4.20";+ let short = Path::new("/h/run");+ assert_eq!(+ socket_path(short, instance),+ Path::new("/h/run/pty-host-p2-0.4.20.sock")+ );+ let long = PathBuf::from(format!("/{}", "a".repeat(89)));+ assert_eq!(long.as_os_str().len(), 90);+ let got = socket_path(&long, instance);+ let name = got.file_name().unwrap().to_str().unwrap();+ assert_eq!(got.parent().unwrap(), long);+ let hex = name+ .strip_prefix("pty-host-s")+ .and_then(|r| r.strip_suffix(".sock"))+ .unwrap();+ assert_eq!(hex.len(), 12);+ assert!(hex.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()));+ assert_eq!(hex, hex12(instance));+ }++ #[test]+ fn two_builds_have_different_files() {+ let run = Path::new("/h/run");+ let a = run_file(run, &instance_name(2, "0.4.20"), "json");+ let b = run_file(run, &instance_name(2, "0.4.21"), "json");+ assert_ne!(a, b);+ assert_eq!(a, Path::new("/h/run/pty-host-p2-0.4.20.json"));+ }+}diff --git a/pty/src/job.rs b/pty/src/job.rsindex 0c59f1849..80cf05746 100644--- a/pty/src/job.rs+++ b/pty/src/job.rs@@ -229,6 +229,7 @@ mod tests {cols: 80,rows: 24,clear_env: Vec::new(),+ seed: None,},1000,tx,diff --git a/pty/src/lib.rs b/pty/src/lib.rsindex ee14eb5de..a8b307094 100644--- a/pty/src/lib.rs+++ b/pty/src/lib.rs@@ -5,6 +5,7 @@ pub mod desktop;pub mod discovery;mod files;pub mod host_lock;+pub mod instance;#[cfg(windows)]pub mod job;pub mod launcher;diff --git a/pty/src/logfile.rs b/pty/src/logfile.rsindex ced89e721..c34fcf0c6 100644--- a/pty/src/logfile.rs+++ b/pty/src/logfile.rs@@ -1,11 +1,11 @@-//! The host's log: `<home>/logs/pty-host.log`, the owner's alone, kept to a size.+//! The host's log: `<home>/logs/pty-host-<instance>.log`, the owner's alone, kept to a size.//!//! The daemon starts the host with no stdio, so `log` records (and the host's own diagnostics) would//! go nowhere without this. Each line goes to the file and to stderr, so a host run by hand in a-//! terminal still shows them. Past [`MAX_BYTES`] the file is moved to `pty-host.log.1` (one older+//! terminal still shows them. Past [`MAX_BYTES`] the file is moved to `pty-host-<instance>.log.1` (one older//! file is kept) and a new one is started.//!-//! One host per home holds the home's lock (`host_lock`), but a host that lost the race for it, or the+//! One host per home and instance holds the home's lock (`host_lock`), but a host that lost the race for it, or the//! Windows copy that left a job (`breakaway`), may append a line or two before it exits. Only the//! lock's holder rotates (`own_rotation`, called once the lock is taken): a loser that rotated would//! leave the winner writing to `.log.1`, and the winner's next rotation would replace those lines.@@ -28,12 +28,14 @@ pub fn log_dir(home: &Path) -> PathBuf {}pub fn log_path(home: &Path) -> PathBuf {- log_dir(home).join("pty-host.log")+ crate::instance::log_path(home, &crate::instance::current())}-/// The rotated file: `pty-host.log.1`.+/// The rotated file: `pty-host-<instance>.log.1`.pub fn rotated_path(home: &Path) -> PathBuf {- log_dir(home).join("pty-host.log.1")+ let mut rotated = log_path(home).into_os_string();+ rotated.push(".1");+ PathBuf::from(rotated)}pub struct FileLog {@@ -114,9 +116,9 @@ impl FileLog {}impl State {- /// `pty-host.log` → `pty-host.log.1` (replacing it), then a new, empty `pty-host.log`. When the- /// rename fails the same file is reopened, and its size counted from zero: the next try is- /// another cap's worth of lines away.+ /// `pty-host-<instance>.log` → `pty-host-<instance>.log.1` (replacing it), then a new, empty+ /// `pty-host-<instance>.log`. When the rename fails the same file is reopened, and its size+ /// counted from zero: the next try is another cap's worth of lines away.fn rotate(&mut self) {self.file = None;let renamed = crate::files::rename(&self.path, &self.rotated).is_ok();diff --git a/pty/src/pane.rs b/pty/src/pane.rsindex c909ece01..a2bd080c4 100644--- a/pty/src/pane.rs+++ b/pty/src/pane.rs@@ -61,6 +61,8 @@ pub struct PaneSpec {pub rows: u16,/// Names the child does not get from the host's own environment (`clearInherited`).pub clear_env: Vec<String>,+ /// Text drawn into the grid before the child starts, so it sits in the scrollback (`Op::Create`'s `seed`).+ pub seed: Option<Vec<u8>>,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -307,6 +309,26 @@ fn user_home() -> Option<PathBuf> {.filter(|dir| dir.is_dir())}+/// A seed as the terminal should read it: capture/history lines end in a bare `\n`, which does not return+/// to column 0 (a staircase), so each one becomes `\r\n`. One line break at the very end is dropped: it ends+/// the last line, it does not start another (a blank history row).+fn seed_bytes(seed: &[u8]) -> Vec<u8> {+ let seed = seed+ .strip_suffix(b"\r\n")+ .or_else(|| seed.strip_suffix(b"\n"))+ .unwrap_or(seed);+ let mut out = Vec::with_capacity(seed.len() + 16);+ let mut previous = 0u8;+ for &byte in seed {+ if byte == b'\n' && previous != b'\r' {+ out.push(b'\r');+ }+ out.push(byte);+ previous = byte;+ }+ out+}+impl Pane {/// A new pane running `spec`. Without a `cwd` it starts in the user's home directory/// (`%USERPROFILE%`, `$HOME`), as a new tmux pane does, not in the host's (whose directory@@ -328,6 +350,21 @@ impl Pane {};let term = Term::new(config, &Size { cols, rows }, Listener(shared.clone()));let screen = Arc::new(Mutex::new(Screen { term, seq: 0 }));+ if let Some(seed) = spec.seed.as_deref() {+ // The seed, then one line feed per row and a cursor home: it scrolls wholly into the history and the+ // child draws on a blank screen from the top, as a new pane's child does. This runs before `attach`,+ // so no stream or child output can interleave.+ let mut screen = lock(&screen);+ let Screen { term, seq } = &mut *screen;+ let mut parser = Processor::<NoSync>::new();+ parser.advance(term, &seed_bytes(seed));+ // A seed that ends with a colour on must not paint the blank screen below it: the line feeds+ // scroll rows in with the cursor's colour.+ parser.advance(term, b"\x1b[0m");+ parser.advance(term, "\r\n".repeat(rows as usize).as_bytes());+ parser.advance(term, b"\x1b[H");+ *seq += 1;+ }let attachment = attach(&id, 1, &spec, cols, rows, &screen, &shared, sink.clone())?;Ok(Pane {id,@@ -1405,6 +1442,7 @@ mod tests {cols: 40,rows: 10,clear_env: Vec::new(),+ seed: None,}}@@ -1437,6 +1475,7 @@ mod tests {cols: 40,rows: 10,clear_env: Vec::new(),+ seed: None,},1000,tx,@@ -1460,6 +1499,7 @@ mod tests {cols: 40,rows: 10,clear_env: Vec::new(),+ seed: None,},1000,tx,@@ -1868,6 +1908,7 @@ mod windows_tests {cols: 80,rows: 24,clear_env: Vec::new(),+ seed: None,}}@@ -2202,3 +2243,16 @@ mod windows_tests {}}}++#[cfg(test)]+mod seed_tests {+ use super::seed_bytes;++ #[test]+ fn a_seed_reads_with_crlf_and_no_row_for_its_last_break() {+ assert_eq!(seed_bytes(b"a\nb\n"), b"a\r\nb");+ assert_eq!(seed_bytes(b"a\r\nb\r\n"), b"a\r\nb");+ assert_eq!(seed_bytes(b"a\r\nb\nc"), b"a\r\nb\r\nc");+ assert_eq!(seed_bytes(b"a\n\n"), b"a\r\n");+ }+}diff --git a/pty/src/pane_ids.rs b/pty/src/pane_ids.rsindex 90d6381c1..b83cc9302 100644--- a/pty/src/pane_ids.rs+++ b/pty/src/pane_ids.rs@@ -5,7 +5,7 @@//! record of `ptyhost:p1:%1` matched a new, unrelated pane (Task 15 review): its tile and its//! input could reach another agent's pane before the reconciler had counted it missing twice.//!-//! The counter lives in `<home>/run/pty-host-<protocol>.panes`, as the decimal ceiling of the ids+//! The counter lives in `<home>/run/pty-host-<instance>.panes`, as the decimal ceiling of the ids//! reserved so far. Ids are reserved in blocks of `BLOCK`: the new ceiling is written (temporary//! file, fsync, rename, owner-only) before any id of its block is handed out, so a crash at any//! point leaves a ceiling at or above every id already used. A new boot starts after it. A@@ -14,13 +14,12 @@use std::io;use std::path::{Path, PathBuf};-use crate::protocol::PROTOCOL;/// How many ids one write of the counter file reserves.pub const BLOCK: u64 = 1000;pub fn file_path(run_dir: &Path) -> PathBuf {- run_dir.join(format!("pty-host-{PROTOCOL}.panes"))+ crate::instance::run_file(run_dir, &crate::instance::current(), "panes")}/// The next pane number, and the reservation that covers it.diff --git a/pty/src/panes.rs b/pty/src/panes.rsindex d57ca3222..e54eeb5fe 100644--- a/pty/src/panes.rs+++ b/pty/src/panes.rs@@ -192,6 +192,7 @@ fn spec(cols,rows,clear_env,+ seed: None,}}@@ -517,6 +518,7 @@ impl Panes {hold,after_exit,clear_inherited,+ seed,} => {let cleared = clearable(clear_inherited);// A child given no directory starts in the user's home (`Pane::spawn`).@@ -528,20 +530,18 @@ impl Panes {if self.closing.load(Ordering::SeqCst) {return Err(OpError::new("bad_request", "the host is shutting down"));}- let pane = Pane::spawn(- id.clone(),- spec(- command.clone(),- cwd,- self.child_env(&id, env.clone()),- cols,- rows,- &cleared,- ),- self.history_limit,- self.sink.clone(),- )- .map_err(|e| OpError::new("spawn_failed", e.to_string()))?;+ let mut pane_spec = spec(+ command.clone(),+ cwd,+ self.child_env(&id, env.clone()),+ cols,+ rows,+ &cleared,+ );+ pane_spec.seed = seed.map(String::into_bytes);+ let pane =+ Pane::spawn(id.clone(), pane_spec, self.history_limit, self.sink.clone())+ .map_err(|e| OpError::new("spawn_failed", e.to_string()))?;let generation = pane.generation();table.insert(id.clone(),diff --git a/pty/src/protocol.rs b/pty/src/protocol.rsindex 683b27e35..c4210989a 100644--- a/pty/src/protocol.rs+++ b/pty/src/protocol.rs@@ -2,15 +2,19 @@ use serde::{Deserialize, Serialize};use std::collections::HashMap;use std::io::{self, Read, Write};-/// The wire protocol this host speaks, fixed at build time. Each value is its own host instance-/// (`p<PROTOCOL>`: its discovery file, endpoint, lock and pane ids), so a host of the next protocol-/// starts beside a running one and the old one drains: the daemon lists, streams and controls its+/// The wire protocol this host speaks, fixed at build time. Each (protocol, version) is its own+/// instance (`p<PROTOCOL>-<tag>`, `instance.rs`: its discovery file, endpoint, lock and pane ids), so a+/// host of another build starts beside a running one and the old one drains: the daemon lists, streams and controls its/// panes, makes new ones on the new host, and shuts the old one down once it has none/// (cli/src/lib/ptyHost/drain.ts).////// - 2: the `shutdown` op./// - 1: the first.pub const PROTOCOL: u32 = 2;++/// Optional protocol-2 abilities this host has, told in the hello reply and the `version` line. A host built+/// before the list sends none, which a client reads as none: protocol 2 itself never changes for these.+pub const FEATURES: &[&str] = &["seed"];pub const MAX_FRAME: u32 = 8 * 1024 * 1024;#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -176,6 +180,13 @@ pub enum Op {/// What `env` sets is still set.#[serde(rename = "clearInherited", default)]clear_inherited: Vec<String>,+ /// Another pane's scrollback (`capture`/`history` style: SGR-only ANSI, lines separated by `\n` or+ /// `\r\n`; one break at the very end is not a row) that the new pane starts with, wholly in its history+ /// above a blank screen. Only a host that lists `seed` in `FEATURES` knows the field; an older one+ /// ignores it and the pane starts with no history, so a client sends `seed` only to a host that lists+ /// the `seed` feature.+ #[serde(default)]+ seed: Option<String>,},Kill {pane: String,diff --git a/pty/src/server.rs b/pty/src/server.rsindex ecfd6b673..054274ff5 100644--- a/pty/src/server.rs+++ b/pty/src/server.rs@@ -25,7 +25,7 @@ use serde_json::{Map, Value, json};use crate::pane::PaneEvent;use crate::panes::Panes;use crate::protocol::{- Failure, HelloLine, Op, PROTOCOL, Request, Role, hello_auth, hello_proof, valid_nonce,+ FEATURES, Failure, HelloLine, Op, PROTOCOL, Request, Role, hello_auth, hello_proof, valid_nonce,};use crate::transport::{Connection, Listener};@@ -214,6 +214,7 @@ impl Ctx {"instance": self.info.instance,"version": self.info.version,"pid": self.info.pid,+ "features": FEATURES,"proof": hello_proof(&self.info.token, nonce),}}).to_string()diff --git a/pty/src/transport/unix.rs b/pty/src/transport/unix.rsindex fe91f1cc1..6ed1f0826 100644--- a/pty/src/transport/unix.rs+++ b/pty/src/transport/unix.rs@@ -1,4 +1,4 @@-//! The Unix socket `<home>/run/pty-host-<protocol>.sock`, readable and writable by its owner only.+//! The Unix socket `<home>/run/pty-host-<instance>.sock`, readable and writable by its owner only.use std::io;use std::os::unix::fs::PermissionsExt;@@ -7,10 +7,9 @@ use std::path::{Path, PathBuf};use std::time::Duration;use super::{Bound, Connection, Listener};-use crate::protocol::PROTOCOL;pub fn socket_path(run_dir: &Path) -> PathBuf {- run_dir.join(format!("pty-host-{PROTOCOL}.sock"))+ crate::instance::socket_path(run_dir, &crate::instance::current())}pub struct UnixTransport {diff --git a/pty/src/transport/windows.rs b/pty/src/transport/windows.rsindex 28eceef46..a6a03f476 100644--- a/pty/src/transport/windows.rs+++ b/pty/src/transport/windows.rs@@ -1,4 +1,4 @@-//! The named pipe `\\.\pipe\harness-pty-<hash>-<random>-p<protocol>`, open to its owner only.+//! The named pipe `\\.\pipe\harness-pty-<hash>-<random>-<instance>`, open to its owner only.//!//! - The name hashes the user's SID and the canonical home, so each user and each home has its//! own pipe, and a long home path cannot make the name too long.@@ -59,7 +59,6 @@ use windows_sys::Win32::System::Threading::{};use super::{Bound, Connection, Listener};-use crate::protocol::PROTOCOL;/// Each direction's pipe buffer.const BUFFER: u32 = 64 * 1024;@@ -80,7 +79,7 @@ fn wide_path(path: &Path) -> Vec<u16> {.collect()}-/// `\\.\pipe\harness-pty-<16 hex of SHA-256(sid + "\0" + home)>-<suffix>-p<protocol>`.+/// `\\.\pipe\harness-pty-<16 hex of SHA-256(sid + "\0" + home)>-<suffix>-<instance>`.pub fn pipe_name(user_sid: &str, canonical_home: &str, suffix: &str) -> String {let mut hash = Sha256::new();hash.update(user_sid.as_bytes());@@ -88,7 +87,10 @@ pub fn pipe_name(user_sid: &str, canonical_home: &str, suffix: &str) -> String {hash.update(canonical_home.as_bytes());let digest = hash.finalize();let hex: String = digest[..8].iter().map(|b| format!("{b:02x}")).collect();- format!(r"\\.\pipe\harness-pty-{hex}-{suffix}-p{PROTOCOL}")+ format!(+ r"\\.\pipe\harness-pty-{hex}-{suffix}-{}",+ crate::instance::current()+ )}/// 16 random hex digits (64 bits from the system's random source, through a v4 UUID).@@ -801,7 +803,7 @@ mod tests {let hash = a.strip_prefix(r"\\.\pipe\harness-pty-").unwrap()- .strip_suffix(&format!("-0123456789abcdef-p{PROTOCOL}"))+ .strip_suffix(&format!("-0123456789abcdef-{}", crate::instance::current())).unwrap();assert_eq!(hash.len(), 16);let s = "0123456789abcdef";@@ -814,7 +816,10 @@ mod tests {let want: String = digest[..8].iter().map(|b| format!("{b:02x}")).collect();assert_eq!(pipe_name("S-1-5-21-1", r"C:\h", s),- format!(r"\\.\pipe\harness-pty-{want}-{s}-p{PROTOCOL}")+ format!(+ r"\\.\pipe\harness-pty-{want}-{s}-{}",+ crate::instance::current()+ ));// A new name each call, for the same home, however it is written: only its hash part is// the home's.@@ -825,8 +830,9 @@ mod tests {pipe_name_for(Path::new(&other)).unwrap(),);assert_ne!(first, second);- let home_part =- |name: &str| name[..name.len() - format!("-{s}-p{PROTOCOL}").len()].to_owned();+ let home_part = |name: &str| {+ name[..name.len() - format!("-{s}-{}", crate::instance::current()).len()].to_owned()+ };assert_eq!(home_part(&first), home_part(&second));let suffix = random_suffix();assert_eq!(suffix.len(), 16);diff --git a/pty/tests/common/mod.rs b/pty/tests/common/mod.rsindex 634cbdfc5..51b58b15b 100644--- a/pty/tests/common/mod.rs+++ b/pty/tests/common/mod.rs@@ -68,7 +68,7 @@ pub fn kill_pid(pid: u32) {}pub fn discovery_file(home: &std::path::Path) -> std::path::PathBuf {- home.join(format!("run/pty-host-{PROTOCOL}.json"))+ harness_pty::instance::run_file(&home.join("run"), &harness_pty::instance::current(), "json")}/// The discovery file of `home` once it is there.diff --git a/pty/tests/control.rs b/pty/tests/control.rsindex 28c20c4e2..be5113723 100644--- a/pty/tests/control.rs+++ b/pty/tests/control.rs@@ -72,7 +72,7 @@ fn a_hello_needs_the_auth_not_the_token_and_a_reflected_proof_is_refused() {fn discovery_names_the_host() {let (mut h, disc) = start();assert_eq!(disc["protocol"], PROTOCOL);- assert_eq!(disc["instance"], format!("p{PROTOCOL}"));+ assert_eq!(disc["instance"], harness_pty::instance::current());assert_eq!(disc["version"], env!("CARGO_PKG_VERSION"));if disc["pid"] != h.child.id() {// On Windows a host started inside a job serves from a copy of itself started outside it;@@ -90,7 +90,10 @@ fn discovery_names_the_host() {let endpoint = std::path::Path::new(&endpoint);assert_eq!(endpoint,- h.home.path().join(format!("run/pty-host-{PROTOCOL}.sock"))+ harness_pty::instance::socket_path(+ &h.home.path().join("run"),+ &harness_pty::instance::current()+ ));let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;assert_eq!(mode(&discovery_file(h.home.path())), 0o600);@@ -98,10 +101,10 @@ fn discovery_names_the_host() {}#[cfg(windows)]{- // `\\.\pipe\harness-pty-<16 hex of the user and home>-<16 random hex>-p<protocol>`.+ // `\\.\pipe\harness-pty-<16 hex of the user and home>-<16 random hex>-<instance>`.let parts: Vec<&str> = endpoint.strip_prefix(r"\\.\pipe\harness-pty-")- .and_then(|rest| rest.strip_suffix(&format!("-p{PROTOCOL}")))+ .and_then(|rest| rest.strip_suffix(&format!("-{}", harness_pty::instance::current()))).unwrap_or_else(|| panic!("{endpoint}")).split('-').collect();@@ -124,8 +127,10 @@ fn discovery_names_the_host() {let mut line = String::new();BufReader::new(s).read_line(&mut line).unwrap();let v: serde_json::Value = serde_json::from_str(&line).unwrap();- assert_eq!(v["hello"]["instance"], format!("p{PROTOCOL}"));+ assert_eq!(v["hello"]["instance"], harness_pty::instance::current());assert_eq!(v["hello"]["pid"], disc["pid"]);+ // A pre-G host sends no `features`; a client reads that as none.+ assert_eq!(v["hello"]["features"], serde_json::json!(["seed"]));}/// `data` as the `write` op carries it.@@ -331,7 +336,12 @@ fn second_host_exits_cleanly() {/// The pane counter's ceiling: how many ids the hosts of a home have reserved.fn reserved(home: &std::path::Path) -> String {- std::fs::read_to_string(home.join(format!("run/pty-host-{PROTOCOL}.panes"))).unwrap()+ std::fs::read_to_string(harness_pty::instance::run_file(+ &home.join("run"),+ &harness_pty::instance::current(),+ "panes",+ ))+ .unwrap()}#[test]@@ -344,8 +354,11 @@ fn hosts_started_together_serve_once() {let run = home.path().join("run");std::fs::create_dir_all(&run).unwrap();drop(- std::os::unix::net::UnixListener::bind(run.join(format!("pty-host-{PROTOCOL}.sock")))- .unwrap(),+ std::os::unix::net::UnixListener::bind(harness_pty::instance::socket_path(+ &run,+ &harness_pty::instance::current(),+ ))+ .unwrap(),);}let mut children: Vec<_> = (0..8)@@ -427,12 +440,14 @@ fn a_squatter_on_the_endpoint_fails_the_start_and_the_discovery_file_is_set_asidlet run = home.path().join("run");std::fs::create_dir_all(&run).unwrap();// A dead host's discovery file, naming the endpoint.- let file = run.join(format!("pty-host-{PROTOCOL}.json"));+ let file = harness_pty::instance::run_file(&run, &harness_pty::instance::current(), "json");std::fs::write(&file, r#"{"stale":true}"#).unwrap();// Another process has the endpoint while no host holds the home's lock.- let _squatter =- std::os::unix::net::UnixListener::bind(run.join(format!("pty-host-{PROTOCOL}.sock")))- .unwrap();+ let _squatter = std::os::unix::net::UnixListener::bind(harness_pty::instance::socket_path(+ &run,+ &harness_pty::instance::current(),+ ))+ .unwrap();// `--no-reexec`: the status is this host's own, not that of a first host that started it.let out = host_command(home.path()).arg("--no-reexec")@@ -487,9 +502,21 @@ fn a_pipe_name_is_new_each_start_and_a_squatter_on_an_old_one_is_passed_by() {};let new = second["endpoint"].as_str().unwrap();assert_ne!(new, old);- // Same user and home: only the random part differs.- let home_part = |name: &str| name.rsplitn(3, '-').nth(2).unwrap().to_owned();- assert_eq!(home_part(new), home_part(&old));+ // Same user and home, and the same instance: only the random part differs. Parsed from the front, and the+ // instance stripped whole: it has dashes of its own (`p2-0.4.31`).+ let suffix = format!("-{}", harness_pty::instance::current());+ let parts = |name: &str| -> (String, String) {+ let rest = name+ .strip_prefix(r"\\.\pipe\harness-pty-")+ .and_then(|rest| rest.strip_suffix(&suffix))+ .unwrap_or_else(|| panic!("{name} does not end in {suffix}"));+ let (home, random) = rest.split_once('-').unwrap_or_else(|| panic!("{name}"));+ (home.to_owned(), random.to_owned())+ };+ let (old_home, old_random) = parts(&old);+ let (new_home, new_random) = parts(new);+ assert_eq!(new_home, old_home, "{old} -> {new}");+ assert_ne!(new_random, old_random, "{old} -> {new}");let (mut w, mut r) = connect(&second);assert_eq!(call(&mut w, &mut r, r#"{"id":1,"op":"titles"}"#)["ok"],@@ -715,7 +742,7 @@ fn stale_socket_is_replaced() {let run = home.path().join("run");std::fs::create_dir_all(&run).unwrap();// A socket file nobody listens on, as a crashed host leaves it.- let path = run.join(format!("pty-host-{PROTOCOL}.sock"));+ let path = harness_pty::instance::socket_path(&run, &harness_pty::instance::current());drop(std::os::unix::net::UnixListener::bind(&path).unwrap());// A child another test forks just now holds the listener until it execs: wait for refusal.let end = Instant::now() + Duration::from_secs(5);@@ -904,7 +931,7 @@ fn children_see_harness_pane() {.to_string(),);let pane = created["pane"].as_str().unwrap().to_string();- let want = format!("hp=p{PROTOCOL}:{pane}.");+ let want = format!("hp={}:{pane}.", harness_pty::instance::current());let end = Instant::now() + WAIT;loop {let cap = call(@@ -1011,3 +1038,76 @@ fn bad_requests_get_error_replies() {// The spawn itself may succeed (env execs the command): either an error or a pane that exits.assert!(v["ok"] == true || v["code"] == "spawn_failed", "{v}");}++/// Two builds of one protocol serve one home side by side, each with its own discovery file.+/// Runs only when `HARNESS_PTY_BIN_OLD` names a build of this source made with another+/// `HARNESS_PTY_VERSION`; otherwise there is no second build to start. Set, it must name a file: a+/// CI step that builds it in the wrong place must fail here, not pass with nothing tested.+#[test]+fn two_versions_serve_side_by_side() {+ let Some(old) = std::env::var_os("HARNESS_PTY_BIN_OLD") else {+ return;+ };+ assert!(+ std::path::Path::new(&old).is_file(),+ "HARNESS_PTY_BIN_OLD names no file: {}",+ std::path::Path::new(&old).display()+ );+ // The other build says its own version; that, not a guess, names its discovery file.+ let out = std::process::Command::new(&old)+ .arg("version")+ .output()+ .unwrap();+ let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();+ let old_instance = harness_pty::instance::instance_name(+ v["protocol"].as_u64().unwrap() as u32,+ v["version"].as_str().unwrap(),+ );+ assert_ne!(old_instance, harness_pty::instance::current());++ let home = tempfile::tempdir().unwrap();+ let mut old_host = std::process::Command::new(&old);+ old_host.args(["serve", "--home"]).arg(home.path());+ let mut old_child = old_host.spawn().unwrap();+ let mut new_child = host_command(home.path()).spawn().unwrap();++ let run = home.path().join("run");+ let read = |instance: &str| -> serde_json::Value {+ let file = harness_pty::instance::run_file(&run, instance, "json");+ let end = Instant::now() + WAIT;+ loop {+ if let Ok(bytes) = std::fs::read(&file)+ && let Ok(disc) = serde_json::from_slice(&bytes)+ {+ return disc;+ }+ assert!(Instant::now() < end, "no discovery file {}", file.display());+ std::thread::sleep(Duration::from_millis(20));+ }+ };+ let old_disc = read(&old_instance);+ let new_disc = read(&harness_pty::instance::current());+ let mut pids = vec![];+ for (disc, instance) in [+ (&old_disc, old_instance.clone()),+ (&new_disc, harness_pty::instance::current()),+ ] {+ let s = dial(disc);+ s.set_read_timeout(Some(WAIT)).unwrap();+ let mut w = s.try_clone().unwrap();+ writeln!(w, "{}", hello(disc["token"].as_str().unwrap(), "control")).unwrap();+ let mut line = String::new();+ BufReader::new(s).read_line(&mut line).unwrap();+ let reply: serde_json::Value = serde_json::from_str(&line).unwrap();+ assert_eq!(reply["hello"]["instance"], instance, "{line}");+ pids.push(disc["pid"].as_u64().unwrap() as u32);+ }+ assert_ne!(old_disc["endpoint"], new_disc["endpoint"]);+ let _ = old_child.kill();+ let _ = new_child.kill();+ let _ = old_child.wait();+ let _ = new_child.wait();+ for pid in pids {+ common::kill_pid(pid);+ }+}diff --git a/pty/tests/fixtures/instances.json b/pty/tests/fixtures/instances.jsonnew file mode 100644index 000000000..afbe53cfe--- /dev/null+++ b/pty/tests/fixtures/instances.json@@ -0,0 +1,32 @@+[+ {+ "protocol": 2,+ "version": "0.4.20",+ "instance": "p2-0.4.20"+ },+ {+ "protocol": 2,+ "version": "0.4.21-dev.win1",+ "instance": "p2-0.4.21-dev.win1"+ },+ {+ "protocol": 2,+ "version": "0.1.0",+ "instance": "p2-0.1.0"+ },+ {+ "protocol": 2,+ "version": "0.4.21+meta",+ "instance": "p2-h169ef517daa5"+ },+ {+ "protocol": 2,+ "version": "1 2",+ "instance": "p2-hf71998fe363b"+ },+ {+ "protocol": 2,+ "version": "1234567890123456789012345678901234567890",+ "instance": "p2-ha4ebdd541454"+ }+]diff --git a/pty/tests/fixtures/ops.json b/pty/tests/fixtures/ops.jsonindex 9dcc9525f..e258ac238 100644--- a/pty/tests/fixtures/ops.json+++ b/pty/tests/fixtures/ops.json@@ -1,5 +1,5 @@[- {"id": 1, "op": "create", "command": ["sh", "-l"], "cwd": "/tmp", "env": {"A": "1"}, "cols": 120, "rows": 40, "owner": "harness:o", "label": "agent", "hold": true, "afterExit": {"command": ["pwsh.exe", "-NoLogo"], "env": {"N": "codex"}}, "clearInherited": ["ANTHROPIC_API_KEY"]},+ {"id": 1, "op": "create", "command": ["sh", "-l"], "cwd": "/tmp", "env": {"A": "1"}, "cols": 120, "rows": 40, "owner": "harness:o", "label": "agent", "hold": true, "afterExit": {"command": ["pwsh.exe", "-NoLogo"], "env": {"N": "codex"}}, "clearInherited": ["ANTHROPIC_API_KEY"], "seed": "a\r\nb"},{"id": 2, "op": "kill", "pane": "%1", "graceMs": 1500},{"id": 3, "op": "inventory"},{"id": 4, "op": "titles"},diff --git a/pty/tests/ops_fixture.rs b/pty/tests/ops_fixture.rsindex 9ba850fa8..5053e5347 100644--- a/pty/tests/ops_fixture.rs+++ b/pty/tests/ops_fixture.rs@@ -31,7 +31,8 @@ fn str_of(v: &Value) -> Option<String> {/// as its default: compare every optional or defaulted field with the fixture.fn assert_every_field_read(op: &Op, v: &Value) {match op {- Op::Create { cwd, env: e, label, after_exit: after, clear_inherited, .. } => {+ Op::Create { cwd, env: e, label, after_exit: after, clear_inherited, seed, .. } => {+ assert_eq!(seed.clone(), str_of(&v["seed"]));assert_eq!(*after, after_exit(&v["afterExit"]));let cleared: Vec<String> = serde_json::from_value(v["clearInherited"].clone()).unwrap();assert_eq!(*clear_inherited, cleared);diff --git a/pty/tests/stream.rs b/pty/tests/stream.rsindex e5cbb5a69..c80d70512 100644--- a/pty/tests/stream.rs+++ b/pty/tests/stream.rs@@ -672,3 +672,123 @@ fn conversation_snapshots_carry_the_joined_history() {"{v}");}++/// `create` with an optional seed, `rows` high.+fn create_seeded(+ w: &mut Conn,+ r: &mut BufReader<Conn>,+ seed: Option<&str>,+ rows: u16,+ unix: &str,+ windows: &str,+) -> String {+ let mut req = serde_json::json!({"id": 1, "op": "create", "command": script(unix, windows), "cols": 80, "rows": rows, "owner": "t", "hold": false});+ if let Some(seed) = seed {+ req["seed"] = serde_json::json!(seed);+ }+ let created = call(w, r, &req.to_string());+ created["pane"].as_str().unwrap().to_string()+}++fn history_snapshot(s: &mut Conn, id: u64) -> serde_json::Value {+ let req = serde_json::json!({"id": id, "history": "plain", "historyLines": 50});+ write_frame(s, Kind::Snapshot, req.to_string().as_bytes()).unwrap();+ loop {+ let (kind, v) = next_reply(s);+ if kind == Kind::SnapshotReply {+ return v;+ }+ }+}++#[test]+fn a_seeded_pane_starts_with_its_seed_in_history() {+ let (_h, disc) = start();+ let (mut w, mut r) = connect(&disc);+ let pane = create_seeded(+ &mut w,+ &mut r,+ Some("one\r\ntwo\r\n\x1b[31mthree\x1b[0m"),+ 10,+ "sleep 1.5; echo ready; sleep 5",+ r#"Start-Sleep -Milliseconds 1500; "ready"; Start-Sleep 5"#,+ );+ let mut s = stream(&disc);+ subscribe_with(&mut s, &pane, 80, 10, false);+ // Before the child prints anything.+ let v = history_snapshot(&mut s, 1);+ let history = v["history"].as_str().unwrap();+ let (one, two, three) = (+ history.find("one").expect(history),+ history.find("two").expect(history),+ history.find("three").expect(history),+ );+ assert!(one < two && two < three, "{history:?}");+ assert!(history.contains("\x1b[31m"), "colour kept: {history:?}");+ assert!(v["capture"].as_str().unwrap().trim().is_empty(), "{v}");+ assert_eq!(v["meta"]["cursor_x"], 0, "{v}");+ assert_eq!(v["meta"]["cursor_y"], 0, "{v}");+ // The child draws from the top of the screen.+ wait_capture(&mut w, &mut r, &pane, "ready");+ let cap = call(+ &mut w,+ &mut r,+ &serde_json::json!({"id": 9, "op": "capture", "pane": pane, "ansi": false, "visible": true}).to_string(),+ );+ assert!(cap["text"].as_str().unwrap().starts_with("ready"), "{cap}");+}++#[test]+fn a_create_without_seed_is_unchanged() {+ let (_h, disc) = start();+ let (mut w, mut r) = connect(&disc);+ let pane = create_seeded(+ &mut w,+ &mut r,+ None,+ 10,+ "sleep 1.5; echo ready; sleep 5",+ r#"Start-Sleep -Milliseconds 1500; "ready"; Start-Sleep 5"#,+ );+ let mut s = stream(&disc);+ subscribe_with(&mut s, &pane, 80, 10, false);+ let v = history_snapshot(&mut s, 1);+ assert_eq!(v["history"], "", "{v}");+ assert!(v["capture"].as_str().unwrap().trim().is_empty(), "{v}");+ wait_capture(&mut w, &mut r, &pane, "ready");+}++#[test]+fn a_history_style_seed_has_no_staircase_and_no_extra_blank_row() {+ let (_h, disc) = start();+ let (mut w, mut r) = connect(&disc);+ let pane = create_seeded(+ &mut w,+ &mut r,+ Some("one\ntwo\n\x1b[31mthree\x1b[0m\n"),+ 10,+ "sleep 5",+ "Start-Sleep 5",+ );+ let mut s = stream(&disc);+ subscribe_with(&mut s, &pane, 80, 10, false);+ let v = history_snapshot(&mut s, 1);+ let lines: Vec<&str> = v["history"].as_str().unwrap().lines().collect();+ assert_eq!(lines.len(), 3, "{lines:?}");+ assert!(lines[0].starts_with("one"), "{lines:?}");+ assert!(lines[1].starts_with("two"), "{lines:?}");+ assert!(lines[2].starts_with("\x1b[31mthree"), "{lines:?}");+}++#[test]+fn a_seed_that_ends_with_a_colour_on_leaves_the_screen_default() {+ let (_h, disc) = start();+ let (mut w, mut r) = connect(&disc);+ let pane = create_seeded(&mut w, &mut r, Some("red\n\x1b[41m"), 10, "sleep 5", "Start-Sleep 5");+ let mut s = stream(&disc);+ subscribe_with(&mut s, &pane, 80, 10, false);+ let v = history_snapshot(&mut s, 1);+ let capture = v["capture"].as_str().unwrap();+ assert!(!capture.contains('\x1b') && capture.trim().is_empty(), "{capture:?}");+ assert!(v["history"].as_str().unwrap().starts_with("red"), "{v}");+}diff --git a/tui/vendor/alacritty_terminal/src/tty/windows/conpty.rs b/tui/vendor/alacritty_terminal/src/tty/windows/conpty.rsindex 3fa9e583b..4c6e302bd 100644--- a/tui/vendor/alacritty_terminal/src/tty/windows/conpty.rs+++ b/tui/vendor/alacritty_terminal/src/tty/windows/conpty.rs@@ -146,6 +146,10 @@ pub fn new(config: &Options, window_size: WindowSize) -> Result<Pty> {assert_eq!(result, S_OK);+ // hn: every failure from here to the running child closes the pseudoconsole (after the pipes,+ // so the close cannot wait for a drain). Left open, its console process (OpenConsole.exe)+ // outlives a failed spawn: a host that is asked for a missing program would leak one per try.+ let spawned = (|| -> Result<PROCESS_INFORMATION> {let mut success;// Prepare child process startup info.@@ -267,14 +271,22 @@ pub fn new(config: &Options, window_size: WindowSize) -> Result<Pty> {TerminateProcess(proc_info.hProcess, 1);CloseHandle(proc_info.hThread);CloseHandle(proc_info.hProcess);- drop(conout);- drop(conin);- (api.close)(pty_handle);return Err(err);}CloseHandle(proc_info.hThread);}}+ Ok(proc_info)+ })();+ let proc_info = match spawned {+ Ok(info) => info,+ Err(err) => {+ drop(conout);+ drop(conin);+ unsafe { (api.close)(pty_handle) };+ return Err(err);+ },+ };let conin = UnblockedWriter::new(conin, PIPE_CAPACITY);let conout = UnblockedReader::new(conout, PIPE_CAPACITY);