Skip to content

The agent that grows with you

Use one scoped query owner for local models

etherneteb7f032cc7f9
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index b61f0d33b4c..256feb10645 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -1,4 +1,5 @@
import { JsonRpcGatewayClient } from '@hermes/shared'
+import { map, type MapStore } from 'nanostores'
import type { HermesApiRequest } from '@/global'
@@ -44,14 +45,20 @@ export class HermesGateway extends JsonRpcGatewayClient {
// REST handlers accept profile reuse the primary dashboard via ?profile=;
// unscoped handlers retain a profile backend. Remote overrides still route to
// their owning backend. Null → primary, so single-profile users are unaffected.
-let _apiProfile: null | string = null
+interface ApiRequestScope {
+ profile: string | null
+ connectionId: string | null
+}
+
+// This is the request authority, not a second copy in a presentation store.
+export const $apiRequestScope: MapStore<ApiRequestScope> = map<ApiRequestScope>({ profile: null, connectionId: null })
export function setApiRequestProfile(profile: null | string): void {
- _apiProfile = profile || null
+ $apiRequestScope.setKey('profile', profile || null)
}
export function profileScoped(profile?: null | string): { profile?: string } {
- const selected = profile === undefined ? _apiProfile : profile
+ const selected = profile === undefined ? $apiRequestScope.get().profile : profile
return selected ? { profile: selected } : {}
}
@@ -60,7 +67,7 @@ export function profileScoped(profile?: null | string): { profile?: string } {
* Read-only twin of setApiRequestProfile for modules (e.g. voice playback)
* that build their own connection URLs and must stay on the same backend. */
export function getApiRequestProfile(): null | string {
- return _apiProfile
+ return $apiRequestScope.get().profile
}
// Registry connection serving the active gateway (null → the local pool).
@@ -69,11 +76,10 @@ export function getApiRequestProfile(): null | string {
// that dial their own backend (pluginSocket) resolve it through the SAME
// source of truth those paths maintain for $connection. That makes the plugin
// socket follow registry-agent activations too, not just profile switches.
-// Same no-store-import contract as _apiProfile (avoids a cycle).
-let _apiConnectionId: null | string = null
+// Same no-store-import contract as profile scope (avoids a cycle).
export function setApiRequestConnection(connectionId: null | string): void {
- _apiConnectionId = connectionId || null
+ $apiRequestScope.setKey('connectionId', connectionId || null)
}
// Registry connection scope for a REST request. A registered remote gateway
@@ -83,11 +89,13 @@ export function setApiRequestConnection(connectionId: null | string): void {
// resolves to no tag, keeping single-source users byte-identical; explicit
// 'local' must remain tagged when the legacy primary points elsewhere.
export function connectionScoped(): { connectionId?: string } {
- return _apiConnectionId ? { connectionId: _apiConnectionId } : {}
+ const connectionId: string | null = $apiRequestScope.get().connectionId
+
+ return connectionId ? { connectionId } : {}
}
// Whether the window's primary connection is the local pool. Pushed from
-// store/session's setConnection (same no-store-import contract as _apiProfile)
+// store/session's setConnection (same no-store-import contract as profile scope)
// so api/ helpers can name the backend an UNTAGGED request lands on without
// importing the heavy session store — which would close a module cycle
// through @/hermes.
@@ -102,7 +110,7 @@ export function setApiRequestLocalMode(local: boolean): void {
* never send this as a request pin (an explicit `'local'` bypasses Electron's
* legacy per-profile remote overrides). */
export function ambientOwnerConnectionId(): string | undefined {
- return _apiConnectionId ?? (_apiLocalMode ? 'local' : undefined)
+ return $apiRequestScope.get().connectionId ?? (_apiLocalMode ? 'local' : undefined)
}
/** Send a REST request to the renderer's active registry source. Request-level
@@ -175,5 +183,5 @@ export function profileScopeKey(scope?: ProfileScope): string {
/** Registry connection id that connection-scoped WS calls should target
* (null → the local pool). Read-only twin of setApiRequestConnection. */
export function getApiRequestConnection(): null | string {
- return _apiConnectionId
+ return $apiRequestScope.get().connectionId
}
diff --git a/apps/desktop/src/api/local-models-owner.test.ts b/apps/desktop/src/api/local-models-owner.test.ts
new file mode 100644
index 00000000000..3ee2149da59
--- /dev/null
+++ b/apps/desktop/src/api/local-models-owner.test.ts
@@ -0,0 +1,24 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+
+import { setApiRequestConnection, setApiRequestProfile } from './client'
+import { getLocalModelsJobs, getLocalModelsStatus, pauseLocalDownload } from './local-models'
+
+beforeEach((): void => {
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: { api: vi.fn().mockResolvedValue({ jobs: [] }) }
+ })
+ setApiRequestConnection('foreground')
+ setApiRequestProfile('default')
+})
+
+it('pins delayed reads and controls to their captured connection and profile', async (): Promise<void> => {
+ const owner = { connectionId: 'background', profile: 'work' }
+ await getLocalModelsStatus(owner)
+ await getLocalModelsJobs(owner)
+ await pauseLocalDownload('download', owner)
+
+ for (const [request] of vi.mocked(window.hermesDesktop.api).mock.calls) {
+ expect(request).toMatchObject(owner)
+ }
+})
diff --git a/apps/desktop/src/api/local-models.ts b/apps/desktop/src/api/local-models.ts
index 7a31ccda0b5..490199573e3 100644
--- a/apps/desktop/src/api/local-models.ts
+++ b/apps/desktop/src/api/local-models.ts
@@ -2,33 +2,41 @@ import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJ
import { hermesApi, profileScoped } from './client'
+export interface LocalModelsScope {
+ connectionId: string | null
+ profile: string
+}
+
// The desktop surface of the managed llama.cpp runtime: status/catalog
// reads, download/install/activate jobs, and server control.
-export function getLocalModelsStatus(): Promise<LocalModelsStatus> {
+export function getLocalModelsStatus(scope?: LocalModelsScope): Promise<LocalModelsStatus> {
return hermesApi<LocalModelsStatus>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
path: '/api/local-models/status'
})
}
-export function getLocalHardware(): Promise<LocalHardware> {
+export function getLocalHardware(scope?: LocalModelsScope): Promise<LocalHardware> {
return hermesApi<LocalHardware>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
path: '/api/local-models/hardware'
})
}
-export function getLocalCatalog(): Promise<{ models: LocalCatalogModel[] }> {
+export function getLocalCatalog(scope?: LocalModelsScope): Promise<{ models: LocalCatalogModel[] }> {
return hermesApi<{ models: LocalCatalogModel[] }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
path: '/api/local-models/catalog'
})
}
-export function installLocalRuntime(backend?: string): Promise<{ backend: string; job_id: string; tag: string }> {
+export function installLocalRuntime(
+ backend?: string,
+ scope?: LocalModelsScope
+): Promise<{ backend: string; job_id: string; tag: string }> {
return hermesApi<{ backend: string; job_id: string; tag: string }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { backend: backend ?? null },
method: 'POST',
path: '/api/local-models/runtime/install'
@@ -44,42 +52,45 @@ export interface QuickstartResponse {
needs_runtime: boolean
}
-export function quickstartLocalModels(modelId?: string): Promise<QuickstartResponse> {
+export function quickstartLocalModels(modelId?: string, scope?: LocalModelsScope): Promise<QuickstartResponse> {
return hermesApi<QuickstartResponse>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { model_id: modelId ?? null },
method: 'POST',
path: '/api/local-models/quickstart'
})
}
-export function downloadLocalModel(modelId: string): Promise<{ already_downloaded?: boolean; job_id: null | string }> {
+export function downloadLocalModel(
+ modelId: string,
+ scope?: LocalModelsScope
+): Promise<{ already_downloaded?: boolean; job_id: null | string }> {
return hermesApi<{ already_downloaded?: boolean; job_id: null | string }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { model_id: modelId },
method: 'POST',
path: '/api/local-models/download'
})
}
-export function deleteLocalModel(modelId: string): Promise<{ ok: boolean }> {
+export function deleteLocalModel(modelId: string, scope?: LocalModelsScope): Promise<{ ok: boolean }> {
return hermesApi<{ ok: boolean }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
method: 'DELETE',
path: `/api/local-models/models/${encodeURIComponent(modelId)}`
})
}
-export function getLocalRuntimeJob(jobId: string): Promise<LocalRuntimeJob> {
+export function getLocalRuntimeJob(jobId: string, scope?: LocalModelsScope): Promise<LocalRuntimeJob> {
return hermesApi<LocalRuntimeJob>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
path: `/api/local-models/jobs/${encodeURIComponent(jobId)}`
})
}
-export function getLocalModelsJobs(): Promise<{ jobs: LocalRuntimeJob[] }> {
+export function getLocalModelsJobs(scope?: LocalModelsScope): Promise<{ jobs: LocalRuntimeJob[] }> {
return hermesApi<{ jobs: LocalRuntimeJob[] }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
path: '/api/local-models/jobs'
})
}
@@ -88,45 +99,48 @@ export function getLocalModelsJobs(): Promise<{ jobs: LocalRuntimeJob[] }> {
// install/update, HF-browsed). The backend answers {ok, paused} /
// {ok, resumed} — a false flag (no live download handle, e.g. a
// quickstart engine leg) is reported to the caller, not treated as success.
-export function pauseLocalDownload(jobId: string): Promise<{ ok: boolean; paused: boolean }> {
+export function pauseLocalDownload(jobId: string, scope?: LocalModelsScope): Promise<{ ok: boolean; paused: boolean }> {
return hermesApi<{ ok: boolean; paused: boolean }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { job_id: jobId },
method: 'POST',
path: '/api/local-models/download/pause'
})
}
-export function resumeLocalDownload(jobId: string): Promise<{ ok: boolean; resumed: boolean }> {
+export function resumeLocalDownload(
+ jobId: string,
+ scope?: LocalModelsScope
+): Promise<{ ok: boolean; resumed: boolean }> {
return hermesApi<{ ok: boolean; resumed: boolean }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { job_id: jobId },
method: 'POST',
path: '/api/local-models/download/resume'
})
}
-export function activateLocalModel(modelId: string): Promise<{ job_id: string }> {
+export function activateLocalModel(modelId: string, scope?: LocalModelsScope): Promise<{ job_id: string }> {
return hermesApi<{ job_id: string }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { model_id: modelId },
method: 'POST',
path: '/api/local-models/activate'
})
}
-export function ejectLocalModel(modelId: string): Promise<{ ok: boolean }> {
+export function ejectLocalModel(modelId: string, scope?: LocalModelsScope): Promise<{ ok: boolean }> {
return hermesApi<{ ok: boolean }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { model_id: modelId },
method: 'POST',
path: '/api/local-models/eject'
})
}
-export function setLocalServer(action: 'start' | 'stop'): Promise<{ ok: boolean }> {
+export function setLocalServer(action: 'start' | 'stop', scope?: LocalModelsScope): Promise<{ ok: boolean }> {
return hermesApi<{ ok: boolean }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { action },
method: 'POST',
path: '/api/local-models/server'
@@ -150,26 +164,31 @@ export interface HFFileGroup {
fit: 'fits-gpu' | 'needs-ram' | 'too-big' | 'unknown'
}
-export function searchHFModels(q: string, limit = 20): Promise<{ hits: HFSearchHit[] }> {
+export function searchHFModels(
+ q: string,
+ limit: number = 20,
+ scope?: LocalModelsScope
+): Promise<{ hits: HFSearchHit[] }> {
return hermesApi<{ hits: HFSearchHit[] }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
path: `/api/local-models/search?q=${encodeURIComponent(q)}&limit=${limit}`
})
}
-export function listHFRepoFiles(repo: string): Promise<{ files: HFFileGroup[] }> {
+export function listHFRepoFiles(repo: string, scope?: LocalModelsScope): Promise<{ files: HFFileGroup[] }> {
return hermesApi<{ files: HFFileGroup[] }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
path: `/api/local-models/search/files?repo=${encodeURIComponent(repo)}`
})
}
export function downloadBrowsedModel(
repo: string,
- paths: string[]
+ paths: string[],
+ scope?: LocalModelsScope
): Promise<{ already_downloaded?: boolean; job_id: null | string; model_id: string }> {
return hermesApi<{ already_downloaded?: boolean; job_id: null | string; model_id: string }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { paths, repo },
method: 'POST',
path: '/api/local-models/download-browsed'
@@ -177,10 +196,11 @@ export function downloadBrowsedModel(
}
export function sideloadLocalModel(
- path: string
+ path: string,
+ scope?: LocalModelsScope
): Promise<{ already_present?: boolean; model_id: string; ok: boolean }> {
return hermesApi<{ already_present?: boolean; model_id: string; ok: boolean }>({
- ...profileScoped(),
+ ...(scope ?? profileScoped()),
body: { path },
method: 'POST',
path: '/api/local-models/sideload'
diff --git a/apps/desktop/src/app/settings/local-model-download-progress.test.tsx b/apps/desktop/src/app/settings/local-model-download-progress.test.tsx
index 08decada982..269d49c3523 100644
--- a/apps/desktop/src/app/settings/local-model-download-progress.test.tsx
+++ b/apps/desktop/src/app/settings/local-model-download-progress.test.tsx
@@ -2,7 +2,6 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libra
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { I18nProvider } from '@/i18n'
-import type * as RuntimeJobs from '@/store/local-runtime-jobs'
import type * as Notifications from '@/store/notifications'
import type { LocalRuntimeJob } from '@/types/hermes'
@@ -16,8 +15,7 @@ vi.mock('@/store/notifications', async importOriginal => ({
notifyError: vi.fn()
}))
-vi.mock('@/store/local-runtime-jobs', async importOriginal => ({
- ...(await importOriginal<typeof RuntimeJobs>()),
+vi.mock('@/store/local-runtime-jobs', (): object => ({
watchLocalRuntimeJobs: vi.fn()
}))
@@ -71,7 +69,7 @@ describe('LocalModelDownloadActions', () => {
await waitFor(() => {
expect(pauseLocalDownload).toHaveBeenCalledTimes(1)
})
- expect(pauseLocalDownload).toHaveBeenCalledWith('j1')
+ expect(pauseLocalDownload).toHaveBeenCalledWith('j1', undefined)
expect(resumeLocalDownload).not.toHaveBeenCalled()
})
@@ -105,7 +103,7 @@ describe('LocalModelDownloadActions', () => {
await waitFor(() => {
expect(resumeLocalDownload).toHaveBeenCalledTimes(1)
})
- expect(resumeLocalDownload).toHaveBeenCalledWith('j1')
+ expect(resumeLocalDownload).toHaveBeenCalledWith('j1', undefined)
expect(pauseLocalDownload).not.toHaveBeenCalled()
})
diff --git a/apps/desktop/src/app/settings/local-model-download-progress.tsx b/apps/desktop/src/app/settings/local-model-download-progress.tsx
index 7d3e8d84189..777d9f96227 100644
--- a/apps/desktop/src/app/settings/local-model-download-progress.tsx
+++ b/apps/desktop/src/app/settings/local-model-download-progress.tsx
@@ -1,11 +1,16 @@
-import { useState } from 'react'
+import { type ReactElement, useState } from 'react'
import { Button } from '@/components/ui/button'
import { pauseLocalDownload, resumeLocalDownload } from '@/hermes'
import { useI18n } from '@/i18n'
import { Loader2, Pause, Play } from '@/lib/icons'
import { cn } from '@/lib/utils'
-import { watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
+import {
+ isCurrentLocalModelsOwner,
+ type LocalModelsOwner,
+ localModelsRequestScope,
+ watchLocalRuntimeJobs
+} from '@/store/local-runtime-jobs'
import { notifyError } from '@/store/notifications'
import type { LocalRuntimeJob } from '@/types/hermes'
@@ -91,7 +96,10 @@ export function LocalModelDownloadProgress({ job }: LocalModelDownloadProps) {
)
}
-export function LocalModelDownloadActions({ job }: LocalModelDownloadProps) {
+export function LocalModelDownloadActions({
+ job,
+ owner
+}: LocalModelDownloadProps & { owner?: LocalModelsOwner }): ReactElement | null {
const { t } = useI18n()
const copy = t.settings.localModels
const [busy, setBusy] = useState<boolean>(false)
@@ -105,14 +113,16 @@ export function LocalModelDownloadActions({ job }: LocalModelDownloadProps) {
// below decides what the row shows; only a real transport failure
// surfaces as an error.
if (kind === 'pause') {
- await pauseLocalDownload(job.job_id)
+ await pauseLocalDownload(job.job_id, owner ? localModelsRequestScope(owner) : undefined)
} else {
- await resumeLocalDownload(job.job_id)
+ await resumeLocalDownload(job.job_id, owner ? localModelsRequestScope(owner) : undefined)
}
- watchLocalRuntimeJobs()
+ watchLocalRuntimeJobs(owner)
} catch (err) {
- notifyError(err, copy.downloadFailed(job.target))
+ if (!owner || isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, copy.downloadFailed(job.target))
+ }
} finally {
setBusy(false)
}
diff --git a/apps/desktop/src/app/settings/local-models-settings.test.tsx b/apps/desktop/src/app/settings/local-models-settings.test.tsx
index bf84f1869aa..1db6e8f480c 100644
--- a/apps/desktop/src/app/settings/local-models-settings.test.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx
@@ -1,9 +1,22 @@
+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), $defaultReasoningEffort: atom<string>('') }
+})
+
+import { QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'
import { I18nProvider } from '@/i18n'
-import { $localRuntimeJobs, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
+import { queryClient } from '@/lib/query-client'
+import { localModelsKey, localModelsOwner, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'
import { LocalModelsSettings } from './local-models-settings'
@@ -105,11 +118,13 @@ const REFUSED_MODEL: LocalCatalogModel = {
function renderPane() {
return render(
- <MemoryRouter>
- <I18nProvider>
- <LocalModelsSettings />
- </I18nProvider>
- </MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <I18nProvider>
+ <LocalModelsSettings />
+ </I18nProvider>
+ </MemoryRouter>
+ </QueryClientProvider>
)
}
@@ -124,7 +139,8 @@ async function renderFullPane(): Promise<ReturnType<typeof renderPane>> {
// straight to the full pane, the runtime section directly.
await waitFor((): void => {
expect(
- Boolean(screen.queryByRole('button', { name: /let me choose/i })) || screen.queryAllByText(/this machine/i).length > 0
+ Boolean(screen.queryByRole('button', { name: /let me choose/i })) ||
+ screen.queryAllByText(/this machine/i).length > 0
).toBe(true)
})
@@ -137,18 +153,23 @@ async function renderFullPane(): Promise<ReturnType<typeof renderPane>> {
return result
}
-beforeEach(() => {
+beforeEach((): void => {
+ queryClient.clear()
+ queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })
mocked.getLocalModelsStatus.mockResolvedValue(BASE_STATUS)
mocked.getLocalHardware.mockResolvedValue(BASE_HARDWARE)
mocked.getLocalCatalog.mockResolvedValue({ models: [FITTING_MODEL, SPILLED_MODEL, REFUSED_MODEL] })
// The backend mock ECHOES the atom: the watcher's immediate poll reads
// seeded jobs instead of wiping them with a default {jobs:[]}.
- mocked.getLocalModelsJobs.mockImplementation(async () => ({ jobs: [...$localRuntimeJobs.get()] }))
- $localRuntimeJobs.set([])
+ mocked.getLocalModelsJobs.mockImplementation(async () => ({
+ jobs: [...(queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])]
+ }))
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
})
afterEach(async () => {
cleanup()
+ queryClient.clear()
mocked.getLocalModelsJobs.mockResolvedValue({ jobs: [] })
await act(async () => {
watchLocalRuntimeJobs()
@@ -318,7 +339,7 @@ describe('LocalModelsSettings', () => {
})
// A running job already in the app-level store — as after closing and
// reopening the pane mid-download.
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'j9',
kind: 'model-download',
@@ -351,7 +372,7 @@ describe('LocalModelsSettings', () => {
runtime_installed: true,
runtime_backend: 'cuda'
})
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'j2',
kind: 'model-download',
@@ -397,7 +418,7 @@ describe('quickstart', () => {
})
it('pins the quickstart progress view while the job runs', async () => {
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'q1',
kind: 'quickstart',
@@ -470,12 +491,15 @@ describe('BrowseSection', () => {
})
fireEvent.click(screen.getByRole('button', { name: /download ·/i }))
await waitFor((): void => {
- expect(mocked.downloadLocalModel).toHaveBeenCalledWith(SPILLED_MODEL.id)
+ expect(mocked.downloadLocalModel).toHaveBeenCalledWith(SPILLED_MODEL.id, {
+ connectionId: null,
+ profile: 'default'
+ })
})
mocked.activateLocalModel.mockResolvedValue({ job_id: 'explicit-spill' })
fireEvent.click(await screen.findByRole('button', { name: /^use$/i }))
await waitFor((): void => {
- expect(mocked.activateLocalModel).toHaveBeenCalledWith(stagedId)
+ expect(mocked.activateLocalModel).toHaveBeenCalledWith(stagedId, { connectionId: null, profile: 'default' })
})
expect(mocked.quickstartLocalModels).not.toHaveBeenCalled()
})
@@ -495,11 +519,13 @@ describe('BrowseSection', () => {
})
render(
- <MemoryRouter>
- <I18nProvider>
- <LocalModelsSettings />
- </I18nProvider>
- </MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <I18nProvider>
+ <LocalModelsSettings />
+ </I18nProvider>
+ </MemoryRouter>
+ </QueryClientProvider>
)
await act(async () => {
await vi.runOnlyPendingTimersAsync()
@@ -514,7 +540,7 @@ describe('BrowseSection', () => {
await act(async () => {
await vi.advanceTimersByTimeAsync(400)
})
- expect(hermes.searchHFModels).toHaveBeenCalledWith('qwen')
+ expect(hermes.searchHFModels).toHaveBeenCalledWith('qwen', 20, { connectionId: null, profile: 'default' })
expect(screen.getByText('unsloth/Qwen3.8-27B-GGUF')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /show files/i }))
@@ -534,7 +560,11 @@ describe('BrowseSection', () => {
await act(async () => {
await vi.runOnlyPendingTimersAsync()
})
- expect(hermes.downloadBrowsedModel).toHaveBeenCalledWith('unsloth/Qwen3.8-27B-GGUF', ['Qwen3.8-27B-Q4_K_M.gguf'])
+ expect(hermes.downloadBrowsedModel).toHaveBeenCalledWith(
+ 'unsloth/Qwen3.8-27B-GGUF',
+ ['Qwen3.8-27B-Q4_K_M.gguf'],
+ { connectionId: null, profile: 'default' }
+ )
} finally {
vi.useRealTimers()
}
@@ -597,33 +627,43 @@ describe('quickstart completion navigation', () => {
// A finished quickstart already in history when the pane mounts —
// must NOT trigger navigation.
- $localRuntimeJobs.set([doneJob])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [doneJob])
render(
- <MemoryRouter initialEntries={['/settings']}>
- <I18nProvider>
- <LocalModelsSettings />
- </I18nProvider>
- <Probe />
- </MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={['/settings']}>
+ <I18nProvider>
+ <LocalModelsSettings />
+ </I18nProvider>
+ <Probe />
+ </MemoryRouter>
+ </QueryClientProvider>
)
await act(async () => {})
expect(routeProbe).not.toHaveBeenCalledWith('/')
// A quickstart the pane SAW running that then completes -> navigate.
const running: LocalRuntimeJob = { ...doneJob, job_id: 'live-run', phase: 'downloading', status: 'running' }
- await act(async () => {
- $localRuntimeJobs.set([doneJob, running])
+ await act(async (): Promise<void> => {
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [doneJob, running])
+ await new Promise<void>((resolve): void => {
+ setTimeout(resolve, 0)
+ })
})
await act(async () => {
- $localRuntimeJobs.set([doneJob, { ...running, phase: 'done', status: 'done' }])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
+ doneJob,
+ { ...running, phase: 'done', status: 'done' }
+ ])
})
- expect(routeProbe).toHaveBeenCalledWith('/')
+ await waitFor((): void => expect(routeProbe).toHaveBeenCalledWith('/'))
})
})
describe('pause / resume integration', () => {
- beforeEach(() => {
+ beforeEach((): void => {
+ queryClient.clear()
+ queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })
vi.mocked(hermes.pauseLocalDownload).mockResolvedValue({ ok: true, paused: true })
vi.mocked(hermes.resumeLocalDownload).mockResolvedValue({ ok: true, resumed: true })
})
@@ -634,7 +674,7 @@ describe('pause / resume integration', () => {
runtime_installed: true,
runtime_backend: 'cuda'
})
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'j1',
kind: 'model-download',
@@ -659,7 +699,7 @@ describe('pause / resume integration', () => {
await waitFor(() => {
expect(hermes.pauseLocalDownload).toHaveBeenCalledTimes(1)
})
- expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('j1')
+ expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('j1', { connectionId: null, profile: 'default' })
expect(hermes.resumeLocalDownload).not.toHaveBeenCalled()
})
@@ -669,7 +709,7 @@ describe('pause / resume integration', () => {
runtime_installed: true,
runtime_backend: 'cuda'
})
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'j1',
kind: 'model-download',
@@ -695,7 +735,7 @@ describe('pause / resume integration', () => {
fireEvent.click(screen.getByRole('button', { name: /resume/i }))
await waitFor(() => {
- expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('j1')
+ expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('j1', { connectionId: null, profile: 'default' })
})
// The watcher re-kicked: an authoritative re-read happens after resume.
@@ -705,7 +745,7 @@ describe('pause / resume integration', () => {
})
it('a paused quickstart stays pinned in the hero with a Resume control', async () => {
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'q1',
kind: 'quickstart',
@@ -731,12 +771,12 @@ describe('pause / resume integration', () => {
fireEvent.click(screen.getByRole('button', { name: /resume/i }))
await waitFor(() => {
- expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('q1')
+ expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('q1', { connectionId: null, profile: 'default' })
})
})
it('a running quickstart hero shows Pause during the download stage', async () => {
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'q1',
kind: 'quickstart',
@@ -765,7 +805,7 @@ describe('pause / resume integration', () => {
runtime_installed: false,
update_available: false
})
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'r1',
kind: 'runtime-install',
@@ -789,12 +829,12 @@ describe('pause / resume integration', () => {
fireEvent.click(pause)
await waitFor(() => {
- expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('r1')
+ expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('r1', { connectionId: null, profile: 'default' })
})
})
it('quickstart hero suppresses the byte counter outside download phases', async () => {
- $localRuntimeJobs.set([
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
{
job_id: 'q1',
kind: 'quickstart',
diff --git a/apps/desktop/src/app/settings/local-models-settings.tsx b/apps/desktop/src/app/settings/local-models-settings.tsx
index bda53c933e4..75d4e51554a 100644
--- a/apps/desktop/src/app/settings/local-models-settings.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.tsx
@@ -1,5 +1,5 @@
-import { useStore } from '@nanostores/react'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { type QueryClient, useQuery, useQueryClient } from '@tanstack/react-query'
+import { type ReactElement, useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router'
import { NEW_CHAT_ROUTE } from '@/app/routes'
@@ -11,9 +11,6 @@ import {
downloadBrowsedModel,
downloadLocalModel,
ejectLocalModel,
- getLocalCatalog,
- getLocalHardware,
- getLocalModelsStatus,
type HFFileGroup,
type HFSearchHit,
installLocalRuntime,
@@ -42,13 +39,23 @@ import {
} from '@/lib/icons'
import { cn } from '@/lib/utils'
import {
- $localRuntimeJobs,
+ isCurrentLocalModelsOwner,
+ localModelsCatalogOptions,
+ localModelsHardwareOptions,
+ localModelsKey,
+ localModelsNotificationTitle,
+ type LocalModelsOwner,
+ localModelsRequestScope,
+ refreshLocalModels,
runningDownloadFor,
runningRuntimeInstall,
+ useLocalModelsOwner,
+ useLocalModelsStatus,
+ useLocalRuntimeJobs,
watchLocalRuntimeJobs
} from '@/store/local-runtime-jobs'
import { notify, notifyError } from '@/store/notifications'
-import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'
+import type { LocalCatalogModel, LocalRuntimeJob } from '@/types/hermes'
import {
gbLabel,
@@ -80,105 +87,57 @@ function isActiveStatus(status: LocalRuntimeJob['status']): boolean {
return status === 'paused' || status === 'running'
}
-export function LocalModelsSettings() {
+export function LocalModelsSettings(): ReactElement {
+ const owner: LocalModelsOwner = useLocalModelsOwner()
+
+ return <ScopedLocalModelsSettings key={JSON.stringify(localModelsKey(owner))} owner={owner} />
+}
+
+function ScopedLocalModelsSettings({ owner }: { owner: LocalModelsOwner }): ReactElement {
const { t } = useI18n()
const copy = t.settings.localModels
- const [status, setStatus] = useState<LocalModelsStatus | null>(null)
- const [hardware, setHardware] = useState<LocalHardware | null>(null)
- const [catalog, setCatalog] = useState<LocalCatalogModel[] | null>(null)
+ const client: QueryClient = useQueryClient()
+ const { data: status } = useLocalModelsStatus(owner)
+ const { data: hardware } = useQuery(localModelsHardwareOptions(owner))
+ const { data: catalog } = useQuery(localModelsCatalogOptions(owner))
const [deleting, setDeleting] = useState<null | string>(null)
- const [serverBusy, setServerBusy] = useState(false)
+ const [serverBusy, setServerBusy] = useState<boolean>(false)
// Quickstart escape hatch: true once the user asks for the full pane
// (model list, HF browser) instead of the one-button setup card.
- const [configure, setConfigure] = useState(false)
- // Jobs live in the app-level store (they must survive this pane
- // unmounting); the pane just renders the slice it cares about.
- const jobs = useStore($localRuntimeJobs)
-
- const refresh = useCallback(() => {
- void getLocalModelsStatus()
- .then(setStatus)
- .catch(() => setStatus(null))
- void getLocalCatalog()
- .then(data => setCatalog(data.models))
- .catch(() => setCatalog([]))
- }, [])
-
- // Snappy first paint: status + catalog immediately; hardware (may shell out
- // to nvidia-smi) backfills and pops in-place. The job watcher also kicks
- // here so reopening the pane rediscovers work started before.
- useEffect(() => {
- refresh()
- watchLocalRuntimeJobs()
- void getLocalHardware()
- .then(setHardware)
- .catch(() => setHardware(null))
- }, [refresh])
-
- // The pane is LIVE while visible: residency changes without user action
- // (boot warm finishing, idle sweep unloading, another surface ejecting),
- // and a stale snapshot here reads as a broken feature — 'VRAM full but
- // the pane says Not in memory'. The status route is built cheap for
- // polling; setTimeout chain, never overlapping.
- useEffect(() => {
- let cancelled = false
- let timer: number | undefined
-
- const tick = async () => {
- try {
- const next = await getLocalModelsStatus()
-
- if (!cancelled) {
- setStatus(next)
- }
- } catch {
- // Backend briefly unreachable — keep the last snapshot.
- }
-
- if (!cancelled) {
- timer = window.setTimeout(() => void tick(), 4_000)
- }
- }
-
- timer = window.setTimeout(() => void tick(), 4_000)
+ const [configure, setConfigure] = useState<boolean>(false)
- return () => {
- cancelled = true
+ const jobs: readonly LocalRuntimeJob[] = useLocalRuntimeJobs(
+ owner,
+ (value: readonly LocalRuntimeJob[]): readonly LocalRuntimeJob[] => value
+ )
- if (timer !== undefined) {
- window.clearTimeout(timer)
- }
- }
- }, [])
+ const refresh = useCallback((): void => refreshLocalModels(owner, client), [owner, client])
- // A job finishing (download done, install done) changes what status/catalog
- // should show — refresh whenever the running set shrinks.
- const runningCount = jobs.filter(j => j.status === 'running').length
- useEffect(() => {
- refresh()
- }, [refresh, runningCount])
-
- async function handleInstallRuntime() {
+ async function handleInstallRuntime(): Promise<void> {
try {
- await installLocalRuntime()
- watchLocalRuntimeJobs()
+ await installLocalRuntime(undefined, localModelsRequestScope(owner))
+ watchLocalRuntimeJobs(owner, client)
} catch (err) {
- notifyError(err, copy.installFailed)
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, copy.installFailed)
+ }
}
}
- async function handleQuickstart() {
+ async function handleQuickstart(): Promise<void> {
try {
- await quickstartLocalModels()
- watchLocalRuntimeJobs()
+ await quickstartLocalModels(undefined, localModelsRequestScope(owner))
+ watchLocalRuntimeJobs(owner, client)
} catch (err) {
- notifyError(err, copy.quickstartFailed)
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, copy.quickstartFailed)
+ }
}
}
- async function handleDownload(model: LocalCatalogModel) {
+ async function handleDownload(model: LocalCatalogModel): Promise<void> {
try {
- const res = await downloadLocalModel(model.id)
+ const res = await downloadLocalModel(model.id, localModelsRequestScope(owner))
if (res.already_downloaded || !res.job_id) {
refresh()
@@ -186,55 +145,63 @@ export function LocalModelsSettings() {
return
}
- watchLocalRuntimeJobs()
+ watchLocalRuntimeJobs(owner, client)
} catch (err) {
- notifyError(err, copy.downloadFailed(model.display_name))
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, copy.downloadFailed(model.display_name))
+ }
}
}
- async function handleActivate(target: null | string, displayName: string) {
+ async function handleActivate(target: null | string, displayName: string): Promise<void> {
if (!target) {
return
}
try {
- await activateLocalModel(target)
- watchLocalRuntimeJobs()
+ await activateLocalModel(target, localModelsRequestScope(owner))
+ watchLocalRuntimeJobs(owner, client)
} catch (err) {
- notifyError(err, copy.activateFailed(displayName))
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, copy.activateFailed(displayName))
+ }
}
}
- async function handleEject(modelId: string) {
+ async function handleEject(modelId: string): Promise<void> {
try {
- await ejectLocalModel(modelId)
- notify({ durationMs: 3_000, kind: 'success', message: copy.ejected, title: copy.title })
+ await ejectLocalModel(modelId, localModelsRequestScope(owner))
+ notify({ durationMs: 3_000, kind: 'success', message: copy.ejected, title: localModelsNotificationTitle(owner) })
refresh()
} catch (err) {
- notifyError(err, copy.ejectFailed)
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, copy.ejectFailed)
+ }
}
}
- async function handleServer(action: 'start' | 'stop') {
+ async function handleServer(action: 'start' | 'stop'): Promise<void> {
setServerBusy(true)
try {
- await setLocalServer(action)
+ await setLocalServer(action, localModelsRequestScope(owner))
notify({
durationMs: 3_500,
kind: 'success',
message: action === 'stop' ? copy.serverStopped : copy.serverStarted,
- title: copy.title
+ title: localModelsNotificationTitle(owner)
})
refresh()
} catch (err) {
- notifyError(err, action === 'stop' ? copy.serverStopFailed : copy.serverStartFailed)
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, action === 'stop' ? copy.serverStopFailed : copy.serverStartFailed)
+ }
} finally {
setServerBusy(false)
}
}
- async function handleDelete(target: string, rowId: string) {
+ async function handleDelete(target: string, rowId: string): Promise<void> {
if (!window.confirm(copy.deleteConfirm(target))) {
return
}
@@ -242,11 +209,18 @@ export function LocalModelsSettings() {
setDeleting(rowId)
try {
- await deleteLocalModel(target)
- notify({ durationMs: 2_500, kind: 'success', message: copy.deleted(target), title: copy.title })
+ await deleteLocalModel(target, localModelsRequestScope(owner))
+ notify({
+ durationMs: 2_500,
+ kind: 'success',
+ message: copy.deleted(target),
+ title: localModelsNotificationTitle(owner)
+ })
refresh()
} catch (err) {
- notifyError(err, copy.deleteFailed)
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(err, copy.deleteFailed)
+ }
} finally {
setDeleting(null)
}
@@ -282,7 +256,7 @@ export function LocalModelsSettings() {
}
}, [jobs, navigate])
- if (!status || catalog === null) {
+ if (!status || !catalog) {
return <SettingsSkeleton sections={[{ rows: 2 }, { rows: 4 }]} />
}
@@ -362,7 +336,7 @@ export function LocalModelsSettings() {
when controls exist (engine legs, server start report
false); the paused state always offers Resume. */}
<div className="mt-5 flex items-center justify-center gap-3">
- <LocalModelDownloadActions job={qJob} />
+ <LocalModelDownloadActions job={qJob} owner={owner} />
</div>
{/* Stage rail: engine -> model -> finish. */}
@@ -473,7 +447,7 @@ export function LocalModelsSettings() {
/>
) : rJob ? (
<ListRow
- action={<LocalModelDownloadActions job={rJob} />}
+ action={<LocalModelDownloadActions job={rJob} owner={owner} />}
below={<LocalModelDownloadProgress job={rJob} />}
description={rJob.detail || copy.installing}
title={
@@ -515,7 +489,7 @@ export function LocalModelsSettings() {
{rJob && status.runtime_installed && (
<ListRow
- action={<LocalModelDownloadActions job={rJob} />}
+ action={<LocalModelDownloadActions job={rJob} owner={owner} />}
below={<LocalModelDownloadProgress job={rJob} />}
description={rJob.detail || copy.updating}
title={
@@ -682,7 +656,7 @@ export function LocalModelsSettings() {
</Tip>
</div>
) : dJob ? (
- <LocalModelDownloadActions job={dJob} />
+ <LocalModelDownloadActions job={dJob} owner={owner} />
) : (
<Button
disabled={!model.fits || anyDownloadRunning || !status.runtime_installed}
@@ -885,7 +859,7 @@ export function LocalModelsSettings() {
{lastError?.kind === 'model-download' && <p className="text-[0.75rem] text-destructive">{lastError.error}</p>}
</SettingsSection>
- <BrowseSection onChanged={refresh} />
+ <BrowseSection onChanged={refresh} owner={owner} />
</SettingsContent>
)
}
@@ -914,16 +888,23 @@ function browsedModelId(group: HFFileGroup): string {
return first.replace(/-\d{5}-of-\d{5}\.gguf$/i, '').replace(/\.gguf$/i, '')
}
-function BrowseSection({ onChanged }: { onChanged: () => void }) {
+function BrowseSection({ owner, onChanged }: { owner: LocalModelsOwner; onChanged: () => void }): ReactElement {
+ const client: QueryClient = useQueryClient()
const { t } = useI18n()
const copy = t.settings.localModels
- const jobs = useStore($localRuntimeJobs)
- const [query, setQuery] = useState('')
+
+ const jobs: readonly LocalRuntimeJob[] = useLocalRuntimeJobs(
+ owner,
+ (value: readonly LocalRuntimeJob[]): readonly LocalRuntimeJob[] => value,
+ false
+ )
+
+ const [query, setQuery] = useState<string>('')
const [hits, setHits] = useState<HFSearchHit[]>([])
- const [searching, setSearching] = useState(false)
+ const [searching, setSearching] = useState<boolean>(false)
const [openRepo, setOpenRepo] = useState<null | string>(null)
const [files, setFiles] = useState<HFFileGroup[]>([])
- const [listing, setListing] = useState(false)
+ const [listing, setListing] = useState<boolean>(false)
const [error, setError] = useState<null | string>(null)
// Guard against the past: a stale search result must never overwrite a
// newer query's hits (the desktop guide's out-of-order rule).
@@ -942,9 +923,9 @@ function BrowseSection({ onChanged }: { onChanged: () => void }) {
const seq = ++searchSeq.current
setSearching(true)
- const handle = setTimeout(() => {
- searchHFModels(q)
- .then(r => {
+ const handle: ReturnType<typeof setTimeout> = setTimeout((): void => {
+ searchHFModels(q, 20, localModelsRequestScope(owner))
+ .then((r: { hits: HFSearchHit[] }): void => {
if (searchSeq.current === seq) {
setHits(r.hits)
setError(null)
@@ -963,64 +944,84 @@ function BrowseSection({ onChanged }: { onChanged: () => void }) {
}, 350)
return () => clearTimeout(handle)
- }, [query])
-
- const openFiles = useCallback((repo: string) => {
- setOpenRepo(repo)
- setFiles([])
- setListing(true)
- listHFRepoFiles(repo)
- .then(r => setFiles(r.files))
- .catch((e: Error) => setError(e.message))
- .finally(() => setListing(false))
- }, [])
+ }, [query, owner])
+
+ const openFiles = useCallback(
+ (repo: string): void => {
+ setOpenRepo(repo)
+ setFiles([])
+ setListing(true)
+ listHFRepoFiles(repo, localModelsRequestScope(owner))
+ .then((r: { files: HFFileGroup[] }): void => setFiles(r.files))
+ .catch((e: Error) => setError(e.message))
+ .finally(() => setListing(false))
+ },
+ [owner]
+ )
const startBrowsedDownload = useCallback(
- (repo: string, group: HFFileGroup) => {
- downloadBrowsedModel(repo, group.paths)
- .then(r => {
+ (repo: string, group: HFFileGroup): void => {
+ downloadBrowsedModel(repo, group.paths, localModelsRequestScope(owner))
+ .then((r: Awaited<ReturnType<typeof downloadBrowsedModel>>): void => {
if (r.already_downloaded) {
- notify({ durationMs: 3_000, kind: 'info', message: copy.browseAlreadyDownloaded, title: copy.browseTitle })
+ notify({
+ durationMs: 3_000,
+ kind: 'info',
+ message: copy.browseAlreadyDownloaded,
+ title: localModelsNotificationTitle(owner)
+ })
return
}
// Same feedback loop as catalog downloads: the job store polls
// and the tile renders live progress from it.
- watchLocalRuntimeJobs()
+ watchLocalRuntimeJobs(owner, client)
notify({
durationMs: 3_000,
kind: 'info',
message: copy.browseDownloadStarted.replace('{name}', r.model_id),
- title: copy.browseTitle
+ title: localModelsNotificationTitle(owner)
})
onChanged()
})
- .catch((e: Error) => notifyError(e, copy.browseTitle))
+ .catch((e: Error): void => {
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(e, copy.browseTitle)
+ }
+ })
},
- [copy.browseAlreadyDownloaded, copy.browseDownloadStarted, copy.browseTitle, onChanged]
+ [copy.browseAlreadyDownloaded, copy.browseDownloadStarted, copy.browseTitle, onChanged, owner, client]
)
- const sideload = useCallback(() => {
+ const sideload = useCallback((): void => {
window.hermesDesktop
.selectPaths({ filters: [{ extensions: ['gguf'], name: 'GGUF models' }], title: copy.sideloadTitle })
- .then(paths => {
+ .then((paths: string[]): Promise<void> | undefined => {
if (!paths.length) {
return
}
- return sideloadLocalModel(paths[0]).then(r => {
- notify({
- durationMs: 3_000,
- kind: 'success',
- message: r.already_present ? copy.sideloadAlreadyPresent : copy.sideloadDone.replace('{name}', r.model_id),
- title: copy.browseTitle
- })
- onChanged()
- })
+ return sideloadLocalModel(paths[0], localModelsRequestScope(owner)).then(
+ (r: Awaited<ReturnType<typeof sideloadLocalModel>>): void => {
+ notify({
+ durationMs: 3_000,
+ kind: 'success',
+ message: r.already_present
+ ? copy.sideloadAlreadyPresent
+ : copy.sideloadDone.replace('{name}', r.model_id),
+ title: localModelsNotificationTitle(owner)
+ })
+ onChanged()
+ }
+ )
+ })
+ .catch((e: Error): void => {
+ if (isCurrentLocalModelsOwner(owner)) {
+ notifyError(e, copy.browseTitle)
+ }
})
- .catch((e: Error) => notifyError(e, copy.browseTitle))
- }, [copy.browseTitle, copy.sideloadAlreadyPresent, copy.sideloadDone, copy.sideloadTitle, onChanged])
+ }, [copy.browseTitle, copy.sideloadAlreadyPresent, copy.sideloadDone, copy.sideloadTitle, onChanged, owner])
return (
<SettingsSection
@@ -1129,7 +1130,7 @@ function BrowseSection({ onChanged }: { onChanged: () => void }) {
: copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))}
</span>
- <LocalModelDownloadActions job={dJob} />
+ <LocalModelDownloadActions job={dJob} owner={owner} />
</>
) : (
<span className="flex items-center justify-between gap-2">
diff --git a/apps/desktop/src/app/shell/model-catalog-menu.search-fold.test.tsx b/apps/desktop/src/app/shell/model-catalog-menu.search-fold.test.tsx
index af60a220252..d44db50b8b0 100644
--- a/apps/desktop/src/app/shell/model-catalog-menu.search-fold.test.tsx
+++ b/apps/desktop/src/app/shell/model-catalog-menu.search-fold.test.tsx
@@ -4,7 +4,6 @@ import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'
import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs } from '@/store/local-runtime-jobs'
import { $visibleModels } from '@/store/model-visibility'
import { ModelCatalogMenu, type ModelMenuController } from './model-catalog-menu'
@@ -27,7 +26,6 @@ vi.mock('@/hermes', () => ({
beforeEach(() => {
$visibleModels.set(null)
- $localRuntimeJobs.set([])
$localModelsEnabled.set(false)
getGlobalModelOptions.mockResolvedValue({
providers: [{ models: ['qwen3.8-flash', 'gpt-5.1'], name: 'OpenRouter', slug: 'openrouter' }]
diff --git a/apps/desktop/src/app/shell/model-catalog-menu.test.tsx b/apps/desktop/src/app/shell/model-catalog-menu.test.tsx
index 7c67285f6b4..eed61122859 100644
--- a/apps/desktop/src/app/shell/model-catalog-menu.test.tsx
+++ b/apps/desktop/src/app/shell/model-catalog-menu.test.tsx
@@ -1,10 +1,23 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+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), $defaultReasoningEffort: atom<string>('') }
+})
+
+import type { QueryClient } from '@tanstack/react-query'
+import { QueryClientProvider } from '@tanstack/react-query'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu'
+import { queryClient } from '@/lib/query-client'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs } from '@/store/local-runtime-jobs'
+import { localModelsKey, localModelsOwner } from '@/store/local-runtime-jobs'
import {
$modelVisibilityOpen,
$visibleModels,
@@ -31,17 +44,24 @@ vi.mock('@/hermes', () => ({
// poll can't wipe the jobs a test staged (the real backend is authority,
// and here the store plays that part).
getLocalModelsJobs: vi.fn(async () => {
- const { $localRuntimeJobs } = await import('@/store/local-runtime-jobs')
+ const { localModelsKey, localModelsOwner } = await import('@/store/local-runtime-jobs')
+ const { queryClient } = await import('@/lib/query-client')
- return { jobs: [...$localRuntimeJobs.get()] }
+ return {
+ jobs: [
+ ...(queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])
+ ]
+ }
}),
getLocalModelsStatus: vi.fn().mockResolvedValue({ loading: {} }),
setApiRequestProfile: vi.fn()
}))
-beforeEach(() => {
+beforeEach((): void => {
+ queryClient.clear()
+ queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })
$visibleModels.set(null)
- $localRuntimeJobs.set([])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
// These suites exercise the local-models rows, which ship behind --local.
$localModelsEnabled.set(true)
setModelVisibilityOpen(false)
@@ -52,9 +72,10 @@ beforeEach(() => {
afterEach(() => {
cleanup()
+ queryClient.clear()
// The backend mock echoes this snapshot; retire fixture jobs before jsdom
// disappears so an in-flight app-level poll cannot schedule another tick.
- $localRuntimeJobs.set([])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
vi.clearAllMocks()
})
@@ -71,7 +92,7 @@ function renderMenu() {
setOptions: vi.fn()
}
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const client: QueryClient = queryClient
render(
<QueryClientProvider client={client}>
@@ -151,7 +172,7 @@ describe('in-flight local downloads', () => {
it('shows a downloading model as a disabled progress row in its own Local group', async () => {
// No llamacpp provider in the catalog (first-ever download).
- $localRuntimeJobs.set([DOWNLOAD_JOB])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
renderMenu()
await screen.findByText(/Gemini 3\.1 Pro/i)
@@ -169,7 +190,7 @@ describe('in-flight local downloads', () => {
{ models: ['gemini-3.1-pro'], name: 'Google', slug: 'google' }
]
})
- $localRuntimeJobs.set([DOWNLOAD_JOB])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
renderMenu()
await screen.findByText(/Qwen3\.6 27B/i)
@@ -179,11 +200,13 @@ describe('in-flight local downloads', () => {
})
it('drops the placeholder row once the download settles', async () => {
- $localRuntimeJobs.set([DOWNLOAD_JOB])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
renderMenu()
await screen.findByText('Qwen3.8 Flash Next (UD-Q4_K_XL)')
- $localRuntimeJobs.set([{ ...DOWNLOAD_JOB, status: 'done', phase: 'done' }])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
+ { ...DOWNLOAD_JOB, status: 'done', phase: 'done' }
+ ])
await waitFor(() => {
expect(screen.queryByText('Qwen3.8 Flash Next (UD-Q4_K_XL)')).toBeNull()
})
@@ -197,7 +220,7 @@ describe('in-flight local downloads', () => {
{ models: ['gemini-3.1-pro'], name: 'Google', slug: 'google' }
]
})
- $localRuntimeJobs.set([DOWNLOAD_JOB])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
renderMenu()
// Staged models exist and a download is running — none of it shows.
diff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsx
index 47d6633c1a6..b197f7fa1ee 100644
--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx
+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx
@@ -1,6 +1,15 @@
import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
-import { createContext, type ReactNode, useContext, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ createContext,
+ type ReactElement,
+ type ReactNode,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from 'react'
import { Codicon } from '@/components/ui/codicon'
import { DisclosureCaret } from '@/components/ui/disclosure-caret'
@@ -19,16 +28,20 @@ import { HighlightMatches } from '@/components/ui/highlight-matches'
import { usePointerQuiet } from '@/components/ui/keyboard-first'
import { Skeleton } from '@/components/ui/skeleton'
import type { HermesGateway } from '@/hermes'
-import { getLocalModelsStatus } from '@/hermes'
import { useI18n } from '@/i18n'
import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
import { displayModelName, modelDisplayParts } from '@/lib/model-status-label'
import { DEFAULT_REASONING_EFFORT, reasoningEffortLabel } from '@/lib/reasoning-effort'
import { foldIncludes, normalize } from '@/lib/text'
-import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs, runningModelDownloads, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
+import {
+ type LocalModelsOwner,
+ runningModelDownloads,
+ useLocalModelsOwner,
+ useLocalModelsStatus,
+ useLocalRuntimeJobs
+} from '@/store/local-runtime-jobs'
import {
$visibleModels,
collapseModelFamilies,
@@ -40,7 +53,7 @@ import {
} from '@/store/model-visibility'
import { $collapsedProviders, toggleCollapsedProvider } from '@/store/provider-collapse'
import { $defaultReasoningEffort } from '@/store/session'
-import type { LocalModelLoadProgress, ModelOptionProvider, ModelOptionsResponse } from '@/types/hermes'
+import type { LocalModelLoadProgress, LocalRuntimeJob, ModelOptionProvider, ModelOptionsResponse } from '@/types/hermes'
import { type FastControl, ModelEditSubmenu, resolveFastControl } from './model-edit-submenu'
@@ -127,12 +140,12 @@ export function ModelCatalogMenu({
profile = 'default',
request,
sessionId = null
-}: ModelCatalogMenuProps) {
+}: ModelCatalogMenuProps): ReactElement {
const { t } = useI18n()
const copy = t.shell.modelMenu
const copyPicker = t.modelPicker
const closeMenu = useContext(ModelMenuCloseContext)
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState<string>('')
const collapsedProviders = useStoreCollapsed()
const defaultEffort = useDefaultEffort()
// Which models the user curated in Edit Models. Read HERE rather than taken
@@ -161,13 +174,8 @@ export function ModelCatalogMenu({
// over the router's SSE stream). Polled only while this menu is mounted
// (it unmounts on close); errors read as "nothing loading" — remote-only
// installs have no local-models routes.
- const localStatus = useQuery({
- queryKey: ['local-models-loading', profile],
- queryFn: () => getLocalModelsStatus(),
- enabled: localModelsEnabled,
- refetchInterval: 2_000,
- retry: false
- })
+ const owner: LocalModelsOwner = useLocalModelsOwner(profile, ownerConnectionId)
+ const localStatus = useLocalModelsStatus(owner, localModelsEnabled)
const loadingModels: Record<string, LocalModelLoadProgress> = localStatus.data?.loading ?? {}
@@ -179,12 +187,15 @@ export function ModelCatalogMenu({
// (breaking open submenus and focus — the #72163 class). Subscribe to a
// STABLE identity projection instead: it changes only when a download
// starts or ends. Each row selects its own percent scalar.
- const downloadsKey = useStoreSelector($localRuntimeJobs, jobs =>
+ const downloadsKey: string = useLocalRuntimeJobs(
+ owner,
+ (jobs: readonly LocalRuntimeJob[]): string =>
+ localModelsEnabled
+ ? runningModelDownloads(jobs)
+ .map(job => `${job.job_id}\u0000${job.target}`)
+ .join('\u0001')
+ : '',
localModelsEnabled
- ? runningModelDownloads(jobs)
- .map(job => `${job.job_id}\u0000${job.target}`)
- .join('\u0001')
- : ''
)
const downloads = useMemo(
@@ -199,30 +210,6 @@ export function ModelCatalogMenu({
[downloadsKey]
)
- useEffect(() => {
- if (localModelsEnabled) {
- watchLocalRuntimeJobs()
- }
- }, [localModelsEnabled])
-
- // A finished download turns into a real selectable model: refetch the
- // catalog so the placeholder row is replaced while the menu is open.
- const refetchOptions = modelOptions.refetch
-
- useEffect(() => {
- let prevActive = runningModelDownloads($localRuntimeJobs.get()).length > 0
-
- return $localRuntimeJobs.listen(next => {
- const active = runningModelDownloads(next).length > 0
-
- if (prevActive && !active) {
- void refetchOptions()
- }
-
- prevActive = active
- })
- }, [refetchOptions])
-
const error = modelOptions.error
? modelOptions.error instanceof Error
? modelOptions.error.message
@@ -593,7 +580,7 @@ export function ModelCatalogMenu({
{!collapsed &&
slug === LOCAL_PROVIDER_SLUG &&
shownDownloads.map(job => (
- <DownloadingModelRow jobId={job.jobId} key={job.jobId} target={job.target} />
+ <DownloadingModelRow jobId={job.jobId} key={job.jobId} owner={owner} target={job.target} />
))}
</DropdownMenuGroup>
)
@@ -604,7 +591,7 @@ export function ModelCatalogMenu({
{copyPicker.localDownloadsHeading}
</DropdownMenuLabel>
{shownDownloads.map(job => (
- <DownloadingModelRow jobId={job.jobId} key={job.jobId} target={job.target} />
+ <DownloadingModelRow jobId={job.jobId} key={job.jobId} owner={owner} target={job.target} />
))}
</DropdownMenuGroup>
)}
@@ -668,7 +655,15 @@ const LOCAL_PROVIDER_SLUG = 'llamacpp'
// same byte progress the Local Models pane shows. Percent is selected HERE,
// per row, so the 700ms byte ticks repaint this leaf only — the menu tree
// above subscribes to download identity, not progress.
-function DownloadingModelRow({ jobId, target }: { jobId: string; target: string }) {
+function DownloadingModelRow({
+ owner,
+ jobId,
+ target
+}: {
+ owner: LocalModelsOwner
+ jobId: string
+ target: string
+}): ReactElement {
const { t } = useI18n()
const copyPicker = t.modelPicker
const copyLocal = t.settings.localModels
@@ -676,11 +671,18 @@ function DownloadingModelRow({ jobId, target }: { jobId: string; target: string
// The row's own scalar slice: percent for live rows, status for the
// paused fork (a paused download must stay listed with its Paused pill,
// not vanish — progress loss is information loss).
- const percent = useStoreSelector($localRuntimeJobs, jobs => jobs.find(job => job.job_id === jobId)?.percent ?? null)
+ const percent: number | null = useLocalRuntimeJobs(
+ owner,
+ (jobs: readonly LocalRuntimeJob[]): number | null =>
+ jobs.find((job: LocalRuntimeJob): boolean => job.job_id === jobId)?.percent ?? null,
+ false
+ )
- const paused = useStoreSelector(
- $localRuntimeJobs,
- jobs => jobs.find(job => job.job_id === jobId)?.status === 'paused'
+ const paused: boolean = useLocalRuntimeJobs(
+ owner,
+ (jobs: readonly LocalRuntimeJob[]): boolean =>
+ jobs.find((job: LocalRuntimeJob): boolean => job.job_id === jobId)?.status === 'paused',
+ false
)
return (
diff --git a/apps/desktop/src/components/model-picker.test.tsx b/apps/desktop/src/components/model-picker.test.tsx
index 8cc1b767a35..ba650d002e2 100644
--- a/apps/desktop/src/components/model-picker.test.tsx
+++ b/apps/desktop/src/components/model-picker.test.tsx
@@ -1,18 +1,34 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+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), $defaultReasoningEffort: atom<string>('') }
+})
+
+import type { QueryClient } from '@tanstack/react-query'
+import { QueryClientProvider } from '@tanstack/react-query'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import type { ReactElement } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { I18nProvider } from '@/i18n'
+import { queryClient } from '@/lib/query-client'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs } from '@/store/local-runtime-jobs'
+import { localModelsKey, localModelsOwner } from '@/store/local-runtime-jobs'
import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'
import type { LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes'
import { ModelPickerDialog } from './model-picker'
vi.mock('@/hermes', () => ({
- getLocalModelsStatus: vi.fn().mockResolvedValue({ loading: {} })
+ getLocalModelsStatus: vi.fn().mockResolvedValue({ loading: {} }),
+ getLocalModelsJobs: vi.fn(async (): Promise<{ jobs: readonly LocalRuntimeJob[] }> => ({
+ jobs: queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
+ }))
}))
vi.mock('@/lib/model-options', async importOriginal => ({
...(await importOriginal<Record<string, unknown>>()),
@@ -59,7 +75,7 @@ const DOWNLOAD_JOB: LocalRuntimeJob = {
}
function renderPicker(ui?: Partial<Parameters<typeof ModelPickerDialog>[0]>) {
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const client: QueryClient = queryClient
const element: ReactElement = (
<QueryClientProvider client={client}>
@@ -79,21 +95,24 @@ function renderPicker(ui?: Partial<Parameters<typeof ModelPickerDialog>[0]>) {
return render(element)
}
-beforeEach(() => {
+beforeEach((): void => {
+ queryClient.clear()
+ queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })
vi.mocked(requestModelOptions).mockResolvedValue(OPTIONS)
- $localRuntimeJobs.set([])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
// These suites exercise the local-models rows, which ship behind --local.
$localModelsEnabled.set(true)
})
afterEach(() => {
cleanup()
+ queryClient.clear()
vi.clearAllMocks()
})
describe('ModelPickerDialog download rows', () => {
it('shows an in-flight download as a disabled progress row in the Local group', async () => {
- $localRuntimeJobs.set([DOWNLOAD_JOB])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
renderPicker()
expect(await screen.findByText('Qwen3.6-27B-UD-Q4_K_XL')).toBeTruthy()
@@ -110,7 +129,7 @@ describe('ModelPickerDialog download rows', () => {
})
it('shows a first-ever download under its own Local group when no local provider exists yet', async () => {
- $localRuntimeJobs.set([DOWNLOAD_JOB])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
vi.mocked(requestModelOptions).mockResolvedValue({
providers: [OPTIONS.providers![1]]
})
@@ -124,26 +143,28 @@ describe('ModelPickerDialog download rows', () => {
it('quickstart shows while downloading but not during later phases', async () => {
const quickstart: LocalRuntimeJob = { ...DOWNLOAD_JOB, job_id: 'q1', kind: 'quickstart', phase: 'downloading' }
- $localRuntimeJobs.set([quickstart])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [quickstart])
renderPicker()
expect(await screen.findByText('Qwen3.8 Flash Next (UD-Q4_K_XL)')).toBeTruthy()
// The model is staged once quickstart moves on to activating it — the
// placeholder row must leave rather than sit beside the real model.
- $localRuntimeJobs.set([{ ...quickstart, phase: 'starting-server' }])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [{ ...quickstart, phase: 'starting-server' }])
await waitFor(() => {
expect(screen.queryByText('Qwen3.8 Flash Next (UD-Q4_K_XL)')).toBeNull()
})
})
it('refetches the model options when a download it saw running completes', async () => {
- $localRuntimeJobs.set([DOWNLOAD_JOB])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
renderPicker()
await screen.findByText('Qwen3.6-27B-UD-Q4_K_XL')
expect(vi.mocked(requestModelOptions).mock.calls.length).toBe(1)
- $localRuntimeJobs.set([{ ...DOWNLOAD_JOB, status: 'done', phase: 'done' }])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
+ { ...DOWNLOAD_JOB, status: 'done', phase: 'done' }
+ ])
await waitFor(() => {
expect(vi.mocked(requestModelOptions).mock.calls.length).toBe(2)
})
diff --git a/apps/desktop/src/components/model-picker.tsx b/apps/desktop/src/components/model-picker.tsx
index 1aa03c6853e..7eb75c95ce2 100644
--- a/apps/desktop/src/components/model-picker.tsx
+++ b/apps/desktop/src/components/model-picker.tsx
@@ -1,17 +1,21 @@
import { useQuery } from '@tanstack/react-query'
-import { useEffect, useMemo, useState } from 'react'
+import { type ReactElement, useMemo, useState } from 'react'
-import { getLocalModelsStatus } from '@/hermes'
import { useI18n } from '@/i18n'
import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
import { modelSearchText } from '@/lib/model-search-text'
import { currentPickerSelection } from '@/lib/model-status-label'
import { foldIncludes, normalize } from '@/lib/text'
-import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs, runningModelDownloads, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
-import type { LocalModelLoadProgress, ModelOptionProvider, ModelPricing } from '@/types/hermes'
+import {
+ type LocalModelsOwner,
+ runningModelDownloads,
+ useLocalModelsOwner,
+ useLocalModelsStatus,
+ useLocalRuntimeJobs
+} from '@/store/local-runtime-jobs'
+import type { LocalModelLoadProgress, LocalRuntimeJob, ModelOptionProvider, ModelPricing } from '@/types/hermes'
import type { HermesGateway } from '../hermes'
import { startManualOnboarding } from '../store/onboarding'
@@ -55,7 +59,7 @@ export function ModelPickerDialog({
profile = 'default',
request,
contentClassName
-}: ModelPickerDialogProps) {
+}: ModelPickerDialogProps): ReactElement {
const { t } = useI18n()
const copy = t.modelPicker
// Own the search term so we can filter manually. cmdk's built-in
@@ -63,7 +67,7 @@ export function ModelPickerDialog({
// an empty query), which destroys the backend's curated order. We disable
// it and do a plain substring filter that preserves array order — matching
// the `hermes model` CLI picker, which shows the curated list verbatim.
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState<string>('')
const modelOptions = useQuery({
queryKey: modelOptionsQueryKey(profile, sessionId, ownerConnectionId),
@@ -80,13 +84,8 @@ export function ModelPickerDialog({
// the llamacpp provider group hides even with staged models on disk).
const localModelsEnabled = $localModelsEnabled.get()
- const localStatus = useQuery({
- queryKey: ['local-models-loading', profile],
- queryFn: () => getLocalModelsStatus(),
- enabled: open && localModelsEnabled,
- refetchInterval: 2_000,
- retry: false
- })
+ const owner: LocalModelsOwner = useLocalModelsOwner(profile, ownerConnectionId)
+ const localStatus = useLocalModelsStatus(owner, open && localModelsEnabled)
const loadingModels: Record<string, LocalModelLoadProgress> = localStatus.data?.loading ?? {}
@@ -96,12 +95,15 @@ export function ModelPickerDialog({
// and this dialog stays MOUNTED app-wide when closed — so subscribe only
// to download identity (changes when a download starts/ends, and never
// while closed); each row selects its own percent scalar (#72163 class).
- const downloadsKey = useStoreSelector($localRuntimeJobs, jobs =>
+ const downloadsKey: string = useLocalRuntimeJobs(
+ owner,
+ (jobs: readonly LocalRuntimeJob[]): string =>
+ open && localModelsEnabled
+ ? runningModelDownloads(jobs)
+ .map(job => `${job.job_id}\u0000${job.target}`)
+ .join('\u0001')
+ : '',
open && localModelsEnabled
- ? runningModelDownloads(jobs)
- .map(job => `${job.job_id}\u0000${job.target}`)
- .join('\u0001')
- : ''
)
const downloads = useMemo(
@@ -116,36 +118,6 @@ export function ModelPickerDialog({
[downloadsKey]
)
- // Rediscover in-flight work on open: the poller idles when nothing was
- // running, and a download can start from any surface.
- useEffect(() => {
- if (open && localModelsEnabled) {
- watchLocalRuntimeJobs()
- }
- }, [open, localModelsEnabled])
-
- // A finished download turns into a real selectable model — refetch the
- // options so the placeholder row is replaced while the picker is open.
- const refetchOptions = modelOptions.refetch
-
- useEffect(() => {
- if (!open) {
- return
- }
-
- let prevActive = runningModelDownloads($localRuntimeJobs.get()).length > 0
-
- return $localRuntimeJobs.listen(next => {
- const active = runningModelDownloads(next).length > 0
-
- if (prevActive && !active) {
- void refetchOptions()
- }
-
- prevActive = active
- })
- }, [open, refetchOptions])
-
const providers = modelOptions.data?.providers ?? []
const { model: optionsModel, provider: optionsProvider } = currentPickerSelection(
@@ -201,6 +173,7 @@ export function ModelPickerDialog({
loading={loading}
loadingModels={loadingModels}
onSelectModel={selectModel}
+ owner={owner}
providers={providers}
search={search}
/>
@@ -221,6 +194,7 @@ export function ModelPickerDialog({
}
function ModelResults({
+ owner,
loading,
error,
providers,
@@ -231,6 +205,7 @@ function ModelResults({
onSelectModel,
search
}: {
+ owner: LocalModelsOwner
loading: boolean
error: string | null
providers: ModelOptionProvider[]
@@ -240,7 +215,7 @@ function ModelResults({
loadingModels: Record<string, LocalModelLoadProgress>
onSelectModel: (provider: ModelOptionProvider, model: string) => void
search: string
-}) {
+}): ReactElement {
const { t } = useI18n()
const copy = t.modelPicker
@@ -355,7 +330,7 @@ function ModelResults({
)
})}
{groupDownloads.map(job => (
- <DownloadingModelRow jobId={job.jobId} key={job.jobId} target={job.target} />
+ <DownloadingModelRow jobId={job.jobId} key={job.jobId} owner={owner} target={job.target} />
))}
{unavailable.size > 0 && (
<div className="px-6 pb-2 pt-1 text-[0.62rem] leading-relaxed text-muted-foreground">
@@ -368,7 +343,7 @@ function ModelResults({
{!hasLocalGroup && visibleDownloads.length > 0 && (
<CommandGroup heading={copy.localDownloadsHeading} key="local-downloads">
{visibleDownloads.map(job => (
- <DownloadingModelRow jobId={job.jobId} key={job.jobId} target={job.target} />
+ <DownloadingModelRow jobId={job.jobId} key={job.jobId} owner={owner} target={job.target} />
))}
</CommandGroup>
)}
@@ -384,16 +359,31 @@ const LOCAL_PROVIDER_SLUG = 'llamacpp'
// where it will land), disabled so it can't be selected early, with the
// same byte progress the settings pane shows. Percent is selected here, per
// row, so the poller's 700ms byte ticks repaint this leaf only.
-function DownloadingModelRow({ jobId, target }: { jobId: string; target: string }) {
+function DownloadingModelRow({
+ owner,
+ jobId,
+ target
+}: {
+ owner: LocalModelsOwner
+ jobId: string
+ target: string
+}): ReactElement {
const { t } = useI18n()
const copy = t.modelPicker
const copyLocal = t.settings.localModels
- const percent = useStoreSelector($localRuntimeJobs, jobs => jobs.find(job => job.job_id === jobId)?.percent ?? null)
+ const percent: number | null = useLocalRuntimeJobs(
+ owner,
+ (jobs: readonly LocalRuntimeJob[]): number | null =>
+ jobs.find((job: LocalRuntimeJob): boolean => job.job_id === jobId)?.percent ?? null,
+ false
+ )
- const paused = useStoreSelector(
- $localRuntimeJobs,
- jobs => jobs.find(job => job.job_id === jobId)?.status === 'paused'
+ const paused: boolean = useLocalRuntimeJobs(
+ owner,
+ (jobs: readonly LocalRuntimeJob[]): boolean =>
+ jobs.find((job: LocalRuntimeJob): boolean => job.job_id === jobId)?.status === 'paused',
+ false
)
return (
diff --git a/apps/desktop/src/store/local-models-query.test.ts b/apps/desktop/src/store/local-models-query.test.ts
new file mode 100644
index 00000000000..4c2aa8a56a0
--- /dev/null
+++ b/apps/desktop/src/store/local-models-query.test.ts
@@ -0,0 +1,93 @@
+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
new file mode 100644
index 00000000000..538136aa46c
--- /dev/null
+++ b/apps/desktop/src/store/local-models-surfaces.test.tsx
@@ -0,0 +1,409 @@
+import { QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, renderHook, type RenderResult, screen } from '@testing-library/react'
+import { MemoryRouter } from 'react-router'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import type { HermesApiRequest, HermesConnection } from '@/global'
+import type { LocalModelsStatus, LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes'
+
+vi.mock('@/hermes', async (): Promise<object> => ({
+ ...(await import('@/api/local-models')),
+ getHermesConfigRecord: async (): Promise<object> => ({}),
+ getGlobalModelOptions: async (): Promise<ModelOptionsResponse> => ({ providers: [] })
+}))
+vi.mock('@/store/profile', async (): Promise<object> => {
+ const { atom } = await import('nanostores')
+
+ return { $activeGatewayProfile: atom<string>('work') }
+})
+vi.mock('@/store/session', async (): Promise<object> => {
+ const { atom } = await import('nanostores')
+
+ return { $connection: atom<HermesConnection | null>(null), $defaultReasoningEffort: atom<string>('') }
+})
+vi.mock('@/store/notifications', (): object => ({ notify: vi.fn(), notifyError: vi.fn() }))
+
+import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'
+import { LocalModelsSettings } from '@/app/settings/local-models-settings'
+import { ModelCatalogMenu, type ModelMenuController } from '@/app/shell/model-catalog-menu'
+import { ModelPickerDialog } from '@/components/model-picker'
+import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu'
+import { I18nProvider } from '@/i18n'
+import { queryClient } from '@/lib/query-client'
+import { $localModelsEnabled } from '@/store/local-models-flag'
+import { notify } from '@/store/notifications'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection } from '@/store/session'
+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'
+
+import {
+ checkLocalRuntimeUpdate,
+ localModelsKey,
+ localModelsOwner,
+ useLocalModelsOwner,
+ useLocalRuntimeJobs,
+ watchLocalRuntimeJobs
+} from './local-runtime-jobs'
+
+stubResizeObserver()
+stubMenuDomApis()
+
+const status: LocalModelsStatus = {
+ enabled: true,
+ tag: 'installed',
+ configured_tag: 'installed',
+ update_available: false,
+ runtime_installed: true,
+ runtime_backend: 'cpu',
+ server_running: false,
+ server_base_url: null,
+ active_model_id: null,
+ loaded_models: {},
+ models: [],
+ models_dir: '/models'
+}
+
+const running: LocalRuntimeJob = {
+ job_id: 'same-id',
+ kind: 'model-download',
+ model_id: 'model',
+ target: 'Download A',
+ status: 'running',
+ phase: 'downloading',
+ detail: '',
+ done_bytes: 1,
+ total_bytes: 2,
+ percent: 50,
+ error: null
+}
+
+let jobs: LocalRuntimeJob[] = []
+
+const api = vi.fn(async (request: HermesApiRequest): Promise<unknown> => {
+ if (request.path.endsWith('/status')) {
+ return structuredClone(status)
+ }
+
+ if (request.path.endsWith('/catalog')) {
+ return { models: [] }
+ }
+
+ if (request.path.endsWith('/jobs')) {
+ return { jobs: structuredClone(jobs) }
+ }
+
+ if (request.path.endsWith('/hardware')) {
+ return {}
+ }
+
+ throw new Error(`Unexpected request ${request.path}`)
+})
+
+const controller: ModelMenuController = {
+ current: { model: '', provider: '', effort: '', fast: false },
+ applyPreset: (): void => {},
+ presetFor: (): object => ({}),
+ select: (): void => {},
+ setOptions: (): void => {}
+}
+
+beforeEach((): void => {
+ vi.useFakeTimers()
+ queryClient.clear()
+ jobs = []
+ api.mockClear()
+ $connection.set(null)
+ vi.mocked(notify).mockClear()
+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } })
+ setApiRequestConnection('A')
+ setApiRequestProfile('work')
+ $activeGatewayProfile.set('work')
+ $localModelsEnabled.set(true)
+})
+afterEach((): void => {
+ cleanup()
+ queryClient.clear()
+ vi.useRealTimers()
+})
+
+async function tick(ms: number = 0): Promise<void> {
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(ms)
+ })
+}
+
+function mountSettings(): RenderResult {
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <I18nProvider>
+ <LocalModelsSettings />
+ </I18nProvider>
+ </MemoryRouter>
+ </QueryClientProvider>
+ )
+}
+
+it('uses one status polling clock across staggered Settings, picker and menu mounts', async (): Promise<void> => {
+ const settings: RenderResult = mountSettings()
+ await tick(400)
+ render(
+ <QueryClientProvider client={queryClient}>
+ <I18nProvider>
+ <ModelPickerDialog
+ currentModel=""
+ currentProvider=""
+ onOpenChange={(): void => {}}
+ onSelect={(): void => {}}
+ open
+ ownerConnectionId="A"
+ profile="work"
+ />
+ </I18nProvider>
+ </QueryClientProvider>
+ )
+ await tick(400)
+ render(
+ <QueryClientProvider client={queryClient}>
+ <I18nProvider>
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <ModelCatalogMenu controller={controller} ownerConnectionId="A" profile="work" />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </I18nProvider>
+ </QueryClientProvider>
+ )
+ 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)
+ expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status'))).toHaveLength(3)
+ cleanup()
+ await tick(4_000)
+ expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status'))).toHaveLength(3)
+})
+
+it('keeps paused work alive after Settings unmount and isolates late results by owner', async (): Promise<void> => {
+ jobs = [{ ...running, status: 'paused' }]
+ const settings: RenderResult = mountSettings()
+ await tick()
+ settings.unmount()
+ jobs = [running]
+ 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)
+ watchLocalRuntimeJobs({ connectionId: 'A', profile: 'work' })
+ setApiRequestConnection('B')
+ jobs = [{ ...running, target: 'Download B' }]
+ watchLocalRuntimeJobs({ connectionId: 'B', profile: 'work' })
+ await tick()
+ release({ jobs: [{ ...running, status: 'done' }] })
+ await tick()
+ expect(queryClient.getQueryData(localModelsKey({ connectionId: 'B', profile: 'work' }, 'jobs'))).toEqual(jobs)
+ expect(notify).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(notify).mock.calls[0][0].title).toContain('A / work')
+ jobs = [{ ...running, target: 'Download B', status: 'done' }]
+ watchLocalRuntimeJobs({ connectionId: 'B', profile: 'work' })
+ await tick()
+ expect(notify).toHaveBeenCalledTimes(2)
+ watchLocalRuntimeJobs({ connectionId: 'B', profile: 'work' })
+ await tick()
+ expect(notify).toHaveBeenCalledTimes(2)
+})
+
+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 settings: RenderResult = mountSettings()
+ await tick()
+ await act(async (): Promise<void> => {
+ if (change === 'connection') {
+ setApiRequestConnection('B')
+ $connection.set({
+ baseUrl: 'http://B',
+ connectionId: 'B',
+ registryScoped: true,
+ token: '',
+ wsUrl: '',
+ logs: [],
+ isFullscreen: false,
+ nativeOverlayWidth: 0,
+ windowButtonPosition: null
+ })
+ } else {
+ setApiRequestProfile('personal')
+ $activeGatewayProfile.set('personal')
+ }
+
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ await tick()
+ expect(settings.container.textContent).toContain('installed')
+ release({ ...status, tag: 'OLD-OWNER' })
+ await tick()
+ expect(settings.container.textContent).not.toContain('OLD-OWNER')
+
+ const expected =
+ change === 'connection' ? { connectionId: 'B', profile: 'work' } : { connectionId: 'A', profile: 'personal' }
+
+ expect(
+ api.mock.calls.some(
+ ([request]): boolean =>
+ request.path.endsWith('/status') &&
+ request.connectionId === expected.connectionId &&
+ request.profile === expected.profile
+ )
+ ).toBe(true)
+ }
+)
+
+it('follows an authoritative route change even when its descriptor is unchanged', async (): Promise<void> => {
+ const hook = renderHook(() => useLocalModelsOwner())
+ expect(hook.result.current.connectionId).toBe('A')
+ await act(async (): Promise<void> => {
+ setApiRequestConnection('B')
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ expect(hook.result.current.connectionId).toBe('B')
+})
+
+it('discards late legacy completions and update notices without invalidating the new catalog', async (): Promise<void> => {
+ setApiRequestConnection(null)
+
+ const connection: HermesConnection = {
+ baseUrl: 'http://A',
+ token: '',
+ wsUrl: '',
+ logs: [],
+ isFullscreen: false,
+ nativeOverlayWidth: 0,
+ windowButtonPosition: null
+ }
+
+ $connection.set(connection)
+ const owner = localModelsOwner()
+ jobs = [running]
+ 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)
+ watchLocalRuntimeJobs(owner)
+ api.mockImplementationOnce((): Promise<unknown> => pendingStatus)
+ 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 })
+ await update
+ await tick()
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ 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
+
+ const menuController: ModelMenuController = {
+ ...controller,
+ get current() {
+ reads += 1
+
+ return controller.current
+ }
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <I18nProvider>
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <ModelCatalogMenu controller={menuController} ownerConnectionId="A" profile="work" />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </I18nProvider>
+ </QueryClientProvider>
+ )
+ await tick(1)
+ const input: HTMLElement = screen.getByRole('textbox', { name: 'Search models' })
+ fireEvent.change(input, { target: { value: 'Download' } })
+ input.focus()
+ await tick(1)
+ const before: number = reads
+ jobs = [{ ...running, done_bytes: 2, percent: 75 }]
+ await tick(700)
+ expect(screen.getByText('75%')).toBeTruthy()
+ expect(window.document.activeElement).toBe(input)
+ expect(reads).toBe(before)
+ const key = localModelsKey({ connectionId: 'A', profile: 'work' }, 'jobs')
+ const snapshot = queryClient.getQueryData(key)
+ api.mockRejectedValueOnce(new Error('offline'))
+ await tick(700)
+ expect(queryClient.getQueryData(key)).toBe(snapshot)
+ expect(screen.getByText('75%')).toBeTruthy()
+ expect(window.document.activeElement).toBe(input)
+})
diff --git a/apps/desktop/src/store/local-runtime-jobs.test.ts b/apps/desktop/src/store/local-runtime-jobs.test.ts
index 983d8a26fb7..61011a05e49 100644
--- a/apps/desktop/src/store/local-runtime-jobs.test.ts
+++ b/apps/desktop/src/store/local-runtime-jobs.test.ts
@@ -1,5 +1,17 @@
+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), $defaultReasoningEffort: atom<string>('') }
+})
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { queryClient } from '@/lib/query-client'
import type { LocalRuntimeJob } from '@/types/hermes'
// The BACKEND is the authority: a staged registry the poll reads from, so
@@ -8,7 +20,9 @@ import type { LocalRuntimeJob } from '@/types/hermes'
const backend = vi.hoisted(() => ({ jobs: [] as LocalRuntimeJob[] }))
vi.mock('@/hermes', () => ({
- getLocalModelsJobs: vi.fn(async () => ({ jobs: backend.jobs })),
+ getLocalModelsJobs: vi.fn(async (): Promise<{ jobs: LocalRuntimeJob[] }> => ({
+ jobs: structuredClone(backend.jobs)
+ })),
getLocalModelsStatus: vi.fn(async () => ({ enabled: true, update_available: false }))
}))
@@ -21,7 +35,7 @@ vi.mock('@/store/notifications', () => ({
notifyError: vi.fn()
}))
-const { $localRuntimeJobs, watchLocalRuntimeJobs } = await import('./local-runtime-jobs')
+const { localModelsKey, localModelsOwner, watchLocalRuntimeJobs } = await import('./local-runtime-jobs')
const { getLocalModelsJobs } = await import('@/hermes')
const { notify, notifyError } = await import('@/store/notifications')
@@ -41,16 +55,16 @@ function job(overrides: Partial<LocalRuntimeJob>): LocalRuntimeJob {
}
}
-beforeEach(() => {
+beforeEach((): void => {
+ queryClient.clear()
+ queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })
vi.clearAllMocks()
backend.jobs = []
- $localRuntimeJobs.set([])
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
})
-afterEach(async () => {
- backend.jobs = []
- watchLocalRuntimeJobs()
- await vi.waitFor(() => expect($localRuntimeJobs.get()).toEqual([]))
+afterEach((): void => {
+ queryClient.clear()
})
const settle = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
@@ -70,7 +84,10 @@ describe('local runtime jobs store — pause/settle contract', () => {
it('running→paused settles NOTHING: no error toast, job stays visible', async () => {
backend.jobs = [job({ done_bytes: 40 })]
await pollTick()
- expect($localRuntimeJobs.get()[0]?.status).toBe('running')
+ expect(
+ (queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0]
+ ?.status
+ ).toBe('running')
// Backend pauses the job (status='paused', error=null).
backend.jobs = [job({ done_bytes: 40, status: 'paused' })]
@@ -80,7 +97,9 @@ describe('local runtime jobs store — pause/settle contract', () => {
expect(notifyError).not.toHaveBeenCalled()
expect(notify).not.toHaveBeenCalled()
- const snapshot = $localRuntimeJobs.get()
+ const snapshot =
+ queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
+
expect(snapshot).toHaveLength(1)
expect(snapshot[0]?.status).toBe('paused')
})
@@ -130,7 +149,10 @@ describe('local runtime jobs store — pause/settle contract', () => {
// And a backend-side resume IS picked up with no local kick at all.
backend.jobs = [job({ done_bytes: 90 })]
await pollTick()
- expect($localRuntimeJobs.get()[0]?.status).toBe('running')
+ expect(
+ (queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0]
+ ?.status
+ ).toBe('running')
})
it('coalesces refresh requests while one backend read is in flight', async () => {
@@ -148,37 +170,50 @@ describe('local runtime jobs store — pause/settle contract', () => {
backend.jobs = [job({ done_bytes: 40 })]
release({ jobs: [] })
await vi.waitFor(() => expect(getLocalModelsJobs).toHaveBeenCalledTimes(2))
- expect($localRuntimeJobs.get()[0]?.done_bytes).toBe(40)
+ expect(
+ (queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0]
+ ?.done_bytes
+ ).toBe(40)
})
- it('does not re-set the atom when a poll returns the identical payload', async () => {
+ it('preserves the query data reference when a poll returns identical payload', async () => {
backend.jobs = [job({ done_bytes: 40 })]
await pollTick()
- expect($localRuntimeJobs.get()).toHaveLength(1)
+ expect(
+ queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
+ ).toHaveLength(1)
+
+ const reference =
+ queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
- const reference = $localRuntimeJobs.get()
await pollTick()
await pollTick()
// Same reference preserved — no-op polls never hand React fresh arrays.
- expect($localRuntimeJobs.get()).toBe(reference)
+ expect(queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []).toBe(
+ reference
+ )
})
- it('equality covers control flags, ranges, percent, detail and error — not just done_bytes', async () => {
+ it('structural sharing includes control flags, ranges, percent, detail and error', async () => {
backend.jobs = [job({ done_bytes: 40, ranges: { 'model.gguf': [[0, 100]] } })]
await pollTick()
- const first = $localRuntimeJobs.get()
+ const first = queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
// Backend flips can_pause:false (e.g. a phase change) with identical bytes.
backend.jobs = [job({ can_pause: false, done_bytes: 40, ranges: { 'model.gguf': [[0, 100]] } })]
await pollTick()
- const second = $localRuntimeJobs.get()
+ const second =
+ queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
+
expect(second).not.toBe(first)
expect(second[0]?.can_pause).toBe(false)
// A ranges-only change re-publishes too.
- const before = $localRuntimeJobs.get()
+ const before =
+ queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
+
backend.jobs = [
job({
can_pause: false,
@@ -192,8 +227,13 @@ describe('local runtime jobs store — pause/settle contract', () => {
})
]
await pollTick()
- expect($localRuntimeJobs.get()).not.toBe(before)
- expect($localRuntimeJobs.get()[0]?.ranges?.['model.gguf']).toEqual([
+ expect(
+ queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? []
+ ).not.toBe(before)
+ expect(
+ (queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0]
+ ?.ranges?.['model.gguf']
+ ).toEqual([
[0, 100],
[100, 200]
])
diff --git a/apps/desktop/src/store/local-runtime-jobs.ts b/apps/desktop/src/store/local-runtime-jobs.ts
index 1a8f3ff361f..82b7878382f 100644
--- a/apps/desktop/src/store/local-runtime-jobs.ts
+++ b/apps/desktop/src/store/local-runtime-jobs.ts
@@ -1,175 +1,373 @@
-import { atom } from 'nanostores'
-
-import { getLocalModelsJobs, getLocalModelsStatus } from '@/hermes'
+import type { QueryClient } from '@tanstack/react-query'
+import {
+ type Query,
+ type QueryCacheNotifyEvent,
+ type QueryKey,
+ QueryObserver,
+ type QueryObserverResult,
+ queryOptions,
+ useQuery,
+ useQueryClient,
+ type UseQueryOptions,
+ type UseQueryResult
+} from '@tanstack/react-query'
+import { useEffect, useMemo } from 'react'
+
+import { $apiRequestScope, getApiRequestConnection, getApiRequestProfile } from '@/api/client'
+import type { LocalModelsScope } from '@/api/local-models'
+import { getLocalCatalog, getLocalHardware, getLocalModelsJobs, getLocalModelsStatus } from '@/hermes'
import { translateNow } from '@/i18n'
+import { queryClient } from '@/lib/query-client'
+import { useStoresSelector } from '@/lib/use-session-slice'
import { notify, notifyError } from '@/store/notifications'
-import type { LocalRuntimeJob } from '@/types/hermes'
-
-// App-level tracker for local-runtime jobs (runtime installs, model
-// downloads). The AUTHORITY is the backend job registry — this store is a
-// cache of it (desktop guide: server truth is cached, not owned). Living at
-// the store layer, not in the settings pane, is what makes a download
-// survive the pane unmounting: anything can start a job, the poller follows
-// it to completion, and completion/failure notify app-wide exactly once.
-
-export const $localRuntimeJobs = atom<readonly LocalRuntimeJob[]>([])
-
-const POLL_ACTIVE_MS = 700
-const POLL_PAUSED_MS = 3_000
-let timer: null | number = null
-// Jobs we've already toasted for, so a poll race can't double-notify.
-const settledNotified = new Set<string>()
-
-// The active set: running OR paused. Paused is NOT settled — it is user
-// intent, not failure — and a paused job that later runs again must stay
-// tracked so its eventual done/error notifies exactly once.
-function isActive(status: LocalRuntimeJob['status']): boolean {
- return status === 'paused' || status === 'running'
+import { $connection } from '@/store/session'
+import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'
+
+export interface LocalModelsOwner extends LocalModelsScope {
+ // Legacy primary routes have no registry pin. Fence them by endpoint instead.
+ legacyBaseUrl?: string
}
-// A job is the same observation unless ANY user-visible payload changed —
-// bytes, percent, phase, detail, error, control flags, and the per-file
-// ranges. The backend re-sorts jobs per poll, so compare by id, not index.
-function jobEqual(a: LocalRuntimeJob, b: LocalRuntimeJob): boolean {
- return (
- a.job_id === b.job_id &&
- a.status === b.status &&
- a.phase === b.phase &&
- a.detail === b.detail &&
- a.done_bytes === b.done_bytes &&
- a.total_bytes === b.total_bytes &&
- a.percent === b.percent &&
- a.error === b.error &&
- a.can_pause === b.can_pause &&
- a.can_resume === b.can_resume &&
- a.pause_requested === b.pause_requested &&
- rangesEqual(a.ranges, b.ranges)
+export function localModelsOwner(profile?: string, connectionId?: string): LocalModelsOwner {
+ const pin: string | null = connectionId ?? getApiRequestConnection()
+
+ return {
+ connectionId: pin,
+ profile: profile ?? getApiRequestProfile() ?? 'default',
+ ...(pin ? {} : { legacyBaseUrl: $connection.get()?.baseUrl ?? '' })
+ }
+}
+
+export function useLocalModelsOwner(profile?: string, connectionId?: string): LocalModelsOwner {
+ const identity: string = useStoresSelector([$apiRequestScope, $connection], (): string =>
+ JSON.stringify(localModelsOwner(profile, connectionId))
)
+
+ return useMemo((): LocalModelsOwner => JSON.parse(identity) as LocalModelsOwner, [identity])
}
-function rangesEqual(
- a: Record<string, [number, number][]> | undefined,
- b: Record<string, [number, number][]> | undefined
-): boolean {
- if (a === b) {
- return true
- }
+export function localModelsKey(owner: LocalModelsOwner, resource?: string): QueryKey {
+ return [
+ 'local-models',
+ owner.connectionId ?? `legacy:${owner.legacyBaseUrl ?? ''}`,
+ owner.profile,
+ ...(resource ? [resource] : [])
+ ]
+}
- if (!a || !b) {
- return false
+export function localModelsRequestScope(owner: LocalModelsOwner): LocalModelsScope {
+ if (!owner.connectionId && owner.legacyBaseUrl !== ($connection.get()?.baseUrl ?? '')) {
+ throw new Error('Local models connection changed')
}
- const keysA = Object.keys(a)
- const keysB = Object.keys(b)
+ return { connectionId: owner.connectionId, profile: owner.profile }
+}
- if (keysA.length !== keysB.length) {
- return false
- }
+export function isCurrentLocalModelsOwner(owner: LocalModelsOwner): boolean {
+ return JSON.stringify(localModelsKey(owner)) === JSON.stringify(localModelsKey(localModelsOwner()))
+}
- return keysA.every(key => {
- const ra = a[key]
- const rb = b[key]
+export function localModelsNotificationTitle(owner: LocalModelsOwner): string {
+ localModelsRequestScope(owner)
+ const title: string = translateNow('settings.localModels.title')
- if (!ra || !rb || ra.length !== rb.length) {
- return false
- }
+ return isCurrentLocalModelsOwner(owner)
+ ? title
+ : `${title} · ${owner.connectionId ?? owner.legacyBaseUrl} / ${owner.profile}`
+}
- return ra.every((range, i) => range[0] === rb[i]?.[0] && range[1] === rb[i]?.[1])
+export function localModelsStatusOptions(owner: LocalModelsOwner): UseQueryOptions<LocalModelsStatus> {
+ return queryOptions({
+ queryKey: localModelsKey(owner, 'status'),
+ queryFn: async (): Promise<LocalModelsStatus> => {
+ const status: LocalModelsStatus = await getLocalModelsStatus(localModelsRequestScope(owner))
+ localModelsRequestScope(owner)
+
+ return status
+ },
+ retry: false
})
}
-function jobsEqual(a: readonly LocalRuntimeJob[], b: readonly LocalRuntimeJob[]) {
- return a.length === b.length && a.every(job => b.some(other => jobEqual(job, other)))
+interface StatusWatch {
+ observer: QueryObserver<LocalModelsStatus>
+ users: number
}
+const statusWatches: WeakMap<QueryClient, Map<string, StatusWatch>> = new WeakMap()
+
+export function useLocalModelsStatus(
+ owner: LocalModelsOwner,
+ enabled: boolean = true
+): UseQueryResult<LocalModelsStatus> {
+ const client: QueryClient = useQueryClient()
+ const result: UseQueryResult<LocalModelsStatus> = useQuery({ ...localModelsStatusOptions(owner), enabled: false })
+ useEffect((): (() => void) | undefined => {
+ if (!enabled) {
+ return
+ }
-function notifySettled(previous: readonly LocalRuntimeJob[], next: readonly LocalRuntimeJob[]) {
- const wasActive = new Set(previous.filter(j => isActive(j.status)).map(j => j.job_id))
+ let watches: Map<string, StatusWatch> | undefined = statusWatches.get(client)
- for (const job of next) {
- if (isActive(job.status) || !wasActive.has(job.job_id) || settledNotified.has(job.job_id)) {
- continue
+ if (!watches) {
+ watches = new Map()
+ statusWatches.set(client, watches)
}
- settledNotified.add(job.job_id)
+ const key: string = JSON.stringify(localModelsKey(owner, 'status'))
+ let watch: StatusWatch | undefined = watches.get(key)
- if (job.status === 'done') {
- notify({
- durationMs: 6_000,
- kind: 'success',
- title: translateNow('settings.localModels.title'),
- message:
- job.kind === 'model-download'
- ? translateNow('settings.localModels.downloadDoneToast', job.target)
- : job.kind === 'model-activate'
- ? translateNow('settings.localModels.activateDoneToast', job.target)
- : job.kind === 'quickstart'
- ? translateNow('settings.localModels.quickstartDoneToast', job.target)
- : translateNow('settings.localModels.installDoneToast')
+ if (!watch) {
+ const observer: QueryObserver<LocalModelsStatus> = new QueryObserver<LocalModelsStatus>(client, {
+ ...localModelsStatusOptions(owner),
+ refetchInterval: 2_000
})
- } else {
- notifyError(
- new Error(job.error ?? job.detail ?? 'failed'),
- job.kind === 'model-download'
- ? translateNow('settings.localModels.downloadFailed', job.target)
- : job.kind === 'model-activate'
- ? translateNow('settings.localModels.activateFailed', job.target)
- : job.kind === 'quickstart'
- ? translateNow('settings.localModels.quickstartFailed')
- : translateNow('settings.localModels.installFailed')
- )
+
+ watch = { observer, users: 0 }
+ watches.set(key, watch)
+ observer.subscribe((): void => {})
}
- }
+
+ const acquired: StatusWatch = watch
+ acquired.users += 1
+
+ return (): void => {
+ acquired.users -= 1
+
+ if (acquired.users === 0) {
+ acquired.observer.destroy()
+ watches.delete(key)
+ }
+ }
+ }, [client, owner, enabled])
+
+ return result
}
-let inFlight = false
-let refreshRequested = false
+export function localModelsCatalogOptions(owner: LocalModelsOwner): UseQueryOptions<LocalCatalogModel[]> {
+ return queryOptions({
+ queryKey: localModelsKey(owner, 'catalog'),
+ queryFn: async (): Promise<LocalCatalogModel[]> => {
+ const { models } = await getLocalCatalog(localModelsRequestScope(owner))
+ localModelsRequestScope(owner)
-async function poll(): Promise<void> {
- timer = null
- inFlight = true
+ return models
+ },
+ retry: false
+ })
+}
- try {
- const { jobs } = await getLocalModelsJobs()
- const previous = $localRuntimeJobs.get()
+export function localModelsHardwareOptions(owner: LocalModelsOwner): UseQueryOptions<LocalHardware> {
+ return queryOptions({
+ queryKey: localModelsKey(owner, 'hardware'),
+ queryFn: async (): Promise<LocalHardware> => {
+ const hardware: LocalHardware = await getLocalHardware(localModelsRequestScope(owner))
+ localModelsRequestScope(owner)
- if (!jobsEqual(previous, jobs)) {
- notifySettled(previous, jobs)
- $localRuntimeJobs.set(jobs)
- }
- } catch {
- // Preserve the last snapshot while the backend is unreachable.
- } finally {
- inFlight = false
- }
+ return hardware
+ },
+ retry: false
+ })
+}
+
+const EMPTY_JOBS: readonly LocalRuntimeJob[] = []
- if (refreshRequested) {
- refreshRequested = false
- void poll()
+function isActive(status: LocalRuntimeJob['status']): boolean {
+ return status === 'paused' || status === 'running'
+}
+
+export function localModelsJobsOptions(owner: LocalModelsOwner): UseQueryOptions<readonly LocalRuntimeJob[]> {
+ return queryOptions({
+ queryKey: localModelsKey(owner, 'jobs'),
+ refetchOnMount: 'always',
+ queryFn: async (): Promise<readonly LocalRuntimeJob[]> => {
+ const { jobs } = await getLocalModelsJobs(localModelsRequestScope(owner))
+ localModelsRequestScope(owner)
+
+ // Normalize backend ordering; QueryClient does all structural sharing.
+ return [...jobs].sort((a: LocalRuntimeJob, b: LocalRuntimeJob): number => a.job_id.localeCompare(b.job_id))
+ },
+ refetchInterval: (query: Query<readonly LocalRuntimeJob[]>): number | false => {
+ if (!owner.connectionId && owner.legacyBaseUrl !== ($connection.get()?.baseUrl ?? '')) {
+ return false
+ }
+
+ const jobs: readonly LocalRuntimeJob[] = query.state.data ?? EMPTY_JOBS
+
+ return jobs.some((job: LocalRuntimeJob): boolean => job.status === 'running')
+ ? 700
+ : jobs.some((job: LocalRuntimeJob): boolean => job.status === 'paused')
+ ? 3_000
+ : false
+ },
+ refetchIntervalInBackground: true,
+ retry: false
+ })
+}
+// Only observers and transition identities live here. All payloads, request
+// deduplication, structural sharing and poll scheduling belong to QueryClient.
+const watchers: WeakMap<QueryClient, Map<string, QueryObserver<readonly LocalRuntimeJob[]>>> = new WeakMap()
+
+export function refreshLocalModels(owner: LocalModelsOwner, client: QueryClient = queryClient): void {
+ if (!owner.connectionId && !isCurrentLocalModelsOwner(owner)) {
return
}
- const jobs = $localRuntimeJobs.get()
- const anyRunning = jobs.some(job => job.status === 'running')
+ void client.invalidateQueries(
+ { queryKey: localModelsKey(owner), predicate: (query: Query): boolean => query.queryKey[3] !== 'jobs' },
+ { cancelRefetch: false }
+ )
+ void client.invalidateQueries(
+ {
+ predicate: (query: Query): boolean =>
+ query.queryKey[0] === 'model-options' &&
+ query.queryKey[1] === owner.profile &&
+ (owner.connectionId ? query.queryKey[4] === owner.connectionId : query.queryKey.length === 3)
+ },
+ { cancelRefetch: false }
+ )
+}
- if (anyRunning || jobs.some(job => job.status === 'paused')) {
- timer = window.setTimeout(() => void poll(), anyRunning ? POLL_ACTIVE_MS : POLL_PAUSED_MS)
+export function watchLocalRuntimeJobs(
+ owner: LocalModelsOwner = localModelsOwner(),
+ client: QueryClient = queryClient
+): void {
+ let owners: Map<string, QueryObserver<readonly LocalRuntimeJob[]>> | undefined = watchers.get(client)
+
+ if (!owners) {
+ owners = new Map()
+ watchers.set(client, owners)
+ client.getQueryCache().subscribe((event: QueryCacheNotifyEvent): void => {
+ if (event.type === 'removed') {
+ const id: string = JSON.stringify(event.query.queryKey)
+ const observer: QueryObserver<readonly LocalRuntimeJob[]> | undefined = watchers.get(client)?.get(id)
+
+ if (!observer) {
+ 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)
+ }
+ }
+ })
}
-}
-export function watchLocalRuntimeJobs(): void {
- if (inFlight) {
- refreshRequested = true
+ const key: QueryKey = localModelsKey(owner, 'jobs')
+ const id: string = JSON.stringify(key)
+
+ if (owners.has(id)) {
+ // In-flight refresh signals need one trailing read. All callers await the
+ // same Query promise, then QueryClient coalesces their trailing refetches.
+ if (client.getQueryState(key)?.fetchStatus === 'fetching') {
+ void client
+ .fetchQuery({ ...localModelsJobsOptions(owner), staleTime: 0 })
+ .catch((): void => {})
+ .then((): Promise<void> => client.refetchQueries({ queryKey: key, exact: true }, { cancelRefetch: false }))
+ } else {
+ void client.refetchQueries({ queryKey: key, exact: true }, { cancelRefetch: false })
+ }
return
}
- if (timer !== null) {
- window.clearTimeout(timer)
- timer = null
- }
+ const observer: QueryObserver<readonly LocalRuntimeJob[]> = new QueryObserver<readonly LocalRuntimeJob[]>(
+ client,
+ localModelsJobsOptions(owner)
+ )
+
+ owners.set(id, observer)
+ let active: Set<string> = new Set()
+ let downloading: Set<string> = new Set()
+ const settledNotified: Set<string> = new Set()
+ observer.subscribe((result: QueryObserverResult<readonly LocalRuntimeJob[]>): void => {
+ if (!result.isSuccess || result.isFetching) {
+ return
+ }
+
+ const jobs: readonly LocalRuntimeJob[] = result.data
+
+ const nextDownloads: Set<string> = new Set(
+ runningModelDownloads(jobs).map((job: LocalRuntimeJob): string => job.job_id)
+ )
+
+ let changed: boolean = [...downloading].some((jobId: string): boolean => !nextDownloads.has(jobId))
+
+ for (const job of jobs) {
+ if (isActive(job.status) || !active.has(job.job_id) || settledNotified.has(job.job_id)) {
+ continue
+ }
- void poll()
+ settledNotified.add(job.job_id)
+ changed = true
+ notifySettled(owner, job)
+ }
+
+ active = new Set(
+ jobs
+ .filter((job: LocalRuntimeJob): boolean => isActive(job.status))
+ .map((job: LocalRuntimeJob): string => job.job_id)
+ )
+ downloading = nextDownloads
+
+ if (changed) {
+ refreshLocalModels(owner, client)
+ }
+ })
+}
+
+export function useLocalRuntimeJobs<T>(
+ owner: LocalModelsOwner,
+ select: (jobs: readonly LocalRuntimeJob[]) => T,
+ enabled: boolean = true
+): T {
+ const client: QueryClient = useQueryClient()
+ const result: UseQueryResult<T> = useQuery({ ...localModelsJobsOptions(owner), enabled: false, select })
+ useEffect((): void => {
+ if (enabled) {
+ watchLocalRuntimeJobs(owner, client)
+ }
+ }, [client, owner, enabled])
+
+ return result.data ?? select(EMPTY_JOBS)
+}
+
+function notifySettled(owner: LocalModelsOwner, job: LocalRuntimeJob): void {
+ if (job.status === 'done') {
+ notify({
+ durationMs: 6_000,
+ kind: 'success',
+ title: localModelsNotificationTitle(owner),
+ message:
+ job.kind === 'model-download'
+ ? translateNow('settings.localModels.downloadDoneToast', job.target)
+ : job.kind === 'model-activate'
+ ? translateNow('settings.localModels.activateDoneToast', job.target)
+ : job.kind === 'quickstart'
+ ? translateNow('settings.localModels.quickstartDoneToast', job.target)
+ : translateNow('settings.localModels.installDoneToast')
+ })
+ } else {
+ notifyError(
+ new Error(job.error ?? job.detail ?? 'failed'),
+ localModelsNotificationTitle(owner) +
+ ': ' +
+ (job.kind === 'model-download'
+ ? translateNow('settings.localModels.downloadFailed', job.target)
+ : job.kind === 'model-activate'
+ ? translateNow('settings.localModels.activateFailed', job.target)
+ : job.kind === 'quickstart'
+ ? translateNow('settings.localModels.quickstartFailed')
+ : translateNow('settings.localModels.installFailed'))
+ )
+ }
}
// Selector: the in-flight (running or paused) download job for a catalog
@@ -204,31 +402,29 @@ export function runningRuntimeInstall(jobs: readonly LocalRuntimeJob[]): LocalRu
return jobs.find(j => j.kind === 'runtime-install' && isActive(j.status)) ?? null
}
-// One engine-update toast per app session: checked at boot (after the
-// gateway is ready), only when the user runs the local engine. The
-// download itself is always a button click in Local Models — this is a
-// pointer, not an installer.
-let updateNotified = false
+const updateNotified: Set<string> = new Set()
+
+export async function checkLocalRuntimeUpdate(owner: LocalModelsOwner = localModelsOwner()): Promise<void> {
+ const identity: string = JSON.stringify(localModelsKey(owner))
-export async function checkLocalRuntimeUpdate() {
- if (updateNotified) {
+ if (updateNotified.has(identity)) {
return
}
try {
- const status = await getLocalModelsStatus()
+ const status: LocalModelsStatus = await queryClient.fetchQuery(localModelsStatusOptions(owner))
+ localModelsRequestScope(owner)
- if (status.enabled && status.update_available) {
- updateNotified = true
+ if (status.enabled && status.update_available && !updateNotified.has(identity)) {
+ updateNotified.add(identity)
notify({
durationMs: 10_000,
kind: 'info',
- title: translateNow('settings.localModels.title'),
+ title: localModelsNotificationTitle(owner),
message: translateNow('settings.localModels.updateToast', status.configured_tag)
})
}
} catch {
- // Backend without the endpoint (older runtime) or transient failure —
- // silently skip; the pane still shows the update row when opened.
+ // Older backends may not have this endpoint. The next boot can retry.
}
}