The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): move the update-hold boot case to its own test file
Teknium3a453d26c20f
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot-update-hold.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-update-hold.test.tsxnew file mode 100644index 00000000000..766ee10091f--- /dev/null+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot-update-hold.test.tsx@@ -0,0 +1,170 @@+import { act, cleanup, render } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { $desktopBoot } from '@/store/boot'+import { closeSecondaryGateways } from '@/store/gateway'+import { $activeGatewayProfile } from '@/store/profile'+import { $connection, $gatewayState } from '@/store/session'++import { FakeWebSocket } from '../../../test/fake-gateway-socket'++import { takeGatewaySurvivor } from './gateway-hmr-survivor'+import { useGatewayBoot } from './use-gateway-boot'++// The blocked update-hold screen's renderer leg (R8 D3/M6): a hold the main+// process publishes on boot progress lands in $desktopBoot even after boot.+// Shares the fake socket with use-gateway-boot.test.tsx; the desktop bridge+// here carries only what the boot hook touches.++vi.mock(import('@/store/notifications'), async importOriginal => ({+ ...(await importOriginal()),+ notifyError: vi.fn()+}))++vi.mock(import('@/store/terminal-backend-warning'), () => ({+ warnIfTerminalBackendUnavailable: vi.fn(async () => false)+}))++const primaryConn = {+ authMode: 'token' as const,+ baseUrl: 'https://vps.example.com',+ connectionId: 'primary-vps',+ profile: 'default',+ token: 't',+ wsUrl: 'wss://vps.example.com/api/ws?token=t'+}++function fakeDesktop() {+ let bootProgressHandler: ((payload: Record<string, unknown>) => void) | null = null+ const unsubscribe = () => () => undefined++ return {+ getConnection: vi.fn(async () => primaryConn),+ getGatewayWsUrl: vi.fn(async (conn?: { wsUrl?: string }) => conn?.wsUrl ?? primaryConn.wsUrl),+ getBootProgress: vi.fn(async () => ({+ error: null,+ fakeMode: false,+ message: '',+ phase: 'init',+ progress: 0,+ retryable: false,+ running: true,+ timestamp: Date.now()+ })),+ onBootProgress: vi.fn(callback => {+ bootProgressHandler = callback++ return () => {+ bootProgressHandler = null+ }+ }),+ emitBootProgress(payload: Record<string, unknown>) {+ bootProgressHandler?.(payload)+ },+ onBackendExit: vi.fn(unsubscribe),+ onConnectionApplied: vi.fn(unsubscribe),+ onPowerResume: vi.fn(unsubscribe),+ revalidateConnection: vi.fn(async () => ({ ok: true, rebuilt: false })),+ onWindowStateChanged: vi.fn(unsubscribe),+ touchBackend: vi.fn(async () => undefined),+ profile: { get: vi.fn(async () => ({ profile: 'default' })) }+ }+}++function Harness() {+ useGatewayBoot({+ beforeConnectionSwitch: () => undefined,+ handleGatewayEvent: () => undefined,+ handleServerRequest: () => false,+ onConnectionReady: () => undefined,+ onGatewayReady: () => undefined,+ refreshHermesConfig: async () => undefined,+ refreshSessions: async () => undefined+ })++ return null+}++function closeSurvivor() {+ try {+ takeGatewaySurvivor()?.gateway.close()+ } catch {+ // ignore+ }+}++const originalWebSocket = globalThis.WebSocket++beforeEach(() => {+ closeSurvivor()+ closeSecondaryGateways()+ $activeGatewayProfile.set('default')+ $connection.set(null)+ vi.useFakeTimers()+ FakeWebSocket.mode = 'open'+ FakeWebSocket.instances = []+ FakeWebSocket.pingMode = 'pong'+ ;(globalThis as { WebSocket: unknown }).WebSocket = FakeWebSocket+ $gatewayState.set('idle')+ $desktopBoot.set({+ error: null,+ fakeMode: false,+ message: '',+ phase: 'init',+ progress: 0,+ running: true,+ timestamp: Date.now(),+ visible: true+ })+})++afterEach(() => {+ cleanup()+ closeSurvivor()+ closeSecondaryGateways()+ $connection.set(null)+ vi.useRealTimers()+ ;(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocket+ delete (window as { hermesDesktop?: unknown }).hermesDesktop+})++async function flushAsync() {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+}++it('a hold published after boot (a pool/profile backend) still reaches the blocked screen (R8 M6)', async () => {+ const desktop = fakeDesktop()++ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop+ render(<Harness />)+ await flushAsync()+ expect($gatewayState.get()).toBe('open')++ const hold = {+ holdId: 'a1b2c3d4e5f60718',+ verdict: 'held' as const,+ ownerPid: 4242,+ since: Date.now() - 6_000,+ checkedAt: Date.now(),+ logPath: '/x/logs/update.log'+ }++ const progress = {+ error: null,+ fakeMode: false,+ message: 'Hermes is ready',+ phase: 'backend.ready',+ progress: 100,+ retryable: false,+ running: false,+ timestamp: Date.now()+ }++ act(() => desktop.emitBootProgress({ ...progress, updateHold: hold }))+ expect($desktopBoot.get().updateHold).toEqual(hold)+ expect($desktopBoot.get().phase).not.toBe('backend.ready')+ act(() => desktop.emitBootProgress({ ...progress, updateHold: null }))+ expect($desktopBoot.get().updateHold).toBeNull()+})diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsxindex 81454803121..c7c477f7129 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx@@ -54,6 +54,7 @@ import {import { warnIfTerminalBackendUnavailable } from '@/store/terminal-backend-warning'import { deferred } from '../../../test/deferred'+import { FakeWebSocket } from '../../../test/fake-gateway-socket'import { takeGatewaySurvivor } from './gateway-hmr-survivor'import { primaryRuntimeConnectionId, useGatewayBoot } from './use-gateway-boot'@@ -78,7 +79,6 @@ vi.mock(import('@/store/terminal-backend-warning'), () => ({// stuck store combo — closing the "inferred by reading code" gap on the// post-boot reconnect loop.-type Listener = (ev: unknown) => voidlet connectionApplied: null | (() => void) = nulllet powerResume: null | (() => void) = nulllet backendExit: null | ((payload?: unknown) => void) = null@@ -97,96 +97,6 @@ describe('primaryRuntimeConnectionId', () => {})})-// Minimal WebSocket stand-in implementing only what json-rpc-gateway.connect()-// touches: readyState, add/removeEventListener('open'|'error'|'close'), close().-class FakeWebSocket {- static OPEN = 1- static CLOSED = 3- // Flipped by the test: 'open' = next socket connects; 'fail' = next socket- // errors (a dead remote). Mirrors a VPS going away after the first connect.- static mode: 'open' | 'fail' = 'open'- static instances: FakeWebSocket[] = []- // Ping behavior: 'pong' answers with a healthy pong frame; 'silent' swallows- // the request (the half-open-socket simulation — connection looks OPEN but- // every RPC hangs until its per-call timeout); 'method-not-found' answers- // the JSON-RPC error a PRE-ping backend returns (a healthy, version-skewed- // response that must NOT trigger a reconnect).- static pingMode: 'pong' | 'silent' | 'method-not-found' = 'pong'-- readyState = 0- private listeners: Record<string, Set<Listener>> = {}-- constructor(public url: string) {- FakeWebSocket.instances.push(this)- const willOpen = FakeWebSocket.mode === 'open'- // Resolve on the next microtask/macrotask so connect()'s promise wiring is- // in place before open/error fires (matches real async socket handshake).- setTimeout(() => {- if (willOpen) {- this.readyState = FakeWebSocket.OPEN- this.emit('open', {})- } else {- this.readyState = FakeWebSocket.CLOSED- this.emit('error', {})- }- }, 0)- }-- addEventListener(type: string, fn: Listener) {- ;(this.listeners[type] ??= new Set()).add(fn)- }-- removeEventListener(type: string, fn: Listener) {- this.listeners[type]?.delete(fn)- }-- close() {- this.readyState = FakeWebSocket.CLOSED- this.emit('close', {})- }-- // Force-drop an open socket, as a sleeping laptop / restarted remote would.- drop() {- this.readyState = FakeWebSocket.CLOSED- this.emit('close', {})- }-- send(data: string) {- let frame: { id?: unknown; method?: string }-- try {- frame = JSON.parse(data) as { id?: unknown; method?: string }- } catch {- return- }-- if (frame.method !== 'ping') {- return- }-- if (FakeWebSocket.pingMode === 'pong') {- this.emit('message', {- data: JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { pong: true } })- })- } else if (FakeWebSocket.pingMode === 'method-not-found') {- this.emit('message', {- data: JSON.stringify({- jsonrpc: '2.0',- id: frame.id,- error: { code: -32601, message: 'Method not found' }- })- })- }- // 'silent': swallow — a healthy socket answers, a half-open one never does.- }-- private emit(type: string, ev: unknown) {- for (const fn of this.listeners[type] ?? []) {- fn(ev)- }- }-}-const primaryConn = {authMode: 'token' as 'oauth' | 'token',baseUrl: 'https://vps.example.com',@@ -559,41 +469,6 @@ describe('primary failure foreground isolation', () => {expect($desktopBoot.get().visible).toBe(false)})- it('a hold published after boot (a pool/profile backend) still reaches the blocked screen (R8 M6)', async () => {- const desktop = fakeDesktop()-- ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop- render(<Harness />)- await flushAsync()- expect($gatewayState.get()).toBe('open')-- const hold = {- holdId: 'a1b2c3d4e5f60718',- verdict: 'held' as const,- ownerPid: 4242,- since: Date.now() - 6_000,- checkedAt: Date.now(),- logPath: '/x/logs/update.log'- }-- const progress = {- error: null,- fakeMode: false,- message: 'Hermes is ready',- phase: 'backend.ready',- progress: 100,- retryable: false,- running: false,- timestamp: Date.now()- }-- act(() => desktop.emitBootProgress({ ...progress, updateHold: hold }))- expect($desktopBoot.get().updateHold).toEqual(hold)- expect($desktopBoot.get().phase).not.toBe('backend.ready')- act(() => desktop.emitBootProgress({ ...progress, updateHold: null }))- expect($desktopBoot.get().updateHold).toBeNull()- })-it('ignores a boot snapshot superseded by a newer progress event', async () => {const snapshot = deferred<Awaited<ReturnType<ReturnType<typeof fakeDesktop>['getBootProgress']>>>()const connection = deferred<typeof primaryConn>()diff --git a/apps/desktop/src/test/fake-gateway-socket.ts b/apps/desktop/src/test/fake-gateway-socket.tsnew file mode 100644index 00000000000..1639ef2f110--- /dev/null+++ b/apps/desktop/src/test/fake-gateway-socket.ts@@ -0,0 +1,91 @@+type Listener = (ev: unknown) => void++// Minimal WebSocket stand-in implementing only what json-rpc-gateway.connect()+// touches: readyState, add/removeEventListener('open'|'error'|'close'), close().+export class FakeWebSocket {+ static OPEN = 1+ static CLOSED = 3+ // Flipped by the test: 'open' = next socket connects; 'fail' = next socket+ // errors (a dead remote). Mirrors a VPS going away after the first connect.+ static mode: 'open' | 'fail' = 'open'+ static instances: FakeWebSocket[] = []+ // Ping behavior: 'pong' answers with a healthy pong frame; 'silent' swallows+ // the request (the half-open-socket simulation — connection looks OPEN but+ // every RPC hangs until its per-call timeout); 'method-not-found' answers+ // the JSON-RPC error a PRE-ping backend returns (a healthy, version-skewed+ // response that must NOT trigger a reconnect).+ static pingMode: 'pong' | 'silent' | 'method-not-found' = 'pong'++ readyState = 0+ private listeners: Record<string, Set<Listener>> = {}++ constructor(public url: string) {+ FakeWebSocket.instances.push(this)+ const willOpen = FakeWebSocket.mode === 'open'+ // Resolve on the next microtask/macrotask so connect()'s promise wiring is+ // in place before open/error fires (matches real async socket handshake).+ setTimeout(() => {+ if (willOpen) {+ this.readyState = FakeWebSocket.OPEN+ this.emit('open', {})+ } else {+ this.readyState = FakeWebSocket.CLOSED+ this.emit('error', {})+ }+ }, 0)+ }++ addEventListener(type: string, fn: Listener) {+ ;(this.listeners[type] ??= new Set()).add(fn)+ }++ removeEventListener(type: string, fn: Listener) {+ this.listeners[type]?.delete(fn)+ }++ close() {+ this.readyState = FakeWebSocket.CLOSED+ this.emit('close', {})+ }++ // Force-drop an open socket, as a sleeping laptop / restarted remote would.+ drop() {+ this.readyState = FakeWebSocket.CLOSED+ this.emit('close', {})+ }++ send(data: string) {+ let frame: { id?: unknown; method?: string }++ try {+ frame = JSON.parse(data) as { id?: unknown; method?: string }+ } catch {+ return+ }++ if (frame.method !== 'ping') {+ return+ }++ if (FakeWebSocket.pingMode === 'pong') {+ this.emit('message', {+ data: JSON.stringify({ jsonrpc: '2.0', id: frame.id, result: { pong: true } })+ })+ } else if (FakeWebSocket.pingMode === 'method-not-found') {+ this.emit('message', {+ data: JSON.stringify({+ jsonrpc: '2.0',+ id: frame.id,+ error: { code: -32601, message: 'Method not found' }+ })+ })+ }+ // 'silent': swallow — a healthy socket answers, a half-open one never does.+ }++ private emit(type: string, ev: unknown) {+ for (const fn of this.listeners[type] ?? []) {+ fn(ev)+ }+ }+}