From 4904c02488112792da09b94c83f253f701e8c1ae Mon Sep 17 00:00:00 2001 From: yujiezhang-ops Date: Fri, 20 Nov 2026 17:25:36 +0800 Subject: [PATCH] feat: make compatibility mode a setting that follows the Agents using it Compatibility mode is an implementation detail of one Agent using one model service, so it no longer has a page or a sidebar entry of its own. - It is still switched on where an Agent needs it: the setup wizard, an Agent's Profile list, a failed model check. The question about starting with the system moves there from the removed page, asked once per session. - It ends on the Agent too. Applying an ordinary Profile drops that Agent's route, and the adapter stops when the last Agent has left (SettleConversion). - Settings holds what is left to set by hand: one switch that names the Agents depending on it, and a fold with the listen address, local keys and model aliases. /conversion redirects there. Fixes found while testing the current release against its real backend: - A route left behind by an Agent that had moved on failed every later save once its Profile was deleted, so compatibility mode could not be stopped, no other Agent could be switched to it and its keys could not be regenerated. A save no longer checks other Agents' routes; a route is checked when it is set, and a request through a dead one is refused on its own. - A Profile that compatibility mode forwards to can no longer be changed to another API type, which made every request of the Agents behind it fail with 401. Deleting it was already refused. - Settings that keep the listen address are swapped in place instead of restarting the listener, which waited five seconds on any answer still streaming and then failed the change. A stop or a move to another address now closes open responses after that grace period instead of failing, and a rollback no longer stops a running adapter first. - The new-Profile form on an Agent page could preselect the adapter's own Provider, which the picker hides, and save a Profile bound to it. Co-Authored-By: Claude Sonnet 5 --- README.md | 2 +- README_ZH.md | 2 +- docs/ui-friendliness-plan.md | 2 +- frontend/e2e/wails.spec.ts | 68 ++++- frontend/src/App.tsx | 4 +- frontend/src/backend/failureCopy.ts | 4 +- .../components/CompatibilitySetting.test.tsx | 147 ++++++++++ .../src/components/CompatibilitySetting.tsx | 204 +++++++++++++ frontend/src/components/NavigationSidebar.tsx | 5 +- frontend/src/i18n.tsx | 27 +- frontend/src/pages/ActivationPage.tsx | 14 +- frontend/src/pages/AgentProfilePage.test.tsx | 38 +++ frontend/src/pages/AgentProfilePage.tsx | 13 +- frontend/src/pages/ConversionPage.test.tsx | 167 ----------- frontend/src/pages/ConversionPage.tsx | 273 ------------------ frontend/src/pages/ProfilesPage.tsx | 3 +- frontend/src/pages/SettingsPage.test.tsx | 26 +- frontend/src/pages/SettingsPage.tsx | 5 + frontend/src/state/applyConversion.test.ts | 52 ++++ frontend/src/state/applyConversion.ts | 36 +++ frontend/src/styles/app.css | 65 +---- internal/app/agent_conversion_test.go | 155 ++++++++++ internal/app/conversion.go | 103 ++++++- internal/app/desktop_conversion.go | 9 +- internal/app/status.go | 33 +-- internal/binding/services.go | 19 +- internal/binding/services_test.go | 31 ++ internal/convertproxy/convert_test.go | 120 ++++++++ internal/convertproxy/server.go | 31 +- 29 files changed, 1077 insertions(+), 581 deletions(-) create mode 100644 frontend/src/components/CompatibilitySetting.test.tsx create mode 100644 frontend/src/components/CompatibilitySetting.tsx delete mode 100644 frontend/src/pages/ConversionPage.test.tsx delete mode 100644 frontend/src/pages/ConversionPage.tsx create mode 100644 frontend/src/state/applyConversion.test.ts diff --git a/README.md b/README.md index 3d9e7d8a..ba10fa29 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ BootAgent does not redistribute Agent packages and does not bundle Node.js, Git, | --- | --- | | Agent is not listed | Refresh Environment overview, check that the command is on `PATH`, or use the Agent's documented manual install path. | | Provider connection check fails | Confirm the endpoint and model match the Agent's protocol. Use Check model for a saved Profile; saving or applying a Profile does not automatically send a model request. | -| Codex reports `does not support endpoint: responses` | Codex is configured to use Responses. Select a model that supports it, or use the API protocol adapter with a working Chat Completions Profile and apply its generated Codex Profile. A model appearing in `/models` does not prove Responses support. | +| Codex reports `does not support endpoint: responses` | Codex is configured to use Responses. Select a model that supports it, or pick a working Chat Completions Profile on Codex's page and apply it with compatibility mode, which converts the requests on this computer. A model appearing in `/models` does not prove Responses support. | | Windows detects a desktop app but its version is unavailable | BootAgent retries the registered package's metadata through Windows PackageManager. If the metadata remains inaccessible, launch is still available; this warning is separate from model API compatibility. | | Marketplace looks incomplete | Check the source status and refresh. A bundled snapshot remains available when an online source is unavailable. | | Import reports a conflict | Review the preview, choose skip or overwrite, and apply only after checking the affected resource names. | diff --git a/README_ZH.md b/README_ZH.md index abcabee9..3f10d495 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -138,7 +138,7 @@ BootAgent 不重新分发 Agent 包,也不捆绑 Node.js、Git、WebView 或 A | --- | --- | | 找不到 Agent | 刷新“环境总览”,确认命令在 `PATH` 中,或按 Agent 官方指引手动安装后再次检测。 | | Provider 连接检查失败 | 确认端点和模型与 Agent 使用的协议一致。对已保存的 Profile 使用“检测模型”;保存或应用 Profile 不会自动发送模型请求。 | -| Codex 报错 `does not support endpoint: responses` | Codex 的配置使用 Responses。选择支持它的模型,或在 API 协议适配中选择可用的 Chat Completions Profile,再应用生成的 Codex Profile。模型出现在 `/models` 中并不证明它支持 Responses。 | +| Codex 报错 `does not support endpoint: responses` | Codex 的配置使用 Responses。选择支持它的模型,或在 Codex 的配置页选一个可用的 Chat Completions 配置模版,用兼容模式应用,由 BootAgent 在本机转换。模型出现在 `/models` 中并不证明它支持 Responses。 | | Windows 检测到桌面应用但版本不可用 | BootAgent 会通过 Windows PackageManager 重试读取已注册应用包的元数据。如果仍无法读取,仍可尝试启动;这个提示与模型 API 兼容性无关。 | | 工具市场内容不完整 | 查看来源状态并点击刷新;在线来源不可用时仍会显示内置目录。 | | 导入提示冲突 | 查看导入预览,选择跳过或覆盖,并确认受影响的资源名称。 | diff --git a/docs/ui-friendliness-plan.md b/docs/ui-friendliness-plan.md index 28a5cc6b..7bda0b24 100644 --- a/docs/ui-friendliness-plan.md +++ b/docs/ui-friendliness-plan.md @@ -140,7 +140,7 @@ | 2 | 配置向导(`setup/*`) | 每步一句说明;协议名移出默认视图 | | 3 | 模型服务、配置模板 | 按用词表改字段名;示例占位;一条提示一句 | | 4 | 多模态 | 账号行合并为一个状态徽标;安装弹窗压成「会使用你在 {服务} 的 Key,每次调用按价格计费」一句,其余进「了解详情」;Skill ID、环境变量、文件路径进「详情」 | -| 5 | 兼容模式(原协议适配) | 已扩大为动线改造(2026-10-12):在出问题的地方提出兼容模式——向导测试连接、Agent 页选模版、检测模型失败;命令行 Agent 一键开启(`ConfigureAgentWithConversion`);兼容模式页改为状态页;下拉框隐藏转换器条目并写明不可选原因 | +| 5 | 兼容模式(原协议适配) | 已扩大为动线改造(2026-10-12):在出问题的地方提出兼容模式——向导测试连接、Agent 页选模版、检测模型失败;命令行 Agent 一键开启(`ConfigureAgentWithConversion`);兼容模式页改为状态页;下拉框隐藏转换器条目并写明不可选原因。2026-11-20:兼容模式不再有自己的页面和侧边栏入口,它由 Agent 开启(同上三处),Agent 换回普通配置模版即退出,最后一个退出后适配器自动停止;总开关、监听地址、本地 Key 和模型别名收进「设置」(`CompatibilitySetting`),旧地址 `/conversion` 跳转到设置 | | 6 | Skills、MCP | 同上规则;`Sparkles` 换为与 Skill 含义相符的图标 | | 7 | Marketplace 详情 | 元信息分组,次要字段进「详情」 | | 8 | 设置、导入导出 | 同上规则 | diff --git a/frontend/e2e/wails.spec.ts b/frontend/e2e/wails.spec.ts index 367e4c04..65f3a80f 100644 --- a/frontend/e2e/wails.spec.ts +++ b/frontend/e2e/wails.spec.ts @@ -270,16 +270,24 @@ test("Claude Desktop adapts a Chat Completions Profile after one confirmation", await page.getByRole("textbox", { name: "模型", exact: true }).fill("bootagent-e2e-model"); await page.getByRole("button", { name: "保存配置模版" }).click(); - // Only the port: there is no single model to choose here any more. The + // Compatibility mode has no page of its own: its old address lands on 设置, + // where the few things set by hand live. Only the port is changed here; the // default 8787 may be taken on the machine running the tests. await page.goto("/#/conversion"); - await page.getByRole("button", { name: "高级设置" }).click(); + await expect(page).toHaveURL(/#\/settings$/); + await expect(page.getByRole("link", { name: "兼容模式" })).toHaveCount(0); + await page.getByText("高级设置").click(); await page.getByLabel("监听地址").fill("127.0.0.1:34125"); await page.getByRole("button", { name: "保存更改" }).click(); - // Nothing uses compatibility mode yet, so once the address is saved the - // primary action goes back to turning it on. The save button is only disabled - // while the request is in flight, which a fast save finishes before this runs. - await expect(page.getByRole("button", { name: "开启兼容模式" })).toBeDisabled(); + // Read back from a fresh page: a receipt may be waiting behind the Profile's. + await expect(page.getByRole("button", { name: "保存更改" })).toBeDisabled(); + await page.reload(); + await page.getByText("高级设置").click(); + await expect(page.getByLabel("监听地址")).toHaveValue("127.0.0.1:34125"); + // Nothing uses it yet, so there is nothing to switch on by hand. + const compatibility = page.getByRole("switch", { name: "兼容模式" }); + await expect(compatibility).not.toBeChecked(); + await expect(compatibility).toBeDisabled(); await page.goto("/#/agents/claude-desktop"); await page.getByLabel("选择 Claude Desktop E2E Chat").check(); @@ -315,19 +323,47 @@ test("Codex and Claude Desktop use different models through compatibility mode", await apply.click(); await expect(page).toHaveURL(/#\/overview$/); - await page.goto("/#/conversion"); - const users = page.getByRole("region", { name: "正在使用的 Agent" }); - const row = (name: string) => users.getByRole("listitem").filter({ has: page.getByText(name, { exact: true }) }); - await expect(row("Codex")).toContainText("codex-e2e-model"); - await expect(row("Claude Desktop")).toContainText("bootagent-e2e-model"); - // ChatGPT Desktop shares Codex's settings, so it follows Codex's route. - await expect(row("ChatGPT Desktop")).toContainText("codex-e2e-model"); - - // Reopening Codex shows the model it uses, not the adapter. - await users.getByRole("button", { name: "为 Codex 更换模型" }).click(); + // 设置 says who depends on it. ChatGPT Desktop shares Codex's settings, so + // it follows Codex. + await page.goto("/#/settings"); + await expect(page.getByRole("switch", { name: "兼容模式" })).toBeChecked(); + const users = page.getByText(/正在使用,使用期间需要保持 BootAgent 运行$/); + await expect(users).toContainText("Codex"); + await expect(users).toContainText("Claude Desktop"); + await expect(users).toContainText("ChatGPT Desktop"); + + // Each Agent's own page shows the model it uses, not the adapter. + // Each from the overview, as a user gets there. + await page.goto("/#/agents/claude-desktop"); + await expect(page.getByLabel("选择 Claude Desktop E2E Chat")).toBeChecked(); + await page.goto("/#/overview"); + await page.goto("/#/agents/codex"); await expect(page.getByLabel("选择 Codex E2E Chat")).toBeChecked(); }); +// Runs after the two cases above. Compatibility mode ends where it began, on +// the Agent: an ordinary Profile takes Codex out of it, and Claude Desktop, +// still on its own route, keeps it running. +test("an Agent given an ordinary Profile leaves compatibility mode", async ({ page }) => { + await page.goto("/#/profiles"); + await page.getByRole("button", { name: "新增配置模版" }).click(); + await page.getByLabel("配置模版 ID").fill("codex-e2e-native"); + await page.getByLabel("名称").fill("Codex E2E Native"); + await page.getByRole("combobox", { name: "API 类型" }).click(); + await page.getByRole("option", { name: "OpenAI Responses" }).click(); + await page.getByRole("textbox", { name: "模型", exact: true }).fill("codex-e2e-native-model"); + await page.getByRole("button", { name: "保存配置模版" }).click(); + + await page.goto("/#/agents/codex"); + await page.getByLabel("选择 Codex E2E Native").check(); + await page.getByRole("button", { name: "应用", exact: true }).click(); + await expect(page).toHaveURL(/#\/overview$/); + + await page.goto("/#/settings"); + await expect(page.getByRole("switch", { name: "兼容模式" })).toBeChecked(); + await expect(page.getByText("Claude Desktop 正在使用,使用期间需要保持 BootAgent 运行", { exact: true })).toBeVisible(); +}); + test("Skills and MCP management lead to their marketplace categories", async ({ page }) => { const browserProblems: string[] = []; page.on("console", (message) => { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 7a20a551..b003cfbb 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -7,7 +7,6 @@ import { InstallTaskPage } from "./pages/InstallTaskPage"; import { AgentProfilePage } from "./pages/AgentProfilePage"; import { AgentSelectionPage } from "./pages/AgentSelectionPage"; import { EnvironmentOverviewPage } from "./pages/EnvironmentOverviewPage"; -import { ConversionPage } from "./pages/ConversionPage"; import { ModelSelectionPage } from "./pages/ModelSelectionPage"; import { MCPPage } from "./pages/MCPPage"; import { MultimodalPage } from "./pages/MultimodalPage"; @@ -107,7 +106,8 @@ function WorkspaceRoutes() { } /> } /> } /> - } /> + {/* Compatibility mode used to have a page; its settings are in 设置 now. */} + } /> } /> } /> } /> diff --git a/frontend/src/backend/failureCopy.ts b/frontend/src/backend/failureCopy.ts index 8493e3e3..d4cba1e1 100644 --- a/frontend/src/backend/failureCopy.ts +++ b/frontend/src/backend/failureCopy.ts @@ -93,11 +93,11 @@ export function failureCopyFor(code: string | null | undefined, status: number | case "CONFIG_WRITE_FAILED": return { message: t("无法写入配置文件"), hint: t("确认配置文件没有被其他程序占用,以及你对它有写入权限") }; case "CONVERSION_PORT_UNAVAILABLE": - return { message: t("兼容模式需要的本机端口被占用"), hint: t("关闭占用端口的程序,或在兼容模式的高级设置里换一个端口") }; + return { message: t("兼容模式需要的本机端口被占用"), hint: t("关闭占用端口的程序,或在「设置」的兼容模式里换一个端口") }; case "CONVERSION_VERIFICATION_FAILED": return { message: t("兼容模式没有通过测试"), hint: t("检查所选模型服务的余额和网络后重试") }; case "CONVERSION_ROLLBACK_FAILED": - return { message: t("兼容模式开启失败,原来的设置未能完整恢复"), hint: t("请保持 BootAgent 运行,并到兼容模式页面检查") }; + return { message: t("兼容模式开启失败,原来的设置未能完整恢复"), hint: t("请保持 BootAgent 运行,并在「设置」里查看兼容模式") }; case "UPDATE_LOCATION_BLOCKED": // Withheld at check time on purpose: the swap runs after the app exits, so // this is the last moment anything can tell the user. diff --git a/frontend/src/components/CompatibilitySetting.test.tsx b/frontend/src/components/CompatibilitySetting.test.tsx new file mode 100644 index 00000000..65e55a93 --- /dev/null +++ b/frontend/src/components/CompatibilitySetting.test.tsx @@ -0,0 +1,147 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { api } from "../backend/api"; +import { BootAgentApiError } from "../backend/errors"; +import * as confirm from "../state/confirmDelete"; +import { FeedbackProvider } from "../state/FeedbackContext"; +import type { ConversionConfig, StatusResponse } from "../types/api"; +import { CompatibilitySetting } from "./CompatibilitySetting"; +import { FeedbackViewport } from "./FeedbackViewport"; + +const nobody = { providers: {}, catalog: [], agents: {}, desktopAgents: [], profiles: [], conversionRoutes: {} } as unknown as StatusResponse; +let mockStatus: StatusResponse | null = nobody; + +vi.mock("../state/WizardContext", () => ({ + useWizard: () => ({ state: { status: mockStatus }, refreshStatus: vi.fn() }), +})); + +const stopped: ConversionConfig = { + enabled: false, + listen: "127.0.0.1:8787", + has_api_key: false, + target_profile: "", + routes: {}, + anthropic_model: "claude-sonnet-5", + responses_model: "gpt-5.6-sol", + chat_model: "gpt-5.6-sol", +}; + +const codexInCompatibilityMode = { + providers: { ppio: { name: "PPIO" } }, + catalog: [{ id: "codex", name: "Codex" }, { id: "claude-code", name: "Claude Code" }], + agents: { codex: { profileId: "bootagent-converter-for-codex" }, "claude-code": { profileId: "bootagent-converter-for-claude-code" } }, + desktopAgents: [], + profiles: [{ id: "ppio-chat", label: "PPIO", provider: "ppio", model: "deepseek-v3", protocol: "openai" }], + conversionRoutes: { codex: "ppio-chat", "claude-code": "ppio-chat" }, +} as unknown as StatusResponse; + +beforeEach(() => { + localStorage.setItem("bootagent.locale", "zh-CN"); + vi.spyOn(api, "getConversion").mockResolvedValue(stopped); +}); + +afterEach(() => { + localStorage.clear(); + vi.restoreAllMocks(); + mockStatus = nobody; +}); + +// PageScaffold normally draws the receipts; a bare component needs the viewport. +const renderSetting = () => render(); + +describe("CompatibilitySetting", () => { + // Nothing to turn on by hand: an Agent switches it on when it needs it. + it("is off and cannot be switched on while no Agent uses it", async () => { + renderSetting(); + expect(await screen.findByText("Agent 需要时会自动开启")).toBeTruthy(); + const toggle = screen.getByRole("switch", { name: "兼容模式" }); + expect(toggle).not.toBeChecked(); + expect(toggle).toBeDisabled(); + }); + + // Before the status has loaded it is not known who uses it, so the row does + // not claim that nobody does and cannot be stopped without the warning. + it("waits for the status before saying who uses it or letting it be stopped", async () => { + mockStatus = null; + vi.spyOn(api, "getConversion").mockResolvedValue({ ...stopped, enabled: true, has_api_key: true }); + renderSetting(); + const toggle = await screen.findByRole("switch", { name: "兼容模式" }); + await waitFor(() => expect(toggle).toBeChecked()); + expect(toggle).toBeDisabled(); + expect(screen.queryByText("没有 Agent 在使用")).toBeNull(); + expect(screen.getByText("正在读取环境状态")).toBeTruthy(); + }); + + it("names the Agents using it while it runs", async () => { + mockStatus = codexInCompatibilityMode; + vi.spyOn(api, "getConversion").mockResolvedValue({ ...stopped, enabled: true, has_api_key: true }); + renderSetting(); + expect(await screen.findByText("Codex、Claude Code 正在使用,使用期间需要保持 BootAgent 运行")).toBeTruthy(); + expect(screen.getByRole("switch", { name: "兼容模式" })).toBeChecked(); + }); + + // Stopping breaks every Agent pointed at it, so it names them and asks. + it("asks before stopping it under the Agents that use it", async () => { + mockStatus = codexInCompatibilityMode; + vi.spyOn(api, "getConversion").mockResolvedValue({ ...stopped, enabled: true, has_api_key: true }); + const save = vi.spyOn(api, "saveConversion").mockImplementation(async (config) => config); + const ask = vi.spyOn(confirm, "confirmAction").mockResolvedValueOnce(false).mockResolvedValueOnce(true); + renderSetting(); + const toggle = await screen.findByRole("switch", { name: "兼容模式" }); + await waitFor(() => expect(toggle).toBeChecked()); + + fireEvent.click(toggle); + await waitFor(() => expect(ask).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining("Codex、Claude Code") }))); + expect(save).not.toHaveBeenCalled(); + + fireEvent.click(toggle); + await waitFor(() => expect(save).toHaveBeenCalledWith(expect.objectContaining({ enabled: false }))); + expect(await screen.findByText("兼容模式已停止")).toBeTruthy(); + expect(screen.getByText("已停止,Codex、Claude Code 暂时无法使用")).toBeTruthy(); + // With Agents waiting on it, it can be switched back on. + expect(toggle).toBeEnabled(); + }); + + it("offers a retry when the settings cannot be read", async () => { + const load = vi.spyOn(api, "getConversion").mockRejectedValueOnce(new BootAgentApiError("boom", "INTERNAL_ERROR", true, 500)); + renderSetting(); + const receipt = await screen.findByRole("alert"); + expect(receipt).toHaveTextContent("无法读取兼容模式设置"); + expect(screen.getByRole("switch", { name: "兼容模式" })).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "重试" })); + expect(await screen.findByText("高级设置")).toBeTruthy(); + expect(load).toHaveBeenCalledTimes(2); + }); + + it("saves an advanced setting without turning compatibility mode on", async () => { + const save = vi.spyOn(api, "saveConversion").mockImplementation(async (config) => config); + renderSetting(); + fireEvent.click(await screen.findByText("高级设置")); + const saveButton = screen.getByRole("button", { name: "保存更改" }); + expect(saveButton).toBeDisabled(); + fireEvent.change(screen.getByLabelText("监听地址"), { target: { value: "127.0.0.1:9797" } }); + fireEvent.click(saveButton); + await waitFor(() => expect(save).toHaveBeenCalledWith(expect.objectContaining({ listen: "127.0.0.1:9797", enabled: false }))); + expect(await screen.findByText("已保存兼容模式设置")).toBeTruthy(); + }); + + // A half-typed address belongs to the save button, not to the switch. + it("does not save edited fields when only the switch is used", async () => { + mockStatus = codexInCompatibilityMode; + const save = vi.spyOn(api, "saveConversion").mockImplementation(async (config) => config); + renderSetting(); + fireEvent.click(await screen.findByText("高级设置")); + fireEvent.change(screen.getByLabelText("监听地址"), { target: { value: "127.0.0.1:1" } }); + fireEvent.click(screen.getByRole("switch", { name: "兼容模式" })); + await waitFor(() => expect(save).toHaveBeenCalledWith(expect.objectContaining({ enabled: true, listen: "127.0.0.1:8787" }))); + }); + + it("keeps the details folded and never shows a local key", async () => { + renderSetting(); + const fold = (await screen.findByText("高级设置")).closest("details"); + expect(fold).not.toHaveAttribute("open"); + expect(screen.queryByLabelText("本地 API Key")).toBeNull(); + expect(screen.getByText("启动时自动生成")).toBeTruthy(); + }); +}); diff --git a/frontend/src/components/CompatibilitySetting.tsx b/frontend/src/components/CompatibilitySetting.tsx new file mode 100644 index 00000000..ee9adbbd --- /dev/null +++ b/frontend/src/components/CompatibilitySetting.tsx @@ -0,0 +1,204 @@ +import { Radio } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; + +import { api } from "../backend/api"; +import { useI18n } from "../i18n"; +import { confirmAction } from "../state/confirmDelete"; +import { agentsUsingConversion } from "../state/conversion"; +import { useFeedback } from "../state/FeedbackContext"; +import { useWizard } from "../state/WizardContext"; +import type { ConversionConfig } from "../types/api"; +import { StatusBadge } from "./StatusBadge"; + +/** + * Compatibility mode, as a setting rather than a page. + * + * It is switched on where an Agent needs it -- the setup wizard, an Agent's + * Profile list, a failed model check -- and ends when the last Agent using it + * is given an ordinary Profile. What is left to set by hand is here: stopping + * it for every Agent at once, and the address, local keys and model names the + * adapter itself uses. + */ +export function CompatibilitySetting() { + const { locale, t } = useI18n(); + const { state, refreshStatus } = useWizard(); + const feedback = useFeedback(); + // Stable across receipts, unlike `feedback`, so the load effect can depend on it. + const reportFailure = feedback.failure; + const [config, setConfig] = useState(null); + const [saved, setSaved] = useState(null); + const [saving, setSaving] = useState(false); + const separator = locale === "en" ? ", " : "、"; + + // Retryable from the receipt: without the settings the row has nothing to show. + const load = useCallback(() => { + void api.getConversion().then((loaded) => { + setConfig(loaded); + setSaved(loaded); + }).catch((error) => reportFailure(error, t("无法读取兼容模式设置"), { key: "conversion-load", action: { label: t("重试"), run: load } })); + }, [reportFailure, t]); + useEffect(load, [load]); + + const persist = async (next: ConversionConfig, done: string, fallback: string) => { + setSaving(true); + try { + const result = await api.saveConversion(next); + setConfig(result); + setSaved(result); + feedback.show({ key: "conversion", tone: "success", message: done }); + void refreshStatus(); + } catch (error) { + feedback.failure(error, fallback, { key: "conversion" }); + } finally { + setSaving(false); + } + }; + + const regenerateKey = async () => { + setSaving(true); + try { + const result = await api.regenerateConversionKey(); + setConfig(result); + setSaved(result); + feedback.show({ key: "conversion-key", tone: "success", message: t("已重新生成本地 Key") }); + void refreshStatus(); + } catch (error) { + feedback.failure(error, t("无法重新生成本地 Key"), { key: "conversion-key" }); + } finally { + setSaving(false); + } + }; + + // Who uses it comes from the shared status. Until that has loaded, the row + // must not say that nobody does, nor let it be stopped without the warning + // that names them. + const known = Boolean(state.status); + const users = agentsUsingConversion(state.status); + const names = users.map((user) => user.name).join(separator); + const running = Boolean(saved?.enabled); + const dirty = Boolean(config && saved && ( + config.listen !== saved.listen + || config.anthropic_model !== saved.anthropic_model + || config.responses_model !== saved.responses_model + || config.chat_model !== saved.chat_model + )); + + // The switch only changes whether it runs. Fields being edited below are + // left for their own button, so toggling never saves a half-typed address. + const toggle = async (enabled: boolean) => { + if (!saved) return; + if (!enabled && users.length && !await confirmAction({ + title: t("停止兼容模式"), + message: t("停止后 {agents} 将无法使用,直到重新开启兼容模式或换一个配置模版。", { agents: names }), + confirmLabel: t("停止"), + cancelLabel: t("取消"), + })) return; + if (enabled) await persist({ ...saved, enabled: true }, t("兼容模式已开启"), t("无法开启兼容模式")); + else await persist({ ...saved, enabled: false }, t("兼容模式已停止"), t("无法停止兼容模式")); + }; + + const summary = !known ? t("正在读取环境状态") : running + ? users.length ? t("{agents} 正在使用,使用期间需要保持 BootAgent 运行", { agents: names }) : t("没有 Agent 在使用") + : users.length ? t("已停止,{agents} 暂时无法使用", { agents: names }) : t("Agent 需要时会自动开启"); + + return ( + <> +
+ +
+ {config ? ( +
+ {t("高级设置")} +
+

{t("让只支持特定格式的 Agent 也能用你的模型服务,在本机转换,不经过其他服务器。每个 Agent 用自己的本机 Key 连接,模型和 Key 仍由各自的配置模版管理。")}

+
+
+ + setConfig({ ...config, listen: event.target.value })} + placeholder="127.0.0.1:8787" + spellCheck={false} + autoCorrect="off" + autoCapitalize="none" + /> +
+
+ +
+ + {config.has_api_key ? t("已安全生成") : t("启动时自动生成")} + + {config.has_api_key ? ( + + ) : null} +
+
+ {/* What each Agent is told the model is called. The model that + actually answers is the one in the Agent's own Profile. */} +
+ + setConfig({ ...config, anthropic_model: event.target.value })} + spellCheck={false} + autoCorrect="off" + autoCapitalize="none" + /> +
+
+ + setConfig({ ...config, responses_model: event.target.value })} + spellCheck={false} + autoCorrect="off" + autoCapitalize="none" + /> +
+
+ + setConfig({ ...config, chat_model: event.target.value })} + spellCheck={false} + autoCorrect="off" + autoCapitalize="none" + /> +
+
+ +
+
+ ) : null} + + ); +} diff --git a/frontend/src/components/NavigationSidebar.tsx b/frontend/src/components/NavigationSidebar.tsx index da2b927d..bd1ff3fe 100644 --- a/frontend/src/components/NavigationSidebar.tsx +++ b/frontend/src/components/NavigationSidebar.tsx @@ -1,4 +1,4 @@ -import { FolderCog, Gauge, Images, Layers3, Network, Radio, Settings, ShoppingBag, Sparkles } from "lucide-react"; +import { FolderCog, Gauge, Images, Layers3, Network, Settings, ShoppingBag, Sparkles } from "lucide-react"; import { NavLink } from "react-router-dom"; import { type TranslationKey, useI18n } from "../i18n"; @@ -8,6 +8,8 @@ import { TaskCenter } from "./TaskCenter"; // Only real destinations belong here. /setup/* are wizard steps behind // SetupGuard: listing them made the sidebar look broken, because clicking one // without a selected Agent bounced straight back to the first step. +// Compatibility mode is not one either: it is switched on from an Agent and +// its few settings live in 设置. const navItems: Array<{ to: string; label: TranslationKey; icon: typeof Gauge }> = [ { to: "/overview", label: "环境总览", icon: Gauge }, { to: "/providers", label: "模型服务", icon: Layers3 }, @@ -16,7 +18,6 @@ const navItems: Array<{ to: string; label: TranslationKey; icon: typeof Gauge }> { to: "/mcp", label: "MCP 服务器", icon: Network }, { to: "/skills", label: "Skills", icon: Sparkles }, { to: "/multimodal", label: "多模态能力", icon: Images }, - { to: "/conversion", label: "兼容模式", icon: Radio }, ]; export function NavigationSidebar() { diff --git a/frontend/src/i18n.tsx b/frontend/src/i18n.tsx index 856619f5..418bab29 100644 --- a/frontend/src/i18n.tsx +++ b/frontend/src/i18n.tsx @@ -127,11 +127,11 @@ const english = { "重新生成 Key": "Regenerate key", "无法重新生成本地 Key": "Unable to regenerate the local key", "兼容模式需要的本机端口被占用": "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", + "关闭占用端口的程序,或在「设置」的兼容模式里换一个端口": "Close the program using the port, or choose another port under Compatibility mode in 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", + "请保持 BootAgent 运行,并在「设置」里查看兼容模式": "Keep BootAgent running and check Compatibility mode in Settings", "Claude Desktop 使用基础地址,保存时将调整为 {url}": "Claude Desktop uses the base address. It will be saved as {url}.", "API 协议适配": "API protocol adapter", "启用协议适配": "Enable protocol adaptation", @@ -140,7 +140,6 @@ const english = { "让只支持某一种 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", "创建配置模板": "Create profile", - "查看环境总览": "View environment overview", "了解协议适配": "About protocol adaptation", "适配服务已停止": "Adapter is stopped", "为什么需要它": "Why this exists", @@ -1042,9 +1041,7 @@ const english = { "{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", @@ -1052,18 +1049,18 @@ const english = { "停止后 {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", + "{agents} 正在使用,使用期间需要保持 BootAgent 运行": "Used by {agents}; BootAgent needs to keep running while they are in use", + "没有 Agent 在使用": "No Agent is using it", + "已停止,{agents} 暂时无法使用": "Stopped; {agents} won't work for now", + "Agent 需要时会自动开启": "Turns on by itself when an Agent needs it", + "让只支持特定格式的 Agent 也能用你的模型服务,在本机转换,不经过其他服务器。每个 Agent 用自己的本机 Key 连接,模型和 Key 仍由各自的配置模版管理。": "Lets Agents that only speak one request format use your model service. Requests are converted on this computer and go through no other server. Each Agent connects with its own local key; models and keys stay in each Agent's profile.", "兼容模式需要 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", @@ -1072,23 +1069,13 @@ const english = { "无法确认能否使用兼容模式": "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", diff --git a/frontend/src/pages/ActivationPage.tsx b/frontend/src/pages/ActivationPage.tsx index 191a9860..1d9ba566 100644 --- a/frontend/src/pages/ActivationPage.tsx +++ b/frontend/src/pages/ActivationPage.tsx @@ -8,7 +8,9 @@ import { DownloadProgress } from "../components/DownloadProgress"; import { LogDisclosure } from "../components/LogDisclosure"; import { PageScaffold } from "../components/PageScaffold"; import { useI18n } from "../i18n"; +import { offerAutostart } from "../state/applyConversion"; import { desktopProtocol, profileAgentIdForDesktop, selectedDesktopApp } from "../state/desktopSetup"; +import { useFeedback } from "../state/FeedbackContext"; import { installTaskRoute, taskCanceller, taskKey, useTaskCenter, useTaskRoute, type TaskCanceller } from "../state/TaskCenterContext"; import { useWizard } from "../state/WizardContext"; import type { AgentInstallResult, InstallRequest, InstallResponse } from "../types/api"; @@ -119,6 +121,14 @@ export function ActivationPage() { }; }, [refreshStatus, requestFor, state.model, state.profileId, state.profileLabel, state.provider, t]); + // An Agent set up through compatibility mode only works while BootAgent + // runs, which is worth one question once it has actually been configured. + const reportFailure = useFeedback().failure; + const offerAutostartFor = useCallback((results: AgentInstallResult[]) => { + if (!state.conversion || !results.some((result) => result.status === "configured")) return; + void offerAutostart(t, (error) => reportFailure(error, t("无法保存开机自启动设置"), { key: "autostart" })); + }, [reportFailure, state.conversion, t]); + const startActivationTasks = useCallback((agentIds: string[]) => { const officialScriptAgents = new Set( (state.status?.catalog ?? []) @@ -281,12 +291,13 @@ export function ActivationPage() { if (response.ok || response.results.some((result) => result.status !== "failed" && result.status !== "skipped")) { await refreshStatus(); } + offerAutostartFor(response.results); } catch (error) { const message = isCancellationError(error) ? t("已取消") : describeFailure(error, t("激活失败"), t).message; finishActivationTasks(startedTasks, [], false, message); dispatch({ type: "ACTIVATION_FAILED", message }); } - }, [dispatch, finishActivationTasks, installCliWithConversion, installDesktop, isDesktop, navigate, refreshStatus, registerActivationCanceller, requestFor, startActivationTasks, state.conversion, state.selectedAgentIds, t]); + }, [dispatch, finishActivationTasks, installCliWithConversion, installDesktop, isDesktop, navigate, offerAutostartFor, refreshStatus, registerActivationCanceller, requestFor, startActivationTasks, state.conversion, state.selectedAgentIds, t]); useEffect( () => @@ -384,6 +395,7 @@ export function ActivationPage() { if (response.ok) { await refreshStatus(); } + offerAutostartFor(response.results); } catch (error) { const message = isCancellationError(error) ? t("已取消") : describeFailure(error, t("重试失败"), t).message; finishActivationTasks(startedTasks, [], false, message); diff --git a/frontend/src/pages/AgentProfilePage.test.tsx b/frontend/src/pages/AgentProfilePage.test.tsx index f7f0cf3c..eb3f1843 100644 --- a/frontend/src/pages/AgentProfilePage.test.tsx +++ b/frontend/src/pages/AgentProfilePage.test.tsx @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api } from "../backend/api"; import { FeedbackViewport } from "../components/FeedbackViewport"; +import { resetAutostartOffer } from "../state/applyConversion"; import { FeedbackProvider } from "../state/FeedbackContext"; import type { ProfileSummary, SaveProfileResult, StatusResponse } from "../types/api"; import { AgentProfilePage } from "./AgentProfilePage"; @@ -580,6 +581,43 @@ describe("AgentProfilePage", () => { expect(await screen.findByRole("heading", { name: "overview" })).toBeTruthy(); }); + // The adapter's own Providers are hidden from the picker, so one must not be + // the default either: the picker showed nothing while the new Profile was + // quietly bound to the adapter. + it("starts a new Profile on a model service of the user's, never the adapter's own", async () => { + const status = statusWith([profile({ id: "team-ppio", protocol: "responses" })]); + status.providers["bootagent-converter-for-codex"] = { + name: "BootAgent codex", home: "", base_url: "http://127.0.0.1:8787/v1", has_key: true, created_at: "2026-11-20T00:00:00Z", + } as StatusResponse["providers"][string]; + mockState = { status, statusState: "success" }; + render( + + } /> + , + ); + + await userEvent.click(screen.getByRole("button", { name: "创建配置模版" })); + expect(screen.getByLabelText("配置模版 ID")).toHaveValue("codex-ppio"); + expect(screen.getByRole("combobox", { name: "模型服务" })).toHaveTextContent("PPIO"); + }); + + // Once an Agent depends on BootAgent running, starting with the system is + // worth one question. It used to be asked on the compatibility mode page. + it("asks about starting with the system after switching an Agent to compatibility mode", async () => { + resetAutostartOffer(); + vi.spyOn(api, "activateAgentWithConversion").mockResolvedValue({ + ok: true, agent: "codex", config: "/c", provider: "bootagent-converter-for-codex", model: "gpt-5.6-sol", + restart: "", next: "", upstreamVerified: true, endToEndVerified: true, + }); + vi.spyOn(api, "getSettings").mockResolvedValue({ autostart: false } as never); + const save = vi.spyOn(api, "saveSettings").mockResolvedValue({ autostart: true } as never); + renderPage([profile({ id: "chat-only", label: "Chat only", protocol: "openai" })]); + + await userEvent.click(screen.getByRole("radio", { name: "选择 Chat only" })); + await userEvent.click(screen.getByRole("button", { name: "用兼容模式应用" })); + await waitFor(() => expect(save).toHaveBeenCalledWith({ autostart: true })); + }); + 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" }), diff --git a/frontend/src/pages/AgentProfilePage.tsx b/frontend/src/pages/AgentProfilePage.tsx index 91a90ffa..1b9db612 100644 --- a/frontend/src/pages/AgentProfilePage.tsx +++ b/frontend/src/pages/AgentProfilePage.tsx @@ -11,8 +11,8 @@ import { SelectField } from "../components/SelectField"; import { useI18n } from "../i18n"; import { desktopApps, desktopProfileUsable, desktopProfiles, desktopProtocol, profileAgentIdForDesktop } from "../state/desktopSetup"; import { byProfileCreatedAt, byProviderCreatedAt, preferProviderWithKey } from "../state/ranking"; -import { applyConversion, confirmConversion, conversionTargets } from "../state/applyConversion"; -import { canConvertProtocol, conversionTargetFor, converterProfileName, isConverterID, providerDisplayName } from "../state/conversion"; +import { applyConversion, confirmConversion, conversionTargets, offerAutostart } from "../state/applyConversion"; +import { canConvertProtocol, conversionTargetFor, converterProfileName, isConverterID, providerDisplayName, userProviders } from "../state/conversion"; import { useFeedback } from "../state/FeedbackContext"; import { saveReceipt } from "../state/saveReceipt"; import { useWizard } from "../state/WizardContext"; @@ -225,8 +225,13 @@ export function AgentProfilePage() { } }; + const autostartFailed = (error: unknown) => feedback.failure(error, t("无法保存开机自启动设置"), { key: "autostart" }); + const openCreate = () => { - const usable = byProviderCreatedAt(status.providers).filter(([, meta]) => + // The adapter's own Providers are never offered (ProviderSegment hides + // them), so one must not be preselected either: the picker would show + // nothing while the draft still pointed at it. + const usable = byProviderCreatedAt(userProviders(status.providers)).filter(([, meta]) => protocol === "anthropic" ? meta.anthropic_base_url : meta.base_url, ); const provider = preferProviderWithKey(usable)?.[0] || "jiekou"; @@ -383,6 +388,7 @@ export function AgentProfilePage() { }); } await refreshStatus(); + if (requiresConversion) void offerAutostart(t, autostartFailed); } catch (error) { // Stays on this page: the choice that failed is what the user may change. feedback.failure(error, t("应用配置模版失败"), { key: `apply:${agentId}` }); @@ -413,6 +419,7 @@ export function AgentProfilePage() { try { await applyConversion(status, conversionTargets(status, [app?.id || owner]), source, t); await refreshStatus(); + void offerAutostart(t, autostartFailed); } catch (error) { feedback.failure(error, t("无法开启兼容模式"), { key: `apply:${agentId}` }); setBusy(false); diff --git a/frontend/src/pages/ConversionPage.test.tsx b/frontend/src/pages/ConversionPage.test.tsx deleted file mode 100644 index 5dd92858..00000000 --- a/frontend/src/pages/ConversionPage.test.tsx +++ /dev/null @@ -1,167 +0,0 @@ -import { fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { MemoryRouter } from "react-router-dom"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { api } from "../backend/api"; -import { BootAgentApiError } from "../backend/errors"; -import { FeedbackProvider } from "../state/FeedbackContext"; -import type { StatusResponse } from "../types/api"; -import { ConversionPage } from "./ConversionPage"; - -let mockStatus: StatusResponse | null = null; - -vi.mock("../state/WizardContext", () => ({ - useWizard: () => ({ state: { status: mockStatus }, refreshStatus: vi.fn() }), -})); - -beforeEach(() => { - localStorage.setItem("bootagent.locale", "zh-CN"); - vi.spyOn(api, "getConversion").mockResolvedValue({ - enabled: false, - listen: "127.0.0.1:8787", - has_api_key: false, - target_profile: "", - routes: {}, - anthropic_model: "claude-sonnet-5", - responses_model: "gpt-5.6-sol", - chat_model: "gpt-5.6-sol", - }); -}); - -afterEach(() => { - localStorage.clear(); - vi.restoreAllMocks(); - mockStatus = null; -}); - -describe("ConversionPage", () => { - it("leads with status and the Agents using it, and keeps the format details behind a disclosure", async () => { - render( - - - , - ); - - const status = await screen.findByText("兼容模式未开启"); - const users = screen.getByText("正在使用的 Agent"); - const guidance = screen.getByText("了解兼容模式"); - - expect(status.compareDocumentPosition(users) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(users.compareDocumentPosition(guidance) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - // There is no single model to pick: each Agent has its own. - expect(screen.queryByRole("combobox")).toBeNull(); - const formats = screen.getByText(/OpenAI Responses 格式/); - expect(formats.closest("details")).not.toHaveAttribute("open"); - fireEvent.click(guidance); - expect(formats.closest("details")).toHaveAttribute("open"); - }); - - it("offers one primary action, and no stop button while stopped", async () => { - render( - - - , - ); - - // Nothing uses it yet, so there is nothing to turn on. - expect(await screen.findByRole("button", { name: "开启兼容模式" })).toBeDisabled(); - expect(screen.queryByRole("button", { name: "停止兼容模式" })).toBeNull(); - }); - - // A failed load leaves the page with nothing on it, so the receipt carries - // the retry rather than the page. - it("offers a retry when the settings cannot be read", async () => { - const load = vi.spyOn(api, "getConversion").mockRejectedValueOnce(new BootAgentApiError("boom", "INTERNAL_ERROR", true, 500)); - render( - - - - - , - ); - const receipt = await screen.findByRole("alert"); - expect(receipt).toHaveTextContent("无法读取兼容模式设置"); - fireEvent.click(screen.getByRole("button", { name: "重试" })); - expect(await screen.findByText("兼容模式未开启")).toBeTruthy(); - expect(load).toHaveBeenCalledTimes(2); - }); - - it("confirms a saved change with a receipt instead of a line in the page", async () => { - vi.spyOn(api, "saveConversion").mockImplementation(async (config) => config); - vi.spyOn(api, "getSettings").mockResolvedValue({ autostart: true } as never); - render( - - - - - , - ); - await screen.findByText("兼容模式未开启"); - fireEvent.click(screen.getByRole("button", { name: "高级设置" })); - fireEvent.change(screen.getByLabelText("监听地址"), { target: { value: "127.0.0.1:9797" } }); - fireEvent.click(screen.getByRole("button", { name: "保存更改" })); - expect(await screen.findByText("已保存兼容模式设置")).toBeTruthy(); - }); - - it("saves an advanced setting without turning compatibility mode on", async () => { - const save = vi.spyOn(api, "saveConversion").mockImplementation(async (config) => config); - vi.spyOn(api, "getSettings").mockResolvedValue({ autostart: true } as never); - render( - - - , - ); - - await screen.findByText("兼容模式未开启"); - fireEvent.click(screen.getByRole("button", { name: "高级设置" })); - fireEvent.change(screen.getByLabelText("监听地址"), { target: { value: "127.0.0.1:9797" } }); - fireEvent.click(screen.getByRole("button", { name: "保存更改" })); - await waitFor(() => expect(save).toHaveBeenCalledWith(expect.objectContaining({ listen: "127.0.0.1:9797", enabled: false }))); - }); - - // The single shared target this replaced showed every Agent on the same - // model; each now names the service its own requests go to. - it("shows each Agent's own model service and links to change only that Agent", async () => { - mockStatus = { - providers: { ppio: { name: "PPIO" }, novita: { name: "Novita" } }, - catalog: [{ id: "codex", name: "Codex" }, { id: "claude-code", name: "Claude Code" }], - agents: { - codex: { profileId: "bootagent-converter-for-codex" }, - "claude-code": { profileId: "bootagent-converter-for-claude-code" }, - }, - desktopAgents: [], - profiles: [ - { id: "ppio-chat", label: "PPIO", provider: "ppio", model: "deepseek-v3", protocol: "openai" }, - { id: "novita-chat", label: "Novita", provider: "novita", model: "glm-5", protocol: "openai" }, - ], - conversionRoutes: { codex: "ppio-chat", "claude-code": "novita-chat" }, - } as unknown as StatusResponse; - render( - - - , - ); - - const list = await screen.findByRole("list"); - const rows = Array.from(list.querySelectorAll("li")).map((row) => row.textContent); - expect(rows[0]).toContain("Codex"); - expect(rows[0]).toContain("PPIO · deepseek-v3"); - expect(rows[1]).toContain("Claude Code"); - expect(rows[1]).toContain("Novita · glm-5"); - expect(screen.getByRole("button", { name: "为 Codex 更换模型" })).toBeTruthy(); - expect(screen.getByRole("button", { name: "开启兼容模式" })).toBeEnabled(); - }); - - it("does not expose a local API key input", async () => { - render( - - - , - ); - - await screen.findByText("兼容模式未开启"); - fireEvent.click(screen.getByRole("button", { name: "高级设置" })); - expect(screen.queryByLabelText("本地 API Key")).toBeNull(); - expect(screen.getByText("启动时自动生成")).toBeTruthy(); - }); -}); diff --git a/frontend/src/pages/ConversionPage.tsx b/frontend/src/pages/ConversionPage.tsx deleted file mode 100644 index fe012a2d..00000000 --- a/frontend/src/pages/ConversionPage.tsx +++ /dev/null @@ -1,273 +0,0 @@ -import { ChevronDown, ChevronUp, CircleHelp, Power } from "lucide-react"; -import { useCallback, useEffect, useRef, useState } from "react"; -import { Link, useNavigate } from "react-router-dom"; - -import { api } from "../backend/api"; -import { PageScaffold } from "../components/PageScaffold"; -import { StatusBadge } from "../components/StatusBadge"; -import { useI18n } from "../i18n"; -import { useWizard } from "../state/WizardContext"; -import { agentsUsingConversion, providerDisplayName } from "../state/conversion"; -import { confirmAction } from "../state/confirmDelete"; -import { useFeedback } from "../state/FeedbackContext"; -import type { ConversionConfig } from "../types/api"; - -/** - * Compatibility mode: the local adapter that lets an Agent speaking its own - * format use a Chat Completions-only model service. - * - * Mostly a status page. Agents are switched to it where the problem shows -- - * the setup wizard's connection test, an Agent's Profile list, a failed model - * check -- so this page says what is running and, for each Agent, which model - * service its requests go to. Each Agent has its own route; changing one is - * done on that Agent's page and changes nothing for the others. - */ -export function ConversionPage() { - const navigate = useNavigate(); - const { locale, t } = useI18n(); - const { state, refreshStatus } = useWizard(); - const status = state.status; - const [config, setConfig] = useState(null); - const [saved, setSaved] = useState(null); - const feedback = useFeedback(); - // Stable across receipts, unlike `feedback`, so the load effect can depend on it. - const reportFailure = feedback.failure; - const [saving, setSaving] = useState(false); - const [showAdvanced, setShowAdvanced] = useState(false); - const autostartPrompted = useRef(false); - const separator = locale === "en" ? ", " : "、"; - - const maybeAskAutostart = async (enabled: boolean) => { - if (!enabled || autostartPrompted.current) return; - autostartPrompted.current = true; - try { - const settings = await api.getSettings(); - if (settings.autostart) return; - if (!await confirmAction({ - title: t("开机自启动"), - message: t("兼容模式需要 BootAgent 保持运行。要让 BootAgent 随系统启动吗?"), - confirmLabel: t("开机自启动"), - cancelLabel: t("暂不启用"), - })) return; - await api.saveSettings({ autostart: true }); - } catch (error) { - feedback.failure(error, t("无法保存开机自启动设置"), { key: "autostart" }); - } - }; - - // Retryable from the receipt: a failed load leaves the page with nothing to - // show, and the receipt is the only control on it. - const load = useCallback(() => { - void api.getConversion().then((loaded) => { - setConfig(loaded); - setSaved(loaded); - void maybeAskAutostart(loaded.enabled); - }).catch((error) => reportFailure(error, t("无法读取兼容模式设置"), { key: "conversion-load", action: { label: t("重试"), run: load } })); - // maybeAskAutostart only reads a ref and stable calls. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [reportFailure, t]); - useEffect(load, [load]); - - const persist = async (next: ConversionConfig, done: string, fallback: string) => { - setSaving(true); - try { - const result = await api.saveConversion(next); - setConfig(result); - setSaved(result); - feedback.show({ key: "conversion", tone: "success", message: done }); - await maybeAskAutostart(result.enabled); - void refreshStatus(); - } catch (error) { - feedback.failure(error, fallback, { key: "conversion" }); - } finally { - setSaving(false); - } - }; - - const regenerateKey = async () => { - setSaving(true); - try { - const result = await api.regenerateConversionKey(); - setConfig(result); - setSaved(result); - feedback.show({ key: "conversion-key", tone: "success", message: t("已重新生成本地 Key") }); - void refreshStatus(); - } catch (error) { - feedback.failure(error, t("无法重新生成本地 Key"), { key: "conversion-key" }); - } finally { - setSaving(false); - } - }; - - const users = agentsUsingConversion(status); - const dirty = Boolean(config && saved && ( - config.listen !== saved.listen - || config.anthropic_model !== saved.anthropic_model - || config.responses_model !== saved.responses_model - || config.chat_model !== saved.chat_model - )); - - const stop = async () => { - if (!config) return; - if (users.length && !await confirmAction({ - title: t("停止兼容模式"), - message: t("停止后 {agents} 将无法使用,直到重新开启兼容模式或换一个配置模版。", { agents: users.map((user) => user.name).join(separator) }), - confirmLabel: t("停止"), - cancelLabel: t("取消"), - })) return; - await persist({ ...config, enabled: false }, t("兼容模式已停止"), t("无法停止兼容模式")); - }; - - // One primary action. Unsaved changes: save them, leaving it running or not. - // Otherwise stopped: turn it on, which only makes sense once an Agent uses - // it. Stopping is the secondary action, and only exists while it runs. - const running = Boolean(config?.enabled); - const savesChanges = dirty || running; - const primaryLabel = savesChanges ? t("保存更改") : t("开启兼容模式"); - const onPrimary = () => { - if (!config) return; - if (savesChanges) void persist(config, t("已保存兼容模式设置"), t("无法保存兼容模式设置")); - else void persist({ ...config, enabled: true }, t("兼容模式已开启"), t("无法开启兼容模式")); - }; - - return ( - void stop()} disabled={saving}> - {t("停止兼容模式")} - - ) : null} - primaryLabel={primaryLabel} - onPrimary={onPrimary} - primaryDisabled={!config || (savesChanges ? !dirty : users.length === 0)} - primaryBusy={saving} - > - {config ?
-
-
- -
-
-

