diff --git a/README.en.md b/README.en.md index 4bfcb28..8b8c1ca 100644 --- a/README.en.md +++ b/README.en.md @@ -4,7 +4,7 @@ [**中文**](README.md) | [**English**](README.en.md) -A lightweight local connector for Claude Code, Codex, WorkBuddy, WorkBuddy AI, OpenClaw and Hermes. +A lightweight local connector for Claude Code, Codex, WorkBuddy, WorkBuddy AI, Visual Studio, VS Code, OpenClaw and Hermes. IteraCompute is configured by default; you can save and switch to other compatible model APIs. The UI, configuration editors and relay are independent implementations. No CC Switch or Magpie application source is copied. The normal workflow requires **Python 3.11+** only: no pip install, @@ -43,19 +43,17 @@ If Windows has no `py` launcher, use `python --version` and `python start.py`, p ### 2. Download and launch -The initial implementation is on `feat/agent-connect` in [PR #1](https://github.com/IteraCompute/agent-connect/pull/1). -Before that PR reaches `main`, use these complete commands: +The initial implementation was merged into the default `main` branch in [PR #1](https://github.com/IteraCompute/agent-connect/pull/1). Download and launch it: ```bash -git clone --branch feat/agent-connect https://github.com/IteraCompute/agent-connect.git +git clone https://github.com/IteraCompute/agent-connect.git cd agent-connect python3 start.py ``` On Windows, replace the last line with `py -3 start.py`. Without Git, download the -[branch ZIP](https://github.com/IteraCompute/agent-connect/archive/refs/heads/feat/agent-connect.zip), -extract it, and open the directory containing `start.py`. After the initial merge, you can also -clone the default `main` branch directly. +[`main` branch ZIP](https://github.com/IteraCompute/agent-connect/archive/refs/heads/main.zip), +extract it, and open the directory containing `start.py`. | Platform | Recommended launch | Alternative | | --- | --- | --- | @@ -86,9 +84,9 @@ see the dated [acceptance record](docs/acceptance.md). 2. Check the API, model and protocol in the connection preview. Once it shows **协议匹配** (Protocol matched), click **连接 Claude Code** (Connect Claude Code), or the equivalent button for your selected client. -3. Agent Connect backs up the original file and writes that client's user configuration. +3. For cards labeled 自动写入配置 (automatic configuration), Agent Connect backs up the original file and writes that client's user configuration. Fully quit and restart the client, then create a fresh session. -4. WorkBuddy / WorkBuddy AI also requires choosing the added `custom-local` model in the +4. Visual Studio opens a setup guide for its model manager. VS Code requires selecting the added model after reload. WorkBuddy / WorkBuddy AI requires choosing the added `custom-local` model in the task model menu; see [client instructions](#connect-each-client). Keep Agent Connect's launcher terminal running while using a connected client. Closing the @@ -136,7 +134,7 @@ This is a complete example. Normally only `api_key` needs changing. Save, then c | Field | Purpose | | --- | --- | | `selected_provider` | API ID for this operation; must match a `[providers.]` table | -| `client` | `claude`, `codex`, `workbuddy`, `workbuddy-ai`, `openclaw` or `hermes` | +| `client` | `claude`, `codex`, `workbuddy`, `workbuddy-ai`, `visual-studio`, `vscode`, `openclaw` or `hermes` | | `name` | Display name | | `api_key` | This provider's credential; never returned to the page or written to client settings | | `base_url` | API root or OpenAI-compatible `/v1` base | @@ -172,8 +170,8 @@ not implement a model catalog, type the model ID it documents instead. | API type | Example base | Protocol | Directly supported clients | | --- | --- | --- | --- | -| OpenAI Chat compatible | `https://api.example.com/v1` | `chat` | WorkBuddy, WorkBuddy AI, OpenClaw, Hermes | -| OpenAI Responses compatible | `https://api.example.com/v1` | `responses` | Codex | +| OpenAI Chat compatible | `https://api.example.com/v1` | `chat` | WorkBuddy, WorkBuddy AI, VS Code, Visual Studio, OpenClaw, Hermes | +| OpenAI Responses compatible | `https://api.example.com/v1` | `responses` | Codex CLI, VS Code | | Anthropic Messages compatible | `https://api.example.com` | `anthropic` | Claude Code | | Multiple native protocols | Vendor's documented base | Only protocols it actually serves | Clients requiring those protocols | | Local OpenAI-compatible server | `http://127.0.0.1:PORT/v1` | As supported by the server | Clients requiring those protocols | @@ -198,20 +196,22 @@ The local relay preserves native protocols. It does not convert Chat to Response A Chat-only service cannot directly serve Claude Code or Codex through the simple app; use the [optional Magpie bridge](docs/advanced.md) when conversion is required. -Configuration also accepts Gemini endpoints, but the six simple client cards use Chat, Responses +Configuration also accepts Gemini endpoints, but the eight client entries use Chat, Responses or Messages. See the [coverage matrix](docs/coverage.md) for Gemini-specific advanced access. ## Connect each client -These are the simple workspace's independent native adapters. No additional vendor key needs +Choose an automatic configuration card or guided setup for Visual Studio. No additional vendor key needs to be entered in the client: it receives a local relay credential, and Agent Connect forwards requests. -| Client | Required native protocol | Default user file edited | +| Client | Required native protocol | Configuration location | | --- | --- | --- | | Claude Code | Anthropic Messages | `~/.claude/settings.json` | | Codex CLI | OpenAI Responses | `~/.codex/config.toml` | | WorkBuddy | OpenAI Chat Completions | `~/.workbuddy/models.json` | | WorkBuddy AI | OpenAI Chat Completions | `~/.workbuddy-ai/models.json` | +| Visual Studio (Windows) | OpenAI Chat Completions | Copilot Chat → Manage Models → Add a model | +| VS Code (stable desktop) | OpenAI Responses preferred, or Chat Completions | User profile’s `chatLanguageModels.json` | | OpenClaw | OpenAI Chat Completions | `~/.openclaw/openclaw.json` | | Hermes | OpenAI Chat Completions | `~/.hermes/config.yaml` | @@ -228,7 +228,7 @@ fixed test message below in a new session. ### Codex -Select **Codex**, connect and restart `codex`. The adapter sets a Responses provider named +Select **Codex CLI**, connect and restart `codex`. The adapter sets a Responses provider named `iteraconnect` and your selected model. If an existing user file already contains an unrelated provider with that name, the app reports an error and preserves the file. Rename that entry before retrying or export and merge the fragment manually. Acceptance covers Codex CLI; @@ -244,6 +244,14 @@ a new task. Select `custom-local:iteracompute/MODEL_ID` in the task model menu; The workspace requests manual verification in the original application. Automated desktop inference acceptance is not available; successful configuration alone is not a passing inference test. +### Visual Studio (Windows) + +Select **获取 Visual Studio 接入信息**. In Visual Studio 2026 18.10 or later, open the Copilot Chat model picker and select Manage Models. Add a Custom Endpoint, or an OpenAI provider that accepts a custom URL. Use the Completions format and the three copy buttons for the endpoint URL, model ID and local relay key. Select that model in a new Agent chat. Remove the endpoint from the same menu to disconnect. [Microsoft model management guide](https://learn.microsoft.com/en-us/visualstudio/ide/copilot-select-add-models?view=visualstudio) + +### VS Code + +Run Agent Connect on the same machine as stable desktop VS Code with the Copilot Chat Custom Endpoint provider. The workbench prefers Responses when advertised and uses Chat Completions for Chat-only APIs. Select **连接 VS Code**, reload the window and select the model under Agent Connect in a new local chat. The adapter targets the default profile. For a named or portable profile, set `ITERACONNECT_VSCODE_USER_DIR` to the directory containing that profile’s `chatLanguageModels.json` before launching the workbench. [VS Code model configuration](https://code.visualstudio.com/docs/agent-customization/language-models) + ### OpenClaw Select **OpenClaw**, connect, restart its relevant processes using your normal launch method @@ -269,7 +277,7 @@ at startup.** | **获取模型** | Vendor model catalog | One catalog request; no generation or draft save | | **测试 API** | Text, complete SSE and a tool-call/result round trip for the selected client's protocol | Up to 4 generation requests, each with a 256-token output budget | | **客户端实测** | Installed Claude Code / Codex / OpenClaw / Hermes process and its actual reply | Uses API quota; temporary settings/directories; no daily logins or chats copied | -| WorkBuddy / WorkBuddy AI | Message and tool task inside the original application | Manual acceptance required and explicitly reported | +| **查看实测步骤** (WorkBuddy editions, VS Code, Visual Studio) | Message and tool task inside the original application | Manual acceptance required and explicitly reported | Recommended sequence: @@ -300,13 +308,15 @@ manual acceptance. Earlier Auto 400/429 and a Haiku tool 502 are retained in the tests on Ubuntu, macOS and Windows with Python 3.11/3.14, plus quality/build, Magpie and the required aggregate check. Cross-platform CI does not replace real-client acceptance on each platform. +See the [2026-11-18 per-client acceptance results and reproduction steps](docs/client-setup-acceptance.md). + ### Read the status labels | Chinese status | Meaning | | --- | --- | | 有未保存更改 | API, model, protocol or client changed; connection, export and tests save automatically | | 协议匹配 / 需要配置 | Checks declared protocol support only; a mismatch disables connection/tests and links to its setting | -| 已检测到安装 | A command or configuration directory exists; execution still needs verification | +| 已检测到安装 | The executable is on PATH. A configuration directory alone is labeled 发现配置目录 | | 已配置 · 可恢复 | An original-config backup exists, not an inference result for this model | | API 测试通过 | All three protocol checks passed; expand the redacted report for details | | 客户端实测通过 | The expected reply was confirmed in a real client's output | @@ -324,7 +334,7 @@ A connected client keeps the provider and model last written for it. Changing a key or base URL affects the local relay. Do not remove providers still used by clients. Restore before switching configuration managers to avoid competing changes. -**Restore:** select the client, click **恢复原配置**, then restart it. The first connection records +**Restore an automatically configured client:** select the client, click **恢复原配置**, then restart it. The first connection records the original content, which remains the backup across reconnections. If the file did not exist before connecting, restoration removes the file created by Agent Connect. @@ -379,7 +389,7 @@ app's TOML and advanced CLI's JSON are independent configurations. To update a c | Symptom | Check / action | | --- | --- | | Missing `python3` / `py`, or unsupported version | Install Python 3.11+ and reopen the terminal; on Windows check `python --version` | -| Missing `start.py` | Use the complete feature branch and enter the extracted/cloned directory; before release, `main` may contain bootstrap files only | +| Missing `start.py` | Download the default `main` branch and enter the extracted/cloned directory containing the file | | Page unavailable / port occupied | Stop the old instance or change both ports; use the full terminal URL if the browser did not open | | Management page is unauthorized | Use the URL from this launch; the management token changes after restarting the service | | API 401 / 403 | Check key, account and model access; reload after editing the private file | diff --git a/README.md b/README.md index ea627f3..1db95bc 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [**中文**](README.md) | [**English**](README.en.md) -一个在本机运行的轻量连接工具,让 Claude Code、Codex、WorkBuddy、WorkBuddy AI、OpenClaw 和 Hermes 使用你选择的模型 API。 +一个在本机运行的轻量连接工具,让 Claude Code、Codex、WorkBuddy、WorkBuddy AI、Visual Studio、VS Code、OpenClaw 和 Hermes 使用你选择的模型 API。 默认提供 IteraCompute,也可以保存和切换其他兼容服务。界面、配置管理和转发均为独立实现,没有复制 CC Switch 或 Magpie 的应用代码。 正常使用只需要 **Python 3.11+**;无需 pip install、Node.js、CC Switch 或 Magpie。 @@ -38,17 +38,15 @@ Windows 没有 `py` 启动器时,可使用 `python --version` 和 `python star ### 2. 下载并启动 -首次发布的代码位于 [PR #1](https://github.com/IteraCompute/agent-connect/pull/1) 的 `feat/agent-connect` 分支。 -在它合并到 `main` 前,使用下面的完整命令: +首次发布的代码已通过 [PR #1](https://github.com/IteraCompute/agent-connect/pull/1) 合并到默认的 `main` 分支。下载并启动: ```bash -git clone --branch feat/agent-connect https://github.com/IteraCompute/agent-connect.git +git clone https://github.com/IteraCompute/agent-connect.git cd agent-connect python3 start.py ``` -Windows 将最后一行换成 `py -3 start.py`。不使用 Git 时,可下载[该分支的 ZIP](https://github.com/IteraCompute/agent-connect/archive/refs/heads/feat/agent-connect.zip),解压后进入包含 `start.py` 的目录。 -首次发布合并后,也可直接克隆默认的 `main` 分支。 +Windows 将最后一行换成 `py -3 start.py`。不使用 Git 时,可下载 [`main` 分支 ZIP](https://github.com/IteraCompute/agent-connect/archive/refs/heads/main.zip),解压后进入包含 `start.py` 的目录。 | 系统 | 推荐启动方式 | 可选启动方式 | | --- | --- | --- | @@ -72,8 +70,8 @@ Windows 将最后一行换成 `py -3 start.py`。不使用 Git 时,可下载[ 1. 点击需要使用的客户端卡片,例如 **Claude Code**。 2. 检查“本次连接”的 API、模型与协议。显示 **协议匹配** 后,点击 **连接 Claude Code** 等对应按钮。 -3. Agent Connect 会备份原配置,并写入这个客户端的用户配置。完全退出并重新启动对应客户端,再新建会话。 -4. WorkBuddy / WorkBuddy AI 还需要在任务的模型菜单中选择新增的 `custom-local` 模型,详见[客户端操作](#连接不同的客户端)。 +3. 对标有“自动写入配置”的软件,Agent Connect 会备份原配置,并写入这个客户端的用户配置。完全退出并重新启动对应客户端,再新建会话。 +4. Visual Studio 选择 **获取 Visual Studio 接入信息**,在 IDE 内添加模型。VS Code 选择 **连接 VS Code**,重新加载后在聊天中选模型。WorkBuddy / WorkBuddy AI 需要在任务的模型菜单中选择新增的 `custom-local` 模型,详见[客户端操作](#连接不同的客户端)。 使用客户端期间,请保持 Agent Connect 的启动终端运行。关闭浏览器标签页不会停止服务;在启动终端按 `Ctrl+C` 才会停止。 下次执行同一个启动命令即可读取已保存的设置。仅重新启动 Agent Connect、地址和模型都没有变化时,无需重复填写 key。 @@ -101,7 +99,7 @@ protocols = ["chat", "responses", "anthropic"] | 字段 | 用途 | | --- | --- | | `selected_provider` | 本次使用的 API 标识,须与某个 `[providers.<标识>]` 一致 | -| `client` | `claude`、`codex`、`workbuddy`、`workbuddy-ai`、`openclaw` 或 `hermes` | +| `client` | `claude`、`codex`、`workbuddy`、`workbuddy-ai`、`visual-studio`、`vscode`、`openclaw` 或 `hermes` | | `name` | 界面显示名称 | | `api_key` | 此服务商的凭据;不会返回给网页或写入客户端配置 | | `base_url` | API 根地址或 OpenAI 兼容的 `/v1` 地址 | @@ -132,8 +130,8 @@ protocols = ["chat", "responses", "anthropic"] | API 类型 | 地址示例 | 勾选的协议 | 可直接接入的客户端 | | --- | --- | --- | --- | -| OpenAI Chat 兼容 | `https://api.example.com/v1` | `chat` | WorkBuddy、WorkBuddy AI、OpenClaw、Hermes | -| OpenAI Responses 兼容 | `https://api.example.com/v1` | `responses` | Codex | +| OpenAI Chat 兼容 | `https://api.example.com/v1` | `chat` | WorkBuddy、WorkBuddy AI、VS Code、Visual Studio、OpenClaw、Hermes | +| OpenAI Responses 兼容 | `https://api.example.com/v1` | `responses` | Codex CLI、VS Code | | Anthropic Messages 兼容 | `https://api.example.com` | `anthropic` | Claude Code | | 同时提供多个原生协议 | 供应商的 API 基地址 | 只勾选实际提供的协议 | 对应协议的客户端 | | 本地 OpenAI 兼容服务 | `http://127.0.0.1:你的端口/v1` | 按服务能力勾选 | 对应协议的客户端 | @@ -154,18 +152,20 @@ anthropic = "https://api.example.com/anthropic" 本地转发保留原生协议,不会自动把 Chat 转换为 Responses 或 Messages。 只有 Chat 的服务不能直接供 Claude Code 或 Codex 使用;需要转换时,参阅[可选 Magpie 高级入口](docs/advanced.md)。 -配置支持 Gemini 基地址,但当前六个简化版客户端卡片使用的是 Chat、Responses 或 Messages;Gemini 专用接入见[覆盖范围](docs/coverage.md)。 +配置支持 Gemini 基地址,但当前八个客户端入口使用的是 Chat、Responses 或 Messages;Gemini 专用接入见[覆盖范围](docs/coverage.md)。 ## 连接不同的客户端 -以下是简化工作台的直接配置方式。无需额外向客户端填写供应商 key;客户端使用本地网关令牌,由 Agent Connect 转发请求。 +工作台提供以下接入方式。无需额外向客户端填写供应商 key;客户端使用本地网关令牌,由 Agent Connect 转发请求。 -| 客户端 | 所需原生协议 | 默认修改的用户配置 | +| 客户端 | 所需原生协议 | 配置位置或操作入口 | | --- | --- | --- | | Claude Code | Anthropic Messages | `~/.claude/settings.json` | | Codex CLI | OpenAI Responses | `~/.codex/config.toml` | | WorkBuddy | OpenAI Chat Completions | `~/.workbuddy/models.json` | | WorkBuddy AI | OpenAI Chat Completions | `~/.workbuddy-ai/models.json` | +| Visual Studio(Windows) | OpenAI Chat Completions | Copilot Chat → 管理模型 → 添加模型 | +| VS Code(桌面稳定版) | 优先 OpenAI Responses,也支持 Chat Completions | 用户配置目录下的 `chatLanguageModels.json` | | OpenClaw | OpenAI Chat Completions | `~/.openclaw/openclaw.json` | | Hermes | OpenAI Chat Completions | `~/.hermes/config.yaml` | @@ -179,7 +179,7 @@ anthropic = "https://api.example.com/anthropic" ### Codex -选择 **Codex** 并连接,再重新启动 `codex`。适配器配置名为 `iteraconnect` 的 Responses 提供方及所选模型。 +选择 **Codex CLI** 并连接,再重新启动 `codex`。适配器配置名为 `iteraconnect` 的 Responses 提供方及所选模型。 如果用户文件中已经有来源不明的同名提供方,程序会报错并保留原文件;请改名后重试,或使用 **导出配置** 手动合并。 这里只验证了 Codex CLI;不把 CLI 测试结果当作其他桌面、IDE 或云端运行方式的验收结果。 @@ -191,6 +191,14 @@ anthropic = "https://api.example.com/anthropic" 工作台会提示在原应用手动验证,因为当前没有自动执行桌面应用推理的测试。仅配置写入成功不算真实接入通过。 +### Visual Studio(Windows) + +打开 **获取 Visual Studio 接入信息**,逐项复制地址、模型 ID 和本地网关令牌。在 Visual Studio 2026 18.10 或更高版本的 Copilot Chat 中打开“管理模型”,添加 Custom Endpoint 或支持自定义地址的 OpenAI,选择 Completions 格式。在 Agent 模式开启新对话并选择该模型。需要移除时,在同一菜单删除端点。[微软模型管理指南](https://learn.microsoft.com/en-us/visualstudio/ide/copilot-select-add-models?view=visualstudio) + +### VS Code + +在与 Agent Connect 同一台设备上的 VS Code 桌面稳定版使用 Copilot Chat 的 Custom Endpoint。服务商声明支持 Responses 时工作台优先使用它,只提供 Chat 时自动配置 Chat Completions。点击 **连接 VS Code**,重新加载窗口,在本地聊天的模型菜单中选择 Agent Connect 下的目标模型。默认写入默认配置文件(profile)。使用命名配置文件或便携版时,把 `ITERACONNECT_VSCODE_USER_DIR` 指向该配置文件中存放 `chatLanguageModels.json` 的目录,再启动工作台。[VS Code 模型设置](https://code.visualstudio.com/docs/agent-customization/language-models) + ### OpenClaw 选择 **OpenClaw** 并连接,再按原来的运行方式重启相关进程、开始新会话。 @@ -213,7 +221,7 @@ anthropic = "https://api.example.com/anthropic" | **获取模型** | 供应商模型目录 | 一次目录请求,不进行生成,不保存草稿 | | **测试 API** | 所选客户端协议的文本、完整 SSE、工具调用与结果回传 | 最多 4 次生成请求,每次输出预算 256 token | | **客户端实测** | 启动已安装的 Claude Code / Codex / OpenClaw / Hermes,检查实际回复 | 会产生 API 用量;临时配置、独立目录,不复制日常登录和聊天 | -| WorkBuddy / WorkBuddy AI | 原应用内发送消息与工具任务 | 需手动验收,工作台会明确提示 | +| **查看实测步骤**(WorkBuddy 两版、VS Code、Visual Studio) | 原应用内发送消息与工具任务 | 需手动验收,工作台会明确提示 | 推荐顺序: @@ -229,6 +237,8 @@ anthropic = "https://api.example.com/anthropic" API 工具测试只回传固定字符串,不执行模型生成的命令。客户端单轮回复通过,不代表它的完整工具循环、长会话、图像、权限或异常恢复均已验收。 +2026-11-18 逐个客户端的结果、测试环境与复跑命令见[本轮验收记录](docs/client-setup-acceptance.md)。 + ![文本、流式与工具调用的独立结果卡](docs/images/test-passed.jpg) 此结果卡截图使用**本地模拟后端**展示界面。真实 IteraCompute 验收发生于 2026-11-16: @@ -243,7 +253,7 @@ API 工具测试只回传固定字符串,不执行模型生成的命令。客 | --- | --- | | 有未保存更改 | 修改了 API、模型、协议或客户端;连接、导出和测试会自动保存 | | 协议匹配 / 需要配置 | 只检查声明的协议;缺少协议时连接与测试不可用,可点“检查协议”定位 | -| 已检测到安装 | 发现命令或配置目录,仍需实测确认能否执行 | +| 已检测到安装 | 在 PATH 中找到启动命令。仅找到目录时单独显示“发现配置目录” | | 已配置 · 可恢复 | 存在原配置备份,不等于当前模型已通过推理测试 | | API 测试通过 | 三项协议检查通过;报告默认收起,可展开查看脱敏详情 | | 客户端实测通过 | 从真实客户端输出中确认了预期回复 | @@ -258,7 +268,7 @@ API 工具测试只回传固定字符串,不执行模型生成的命令。客 已连接的客户端仍使用它最近一次连接时写入的服务商和模型;修改同一服务商的 key / 地址会影响本地转发。 不要删除仍被客户端使用的服务商配置。使用多个配置管理器前,先恢复原配置,避免相互覆盖。 -**恢复:** 选中目标客户端,点击 **恢复原配置**,再重启客户端。 +**恢复:** 对自动写入的软件,选中目标客户端,点击 **恢复原配置**,再重启客户端。 第一次连接前会保存原始内容;重复连接仍保留这份原始备份。原文件原本不存在时,恢复会移除由本工具创建的文件。 如果客户端或其他工具在连接后改写了该文件,自动恢复会停止,避免覆盖后续修改。请对照 `native-backups` 中的备份手动合并;不要为了恢复而直接删除整个客户端配置目录。 @@ -307,7 +317,7 @@ itera-connect app --settings /absolute/path/to/private.toml | 现象 | 检查与处理 | | --- | --- | | `python3` / `py` 不存在,或提示版本过低 | 安装 Python 3.11+,重新打开终端;Windows 可检查 `python --version` | -| 找不到 `start.py` | 确认解压/克隆的是完整功能分支,并进入文件所在目录;发布前 `main` 可能只有初始化文件 | +| 找不到 `start.py` | 确认从默认的 `main` 分支下载,并进入解压或克隆后包含该文件的目录 | | 页面打不开、地址占用 | 停止旧实例,或使用上面的两个端口参数;浏览器未打开时复制终端完整地址 | | 本地页面提示未授权 | 使用本次启动打印的完整地址;重启服务后管理令牌会变化 | | API 返回 401 / 403 | 核对 key、账号和模型权限;修改文件后点“重新读取” | diff --git a/docs/acceptance.md b/docs/acceptance.md index 79271a6..0f93b72 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -1,5 +1,7 @@ # Acceptance record +See the [2026-11-18 client setup run](client-setup-acceptance.md) for the eight workbench entries, installed CLI runs and desktop checks. + Date: **2026-11-16 (Asia/Shanghai)**. Candidate: **0.1.0**, independent simple local client. A dedicated key was supplied through ignored `agent-connect.local.toml`. Real requests went to diff --git a/docs/client-setup-acceptance.md b/docs/client-setup-acceptance.md new file mode 100644 index 0000000..361de18 --- /dev/null +++ b/docs/client-setup-acceptance.md @@ -0,0 +1,42 @@ +# 客户端接入验收 · 2026-11-18 + +验证环境为 Linux x64,真实服务为 IteraCompute,模型为 `openai/gpt-6-luna`。四个 CLI 在临时用户目录中读取工作台适配器生成的配置,各发起一次单轮任务。仅当客户端报告成功并返回约定文本时计为通过。 + +| 客户端 | 工作台验证 | 本轮客户端结果 | +| --- | --- | --- | +| Codex CLI 0.156.1 | 连接、切换模型、保留已有 TOML 并恢复 | 真实 API 单轮通过,24.527 秒 | +| Claude Code 2.1.312 | 连接、切换模型、保留无关环境项并恢复 | 真实 API 单轮通过,11.253 秒 | +| WorkBuddy | 数组及对象配置、模型白名单、重名冲突、切换和恢复,生成的 URL 完成模拟请求 | 本机未安装桌面版,待在已登录的客户端选择模型并发送消息 | +| WorkBuddy AI | 国际版独立配置目录,白名单、切换和恢复,生成的 URL 完成模拟请求 | 本机未安装国际版,桌面会话待验收 | +| Visual Studio | 工作台生成指定服务商的端点、模型及本地令牌,模拟服务验证模型目录和聊天请求 | 需要 Windows 和支持自定义端点的 Visual Studio。模型管理器中的保存、选模、回复待验收 | +| VS Code 1.141.0 | Custom Endpoint 配置写入、切换、JSONC 注释保留、冲突拒绝、逐字节恢复,生成的端点完成模拟请求 | 真实 IDE 使用 Chat 对模拟服务完成单轮,使用 Responses 对真实 API 完成单轮,两次均恢复配置 | +| OpenClaw 2026.10.2 | 连接、默认模型、允许列表和恢复 | 真实 API 单轮通过,15.986 秒 | +| Hermes 0.23.1 | 连接、提供方与 transport、切换和恢复 | 真实 API 单轮通过,33.345 秒 | + +## VS Code 桌面验证 + +在 VS Code 1.141.0 的独立桌面窗口中,从磁盘加载机器上安装的 GitHub Copilot Chat 0.69.0。以空用户目录启动,由适配器写入默认 profile,验证模型出现在聊天栏,在本地聊天中发送固定单轮消息。模拟服务实际收到 Chat Completions POST,界面显示了完整预期回复;退出后成功恢复。运行方式见[桌面验证命令](testing.md#reproduce-the-client-setup-checks)。[VS Code 模拟后端回复截图](images/vscode-fixture.png) + +首次测试时,IDE 选中了模型,直接写入提供方的 `apiKey` 字段却导致本地网关拒绝了请求。适配器改用 Custom Endpoint 支持的模型级 Authorization 请求头,内容为本地网关令牌。浏览器工作台和文件配置测试均未捕获这个问题,保留了桌面对话回归测试。 + +对同一个真实模型,VS Code 的 Chat Completions 会话曾收到 HTTP 400,后续一次在等待窗口内没有收到预期回复。对同一端点切换到 Responses 并发送完整历史后,真实桌面收到约定回复并恢复配置。工作台因此在服务商声明支持两个协议时优先选 Responses,仅支持 Chat 时仍使用 Chat Completions。 + +## 真实协议测试 + +每种协议做一次普通回复、一次完整 SSE,以及一次包含两次请求的工具调用往返。表中为用时(秒),九项均通过。四个客户端的单轮回复和服务商层的工具往返分别计数。 + +| 原生协议 | 文本 | 流式 | 工具往返 | +| --- | ---: | ---: | ---: | +| Chat Completions | 9.673 | 5.696 | 20.751 | +| Responses | 7.904 | 7.901 | 25.027 | +| Anthropic Messages | 5.998 | 10.119 | 18.981 | + +## 复跑与取证 + +1. 按[开发测试说明](testing.md)安装开发依赖。运行 `python -m unittest discover -v`。本机启用固定版本 Magpie 和四个 CLI 后运行了 58 项测试。适配器测试会预置已有用户设置、连接、再次切换、恢复并比较原始内容。 +2. 运行 `python -m tests.workbench_browser`。Chromium 对八个入口逐个点击,验证七个文件适配器的写入与恢复,以及 Visual Studio 引导的生成和字段复制。桌面宽度 1360 px,窄屏 390 px。测试使用本机模拟服务。[桌面工作台截图](images/client.jpg) +3. 在私有 TOML 中选择测试服务商、模型并填入专用凭据。按测试说明运行 `scripts/check_live.py`,可用 `--clients` 或 `--protocols` 单独复跑某一项。将状态、版本、日期和用时记入验收记录。 +4. 桌面验收时,在目标软件的新会话选择刚接入的模型,发送 `Reply with exactly ITERACONNECT_OK.` 并核对回复。WorkBuddy 两个版本在任务菜单选择工作台显示的完整 `custom-local:` 模型。VS Code 在本地聊天中选择 Agent Connect 模型,Visual Studio 在 Copilot Chat 的模型管理器保存端点并选中模型。 +5. 在一次性工作目录中验证一次创建并读取小文件的工具流程。退出后恢复配置,或在 Visual Studio 模型管理器中移除测试端点。分别记录回复、工具、恢复结果。截图只保留软件版本、模型选择和测试结果。 + +接入方式参考了 CC Switch 的客户端选择与服务商切换流程。WorkBuddy 已启用非空白名单时需要同步更新模型 ID,空白名单表示显示全部。微软两个 IDE 分别使用模型管理器和用户配置文件。[CC Switch 工作台](https://github.com/farion1231/cc-switch) · [WorkBuddy 白名单处理](https://github.com/farion1231/cc-switch/blob/09acca04941a359096bb16ea4fa4073c5e2c46e5/src-tauri/src/workbuddy_config.rs) · [Visual Studio 模型管理](https://learn.microsoft.com/en-us/visualstudio/ide/copilot-select-add-models?view=visualstudio) · [VS Code Custom Endpoint](https://code.visualstudio.com/docs/agent-customization/language-models) diff --git a/docs/configuration.md b/docs/configuration.md index 0c240ed..66503df 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -42,6 +42,15 @@ The independent native adapters honor `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `WORKBU `WORKBUDDY_AI_CONFIG_DIR`, `OPENCLAW_STATE_DIR` / `OPENCLAW_CONFIG_PATH`, and `HERMES_HOME`. Defaults are `~/.claude/settings.json`, `~/.codex/config.toml`, `~/.workbuddy/models.json`, `~/.workbuddy-ai/models.json`, `~/.openclaw/openclaw.json` and `~/.hermes/config.yaml`. +On stable desktop VS Code, the adapter adds a Custom Endpoint to `chatLanguageModels.json` under +`%APPDATA%/Code/User` (Windows), `~/Library/Application Support/Code/User` (macOS), or +`$XDG_CONFIG_HOME/Code/User` (Linux, default `~/.config/Code/User`). Set +`ITERACONNECT_VSCODE_USER_DIR` for a named profile or nonstandard user directory. JSONC comments, +trailing commas and existing groups are preserved. VS Code uses a model-level Authorization header +carrying the loopback relay token. When available, Responses sends full history on each turn. +For a Chat-only provider, the adapter selects Chat Completions. The generated chat profile enables tools, disables vision and +uses local budgets of 16,384 input tokens and 2,048 output tokens. Visual Studio on Windows uses the IDE's model +manager and displays per-field copy buttons in the workbench. Original contents and the installed content hash are journaled under `native-backups` in the Agent Connect state directory. Restore only proceeds if the file still matches the known applied/transaction state. Existing unrelated JSON fields and TOML/YAML settings are preserved. diff --git a/docs/coverage.md b/docs/coverage.md index 477bc1c..2e7a7c2 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -4,8 +4,7 @@ `python3 start.py` uses original UI, settings, native adapters and the relay. It needs no upstream binary. API switching, custom native endpoints, model discovery, connect/restore and API/client -tests are available in one local interface. Six client entries cover Claude Code, Codex, -WorkBuddy, WorkBuddy AI, OpenClaw and Hermes. Config adaptation is separate from actual app +tests are available in one local interface. Seven file adapters cover Claude Code, Codex CLI, WorkBuddy, WorkBuddy AI, VS Code, OpenClaw and Hermes. Visual Studio on Windows has a separate guided Copilot Chat endpoint setup. Config adaptation is separate from actual app inference verification; see acceptance.md. Protocol conversion, subscription login, upstream plugins and additional clients remain in the optional advanced interfaces below. diff --git a/docs/images/client.jpg b/docs/images/client.jpg index cc58e3a..9eaa9fb 100644 Binary files a/docs/images/client.jpg and b/docs/images/client.jpg differ diff --git a/docs/images/vscode-fixture.png b/docs/images/vscode-fixture.png new file mode 100644 index 0000000..60d6a3c Binary files /dev/null and b/docs/images/vscode-fixture.png differ diff --git a/docs/testing.md b/docs/testing.md index f192f24..7694227 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -51,6 +51,48 @@ Host/Origin/control-token enforcement, local-fixture probes, independent configu preservation, reconnect, exact restoration and protection against later edits. The opt-in `NativeSettingsClientTests` reads these new native configs with the installed actual clients. +### Reproduce the client setup checks + +Run the fixture suite with `python -m unittest discover -v`. To exercise the actual workbench +in a disposable Chromium session, install Playwright in a development environment and run: + +```bash +python -m pip install playwright +python -m playwright install chromium +python -m tests.workbench_browser +``` + +Use `--screenshot reports/workbench.jpg` with an existing output directory to keep a fixture +screenshot. The test checks all eight cards, their setup or restore actions, guided field copying, +stale field removal, manual test instructions, API result cards, keyboard input and a narrow +viewport. The fixture model is named `fixture-model`. + +To run VS Code desktop chat itself on Linux, enable the installed Copilot Chat extension and +use the same Playwright development environment with Xvfb. This starts an isolated Electron +extension development host, loads that installed extension from disk, selects the only local +model in the fresh profile, sends the fixed test message, checks the assistant's rendered response, +then restores the original profile. The default paths match Microsoft's Debian package. +`--electron` and `--copilot` accept other installation paths. + +```bash +xvfb-run -a python -m tests.vscode_desktop +xvfb-run -a python -m tests.vscode_desktop --settings agent-connect.local.toml +``` + +The first command uses a Chat-only local vendor fixture. The second incurs API usage on the +explicitly selected provider and model. To capture a fixture-only screenshot, add +`--screenshot reports/vscode-fixture.png` to the first command. + +For a real provider run with the CLIs, explicitly select the private settings file, protocols and installed +CLIs. The following command sends generation requests to the selected provider and model. +The script uses temporary client homes and outputs only the test name, status and elapsed seconds. + +```bash +python scripts/check_live.py --settings agent-connect.local.toml --protocols chat responses anthropic --clients codex claude openclaw hermes +``` + +See the [per-client evidence and desktop acceptance procedure](client-setup-acceptance.md). + ### Browser UI regression Use a temporary HOME/config directory and a local fixture vendor; do not connect the UI test diff --git a/scripts/check_live.py b/scripts/check_live.py new file mode 100644 index 0000000..3e11fde --- /dev/null +++ b/scripts/check_live.py @@ -0,0 +1,56 @@ +"""Exercise the selected private provider with isolated clients. Print only test outcomes.""" + +import argparse +import os +import tempfile +import threading +from pathlib import Path +from unittest.mock import patch + +from iteraconnect.diagnostics import probe +from iteraconnect.gateway import Gateway +from iteraconnect.settings import read_settings, runtime_config +from iteraconnect.smoke import smoke + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--settings", type=Path, required=True) + parser.add_argument("--clients", nargs="+", choices=("claude", "codex", "openclaw", "hermes")) + parser.add_argument("--protocols", nargs="+", choices=("chat", "responses", "anthropic")) + args = parser.parse_args() + if not args.clients and not args.protocols: + parser.error("select clients or protocols to test") + if not args.settings.is_file(): + parser.error("supply an existing private test settings file") + data = read_settings(args.settings) + pid = data["selected_provider"] + if not data["providers"][pid]["api_key"]: + parser.error("the selected provider requires a dedicated test key") + passed = True + with tempfile.TemporaryDirectory() as state, patch.dict(os.environ, ITERACONNECT_HOME=state): + config = runtime_config(data) + with Gateway(config, address=("127.0.0.1", 0)) as relay: + config["gateway"]["port"] = relay.server_port + worker = threading.Thread(target=relay.serve_forever, daemon=True) + worker.start() + try: + if args.protocols: + report = probe(config, pid, protocols=args.protocols) + for row in report["results"]: + print( + row["protocol"], row["case"], row["status"], row["seconds"], flush=True + ) + passed &= report["passed"] + for client in args.clients or []: + row = smoke(config, client, pid, native=True) + print(client, row["status"], row.get("seconds", "-"), flush=True) + passed &= row["status"] == "passed" + finally: + relay.shutdown() + worker.join() + return 0 if passed else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/iteraconnect/app.py b/src/iteraconnect/app.py index d41129d..c654686 100644 --- a/src/iteraconnect/app.py +++ b/src/iteraconnect/app.py @@ -14,7 +14,7 @@ from pathlib import Path from urllib.parse import urlsplit -from .config import ConnectError, state_dir +from .config import ConnectError, gateway_key, gateway_url, state_dir from .diagnostics import probe from .gateway import Gateway, provider_models from .native import client_path, connect_native, disconnect_native, render_native @@ -66,17 +66,28 @@ def state(self): "settings": public_settings(self.data), "settings_path": str(self.settings_path), "relay_port": self.relay.server_port, - "clients": [ - { - "id": k, - "name": v[0], - "protocol": v[1], - "installed": bool(shutil.which(k)) or client_path(k).parent.exists(), - "config_path": str(client_path(k)), - "connected": (state_dir() / "native-backups" / (k + ".json")).exists(), - } - for k, v in CLIENTS.items() - ], + "clients": [self.client_state(k) for k in CLIENTS], + } + + @staticmethod + def client_state(target): + client = CLIENTS[target] + path = None if client.guided else client_path(target) + command = {"vscode": "code", "visual-studio": "devenv"}.get(target, target) + return { + "id": target, + "name": client.name, + "protocol": client.protocols[0], + "protocols": client.protocols, + "guided": client.guided, + "manual_test": client.manual_test, + "next_step": client.next_step, + "installed": bool(shutil.which(command)), + "config_detected": bool(path and path.parent.exists()), + "config_path": str(path) if path else None, + "connected": bool( + path and (state_dir() / "native-backups" / (target + ".json")).exists() + ), } def draft_models(self, body): @@ -108,32 +119,44 @@ def draft_models(self, body): finally: os.environ.pop(key_env, None) + def save_selection(self, body): + data = copy.deepcopy(self.data) + pid, target = body.get("provider"), body.get("client") + if target not in CLIENTS or not isinstance(pid, str): + raise ConnectError("请选择有效的 API 和客户端。") + old = data["providers"].get(pid, {}) + p = {k: body.get(k, old.get(k)) for k in ("name", "base_url", "model", "protocols")} + p["api_key"] = body.get("api_key") or old.get("api_key", "") + if "endpoints" in body: + p["endpoints"] = body["endpoints"] + elif "endpoints" in old: + p["endpoints"] = old["endpoints"] + data["providers"][pid] = p + data["selected_provider"], data["client"] = pid, target + self.activate(data, persist=True) + def action(self, route, body): if route == "/api/models" and body: return self.draft_models(body) if route == "/api/reload": self.activate(read_settings(self.settings_path)) return self.state() + if route == "/api/disconnect": + target = body.get("client", self.data["client"]) + if target not in CLIENTS or CLIENTS[target].guided: + raise ConnectError("此客户端请在应用的模型管理中移除端点。") + return disconnect_native(target) if route == "/api/save": - data = copy.deepcopy(self.data) - pid, target = body.get("provider"), body.get("client") - if target not in CLIENTS or not isinstance(pid, str): - raise ConnectError("请选择有效的 API 和客户端。") - old = data["providers"].get(pid, {}) - p = {k: body.get(k, old.get(k)) for k in ("name", "base_url", "model", "protocols")} - p["api_key"] = body.get("api_key") or old.get("api_key", "") - if "endpoints" in body: - p["endpoints"] = body["endpoints"] - elif "endpoints" in old: - p["endpoints"] = old["endpoints"] - data["providers"][pid] = p - data["selected_provider"], data["client"] = pid, target - self.activate(data, persist=True) + self.save_selection(body) return self.state() + if body and route in ("/api/connect", "/api/export", "/api/probe", "/api/smoke"): + self.save_selection(body) + return {**self.run_selected(route), "state": self.state()} + return self.run_selected(route) + + def run_selected(self, route): pid, target = self.data["selected_provider"], self.data["client"] p = self.data["providers"][pid] - if route == "/api/disconnect": - return disconnect_native(target) if route == "/api/export": fragment = render_native(target, "", self.config, pid, p["model"]) # Export substitutes the local relay token, never a vendor key. @@ -143,17 +166,27 @@ def action(self, route, body): if route == "/api/models": return {"models": [m["id"] for m in provider_models(self.config["providers"][pid])]} if route == "/api/connect": + if CLIENTS[target].guided: + if "chat" not in p["protocols"]: + raise ConnectError("Visual Studio 的此接入方式需要 Chat Completions。") + return { + "setup": "guided", + "base_url": gateway_url(self.config, pid) + "/v1", + "model": p["model"], + "local_key": gateway_key(), + } return connect_native(target, self.config, pid, p["model"]) if route == "/api/probe": - protocol = CLIENTS[target][1] + protocol = CLIENTS[target].select_protocol(p["protocols"]) if protocol not in p["protocols"]: raise ConnectError(f"此客户端需要 {protocol} 协议,当前 API 未配置。") return probe(self.config, pid, protocols=[protocol], budget=256) if route == "/api/smoke": - if target not in ("claude", "codex", "openclaw", "hermes"): + if CLIENTS[target].manual_test: return { "status": "manual-required", - "message": "此客户端需要在原应用中手动发送测试消息;配置成功不代表实测通过。", + "message": CLIENTS[target].next_step.format(provider=pid, model=p["model"]) + + " 在新会话发送:Reply with exactly ITERACONNECT_OK. 核对回复。", } return smoke(self.config, target, pid, timeout=90, native=True) raise ConnectError("未知操作。") @@ -228,6 +261,7 @@ def do_POST(self): if not self.server.operation.acquire(blocking=False): self.reply(409, {"error": "上一个操作仍在进行,请稍后重试。"}) return + previous_data = self.server.data try: size = int(self.headers.get("Content-Length", "0")) if not 0 < size <= 32768 or self.headers.get("Content-Type") != "application/json": @@ -237,14 +271,19 @@ def do_POST(self): raise ValueError self.reply(200, self.server.action(self.path, body)) except ConnectError as e: - self.reply(400, {"error": str(e)}) + self.action_error(str(e), previous_data) except (ValueError, TypeError, KeyError, AttributeError, OSError): - self.reply( - 400, {"error": "操作未完成,请检查配置、文件权限及网络。详细内容不会返回密钥。"} - ) + self.action_error("操作未完成,请检查配置、文件权限及网络。", previous_data) finally: self.server.operation.release() + def action_error(self, message, previous_data): + error = {"error": message} + if self.server.data is not previous_data: + # The submitted API was saved before the client operation failed. + error.update(error="API 设置已保存。" + message, state=self.server.state()) + self.reply(400, error) + def serve_app(settings, port=18424, relay_port=18423, open_browser=True): with App(settings, port, relay_port) as app, app.relay: diff --git a/src/iteraconnect/native.py b/src/iteraconnect/native.py index 691ebc2..26c4bfe 100644 --- a/src/iteraconnect/native.py +++ b/src/iteraconnect/native.py @@ -12,10 +12,13 @@ from .config import ConnectError, gateway_key, gateway_url, private_write, state_dir from .settings import CLIENTS +from .vscode import insert_group, models_path def client_path(target, home=None): home = home or Path.home() + if target == "vscode": + return models_path(home) folders = { "claude": ("CLAUDE_CONFIG_DIR", ".claude", "settings.json"), "codex": ("CODEX_HOME", ".codex", "config.toml"), @@ -69,7 +72,7 @@ def edit_codex(text, root, key, model): pattern = rf"(?m)^{name}\s*=.*$" matches = list(re.finditer(pattern, text)) if name in before: - if not matches or ("[" in text[: matches[0].start()]): + if not matches: raise ConnectError("Codex 根配置使用复杂 TOML,请使用手动导出。") text = ( text[: matches[0].start()] @@ -163,12 +166,17 @@ def yaml_put(text, path, value, remove=False): def render_native(target, text, config, pid, model): - protocol = CLIENTS[target][1] - if protocol not in config["providers"][pid]["endpoints"]: + if target not in CLIENTS or CLIENTS[target].guided: + raise ConnectError("此客户端使用应用内引导接入。") + endpoints = config["providers"][pid]["endpoints"] + protocol = CLIENTS[target].select_protocol(endpoints) + if protocol not in endpoints: raise ConnectError( f"当前 API 缺少 {protocol} 协议。请选择支持它的 API,或使用高级协议适配。" ) root, key = gateway_url(config, pid), gateway_key() + if target == "vscode": + return insert_group(text, root, key, model, protocol) if target == "codex": return edit_codex(text, root, key, model) if target == "hermes": @@ -228,10 +236,26 @@ def render_native(target, text, config, pid, model): models = value.get("models") if isinstance(value, dict) else value if not isinstance(models, list) or any(not isinstance(x, dict) for x in models): raise ValueError + managed = { + x["id"] + for x in models + if x.get("vendor") == "iteraconnect" and isinstance(x.get("id"), str) + } models = [x for x in models if x.get("vendor") != "iteraconnect"] + model_id = pid + "/" + model + if any(x.get("id") == model_id for x in models): + raise ConnectError("WorkBuddy 已有同名模型,请先重命名或导出配置。") + if isinstance(value, dict) and "availableModels" in value: + allowed = value["availableModels"] + if not isinstance(allowed, list) or any(not isinstance(i, str) for i in allowed): + raise ValueError + if allowed: + value["availableModels"] = [ + i for i in allowed if i not in managed and i != model_id + ] + [model_id] models.append( { - "id": pid + "/" + model, + "id": model_id, "name": "Agent Connect · " + model, "vendor": "iteraconnect", "apiKey": key, @@ -302,13 +326,15 @@ def connect_native(target, config, pid, model, home=None, backups=None): text = (old or b"").decode("utf-8") except UnicodeError: raise ConnectError("客户端配置不是 UTF-8;原文件未修改。") from None - new = render_native(target, text, config, pid, model).encode() if record.exists(): saved = json.loads(record.read_text()) if saved["path"] != str(path) or saved["applied_sha256"] != digest(old or b""): raise ConnectError("客户端配置在连接后发生变化。请先手动核对备份,避免覆盖你的修改。") else: saved = {"path": str(path), "original": text if old is not None else None} + # Rebuild the VS Code insertion from its verified baseline on reconnect. + source = (saved["original"] or "") if target == "vscode" else text + new = render_native(target, source, config, pid, model).encode() # Journal before mutation. If interrupted, rollback accepts the known before/after digest. saved["previous_sha256"] = digest(old or b"") saved["applied_sha256"] = digest(new) @@ -316,12 +342,7 @@ def connect_native(target, config, pid, model, home=None, backups=None): private_write(path, new) return { "path": str(path), - "message": "配置已连接。重启客户端后生效;使用期间保持 Agent Connect 运行。" - + ( - " 在 WorkBuddy 的模型选择器中选择 custom-local:" + pid + "/" + model + "。" - if target.startswith("workbuddy") - else "" - ), + "message": "配置已写入。" + CLIENTS[target].next_step.format(provider=pid, model=model), } diff --git a/src/iteraconnect/settings.py b/src/iteraconnect/settings.py index 61621a0..9cf52ef 100644 --- a/src/iteraconnect/settings.py +++ b/src/iteraconnect/settings.py @@ -8,16 +8,54 @@ import re import tomllib from pathlib import Path +from typing import NamedTuple from .config import DEFAULT, ConnectError, private_write, validate, validate_url + +class Client(NamedTuple): + name: str + protocols: tuple[str, ...] + next_step: str + manual_test: bool = False + guided: bool = False + + def select_protocol(self, available): + return next((p for p in self.protocols if p in available), self.protocols[0]) + + CLIENTS = { - "claude": ("Claude Code", "anthropic"), - "codex": ("Codex", "responses"), - "workbuddy": ("WorkBuddy", "chat"), - "workbuddy-ai": ("WorkBuddy AI", "chat"), - "openclaw": ("OpenClaw", "chat"), - "hermes": ("Hermes", "chat"), + "claude": Client("Claude Code", ("anthropic",), "在新终端启动 claude,开始新会话。"), + "codex": Client("Codex CLI", ("responses",), "在新终端启动 codex,开始新会话。"), + "workbuddy": Client( + "WorkBuddy", + ("chat",), + "重启 WorkBuddy,新建任务,在模型菜单选择 custom-local:{provider}/{model}。", + manual_test=True, + ), + "workbuddy-ai": Client( + "WorkBuddy AI", + ("chat",), + "重启 WorkBuddy AI,新建任务,在模型菜单选择 custom-local:{provider}/{model}。", + manual_test=True, + ), + "visual-studio": Client( + "Visual Studio", + ("chat",), + "在 Windows 的 Visual Studio 2026 中打开 Copilot Chat → 管理模型,添加自定义端点。", + manual_test=True, + guided=True, + ), + "vscode": Client( + "VS Code", + ("responses", "chat"), + "在 VS Code 中启用 Copilot Chat 并重新加载窗口,在本地聊天中选择 Agent Connect 下的 {model}。", + manual_test=True, + ), + "openclaw": Client("OpenClaw", ("chat",), "重启 OpenClaw,在新会话中使用默认模型。"), + "hermes": Client( + "Hermes", ("chat",), "重启 Hermes,在新会话中使用 custom:iteraconnect 提供方。" + ), } APP_DEFAULT = { "selected_provider": "iteracompute", diff --git a/src/iteraconnect/vscode.py b/src/iteraconnect/vscode.py new file mode 100644 index 0000000..1883137 --- /dev/null +++ b/src/iteraconnect/vscode.py @@ -0,0 +1,77 @@ +"""Insert a Custom Endpoint group into the VS Code user's model catalog.""" + +import json +import os +import re +import sys +from pathlib import Path + +from .config import ConnectError + + +def models_path(home): + if location := os.environ.get("ITERACONNECT_VSCODE_USER_DIR"): + user = Path(location).expanduser() + elif sys.platform == "darwin": + user = home / "Library/Application Support/Code/User" + elif os.name == "nt": + user = Path(os.environ.get("APPDATA") or home / "AppData/Roaming") / "Code/User" + else: + user = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") / "Code/User" + return user / "chatLanguageModels.json" + + +# Mask comments without changing offsets or matching comment markers inside strings. +_STRING = r'"(?:[^"\\]|\\.)*"' +_TOKENS = re.compile(_STRING + r"|//[^\r\n]*|/\*[\s\S]*?\*/") +_TRAILING_COMMA = re.compile(_STRING + r"|,\s*(?=[]}])") + + +def insert_group(text, root, key, model, protocol): + responses = protocol == "responses" + group = { + "name": "Agent Connect", + "vendor": "customendpoint", + "apiType": "responses" if responses else "chat-completions", + "models": [ + { + "id": model, + "name": model, + "url": root + ("/v1/responses" if responses else "/v1/chat/completions"), + # VS Code resolves the provider apiKey via its interactive secret store. + # Custom Endpoint supports an explicit auth header for local gateways. + "requestHeaders": {"Authorization": "Bearer " + key}, + "toolCalling": True, + "vision": False, + "maxInputTokens": 16384, + "maxOutputTokens": 2048, + } + ], + } + if responses: + group["models"][0]["statefulResponses"] = False + if not text.strip(): + return json.dumps([group], ensure_ascii=False, indent=2) + "\n" + sanitized = _TOKENS.sub(lambda m: " " * len(m[0]) if m[0].startswith("/") else m[0], text) + + def remove_trailing(m): + if m[0].startswith(",") and sanitized[: m.start()].rstrip()[-1:] not in ("[", "{", ",", ""): + return " " * len(m[0]) + return m[0] + + try: + groups = json.loads(_TRAILING_COMMA.sub(remove_trailing, sanitized)) + if not isinstance(groups, list) or not all(isinstance(g, dict) for g in groups): + raise ValueError + except ValueError: + raise ConnectError( + "无法读取 VS Code 模型列表,请导出配置并在“管理语言模型”中添加。" + ) from None + if any(g.get("name") == group["name"] for g in groups): + raise ConnectError("VS Code 已有 Agent Connect 分组。请先重命名该分组或使用手动导出。") + # Insert at the opening bracket. Existing groups, comments and trailing commas stay verbatim. + pos = sanitized.index("[") + 1 + inserted = "\n" + "\n".join( + " " + line for line in json.dumps(group, ensure_ascii=False, indent=2).splitlines() + ) + return text[:pos] + inserted + ("," if groups else "") + "\n" + text[pos:] diff --git a/src/iteraconnect/web/app.css b/src/iteraconnect/web/app.css index a261be0..de2f209 100644 --- a/src/iteraconnect/web/app.css +++ b/src/iteraconnect/web/app.css @@ -1428,3 +1428,46 @@ footer .icon { transition: none !important; } } + +.setup-guide { + margin-top: 16px; + background: #f7f9f4; + border: 1px solid #dce6d8; + border-radius: 10px; + padding: 16px; + font-size: 12px; + line-height: 1.7; + overflow-wrap: anywhere; +} +.setup-guide h3 { + font-size: 14px; + margin: 0; +} +.setup-guide ol { + padding-left: 20px; +} +.setup-guide li + li { + margin-top: 10px; +} +.setup-guide p { + color: var(--muted); +} +.guide-value { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 4px 10px; + margin-top: 8px; +} +.guide-value label { + grid-column: 1 / -1; +} +.guide-value input { + font-family: ui-monospace, monospace; + min-width: 0; +} +.client[data-id="visual-studio"] .client-icon, +.client[data-id="vscode"] .client-icon { + color: #635288; + background: #f1edf8; + font-size: 13px; +} diff --git a/src/iteraconnect/web/app.js b/src/iteraconnect/web/app.js index e65380c..207b165 100644 --- a/src/iteraconnect/web/app.js +++ b/src/iteraconnect/web/app.js @@ -5,6 +5,8 @@ const clientIcons = { codex: "⌘", workbuddy: "W", "workbuddy-ai": "W", + "visual-studio": "VS", + vscode: "〈〉", openclaw: "◈", hermes: "H", }; @@ -62,11 +64,16 @@ async function api(path, body) { ); } const data = await response.json(); - if (!response.ok) throw new Error(data.error || "操作未完成,请重试。"); + if (!response.ok) { + if (data.state) render(data.state); + throw new Error(data.error || "操作未完成,请重试。"); + } return data; } function result(title, message, kind = "", data) { resultSelection = undefined; + $("setup-guide").hidden = true; + $("guide-fields").replaceChildren(); $("result").className = "result-box" + (kind ? " " + kind : ""); $("result-title").textContent = title; $("result-message").textContent = message; @@ -93,7 +100,7 @@ function updateAvailability() { $("workspace").setAttribute("aria-busy", String(working)); if (!state || working) return; const client = state.clients.find((c) => c.id === selectedClient); - const matched = selectedProtocols().includes(client.protocol); + const matched = client.protocols.some((p) => selectedProtocols().includes(p)); ["connect", "probe", "smoke", "export"].forEach((id) => { $(id).disabled = !matched; }); @@ -187,6 +194,16 @@ function selectionSnapshot() { Boolean($("api-key").value.trim()), ]); } +function clientNextStep(client) { + const values = { + provider: adding ? $("provider-id").value.trim() : $("provider").value, + model: $("model").value.trim(), + }; + return client.next_step.replace( + /\{(provider|model)\}/g, + (_, name) => values[name] || "…", + ); +} function updatePath() { if (!state) return; if (resultSelection && resultSelection !== selectionSnapshot()) { @@ -195,7 +212,8 @@ function updatePath() { const p = state.settings.providers[$("provider").value]; const client = state.clients.find((c) => c.id === selectedClient); const currentProtocols = selectedProtocols(); - const matched = currentProtocols.includes(client.protocol); + const protocol = client.protocols.find((p) => currentProtocols.includes(p)); + const matched = Boolean(protocol); const keyEntered = Boolean($("api-key").value.trim()); $("key-status").textContent = keyEntered ? "待保存" @@ -208,24 +226,32 @@ function updatePath() { $("path-model").textContent = $("model").value.trim() || "请选择模型"; $("path-client").textContent = client.name; $("path-client-icon").textContent = clientIcons[client.id]; - $("connect-label").textContent = "连接 " + client.name; - $("required-protocol").textContent = protocols[client.protocol]; + $("native-actions").hidden = client.guided; + $("smoke-label").textContent = client.manual_test + ? "查看实测步骤" + : "客户端实测"; + $("connect-label").textContent = client.guided + ? "获取 Visual Studio 接入信息" + : "连接 " + client.name; + $("required-protocol").textContent = + protocols[protocol || client.protocols[0]]; $("protocol-match").textContent = matched ? "协议匹配" : "需要配置"; $("protocol-match").classList.toggle("missing", !matched); $("protocol-summary").textContent = `${currentProtocols.length} 种协议`; $("compatibility").hidden = matched; $("compatibility-text").textContent = - `此客户端需要 ${protocols[client.protocol]}。请确认 API 支持后,在地址与协议中勾选。`; + `此客户端支持 ${client.protocols.map((p) => protocols[p]).join(" 或 ")}。请确认 API 支持后,在地址与协议中勾选。`; $("connection-status").textContent = client.connected - ? "已配置 · 可恢复" - : "尚未连接"; + ? "此软件有备份" + : client.guided + ? "在软件内添加" + : "尚未连接"; $("connection-status").className = "badge " + (client.connected ? "good" : "neutral"); - $("client-hint").textContent = client.id.startsWith("workbuddy") - ? "连接后重启 WorkBuddy,在任务中选择 custom-local 模型。" - : client.installed - ? "自动备份并写入配置,连接后重启客户端即可使用。" - : "尚未检测到安装。可以先连接配置,再安装客户端。"; + const nextStep = clientNextStep(client); + $("client-hint").textContent = client.guided + ? nextStep + : "接入后:" + nextStep; document.querySelectorAll(".client").forEach((el) => { const selected = el.dataset.id === selectedClient; el.classList.toggle("selected", selected); @@ -256,8 +282,18 @@ function render(next) { $("provider").append(option); }); $("provider").value = next.settings.selected_provider; + renderClients(); + $("settings-location").textContent = + "本地配置:" + next.settings_path.split(/[\\/]/).pop(); + $("settings-location").title = next.settings_path; + loadProvider(); + if (first && next.settings.providers[next.settings.selected_provider].has_key) + result("已读取本地配置", "选择客户端即可连接,也可以先测试 API。"); +} +function renderClients() { + $("client-count").textContent = state.clients.length + " 个客户端"; $("clients").replaceChildren(); - next.clients.forEach((c) => { + state.clients.forEach((c) => { const button = document.createElement("button"); button.className = "client"; button.dataset.id = c.id; @@ -269,16 +305,20 @@ function render(next) { textElement( "span", "client-type", - c.id === "hermes" || c.id === "openclaw" ? "智能体" : "编码工具", + c.guided ? "应用内引导" : "自动写入配置", ), textElement( "span", "client-status" + (c.connected || c.installed ? " detected" : ""), c.connected ? "已配置 · 可恢复" - : c.installed - ? "已检测到安装" - : "可配置 · 未检测到", + : c.guided + ? "Windows · Copilot Chat" + : c.installed + ? "已检测到安装" + : c.config_detected + ? "发现配置目录" + : "可配置 · 未检测到", ), ); const mark = textElement("span", "client-check", ""); @@ -302,30 +342,24 @@ function render(next) { ]; if (!keys.includes(event.key)) return; event.preventDefault(); - const index = next.clients.findIndex( + const index = state.clients.findIndex( (item) => item.id === selectedClient, ); const at = event.key === "Home" ? 0 : event.key === "End" - ? next.clients.length - 1 + ? state.clients.length - 1 : (index + (["ArrowLeft", "ArrowUp"].includes(event.key) ? -1 : 1) + - next.clients.length) % - next.clients.length; - selectedClient = next.clients[at].id; + state.clients.length) % + state.clients.length; + selectedClient = state.clients[at].id; updatePath(); $("clients").children[at].focus(); }; $("clients").append(button); }); - $("settings-location").textContent = - "本地配置:" + next.settings_path.split(/[\\/]/).pop(); - $("settings-location").title = next.settings_path; - loadProvider(); - if (first && next.settings.providers[next.settings.selected_provider].has_key) - result("已读取本地配置", "选择客户端即可连接,也可以先测试 API。"); } function form({ catalog = false, requireKey = false } = {}) { clearErrors(); @@ -532,24 +566,69 @@ $("models").onclick = () => data.models.length ? "success" : "", ); }); +async function submitAction(route, requireKey = false) { + const { state: next, ...data } = await api(route, form({ requireKey })); + render(next); + return data; +} +function showGuide(data) { + result( + "接入信息已准备好", + "在 Visual Studio 中添加模型后,发送测试消息确认回复。", + ); + const fields = [ + ["base_url", "端点地址"], + ["model", "模型 ID"], + ["local_key", "API Key(本地网关令牌)"], + ]; + fields.forEach(([name, label]) => { + const row = textElement("div", "guide-value", ""); + const input = document.createElement("input"); + input.id = "guide-" + name; + input.type = name === "local_key" ? "password" : "text"; + input.readOnly = true; + input.value = data[name]; + const title = textElement("label", "", label); + title.htmlFor = input.id; + const copy = textElement("button", "secondary", "复制"); + copy.setAttribute("aria-label", "复制" + label); + copy.onclick = async () => { + try { + await navigator.clipboard.writeText(input.value); + copy.textContent = "已复制"; + } catch { + input.type = "text"; + input.focus(); + input.select(); + copy.textContent = "请手动复制"; + } + }; + row.append(title, input, copy); + $("guide-fields").append(row); + }); + $("setup-guide").hidden = false; + $("guide-title").focus(); + resultSelection = selectionSnapshot(); +} $("connect").onclick = () => - busy("正在备份并连接客户端…", async () => { - await save({ requireKey: true }); - const data = await api("connect", {}); - render(await api("state")); + busy("正在准备接入…", async () => { + const data = await submitAction("connect", true); + if (data.setup === "guided") return showGuide(data); result("客户端已配置", data.message, "success"); + resultSelection = selectionSnapshot(); + $("client-hint").textContent = data.message; }); $("disconnect").onclick = () => busy("正在检查并恢复原配置…", async () => { - await save(); - const data = await api("disconnect", {}); - render(await api("state")); + const data = await api("disconnect", { client: selectedClient }); + state.clients.find((c) => c.id === selectedClient).connected = false; + renderClients(); + updatePath(); result("已恢复原配置", data.message, "success"); }); $("export").onclick = () => busy("正在生成配置片段…", async () => { - await save(); - const data = await api("export", {}); + const data = await submitAction("export"); result("配置片段已生成", data.message); $("result-json").textContent = data.fragment; $("details-label").textContent = "查看配置片段"; @@ -572,16 +651,29 @@ $("copy-export").onclick = async () => { } }; ["probe", "smoke"].forEach((type) => { - $(type).onclick = () => - busy( + $(type).onclick = () => { + const client = state.clients.find((c) => c.id === selectedClient); + if (type === "smoke" && client.manual_test) { + showTest( + { + status: "manual-required", + message: + clientNextStep(client) + + " 在新会话发送:Reply with exactly ITERACONNECT_OK. 核对回复。", + }, + type, + ); + return; + } + return busy( type === "probe" ? "正在测试文本、流式与工具调用,请稍候…" : "正在启动隔离的客户端测试,最长约 90 秒…", async () => { - await save({ requireKey: true }); - showTest(await api(type, {}), type); + showTest(await submitAction(type, true), type); }, ); + }; }); updateAvailability(); api("state") diff --git a/src/iteraconnect/web/index.html b/src/iteraconnect/web/index.html index 6f633a1..a144a85 100644 --- a/src/iteraconnect/web/index.html +++ b/src/iteraconnect/web/index.html @@ -84,9 +84,8 @@
-
YOUR MODELS. YOUR TOOLS.
-

