Skip to content

The agent that grows with you

Remove speculative query resurrection and reuse existing async test fixtures

ethernet438ec7480e83
diff --git a/apps/desktop/src/app/settings/connections-registry.test.tsx b/apps/desktop/src/app/settings/connections-registry.test.tsx
index 96e6774da40..2409436e4fd 100644
--- a/apps/desktop/src/app/settings/connections-registry.test.tsx
+++ b/apps/desktop/src/app/settings/connections-registry.test.tsx
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { DesktopConnectionsRegistry } from '@/global'
import { _resetFleetRosterForTests, refreshFleetRoster } from '@/store/fleet-roster'
import { $connection } from '@/store/session'
+import { deferred } from '@/test/deferred'
import {
ConnectionsRegistrySection,
@@ -116,13 +117,8 @@ describe('ConnectionsRegistrySection', () => {
const applyConnectionConfig = vi.fn()
const saveConnectionConfig = vi.fn()
const probeConnectionConfig = vi.fn().mockResolvedValue({ reachable: true, authMode: 'oauth', providers: [] })
- let finishLogin!: (value: { connected: boolean }) => void
-
- const oauthLoginConnectionConfig = vi.fn().mockReturnValue(
- new Promise<{ connected: boolean }>(resolve => {
- finishLogin = resolve
- })
- )
+ const pendingLogin = deferred<{ connected: boolean }>()
+ const oauthLoginConnectionConfig = vi.fn().mockReturnValue(pendingLogin.promise)
Object.assign(window.hermesDesktop, {
applyConnectionConfig,
@@ -139,7 +135,7 @@ describe('ConnectionsRegistrySection', () => {
fireEvent.click(await screen.findByRole('button', { name: /Sign in with/ }))
await waitFor(() => expect(oauthLoginConnectionConfig).toHaveBeenCalledWith('https://a.example'))
fireEvent.change(url, { target: { value: 'https://b.example' } })
- await act(async () => finishLogin({ connected: true }))
+ await act(async (): Promise<void> => pendingLogin.resolve({ connected: true }))
expect(screen.queryByText('Signed in')).toBeNull()
fireEvent.click(screen.getByText('Save connection'))
await waitFor(() =>
diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsx
index 31d4fe470fb..3a4d0a10fd4 100644
--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx
@@ -1,6 +1,8 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { deferred } from '@/test/deferred'
+
// Collect the component graph before the behavioral test deadline starts.
import { GatewaySettings } from './gateway-settings'
@@ -60,20 +62,10 @@ describe('GatewaySettings', () => {
it('releases a pending save after a late probe invalidates its response', async () => {
const saved = { ...localConnection, mode: 'remote', remoteUrl: 'https://a.example', remoteTokenSet: true }
getConnectionConfig.mockResolvedValue(saved)
- let finishSave!: (value: typeof saved) => void
- let finishProbe!: (value: { reachable: boolean; authMode: string; providers: never[] }) => void
- saveConnectionConfig.mockReturnValueOnce(
- new Promise<typeof saved>(resolve => {
- finishSave = resolve
- })
- )
-
- const probeConnectionConfig = vi.fn(
- () =>
- new Promise<{ reachable: boolean; authMode: string; providers: never[] }>(resolve => {
- finishProbe = resolve
- })
- )
+ const pendingSave = deferred<typeof saved>()
+ const pendingProbe = deferred<{ reachable: boolean; authMode: string; providers: never[] }>()
+ saveConnectionConfig.mockReturnValueOnce(pendingSave.promise)
+ const probeConnectionConfig = vi.fn().mockReturnValue(pendingProbe.promise)
Object.assign(window.hermesDesktop, { probeConnectionConfig })
render(<GatewaySettings />)
@@ -87,8 +79,8 @@ describe('GatewaySettings', () => {
remoteToken: undefined
})
expect(saveButton.disabled).toBe(true)
- await act(async () => finishProbe({ reachable: true, authMode: 'oauth', providers: [] }))
- await act(async () => finishSave(saved))
+ await act(async (): Promise<void> => pendingProbe.resolve({ reachable: true, authMode: 'oauth', providers: [] }))
+ await act(async (): Promise<void> => pendingSave.resolve(saved))
expect(saveButton.disabled).toBe(false)
expect(screen.getByRole('button', { name: /Sign in with/ })).toBeTruthy()
expect(screen.queryByPlaceholderText('Existing token saved')).toBeNull()
@@ -96,12 +88,8 @@ describe('GatewaySettings', () => {
it('pre-saves OAuth before login and applies the resolved auth mode without requiring a test', async () => {
getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'remote', remoteUrl: 'https://login.example' })
- let finishSave!: () => void
- saveConnectionConfig.mockReturnValueOnce(
- new Promise<void>(resolve => {
- finishSave = resolve
- })
- )
+ const pendingSave = deferred<void>()
+ saveConnectionConfig.mockReturnValueOnce(pendingSave.promise)
const oauthLoginConnectionConfig = vi.fn().mockResolvedValue({ connected: true })
const applyConnectionConfig = vi.fn().mockResolvedValue(localConnection)
const testConnectionConfig = vi.fn()
@@ -123,7 +111,7 @@ describe('GatewaySettings', () => {
remoteUrl: 'https://login.example'
})
expect(oauthLoginConnectionConfig).not.toHaveBeenCalled()
- await act(async () => finishSave())
+ await act(async (): Promise<void> => pendingSave.resolve())
await screen.findByText('Signed in')
expect(oauthLoginConnectionConfig).toHaveBeenCalledExactlyOnceWith('https://login.example')
fireEvent.click(screen.getByRole('button', { name: 'Save and reconnect' }))
@@ -151,12 +139,8 @@ describe('GatewaySettings', () => {
getConnectionConfig.mockResolvedValue(saved)
saveConnectionConfig.mockResolvedValue(saved)
- let finishSave!: (value: typeof saved) => void
- saveConnectionConfig.mockReturnValueOnce(
- new Promise<typeof saved>(resolve => {
- finishSave = resolve
- })
- )
+ const pendingSave = deferred<typeof saved>()
+ saveConnectionConfig.mockReturnValueOnce(pendingSave.promise)
Object.assign(window.hermesDesktop, {
probeConnectionConfig: vi.fn().mockResolvedValue({ reachable: true, authMode: 'token', providers: [] })
})
@@ -172,7 +156,7 @@ describe('GatewaySettings', () => {
})
)
// Flush the save's reset and probe effects before acquiring the replacement field.
- await act(async () => finishSave(saved))
+ await act(async (): Promise<void> => pendingSave.resolve(saved))
const tokenInput = await screen.findByPlaceholderText('Existing token saved-preview')
expect(tokenInput.isConnected, 'saved credential control must survive the refresh probe').toBe(true)
fireEvent.change(tokenInput, { target: { value: 'replacement' } })
@@ -194,13 +178,8 @@ describe('GatewaySettings', () => {
it('discards an old token test while saving the current credential-ready payload', async () => {
getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'remote', remoteUrl: 'https://a.example' })
const probeConnectionConfig = vi.fn().mockResolvedValue({ reachable: true, authMode: 'token', providers: [] })
- let finishTest!: (value: { ok: boolean; baseUrl: string }) => void
-
- const testConnectionConfig = vi.fn().mockReturnValue(
- new Promise<{ ok: boolean; baseUrl: string }>(resolve => {
- finishTest = resolve
- })
- )
+ const pendingTest = deferred<{ ok: boolean; baseUrl: string }>()
+ const testConnectionConfig = vi.fn().mockReturnValue(pendingTest.promise)
Object.assign(window.hermesDesktop, { probeConnectionConfig, testConnectionConfig })
render(<GatewaySettings />)
@@ -214,7 +193,7 @@ describe('GatewaySettings', () => {
remoteToken: 'old-token'
})
fireEvent.change(token, { target: { value: 'new-token' } })
- await act(async () => finishTest({ ok: true, baseUrl: 'https://a.example' }))
+ await act(async (): Promise<void> => pendingTest.resolve({ ok: true, baseUrl: 'https://a.example' }))
expect(screen.queryByText('Connected to https://a.example')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Save for next restart' }))
await waitFor(() =>
diff --git a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx
index e15cf9443d5..50d33c812eb 100644
--- a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx
+++ b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx
@@ -2,6 +2,7 @@ import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { DesktopConnectionProbeResult } from '@/global'
+import { deferred } from '@/test/deferred'
import { useRemoteSetup } from './use-remote-setup'
import type { RemoteSetupHost } from './use-remote-setup'
@@ -29,15 +30,10 @@ afterEach(() => {
describe('remote setup owner', () => {
it.each<RemoteSetupHost>(['first-run', 'settings', 'registry'])(
'rejects stale probe results in %s despite fresh host callbacks',
- async host => {
- const replies: ((value: DesktopConnectionProbeResult) => void)[] = []
-
- const probeConnectionConfig = vi.fn(
- () =>
- new Promise<DesktopConnectionProbeResult>(resolve => {
- replies.push(resolve)
- })
- )
+ async (host: RemoteSetupHost): Promise<void> => {
+ const oldProbe = deferred<DesktopConnectionProbeResult>()
+ const newProbe = deferred<DesktopConnectionProbeResult>()
+ const probeConnectionConfig = vi.fn().mockReturnValueOnce(oldProbe.promise).mockReturnValueOnce(newProbe.promise)
Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { probeConnectionConfig } })
const { result, rerender } = renderHook(() => useRemoteSetup({ host, onNotice: () => {} }))
@@ -54,9 +50,9 @@ describe('remote setup owner', () => {
await vi.advanceTimersByTimeAsync(500)
})
expect(probeConnectionConfig.mock.calls).toEqual([['https://a.example'], ['https://b.example']])
- await act(async () => {
- replies[1](probeResult('oauth', 'new'))
- replies[0](probeResult('token', 'old'))
+ await act(async (): Promise<void> => {
+ newProbe.resolve(probeResult('oauth', 'new'))
+ oldProbe.resolve(probeResult('token', 'old'))
})
expect(result.current.payload).toEqual({
mode: 'remote',
@@ -70,14 +66,8 @@ describe('remote setup owner', () => {
it('does not publish login completion after the editor unmounts without a probe bridge', async () => {
const onNotice = vi.fn()
- let finish!: (value: { connected: boolean }) => void
-
- const oauthLoginConnectionConfig = vi.fn(
- () =>
- new Promise<{ connected: boolean }>(resolve => {
- finish = resolve
- })
- )
+ const pendingLogin = deferred<{ connected: boolean }>()
+ const oauthLoginConnectionConfig = vi.fn().mockReturnValue(pendingLogin.promise)
Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { oauthLoginConnectionConfig } })
const { result, unmount } = renderHook(() => useRemoteSetup({ host: 'registry', onNotice }))
@@ -91,8 +81,8 @@ describe('remote setup owner', () => {
})
expect(oauthLoginConnectionConfig).toHaveBeenCalledExactlyOnceWith('https://a.example')
unmount()
- await act(async () => {
- finish({ connected: true })
+ await act(async (): Promise<void> => {
+ pendingLogin.resolve({ connected: true })
await login
})
expect(onNotice).not.toHaveBeenCalled()
diff --git a/apps/desktop/src/store/local-models-query.test.ts b/apps/desktop/src/store/local-models-query.test.ts
deleted file mode 100644
index 4c2aa8a56a0..00000000000
--- a/apps/desktop/src/store/local-models-query.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { QueryClient, QueryObserver } from '@tanstack/react-query'
-import { afterEach, expect, it, vi } from 'vitest'
-
-import type { LocalRuntimeJob } from '@/types/hermes'
-
-vi.mock('@/hermes', (): object => ({
- getLocalModelsJobs: vi.fn(),
- getLocalModelsStatus: vi.fn(),
- getLocalCatalog: vi.fn(),
- getLocalHardware: vi.fn()
-}))
-vi.mock('@/store/notifications', (): object => ({ notify: vi.fn(), notifyError: vi.fn() }))
-vi.mock('@/i18n', (): object => ({ translateNow: (key: string): string => key }))
-vi.mock('@/store/profile', async (): Promise<object> => {
- const { atom } = await import('nanostores')
-
- return { $activeGatewayProfile: atom<string>('default') }
-})
-vi.mock('@/store/session', async (): Promise<object> => {
- const { atom } = await import('nanostores')
-
- return { $connection: atom(null) }
-})
-
-import { getLocalModelsJobs } from '@/hermes'
-import { queryClient } from '@/lib/query-client'
-
-import { localModelsKey } from './local-runtime-jobs'
-import { watchLocalRuntimeJobs } from './local-runtime-jobs'
-
-const clients: QueryClient[] = []
-afterEach((): void => {
- for (const client of clients) {
- client.clear()
- }
-
- vi.clearAllMocks()
-})
-
-it('publishes a pinned job response into the shared QueryClient observer', async (): Promise<void> => {
- const client: QueryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- clients.push(client)
- const owner = { connectionId: 'A', profile: 'work' }
-
- const job: LocalRuntimeJob = {
- job_id: 'j',
- kind: 'model-download',
- model_id: 'm',
- target: 'Model A',
- status: 'running',
- phase: 'downloading',
- detail: '',
- done_bytes: 1,
- total_bytes: 2,
- error: null
- }
-
- vi.mocked(getLocalModelsJobs).mockResolvedValue({ jobs: [job] })
-
- const observer: QueryObserver<readonly LocalRuntimeJob[]> = new QueryObserver<readonly LocalRuntimeJob[]>(client, {
- queryKey: ['local-models', 'A', 'work', 'jobs'],
- enabled: false
- })
-
- const unsubscribe: () => void = observer.subscribe((): void => {})
- watchLocalRuntimeJobs(owner, client)
- await vi.waitFor((): void => expect(observer.getCurrentResult().data).toEqual([job]))
- expect(getLocalModelsJobs).toHaveBeenCalledWith(owner)
- unsubscribe()
-})
-
-it('coalesces one trailing read while the production cache is still fresh', async (): Promise<void> => {
- clients.push(queryClient)
- const owner = { connectionId: 'A', profile: 'work' }
- vi.mocked(getLocalModelsJobs).mockResolvedValue({ jobs: [] })
- watchLocalRuntimeJobs(owner)
- await vi.waitFor((): void => expect(queryClient.getQueryData(localModelsKey(owner, 'jobs'))).toEqual([]))
-
- let release: (value: { jobs: LocalRuntimeJob[] }) => void = (): void => {}
-
- const pending: Promise<{ jobs: LocalRuntimeJob[] }> = new Promise((resolve): void => {
- release = resolve
- })
-
- vi.mocked(getLocalModelsJobs).mockReturnValueOnce(pending)
- watchLocalRuntimeJobs(owner)
- watchLocalRuntimeJobs(owner)
- watchLocalRuntimeJobs(owner)
- await Promise.resolve()
- expect(getLocalModelsJobs).toHaveBeenCalledTimes(2)
- release({ jobs: [] })
- await vi.waitFor((): void => expect(getLocalModelsJobs).toHaveBeenCalledTimes(3))
-})
diff --git a/apps/desktop/src/store/local-models-surfaces.test.tsx b/apps/desktop/src/store/local-models-surfaces.test.tsx
index 326778754fd..d5ab528c6bb 100644
--- a/apps/desktop/src/store/local-models-surfaces.test.tsx
+++ b/apps/desktop/src/store/local-models-surfaces.test.tsx
@@ -34,6 +34,7 @@ import { $localModelsEnabled } from '@/store/local-models-flag'
import { notify } from '@/store/notifications'
import { $activeGatewayProfile } from '@/store/profile'
import { $connection } from '@/store/session'
+import { deferred } from '@/test/deferred'
import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'
import {
@@ -42,7 +43,6 @@ import {
localModelsOwner,
refreshLocalModels,
useLocalModelsOwner,
- useLocalRuntimeJobs,
watchLocalRuntimeJobs
} from './local-runtime-jobs'
@@ -177,15 +177,6 @@ it('uses one status polling clock across staggered Settings, picker and menu mou
)
await tick(2_000)
- const statusQuery = queryClient
- .getQueryCache()
- .find({ queryKey: localModelsKey({ connectionId: 'A', profile: 'work' }, 'status') })
-
- expect(
- statusQuery?.observers.filter(
- (observer): boolean => Boolean(observer.options.refetchInterval) && observer.options.enabled !== false
- )
- ).toHaveLength(1)
expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status'))).toHaveLength(2)
settings.unmount()
await tick(2_000)
@@ -204,19 +195,14 @@ it('keeps paused work alive after Settings unmount and isolates late results by
await tick(3_000)
expect(queryClient.getQueryData(localModelsKey({ connectionId: 'A', profile: 'work' }, 'jobs'))).toEqual([running])
- let release: (value: unknown) => void = (): void => {}
-
- const pending: Promise<unknown> = new Promise((resolve): void => {
- release = resolve
- })
-
- api.mockImplementationOnce((): Promise<unknown> => pending)
+ const pending = deferred<{ jobs: LocalRuntimeJob[] }>()
+ api.mockReturnValueOnce(pending.promise)
watchLocalRuntimeJobs({ connectionId: 'A', profile: 'work' })
setApiRequestConnection('B')
jobs = [{ ...running, target: 'Download B' }]
watchLocalRuntimeJobs({ connectionId: 'B', profile: 'work' })
await tick()
- release({ jobs: [{ ...running, status: 'done' }] })
+ pending.resolve({ jobs: [{ ...running, status: 'done' }] })
await tick()
expect(queryClient.getQueryData(localModelsKey({ connectionId: 'B', profile: 'work' }, 'jobs'))).toEqual(jobs)
expect(notify).toHaveBeenCalledTimes(1)
@@ -233,13 +219,8 @@ it('keeps paused work alive after Settings unmount and isolates late results by
it.each(['connection', 'profile'] as const)(
'does not paint a late Settings snapshot after a %s switch',
async (change: 'connection' | 'profile'): Promise<void> => {
- let release: (value: unknown) => void = (): void => {}
-
- const pending: Promise<unknown> = new Promise((resolve): void => {
- release = resolve
- })
-
- api.mockImplementationOnce((): Promise<unknown> => pending)
+ const pending = deferred<LocalModelsStatus>()
+ api.mockReturnValueOnce(pending.promise)
const settings: RenderResult = mountSettings()
await tick()
await act(async (): Promise<void> => {
@@ -265,7 +246,7 @@ it.each(['connection', 'profile'] as const)(
})
await tick()
expect(settings.container.textContent).toContain('installed')
- release({ ...status, tag: 'OLD-OWNER' })
+ pending.resolve({ ...status, tag: 'OLD-OWNER' })
await tick()
expect(settings.container.textContent).not.toContain('OLD-OWNER')
@@ -312,27 +293,17 @@ it('discards late legacy completions and update notices without invalidating the
watchLocalRuntimeJobs(owner)
await tick()
- let releaseJobs: (value: unknown) => void = (): void => {}
-
- let releaseStatus: (value: unknown) => void = (): void => {}
-
- const pendingJobs: Promise<unknown> = new Promise((resolve): void => {
- releaseJobs = resolve
- })
-
- const pendingStatus: Promise<unknown> = new Promise((resolve): void => {
- releaseStatus = resolve
- })
-
- api.mockImplementationOnce((): Promise<unknown> => pendingJobs)
+ const pendingJobs = deferred<{ jobs: LocalRuntimeJob[] }>()
+ const pendingStatus = deferred<LocalModelsStatus>()
+ api.mockReturnValueOnce(pendingJobs.promise)
watchLocalRuntimeJobs(owner)
- api.mockImplementationOnce((): Promise<unknown> => pendingStatus)
+ api.mockReturnValueOnce(pendingStatus.promise)
const update: Promise<void> = checkLocalRuntimeUpdate(owner)
$connection.set({ ...connection, baseUrl: 'http://B' })
const key: readonly string[] = ['model-options', 'work', 'global']
queryClient.setQueryData(key, { providers: [] })
- releaseJobs({ jobs: [{ ...running, status: 'done' }] })
- releaseStatus({ ...status, update_available: true })
+ pendingJobs.resolve({ jobs: [{ ...running, status: 'done' }] })
+ pendingStatus.resolve({ ...status, update_available: true })
await update
await tick()
expect(queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(owner, 'jobs'))).toEqual([running])
@@ -343,32 +314,6 @@ it('discards late legacy completions and update notices without invalidating the
expect(notify).not.toHaveBeenCalled()
})
-it('reconnects mounted job subscribers if their query is removed', async (): Promise<void> => {
- jobs = [running]
- const owner = { connectionId: 'A', profile: 'work' }
-
- const hook = renderHook(
- (): string =>
- useLocalRuntimeJobs(owner, (rows: readonly LocalRuntimeJob[]): string => rows[0]?.status ?? 'missing'),
- {
- wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- }
- )
-
- await tick(1)
- expect(hook.result.current).toBe('running')
- await act(async (): Promise<void> => {
- queryClient.removeQueries({ queryKey: localModelsKey(owner, 'jobs'), exact: true })
- await vi.advanceTimersByTimeAsync(1)
- })
- hook.rerender()
- await tick(1)
- expect(hook.result.current).toBe('running')
- jobs = [{ ...running, status: 'paused' }]
- await tick(700)
- expect(hook.result.current).toBe('paused')
-})
-
it('keeps menu focus and its scalar selection stable across byte updates and outages', async (): Promise<void> => {
jobs = [running]
let reads: number = 0
diff --git a/apps/desktop/src/store/local-runtime-jobs.test.ts b/apps/desktop/src/store/local-runtime-jobs.test.ts
index 61011a05e49..6ebe5f1c62d 100644
--- a/apps/desktop/src/store/local-runtime-jobs.test.ts
+++ b/apps/desktop/src/store/local-runtime-jobs.test.ts
@@ -9,11 +9,15 @@ vi.mock('@/store/session', async (): Promise<object> => {
return { $connection: atom(null), $defaultReasoningEffort: atom<string>('') }
})
+import { QueryClient, type QueryKey, QueryObserver } from '@tanstack/react-query'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { queryClient } from '@/lib/query-client'
+import { deferred } from '@/test/deferred'
import type { LocalRuntimeJob } from '@/types/hermes'
+import type { LocalModelsOwner } from './local-runtime-jobs'
+
// The BACKEND is the authority: a staged registry the poll reads from, so
// transitions arrive the way production sees them — via a poll response,
// never by mutating the cache directly.
@@ -155,27 +159,55 @@ describe('local runtime jobs store — pause/settle contract', () => {
).toBe('running')
})
- it('coalesces refresh requests while one backend read is in flight', async () => {
- let release: (value: { jobs: LocalRuntimeJob[] }) => void = () => {}
+ it('publishes a pinned job response into an injected QueryClient observer', async (): Promise<void> => {
+ const client: QueryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const owner: LocalModelsOwner = { connectionId: 'A', profile: 'work' }
+ backend.jobs = [job({ done_bytes: 1, total_bytes: 2 })]
- const pending = new Promise<{ jobs: LocalRuntimeJob[] }>(resolve => {
- release = resolve
+ const observer: QueryObserver<readonly LocalRuntimeJob[]> = new QueryObserver<readonly LocalRuntimeJob[]>(client, {
+ queryKey: ['local-models', 'A', 'work', 'jobs'],
+ enabled: false
})
- vi.mocked(getLocalModelsJobs).mockReturnValueOnce(pending)
- watchLocalRuntimeJobs()
- watchLocalRuntimeJobs()
- watchLocalRuntimeJobs()
- expect(getLocalModelsJobs).toHaveBeenCalledTimes(1)
- backend.jobs = [job({ done_bytes: 40 })]
- release({ jobs: [] })
- await vi.waitFor(() => expect(getLocalModelsJobs).toHaveBeenCalledTimes(2))
- expect(
- (queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0]
- ?.done_bytes
- ).toBe(40)
+ const unsubscribe: () => void = observer.subscribe((): void => {})
+
+ try {
+ watchLocalRuntimeJobs(owner, client)
+ await vi.waitFor((): void => expect(observer.getCurrentResult().data).toEqual(backend.jobs))
+ expect(getLocalModelsJobs).toHaveBeenCalledWith(owner)
+ expect(queryClient.getQueryData(localModelsKey(owner, 'jobs'))).toBeUndefined()
+ } finally {
+ unsubscribe()
+ client.clear()
+ }
})
+ it.each(['cold', 'warm'] as const)(
+ 'coalesces one trailing read with a %s production cache',
+ async (cache: 'cold' | 'warm'): Promise<void> => {
+ const owner: LocalModelsOwner = { connectionId: 'A', profile: 'work' }
+ const key: QueryKey = localModelsKey(owner, 'jobs')
+
+ if (cache === 'warm') {
+ watchLocalRuntimeJobs(owner)
+ await vi.waitFor((): void => expect(queryClient.getQueryData(key)).toEqual([]))
+ }
+
+ vi.mocked(getLocalModelsJobs).mockClear()
+ const pending = deferred<{ jobs: LocalRuntimeJob[] }>()
+ vi.mocked(getLocalModelsJobs).mockReturnValueOnce(pending.promise)
+ watchLocalRuntimeJobs(owner)
+ watchLocalRuntimeJobs(owner)
+ watchLocalRuntimeJobs(owner)
+ await Promise.resolve()
+ expect(getLocalModelsJobs).toHaveBeenCalledTimes(1)
+ backend.jobs = [job({ done_bytes: 40 })]
+ pending.resolve({ jobs: [] })
+ await vi.waitFor((): void => expect(getLocalModelsJobs).toHaveBeenCalledTimes(2))
+ expect(queryClient.getQueryData<readonly LocalRuntimeJob[]>(key)?.[0]?.done_bytes).toBe(40)
+ }
+ )
+
it('preserves the query data reference when a poll returns identical payload', async () => {
backend.jobs = [job({ done_bytes: 40 })]
await pollTick()
diff --git a/apps/desktop/src/store/local-runtime-jobs.ts b/apps/desktop/src/store/local-runtime-jobs.ts
index 82b7878382f..93016a6dff6 100644
--- a/apps/desktop/src/store/local-runtime-jobs.ts
+++ b/apps/desktop/src/store/local-runtime-jobs.ts
@@ -246,16 +246,8 @@ export function watchLocalRuntimeJobs(
return
}
- if (event.query.getObserversCount() > 1) {
- // A mounted consumer still needs this owner. Rebind both the polling
- // observer and its passive projections to the replacement query.
- for (const subscriber of [...event.query.observers]) {
- subscriber.setOptions(subscriber.options)
- }
- } else {
- observer.destroy()
- watchers.get(client)?.delete(id)
- }
+ observer.destroy()
+ watchers.get(client)?.delete(id)
}
})
}