{t("正在使用的 Agent")}

-
- {users.length === 0 ? ( -
- {t("还没有 Agent 使用兼容模式")} - {t("查看环境总览")} -
- ) : ( -
    - {users.map((user) => ( -
  • - {user.name} - - {user.target - ? `${status ? providerDisplayName(status.providers, user.target.provider, t) : user.target.provider} · ${user.target.model}` - : t("使用的配置模版已删除")} - - {running ? {t("运行中")} : {t("已停止")}} - -
  • - ))} -
- )} -
- -
- - - {showAdvanced ? ( -
-
- - setConfig({ ...config, listen: event.target.value })} - placeholder="127.0.0.1:8787" - spellCheck={false} - autoCorrect="off" - autoCapitalize="none" - /> -
-
- -
- - {config.has_api_key ? t("已安全生成") : t("启动时自动生成")} - - {config.has_api_key ? ( - - ) : null} -
-
- {/* What each Agent is told the model is called. The model that - actually answers is the one chosen above. */} -
- - setConfig({ ...config, anthropic_model: event.target.value })} - spellCheck={false} - autoCorrect="off" - autoCapitalize="none" - /> -
-
- - setConfig({ ...config, responses_model: event.target.value })} - spellCheck={false} - autoCorrect="off" - autoCapitalize="none" - /> -
-
- - setConfig({ ...config, chat_model: event.target.value })} - spellCheck={false} - autoCorrect="off" - autoCapitalize="none" - /> -
-
- ) : null} -
- -
- {t("了解兼容模式")} -
-

