The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): bound managed SSH durable recovery when a scope never restores
Austin Pickett99bc0d184272
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex c3b08a36247..9add01a3345 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -335,6 +335,7 @@ import {managedSshRecoveryScopes,managedSshScopeRole,managedSshTokenPersistencePlan,+ MAX_MANAGED_SSH_RECOVERY_ATTEMPTS,recoverManagedSshScopes,refusedManagedSshUpdate,type RemoteUpdateTarget,@@ -9697,6 +9698,7 @@ function readManagedSshRecoveryRecords(): any[] {record.source?.kind !== 'ssh' ||record.source?.id !== record.connectionId ||!['prepared', 'launching'].includes(record.phase) ||+ (record.attempts !== undefined && (!Number.isSafeInteger(record.attempts) || record.attempts < 0)) ||!Array.isArray(record.scopes) ||record.scopes.length > 256) {@@ -9793,6 +9795,19 @@ function markManagedSshRecoveryLaunching(connectionId, correlationId) {writeManagedSshRecoveryRecords(records)}+function recordManagedSshRecoveryAttempt(connectionId, correlationId, attempts) {+ const records = readManagedSshRecoveryRecords()++ const index = records.findIndex(+ record => record.connectionId === connectionId && record.correlationId === correlationId+ )++ if (index >= 0) {+ records[index] = { ...records[index], attempts }+ writeManagedSshRecoveryRecords(records)+ }+}+function clearManagedSshRecovery(connectionId, correlationId) {const records = readManagedSshRecoveryRecords()@@ -11812,7 +11827,8 @@ async function recoverManagedSshUpdate(record) {try {transport = await openManagedSshUpdateTransport(record.source)- const results = await recoverManagedSshScopes<any>({+ const { attempts, disposition, results } = await recoverManagedSshScopes<any>({+ attempts: record.attempts ?? 0,scopes: record.scopes,awaitClearance: () =>waitForManagedRemoteClearance(transport!.target, record.correlationId, {@@ -11828,17 +11844,28 @@ async function recoverManagedSshUpdate(record) {: scope.kind === 'legacy'? ensureManagedSshBackendAtKey(record.source, scope.profile, scope.key, recoveryCorrelation, 'profile'): ensureManagedSshBackend(record.source, scope.profile, recoveryCorrelation),- completeRecovery: async () => clearManagedSshRecovery(connectionId, record.correlationId)+ completeRecovery: async () => clearManagedSshRecovery(connectionId, record.correlationId),+ recordFailedAttempt: async next => recordManagedSshRecoveryAttempt(connectionId, record.correlationId, next)})- if (results.every(result => result.status === 'fulfilled')) {+ const unrestored = record.scopes+ .filter((_scope, index) => results[index]?.status === 'rejected')+ .map(scope => scope.profile)++ if (disposition === 'complete') {sshRememberLog(`[ssh-update] restored ${record.scopes.length} scope(s) from durable recovery for ${connectionId}`)+ } else if (disposition === 'abandon') {+ sshRememberLog(+ `[ssh-update] durable recovery for ${connectionId} stopped after ${attempts} attempt(s); ` ++ `connection released with ${unrestored.length} scope(s) not restored (${unrestored.join(', ')}). ` ++ 'Reconnecting starts them again.'+ )} else {- const failures = results.filter(result => result.status === 'rejected').lengthsshRememberLog(- `[ssh-update] durable recovery for ${connectionId} left ${failures} scope(s) pending; will retry next launch`+ `[ssh-update] durable recovery for ${connectionId} left ${unrestored.length} scope(s) pending ` ++ `(attempt ${attempts} of ${MAX_MANAGED_SSH_RECOVERY_ATTEMPTS}); will retry next launch`)}} catch (error: any) {diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.tsindex 93aca8da4ce..4f263a5942d 100644--- a/apps/desktop/electron/managed-ssh-update.test.ts+++ b/apps/desktop/electron/managed-ssh-update.test.ts@@ -13,9 +13,11 @@ import {buildWindowsManagedUpdateLaunch,fenceManagedSshBootstrapPublication,ManagedConnectionUpdateGate,+ managedSshRecoveryDisposition,managedSshRecoveryScopes,managedSshScopeRole,managedSshTokenPersistencePlan,+ MAX_MANAGED_SSH_RECOVERY_ATTEMPTS,parseRemoteUpdateObservation,RECEIPT_GRACE_MS,recoverManagedSshScopes,@@ -100,14 +102,105 @@ test('inactive SSH crash recovery keeps ordinary dials fenced until positive cleassert.throws(() => relaunchedGate.assertCanDial('homelab'), /paused/)assert.equal(journalCleared, false)releaseClearance()- const results = await recovery+ const { disposition, results } = await recovery+ assert.equal(disposition, 'complete')assert.deepEqual(results, [])assert.equal(restoreCalls, 0)assert.equal(journalCleared, true)assert.doesNotThrow(() => relaunchedGate.assertCanDial('homelab'))})+test('durable recovery disposition is bounded once the remote install is clear', () => {+ const max = MAX_MANAGED_SSH_RECOVERY_ATTEMPTS++ assert.equal(managedSshRecoveryDisposition({ attempts: 0, restoreFailures: 0, updateSucceeded: false }), 'complete')+ assert.equal(managedSshRecoveryDisposition({ attempts: 1, restoreFailures: 1, updateSucceeded: false }), 'retry')+ assert.equal(+ managedSshRecoveryDisposition({ attempts: max - 1, restoreFailures: 1, updateSucceeded: false }),+ 'retry'+ )+ assert.equal(managedSshRecoveryDisposition({ attempts: max, restoreFailures: 1, updateSucceeded: false }), 'abandon')+ assert.equal(managedSshRecoveryDisposition({ attempts: 1, restoreFailures: 2, updateSucceeded: true }), 'abandon')+ assert.equal(+ managedSshRecoveryDisposition({ attempts: 2, maxAttempts: 5, restoreFailures: 1, updateSucceeded: false }),+ 'retry'+ )+})++async function relaunchRecoveryWithStuckScope(options: {+ attempts: number+ clearance?: { exitCode: null | number; receipt: null | { correlationId: string; outcome: string } }+}) {+ let durableOwner: string | null = CORRELATION+ let recordedAttempts: null | number = null+ const gate = new ManagedConnectionUpdateGate(id => (id === 'homelab' ? durableOwner : null))++ const outcome = await recoverManagedSshScopes({+ attempts: options.attempts,+ scopes: [{ profile: 'default' }, { profile: 'stuck' }],+ awaitClearance: async () => options.clearance ?? { exitCode: null, receipt: null },+ restoreScope: async scope => {+ if (scope.profile === 'stuck') {+ throw new Error('serve never became healthy')+ }+ },+ recordFailedAttempt: async next => {+ recordedAttempts = next+ },+ completeRecovery: async () => {+ durableOwner = null+ }+ })++ return { gate, outcome, recordedAttempts }+}++test('a scope that never restores stops fencing the connection after bounded relaunch attempts (#107827)', async () => {+ const first = await relaunchRecoveryWithStuckScope({ attempts: 0 })++ assert.equal(first.outcome.disposition, 'retry')+ assert.equal(first.recordedAttempts, 1)+ assert.throws(() => first.gate.assertCanDial('homelab'), /paused/)+ assert.throws(() => first.gate.assertCanMutate('homelab'), /edited or removed/)++ const last = await relaunchRecoveryWithStuckScope({ attempts: MAX_MANAGED_SSH_RECOVERY_ATTEMPTS - 1 })++ assert.equal(last.outcome.disposition, 'abandon')+ assert.equal(last.outcome.attempts, MAX_MANAGED_SSH_RECOVERY_ATTEMPTS)+ assert.equal(last.recordedAttempts, null)+ assert.deepEqual(+ last.outcome.results.map(result => result.status),+ ['fulfilled', 'rejected']+ )+ assert.doesNotThrow(() => last.gate.assertCanDial('homelab'))+ assert.doesNotThrow(() => last.gate.assertCanMutate('homelab'))+})++test('a correlated remote exit 0 ends durable recovery on the first failed restore', async () => {+ const success = await relaunchRecoveryWithStuckScope({+ attempts: 0,+ clearance: { exitCode: 0, receipt: { correlationId: CORRELATION, outcome: 'success' } }+ })++ assert.equal(success.outcome.disposition, 'abandon')+ assert.doesNotThrow(() => success.gate.assertCanDial('homelab'))++ // Reported shape: `.update_exit_code.<correlation>` is 0 but no receipt was written.+ const exitOnly = await relaunchRecoveryWithStuckScope({ attempts: 0, clearance: { exitCode: 0, receipt: null } })++ assert.equal(exitOnly.outcome.disposition, 'abandon')+ assert.doesNotThrow(() => exitOnly.gate.assertCanDial('homelab'))++ const failed = await relaunchRecoveryWithStuckScope({+ attempts: 0,+ clearance: { exitCode: 1, receipt: { correlationId: CORRELATION, outcome: 'failed' } }+ })++ assert.equal(failed.outcome.disposition, 'retry')+ assert.throws(() => failed.gate.assertCanDial('homelab'), /paused/)+})+test('managed update joins a pre-claim bootstrap until its final gate check rolls back the serve', async () => {const gate = new ManagedConnectionUpdateGate()const coordinator = createBootstrapCoordinator()@@ -779,6 +872,59 @@ test('managed lifecycle attempts every drain and every restore when one ownershiassert.match(result.error || '', /foreign owner/)})+async function updateWithStuckRestore(exitCode: number, outcome: string) {+ let journalCleared = false++ const result = await runManagedSshUpdate({+ connectionId: 'home',+ correlationId: CORRELATION,+ scopes: [+ { key: 'a', profile: 'default' },+ { key: 'b', profile: 'stuck' }+ ],+ preflightRemote: async () => {},+ prepareRecovery: async () => {},+ drainScope: async () => {},+ updateRemote: async () => ({ exitCode, receipt: { correlationId: CORRELATION, outcome } }),+ awaitRestoreClearance: async () => {},+ closeTransports: async () => {},+ restoreScope: async scope => {+ if (scope.profile === 'stuck') {+ throw new Error('serve never became healthy')+ }+ },+ completeRecovery: async () => {+ journalCleared = true+ },+ releaseGate: () => {}+ })++ return { journalCleared, result }+}++test('a successful update clears the journal even when one scope fails to restore (#107827)', async () => {+ const { journalCleared, result } = await updateWithStuckRestore(0, 'success')++ assert.equal(journalCleared, true)+ assert.equal(result.updateOk, true)+ assert.equal(result.restoreOk, false)+ assert.equal(result.outcome, 'restore-failed')+ assert.deepEqual(+ result.scopes.map(scope => [scope.profile, scope.restored]),+ [+ ['default', true],+ ['stuck', false]+ ]+ )+})++test('a failed update keeps the journal for relaunch recovery when a scope fails to restore', async () => {+ const { journalCleared, result } = await updateWithStuckRestore(1, 'failed')++ assert.equal(journalCleared, false)+ assert.equal(result.outcome, 'update-and-restore-failed')+})+test('managed lifecycle journals before drain and leaves scopes stopped when clearance cannot be proved', async () => {const events: string[] = []diff --git a/apps/desktop/electron/managed-ssh-update.ts b/apps/desktop/electron/managed-ssh-update.tsindex 3efb3b791e0..30af832e6b4 100644--- a/apps/desktop/electron/managed-ssh-update.ts+++ b/apps/desktop/electron/managed-ssh-update.ts@@ -22,6 +22,9 @@ const DEFAULT_REMOTE_UPDATE_TIMEOUT_MS = 60 * 60 * 1000const DEFAULT_REMOTE_CLEARANCE_TIMEOUT_MS = 5 * 60 * 1000const DEFAULT_REMOTE_UPDATE_POLL_MS = 1_000const RECEIPT_GRACE_MS = 15_000+// Durable recovery retries a scope that failed to restore on each launch, but+// only this many times: after that the journal stops fencing the connection.+const MAX_MANAGED_SSH_RECOVERY_ATTEMPTS = 3const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/type ManagedUpdateOutcome = 'updated' | 'update-failed' | 'restore-failed' | 'update-and-restore-failed' | 'refused'@@ -96,7 +99,7 @@ interface ManagedUpdateDeps<TScope extends ManagedSshScope = ManagedSshScope> {preflightRemote: () => Promise<void>drainScope: (scope: TScope) => Promise<void>updateRemote: () => Promise<RemoteUpdateProof>- awaitRestoreClearance: () => Promise<void>+ awaitRestoreClearance: () => Promise<unknown>closeTransports: () => Promise<void>restoreScope: (scope: TScope) => Promise<unknown>releaseGate: () => void@@ -716,7 +719,7 @@ async function waitForManagedRemoteClearance(sleep?: (ms: number) => Promise<void>requireTerminal?: boolean} = {}-): Promise<void> {+): Promise<RemoteUpdateObservation> {const timeoutMs = options.timeoutMs ?? DEFAULT_REMOTE_CLEARANCE_TIMEOUT_MSconst pollMs = options.pollMs ?? DEFAULT_REMOTE_UPDATE_POLL_MSconst now = options.now || Date.now@@ -741,7 +744,7 @@ async function waitForManagedRemoteClearance(observation.exitCode !== null ||observation.receipt !== null) {- return+ return observation}}} catch {@@ -761,6 +764,40 @@ async function waitForManagedRemoteClearance(}}+type ManagedSshRecoveryDisposition = 'abandon' | 'complete' | 'retry'++// Only meaningful once the remote install marker is positively clear: the+// mutator is gone, so the durable fence protects nothing except the retry of+// scopes that failed to restore. Bound that retry instead of fencing forever+// (#107827). A correlated exit 0 ends it at once; otherwise stop+// after MAX_MANAGED_SSH_RECOVERY_ATTEMPTS failed attempts. An abandoned scope+// is just a stopped service: the next ordinary dial starts it again.+function managedSshRecoveryDisposition(input: {+ attempts: number+ maxAttempts?: number+ restoreFailures: number+ updateSucceeded: boolean+}): ManagedSshRecoveryDisposition {+ if (input.restoreFailures === 0) {+ return 'complete'+ }++ if (input.updateSucceeded || input.attempts >= (input.maxAttempts ?? MAX_MANAGED_SSH_RECOVERY_ATTEMPTS)) {+ return 'abandon'+ }++ return 'retry'+}++// The correlated terminal exit code is proof on its own: some backends exit 0+// without writing a receipt (#101516). A receipt that reports a non-success+// outcome still vetoes it.+function remoteUpdateSucceeded(observation: null | Pick<RemoteUpdateObservation, 'exitCode' | 'receipt'> | void) {+ return Boolean(+ observation && observation.exitCode === 0 && (!observation.receipt || observation.receipt.outcome === 'success')+ )+}+function errorMessage(error: unknown): string {return error instanceof Error ? error.message : String(error)}@@ -858,7 +895,16 @@ async function runManagedSshUpdate<TScope extends ManagedSshScope>(}try {- if (recoveryPrepared && !restorationBlocked && restoreResults.every(result => result.restored)) {+ const disposition = managedSshRecoveryDisposition({+ attempts: 0,+ restoreFailures: restoreResults.filter(result => !result.restored).length,+ updateSucceeded: remoteUpdateSucceeded(proof)+ })++ // A scope that fails to restore after a proven-successful update must not+ // leave the connection fenced until relaunch; its failure is reported in+ // `scopes` and the next dial starts it again.+ if (recoveryPrepared && !restorationBlocked && disposition !== 'retry') {await deps.completeRecovery?.()}} catch (error) {@@ -930,23 +976,42 @@ async function waitForManagedUpdateOperations(getOperations: () => Iterable<Promasync function recoverManagedSshScopes<TScope>(deps: {afterClearance?: () => Promise<void>- awaitClearance: () => Promise<void>+ // Failed attempts already recorded in the journal, not counting this one.+ attempts?: number+ awaitClearance: () => Promise<null | Pick<RemoteUpdateObservation, 'exitCode' | 'receipt'> | void>completeRecovery: () => Promise<void>+ maxAttempts?: number+ recordFailedAttempt?: (attempts: number) => Promise<void>restoreScope: (scope: TScope) => Promise<unknown>scopes: TScope[]-}): Promise<PromiseSettledResult<unknown>[]> {- await deps.awaitClearance()+}): Promise<{+ attempts: number+ disposition: ManagedSshRecoveryDisposition+ results: PromiseSettledResult<unknown>[]+}> {+ const clearance = await deps.awaitClearance()await deps.afterClearance?.()const results = await Promise.allSettled(deps.scopes.map(scope => deps.restoreScope(scope)))-- if (results.every(result => result.status === 'fulfilled')) {+ const restoreFailures = results.filter(result => result.status === 'rejected').length+ const attempts = (deps.attempts ?? 0) + (restoreFailures > 0 ? 1 : 0)++ const disposition = managedSshRecoveryDisposition({+ attempts,+ maxAttempts: deps.maxAttempts,+ restoreFailures,+ updateSucceeded: remoteUpdateSucceeded(clearance)+ })++ if (disposition === 'retry') {+ await deps.recordFailedAttempt?.(attempts)+ } else {// This intentionally runs for an empty scope list. An inactive connection// still journals the detached mutator so a crash/relaunch remains fenced;// positive marker clearance is what authorizes removing that durable gate.await deps.completeRecovery()}- return results+ return { attempts, disposition, results }}async function fenceManagedSshBootstrapPublication<T>(deps: {@@ -1056,6 +1121,7 @@ export {launchManagedRemoteUpdate,ManagedConnectionUpdateGate,type ManagedConnectionUpdateResult,+ managedSshRecoveryDisposition,type ManagedSshRecoveryScope,managedSshRecoveryScopes,type ManagedSshScope,@@ -1066,6 +1132,7 @@ export {type ManagedUpdateReceiptSummary,type ManagedUpdateScopeResult,markerIsClear,+ MAX_MANAGED_SSH_RECOVERY_ATTEMPTS,observeManagedRemoteUpdate,parseRemoteUpdateObservation,RECEIPT_GRACE_MS,