diff --git a/desktop/renderer/env.d.ts b/desktop/renderer/env.d.ts index def4fb8..5255bf4 100644 --- a/desktop/renderer/env.d.ts +++ b/desktop/renderer/env.d.ts @@ -221,8 +221,13 @@ interface OpenClawAPI { write( config: unknown, expectedConfig?: unknown, - intent?: { kind: "initial-setup"; providerKey: string } | { kind: "search-settings" }, + intent?: + | { kind: "initial-setup"; providerKey: string } + | import("../src/search-setup-progress").SearchSettingsWriteIntent, ): Promise; + onSearchProgress( + callback: (progress: import("../src/search-setup-progress").SearchSetupProgress) => void, + ): () => void; }; settings: { get(): Promise; diff --git a/desktop/renderer/src/browser-openclaw.ts b/desktop/renderer/src/browser-openclaw.ts index 5bab36c..f165884 100644 --- a/desktop/renderer/src/browser-openclaw.ts +++ b/desktop/renderer/src/browser-openclaw.ts @@ -42,6 +42,7 @@ export function createBrowserOpenClawMock(): OpenClawAPI { read: async () => ({}), readEnv: async () => ({}), write: noopAsync, + onSearchProgress: noopSub, isConfigured: async () => true, initialSetupRequired: async () => false, needsSetup: async () => false, diff --git a/desktop/renderer/src/i18n/en-US.ts b/desktop/renderer/src/i18n/en-US.ts index 89f5f7b..e5626bc 100644 --- a/desktop/renderer/src/i18n/en-US.ts +++ b/desktop/renderer/src/i18n/en-US.ts @@ -595,6 +595,12 @@ export default { "settings.searchApiKeyRequired": "API key required", "settings.searchApiKeyFormatInvalid": "Check the key format", "settings.searchSaveFailed": "Failed to save", + "settings.searchProgress": "{stage} · {seconds}s", + "settings.searchPreparing": "Preparing", + "settings.searchFetching": "Fetching component", + "settings.searchInstalling": "Installing component", + "settings.searchActivating": "Enabling search", + "settings.searchVerifying": "Checking readiness", "settings.saveFailed": "Save failed: {error}", "settings.openLinkFailed": "Could not open the link: {error}", "settings.clearHistoryConfirm": diff --git a/desktop/renderer/src/i18n/zh-CN.ts b/desktop/renderer/src/i18n/zh-CN.ts index 45897e4..b107585 100644 --- a/desktop/renderer/src/i18n/zh-CN.ts +++ b/desktop/renderer/src/i18n/zh-CN.ts @@ -557,6 +557,12 @@ export default { "settings.searchApiKeyRequired": "需要 API 密钥", "settings.searchApiKeyFormatInvalid": "请检查密钥格式", "settings.searchSaveFailed": "保存失败", + "settings.searchProgress": "{stage} · {seconds} 秒", + "settings.searchPreparing": "准备组件", + "settings.searchFetching": "获取组件", + "settings.searchInstalling": "安装组件", + "settings.searchActivating": "启用搜索", + "settings.searchVerifying": "确认就绪", "settings.saveFailed": "保存失败:{error}", "settings.openLinkFailed": "无法打开链接:{error}", "settings.clearHistoryConfirm": "确定要清除所有聊天记录吗?此操作不可撤销。", diff --git a/desktop/renderer/src/views/SettingsView.test.ts b/desktop/renderer/src/views/SettingsView.test.ts index 1190ff3..36646e8 100644 --- a/desktop/renderer/src/views/SettingsView.test.ts +++ b/desktop/renderer/src/views/SettingsView.test.ts @@ -2524,6 +2524,9 @@ describe("SettingsView", () => { }); describe("SettingsView search autosave events", () => { + type ProgressListener = Parameters[0]; + let emitSearchProgress: ProgressListener; + let unsubscribeProgress: ReturnType; function control(tag: "select" | "option" | "input") { return defineComponent({ name: `Search${tag}Control`, @@ -2615,8 +2618,16 @@ describe("SettingsView search autosave events", () => { }); toast = vi.spyOn(ElMessage, "error").mockImplementation(() => ({ close: vi.fn() })); unsubscribeDisplay = vi.fn(); + unsubscribeProgress = vi.fn(); window.openclaw = { - config: { read, write }, + config: { + read, + write, + onSearchProgress: vi.fn((listener: ProgressListener) => { + emitSearchProgress = listener; + return unsubscribeProgress; + }), + }, model: { ...createBrowserOpenClawMock().model, listGitHubCopilotModels: vi.fn().mockResolvedValue([]), @@ -2636,6 +2647,67 @@ describe("SettingsView search autosave events", () => { afterEach(() => { wrappers.forEach((wrapper) => wrapper.unmount()); toast.mockRestore(); + vi.useRealTimers(); + }); + + it("shows real stages with elapsed time and stops observing on completion", async () => { + const wrapper = await mountSearch(); + vi.useFakeTimers(); + const pending = deferred(); + write.mockImplementationOnce(() => pending.promise); + await key(wrapper).trigger("blur"); + await flushPromises(); + const { requestId } = write.mock.calls[0][2]; + expect(status(wrapper).text()).toBe("Preparing · 0s"); + await vi.advanceTimersByTimeAsync(22_000); + expect(status(wrapper).text()).toBe("Preparing · 22s"); + emitSearchProgress({ requestId: "unrelated", stage: "fetching" }); + await flushPromises(); + expect(status(wrapper).text()).toBe("Preparing · 22s"); + emitSearchProgress({ requestId, stage: "installing" }); + await flushPromises(); + expect(status(wrapper).text()).toBe("Installing component · 22s"); + pending.resolve(); + await flushPromises(); + expect(status(wrapper).text()).toBe("Saved"); + expect(unsubscribeProgress).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + emitSearchProgress({ requestId, stage: "verifying" }); + await flushPromises(); + expect(status(wrapper).text()).toBe("Saved"); + }); + + it("ignores progress for an edited form and cleans up when leaving during a write", async () => { + const wrapper = await mountSearch(); + vi.useFakeTimers(); + const pending = deferred(); + write.mockImplementationOnce(() => pending.promise); + await key(wrapper).trigger("blur"); + await flushPromises(); + const { requestId } = write.mock.calls[0][2]; + await provider(wrapper).setValue("tavily"); + const invalid = status(wrapper).text(); + emitSearchProgress({ requestId, stage: "installing" }); + await flushPromises(); + expect(status(wrapper).text()).toBe(invalid); + expect(vi.getTimerCount()).toBe(0); + wrapper.unmount(); + wrappers = []; + expect(unsubscribeProgress).toHaveBeenCalledOnce(); + pending.resolve(); + await flushPromises(); + expect(toast).not.toHaveBeenCalled(); + }); + + it("stops the elapsed timer and subscription on failure", async () => { + const wrapper = await mountSearch(); + vi.useFakeTimers(); + write.mockRejectedValueOnce(new Error("installation failed")); + await key(wrapper).trigger("blur"); + await flushPromises(); + expect(status(wrapper).text()).toBe("Failed to save"); + expect(unsubscribeProgress).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); }); it("loads the selected provider key from the Gateway plugin configuration", async () => { @@ -2661,7 +2733,10 @@ describe("SettingsView search autosave events", () => { pending.resolve(structuredClone(config)); await flushPromises(); expect(write).toHaveBeenCalledOnce(); - expect(write).toHaveBeenCalledWith(expect.anything(), original, { kind: "search-settings" }); + expect(write).toHaveBeenCalledWith(expect.anything(), original, { + kind: "search-settings", + requestId: expect.any(String), + }); expect(config).toMatchObject({ unrelated: { keep: true }, tools: { diff --git a/desktop/renderer/src/views/SettingsView.vue b/desktop/renderer/src/views/SettingsView.vue index 1f6121a..142f8f8 100644 --- a/desktop/renderer/src/views/SettingsView.vue +++ b/desktop/renderer/src/views/SettingsView.vue @@ -450,7 +450,10 @@

{{ t("settings.webSearch") }}

- + {{ t("settings.searchNotConfigured") }} ("idle"); const searchSaveError = ref(""); +const searchStage = ref("preparing"); +const searchElapsedSeconds = ref(0); +const searchStageLabels: Record = { + preparing: "settings.searchPreparing", + fetching: "settings.searchFetching", + installing: "settings.searchInstalling", + activating: "settings.searchActivating", + verifying: "settings.searchVerifying", +}; +let searchFormGeneration = 0; +let searchProgressTimer: ReturnType | undefined; +let unsubscribeSearchProgress: (() => void) | undefined; +watch( + searchSaveStatus, + (status) => { + clearInterval(searchProgressTimer); + searchProgressTimer = undefined; + if (status !== "saving") return; + searchStage.value = "preparing"; + searchElapsedSeconds.value = 0; + const started = performance.now(); + searchProgressTimer = setInterval(() => { + searchElapsedSeconds.value = Math.floor((performance.now() - started) / 1000); + }, 1000); + }, + { flush: "sync" }, +); const searchSaveStatusClass = computed(() => { if (searchSaveStatus.value === "saved") return "status-indicator--ok"; if (searchSaveStatus.value === "saving") return "status-indicator--muted"; return "status-indicator--error"; }); const searchSaveStatusText = computed(() => { - if (searchSaveStatus.value === "saving") return t("settings.saving"); + if (searchSaveStatus.value === "saving") + return t("settings.searchProgress", { + stage: t(searchStageLabels[searchStage.value]), + seconds: searchElapsedSeconds.value, + }); if (searchSaveStatus.value === "saved") return t("settings.saved"); if (searchSaveStatus.value === "invalid") return searchSaveError.value; if (searchSaveStatus.value === "error") return t("settings.searchSaveFailed"); @@ -1846,6 +1881,7 @@ const searchAutosave = createSearchAutosave({ watch( [searchProvider, () => searchKeys[searchProvider.value]], () => { + searchFormGeneration += 1; searchAutosave.invalidate(); searchSaveError.value = ""; searchSaveStatus.value = "idle"; @@ -2166,6 +2202,8 @@ onMounted(async () => { onUnmounted(() => { searchAutosave.dispose(); + clearInterval(searchProgressTimer); + unsubscribeSearchProgress?.(); unsubscribeMxcDisplay?.(); window.removeEventListener("focus", handleSettingsWindowFocus); copilotModelsGeneration += 1; @@ -2432,12 +2470,31 @@ async function persistSearchConfig( request: SearchSaveRequest, canWrite: () => boolean, ): Promise { + const generation = searchFormGeneration; const config = await window.openclaw.config.read(); if (!canWrite()) return false; - await window.openclaw.config.write(patchSearchConfig(config, request), config, { - kind: "search-settings", + const requestId = crypto.randomUUID(); + const unsubscribe = window.openclaw.config.onSearchProgress?.((progress) => { + if ( + canWrite() && + generation === searchFormGeneration && + searchSaveStatus.value === "saving" && + progress.requestId === requestId && + Object.hasOwn(searchStageLabels, progress.stage) + ) + searchStage.value = progress.stage; }); - return true; + unsubscribeSearchProgress = unsubscribe; + try { + await window.openclaw.config.write(patchSearchConfig(config, request), config, { + kind: "search-settings", + requestId, + }); + return true; + } finally { + unsubscribe?.(); + if (unsubscribeSearchProgress === unsubscribe) unsubscribeSearchProgress = undefined; + } } // Capture and validate synchronously before any read, then serialize read/patch/write. diff --git a/desktop/src/config-write-service.test.ts b/desktop/src/config-write-service.test.ts index 7424211..243af3a 100644 --- a/desktop/src/config-write-service.test.ts +++ b/desktop/src/config-write-service.test.ts @@ -151,6 +151,7 @@ describe("guarded configuration writes", () => { next, before, expect.any(Function), + undefined, ); expect(state.deps.persist).not.toHaveBeenCalled(); expect(state.deps.startServices).not.toHaveBeenCalled(); @@ -168,10 +169,42 @@ describe("guarded configuration writes", () => { next, before, expect.any(Function), + undefined, ); expect(state.deps.persist).not.toHaveBeenCalled(); }); + it("passes a validated search request id through to progress reporting", async () => { + const before = routedConfig(); + const state = fixture({ mxc: false, current: before }); + const next = searchChange(before); + await writeGuardedConfig(state.deps, next, before, { + kind: "search-settings", + requestId: "search-123", + }); + expect(state.deps.applySearch).toHaveBeenCalledExactlyOnceWith( + next, + before, + expect.any(Function), + "search-123", + ); + }); + + it.each(["", "x".repeat(129), 123, null])( + "rejects an invalid search request id: %s", + async (requestId) => { + const before = routedConfig(); + const state = fixture({ mxc: false, current: before }); + await expect( + writeGuardedConfig(state.deps, searchChange(before), before, { + kind: "search-settings", + requestId, + }), + ).rejects.toThrow("Invalid configuration write intent"); + expect(state.deps.applySearch).not.toHaveBeenCalled(); + }, + ); + it.each(["gateway", "hooks", "exec"] as const)( "rejects a search update that also changes %s", async (section) => { diff --git a/desktop/src/config-write-service.ts b/desktop/src/config-write-service.ts index 3794c4c..7b2e91d 100644 --- a/desktop/src/config-write-service.ts +++ b/desktop/src/config-write-service.ts @@ -11,6 +11,7 @@ import { validateWindowsNodeMxcGatewayPolicy, } from "./windows-node-mxc"; import { assertWindowsNodeMxcModelOrPluginChange } from "./windows-node-mxc-model-config"; +import type { SearchSettingsWriteIntent } from "./search-setup-progress"; interface ConfigWriteDependencies { readConfig(): unknown; @@ -26,7 +27,12 @@ interface ConfigWriteDependencies { persist(config: Record): void; applyModel(params: ModelConfigUpdate): Promise; applyPlugins(config: unknown, expectedConfig: unknown): Promise; - applySearch(config: unknown, expectedConfig: unknown, assertCurrent: () => void): Promise; + applySearch( + config: unknown, + expectedConfig: unknown, + assertCurrent: () => void, + requestId?: string, + ): Promise; startServices(): Promise; } @@ -40,17 +46,22 @@ function readCurrent(deps: ConfigWriteDependencies): unknown { function writeIntent( value: unknown, -): { kind: "initial-setup"; providerKey: string } | { kind: "search-settings" } | null { +): { kind: "initial-setup"; providerKey: string } | SearchSettingsWriteIntent | null { if (value === undefined) return null; if ( value && typeof value === "object" && !Array.isArray(value) && - Object.keys(value).length === 1 && + Object.keys(value).every((key) => key === "kind" || key === "requestId") && "kind" in value && - value.kind === "search-settings" + value.kind === "search-settings" && + (!("requestId" in value) || + (typeof value.requestId === "string" && /^[\w-]{1,128}$/.test(value.requestId))) ) - return { kind: "search-settings" }; + return { + kind: "search-settings", + ...("requestId" in value ? { requestId: value.requestId as string } : {}), + }; if ( !value || typeof value !== "object" || @@ -159,7 +170,12 @@ export async function writeGuardedConfig( if (!policy.ready) { throw new Error(`Gateway command routing is not ready: ${policy.blockers.join("; ")}`); } - await deps.applySearch(config, expectedConfig, assertLifecycle); + await deps.applySearch( + config, + expectedConfig, + assertLifecycle, + parsedIntent?.kind === "search-settings" ? parsedIntent.requestId : undefined, + ); return; } diff --git a/desktop/src/gateway-client.test.ts b/desktop/src/gateway-client.test.ts index dc6c597..5a8328c 100644 --- a/desktop/src/gateway-client.test.ts +++ b/desktop/src/gateway-client.test.ts @@ -21,6 +21,62 @@ import { } from "./constants"; import { GatewaySessionObserver } from "./gateway-session-observer"; +describe("GatewayClient plugin install progress", () => { + it.each(["response", "timeout", "disconnect"])( + "correlates progress to its request and ignores it after %s", + async (settlement) => { + vi.useFakeTimers(); + try { + const client = Object.create(GatewayClient.prototype) as GatewayClient; + const send = vi.fn(); + const progress = vi.fn(); + Object.assign(client, { pending: new Map(), ws: { readyState: 1, send } }); + const response = client.request("plugins.install", {}, 1000, progress); + const result = response.catch((error: Error) => error.message); + const { id } = JSON.parse(send.mock.calls[0][0]); + const emit = (requestId: string) => + client["handleMessage"]( + JSON.stringify({ + type: "event", + event: "plugins.install.progress", + payload: { requestId, stage: "dependencies", status: "started" }, + }), + ); + emit("another-request"); + expect(progress).not.toHaveBeenCalled(); + emit(id); + expect(progress).toHaveBeenCalledExactlyOnceWith({ + requestId: id, + stage: "dependencies", + status: "started", + }); + if (settlement === "response") { + // A broken progress observer cannot break the operation's eventual response. + progress.mockImplementationOnce(() => { + throw new Error("observer failed"); + }); + emit(id); + client["handleMessage"](JSON.stringify({ type: "res", id, ok: true, payload: "done" })); + await expect(result).resolves.toBe("done"); + } else if (settlement === "timeout") { + await vi.advanceTimersByTimeAsync(1000); + await expect(result).resolves.toContain("timed out"); + } else { + client["flushPending"]("disconnected"); + await expect(result).resolves.toBe("disconnected"); + } + progress.mockClear(); + emit(id); + expect(progress).not.toHaveBeenCalled(); + expect(client["pending"].size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } + }, + ); +}); + describe("GatewayClient agent roster", () => { it.each([undefined, 250])("forwards the roster RPC timeout budget %s", async (timeoutMs) => { const client = Object.create(GatewayClient.prototype) as GatewayClient; diff --git a/desktop/src/gateway-client.ts b/desktop/src/gateway-client.ts index 000c5b3..d0baeeb 100644 --- a/desktop/src/gateway-client.ts +++ b/desktop/src/gateway-client.ts @@ -219,6 +219,7 @@ export function normalizeGatewayChannelsStatus( type Pending = { resolve: (value: unknown) => void; reject: (err: Error) => void; + onProgress?: (payload: unknown) => void; }; export type GatewayClientOptions = { @@ -335,6 +336,7 @@ export class GatewayClient { method: string, params?: unknown, timeoutMs: number | null = WS_REQUEST_TIMEOUT_MS, + onProgress?: (payload: unknown) => void, ): Promise { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { throw new Error("gateway not connected"); @@ -352,6 +354,7 @@ export class GatewayClient { } }, timeoutMs); this.pending.set(id, { + onProgress: method === "plugins.install" ? onProgress : undefined, resolve: (v) => { clearTimeout(timer); resolve(v as T); @@ -922,6 +925,20 @@ export class GatewayClient { if (frame.type === "event") { const evt = parsed as GatewayEventFrame; + if (evt.event === "plugins.install.progress") { + const payload = evt.payload; + if (payload && typeof payload === "object" && "requestId" in payload) { + const requestId = payload.requestId; + if (typeof requestId === "string") { + try { + this.pending.get(requestId)?.onProgress?.(payload); + } catch { + // Presentation observers must not interrupt the request or transport. + } + } + } + return; + } // Handle connect.challenge — gateway may require a nonce handshake if (evt.event === "connect.challenge") { const payload = evt.payload as { nonce?: string } | undefined; diff --git a/desktop/src/main.ts b/desktop/src/main.ts index 3a9fc1e..4a5135d 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -7645,12 +7645,16 @@ function registerIpcHandlers(): void { () => undefined, "plugin", ), - applySearch: (next, expected, assertCurrent) => + applySearch: (next, expected, assertCurrent, requestId) => applySearchConfig( { gateway: () => gwClient, readConfig, assertCurrent, + onProgress: (stage) => { + if (requestId && !_event.sender.isDestroyed()) + _event.sender.send("config:search-progress", { requestId, stage }); + }, assertMxcReady: async () => { if (!isWindowsNodeMxcDesired()) return; const status = await getWindowsNodeMxcStatus(); diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts index 8defc3a..091026c 100644 --- a/desktop/src/preload.ts +++ b/desktop/src/preload.ts @@ -1,6 +1,7 @@ import { contextBridge, ipcRenderer } from "electron"; import type { GatewayRestartOptions } from "./gateway-restart-reason"; import type { ModelConfigUpdate } from "./model-config-application"; +import type { SearchSettingsWriteIntent, SearchSetupProgress } from "./search-setup-progress"; // Sandboxed preloads cannot require local modules; keep runtime IPC adapters self-contained. import type { ChatAttachment, @@ -61,8 +62,14 @@ contextBridge.exposeInMainWorld("openclaw", { write: ( config: unknown, expectedConfig?: unknown, - intent?: { kind: "initial-setup"; providerKey: string } | { kind: "search-settings" }, + intent?: { kind: "initial-setup"; providerKey: string } | SearchSettingsWriteIntent, ) => ipcRenderer.invoke("config:write", config, expectedConfig, intent), + onSearchProgress: (callback: (progress: SearchSetupProgress) => void) => { + const handler = (_event: Electron.IpcRendererEvent, progress: SearchSetupProgress) => + callback(progress); + ipcRenderer.on("config:search-progress", handler); + return () => ipcRenderer.removeListener("config:search-progress", handler); + }, }, // --- Settings --- diff --git a/desktop/src/search-config-application.test.ts b/desktop/src/search-config-application.test.ts index 1d56321..86d9a83 100644 --- a/desktop/src/search-config-application.test.ts +++ b/desktop/src/search-config-application.test.ts @@ -31,6 +31,7 @@ function fixture(provider = "brave") { invalidSnapshot: false, restartRequired: false, afterInstall: () => {}, + installProgress: [] as unknown[], }; const id = provider === "parallel-free" ? "parallel" : provider; const gateway = { @@ -46,74 +47,88 @@ function fixture(provider = "brave") { "plugins.setEnabled", "plugins.reload", ], - request: vi.fn(async (method: string, params: JsonObject): Promise => { - switch (method) { - case "config.get": - return { - valid: !state.invalidSnapshot, - hash, - config: structuredClone(config), - configRevisionHash: hash, - appliedConfigHash: hash, - }; - case "plugins.list": - return { - plugins: [ - { + request: vi.fn( + async ( + method: string, + params: JsonObject, + _timeoutMs?: number, + onProgress?: (payload: unknown) => void, + ): Promise => { + switch (method) { + case "config.get": + return { + valid: !state.invalidSnapshot, + hash, + config: structuredClone(config), + configRevisionHash: hash, + appliedConfigHash: hash, + }; + case "plugins.list": + return { + plugins: [ + { + id, + installed: state.pluginInstalled, + enabled: state.pluginEnabled, + version: "2026.10.5", + runtime: { + state: state.pluginRuntimeFailure + ? "service-failed" + : state.pluginActive + ? "active" + : "unloaded", + }, + }, + ], + mutationAllowed: true, + }; + case "plugins.install": + case "plugins.setEnabled": + case "plugins.reload": { + if (method === "plugins.install") + state.installProgress.forEach((event) => onProgress?.(event)); + state.pluginInstalled = true; + state.pluginEnabled = true; + if (method !== "plugins.reload" || !state.reloadStaysUnloaded) + state.pluginActive = true; + if (method !== "plugins.reload") { + const plugins = config.plugins as { allow: string[]; entries: JsonObject }; + if (!plugins.allow.includes(id)) plugins.allow.push(id); + plugins.entries[id] = { enabled: true }; + hash = "plugin"; + state.afterInstall(); + } + return { + ok: true, + restartRequired: false, + runtime: { generation: 1, pluginIds: [id] }, + }; + } + case "plugins.inspect": + return { + ok: true, + plugin: { id, installed: state.pluginInstalled, enabled: state.pluginEnabled, version: "2026.10.5", - runtime: { - state: state.pluginRuntimeFailure - ? "service-failed" - : state.pluginActive - ? "active" - : "unloaded", - }, }, - ], - mutationAllowed: true, - }; - case "plugins.install": - case "plugins.setEnabled": - case "plugins.reload": { - state.pluginInstalled = true; - state.pluginEnabled = true; - if (method !== "plugins.reload" || !state.reloadStaysUnloaded) state.pluginActive = true; - if (method !== "plugins.reload") { - const plugins = config.plugins as { allow: string[]; entries: JsonObject }; - if (!plugins.allow.includes(id)) plugins.allow.push(id); - plugins.entries[id] = { enabled: true }; - hash = "plugin"; - state.afterInstall(); - } - return { ok: true, restartRequired: false, runtime: { generation: 1, pluginIds: [id] } }; + }; + case "config.apply": + expect(params.baseHash).toBe(hash); + config = JSON.parse(String(params.raw)); + if (state.activateOnApply) state.pluginActive = true; + hash = "after"; + return { + ok: true, + hash, + sentinel: { payload: { stats: { requiresRestart: state.restartRequired } } }, + }; + default: + throw new Error(`Unexpected request: ${method}`); } - case "plugins.inspect": - return { - ok: true, - plugin: { - id, - installed: state.pluginInstalled, - enabled: state.pluginEnabled, - version: "2026.10.5", - }, - }; - case "config.apply": - expect(params.baseHash).toBe(hash); - config = JSON.parse(String(params.raw)); - if (state.activateOnApply) state.pluginActive = true; - hash = "after"; - return { - ok: true, - hash, - sentinel: { payload: { stats: { requiresRestart: state.restartRequired } } }, - }; - default: - throw new Error(`Unexpected request: ${method}`); - } - }), + }, + ), }; const deps = { gateway: () => gateway, @@ -135,6 +150,44 @@ function fixture(provider = "brave") { } describe("applying web search settings", () => { + it("reports observed install stages and verifies readiness after applying configuration", async () => { + const test = fixture(); + const stages: string[] = []; + test.state.installProgress = [ + { stage: "resolve", status: "started" }, + { stage: "dependencies", status: "completed" }, + { stage: "unknown", status: "started" }, + null, + { stage: "dependencies", status: "started" }, + { stage: "runtime", status: "started" }, + ]; + await applySearchConfig( + { ...test.deps, onProgress: (stage) => stages.push(stage) }, + test.target, + test.original, + ); + expect(stages).toEqual([ + "preparing", + "fetching", + "installing", + "activating", + "verifying", + "activating", + "verifying", + ]); + expect(test.deps.assertMxcReady).toHaveBeenCalledOnce(); + }); + + it("does not report fetching or installation when the component is already present", async () => { + const test = fixture(); + test.state.pluginInstalled = true; + const onProgress = vi.fn(); + await applySearchConfig({ ...test.deps, onProgress }, test.target, test.original); + expect(onProgress).not.toHaveBeenCalledWith("fetching"); + expect(onProgress).not.toHaveBeenCalledWith("installing"); + expect(onProgress).toHaveBeenLastCalledWith("verifying"); + }); + it.each([ ["brave", "brave"], ["tavily", "tavily"], diff --git a/desktop/src/search-config-application.ts b/desktop/src/search-config-application.ts index 3b46826..4755fa7 100644 --- a/desktop/src/search-config-application.ts +++ b/desktop/src/search-config-application.ts @@ -9,6 +9,7 @@ import { type SearchProviderGateway, } from "./search-provider-plugin"; import { validateWindowsNodeMxcGatewayPolicy } from "./windows-node-mxc"; +import type { SearchSetupStage } from "./search-setup-progress"; type JsonObject = Record; @@ -19,6 +20,7 @@ interface Dependencies { assertMxcReady(): Promise; nodeId(): string; wait?(milliseconds: number): Promise; + onProgress?(stage: SearchSetupStage): void; } function object(value: unknown): JsonObject { @@ -132,6 +134,7 @@ export async function applySearchConfig( }; assertCurrent(); + deps.onProgress?.("preparing"); assertModelConfigUnchanged(expected, deps.readConfig()); const before = await snapshot(); assertModelConfigUnchanged(expected, deps.readConfig()); @@ -139,7 +142,13 @@ export async function applySearchConfig( if (reload === "off" || reload === "restart") throw new Error("Web search settings require configuration hot reload; no restart attempted"); - await ensureSearchProviderPlugin(gateway, search.provider, assertCurrent); + await ensureSearchProviderPlugin( + gateway, + search.provider, + assertCurrent, + undefined, + deps.onProgress, + ); const current = object(deps.readConfig()); if ( !isDeepStrictEqual( @@ -182,6 +191,7 @@ export async function applySearchConfig( } let result: JsonObject; try { + deps.onProgress?.("activating"); result = object( await gateway.request( "config.apply", @@ -217,6 +227,7 @@ export async function applySearchConfig( await (deps.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(500); assertCurrent(); } + deps.onProgress?.("verifying"); if (search.enabled !== false) await assertSearchProviderPluginActive(gateway, search.provider, assertCurrent); await deps.assertMxcReady(); diff --git a/desktop/src/search-provider-plugin.ts b/desktop/src/search-provider-plugin.ts index 6e6b9fa..8316c4d 100644 --- a/desktop/src/search-provider-plugin.ts +++ b/desktop/src/search-provider-plugin.ts @@ -1,3 +1,5 @@ +import { searchInstallStage, type SearchSetupStage } from "./search-setup-progress"; + type JsonObject = Record; export interface SearchProviderGateway { @@ -5,7 +7,12 @@ export interface SearchProviderGateway { serverVersion: string | null; connectionGeneration: number; methods: readonly string[]; - request(method: string, params: JsonObject, timeoutMs?: number): Promise; + request( + method: string, + params: JsonObject, + timeoutMs?: number, + onProgress?: (payload: unknown) => void, + ): Promise; } const providers = { @@ -96,6 +103,7 @@ export async function ensureSearchProviderPlugin( provider: unknown, assertCurrent: () => void, onInstall?: () => void, + onProgress?: (stage: SearchSetupStage) => void, ): Promise { const plugin = searchProviderPlugin(provider); if ( @@ -117,14 +125,24 @@ export async function ensureSearchProviderPlugin( let application: JsonObject | undefined; if (current.installed !== true || current.version !== version || current.state === "error") { onInstall?.(); + const observers: [(payload: unknown) => void] | [] = onProgress + ? [ + (payload) => { + const stage = searchInstallStage(payload); + if (stage) onProgress(stage); + }, + ] + : []; application = object( await gateway.request( "plugins.install", { source: "npm", spec: `${plugin.package}@${version}`, expectedPluginId: plugin.id }, 300_000, + ...observers, ), ); } else if (current.enabled !== true) { + onProgress?.("activating"); application = object( await gateway.request("plugins.setEnabled", { pluginId: plugin.id, enabled: true }, 300_000), ); @@ -132,6 +150,7 @@ export async function ensureSearchProviderPlugin( !["active", "unloaded"].includes(String(object(current.runtime).state)) || object(current.runtime).error ) { + onProgress?.("activating"); application = object( await gateway.request( "plugins.reload", @@ -142,6 +161,7 @@ export async function ensureSearchProviderPlugin( } assertCurrent(); if (application) assertLifecycleApplication(application, plugin.id); + onProgress?.("verifying"); await verifiedRuntimeState(gateway, plugin.id, version, assertCurrent); return plugin.id; } diff --git a/desktop/src/search-setup-progress.ts b/desktop/src/search-setup-progress.ts new file mode 100644 index 0000000..483037f --- /dev/null +++ b/desktop/src/search-setup-progress.ts @@ -0,0 +1,28 @@ +export type SearchSetupStage = "preparing" | "fetching" | "installing" | "activating" | "verifying"; + +export interface SearchSetupProgress { + requestId: string; + stage: SearchSetupStage; +} + +export interface SearchSettingsWriteIntent { + kind: "search-settings"; + requestId?: string; +} + +// Only report observed activities; completion of one activity does not start the next. +export function searchInstallStage(payload: unknown): SearchSetupStage | undefined { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return; + const event = payload as Record; + if (event.status !== "started") return; + switch (event.stage) { + case "resolve": + return "fetching"; + case "files": + case "dependencies": + case "scan": + return "installing"; + case "runtime": + return "activating"; + } +}