Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复 Ollama 下载界面跳动与进度交替 (#4324)
Dash5d1d18ee3b9b
diff --git a/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.ts b/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.tsindex e7b52747f8..9948a2f30b 100644--- a/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.ts+++ b/apps/desktop/src/main/local-model-runtime/__tests__/managedOllamaProvider.test.ts@@ -21,6 +21,7 @@ import {syncManagedOllamaAgentProjections,upsertManagedOllamaModel,upsertManagedOllamaModels,+ toPlainRuntimeModel,} from '../managedOllamaProvider.js';function providerWith(id: string) {@@ -160,3 +161,14 @@ describe('managed Ollama model identity', () => {expect(updateCustomProvider).not.toHaveBeenCalled();});});++describe('local model display names', () => {+ it.each([+ ['hf.co/ornith-ai/Ornith-1.5-35B-A3B-GGUF:Q4_K_M', 'Ornith 1.5 35B A3B (Q4_K_M)'],+ ['hf.co/team/Example-GGUF:Q8_0', 'Example (Q8_0)'],+ ['hf.co/team/Example-GGUF:latest', 'Example'],+ ['custom-model:8b', 'custom-model:8b'],+ ])('formats %s without changing its execution ID', (id, name) => {+ expect(toPlainRuntimeModel(id)).toMatchObject({ id, name });+ });+});diff --git a/apps/desktop/src/main/local-model-runtime/__tests__/service.list.test.ts b/apps/desktop/src/main/local-model-runtime/__tests__/service.list.test.tsnew file mode 100644index 0000000000..534d3745ec--- /dev/null+++ b/apps/desktop/src/main/local-model-runtime/__tests__/service.list.test.ts@@ -0,0 +1,170 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { CustomProviderConfig } from '@cindy/model-providers';++vi.mock('../../maker-host/custom-provider-store.js', () => ({+ createCustomProvider: vi.fn(),+ getCustomProvider: vi.fn(),+ updateCustomProvider: vi.fn(),+}));+vi.mock('../localConnectDetect.js', () => ({ detectLocalConnectPresets: async () => [] }));++import { getCustomProvider, updateCustomProvider } from '../../maker-host/custom-provider-store.js';+import {+ buildEmptyManagedOllamaProvider,+ upsertManagedOllamaModels,+} from '../managedOllamaProvider.js';+import { createLocalModelService } from '../service.js';++// Real service and projection logic, with only persistence and Ollama I/O replaced.+describe('Ollama list refresh convergence', () => {+ let provider: CustomProviderConfig;+ let toolsSupported: boolean;+ let tagsFail: boolean;+ let offline: boolean;+ const model = 'test-tools:latest';+ const pausedPullStore = {+ read: async () => null,+ readSync: () => null,+ readAll: async () => [],+ readAllSync: () => [],+ write: async () => undefined,+ remove: async () => null,+ clear: async () => undefined,+ };+ const makeService = () =>+ createLocalModelService({+ platform: 'darwin',+ arch: 'arm64',+ totalmem: () => 128 * 1024 ** 3,+ pausedPullStore,+ fetchImpl: async (url) => {+ if (offline) throw new TypeError('fetch failed');+ if (String(url).endsWith('/api/tags')) {+ if (tagsFail) throw new Error('temporarily unavailable');+ return new Response(JSON.stringify({ models: [{ name: model, size: 1024 }] }));+ }+ if (String(url).endsWith('/api/show')) {+ return new Response(JSON.stringify({ capabilities: toolsSupported ? ['tools'] : [] }));+ }+ return new Response(JSON.stringify({ version: '0.32.14' }));+ },+ streamPull: async (_name, _onEvent, signal) =>+ new Promise<void>((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true });+ }),+ });++ beforeEach(() => {+ vi.clearAllMocks();+ provider = buildEmptyManagedOllamaProvider();+ toolsSupported = true;+ tagsFail = false;+ offline = false;+ vi.mocked(getCustomProvider).mockImplementation(async () => provider);+ vi.mocked(updateCustomProvider).mockImplementation(async (_id, next) => {+ // Persistence reconstructs objects in its own key order. Compare values,+ // not the insertion order of JSON keys (including nested model metadata).+ const reorder = (value: unknown): unknown => {+ if (Array.isArray(value)) return value.map(reorder);+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value)+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([key, item]) => [key, reorder(item)]),+ );+ }+ return value;+ };+ provider = reorder(next) as CustomProviderConfig;+ return provider;+ });+ });++ it('settles after one import instead of broadcasting changes forever', async () => {+ const service = makeService();+ expect((await service.list()).catalogDirty).toBe(true);+ vi.mocked(updateCustomProvider).mockClear();+ for (let i = 0; i < 3; i++) {+ const result = await service.list();+ expect(result.catalogDirty).toBe(false);+ expect(result.memoryGb).toBe(128);+ expect(provider.runtimes.codex?.models.map((entry) => entry.id)).toEqual([model]);+ }+ expect(updateCustomProvider).not.toHaveBeenCalled();+ });++ it('keeps coding models and hardware information stable during a pull', async () => {+ const service = makeService();+ await service.list();+ const pull = service.pull('another-model:latest').catch(() => undefined);+ try {+ await vi.waitFor(() => expect(service.activePulls()).toHaveLength(1));+ vi.mocked(updateCustomProvider).mockClear();+ for (let i = 0; i < 3; i++) {+ const result = await service.list();+ expect(result.status.kind).toBe('pulling');+ expect(result.catalogDirty).toBe(false);+ expect(result.memoryGb).toBe(128);+ expect(result.pulls[0]?.name).toBe('another-model:latest');+ }+ expect(updateCustomProvider).not.toHaveBeenCalled();+ } finally {+ await service.abortPull('pause', 'another-model:latest');+ await pull;+ }+ });++ it('retains projections on tags failure, but applies a real capabilities change once', async () => {+ const service = makeService();+ await service.list();+ vi.mocked(updateCustomProvider).mockClear();+ tagsFail = true;+ expect((await service.list()).catalogDirty).toBe(false);+ expect(updateCustomProvider).not.toHaveBeenCalled();+ expect(provider.runtimes.codex?.models).toHaveLength(1);+ tagsFail = false;+ toolsSupported = false;+ expect((await service.list()).catalogDirty).toBe(true);+ expect(provider.runtimes.codex?.models).toHaveLength(0);+ expect((await service.list()).catalogDirty).toBe(false);+ expect(updateCustomProvider).toHaveBeenCalledTimes(1);+ });++ it.each(['offline', 'tags failure'])(+ 'keeps legacy models Pi-only during %s until capabilities are known',+ async (failure) => {+ const legacyModel = { id: model, name: 'Existing model', contextWindow: 32_768 };+ provider.runtimes = {+ pi: { ...provider.runtimes.pi!, models: [legacyModel] },+ };+ offline = failure === 'offline';+ tagsFail = failure === 'tags failure';+ const service = makeService();+ expect((await service.list()).catalogDirty).toBe(true);+ expect(provider.runtimes.pi?.models).toEqual([legacyModel]);+ expect(provider.runtimes['claude-code']?.models).toEqual([]);+ expect(provider.runtimes.codex?.models).toEqual([]);+ expect((await service.list()).catalogDirty).toBe(false);+ expect(updateCustomProvider).toHaveBeenCalledTimes(1);++ offline = false;+ tagsFail = false;+ toolsSupported = false;+ await service.list();+ expect(provider.runtimes.pi?.models.map((entry) => entry.id)).toEqual([model]);+ expect(provider.runtimes['claude-code']?.models).toEqual([]);+ expect(provider.runtimes.codex?.models).toEqual([]);+ toolsSupported = true;+ expect((await service.list()).catalogDirty).toBe(true);+ expect(provider.runtimes['claude-code']?.models.map((entry) => entry.id)).toEqual([model]);+ expect(provider.runtimes.codex?.models.map((entry) => entry.id)).toEqual([model]);+ expect((await service.list()).catalogDirty).toBe(false);+ },+ );++ it('reports a legacy migration even if the subsequent upsert is unchanged', async () => {+ provider.runtimes = { pi: provider.runtimes.pi! };+ expect(await upsertManagedOllamaModels([])).toMatchObject({ ok: true, changed: true });+ expect(await upsertManagedOllamaModels([])).toMatchObject({ ok: true, changed: false });+ });+});diff --git a/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.ts b/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.tsindex d446b0d547..24210d00b7 100644--- a/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.ts+++ b/apps/desktop/src/main/local-model-runtime/__tests__/service.owner.test.ts@@ -5,8 +5,8 @@ vi.mock('../managedOllamaProvider.js', async (importOriginal) => {return {...actual,readManagedOllamaProvider: vi.fn(async () => actual.buildEmptyManagedOllamaProvider()),- syncManagedOllamaAgentProjections: vi.fn(async (_agents, opts) => {- if (opts?.stillActive && !opts.stillActive()) return false;+ migrateManagedOllamaOnCatalogLoad: vi.fn(async (stillActive) => {+ if (stillActive && !stillActive()) return false;return false;}),upsertManagedOllamaModel: vi.fn(async (_model, _agents, opts) => {@@ -31,7 +31,7 @@ vi.mock('../managedOllamaProvider.js', async (importOriginal) => {import { createLocalModelService, OwnerChangedError } from '../service.js';import {readManagedOllamaProvider,- syncManagedOllamaAgentProjections,+ migrateManagedOllamaOnCatalogLoad,upsertManagedOllamaModel,upsertManagedOllamaModels,} from '../managedOllamaProvider.js';@@ -68,7 +68,7 @@ describe('owner change during pull', () => {vi.mocked(upsertManagedOllamaModel).mockClear();vi.mocked(upsertManagedOllamaModels).mockClear();vi.mocked(readManagedOllamaProvider).mockClear();- vi.mocked(syncManagedOllamaAgentProjections).mockClear();+ vi.mocked(migrateManagedOllamaOnCatalogLoad).mockClear();});it('does not upsert or import a pull finished after the account switched', async () => {@@ -132,7 +132,7 @@ describe('owner change during pull', () => {expect(upsertManagedOllamaModels).not.toHaveBeenCalled();});- it('passes the captured owner into projection sync during list', async () => {+ it('passes the captured owner into legacy migration during list', async () => {const service = createLocalModelService({fetchImpl: readyFetch(),});@@ -140,11 +140,8 @@ describe('owner change during pull', () => {owner: { dataOwnerId: 'alice', generation: 1 },ownerStillActive: () => false,});- expect(syncManagedOllamaAgentProjections).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ stillActive: expect.any(Function) }),- );- const opts = vi.mocked(syncManagedOllamaAgentProjections).mock.calls[0]?.[1];- expect(opts?.stillActive?.()).toBe(false);+ expect(migrateManagedOllamaOnCatalogLoad).toHaveBeenCalledWith(expect.any(Function));+ const opts = vi.mocked(migrateManagedOllamaOnCatalogLoad).mock.calls[0]?.[0];+ expect(opts?.()).toBe(false);});});diff --git a/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.ts b/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.tsindex c82052b723..dd8532efa3 100644--- a/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.ts+++ b/apps/desktop/src/main/local-model-runtime/managedOllamaProvider.ts@@ -1,3 +1,4 @@+import { isDeepStrictEqual } from 'node:util';import type {AgentKind,CustomProviderConfig,@@ -23,7 +24,7 @@ import {} from '../maker-host/custom-provider-store.js';export type ManagedEnsureResult =- | { ok: true; created: boolean; provider: CustomProviderConfig }+ | { ok: true; created: boolean; changed?: boolean; provider: CustomProviderConfig }| { ok: false; code: 'OWNER_CHANGED' }| { ok: false; code: 'MANAGED_ID_CONFLICT'; existing: CustomProviderConfig };@@ -96,13 +97,23 @@ export function buildEmptyManagedOllamaProvider(): CustomProviderConfig {};}+/** Keep the repository identity and quantization visible without the HF transport prefix. */+function localModelDisplayName(name: string): string {+ const curated = curatedOllamaDisplayName(name);+ if (curated) return curated;+ const hf = /^hf\.co\/[^/]+\/([^/:]+)(?::([^/]+))?$/.exec(name);+ if (!hf) return name;+ const title = hf[1]!.replace(/[-_]GGUF$/i, '').replace(/[-_]+/g, ' ');+ return hf[2] && hf[2] !== 'latest' ? `${title} (${hf[2]})` : title;+}+export function toPlainRuntimeModel(name: string,contextLength?: number,): ProviderRuntimeModelConfig {return {id: name,- name: curatedOllamaDisplayName(name) ?? name,+ name: localModelDisplayName(name),reasoning: false,...(contextLength && contextLength > 0 ? { contextWindow: contextLength } : {}),};@@ -176,10 +187,10 @@ export function migrateManagedOllamaProvider(...existing,runtimes: {pi: emptyPiRuntime(piModels),- 'claude-code': emptyClaudeRuntime(- piModels.map((model) => toAgentModel(model, 'claude-code')),- ),- codex: emptyCodexRuntime(piModels.map((model) => toAgentModel(model, 'codex'))),+ // Migration has no capability evidence. Imports populate coding runtimes+ // only after probing each model; offline legacy models remain Pi-only.+ 'claude-code': emptyClaudeRuntime(),+ codex: emptyCodexRuntime(),},};}@@ -194,7 +205,7 @@ export async function migrateManagedOllamaOnCatalogLoad(if (!existing || !fingerprintOf(existing)) return false;const migrated = migrateManagedOllamaProvider(existing);if (!migrated) return false;- if (JSON.stringify(migrated.runtimes) === JSON.stringify(existing.runtimes)) {+ if (isDeepStrictEqual(migrated.runtimes, existing.runtimes)) {return false;}if (!stillCurrent()) return false;@@ -219,7 +230,7 @@ export async function syncManagedOllamaAgentProjections(for (const model of piModels) {next = applyModelToAgents(next, model, agents, 'upsert');}- if (JSON.stringify(next.runtimes) === JSON.stringify(existing.runtimes)) return false;+ if (isDeepStrictEqual(next.runtimes, existing.runtimes)) return false;if (ownerChanged(opts)) return false;const updated = await updateCustomProvider(MANAGED_OLLAMA_PROVIDER_ID, next);return updated !== null;@@ -274,12 +285,17 @@ export async function upsertManagedOllamaModels(next = retainCanonicalModels(next, opts.retainCanonicalIds);}if (opts?.stillActive && !opts.stillActive()) return { ok: false, code: 'OWNER_CHANGED' };- if (JSON.stringify(next.runtimes) === JSON.stringify(latest.runtimes)) {- return { ok: true, created: false, provider: latest };+ if (isDeepStrictEqual(next.runtimes, latest.runtimes)) {+ return {+ ok: true,+ created: ensured.created,+ changed: ensured.changed === true || ensured.created,+ provider: latest,+ };}const updated = await updateCustomProvider(MANAGED_OLLAMA_PROVIDER_ID, next);if (!updated) return { ok: false, code: 'MANAGED_ID_CONFLICT', existing: latest };- return { ok: true, created: false, provider: updated };+ return { ok: true, created: false, changed: true, provider: updated };});}@@ -325,7 +341,7 @@ export async function removeManagedOllamaModel(if (ownerChanged(opts)) return { ok: false, code: 'OWNER_CHANGED' };const updated = await updateCustomProvider(MANAGED_OLLAMA_PROVIDER_ID, next);if (!updated) return { ok: false, code: 'MANAGED_ID_CONFLICT', existing };- return { ok: true, created: false, provider: updated };+ return { ok: true, created: false, changed: true, provider: updated };});}@@ -366,7 +382,7 @@ async function ensureManagedOllamaProviderUnlocked(if (!existing) {try {const created = await createCustomProvider(buildEmptyManagedOllamaProvider());- return { ok: true, created: true, provider: created };+ return { ok: true, created: true, changed: true, provider: created };} catch {if (ownerChanged(opts)) return { ok: false, code: 'OWNER_CHANGED' };const raced = await getCustomProvider(MANAGED_OLLAMA_PROVIDER_ID);@@ -376,7 +392,7 @@ async function ensureManagedOllamaProviderUnlocked(if (migrated !== raced) {if (ownerChanged(opts)) return { ok: false, code: 'OWNER_CHANGED' };const updated = await updateCustomProvider(MANAGED_OLLAMA_PROVIDER_ID, migrated);- if (updated) return { ok: true, created: false, provider: updated };+ if (updated) return { ok: true, created: false, changed: true, provider: updated };}return { ok: true, created: false, provider: raced };}@@ -391,7 +407,7 @@ async function ensureManagedOllamaProviderUnlocked(if (ownerChanged(opts)) return { ok: false, code: 'OWNER_CHANGED' };const updated = await updateCustomProvider(MANAGED_OLLAMA_PROVIDER_ID, migrated);if (!updated) return { ok: false, code: 'MANAGED_ID_CONFLICT', existing };- return { ok: true, created: false, provider: updated };+ return { ok: true, created: false, changed: true, provider: updated };}return { ok: true, created: false, provider: existing };}diff --git a/apps/desktop/src/main/local-model-runtime/service.ts b/apps/desktop/src/main/local-model-runtime/service.tsindex bef92248d2..8a4313ae63 100644--- a/apps/desktop/src/main/local-model-runtime/service.ts+++ b/apps/desktop/src/main/local-model-runtime/service.ts@@ -49,7 +49,7 @@ import { probeOllamaStatus, startOfficialOllamaApp } from './ollamaRuntime.js';import {ensureManagedOllamaProvider,managedOllamaRemovalGeneration,- syncManagedOllamaAgentProjections,+ migrateManagedOllamaOnCatalogLoad,readManagedOllamaProvider,removeManagedOllamaModel,toPlainRuntimeModel,@@ -467,10 +467,11 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Localconst pulls = visiblePulls(await rememberedPaused());const pull = pulls[0] ?? null;const pausedPull = pulls.find((item) => item.phase === 'paused') ?? null;- const catalogDirty = await syncManagedOllamaAgentProjections(- resolveManagedOllamaAgents({ version: current.version }),- { stillActive: opts?.ownerStillActive },- ).catch(() => false);+ // Preserve existing agent membership until per-model capabilities are probed.+ // Version alone has no tools evidence and would remove then re-add coding models.+ const catalogDirty = await migrateManagedOllamaOnCatalogLoad(opts?.ownerStillActive).catch(+ () => false,+ );const detectedLocalPresetIds = await detectedLocalPresetIdsPromise;if (current.kind !== 'ready' && current.kind !== 'pulling') {return {@@ -855,7 +856,7 @@ export function createLocalModelService(deps: LocalModelServiceDeps = {}): Localif (result.ok) {for (const tag of named) clearUnclaimed(tag.name);}- return result.ok;+ return result.ok && result.changed === true;}function keepPullNames(): string[] {diff --git a/apps/desktop/src/renderer/__tests__/ollamaProviderDetail.test.tsx b/apps/desktop/src/renderer/__tests__/ollamaProviderDetail.test.tsxnew file mode 100644index 0000000000..c1034fa652--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/ollamaProviderDetail.test.tsx@@ -0,0 +1,188 @@+// @vitest-environment jsdom+import React from 'react';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { LocalModelPullProgress } from '../../shared/localModelRuntime';+import { OllamaProviderDetail } from '../components/settings/OllamaProviderDetail';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),+}));+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));+vi.mock('../components/settings/LocalOllamaInstall', () => ({+ LocalOllamaInstall: () => null,+ offersManagedOllamaInstall: () => false,+}));+vi.mock('../components/settings/DownloadMeter', () => ({+ DownloadMeter: ({ progress }: { progress: { percent?: number } }) => (+ <div data-testid="progress">{progress.percent ?? 'starting'}</div>+ ),+}));++const model = {+ id: 'test',+ name: 'Test model',+ libraryName: 'test:latest',+ minUnifiedMemoryGb: 8,+ sizeBytes: 1024,+};+const progress = (+ percent: number,+ phase: LocalModelPullProgress['phase'] = 'downloading',+): LocalModelPullProgress => ({+ name: model.libraryName,+ status: phase!,+ phase,+ percent,+ done: phase === 'success',+});+const snapshot = (pulls: LocalModelPullProgress[] = []) => ({+ status: { kind: 'ready' },+ models: [],+ catalog: [model],+ featured: [model],+ memoryGb: 128,+ pulls,+});+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: Error) => void;+ const promise = new Promise<T>((r, fail) => {+ resolve = r;+ reject = fail;+ });+ return { promise, resolve, reject };+}+let onProgress: (value: LocalModelPullProgress) => void;+let onCatalog: () => void;+const list = vi.fn();+const pull = vi.fn();+const changed = vi.fn();+const downloadLabel = 'settings.providers.local.downloadAdd';+const download = () =>+ screen.getAllByText(downloadLabel).find((el) => !el.hasAttribute('disabled'))!;++beforeEach(() => {+ list.mockReset().mockResolvedValue(snapshot());+ pull.mockReset().mockReturnValue(new Promise(() => undefined));+ changed.mockReset();+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'darwin',+ maker: {+ localModelList: list,+ localModelPull: pull,+ onProvidersChanged: (cb: typeof onCatalog) => {+ onCatalog = cb;+ return () => undefined;+ },+ onLocalModelPullProgress: (cb: typeof onProgress) => {+ onProgress = cb;+ return () => undefined;+ },+ onLocalModelStatus: () => () => undefined,+ },+ },+ });+});+afterEach(cleanup);+const mount = async () => {+ await act(async () => {+ render(<OllamaProviderDetail onChanged={changed} />);+ });+};++describe('Ollama download snapshot ordering', () => {+ it('does not replace a newly started download with a late empty list', async () => {+ await mount();+ const old = deferred<ReturnType<typeof snapshot>>();+ list.mockReturnValueOnce(old.promise);+ act(() => onCatalog());+ fireEvent.click(download());+ expect(screen.getByTestId('progress').textContent).toBe('starting');+ await act(async () => old.resolve(snapshot()));+ expect(screen.getByTestId('progress').textContent).toBe('starting');+ });++ it('keeps newer progress while still restoring unrelated paused downloads', async () => {+ const old = deferred<ReturnType<typeof snapshot>>();+ list.mockReturnValueOnce(old.promise);+ await mount();+ act(() => onProgress(progress(40)));+ await act(async () =>+ old.resolve(+ snapshot([progress(5), { ...progress(12, 'paused'), name: 'other:latest', done: true }]),+ ),+ );+ expect(screen.getAllByTestId('progress').map((el) => el.textContent)).toEqual(['40', '12']);+ });++ it('does not resurrect a completed download from a late list', async () => {+ const old = deferred<ReturnType<typeof snapshot>>();+ list.mockReturnValueOnce(old.promise);+ await mount();+ act(() => {+ onProgress(progress(40));+ onProgress(progress(100, 'success'));+ });+ await act(async () => old.resolve(snapshot([progress(5)])));+ expect(screen.queryByTestId('progress')).toBeNull();+ });++ it('ignores an older list that finishes after a newer refresh', async () => {+ const old = deferred<ReturnType<typeof snapshot>>();+ list.mockReturnValueOnce(old.promise).mockResolvedValueOnce(snapshot([progress(60)]));+ await mount();+ await act(async () => onCatalog());+ await act(async () => old.resolve(snapshot([progress(5)])));+ expect(screen.getByTestId('progress').textContent).toBe('60');+ });++ it('keeps a local start while the pull IPC has not registered it yet', async () => {+ await mount();+ fireEvent.click(download());+ await act(async () => onCatalog());+ expect(screen.getByTestId('progress').textContent).toBe('starting');+ });++ it.each([false, true])('keeps the resumed pull guarded after the old refresh (fails=%s)', async (fails) => {+ await mount();+ const first = deferred<{ stopped: boolean }>();+ pull.mockReturnValueOnce(first.promise);+ fireEvent.click(download());+ act(() => onProgress({ ...progress(25, 'paused'), done: true }));+ const old = deferred<ReturnType<typeof snapshot>>();+ list.mockReturnValueOnce(old.promise);+ await act(async () => first.resolve({ stopped: true }));+ // Resume while the old call is still awaiting its post-stop list refresh.+ const input = document.querySelector('#ollama-manual-download')!;+ fireEvent.change(input, { target: { value: 'test' } });+ const manual = screen.getAllByText(downloadLabel).at(-1)!;+ fireEvent.click(manual);+ expect(pull).toHaveBeenCalledTimes(2);+ act(() => onProgress(progress(40)));+ await act(async () => {+ if (fails) old.reject(new Error('list unavailable'));+ else old.resolve(snapshot([progress(25, 'paused')]));+ });+ fireEvent.click(manual);+ expect(pull).toHaveBeenCalledTimes(2);+ expect(screen.getByTestId('progress').textContent).toBe('40');+ });++ it('dispatches once when the same model is submitted twice', async () => {+ await mount();+ const input = document.querySelector('#ollama-manual-download')!;+ fireEvent.change(input, { target: { value: 'test' } });+ const buttons = screen.getAllByText(downloadLabel);+ const manual = buttons[buttons.length - 1]!;+ fireEvent.click(manual);+ fireEvent.click(manual);+ expect(pull).toHaveBeenCalledTimes(1);+ act(() => onProgress(progress(25)));+ fireEvent.click(manual);+ expect(screen.getByTestId('progress').textContent).toBe('25');+ expect(pull).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx b/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsxindex 7ae3a44ca0..c8abd6fdf7 100644--- a/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx+++ b/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { Pause, Play, X } from 'lucide-react';@@ -14,6 +14,7 @@ import type {LocalRuntimeStatus,} from '../../../shared/localModelRuntime';import {+ canonicalOllamaModelRef,classifyOllamaPullError,filterCuratedOllamaModels,isHfMlxPullName,@@ -125,42 +126,64 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {const [busy, setBusy] = useState(false);const [pulls, setPulls] = useState<Record<string, LocalModelPullProgress>>({});- const replaceListedPulls = useCallback((items: readonly LocalModelPullProgress[]) => {- setPulls((current) => {- const next: Record<string, LocalModelPullProgress> = {};- for (const item of items) {- if (item.phase === 'cancelled' || item.phase === 'success') continue;- next[item.name] = item;- }- for (const [name, item] of Object.entries(current)) {- if (!next[name] && item.phase === 'error') next[name] = item;- }- return next;- });- }, []);+ const refreshGeneration = useRef(0);+ const progressRevision = useRef(0);+ const statusRevision = useRef(0);+ const updatedPulls = useRef(new Map<string, number>());+ const pendingPulls = useRef(new Set<string>());++ const replaceListedPulls = useCallback(+ (items: readonly LocalModelPullProgress[], since: number) => {+ setPulls((current) => {+ const next: Record<string, LocalModelPullProgress> = {};+ for (const item of items) {+ if (item.phase === 'cancelled' || item.phase === 'success') continue;+ next[canonicalOllamaModelRef(item.name)] = item;+ }+ for (const [name, item] of Object.entries(current)) {+ if (!next[name] && item.phase === 'error') next[name] = item;+ }+ // A slow list response must not undo progress, start, pause or completion+ // events received after that request began. Keep terminal deletions too.+ for (const [name, revision] of updatedPulls.current) {+ if (revision <= since && !pendingPulls.current.has(name)) continue;+ if (current[name]) next[name] = current[name];+ else delete next[name];+ }+ return next;+ });+ },+ [],+ );const upsertPull = useCallback((item: LocalModelPullProgress) => {+ const name = canonicalOllamaModelRef(item.name);+ updatedPulls.current.set(name, ++progressRevision.current);setPulls((current) => {if (item.phase === 'cancelled' || item.phase === 'success') {- if (!(item.name in current)) return current;+ if (!(name in current)) return current;const next = { ...current };- delete next[item.name];+ delete next[name];return next;}- return { ...current, [item.name]: item };+ return { ...current, [name]: item };});}, []);const refresh = useCallback(async () => {+ const generation = ++refreshGeneration.current;+ const since = progressRevision.current;+ const statusSince = statusRevision.current;const result = await window.electronAPI.maker.localModelList();- setStatus(result.status);+ if (generation !== refreshGeneration.current) return;+ if (statusSince === statusRevision.current) setStatus(result.status);setModels(result.models);setCatalog(result.catalog ?? []);setFeatured(result.featured ?? []);setMemoryGb(result.memoryGb ?? 0);setRecommendReason(result.recommendReason ?? 'unknown');setAppleSilicon(result.appleSilicon === true);- replaceListedPulls(result.pulls ?? []);+ replaceListedPulls(result.pulls ?? [], since);if (result.catalogDirty) onChanged();}, [onChanged, replaceListedPulls]);@@ -170,12 +193,14 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {void refresh().catch(() => undefined);});const offStatus = window.electronAPI.maker.onLocalModelStatus((next) => {+ statusRevision.current += 1;setStatus(next as LocalRuntimeStatus);});const offPull = window.electronAPI.maker.onLocalModelPullProgress((next) => {upsertPull(next as LocalModelPullProgress);});return () => {+ refreshGeneration.current += 1;offCatalog();offStatus();offPull();@@ -206,15 +231,25 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {toast.error(t('settings.providers.local.pullError.not-gguf'));return;}+ const key = canonicalOllamaModelRef(name);+ if (pendingPulls.current.has(key)) return;+ pendingPulls.current.add(key);upsertPull({ name, status: 'starting', phase: 'starting', done: false });try {- const result = await window.electronAPI.maker.localModelPull(name);+ let result;+ try {+ result = await window.electronAPI.maker.localModelPull(name);+ } finally {+ // Release only this IPC's guard, before awaiting a refresh that may+ // outlive a resumed download. Never clear another call's guard later.+ pendingPulls.current.delete(key);+ }if (result.stopped) {- await refresh();+ await refresh().catch(() => undefined);return;}upsertPull({ name, status: 'success', phase: 'success', percent: 100, done: true });- await refresh();+ await refresh().catch(() => undefined);onChanged();toast.success(t('settings.providers.local.added'));} catch (error) {@@ -240,7 +275,7 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {const handleAbort = async (reason: 'pause' | 'cancel', name: string) => {try {- const current = pulls[name];+ const current = pulls[canonicalOllamaModelRef(name)];if (reason === 'cancel' && current?.phase === 'paused') {await window.electronAPI.maker.localModelDiscardPaused(name);} else {@@ -284,7 +319,7 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {const renderCatalogCard = (entry: CuratedOllamaModel) => {const installed = models.some((model) => ollamaModelRefsEqual(model.name, entry.libraryName));- const pull = pulls[entry.libraryName];+ const pull = pulls[canonicalOllamaModelRef(entry.libraryName)];const pulling = Boolean(pull && (!pull.done || pull.phase === 'paused'));const failed = pull?.phase === 'error';if (!searching && installed && !pulling && !failed) return null;