Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion desktop/renderer/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
onSearchProgress(
callback: (progress: import("../src/search-setup-progress").SearchSetupProgress) => void,
): () => void;
};
settings: {
get(): Promise<AppSettings>;
Expand Down
1 change: 1 addition & 0 deletions desktop/renderer/src/browser-openclaw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions desktop/renderer/src/i18n/en-US.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
6 changes: 6 additions & 0 deletions desktop/renderer/src/i18n/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": "确定要清除所有聊天记录吗?此操作不可撤销。",
Expand Down
79 changes: 77 additions & 2 deletions desktop/renderer/src/views/SettingsView.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2524,6 +2524,9 @@ describe("SettingsView", () => {
});

describe("SettingsView search autosave events", () => {
type ProgressListener = Parameters<OpenClawAPI["config"]["onSearchProgress"]>[0];
let emitSearchProgress: ProgressListener;
let unsubscribeProgress: ReturnType<typeof vi.fn>;
function control(tag: "select" | "option" | "input") {
return defineComponent({
name: `Search${tag}Control`,
Expand Down Expand Up @@ -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([]),
Expand All @@ -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<void>();
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<void>();
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 () => {
Expand All @@ -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: {
Expand Down
67 changes: 62 additions & 5 deletions desktop/renderer/src/views/SettingsView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,10 @@
<div class="sub-label-row">
<h3 class="sub-label">{{ t("settings.webSearch") }}</h3>
<div class="sub-label-actions">
<span v-if="!searchConfigured" class="search-configuration-state">
<span
v-if="!searchConfigured && searchSaveStatus !== 'saving'"
class="search-configuration-state"
>
{{ t("settings.searchNotConfigured") }}
</span>
<span
Expand Down Expand Up @@ -1023,6 +1026,7 @@ import {
type ConfiguredModel,
} from "@/utils/configured-models";
import type { LocalModelFileStatus } from "../../../src/local-model-types";
import type { SearchSetupStage } from "../../../src/search-setup-progress";
import {
createSearchAutosave,
patchSearchConfig,
Expand Down Expand Up @@ -1811,13 +1815,44 @@ const searchConfigured = ref(false);
type SearchSaveStatus = "idle" | "saving" | "saved" | "error" | "invalid";
const searchSaveStatus = ref<SearchSaveStatus>("idle");
const searchSaveError = ref("");
const searchStage = ref<SearchSetupStage>("preparing");
const searchElapsedSeconds = ref(0);
const searchStageLabels: Record<SearchSetupStage, string> = {
preparing: "settings.searchPreparing",
fetching: "settings.searchFetching",
installing: "settings.searchInstalling",
activating: "settings.searchActivating",
verifying: "settings.searchVerifying",
};
let searchFormGeneration = 0;
let searchProgressTimer: ReturnType<typeof setInterval> | 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");
Expand Down Expand Up @@ -1846,6 +1881,7 @@ const searchAutosave = createSearchAutosave({
watch(
[searchProvider, () => searchKeys[searchProvider.value]],
() => {
searchFormGeneration += 1;
searchAutosave.invalidate();
searchSaveError.value = "";
searchSaveStatus.value = "idle";
Expand Down Expand Up @@ -2166,6 +2202,8 @@ onMounted(async () => {

onUnmounted(() => {
searchAutosave.dispose();
clearInterval(searchProgressTimer);
unsubscribeSearchProgress?.();
unsubscribeMxcDisplay?.();
window.removeEventListener("focus", handleSettingsWindowFocus);
copilotModelsGeneration += 1;
Expand Down Expand Up @@ -2432,12 +2470,31 @@ async function persistSearchConfig(
request: SearchSaveRequest,
canWrite: () => boolean,
): Promise<boolean> {
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.
Expand Down
33 changes: 33 additions & 0 deletions desktop/src/config-write-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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) => {
Expand Down
28 changes: 22 additions & 6 deletions desktop/src/config-write-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -26,7 +27,12 @@ interface ConfigWriteDependencies {
persist(config: Record<string, unknown>): void;
applyModel(params: ModelConfigUpdate): Promise<void>;
applyPlugins(config: unknown, expectedConfig: unknown): Promise<void>;
applySearch(config: unknown, expectedConfig: unknown, assertCurrent: () => void): Promise<void>;
applySearch(
config: unknown,
expectedConfig: unknown,
assertCurrent: () => void,
requestId?: string,
): Promise<void>;
startServices(): Promise<void>;
}

Expand All @@ -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" ||
Expand Down Expand Up @@ -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;
}

Expand Down
Loading
Loading