+ {/* Facts a newcomer does not need to use the Agent. The Profile, Provider
+ and model are already in the row above, so they are not repeated. */}
+
+ {installations.length ? (
+
);
}
diff --git a/frontend/src/components/AppWindow.test.tsx b/frontend/src/components/AppWindow.test.tsx
new file mode 100644
index 00000000..0a1e483e
--- /dev/null
+++ b/frontend/src/components/AppWindow.test.tsx
@@ -0,0 +1,58 @@
+import { render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+let mockStatus: { migrationNotice?: string; catalog: unknown[] } = { catalog: [] };
+
+vi.mock("@wailsio/runtime", () => ({ Events: { On: vi.fn(), Off: vi.fn() } }));
+vi.mock("./NavigationSidebar", () => ({ NavigationSidebar: () => null }));
+vi.mock("../state/WizardContext", () => ({
+ useWizard: () => ({ state: { status: mockStatus } }),
+}));
+
+import { I18nProvider } from "../i18n";
+import { FeedbackProvider } from "../state/FeedbackContext";
+import { AppWindow } from "./AppWindow";
+import { PageScaffold } from "./PageScaffold";
+
+const renderWindow = () =>
+ render(
+
+
+
+
+
+
+
+
+ ,
+ );
+
+beforeEach(() => localStorage.setItem("bootagent.locale", "zh-CN"));
+afterEach(() => {
+ localStorage.clear();
+ mockStatus = { catalog: [] };
+});
+
+describe("AppWindow migration notice", () => {
+ it("reports a failed migration as a receipt instead of a paragraph above the page", async () => {
+ mockStatus = { catalog: [], migrationNotice: "无法迁移旧 BootAgent 配置:inspect legacy configuration: denied" };
+ const { container } = renderWindow();
+
+ const receipt = await screen.findByRole("alert");
+ expect(receipt).toHaveTextContent("没能迁移旧版配置");
+ expect(container.querySelector(".app-main")?.firstElementChild).toHaveClass("page-scaffold");
+ });
+
+ it("reports a completed migration as a warning that waits to be read", async () => {
+ mockStatus = { catalog: [], migrationNotice: "OneAgent configuration was migrated to BootAgent." };
+ renderWindow();
+
+ expect(await screen.findByRole("alert")).toHaveTextContent("已迁移旧版配置");
+ });
+
+ it("shows nothing without a notice", () => {
+ renderWindow();
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+});
diff --git a/frontend/src/components/AppWindow.tsx b/frontend/src/components/AppWindow.tsx
index 42de7da8..430cf787 100644
--- a/frontend/src/components/AppWindow.tsx
+++ b/frontend/src/components/AppWindow.tsx
@@ -1,20 +1,38 @@
-import type { PropsWithChildren } from "react";
+import { type PropsWithChildren, useEffect, useRef } from "react";
import { NavigationSidebar } from "./NavigationSidebar";
+import { useFeedback } from "../state/FeedbackContext";
import { useWizard } from "../state/WizardContext";
import { useI18n } from "../i18n";
+/** The prefix internal/app/status.go puts on a migration that failed. */
+const MIGRATION_FAILED_PREFIX = "无法迁移";
+
export function AppWindow({ children }: PropsWithChildren) {
const { t } = useI18n();
const { state } = useWizard();
+ const feedback = useFeedback();
+ const notice = state.status?.migrationNotice ?? "";
+ // The notice is in every status poll for the life of the process. It used to
+ // be a paragraph above every page, taking height from each of them; it is now
+ // one receipt, shown once, that stays until the user closes it.
+ const shown = useRef("");
+ useEffect(() => {
+ if (!notice || shown.current === notice) return;
+ shown.current = notice;
+ const failed = notice.startsWith(MIGRATION_FAILED_PREFIX);
+ feedback.show({
+ key: "migration",
+ tone: failed ? "failure" : "warning",
+ message: failed ? t("没能迁移旧版配置") : t("已迁移旧版配置"),
+ detail: notice,
+ });
+ }, [notice, feedback, t]);
return (
event.preventDefault()}>
-
- {state.status?.migrationNotice ?
{state.status.migrationNotice}
: null}
- {children}
-
+ {children}
);
diff --git a/frontend/src/components/ConnectionStatus.test.tsx b/frontend/src/components/ConnectionStatus.test.tsx
index 53fbadd5..440a97c3 100644
--- a/frontend/src/components/ConnectionStatus.test.tsx
+++ b/frontend/src/components/ConnectionStatus.test.tsx
@@ -43,9 +43,12 @@ describe("ConnectionStatus", () => {
expect(screen.queryByText(/BootAgent chose the model/)).toBeNull();
});
- it("reports a successful probe with the provider's own message", () => {
- show(probe({ ok: true, status: 200, message: "连接正常", error_code: null }));
- expect(screen.getByText("连接正常")).toBeTruthy();
+ // The backend's success sentence is English ("OpenAI Chat Completions
+ // connection test passed."), so the verdict is the interface's own words.
+ it("reports a successful probe in its own words, not the backend's", () => {
+ show(probe({ ok: true, status: 200, message: "OpenAI Chat Completions connection test passed.", error_code: null }));
+ expect(screen.getByText("Connection works")).toBeTruthy();
+ expect(screen.queryByText(/connection test passed/)).toBeNull();
});
// The backend's own sentences are English and written for a maintainer reading a
diff --git a/frontend/src/components/ConnectionStatus.tsx b/frontend/src/components/ConnectionStatus.tsx
index 8d9e8f5e..4c397b46 100644
--- a/frontend/src/components/ConnectionStatus.tsx
+++ b/frontend/src/components/ConnectionStatus.tsx
@@ -48,7 +48,9 @@ export function ConnectionStatus({ state, result }: { state: AsyncState; result:
- {result.message}
+ {/* Not result.message: the backend writes " connection test
+ passed." in English, and which protocols passed is listed below. */}
+ {t("连接正常")}
{breakdown}
diff --git a/frontend/src/components/DesktopAppSection.test.tsx b/frontend/src/components/DesktopAppSection.test.tsx
index c22e8cf5..2c0c863b 100644
--- a/frontend/src/components/DesktopAppSection.test.tsx
+++ b/frontend/src/components/DesktopAppSection.test.tsx
@@ -1,9 +1,14 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { BootAgentApiError } from "../backend/errors";
import type { DesktopAgentActionResult, DesktopAgentStatus } from "../types/api";
+import { FeedbackProvider } from "../state/FeedbackContext";
import { TaskCenterProvider } from "../state/TaskCenterContext";
+import { ACTION_DONE_MS } from "./ActionButton";
import { DesktopAppSection } from "./DesktopAppSection";
+import { FeedbackViewport } from "./FeedbackViewport";
+import { TaskCenter } from "./TaskCenter";
const bridge = vi.hoisted(() => ({
onInstallOutput: () => () => {},
@@ -58,12 +63,18 @@ describe("DesktopAppSection", () => {
);
expect(screen.getByRole("heading", { name: "桌面 Agent" })).toBeTruthy();
- const configNote = screen.getByText("与 Example CLI 共用配置文件 /home/u/.example/config.toml;安装和启动不会改动配置");
- expect(configNote.closest(".desktop-app-row")).toBeTruthy();
+ // The settings file is a detail: in the row's closed fold, not its text.
+ const configPath = screen.getByText("/home/u/.example/config.toml");
+ expect(configPath.closest("details")?.open).toBe(false);
+ expect(configPath.closest(".desktop-app-row")).toBeTruthy();
+ expect(screen.getByText("和 Example CLI 用同一份设置,安装和启动不会改动它").closest("details")).toBe(configPath.closest("details"));
fireEvent.click(screen.getByRole("button", { name: "安装" }));
await waitFor(() => expect(onChanged).toHaveBeenCalledTimes(1));
expect(bridge.installDesktopAgent).toHaveBeenCalledWith("chatgpt-desktop");
- expect(screen.getByText("Example Desktop 安装完成")).toBeTruthy();
+ // The outcome belongs to the Task Center, not to a notice inside the card
+ // that pushed the rows below it down.
+ expect(screen.queryByText("Example Desktop 安装完成")).toBeNull();
+ expect(document.querySelector(".desktop-app-section .notice-success")).toBeNull();
});
it("offers conversation migration in the action menu for installed ChatGPT Desktop", () => {
@@ -150,16 +161,15 @@ describe("DesktopAppSection", () => {
fireEvent.click(screen.getByRole("button", { name: "启动" }));
await waitFor(() => expect(bridge.openDesktopAgent).toHaveBeenCalledTimes(1));
expect(bridge.openDesktopAgent).toHaveBeenCalledWith("chatgpt-desktop");
- expect(screen.getByText("Example Desktop 已打开")).toBeTruthy();
+ // Confirmed on the button itself rather than in a notice above the card.
+ expect(await screen.findByRole("button", { name: "已打开" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "更新" })).toBeNull();
// The version is a token now, so its heading lives in title= rather than
// beside the value. Assert the labelled element, not the concatenation.
expect(screen.getByTitle("版本").textContent).toBe("26.727.51351");
});
- it("retires the launch notice on its own", async () => {
- // It used to stay until the user launched again or navigated away, which
- // unmounted the row -- so on the page where you launch from, it never left.
+ it("returns the launch button to its label after confirming", async () => {
vi.useFakeTimers();
try {
bridge.openDesktopAgent.mockResolvedValue(undefined);
@@ -169,56 +179,42 @@ describe("DesktopAppSection", () => {
,
);
- fireEvent.click(screen.getByRole("button", { name: "启动" }));
- await vi.waitFor(() => expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy());
- // Still there a moment later: it is readable, not a flash.
- await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
- expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy();
-
- await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
- expect(screen.queryByText("Example Desktop 已打开")).toBeNull();
+ const button = screen.getByRole("button", { name: "启动" });
+ fireEvent.click(button);
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(button).toHaveAccessibleName("已打开");
+ await act(async () => { await vi.advanceTimersByTimeAsync(ACTION_DONE_MS); });
+ expect(button).toHaveAccessibleName("启动");
} finally {
vi.useRealTimers();
}
});
- it("restarts the countdown when the app is launched again", async () => {
- // The second launch repeats the same message. If the reset to "" did not
- // land between the two, the effect would not re-run and the notice would
- // still vanish on the first launch's schedule.
- vi.useFakeTimers();
- try {
- bridge.openDesktopAgent.mockResolvedValue(undefined);
- render(
-
+ it("reports an open failure as a receipt and keeps a marker that reopens it", async () => {
+ bridge.openDesktopAgent.mockRejectedValue(new BootAgentApiError("Cannot open Example Desktop", "INTERNAL_ERROR", true, 500));
+ const { container } = render(
+
+
- ,
- );
+
+
+ ,
+ );
- // Settle the launch before reading the clock: the notice is set after an
- // awaited call, so advancing first would arm the timer mid-advance and
- // measure from the wrong instant.
- const launch = async () => {
- fireEvent.click(screen.getByRole("button", { name: "启动" }));
- await act(async () => { await vi.advanceTimersByTimeAsync(0); });
- };
-
- await launch();
- expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy();
- await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
-
- await launch();
- expect(bridge.openDesktopAgent).toHaveBeenCalledTimes(2);
- // 3s of the first window had already elapsed; the notice outliving another
- // 2s proves the clock restarted rather than carried over.
- await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
- expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy();
-
- await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
- expect(screen.queryByText("Example Desktop 已打开")).toBeNull();
- } finally {
- vi.useRealTimers();
- }
+ fireEvent.click(screen.getByRole("button", { name: "启动" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("无法打开 Example Desktop");
+ // Nothing was written into the card.
+ expect(container.querySelector(".desktop-app-section .notice-error")).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "关闭" }));
+ expect(screen.queryByRole("alert")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "启动失败" }));
+ expect(screen.getByRole("alert")).toHaveTextContent("无法打开 Example Desktop");
+
+ // The next open that succeeds clears the marker.
+ bridge.openDesktopAgent.mockResolvedValue(undefined);
+ fireEvent.click(screen.getByRole("button", { name: "启动" }));
+ await waitFor(() => expect(screen.queryByRole("button", { name: "启动失败" })).toBeNull());
});
it("keeps the bar and reports the outcome across a navigation mid-download", async () => {
@@ -234,6 +230,7 @@ describe("DesktopAppSection", () => {
const view = render(
+ ,
);
@@ -244,6 +241,7 @@ describe("DesktopAppSection", () => {
// Leaving the page unmounts the row while the install keeps running.
view.rerender(
+
另一个页面
,
);
@@ -252,6 +250,7 @@ describe("DesktopAppSection", () => {
// Coming back must show the bar again, without starting a second install.
view.rerender(
+ ,
);
@@ -259,8 +258,9 @@ describe("DesktopAppSection", () => {
expect(bridge.installDesktopAgent).toHaveBeenCalledTimes(1);
await act(async () => { complete(action(installed)); });
- // The verdict was recorded in the provider, so it survives the round trip.
- await waitFor(() => expect(screen.getByText("Example Desktop 安装完成")).toBeTruthy());
+ // The verdict was recorded in the provider, so it survives the round trip
+ // and is reported where install outcomes live: the Task Center.
+ await waitFor(() => expect(screen.getByText(/Example Desktop 安装完成/)).toBeTruthy());
expect(screen.queryByRole("progressbar", { name: "下载进度" })).toBeNull();
});
@@ -271,8 +271,8 @@ describe("DesktopAppSection", () => {
,
);
- expect(screen.getByText("应用状态检测不可用")).toBeTruthy();
- expect(screen.queryByText("已检测到应用,但版本信息不可用")).toBeNull();
+ expect(screen.getByText("暂时无法检查这个应用是否已安装。")).toBeTruthy();
+ expect(screen.queryByText("读不到这个应用的版本,不影响启动和使用。")).toBeNull();
});
it("can omit an uninstalled app from the overview", () => {
@@ -293,8 +293,7 @@ describe("DesktopAppSection", () => {
,
);
- expect(screen.getByText("已检测到应用,但版本信息不可用")).toBeTruthy();
- expect(screen.getByText("可继续尝试启动;版本检测与模型 API 兼容性无关。")).toBeTruthy();
+ expect(screen.getByText("读不到这个应用的版本,不影响启动和使用。")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "启动" }));
await waitFor(() => expect(bridge.openDesktopAgent).toHaveBeenCalledWith("chatgpt-desktop"));
});
diff --git a/frontend/src/components/DesktopAppSection.tsx b/frontend/src/components/DesktopAppSection.tsx
index e04262e9..ee849c22 100644
--- a/frontend/src/components/DesktopAppSection.tsx
+++ b/frontend/src/components/DesktopAppSection.tsx
@@ -1,15 +1,18 @@
import { AppWindow, Download, History, Play, Plus, RefreshCw, SlidersHorizontal, TriangleAlert } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { api, describeFailure } from "../backend/api";
import { useI18n } from "../i18n";
-import { converterProfileName } from "../state/conversion";
+import { converterProfileName, isConverterID } from "../state/conversion";
+import { useFeedback } from "../state/FeedbackContext";
import { useConversationMigration } from "../hooks/useConversationMigration";
import { taskCanceller, taskKey, useTaskCenter, useTaskRoute } from "../state/TaskCenterContext";
import type { DesktopAgentStatus, ProfileSummary } from "../types/api";
+import { ActionButton } from "./ActionButton";
import { DownloadProgress } from "./DownloadProgress";
import { EditionTag } from "./EditionTag";
import { AgentActionMenu, type AgentActionMenuItem } from "./AgentActionMenu";
+import { DetailsDisclosure } from "./DetailsDisclosure";
import { AgentIcon } from "./icons/agents";
interface DesktopAppSectionProps {
@@ -25,27 +28,23 @@ interface DesktopAppSectionProps {
showHeading?: boolean;
}
-type Action = "install" | "open";
-
-/**
- * How long "{name} 已打开" stays on screen.
- *
- * Long enough to be read, short enough that it does not become furniture. This
- * only bounds the launch confirmation: an install outcome lives in the Task
- * Center until the user dismisses it, and a failure stays until the next
- * attempt, because both carry something still worth acting on.
- */
-const LAUNCH_NOTICE_MS = 4000;
-
export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfigure, profile, providerName, model, showUninstalled = true, showHeading = true }: DesktopAppSectionProps) {
const { t } = useI18n();
- const profileName = profile ? converterProfileName(profile.id, profile.label || profile.id, t) : desktopApp.profileId || "";
+ // The overview passes the model service behind the adapter for an app in
+ // compatibility mode; the app itself is still bound to its converter Profile.
+ const viaConversion = Boolean(profile && desktopApp.profileId && isConverterID(desktopApp.profileId) && profile.id !== desktopApp.profileId);
+ const profileName = profile
+ ? viaConversion ? t("{name}(兼容模式)", { name: profile.label || profile.id }) : converterProfileName(profile.id, profile.label || profile.id, t)
+ : desktopApp.profileId || "";
const { startTask, finishTask, setTaskCanceller, taskFor } = useTaskCenter();
const route = useTaskRoute();
const migration = useConversationMigration();
- const [pending, setPending] = useState("");
- const [localNotice, setLocalNotice] = useState("");
- const [localFailure, setLocalFailure] = useState("");
+ const feedback = useFeedback();
+ const [installing, setInstalling] = useState(false);
+ const [opening, setOpening] = useState(false);
+ // The last failure to open the app, kept so the row can still name it after
+ // its receipt is closed. Cleared by the next open that succeeds.
+ const [openFailure, setOpenFailure] = useState(null);
if (!desktopApp?.supported || (!showUninstalled && !desktopApp.installed)) return null;
@@ -56,22 +55,19 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi
const installTaskID = taskKey("install", desktopApp.id);
const installTask = taskFor(installTaskID);
const downloading = installTask?.state === "running";
- const busy = Boolean(pending) || downloading;
- const notice = localNotice || (installTask?.state === "success" ? installTask.message : "");
- const failure = localFailure || (!localNotice && installTask?.state === "failure" ? installTask.message : "");
+ const busy = installing || opening || downloading;
+ const openKey = `open:${desktopApp.id}`;
+ // An install outcome lives in the Task Center; the row keeps only a marker for
+ // a failure, which reopens its reason as a receipt. Neither is written into
+ // the card, where it pushed the rows below it down.
+ const failureMarker = openFailure
+ ? { label: t("启动失败"), reopen: () => feedback.failure(openFailure, t("无法打开 {name}", { name: desktopApp.name }), { key: openKey }) }
+ : installTask?.state === "failure"
+ ? { label: t("安装失败"), reopen: () => feedback.show({ key: installTaskID, tone: "failure", message: t("无法安装 {name}", { name: desktopApp.name }), detail: installTask.message || undefined }) }
+ : null;
- // Launching an app says everything it has to say the moment it appears, so it
- // retires itself. Previously nothing cleared it: it sat there until the user
- // launched again or navigated away, which unmounted the row.
- useEffect(() => {
- if (!localNotice) return;
- const timer = setTimeout(() => setLocalNotice(""), LAUNCH_NOTICE_MS);
- return () => clearTimeout(timer);
- }, [localNotice]);
-
- const run = async (action: Action) => {
- const downloads = action === "install";
- if (downloads && !startTask({
+ const install = async () => {
+ if (!startTask({
id: installTaskID,
kind: "install",
target: desktopApp.id,
@@ -79,39 +75,44 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi
route,
progressTarget: desktopApp.id,
})) return;
- setPending(action);
- setLocalNotice("");
- setLocalFailure("");
- // Opening the app is not a download, so it gets no shared bar. Terminal
- // install cards stay in the center until the user dismisses them.
+ setInstalling(true);
try {
- const request = action === "install" ? api.installDesktopAgent(desktopApp.id) : null;
- if (request) setTaskCanceller(installTaskID, taskCanceller(request));
- const result = request ? await request : null;
- let message: string;
- if (action === "open") {
- await api.openDesktopAgent(desktopApp.id);
- message = t("{name} 已打开", { name: desktopApp.name });
- } else if (result?.status === "installed") {
- message = t("{name} 安装完成", { name: desktopApp.name });
- } else if (result?.status === "already-installed") {
- message = t("{name} 已安装", { name: desktopApp.name });
- } else {
- message = t("官方安装器已启动");
- }
+ const request = api.installDesktopAgent(desktopApp.id);
+ setTaskCanceller(installTaskID, taskCanceller(request));
+ const result = await request;
+ const message = result?.status === "installed"
+ ? t("{name} 安装完成", { name: desktopApp.name })
+ : result?.status === "already-installed"
+ ? t("{name} 已安装", { name: desktopApp.name })
+ : t("官方安装器已启动");
// Recorded in the provider, so it still reaches the user if this row
// unmounted while the install was running.
- if (downloads) finishTask(installTaskID, { kind: "success", message });
- else setLocalNotice(message);
+ finishTask(installTaskID, { kind: "success", message });
await onChanged();
} catch (error) {
- const message = describeFailure(error, t("{name} 操作失败", { name: desktopApp.name }), t).message;
- if (downloads) finishTask(installTaskID, { kind: "failure", message });
- else setLocalFailure(message);
+ finishTask(installTaskID, { kind: "failure", message: describeFailure(error, t("{name} 操作失败", { name: desktopApp.name }), t).message });
} finally {
- setPending("");
+ setInstalling(false);
}
};
+
+ // Opening the app is not a download, so it gets no task and no shared bar:
+ // the button confirms it in place, and a failure goes to a receipt.
+ const open = async () => {
+ setOpening(true);
+ try {
+ await api.openDesktopAgent(desktopApp.id);
+ setOpenFailure(null);
+ } catch (error) {
+ setOpenFailure(error);
+ throw error;
+ } finally {
+ setOpening(false);
+ }
+ // Not awaited: a slow status refresh would hold the button on its spinner
+ // after the app is already on screen.
+ void onChanged();
+ };
const menuItems: AgentActionMenuItem[] = desktopApp.installed ? [
...(desktopApp.id === "chatgpt-desktop" ? [{
id: "migration",
@@ -138,15 +139,10 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi
) : null}
- {failure ?
- ) : null}
+ {/* File locations are for whoever wants to look; using the app needs none of them. */}
+
{/* No local flag in the condition: DownloadProgress reads the shared
in-flight state itself, so navigating away and back keeps the bar. */}
diff --git a/frontend/src/components/DetailsDisclosure.tsx b/frontend/src/components/DetailsDisclosure.tsx
new file mode 100644
index 00000000..8c98e1ee
--- /dev/null
+++ b/frontend/src/components/DetailsDisclosure.tsx
@@ -0,0 +1,40 @@
+import type { ReactNode } from "react";
+
+import { useI18n } from "../i18n";
+
+export interface DetailRow {
+ label: string;
+ value: ReactNode;
+ /** Paths, IDs and URLs: monospace, and the full value on hover. */
+ code?: boolean;
+ /** Spans the whole width, for values that are a sentence rather than a token. */
+ wide?: boolean;
+}
+
+/**
+ * The "详情" fold on a card or row. Technical facts -- file paths, program
+ * locations, endpoints, package names -- live here rather than in the row
+ * itself: a newcomer does not need them to use the Agent, and a developer gets
+ * them back in one click (docs/ui-friendliness-plan.md, principle 2). Empty
+ * values are dropped, so callers can pass every fact they know; with nothing
+ * left to show, there is no fold.
+ */
+export function DetailsDisclosure({ rows, className = "", children }: { rows: DetailRow[]; className?: string; children?: ReactNode }) {
+ const { t } = useI18n();
+ const shown = rows.filter((row) => row.value !== "" && row.value !== null && row.value !== undefined && row.value !== false);
+ if (!shown.length && !children) return null;
+ return (
+
+ {t("详情")}
+
+ {shown.map((row) => (
+
+ {row.label}
+ {row.value}
+
+ ))}
+ {children}
+
+
+ );
+}
diff --git a/frontend/src/components/EnvironmentSummary.test.tsx b/frontend/src/components/EnvironmentSummary.test.tsx
new file mode 100644
index 00000000..174aa4f5
--- /dev/null
+++ b/frontend/src/components/EnvironmentSummary.test.tsx
@@ -0,0 +1,51 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+
+import type { StatusResponse } from "../types/api";
+import { EnvironmentSummary } from "./EnvironmentSummary";
+
+function runtime(id: string, name: string, installed: boolean, version = "") {
+ return {
+ id, name, command: id, installed, version, lockedVersion: "1.0.0", managed: false, supported: true,
+ note: "", license: "", licenseUrl: "", source: "", installPath: "",
+ };
+}
+
+function status(overrides: Partial = {}): StatusResponse {
+ return {
+ platform: { os: "macos", arch: "arm64", shell: "zsh" },
+ runtimes: [runtime("node", "Node.js", true, "22.1.0"), runtime("uv", "uv", false)],
+ capabilities: { canInstall: {}, missingRuntime: { aider: "uv" }, supportedAgentIds: [] },
+ catalog: [{ id: "codex" }, { id: "aider" }],
+ agents: { codex: { installed: true }, aider: { installed: false }, workbuddy: { installed: true } },
+ desktopAgents: [{ id: "workbuddy", installed: true }, { id: "zcode", installed: false }],
+ ...overrides,
+ } as unknown as StatusResponse;
+}
+
+function facts() {
+ return [...screen.getByRole("group", { name: "本机环境" }).children].map((item) => item.textContent);
+}
+
+describe("EnvironmentSummary", () => {
+ it("names the system, each runtime and how many Agents are installed", () => {
+ render();
+ // Two installed, not three: workbuddy is in agents as the owner of the
+ // desktop app's profile, and counting that map would count it twice.
+ expect(facts()).toEqual(["系统macOS · arm64", "Node.js版本 22.1.0", "uv未安装", "已安装的 Agent2 个"]);
+ });
+
+ // The default arrival is a desktop Agent, which needs no runtime. A bare "not
+ // installed" beside it would read as a fault on a machine that has none.
+ it("says whether the current selection needs a missing runtime", () => {
+ const { rerender } = render();
+ expect(facts()[2]).toBe("uv未安装,当前选择用不到");
+ rerender();
+ expect(facts()[2]).toBe("uv未安装,当前选择需要");
+ });
+
+ it("reports a machine with nothing installed without a zero", () => {
+ render();
+ expect(facts().at(-1)).toBe("已安装的 Agent还没有");
+ });
+});
diff --git a/frontend/src/components/EnvironmentSummary.tsx b/frontend/src/components/EnvironmentSummary.tsx
new file mode 100644
index 00000000..b7aa676e
--- /dev/null
+++ b/frontend/src/components/EnvironmentSummary.tsx
@@ -0,0 +1,52 @@
+import { useI18n } from "../i18n";
+import type { StatusResponse } from "../types/api";
+
+const OS_NAMES: Record = { macos: "macOS", windows: "Windows", linux: "Linux" };
+
+interface EnvironmentSummaryProps {
+ status: StatusResponse;
+ selectedAgentIds: string[];
+}
+
+/**
+ * What was found on this machine, shown before the first choice. A missing
+ * runtime is only a problem for an Agent that installs through it, so each one
+ * says whether the current selection needs it instead of reading as a fault.
+ */
+export function EnvironmentSummary({ status, selectedAgentIds }: EnvironmentSummaryProps) {
+ const { t } = useI18n();
+ const runtimes = (status.runtimes ?? []).filter((runtime) => runtime.supported || runtime.installed);
+ const needed = new Set(
+ selectedAgentIds
+ .filter((id) => !status.agents?.[id]?.installed)
+ .map((id) => status.capabilities.missingRuntime?.[id])
+ .filter(Boolean),
+ );
+ // Counted from the two lists the page shows. status.agents also holds the
+ // profile owners of desktop Agents, which would count those twice.
+ const installed = (status.catalog ?? []).filter((item) => status.agents?.[item.id]?.installed).length
+ + (status.desktopAgents ?? []).filter((app) => app.installed).length;
+
+ return (
+
+
+ {item.message}
+ {item.detail ? (
+ setExpanded((open) => !open)}>
+ {t("详情")}
+
+ ) : null}
+ {item.action ? (
+ // The action reports its own outcome, under the same key when it is a
+ // retry, so this message goes first rather than lingering beside it.
+ { onDismiss(); void item.action?.run(); }}>
+ {item.action.label}
+
+ ) : null}
+
+
+
+
+ {expanded && item.detail ?
{item.detail}
: null}
+
+ );
+}
+
+/**
+ * The receipt overlay, top right of the page body. PageScaffold renders it in
+ * the body's own grid cell, so it covers a corner of the content instead of
+ * taking a row of the layout: nothing on the page moves when it appears.
+ */
+export function FeedbackViewport() {
+ const { t } = useI18n();
+ const { available, items, dismiss } = useFeedback();
+ if (!available) return null;
+ const current = items[0];
+ return (
+ // Always mounted, even empty: a live region inserted together with its
+ // first message is not reliably announced.
+
+ {current ? dismiss(current.id)} /> : null}
+
+ );
+}
diff --git a/frontend/src/components/FirstTaskSection.test.tsx b/frontend/src/components/FirstTaskSection.test.tsx
new file mode 100644
index 00000000..876ad213
--- /dev/null
+++ b/frontend/src/components/FirstTaskSection.test.tsx
@@ -0,0 +1,99 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { api } from "../backend/api";
+import { BootAgentApiError } from "../backend/errors";
+import type { FirstTaskResult } from "../types/api";
+import { FirstTaskSection } from "./FirstTaskSection";
+
+const DIRECTORY = "/tmp/bootagent-first-task-123";
+
+function result(overrides: Partial = {}): FirstTaskResult {
+ return { agent_id: "codex", ok: true, directory: DIRECTORY, files: ["index.html"], log: "Created index.html", ...overrides };
+}
+
+async function renderSection(agentId = "codex") {
+ vi.spyOn(api, "firstTaskAgents").mockResolvedValue([{ id: "codex", name: "Codex" }]);
+ const page = render();
+ await waitFor(() => expect(api.firstTaskAgents).toHaveBeenCalled());
+ return page;
+}
+
+describe("FirstTaskSection", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("is absent for an Agent that cannot run unattended", async () => {
+ const run = vi.spyOn(api, "runFirstTask");
+ const { container } = await renderSection("opencode");
+
+ expect(container.innerHTML).toBe("");
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ // The run is a billed request to the user's own Provider. It has to be said
+ // before the button, and nothing may be sent until the button is pressed.
+ it("says the run is billed and waits to be asked", async () => {
+ const run = vi.spyOn(api, "runFirstTask").mockResolvedValue(result());
+ await renderSection();
+
+ const start = await screen.findByRole("button", { name: "开始" });
+ expect(screen.getByText(/真实的模型调用,由模型服务按它的价格计费/)).toBeTruthy();
+ expect(screen.getByText(/只会写入这个目录/)).toBeTruthy();
+ expect(run).not.toHaveBeenCalled();
+
+ fireEvent.click(start);
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(run).toHaveBeenCalledWith("codex", "zh-CN");
+ });
+
+ it("shows where the page is and what was written", async () => {
+ vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ files: ["assets/style.css", "index.html"] }));
+ await renderSection();
+ fireEvent.click(await screen.findByRole("button", { name: "开始" }));
+
+ expect((await screen.findByRole("status")).textContent).toContain("Codex 写好了");
+ expect(screen.getByText(DIRECTORY)).toBeTruthy();
+ expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual(["assets/style.css", "index.html"]);
+ // The record is there, behind a disclosure rather than poured onto the page.
+ expect(screen.queryByText("Created index.html")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: /查看运行记录/ }));
+ expect(screen.getByText("Created index.html")).toBeTruthy();
+ });
+
+ it("offers a next step when the Agent wrote nothing", async () => {
+ const run = vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ ok: false, directory: "", files: [], log: "401 Unauthorized" }));
+ await renderSection();
+ fireEvent.click(await screen.findByRole("button", { name: "开始" }));
+
+ expect((await screen.findByRole("alert")).textContent).toContain("Codex 没有写出任何文件");
+ expect(screen.getByRole("button", { name: "检查模型服务" })).toBeTruthy();
+ // The reason is in the record, so a failure opens it without being asked.
+ expect(screen.getByText("401 Unauthorized")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "重试" }));
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ // Files exist, so they are shown, but the Agent did not finish cleanly and the
+ // page may be half written. Calling that a success would misreport it.
+ it("keeps the files of a run that ended badly without calling it done", async () => {
+ vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ ok: false }));
+ await renderSection();
+ fireEvent.click(await screen.findByRole("button", { name: "开始" }));
+
+ expect((await screen.findByRole("alert")).textContent).toContain("Codex 没有正常结束");
+ expect(screen.getByText(DIRECTORY)).toBeTruthy();
+ expect(screen.queryByRole("status")).toBeNull();
+ });
+
+ it("reports a run that could not start", async () => {
+ vi.spyOn(api, "runFirstTask").mockRejectedValue(new BootAgentApiError("The selected Agent is not installed", "PREREQUISITE_MISSING", false, 400));
+ await renderSection();
+ fireEvent.click(await screen.findByRole("button", { name: "开始" }));
+
+ expect(await screen.findByRole("alert")).toBeTruthy();
+ expect(screen.getByRole("button", { name: "重试" })).toBeTruthy();
+ expect(screen.queryByRole("status")).toBeNull();
+ });
+});
diff --git a/frontend/src/components/FirstTaskSection.tsx b/frontend/src/components/FirstTaskSection.tsx
new file mode 100644
index 00000000..0fd185f2
--- /dev/null
+++ b/frontend/src/components/FirstTaskSection.tsx
@@ -0,0 +1,121 @@
+import { Copy, ExternalLink, Play, RefreshCw } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useNavigate } from "react-router-dom";
+
+import { api, failureLine, isCancellationError } from "../backend/api";
+import { useI18n } from "../i18n";
+import type { FirstTaskResult } from "../types/api";
+import { copyToClipboard } from "../utils/clipboard";
+import { LogDisclosure } from "./LogDisclosure";
+
+/**
+ * Offers one small, real task to an Agent that has just been installed: it
+ * writes a page in a temporary directory of its own. Rendered only for Agents
+ * the backend can drive unattended, so it is absent rather than disabled for
+ * the rest.
+ *
+ * Nothing is sent until the button is pressed: the run is a billed request.
+ */
+export function FirstTaskSection({ agentId }: { agentId: string }) {
+ const { t, locale } = useI18n();
+ const navigate = useNavigate();
+ // Empty until the backend confirms it can drive this Agent, and then its name.
+ const [agentName, setAgentName] = useState("");
+ const [running, setRunning] = useState(false);
+ const [result, setResult] = useState(null);
+ const [failure, setFailure] = useState("");
+ const [copied, setCopied] = useState(false);
+ const request = useRef | null>(null);
+
+ useEffect(() => {
+ let active = true;
+ void api.firstTaskAgents()
+ .then((agents) => { if (active) setAgentName(agents.find((agent) => agent.id === agentId)?.name ?? ""); })
+ .catch(() => {});
+ return () => { active = false; };
+ }, [agentId]);
+ // Leaving the page ends the run: nobody would see its result, and it would
+ // keep spending on the user's account.
+ useEffect(() => () => { void request.current?.cancel?.(); }, []);
+
+ if (!agentName) return null;
+
+ const run = async () => {
+ setRunning(true);
+ setResult(null);
+ setFailure("");
+ setCopied(false);
+ const pending = api.runFirstTask(agentId, locale);
+ request.current = pending;
+ try {
+ setResult(await pending);
+ } catch (error) {
+ if (!isCancellationError(error)) setFailure(failureLine(error, t("小任务没能运行"), t));
+ } finally {
+ request.current = null;
+ setRunning(false);
+ }
+ };
+
+ const files = result?.files ?? [];
+ const problem = failure
+ || (result && !result.ok
+ ? files.length
+ ? t("{agent} 没有正常结束,下面的文件可能不完整", { agent: agentName })
+ : t("{agent} 没有写出任何文件", { agent: agentName })
+ : "");
+ const finished = Boolean(result || failure);
+
+ return (
+
+
: null}
+ ({ label: t("{name} 下载地址", { name: runtime.name }), value: runtime.source, code: true })),
+ ]}
+ />
>
);
return (
-
+
{body}
diff --git a/frontend/src/components/SelectField.test.tsx b/frontend/src/components/SelectField.test.tsx
index f999b31e..55f698a0 100644
--- a/frontend/src/components/SelectField.test.tsx
+++ b/frontend/src/components/SelectField.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { describe, expect, it } from "vitest";
@@ -102,6 +102,35 @@ describe("SelectField", () => {
expect(screen.queryByRole("listbox")).toBeNull();
});
+ describe("scrolling while the list is open", () => {
+ /** jsdom lays nothing out, so the trigger's position is whatever this says. */
+ function placeTriggerAt(top: number) {
+ trigger().getBoundingClientRect = () => ({ top, bottom: top + 36, left: 0, right: 200, width: 200, height: 36, x: 0, y: top, toJSON: () => ({}) });
+ }
+
+ // The list is positioned from the trigger, so a scroll that moves the
+ // trigger leaves it in the wrong place.
+ it("closes when the scroll moved the trigger", async () => {
+ render();
+ placeTriggerAt(100);
+ await userEvent.click(trigger());
+ placeTriggerAt(40);
+ fireEvent.scroll(document.body);
+ expect(screen.queryByRole("listbox")).toBeNull();
+ });
+
+ // Opening the list makes the browser scroll its container to show it. That
+ // scroll arrives after the list has been placed, and closing on it shut the
+ // list the moment it opened on a page that was scrolled down.
+ it("stays open when the scroll left the trigger where it was", async () => {
+ render();
+ placeTriggerAt(100);
+ await userEvent.click(trigger());
+ fireEvent.scroll(document.body);
+ expect(screen.getByRole("listbox")).toBeTruthy();
+ });
+ });
+
it("jumps to an option by typing its first letters", async () => {
render();
trigger().focus();
diff --git a/frontend/src/components/SelectField.tsx b/frontend/src/components/SelectField.tsx
index 270cb8f6..268c05fd 100644
--- a/frontend/src/components/SelectField.tsx
+++ b/frontend/src/components/SelectField.tsx
@@ -50,6 +50,7 @@ export function SelectField({ value, options, onChange, label, id, className = "
const [dropUp, setDropUp] = useState(false);
const triggerRef = useRef(null);
const listRef = useRef(null);
+ const openedAt = useRef({ top: 0, left: 0 });
const typeahead = useRef({ query: "", at: 0 });
const selectedIndex = options.findIndex((option) => option.value === value);
@@ -76,6 +77,7 @@ export function SelectField({ value, options, onChange, label, id, className = "
const list = listRef.current;
if (!trigger || !list) return;
const box = trigger.getBoundingClientRect();
+ openedAt.current = { top: box.top, left: box.left };
// The margin covers the 5px CSS offset plus room for the shadow, and gives
// the sidebar pickers -- which sit near the bottom edge -- a reason to flip
// before the list is merely technically on screen with nothing to spare.
@@ -95,15 +97,22 @@ export function SelectField({ value, options, onChange, label, id, className = "
const target = event.target as Node;
if (!triggerRef.current?.contains(target) && !listRef.current?.contains(target)) close(false);
};
- // Any scroll or resize invalidates the measured position above.
- const onReflow = () => close(false);
+ // A resize invalidates the measured position above. A scroll only does if it
+ // moved the trigger: scroll events are delivered a frame late, so one from
+ // just before the list opened arrives after it, with the trigger already
+ // where it was measured.
+ const onResize = () => close(false);
+ const onScroll = () => {
+ const box = triggerRef.current?.getBoundingClientRect();
+ if (!box || box.top !== openedAt.current.top || box.left !== openedAt.current.left) close(false);
+ };
document.addEventListener("pointerdown", onPointerDown);
- window.addEventListener("resize", onReflow);
- window.addEventListener("scroll", onReflow, true);
+ window.addEventListener("resize", onResize);
+ window.addEventListener("scroll", onScroll, true);
return () => {
document.removeEventListener("pointerdown", onPointerDown);
- window.removeEventListener("resize", onReflow);
- window.removeEventListener("scroll", onReflow, true);
+ window.removeEventListener("resize", onResize);
+ window.removeEventListener("scroll", onScroll, true);
};
}, [open]);
diff --git a/frontend/src/i18n.tsx b/frontend/src/i18n.tsx
index 87dfd10b..856619f5 100644
--- a/frontend/src/i18n.tsx
+++ b/frontend/src/i18n.tsx
@@ -33,7 +33,6 @@ const english = {
"继续卸载": "Continue uninstall",
"可卸载": "Removable",
"不可卸载": "Not removable",
- "检测到的安装实例": "Detected installations",
"选择目标 Agent": "Select target Agents",
"没有可管理目标": "No compatible Agent targets",
"导入预览为空": "Import preview is empty",
@@ -50,7 +49,6 @@ const english = {
"导入将覆盖已有配置:{names}": "The import will overwrite existing configuration: {names}",
"导入预览新增:{names};覆盖:{conflicts}": "Import preview - new: {names}; overwrite: {conflicts}",
"无": "None",
- "已导入 BootAgent,可在 Skills 页面选择目标 Agent": "Imported into BootAgent; select target Agents on the Skills page",
"确认导入并应用": "Confirm import and apply",
"请选择至少一个目标 Agent": "Select at least one target Agent",
"导入并应用完成": "Imported and applied",
@@ -99,7 +97,6 @@ const english = {
"开机自启动": "Launch at login",
"登录系统后自动启动 BootAgent": "Start BootAgent automatically when you log in",
"暂不启用": "Not now",
- "API 转换已启用,是否让 BootAgent 随系统启动?": "API conversion is enabled. Start BootAgent automatically when you log in?",
"API 模式:": "API mode: ",
"无法保存开机自启动设置": "Could not save the launch-at-login setting",
"启动 CLI Agent 的终端": "Terminal for launching CLI Agents",
@@ -112,9 +109,6 @@ const english = {
"每个目标分别保留历史版本,默认保留 3 个": "Keep history per target; the default is 3 versions",
"无法保存备份设置": "Could not save the backup setting",
"无法读取备份设置": "Could not read the backup setting",
- "无法读取格式转换设置": "Could not read the format conversion settings",
- "无法保存格式转换设置": "Could not save the format conversion settings",
- "无法切换格式转换": "Could not change format conversion state",
"启动格式转换": "Start format conversion",
"停止格式转换": "Stop format conversion",
"格式转换状态": "Format conversion status",
@@ -122,10 +116,8 @@ const english = {
"格式转换当前已停止": "Format conversion is stopped",
"监听本机端口并将请求转发到目标 Profile": "Listen on a local port and forward requests to the target Profile",
"本地格式转换": "Local format conversion",
- "格式转换设置": "Format conversion settings",
"启用本地 API 格式转换": "Enable local API format conversion",
"将 Anthropic Messages、OpenAI Responses 和 Chat Completions 转发到目标 Profile": "Forward Anthropic Messages, OpenAI Responses, and Chat Completions to the target Profile",
- "Chat Completions 模型": "Chat Completions model",
"目标 Profile": "Target Profile",
"监听地址": "Listen address",
"本地 API Key": "Local API key",
@@ -134,50 +126,29 @@ const english = {
"启动时自动生成": "Generated automatically on start",
"重新生成 Key": "Regenerate key",
"无法重新生成本地 Key": "Unable to regenerate the local key",
- "本地协议适配端口不可用": "The local protocol adapter port is unavailable",
- "关闭占用该端口的程序,或在高级设置中更换端口": "Close the program using that port, or choose another port in advanced settings",
- "协议适配端到端验证失败": "Protocol adaptation end-to-end verification failed",
- "检查上游配置模板、模型服务余额和网络后重试": "Check the upstream Profile, model service balance, and network, then retry",
- "协议适配失败且未能完整恢复原配置": "Protocol adaptation failed and the previous configuration could not be fully restored",
- "保留 BootAgent 运行并检查 Claude Desktop 与协议适配设置": "Keep BootAgent running and inspect the Claude Desktop and protocol adapter settings",
+ "兼容模式需要的本机端口被占用": "The local port compatibility mode needs is in use",
+ "关闭占用端口的程序,或在兼容模式的高级设置里换一个端口": "Close the program using the port, or choose another port in compatibility mode's advanced settings",
+ "兼容模式没有通过测试": "Compatibility mode did not pass its test",
+ "检查所选模型服务的余额和网络后重试": "Check the chosen model service's balance and the network, then try again",
+ "兼容模式开启失败,原来的设置未能完整恢复": "Compatibility mode could not be turned on, and the previous settings were not fully restored",
+ "请保持 BootAgent 运行,并到兼容模式页面检查": "Keep BootAgent running and check the compatibility mode page",
"Claude Desktop 使用基础地址,保存时将调整为 {url}": "Claude Desktop uses the base address. It will be saved as {url}.",
- "Anthropic 模型": "Anthropic model",
- "Responses 模型": "Responses model",
- "保存格式转换设置": "Save format conversion settings",
"API 协议适配": "API protocol adapter",
"启用协议适配": "Enable protocol adaptation",
"启用协议适配并应用": "Enable adapter and apply",
- "启用并应用": "Enable and apply",
- "BootAgent 将在本机启动协议适配服务,并自动把 Claude Desktop 指向该服务。是否继续?": "BootAgent will start the local protocol adapter and point Claude Desktop to it automatically. Continue?",
- "正在检查模型服务的协议兼容性": "Checking protocol compatibility",
- "无法检查协议兼容性": "Unable to check protocol compatibility",
"该模型服务不能直接使用 Claude Desktop 所需的 Anthropic Messages。BootAgent 可以在本机转换请求格式。": "This model service cannot be used directly with the Anthropic Messages API required by Claude Desktop. BootAgent can translate requests locally.",
- "无法确认该配置模版可以通过协议适配使用": "This profile could not be verified for protocol adaptation",
"让只支持某一种 API 协议的 Agent 也能用上这个模型服务": "Let an Agent that speaks only one API protocol use a model service anyway",
"将 Responses 与 Messages 请求转换为目标服务支持的 Chat Completions": "Convert Responses and Messages requests into Chat Completions supported by the target service",
- "服务状态": "Service status",
- "选择目标配置后即可启动": "Select a target profile to start",
- "还没有可用的 Chat Completions 配置模板": "No Chat Completions profile is available yet",
"创建配置模板": "Create profile",
- "适用 Agent": "Compatible Agents",
- "{count} 个可使用": "{count} available",
- "当前没有可使用协议适配的 Agent": "No installed Agent can use protocol adaptation yet",
"查看环境总览": "View environment overview",
"了解协议适配": "About protocol adaptation",
- "不同 Agent 使用的 API 协议并不相同。Codex 使用 OpenAI Responses,Claude Code 使用 Anthropic Messages,其他 Agent 可能使用 Chat Completions。": "Agents use different API protocols. Codex uses OpenAI Responses, Claude Code uses Anthropic Messages, and other Agents may use Chat Completions.",
- "BootAgent 只在本机转换请求格式,再把请求发往上方选中的配置模板;模型与凭据仍由该配置模板管理。": "BootAgent converts request formats locally and forwards them to the selected profile; that profile still owns the model and credentials.",
- "适配服务运行中": "Adapter is running",
"适配服务已停止": "Adapter is stopped",
- "停止服务": "Stop adapter",
- "启动服务": "Start adapter",
- "保存设置": "Save",
"为什么需要它": "Why this exists",
"不同 Agent 要求的 API 协议不一样:Codex 只发 OpenAI Responses 请求,Claude Code 只发 Anthropic Messages 请求,OpenCode 和 Aider 发 Chat Completions 请求。而一个模型服务通常只支持其中一部分。": "Agents disagree about which API they speak: Codex sends OpenAI Responses requests, Claude Code sends Anthropic Messages requests, and OpenCode and Aider send Chat Completions requests. A given model service usually serves only some of those.",
"开启后,BootAgent 会在本机监听一个地址,把这三种协议的请求都翻译成 Chat Completions 再转发给下面选中的模型服务。这样协议不匹配的 Agent 也能连上它。": "When this is on, BootAgent listens on a local address and rewrites all three request formats into Chat Completions before forwarding them to the model service you pick below. That is what lets a mismatched Agent connect.",
"哪些 Agent 会用到它": "Which Agents can use it",
"把下面这些 Agent 的配置模版指向本适配器,它们就会走本地转换": "Point these Agents at the adapter and their requests will go through the local conversion",
"需要 {protocol}": "needs {protocol}",
- "已指向适配器": "using the adapter",
"没有可用的 Agent,先在环境总览里安装一个": "No Agents yet. Install one from the environment overview first.",
"请求最终发往": "Requests end up at",
"适配器把所有请求都转成 Chat Completions 发给这个配置模版,所以它必须是 Chat Completions 协议的": "The adapter converts every request into Chat Completions before sending it here, so this profile has to be a Chat Completions one",
@@ -313,6 +284,59 @@ const english = {
"任务时间线": "Task timeline",
"同批任务": "Tasks in this batch",
"错误码": "Error code",
+ "通知": "Notifications",
+ "已打开": "Opened",
+ "启动失败": "Launch failed",
+ "查看原因": "Show the reason",
+ "无法启动 {name}": "Couldn't launch {name}",
+ "无法打开 {name}": "Couldn't open {name}",
+ "无法安装 {name}": "Couldn't install {name}",
+ "无法更新 {name}": "Couldn't update {name}",
+ "无法卸载 {name}": "Couldn't uninstall {name}",
+ "已改用 {terminal} 打开": "Opened in {terminal} instead",
+ "设置里选择的 {terminal} 未安装,可以在设置中更换": "{terminal}, chosen in Settings, is not installed. You can choose another terminal in Settings.",
+ "去设置": "Open Settings",
+ "已应用,重启 {name} 后生效": "Applied. Restart {name} to use it",
+ "{agent} 已改用「{profile}」": "{agent} now uses “{profile}”",
+ "{agent} 已改用兼容模式": "{agent} now uses compatibility mode",
+ "连接正常": "Connection works",
+ "启动目录不存在": "The launch folder does not exist",
+ "换一个已有的文件夹,或用目录旁的按钮选择": "Choose an existing folder, or pick one with the button beside the path",
+ "找不到可用的终端": "No terminal is available",
+ "安装一个终端程序,或在设置中选择已安装的终端": "Install a terminal, or choose an installed one in Settings",
+ "终端没有打开": "The terminal did not open",
+ "稍后重试,或在设置中换一个终端": "Try again, or choose another terminal in Settings",
+ "没有返回模型,请手动输入模型 ID": "No models were returned. Enter a model ID by hand",
+ "无法获取模型列表,请手动输入模型 ID": "Couldn't list models. Enter a model ID by hand",
+ "「{name}」正在使用,无法删除": "“{name}” is in use and can't be deleted",
+ "使用它的 Agent:{agents}": "Used by: {agents}",
+ "已删除「{name}」": "Deleted “{name}”",
+ "已保存,{count} 个 Agent 未能更新": "Saved, but {count} Agent(s) couldn't be updated",
+ "已保存,{count} 个 Agent 已更新": "Saved and updated {count} Agent(s)",
+ "已保存「{name}」": "Saved “{name}”",
+ "已重新生成本地 Key": "Local key regenerated",
+ "兼容模式已停止": "Compatibility mode stopped",
+ "已保存兼容模式设置": "Compatibility mode settings saved",
+ "兼容模式已开启": "Compatibility mode is on",
+ "无法读取设置": "Couldn't read settings",
+ "没能迁移旧版配置": "Couldn't migrate the old configuration",
+ "已迁移旧版配置": "Old configuration migrated",
+ "无法扫描 MCP 配置": "Couldn't scan MCP configuration",
+ "没能读取 MCP 服务器": "Couldn't read MCP servers",
+ "点击重新扫描再试一次": "Click Rescan to try again",
+ "无法读取「{name}」": "Couldn't read “{name}”",
+ "无法应用 MCP 更改": "Couldn't apply MCP changes",
+ "已同步 {count} 个 MCP 服务器": "Synced {count} MCP server(s)",
+ "{count} 项未能应用": "{count} change(s) not applied",
+ "无法扫描 Skills": "Couldn't scan Skills",
+ "没能读取 Skills": "Couldn't read Skills",
+ "无法读取要导入的 Skill": "Couldn't read the Skill to import",
+ "无法应用 Skills": "Couldn't apply Skills",
+ "已应用 {count} 个 Skill": "Applied {count} Skill(s)",
+ "无法导入 Skill": "Couldn't import Skills",
+ "已导入 {count} 个 Skill": "Imported {count} Skill(s)",
+ "{count} 个 Skill 未能导入": "{count} Skill(s) not imported",
+ "勾选目标 Agent 后点「应用 Skills」即可使用": "Select target Agents, then click Apply Skills to use them",
"退出码": "Exit code",
"配置中": "Configuring",
"失败": "Failed",
@@ -321,8 +345,6 @@ const english = {
"等待执行": "Waiting",
"高级选项": "Advanced options",
"模型服务": "Provider",
- "检测状态": "Detected state",
- "备注": "Note",
"新增模型服务": "Add provider",
"模型服务 ID": "Provider ID",
"搜索模型": "Search models",
@@ -437,7 +459,6 @@ const english = {
"已下载 {done} MB / {total} MB({percent}%)": "Downloaded {done} MB of {total} MB ({percent}%)",
"已下载 {done} MB": "Downloaded {done} MB",
"按官方方式安装与登录": "Install and sign in using the official method",
- "已检测到": "Detected",
"官方安装": "Official install",
"官方文档": "Official docs",
"显示官方安装与配置步骤": "Show official installation and setup steps",
@@ -446,15 +467,11 @@ const english = {
"支持检测、安装与配置,但运行时无法被 BootAgent 管理": "Supports detection, installation, and configuration, but runtime is not managed by BootAgent",
"选择 {name}": "Select {name}",
"配置无法解析": "Configuration could not be parsed",
- "配置文件当前指向 {url}": "Configuration file currently points to {url}",
- "检测到的配置,非 BootAgent 写入": "Detected configuration not written by BootAgent",
"未配置": "Not configured",
- "{version}(锁定 {lockedVersion})": "{version} (locked to {lockedVersion})",
"选择 Agent": "Select agents",
"选择要安装的桌面 Agent,每次安装一个": "Choose the desktop agent to install. One per run",
"安装应用后,会把选定的配置模版应用到对应的配置": "After installation, the selected profile is applied to the matching configuration",
"不支持": "Unsupported",
- "与 {name} 共用配置": "Shares configuration with {name}",
"已安装,可直接应用配置模版": "Installed; a profile can be applied now",
"安装官方桌面应用": "Install the official desktop application",
"第三方桌面应用,非官方出品": "Third-party desktop application, not an official release",
@@ -490,6 +507,12 @@ const english = {
// the user may not have yet. "Register and get a key" promised the sign-up
// flow; this wording covers both arriving signed in and having to sign up.
"获取 API Key": "Get an API key",
+ "关于 API Key": "About API keys",
+ "API Key 是 {provider} 发给你的访问凭证,Agent 用它调用模型": "An API key is the credential {provider} issues to you. Agents use it to call models",
+ "还没有的话,点「获取 API Key」打开 {provider} 的官方页面,在那里注册并创建": "If you do not have one, \"Get an API key\" opens {provider}'s own page, where you sign up and create it",
+ // States who bills and stops there. An amount, or a word like "cheap", would
+ // be a promise about a price only the Provider sets.
+ "连通测试和 Agent 的每次调用都是真实请求,由 {provider} 按它的价格计费;BootAgent 不收费,也不预估费用": "Connection tests and every call an Agent makes are real requests, billed by {provider} at its prices. BootAgent charges nothing and does not estimate the cost",
"自定义模型名称(可选)": "Custom model name (optional)",
// The connection step's model field. It only decides what the probe requests --
// the configured model is chosen on the next step -- and saying so plainly is
@@ -556,13 +579,8 @@ const english = {
"本机已安装 Agent 及其当前模型服务、配置模版与模型": "Installed agents and their current providers, profiles, and models",
"刷新状态": "Refresh status",
"桌面 Agent": "Desktop Agent",
- "与 {name} 共用配置文件 {path};安装和启动不会改动配置": "Shares the {path} configuration file with {name}; installation and launch do not modify it",
- "配置文件:{path}": "Configuration file: {path}",
"位置": "Location",
"打开": "Open",
- "已检测到应用,但版本信息不可用": "The app was detected, but version information is unavailable",
- "可继续尝试启动;版本检测与模型 API 兼容性无关。": "You can still try launching the app; version detection is separate from model API compatibility.",
- "应用状态检测不可用": "Desktop app status could not be inspected",
"{name} 已打开": "{name} opened",
"{name} 安装完成": "{name} installed",
"{name} 已安装": "{name} is already installed",
@@ -572,7 +590,6 @@ const english = {
"已安装 Agent": "Installed agents",
"共 {count} 个": "Total: {count}",
"尚未安装任何命令行 Agent": "No command-line agents installed",
- "在新终端窗口中启动,并载入 BootAgent 写入的配置": "Open a new terminal window running this agent with the configuration BootAgent wrote",
"无法启动 Agent": "Could not launch the agent",
"选择启动目录": "Choose launch directory",
"启动目录": "Launch directory",
@@ -589,30 +606,22 @@ const english = {
"卸载 Agent": "Uninstall agent",
"卸载并删除全部数据": "Uninstall and delete all data",
"确认永久删除数据": "Confirm permanent data deletion",
- "全量清理将永久删除配置文件、凭据、会话和对话数据,删除后无法找回。请确认你已完成备份。": "Full cleanup permanently deletes configuration files, credentials, sessions, and conversation data. This cannot be undone. Confirm that you have made a backup.",
"永久删除并卸载": "Permanently delete and uninstall",
"卸载中": "Uninstalling",
"卸载 {name}": "Uninstall {name}",
- "确定卸载「{name}」吗?只会移除 Agent 程序,配置模版、模型服务、配置文件和对话数据都会保留。": "Uninstall “{name}”? Only the agent program will be removed. Profiles, providers, configuration files, and conversation data will be preserved.",
"已卸载 {name},配置和对话数据已保留": "Uninstalled {name}. Configuration and conversation data were preserved.",
"已卸载 {name},全部数据已删除": "Uninstalled {name}. All data was deleted.",
"无法卸载 Agent": "Could not uninstall the agent",
- "运行时": "Runtimes",
- "缺少 {count} 个运行时,安装后即可自动安装对应 Agent": "{count} runtime(s) missing. Install them to enable automatic agent installation",
- "Agent 安装所需的运行时都已就绪": "Every runtime needed to install agents is ready",
"运行时安装失败": "Could not install the runtime",
"版本 {version}": "Version {version}",
"版本未知": "Version unknown",
"{agents} 需要": "Required by {agents}",
- "锁定版本": "Locked version",
"由 BootAgent 安装": "Installed by BootAgent",
"本机已有": "Already on this machine",
"安装": "Install",
"安装 {name}": "Install {name}",
"安装运行时": "Install runtime",
"安装中": "Installing",
- "运行时会安装到 {dir},并写入登录 PATH,不需要管理员权限": "Runtimes install into {dir} and are added to your login PATH. No administrator rights needed",
- "运行时会安装到 BootAgent 的托管目录,并写入登录 PATH,不需要管理员权限": "Runtimes install into BootAgent's managed directory and are added to your login PATH. No administrator rights needed",
"运行时下载": "Runtime downloads",
// Both hosts are always tried (downloadSources, bootstrap.go:364-372), so by the
// time a download fails the mirror has been attempted and the setting cannot help.
@@ -639,7 +648,6 @@ const english = {
"应用": "Apply",
"应用配置模版": "Apply profile",
"{name} 已应用": "{name} applied",
- "当前指向": "Current target",
"配置文件": "Configuration file",
"备份": "Backups",
"已有历史备份": "Previous backup available",
@@ -811,7 +819,6 @@ const english = {
"MCP 官方 Registry": "Official MCP Registry",
"npm": "npm",
"确认跨环境卸载": "Confirm cross-environment uninstall",
- "当前 Agent 由另一套 Node/npm 环境管理。是否允许使用已记录的原始 npm 环境卸载?不会使用 sudo,也不会删除配置和对话数据。": "This Agent is managed by another Node/npm environment. Allow uninstalling it with the recorded original npm environment? sudo will not be used, and configuration and conversations will be kept.",
"允许并继续": "Allow and continue",
"Agent 尚未安装": "Agent is not installed",
"先安装这个 Agent,再执行卸载": "Install this Agent before uninstalling it",
@@ -904,7 +911,6 @@ const english = {
"科恩实验室": "Keen Security Lab",
"三堡实验室": "Sanbu Lab",
"查看报告": "View report",
- "版本信息": "Version info",
"最新版本": "Latest version",
"更新日志": "Changelog",
"安装量": "Installs",
@@ -916,6 +922,33 @@ const english = {
"收藏数": "Stars",
"下载量": "Downloads",
// multimodal capabilities
+ "这个 Agent 的设置无法读取": "This Agent's settings cannot be read",
+ "实际使用的接口地址是 {url}": "The endpoint actually in use is {url}",
+ "设置已在 BootAgent 之外被修改": "Settings were changed outside BootAgent",
+ "这份设置不是 BootAgent 写入的": "These settings were not written by BootAgent",
+ "正在使用 BootAgent 之外的设置": "Using settings from outside BootAgent",
+ "卸载「{name}」?只移除程序,你的设置和对话都会保留。": "Uninstall \"{name}\"? Only the program is removed; your settings and conversations are kept.",
+ "会永久删除这个 Agent 的设置、登录信息和全部对话,无法找回。": "This permanently deletes this Agent's settings, sign-in details and every conversation. They cannot be recovered.",
+ "这个 Agent 是用另一套 Node.js 安装的。要用当初安装它的那一套来卸载吗?不会删除你的设置和对话。": "This Agent was installed with a different Node.js. Uninstall it with the one that installed it? Your settings and conversations are not deleted.",
+ "在新的终端窗口里打开": "Open in a new terminal window",
+ "接口地址": "Endpoint",
+ "推荐版本": "Recommended version",
+ "说明": "Note",
+ "安装包": "Package",
+ "安装位置": "Installed at",
+ "读不到这个应用的版本,不影响启动和使用。": "The app's version cannot be read. You can still open and use it.",
+ "暂时无法检查这个应用是否已安装。": "Cannot check whether this app is installed right now.",
+ "设置文件": "Settings file",
+ "共用设置": "Shared settings",
+ "和 {name} 用同一份设置,安装和启动不会改动它": "Uses the same settings as {name}; installing and opening do not change them",
+ "程序位置": "Program location",
+ "还差 {count} 个运行环境,装好后就能安装对应的 Agent": "{count} runtime environments missing; install them to install the Agents that need them",
+ "安装 Agent 需要的运行环境都已就绪": "Everything needed to install Agents is ready",
+ "会装在 BootAgent 自己的目录里,不需要管理员权限。": "Installed in BootAgent's own folder; no administrator rights needed.",
+ "运行环境": "Runtime environments",
+ "安装目录": "Install folder",
+ "官方下载": "Official download",
+ "{name} 下载地址": "{name} download",
"多模态能力": "Multimodal capabilities",
"按能力查看已保存 API Key 的模型服务能做什么。列出模型不收费;点击实测会发出真实请求。": "See what the providers you have saved an API key for can do, one capability at a time. Listing models is free; Probe sends a real request.",
"多模态能力分类": "Multimodal capabilities",
@@ -998,6 +1031,84 @@ const english = {
"其他 Agent(说明文件)": "Other Agents (guide)",
"其他 Agent(生成说明文件)": "Other Agents (write a guide)",
"{agents}没有可配置的环境变量,Key 会写进 BootAgent 的私有文件 {path},由 Skill 的脚本读取。": "{agents} have no configurable environment, so the key goes into BootAgent's private file {path}, which the Skill's script reads.",
+ "BootAgent 会在本机开启兼容模式,并先发送两次测试请求,可能产生少量费用。": "BootAgent will turn on compatibility mode on this computer and send two test requests first, which may cost a little.",
+ "Claude Code 看到的模型名": "Model name Claude Code sees",
+ "Codex 看到的模型名": "Model name Codex sees",
+ "{agents} 已改用兼容模式": "{agents} now use compatibility mode",
+ "尚未确认 {provider} 支持 {agent} 的请求格式({protocol}),可以改用兼容模式,由 BootAgent 在本机转换": "{provider} isn't confirmed to support {agent}'s request format ({protocol}); compatibility mode lets BootAgent convert it on this computer",
+ "{agent} 不能直接使用这个模型服务,BootAgent 可以在本机转换后使用": "{agent} can't use this model service directly, but BootAgent can convert its requests on this computer",
+ "{agent} 不能直接使用这个模型服务,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行": "{agent} can't use this model service directly, so applying turns on compatibility mode, which needs BootAgent to keep running",
+ "{agent} 不能直接使用这个配置模版,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行": "{agent} can't use this profile directly, so applying turns on compatibility mode, which needs BootAgent to keep running",
+ "{name}(不支持此格式)": "{name} (format not supported)",
+ "{name}(兼容模式)": "{name} (compatibility mode)",
+ "不用兼容模式": "Don't use compatibility mode",
+ "了解兼容模式": "About compatibility mode",
+ "使用兼容模式": "Use compatibility mode",
+ "使用期间需要保持 BootAgent 运行": "BootAgent needs to keep running while it is in use",
+ "使用的模型": "Model to use",
+ "保存更改": "Save changes",
+ "停止": "Stop",
+ "停止兼容模式": "Stop compatibility mode",
+ "停止后 {agents} 将无法使用,直到重新开启兼容模式或换一个配置模版。": "Once stopped, {agents} won't work until compatibility mode is turned back on or they switch to another profile.",
+ "其他 Agent 看到的模型名": "Model name other Agents see",
+ "兼容模式": "Compatibility mode",
+ "兼容模式未开启": "Compatibility mode is off",
+ "兼容模式状态": "Compatibility mode status",
+ "兼容模式运行中": "Compatibility mode is running",
+ "兼容模式需要 BootAgent 保持运行。要让 BootAgent 随系统启动吗?": "Compatibility mode needs BootAgent to keep running. Start BootAgent automatically when you log in?",
+ "兼容模式(Claude Code)": "Compatibility mode (Claude Code)",
+ "兼容模式(Codex)": "Compatibility mode (Codex)",
+ "兼容模式(OpenCode / Aider)": "Compatibility mode (OpenCode / Aider)",
+ "兼容模式,在本机转换": "Compatibility mode, converted on this computer",
+ "已停止": "Stopped",
+ "已选择兼容模式,使用 {agent} 时需要保持 BootAgent 运行": "Compatibility mode chosen; BootAgent needs to keep running while you use {agent}",
+ "已通过兼容模式配置": "Configured through compatibility mode",
+ "开启兼容模式": "Turn on compatibility mode",
+ "开启并应用": "Turn on and apply",
+ "换一个模型服务": "Choose another model service",
+ "无法保存兼容模式设置": "Could not save compatibility mode settings",
+ "无法停止兼容模式": "Could not stop compatibility mode",
+ "无法开启兼容模式": "Could not turn on compatibility mode",
+ "无法确认能否使用兼容模式": "Could not confirm whether compatibility mode can be used",
+ "无法确认这个配置模版能否通过兼容模式使用": "Could not confirm whether this profile works through compatibility mode",
+ "无法读取兼容模式设置": "Could not read compatibility mode settings",
+ "正在使用的 Agent": "Agents using it",
+ "正在确认能否使用兼容模式": "Checking whether compatibility mode can be used",
+ "用兼容模式应用": "Apply with compatibility mode",
+ "让只支持特定格式的 Agent 也能用你的模型服务,在本机转换,不经过其他服务器。": "Lets Agents that only speak one format use your model service, converted on this computer without going through any other server.",
+ "运行中": "Running",
+ "还没有 Agent 使用兼容模式": "No Agent uses compatibility mode yet",
+ "这个模型服务可能不支持该 Agent 的请求格式,可以换一个模型,或用兼容模式在本机转换": "This model service may not accept this Agent's request format; try another model, or use compatibility mode to convert on this computer",
+ "连接方式": "Connection",
+ "本机转换": "Converted on this computer",
+ "Codex 发出的是 OpenAI Responses 格式,Claude Code 是 Anthropic Messages 格式,很多模型服务只支持 OpenAI Chat Completions。BootAgent 在本机把前两种转换成 Chat Completions,再发往每个 Agent 各自选择的模型。": "Codex sends requests in the OpenAI Responses format and Claude Code in the Anthropic Messages format, while many model services only accept OpenAI Chat Completions. BootAgent converts the first two into Chat Completions on this computer, then sends each Agent's requests to the model that Agent uses.",
+ "每个 Agent 用自己的本机 Key 连接,互不影响;模型和 Key 仍由各自的配置模版管理。": "Each Agent connects with a local key of its own, so they don't affect each other; models and keys are still managed by each Agent's profile.",
+ "{agent} 正在通过兼容模式使用这个配置模版,使用期间需要保持 BootAgent 运行": "{agent} uses this profile through compatibility mode, which needs BootAgent to keep running",
+ "为 {name} 更换模型": "Change the model {name} uses",
+ "使用的配置模版已删除": "The profile it used was deleted",
+ "在 Agent 的配置页选择配置模版时会自动开启": "Turns on by itself when you choose a profile on an Agent's page",
+ "开启后这些 Agent 才能使用": "These Agents work once it is on",
+ "更换": "Change",
+ "跑一个小任务试试": "Try one small task",
+ // Says who bills and stops there, like the key explainer: no amount, no "small".
+ "让 {agent} 在一个临时目录里写一个介绍页,只会写入这个目录。这是真实的模型调用,由模型服务按它的价格计费": "{agent} writes an introduction page in a temporary directory and writes nowhere else. This is a real model call, billed by the provider at its prices",
+ "开始": "Start",
+ "正在运行,通常需要一两分钟": "Running, usually a minute or two",
+ "{agent} 写好了,文件在下面这个目录": "{agent} is done. The files are in the directory below",
+ "{agent} 没有正常结束,下面的文件可能不完整": "{agent} did not finish cleanly, so the files below may be incomplete",
+ "{agent} 没有写出任何文件": "{agent} did not write any file",
+ "小任务没能运行": "The task could not run",
+ "复制路径": "Copy path",
+ "生成的文件": "Files written",
+ "检查模型服务": "Check the provider",
+ "查看运行记录": "View the run record",
+ "本机环境": "This computer",
+ "系统": "System",
+ "已安装的 Agent": "Agents installed",
+ "{count} 个": "{count}",
+ "还没有": "None yet",
+ "未安装,当前选择需要": "Not installed, and this choice needs it",
+ "未安装,当前选择用不到": "Not installed, and this choice does not need it",
} as const;
export type Locale = "zh-CN" | "en";
diff --git a/frontend/src/pages/ActivationPage.test.tsx b/frontend/src/pages/ActivationPage.test.tsx
index a31f6803..aaf94086 100644
--- a/frontend/src/pages/ActivationPage.test.tsx
+++ b/frontend/src/pages/ActivationPage.test.tsx
@@ -134,6 +134,64 @@ describe("ActivationPage partial results", () => {
expect(screen.queryByText("openclaw onboard")).toBeNull();
});
+ it("installs without configuring, then points the Agent at the adapter in compatibility mode", async () => {
+ const install = vi.spyOn(api, "install").mockResolvedValue({
+ ok: true, results: [result("codex", { status: "skipped" })], log: "", probe: null, next: "",
+ } as never);
+ const saveProfile = vi.spyOn(api, "saveProfile").mockResolvedValue({
+ profile: { id: "codex-ppio-compat", label: "Codex · PPIO", provider: "ppio", baseUrl: null, model: "deepseek/deepseek-v3", protocol: "openai", activatedAt: null },
+ reapplied: null,
+ failures: null,
+ });
+ const activate = vi.spyOn(api, "activateAgentWithConversion").mockResolvedValue({
+ ok: true, agent: "codex", config: "/c", provider: "bootagent-converter-responses", model: "gpt-5.6-sol",
+ restart: "", next: "codex", upstreamVerified: true, endToEndVerified: true,
+ });
+ state = {
+ ...initialWizardState,
+ status,
+ statusState: "success",
+ setupKind: "cli",
+ selectedAgentIds: ["codex"],
+ provider: "ppio",
+ model: "deepseek/deepseek-v3",
+ profileId: "codex-ppio-compat",
+ profileLabel: "Codex · PPIO",
+ conversion: true,
+ activationState: "idle",
+ activationRequested: true,
+ };
+
+ render();
+ await waitFor(() => expect(activate).toHaveBeenCalledWith("codex", "codex-ppio-compat"));
+ expect(install).toHaveBeenCalledWith(expect.objectContaining({ agents: ["codex"], configure: false, install_agent: true }));
+ expect(saveProfile).toHaveBeenCalledWith(expect.objectContaining({ id: "codex-ppio-compat", provider: "ppio", protocol: "openai" }));
+ });
+
+ it("refreshes after a failed compatibility mode step, so the saved Profile is visible", async () => {
+ vi.spyOn(api, "install").mockResolvedValue({
+ ok: true, results: [result("codex", { status: "skipped" })], log: "", probe: null, next: "",
+ } as never);
+ vi.spyOn(api, "saveProfile").mockResolvedValue({
+ profile: { id: "codex-ppio-compat", label: "Codex · PPIO", provider: "ppio", baseUrl: null, model: "m", protocol: "openai", activatedAt: null },
+ reapplied: null,
+ failures: null,
+ });
+ const { BootAgentApiError } = await import("../backend/errors");
+ vi.spyOn(api, "activateAgentWithConversion").mockRejectedValue(
+ new BootAgentApiError("port in use", "CONVERSION_PORT_UNAVAILABLE", true, 409),
+ );
+ state = {
+ ...initialWizardState,
+ status, statusState: "success", setupKind: "cli", selectedAgentIds: ["codex"],
+ provider: "ppio", model: "m", profileId: "codex-ppio-compat", profileLabel: "Codex · PPIO",
+ conversion: true, activationState: "idle", activationRequested: true,
+ };
+
+ render();
+ await waitFor(() => expect(refreshStatus).toHaveBeenCalled());
+ });
+
it("configures a manual desktop app without requesting an install", async () => {
vi.spyOn(api, "saveProfile").mockResolvedValue({
profile: { id: "claude-desktop-jiekou", label: "Claude Desktop", provider: "jiekou", baseUrl: null, model: "claude-sonnet-4-5", protocol: "anthropic", activatedAt: null },
diff --git a/frontend/src/pages/ActivationPage.tsx b/frontend/src/pages/ActivationPage.tsx
index 4574c95d..191a9860 100644
--- a/frontend/src/pages/ActivationPage.tsx
+++ b/frontend/src/pages/ActivationPage.tsx
@@ -11,7 +11,7 @@ import { useI18n } from "../i18n";
import { desktopProtocol, profileAgentIdForDesktop, selectedDesktopApp } from "../state/desktopSetup";
import { installTaskRoute, taskCanceller, taskKey, useTaskCenter, useTaskRoute, type TaskCanceller } from "../state/TaskCenterContext";
import { useWizard } from "../state/WizardContext";
-import type { AgentInstallResult, InstallRequest } from "../types/api";
+import type { AgentInstallResult, InstallRequest, InstallResponse } from "../types/api";
export function ActivationPage() {
const navigate = useNavigate();
@@ -58,13 +58,67 @@ export function ActivationPage() {
model: state.model,
profile_id: state.profileId,
profile_label: state.profileLabel,
- configure: true,
+ // In compatibility mode the Agent is pointed at the local adapter after
+ // it is installed, not at the Provider during the install.
+ configure: !state.conversion,
install_agent: true,
skip_test: false,
}),
- [state.model, state.profileId, state.profileLabel, state.provider],
+ [state.conversion, state.model, state.profileId, state.profileLabel, state.provider],
);
+ /**
+ * Installs, then points each installed Agent at the local adapter, which
+ * forwards to a Chat Completions Profile on the chosen Provider. A failed
+ * adapter step fails that Agent's row and can be retried: installing again
+ * is a no-op for an Agent already there.
+ */
+ const installCliWithConversion = useCallback(async (agents: string[], register: (cancel?: TaskCanceller) => void): Promise => {
+ const installRequest = api.install(requestFor(agents));
+ register(taskCanceller(installRequest));
+ const installed = await installRequest;
+ const profileRequest = api.saveProfile({
+ id: state.profileId,
+ label: state.profileLabel,
+ provider: state.provider,
+ apiBaseUrl: "",
+ apiKey: "",
+ model: state.model,
+ configMode: "provider",
+ protocol: "openai",
+ });
+ register(taskCanceller(profileRequest));
+ const { profile } = await profileRequest;
+ const results: AgentInstallResult[] = [];
+ const next: string[] = [];
+ for (const result of installed.results) {
+ if (result.status === "failed") {
+ results.push(result);
+ continue;
+ }
+ try {
+ const request = api.activateAgentWithConversion(result.agent, profile.id);
+ register(taskCanceller(request));
+ const activated = await request;
+ results.push({ ...result, status: "configured", message: t("已通过兼容模式配置") });
+ if (activated.next) next.push(activated.next);
+ } catch (error) {
+ if (isCancellationError(error)) throw error;
+ results.push({ ...result, status: "failed", message: describeFailure(error, t("无法开启兼容模式"), t).message, retryable: true });
+ }
+ }
+ // The Profile is saved even when every Agent failed, and the callers only
+ // refresh after a success: without this it stayed invisible to the
+ // compatibility mode page the failure points the user to.
+ await refreshStatus();
+ return {
+ ...installed,
+ ok: results.every((result) => result.status !== "failed"),
+ results,
+ next: next.join("\n"),
+ };
+ }, [refreshStatus, requestFor, state.model, state.profileId, state.profileLabel, state.provider, t]);
+
const startActivationTasks = useCallback((agentIds: string[]) => {
const officialScriptAgents = new Set(
(state.status?.catalog ?? [])
@@ -159,14 +213,17 @@ export function ActivationPage() {
apiKey: "",
model: state.model,
configMode: "provider",
- protocol: desktopProtocol(desktop),
+ // Compatibility mode forwards to Chat Completions, whatever the app speaks.
+ protocol: state.conversion ? "openai" : desktopProtocol(desktop),
});
register(taskCanceller(profileRequest));
const { profile } = await profileRequest;
const installRequest = desktop.installed || desktop.manualInstall ? undefined : api.installDesktopAgent(desktop.id);
if (installRequest) register(taskCanceller(installRequest));
const installed = installRequest ? await installRequest : undefined;
- const configureRequest = api.configureDesktopAgent(desktop.id, profile.id);
+ const configureRequest = state.conversion
+ ? api.configureDesktopAgentWithConversion(desktop.id, profile.id)
+ : api.configureDesktopAgent(desktop.id, profile.id);
register(taskCanceller(configureRequest));
const configured = await configureRequest;
return {
@@ -181,7 +238,7 @@ export function ActivationPage() {
log: configured.message,
next: configured.restart || "",
};
- }, [desktop, state.profileId, state.profileLabel, state.provider, state.model, t]);
+ }, [desktop, state.conversion, state.profileId, state.profileLabel, state.provider, state.model, t]);
const activate = useCallback(async () => {
const startedTasks = startActivationTasks(state.selectedAgentIds);
@@ -200,6 +257,8 @@ export function ActivationPage() {
if (isDesktop) {
response = await installDesktop((cancel) => registerActivationCanceller(startedTasks, cancel))
.then((result) => ({ ...result, ok: true, probe: null }));
+ } else if (state.conversion) {
+ response = await installCliWithConversion(state.selectedAgentIds, (cancel) => registerActivationCanceller(startedTasks, cancel));
} else {
const request = api.install(requestFor(state.selectedAgentIds));
registerActivationCanceller(startedTasks, taskCanceller(request));
@@ -227,7 +286,7 @@ export function ActivationPage() {
finishActivationTasks(startedTasks, [], false, message);
dispatch({ type: "ACTIVATION_FAILED", message });
}
- }, [dispatch, finishActivationTasks, installDesktop, isDesktop, navigate, refreshStatus, registerActivationCanceller, requestFor, startActivationTasks, state.selectedAgentIds, t]);
+ }, [dispatch, finishActivationTasks, installCliWithConversion, installDesktop, isDesktop, navigate, refreshStatus, registerActivationCanceller, requestFor, startActivationTasks, state.conversion, state.selectedAgentIds, t]);
useEffect(
() =>
@@ -302,6 +361,8 @@ export function ActivationPage() {
if (isDesktop) {
response = await installDesktop((cancel) => registerActivationCanceller(startedTasks, cancel))
.then((result) => ({ ...result, ok: true, probe: null }));
+ } else if (state.conversion) {
+ response = await installCliWithConversion([agentId], (cancel) => registerActivationCanceller(startedTasks, cancel));
} else {
const request = api.install(requestFor([agentId]));
registerActivationCanceller(startedTasks, taskCanceller(request));
diff --git a/frontend/src/pages/AgentProfilePage.test.tsx b/frontend/src/pages/AgentProfilePage.test.tsx
index dcf48717..f7f0cf3c 100644
--- a/frontend/src/pages/AgentProfilePage.test.tsx
+++ b/frontend/src/pages/AgentProfilePage.test.tsx
@@ -1,9 +1,11 @@
-import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { api } from "../backend/api";
+import { FeedbackViewport } from "../components/FeedbackViewport";
+import { FeedbackProvider } from "../state/FeedbackContext";
import type { ProfileSummary, SaveProfileResult, StatusResponse } from "../types/api";
import { AgentProfilePage } from "./AgentProfilePage";
@@ -68,15 +70,24 @@ function statusWith(profiles: ProfileSummary[]): StatusResponse {
function renderPage(profiles: ProfileSummary[]) {
mockState = { status: statusWith(profiles), statusState: "success" };
return render(
-
-
- } />
- overview} />
-
- ,
+
+
+
+ } />
+ overview} />
+
+
+ ,
);
}
+/** The receipt on screen, with 详情 open. */
+async function failureReceipt() {
+ const receipt = await screen.findByRole("alert");
+ fireEvent.click(within(receipt).getByRole("button", { name: "详情" }));
+ return receipt;
+}
+
function renderClaudeDesktopPage(profiles: ProfileSummary[]) {
const status = statusWith(profiles);
status.desktopAgents = [{
@@ -119,7 +130,56 @@ const availableCheck = {
profileId: "team-ppio", model: "deepseek/deepseek-v3", status: "available" as const, protocol: "responses", agents: ["codex"],
};
+/** The page inside the app's feedback layer, with the overview showing receipts. */
+function renderWithReceipts(path: string, status: StatusResponse) {
+ mockState = { status, statusState: "success" };
+ render(
+
+
+
+ } />
+
overview
>} />
+
+
+ ,
+ );
+}
+
describe("AgentProfilePage", () => {
+ // The overview row changing was the only sign the apply worked; the receipt
+ // outlives this page and says it in words.
+ it("names the applied Profile on the overview it returns to", async () => {
+ vi.spyOn(api, "activateAgent").mockResolvedValue({
+ ok: true, agent: "codex", config: "/c", provider: "ppio",
+ model: "deepseek/deepseek-v3", restart: "", next: "",
+ });
+ renderWithReceipts("/agents/codex", statusWith([profile()]));
+ fireEvent.click(screen.getByRole("button", { name: "应用" }));
+ await screen.findByRole("heading", { name: "overview" });
+ expect(screen.getByText("Codex 已改用「团队 PPIO」")).toBeTruthy();
+ });
+
+ // The backend reports that a desktop app reads its settings at startup; that
+ // used to be dropped, so the running app looked switched when it was not.
+ it("keeps a restart reminder after applying to a desktop app", async () => {
+ const status = statusWith([profile({ id: "desk", label: "桌面", protocol: "anthropic", model: "claude-sonnet-5-5" })]);
+ status.desktopAgents = [{
+ id: "claude-desktop", name: "Claude Desktop", installed: true, supported: true,
+ version: "1.0.0", source: "application", protocol: "anthropic", profileAgentId: "claude-desktop", profileId: null,
+ }];
+ status.providers = { ppio: { name: "PPIO", home: "", base_url: "https://api.ppio.com/openai", anthropic_base_url: "https://api.ppio.com/anthropic", has_key: true } };
+ const configure = vi.spyOn(api, "configureDesktopAgent").mockResolvedValue({
+ agent: "claude-desktop", profileId: "desk", profileAgentId: "claude-desktop",
+ message: "Claude Desktop model applied", restart: "Restart Claude Desktop",
+ });
+ renderWithReceipts("/agents/claude-desktop", status);
+ fireEvent.click(screen.getByRole("button", { name: "应用" }));
+ await waitFor(() => expect(configure).toHaveBeenCalledWith("claude-desktop", "desk"));
+ await screen.findByRole("heading", { name: "overview" });
+ // A warning, so it waits to be closed rather than retiring itself.
+ expect(screen.getByRole("alert")).toHaveTextContent("已应用,重启 Claude Desktop 后生效");
+ });
+
// Requirement: after applying, land where the result is visible instead of
// staying on a screen whose job is done.
it("returns to the overview after a successful apply", async () => {
@@ -140,7 +200,9 @@ describe("AgentProfilePage", () => {
);
renderPage([profile()]);
fireEvent.click(screen.getByRole("button", { name: "应用" }));
- expect(await screen.findByText("Endpoint refused the key")).toBeTruthy();
+ const receipt = await failureReceipt();
+ expect(receipt).toHaveTextContent("应用配置模版失败");
+ expect(receipt).toHaveTextContent("Endpoint refused the key");
// Not navigated away: the user needs to see the error next to the choice.
expect(screen.queryByRole("heading", { name: "overview" })).toBeNull();
});
@@ -267,6 +329,21 @@ describe("AgentProfilePage", () => {
// Both inline save paths dropped result.failures, so an Agent that could not
// be rewritten went unreported here.
+ // The model belongs to the Profile, so an edit made for this Agent also
+ // moves every other Agent on it. That used to happen with nothing said.
+ it("names the other Agents an inline model edit moved", async () => {
+ vi.spyOn(api, "saveProfile").mockResolvedValue({ ...saved({ model: "deepseek/deepseek-r1" }), reapplied: ["codex", "opencode"] });
+ renderPage([profile()]);
+ await waitFor(() => expect(screen.getByLabelText("模型")).toHaveAttribute("placeholder", "搜索模型"));
+ const field = screen.getByLabelText("模型");
+ await userEvent.clear(field);
+ await userEvent.type(field, "deepseek/deepseek-r1");
+ await userEvent.tab();
+ const receipt = (await screen.findByText("已保存,2 个 Agent 已更新")).closest(".feedback-toast") as HTMLElement;
+ fireEvent.click(within(receipt).getByRole("button", { name: "详情" }));
+ expect(receipt).toHaveTextContent("Codex、opencode");
+ });
+
it("reports an Agent an inline model edit could not rewrite", async () => {
vi.spyOn(api, "saveProfile").mockResolvedValue({ ...saved({ model: "deepseek/deepseek-r1" }), failures: { codex: "写入失败" } });
renderPage([profile()]);
@@ -275,7 +352,9 @@ describe("AgentProfilePage", () => {
await userEvent.clear(field);
await userEvent.type(field, "deepseek/deepseek-r1");
await userEvent.tab();
- expect(await screen.findByText(/Codex.*重新应用失败.*写入失败/)).toBeTruthy();
+ const receipt = await failureReceipt();
+ expect(receipt).toHaveTextContent("已保存,1 个 Agent 未能更新");
+ expect(receipt).toHaveTextContent("Codex: 写入失败");
});
// Apply right after typing: the flush saves the new model, and the Apply has
@@ -312,7 +391,10 @@ describe("AgentProfilePage", () => {
fireEvent.click(screen.getByRole("button", { name: "应用" }));
// CONFIG_WRITE_FAILED is shown as its localized copy, not the raw message.
- expect(await screen.findByText("无法写入配置文件")).toBeTruthy();
+ const receipt = await failureReceipt();
+ expect(receipt).toHaveTextContent("无法保存配置模版");
+ expect(receipt).toHaveTextContent("无法写入配置文件");
+ expect(receipt).not.toHaveTextContent("disk full");
expect(activate).not.toHaveBeenCalled();
expect(screen.queryByRole("heading", { name: "overview" })).toBeNull();
});
@@ -433,15 +515,26 @@ describe("AgentProfilePage", () => {
expect(await screen.findByLabelText("思考深度")).toBeTruthy();
});
- it("shows generated adapter Profiles with a Chinese user-facing name", () => {
- renderPage([profile({
- id: "bootagent-converter-responses",
- label: "BootAgent Converter responses",
- })]);
+ // An Agent in compatibility mode is shown on the Profile its requests go
+ // to; the adapter's own Profile is an implementation detail.
+ it("preselects the model service a compatibility-mode Agent really uses", () => {
+ const status = statusWith([
+ profile({ id: "bootagent-converter-for-codex", label: "BootAgent codex", provider: "bootagent-converter-for-codex", model: "gpt-5.6-sol" }),
+ profile({ id: "team-ppio", label: "团队 PPIO", protocol: "responses" }),
+ profile({ id: "chat-only", label: "Chat only", protocol: "openai" }),
+ ]);
+ status.agents.codex = { ...status.agents.codex, profileId: "bootagent-converter-for-codex" };
+ status.conversionRoutes = { codex: "chat-only" };
+ mockState = { status, statusState: "success" };
+ render(
+
+ } />
+ ,
+ );
- expect(screen.getAllByText("协议适配(Codex)")).toHaveLength(2);
- expect(screen.queryByText("BootAgent Converter responses")).toBeNull();
- expect(screen.getByRole("radio", { name: "选择 协议适配(Codex)" })).toBeTruthy();
+ expect(screen.queryByText("BootAgent codex")).toBeNull();
+ expect(screen.getByRole("radio", { name: "选择 Chat only" })).toBeChecked();
+ expect(screen.getByText("Codex 正在通过兼容模式使用这个配置模版,使用期间需要保持 BootAgent 运行")).toBeTruthy();
});
it("offers one-confirmation protocol adaptation for a Chat Completions Profile", async () => {
@@ -458,10 +551,69 @@ describe("AgentProfilePage", () => {
id: "chat-profile", label: "Chat Profile", provider: "chat-only", model: "model-a", protocol: "openai",
})]);
- expect(await screen.findByText("该模型服务不能直接使用 Claude Desktop 所需的 Anthropic Messages。BootAgent 可以在本机转换请求格式。")).toBeTruthy();
- const apply = screen.getByRole("button", { name: "启用协议适配并应用" });
+ expect(await screen.findByText("Claude Desktop 不能直接使用这个模型服务,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行")).toBeTruthy();
+ const apply = screen.getByRole("button", { name: "用兼容模式应用" });
await userEvent.click(apply);
await waitFor(() => expect(configure).toHaveBeenCalledWith("claude-desktop", "chat-profile"));
expect(await screen.findByRole("heading", { name: "overview" })).toBeTruthy();
});
+
+ // A command-line Agent used to have no route to the adapter at all: a Chat
+ // Completions Profile was never listed for Codex, and pointing Codex at the
+ // adapter meant picking a hidden converter Profile by hand.
+ it("lists a Chat Completions Profile for Codex and applies it through compatibility mode", async () => {
+ const assess = vi.spyOn(api, "assessDesktopAgentProfile");
+ const activate = vi.spyOn(api, "activateAgent");
+ const convert = vi.spyOn(api, "activateAgentWithConversion").mockResolvedValue({
+ ok: true, agent: "codex", config: "/c", provider: "bootagent-converter-responses", model: "gpt-5.6-sol",
+ restart: "", next: "", upstreamVerified: true, endToEndVerified: true,
+ });
+ renderPage([profile({ id: "chat-only", label: "Chat only", protocol: "openai" })]);
+
+ await userEvent.click(screen.getByRole("radio", { name: "选择 Chat only" }));
+ expect(screen.getByText("Codex 不能直接使用这个配置模版,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行")).toBeTruthy();
+ // Nothing billed is sent on selection: the check belongs to the button.
+ expect(assess).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole("button", { name: "用兼容模式应用" }));
+ await waitFor(() => expect(convert).toHaveBeenCalledWith("codex", "chat-only"));
+ expect(activate).not.toHaveBeenCalled();
+ expect(await screen.findByRole("heading", { name: "overview" })).toBeTruthy();
+ });
+
+ it("does not offer Chat Completions Profiles to an Agent that already speaks it", () => {
+ const status = statusWith([
+ profile({ id: "chat-only", label: "Chat only", protocol: "openai" }),
+ profile({ id: "responses-only", label: "Responses only", protocol: "responses" }),
+ ]);
+ status.catalog = [{ ...status.catalog[0], id: "opencode", name: "OpenCode", protocol: "openai" }];
+ status.agents = { opencode: { ...status.agents.codex, profileId: null } };
+ mockState = { status, statusState: "success" };
+ render(
+
+ } />
+ ,
+ );
+
+ expect(screen.getByRole("radio", { name: "选择 Chat only" })).toBeTruthy();
+ expect(screen.queryByRole("radio", { name: "选择 Responses only" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "用兼容模式应用" })).toBeNull();
+ });
+
+ it("turns a refused check into compatibility mode on the same Provider and model", async () => {
+ vi.mocked(api.checkProfileModel).mockResolvedValue(refusedCheck);
+ const saveProfile = vi.spyOn(api, "saveProfile").mockResolvedValue(saved({ id: "team-ppio-compat", protocol: "openai" }));
+ const convert = vi.spyOn(api, "activateAgentWithConversion").mockResolvedValue({
+ ok: true, agent: "codex", config: "/c", provider: "bootagent-converter-responses", model: "gpt-5.6-sol",
+ restart: "", next: "", upstreamVerified: true, endToEndVerified: true,
+ });
+ renderPage([profile()]);
+
+ await userEvent.click(screen.getByRole("button", { name: /检测模型/ }));
+ await userEvent.click(await screen.findByRole("button", { name: "使用兼容模式" }));
+ await waitFor(() => expect(convert).toHaveBeenCalledWith("codex", "team-ppio-compat"));
+ expect(saveProfile).toHaveBeenCalledWith(expect.objectContaining({
+ id: "team-ppio-compat", provider: "ppio", model: "deepseek/deepseek-v3", protocol: "openai",
+ }));
+ expect(await screen.findByRole("heading", { name: "overview" })).toBeTruthy();
+ });
});
diff --git a/frontend/src/pages/AgentProfilePage.tsx b/frontend/src/pages/AgentProfilePage.tsx
index 4da30611..91a90ffa 100644
--- a/frontend/src/pages/AgentProfilePage.tsx
+++ b/frontend/src/pages/AgentProfilePage.tsx
@@ -2,7 +2,7 @@ import { Check, Pencil, Plus, Save, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { useNavigate, useParams } from "react-router-dom";
-import { api, describeFailure } from "../backend/api";
+import { api } from "../backend/api";
import { ModelCheckButton, ModelCheckNotice } from "../components/ModelCheckNotice";
import { PageScaffold } from "../components/PageScaffold";
import { ProviderModelPicker } from "../components/ProviderModelPicker";
@@ -10,9 +10,11 @@ import { ProviderSegment } from "../components/ProviderSegment";
import { SelectField } from "../components/SelectField";
import { useI18n } from "../i18n";
import { desktopApps, desktopProfileUsable, desktopProfiles, desktopProtocol, profileAgentIdForDesktop } from "../state/desktopSetup";
-import { confirmAction } from "../state/confirmDelete";
import { byProfileCreatedAt, byProviderCreatedAt, preferProviderWithKey } from "../state/ranking";
-import { converterProfileName, isConverterID } from "../state/conversion";
+import { applyConversion, confirmConversion, conversionTargets } from "../state/applyConversion";
+import { canConvertProtocol, conversionTargetFor, converterProfileName, isConverterID, providerDisplayName } from "../state/conversion";
+import { useFeedback } from "../state/FeedbackContext";
+import { saveReceipt } from "../state/saveReceipt";
import { useWizard } from "../state/WizardContext";
import type { DesktopAgentProfileAssessment, ProfileModelCheck, ProfileSummary, ProtocolId, ProviderId } from "../types/api";
@@ -63,6 +65,9 @@ export function AgentProfilePage() {
const navigate = useNavigate();
const { locale, t } = useI18n();
const { state, refreshStatus } = useWizard();
+ const feedback = useFeedback();
+ // Stable across receipts, unlike `feedback`, so an effect can depend on it.
+ const reportFailure = feedback.failure;
const status = state.status;
const app = status ? desktopApps(status).find((candidate) => candidate.id === agentId) || null : null;
const owner = app ? profileAgentIdForDesktop(app) : agentId;
@@ -73,7 +78,6 @@ export function AgentProfilePage() {
const [selectedId, setSelectedId] = useState("");
const [draft, setDraft] = useState(null);
const [busy, setBusy] = useState(false);
- const [failure, setFailure] = useState("");
// The model of the selected Profile, edited in place. null means "showing what
// is stored"; a string means the field has been touched and not yet committed.
const [modelDraft, setModelDraft] = useState(null);
@@ -96,23 +100,37 @@ export function AgentProfilePage() {
const profiles = useMemo(() => {
if (!status) return [];
const protocol = catalog?.protocol || "";
- const result = app ? desktopProfiles(status, app) : status.profiles.filter((profile) => profile.protocol === protocol);
- return byProfileCreatedAt(result);
+ // A command-line Agent speaking its own format can also use a Chat
+ // Completions Profile, through compatibility mode. The adapter's own
+ // Profiles never appear: an Agent in compatibility mode is shown on the
+ // Profile its requests go to, which is the one a user would pick again.
+ const result = app
+ ? desktopProfiles(status, app)
+ : status.profiles.filter((profile) => profile.protocol === protocol || (canConvertProtocol(protocol) && profile.protocol === "openai"));
+ return byProfileCreatedAt(result.filter((profile) => !isConverterID(profile.id)));
}, [app, catalog?.protocol, status]);
+ // Bound to its converter Profile, an Agent in compatibility mode is
+ // preselected on that route's target instead.
+ const boundId = app?.profileId || currentAgent?.profileId || "";
+ const conversionTarget = boundId && isConverterID(boundId) && status ? conversionTargetFor(status, app?.id || owner) : undefined;
+ const currentId = conversionTarget?.id || boundId;
useEffect(() => {
if (!selectedId) {
- const current = app?.profileId || currentAgent?.profileId || "";
- if (current && profiles.some((profile) => profile.id === current)) setSelectedId(current);
+ if (currentId && profiles.some((profile) => profile.id === currentId)) setSelectedId(currentId);
else if (profiles[0]) setSelectedId(profiles[0].id);
}
- }, [app?.profileId, currentAgent?.profileId, profiles, selectedId]);
+ }, [currentId, profiles, selectedId]);
const selected = profiles.find((profile) => profile.id === selectedId);
- const requiresConversion = Boolean(app?.id === "claude-desktop" && selected?.protocol === "openai");
+ // Claude Desktop is assessed first; a command-line Agent is checked when
+ // applied, because every check is a billed request (ConfigureAgentWithConversion).
+ const desktopConversion = Boolean(app?.id === "claude-desktop" && selected?.protocol === "openai");
+ const cliConversion = Boolean(!app && canConvertProtocol(protocol) && selected?.protocol === "openai");
+ const requiresConversion = desktopConversion || cliConversion;
useEffect(() => {
- if (!app || !selected || !requiresConversion) {
+ if (!app || !selected || !desktopConversion) {
setAssessment(null);
setAssessing(false);
return;
@@ -123,12 +141,12 @@ export function AgentProfilePage() {
void api.assessDesktopAgentProfile(app.id, selected.id).then((result) => {
if (active) setAssessment(result);
}).catch((error) => {
- if (active) setFailure(describeFailure(error, t("无法检查协议兼容性"), t).message);
+ if (active) reportFailure(error, t("无法确认能否使用兼容模式"), { key: `assess:${app.id}:${selected.id}` });
}).finally(() => {
if (active) setAssessing(false);
});
return () => { active = false; };
- }, [app, requiresConversion, selected, t]);
+ }, [app, desktopConversion, reportFailure, selected, t]);
if (!status) {
return (
@@ -150,7 +168,7 @@ export function AgentProfilePage() {
const duplicateID = Boolean(draft && !draft.originalId && status.profiles.some((profile) => profile.id === draft.id.trim().toLowerCase()));
const canSave = Boolean(draft?.id.trim() && draft?.provider && draft?.model.trim() && !duplicateID);
const canApply = Boolean(selected && desktopProfileUsable(status, selected, app) && (
- !requiresConversion || assessment?.compatibility === "convertible"
+ !desktopConversion || assessment?.compatibility === "convertible"
));
const separator = locale === "en" ? ", " : "、";
@@ -165,7 +183,7 @@ export function AgentProfilePage() {
* the Profile showed nothing at all. Nothing is sent to the model: that is
* what 检测模型 is for.
*/
- const persistProfile = async (request: SaveRequest, invalidateCheck = true) => {
+ const persistProfile = async (request: SaveRequest, invalidateCheck = true, announce = true) => {
if (invalidateCheck) {
checkGeneration.current += 1;
setChecking(false);
@@ -173,13 +191,12 @@ export function AgentProfilePage() {
if (checked?.profileId === request.id) setChecked(null);
const before = status.profiles.find((profile) => profile.id === request.id);
const result = await api.saveProfile(request);
- const failures = Object.entries(result.failures ?? {});
- if (failures.length) {
- setFailure(t("{agents} 重新应用失败:{message}", {
- agents: failures.map(([id]) => nameOf(id)).join(separator),
- message: failures[0][1] ?? "",
- }));
- }
+ // The receipt names every Agent the save rewrote, which is the only sign
+ // that a model changed here also changed it for the other Agents on this
+ // Profile. A save that is only the first half of 应用 or 检测模型 stays quiet
+ // on success: that action reports for both.
+ const receipt = saveReceipt({ key: `profile:${request.id}`, name: request.label || request.id, result, nameOf, t, separator });
+ if (announce || receipt.tone !== "success") feedback.show(receipt);
const edit = before && before.provider === request.provider && before.model && before.model !== request.model
? { profileId: request.id, previousModel: before.model, request }
: null;
@@ -197,13 +214,12 @@ export function AgentProfilePage() {
if (current?.model !== checked.model || current.provider !== lastEdit.request.provider) return;
const request = { ...lastEdit.request, model: checked.previousModel };
setBusy(true);
- setFailure("");
try {
await persistProfile(request);
setChecked(null);
await refreshStatus();
} catch (error) {
- setFailure(describeFailure(error, t("无法保存配置模版"), t).message);
+ feedback.failure(error, t("无法保存配置模版"), { key: `profile:${request.id}` });
} finally {
setBusy(false);
}
@@ -220,7 +236,6 @@ export function AgentProfilePage() {
let id = baseID;
let suffix = 2;
while (ids.has(id)) id = `${baseID}-${suffix++}`;
- setFailure("");
setDraft({
id,
label: t("{name} 配置模版", { name: targetName }),
@@ -234,7 +249,6 @@ export function AgentProfilePage() {
const openEdit = (profile: ProfileSummary) => {
if (isConverterID(profile.id)) return;
- setFailure("");
setDraft(draftFrom(profile));
};
@@ -242,7 +256,6 @@ export function AgentProfilePage() {
event.preventDefault();
if (!draft || !canSave) return;
setBusy(true);
- setFailure("");
try {
const { result: saved } = await persistProfile({
id: draft.id.trim().toLowerCase(),
@@ -260,7 +273,7 @@ export function AgentProfilePage() {
setDraft(null);
await refreshStatus();
} catch (error) {
- setFailure(describeFailure(error, t("无法保存配置模版"), t).message);
+ feedback.failure(error, t("无法保存配置模版"), { key: `profile:${draft.id.trim().toLowerCase()}` });
} finally {
setBusy(false);
}
@@ -274,12 +287,11 @@ export function AgentProfilePage() {
* write a Profile per letter typed. Everything else about the Profile is passed
* through unchanged, so this cannot quietly reset a field the editor owns.
*/
- const commitModel = async (profile: ProfileSummary, next: string, invalidateCheck = true): Promise => {
+ const commitModel = async (profile: ProfileSummary, next: string, invalidateCheck = true, announce = true): Promise => {
const model = next.trim();
setModelDraft(null);
if (!model || model === (profile.model || "")) return { kind: "unchanged" };
setSavingModel(true);
- setFailure("");
try {
const { edit } = await persistProfile({
id: profile.id,
@@ -292,11 +304,11 @@ export function AgentProfilePage() {
context1M: Boolean(profile.context1M),
configMode: "provider",
protocol: profile.protocol || (app ? desktopProtocol(app) : catalog?.protocol || ""),
- }, invalidateCheck);
+ }, invalidateCheck, announce);
await refreshStatus();
return { kind: "saved", model, edit };
} catch (error) {
- setFailure(describeFailure(error, t("无法保存配置模版"), t).message);
+ feedback.failure(error, t("无法保存配置模版"), { key: `profile:${profile.id}` });
return { kind: "failed" };
} finally {
setSavingModel(false);
@@ -312,18 +324,17 @@ export function AgentProfilePage() {
if (!selected || checking || busy || savingModel) return;
const generation = ++checkGeneration.current;
setChecking(true);
- setFailure("");
try {
// This save belongs to the check; other saves and leaving the page
// invalidate its generation, including while this flush is awaiting.
- const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft, false) : { kind: "unchanged" };
+ const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft, false, false) : { kind: "unchanged" };
if (flushed.kind === "failed" || checkGeneration.current !== generation) return;
const check = await api.checkProfileModel(selected.id, [app?.id || owner]);
if (checkGeneration.current !== generation) return;
const edit = flushed.kind === "saved" ? flushed.edit : lastEdit;
setChecked({ ...check, previousModel: edit?.profileId === selected.id && edit.request.model === check.model ? edit.previousModel : undefined });
} catch (error) {
- if (checkGeneration.current === generation) setFailure(describeFailure(error, t("无法检测模型"), t).message);
+ if (checkGeneration.current === generation) feedback.failure(error, t("无法检测模型"), { key: `check:${selected.id}` });
} finally {
if (checkGeneration.current === generation) setChecking(false);
}
@@ -335,10 +346,9 @@ export function AgentProfilePage() {
// left 应用 enabled while the save was in flight, so a second click started
// a second Apply.
setBusy(true);
- setFailure("");
// An uncommitted inline model edit is flushed first, so clicking 应用 straight
// after typing applies what is on screen rather than the older stored model.
- const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft) : { kind: "unchanged" };
+ const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft, true, false) : { kind: "unchanged" };
if (flushed.kind === "failed") {
// The Profile still holds the old model; applying now would apply that
// while the field showed the new one. The save's error is already shown.
@@ -349,22 +359,20 @@ export function AgentProfilePage() {
// before the click, and activating with it would write the old model back
// over the Agents the flush had just moved to the new one.
const model = flushed.kind === "saved" ? flushed.model : selected.model || "";
+ // Set by a desktop app that only reads its settings at startup. The backend
+ // says so for every managed write; dropping it left the user believing the
+ // running app had already switched.
+ let restart = "";
try {
- if (app) {
- if (requiresConversion) {
- if (!await confirmAction({
- title: t("启用协议适配"),
- message: t("BootAgent 将在本机启动协议适配服务,并自动把 Claude Desktop 指向该服务。是否继续?"),
- confirmLabel: t("启用并应用"),
- cancelLabel: t("取消"),
- })) {
- setBusy(false);
- return;
- }
- await api.configureDesktopAgentWithConversion(app.id, selected.id);
- } else {
- await api.configureDesktopAgent(app.id, selected.id);
+ if (requiresConversion) {
+ if (!await confirmConversion(t)) {
+ setBusy(false);
+ return;
}
+ if (app) restart = (await api.configureDesktopAgentWithConversion(app.id, selected.id))?.restart || "";
+ else await api.activateAgentWithConversion(owner, selected.id);
+ } else if (app) {
+ restart = (await api.configureDesktopAgent(app.id, selected.id))?.restart || "";
} else {
await api.activateAgent(owner, {
provider: selected.provider,
@@ -376,15 +384,41 @@ export function AgentProfilePage() {
}
await refreshStatus();
} catch (error) {
- setFailure(describeFailure(error, t("应用配置模版失败"), t).message);
+ // Stays on this page: the choice that failed is what the user may change.
+ feedback.failure(error, t("应用配置模版失败"), { key: `apply:${agentId}` });
setBusy(false);
return;
}
// Straight back to the overview, which is where the result is visible: the
- // Agent's row now names this Profile. Staying here left the user on a
- // screen whose job was done, with a success notice as the only feedback and
- // a second click needed to see the effect. `replace` so Back does not
- // return to a selection that has already been applied.
+ // Agent's row now names this Profile. The receipt outlives this page, so
+ // the switch is also said in words rather than left for the user to spot in
+ // the row. `replace` so Back does not return to a selection that has
+ // already been applied.
+ feedback.show(restart
+ ? { key: `apply:${agentId}`, tone: "warning", message: t("已应用,重启 {name} 后生效", { name: targetName }) }
+ : { key: `apply:${agentId}`, tone: "success", message: t("{agent} 已改用「{profile}」", { agent: targetName, profile: displayProfileName(selected) }) });
+ navigate("/overview", { replace: true });
+ };
+
+ /**
+ * The remedy a failed check offers: the checked Profile's Provider and model,
+ * through compatibility mode. A Chat Completions Profile for them is reused
+ * or saved first, since that is what the adapter forwards to.
+ */
+ const useConversion = async () => {
+ const source = checked && status.profiles.find((profile) => profile.id === checked.profileId);
+ if (!source || busy) return;
+ if (!await confirmConversion(t)) return;
+ setBusy(true);
+ try {
+ await applyConversion(status, conversionTargets(status, [app?.id || owner]), source, t);
+ await refreshStatus();
+ } catch (error) {
+ feedback.failure(error, t("无法开启兼容模式"), { key: `apply:${agentId}` });
+ setBusy(false);
+ return;
+ }
+ feedback.show({ key: `apply:${agentId}`, tone: "success", message: t("{agent} 已改用兼容模式", { agent: targetName }) });
navigate("/overview", { replace: true });
};
@@ -393,7 +427,7 @@ export function AgentProfilePage() {
title={t("选择配置模版")}
backLabel={t("返回总览")}
onBack={() => navigate("/overview")}
- primaryLabel={busy ? t("应用中") : requiresConversion ? t("启用协议适配并应用") : t("应用")}
+ primaryLabel={busy ? t("应用中") : requiresConversion ? t("用兼容模式应用") : t("应用")}
onPrimary={() => void apply()}
primaryDisabled={!canApply || busy || savingModel || checking}
footerNote={selected ? displayProfileName(selected) : t("选择一个配置模版")}
@@ -405,7 +439,6 @@ export function AgentProfilePage() {
)}
>
- {failure ?
) : null}
@@ -529,7 +570,7 @@ export function AgentProfilePage() {
common change -- same Profile, different model -- costs no
trip through the editor. The others stay one line of text;
a picker on every card would be a wall of inputs. */}
-
);
})}
diff --git a/frontend/src/pages/ProfilesPage.test.tsx b/frontend/src/pages/ProfilesPage.test.tsx
index dac35d9c..342ed825 100644
--- a/frontend/src/pages/ProfilesPage.test.tsx
+++ b/frontend/src/pages/ProfilesPage.test.tsx
@@ -1,8 +1,9 @@
-import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
import { api } from "../backend/api";
+import { FeedbackProvider } from "../state/FeedbackContext";
import type { SaveProfileResult, ProfileSummary, StatusResponse } from "../types/api";
import { ProfilesPage } from "./ProfilesPage";
@@ -95,16 +96,25 @@ function renderPage(profiles: ProfileSummary[]) {
mockState = { status: statusWith(profiles), statusState: "success" };
dispatch.mockClear();
render(
-
-
- } />
- onboarding} />
- overview} />
-
- ,
+
+
+
+ } />
+ onboarding} />
+ overview} />
+
+
+ ,
);
}
+/** Opens the open receipt's 详情 and returns the receipt. */
+function receiptWithDetail() {
+ const receipt = screen.getByRole("alert");
+ fireEvent.click(within(receipt).getByRole("button", { name: "详情" }));
+ return receipt;
+}
+
describe("ProfilesPage", () => {
afterEach(() => {
vi.restoreAllMocks();
@@ -188,7 +198,9 @@ describe("ProfilesPage", () => {
it("explains why an in-use Profile cannot be deleted", () => {
renderPage([profile()]);
fireEvent.click(screen.getByRole("button", { name: "删除 团队 PPIO" }));
- expect(screen.getByText(/配置模版正在被.*使用,无法删除/)).toBeTruthy();
+ const receipt = receiptWithDetail();
+ expect(receipt).toHaveTextContent("「团队 PPIO」正在使用,无法删除");
+ expect(receipt).toHaveTextContent(/使用它的 Agent:.*Codex/);
});
it("creates a Profile inline without entering onboarding", async () => {
@@ -264,7 +276,11 @@ describe("ProfilesPage", () => {
fireEvent.click(screen.getByRole("button", { name: "编辑 团队 PPIO" }));
fireEvent.click(screen.getByRole("button", { name: "保存配置模版" }));
- await waitFor(() => expect(screen.getByText(/已重新应用到.*Codex/)).toBeTruthy());
+ // A success, so a polite receipt rather than an alert; the Agents it
+ // rewrote are behind 详情.
+ const receipt = (await screen.findByText("已保存,1 个 Agent 已更新")).closest(".feedback-toast") as HTMLElement;
+ fireEvent.click(within(receipt).getByRole("button", { name: "详情" }));
+ expect(receipt).toHaveTextContent("Codex");
});
it("reports a Profile edit whose reapply failed", async () => {
@@ -275,7 +291,8 @@ describe("ProfilesPage", () => {
fireEvent.click(screen.getByRole("button", { name: "编辑 团队 PPIO" }));
fireEvent.click(screen.getByRole("button", { name: "保存配置模版" }));
- await waitFor(() => expect(screen.getByText(/Codex.*重新应用失败.*写入失败/)).toBeTruthy());
+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("已保存,1 个 Agent 未能更新"));
+ expect(receiptWithDetail()).toHaveTextContent("Codex: 写入失败");
});
// The editor is a page of its own. The list used to stay rendered below the
diff --git a/frontend/src/pages/ProfilesPage.tsx b/frontend/src/pages/ProfilesPage.tsx
index c03d72de..64f82dd0 100644
--- a/frontend/src/pages/ProfilesPage.tsx
+++ b/frontend/src/pages/ProfilesPage.tsx
@@ -2,7 +2,7 @@ import { KeyRound, Layers, Pencil, Plus, Save, Trash2, X } from "lucide-react";
import { useEffect, useRef, useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
-import { api, describeFailure } from "../backend/api";
+import { api } from "../backend/api";
import { CardUsers } from "../components/CardUsers";
import { ModelCheckButton, ModelCheckNotice } from "../components/ModelCheckNotice";
import { PageScaffold } from "../components/PageScaffold";
@@ -10,7 +10,10 @@ import { ProviderModelPicker } from "../components/ProviderModelPicker";
import { ProviderSegment } from "../components/ProviderSegment";
import { SelectField } from "../components/SelectField";
import { useI18n } from "../i18n";
+import { applyConversion, confirmConversion, conversionTargets } from "../state/applyConversion";
import { confirmDelete } from "../state/confirmDelete";
+import { useFeedback } from "../state/FeedbackContext";
+import { saveReceipt } from "../state/saveReceipt";
import { byProviderCreatedAt, preferProviderWithKey } from "../state/ranking";
import { isConverterID } from "../state/conversion";
import { useWizard } from "../state/WizardContext";
@@ -60,8 +63,8 @@ export function ProfilesPage() {
const status = state.status;
const [editor, setEditor] = useState(null);
const [busy, setBusy] = useState(false);
- const [failure, setFailure] = useState("");
- const [applied, setApplied] = useState("");
+ const feedback = useFeedback();
+ const separator = locale === "en" ? ", " : "、";
// A check runs only when the user presses 检测模型: it is a billed request.
const [checked, setChecked] = useState(null);
const [checkingId, setCheckingId] = useState("");
@@ -121,8 +124,6 @@ export function ProfilesPage() {
const openCreate = () => {
const [provider = "ppio", providerMeta] = preferProviderWithKey(byProviderCreatedAt(Object.fromEntries(Object.entries(status.providers).filter(([providerId]) => !isConverterID(providerId))))) || [];
- setFailure("");
- setApplied("");
setEditor({
id: suggestProfileID(provider),
label: suggestProfileLabel(provider),
@@ -184,18 +185,7 @@ export function ProfilesPage() {
setLastEdit(before && before.provider === request.provider && before.model && before.model !== request.model
? { profileId: request.id, previousModel: before.model, request }
: null);
- const reapplied = result.reapplied ?? [];
- const failures = Object.entries(result.failures ?? {});
- if (failures.length) {
- setFailure(t("{agents} 重新应用失败:{message}", {
- agents: failures.map(([agentId]) => nameOf(agentId)).join(locale === "en" ? ", " : "、"),
- message: failures[0][1] ?? "",
- }));
- } else if (reapplied.length) {
- setApplied(t("已重新应用到 {agents}", {
- agents: reapplied.map(nameOf).join(locale === "en" ? ", " : "、"),
- }));
- }
+ feedback.show(saveReceipt({ key: `profile:${request.id}`, name: request.label || request.id, result, nameOf, t, separator }));
await refreshStatus();
};
@@ -203,8 +193,6 @@ export function ProfilesPage() {
event.preventDefault();
if (!editor || !canSave) return;
setBusy(true);
- setFailure("");
- setApplied("");
try {
await persist({
id: editor.id.trim().toLowerCase(),
@@ -220,7 +208,8 @@ export function ProfilesPage() {
});
setEditor(null);
} catch (error) {
- setFailure(describeFailure(error, t("无法保存配置模版"), t).message);
+ // The editor stays open with what was typed, so the save can be retried.
+ feedback.failure(error, t("无法保存配置模版"), { key: `profile:${editor.id.trim().toLowerCase()}` });
} finally {
setBusy(false);
}
@@ -229,14 +218,13 @@ export function ProfilesPage() {
const checkModel = async (profileId: string) => {
const generation = ++checkGeneration.current;
setCheckingId(profileId);
- setFailure("");
try {
const check = await api.checkProfileModel(profileId);
if (checkGeneration.current !== generation) return;
const edit = lastEdit?.profileId === profileId && lastEdit.request.model === check.model ? lastEdit : null;
setChecked({ ...check, previousModel: edit?.previousModel });
} catch (error) {
- if (checkGeneration.current === generation) setFailure(describeFailure(error, t("无法检测模型"), t).message);
+ if (checkGeneration.current === generation) feedback.failure(error, t("无法检测模型"), { key: `check:${profileId}` });
} finally {
if (checkGeneration.current === generation) setCheckingId("");
}
@@ -250,23 +238,45 @@ export function ProfilesPage() {
if (current?.model !== checked.model || current.provider !== lastEdit.request.provider) return;
const request = { ...lastEdit.request, model: checked.previousModel };
setBusy(true);
- setFailure("");
- setApplied("");
try {
await persist(request);
setChecked(null);
} catch (error) {
- setFailure(describeFailure(error, t("无法保存配置模版"), t).message);
+ feedback.failure(error, t("无法保存配置模版"), { key: `profile:${request.id}` });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ /**
+ * The remedy a failed check offers here: every Agent the check covered that
+ * compatibility mode can serve is switched to it, forwarding to this
+ * Profile's Provider and model.
+ */
+ const useConversion = async (check: ProfileModelCheck) => {
+ const source = status.profiles.find((profile) => profile.id === check.profileId);
+ const targets = conversionTargets(status, check.agents);
+ if (!source || !targets.length || busy) return;
+ const names = targets.map(nameOf);
+ if (!await confirmConversion(t)) return;
+ setBusy(true);
+ const key = `conversion:${check.profileId}`;
+ try {
+ await applyConversion(status, targets, source, t);
+ setChecked(null);
+ feedback.show({ key, tone: "success", message: t("{agent} 已改用兼容模式", { agent: names.join(separator) }) });
+ await refreshStatus();
+ } catch (error) {
+ feedback.failure(error, t("无法开启兼容模式"), { key });
} finally {
setBusy(false);
}
};
const remove = async (profile: ProfileSummary, users: typeof configurableAgents) => {
+ const key = `profile:${profile.id}`;
if (users.length) {
- setFailure(t("配置模版正在被 {agents} 使用,无法删除", {
- agents: users.map((agent) => agent.name).join(locale === "en" ? ", " : "、"),
- }));
+ feedback.show({ key, tone: "warning", message: t("「{name}」正在使用,无法删除", { name: profile.label }), detail: t("使用它的 Agent:{agents}", { agents: users.map((agent) => agent.name).join(separator) }) });
return;
}
// Asked after the in-use check, so a Profile that cannot be deleted anyway
@@ -278,13 +288,13 @@ export function ProfilesPage() {
cancelLabel: t("取消"),
})) return;
setBusy(true);
- setFailure("");
try {
await api.deleteProfile(profile.id);
if (editor?.originalId === profile.id) setEditor(null);
+ feedback.show({ key, tone: "success", message: t("已删除「{name}」", { name: profile.label }) });
await refreshStatus();
} catch (error) {
- setFailure(describeFailure(error, t("无法删除配置模版"), t).message);
+ feedback.failure(error, t("无法删除配置模版"), { key });
} finally {
setBusy(false);
}
@@ -429,11 +439,6 @@ export function ProfilesPage() {
) : null}
- {failure ?
{failure}
: null}
- {/* The editor is a page of its own: the list, and notices about what
- happened to it, return when the editor closes. Rendering them below
- the form read as the previous page appended to this one. */}
- {applied && !editor ?
{t("应用完成")}{applied}
: null}
{checked && !editor ? (
void revertModel()}
onRecheck={() => void checkModel(checked.profileId)}
+ onUseConversion={conversionTargets(status, checked.agents).length ? () => void useConversion(checked) : undefined}
onDismiss={() => setChecked(null)}
/>
) : null}
@@ -469,7 +475,7 @@ export function ProfilesPage() {
{status.providers[profile.provider]?.has_key ? t("模型服务已有 Key") : t("模型服务缺少 Key")}
- { setEditor(editDraft(profile, protocolOf(profile))); setFailure(""); setApplied(""); }} aria-label={t("编辑 {name}", { name: profile.label })} title={t("编辑")}>
+ { setEditor(editDraft(profile, protocolOf(profile))); }} aria-label={t("编辑 {name}", { name: profile.label })} title={t("编辑")}>
{/* disabled while busy: without it a double-click sent two
diff --git a/frontend/src/pages/ProviderKeyPage.test.tsx b/frontend/src/pages/ProviderKeyPage.test.tsx
index 9e18c713..e551c57b 100644
--- a/frontend/src/pages/ProviderKeyPage.test.tsx
+++ b/frontend/src/pages/ProviderKeyPage.test.tsx
@@ -1,8 +1,10 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { MemoryRouter } from "react-router-dom";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
import { api } from "../backend/api";
+import { BootAgentApiError } from "../backend/errors";
+import { FeedbackProvider } from "../state/FeedbackContext";
import { initialWizardState, wizardReducer, type WizardAction, type WizardState } from "../state/wizardReducer";
import type { StatusResponse } from "../types/api";
import { ProviderKeyPage } from "./ProviderKeyPage";
@@ -27,6 +29,28 @@ const status = {
catalog: [],
} as unknown as StatusResponse;
+// Built-in Providers as the protocol table describes them: Chat Completions is
+// confirmed on both, OpenAI Responses (what Codex speaks) only on the second.
+const tabledStatus = {
+ providers: {
+ jiekou: {
+ name: "JieKou.AI", home: "", base_url: "https://api.jiekou.test/openai", has_key: true,
+ protocols: { openai: "implementation-supported", anthropic: "implementation-supported", responses: "route-present-unverified" },
+ },
+ deepseek: {
+ name: "DeepSeek", home: "", base_url: "https://api.deepseek.test", has_key: true,
+ protocols: { openai: "implementation-supported", anthropic: "implementation-supported", responses: "implementation-supported" },
+ },
+ },
+ catalog: [{ id: "codex", name: "Codex", protocol: "responses", configMode: "auto", selectsModel: true }],
+} as unknown as StatusResponse;
+
+const codexOn = (provider: string, patch: Partial = {}): WizardState => ({
+ ...initialWizardState, status: tabledStatus, statusState: "success", setupKind: "cli", selectedAgentIds: ["codex"], provider, ...patch,
+});
+
+const SUGGESTION = "尚未确认 JieKou.AI 支持 Codex 的请求格式(OpenAI Responses),可以改用兼容模式,由 BootAgent 在本机转换";
+
/** Pins the selected Provider to the one this fixture defines. Inheriting the
* wizard's initial Provider instead coupled these cases to whichever Provider
* ships first in providers.lock.json: when that changed, every case here looked
@@ -45,6 +69,202 @@ vi.mock("../state/WizardContext", () => ({
describe("ProviderKeyPage", () => {
afterEach(() => vi.restoreAllMocks());
+ // A Chat Completions-only service used to leave Codex users with a failure
+ // that pointed at "another API type" the wizard has no control for, and a
+ // Continue button that installed an Agent which then failed on first use.
+ it("offers compatibility mode when Codex's format fails but Chat Completions works", async () => {
+ const codexStatus = {
+ ...status,
+ catalog: [{ id: "codex", name: "Codex", protocol: "responses", configMode: "auto", selectsModel: true }],
+ } as unknown as StatusResponse;
+ state = { ...baseState, status: codexStatus, statusState: "success", setupKind: "cli", selectedAgentIds: ["codex"] };
+ keyRef.current = "";
+ vi.spyOn(api, "probe").mockResolvedValue({
+ ok: false, reachable: true, status: 404, message: "Model does not support OpenAI Responses.",
+ error_code: "PROTOCOL_UNSUPPORTED", retryable: false, convertible: ["responses"],
+ });
+ const page = render();
+
+ fireEvent.click(screen.getByRole("button", { name: "测试连接" }));
+ await waitFor(() => expect(state.connectionState).toBe("error"));
+ page.rerender();
+
+ expect(screen.getByText("Codex 不能直接使用这个模型服务,BootAgent 可以在本机转换后使用")).toBeTruthy();
+ // The plain failure, which tells the user to switch API type, is replaced.
+ expect(screen.queryByText("这个模型不支持所选的 API 类型")).toBeNull();
+ expect(screen.getByRole("button", { name: "继续选择模型" })).toBeDisabled();
+
+ fireEvent.click(screen.getByRole("button", { name: "使用兼容模式" }));
+ page.rerender();
+ expect(state.conversion).toBe(true);
+ expect(screen.getByText("已选择兼容模式,使用 Codex 时需要保持 BootAgent 运行")).toBeTruthy();
+ expect(screen.getByRole("button", { name: "继续选择模型" })).toBeEnabled();
+ });
+
+ it("keeps the plain failure when compatibility mode cannot help", async () => {
+ const codexStatus = {
+ ...status,
+ catalog: [{ id: "codex", name: "Codex", protocol: "responses", configMode: "auto", selectsModel: true }],
+ } as unknown as StatusResponse;
+ state = { ...baseState, status: codexStatus, statusState: "success", setupKind: "cli", selectedAgentIds: ["codex"] };
+ keyRef.current = "";
+ vi.spyOn(api, "probe").mockResolvedValue({
+ ok: false, reachable: true, status: 401, message: "API key was rejected (401).",
+ error_code: "API_KEY_REJECTED", retryable: true, convertible: null,
+ });
+ const page = render();
+
+ fireEvent.click(screen.getByRole("button", { name: "测试连接" }));
+ await waitFor(() => expect(state.connectionState).toBe("error"));
+ page.rerender();
+
+ expect(screen.queryByRole("button", { name: "使用兼容模式" })).toBeNull();
+ expect(screen.getByRole("button", { name: "继续选择模型" })).toBeEnabled();
+ });
+
+ // The connection test is optional, so a first-time user who skipped it got no
+ // word about compatibility mode and installed a Codex that failed on its first
+ // request. The protocol table answers the same question without a request.
+ it("suggests compatibility mode from the protocol table, without a connection test", () => {
+ state = codexOn("jiekou");
+ keyRef.current = "";
+ const probe = vi.spyOn(api, "probe");
+ const models = vi.spyOn(api, "models").mockResolvedValue({ ok: true, reachable: true, status: 200, message: "", error_code: null, retryable: false, models: [] });
+ const page = render();
+
+ expect(screen.getByText(SUGGESTION)).toBeTruthy();
+ // "Not confirmed" is all the table can say; it has not shown a failure.
+ expect(screen.queryByText(/不能直接使用/)).toBeNull();
+ expect(screen.queryByRole("alert")).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "使用兼容模式" }));
+ page.rerender();
+ expect(state.conversion).toBe(true);
+ expect(screen.getByText("已选择兼容模式,使用 Codex 时需要保持 BootAgent 运行")).toBeTruthy();
+ expect(screen.queryByText(SUGGESTION)).toBeNull();
+ expect(screen.getByRole("button", { name: "继续选择模型" })).toBeEnabled();
+
+ // Billed requests start from a button the user pressed, never from a guess.
+ expect(probe).not.toHaveBeenCalled();
+ // Listing models is the page's existing unbilled lookup, not a probe.
+ expect(models.mock.calls.length).toBeLessThanOrEqual(1);
+ });
+
+ it("lets the user continue without taking the untested suggestion", async () => {
+ state = codexOn("jiekou");
+ keyRef.current = "";
+ const probe = vi.spyOn(api, "probe");
+ vi.spyOn(api, "models").mockResolvedValue({ ok: true, reachable: true, status: 200, message: "", error_code: null, retryable: false, models: [] });
+ render(
+
+
+ } />
+ model step} />
+
+ ,
+ );
+
+ expect(screen.getByText(SUGGESTION)).toBeTruthy();
+ const next = screen.getByRole("button", { name: "继续选择模型" });
+ expect(next).toBeEnabled();
+ fireEvent.click(next);
+
+ expect(await screen.findByRole("heading", { name: "model step" })).toBeTruthy();
+ expect(state.conversion).toBe(false);
+ expect(probe).not.toHaveBeenCalled();
+ });
+
+ it("makes no suggestion when the Provider has confirmed the Agent's format", () => {
+ state = codexOn("deepseek");
+ keyRef.current = "";
+ vi.spyOn(api, "models").mockResolvedValue({ ok: true, reachable: true, status: 200, message: "", error_code: null, retryable: false, models: [] });
+ render();
+
+ expect(screen.queryByText(/尚未确认/)).toBeNull();
+ expect(screen.queryByRole("button", { name: "使用兼容模式" })).toBeNull();
+ expect(screen.getByRole("button", { name: "继续选择模型" })).toBeEnabled();
+ });
+
+ it("makes no suggestion for a custom Provider, which has no protocol table", () => {
+ const custom = {
+ ...tabledStatus,
+ providers: { mine: { name: "Mine", home: "", base_url: "https://api.mine.test/v1", has_key: true, custom: true } },
+ } as unknown as StatusResponse;
+ state = codexOn("mine", { status: custom });
+ keyRef.current = "";
+ vi.spyOn(api, "models").mockResolvedValue({ ok: true, reachable: true, status: 200, message: "", error_code: null, retryable: false, models: [] });
+ render();
+
+ expect(screen.queryByText(/尚未确认/)).toBeNull();
+ expect(screen.queryByRole("button", { name: "使用兼容模式" })).toBeNull();
+ });
+
+ // Only the untested suggestion is optional. Once a test has shown the Agent's
+ // format failing while Chat Completions works, the choice is required again.
+ it("requires the choice once a connection test has actually failed", async () => {
+ state = codexOn("jiekou");
+ keyRef.current = "";
+ vi.spyOn(api, "models").mockResolvedValue({ ok: true, reachable: true, status: 200, message: "", error_code: null, retryable: false, models: [] });
+ vi.spyOn(api, "probe").mockResolvedValue({
+ ok: false, reachable: true, status: 404, message: "Model does not support OpenAI Responses.",
+ error_code: "PROTOCOL_UNSUPPORTED", retryable: false, convertible: ["responses"],
+ });
+ const page = render();
+ expect(screen.getByRole("button", { name: "继续选择模型" })).toBeEnabled();
+
+ fireEvent.click(screen.getByRole("button", { name: "测试连接" }));
+ await waitFor(() => expect(state.connectionState).toBe("error"));
+ page.rerender();
+
+ expect(screen.queryByText(SUGGESTION)).toBeNull();
+ expect(screen.getByRole("alert")).toHaveTextContent("Codex 不能直接使用这个模型服务,BootAgent 可以在本机转换后使用");
+ expect(screen.getAllByRole("button", { name: "使用兼容模式" })).toHaveLength(1);
+ expect(screen.getByRole("button", { name: "继续选择模型" })).toBeDisabled();
+ });
+
+ it("drops the suggestion once a connection test passes", async () => {
+ state = codexOn("jiekou");
+ keyRef.current = "";
+ vi.spyOn(api, "models").mockResolvedValue({ ok: true, reachable: true, status: 200, message: "", error_code: null, retryable: false, models: [] });
+ vi.spyOn(api, "probe").mockResolvedValue({ ok: true, reachable: true, status: 200, message: "ok", error_code: null, retryable: false });
+ const page = render();
+
+ fireEvent.click(screen.getByRole("button", { name: "测试连接" }));
+ await waitFor(() => expect(state.connectionState).toBe("success"));
+ page.rerender();
+
+ expect(screen.queryByText(SUGGESTION)).toBeNull();
+ expect(screen.queryByRole("button", { name: "使用兼容模式" })).toBeNull();
+ });
+
+ // A first-time user has no key saved, so the key is typed on this same step
+ // and cleared again when Continue saves it. Both used to reset the choice.
+ it("keeps an untested choice while the key is typed and saved", async () => {
+ const noKey = {
+ ...tabledStatus,
+ providers: { jiekou: { ...tabledStatus.providers.jiekou, has_key: false } },
+ } as unknown as StatusResponse;
+ state = codexOn("jiekou", { status: noKey });
+ keyRef.current = "";
+ const save = vi.spyOn(api, "saveProvider").mockResolvedValue({
+ entry: { id: "jiekou", name: "JieKou.AI", home: "", base_url: "https://api.jiekou.test/openai", anthropic_base_url: "", api_key: "", built_in: true },
+ reapplied: [],
+ failures: {},
+ });
+ const page = render();
+
+ fireEvent.click(screen.getByRole("button", { name: "使用兼容模式" }));
+ page.rerender();
+ fireEvent.change(screen.getByLabelText("API Key"), { target: { value: "new-key" } });
+ page.rerender();
+ expect(state.conversion).toBe(true);
+
+ fireEvent.click(screen.getByRole("button", { name: "继续选择模型" }));
+ await waitFor(() => expect(save).toHaveBeenCalledWith(expect.objectContaining({ id: "jiekou", api_key: "new-key" })));
+ await waitFor(() => expect(keyRef.current).toBe(""));
+ expect(state.conversion).toBe(true);
+ });
+
it("uses a custom model name for the connection test", async () => {
state = { ...baseState, status, statusState: "success", hasApiKey: false };
keyRef.current = "test-key";
@@ -174,6 +394,17 @@ describe("ProviderKeyPage", () => {
await waitFor(() => expect(save).toHaveBeenCalledWith(expect.objectContaining({ api_key: "sk-rotated" })));
});
+ it("reports a failed key save as a receipt and stays on the page", async () => {
+ state = { ...baseState, status, statusState: "success", hasApiKey: true };
+ keyRef.current = "sk-rotated";
+ vi.spyOn(api, "saveProvider").mockRejectedValue(new BootAgentApiError("disk full", "CONFIG_WRITE_FAILED", false, 500));
+ render();
+
+ fireEvent.click(screen.getByRole("button", { name: "继续选择模型" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("无法保存模型服务");
+ expect(document.querySelector(".provider-form p")).toBeNull();
+ });
+
it("continues without a save when nothing was typed", async () => {
state = { ...baseState, status, statusState: "success", hasApiKey: true };
keyRef.current = "";
@@ -212,4 +443,46 @@ describe("ProviderKeyPage", () => {
expect(screen.queryByRole("button", { name: "获取 API Key" })).toBeNull();
});
+
+ describe("what a key is, for someone who has never had one", () => {
+ const withoutKey = (provider: Record = {}) => ({
+ ...baseState,
+ status: {
+ ...status,
+ providers: { ppio: { ...status.providers.ppio, has_key: false, key_management_url: "https://ppio.com/settings/key-management", ...provider } },
+ } as unknown as StatusResponse,
+ statusState: "success" as const,
+ });
+ const explainer = () => screen.queryByRole("list", { name: "关于 API Key" });
+
+ it("says what it is, where it comes from and who charges for it", () => {
+ state = withoutKey();
+ render();
+
+ const lines = [...(explainer()?.children ?? [])].map((line) => line.textContent);
+ expect(lines).toEqual([
+ "API Key 是 PPIO 发给你的访问凭证,Agent 用它调用模型",
+ "还没有的话,点「获取 API Key」打开 PPIO 的官方页面,在那里注册并创建",
+ // No amount and no promise: the price is the Provider's to state.
+ "连通测试和 Agent 的每次调用都是真实请求,由 PPIO 按它的价格计费;BootAgent 不收费,也不预估费用",
+ ]);
+ });
+
+ // The second line names a button. Without a published page there is no
+ // button, and the sentence would send the user looking for one.
+ it("does not point at a button that is not there", () => {
+ state = withoutKey({ key_management_url: "", home: "" });
+ render();
+
+ expect(explainer()?.children).toHaveLength(2);
+ expect(explainer()?.textContent).not.toContain("获取 API Key");
+ });
+
+ it("stays out of the way once a key is saved", () => {
+ state = { ...baseState, status, statusState: "success", hasApiKey: true };
+ render();
+
+ expect(explainer()).toBeNull();
+ });
+ });
});
diff --git a/frontend/src/pages/ProviderKeyPage.tsx b/frontend/src/pages/ProviderKeyPage.tsx
index d81be5fd..833f8ed0 100644
--- a/frontend/src/pages/ProviderKeyPage.tsx
+++ b/frontend/src/pages/ProviderKeyPage.tsx
@@ -1,4 +1,4 @@
-import { ExternalLink, FlaskConical, Link2 } from "lucide-react";
+import { ArrowLeftRight, ExternalLink, FlaskConical, Link2 } from "lucide-react";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
@@ -9,6 +9,8 @@ import { ProviderModelPicker } from "../components/ProviderModelPicker";
import { ProviderSegment } from "../components/ProviderSegment";
import { SecureKeyField } from "../components/SecureKeyField";
import { useI18n } from "../i18n";
+import { useFeedback } from "../state/FeedbackContext";
+import { probeOffersConversion, providerSuggestsConversion } from "../state/conversion";
import { desktopProtocol, profileAgentIdForDesktop, selectedDesktopApp } from "../state/desktopSetup";
import { useWizard } from "../state/WizardContext";
import { wizardNeedsModel } from "../state/wizardReducer";
@@ -20,11 +22,12 @@ export function ProviderKeyPage() {
const { t } = useI18n();
const { state, dispatch, secret, refreshStatus } = useWizard();
const [savingKey, setSavingKey] = useState(false);
- const [saveFailure, setSaveFailure] = useState("");
+ const feedback = useFeedback();
const providerMeta = state.status?.providers[state.provider];
const apiBaseUrl = providerMeta?.base_url || "";
const providerHasKey = Boolean(providerMeta?.has_key);
const builtInProvider = Boolean(providerMeta && !providerMeta.custom);
+ const hasKeyPage = Boolean(providerMeta?.key_management_url || providerMeta?.home);
const canProbe = providerHasKey;
const desktop = state.setupKind === "desktop" && state.status
? selectedDesktopApp(state.status, state.selectedAgentIds)
@@ -32,8 +35,6 @@ export function ProviderKeyPage() {
const probeAgentIds = desktop
? [profileAgentIdForDesktop(desktop)]
: state.selectedAgentIds;
- // A new key is persisted before continuing; probing remains optional.
- const canContinue = canProbe || (builtInProvider && state.hasApiKey);
// The selected Agents decide which protocols get tested; a model that serves
// Chat Completions may still refuse Responses, so do not imply a single one.
@@ -46,16 +47,31 @@ export function ProviderKeyPage() {
return [...new Set(selected)].sort();
}, [desktop, probeAgentIds, state.status]);
+ // Compatibility mode is offered where activation can carry it out: a
+ // command-line Agent, or Claude Desktop, whose adapter path already exists.
+ // Other desktop apps share another Agent's settings and stay as they are.
+ const conversionProtocol = protocols.length === 1 && (!desktop || desktop.id === "claude-desktop") ? protocols[0] : undefined;
+ const conversionOffered = state.connectionState === "error" && probeOffersConversion(state.connection, conversionProtocol);
+ // Read from the Provider's protocol table, with no request sent. It speaks
+ // only until a connection test has: a test's verdict replaces the guess.
+ const conversionSuggested = state.connectionState === "idle" && providerSuggestsConversion(providerMeta, conversionProtocol);
+ const agentName = desktop?.name || state.status?.catalog.find((item) => item.id === state.selectedAgentIds[0])?.name || "";
+ // A new key is persisted before continuing; probing remains optional. A test
+ // that found compatibility mode would help is the exception: continuing past
+ // it unanswered installs an Agent that fails on its first request. The
+ // untested suggestion is not: nothing has shown the Provider cannot serve it.
+ const canContinue = (canProbe || (builtInProvider && state.hasApiKey)) && (!conversionOffered || state.conversion);
+
const endpoint = useMemo(() => {
if (!apiBaseUrl) return "";
const base = apiBaseUrl.replace(/\/$/, "");
if (!protocols.length) return `${base}/v1/chat/completions`;
+ if (state.conversion) return `${base} · ${t("兼容模式")}`;
return `${base} · ${protocols.map((p) => PROTOCOL_LABELS[p]).join(" + ")}`;
- }, [apiBaseUrl, protocols]);
+ }, [apiBaseUrl, protocols, state.conversion, t]);
const changeProvider = (provider: ProviderId) => {
secret.clearApiKey();
- setSaveFailure("");
dispatch({ type: "SET_PROVIDER", value: provider });
};
@@ -76,7 +92,6 @@ export function ProviderKeyPage() {
}
if (!providerMeta || !builtInProvider || !secret.keyRef.current) return;
setSavingKey(true);
- setSaveFailure("");
try {
await api.saveProvider({
id: state.provider,
@@ -91,7 +106,7 @@ export function ProviderKeyPage() {
await refreshStatus();
navigate(afterProvider);
} catch (error) {
- setSaveFailure(describeFailure(error, t("无法保存模型服务"), t).message);
+ feedback.failure(error, t("无法保存模型服务"), { key: "setup:provider" });
} finally {
setSavingKey(false);
}
@@ -146,11 +161,25 @@ export function ProviderKeyPage() {
onAdd={() => navigate(`/providers/new?returnTo=${encodeURIComponent("/setup/provider")}`)}
onChange={changeProvider}
protocol={protocols.length === 1 ? protocols[0] : ""}
+ // A Provider with only an OpenAI address can still serve Claude Code
+ // here: the connection test will offer compatibility mode for it.
+ convertible={Boolean(conversionProtocol)}
/>
{!providerHasKey && builtInProvider ? (
-
+ <>
+
+ {/* Only for someone without a key yet: they are the one who may not
+ know what is being asked for, or that the Provider is who bills. */}
+
{t("这个模型服务还没有 Key,先到模型服务页面填写")}
@@ -160,13 +189,12 @@ export function ProviderKeyPage() {
) : null}
- {saveFailure ?
{saveFailure}
: null}
{providerMeta?.name}{providerMeta?.base_url}
- {providerMeta?.key_management_url || providerMeta?.home ? (
+ {hasKeyPage ? (
void openRegistration()}>
{t("获取 API Key")}
@@ -196,8 +224,52 @@ export function ProviderKeyPage() {
{t("测试连接")}
-
+ {/* Replaced rather than joined: the plain failure would tell the user
+ to switch API type, which the wizard has no control for, right
+ beside the one choice that fixes it. */}
+ {conversionOffered ? null : }
);
diff --git a/frontend/src/pages/ProvidersPage.test.tsx b/frontend/src/pages/ProvidersPage.test.tsx
index 3c7022c2..e4a194d0 100644
--- a/frontend/src/pages/ProvidersPage.test.tsx
+++ b/frontend/src/pages/ProvidersPage.test.tsx
@@ -1,8 +1,9 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
import { api } from "../backend/api";
+import { FeedbackProvider } from "../state/FeedbackContext";
import type { StatusResponse } from "../types/api";
import { ProvidersPage } from "./ProvidersPage";
@@ -77,12 +78,20 @@ function statusWith(agents: Record): StatusResponse {
function renderPage(agents: Record) {
mockState = { status: statusWith(agents), statusState: "success" };
render(
-
-
- ,
+
+
+
+
+ ,
);
}
+/** The open receipt, with its 详情 expanded. */
+function receiptWithDetail(receipt: HTMLElement) {
+ fireEvent.click(within(receipt).getByRole("button", { name: "详情" }));
+ return receipt;
+}
+
describe("ProvidersPage", () => {
afterEach(() => {
vi.restoreAllMocks();
@@ -111,9 +120,11 @@ describe("ProvidersPage", () => {
if (!mockState.status) throw new Error("missing status");
mockState.status.providers.acme = { name: "Acme", home: "", base_url: "https://api.acme.test", custom: true };
const remove = vi.spyOn(api, "deleteProvider");
- render();
+ render();
fireEvent.click(screen.getByRole("button", { name: "删除 Acme" }));
- expect(screen.getByText(/模型服务正在被.*使用,无法删除/)).toBeTruthy();
+ const receipt = receiptWithDetail(screen.getByRole("alert"));
+ expect(receipt).toHaveTextContent("「Acme」正在使用,无法删除");
+ expect(receipt).toHaveTextContent("使用它的 Agent:codex");
expect(remove).not.toHaveBeenCalled();
});
@@ -198,7 +209,8 @@ describe("ProvidersPage", () => {
fireEvent.change(screen.getByLabelText("API Key"), { target: { value: "sk-rotated" } });
fireEvent.click(screen.getByRole("button", { name: /^保存$/ }));
- await waitFor(() => expect(screen.getByText(/已重新应用到.*Claude Code/)).toBeTruthy());
+ const receipt = (await screen.findByText("已保存,2 个 Agent 已更新")).closest(".feedback-toast") as HTMLElement;
+ expect(receiptWithDetail(receipt)).toHaveTextContent("codex、Claude Code");
});
it("reports an Agent that could not be rewritten", async () => {
@@ -217,7 +229,8 @@ describe("ProvidersPage", () => {
fireEvent.change(screen.getByLabelText("API Key"), { target: { value: "sk-rotated" } });
fireEvent.click(screen.getByRole("button", { name: /^保存$/ }));
- await waitFor(() => expect(screen.getByText(/Claude Code 重新应用失败:model is required/)).toBeTruthy());
+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("已保存,1 个 Agent 未能更新"));
+ expect(receiptWithDetail(screen.getByRole("alert"))).toHaveTextContent("Claude Code: model is required");
});
it("adds a Provider from the management page", async () => {
@@ -285,7 +298,7 @@ describe("ProvidersPage", () => {
apiKey: "sk-acme",
draft: true,
})));
- await waitFor(() => expect(screen.getByText("连接成功")).toBeTruthy());
+ await waitFor(() => expect(screen.getByText("连接正常")).toBeTruthy());
// The whole point of testing before saving: a key that turns out to be wrong
// must not have been written to disk on the way.
expect(save).not.toHaveBeenCalled();
diff --git a/frontend/src/pages/ProvidersPage.tsx b/frontend/src/pages/ProvidersPage.tsx
index f22c7cb0..8b8766ac 100644
--- a/frontend/src/pages/ProvidersPage.tsx
+++ b/frontend/src/pages/ProvidersPage.tsx
@@ -2,13 +2,15 @@ import { ExternalLink, FlaskConical, KeyRound, Pencil, Plus, Save, Trash2, X } f
import { useEffect, useRef, useState, type FormEvent } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
-import { api, describeFailure } from "../backend/api";
+import { api } from "../backend/api";
import { CardUsers } from "../components/CardUsers";
import { ConnectionStatus } from "../components/ConnectionStatus";
import { PageScaffold } from "../components/PageScaffold";
import { SecureKeyField } from "../components/SecureKeyField";
import { useI18n } from "../i18n";
import { confirmDelete } from "../state/confirmDelete";
+import { useFeedback } from "../state/FeedbackContext";
+import { saveReceipt } from "../state/saveReceipt";
import { anthropicClientBaseURL } from "../state/providerUrl";
import { useWizard } from "../state/WizardContext";
import { byProviderCreatedAt } from "../state/ranking";
@@ -56,8 +58,8 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
// button, which opens the same editor on the list route.
const [creating, setCreating] = useState(create);
const [busy, setBusy] = useState(false);
- const [failure, setFailure] = useState("");
- const [applied, setApplied] = useState("");
+ const feedback = useFeedback();
+ const separator = locale === "en" ? ", " : "、";
// Local rather than the wizard reducer's connection state: that one belongs to
// the setup flow, and sharing it would let a test here overwrite what the
// wizard is showing, and the reverse.
@@ -127,14 +129,12 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
const edit = async (providerId: string) => {
if (isConverterID(providerId)) return;
setBusy(true);
- setFailure("");
- setApplied("");
clearProbe();
try {
setEditor(await api.getProvider(providerId));
setCreating(false);
} catch (error) {
- setFailure(describeFailure(error, t("无法读取模型服务"), t).message);
+ feedback.failure(error, t("无法读取模型服务"), { key: `provider:${providerId}` });
} finally {
setBusy(false);
}
@@ -155,7 +155,6 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
if (!editor) return;
setProbeState("loading");
setProbeResult(null);
- setFailure("");
try {
const result = await api.probe({
provider: editor.id.trim(),
@@ -174,7 +173,7 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
} catch (error) {
setProbeResult(null);
setProbeState("error");
- setFailure(describeFailure(error, t("连接测试失败"), t).message);
+ feedback.failure(error, t("连接测试失败"), { key: "provider-probe" });
}
};
@@ -199,8 +198,7 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
event.preventDefault();
if (!editor) return;
setBusy(true);
- setFailure("");
- setApplied("");
+ const key = `provider:${editor.id.trim()}`;
try {
// Changing an endpoint or key rewrites every Agent already using this
// Provider, so the outcome has to be reported rather than silently applied.
@@ -212,33 +210,22 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
anthropic_base_url: anthropicClientBaseURL(editor.anthropic_base_url || ""),
create: creating,
});
- const reapplied = result.reapplied ?? [];
- const failures = Object.entries(result.failures ?? {});
- if (failures.length) {
- setFailure(t("{agents} 重新应用失败:{message}", {
- agents: failures.map(([agentId]) => nameOf(agentId)).join(locale === "en" ? ", " : "、"),
- message: failures[0][1] ?? "",
- }));
- } else if (reapplied.length) {
- setApplied(t("已重新应用到 {agents}", {
- agents: reapplied.map(nameOf).join(locale === "en" ? ", " : "、"),
- }));
- }
+ feedback.show(saveReceipt({ key, name: editor.name.trim() || editor.id.trim(), result, nameOf, t, separator }));
await refreshStatus();
if (create) navigate(returnTo);
else setEditor(null);
} catch (error) {
- setFailure(describeFailure(error, t("无法保存模型服务"), t).message);
+ // The editor stays open with what was typed, so the save can be retried.
+ feedback.failure(error, t("无法保存模型服务"), { key });
} finally {
setBusy(false);
}
};
const remove = async (providerId: string, name: string, users: string[]) => {
+ const key = `provider:${providerId}`;
if (users.length) {
- setFailure(t("模型服务正在被 {agents} 使用,无法删除", {
- agents: users.map(nameOf).join(locale === "en" ? ", " : "、"),
- }));
+ feedback.show({ key, tone: "warning", message: t("「{name}」正在使用,无法删除", { name }), detail: t("使用它的 Agent:{agents}", { agents: users.map(nameOf).join(separator) }) });
return;
}
// The saved API key goes with it, which is the part a user does not get back.
@@ -249,14 +236,13 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
cancelLabel: t("取消"),
})) return;
setBusy(true);
- setFailure("");
- setApplied("");
try {
await api.deleteProvider(providerId);
if (editor?.id === providerId) setEditor(null);
+ feedback.show({ key, tone: "success", message: t("已删除「{name}」", { name }) });
await refreshStatus();
} catch (error) {
- setFailure(describeFailure(error, t("无法删除模型服务"), t).message);
+ feedback.failure(error, t("无法删除模型服务"), { key });
} finally {
setBusy(false);
}
@@ -275,7 +261,7 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
title={create ? t("新增模型服务") : t("模型服务")}
bodyClassName="management-page"
secondaryAction={!create ? (
- { setEditor({ ...emptyProvider, id: suggestProviderID(Object.keys(status.providers)) }); setCreating(true); setFailure(""); setApplied(""); }}>
+ { setEditor({ ...emptyProvider, id: suggestProviderID(Object.keys(status.providers)) }); setCreating(true); }}>
{t("新增模型服务")}
@@ -389,11 +375,6 @@ export function ProvidersPage({ create = false }: { create?: boolean }) {
) : null}
- {failure ?
{failure}
: null}
- {/* The editor is a page of its own: the list, and the notice about what
- the last save did to it, return when the editor closes. Rendering them
- below the form read as the previous page appended to this one. */}
- {applied && !editor ?
{t("应用完成")}{applied}
: null}
{!create && !editor ?
{byProviderCreatedAt(Object.fromEntries(Object.entries(status.providers).filter(([providerId]) => !isConverterID(providerId)))).map(([providerId, meta]) => {
diff --git a/frontend/src/pages/ReviewPage.tsx b/frontend/src/pages/ReviewPage.tsx
index 350c8ce9..be475ba1 100644
--- a/frontend/src/pages/ReviewPage.tsx
+++ b/frontend/src/pages/ReviewPage.tsx
@@ -31,7 +31,9 @@ export function ReviewPage() {
// no separate field.
const targetID = desktop ? profileAgentIdForDesktop(desktop) : state.selectedAgentIds[0] ?? "agent";
const targetName = desktop?.name || selectedCatalog[0]?.name || state.selectedAgentIds[0] || "";
- const defaultId = `${targetID}-${state.provider}`.replace(/[^a-z0-9_-]/gi, "-").toLowerCase();
+ // A compatibility-mode Profile speaks Chat Completions, not the Agent's own
+ // format, so it gets an ID of its own instead of overwriting a native one.
+ const defaultId = `${targetID}-${state.provider}${state.conversion ? "-compat" : ""}`.replace(/[^a-z0-9_-]/gi, "-").toLowerCase();
const defaultLabel = `${targetName} · ${providerName}`;
const profileLabel = state.profileLabel || defaultLabel;
@@ -80,6 +82,7 @@ export function ReviewPage() {
// wizard forgot to collect, and the user would go looking for it.
: }
+ {state.conversion ? : null}
diff --git a/frontend/src/pages/SettingsPage.test.tsx b/frontend/src/pages/SettingsPage.test.tsx
index 3105d79a..09e3c9f0 100644
--- a/frontend/src/pages/SettingsPage.test.tsx
+++ b/frontend/src/pages/SettingsPage.test.tsx
@@ -1,15 +1,16 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
import { api } from "../backend/api";
import { BootAgentApiError } from "../backend/errors";
+import { FeedbackProvider } from "../state/FeedbackContext";
import { ThemeProvider } from "../state/ThemeContext";
import { SettingsPage } from "./SettingsPage";
const show = () =>
- render(} />transfer child} />);
+ render(} />transfer child} />);
describe("SettingsPage", () => {
afterEach(() => vi.restoreAllMocks());
@@ -24,7 +25,7 @@ describe("SettingsPage", () => {
terminal_app: "",
terminals: [],
});
- render(} />transfer child} />);
+ render(} />transfer child} />);
expect(screen.getByRole("combobox", { name: "外观" })).toBeTruthy();
expect(screen.getByRole("combobox", { name: "语言" })).toBeTruthy();
expect(await screen.findByRole("switch", { name: "优先使用国内镜像" })).toBeTruthy();
@@ -49,7 +50,11 @@ describe("SettingsPage", () => {
);
show();
fireEvent.click(screen.getByRole("button", { name: /帮助文档/ }));
- await waitFor(() => expect(screen.getByText("Unable to open the help site")).toBeTruthy());
+ // A receipt, with the reason behind 详情.
+ const receipt = await screen.findByRole("alert");
+ expect(receipt).toHaveTextContent("无法打开帮助文档");
+ fireEvent.click(within(receipt).getByRole("button", { name: "详情" }));
+ expect(within(receipt).getByText("Unable to open the help site")).toBeTruthy();
});
it("loads and saves per-target backup retention", async () => {
diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsx
index 30640279..68e9b0c8 100644
--- a/frontend/src/pages/SettingsPage.tsx
+++ b/frontend/src/pages/SettingsPage.tsx
@@ -3,7 +3,7 @@ import { useState } from "react";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
-import { api, describeFailure, failureLine } from "../backend/api";
+import { api, failureLine } from "../backend/api";
import { OTA_PROGRESS_TARGET } from "../backend/wails";
import { MirrorSetting } from "../components/MirrorSetting";
import { PageScaffold } from "../components/PageScaffold";
@@ -11,6 +11,7 @@ import { SelectField } from "../components/SelectField";
import { ThemePicker } from "../components/ThemePicker";
import { GitHubMark } from "../components/icons/GitHubMark";
import { useI18n } from "../i18n";
+import { useFeedback } from "../state/FeedbackContext";
import { taskCanceller, taskKey, updateTaskRoute, useTaskCenter } from "../state/TaskCenterContext";
import type { Settings } from "../types/api";
@@ -28,12 +29,11 @@ export function SettingsPage() {
const [checking, setChecking] = useState(false);
const [updateMessage, setUpdateMessage] = useState("");
const [latestVersion, setLatestVersion] = useState("");
- const [helpFailure, setHelpFailure] = useState("");
const [settings, setSettings] = useState(null);
const [backupRetention, setBackupRetention] = useState("");
- const [backupFailure, setBackupFailure] = useState("");
- const [autostartFailure, setAutostartFailure] = useState("");
- const [terminalFailure, setTerminalFailure] = useState("");
+ // Each control shows its own saved value, so a save that worked needs no
+ // words; one that failed is reverted and explained in a receipt.
+ const feedback = useFeedback();
useEffect(() => {
// The desktop bridge normally returns a string, but a browser preview or an
@@ -54,14 +54,13 @@ export function SettingsPage() {
if (!active) return;
setSettings(null);
setBackupRetention(defaultBackupRetention);
- setBackupFailure(t("无法读取备份设置"));
+ feedback.show({ key: "settings-load", tone: "failure", message: t("无法读取设置") });
});
return () => { active = false; };
}, []);
const saveTerminalApp = async (next: string) => {
if (!settings) return;
- setTerminalFailure("");
// Optimistic: the picker is the only writer, so showing the choice now keeps
// the control responsive, and a failure below restores the stored value.
const previous = settings.terminal_app;
@@ -71,7 +70,7 @@ export function SettingsPage() {
setSettings(saved);
} catch (error) {
setSettings({ ...settings, terminal_app: previous });
- setTerminalFailure(describeFailure(error, t("无法保存终端设置"), t).message);
+ feedback.failure(error, t("无法保存终端设置"), { key: "terminal-app" });
}
};
@@ -79,13 +78,14 @@ export function SettingsPage() {
if (!settings) return;
const nextRetention = boundedBackupRetention(backupRetention === "" ? defaultBackupRetention : backupRetention);
setBackupRetention(nextRetention);
- setBackupFailure("");
+ if (nextRetention === settings.backup_retention) return;
try {
const saved = await api.saveSettings({ backup_retention: nextRetention });
setSettings(saved);
setBackupRetention(saved.backup_retention ?? nextRetention);
} catch (error) {
- setBackupFailure(describeFailure(error, t("无法保存备份设置"), t).message);
+ setBackupRetention(settings.backup_retention ?? defaultBackupRetention);
+ feedback.failure(error, t("无法保存备份设置"), { key: "backup-retention" });
}
};
@@ -93,13 +93,12 @@ export function SettingsPage() {
if (!settings) return;
const previous = settings.autostart;
setSettings({ ...settings, autostart: enabled });
- setAutostartFailure("");
try {
const saved = await api.saveSettings({ autostart: enabled });
setSettings(saved);
} catch (error) {
setSettings({ ...settings, autostart: previous });
- setAutostartFailure(describeFailure(error, t("无法保存开机自启动设置"), t).message);
+ feedback.failure(error, t("无法保存开机自启动设置"), { key: "autostart" });
}
};
@@ -136,20 +135,18 @@ export function SettingsPage() {
};
const openHelp = async () => {
- setHelpFailure("");
try {
await api.openHelp();
} catch (error) {
- setHelpFailure(describeFailure(error, t("无法打开帮助文档"), t).message);
+ feedback.failure(error, t("无法打开帮助文档"), { key: "open-help" });
}
};
const openGitHub = async () => {
- setHelpFailure("");
try {
await api.openGitHub();
} catch (error) {
- setHelpFailure(describeFailure(error, t("无法打开 GitHub"), t).message);
+ feedback.failure(error, t("无法打开 GitHub"), { key: "open-github" });
}
};
return (
@@ -209,7 +206,6 @@ export function SettingsPage() {
/>