{t("Codex 发出的是 OpenAI Responses 格式,Claude Code 是 Anthropic Messages 格式,很多模型服务只支持 OpenAI Chat Completions。BootAgent 在本机把前两种转换成 Chat Completions,再发往每个 Agent 各自选择的模型。")}

-

{t("每个 Agent 用自己的本机 Key 连接,互不影响;模型和 Key 仍由各自的配置模版管理。")}

-
-
-
: null} -
- ); -} diff --git a/frontend/src/pages/ProfilesPage.tsx b/frontend/src/pages/ProfilesPage.tsx index 64f82dd0..deb50d77 100644 --- a/frontend/src/pages/ProfilesPage.tsx +++ b/frontend/src/pages/ProfilesPage.tsx @@ -10,7 +10,7 @@ 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 { applyConversion, confirmConversion, conversionTargets, offerAutostart } from "../state/applyConversion"; import { confirmDelete } from "../state/confirmDelete"; import { useFeedback } from "../state/FeedbackContext"; import { saveReceipt } from "../state/saveReceipt"; @@ -266,6 +266,7 @@ export function ProfilesPage() { setChecked(null); feedback.show({ key, tone: "success", message: t("{agent} 已改用兼容模式", { agent: names.join(separator) }) }); await refreshStatus(); + void offerAutostart(t, (error) => feedback.failure(error, t("无法保存开机自启动设置"), { key: "autostart" })); } catch (error) { feedback.failure(error, t("无法开启兼容模式"), { key }); } finally { diff --git a/frontend/src/pages/SettingsPage.test.tsx b/frontend/src/pages/SettingsPage.test.tsx index 09e3c9f0..016ca197 100644 --- a/frontend/src/pages/SettingsPage.test.tsx +++ b/frontend/src/pages/SettingsPage.test.tsx @@ -1,7 +1,7 @@ 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api } from "../backend/api"; import { BootAgentApiError } from "../backend/errors"; @@ -12,9 +12,33 @@ import { SettingsPage } from "./SettingsPage"; const show = () => render(} />transfer child} />); +// The compatibility mode rows read the Agents using it from the shared status. +vi.mock("../state/WizardContext", () => ({ + useWizard: () => ({ state: { status: null }, refreshStatus: vi.fn() }), +})); + describe("SettingsPage", () => { + beforeEach(() => { + vi.spyOn(api, "getConversion").mockResolvedValue({ + enabled: false, + listen: "127.0.0.1:8787", + has_api_key: false, + target_profile: "", + routes: {}, + anthropic_model: "claude-sonnet-5", + responses_model: "gpt-5.6-sol", + chat_model: "gpt-5.6-sol", + }); + }); afterEach(() => vi.restoreAllMocks()); + // Compatibility mode has no page of its own; what can be set by hand is here. + it("holds compatibility mode as a setting", async () => { + show(); + expect(await screen.findByRole("switch", { name: "兼容模式" })).not.toBeChecked(); + expect(await screen.findByText("高级设置")).toBeTruthy(); + }); + it("contains appearance and download settings and opens the transfer child page", async () => { vi.spyOn(api, "getSettings").mockResolvedValue({ schema_version: 1, diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsx index 68e9b0c8..15e98bf8 100644 --- a/frontend/src/pages/SettingsPage.tsx +++ b/frontend/src/pages/SettingsPage.tsx @@ -5,6 +5,7 @@ import { useNavigate } from "react-router-dom"; import { api, failureLine } from "../backend/api"; import { OTA_PROGRESS_TARGET } from "../backend/wails"; +import { CompatibilitySetting } from "../components/CompatibilitySetting"; import { MirrorSetting } from "../components/MirrorSetting"; import { PageScaffold } from "../components/PageScaffold"; import { SelectField } from "../components/SelectField"; @@ -230,6 +231,10 @@ export function SettingsPage() { /> +
+

