Python
Settings: Customization tab with the Web search section
Rohit C Prasadd1d9b12227de
diff --git a/surfaces/gui/e2e/customization.spec.ts b/surfaces/gui/e2e/customization.spec.tsnew file mode 100644index 00000000..a584930a--- /dev/null+++ b/surfaces/gui/e2e/customization.spec.ts@@ -0,0 +1,71 @@+// Settings ▸ Customization (UX-058): the Web search providers as radio rows with a key per+// service, and the "Fetch pages through the search service" switch. The fixture answers+// GET/POST /v1/web-search, PUT/DELETE /v1/web-search/keys/{name} and+// POST /v1/web-search/fetch-via-provider from per-test state.+import { expect } from "@playwright/test";+import { test } from "./fixtures";++test("customization: open the tab, add a key, pick the provider, flip the fetch switch", async ({ page }) => {+ await page.goto("/#/settings/customization");+ const tab = page.getByTestId("customization-tab");+ await expect(tab).toBeVisible();+ await expect(tab.getByRole("heading", { name: "Customization" })).toBeVisible();+ await expect(tab.getByText("Web search", { exact: true })).toBeVisible();++ // DuckDuckGo is in use; the keyless rows explain themselves; keyed rows say where the key is.+ await expect(page.getByTestId("websearch-in-use-duckduckgo")).toHaveText("In use");+ await expect(page.getByTestId("websearch-status-duckduckgo")).toHaveText("No key. Rate-limited, fine for occasional searches.");+ await expect(page.getByTestId("websearch-status-tavily")).toHaveText("Key saved");+ await expect(page.getByTestId("websearch-status-brave")).toHaveText("Key from environment BRAVE_API_KEY");+ await expect(page.getByTestId("websearch-key-button-tavily")).toHaveText("Update key");+ await expect(page.getByTestId("websearch-key-button-exa")).toHaveText("Add key");+ // Exa has no key, so it cannot be chosen yet.+ await expect(page.getByTestId("websearch-radio-exa")).toBeDisabled();+ await expect(page.getByTestId("websearch-radio-you")).toBeEnabled();++ // Add a key: a wrong one is refused with the server's message, a good one is stored.+ await page.getByTestId("websearch-key-button-exa").click();+ const input = page.getByTestId("websearch-key-input");+ await expect(input).toHaveAttribute("type", "password");+ await expect(page.getByText("Checked with one search.")).toBeVisible();+ await input.fill("bad-exa-key");+ await page.getByTestId("websearch-key-save").click();+ await expect(page.getByTestId("websearch-error")).toContainText("401 Unauthorized");+ await expect(page.getByTestId("websearch-radio-exa")).toBeDisabled();+ await input.fill("exa-good-key");+ await page.getByTestId("websearch-key-save").click();+ await expect(page.getByTestId("websearch-key-input")).toHaveCount(0);+ await expect(page.getByTestId("websearch-status-exa")).toHaveText("Key saved");+ await expect(page.getByTestId("websearch-key-button-exa")).toHaveText("Update key");++ // Now it can be picked; the pill moves and the fetch switch comes alive (Exa offers it).+ const fetchSwitch = page.getByTestId("websearch-fetch-toggle").getByRole("switch");+ await expect(fetchSwitch).toBeDisabled();+ await expect(page.getByTestId("websearch-fetch-note")).toContainText("DuckDuckGo doesn't offer this.");+ await page.getByTestId("websearch-radio-exa").click();+ await expect(page.getByTestId("websearch-in-use-exa")).toHaveText("In use");+ await expect(page.getByTestId("websearch-in-use-duckduckgo")).toHaveCount(0);+ await expect(fetchSwitch).toBeEnabled();+ await expect(page.getByTestId("websearch-fetch-note")).toHaveCount(0);+ await expect(page.getByText(/On: Exa fetches them, and sees each page address\./)).toBeVisible();++ await expect(fetchSwitch).toHaveAttribute("aria-checked", "false");+ await fetchSwitch.click();+ await expect(fetchSwitch).toHaveAttribute("aria-checked", "true");++ // The choice survives a reload: the fixture holds it like the server would.+ await page.reload();+ await expect(page.getByTestId("websearch-in-use-exa")).toBeVisible();+ await expect(page.getByTestId("websearch-fetch-toggle").getByRole("switch")).toHaveAttribute("aria-checked", "true");+});++test("customization: removing the active provider's only key falls back to DuckDuckGo", async ({ page }) => {+ await page.goto("/#/settings/customization");+ await page.getByTestId("websearch-radio-tavily").click();+ await expect(page.getByTestId("websearch-in-use-tavily")).toBeVisible();+ await page.getByTestId("websearch-key-button-tavily").click();+ await page.getByTestId("websearch-key-remove").click();+ await expect(page.getByTestId("websearch-in-use-duckduckgo")).toBeVisible();+ await expect(page.getByTestId("websearch-key-button-tavily")).toHaveText("Add key");+ await expect(page.getByTestId("websearch-radio-tavily")).toBeDisabled();+});diff --git a/surfaces/gui/e2e/fixtures.ts b/surfaces/gui/e2e/fixtures.tsindex 75218c97..434f1a08 100644--- a/surfaces/gui/e2e/fixtures.ts+++ b/surfaces/gui/e2e/fixtures.ts@@ -1102,6 +1102,21 @@ export async function mockApi(page: import("@playwright/test").Page) {});});+ // UX-058: the Web search section's per-test state (mirrors GET /v1/web-search).+ const webSearch = {+ provider: "duckduckgo",+ fetch_via_provider: false,+ providers: [+ { name: "duckduckgo", display_name: "DuckDuckGo", key_mode: "none", key_url: "", key_source: null as "store" | "env" | null, key_env: "", supports_fetch: false },+ { name: "you", display_name: "You.com", key_mode: "optional", key_url: "https://you.com/platform", key_source: null as "store" | "env" | null, key_env: "", supports_fetch: false },+ { name: "tavily", display_name: "Tavily", key_mode: "required", key_url: "https://tavily.com", key_source: "store" as "store" | "env" | null, key_env: "", supports_fetch: true },+ { name: "brave", display_name: "Brave Search", key_mode: "required", key_url: "https://brave.com/search/api", key_source: "env" as "store" | "env" | null, key_env: "BRAVE_API_KEY", supports_fetch: false },+ { name: "serper", display_name: "Serper", key_mode: "required", key_url: "https://serper.dev", key_source: null as "store" | "env" | null, key_env: "", supports_fetch: false },+ { name: "exa", display_name: "Exa", key_mode: "required", key_url: "https://exa.ai", key_source: null as "store" | "env" | null, key_env: "", supports_fetch: true },+ { name: "firecrawl", display_name: "Firecrawl", key_mode: "required", key_url: "https://firecrawl.dev", key_source: null as "store" | "env" | null, key_env: "", supports_fetch: true },+ ],+ };+await page.route("**/v1/capabilities", (route) =>route.fulfill({status: 200,@@ -1462,6 +1477,47 @@ export async function mockApi(page: import("@playwright/test").Page) {if (p.endsWith("/v1/health")) return json(HEALTH);if (p.endsWith("/v1/settings")) return json(SETTINGS);++ // Settings ▸ Customization ▸ Web search (UX-058). Keys live per provider; "Test and+ // save" fails for a key spelled "bad-*", the way the real server relays a 401.+ const webSearchSnapshot = () => ({+ provider: webSearch.provider,+ fetch_via_provider: webSearch.fetch_via_provider,+ providers: webSearch.providers.map((row) => ({ ...row, has_key: row.key_source !== null })),+ });+ const webSearchReply = (ok: boolean, error = "") =>+ ok ? json({ ok: true, ...webSearchSnapshot() }) : json({ ok: false, error }, 400);+ if (p.endsWith("/v1/web-search") && m === "GET") return json(webSearchSnapshot());+ if (p.endsWith("/v1/web-search") && m === "POST") {+ const name = String(req.postDataJSON()?.provider || "");+ const row = webSearch.providers.find((r) => r.name === name);+ if (!row) return webSearchReply(false, `unknown provider: ${name}`);+ if (row.key_mode === "required" && row.key_source === null)+ return webSearchReply(false, `${row.display_name} needs an API key before it can be chosen. Add one first.`);+ webSearch.provider = name;+ return webSearchReply(true);+ }+ const keyMatch = p.match(/\/v1\/web-search\/keys\/([\w-]+)$/);+ if (keyMatch && (m === "PUT" || m === "DELETE")) {+ const row = webSearch.providers.find((r) => r.name === keyMatch[1]);+ if (!row) return webSearchReply(false, `unknown provider: ${keyMatch[1]}`);+ if (m === "DELETE") {+ row.key_source = null;+ row.key_env = "";+ if (webSearch.provider === row.name && row.key_mode === "required") webSearch.provider = "duckduckgo";+ return webSearchReply(true);+ }+ const key = String(req.postDataJSON()?.api_key || "").trim();+ if (!key) return webSearchReply(false, "api_key required");+ if (key.startsWith("bad-")) return webSearchReply(false, "Client error '401 Unauthorized' for url 'https://api.example/search'");+ row.key_source = "store";+ row.key_env = "";+ return webSearchReply(true);+ }+ if (p.endsWith("/v1/web-search/fetch-via-provider") && m === "POST") {+ webSearch.fetch_via_provider = !!req.postDataJSON()?.enabled;+ return webSearchReply(true);+ }if (p.endsWith("/v1/settings/context-bar") && m === "POST") {Object.assign(SETTINGS, req.postDataJSON());return json({ ok: true, context_bar: SETTINGS.context_bar });diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex cf2462b1..6b343639 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -1271,6 +1271,72 @@ export async function inspectPdf(return res.json();}+// -- Settings ▸ Customization ▸ Web search (UX-058) --------------------------------+// One provider is active; every provider keeps its own key in the machine's secret store+// (never returned here — only whether one exists and where it came from).+export type WebSearchProviderInfo = {+ name: string;+ display_name: string;+ key_mode: "none" | "optional" | "required";+ key_url: string;+ has_key: boolean;+ key_source: "store" | "env" | null;+ // The environment variable the key comes from, when key_source is "env".+ key_env: string;+ // Whether `web_fetch` can read pages through this provider (Exa, Firecrawl, Tavily).+ supports_fetch: boolean;+};+export type WebSearchInfo = {+ provider: string;+ fetch_via_provider: boolean;+ providers: WebSearchProviderInfo[];+};+type WebSearchResult = { ok: boolean; error?: string } & Partial<WebSearchInfo>;++export async function getWebSearch(machineId?: string | null): Promise<WebSearchInfo> {+ const res = await fetch(`${engineBase(machineId)}/v1/web-search`);+ if (!res.ok) throw new Error(`web-search: ${res.status}`);+ return res.json();+}++/** Make `name` the active search service. A 400 (a keyed service with no key) comes back+ * as `{ok: false, error}` with the server's plain message. */+export async function setWebSearchProvider(name: string, machineId?: string | null): Promise<WebSearchResult> {+ const res = await fetch(`${engineBase(machineId)}/v1/web-search`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ provider: name }),+ });+ return res.json();+}++/** "Test and save": the server runs one search with the key before storing it. */+export async function setWebSearchKey(name: string, apiKey: string, machineId?: string | null): Promise<WebSearchResult> {+ const res = await fetch(`${engineBase(machineId)}/v1/web-search/keys/${encodeURIComponent(name)}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ api_key: apiKey }),+ });+ return res.json();+}++export async function clearWebSearchKey(name: string, machineId?: string | null): Promise<WebSearchResult> {+ const res = await fetch(`${engineBase(machineId)}/v1/web-search/keys/${encodeURIComponent(name)}`, {+ method: "DELETE",+ });+ return res.json();+}++/** "Fetch pages through the search service" — honoured while the active provider offers it. */+export async function setFetchViaProvider(enabled: boolean, machineId?: string | null): Promise<WebSearchResult> {+ const res = await fetch(`${engineBase(machineId)}/v1/web-search/fetch-via-provider`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled }),+ });+ return res.json();+}+/** Persist whether the composer shows the context-window fill bar. */export async function setContextBar(shown: boolean,diff --git a/surfaces/gui/src/components/CustomizationTab.test.tsx b/surfaces/gui/src/components/CustomizationTab.test.tsxnew file mode 100644index 00000000..54d2307b--- /dev/null+++ b/surfaces/gui/src/components/CustomizationTab.test.tsx@@ -0,0 +1,217 @@+// Settings ▸ Customization (UX-058): the Web search card lists the providers as radio rows+// from GET /v1/web-search; a keyed provider without a key cannot be chosen; the right-hand+// control reads Add key / Update key / In use; "Test and save" sends the key; the fetch+// switch is live only while the active provider offers it.+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";++const row = (name: string, display: string, key_mode: string, extra: Record<string, unknown> = {}) => ({+ name,+ display_name: display,+ key_mode,+ key_url: key_mode === "none" ? "" : `https://${name}.example`,+ has_key: false,+ key_source: null,+ key_env: "",+ supports_fetch: ["exa", "firecrawl", "tavily"].includes(name),+ ...extra,+});++const base = {+ provider: "duckduckgo",+ fetch_via_provider: false,+ providers: [+ row("duckduckgo", "DuckDuckGo", "none"),+ row("you", "You.com", "optional"),+ row("tavily", "Tavily", "required", { has_key: true, key_source: "store" }),+ row("brave", "Brave Search", "required", { has_key: true, key_source: "env", key_env: "BRAVE_API_KEY" }),+ row("serper", "Serper", "required"),+ row("exa", "Exa", "required"),+ row("firecrawl", "Firecrawl", "required"),+ ],+};+let snapshot: any = structuredClone(base);++const reply = (patch: any = {}) => ({ ok: true, ...snapshot, ...patch });+const getWebSearch = vi.fn(async () => snapshot);+const setWebSearchProvider = vi.fn(async (name: string) => {+ snapshot = { ...snapshot, provider: name };+ return reply();+});+const setWebSearchKey = vi.fn(async (name: string, key: string) => {+ if (key.startsWith("bad")) return { ok: false, error: "Client error '401 Unauthorized'" };+ snapshot = {+ ...snapshot,+ providers: snapshot.providers.map((p: any) => (p.name === name ? { ...p, has_key: true, key_source: "store", key_env: "" } : p)),+ };+ return reply();+});+const clearWebSearchKey = vi.fn(async (name: string) => {+ snapshot = {+ ...snapshot,+ provider: snapshot.provider === name ? "duckduckgo" : snapshot.provider,+ providers: snapshot.providers.map((p: any) => (p.name === name ? { ...p, has_key: false, key_source: null } : p)),+ };+ return reply();+});+const setFetchViaProvider = vi.fn(async (enabled: boolean) => {+ snapshot = { ...snapshot, fetch_via_provider: enabled };+ return reply();+});+const openExternal = vi.fn();++vi.mock("../api", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../api")>();+ return {+ ...actual,+ getWebSearch: () => getWebSearch(),+ setWebSearchProvider: (name: string) => setWebSearchProvider(name),+ setWebSearchKey: (name: string, key: string) => setWebSearchKey(name, key),+ clearWebSearchKey: (name: string) => clearWebSearchKey(name),+ setFetchViaProvider: (enabled: boolean) => setFetchViaProvider(enabled),+ };+});+vi.mock("../tauri", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../tauri")>();+ return { ...actual, openExternal: (url: string) => openExternal(url) };+});++import { CustomizationTab } from "./CustomizationTab";++const radio = (name: string) => screen.getByTestId(`websearch-radio-${name}`) as HTMLInputElement;+const fetchSwitch = () => within(screen.getByTestId("websearch-fetch-toggle")).getByRole("switch");++describe("Settings ▸ Customization ▸ Web search", () => {+ beforeEach(() => {+ snapshot = structuredClone(base);+ for (const fn of [getWebSearch, setWebSearchProvider, setWebSearchKey, clearWebSearchKey, setFetchViaProvider, openExternal]) fn.mockClear();+ });+ afterEach(cleanup);++ it("lists the providers in server order with their status lines and controls", async () => {+ render(<CustomizationTab />);+ await screen.findByTestId("websearch-providers");+ expect(screen.getByText("Customization")).toBeTruthy();+ expect(screen.getByText("Pick the services OpenWorker uses behind its tools. Each choice applies to new sessions on this machine.")).toBeTruthy();+ const names = within(screen.getByTestId("websearch-providers")).getAllByRole("radio").map((r) => r.getAttribute("data-testid"));+ expect(names).toEqual(base.providers.map((p) => `websearch-radio-${p.name}`));++ // Status lines only where they say something.+ expect(screen.getByTestId("websearch-status-duckduckgo").textContent).toBe("No key. Rate-limited, fine for occasional searches.");+ expect(screen.getByTestId("websearch-status-you").textContent).toBe("Works without a key, with a daily limit. A key lifts it.");+ expect(screen.getByTestId("websearch-status-tavily").textContent).toBe("Key saved");+ expect(screen.getByTestId("websearch-status-brave").textContent).toBe("Key from environment BRAVE_API_KEY");+ expect(screen.queryByTestId("websearch-status-exa")).toBeNull();++ // The active row wears the pill and, being keyless, no key button.+ expect(screen.getByTestId("websearch-in-use-duckduckgo").textContent).toBe("In use");+ expect(screen.queryByTestId("websearch-key-button-duckduckgo")).toBeNull();+ // Add key without a key, Update key with one (stored or from the environment).+ expect(screen.getByTestId("websearch-key-button-exa").textContent).toBe("Add key");+ expect(screen.getByTestId("websearch-key-button-you").textContent).toBe("Add key");+ expect(screen.getByTestId("websearch-key-button-tavily").textContent).toBe("Update key");+ expect(screen.getByTestId("websearch-key-button-brave").textContent).toBe("Update key");+ expect(screen.getByText("A service with no key can't be chosen until one is added. The agent's approval card names the service in use.")).toBeTruthy();+ });++ it("a keyed provider without a key cannot be chosen; keyless and keyed-with-key can", async () => {+ render(<CustomizationTab />);+ await screen.findByTestId("websearch-providers");+ expect(radio("exa").disabled).toBe(true);+ expect(radio("serper").disabled).toBe(true);+ expect(radio("you").disabled).toBe(false);+ expect(radio("tavily").disabled).toBe(false);+ expect(radio("brave").disabled).toBe(false);+ expect(radio("duckduckgo").checked).toBe(true);++ fireEvent.click(radio("tavily"));+ await waitFor(() => expect(setWebSearchProvider).toHaveBeenCalledWith("tavily"));+ await waitFor(() => expect(radio("tavily").checked).toBe(true));+ expect(screen.getByTestId("websearch-in-use-tavily")).toBeTruthy();+ expect(screen.queryByTestId("websearch-in-use-duckduckgo")).toBeNull();+ // The active keyed provider still offers Update key next to the pill.+ expect(screen.getByTestId("websearch-key-button-tavily").textContent).toBe("Update key");+ });++ it("Add key opens the inline row; Test and save stores the key and the row reads Update key", async () => {+ render(<CustomizationTab />);+ await screen.findByTestId("websearch-providers");+ expect(screen.queryByTestId("websearch-key-input")).toBeNull();+ fireEvent.click(screen.getByTestId("websearch-key-button-exa"));+ const input = screen.getByTestId("websearch-key-input") as HTMLInputElement;+ expect(input.type).toBe("password");+ expect(input.placeholder).toBe("Exa API key");+ expect(screen.getByText("Checked with one search.")).toBeTruthy();+ expect(screen.queryByTestId("websearch-key-remove")).toBeNull(); // nothing stored yet+ const save = screen.getByTestId("websearch-key-save") as HTMLButtonElement;+ expect(save.textContent).toBe("Test and save");+ expect(save.disabled).toBe(true); // nothing typed++ fireEvent.click(screen.getByTestId("websearch-key-url-exa"));+ expect(openExternal).toHaveBeenCalledWith("https://exa.example");++ fireEvent.change(input, { target: { value: "exa-123" } });+ fireEvent.click(save);+ await waitFor(() => expect(setWebSearchKey).toHaveBeenCalledWith("exa", "exa-123"));+ await waitFor(() => expect(screen.queryByTestId("websearch-key-input")).toBeNull());+ expect(screen.getByTestId("websearch-key-button-exa").textContent).toBe("Update key");+ expect(screen.getByTestId("websearch-status-exa").textContent).toBe("Key saved");+ expect(radio("exa").disabled).toBe(false);+ });++ it("a failed check shows the server's message and keeps the row open", async () => {+ render(<CustomizationTab />);+ await screen.findByTestId("websearch-providers");+ fireEvent.click(screen.getByTestId("websearch-key-button-serper"));+ fireEvent.change(screen.getByTestId("websearch-key-input"), { target: { value: "bad-key" } });+ fireEvent.click(screen.getByTestId("websearch-key-save"));+ await screen.findByTestId("websearch-error");+ expect(screen.getByTestId("websearch-error").textContent).toBe("Client error '401 Unauthorized'");+ expect(screen.getByTestId("websearch-key-input")).toBeTruthy();+ expect(screen.getByTestId("websearch-key-cancel").textContent).toBe("Cancel");+ expect(radio("serper").disabled).toBe(true);+ fireEvent.click(screen.getByTestId("websearch-key-cancel"));+ expect(screen.queryByTestId("websearch-key-input")).toBeNull();+ });++ it("Remove key is offered for a stored key and forgets it", async () => {+ render(<CustomizationTab />);+ await screen.findByTestId("websearch-providers");+ fireEvent.click(screen.getByTestId("websearch-key-button-tavily"));+ fireEvent.click(screen.getByTestId("websearch-key-remove"));+ await waitFor(() => expect(clearWebSearchKey).toHaveBeenCalledWith("tavily"));+ await waitFor(() => expect(screen.getByTestId("websearch-key-button-tavily").textContent).toBe("Add key"));+ expect(screen.queryByTestId("websearch-status-tavily")).toBeNull();+ expect(radio("tavily").disabled).toBe(true);+ // An environment key is not removable from here.+ fireEvent.click(screen.getByTestId("websearch-key-button-brave"));+ expect(screen.queryByTestId("websearch-key-remove")).toBeNull();+ });++ it("the fetch switch is disabled with a note until the active provider offers it", async () => {+ render(<CustomizationTab />);+ await screen.findByTestId("websearch-fetch-card");+ expect(screen.getByText("Fetch pages through the search service")).toBeTruthy();+ expect(screen.getByText("Off: pages are fetched from this machine. On: the search service fetches them, and sees each page address. Offered by Exa, Firecrawl and Tavily.")).toBeTruthy();+ expect(screen.getByTestId("websearch-fetch-note").textContent).toBe("DuckDuckGo doesn't offer this. Choose Exa, Firecrawl or Tavily to turn it on.");+ expect((fetchSwitch() as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(fetchSwitch());+ expect(setFetchViaProvider).not.toHaveBeenCalled();++ fireEvent.click(radio("tavily"));+ await waitFor(() => expect((fetchSwitch() as HTMLButtonElement).disabled).toBe(false));+ expect(screen.queryByTestId("websearch-fetch-note")).toBeNull();+ expect(screen.getByText(/On: Tavily fetches them/)).toBeTruthy();+ expect(fetchSwitch().getAttribute("aria-checked")).toBe("false");+ fireEvent.click(fetchSwitch());+ await waitFor(() => expect(setFetchViaProvider).toHaveBeenCalledWith(true));+ await waitFor(() => expect(fetchSwitch().getAttribute("aria-checked")).toBe("true"));+ });++ it("an unreachable server shows one line instead of an empty page", async () => {+ getWebSearch.mockRejectedValueOnce(new Error("down"));+ render(<CustomizationTab />);+ await screen.findByTestId("websearch-load-error");+ expect(screen.getByTestId("websearch-load-error").textContent).toBe("Couldn't load the web search settings.");+ });+});diff --git a/surfaces/gui/src/components/CustomizationTab.tsx b/surfaces/gui/src/components/CustomizationTab.tsxnew file mode 100644index 00000000..07e10a14--- /dev/null+++ b/surfaces/gui/src/components/CustomizationTab.tsx@@ -0,0 +1,303 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ clearWebSearchKey,+ getWebSearch,+ setFetchViaProvider,+ setWebSearchKey,+ setWebSearchProvider,+ type Machine,+ type WebSearchInfo,+ type WebSearchProviderInfo,+} from "../api";+import { openExternal } from "../tauri";+import { PanelHead } from "./IntegrationsView";+import { Toggle } from "./Toggle";++// Settings ▸ Customization (UX-058): the services OpenWorker uses behind its tools. Today+// one section, Web search — the provider behind `web_search` as radio rows with a key per+// service (kept in the machine's secret store; "Test and save" runs one search first) — and+// the "Fetch pages through the search service" switch for `web_fetch`. Memory, speech+// recognition and the browser come here later, as placeholders in the approved mock.+// Same card idiom as the Sandbox page: one bordered card, hairline-divided rows, ghost+// controls on the right, no new card types.++const CARD = "rounded-xl2 border border-line bg-panel";+const FIELD_LABEL = "text-ui font-medium text-ink";+const INPUT =+ "flex-1 min-w-0 px-3 py-1.5 rounded-lg border border-line bg-paper text-ui text-ink outline-none focus:border-accent";+const BTN_BORDERED =+ "text-ui px-3 py-1.5 rounded-lg border border-line bg-paper hover:border-lineStrong shrink-0 disabled:opacity-40";+const GHOST =+ "text-meta text-muted hover:text-ink hover:bg-paper px-2 py-1 rounded-md shrink-0 disabled:opacity-40";+const PILL = "text-label font-medium px-2 py-0.5 rounded-full bg-okSoft text-ok shrink-0";++// The approved mock's fixed status lines for the keyless services. Everyone else says+// where its key is, or nothing.+const KEYLESS_STATUS: Record<string, string> = {+ duckduckgo: "customization.websearch.status_duckduckgo",+ you: "customization.websearch.status_you",+};++export function CustomizationTab({ machine }: { machine?: Machine | null }) {+ const { t } = useTranslation();+ const machineId = machine?.id ?? null;+ const [info, setInfo] = useState<WebSearchInfo | null>(null);+ const [loadError, setLoadError] = useState("");+ // The provider whose inline key row is open (one at a time), its draft and its state.+ const [open, setOpen] = useState<string | null>(null);+ const [draft, setDraft] = useState("");+ const [busy, setBusy] = useState(false);+ // One message at a time, under the row it belongs to: `{name, text}`.+ const [error, setError] = useState<{ name: string; text: string } | null>(null);++ useEffect(() => {+ let alive = true;+ getWebSearch(machineId)+ .then((got) => {+ if (alive) setInfo(got);+ })+ .catch(() => {+ if (alive) setLoadError(t("customization.websearch.load_failed"));+ });+ return () => {+ alive = false;+ };+ }, [machineId, t]);++ // Every mutation answers with the whole section, so the page reflects the server's view+ // (a removed key may move the active provider back to the keyless default).+ const apply = (got: { ok: boolean; error?: string } & Partial<WebSearchInfo>, name: string) => {+ if (got.ok && got.providers) {+ setInfo({ provider: got.provider!, fetch_via_provider: !!got.fetch_via_provider, providers: got.providers });+ setError(null);+ return true;+ }+ setError({ name, text: got.error || t("customization.websearch.failed") });+ return false;+ };++ const choose = async (p: WebSearchProviderInfo) => {+ if (!info || p.name === info.provider) return;+ apply(await setWebSearchProvider(p.name, machineId), p.name);+ };++ const openKeyRow = (name: string) => {+ setOpen(name);+ setDraft("");+ setError(null);+ };++ const saveKey = async (p: WebSearchProviderInfo) => {+ const key = draft.trim();+ if (!key || busy) return;+ setBusy(true);+ try {+ if (apply(await setWebSearchKey(p.name, key, machineId), p.name)) {+ setOpen(null);+ setDraft("");+ }+ } finally {+ setBusy(false);+ }+ };++ const removeKey = async (p: WebSearchProviderInfo) => {+ if (busy) return;+ setBusy(true);+ try {+ if (apply(await clearWebSearchKey(p.name, machineId), p.name)) {+ setOpen(null);+ setDraft("");+ }+ } finally {+ setBusy(false);+ }+ };++ const flipFetch = async (next: boolean) => {+ if (!info) return;+ setInfo({ ...info, fetch_via_provider: next }); // optimistic; the reply settles it+ apply(await setFetchViaProvider(next, machineId), "fetch");+ };++ const statusLine = (p: WebSearchProviderInfo): string => {+ if (p.key_source === "store") return t("customization.websearch.key_saved");+ if (p.key_source === "env") return t("customization.websearch.key_env", { var: p.key_env || "" });+ const fixed = KEYLESS_STATUS[p.name];+ return fixed ? t(fixed) : "";+ };++ const active = info?.providers.find((p) => p.name === info.provider) ?? null;+ const fetchOffered = !!active?.supports_fetch;+ const fetchService = fetchOffered && active ? active.display_name : t("customization.fetch.service_generic");++ return (+ <section data-testid="customization-tab">+ <PanelHead+ title={t("customization.title")}+ sub={machine ? t("customization.lead_machine", { name: machine.name }) : t("customization.lead")}+ />++ <div className={FIELD_LABEL}>{t("customization.websearch.title")}</div>+ <p className="text-meta text-muted mt-0.5 mb-3 leading-relaxed">{t("customization.websearch.desc")}</p>++ {loadError ? (+ <div className="text-ui text-danger" data-testid="websearch-load-error">+ {loadError}+ </div>+ ) : !info ? null : (+ <>+ <div+ className={CARD + " divide-y divide-line"}+ role="radiogroup"+ aria-label={t("customization.websearch.title")}+ data-testid="websearch-providers"+ >+ {info.providers.map((p) => {+ const isActive = p.name === info.provider;+ const takesKey = p.key_mode !== "none";+ // A service that needs a key cannot be chosen until one is at hand (store or+ // environment); the footnote under the card says so.+ const selectable = isActive || p.key_mode !== "required" || p.has_key;+ const status = statusLine(p);+ const isOpen = open === p.name;+ const rowError = error && error.name === p.name ? error.text : "";+ return (+ <div key={p.name} className="px-4 py-2.5" data-testid={`websearch-row-${p.name}`}>+ <div className="flex items-center gap-3">+ <label className={"flex items-center gap-3 flex-1 min-w-0 " + (selectable ? "cursor-pointer" : "")}>+ <input+ type="radio"+ name="websearch-provider"+ className={selectable ? "" : "opacity-50"}+ checked={isActive}+ disabled={!selectable}+ onChange={() => void choose(p)}+ data-testid={`websearch-radio-${p.name}`}+ />+ <span className="flex-1 min-w-0">+ <span className={"block text-ui font-medium " + (selectable ? "text-ink" : "text-ink/60")}>+ {p.display_name}+ </span>+ {status ? (+ <span className="block text-meta text-muted" data-testid={`websearch-status-${p.name}`}>+ {status}+ </span>+ ) : null}+ </span>+ </label>+ {isActive ? (+ <span className={PILL} data-testid={`websearch-in-use-${p.name}`}>+ {t("customization.websearch.in_use")}+ </span>+ ) : null}+ {takesKey ? (+ isOpen ? (+ <button type="button" className={GHOST} onClick={() => setOpen(null)} data-testid="websearch-key-cancel">+ {t("customization.websearch.cancel")}+ </button>+ ) : (+ <button+ type="button"+ className={GHOST}+ onClick={() => openKeyRow(p.name)}+ data-testid={`websearch-key-button-${p.name}`}+ >+ {p.has_key ? t("customization.websearch.update_key") : t("customization.websearch.add_key")}+ </button>+ )+ ) : null}+ </div>+ {isOpen ? (+ <div className="mt-2 pl-7 flex items-center gap-2 flex-wrap" data-testid={`websearch-key-row-${p.name}`}>+ <input+ type="password"+ className={INPUT}+ placeholder={t("customization.websearch.key_placeholder", { name: p.display_name })}+ value={draft}+ autoFocus+ spellCheck={false}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void saveKey(p);+ }}+ data-testid="websearch-key-input"+ />+ <button+ type="button"+ className={BTN_BORDERED}+ disabled={busy || !draft.trim()}+ onClick={() => void saveKey(p)}+ data-testid="websearch-key-save"+ >+ {busy ? t("customization.websearch.testing") : t("customization.websearch.test_and_save")}+ </button>+ <span className="text-meta text-faint">+ {t("customization.websearch.checked_hint")}{" "}+ {p.key_url ? (+ <button+ type="button"+ className="text-accent hover:underline"+ onClick={() => openExternal(p.key_url)}+ data-testid={`websearch-key-url-${p.name}`}+ >+ {t("customization.websearch.get_key")}+ </button>+ ) : null}+ </span>+ {p.key_source === "store" ? (+ <button+ type="button"+ className={GHOST + " ml-auto"}+ disabled={busy}+ onClick={() => void removeKey(p)}+ data-testid="websearch-key-remove"+ >+ {t("customization.websearch.remove_key")}+ </button>+ ) : null}+ </div>+ ) : null}+ {rowError ? (+ <div className="mt-1.5 pl-7 text-meta text-danger" data-testid="websearch-error">+ {rowError}+ </div>+ ) : null}+ </div>+ );+ })}+ </div>+ <p className="text-meta text-faint mt-2.5">{t("customization.websearch.footnote")}</p>++ <div className={CARD + " mt-3.5 px-4 py-3 flex items-start gap-3"} data-testid="websearch-fetch-card">+ <div className="flex-1 min-w-0">+ <div className="text-ui font-medium text-ink">{t("customization.fetch.title")}</div>+ <div className="text-meta text-muted leading-relaxed">+ {t("customization.fetch.desc", { service: fetchService })}+ </div>+ {!fetchOffered ? (+ <div className="text-meta text-faint mt-1" data-testid="websearch-fetch-note">+ {t("customization.fetch.unsupported", { service: active?.display_name ?? info.provider })}+ </div>+ ) : null}+ {error && error.name === "fetch" ? (+ <div className="mt-1.5 text-meta text-danger" data-testid="websearch-error">+ {error.text}+ </div>+ ) : null}+ </div>+ <span data-testid="websearch-fetch-toggle">+ <Toggle+ checked={fetchOffered && info.fetch_via_provider}+ disabled={!fetchOffered}+ onChange={(next) => void flipFetch(next)}+ title={t("customization.fetch.title")}+ />+ </span>+ </div>+ </>+ )}+ </section>+ );+}diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsxindex d5a363cf..1a7d3eb3 100644--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@ -72,6 +72,7 @@ import { MachinesSection } from "./MachinesSection";import { RemoteConnectorsPanel } from "./RemoteConnectorsPanel";import { MemorySection } from "./MemorySection";import { SandboxSection } from "./SandboxSection";+import { CustomizationTab } from "./CustomizationTab";import { PersonasTab } from "./PersonasTab";import { SkillsTab } from "./SkillsTab";import { showPersonas } from "../flags";@@ -94,6 +95,8 @@ export type SetTab =| "sandbox"| "machines"| "connectors"+ // UX-058: the services behind the tools (web search provider + keys, fetch switch).+ | "customization"| "personas"// UX-049: per-connector glance pages (App group), shown once connected somewhere.| "slack"@@ -147,6 +150,7 @@ const SET_GROUPS: { name: string; nameKey?: string; scope: "app" | "machine" | "tabs: [{ key: "models", label: "Models & Keys", labelKey: "settings.tab.models", icon: "code" },{ key: "connectors", label: "Connectors", labelKey: "nav.connectors", icon: "plug" },+ { key: "customization", label: "Customization", labelKey: "settings.tab.customization", icon: "sliders" },{ key: "context", label: "Context optimization", labelKey: "settings.tab.context", icon: "refresh" },{ key: "skills", label: "Skills", labelKey: "settings.tab.skills", icon: "book" },{ key: "memory", label: "Memory", labelKey: "settings.tab.memory", icon: "archive" },@@ -397,6 +401,8 @@ export function SettingsView({/>) : tab === "sandbox" ? (<SandboxSection key={scopeId || "local"} machine={scoped} onProviderChanged={onSandboxProviderChanged} />+ ) : tab === "customization" ? (+ <CustomizationTab key={scopeId || "local"} machine={scoped} />) : tab === "machines" ? (<MachinesSection />) : tab === "slack" || tab === "github" ? (diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex e5fbd9fe..b9b4221e 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -356,7 +356,8 @@"personas": "Coworkers","context": "Context optimization","skills": "Skills",- "memory": "Memory"+ "memory": "Memory",+ "customization": "Customization"},"general_title": "General","general_sub": "How OpenWorker looks and behaves on this machine.",@@ -726,6 +727,7 @@"save_skill_footer": "Approving adds it to your skills on this computer — usable in every conversation from then on.","search_note": "Queries go to your configured search provider.","search_note_current": "Queries go to your configured search provider (currently: {{provider}}).",+ "fetch_note_current": "The page is fetched through {{provider}}, which sees its address.","reviewer_unsure": "reviewer wasn’t sure: {{note}}","site_wall_note": "{{host}} is not on your allowed sites.","network": {@@ -2842,4 +2844,37 @@"add": "Add","save": "Save"}+,+ "customization": {+ "title": "Customization",+ "lead": "Pick the services OpenWorker uses behind its tools. Each choice applies to new sessions on this machine.",+ "lead_machine": "Pick the services OpenWorker uses behind its tools on {{name}}. Each choice applies to new sessions there.",+ "websearch": {+ "title": "Web search",+ "desc": "Used by the web_search tool. Keys are kept in this machine's secret store; each service keeps its own, so switching back costs nothing.",+ "status_duckduckgo": "No key. Rate-limited, fine for occasional searches.",+ "status_you": "Works without a key, with a daily limit. A key lifts it.",+ "key_saved": "Key saved",+ "key_env": "Key from environment {{var}}",+ "in_use": "In use",+ "add_key": "Add key",+ "update_key": "Update key",+ "cancel": "Cancel",+ "key_placeholder": "{{name}} API key",+ "test_and_save": "Test and save",+ "testing": "Testing…",+ "checked_hint": "Checked with one search.",+ "get_key": "Get a key ↗",+ "remove_key": "Remove key",+ "footnote": "A service with no key can't be chosen until one is added. The agent's approval card names the service in use.",+ "load_failed": "Couldn't load the web search settings.",+ "failed": "That didn't work. Try again."+ },+ "fetch": {+ "title": "Fetch pages through the search service",+ "desc": "Off: pages are fetched from this machine. On: {{service}} fetches them, and sees each page address. Offered by Exa, Firecrawl and Tavily.",+ "service_generic": "the search service",+ "unsupported": "{{service}} doesn't offer this. Choose Exa, Firecrawl or Tavily to turn it on."+ }+ }}diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 04bead5a..c80bbec7 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -349,7 +349,8 @@"personas": "同事","context": "上下文优化","skills": "技能",- "memory": "记忆"+ "memory": "记忆",+ "customization": "自定义"},"general_title": "通用","general_sub": "OpenWorker 在本机的外观与行为。",@@ -715,6 +716,7 @@"save_skill_footer": "批准后会将其添加到本机的技能中 —— 此后每个会话都可使用。","search_note": "查询会发送到你配置的搜索服务商。","search_note_current": "查询会发送到你配置的搜索服务商(当前:{{provider}})。",+ "fetch_note_current": "该网页通过 {{provider}} 抓取,它会看到网页地址。","reviewer_unsure": "审查器不确定:{{note}}","site_wall_note": "{{host}} 不在你允许的网站列表中。","network": {@@ -2802,4 +2804,37 @@"add": "添加","save": "保存"}+,+ "customization": {+ "title": "自定义",+ "lead": "选择 OpenWorker 各工具背后使用的服务。所做选择对本机的新会话生效。",+ "lead_machine": "选择 OpenWorker 在 {{name}} 上各工具背后使用的服务。所做选择对该机器的新会话生效。",+ "websearch": {+ "title": "网页搜索",+ "desc": "供 web_search 工具使用。密钥保存在本机的密钥库中;每个服务各自保留密钥,切换回来无需重新填写。",+ "status_duckduckgo": "无需密钥。有频率限制,偶尔搜索够用。",+ "status_you": "无需密钥即可使用,但有每日上限;添加密钥可解除。",+ "key_saved": "已保存密钥",+ "key_env": "密钥来自环境变量 {{var}}",+ "in_use": "使用中",+ "add_key": "添加密钥",+ "update_key": "更新密钥",+ "cancel": "取消",+ "key_placeholder": "{{name}} API 密钥",+ "test_and_save": "测试并保存",+ "testing": "测试中…",+ "checked_hint": "会用一次搜索来检查。",+ "get_key": "获取密钥 ↗",+ "remove_key": "移除密钥",+ "footnote": "没有密钥的服务要先添加密钥才能选用。智能体的审批卡片会注明所用的服务。",+ "load_failed": "无法加载网页搜索设置。",+ "failed": "操作未成功,请重试。"+ },+ "fetch": {+ "title": "通过搜索服务抓取网页",+ "desc": "关闭:网页由本机抓取。开启:由 {{service}} 抓取,它会看到每个网页地址。Exa、Firecrawl 和 Tavily 提供此功能。",+ "service_generic": "搜索服务",+ "unsupported": "{{service}} 不提供此功能。选择 Exa、Firecrawl 或 Tavily 后即可开启。"+ }+ }}diff --git a/surfaces/gui/src/routes.ts b/surfaces/gui/src/routes.tsindex a52e35b0..311ff874 100644--- a/surfaces/gui/src/routes.ts+++ b/surfaces/gui/src/routes.ts@@ -28,6 +28,8 @@ const TAB_BY_SLUG: Record<string, string> = {coworkers: "personas",machines: "machines",connectors: "connectors",+ // UX-058: the services behind the tools.+ customization: "customization",// UX-049: per-connector glance pages.slack: "slack",github: "github",