The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): cancel timed-out gateway activations
Zeus-Deusb687c6b2c15e
diff --git a/apps/desktop/src/lib/with-timeout.ts b/apps/desktop/src/lib/with-timeout.tsindex e8cde975162..83b3e035bc8 100644--- a/apps/desktop/src/lib/with-timeout.ts+++ b/apps/desktop/src/lib/with-timeout.ts@@ -11,10 +11,22 @@ export function isTimeoutError(error: unknown): error is TimeoutError {return error instanceof TimeoutError}-/** Settle with `promise`, or reject with a TimeoutError after `ms`. */-export function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {+/** Settle with `promise`, or reject with a TimeoutError after `ms`.+ * `onTimeout` runs synchronously before the rejection is published so callers+ * can revoke ownership of work that would otherwise keep running unowned. */+export function withTimeout<T>(+ promise: Promise<T>,+ ms: number,+ message: string,+ onTimeout?: (error: TimeoutError) => void+): Promise<T> {return new Promise<T>((resolve, reject) => {- const timer = setTimeout(() => reject(new TimeoutError(message)), ms)+ const timer = setTimeout(() => {+ const error = new TimeoutError(message)++ onTimeout?.(error)+ reject(error)+ }, ms)Promise.resolve(promise).then(value => {diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.tsindex 9c4afe7f31b..b0fc2849804 100644--- a/apps/desktop/src/store/connections.test.ts+++ b/apps/desktop/src/store/connections.test.ts@@ -23,6 +23,7 @@ const $gatewaySwitching = atom(false)interface ActivationOptions {beforeActivate?: () => boolean+ signal?: AbortSignal}const ensureGatewayAgent = vi.fn(@@ -112,7 +113,7 @@ beforeEach(() => {ensureGatewayAgent.mockReset()// Mirrors the real door: the commit hook runs right before the activation// publishes, and a declined hook publishes nothing.- ensureGatewayAgent.mockImplementation(async (connectionId, _profile, options) => {+ ensureGatewayAgent.mockImplementation(async (connectionId, profile, options) => {if (options?.beforeActivate && !options.beforeActivate()) {return}@@ -120,7 +121,7 @@ beforeEach(() => {$connection.set({connectionId: connectionId ?? undefined,mode: connectionId === 'local' ? 'local' : 'remote',- profile: 'default',+ profile,registryScoped: true})})@@ -445,6 +446,48 @@ describe('selectConnection', () => {expect($pendingConnectionId.get()).toBeNull()})+ it('does not spend the activation timeout while waiting for the serialized commit turn', async () => {+ vi.useFakeTimers()++ try {+ const mutex = deferred()++ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })+ ensureGatewayAgent.mockImplementationOnce(async (connectionId, _profile, options) => {+ await mutex.promise++ if (options?.beforeActivate && !options.beforeActivate()) {+ return+ }++ $connection.set({+ connectionId: connectionId ?? undefined,+ mode: 'remote',+ profile: 'default',+ registryScoped: true+ })+ })++ const attempt = selectConnection('homelab')+ await vi.waitFor(() => expect(ensureGatewayAgent).toHaveBeenCalledTimes(1))++ // Queue ownership belongs to the shared mutex, not the actual activation+ // attempt, so waiting here must not consume its 20-second commit budget.+ await vi.advanceTimersByTimeAsync(20_000)+ expect(beginGatewaySwitch).not.toHaveBeenCalled()++ mutex.resolve()+ await attempt++ expect($connection.get()?.connectionId).toBe('homelab')+ expect(beginGatewaySwitch).toHaveBeenCalledTimes(1)+ expect($gatewaySwitching.get()).toBe(false)+ } finally {+ vi.useRealTimers()+ }+ })+it('a dial that never answers times out: nothing severed, the click fails visibly, and the source can be retried', async () => {vi.useFakeTimers()@@ -546,6 +589,56 @@ describe('selectConnection', () => {}})+ it('a timed-out activation cannot publish the target after it eventually settles', async () => {+ vi.useFakeTimers()++ try {+ const activation = deferred()++ setConnectionsRegistry(registry)+ $connection.set({ connectionId: 'local', mode: 'local' })+ ensureGatewayAgent.mockImplementationOnce(async (connectionId, _profile, options) => {+ options?.beforeActivate?.()+ await activation.promise++ // Mirrors the real activation door: cancellation ownership is checked+ // immediately before publishing after the async activation work.+ if (options?.signal?.aborted) {+ return+ }++ $connection.set({+ connectionId: connectionId ?? undefined,+ mode: 'remote',+ profile: 'default',+ registryScoped: true+ })+ })++ const outcome = selectConnection('homelab').then(+ () => 'resolved',+ (error: Error) => error.message+ )++ await vi.advanceTimersByTimeAsync(20_000)++ expect(await outcome).toMatch(/Timed out activating "Homelab"/)+ expect($connection.get()?.connectionId).toBe('local')+ expect($gatewaySwitching.get()).toBe(false)++ activation.resolve()+ await vi.advanceTimersByTimeAsync(0)++ expect($connection.get()?.connectionId).toBe('local')+ expect(beginGatewaySwitch).toHaveBeenCalledTimes(1)+ expect(endGatewaySwitch).toHaveBeenCalledTimes(1)+ expect($gatewaySwitching.get()).toBe(false)+ expect($pendingConnectionId.get()).toBeNull()+ } finally {+ vi.useRealTimers()+ }+ })+it('boot-time restore leaves "All profiles" browse mode on (#93197)', async () => {// Fresh boot: nothing active yet, registry restores last-used. The// persisted showAllProfiles=true must survive the silent restore.diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.tsindex 16265b88ea9..e47e3f8057c 100644--- a/apps/desktop/src/store/connections.ts+++ b/apps/desktop/src/store/connections.ts@@ -220,6 +220,12 @@ export async function selectConnection(connectionId: string): Promise<void> {const targetProfile = normalizeProfileKey($lastProfileByConnection.get()[connectionId] ?? 'default')const targetKey = `${connectionId}::${targetProfile}`+ const targetIsActive = () => {+ const active = $connection.get()++ return active?.connectionId === connectionId && normalizeProfileKey(active.profile) === targetProfile+ }+if (pendingTarget === targetKey) {return}@@ -275,29 +281,56 @@ export async function selectConnection(connectionId: string): Promise<void> {// backend's bindings, then publish, with nothing in between. A click that// superseded this switch while it was queued makes the hook decline —// neither wipe nor activation — so the user never flips through it.+ const activationController = new AbortController()+ let markActivationStarted: () => void = () => undefined++ const activationStarted = new Promise<void>(resolve => {+ markActivationStarted = resolve+ })+try {try {- await withTimeout(- ensureGatewayAgent(connectionId, targetProfile, {- beforeActivate: () => {- if (revision !== switchRevision) {- return false- }-- token = beginGatewaySwitch()+ const activation = ensureGatewayAgent(connectionId, targetProfile, {+ signal: activationController.signal,+ beforeActivate: () => {+ if (revision !== switchRevision) {+ return false+ }- return true+ token = beginGatewaySwitch()+ markActivationStarted()++ return true+ }+ })++ const timedActivation = activationStarted.then(() =>+ withTimeout(+ activation,+ SWITCH_COMMIT_TIMEOUT_MS,+ `Timed out activating "${targetConnection.label}".`,+ error => {+ // withTimeout does not cancel its input. Revoke this activation's+ // ownership before publishing the timeout so a queued/stalled+ // ensure cannot wake later and commit without a caller. If the+ // gateway already published the target, the commit landed and its+ // trailing descriptor resync remains a harmless fail-open straggler.+ if (!targetIsActive()) {+ activationController.abort(error)+ }}- }),- SWITCH_COMMIT_TIMEOUT_MS,- `Timed out activating "${targetConnection.label}".`+ ))++ // Queue time belongs to the profile-store mutex. Start the bounded+ // commit window only once beforeActivate grants this request its turn.+ await Promise.race([activation, timedActivation])} catch (error) {// The socket is activated and its descriptor published synchronously;// only the best-effort descriptor resync trails it. A commit that timed// out AFTER the new source became active has landed — the straggler is// fail-open and cannot undo it.- if (!isTimeoutError(error) || $connection.get()?.connectionId !== connectionId) {+ if (!isTimeoutError(error) || !targetIsActive()) {throw error}}@@ -306,7 +339,7 @@ export async function selectConnection(connectionId: string): Promise<void> {return}- if ($connection.get()?.connectionId !== connectionId) {+ if (!targetIsActive()) {throw new Error(`Connection "${targetConnection.label}" did not become active.`)}} finally {diff --git a/apps/desktop/src/store/gateway-profile-request.test.ts b/apps/desktop/src/store/gateway-profile-request.test.tsindex 2aa098f5deb..dc297e91d0c 100644--- a/apps/desktop/src/store/gateway-profile-request.test.ts+++ b/apps/desktop/src/store/gateway-profile-request.test.ts@@ -370,6 +370,39 @@ describe('requestGatewayForAgent', () => {expect(onActiveConnectionChanged).not.toHaveBeenCalled()expect($gateway.get()).toBe(primary)})++ it('does not activate or publish a source whose activation owner aborted while dialing', async () => {+ const primary = makePrimary()+ const onActiveConnectionChanged = vi.fn()+ const controller = new AbortController()++ setPrimaryGateway(primary as never, 'default')+ configureGatewayRegistry({ onActiveConnectionChanged, onEvent: vi.fn() })+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {+ getConnection: vi.fn(async profile => ({ port: 4242, profile })),+ getConnectionFor: vi.fn(async ({ connectionId, profile }) => ({ connectionId, port: 5151, profile })),+ getGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }) => ({+ ok: true as const,+ wsUrl: `ws://${connectionId}/${profile}`+ })),+ touchBackend: vi.fn(async () => undefined)+ }+ await ensureGatewayForProfile('default')++ let releaseConnect: () => void = () => undefined+ connectGate = new Promise<void>(resolve => {+ releaseConnect = resolve+ })+ const abandoned = ensureGatewayForAgent('source-b', 'default', { signal: controller.signal })+ await vi.waitFor(() => expect(secondaryGateways[0]?.connect).toHaveBeenCalledOnce())++ controller.abort()+ releaseConnect()++ expect(await abandoned).toBe(false)+ expect(onActiveConnectionChanged).not.toHaveBeenCalled()+ expect($gateway.get()).toBe(primary)+ })})describe('retainGatewayForAgent (#93602)', () => {diff --git a/apps/desktop/src/store/gateway-switch.test.ts b/apps/desktop/src/store/gateway-switch.test.tsindex 089ede4019a..a6a67f7157f 100644--- a/apps/desktop/src/store/gateway-switch.test.ts+++ b/apps/desktop/src/store/gateway-switch.test.ts@@ -148,6 +148,31 @@ describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit poiexpect($gatewaySwitching.get()).toBe(false)})+ it('repeated overlapping commits safely re-run the lifecycle and wipe without losing barrier ownership', () => {+ const beforeConnectionSwitch = vi.fn()++ const off = registerGatewaySwitchLifecycle({+ beforeConnectionSwitch,+ refreshSessions: async () => undefined+ })++ const older = beginGatewaySwitch()+ // Simulate stale gateway-bound state racing back before the newer commit.+ setSessions([{ id: 'late', title: 'late old-source row', profile: 'default' } as never])+ setActiveSessionId('late-runtime')+ const newer = beginGatewaySwitch()++ expect(beforeConnectionSwitch).toHaveBeenCalledTimes(2)+ expect($sessions.get()).toEqual([])+ expect($activeSessionId.get()).toBeNull()++ endGatewaySwitch(older)+ expect($gatewaySwitching.get()).toBe(true)+ endGatewaySwitch(newer)+ expect($gatewaySwitching.get()).toBe(false)+ off()+ })+it('still severs the bindings when no lifecycle is registered (windows that never mount the boot hook)', () => {beginGatewaySwitch()@@ -217,7 +242,14 @@ describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit poioff()setSessionsLoading(true)+ const debug = vi.spyOn(console, 'debug').mockImplementation(() => undefined)+recoverActiveSourceAfterFailedGatewaySwitch()await vi.waitFor(() => expect($sessionsLoading.get()).toBe(false))++ expect(debug).toHaveBeenCalledWith(+ '[gateway-switch] cannot repaint the active source because no switch lifecycle is registered'+ )+ debug.mockRestore()})})diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.tsindex ca15235b4dd..3348274cc0c 100644--- a/apps/desktop/src/store/gateway-switch.ts+++ b/apps/desktop/src/store/gateway-switch.ts@@ -107,8 +107,17 @@ export function endGatewaySwitch(token?: GatewaySwitchToken): void {* always disarms.*/export function recoverActiveSourceAfterFailedGatewaySwitch(): void {+ const lifecycle = switchLifecycle++ if (!lifecycle) {+ console.debug('[gateway-switch] cannot repaint the active source because no switch lifecycle is registered')+ setSessionsLoading(false)++ return+ }+void Promise.resolve()- .then(() => switchLifecycle?.refreshSessions())+ .then(() => lifecycle.refreshSessions()).catch(() => undefined).finally(() => setSessionsLoading(false))}diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex efb72c7a9e4..50821490f46 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -912,13 +912,21 @@ export async function openGatewayForAgent(}}-export async function ensureGatewayForAgent(connectionId: null | string, profile: string): Promise<boolean> {+export async function ensureGatewayForAgent(+ connectionId: null | string,+ profile: string,+ { signal }: { signal?: AbortSignal } = {}+): Promise<boolean> {const scope = registryBackendScopeKey(connectionId, profile)if (scope === normKey(profile)) {+ if (signal?.aborted) {+ return false+ }+await ensureGatewayForProfile(profile)- return true+ return !signal?.aborted}if (!window.hermesDesktop?.getConnectionFor) {@@ -955,6 +963,12 @@ export async function ensureGatewayForAgent(connectionId: null | string, profile// The activation is settling either way — release the prune lease.entry.activationLeaseUntil = 0+ // A timed-out owner may leave the dial running, but it no longer has the+ // right to move the foreground route when that work eventually settles.+ if (signal?.aborted) {+ return false+ }+// A source edit/remove may dispose this entry while its dial is still in// flight. Only the still-registered, still-owned activation may publish.const activated =diff --git a/apps/desktop/src/store/profile-agent-activation.test.ts b/apps/desktop/src/store/profile-agent-activation.test.tsindex 24a73db609c..74408a2619e 100644--- a/apps/desktop/src/store/profile-agent-activation.test.ts+++ b/apps/desktop/src/store/profile-agent-activation.test.ts@@ -274,4 +274,38 @@ describe('ensureGatewayAgent commit hook (beforeActivate) — the Sessions switcvi.useRealTimers()}})++ it('an aborted activation releases the mutex and cannot publish when its work settles later', async () => {+ const activationGate = deferred()+ const controller = new AbortController()++ ensureGatewayForAgent.mockImplementationOnce(async () => {+ await activationGate.promise++ return true+ })+ getConnectionFor.mockImplementation(async ({ profile }) => agentConn({ profile: profile ?? 'default' }))++ const abandoned = ensureGatewayAgent('homelab', 'research', { signal: controller.signal })+ await vi.waitFor(() => expect(ensureGatewayForAgent).toHaveBeenCalledTimes(1))++ controller.abort()++ try {+ const winner = ensureGatewayAgent('homelab', 'writer')+ await vi.waitFor(() => expect(ensureGatewayForAgent).toHaveBeenCalledTimes(2))+ await winner++ expect($activeGatewayProfile.get()).toBe('writer')+ expect($connection.get()?.profile).toBe('writer')+ } finally {+ activationGate.resolve()+ await abandoned+ }++ // The detached activation completed after cancellation but did not regain+ // ownership and overwrite the newer source/profile publication.+ expect($activeGatewayProfile.get()).toBe('writer')+ expect($connection.get()?.profile).toBe('writer')+ })})diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex d35062c0904..3a7a50caa14 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -470,12 +470,42 @@ export async function openGatewayAgent(connectionId: string, profile: string): P// null-connectionId profile fallthrough.export interface EnsureGatewayAgentOptions {beforeActivate?: () => boolean+ /** Revokes this caller's right to activate or publish after async work. */+ signal?: AbortSignal+}++function releaseWhenAborted(promise: Promise<void>, signal?: AbortSignal): Promise<void> {+ if (!signal) {+ return promise+ }++ if (signal.aborted) {+ return Promise.resolve()+ }++ return new Promise<void>((resolve, reject) => {+ const onAbort = () => {+ signal.removeEventListener('abort', onAbort)+ resolve()+ }++ const settle = (callback: () => void) => {+ signal.removeEventListener('abort', onAbort)+ callback()+ }++ signal.addEventListener('abort', onAbort, { once: true })+ promise.then(+ () => settle(resolve),+ error => settle(() => reject(error))+ )+ })}export async function ensureGatewayAgent(connectionId: null | string,profile: string,- { beforeActivate }: EnsureGatewayAgentOptions = {}+ { beforeActivate, signal }: EnsureGatewayAgentOptions = {}): Promise<void> {const target = normalizeProfileKey(profile)const connection = (connectionId ?? '').trim() || null@@ -492,18 +522,32 @@ export async function ensureGatewayAgent(await gatewaySwitch.catch(() => undefined)}+ if (signal?.aborted) {+ return+ }+$gatewaySwapTarget.set(target)- gatewaySwitch = (async () => {++ const activationWork = (async () => {+ if (signal?.aborted) {+ return+ }+if (beforeActivate && !beforeActivate()) {return}// Descriptor resolves concurrently with the dial, same as the profile// path, so no await sits between the activation and the publication.- const [descriptor, activated] = await Promise.all([- resolveConnectionForAgent(connection, target),- ensureGatewayForAgent(connection, target)- ])+ const activation = signal+ ? ensureGatewayForAgent(connection, target, { signal })+ : ensureGatewayForAgent(connection, target)++ const [descriptor, activated] = await Promise.all([resolveConnectionForAgent(connection, target), activation])++ if (signal?.aborted) {+ return+ }if (!activated) {// The target stopped existing mid-dial (source edited/removed). Keep@@ -527,6 +571,10 @@ export async function ensureGatewayAgent(})})()+ // Cancellation releases the mutex immediately; activationWork remains+ // observed and is ownership-guarded at both gateway and publication seams.+ gatewaySwitch = releaseWhenAborted(activationWork, signal)+try {await gatewaySwitch} finally {