{t("兼容模式")}

+ +

{t("数据")}

diff --git a/frontend/src/state/applyConversion.test.ts b/frontend/src/state/applyConversion.test.ts new file mode 100644 index 00000000..baaaa33b --- /dev/null +++ b/frontend/src/state/applyConversion.test.ts @@ -0,0 +1,52 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { api } from "../backend/api"; +import { sourceTranslate } from "../i18n"; +import type { Settings } from "../types/api"; +import { offerAutostart, resetAutostartOffer } from "./applyConversion"; +import * as confirm from "./confirmDelete"; + +const settings = (autostart: boolean) => ({ autostart }) as Settings; + +beforeEach(() => resetAutostartOffer()); +afterEach(() => vi.restoreAllMocks()); + +// An Agent in compatibility mode stops working when BootAgent is not running, +// so switching one to it is when starting with the system is worth a question. +describe("offerAutostart", () => { + it("turns on starting with the system when the user agrees", async () => { + vi.spyOn(api, "getSettings").mockResolvedValue(settings(false)); + const save = vi.spyOn(api, "saveSettings").mockResolvedValue(settings(true)); + const ask = vi.spyOn(confirm, "confirmAction").mockResolvedValue(true); + await offerAutostart(sourceTranslate, vi.fn()); + expect(ask).toHaveBeenCalledWith(expect.objectContaining({ message: "兼容模式需要 BootAgent 保持运行。要让 BootAgent 随系统启动吗?" })); + expect(save).toHaveBeenCalledWith({ autostart: true }); + }); + + it("does not ask when BootAgent already starts with the system", async () => { + vi.spyOn(api, "getSettings").mockResolvedValue(settings(true)); + const ask = vi.spyOn(confirm, "confirmAction"); + await offerAutostart(sourceTranslate, vi.fn()); + expect(ask).not.toHaveBeenCalled(); + }); + + it("asks once, and leaves the setting alone after a no", async () => { + vi.spyOn(api, "getSettings").mockResolvedValue(settings(false)); + const save = vi.spyOn(api, "saveSettings"); + const ask = vi.spyOn(confirm, "confirmAction").mockResolvedValue(false); + await offerAutostart(sourceTranslate, vi.fn()); + await offerAutostart(sourceTranslate, vi.fn()); + expect(ask).toHaveBeenCalledTimes(1); + expect(save).not.toHaveBeenCalled(); + }); + + it("reports a setting that could not be saved", async () => { + const failure = new Error("autostart is not supported on this platform"); + vi.spyOn(api, "getSettings").mockResolvedValue(settings(false)); + vi.spyOn(api, "saveSettings").mockRejectedValue(failure); + vi.spyOn(confirm, "confirmAction").mockResolvedValue(true); + const report = vi.fn(); + await offerAutostart(sourceTranslate, report); + expect(report).toHaveBeenCalledWith(failure); + }); +}); diff --git a/frontend/src/state/applyConversion.ts b/frontend/src/state/applyConversion.ts index 3835f77c..d0f77c9a 100644 --- a/frontend/src/state/applyConversion.ts +++ b/frontend/src/state/applyConversion.ts @@ -33,6 +33,42 @@ export async function confirmConversion(t: Translate): Promise { }); } +let autostartOffered = false; + +/** + * Asks, once per session, whether BootAgent should start with the system. An + * Agent in compatibility mode only works while BootAgent runs, so the moment + * one is switched to it is when this matters. Never asked when BootAgent + * already starts with the system, and never in the way of the result: callers + * do not wait for it. + */ +export async function offerAutostart(t: Translate, reportFailure: (error: unknown) => void): Promise { + if (autostartOffered) return; + autostartOffered = true; + try { + if ((await api.getSettings()).autostart) return; + } catch { + // Unreadable settings are not worth a question about them. + return; + } + if (!await confirmAction({ + title: t("开机自启动"), + message: t("兼容模式需要 BootAgent 保持运行。要让 BootAgent 随系统启动吗?"), + confirmLabel: t("开机自启动"), + cancelLabel: t("暂不启用"), + })) return; + try { + await api.saveSettings({ autostart: true }); + } catch (error) { + reportFailure(error); + } +} + +/** Lets a test ask again. */ +export function resetAutostartOffer(): void { + autostartOffered = false; +} + /** * The Chat Completions Profile compatibility mode forwards to for `source`: * the source itself when it already is one, an existing Profile with the same diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index a5233f4f..67d2866a 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -2176,62 +2176,19 @@ .provider-editor-wide, .profile-editor-wide { grid-column: 1 / -1; } -.conversion-editor { width: 100%; max-width: none; border-top: 0; border-bottom: 0; } -.conversion-editor .select-field { width: 100%; } -.conversion-editor .select-field-trigger { min-height: 38px; border-color: var(--border-strong); background: var(--surface-subtle); } -.conversion-action.is-running { border-color: var(--red); color: var(--red); } -.conversion-action.is-running:hover { background: var(--red-soft); } -.conversion-action.is-stopped { border-color: var(--green); color: var(--green); } -.conversion-action.is-stopped:hover { background: var(--green-soft); } - -.conversion-status { display: flex; align-items: center; gap: 10px; padding: 11px 12px; margin-bottom: 18px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface-subtle); } -.conversion-status-dot { width: 8px; height: 8px; flex: 0 0 auto; border-radius: 50%; background: var(--red); } -.conversion-status.is-running .conversion-status-dot { background: var(--green); } -.conversion-status div { min-width: 0; display: flex; align-items: baseline; gap: 8px; } -.conversion-status strong { font-size: 13px; color: var(--text-primary); } -.conversion-status span:last-child { overflow: hidden; color: var(--text-tertiary); font-size: 12px; text-overflow: ellipsis; white-space: nowrap; } - -/* Agent list */ -.conversion-agents { margin-bottom: 20px; } -.conversion-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; } -.conversion-section-heading h3 { margin: 0; font-size: 12px; font-weight: 600; color: var(--text-secondary); } -.conversion-section-heading > span { color: var(--text-tertiary); font-size: 11px; } -.conversion-agent-list { list-style: none; margin: 8px 0 0; padding: 0; border: 1px solid var(--border); border-radius: var(--radius-control); overflow: hidden; } -.conversion-agent-list li { display: flex; align-items: center; gap: 10px; padding: 9px 14px; border-bottom: 1px solid var(--border-faint); font-size: 13px; } -.conversion-agent-list li:last-child { border-bottom: 0; } -.conversion-agent-name { font-weight: 500; color: var(--text-primary); } -.conversion-agent-protocol { color: var(--text-tertiary); font-size: 12px; margin-left: 2px; } -/* push status badge to the right */ -.conversion-agent-list li > :last-child { margin-left: auto; } - -/* Target profile field */ -.conversion-editor .provider-editor-grid { margin-bottom: 20px; } -.conversion-empty-action { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 7px; color: var(--text-tertiary); font-size: 12px; } -.conversion-empty-action a { flex: 0 0 auto; color: var(--accent); font-weight: 500; text-decoration: none; } -.conversion-empty-action a:hover { text-decoration: underline; } - -/* Advanced-settings toggle */ -.conversion-advanced { margin-top: 4px; } -.conversion-advanced-toggle { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface-subtle); color: var(--text-secondary); font-size: 13px; cursor: pointer; } -.conversion-advanced-toggle:hover { background: var(--surface-pressed); color: var(--text-primary); } -.conversion-advanced-toggle .conversion-hint { margin-left: 6px; font-size: 11px; color: var(--text-tertiary); font-weight: 400; } -.conversion-advanced .provider-editor-grid { margin-top: 16px; } +/* Compatibility mode in 设置: the switch row, and one fold for what the adapter + itself uses. The fold is a settings row so it keeps the section's rules. */ +.settings-row.compatibility-advanced { display: block; padding: 0 10px; } +.compatibility-advanced summary { min-height: 40px; display: flex; align-items: center; gap: 6px; color: var(--text-secondary); font-size: 12px; cursor: pointer; list-style: none; } +.compatibility-advanced summary::-webkit-details-marker { display: none; } +.compatibility-advanced summary::after { content: "+"; } +.compatibility-advanced[open] summary::after { content: "-"; } +.compatibility-advanced summary:hover { color: var(--text-primary); } +.compatibility-advanced-body { padding: 2px 0 14px; } +.compatibility-advanced-body p { max-width: 720px; margin: 0 0 14px; color: var(--text-secondary); font-size: 12px; line-height: 1.55; } +.compatibility-advanced-body .provider-editor-grid { margin-bottom: 14px; } .conversion-key-status { min-width: 0; min-height: 38px; display: flex; align-items: center; gap: 10px; } .conversion-key-status .button { min-width: 0; margin-left: auto; white-space: nowrap; } -.conversion-guidance { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border-faint); color: var(--text-secondary); font-size: 12px; } -.conversion-guidance summary { display: inline-flex; align-items: center; gap: 6px; color: var(--text-secondary); cursor: pointer; font-weight: 500; list-style: none; } -.conversion-guidance summary::-webkit-details-marker { display: none; } -.conversion-guidance div { max-width: 720px; padding-top: 10px; } -.conversion-guidance p { margin: 0 0 7px; line-height: 1.55; } -.conversion-guidance p:last-child { margin-bottom: 0; } - -/* Section sub-heading above the three model fields */ -.conversion-subheading { margin: 20px 0 4px; font-size: 12px; font-weight: 600; color: var(--text-secondary); letter-spacing: 0.04em; text-transform: uppercase; } - -/* Generic hint / caption text used across the page */ -.conversion-hint { display: block; margin-top: 5px; font-size: 12px; line-height: 1.5; color: var(--text-tertiary); } -/* One-liner intro sentence at the top of the page */ -.conversion-intro { margin: 0 0 20px; font-size: 13px; line-height: 1.6; color: var(--text-secondary); } @media (max-width: 560px) { .conversion-key-status { align-items: stretch; flex-direction: column; } diff --git a/internal/app/agent_conversion_test.go b/internal/app/agent_conversion_test.go index d658d9ff..8cbc2f2e 100644 --- a/internal/app/agent_conversion_test.go +++ b/internal/app/agent_conversion_test.go @@ -355,3 +355,158 @@ func TestProbeProviderReportsAProtocolCompatibilityModeCanServe(t *testing.T) { }) } } + +// leaveCompatibilityMode applies an ordinary Profile to an Agent, which is the +// only way an Agent leaves compatibility mode. +func leaveCompatibilityMode(t *testing.T, core *UseCases, agentID string) { + t.Helper() + protocol, err := conversionAgentProtocol(agentID) + if err != nil { + t.Fatal(err) + } + if _, err := core.providers.Get("native-upstream"); err != nil { + if _, err := core.SaveProvider(context.Background(), provider.Entry{ + ID: "native-upstream", Name: "Native upstream", BaseURL: "https://native.example/v1", AnthropicBaseURL: "https://native.example", APIKey: "native-secret", + }, true, false); err != nil { + t.Fatal(err) + } + } + profileID := "native-" + agentID + if _, err := core.SaveProfile(context.Background(), SaveProfileOptions{ + ID: profileID, Label: profileID, Provider: "native-upstream", Model: "model-n", Protocol: protocol, ConfigMode: "provider", + }); err != nil { + t.Fatal(err) + } + if _, err := core.ActivateAgent(context.Background(), ActivateAgentOptions{ + AgentID: agentID, Provider: "native-upstream", Model: "model-n", ProfileID: profileID, + }); err != nil { + t.Fatal(err) + } +} + +func adapterListening(listen string) bool { + connection, err := net.Dial("tcp", listen) + if err != nil { + return false + } + _ = connection.Close() + return true +} + +// Compatibility mode has no switch of its own to remember. It ends where it +// began, on the Agent: one that moves to an ordinary Profile gives up its +// route, and the adapter stops when the last one has. +func TestSettleConversionDropsTheRoutesOfAgentsThatLeftAndStopsWhenNoneIsLeft(t *testing.T) { + upstream := chatOnlyUpstream(t) + core, _, listen := chatProfileCore(t, upstream.URL) + for _, agentID := range []string{"codex", "claude-code"} { + if _, err := core.ConfigureAgentWithConversion(context.Background(), agentID, "chat-upstream"); err != nil { + t.Fatal(err) + } + } + + leaveCompatibilityMode(t, core, "codex") + if err := core.SettleConversion(context.Background()); err != nil { + t.Fatal(err) + } + conversion, err := core.Conversion(context.Background()) + if err != nil || !conversion.Enabled || len(conversion.Routes) != 1 || conversion.Routes["claude-code"] != "chat-upstream" { + t.Fatalf("after Codex left: %#v, err=%v", conversion, err) + } + if !adapterListening(listen) { + t.Fatal("the adapter stopped while Claude Code still used it") + } + + leaveCompatibilityMode(t, core, "claude-code") + if err := core.SettleConversion(context.Background()); err != nil { + t.Fatal(err) + } + conversion, err = core.Conversion(context.Background()) + if err != nil || conversion.Enabled || len(conversion.Routes) != 0 { + t.Fatalf("after the last Agent left: %#v, err=%v", conversion, err) + } + if adapterListening(listen) { + t.Fatal("the adapter kept running with no Agent pointed at it") + } +} + +// An Agent that left compatibility mode used to leave its route behind, and a +// route whose Profile was then deleted failed every later save: the adapter +// could not be stopped, no other Agent could be switched to it, and its keys +// could not be regenerated. +func TestALeftoverRouteDoesNotBlockCompatibilityModeForOtherAgents(t *testing.T) { + upstream := chatOnlyUpstream(t) + core, _, listen := chatProfileCore(t, upstream.URL) + if _, err := core.SaveProfile(context.Background(), SaveProfileOptions{ + ID: "short-lived", Label: "Short-lived", Provider: "chat-upstream", Model: "model-b", Protocol: provider.ProtocolOpenAI, ConfigMode: "provider", + }); err != nil { + t.Fatal(err) + } + if _, err := core.ConfigureAgentWithConversion(context.Background(), "codex", "short-lived"); err != nil { + t.Fatal(err) + } + // Not settled: this is the state an earlier version left on disk. + leaveCompatibilityMode(t, core, "codex") + if err := core.DeleteProfile(context.Background(), "short-lived"); err != nil { + t.Fatal(err) + } + if conversion, _ := core.Conversion(context.Background()); conversion.Routes["codex"] != "short-lived" { + t.Fatalf("the leftover route this test is about is missing: %#v", conversion.Routes) + } + + if _, err := core.ConfigureAgentWithConversion(context.Background(), "claude-code", "chat-upstream"); err != nil { + t.Fatalf("another Agent could not use compatibility mode: %v", err) + } + if _, err := core.RegenerateConversionAPIKey(context.Background()); err != nil { + t.Fatalf("local keys could not be regenerated: %v", err) + } + if _, err := core.SetConversionEnabled(context.Background(), false); err != nil { + t.Fatalf("compatibility mode could not be stopped: %v", err) + } + if adapterListening(listen) { + t.Fatal("the adapter kept running after it was stopped") + } + // And the next settle clears it away, without stopping what is in use. + if _, err := core.SetConversionEnabled(context.Background(), true); err != nil { + t.Fatal(err) + } + if err := core.SettleConversion(context.Background()); err != nil { + t.Fatal(err) + } + conversion, err := core.Conversion(context.Background()) + if err != nil || !conversion.Enabled || len(conversion.Routes) != 1 || conversion.Routes["claude-code"] != "chat-upstream" { + t.Fatalf("after settling: %#v, err=%v", conversion, err) + } +} + +// The adapter only converts into Chat Completions. Changing what the target +// Profile speaks would have every request of the Agent behind it refused, so +// it is refused at the edit, like deleting the Profile is. +func TestChangingTheProtocolOfARouteTargetIsRefusedWhileAnAgentUsesIt(t *testing.T) { + upstream := chatOnlyUpstream(t) + core, _, _ := chatProfileCore(t, upstream.URL) + if _, err := core.ConfigureAgentWithConversion(context.Background(), "codex", "chat-upstream"); err != nil { + t.Fatal(err) + } + edit := SaveProfileOptions{ID: "chat-upstream", Label: "Chat upstream", Provider: "chat-upstream", Model: "model-a", Protocol: provider.ProtocolResponses, ConfigMode: "provider"} + if _, err := core.SaveProfile(context.Background(), edit); err == nil || !strings.Contains(err.Error(), "codex") { + t.Fatalf("protocol change error = %v", err) + } + if stored := core.profileByID("chat-upstream"); stored.Protocol != provider.ProtocolOpenAI { + t.Fatalf("the refused edit was stored: protocol = %q", stored.Protocol) + } + // Any other edit still goes through. + edit.Protocol, edit.Model = provider.ProtocolOpenAI, "model-b" + if _, err := core.SaveProfile(context.Background(), edit); err != nil { + t.Fatal(err) + } + + leaveCompatibilityMode(t, core, "codex") + if err := core.SettleConversion(context.Background()); err != nil { + t.Fatal(err) + } + edit.Protocol = provider.ProtocolResponses + if _, err := core.SaveProfile(context.Background(), edit); err != nil { + t.Fatalf("the Profile could not be changed once nothing was forwarded to it: %v", err) + } +} diff --git a/internal/app/conversion.go b/internal/app/conversion.go index 9a5ffdd5..ff602deb 100644 --- a/internal/app/conversion.go +++ b/internal/app/conversion.go @@ -307,6 +307,9 @@ func (u *UseCases) ensureConversionRoute(ctx context.Context, agentID, profileID if err != nil { return ConversionConfig{}, "", err } + if target := u.profileByID(profileID); target.ID == "" || target.Protocol != provider.ProtocolOpenAI { + return ConversionConfig{}, "", oneerrors.New(oneerrors.InvalidRequest, "Compatibility mode forwards to a Chat Completions Profile") + } c, err := u.Conversion(ctx) if err != nil { return c, "", err @@ -397,15 +400,13 @@ func (u *UseCases) saveConversion(ctx context.Context, c ConversionConfig) (Conv if err := validateConversionListen(c.Listen); err != nil { return c, err } + // Routes are not checked here. A route is checked when it is set, and a + // request through one whose target has since gone is refused on its own + // (conversionTarget). Checking every route on every save let one Agent's + // leftover route block stopping the adapter for all of them. if c.Routes == nil { c.Routes = map[string]string{} } - for agentID, profileID := range c.Routes { - target := u.profileByID(profileID) - if target.ID == "" || target.Protocol != provider.ProtocolOpenAI { - return c, fmt.Errorf("compatibility mode for %s must forward to a Chat Completions Profile", agentID) - } - } if c.AnthropicModel == "" { c.AnthropicModel = defaultAnthropicConversionModel } @@ -432,6 +433,96 @@ func (u *UseCases) saveConversion(ctx context.Context, c ConversionConfig) (Conv return stored, nil } +// conversionUsers is the Agents whose own files point at the adapter, each with +// the converter Profile it is bound to. +func (u *UseCases) conversionUsers() (map[string]string, error) { + bindings, err := u.profiles.ListAgentBindings() + if err != nil { + return nil, err + } + users := map[string]string{} + for agentID, binding := range bindings { + if isConverterID(binding.ProfileRef) { + users[agentID] = binding.ProfileRef + } + } + return users, nil +} + +// SettleConversion brings compatibility mode in line with the Agents that use +// it: the route of an Agent that has moved to an ordinary Profile is dropped, +// and the adapter stops once no Agent is pointed at it. +// +// Compatibility mode has no page of its own. It starts when an Agent needs it +// and this is how it ends, so nothing is left running, or left pointing at a +// Profile the user may now delete, after the last Agent has moved on. +// +// Callers must not hold conversionMu or writeMu. +func (u *UseCases) SettleConversion(ctx context.Context) error { + if u == nil { + return nil + } + u.conversionMu.Lock() + defer u.conversionMu.Unlock() + c, err := u.Conversion(ctx) + if err != nil { + return err + } + if !c.Enabled && len(c.Routes) == 0 { + return nil + } + users, err := u.conversionUsers() + if err != nil { + return err + } + changed := false + for agentID := range c.Routes { + if users[agentID] != converterRouteID(agentID) { + delete(c.Routes, agentID) + changed = true + } + } + if c.Enabled && len(users) == 0 { + c.Enabled = false + changed = true + } + if !changed { + return nil + } + _, err = u.saveConversion(ctx, c) + return err +} + +// conversionTargetUsers is the Agents whose requests compatibility mode +// forwards to `profileID`. They are bound to a converter Profile, so the +// bindings alone do not show that they depend on this one. Callers must hold +// writeMu. +func (u *UseCases) conversionTargetUsers(ctx context.Context, profileID string, bindings map[string]profileStore.AgentBinding) []string { + conversion, err := u.Conversion(ctx) + if err != nil { + return nil + } + var users []string + for agentID, target := range conversion.Routes { + if target != profileID { + continue + } + if binding, err := u.profiles.ReadAgentBinding(agentID); err == nil && binding != nil && binding.ProfileRef == converterRouteID(agentID) { + users = append(users, agentID) + } + } + if conversion.TargetProfile == profileID { + for agentID, binding := range bindings { + if !slices.Contains(users, agentID) && isConverterID(binding.ProfileRef) { + if _, routed := routeAgent(binding.ProfileRef); !routed { + users = append(users, agentID) + } + } + } + } + return users +} + func profileModel(profile profileStore.Profile) string { if profile.Model == nil { return "" diff --git a/internal/app/desktop_conversion.go b/internal/app/desktop_conversion.go index b273547c..9ce72844 100644 --- a/internal/app/desktop_conversion.go +++ b/internal/app/desktop_conversion.go @@ -213,14 +213,15 @@ func (u *UseCases) restoreManagedFiles(ctx context.Context, snapshots []managedF return result } +// restoreConversionRuntime puts the listener back to what the restored +// settings say. A running adapter is handed its settings again rather than +// stopped first: stopping would cut the answers other Agents are receiving, +// for a change that failed and was none of their business. func (u *UseCases) restoreConversionRuntime(previous ConversionConfig) error { - if err := u.conversion.SetConfig(convertproxy.Config{Enabled: false}); err != nil { - return err - } if previous.Enabled { return u.startSavedConversion() } - return nil + return u.conversion.SetConfig(convertproxy.Config{Enabled: false}) } func (u *UseCases) rollbackConversionFailure(ctx context.Context, cause error, previous ConversionConfig, snapshots []managedFileSnapshot) error { diff --git a/internal/app/status.go b/internal/app/status.go index 06f69f64..968f7a08 100644 --- a/internal/app/status.go +++ b/internal/app/status.go @@ -672,6 +672,19 @@ func (u *UseCases) SaveProfile(ctx context.Context, options SaveProfileOptions) } } before := u.profileByID(options.ID) + // Compatibility mode converts into Chat Completions and nothing else. An + // Agent forwarded to this Profile would have every request refused if the + // Profile stopped speaking it, with nothing on its own page to say why. + if before.Protocol == provider.ProtocolOpenAI && options.Protocol != provider.ProtocolOpenAI { + bindings, err := u.catalogAgentBindings(true) + if err != nil { + return SaveProfileResult{}, err + } + if users := u.conversionTargetUsers(ctx, options.ID, bindings); len(users) > 0 { + sort.Strings(users) + return SaveProfileResult{}, oneerrors.New(oneerrors.InvalidRequest, fmt.Sprintf("Profile %s is used through compatibility mode by Agent(s): %s, and must stay a Chat Completions Profile", options.ID, strings.Join(users, ", "))) + } + } stored, err := u.profiles.Save(ctx, profileStore.SaveRequest{ ID: options.ID, Label: options.Label, @@ -777,23 +790,9 @@ func (u *UseCases) DeleteProfile(ctx context.Context, id string) error { // An Agent in compatibility mode is bound to its converter Profile, but its // requests go to the route's target: deleting that would break it as // surely as deleting the Profile it is bound to. - if conversion, err := u.Conversion(ctx); err == nil { - for agentID, target := range conversion.Routes { - if target != id || slices.Contains(users, agentID) { - continue - } - if binding, err := u.profiles.ReadAgentBinding(agentID); err == nil && binding != nil && binding.ProfileRef == converterRouteID(agentID) { - users = append(users, agentID) - } - } - if conversion.TargetProfile == id { - for agentID, binding := range bindings { - if !slices.Contains(users, agentID) && isConverterID(binding.ProfileRef) { - if _, routed := routeAgent(binding.ProfileRef); !routed { - users = append(users, agentID) - } - } - } + for _, agentID := range u.conversionTargetUsers(ctx, id, bindings) { + if !slices.Contains(users, agentID) { + users = append(users, agentID) } } if len(users) > 0 { diff --git a/internal/binding/services.go b/internal/binding/services.go index 2da940e3..f30b2265 100644 --- a/internal/binding/services.go +++ b/internal/binding/services.go @@ -5,6 +5,7 @@ package binding import ( "context" "fmt" + "log/slog" "net/url" "strings" "time" @@ -157,6 +158,16 @@ func (s *DesktopAgentService) Open(ctx context.Context, request DesktopAgentRequ return s.core.OpenDesktopAgent(ctx, request.AgentID) } +// settleConversion runs once an Agent has been given an ordinary Profile, the +// one way an Agent leaves compatibility mode. A failure is logged rather than +// returned: the Agent was configured, and all that is left behind is an +// adapter with nothing pointed at it. +func settleConversion(ctx context.Context, core *app.UseCases) { + if err := core.SettleConversion(context.WithoutCancel(ctx)); err != nil { + slog.Warn("compatibility mode could not be settled", "error", err) + } +} + // Configure applies a saved Profile to the selected desktop Agent. The profile // ID is the only user-supplied value; secrets stay in the Go profile store. func (s *DesktopAgentService) Configure(ctx context.Context, request DesktopAgentProfileRequest) (app.DesktopAgentProfileResult, error) { @@ -166,7 +177,12 @@ func (s *DesktopAgentService) Configure(ctx context.Context, request DesktopAgen if s == nil || s.core == nil { return app.DesktopAgentProfileResult{}, notReady("Desktop agent service is not configured") } - return s.core.ConfigureDesktopAgent(ctx, request.AgentID, request.ProfileID) + result, err := s.core.ConfigureDesktopAgent(ctx, request.AgentID, request.ProfileID) + if err != nil { + return result, err + } + settleConversion(ctx, s.core) + return result, nil } // AssessProfile verifies whether a saved Profile can be used directly or @@ -561,6 +577,7 @@ func (s *AgentService) Activate(ctx context.Context, request ActivateRequest) (A if err != nil { return ActivateResponse{}, err } + settleConversion(ctx, s.core) return ActivateResponse{ OK: true, Agent: result.AgentID, diff --git a/internal/binding/services_test.go b/internal/binding/services_test.go index b5210ea8..c768e5fb 100644 --- a/internal/binding/services_test.go +++ b/internal/binding/services_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "io" + "net" "net/http" "net/url" "os" @@ -395,6 +396,36 @@ func TestAgentServiceActivatesThroughGoUseCase(t *testing.T) { } } +// Applying an ordinary Profile is how an Agent leaves compatibility mode, so +// that is the moment the adapter is checked for anyone still using it. +func TestAgentServiceActivateStopsAnAdapterNoAgentUses(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + listen := listener.Addr().String() + _ = listener.Close() + core := app.NewUseCases(app.StatusOptions{ + Home: t.TempDir(), + Platform: platform.For("linux", "amd64"), + Lookup: func(string) (string, bool) { return "", false }, + }) + t.Cleanup(func() { _ = core.CloseConversion() }) + if _, err := core.SaveConversion(context.Background(), app.ConversionConfig{Enabled: true, Listen: listen}); err != nil { + t.Fatal(err) + } + service := &AgentService{core: core} + if _, err := service.Activate(context.Background(), ActivateRequest{ + AgentID: "codex", Provider: "ppio", APIKey: "binding-secret", Model: "model-a", + }); err != nil { + t.Fatal(err) + } + conversion, err := core.Conversion(context.Background()) + if err != nil || conversion.Enabled { + t.Fatalf("compatibility mode after the only Agent took an ordinary Profile: %#v, err=%v", conversion, err) + } +} + func TestAgentServiceInstallsThroughGoUseCase(t *testing.T) { home := t.TempDir() core := app.NewUseCases(app.StatusOptions{ diff --git a/internal/convertproxy/convert_test.go b/internal/convertproxy/convert_test.go index fbc352b9..35d93b60 100644 --- a/internal/convertproxy/convert_test.go +++ b/internal/convertproxy/convert_test.go @@ -9,6 +9,7 @@ import ( "strings" "sync" "testing" + "time" ) func TestAnthropicRequest(t *testing.T) { @@ -265,3 +266,122 @@ func TestResolveRoutesEachLocalKeyToItsOwnTarget(t *testing.T) { t.Fatalf("unknown key status = %d, upstream requests = %d", recorder.Code, len(got)) } } + +// heldUpstream answers a streaming request with one chunk and then keeps the +// response open until release is closed: an Agent in the middle of an answer. +func heldUpstream(t *testing.T) (upstream *httptest.Server, started chan struct{}, release chan struct{}) { + t.Helper() + started, release = make(chan struct{}, 1), make(chan struct{}) + upstream = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"first\"}}]}\n\n") + w.(http.Flusher).Flush() + started <- struct{}{} + select { + case <-release: + _, _ = io.WriteString(w, "data: [DONE]\n\n") + case <-r.Context().Done(): + } + })) + // Cut first: a test that fails with the response still held would otherwise + // hang here instead of reporting. + t.Cleanup(func() { + upstream.CloseClientConnections() + upstream.Close() + }) + return upstream, started, release +} + +// openStream starts a streaming request through the adapter and reports how it +// ended: the whole body, or the error that cut it short. +func openStream(address string) chan error { + done := make(chan error, 1) + go func() { + response, err := http.Post("http://"+address+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"client","stream":true,"messages":[]}`)) + if err != nil { + done <- err + return + } + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err == nil && !strings.Contains(string(body), "[DONE]") { + err = io.ErrUnexpectedEOF + } + done <- err + }() + return done +} + +// A new alias or a new route keeps the address, and must not wait on -- or +// cut -- an answer another Agent is still receiving. +func TestSetConfigKeepsAnOpenResponseWhenTheAddressIsUnchanged(t *testing.T) { + upstream, started, release := heldUpstream(t) + address := reserveAddress(t) + server := New(nil) + defer server.Close() + config := Config{Enabled: true, Listen: address, TargetBaseURL: upstream.URL, Models: []string{"before"}} + if err := server.SetConfig(config); err != nil { + t.Fatal(err) + } + stream := openStream(address) + <-started + + config.Models = []string{"after"} + changed := make(chan error, 1) + go func() { changed <- server.SetConfig(config) }() + select { + case err := <-changed: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("a change that keeps the address waited on an open response") + } + models, err := http.Get("http://" + address + "/v1/models") + if err != nil { + t.Fatal(err) + } + listed, _ := io.ReadAll(models.Body) + _ = models.Body.Close() + if !strings.Contains(string(listed), `"after"`) { + t.Fatalf("the new settings did not take effect: %s", listed) + } + close(release) + if err := <-stream; err != nil { + t.Fatalf("the open response was cut: %v", err) + } +} + +// Stopping is the user's decision. An answer still streaming gets a moment to +// finish and is then closed; it used to fail the stop and leave the listener +// gone with the settings still saying it ran. +func TestSetConfigStopsWhileAResponseIsStillOpen(t *testing.T) { + grace := shutdownGrace + shutdownGrace = 50 * time.Millisecond + defer func() { shutdownGrace = grace }() + upstream, started, _ := heldUpstream(t) + address := reserveAddress(t) + server := New(nil) + defer server.Close() + config := Config{Enabled: true, Listen: address, TargetBaseURL: upstream.URL} + if err := server.SetConfig(config); err != nil { + t.Fatal(err) + } + stream := openStream(address) + <-started + + if err := server.SetConfig(Config{Enabled: false}); err != nil { + t.Fatalf("stopping with an open response failed: %v", err) + } + select { + case err := <-stream: + if err == nil { + t.Fatal("the response outlived the adapter it came through") + } + case <-time.After(2 * time.Second): + t.Fatal("the open response was not closed") + } + if err := server.SetConfig(config); err != nil { + t.Fatalf("the adapter could not start again on its address: %v", err) + } +} diff --git a/internal/convertproxy/server.go b/internal/convertproxy/server.go index f3d41153..3bf54de8 100644 --- a/internal/convertproxy/server.go +++ b/internal/convertproxy/server.go @@ -105,15 +105,21 @@ func (s *Server) SetConfig(cfg Config) error { defer s.lifecycleMu.Unlock() s.mu.Lock() + // Settings that keep the address are swapped in place. Restarting the + // listener would wait on, and then cut, whatever an Agent is streaming, for + // a change that every request reads from the configuration anyway. + if cfg.Enabled && s.http != nil && s.cfg.Listen == cfg.Listen { + s.cfg = cfg + s.mu.Unlock() + return nil + } old := s.http oldListener := s.listener s.http = nil s.listener = nil s.mu.Unlock() if old != nil { - if err := shutdownHTTPServer(old); err != nil { - return err - } + stopHTTPServer(old) } if oldListener != nil { _ = oldListener.Close() @@ -158,17 +164,26 @@ func (s *Server) Close() error { } return nil } - err := shutdownHTTPServer(server) + stopHTTPServer(server) if listener != nil { _ = listener.Close() } - return err + return nil } -func shutdownHTTPServer(server *http.Server) error { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) +// shutdownGrace is how long open responses get to finish before they are closed. +var shutdownGrace = 5 * time.Second + +// stopHTTPServer lets open responses finish for a moment and then closes them. +// A stream an Agent is still reading must not keep the adapter from stopping +// or from moving to another address: waiting on it used to fail the change and +// leave the listener closed with the settings still saying it ran. +func stopHTTPServer(server *http.Server) { + ctx, cancel := context.WithTimeout(context.Background(), shutdownGrace) defer cancel() - return server.Shutdown(ctx) + if err := server.Shutdown(ctx); err != nil { + _ = server.Close() + } } func (s *Server) handle(w http.ResponseWriter, r *http.Request) { s.mu.RLock()