Skip to content

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.

Fix account recovery, terminal ownership, and native input reliability (#412)

Deed8c112824610
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 03e90784b..2d1dccd04 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -450,6 +450,31 @@ function processEntrypoint(args) {
return tokens[index] || ''
}
+/** Hermes' managed launchers exec Python -I -c with a path bootstrap, then either import main
+ * or run it through runpy. Require that executable prefix and actual code, never a script argument
+ * or a quoted mention. argv[0] is authoritative here: macOS can truncate an absolute `comm` path.
+ * Keep the standalone hook's copy in sync. */
+function hermesInlineLauncher(row) {
+ const args = row.args.trim()
+ if (!/^python(?:\d+(?:\.\d+)*)?$/.test(basename(argvTokens(args)[0] ?? '').toLowerCase())) return false
+ const prefix = /^(?:"[^"]+"|'[^']+'|\S+)(?:\s+-(?:I|E|s|S|u|B|O{1,2}|q))*\s+-c\s+/.exec(args)
+ if (!prefix) return false
+ const source = args.slice(prefix[0].length).replace(/^["']/, '')
+ // Mask string literals before looking for Python statements. A print/prompt containing a whole
+ // launcher is still data. Keep literal values only to identify runpy's exact entry module.
+ const literals = []
+ const code = source.replace(/(['"])(?:\\[\s\S]|(?!\1)[^\\])*?\1/g, (literal) => {
+ literals.push(literal.slice(1, -1))
+ return `__literal${literals.length - 1}__`
+ })
+ if (!/^import\s+(?:(?:os|re|sys|runpy)\s*,\s*)*(?:sys|runpy)[;\s]+(?:os\.environ\.pop\(__literal\d+__,\s*None\)[;\s]+)*sys\.path\.insert\(\s*0,\s*__literal\d+__\s*\)/.test(code)) return false
+ if (/\bimport\s+hermes_bootstrap\b/.test(code)
+ && /\bfrom\s+hermes_cli\.main\s+import\s+main\b/.test(code)
+ && /\bsys\.exit\(\s*main\(\)\s*\)/.test(code)) return true
+ const run = /\brunpy\.run_module\(\s*__literal(\d+)__\s*,\s*run_name\s*=\s*__literal(\d+)__(?:\s*,\s*alter_sys\s*=\s*True)?\s*\)/.exec(code)
+ return !!run && literals[Number(run[1])] === 'hermes_cli.main' && literals[Number(run[2])] === '__main__'
+}
+
const ENGINE_COMMANDS = {
claude: 'claude', codex: 'codex', cursor: 'agent', hermes: 'hermes', commandcode: 'cmd',
devin: 'devin', muse: 'muse', grok: 'grok', agy: 'agy', copilot: 'copilot',
@@ -545,6 +570,7 @@ function processMatchScore(row, engine, ownership, allowAgentHint = false) {
return /command-code[\/\\]dist[\/\\]index\.mjs$/.test(entrypoint) ? 2 : 0
}
if (engine === 'devin') return /devin[\/\\]cli[\/\\]_versions[\/\\][^/\\]+[\/\\]bin[\/\\]devin$/.test(entrypoint) ? 2 : 0
+ if (engine === 'hermes' && hermesInlineLauncher(row)) return 2
if (engine === 'hermes') return /hermes-agent[\/\\]hermes$/.test(entrypoint)
|| /^(?:hermes|hermes_cli)(?:\.|$)/.test(entrypoint) ? 2 : 0
if (engine === 'muse') return /^muse-bin-/.test(executable) || /^muse-bin-/.test(entrybase) ? 3 : 0
@@ -837,9 +863,9 @@ function processStartMarker(pid) {
} catch { /* non-Linux or exited process; use ps below */ }
try {
const started = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
- encoding: 'utf8', timeout: 1000,
+ encoding: 'utf8', timeout: 1000, env: { ...psEnv(), TZ: 'UTC' },
}).trim()
- return started ? `ps:${started}` : null
+ return started ? `ps-c:${started}` : null
} catch { return null }
}
@@ -848,7 +874,23 @@ function processAlive(pid, startMarker = '') {
try { process.kill(pid, 0) } catch (error) { if (error?.code !== 'EPERM') return false }
if (!startMarker) return true
const current = processStartMarker(pid)
- return current === null || current === startMarker
+ // Pre-upgrade ps markers may use another locale; a mismatch is not death.
+ const comparable = current !== null && ['linux:', 'ps-c:'].some(
+ (prefix) => startMarker.startsWith(prefix) && current.startsWith(prefix),
+ )
+ return !comparable || current === startMarker
+}
+
+
+// The legacy field stays empty for ps-c so old readers fall back to PID liveness during upgrade.
+function processLockIdentity(pid) {
+ const generationMarker = processStartMarker(pid) || ''
+ return { startMarker: generationMarker.startsWith('ps-c:') ? '' : generationMarker, generationMarker }
+}
+
+function lockStartMarker(owner) {
+ return typeof owner?.generationMarker === 'string' ? owner.generationMarker
+ : typeof owner?.startMarker === 'string' ? owner.startMarker : ''
}
async function withRegistryLock(registryFile, fn) {
@@ -857,7 +899,7 @@ async function withRegistryLock(registryFile, fn) {
try {
secureStateDirectory(dataDir)
} catch { return }
- const processMarker = processStartMarker(process.pid) || ''
+ const processIdentity = processLockIdentity(process.pid)
for (let i = 0; i < LOCK_RETRIES; i++) {
if (remainingBudget(750) < 50) return
const token = randomUUID()
@@ -868,7 +910,7 @@ async function withRegistryLock(registryFile, fn) {
const ownerFile = join(lockDir, 'owner.json')
const ownerFd = openSync(ownerFile, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
try {
- writeFileSync(ownerFd, JSON.stringify({ pid: process.pid, startMarker: processMarker, token }))
+ writeFileSync(ownerFd, JSON.stringify({ pid: process.pid, ...processIdentity, token }))
fsyncSync(ownerFd)
} finally { closeSync(ownerFd) }
try {
@@ -888,12 +930,12 @@ async function withRegistryLock(registryFile, fn) {
|| (ownerStat.mode & 0o777) !== 0o600) return
const owner = JSON.parse(readFileSync(join(lockDir, 'owner.json'), 'utf8'))
const ownerPid = Number(owner?.pid)
- const ownerStartMarker = typeof owner?.startMarker === 'string' ? owner.startMarker : ''
+ const ownerStartMarker = lockStartMarker(owner)
const ownerToken = typeof owner?.token === 'string' ? owner.token : ''
if (!processAlive(ownerPid, ownerStartMarker) && ownerPid > 0 && ownerToken) {
const current = JSON.parse(readFileSync(join(lockDir, 'owner.json'), 'utf8'))
if (Number(current?.pid) === ownerPid
- && current?.startMarker === ownerStartMarker
+ && lockStartMarker(current) === ownerStartMarker
&& current?.token === ownerToken
&& !processAlive(ownerPid, ownerStartMarker)) {
rmSync(lockDir, { recursive: true, force: true })
diff --git a/cli/scripts/resume-native-e2e.ts b/cli/scripts/resume-native-e2e.ts
index 7d0f0b945..9b4fee118 100644
--- a/cli/scripts/resume-native-e2e.ts
+++ b/cli/scripts/resume-native-e2e.ts
@@ -145,23 +145,28 @@ try {
const inventory = await rpc('agents_list', { includeStopped: true })
assert(inventory.agents.some((a: any) => a.id === old.agentId && a.status === 'stopped'))
const openSaved = async (creationId: string) => {
- let settled = false, submitted = false
+ let settled = false, submitted = false, historyVisible = false
const hookCount = hooks.length
+ const nativeHookSeen = () => hooks.some(h => h.engine === engine && h.sessionId === sessionId)
+ const needHook = !nativeHookSeen()
const opening = rpc('agent_resume', { agentId: old.agentId, creationId }).finally(() => { settled = true })
const deadline = Date.now() + 45000
- while (!settled && Date.now() < deadline) {
+ // Readiness now uses the live process and can precede the first TUI paint or startup hook.
+ // Verify those independently; finishing the RPC must not stop this fixture from driving
+ // Codex's deferred hook through its loopback-only synthetic turn.
+ while ((!settled || !historyVisible || (needHook && !nativeHookSeen())) && Date.now() < deadline) {
const row = registry.byAgent(old.agentId)
if (row) {
await tmux('resize-window', '-t', row.tmuxPane, '-x', '140', '-y', '45')
const screen = await tmux('capture-pane', '-p', '-S', '-500', '-t', row.tmuxPane)
+ historyVisible ||= screen.includes(marker)
writeFileSync(join(root, `${engine}-screen.txt`), screen)
if (/Hooks need review/.test(screen)) await tmux('send-keys', '-t', row.tmuxPane, 'Down', 'Enter')
if (/trust this folder|trust the files|Yes, I trust|confirm.*API key/i.test(screen)) await tmux('send-keys', '-t', row.tmuxPane, 'Enter')
// Codex 0.154 defers SessionStart until the next submitted turn. First prove
// that opening alone restored visible history, then simulate user input so
// the real hook can confirm the receipt. Production never submits a prompt.
- if (engine === 'codex' && row.launch?.state === 'starting' && !submitted && hooks.length === hookCount && screen.includes(marker) && /Ask Codex/.test(screen)) {
- assert.equal(row.launch?.state, 'starting')
+ if (engine === 'codex' && needHook && !submitted && hooks.length === hookCount && screen.includes(marker) && /Ask Codex/.test(screen)) {
submitted = true
log('Codex history is visible before input; verifying its deferred native hook')
await tmux('send-keys', '-t', row.tmuxPane, '-l', 'Fixture verification only. Do not use tools.')
@@ -172,6 +177,8 @@ try {
await new Promise(r => setTimeout(r, 250))
}
assert(settled, `${engine} did not confirm: ${readFileSync(join(root, `${engine}-screen.txt`), 'utf8')}`)
+ assert(historyVisible, `${engine} did not render the saved conversation`)
+ assert(!needHook || nativeHookSeen(), `${engine} did not send its native SessionStart`)
return opening
}
const creationId = randomUUID()
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index fe61a3b66..cb0518812 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -132,7 +132,6 @@ import {
permissionModeFromArgv,
clearPaneRemainOnExit,
resolvePaneEngineProcess,
- checkSessionRuntime,
tmuxPaneState,
} from './lib/tmux.js'
import { ALL_TERMINAL_BACKENDS } from './config/terminalConfig.js'
diff --git a/cli/src/dsh/portability.integration.spec.ts b/cli/src/dsh/portability.integration.spec.ts
index 652b8dd3f..e7e464bdb 100644
--- a/cli/src/dsh/portability.integration.spec.ts
+++ b/cli/src/dsh/portability.integration.spec.ts
@@ -95,6 +95,8 @@ describe('the whole store × engine matrix', () => {
}
})
+// Each case runs several real child processes. The 5s unit-test default can expire under a full
+// suite's load even when every child succeeds; keep an explicit bounded integration-test budget.
for (const engine of PROCESS_ENGINES) it(`${engine}: prepare → spawn → tool → verdict → restart → fork`, async () => {
const dir = join(root, 'package')
write(join(dir, 'harness.json'), JSON.stringify({ spec: 1, id: 'test/portable', name: 'Portable', engine: 'claude',
@@ -142,4 +144,4 @@ for (const engine of PROCESS_ENGINES) it(`${engine}: prepare → spawn → tool
expect(fork.env.HARNESS_CONTEXT_FILE).not.toBe(launch.env.HARNESS_CONTEXT_FILE)
expect(readFileSync(join(workspace, 'scene.txt'), 'utf8')).toBe('drawn by test/portable\n')
expect((await materializeWorkspace(pkg, workspace, {}, engine)).initLines).toEqual([])
-})
+}, 15_000)
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 23692d26e..b940b4d84 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -75,7 +75,8 @@ function runHook(opts: RunHookOpts): Promise<string> {
const executable = opts.processExecutable ?? (opts.processEngine === 'cursor' ? 'agent' : opts.processEngine)
const processArgs = opts.processArgs ?? executable
writeFileSync(join(binDir, 'tmux'), '#!/bin/sh\necho 7000\n', { mode: 0o755 })
- writeFileSync(join(binDir, 'ps'), `#!/bin/sh\nprintf '%s\\n' '7000 1 zsh Mon Aug 10 10:00:00 2026 -zsh' '7001 7000 ${executable} Mon Aug 10 10:00:01 2026 ${processArgs}' '${process.pid} 7001 node Mon Aug 10 10:00:02 2026 hook-parent'\n`, { mode: 0o755 })
+ const shellQuote = (value: string) => "'" + value.replace(/'/g, "'\\''") + "'"
+ writeFileSync(join(binDir, 'ps'), `#!/bin/sh\nprintf '%s\\n' '7000 1 zsh Mon Aug 10 10:00:00 2026 -zsh' ${shellQuote(`7001 7000 ${executable} Mon Aug 10 10:00:01 2026 ${processArgs}`)} '${process.pid} 7001 node Mon Aug 10 10:00:02 2026 hook-parent'\n`, { mode: 0o755 })
if (opts.processEngine === 'cursor') {
const target = join(binDir, 'cursor-agent-target')
writeFileSync(target, '#!/bin/sh\n', { mode: 0o755 })
@@ -579,6 +580,26 @@ describe('hook notify terminal scope', () => {
}
})
+ it.each([
+ "import sys, runpy; sys.path.insert(0, '/opt/custom'); runpy.run_module('hermes_cli.main', run_name='__main__')",
+ "import os, re, sys; sys.path.insert(0, '/opt/custom'); import hermes_bootstrap; from hermes_cli.main import main; sys.exit(main())",
+ "import os, sys, runpy; os.environ.pop('PYTHONHOME', None); sys.path.insert(0, '/opt/custom'); os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or '/home/demo/.hermes'; import hermes_bootstrap; runpy.run_module('hermes_cli.main', run_name='__main__', alter_sys=True)",
+ ])('offline Hermes discovery follows a managed Python bootstrap: %s', async (source) => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-hermes-launcher-'))
+ tmpDirs.push(dir)
+ const common = {
+ port: 9, tmuxPane: '%82', engine: 'hermes' as const, processEngine: 'hermes' as const,
+ processExecutable: '/home/demo/.her', hermesHome: join(dir, 'hermes'), hermesSource: 'cli' as const,
+ input: { hook_event_name: 'on_session_start', session_id: '20260810_120000_a1b2c3' },
+ }
+ await runHook({ ...common, dataDir: join(dir, 'data'), processArgs: `/opt/python3 -I -I -c ${source}` })
+ expect(JSON.parse(readFileSync(join(dir, 'data', 'registry.json'), 'utf8'))).toMatchObject([
+ { engine: 'hermes', tmuxPane: '%82', processIdentity: { pid: 7001 } },
+ ])
+ await runHook({ ...common, dataDir: join(dir, 'unrelated'), processArgs: `python3 worker.py -c ${source}` })
+ expect(() => readFileSync(join(dir, 'unrelated', 'registry.json'), 'utf8')).toThrow()
+ })
+
it('still binds a CLI Hermes session when its store is slow to answer, as on a loaded machine', async () => {
const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-hermes-slow-'))
tmpDirs.push(dir)
diff --git a/cli/src/lib/askQuestion.spec.ts b/cli/src/lib/askQuestion.spec.ts
index 7c5c36f38..7ebe512c7 100644
--- a/cli/src/lib/askQuestion.spec.ts
+++ b/cli/src/lib/askQuestion.spec.ts
@@ -39,6 +39,42 @@ describe('shapeQuestions', () => {
})
})
+describe('question answers stay with one agent', () => {
+ const first = { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession
+ const second = { agentId: 'a2', sessionId: 's2', engine: 'claude' } as RegisteredSession
+ const getSession = (id: string) => [first, second].find((s) => s.agentId === id || s.sessionId === id)
+
+ it('refuses a remembered question redirected to another agent with the same dialog', async () => {
+ const keys: string[] = []
+ const controller = new AskQuestionController({
+ getSession, capture: async () => fixture('single'),
+ sendKey: async (target) => { keys.push(target); return true },
+ sendText: async () => true, wait: async () => {},
+ })
+ const requestId = questionRequestId('s1', asQuestion(parseQuestionPane(fixture('single'))))
+ controller.remember(requestId, 's1')
+ expect(await controller.answer({ agentId: 'a2', requestId, answers: { q: 'Tea' } }))
+ .toMatchObject({ ok: false, error: 'STALE_QUESTION' })
+ expect(keys).toEqual([])
+ })
+
+ it('serializes answers by agent even when clients use different aliases', async () => {
+ let release!: (screen: string) => void
+ const capture = new Promise<string>((resolve) => { release = resolve })
+ const controller = new AskQuestionController({
+ getSession, capture: () => capture,
+ sendKey: async () => true, sendText: async () => true,
+ })
+ const firstAnswer = controller.answer({ sessionId: 's1', answers: { q: 'Tea' } })
+ expect(controller.isDriving('a1')).toBe(true)
+ expect(await controller.answer({ agentId: 'a1', answers: { q: 'Tea' } }))
+ .toMatchObject({ ok: false, error: 'ANSWER_BUSY' })
+ release('No dialog')
+ await firstAnswer
+ expect(controller.isDriving('s1')).toBe(false)
+ })
+})
+
describe('the Hermes clarify dialog', () => {
// Real capture from hermes on a live pane: the SAME dialog Claude paints (`❯ 1. Xanh` rows, a footer
// reading "Enter to confirm") wrapped in a box-drawing frame. Peeling the frame is the whole adaptation
diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.ts
index 82f3eba00..b919afb82 100644
--- a/cli/src/lib/askQuestion.ts
+++ b/cli/src/lib/askQuestion.ts
@@ -760,7 +760,11 @@ export class AskQuestionController {
console.warn(`[question] no terminal target for ${sessionId.slice(0, 8)} — answer dropped`)
return { ok: false, error: 'AGENT_NOT_FOUND', detail: 'That agent is no longer running.' }
}
- if (this.driving.has(sessionId)) {
+ if (remembered) {
+ const owner = this.deps.getSession(remembered)
+ if ((owner?.agentId || owner?.sessionId) !== terminalTarget) return STALE_CHANGED
+ }
+ if (this.driving.has(terminalTarget)) {
console.warn(`[question] ${sessionId.slice(0, 8)} answer dropped · already driving this dialog`)
return { ok: false, error: 'ANSWER_BUSY', detail: 'Another answer is already being entered for this agent.' }
}
@@ -775,7 +779,7 @@ export class AskQuestionController {
// The ids the watcher could have announced this dialog under: the session it was remembered for, and
// the session as the registry knows it now.
const owners = [...new Set([remembered, session?.sessionId].filter((id): id is string => !!id))]
- this.driving.add(sessionId)
+ this.driving.add(terminalTarget)
try {
const result = await this.drive(terminalTarget, answers, this.deps.getSession(sessionId)?.engine ?? 'claude', payload.allowPermissions !== false, { requestId, owners }, payload.expectedQuestions ? payload : undefined)
this.pending.delete(requestId)
@@ -783,7 +787,7 @@ export class AskQuestionController {
console.log(`[question] ${sessionId.slice(0, 8)} answered from device · ${outcome} (req=${requestId || 'none'})`)
return result
} finally {
- this.driving.delete(sessionId)
+ this.driving.delete(terminalTarget)
release?.()
}
}
@@ -948,7 +952,8 @@ export class AskQuestionController {
/** True while a dialog is being keyed — the watcher pauses so a half-driven dialog isn't re-announced. */
isDriving(sessionId: string): boolean {
- return this.driving.has(sessionId)
+ const session = this.deps.getSession(sessionId)
+ return this.driving.has(session?.agentId || session?.sessionId || sessionId)
}
/** Free-text answer (a voice answer is always free text): open the "Type something." row, type, Enter. */
diff --git a/cli/src/lib/autonomous-device/direct.spec.ts b/cli/src/lib/autonomous-device/direct.spec.ts
index 4b5740b96..fc34fce0a 100644
--- a/cli/src/lib/autonomous-device/direct.spec.ts
+++ b/cli/src/lib/autonomous-device/direct.spec.ts
@@ -41,6 +41,12 @@ describe('direct Autonomous device endpoint selection', () => {
// Graceful close (not terminate) so a pair.revoke frame queued just before is flushed to the device.
await vi.waitFor(() => expect(closed).toEqual([1000]))
})
+ it('pairs a device just selected even when the next mDNS browse misses it', async () => {
+ const f = await fixture()
+ await f.direct.discover()
+ f.discovery.mockResolvedValueOnce([])
+ expect(await f.direct.pair(f.row.id, 'CODE12')).toMatchObject({ state: 'paired', fingerprint: f.fp })
+ })
it('does not persist success if PAKE identity has not authenticated its session', async () => {
const f = await fixture()
f.host.pair = async () => { for (const ws of f.wss.clients) ws.close(); return { ok: true, label: 'Device', fingerprint: 'computer' } }
diff --git a/cli/src/lib/autonomous-device/direct.ts b/cli/src/lib/autonomous-device/direct.ts
index 1a4412c42..398964132 100644
--- a/cli/src/lib/autonomous-device/direct.ts
+++ b/cli/src/lib/autonomous-device/direct.ts
@@ -56,9 +56,13 @@ export class AutonomousDeviceDirect {
this.pairing = true
let success = false
try {
+ // A single missed mDNS response must not erase the endpoint the user just selected.
+ // Fresh discovery wins when it has an address; pairing still authenticates the device.
+ const previous = this.candidates.get(device)
await this.discover()
- const candidate = this.candidates.get(device)
+ const candidate = this.candidates.get(device) ?? previous
if (!candidate) throw Object.assign(new Error('Selected device is no longer discoverable'), { code: 'DEVICE_NOT_FOUND' })
+ this.candidates.set(device, candidate)
const old = this.links.get(device); if (old) { old.ws.terminate(); this.links.delete(device) }
await this.connect(candidate, true)
const link = this.links.get(device)!
diff --git a/cli/src/lib/daemonSpawnLock.spec.ts b/cli/src/lib/daemonSpawnLock.spec.ts
index 0a5fad38e..c6b476470 100644
--- a/cli/src/lib/daemonSpawnLock.spec.ts
+++ b/cli/src/lib/daemonSpawnLock.spec.ts
@@ -3,6 +3,7 @@ import { spawn, spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
+import { processStartMarker } from './processLiveness.js'
let dataDir = ''
@@ -127,7 +128,7 @@ describe('daemon spawn lock', () => {
const lock = await loadLock()
mkdirSync(lockDir(), { mode: 0o700 })
writeFileSync(ownerFile(), JSON.stringify({
- pid: process.pid, startMarker: 'different-process-generation', token: 'stale', purpose: 'start', since: Date.now(),
+ pid: process.pid, startMarker: '', generationMarker: `${processStartMarker(process.pid)}-earlier`, token: 'stale', purpose: 'start', since: Date.now(),
}), { mode: 0o600 })
const release = await lock.acquireSpawnLock('start', { waitMs: 1000 })
expect(lock.readSpawnLockOwner()?.token).not.toBe('stale')
diff --git a/cli/src/lib/daemonSpawnLock.ts b/cli/src/lib/daemonSpawnLock.ts
index ef950f04d..c5dd5adc8 100644
--- a/cli/src/lib/daemonSpawnLock.ts
+++ b/cli/src/lib/daemonSpawnLock.ts
@@ -38,7 +38,7 @@ import {
import { randomUUID } from 'crypto'
import { join } from 'path'
import { env } from '../config/env.js'
-import { lockOwnerAlive, processStartMarker } from './processLiveness.js'
+import { lockOwnerAlive, lockStartMarker, processLockIdentity } from './processLiveness.js'
import { secureStateDirectory } from './secureState.js'
/** `login` is a forced sign-in: the daemon is stopped and the session on disk is about to change
@@ -48,6 +48,7 @@ export type SpawnLockPurpose = 'start' | 'update' | 'handoff' | 'stop' | 'login'
export interface SpawnLockOwner {
pid: number
startMarker: string
+ generationMarker?: string
token: string
purpose: SpawnLockPurpose
since: number
@@ -143,6 +144,7 @@ export function readSpawnLockOwner(): SpawnLockOwner | null {
return {
pid,
startMarker: typeof raw.startMarker === 'string' ? raw.startMarker : '',
+ generationMarker: typeof raw.generationMarker === 'string' ? raw.generationMarker : undefined,
token: raw.token,
purpose: isPurpose(raw.purpose) ? raw.purpose : 'start',
since: Number.isFinite(Number(raw.since)) ? Number(raw.since) : 0,
@@ -168,7 +170,7 @@ function tryCreate(purpose: SpawnLockPurpose): string | null {
const fd = openSync(ownerPath(), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
try {
const owner: SpawnLockOwner = {
- pid: process.pid, startMarker: processStartMarker(process.pid) ?? '', token, purpose, since: Date.now(),
+ pid: process.pid, ...processLockIdentity(process.pid), token, purpose, since: Date.now(),
}
writeFileSync(fd, JSON.stringify(owner))
fsyncSync(fd)
@@ -198,11 +200,11 @@ function releaseOwnedBy(token: string): void {
/** Remove a lock whose owner is gone — re-read first so a lock that changed hands meanwhile survives. */
function reclaimIfStale(owner: SpawnLockOwner): boolean {
- if (lockOwnerAlive(owner.pid, owner.startMarker)) return false
+ if (lockOwnerAlive(owner.pid, lockStartMarker(owner))) return false
try {
const current = readSpawnLockOwner()
- if (current && current.pid === owner.pid && current.startMarker === owner.startMarker
- && current.token === owner.token && !lockOwnerAlive(owner.pid, owner.startMarker)) {
+ if (current && current.pid === owner.pid && lockStartMarker(current) === lockStartMarker(owner)
+ && current.token === owner.token && !lockOwnerAlive(owner.pid, lockStartMarker(owner))) {
rmSync(SPAWN_LOCK_DIR, { recursive: true, force: true })
return true
}
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index c0faf66ff..c94d09eea 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -7,7 +7,7 @@ const env = { cwd: '/work/repo', home: '/home/me' }
describe('harness new: the words', () => {
it('asks nothing: claude, here, on this machine', () => {
expect(parseNewArgs([], env)).toEqual({
- agent: 'claude', machine: null, cwd: '/work/repo', projectName: null, mode: 'auto', prompt: null, name: null, json: false,
+ agent: 'claude', machine: null, cwd: '/work/repo', projectName: null, mode: 'auto', modeGiven: false, prompt: null, name: null, json: false,
})
})
@@ -65,6 +65,23 @@ describe('harness new: the words', () => {
expect(newAgentPayload(parseNewArgs(['acme/blender', '.'], env), '/work/repo', 'codex')).toMatchObject({ engine: 'codex', dsh: 'acme/blender' })
})
+ it('only sends a permission mode to the engines that take one', () => {
+ // The engines with no PERMISSION_MODES row cannot be handed the default `auto`: the daemon refuses
+ // a mode the engine has no contract for (INVALID_PERMISSION_MODE), which made `harness new hermes`
+ // — and pi, amp, muse, kilo, grok, devin, commandcode, agy, copilot — impossible to run at all.
+ for (const agent of ['hermes', 'pi', 'amp', 'muse', 'kilo', 'grok', 'devin', 'commandcode', 'agy', 'copilot']) {
+ const payload = newAgentPayload(parseNewArgs([agent], env), '/work/repo')
+ expect(payload, agent).toMatchObject({ engine: agent, bypassPermission: false })
+ expect(payload, agent).not.toHaveProperty('permissionMode')
+ }
+ // An engine that has the mode still gets it, and the store harness is judged on the engine it runs on.
+ expect(newAgentPayload(parseNewArgs(['opencode'], env), '/work/repo')).toMatchObject({ permissionMode: 'auto', bypassPermission: true })
+ expect(newAgentPayload(parseNewArgs(['acme/blender'], env), '/work/repo', 'hermes')).not.toHaveProperty('permissionMode')
+ // A mode the person typed stays theirs to get wrong: the daemon refuses it, it is not silently swapped.
+ expect(newAgentPayload(parseNewArgs(['hermes', '--mode', 'ask'], env), '/work/repo')).toMatchObject({ engine: 'hermes', permissionMode: 'ask', bypassPermission: false })
+ expect(newAgentPayload(parseNewArgs(['hermes', '--plan'], env), '/work/repo')).toMatchObject({ engine: 'hermes', permissionMode: 'plan', bypassPermission: false })
+ })
+
it('finds the machine by id, name or an unambiguous start of one', () => {
const machines = [
{ machineId: 'm1', label: 'Mac mini', status: 'online', current: false },
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index b62a2c68f..8fb68de37 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -1,6 +1,11 @@
import { randomUUID } from 'node:crypto'
import { isAbsolute, join, resolve } from 'node:path'
+import { ENGINES, type AgentEngine } from '../engines/types.js'
import { projectFolderSlug } from './agentNames.js'
+import { permissionModeFlags } from './engineLaunch.js'
+
+/** Engine names, so an unknown word is judged rather than cast (the shape `registry.ts` uses). */
+const ENGINE_NAMES: ReadonlySet<string> = new Set(ENGINES)
/**
* `harness new` — make a harness from a shell, in the words the app's box uses:
@@ -26,6 +31,9 @@ export interface NewArgs {
/** A new project: its name, or '' to let the clock name it; null when `cwd` is given. */
projectName: string | null
mode: string
+ /** True when `--mode`/`--plan` was typed by the person. The default `auto` is not a request: see
+ * [newAgentPayload]. */
+ modeGiven: boolean
prompt: string | null
name: string | null
json: boolean
@@ -65,6 +73,7 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string })
let folder: string | null = null
let projectName: string | null = null
let mode = 'auto'
+ let modeGiven = false
let prompt: string | null = null
let name: string | null = null
let json = false
@@ -83,8 +92,8 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string })
break
}
if (word === '--json') json = true
- else if (word === '--plan') mode = 'plan'
- else if (word === '--mode') { mode = value(word, i); i++ }
+ else if (word === '--plan') { mode = 'plan'; modeGiven = true }
+ else if (word === '--mode') { mode = value(word, i); modeGiven = true; i++ }
else if (word === '--prompt' || word === '--task') { prompt = value(word, i); i++ }
else if (word === '--name') { name = value(word, i); i++ }
else if (word === '--new') {
@@ -132,7 +141,7 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string })
if (machine === null) cwd = env.cwd
else projectName = ''
}
- return { agent: words[0] ?? 'claude', machine, cwd, projectName, mode, prompt, name, json }
+ return { agent: words[0] ?? 'claude', machine, cwd, projectName, mode, modeGiven, prompt, name, json }
}
/** The `agent_create` payload for [args]: the same fields the app's box sends. [baseEngine] is the
@@ -141,15 +150,29 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string })
export function newAgentPayload(args: NewArgs, cwd: string | null, baseEngine = 'claude'): Record<string, unknown> {
const harness = args.agent.includes('/') ? args.agent : null
const terminal = args.agent === 'terminal'
+ const engine = harness ? baseEngine : args.agent
+ // A mode is only an engine's to take. The usage says `--mode` applies "where the agent has it", but
+ // the default `auto` went to every engine, and the daemon refuses a mode an engine has no
+ // `PERMISSION_MODES` row for (`INVALID_PERMISSION_MODE` in backendSocket.ts) — so the ten engines
+ // without a row (hermes, pi, amp, muse, kilo, grok, devin, commandcode, agy, copilot) could not be
+ // created from the CLI at all, and neither could a store harness running on one of them.
+ // An unasked-for default is therefore left out: the engine opens in its own default mode. A mode the
+ // person typed is still sent, so the daemon's refusal — "refused rather than quietly launched in
+ // some other mode" — stays the answer where a choice was actually made.
+ const hasMode = ENGINE_NAMES.has(engine) && permissionModeFlags(engine as AgentEngine, args.mode) !== null
+ const mode = args.modeGiven || hasMode ? args.mode : null
+ // A row that keeps claiming Auto while running without the flag is the more expensive lie, so the
+ // bypass is only claimed where the engine really has the mode it was asked for.
+ const approves = mode !== null && (mode === 'auto' || mode === 'full') && hasMode
return {
- engine: harness ? baseEngine : args.agent,
+ engine,
...(harness ? { dsh: harness } : {}),
...(cwd !== null ? { cwd } : terminal ? {} : {
projectSource: 'new',
...(args.projectName ? { projectName: projectFolderSlug(args.projectName) } : {}),
}),
- bypassPermission: !terminal && (args.mode === 'auto' || args.mode === 'full'),
- ...(terminal ? {} : { permissionMode: args.mode }),
+ bypassPermission: !terminal && approves,
+ ...(terminal || mode === null ? {} : { permissionMode: mode }),
...(args.prompt ? { prompt: args.prompt } : {}),
...(args.name ? { name: args.name } : {}),
creationId: randomUUID(),
diff --git a/cli/src/lib/processLiveness.spec.ts b/cli/src/lib/processLiveness.spec.ts
new file mode 100644
index 000000000..659e9a08a
--- /dev/null
+++ b/cli/src/lib/processLiveness.spec.ts
@@ -0,0 +1,80 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { runInNewContext } from 'node:vm'
+import { psEnv } from './childLocale.js'
+
+const mocks = vi.hoisted(() => ({ read: vi.fn(), exec: vi.fn() }))
+vi.mock('fs', () => ({ readFileSync: mocks.read }))
+vi.mock('node:child_process', () => ({ execFileSync: mocks.exec }))
+
+import { lockOwnerAlive, lockStartMarker, processLockIdentity, processStartMarker } from './processLiveness.js'
+
+const { readFileSync } = await vi.importActual<typeof import('node:fs')>('node:fs')
+const hook = readFileSync(new URL('../../hook/notify.mjs', import.meta.url), 'utf8')
+const hookFunctions = hook.slice(hook.indexOf('function processStartMarker('), hook.indexOf('async function withRegistryLock('))
+const hookApi = runInNewContext(`${hookFunctions}; ({ processStartMarker, lockOwnerAlive: processAlive, processLockIdentity, lockStartMarker })`, {
+ readFileSync: mocks.read, execFileSync: mocks.exec, process, psEnv,
+}) as { processStartMarker: typeof processStartMarker; lockOwnerAlive: typeof lockOwnerAlive;
+ processLockIdentity: typeof processLockIdentity; lockStartMarker: typeof lockStartMarker }
+
+describe.each([
+ ['daemon', { processStartMarker, lockOwnerAlive, processLockIdentity, lockStartMarker }],
+ ['offline hook', hookApi],
+] as const)('%s lock generations', (_, api) => {
+ beforeEach(() => {
+ mocks.read.mockReset().mockImplementation(() => { throw new Error('No /proc') })
+ mocks.exec.mockReset().mockImplementation((_cmd, _args, options) =>
+ options.env?.LC_TIME === 'C' && options.env?.LC_ALL === '' && options.env?.TZ === 'UTC'
+ ? 'Sun Sep 27 20:00:00 2026\n'
+ : 'Sun 27 Sep 20:00:00 2026\n')
+ })
+
+ it('writes the same versioned timestamp under different caller locales', () => {
+ const original = process.env.LC_ALL
+ try {
+ for (const locale of ['en_GB.UTF-8', 'ja_JP.UTF-8', 'C']) {
+ process.env.LC_ALL = locale
+ expect(api.processStartMarker(process.pid)).toBe('ps-c:Sun Sep 27 20:00:00 2026')
+ }
+ } finally {
+ if (original === undefined) delete process.env.LC_ALL
+ else process.env.LC_ALL = original
+ }
+ })
+
+ it('preserves a live legacy or unknown lock across an upgrade', () => {
+ expect(api.lockOwnerAlive(process.pid, 'ps:Sun 27 Sep 20:00:00 2026')).toBe(true)
+ expect(api.lockOwnerAlive(process.pid, 'future-format:123')).toBe(true)
+ })
+
+ it('writes locks that old readers cannot steal under either locale', () => {
+ const owner = api.processLockIdentity(process.pid)
+ for (const legacyMarker of ['ps:Sun Sep 27 20:00:00 2026', 'ps:Sun 27 Sep 20:00:00 2026']) {
+ // The pre-migration reader's condition after its PID existence check.
+ expect(!owner.startMarker || legacyMarker === owner.startMarker).toBe(true)
+ }
+ expect(api.lockOwnerAlive(process.pid, api.lockStartMarker(owner))).toBe(true)
+ expect(api.lockOwnerAlive(process.pid, api.lockStartMarker({ ...owner,
+ generationMarker: 'ps-c:Sun Sep 27 19:00:00 2026' }))).toBe(false)
+ expect(api.lockStartMarker({ startMarker: 'ps:legacy' })).toBe('ps:legacy')
+ })
+
+ it('still detects process generation changes in comparable markers', () => {
+ expect(api.lockOwnerAlive(process.pid, 'ps-c:Sun Sep 27 20:00:00 2026')).toBe(true)
+ expect(api.lockOwnerAlive(process.pid, 'ps-c:Sun Sep 27 19:00:00 2026')).toBe(false)
+ })
+
+ it('uses Linux start ticks when proc is readable', () => {
+ mocks.read.mockReturnValue(`123 (name with ) parens) ${Array(19).fill('0').join(' ')} 456 0`)
+ expect(api.processStartMarker(process.pid)).toBe('linux:456')
+ expect(api.lockOwnerAlive(process.pid, 'linux:456')).toBe(true)
+ expect(api.lockOwnerAlive(process.pid, 'linux:455')).toBe(false)
+ expect(mocks.exec).not.toHaveBeenCalled()
+ })
+
+ it('does not reclaim a live owner when its timestamp is unreadable', () => {
+ mocks.exec.mockImplementation(() => { throw new Error('Process query failed') })
+ expect(api.lockOwnerAlive(process.pid, 'ps-c:Sun Sep 27 20:00:00 2026')).toBe(true)
+ expect(api.lockOwnerAlive(999_999_999, 'ps:legacy')).toBe(false)
+ expect(api.processStartMarker(-1)).toBeNull()
+ })
+})
diff --git a/cli/src/lib/processLiveness.ts b/cli/src/lib/processLiveness.ts
index e6c01f7c3..788e427ec 100644
--- a/cli/src/lib/processLiveness.ts
+++ b/cli/src/lib/processLiveness.ts
@@ -11,6 +11,7 @@
import { readFileSync } from 'fs'
import { execFileSync } from 'node:child_process'
+import { psEnv } from './childLocale.js'
export function processExists(pid: number): boolean {
if (!Number.isSafeInteger(pid) || pid <= 0) return false
@@ -28,15 +29,38 @@ export function processStartMarker(pid: number): string | null {
} catch { /* non-Linux or exited process; use ps below */ }
try {
const started = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
- encoding: 'utf8', timeout: 1_000,
+ encoding: 'utf8', timeout: 1_000, env: { ...psEnv(), TZ: 'UTC' },
}).trim()
- return started ? `ps:${started}` : null
+ return started ? `ps-c:${started}` : null
} catch { return null }
}
+export interface LockGeneration {
+ startMarker?: unknown
+ generationMarker?: unknown
+}
+
+/** Older readers compare every nonempty marker literally. Leave their field empty for the new
+ * locale-pinned format so they use PID liveness during an upgrade, never steal a live new lock.
+ * New readers retain PID-reuse detection through the separate versioned field. */
+export function processLockIdentity(pid: number): { startMarker: string; generationMarker: string } {
+ const generationMarker = processStartMarker(pid) ?? ''
+ return { startMarker: generationMarker.startsWith('ps-c:') ? '' : generationMarker, generationMarker }
+}
+
+export function lockStartMarker(owner: LockGeneration | null | undefined): string {
+ return typeof owner?.generationMarker === 'string' ? owner.generationMarker
+ : typeof owner?.startMarker === 'string' ? owner.startMarker : ''
+}
+
export function lockOwnerAlive(pid: number, startMarker: string): boolean {
if (!processExists(pid)) return false
if (!startMarker) return true
const current = processStartMarker(pid)
- return current === null || current === startMarker
+ // Legacy ps markers inherited the writer's locale. They cannot be compared
+ // safely with a new reader's timestamp; keep that live owner until it exits.
+ const comparable = current !== null && ['linux:', 'ps-c:'].some(
+ (prefix) => startMarker.startsWith(prefix) && current.startsWith(prefix),
+ )
+ return !comparable || current === startMarker
}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 9a9daa116..b03bf0d8a 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
+import { processStartMarker } from './processLiveness.js'
import type { AgentEngine } from '../engines/types.js'
import type { ProcessIdentity, RegisteredSession, RegisterInput } from './registry.js'
@@ -364,7 +365,7 @@ describe('registry remote display names', () => {
mkdirSync(lockDir, { mode: 0o700 })
writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({
pid: process.pid,
- startMarker: 'different-process-generation',
+ startMarker: '', generationMarker: `${processStartMarker(process.pid)}-earlier`,
token: 'stale-owner',
}), { mode: 0o600 })
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 832a22185..8beb4b82d 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -47,7 +47,7 @@ import { parseGridLaunchOverride, type GridLaunchOverride, type GridLaunchRecord
import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'
import { agyTranscriptPath } from '../engines/agy/session.js'
import { copilotTranscriptPath } from '../engines/copilot/session.js'
-import { lockOwnerAlive, processStartMarker } from './processLiveness.js'
+import { lockOwnerAlive, lockStartMarker, processLockIdentity } from './processLiveness.js'
import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
import { mergeTerminalRuntimes, processIdentityKey, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
import type { HookTerminalHint, ProcessIdentity, TerminalRuntimeRef } from './terminalTypes.js'
@@ -365,7 +365,7 @@ function removeRegistryLockOwnedBy(token: string): void {
function withRegistryFileLock<T>(apply: () => T): T {
secureStateDirectory(env.ADAPTER_DATA_DIR)
const uid = typeof process.getuid === 'function' ? process.getuid() : null
- const processMarker = processStartMarker(process.pid) ?? ''
+ const processIdentity = processLockIdentity(process.pid)
for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt++) {
const token = randomUUID()
let created = false
@@ -375,7 +375,7 @@ function withRegistryFileLock<T>(apply: () => T): T {
const owner = join(LOCK_DIR, 'owner.json')
const fd = openSync(owner, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
try {
- writeFileSync(fd, JSON.stringify({ pid: process.pid, startMarker: processMarker, token }))
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, ...processIdentity, token }))
fsyncSync(fd)
} finally { closeSync(fd) }
try {
@@ -397,10 +397,10 @@ function withRegistryFileLock<T>(apply: () => T): T {
if (!ownerStat.isFile() || ownerStat.isSymbolicLink() || (uid !== null && ownerStat.uid !== uid)
|| (ownerStat.mode & 0o777) !== 0o600) throw new Error('registry lock owner has unsafe owner, mode, or type')
const owner = JSON.parse(readFileSync(join(LOCK_DIR, 'owner.json'), 'utf8')) as {
- pid?: unknown; startMarker?: unknown; token?: unknown
+ pid?: unknown; startMarker?: unknown; generationMarker?: unknown; token?: unknown
}
ownerPid = Number(owner.pid)
- ownerStartMarker = typeof owner.startMarker === 'string' ? owner.startMarker : ''
+ ownerStartMarker = lockStartMarker(owner)
ownerToken = typeof owner.token === 'string' ? owner.token : ''
} catch (inspectionError) {
if (inspectionError instanceof Error && inspectionError.message.startsWith('registry lock')) throw inspectionError
@@ -408,10 +408,10 @@ function withRegistryFileLock<T>(apply: () => T): T {
if (ownerPid > 0 && ownerToken && !lockOwnerAlive(ownerPid, ownerStartMarker)) {
try {
const current = JSON.parse(readFileSync(join(LOCK_DIR, 'owner.json'), 'utf8')) as {
- pid?: unknown; startMarker?: unknown; token?: unknown
+ pid?: unknown; startMarker?: unknown; generationMarker?: unknown; token?: unknown
}
if (Number(current.pid) === ownerPid
- && current.startMarker === ownerStartMarker
+ && lockStartMarker(current) === ownerStartMarker
&& current.token === ownerToken
&& !lockOwnerAlive(ownerPid, ownerStartMarker)) {
rmSync(LOCK_DIR, { recursive: true, force: true })
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index 6b4a4ed85..45b465122 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -111,9 +111,22 @@ describe('production resume handler', () => {
// muse never hooks, so nothing else would ever leave this row `starting` — it would read as
// "Starting" for ever and keep discovery out of the pane.
rewrite({ engine: 'muse' })
+ vi.mocked(resolvePaneEngineProcess).mockResolvedValue(identity)
expect(await start()).toMatchObject({ ok: true, session: { launch: { state: 'ready' } } })
})
+ it('persists the verified process before announcing a resume that has no hook yet', async () => {
+ // A process probe only reads. The ordinary fixture also imitates discovery, which used to
+ // hide a ready row with no process identity until the next reconcile or SessionStart hook.
+ vi.mocked(resolvePaneEngineProcess).mockResolvedValue(identity)
+ const result = await start()
+ expect(result).toMatchObject({ ok: true, session: { processIdentity: identity, launch: { state: 'ready' } } })
+ expect(registry.byAgent(saved.agentId)?.processIdentity).toEqual(identity)
+ expect(deps.announceSession).toHaveBeenLastCalledWith(expect.objectContaining({ processIdentity: identity }))
+ registry.load()
+ expect(registry.byAgent(saved.agentId)?.processIdentity).toEqual(identity)
+ })
+
it('opens a retained terminal as a new shell without a vendor resume argument', async () => {
rewrite({ engine: 'terminal', sessionId: '', transcriptPath: '' })
expect(await start()).toMatchObject({ ok: true, resumed: true, session: { engine: 'terminal', launch: { state: 'ready' } } })
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index 1d449a305..859f79fe6 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -17,7 +17,7 @@ import type { LaunchOverrides, LaunchOverridesResult } from './launchOverrides.j
import type { AgentRestartCoordinator } from './restartAgent.js'
export interface ResumeAgentServiceDeps {
- registry: Pick<typeof liveRegistry, 'byAgent' | 'bySession' | 'resumePendingAgent' | 'setLaunch'>
+ registry: Pick<typeof liveRegistry, 'byAgent' | 'bySession' | 'resumePendingAgent' | 'setLaunch' | 'updateProcessIdentity'>
stoppedAgents: StoppedAgentStore
tmuxBackend: CreateAgentPaneDeps['tmuxBackend'] | null
restartJobs: AgentRestartCoordinator
@@ -83,6 +83,10 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
})
if (!ownsRoute()) return resumeChanged
if (result.ok) {
+ // A probe proves the new PID but does not publish it. Persist that proof before readiness;
+ // an engine whose hook is delayed or absent must still be attachable and stoppable now.
+ if (!result.session.processIdentity
+ || !registry.updateProcessIdentity(saved.agentId, result.session.processIdentity)) return resumeChanged
await clearPaneRemainOnExit(saved.tmuxPane)
if (!ownsRoute()) return resumeChanged
stoppedAgents.finishResume(saved.agentId)
@@ -93,11 +97,12 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
// asking WHICH proof confirmed it got that wrong in both directions, so ask the row instead.
const confirmed = registry.byAgent(saved.agentId)
const ready = confirmed?.launch?.state === 'ready'
- ? result.session
+ ? confirmed
: registry.setLaunch(saved.agentId, { state: 'ready' }) ?? result.session
console.log(`[resume] ${sid(saved.agentId)} confirmed · engine=${saved.engine}`
+ ` · hook=${(confirmed?.lastHookAt ?? 0) > 0 ? 'yes' : 'no'} · ${result.resumed ? 'same conversation' : 'fresh'}`)
announceSession(ready)
+ return { ...result, session: ready }
} else if (result.error !== 'AGENT_CHANGED') {
const row = registry.byAgent(saved.agentId)!
const failed = registry.setLaunch(row.agentId, { state: 'failed', error: result.error, detail: result.detail })
diff --git a/cli/src/lib/resumeStoppedAgent.ts b/cli/src/lib/resumeStoppedAgent.ts
index c874e7504..ae7d82d82 100644
--- a/cli/src/lib/resumeStoppedAgent.ts
+++ b/cli/src/lib/resumeStoppedAgent.ts
@@ -120,7 +120,7 @@ export async function waitForResumedAgent(saved: RegisteredSession, deps: Resume
// the person could type in — with `active` cleared and the desk refusing to open it, the cost of
// the strict rule was never the resume, it was the harness. A resume that reopened the WRONG
// conversation is still caught, by `registry.register`'s mismatch guard, when the hook arrives.
- if (process) return { ok: true, session: row, resumed: resumesConversation(saved.engine, saved.sessionId) }
+ if (process) return { ok: true, session: { ...row, processIdentity: process }, resumed: resumesConversation(saved.engine, saved.sessionId) }
await deps.sleep(250)
}
return resumeUnconfirmed
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index 4aebaf675..bf085505c 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -250,6 +250,25 @@ describe('tmux process primitives', () => {
expect(engineProcessMatchScore({ executable: comm, args: `${python} -m hermes_cli.main` }, 'hermes')).toBe(2)
})
+ it('recognizes managed Hermes runpy launchers without relying on their install directory', () => {
+ const bootstrap = "import os, sys, runpy; os.environ.pop('PYTHONHOME', None); os.environ.pop('PYTHONPATH', None); os.environ.pop('VIRTUAL_ENV', None); sys.path.insert(0, '/opt/custom install'); os.environ['HERMES_HOME'] = os.environ.get('HERMES_HOME') or str(__import__('hermes_constants').get_default_hermes_root()); import hermes_bootstrap; runpy.run_module('hermes_cli.main', run_name='__main__', alter_sys=True)"
+ const old = "import sys, runpy; sys.path.insert(0, '/opt/hermes-agent'); runpy.run_module('hermes_cli.main', run_name='__main__')"
+ for (const code of [bootstrap, old]) {
+ for (const source of [code, `\"${code}\"`]) {
+ expect(engineProcessMatchScore({ executable: '/home/demo/.her', args: `/opt/python3.14 -I -I -c ${source} --resume 20260927_101500_ab12cd` }, 'hermes')).toBe(2)
+ }
+ }
+ for (const args of [
+ `python3 worker.py -c ${bootstrap}`,
+ `node -c ${bootstrap}`,
+ `python3 -c print(\"${bootstrap}\")`,
+ `python3 -c ${bootstrap.replace('hermes_cli.main', 'acp_adapter.entry')}`,
+ "python3 -c import sys; sys.path.insert(0, '/opt/hermes-agent'); print('from hermes_cli.main import main')",
+ ]) {
+ expect(engineProcessMatchScore({ executable: 'python3', args }, 'hermes')).toBe(0)
+ }
+ })
+
it('reads an engine through the ori launcher, before and after its exec', () => {
// `ori claude` computes an environment and then execve's the vendor binary away, so for all but the
// first ~100ms the pane row IS `claude` — that case must keep scoring exactly as a bare launch does.
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index a2b0dff6f..707454d8b 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -116,36 +116,29 @@ function hasCursorPackageEntrypoint(args: string): boolean {
/cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/i.test(token))
}
-/**
- * Hermes launches itself as inline source, so its argv names no script at all.
- *
- * `~/.hermes/hermes-agent/.hermes/bin/hermes` is a `sh` stub that `exec`s Hermes' own vendored
- * interpreter with the whole launcher as `-c` text:
- *
- * ~/.hermes/tools/python-3.14.7+20260901-darwin-arm64/bin/python3 -I -c 'import os, re, sys
- * …sys.path.insert(0, "<root>/hermes-agent")…from hermes_cli.main import main…sys.exit(main())'
- *
- * The stub is exec'd away, so `comm` is `python3`, and `processEntrypoint` correctly refuses to read
- * inline source as an entrypoint — nothing on this row carries the engine's name anywhere the matcher
- * looks. Measured on 0.21.5+2144.g7b761da: a New Harness pane was retained six seconds after starting
- * ("engine process absent after 2 confirmed scans") over a Hermes that was running and drawing its
- * dashboard, and selecting it again spent the whole readiness budget before RESUME_UNCONFIRMED.
- *
- * BOTH markers are required, and each rules out a different false positive. The sys.path root alone is
- * also in `hermes-acp`, the other stub in that bin, identical but for `from acp_adapter.entry import
- * main` — an ACP adapter is not the harness's engine. The `hermes_cli` import alone is a word that
- * could appear in a prompt; a prompt is not python source that has also just put Hermes' own package
- * root on the path. Together they are the launcher and nothing else, wherever HERMES_HOME puts it.
- */
+/** Hermes' managed launchers exec Python -I -c with a path bootstrap, then either import main
+ * or run it through runpy. Require that executable prefix and actual code, never a script argument
+ * or a quoted mention. argv[0] is authoritative here: macOS can truncate an absolute `comm` path.
+ * Keep the standalone hook's copy in sync. */
function hermesInlineLauncher(row: Pick<ProcessRow, 'args'>): boolean {
- // argv[0], not `comm`: macOS prints comm through a 16-column field here, so every absolute path
- // can reach this parser as a truncated home directory, not the interpreter executable.
- const tokens = argvTokens(row.args)
- if (!/^python(?:\d+(?:\.\d+)*)?$/.test(basename(tokens[0] ?? '').toLowerCase())) return false
- const inline = row.args.search(/\s-(?:c|-command)\s/)
- if (inline < 0) return false
- const source = row.args.slice(inline)
- return /[\/\\]hermes-agent['"]/.test(source) && /\b(?:from|import)\s+hermes_cli\b/.test(source)
+ const args = row.args.trim()
+ if (!/^python(?:\d+(?:\.\d+)*)?$/.test(basename(argvTokens(args)[0] ?? '').toLowerCase())) return false
+ const prefix = /^(?:"[^"]+"|'[^']+'|\S+)(?:\s+-(?:I|E|s|S|u|B|O{1,2}|q))*\s+-c\s+/.exec(args)
+ if (!prefix) return false
+ const source = args.slice(prefix[0].length).replace(/^["']/, '')
+ // Mask string literals before looking for Python statements. A print/prompt containing a whole
+ // launcher is still data. Keep literal values only to identify runpy's exact entry module.
+ const literals: string[] = []
+ const code = source.replace(/(['"])(?:\\[\s\S]|(?!\1)[^\\])*?\1/g, (literal) => {
+ literals.push(literal.slice(1, -1))
+ return `__literal${literals.length - 1}__`
+ })
+ if (!/^import\s+(?:(?:os|re|sys|runpy)\s*,\s*)*(?:sys|runpy)[;\s]+(?:os\.environ\.pop\(__literal\d+__,\s*None\)[;\s]+)*sys\.path\.insert\(\s*0,\s*__literal\d+__\s*\)/.test(code)) return false
+ if (/\bimport\s+hermes_bootstrap\b/.test(code)
+ && /\bfrom\s+hermes_cli\.main\s+import\s+main\b/.test(code)
+ && /\bsys\.exit\(\s*main\(\)\s*\)/.test(code)) return true
+ const run = /\brunpy\.run_module\(\s*__literal(\d+)__\s*,\s*run_name\s*=\s*__literal(\d+)__(?:\s*,\s*alter_sys\s*=\s*True)?\s*\)/.exec(code)
+ return !!run && literals[Number(run[1])] === 'hermes_cli.main' && literals[Number(run[2])] === '__main__'
}
function agentAliasCandidate(row: Pick<ProcessRow, 'executable' | 'args'>): boolean {
@@ -160,7 +153,7 @@ function agentAliasCandidate(row: Pick<ProcessRow, 'executable' | 'args'>): bool
* `comm` can itself contain spaces: Command Code rewrites its argv to `⌘ <session title>` and macOS
* prints that verbatim as the command name. Splitting comm off as a single `\S+` therefore shifted every
* later field — `startMarker` came out as `"<rest of title> Thu Jul 30"` instead of a start time, so it
- * changed whenever Command Code renamed the session, `validateSessionRuntime` saw a different process,
+ * changed whenever Command Code renamed the session, runtime validation saw a different process,
* and the reaper evicted a live pane ~10s after its first turn (observed four times on one session; the
* pane went on serving turn-stop hooks after being declared "gone"). It also silently defeated the
* PID-reuse guard that startMarker exists for.
@@ -747,7 +740,7 @@ type PaneProcessLookup =
| { ok: true; identity: ProcessIdentity }
| { ok: false; unknown: boolean; reason: string }
-async function lookupPaneEngineProcess(
+export async function lookupPaneEngineProcess(
pane: string,
engine: RegisteredSession['engine'],
): Promise<PaneProcessLookup> {
@@ -845,11 +838,6 @@ export async function resolvePaneEngineProcess(
export const LSTART_MARKER_RE =
/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}\s+\d{1,2}:\d{2}:\d{2}\s+\d{4}$/
-/** Pane + engine process validation. A saved identity prevents PID reuse from reviving a stale entry. */
-export async function validateSessionRuntime(session: RegisteredSession): Promise<boolean> {
- return (await checkSessionRuntime(session)).state === 'alive'
-}
-
/**
* The same check, but three-valued and with a reason — the reaper needs both.
*
diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.ts
index 30cb34688..1045ce6fc 100644
--- a/cli/src/lib/tmuxAgentDiscovery.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts
@@ -41,6 +41,7 @@ describe('tmux process agent snapshot discovery', () => {
['opencode', 'opencode', 'opencode'],
['pi', 'pi', 'pi'],
['hermes', 'python', '/opt/hermes-agent/hermes'],
+ ['hermes', 'python3', "python3 -I -I -c import sys, runpy; sys.path.insert(0, '/opt/custom'); runpy.run_module('hermes_cli.main', run_name='__main__')"],
['commandcode', '⌘ Project', '⌘ Project'],
['devin', 'devin', 'devin'],
['muse', 'muse-bin-1.2.3', 'muse-bin-1.2.3'],
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index 7c0315f44..f8127859c 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -14,6 +14,17 @@ afterEach(() => {
})
describe('TmuxBackend lifecycle', () => {
+ it.each(['tmux', 'ps'] as const)('does not declare a running pane gone when the %s probe fails', async failed => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-probe-'))
+ dirs.push(dir)
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh\n${failed === 'tmux' ? 'exit 1' : 'echo 12345'}\n`, { mode: 0o700 })
+ writeFileSync(join(dir, 'ps'), '#!/bin/sh\nexit 1\n', { mode: 0o700 })
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ expect(await new TmuxBackend().validate({ backend: 'tmux', paneId: '%42' }, {
+ engine: 'claude', processIdentity: { pid: 12345, executable: 'claude', startMarker: 'Sun Sep 27 20:00:00 2026' },
+ })).toMatchObject({ state: 'unknown' })
+ })
+
it('creates a detached session and closes only its exact pane', async () => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-lifecycle-'))
dirs.push(dir)
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index af3635d36..fda7aa994 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -25,7 +25,7 @@ import {
ENGINE_EXIT_PANE_OPTION,
listPaneTitles,
LSTART_MARKER_RE,
- resolvePaneEngineProcess,
+ lookupPaneEngineProcess,
sendKeyToTmux,
sendLiteralToTmux,
sendToTmux,
@@ -315,17 +315,17 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
async validate(runtime: TmuxRuntimeRef, expected: TerminalProcessExpectation): Promise<RuntimeValidation> {
try {
- const live = await resolvePaneEngineProcess(runtime.paneId, expected.engine)
- if (!live) return { state: 'gone', reason: `no ${expected.engine} process under tmux pane` }
+ const found = await lookupPaneEngineProcess(runtime.paneId, expected.engine)
+ if (!found.ok) return { state: found.unknown ? 'unknown' : 'gone', reason: found.reason }
+ const live = found.identity
// A saved marker that is not a C-locale `lstart` stamp was written either by the pre-fix parser,
// with its fields shifted, or by a `ps` that still inherited the user's LC_TIME (see psEnv in
// lib/childLocale.ts). Either way it can never equal the corrected stamp for the same live
// process, so comparing it would report a running engine as gone — once, on the upgrade that
// fixed the reading. The pane still has a matching engine process; take it.
//
- // checkSessionRuntime makes the same allowance, but nothing calls that function today, so this
- // is where the allowance has to live: coordinator.validate/acquireLease pass the PERSISTED
- // identity straight through to here.
+ // Resume's checkSessionRuntime makes the same allowance. The coordinator passes persisted
+ // identities directly here when validating or acquiring a terminal lease.
if (expected.processIdentity && !LSTART_MARKER_RE.test(expected.processIdentity.startMarker)) {
return { state: 'alive' }
}
diff --git a/cli/src/lib/tmuxBackendValidate.spec.ts b/cli/src/lib/tmuxBackendValidate.spec.ts
index 982ff5f2c..cccd7e84d 100644
--- a/cli/src/lib/tmuxBackendValidate.spec.ts
+++ b/cli/src/lib/tmuxBackendValidate.spec.ts
@@ -1,7 +1,7 @@
/**
* `validate` is the live path: `terminals.validate` / `acquireLease` hand it the identity PERSISTED in
* the registry, so it is the one place a marker written by an older CLI is compared against one read
- * today. `checkSessionRuntime` makes the same allowance, but nothing calls it.
+ * today. Resume's `checkSessionRuntime` makes the same allowance.
*
* Own file, and one narrowly-mocked import, because the sibling `tmuxBackend.spec.ts` drives the real
* binary through stub `tmux`/`ps` scripts on PATH — the wrong instrument for asserting which branch of
@@ -9,10 +9,10 @@
*/
import { describe, expect, it, vi } from 'vitest'
-const resolvePaneEngineProcess = vi.hoisted(() => vi.fn())
+const lookupPaneEngineProcess = vi.hoisted(() => vi.fn())
vi.mock('./tmux.js', async (importOriginal) => ({
...(await importOriginal<typeof import('./tmux.js')>()),
- resolvePaneEngineProcess,
+ lookupPaneEngineProcess,
}))
const { TmuxBackend } = await import('./tmuxBackend.js')
@@ -23,7 +23,7 @@ const LIVE = { pid: 15160, executable: '/Users/admin/.local/bin/claude', startMa
describe('TmuxBackend.validate and the pre-psEnv start marker', () => {
it('keeps a pane whose saved marker was written under the user own LC_TIME', async () => {
- resolvePaneEngineProcess.mockResolvedValue(LIVE)
+ lookupPaneEngineProcess.mockResolvedValue({ ok: true, identity: LIVE })
// hu_HU parsed fine before psEnv landed, so a marker like this is on disk for real users. It can
// never equal the C-locale stamp above, and comparing it would report a running engine as gone.
const saved = { ...LIVE, startMarker: 'K szept. 15 23:10:38 2026' }
@@ -34,7 +34,7 @@ describe('TmuxBackend.validate and the pre-psEnv start marker', () => {
})
it('keeps a pane whose saved marker came from the shifted pre-fix parser', async () => {
- resolvePaneEngineProcess.mockResolvedValue(LIVE)
+ lookupPaneEngineProcess.mockResolvedValue({ ok: true, identity: LIVE })
const saved = { ...LIVE, startMarker: 'Greeting Thu Jul 30 11:00:03 2026' }
expect((await new TmuxBackend().validate(PANE, { engine: 'claude', processIdentity: saved })).state)
@@ -42,7 +42,7 @@ describe('TmuxBackend.validate and the pre-psEnv start marker', () => {
})
it('still evicts a pane whose engine really was replaced', async () => {
- resolvePaneEngineProcess.mockResolvedValue(LIVE)
+ lookupPaneEngineProcess.mockResolvedValue({ ok: true, identity: LIVE })
// A C-locale stamp IS comparable, so a genuine difference must still count — the allowance above
// must not become a hole in the PID-reuse guard.
const saved = { ...LIVE, pid: 999, startMarker: 'Mon Sep 14 08:00:00 2026' }
@@ -55,7 +55,7 @@ describe('TmuxBackend.validate and the pre-psEnv start marker', () => {
})
it('reports an empty pane as gone, saved marker or not', async () => {
- resolvePaneEngineProcess.mockResolvedValue(null)
+ lookupPaneEngineProcess.mockResolvedValue({ ok: false, unknown: false, reason: 'no claude process under pane %42' })
const saved = { ...LIVE, startMarker: 'K szept. 15 23:10:38 2026' }
expect((await new TmuxBackend().validate(PANE, { engine: 'claude', processIdentity: saved })).state)
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index f0d7684bc..53d4466b4 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1719,6 +1719,7 @@ class AppNotifier extends ChangeNotifier {
String? signOutError;
Future<void>? _logoutInFlight;
Future<void>? _workspaceCleanup;
+ bool _guestDeskRestorePending = false;
AppNotifier({
required AppConfig config,
@@ -3201,8 +3202,13 @@ class AppNotifier extends ChangeNotifier {
}
}
if (from != null) {
- await _reseatDesk(from: from, to: current, dropOthers: isGuest);
- if (!_authWorkCurrent(revision)) return;
+ final restored = await _reseatDesk(
+ from: from,
+ to: current,
+ dropOthers: isGuest,
+ revision: revision,
+ );
+ if (!_authWorkCurrent(revision) || !restored) return;
}
// ONLY ONCE THE DESK REALLY NAMES THIS MACHINE.
//
@@ -3250,41 +3256,27 @@ class AppNotifier extends ChangeNotifier {
/// the store. Reusing the cold-start restore is what keeps this from becoming a
/// second, subtly different way to build a grid.
///
- /// [revision] is the sign-out's own, when it has one: the explicit sign-out
- /// already invalidated the previous work, and a second invalidation here would
- /// orphan its own wait. A session that ended underneath us passes none and
- /// invalidates for itself — the in-flight work belongs to the account that
- /// just left.
- Future<void> _becomeGuest({String? banner, int? revision}) async {
- revision ??= _invalidateAuthWork();
- final before = localMachineState?.machine.machineId;
+ /// Both callers invalidate old account work before clearing its workspace.
+ /// Reuse that revision so the expiry explanation survives the guest restore.
+ Future<void> _becomeGuest({
+ String? banner,
+ String? previousMachineId,
+ required int revision,
+ }) async {
+ _guestDeskRestorePending = true;
signedIn = false;
currentUser = null;
analyticsAccount.clear();
- // The desk is the ACCOUNT's document (`Desk{userId}`): a guest has none, and
- // the tabs closing here are this window leaving the account, not the person
- // closing them — so nothing is sent.
- _deskRetry?.cancel();
- _deskRetry = null;
- _desk.reset();
- _stopAllOfflineRetries();
- _stopAllLinkRetries();
- _stopAllAgentSyncTimers();
- _clearAllTurnActivity();
- // Every connection goes: the daemon this window was talking to is being
- // replaced by one with a different identity, and a remote lane was borrowed
- // from the account that is changing hands.
- await _pool?.closeAll();
+ if (banner != null) {
+ _lastError = banner;
+ _lastErrorRetryable = true;
+ }
+ // Account teardown already removed private remote content. Finish closing
+ // its transports before restoring this computer from the saved desk.
+ await _workspaceCleanup;
+ if (!_authWorkCurrent(revision)) return;
+ final before = previousMachineId ?? await _paneLayout?.loadLocalMachineId();
if (!_authWorkCurrent(revision)) return;
- machines = [];
- machinesAreStale = false;
- machineStates.clear();
- sessionPreviews.clear();
- sessionTails.clear();
- gridPictures.clear();
- _stopWakeFollowers();
- expandedMachines.clear();
- selectedMachineId = null;
_ensurePool();
notifyListeners();
try {
@@ -3309,10 +3301,25 @@ class AppNotifier extends ChangeNotifier {
// Remote tiles leave with the account — a guest has no machine to attach
// them to, and a tile waiting forever reads as broken rather than as
// signed out. This computer's follow it to the id the daemon serves now.
- await _reseatDesk(from: before ?? after, to: after, dropOthers: true);
+ final restored = await _reseatDesk(
+ from: before ?? after,
+ to: after,
+ dropOthers: true,
+ revision: revision,
+ persistCurrent: false,
+ );
if (!_authWorkCurrent(revision)) return;
+ if (!restored) {
+ // Keep the restore pending and the old identity intact. The unchanged
+ // saved layout may still contain private remote panes, so do not read it
+ // back into the guest workspace until the filtered write succeeds.
+ status = AppStatus.authenticated;
+ notifyListeners();
+ return;
+ }
await _paneLayout?.saveLocalMachineId(after);
if (!_authWorkCurrent(revision)) return;
+ _guestDeskRestorePending = false;
}
// A guest ends on the desk, whichever screen it started from.
status = AppStatus.authenticated;
@@ -3331,32 +3338,77 @@ class AppNotifier extends ChangeNotifier {
/// the file is rewritten, and the cold-start restore reads it back; tiles whose
/// machines are already connected are attached straight away rather than
/// waiting for a connect event that already happened.
- Future<void> _reseatDesk({
+ ///
+ /// The tiles detaching is teardown a sign-in waits for, and a sign-in that
+ /// started meanwhile ([revision] superseded) owns the grid from there: this
+ /// leaves it empty rather than restoring the desk this re-seat was for, and
+ /// that sign-in's own bootstrap restores the file and follows the id.
+ Future<bool> _reseatDesk({
+ required String from,
+ required String to,
+ required bool dropOthers,
+ required int revision,
+ bool persistCurrent = true,
+ }) {
+ final previous = _workspaceCleanup;
+ var restored = false;
+ return _trackWorkspaceCleanup(() async {
+ await previous;
+ if (!_authWorkCurrent(revision)) return;
+ restored = await _reseatDeskAfterCleanup(
+ from: from,
+ to: to,
+ dropOthers: dropOthers,
+ revision: revision,
+ persistCurrent: persistCurrent,
+ );
+ }()).then((_) => restored);
+ }
+
+ Future<bool> _reseatDeskAfterCleanup({
required String from,
required String to,
required bool dropOthers,
+ required int revision,
+ required bool persistCurrent,
}) async {
final store = _paneLayout;
- if (store == null) return;
- _persistLayout();
+ if (store == null) return true;
+ // After sign-out the live grid is intentionally empty. Saving it here
+ // would destroy the local work we are about to recover.
+ if (persistCurrent) _persistLayout();
await store.flushSwarms();
- await store.rekeyMachine(from: from, to: to, dropOthers: dropOthers);
- if (_disposed) return;
+ if (!_authWorkCurrent(revision)) return false;
+ if (!await store.rekeyMachine(from: from, to: to, dropOthers: dropOthers)) {
+ if (_authWorkCurrent(revision)) {
+ _lastError =
+ 'Could not restore this computer’s saved workspace. Try again.';
+ _lastErrorRetryable = true;
+ }
+ return false;
+ }
+ if (_disposed) return false;
+ // The file and the id it is keyed by move together, whatever happens next:
+ // a sign-in that overtakes this re-seat finds the desk through that id.
+ await store.saveLocalMachineId(to);
+ if (_disposed) return false;
await _closeAllPanes(persist: false);
- if (_disposed) return;
+ if (_disposed) return false;
_closedHistory.clear();
final starter = Swarm(id: 'swarm-${_nextSwarmId++}');
swarms
..clear()
..add(starter);
_activeSwarmId = starter.id;
+ if (!_authWorkCurrent(revision)) return false;
await _restorePaneLayout();
- if (_disposed) return;
+ if (!_authWorkCurrent(revision)) return false;
for (final machine in machineStates.values) {
// A restore at launch, or a machine re-seated under it.
_attachPendingPanes(machine, intent: AttachIntent.automatic);
}
_announceAppFocus();
+ return true;
}
/// The local daemon (`harness start`) must be up before any local REST/WS call can work — unlike
@@ -3565,7 +3617,7 @@ class AppNotifier extends ChangeNotifier {
if (status == AppStatus.unauthenticated || isGuest) {
return; // idempotent: several sources can race here
}
- _invalidateAuthWork();
+ final revision = _invalidateAuthWork();
cliLogin.cancel();
_sessionExpired = true;
currentUser = null;
@@ -3573,10 +3625,11 @@ class AppNotifier extends ChangeNotifier {
pendingAuthorizeUrl = null;
_awaitingFirstMessage = null;
analyticsAccount.clear();
+ final previousMachineId = localMachineState?.machine.machineId;
+ _clearAccountWorkspace();
// A VIEWER has nowhere to be but its login screen — no daemon, nothing of
// its own to show.
- if (viewer != null) {
- _clearAccountWorkspace();
+ if (viewer != null || localManualFixture != null) {
_lastError = message;
_lastErrorRetryable = true;
status = AppStatus.unauthenticated;
@@ -3587,8 +3640,18 @@ class AppNotifier extends ChangeNotifier {
// and goes on serving this computer, so the agents that were running are
// still running. This computer's tiles stay (under the id it serves now),
// the other machines' leave, and the banner says why the list got shorter.
+ //
+ // The work was invalidated above, so the guest transition runs under THIS
+ // revision: invalidating again would clear [sessionExpired], and the banner
+ // would read as a failed sign-in rather than as the session having ended.
_closedHistory.clear();
- unawaited(_becomeGuest(banner: message));
+ unawaited(
+ _becomeGuest(
+ banner: message,
+ previousMachineId: previousMachineId,
+ revision: revision,
+ ),
+ );
}
/// Remove the old account's live objects without overwriting its saved desk.
@@ -3643,25 +3706,32 @@ class AppNotifier extends ChangeNotifier {
..add(starter);
_activeSwarmId = starter.id;
_autoPickedAgent = false;
+ _trackWorkspaceCleanup(
+ Future.wait<void>([panesClosed, if (pool != null) pool.closeAll()]),
+ );
+ }
+
+ /// The old account's terminals detaching and its connections closing, which
+ /// a sign-in waits for (see [login]) so it cannot overtake them: a new
+ /// session must not be set up while the last one is still being torn down.
+ /// Joins any teardown already in flight; completes when all of it has, and
+ /// never with an error.
+ Future<void> _trackWorkspaceCleanup(Future<void> work) {
late final Future<void> cleanup;
- cleanup =
- Future.wait<void>([
- ?_workspaceCleanup,
- panesClosed,
- if (pool != null) pool.closeAll(),
- ])
- .then<void>(
- (_) {},
- onError: (Object error) {
- debugPrint('account connection cleanup failed: $error');
- },
- )
- .whenComplete(() {
- if (identical(_workspaceCleanup, cleanup)) {
- _workspaceCleanup = null;
- }
- });
+ cleanup = Future.wait<void>([?_workspaceCleanup, work])
+ .then<void>(
+ (_) {},
+ onError: (Object error) {
+ debugPrint('account connection cleanup failed: $error');
+ },
+ )
+ .whenComplete(() {
+ if (identical(_workspaceCleanup, cleanup)) {
+ _workspaceCleanup = null;
+ }
+ });
_workspaceCleanup = cleanup;
+ return cleanup;
}
void _startUpdateChecking() {
@@ -3886,6 +3956,7 @@ class AppNotifier extends ChangeNotifier {
Future<void> login() async {
if (_disposed || signingIn || signingOut || signOutError != null) return;
+ final wasGuest = isGuest;
final revision = _invalidateAuthWork();
_closedHistory.clear();
_monitorHarnesses.clear();
@@ -3928,6 +3999,7 @@ class AppNotifier extends ChangeNotifier {
if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
return;
}
+ _guestDeskRestorePending = false;
analytics.signedIn();
// Restarts the clock even if `_trackAppOpened` already started one: this
// person met the login screen, so their wait begins where the launch's
@@ -3935,7 +4007,7 @@ class AppNotifier extends ChangeNotifier {
_armFirstMessage('sign_in');
} catch (error) {
if (!_authWorkCurrent(revision)) return;
- status = AppStatus.unauthenticated;
+ status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
_lastError = error.toString();
_lastErrorRetryable = true;
// A short code, never `error.toString()` — a CLI failure carries paths
@@ -3946,6 +4018,9 @@ class AppNotifier extends ChangeNotifier {
analytics.signInFailed(
error is CliNotAvailableException ? 'cli_missing' : 'failed',
);
+ if (wasGuest && _guestDeskRestorePending && !signedIn) {
+ unawaited(_becomeGuest(revision: revision));
+ }
} finally {
// Takes the in-app browser view down once the redirect has landed; a no-op
// where the page opened in a browser of its own.
@@ -4016,14 +4091,19 @@ class AppNotifier extends ChangeNotifier {
/// cancelled attempt and cannot change a subsequent sign-in.
void cancelLogin() {
if (_disposed || !canCancelLogin) return;
- _invalidateAuthWork();
+ final revision = _invalidateAuthWork();
signingIn = false;
pendingAuthorizeUrl = null;
- status = AppStatus.unauthenticated;
+ status = isGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
_lastError = null;
_lastErrorRetryable = false;
cliLogin.cancel();
notifyListeners();
+ // Cancellation can supersede the guest restore while old terminals are
+ // still detaching. Resume that restore under the new revision.
+ if (isGuest && _guestDeskRestorePending) {
+ unawaited(_becomeGuest(revision: revision));
+ }
}
Future<void> logout() {
@@ -4048,6 +4128,7 @@ class AppNotifier extends ChangeNotifier {
Future<void> _logout() async {
final revision = _invalidateAuthWork();
+ final previousMachineId = localMachineState?.machine.machineId;
cliLogin.cancel();
signingIn = false;
signingOut = true;
@@ -4060,7 +4141,10 @@ class AppNotifier extends ChangeNotifier {
// and becomes a guest — the daemon comes back signed out and keeps serving
// this computer, so signing out of the account is not a reason to take the
// agents off the screen. The rebind at the end sits the desk back down.
- if (viewer != null) status = AppStatus.unauthenticated;
+ // The local-manual dev fixture goes back to the login screen too: it has
+ // no daemon of its own, and a guest desk would be served by the REAL CLI.
+ final becomesGuest = viewer == null && localManualFixture == null;
+ if (!becomesGuest) status = AppStatus.unauthenticated;
currentUser = null;
analyticsAccount.clear();
notifyListeners();
@@ -4090,8 +4174,10 @@ class AppNotifier extends ChangeNotifier {
// The CLI restarts its daemon signed out (`harness logout` does it itself),
// so this window waits for that one and sits its desk back down on the id it
// serves. In the background: the person asked to sign out, and that is done.
- if (viewer == null && didClear) {
- unawaited(_becomeGuest(revision: revision));
+ if (becomesGuest && didClear) {
+ unawaited(
+ _becomeGuest(previousMachineId: previousMachineId, revision: revision),
+ );
}
}
@@ -5336,6 +5422,10 @@ class AppNotifier extends ChangeNotifier {
Future<void> _performRetryMachines({required bool automatic}) async {
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
+ if (isGuest && _guestDeskRestorePending) {
+ await _becomeGuest(revision: revision);
+ return;
+ }
// Re-verify the daemon first: a retry that skips straight to `refreshMachines()` can hit
// the exact same "daemon not connected yet" timeout the button was pressed to escape.
try {
@@ -5354,10 +5444,10 @@ class AppNotifier extends ChangeNotifier {
if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated) {
return;
}
- if (currentUser == null) unawaited(_loadProfile());
+ if (signedIn && currentUser == null) unawaited(_loadProfile());
// A boot that found the daemon still connecting finishes THROUGH here (see
// `_loadProfile`), so the desk is joined here as well — once.
- _deskEnsure(revision);
+ if (signedIn) _deskEnsure(revision);
try {
if (!await refreshMachines() || !_authWorkCurrent(revision)) return;
if (!automatic) _lastError = null;
@@ -7394,8 +7484,7 @@ class AppNotifier extends ChangeNotifier {
'MEDIA_TOO_LARGE' => 'Remote previews support files up to 512 MB. Use a smaller export or transfer this file separately.',
'MEDIA_CHANGED' => 'The file changed while downloading. Wait for it to finish generating and try again.',
'MEDIA_UNSUPPORTED' => 'This file is not a supported image or video.',
- 'MEDIA_INVALID_REQUEST' =>
- 'This file is outside the folders Harness reads for this agent. Use one in its working folder or a temp folder.',
+ 'MEDIA_INVALID_REQUEST' => 'This file is outside the folders Harness reads for this agent. Use one in its working folder or a temp folder.',
'AGENT_NOT_FOUND' =>
'This agent is no longer available. Reconnect and try again.',
'NOT_TEXT' || 'FILE_TOO_LARGE' => 'Update the Harness CLI on this remote machine to open media previews.',
diff --git a/desktop/lib/state/pane_layout_store.dart b/desktop/lib/state/pane_layout_store.dart
index 1fe670c96..12c3cedc1 100644
--- a/desktop/lib/state/pane_layout_store.dart
+++ b/desktop/lib/state/pane_layout_store.dart
@@ -163,17 +163,19 @@ class PaneLayoutStore {
///
/// [dropOthers] is the sign-out: a guest has no machine to attach a remote
/// tile to, and a tile waiting forever reads as broken, not as signed out.
- Future<void> rekeyMachine({
+ /// Returns false when the rewritten layout could not be saved. Callers must
+ /// retain the old machine identity and retry before restoring account content.
+ Future<bool> rekeyMachine({
required String from,
required String to,
bool dropOthers = false,
}) async {
await flushSwarms();
final saved = await loadSwarms();
- if (saved == null) return;
+ if (saved == null) return true;
var changed = false;
final swarms = saved['swarms'];
- if (swarms is! List) return;
+ if (swarms is! List) return true;
for (final raw in swarms) {
if (raw is! Map || raw['panes'] is! List) continue;
final kept = <Object?>[];
@@ -191,12 +193,12 @@ class PaneLayoutStore {
}
raw['panes'] = kept;
}
- if (!changed) return;
+ if (!changed) return true;
try {
await _storage.write('swarm_layout_v1', jsonEncode(saved));
+ return true;
} catch (_) {
- // The desk comes back under the old ids at the next launch, where the
- // remembered id (above) gets another chance at it.
+ return false;
}
}
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 519595636..24ed876f6 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -1233,6 +1233,7 @@ class _PaneCell extends StatelessWidget {
child: _FileDropZone(
notifier: notifier,
pane: pane,
+ visible: visible,
child: _SwapZone(
notifier: notifier,
paneId: pane.id,
@@ -1627,11 +1628,13 @@ class _FileDropZone extends StatefulWidget {
const _FileDropZone({
required this.notifier,
required this.pane,
+ required this.visible,
required this.child,
});
final AppNotifier notifier;
final TerminalPane pane;
+ final bool visible;
final Widget child;
@override
@@ -1641,10 +1644,21 @@ class _FileDropZone extends StatefulWidget {
class _FileDropZoneState extends State<_FileDropZone> {
bool _hovering = false;
+ bool get _active =>
+ mounted && widget.visible && widget.notifier.panes.contains(widget.pane);
+
+ bool _canDeliver(TerminalSession session, String streamId) =>
+ _active &&
+ identical(widget.pane.session, session) &&
+ session.streamId == streamId &&
+ session.acceptsInput;
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
return DropTarget(
+ key: ValueKey('pane-file-drop-${widget.pane.id}'),
+ enable: widget.visible && (widget.pane.session?.acceptsInput ?? false),
onDragEntered: (_) => setState(() => _hovering = true),
onDragExited: (_) => setState(() => _hovering = false),
onDragDone: (details) async {
@@ -1706,10 +1720,11 @@ class _FileDropZoneState extends State<_FileDropZone> {
}
Future<void> _handleDrop(List<DropItem> files) async {
- if (files.isEmpty) return;
- widget.notifier.focusPane(widget.pane.id);
+ if (files.isEmpty || !_active) return;
final session = widget.pane.session;
- if (session == null) return; // pane not attached to a live session yet
+ if (session == null || !session.acceptsInput) return;
+ final streamId = session.streamId!;
+ widget.notifier.focusPane(widget.pane.id);
final machine = widget.notifier.stateOf(widget.pane.machineId);
final images = <DropItem>[];
@@ -1735,7 +1750,7 @@ class _FileDropZoneState extends State<_FileDropZone> {
// Only the first image: several back-to-back would race the same OS clipboard + single Ctrl+V
// nudge on the daemon side — see pasteImage's own doc.
if (images.isNotEmpty) {
- await _dropImage(images.first, machine, session);
+ await _dropImage(images.first, machine, session, streamId);
if (images.length > 1) {
final ignored = images.length - 1;
_toast(
@@ -1746,7 +1761,7 @@ class _FileDropZoneState extends State<_FileDropZone> {
// Every non-image file, independently — no shared resource to race over.
for (final item in others) {
- await _dropFile(item, machine, session);
+ await _dropFile(item, machine, session, streamId);
}
}
@@ -1754,7 +1769,9 @@ class _FileDropZoneState extends State<_FileDropZone> {
DropItem item,
MachineState? machine,
TerminalSession session,
+ String streamId,
) async {
+ if (!_canDeliver(session, streamId)) return;
// Not "cannot receive a native image paste" — that's a real capability gap, this is just a
// race between the drop landing and machine state loading. Conflating the two would send the
// user to fix a machine that is perfectly fine.
@@ -1770,6 +1787,7 @@ class _FileDropZoneState extends State<_FileDropZone> {
return;
}
final png = await ensurePngBytes(raw);
+ if (!_canDeliver(session, streamId)) return;
if (png == null) {
_toast('${item.name} is not a readable image');
return;
@@ -1781,6 +1799,7 @@ class _FileDropZoneState extends State<_FileDropZone> {
// the chunked-upload path, which is for a genuinely remote machine's DIFFERENT clipboard.
if (machine.isLocalMachine) {
final wrote = await NativeClipboard.writeImagePng(png);
+ if (!_canDeliver(session, streamId)) return;
if (!wrote) {
_toast('Could not set the clipboard on this machine');
return;
@@ -1806,7 +1825,9 @@ class _FileDropZoneState extends State<_FileDropZone> {
DropItem item,
MachineState? machine,
TerminalSession session,
+ String streamId,
) async {
+ if (!_canDeliver(session, streamId)) return;
// Same reasoning as _dropImage: null here is a transient race, not "this machine can't do
// this" — say so distinctly rather than falling through to the remote/upload branch below,
// which would silently take the wire for what might actually be a local pane.
@@ -1835,6 +1856,7 @@ class _FileDropZoneState extends State<_FileDropZone> {
_toast('Could not read ${item.name}');
return;
}
+ if (!_canDeliver(session, streamId)) return;
if (bytes.length > terminalLocalPasteFileMaxPayloadBytes) {
_toast(
'${item.name} is larger than ${_mb(terminalLocalPasteFileMaxPayloadBytes)}',
diff --git a/desktop/test/desktop_account_transition_test.dart b/desktop/test/desktop_account_transition_test.dart
new file mode 100644
index 000000000..6fe9d4b16
--- /dev/null
+++ b/desktop/test/desktop_account_transition_test.dart
@@ -0,0 +1,302 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+class _Login extends CliLogin {
+ var logins = 0;
+ Completer<void>? pending;
+ bool fail = false;
+
+ @override
+ Future<void> logout() async {}
+
+ @override
+ Future<void> login({required void Function(String) onAuthorizeUrl}) async {
+ logins++;
+ await pending?.future;
+ if (fail) throw StateError('Fixture sign-in failed.');
+ }
+}
+
+class _Api extends ApiClient {
+ _Api()
+ : super(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ );
+
+ @override
+ Future<Map<String, dynamic>?> me() async => null;
+}
+
+class _Desktop extends AppNotifier {
+ _Desktop(this.storage, this.loginFixture)
+ : super(
+ config: AppConfig.dev,
+ configStore: null,
+ authSession: AuthSession(storage: MemoryStore()),
+ cliLogin: loginFixture,
+ paneLayoutStore: PaneLayoutStore(storage: storage),
+ ) {
+ api = _Api();
+ status = AppStatus.authenticated;
+ }
+
+ final MemoryStore storage;
+ final _Login loginFixture;
+ var guestInventoryAvailable = true;
+ var daemonGates = 0;
+
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ daemonGates++;
+ }
+
+ @override
+ Future<bool> refreshMachines() async {
+ machines = [];
+ machineStates.clear();
+ if (!signedIn && !guestInventoryAvailable) return true;
+ final id = signedIn ? 'account-local' : 'computer-local';
+ final machine = Machine(
+ machineId: id,
+ computerId: 'computer-local',
+ authMode: MachineAuthMode.remote,
+ name: 'This computer',
+ );
+ machines = [machine];
+ machineStates[id] = MachineState(machine)..localOnly = true;
+ return true;
+ }
+
+ Future<void> arrange({Completer<bool>? detach}) async {
+ await refreshMachines();
+ await PaneLayoutStore(storage: storage).saveLocalMachineId('account-local');
+ renameSwarm(activeSwarmId, 'Research');
+ for (final (machine, agent) in [
+ ('account-local', 'local-agent'),
+ ('remote', 'remote-agent'),
+ ]) {
+ adoptSessionForTest(
+ TerminalSession(
+ machineId: machine,
+ agentId: agent,
+ agentName: agent,
+ engineId: 'codex',
+ send: (type, _) => type == 'terminal_close' && detach != null
+ ? detach.future
+ : Future.value(true),
+ sendBinary: (_) async => true,
+ )..streamId = agent,
+ );
+ }
+ renameSwarm(activeSwarmId, 'Research');
+ await flushPaneLayout();
+ }
+}
+
+class _HeldWrite extends MemoryStore {
+ bool hold = false;
+ final writing = Completer<void>();
+ final release = Completer<void>();
+
+ @override
+ Future<void> write(String key, String value) async {
+ if (hold && key == 'swarm_layout_v1') {
+ hold = false;
+ writing.complete();
+ await release.future;
+ }
+ await super.write(key, value);
+ }
+}
+
+class _RefusingWrite extends MemoryStore {
+ bool fail = false;
+
+ @override
+ Future<void> write(String key, String value) async {
+ if (fail && key == 'swarm_layout_v1') throw StateError('Fixture disk full');
+ await super.write(key, value);
+ }
+}
+
+Future<void> _settle() async {
+ for (var i = 0; i < 20; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+}
+
+void main() {
+ test(
+ 'a failed guest layout write preserves the old identity and can retry',
+ () async {
+ final storage = _RefusingWrite();
+ final app = _Desktop(storage, _Login());
+ addTearDown(app.dispose);
+ await app.arrange();
+ final saved = storage.values['swarm_layout_v1'];
+ storage.fail = true;
+ app.expireSessionForTest('Session expired.');
+ await _settle();
+ expect(storage.values['swarm_layout_v1'], saved);
+ expect(storage.values['local_machine_id'], 'account-local');
+ expect(app.allPanes, isEmpty);
+ expect(app.lastError, contains('restore'));
+ storage.fail = false;
+ await app.retryMachines();
+ expect(app.allPanes.map((p) => (p.machineId, p.agentId)), [
+ ('computer-local', 'local-agent'),
+ ]);
+ expect(storage.values['local_machine_id'], 'computer-local');
+ },
+ );
+
+ for (final expires in [false, true]) {
+ test(
+ 'desktop ${expires ? 'expiry' : 'sign-out'} preserves local work',
+ () async {
+ final storage = MemoryStore();
+ final app = _Desktop(storage, _Login());
+ addTearDown(app.dispose);
+ await app.arrange();
+ if (expires) {
+ app.expireSessionForTest('Session expired. Sign in again.');
+ } else {
+ await app.logout();
+ }
+ await _settle();
+ expect(app.isGuest, isTrue);
+ expect(app.status, AppStatus.authenticated);
+ expect(app.allPanes.map((p) => (p.machineId, p.agentId)), [
+ ('computer-local', 'local-agent'),
+ ]);
+ expect(app.swarms.single.name, 'Research');
+ expect(app.sessionExpired, expires);
+ final saved = jsonDecode(storage.values['swarm_layout_v1']!);
+ expect(saved['swarms'][0]['panes'], hasLength(1));
+ await app.login();
+ expect(app.allPanes.map((p) => (p.machineId, p.agentId)), [
+ ('account-local', 'local-agent'),
+ ]);
+ },
+ );
+ }
+
+ test(
+ 'expiry hides remote panes even when the guest daemon is unavailable',
+ () async {
+ final storage = MemoryStore();
+ final app = _Desktop(storage, _Login())..guestInventoryAvailable = false;
+ addTearDown(app.dispose);
+ await app.arrange();
+ final saved = storage.values['swarm_layout_v1'];
+ app.expireSessionForTest('Session expired.');
+ await _settle();
+ expect(app.allPanes.where((pane) => pane.machineId == 'remote'), isEmpty);
+ expect(storage.values['swarm_layout_v1'], saved);
+ expect(app.sessionExpired, isTrue);
+ app.guestInventoryAvailable = true;
+ await app.retryMachines();
+ expect(app.allPanes.map((p) => (p.machineId, p.agentId)), [
+ ('computer-local', 'local-agent'),
+ ]);
+ },
+ );
+
+ for (final cancel in [false, true]) {
+ test(
+ 'desktop sign-in ${cancel ? 'cancels during' : 'waits for'} guest teardown',
+ () async {
+ final cli = _Login();
+ final app = _Desktop(MemoryStore(), cli);
+ addTearDown(app.dispose);
+ final detached = Completer<bool>();
+ await app.arrange(detach: detached);
+ app.expireSessionForTest('Session expired.');
+ await _settle();
+ final login = app.login();
+ await _settle();
+ expect(cli.logins, 0);
+ if (cancel) app.cancelLogin();
+ detached.complete(true);
+ await login;
+ await _settle();
+ expect(cli.logins, cancel ? 0 : 1);
+ expect(app.status, AppStatus.authenticated);
+ expect(app.isGuest, cancel);
+ expect(
+ app.allPanes.map((p) => (p.machineId, p.agentId)),
+ contains((
+ cancel ? 'computer-local' : 'account-local',
+ 'local-agent',
+ )),
+ );
+ },
+ );
+ }
+
+ test(
+ 'cancelling a guest sign-in keeps the local workspace available',
+ () async {
+ final cli = _Login()..pending = Completer<void>();
+ final app = _Desktop(MemoryStore(), cli)..signedIn = false;
+ addTearDown(app.dispose);
+ final login = app.login();
+ await _settle();
+ app.cancelLogin();
+ expect(app.status, AppStatus.authenticated);
+ expect(app.isGuest, isTrue);
+ cli.pending!.complete();
+ await login;
+ expect(app.signedIn, isFalse);
+ expect(app.status, AppStatus.authenticated);
+ },
+ );
+
+ test('failed guest sign-in keeps the local workspace available', () async {
+ final app = _Desktop(MemoryStore(), _Login()..fail = true)
+ ..signedIn = false;
+ addTearDown(app.dispose);
+ await app.login();
+ expect(app.isGuest, isTrue);
+ expect(app.status, AppStatus.authenticated);
+ expect(app.lastError, contains('Fixture sign-in failed'));
+ });
+
+ test(
+ 'sign-in waits for a guest layout write and follows its committed identity',
+ () async {
+ final storage = _HeldWrite();
+ final cli = _Login();
+ final app = _Desktop(storage, cli);
+ addTearDown(app.dispose);
+ await app.arrange();
+ storage.hold = true;
+ app.expireSessionForTest('Session expired.');
+ await storage.writing.future;
+ final login = app.login();
+ await _settle();
+ expect(cli.logins, 0);
+ storage.release.complete();
+ await login;
+ await _settle();
+ expect(cli.logins, 1);
+ expect(storage.values['local_machine_id'], 'account-local');
+ expect(app.allPanes.map((p) => (p.machineId, p.agentId)), [
+ ('account-local', 'local-agent'),
+ ]);
+ },
+ );
+}
diff --git a/desktop/test/pane_file_drop_test.dart b/desktop/test/pane_file_drop_test.dart
new file mode 100644
index 000000000..bc2dabc5c
--- /dev/null
+++ b/desktop/test/pane_file_drop_test.dart
@@ -0,0 +1,161 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:desktop_drop/desktop_drop.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+final _png = base64Decode(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+);
+
+class _HeldImage extends DropItemFile {
+ _HeldImage() : super.fromData(_png, name: 'fixture.png');
+ final reading = Completer<void>();
+ final release = Completer<Uint8List>();
+
+ @override
+ Stream<Uint8List> openRead([int? start, int? end]) {
+ if (!reading.isCompleted) reading.complete();
+ return Stream.fromFuture(release.future);
+ }
+}
+
+void drop(DropTarget target, DropItem file) {
+ target.onDragDone!(
+ DropDoneDetails(
+ files: [file],
+ localPosition: const Offset(20, 20),
+ globalPosition: const Offset(20, 20),
+ ),
+ );
+}
+
+void main() {
+ const clipboard = MethodChannel('harness/clipboard_image');
+
+ testWidgets('one image drop reaches only the visible pane across tabs', (
+ tester,
+ ) async {
+ var writes = 0;
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(clipboard, (
+ _,
+ ) async {
+ writes++;
+ return true;
+ });
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ clipboard,
+ null,
+ ),
+ );
+ final app = createApp(connected: true);
+ app.machineStates['m']!.localOnly = true;
+ final firstInput = <TerminalBinaryFrame>[];
+ final secondInput = <TerminalBinaryFrame>[];
+ final first = app.adoptSessionForTest(terminal('a0', firstInput));
+ await mount(tester, app);
+ app.newSwarm(name: 'Second');
+ final second = app.adoptSessionForTest(terminal('a1', secondInput));
+ await tester.pump(const Duration(milliseconds: 100));
+ final targets = tester
+ .widgetList<DropTarget>(find.byType(DropTarget, skipOffstage: false))
+ .toList();
+ expect(targets, hasLength(2));
+ expect(targets.where((target) => target.enable), hasLength(1));
+ // Also exercise a callback queued before its tab became hidden.
+ for (final target in targets) {
+ drop(target, DropItemFile.fromData(_png, name: 'fixture.png'));
+ }
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(writes, 1);
+ expect(firstInput, isEmpty);
+ expect(secondInput, hasLength(1));
+ expect(app.focusedPane, same(second));
+ app.selectSwarm(app.swarms.first.id);
+ await tester.pump();
+ expect(
+ tester
+ .widget<DropTarget>(
+ find.byKey(ValueKey('pane-file-drop-${first.id}')),
+ )
+ .enable,
+ isTrue,
+ );
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ for (final change in ['tab', 'stream', 'readonly']) {
+ testWidgets('an image still being read cannot cross a $change change', (
+ tester,
+ ) async {
+ var writes = 0;
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ clipboard,
+ (_) async {
+ writes++;
+ return true;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ clipboard,
+ null,
+ ),
+ );
+ final app = createApp(connected: true);
+ app.machineStates['m']!.localOnly = true;
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final pane = app.adoptSessionForTest(session);
+ await mount(tester, app);
+ final target = tester.widget<DropTarget>(
+ find.byKey(ValueKey('pane-file-drop-${pane.id}')),
+ );
+ final file = _HeldImage();
+ drop(target, file);
+ await tester.pump();
+ expect(file.reading.isCompleted, isTrue);
+ switch (change) {
+ case 'tab':
+ app.newSwarm(name: 'Different work');
+ case 'stream':
+ session.streamId = 'replacement';
+ case 'readonly':
+ session.watching = true;
+ }
+ await tester.pump();
+ file.release.complete(_png);
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(writes, 0);
+ expect(input, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+ }
+
+ testWidgets('zoomed-out panes do not register drop handlers', (tester) async {
+ final app = createApp(connected: true);
+ app.adoptSessionForTest(terminal('a0', []));
+ app.adoptSessionForTest(terminal('a1', []));
+ app.toggleZoomPane();
+ await mount(tester, app);
+ expect(
+ tester
+ .widgetList<DropTarget>(find.byType(DropTarget, skipOffstage: false))
+ .where((target) => target.enable),
+ hasLength(1),
+ );
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+}
diff --git a/desktop/test/signout_recovery_test.dart b/desktop/test/signout_recovery_test.dart
index a73cd8b76..df6079476 100644
--- a/desktop/test/signout_recovery_test.dart
+++ b/desktop/test/signout_recovery_test.dart
@@ -59,7 +59,7 @@ Widget signOutHost(
);
}
-AppNotifier signOutApp(SignOutFixture cli, {bool local = false}) =>
+GuestTestApp signOutApp(SignOutFixture cli, {bool local = false}) =>
GuestTestApp(
config: AppConfig.dev,
configStore: null,
@@ -114,8 +114,21 @@ void main() {
addTearDown(app.dispose);
await app.logout();
expect(cli.attempts, isEmpty);
- expect(app.status, AppStatus.authenticated);
- expect(app.isGuest, isTrue);
+ expect(app.daemonGates, 0);
+ expect(app.status, AppStatus.unauthenticated);
+ },
+ );
+
+ test(
+ 'expiry of a development fixture never starts the real daemon',
+ () async {
+ final app = signOutApp(SignOutFixture(), local: true);
+ addTearDown(app.dispose);
+ app.expireSessionForTest('Fixture expired.');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.daemonGates, 0);
+ expect(app.status, AppStatus.unauthenticated);
+ expect(app.sessionExpired, isTrue);
},
);
diff --git a/desktop/test/support/guest_app.dart b/desktop/test/support/guest_app.dart
index 41e693b24..e528bdde9 100644
--- a/desktop/test/support/guest_app.dart
+++ b/desktop/test/support/guest_app.dart
@@ -11,8 +11,12 @@ class GuestTestApp extends AppNotifier {
super.localManualFixture,
});
+ var daemonGates = 0;
+
@override
- Future<void> ensureCliDaemonReady() async {}
+ Future<void> ensureCliDaemonReady() async {
+ daemonGates++;
+ }
@override
Future<bool> refreshMachines() async => true;
diff --git a/desktop/test/terminal_view_interaction_test.dart b/desktop/test/terminal_view_interaction_test.dart
index 4b12768e6..704f29993 100644
--- a/desktop/test/terminal_view_interaction_test.dart
+++ b/desktop/test/terminal_view_interaction_test.dart
@@ -1,3 +1,5 @@
+import 'dart:ui' show SemanticsAction;
+
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
@@ -7,6 +9,93 @@ import 'package:xterm/xterm.dart';
import 'package:xterm/src/ui/custom_text_edit.dart';
void main() {
+ testWidgets(
+ 'native accessibility can insert text once into a writable terminal',
+ (tester) async {
+ final semantics = tester.ensureSemantics();
+ final terminal = Terminal(maxLines: 20)..resize(80, 4);
+ final output = <String>[];
+ terminal.onOutput = output.add;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SizedBox(
+ width: 800,
+ height: 200,
+ child: TerminalView(terminal, autofocus: true),
+ ),
+ ),
+ );
+ await tester.pump();
+ final input = find.bySemanticsLabel('Terminal input');
+ expect(input, findsOneWidget);
+ final node = tester.getSemantics(input);
+ expect(
+ node.getSemanticsData().hasAction(SemanticsAction.setText),
+ isTrue,
+ );
+ tester
+ .renderObject(input)
+ .owner!
+ .semanticsOwner!
+ .performAction(node.id, SemanticsAction.setText, 'Dictated text');
+ await tester.pump();
+ expect(output.join(), 'Dictated text');
+ // The platform echo and subsequent typing must not repeat the dictated phrase.
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'Dictated text',
+ selection: TextSelection.collapsed(offset: 13),
+ ),
+ );
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'Dictated text!',
+ selection: TextSelection.collapsed(offset: 14),
+ ),
+ );
+ await tester.pump();
+ expect(output.join(), 'Dictated text!');
+ await tester.pumpWidget(const SizedBox());
+ semantics.dispose();
+ },
+ variant: TargetPlatformVariant({
+ TargetPlatform.macOS,
+ TargetPlatform.linux,
+ }),
+ );
+
+ testWidgets(
+ 'an observed terminal exposes no accessibility editing action',
+ (tester) async {
+ final semantics = tester.ensureSemantics();
+ final terminal = Terminal(maxLines: 20)..resize(80, 4);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SizedBox(
+ width: 800,
+ height: 200,
+ child: TerminalView(terminal, readOnly: true),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(find.bySemanticsLabel('Terminal input'), findsNothing);
+ final node = tester.getSemantics(
+ find.bySemanticsLabel('Terminal output'),
+ );
+ expect(
+ node.getSemanticsData().hasAction(SemanticsAction.setText),
+ isFalse,
+ );
+ await tester.pumpWidget(const SizedBox());
+ semantics.dispose();
+ },
+ variant: TargetPlatformVariant({
+ TargetPlatform.macOS,
+ TargetPlatform.linux,
+ }),
+ );
+
test('does not turn an xterm keyboard command into text styling', () {
final terminal = Terminal(maxLines: 20, reflowEnabled: false)
..resize(80, 4);
diff --git a/desktop/third_party/xterm/lib/src/ui/custom_text_edit.dart b/desktop/third_party/xterm/lib/src/ui/custom_text_edit.dart
index 46aaf2141..d9de5c5d7 100644
--- a/desktop/third_party/xterm/lib/src/ui/custom_text_edit.dart
+++ b/desktop/third_party/xterm/lib/src/ui/custom_text_edit.dart
@@ -95,46 +95,45 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
Widget build(BuildContext context) {
return Focus(
focusNode: widget.focusNode,
- // The web text-field node below owns focus semantics. A second focused ancestor can
- // deactivate its DOM editor when input moves between two custom editors.
- includeSemantics: !kIsWeb,
+ // The text-field node owns focus semantics. A second focused ancestor can
+ // deactivate the web editor or hide the native accessibility input target.
+ includeSemantics: false,
autofocus: widget.autofocus,
onKeyEvent: _onKeyEvent,
- // Flutter web's accessibility input strategy creates its DOM editor from a semantic
- // text field. A bare TextInputClient receives arrows/Enter but loses every printable key
- // when a screen reader (or accessibility automation) enables semantics.
- child: kIsWeb
- ? ListenableBuilder(
- listenable:
- Listenable.merge([widget.focusNode, _semanticEditingState]),
- builder: (context, _) => Semantics(
- container: true,
- excludeSemantics: true,
- // Read-only observers are output surfaces, not browser editors. The web engine
- // creates a writable DOM textarea even for a semantic readOnly text field.
- textField: !widget.readOnly,
- enabled: true,
- focusable: !widget.readOnly,
- focused: !widget.readOnly && widget.focusNode.hasFocus,
- multiline: true,
- label: widget.semanticLabel ??
- (widget.readOnly ? 'Terminal output' : 'Terminal input'),
- value: _semanticEditingState.value.text,
- onTap: widget.readOnly ? null : requestKeyboard,
- onFocus: widget.readOnly ? null : requestKeyboard,
- onSetText: widget.readOnly
- ? null
- : (text) {
- updateEditingValue(TextEditingValue(
- text: text,
- selection:
- TextSelection.collapsed(offset: text.length),
- ));
- },
- child: widget.child,
- ),
- )
- : widget.child,
+ // Browser input and native dictation/accessibility both need an editable semantic
+ // target: a bare TextInputClient exposes no text field to macOS accessibility.
+ child: ListenableBuilder(
+ listenable: Listenable.merge([widget.focusNode, _semanticEditingState]),
+ builder: (context, _) => Semantics(
+ container: true,
+ excludeSemantics: true,
+ // Read-only observers are output surfaces, not browser editors. The web engine
+ // creates a writable DOM textarea even for a semantic readOnly text field.
+ textField: !widget.readOnly,
+ enabled: true,
+ focusable: !widget.readOnly,
+ focused: !widget.readOnly && widget.focusNode.hasFocus,
+ multiline: true,
+ label: widget.semanticLabel ??
+ (widget.readOnly ? 'Terminal output' : 'Terminal input'),
+ value: _semanticEditingState.value.text,
+ onTap: widget.readOnly ? null : requestKeyboard,
+ onFocus: widget.readOnly ? null : requestKeyboard,
+ onSetText: widget.readOnly
+ ? null
+ : (text) {
+ if (widget.readOnly) return;
+ updateEditingValue(TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(offset: text.length),
+ ));
+ // A semantic action did not originate in the platform editor. Keep
+ // its buffer current so the next native key cannot replay old text.
+ _connection?.setEditingState(_currentEditingState);
+ },
+ child: widget.child,
+ ),
+ ),
);
}
diff --git a/docs/research/2026-09-27-app-reliability-handoff.md b/docs/research/2026-09-27-app-reliability-handoff.md
new file mode 100644
index 000000000..c04250326
--- /dev/null
+++ b/docs/research/2026-09-27-app-reliability-handoff.md
@@ -0,0 +1,163 @@
+# App reliability — historical pause checkpoint
+
+The user resumed this work on September 28. This file records the earlier pause;
+its outstanding-work and validation notes describe that checkpoint, not the
+current branch. See [the completed reliability pass](2026-09-28-app-reliability.md)
+for the reconciled implementation, regression evidence, and remaining limits.
+
+At the pause, the reliability changes were uncommitted. They were preserved as
+`e3744d14` on `codex/app-reliability-checkpoint` before reconciling current main.
+
+## Workspace and prior release
+
+- Worktree: `/Users/ab/harnesses/worktrees/autonomous-harness/brave-ibis`.
+- Branch: `codex/app-reliability`, based on `origin/main` at `56651674170a3011ef6809bb17b3a56016e97ee9`.
+- The previous external-engine task is complete: CLI 0.3.15 and Desktop 1.2.9
+ were released from that commit. See `2026-09-27-external-engines-completion.md`.
+- All modifications and new tests listed below are intentionally uncommitted.
+- Existing personal daemon, tmux, accounts, and engine installations were not
+ modified. Tests use isolated fixtures. No persistent test service is running.
+
+## Changes in progress
+
+### CLI launch modes (#371 / PR #383)
+
+Copied the reviewed `newCommand.ts` and its tests from `origin/pr-383`
+(`0551e7c6bdca431b039a2cd96748d84ad042a75f`). Default permission modes are only
+sent to engines that implement them. Explicit user choices still reach daemon
+validation. Store harnesses use their underlying engine's capabilities.
+
+The upstream regressions failed before the source change; afterward
+`newCommand.spec.ts` and `engineLaunch.spec.ts` passed all 94 tests.
+The imported source comment incorrectly says "eleven" unsupported engines;
+the list has ten. Tidy that comment before committing and credit PR #383.
+
+### Desktop account transitions (PR #325 and additional confirmed failures)
+
+Applied only PR #325's production patch to `desktop/lib/state/app_state.dart`,
+then extended it. Its old test changes overlap the previous release's fixture
+updates, so they were not copied. The original PR's commits are in
+`origin/pr-325` (`47a8976d`, `d5b3cc32`, `1b454db8`, `999cd17d`).
+
+New `desktop_account_transition_test.dart` exercises native desktop transitions
+with both local and remote panes. Its first six tests all failed on the original
+source. The implementation now:
+
+- preserves the expiry flag by reusing the existing auth revision;
+- clears old account content immediately, including when the guest daemon is unavailable;
+- restores local panes from the saved desk without writing an empty grid over it;
+- captures the old local identity before teardown and falls back to the saved identity;
+- tracks the entire layout rekey/write/teardown operation so a new sign-in waits;
+- keeps failed/cancelled guest sign-in on the usable guest desktop;
+- resumes a pending guest restore after cancellation or Retry;
+- prevents local-manual fixture logout **and expiry** from starting the real daemon;
+- avoids account profile/desk requests when a guest retries machine discovery.
+
+`support/guest_app.dart` counts daemon gates. `signout_recovery_test.dart`
+asserts the fixture isolation behavior rather than the previous guest expectation.
+
+Validation: 38 account/expiry/sign-out/guest tests passed after the initial fix.
+Then all eight new native transition tests passed, including a delayed disk write
+racing sign-in and guest recovery after missing inventory. Full suite, analysis,
+formatting, and broader lifecycle review remain to do. Review comments around
+`_guestDeskRestorePending`; its field currently interrupts the method docblock.
+
+### Daemon lock generation (#59)
+
+`processLiveness.ts` and the standalone `hook/notify.mjs` now read `ps` under
+`psEnv()` and write `ps-c:` generation markers. Legacy `ps:` and unknown formats
+are conservatively treated as live while their PID exists; comparable `ps-c:`
+and Linux tick markers still reject PID reuse. Updated existing reuse fixtures
+to use a mismatched marker in the actual current format.
+
+New `processLiveness.spec.ts` exercises both daemon code and the real standalone
+hook functions, with controlled process-query dependencies, for locale changes,
+legacy migration, PID reuse, Linux ticks, and unavailable timestamps.
+
+All 104 lock/registry tests passed with process/socket access. The first run was
+sandbox-blocked (`uv_uptime` and tsx IPC EPERM), not a product failure. Remember
+to consider coexistence with older writers when reviewing migration behavior.
+
+### File/image drop routing (#73)
+
+`pane_grid.dart` passes visibility to `_FileDropZone`, disables hidden/read-only
+drop targets, and checks pane/session/stream identity after asynchronous file
+reads and clipboard writes. A drop cannot send input into another tab or a
+replacement stream. Existing local clipboard paste semantics are retained.
+
+New `pane_file_drop_test.dart`: four tests passed for tab/stream/read-only changes
+during a read and zoom visibility. The cross-tab test failed because its first
+tab had never been mounted, so there was only one cached target. **The fixture
+was just corrected to mount the first tab before switching; rerun it first.**
+Do not claim all drop tests pass yet. A baseline comparison of the drop tests
+against the old implementation is also useful.
+
+### Stale question answers (PR #367)
+
+Applied the reviewed full patch from `origin/pr-367` (commits `55ecf474`,
+`fc4aabba`, `a7447eb8`, `e8f71075`). It checks an answer's request ID against the
+live dialog, stops positional answers from reaching later unrelated questions,
+selects the latest dialog rather than scrollback across engine readers, and
+returns encrypted answer results only to the originating client.
+
+The imported patch passed 520 tests across 14 dialog/backend/engine files.
+Immediately before pausing, added two further protections in `askQuestion.ts`
+and two tests: a remembered question cannot be redirected to another agent with
+the same dialog, and concurrent answers using agent ID versus session ID share
+one canonical agent lock. **These last changes have not been tested yet.**
+
+## Outstanding investigation
+
+1. Finish the tests and review above, then run CLI typecheck/build/full suite,
+ Flutter formatting/analysis/full suite, and relevant isolated end-to-end
+ recovery checks. Read `desktop/AGENTS.md`, `desktop/CLAUDE.md`, and the terminal
+ workspace/dialog design docs before further UI changes (already read here).
+2. Fix Hermes Linux discovery (#372): current `processEntrypoint` in both
+ `cli/src/lib/tmux.ts` and `cli/hook/notify.mjs` intentionally rejects all
+ Python `-c` invocations. Official new Hermes uses managed Python `-I -c`
+ with a bootstrap, so it is missed. **No code change made yet.** Verify a
+ narrowly anchored launcher signature; do not match arbitrary prompt text or
+ any Python process mentioning Hermes. Add positive and negative discovery
+ and offline-hook tests. Installed local Hermes is an older venv launcher,
+ so its successful discovery does not prove the Linux case.
+3. Source research found the authoritative command in
+ `NousResearch/hermes-agent/hermes_cli/_launchers.py`, `runtime_command`:
+ `python -I -c` then `import os, sys, runpy;` environment cleanup,
+ `sys.path.insert(0, <repo root>);` a HERMES_HOME assignment,
+ `import hermes_bootstrap; runpy.run_module('hermes_cli.main',
+ run_name='__main__', alter_sys=True)`. Issue #372 reports an older
+ `-I -I -c import sys, runpy; sys.path.insert(...)` form. Reject unrelated
+ inline code, prompts, shell/Node interpreters, and other Hermes modules.
+4. Continue reliability triage rather than assuming old reports are resolved:
+ #105 pane freeze/reconnect, #49 GUI tmux lookup, #50 daemon port ownership,
+ #45 cross-tab pane deletion, #41 restore scroll, #67 installation diagnostics.
+ #58 is unused runtime-validation code. PR #366 has pane/tab close behavior
+ and launch progress; fetched for review but not applied. Do not merge feature
+ PRs (#394/#395 web sharing or mobile work) as part of this reliability task.
+5. #284 describes a native Flutter raster crash on macOS 27 with mirrored mixed
+ DPI displays. It has no full crash report in the issue; do not claim a fix
+ without reproducing or finding evidence. #107/#108/#110 are WSL-specific;
+ some may need the actual environment/upstream runtime investigation.
+6. Keep a clear final triage record of fixed, already-covered, unconfirmed,
+ and environment-dependent reports. Do not claim every possible app bug is gone.
+7. Commit in reviewable groups, credit the existing PRs, reconcile main, and
+ continue the user's authorized merge/release workflow only after resumption
+ and successful checks. No new reliability PR exists yet.
+
+## Local tools and receipts
+
+- Node: `/Users/ab/.local/bin/node` (22.23.1); run npm/npx in `cli/`.
+- Flutter: `/Users/ab/development/flutter-3.47.2/bin/flutter`; use `--no-pub`.
+- Git and gh use the shared git directory/network, so require escalation here.
+ Flutter needs access to its SDK cache. CLI process/socket suites also need
+ escalation; otherwise sandbox errors can look like regressions.
+- Full open-issue inventory: `/private/tmp/harness-reliability-issues.json`.
+- Test logs: `/private/tmp/harness-desktop-reliability-baseline.log`,
+ `harness-desktop-reliability-focused.log`, `harness-reliability-regressions.log`,
+ `harness-lock-tests.log`, `harness-question-tests.log`, `harness-drop-tests.log`.
+- Imported patches: `/private/tmp/harness-pr325-production.patch`,
+ `/private/tmp/harness-pr367.patch` and `harness-pr367-question.patch`.
+- Official source copies: `/private/tmp/hermes-official-launchers.py`,
+ `hermes-official-install.sh`, `hermes-official-launcher`, `hermes-official-launch.py`.
+- Remote refs `origin/pr-325`, `origin/pr-383`, `origin/pr-367`, `origin/pr-366`
+ are fetched. Original external-engines worktree/branch remains untouched.
diff --git a/docs/research/2026-09-28-app-reliability.md b/docs/research/2026-09-28-app-reliability.md
new file mode 100644
index 000000000..1c9de5cc9
--- /dev/null
+++ b/docs/research/2026-09-28-app-reliability.md
@@ -0,0 +1,111 @@
+# App reliability — September 28, 2026
+
+This pass resumed the September 27 checkpoint and reconciled it with current
+main. The earlier external-engine work and releases remain intact. Main already
+contained PR #367's stale-dialog protection, so this branch preserves its newer
+reviewed-question and spoken-answer validation and adds only the missing guards.
+
+## Changes and regression evidence
+
+| Area | Result | Evidence |
+| --- | --- | --- |
+| CLI launch modes (#371) | `harness new` supplies a default permission mode only when the selected engine implements it. Explicit choices still undergo daemon validation; store harnesses use the underlying engine. | The imported regressions failed before the change; launch and argument tests pass. Adapted from PR #383, `0551e7c6`, by Silexperience210. |
+| Desktop sign-out, expiry, and guest recovery | Account content is removed immediately, local panes restore from the saved desk, the expiry explanation survives, and a new sign-in waits for layout rekey/write/teardown. Failed or cancelled guest sign-in stays usable; Retry completes an interrupted guest restore. Local-manual fixtures never start the real daemon. | Nine native-desktop state regressions cover local/remote panes, delayed or failed persistence, cancellation, and missing guest inventory. A failed layout write preserves the old machine ID and leaves guest recovery retryable. The first six failed on the old implementation. Extends PR #325 by jaylfc. |
+| File/image drops (#73) | Only visible writable panes accept drops. Deferred reads and clipboard completion recheck the pane, session, and stream before delivering input. | Five widget tests cover cached tabs, zoom, and changes during reads. The cross-tab regression fails against main's implementation and passes with the fix. |
+| Lock ownership (#59) | Process timestamps use a fixed locale and UTC. Versioned generation evidence prevents PID reuse; legacy or unknown evidence is conservative. New timestamp records leave the legacy comparison field empty, so an older daemon cannot steal a live new lock during an upgrade. | Daemon and standalone-hook tests cover both migration directions, locales, PID reuse, Linux ticks, unreadable timestamps, and dead PIDs. A live process smoke test also varies locale and timezone. |
+| Hermes managed launchers (#372) | Daemon discovery and the standalone hook recognize both direct imports and `runpy` Python bootstraps, including custom installation directories. Matching requires an actual Python inline launcher and masks string literals before interpreting code. | Five new discovery/hook cases failed before the fix. Positive and negative cases pass afterward. A real Python `-I -I -c` process in a disposable tmux server is discovered and validated. Extends main's `0d779626`. |
+| False terminal eviction | A failed tmux or process-table query remains `unknown` instead of becoming `gone`. The unused boolean validation wrapper and obsolete comments are removed; resume still uses `checkSessionRuntime`. | Both controlled subprocess failures reproduced the old false eviction. Coordinator, backend, and resume tests pass. Live smoke testing recovers from `unknown` to `alive` after restoring the process probe. Addresses one concrete cause related to #105 and corrects #58's obsolete description. |
+| Question routing | A remembered question cannot be redirected to another agent with identical dialog text. Concurrent answers using agent and session aliases share one canonical agent lock. | Two additional regressions, together with main's existing reviewed-answer validation. |
+| Native accessibility input (#249) | Native terminals expose the editable semantics already used by the browser. Accessibility insertion updates the platform buffer; a subsequent echo or typed character does not repeat the phrase. Read-only terminals expose no editing action. | Four new macOS/Linux-platform widget variants failed before the change. Keyboard, IME, focus, and drop tests pass. This verifies the app's accessibility insertion path, not Wispr Flow itself. |
+| Resume process identity | A resume that becomes ready from process evidence persists the verified identity before announcing readiness. Attachment and Stop need not wait for discovery or a delayed hook. | The real Claude resume fixture exposed a null PID after reopening; a focused unit regression reproduced it. Native Claude and Codex acceptance tests now pass. The fixture separately waits for rendering and deferred startup hooks, matching current readiness semantics. |
+| Device pairing | A selected discovery candidate survives one missed mDNS browse. A fresh endpoint takes precedence, and pairing still requires authenticated device identity. | The regression fails before the fix; all 188 device tests pass afterward, including wrong-code, unknown-device, reconnect, and revocation cases. Adapted from PR #354, `ce725639`, by 69tc. |
+| Dependency reproducibility | The pnpm lockfile now includes the existing slugify dependency and its two transitive dependencies, at the same versions already present in the npm lockfile. | Linux CI initially stopped before tests because the dependency was missing. The repaired lockfile passes pnpm 11's frozen-lockfile check without changing package versions. |
+
+The process-launch portability integration cases now have an explicit 15-second
+test budget. A full run under simultaneous native-build load exceeded the old
+five-second unit-test default. Production subprocess deadlines are unchanged.
+Linux CI also exposed the Cursor hook fixture's accidental reliance on an unset
+host XDG config directory. The existing test fails with a temporary XDG root
+before the isolation fix. Equivalent lockfile and Cursor-fixture fixes landed
+in main with PR #365 during verification; the final rebase retains main's
+versions and drops the duplicate repair commits.
+The newly merged native TUI fixture exposed another race on Linux ARM64: pane
+death can be visible before its queued `pane-died` hook runs. The fixture now
+waits for delivery and then requires exactly one hook for every rapid exit.
+Missing hooks still time out, and duplicate hooks still fail with engine/index
+diagnostics. The complete fixture passes locally against `hn` and tmux.
+The ARM64 rerun confirmed that fix, then exposed first paint occurring before
+the command socket was ready. Cleanup now waits for session readiness after
+measuring first paint; the tiny-PTY check waits for its file contents, not just
+file creation. Timing and exact-size assertions remain intact.
+
+## Validation
+
+The final base is `02496104` (PR #365). The complete CLI suite was rerun after
+that integration. Desktop files are unchanged from the complete desktop run
+on `0eeef83b`, including PR #411's Git-context changes. Local checks use macOS
+26.6.2 arm64, Node 22.23.1, and Flutter 3.47.2.
+
+- CLI typecheck and build pass. Full suite: **5,786 passed, 37 skipped**.
+- Desktop: **3,872 passed, 12 skipped**. Analysis has **12 existing informational
+ notices in vendored xterm**, no errors or warnings.
+- Native macOS terminal integration: **2 passed**. The normal debug
+ `lib/main.dart` application was rebuilt afterward, replacing the fixture build.
+- Native Claude and Codex acceptance: saved history and native startup hooks,
+ repeated immediate pause/resume, stable logical identity with new tmux/PID
+ identity, existing-process attachment, receipt replay, recovery of missing
+ conversation IDs, persistence, and preservation of neighboring panes and a
+ surviving shell all pass.
+- Live Hermes-style Python bootstrap: discovery, healthy validation, failed
+ process-query handling, recovery, and locale/timezone-stable lock identity pass.
+- Native TUI acceptance passes: retained exits/signals and exactly-once hooks,
+ history, holder-crash recovery, respawn, startup typeahead, first paint without
+ a terminal-identification reply, and the actual 1×1 PTY size.
+- Installed-engine multiplexer suite on macOS with tmux **3.5a**: **9 passed,
+ 9 skipped**. Discovery and process-only deletion preserve the pane for Claude
+ **2.1.283**, Codex **0.154.0**, OpenCode **1.18.32**, Pi **0.85.1**, Hermes
+ **0.18.0**, and Grok **1.0.34**. The Grok `agent` alias, backend lifecycle,
+ and literal/submitted input cases also pass. Cursor, CommandCode, Devin, Muse,
+ Amp, Kilo, Antigravity, and Copilot have no verified installed executable;
+ the terminal-only row has no engine binary. Those rows are unavailable,
+ not passing. These checks establish process discovery and lifecycle, not
+ credentialed model calls. The installed Hermes uses the older venv launcher;
+ the separate Python smoke above covers the managed inline launcher.
+- Docker-backed local/remote full-stack E2E was **not run**: neither configured
+ Docker endpoint was running. The native acceptance and smoke tests above use
+ their own temporary data, profiles, loopback services, and tmux sockets.
+
+No test changed the user's daemon, tmux server, credentials, engine hooks, or
+installed application. The native application build stays inside this worktree.
+
+Local receipts for this run are under `/private/tmp/harness-reliability-*`;
+focused red/green receipts include `harness-probe-*`, `harness-pair-*`,
+`harness-resume-identity-*`, `harness-accessibility-*`, and `harness-hermes-before.log`.
+Repeat the Docker-backed stack using
+[the development recipe](../development.md#isolated-end-to-end-testing).
+
+## Remaining report triage
+
+These are the limits of this pass, not a claim that every possible reliability
+problem is resolved.
+
+| Report | Current finding / remaining work |
+| --- | --- |
+| #49: GUI cannot find Homebrew tmux | Current main resolves through the user's shell, updates the daemon PATH, and falls back to managed tmux. Startup can also serve without a tmux backend. Existing path/provisioning tests pass; the old second fatal preflight is no longer the daemon path. |
+| #45: closing a pane removes it from other tabs | Current main has per-tab close and shared-pane ownership. Tests preserve another tab's terminal and send no `agent_delete` when closing a view. Global Stop is a separate operation. |
+| #41: reopening shows the top of scrollback | Current main follows delayed initial output and preserves a parked reader's position through reconnect/tab changes. Terminal tail and reconnect tests pass. No fresh reproduction of the reported restart jump here. |
+| #67 / #92: store installation fails without useful diagnostics | Current main sends install phase, error code, and detail, and renders failure-specific recovery guidance. Store/install tests pass. A specific Marp or KiCad failure on another machine still needs its install/doctor log. No real store install was performed in the user's environment. |
+| #105: WSLg pane freezes while tmux continues | The confirmed probe-failure eviction defect is fixed, alongside existing reconnect, stale-connection, keyframe, and stream-routing tests. A Windows/WSLg reproduction and the full Docker-backed transport chain remain unverified. |
+| #50: macOS exiting process retains a port | Current main serializes daemon spawn/handoff and performs SIGINT/SIGTERM cleanup. The reported kernel exit state and unreleasable socket were not reproduced; those mechanisms do not establish a fix for that OS failure. |
+| #284: native raster crash on macOS 27 with mirrored mixed-DPI displays | Needs the affected display setup and full native crash report. The native fixture passed on this host; that is not proof for the reported configuration. |
+| #249: Wispr Flow insertion | The missing native accessibility entry point is fixed and tested. End-to-end dictation using Wispr Flow remains to verify with that application. |
+| #107 / #108 / #110: WSL media, viewer, and unified-exec failures | Need the affected WSL/WSLg runtime. No Windows-specific fix is claimed from macOS tests. |
+| #39: device notification selects the wrong agent | The original report has no reproduction details. Desktop routing tests cover machine/stream identity across tabs; the physical-device notification path still needs a concrete failing trace. |
+| #29: idle tmux sessions accumulate | Idle does not prove a conversation is disposable. Existing Stop/resume retains history; automatic idle cleanup is a retention/product-policy decision, not a safe inferred deletion. |
+| #93: pin store dependencies to immutable revisions | Supply-chain policy and repository-pinning work remains separate from this runtime reliability pass; current path-containment fixes on main were preserved. |
+| PR #366: final-pane tab close / launch-progress UX | Not imported wholesale. It changes workspace behavior beyond these confirmed fixes and still needs its own review. |
+
+Other inventory entries request features or platform support (workflows, SCM,
+Windows/psmux, localization, terminology, completion). They are not treated as
+verified runtime defects. Recent main changes already cover trust groups, mobile
+launching, and web sharing; this pass preserves those changes.
diff --git a/tui/tests/native-terminal.py b/tui/tests/native-terminal.py
index d3ea28e20..27c6d0b59 100644
--- a/tui/tests/native-terminal.py
+++ b/tui/tests/native-terminal.py
@@ -199,9 +199,16 @@ try:
for index in range(10, 22):
wait(lambda: same('list-panes', '-t', f'work:{index}', '-F', '#{pane_dead}:#{pane_dead_status}') == '1:7', f'fast exit {index}')
for kind in ('hn', 'tmux'):
- assert cli(kind, 'show', '-gv', '@died').stdout.split(',').count(f'{index}:7:') == 1
+ # Death is visible before its queued hook necessarily runs. Await delivery,
+ # then check every count together below so duplicate hooks still fail.
+ wait(lambda: cli(kind, 'show', '-gv', '@died').stdout.split(',').count(f'{index}:7:') >= 1,
+ f'{kind} pane-died delivered for fast exit {index}')
capture = cli(kind, 'capture-pane', '-p', '-S', '-1000', '-t', f'work:{index}').stdout
wait(lambda: cli(kind, 'capture-pane', '-p', '-S', '-1000', '-t', f'work:{index}').stdout.count(f'FAST_{index}') == 1, f'{kind} fast output {index}: {capture!r}')
+ for kind in ('hn', 'tmux'):
+ deaths = cli(kind, 'show', '-gv', '@died').stdout.split(',')
+ for index in range(10, 22):
+ assert deaths.count(f'{index}:7:') == 1, (kind, index, deaths)
stop_servers()
ui.proc.wait(timeout=4)
ui.stop()
@@ -231,13 +238,17 @@ try:
elapsed = time.monotonic() - start
assert elapsed < .6, (kind, elapsed)
print(f'PASS {kind} first screen without DA1: {elapsed:.3f}s', flush=True)
+ # First paint can precede the command socket on a fast host. Measure it above,
+ # but do not race cleanup against the session still being created.
+ wait(lambda: cli(kind, 'has-session', '-t', 'work', check=False).returncode == 0,
+ f'{kind} first-screen session ready for cleanup')
cli(kind, 'kill-server')
ui.proc.wait(timeout=4)
ui.stop()
time.sleep(.15)
tiny = BASE / f'{kind}-size'
ui = Terminal(kind, 'new-session', '-s', 'tiny', f'stty size > {shlex.quote(str(tiny))}; sleep 2', cols=1, rows=1)
- wait(tiny.exists, f'{kind} tiny initial size')
+ wait(lambda: tiny.exists() and tiny.read_text().strip(), f'{kind} tiny initial size written')
assert tiny.read_text().strip() == '1 1', (kind, tiny.read_text())
assert cli(kind, 'display-message', '-p', '-t', 'tiny:0', '#{pane_width}x#{pane_height}').stdout.strip() == '1x1'
cli(kind, 'kill-server')