把模型,接入你的工作流。

-

选择 API 和客户端,让你熟悉的工具用上你需要的模型。

+

连接你的软件

+

首次填写 API key 和模型,然后选择软件。下次打开可直接切换。

@@ -242,9 +241,9 @@

配置你的 API

02

选择你的客户端

-

编码工具或智能体,都可以接入

+

选择要使用这个模型的软件

- 6 个客户端 +
选择你的客户端

自动备份原配置,连接后重启客户端即可使用。

- diff --git a/tests/test_app.py b/tests/test_app.py index 205f57b..979b6d5 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -11,6 +11,7 @@ import unittest from pathlib import Path from unittest.mock import patch +from urllib.request import Request, urlopen from iteraconnect.app import App from iteraconnect.config import DEFAULT, ConnectError @@ -86,6 +87,7 @@ def test_all_adapters_preserve_settings_reconnect_and_restore_exactly(self): "codex": '# a comment\nmodel = "old"\n[history]\npersistence = "none"\n', "workbuddy": '[{"id":"mine","vendor":"mine","enabled":false}]\n', "workbuddy-ai": '[{"id":"mine","vendor":"mine","enabled":false}]\n', + "vscode": '[{"vendor":"mine","models":[{"id":"keep"}]}]\n', "openclaw": '{"messages":{"responsePrefix":"keep"},"agents":{"defaults":{"models":{"mine/old":{}}}}}\n', "hermes": "# my config\nmodel:\n provider: openrouter\n default: old\nui:\n theme: dark", } @@ -152,7 +154,7 @@ def test_workbuddy_object_and_duplicate_json_fields(self): '{"models":[{"id":"mine","vendor":"mine"}],"availableModels":["mine"],"theme":"dark"}' ) data = json.loads(render_native("workbuddy", text, DEFAULT, "iteracompute", MODEL)) - self.assertEqual(data["availableModels"], ["mine"]) + self.assertEqual(data["availableModels"], ["mine", "iteracompute/" + MODEL]) self.assertEqual(data["theme"], "dark") self.assertEqual(len(data["models"]), 2) with self.assertRaises(ConnectError): @@ -160,6 +162,60 @@ def test_workbuddy_object_and_duplicate_json_fields(self): "claude", '{"env":{},"env":{"KEEP":"yes"}}', DEFAULT, "iteracompute", MODEL ) + def test_workbuddy_picker_survives_switches_and_respects_unrestricted_lists(self): + for target in ("workbuddy", "workbuddy-ai"): + for allowed in ([], ["mine"], None): + with self.subTest(target=target, allowed=allowed): + seed = {"models": [{"id": "mine"}]} + if allowed is not None: + seed["availableModels"] = allowed + first = render_native(target, json.dumps(seed), DEFAULT, "iteracompute", MODEL) + updated = json.loads( + render_native(target, first, DEFAULT, "iteracompute", "new/model") + ) + expected = ["mine", "iteracompute/new/model"] if allowed else allowed + self.assertEqual(updated.get("availableModels"), expected) + self.assertEqual( + [r["id"] for r in updated["models"]], ["mine", "iteracompute/new/model"] + ) + with self.assertRaises(ConnectError): + render_native(target, '[{"id":"iteracompute/dup"}]', DEFAULT, "iteracompute", "dup") + + def test_codex_root_after_array_and_comment_preserves_nested_settings(self): + original = '# models [example]\nfeatures_list = ["keep"]\nmodel = "old"\n[profiles.test]\nmodel="keep"\n' + edited = tomllib.loads(render_native("codex", original, DEFAULT, "iteracompute", MODEL)) + self.assertEqual(edited["model"], MODEL) + self.assertEqual(edited["profiles"]["test"]["model"], "keep") + + def test_vscode_jsonc_preservation_switch_conflicts_and_exact_restore(self): + with tempfile.TemporaryDirectory() as directory: + home = Path(directory) + backups = home / "backups" + path = client_path("vscode", home) + path.parent.mkdir(parents=True) + original = ( + b'// [ providers ]\r\n[ /* keep */ {"url":"https://mine/a,]", "models":[],}, ]\r\n' + ) + path.write_bytes(original) + for model in ("first", "next/model"): + connect_native("vscode", DEFAULT, "iteracompute", model, home, backups) + raw = path.read_bytes() + self.assertIn(b'/* keep */ {"url":"https://mine/a,]", "models":[],},', raw) + self.assertEqual(raw.count(b'"vendor": "customendpoint"'), 1) + self.assertIn(model.encode(), raw) + path.write_bytes(raw + b"// new edit") + with self.assertRaises(ConnectError): + disconnect_native("vscode", home, backups) + path.write_bytes(raw) + disconnect_native("vscode", home, backups) + self.assertEqual(path.read_bytes(), original) + for seed in ('[{"name":"Agent Connect"}]', "[,]", "{}", "[/* broken]"): + path.write_text(seed) + with self.assertRaises(ConnectError): + connect_native("vscode", DEFAULT, "iteracompute", MODEL, home, backups) + self.assertEqual(path.read_text(), seed) + self.assertFalse((backups / "vscode.json").exists()) + def test_hermes_stale_endpoint_and_key_command_cannot_override_selection(self): values = ( 'model:\n provider: custom\n base_url: "https://oldvendor.example/v1"\n api_key: old-key\n key_env: OLD_KEY\nproviders:\n iteraconnect:\n key_cmd: old-helper\n api: "https://oldvendor.example/v1"\nui:\n theme: dark\n', @@ -331,6 +387,124 @@ def test_failed_draft_discovery_cleans_up_and_preserves_the_saved_key(self): self.assertEqual(self.app.data["providers"]["iteracompute"]["api_key"], VENDOR_KEY) self.assertEqual(dict(os.environ), before_env) + def test_visual_studio_guided_setup_is_scoped_and_never_records_a_connection(self): + selected = {"provider": "iteracompute", "client": "visual-studio", "api_key": VENDOR_KEY} + self.assertEqual(self.call("/api/connect", selected, auth=False)[0], 401) + status, raw = self.call("/api/connect", selected) + self.assertEqual(status, 200) + self.assertNotIn(VENDOR_KEY.encode(), raw) + guide = json.loads(raw) + self.assertEqual(guide["local_key"], LOCAL_KEY) + self.assertEqual( + guide["base_url"], f"http://127.0.0.1:{self.app.relay.server_port}/p/iteracompute/v1" + ) + self.assertEqual(guide["setup"], "guided") + self.assertNotIn(LOCAL_KEY.encode(), self.call("/api/state")[1]) + client = next(c for c in guide["state"]["clients"] if c["id"] == "visual-studio") + self.assertIsNone(client["config_path"]) + self.assertFalse(client["connected"]) + self.assertTrue(client["manual_test"]) + self.assertEqual(json.loads(self.call("/api/smoke", {})[1])["status"], "manual-required") + for route in ("disconnect", "export"): + self.assertEqual(self.call("/api/" + route, {})[0], 400) + status, failed = self.call("/api/connect", {**selected, "protocols": ["responses"]}) + self.assertEqual(status, 400) + self.assertNotIn(VENDOR_KEY.encode(), failed) + self.assertEqual(json.loads(failed)["state"]["settings"]["client"], "visual-studio") + + def test_desktop_connection_values_route_model_catalog_and_chat_to_fixture(self): + from iteraconnect.diagnostics import payload, send + + worker = threading.Thread(target=self.app.relay.serve_forever, daemon=True) + worker.start() + self.addCleanup(self.app.relay.shutdown) + base = Path(self.folder.name) + dirs = { + "WORKBUDDY_CONFIG_DIR": str(base / "wb"), + "WORKBUDDY_AI_CONFIG_DIR": str(base / "wbai"), + "ITERACONNECT_VSCODE_USER_DIR": str(base / "vs-code"), + } + with stack() as (config, vendor, _gateway), patch.dict(os.environ, dirs): + for target in ("visual-studio", "vscode", "workbuddy", "workbuddy-ai"): + with self.subTest(target=target): + status, raw = self.call( + "/api/connect", + { + "provider": "custom", + "client": target, + "name": "Fixture", + "model": MODEL, + "protocols": ["chat"], + "base_url": config["providers"]["iteracompute"]["endpoints"]["chat"], + "api_key": VENDOR_KEY, + }, + ) + self.assertEqual(status, 200) + if target == "visual-studio": + guide = json.loads(raw) + key, model = guide["local_key"], guide["model"] + url = guide["base_url"] + "/chat/completions" + request = Request( + guide["base_url"] + "/models", + headers={"Authorization": "Bearer " + key}, + ) + with urlopen(request, timeout=5) as response: + self.assertIn(MODEL, [row["id"] for row in json.load(response)["data"]]) + else: + row = json.loads(client_path(target).read_text())[0] + if target == "vscode": + route = row["models"][0] + key = route["requestHeaders"]["Authorization"].removeprefix("Bearer ") + else: + route, key = row, row["apiKey"] + model, url = route["id"], route["url"] + result = send(url, key, "chat", payload("chat", model, 256, False), 5) + self.assertEqual(result["choices"][0]["message"]["content"], "ITERACONNECT_OK") + self.assertTrue( + vendor.requests[-1][2]["Authorization"] == "Bearer " + VENDOR_KEY + ) + self.assertEqual(vendor.requests[-1][3]["model"], MODEL) + + def test_one_click_actions_target_the_submitting_tab_and_restore_without_saving_drafts(self): + folder = Path(self.folder.name) + with patch.dict( + os.environ, + { + "ITERACONNECT_VSCODE_USER_DIR": str(folder / "Code/User"), + "CODEX_HOME": str(folder / "Codex"), + }, + ): + for client in ("codex", "vscode"): + status, raw = self.call( + "/api/connect", + { + "provider": "iteracompute", + "client": client, + "model": "owner/model", + "api_key": VENDOR_KEY, + }, + ) + self.assertEqual(status, 200) + self.assertNotIn(VENDOR_KEY.encode(), raw) + self.assertTrue(client_path(client).exists()) + group = json.loads(client_path("vscode").read_text())[0] + entry = group["models"][0] + self.assertEqual(entry["id"], "owner/model") + self.assertEqual(group["apiType"], "responses") + self.assertFalse(entry["statefulResponses"]) + self.assertTrue(entry["toolCalling"]) + self.assertFalse(entry["vision"]) + self.assertGreater(entry["maxInputTokens"], entry["maxOutputTokens"]) + self.assertEqual( + group["models"][0]["url"], + f"http://127.0.0.1:{self.app.relay.server_port}/p/iteracompute/v1/responses", + ) + settings = self.app.settings_path.read_bytes() + self.assertEqual(self.call("/api/disconnect", {"client": "codex"})[0], 200) + self.assertFalse(client_path("codex").exists()) + self.assertTrue(client_path("vscode").exists()) + self.assertEqual(self.app.settings_path.read_bytes(), settings) + def test_external_key_file_edits_are_not_overwritten_by_stale_ui(self): data = read_settings(self.app.settings_path) data["providers"]["iteracompute"]["api_key"] = VENDOR_KEY diff --git a/tests/vscode_desktop.py b/tests/vscode_desktop.py new file mode 100644 index 0000000..62ab47d --- /dev/null +++ b/tests/vscode_desktop.py @@ -0,0 +1,146 @@ +"""Opt-in VS Code desktop chat acceptance on Linux with Playwright and a virtual display.""" + +import argparse +import json +import os +import subprocess +import tempfile +import threading +import time +from contextlib import contextmanager +from pathlib import Path +from unittest.mock import patch + +from iteraconnect.diagnostics import PROMPT +from iteraconnect.gateway import Gateway +from iteraconnect.native import connect_native, disconnect_native +from iteraconnect.settings import read_settings, runtime_config +from iteraconnect.smoke import sandbox_env + +from .fixtures import TEXT, stack + + +@contextmanager +def backend(settings): + if settings is None: + with stack(chat_only=True) as (config, vendor, _): + yield config, "iteracompute" + assert any(r[0] == "POST" and r[1] == "/v1/chat/completions" for r in vendor.requests) + return + if not settings.is_file(): + raise ValueError("Supply an existing private test settings file") + data = read_settings(settings) + pid = data["selected_provider"] + if not data["providers"][pid]["api_key"]: + raise ValueError("A dedicated provider test key is required") + config = runtime_config(data) + with Gateway(config, address=("127.0.0.1", 0)) as server: + config["gateway"]["port"] = server.server_port + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + try: + yield config, pid + finally: + server.shutdown() + worker.join() + + +def chat(pw, root, args, model): + user_data = root / "Code" + env = sandbox_env(root) + env.update(DISPLAY=os.environ["DISPLAY"], XAUTHORITY=os.environ.get("XAUTHORITY", "")) + work = root / "workspace" + work.mkdir() + cmd = [ + str(args.electron), + "--user-data-dir", + str(user_data), + "--extensions-dir", + str(root / "extensions"), + "--extensionDevelopmentPath=" + str(args.copilot), + "--remote-debugging-address=127.0.0.1", + "--remote-debugging-port=0", + "--skip-welcome", + "--skip-release-notes", + "--disable-gpu", + str(work), + ] + with subprocess.Popen( + cmd, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True + ) as proc: + try: + port_file = user_data / "DevToolsActivePort" + deadline = time.monotonic() + 30 + while not port_file.is_file() and proc.poll() is None and time.monotonic() < deadline: + time.sleep(0.15) + port = int(port_file.read_text().splitlines()[0]) + browser = pw.chromium.connect_over_cdp(f"http://127.0.0.1:{port}") + page = browser.contexts[0].pages[0] + editor = page.locator(".interactive-input-part .monaco-editor").last + page.get_by_text(model, exact=True).first.wait_for(state="attached", timeout=60000) + editor.click(position={"x": 45, "y": 12}) + page.keyboard.type(PROMPT) + page.keyboard.press("Enter") + page.locator(".interactive-response").get_by_text(TEXT, exact=True).first.wait_for( + timeout=90000 + ) + if args.screenshot: + page.screenshot(path=args.screenshot) + finally: + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + + +def main(): + from playwright.sync_api import sync_playwright + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--electron", type=Path, default=Path("/usr/share/code/code")) + parser.add_argument( + "--copilot", type=Path, default=Path("/usr/share/code/resources/app/extensions/copilot") + ) + parser.add_argument("--settings", type=Path, help="explicitly use the selected real provider") + parser.add_argument("--screenshot", type=Path, help="capture a fixture result") + args = parser.parse_args() + if args.settings and args.screenshot: + parser.error("the automated screenshot is for fixture runs") + with ( + tempfile.TemporaryDirectory(prefix="iteraconnect-vscode-") as directory, + sync_playwright() as pw, + ): + root = Path(directory) + user = root / "Code/User" + user.mkdir(parents=True) + (user / "settings.json").write_text( + json.dumps( + { + "workbench.startupEditor": "none", + "telemetry.telemetryLevel": "off", + "update.mode": "none", + "security.workspace.trust.enabled": False, + } + ) + ) + with ( + patch.dict( + os.environ, + ITERACONNECT_VSCODE_USER_DIR=str(user), + ITERACONNECT_HOME=str(root / "state"), + ), + backend(args.settings) as (config, pid), + ): + model = config["providers"][pid]["default_model"] + connect_native("vscode", config, pid, model) + chat(pw, root, args, model) + disconnect_native("vscode") + assert not (user / "chatLanguageModels.json").exists() + print( + "VS Code desktop chat and restore passed ·", "real provider" if args.settings else "fixture" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/workbench_browser.py b/tests/workbench_browser.py new file mode 100644 index 0000000..006c38b --- /dev/null +++ b/tests/workbench_browser.py @@ -0,0 +1,127 @@ +"""Run the packaged workbench in Chromium against a localhost fixture vendor.""" + +import argparse +import copy +import os +import tempfile +import threading +from pathlib import Path +from unittest.mock import patch + +from iteraconnect.app import App +from iteraconnect.native import client_path +from iteraconnect.settings import APP_DEFAULT, CLIENTS, write_settings +from iteraconnect.smoke import sandbox_env + +from .fixtures import LOCAL_KEY, MODEL, VENDOR_KEY, stack + + +def exercise(page, app, screenshot): + from playwright.sync_api import expect + + page.goto(app.origin + "/#" + app.token) + expect(page.get_by_role("radio")).to_have_count(len(CLIENTS)) + for target, client in CLIENTS.items(): + page.get_by_role("radio", name=client.name, exact=True).click() + page.locator("#connect").click() + if client.guided: + expect(page.locator("#setup-guide")).to_be_visible() + expect(page.locator("#guide-model")).to_have_value(MODEL) + assert page.locator("#guide-local_key").input_value() == LOCAL_KEY + expect(page.locator("#guide-local_key")).to_have_attribute("type", "password") + page.get_by_role("button", name="复制端点地址").click() + expect(page.get_by_role("button", name="复制端点地址")).to_have_text("已复制") + assert ( + page.evaluate("navigator.clipboard.readText()") + == page.locator("#guide-base_url").input_value() + ) + expect(page.locator("#native-actions")).to_be_hidden() + else: + expect(page.locator("#result-title")).to_have_text("客户端已配置") + path = client_path(target) + assert path.exists() and VENDOR_KEY not in path.read_text() + page.locator("#disconnect").click() + expect(page.locator("#result-title")).to_have_text("已恢复原配置") + assert not path.exists() + if client.manual_test: + page.locator("#smoke").click() + expect(page.locator("#result-title")).to_have_text("需要在客户端继续操作") + expect(page.locator("#result-message")).to_contain_text("ITERACONNECT_OK") + print(target, "workbench flow passed", flush=True) + + page.locator('[data-id="visual-studio"]').click() + page.locator("#connect").click() + expect(page.locator("#setup-guide")).to_be_visible() + page.locator('[data-id="vscode"]').click() + expect(page.locator("#guide-fields input")).to_have_count(0) + expect(page.locator("#required-protocol")).to_have_text("Responses") + page.locator("#advanced").evaluate("(item) => item.open = true") + page.locator('[name="protocol"][value="responses"]').uncheck() + expect(page.locator("#required-protocol")).to_have_text("Chat Completions") + page.locator("#probe").click() + expect(page.locator("#result-title")).to_have_text("API 测试通过") + expect(page.locator(".result-card")).to_have_count(3) + page.locator('[data-id="vscode"]').press("Home") + expect(page.locator('[data-id="claude"]')).to_have_attribute("aria-checked", "true") + page.locator("#advanced").evaluate("(item) => item.open = true") + page.locator('[name="protocol"][value="anthropic"]').uncheck() + expect(page.locator("#connect")).to_be_disabled() + page.locator('[name="protocol"][value="anthropic"]').check() + page.locator("#advanced").evaluate("(item) => item.open = false") + page.reload() + expect(page.locator("#clients button")).to_have_count(len(CLIENTS)) + page.locator('[data-id="workbuddy"]').click() + if screenshot: + page.mouse.move(0, 0) + page.emulate_media(reduced_motion="reduce") + page.screenshot(path=screenshot, full_page=True, animations="disabled") + page.set_viewport_size({"width": 390, "height": 844}) + page.locator('[data-id="visual-studio"]').click() + page.locator("#connect").click() + expect(page.locator("#setup-guide")).to_be_visible() + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + print("protocol validation, fixture probe, keyboard selection and 390px guide passed") + + +def main(): + from playwright.sync_api import sync_playwright + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--screenshot", type=Path, help="save the desktop fixture workbench") + args = parser.parse_args() + with sync_playwright() as pw, tempfile.TemporaryDirectory() as directory: + browser = pw.chromium.launch() + home = Path(directory) + env = sandbox_env(home) + env.update( + ITERACONNECT_HOME=str(home / "state"), + ITERACONNECT_VSCODE_USER_DIR=str(home / "Code/User"), + WORKBUDDY_CONFIG_DIR=str(home / ".workbuddy"), + WORKBUDDY_AI_CONFIG_DIR=str(home / ".workbuddy-ai"), + ) + with patch.dict(os.environ, env), stack() as (config, _, _relay): + data = copy.deepcopy(APP_DEFAULT) + data["providers"]["iteracompute"].update( + api_key=VENDOR_KEY, + model=MODEL, + base_url=config["providers"]["iteracompute"]["endpoints"]["anthropic"], + ) + settings = home / "agent-connect.local.toml" + write_settings(settings, data) + with App(settings, port=0, relay_port=0) as app, app.relay: + for server in (app, app.relay): + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + context = browser.new_context(viewport={"width": 1360, "height": 960}) + context.grant_permissions( + ["clipboard-read", "clipboard-write"], origin=app.origin + ) + exercise(context.new_page(), app, args.screenshot) + finally: + app.shutdown() + app.relay.shutdown() + browser.close() + + +if __name__ == "__main__": + main()