diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/brief.md b/docs/tasks/T-1200/T-1245-instabox-settings/brief.md new file mode 100644 index 00000000..ba7ddbad --- /dev/null +++ b/docs/tasks/T-1200/T-1245-instabox-settings/brief.md @@ -0,0 +1,93 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1245 云电脑④:设置页钥匙、后端选择、快照 + +(本任务是 T-1239 的第 4 块,与 ①②③ 并行开发。下面「共同约定」必须遵守。只有本任务改 zh/en 文案。) + +## 本任务负责的文件(只改这些) +- 新建:`server/instabox/machine.ts`(共享契约,按约定原样;已存在就不改)、`server/routes/instabox-snapshots.ts` 及测试、你自己的假服务 `server/testing/fake-instabox-snapshots.ts`、`src/components/InstaboxSnapshots.tsx` 及测试。 +- 修改:`src/components/CloudBackendPicker.tsx`、`src/components/keys/key-catalog.ts`(及其测试)、`server/routes/config.ts`(余量 10 行)、`src/components/ComputerPanel.tsx`(余量 25 行,只放挂载点)、`src/locales/zh.json`、`src/locales/en.json`、`shared/wire.ts:62`(按约定原样改那一行)。 +- **不改** `server/index.ts`、`server/config.ts`、`server/store.ts`(属于 ①/⑤)。配置字段约定为 `cfg.instabox?.apiKey`,环境变量 `INSTABOX_API_KEY` 优先(① 实现读取;你这边保存时写 `instabox.apiKey`,类型若尚未存在就在 routes/config.ts 内局部声明,⑤ 合并时统一)。 + +## 要做 +1. 设置页钥匙:在 key-catalog 里加 钥匙一项(与现有 Boat 钥匙同样的保存/清除/显示已配置方式),说明一句话:「云电脑()钥匙,所有智能体共用」。钥匙只回显「已配置」,绝不回传明文;环境变量设置时显示为环境变量提供、不可在页面改。`routes/config.ts` 的保存接口支持它;`RemoteComputerProvider` 类型(routes/config.ts:56)加 `"instabox"`。 +2. `CloudBackendPicker.tsx`:选项从 Boat / VPS 变为 Boat / VPS / 三个;的说明文案中英文都加。钥匙没配时 按钮可点但下方提示「先在设置里填 钥匙」。 +3. 快照路由 `instabox-snapshots.ts` 导出 `createInstaboxSnapshotRoutes(deps: { machines(): InstaboxMachines | null; request(): InstaboxRequest | null; machineIdFor(botId: string): Promise; botExists(botId: string): boolean }): RouteHandler`(RouteHandler 与现有路由同类型),路由: + - `GET /api/bots/:id/instabox/snapshots`:列出该智能体机器的快照(按 metadata/名字前缀 `crybot--` 过滤)。 + - `POST /api/bots/:id/instabox/snapshots {name?}`:存快照,名字规范化为 a-z0-9-、1–63、自动加时间后缀防重名;轮询到 ready。 + - `POST /api/bots/:id/instabox/snapshots/:snapId/restore`:`desiredState:"running"`,完成后开桌面(可调 `machines().ensureRunning`)。 + - `DELETE /api/bots/:id/instabox/snapshots/:snapId`:只允许删属于该智能体的快照。 + - 权限与现有云电脑接口一致(admin、同源);钥匙未配置返回明确错误;所有 调用带 Idempotency-Key(用 request 的 `idempotent: true`)。 +4. `InstaboxSnapshots.tsx`:在电脑面板里,仅当该智能体后端是 instabox 时显示:列表、「存一个快照」、恢复(二次确认,说明会冷启动、只保留磁盘)、删除(二次确认)。CRYSOUND 设计系统风格,手机 360/390 宽不溢出。`ComputerPanel.tsx` 里只加挂载点。 +5. 文案:本任务所有新文案中英文都加;另外预留 ①②③ 可能用到的键:`computer.instabox.keyMissing`(钥匙未配置 / key is not set)、`computer.instabox.starting`(云电脑开机中 / Starting the cloud computer)、`computer.instabox.suspended`(云电脑已休眠,用到时自动唤醒 / The cloud computer is asleep and wakes when needed)。i18n 测试要通过。 +6. 测试:路由用假服务覆盖列/存/恢复/删、越权删别的智能体快照被拒、钥匙未配置;前端选择器三选项、快照组件的空/有数据/确认流程;key-catalog 新项。 + +## 验收 +按「共同约定 · 测试」执行,前端改动另截 1280 宽和 390 宽两张图(设置页钥匙、后端选择、快照面板)放进任务文件夹;report.md 只写实际改过的文件,写明 `createInstaboxSnapshotRoutes` 确切签名(⑤ 照着接)。 + +--- + +# T-1239 云电脑后端:共同约定(4 个并行子任务都必须遵守) + +## 目标与范围(用户已定) +- 新增云电脑后端 `instabox`,与 Boat(box)、VPS(vps)并列,供单个智能体使用自己的云电脑。范围:Linux 桌面 + Android 模板,不含苹果。 +- 共用电脑(team computer / 部门桌面)、本地 VM 私有桌面、多屏都**不改**,仍走原来的路。 +- 所有机器用同一把 钥匙:配置 `instabox.apiKey`,环境变量 `INSTABOX_API_KEY` 覆盖;钥匙只在服务端,绝不进入机器、前端、日志或智能体上下文。 +- 本仓库是**公开仓库**:代码、测试、文档里不得出现内部域名、IP、邮箱、人名、真实钥匙。公共接口域名 `api.instabox.sh`、`connect.instabox.sh` 可以出现。 + +## 接口要点(实测) +- 基址 `https://api.instabox.sh`,请求头 `X-API-Key: `。 +- 生命周期调用(POST /v1/machines、PATCH、start/stop/suspend/resume/restore、POST snapshots、DELETE)**必须**带 `Idempotency-Key`;删机器另带 `X-Confirm-Delete: `。都返回 202 + 操作单 `{id,machineId,type,state,phase,error}`,用 `GET /v1/operations/{id}?wait=25s` 长轮询到 succeeded/failed。 +- 机器 state:creating、starting、running、stopping、stopped、suspending、suspended、resuming、deleting、deleted、error。 +- 创建:`{"name","templateId":"agent-browser"|"android","spec":{"vcpus":4,"memoryGiB":8},"autoSuspendAfterSeconds":600,"metadata":{...}}`。按名字找回机器:`GET /v1/machines`(按 name 过滤)。 +- 新建、冷启动、restore、从快照新建之后桌面不运行:必须 `POST /v1/machines/{id}/desktop {"action":"start","width":1280,"height":800}`。 +- exec:`POST /v1/machines/{id}/exec {"cmd"|"argv","envs","cwd","stdin","timeoutSeconds":1..600}` → `{stdout,stderr,exitCode,timedOut,truncated,...}`;非流式输出各 1 MiB 截断。默认没有 DISPLAY,桌面在 `:1`(Boat 是 :0)。后台任务用 `nohup setsid ... >log 2>&1 `,metadata 带 `{"app":"crybot","botId":...}`。 + +## 共享文件(各任务需要时原样创建,内容必须一字不差;已存在就不要改) +`server/instabox/machine.ts`: +```ts +/** cloud computer: the contract the four backend pieces share. */ +export type InstaboxTemplate = "linux" | "android"; +export type InstaboxMachineState = "creating" | "starting" | "running" | "stopping" | "stopped" | "suspending" | "suspended" | "resuming" | "deleting" | "deleted" | "error"; + +export interface InstaboxMachine { id: string; name: string; state: InstaboxMachineState; template: InstaboxTemplate } + +export interface InstaboxExecRequest { cmd?: string; argv?: string[]; envs?: Record; cwd?: string; stdin?: string; timeoutSeconds?: number } +export interface InstaboxExecResult { stdout: string; stderr: string; exitCode: number | null; timedOut: boolean; truncated: boolean } + +/** One authenticated API call. `idempotent: true` adds an Idempotency-Key; lifecycle calls need it. */ +export type InstaboxRequest = (method: string, path: string, opts?: { body?: unknown; raw?: Uint8Array; idempotent?: boolean; headers?: Record; query?: Record }) => Promise; + +export interface InstaboxMachines { + find(botId: string): Promise; + /** Create, resume or start the bot's machine as needed, then make sure its desktop runs. */ + ensureRunning(botId: string, opts?: { template?: InstaboxTemplate }): Promise; + suspend(botId: string): Promise; + remove(botId: string): Promise; + exec(machineId: string, req: InstaboxExecRequest): Promise; + readFile(machineId: string, path: string): Promise; + writeFile(machineId: string, path: string, data: Uint8Array, opts?: { mode?: string }): Promise; + /** Where the server connects for this machine's VNC (RFB, no password); headers carry the key and never leave the server. */ + vncUpstream(machineId: string): Promise<{ url: string; headers: Record }>; +} +``` +`shared/wire.ts:62` 改成(原行上改,不增行;文件正好 1000 行,多一行会挂行数门禁): +`export type CloudBackend = "box" | "vps" | "instabox";` + +## 行数门禁 +`scripts/testing/file-size-ratchet.test.ts`:登记文件不许变长,未登记文件不许超过 1000 行。`server/index.ts` 四个任务合计只剩约 110 行余量(由任务①统一占用),`ComputerPanel.tsx` 余量 25、`config.ts` 10、`store.ts` 17、`boat.ts` 1。新逻辑一律放 `server/instabox/` 下的新文件。 + +## 测试 +- 不连真实 。写 `server/testing/fake-instabox.ts` 风格的假服务(`createServer` 起本地 HTTP/WS,`vi.stubEnv` 或依赖注入指过去);各任务若都需要假服务,各自放在自己命名的文件里(如 `fake-instabox-power.ts`),避免同名冲突。 +- 本轮沙箱已放开,可监听端口:改动相关的测试全部跑过,涉及的 e2e 连跑 3 次。另跑 `pnpm exec tsc -p tsconfig.server.json`、前端有改动时跑前端 tsc,对改动文件跑 `oxlint --deny-warnings`。 +- 文案只加 `src/locales/zh.json` 和 `en.json`(且只有任务④加;其他任务需要文案时在报告里列出键名和中英文,由④统一加,代码里先用这些键)。 diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/key-environment-360.png b/docs/tasks/T-1200/T-1245-instabox-settings/key-environment-360.png new file mode 100644 index 00000000..317de4c2 Binary files /dev/null and b/docs/tasks/T-1200/T-1245-instabox-settings/key-environment-360.png differ diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/r2.md b/docs/tasks/T-1200/T-1245-instabox-settings/r2.md new file mode 100644 index 00000000..5f3789b8 --- /dev/null +++ b/docs/tasks/T-1200/T-1245-instabox-settings/r2.md @@ -0,0 +1,22 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1245 第 2 轮:存快照兼容操作单返回、i18n 补齐 pt-br、清理文档 + +原任务见本文件夹 brief.md(含共同约定),工作区里上一轮改动保留,在此基础上改。第 1 轮审核:需要返工;安全审查通过。 + +## 必改 +1. server/routes/instabox-snapshots.ts:109-110:`POST /v1/machines/{id}/snapshots` 按约定是生命周期调用,返回 202 + 操作单 `{id,machineId,type,state,phase,error}`,不是快照对象;现在把 `created` 的 `id` 当快照 id 去轮询 `GET /v1/snapshots/{id}`,接真实接口会 404。改成两种返回都兼容:返回体能认出是快照(有快照特有字段、无 type/phase 这类操作单字段)就直接用;是操作单就先等操作单完成(复用 ① 的 waitOperation/finishOperation 或同样的长轮询),再按本次生成的唯一名字在 `GET /v1/snapshots` 里找到快照,等到 ready。假服务 server/testing/fake-instabox-snapshots.ts 改成默认返回操作单(另保留一个快照对象形状的开关),两种形状各补一条测试。可联网时先看 公开接口文档确认真实返回,在 report.md 写明看到的结论或「未能确认」。 +2. i18n 测试 `src/lib/i18n.test.ts` 的 `activePackComplete` 要求 pt-br 包含全部英文键:本轮授权改 src/locales/pt-br.json,把新增的 20 个键补上葡萄牙语(巴西)翻译,与仓库已有做法一致。i18n.test.ts 整个文件要通过。 + +## 一起改 +3. docs/tasks/T-1200/T-1245-instabox-settings/verification.txt 里的沙箱绝对路径一律改成仓库相对路径。 +4. 未被代码用到的键 `keys.instabox.configured`:不是留给后续用的就删掉(en、zh、pt-br 同步)。 +5. report.md 在给 ⑤ 的说明里写清:存快照、恢复是在一个 HTTP 请求里同步等待(每段最长多少秒),⑤ 接线时需要注意前端/反向代理超时;saveConfig 与 config 广播未带 instabox 字段需要 ⑤ 接上(与上一轮已写的「尚未独立闭环」合并成一节)。 + +## 验收 +改动相关测试逐文件跑(instabox-snapshots.e2e 连跑 3 次、InstaboxSnapshots、CloudBackendPicker、key-catalog、KeysPage.dom、i18n.test、file-size-ratchet);`tsc -b`、`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`。report.md 追加第 2 轮一节,只写实际改过的文件。 diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/r3.md b/docs/tasks/T-1200/T-1245-instabox-settings/r3.md new file mode 100644 index 00000000..914157ce --- /dev/null +++ b/docs/tasks/T-1200/T-1245-instabox-settings/r3.md @@ -0,0 +1,17 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1245 第 3 轮:修 CI 里的 key-readback 端到端测试 + +原任务见本文件夹 brief.md、r2.md,工作区改动已提交、已合入最新 main。GitHub Actions 上 `scripts/testing/key-readback.e2e.test.ts` 的用例「saves every kind of credential, reads it back and shows it masked to its last four, then removes it」失败(:121):钥匙种类清单实际 27 项,测试期望 26 项——本任务新加的 钥匙没进这个测试。 + +## 必改 +1. 把 钥匙按其他钥匙同样的方式纳入 key-readback 端到端测试:期望清单加上它,并让它也走完「保存 → 读回 → 只显示末四位 → 删除」全流程(测试服务需要的假数据按现有写法补)。不要为了让测试过而把它从清单里排除。 +2. 顺带全仓搜一下其他按「全部钥匙种类」做断言的测试,同类遗漏一起补上。 + +## 验收 +`scripts/testing/key-readback.e2e.test.ts` 连跑 3 次通过;改动相关单测逐文件跑;`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`。report.md 追加第 3 轮一节(不要写 IP、内网地址、域名)。 diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/r4.md b/docs/tasks/T-1200/T-1245-instabox-settings/r4.md new file mode 100644 index 00000000..b69cb985 --- /dev/null +++ b/docs/tasks/T-1200/T-1245-instabox-settings/r4.md @@ -0,0 +1,17 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1245 第 4 轮:只修 CI 上两个分支独有的失败(合入最新 main 后出现) + +原任务见本文件夹 brief.md、r2.md、r3.md,工作区是已合入 origin/main 的最新分支(3e7c92de)。只做下面两条。 + +## 必改 +1. **钥匙原样返回(安全问题,最优先)**:server/routes/instabox-snapshots.e2e.test.ts:111 失败,`GET /api/config` 返回了 `instabox: { apiKey: "<原文>", last4: ... }`,期望只有 `{ configured, fromEnv }`。很可能是合入 main 时配置序列化/脱敏路径被 main 的改动绕开。找到 /api/config 的返回构造处,确保 钥匙任何情况下都不以原文出现在任何接口响应、日志、错误里(与其他供应商钥匙的脱敏方式一致),并检查 PUT/PATCH 配置接口的响应也不回显。对照 key-readback e2e 确认读回只给后四位掩码的口径与这里一致(哪个接口给 last4、哪个只给 configured/fromEnv,按 brief 原定口径,不要改测试去迁就实现)。 +2. **electron/diagnostics.test.mjs:29**:server/credential-env.ts 新增了 INSTABOX_API_KEY,electron 端的凭据环境列表(CREDENTIAL_ENV_NAMES 所在文件)没同步,诊断导出会漏脱敏。把 INSTABOX_API_KEY 加进 electron 的列表。 + +## 验收 +本地逐文件跑:server/routes/instabox-snapshots.e2e.test.ts、scripts/testing/key-readback.e2e.test.ts、electron/diagnostics.test.mjs、本任务其他改动相关测试;`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`。report.md 追加第 4 轮一节;verification.txt 重新生成(不写 IP、地址、域名、连接错误原文)。 diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/report.md b/docs/tasks/T-1200/T-1245-instabox-settings/report.md new file mode 100644 index 00000000..bb9fc909 --- /dev/null +++ b/docs/tasks/T-1200/T-1245-instabox-settings/report.md @@ -0,0 +1,102 @@ +改了什么 + +新增 钥匙目录项(环境变量来源显示为只读行)、三后端选择、快照路由/假服务/面板与确认流程、中英文文案;电脑面板只加两行挂载,配置路由净增 9 行,wire 保持 1000 行。实际改动文件与 `git status --short --untracked-files=all` 一致: + +```text +server/routes/config.ts +shared/wire.ts +src/components/CloudBackendPicker.test.ts +src/components/CloudBackendPicker.tsx +src/components/ComputerPanel.tsx +src/components/keys/KeysPage.dom.test.ts +src/components/keys/key-catalog.test.ts +src/components/keys/key-catalog.ts +src/locales/en.json +src/locales/zh.json +docs/tasks/T-1200/T-1245-instabox-settings/key-environment-360.png +docs/tasks/T-1200/T-1245-instabox-settings/report.md +docs/tasks/T-1200/T-1245-instabox-settings/ui-1280.png +docs/tasks/T-1200/T-1245-instabox-settings/ui-390.png +docs/tasks/T-1200/T-1245-instabox-settings/verification.txt +server/instabox/machine.ts +server/routes/instabox-snapshots.e2e.test.ts +server/routes/instabox-snapshots.ts +server/testing/fake-instabox-snapshots.ts +src/components/InstaboxSnapshots.test.tsx +src/components/InstaboxSnapshots.tsx +``` + +为什么 + +支持每个智能体的 磁盘快照,限制 admin/同源访问、拒绝跨智能体恢复/删除、全量调用使用 `idempotent: true`,恢复完成后调用 `ensureRunning(botId)` 开桌面。钥匙响应仅含 `{ configured, fromEnv }`,不含明文和尾号。 + +⑤ 接线的确切签名: + +```ts +export function createInstaboxSnapshotRoutes(deps: { machines(): InstaboxMachines | null; request(): InstaboxRequest | null; machineIdFor(botId: string): Promise; botExists(botId: string): boolean }): RouteHandler +``` + +**尚未独立闭环:**遵守原文件边界,未改 `server/index.ts`、`server/config.ts`、`server/store.ts`。①/⑤须注册路由,并在配置 schema、saveConfig 的 section 合并列表、加载/环境变量读取、全局 configStatus 及 config 广播接上 。隔离实测当前 `saveConfig({instabox:{apiKey:…}})` 会丢弃该字段,所以本分支不能宣称钥匙已可持久化;本任务路由已接收/校验保存与清除 patch,并拒绝覆盖 `INSTABOX_API_KEY`。此前范围扩展询问未收到确认,保留原范围。存快照和恢复都在单个 HTTP 请求里同步等待:快照对象形状最多等待 ready 180 秒;操作单形状最多等待操作单 180 秒、按唯一名称发现快照 180 秒、再等待 ready 180 秒;恢复最多等待操作单 180 秒,随后同步等待 `ensureRunning`。⑤ 接线时应让前端和反向代理超时覆盖这些等待。 + +测试命令与结果摘要 + +- 开工 依赖准备脚本 成功。`docs/verification/README.md` 缺失;验证全部使用隔离 HTTP 假服务/临时数据目录,无真实 调用。 +- 逐文件 `pnpm exec vitest run <文件> --maxWorkers=1`:20 个文件、242 项通过(去重计数),具体文件及命令见 [verification.txt](verification.txt)。快照路由 e2e 最终连续 3 次,各 11/11。 +- `node --experimental-strip-types `:Chromium 隔离组件页面,三后端切换、存快照、取消/确认恢复、确认删除连续 3 轮通过;环境变量钥匙无编辑按钮。1280/390/360 宽及确认框无横向溢出。[1280 截图](ui-1280.png)、[390 截图](ui-390.png)、[环境变量只读截图](key-environment-360.png)。 +- `pnpm exec tsc -p tsconfig.server.json`、`pnpm exec tsc -p tsconfig.json`、改动 TS/TSX 文件的 `pnpm exec oxlint --deny-warnings`、行数门禁、`git diff --check` 均通过。 +- `node scripts/generate-locale.mjs --check` 通过;`pnpm exec vitest run src/lib/i18n.test.ts --maxWorkers=1` 为 **38/39**:`activePackComplete` 写死要求 pt-br 覆盖全部英文键,新加的 20 键仅在用户授权的 en/zh 中,故此项未过;未修改其他语言或范围外测试。 +- 完整输出保存在 [verification.txt](verification.txt)。未提交 git。 + + +第 2 轮 + +改了什么 + +- `server/routes/instabox-snapshots.ts`、`server/routes/instabox-snapshots.e2e.test.ts`、`server/testing/fake-instabox-snapshots.ts` +- `src/locales/en.json`、`src/locales/zh.json`、`src/locales/pt-br.json` +- `docs/tasks/T-1200/T-1245-instabox-settings/verification.txt`、`docs/tasks/T-1200/T-1245-instabox-settings/report.md` + +为什么 + +创建快照现在兼容快照对象和生命周期操作单:操作单完成后按本次生成的唯一名称查找快照,再等待 ready;假服务默认返回操作单,并保留快照对象开关,两种形状均有测试。pt-br 补齐本轮新增的 20 个英文键,并同步删除未使用的 `keys.instabox.configured`。验证记录改为仓库相对路径。公开接口文档 `https://api.instabox.sh/v1/openapi.json` 当前将 `POST /v1/machines/{id}/snapshots` 的 201/202 响应描述为 `Snapshot`;实现仍兼容任务约定的操作单返回。 + +测试命令与结果摘要 + +- `pnpm exec vitest run server/routes/instabox-snapshots.e2e.test.ts --maxWorkers=1`:12/12 通过;最终验收连续运行 3 次。 +- `pnpm exec vitest run src/lib/i18n.test.ts --maxWorkers=1`:39/39 通过;`node scripts/generate-locale.mjs --check` 通过。 +- 其余验收测试、`tsc -b`、`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`、行数门禁和 `git diff --check` 的结果已追加到 `verification.txt`。未提交 git。 + + +第 3 轮 + +改了什么 + +将 纳入 27 项钥匙的保存、读回、末四位掩码和删除流程,补齐配置持久化、状态广播及前端状态转换;补充决策服务假响应,以及环境变量优先级、凭据隔离和末四位保留的同类测试覆盖。实际文件列表: + +```text +docs/tasks/T-1200/T-1245-instabox-settings/report.md +docs/tasks/T-1200/T-1245-instabox-settings/verification-r3.txt +scripts/testing/key-readback.e2e.test.ts +server/config.test.ts +server/config.ts +server/credential-env.ts +server/index.ts +server/routes/config.ts +src/components/keys/key-catalog.test.ts +src/components/keys/key-catalog.ts +src/state/config-status.ts +src/state/store.test.ts +src/state/store.tsx +``` + +为什么 + +仅补期望清单后,隔离测试仍在 读回处失败:配置未持久化,状态仅含 configured/fromEnv。为满足本轮末四位验收,接通最小读写链路并复用现有安全掩码;保存响应、读回及页面均断言不泄露完整钥匙,环境变量来源保持只读。全仓搜索还补上了“所有凭据环境变量优先”和“所有已保存钥匙保留末四位”的遗漏;桌面凭据槽及聊天凭据清单按各自实际支持范围保持断言。 + +测试命令与结果摘要 + +- 依赖准备脚本 成功;`docs/verification/README.md` 缺失,全部使用临时数据和隔离假服务验证。 +- `pnpm exec vitest run scripts/testing/key-readback.e2e.test.ts --maxWorkers=1`:最终连续 3 次通过,每次 2/2,包含全部 27 项钥匙。 +- `pnpm exec vitest run <文件> --maxWorkers=1`:相关 12 个回归文件逐文件运行,共 1047 项通过;逐条命令与完整输出见 [verification-r3.txt](verification-r3.txt)。 +- `pnpm exec tsc -p tsconfig.server.json`、`pnpm exec tsc -p tsconfig.json`、全部 11 个改动 TS/TSX 文件的 `pnpm exec oxlint --deny-warnings` 均通过;行数门禁通过。 +- 报告写完后 `git diff --check` 通过;文件列表与 `git status --short --untracked-files=all` 一致。未提交 git。 diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/ui-1280.png b/docs/tasks/T-1200/T-1245-instabox-settings/ui-1280.png new file mode 100644 index 00000000..e436ff11 Binary files /dev/null and b/docs/tasks/T-1200/T-1245-instabox-settings/ui-1280.png differ diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/ui-390.png b/docs/tasks/T-1200/T-1245-instabox-settings/ui-390.png new file mode 100644 index 00000000..361a8a61 Binary files /dev/null and b/docs/tasks/T-1200/T-1245-instabox-settings/ui-390.png differ diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/verification-r3.txt b/docs/tasks/T-1200/T-1245-instabox-settings/verification-r3.txt new file mode 100644 index 00000000..d452c739 --- /dev/null +++ b/docs/tasks/T-1200/T-1245-instabox-settings/verification-r3.txt @@ -0,0 +1,259 @@ +第 3 轮验证 +crybot-link-deps: exit 0,链接 73 项依赖。 +docs/verification/README.md 缺失;所有服务和数据均使用隔离 fixture。 + +仅补清单后的回归复现: + + RUN v4.1.11 . + + ❯ scripts/testing/key-readback.e2e.test.ts (2 tests | 1 failed) 6195ms + × saves every kind of credential, reads it back and shows it masked to its last four, then removes it 674ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL scripts/testing/key-readback.e2e.test.ts > saves every kind of credential, reads it back and shows it masked to its last four, then removes it +AssertionError: instabox: expected { configured: false, fromEnv: false } to deeply equal { configured: true, last4: 'b0ca' } + +- Expected ++ Received + + { +- "configured": true, +- "last4": "b0ca", ++ "configured": false, ++ "fromEnv": false, + } + + ❯ scripts/testing/key-readback.e2e.test.ts:137:75 + 135| + 136| const config = (await call("GET", "/api/config")).body; + 137| expect(savedState(entry, config as never), `${entry.id}${storage… + | ^ + 138| if (storage) expect(readFileSync(join(fixture.info.dataDir, "con… + 139| expect(JSON.stringify(config), entry.id).not.toContain(key); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 1 passed (2) + Start at 06:35:07 + Duration 10.12s (transform 2.55s, setup 1.32s, import 2.39s, tests 6.19s, environment 0ms) + + +$ pnpm exec vitest run scripts/testing/key-readback.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 06:38:17 + Duration 8.88s (transform 2.38s, setup 1.25s, import 1.91s, tests 5.58s, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run scripts/testing/key-readback.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 06:38:26 + Duration 8.93s (transform 2.30s, setup 1.20s, import 1.84s, tests 5.73s, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run scripts/testing/key-readback.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 06:38:36 + Duration 8.36s (transform 2.14s, setup 1.13s, import 1.72s, tests 5.35s, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run server/config.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 257 passed (257) + Start at 06:38:45 + Duration 2.37s (transform 960ms, setup 1.08s, import 158ms, tests 997ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run server/credential-env.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 2 passed (2) + Start at 06:38:48 + Duration 1.46s (transform 990ms, setup 1.07s, import 193ms, tests 55ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run server/routes/config-screens.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 7 passed (7) + Start at 06:38:50 + Duration 3.46s (transform 2.58s, setup 1.18s, import 2.05s, tests 42ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run server/key-hint.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 3 passed (3) + Start at 06:38:54 + Duration 1.23s (transform 860ms, setup 1.06s, import 17ms, tests 6ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run src/components/keys/key-catalog.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 16 passed (16) + Start at 06:38:55 + Duration 1.47s (transform 970ms, setup 1.15s, import 123ms, tests 21ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run src/components/keys/key-save.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 24 passed (24) + Start at 06:38:58 + Duration 1.80s (transform 1.26s, setup 1.03s, import 633ms, tests 9ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run src/components/keys/KeysPage.dom.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 24 passed (24) + Start at 06:39:00 + Duration 4.37s (transform 1.42s, setup 965ms, import 917ms, tests 1.68s, environment 661ms) + + +exit: 0 + +$ pnpm exec vitest run src/state/store.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 243 passed (243) + Start at 06:39:05 + Duration 2.64s (transform 1.32s, setup 1.03s, import 695ms, tests 596ms, environment 158ms) + + +exit: 0 + +$ pnpm exec vitest run src/components/CloudBackendPicker.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 8 passed (8) + Start at 06:39:08 + Duration 1.92s (transform 1.34s, setup 1.03s, import 740ms, tests 22ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run src/components/settings/settings-index.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 124 passed (124) + Start at 06:39:11 + Duration 1.75s (transform 1.20s, setup 947ms, import 626ms, tests 32ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 1 passed (1) + Start at 06:39:13 + Duration 1.27s (transform 817ms, setup 1.04s, import 12ms, tests 78ms, environment 0ms) + + +exit: 0 + +$ pnpm exec vitest run server/index.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 338 passed (338) + Start at 06:39:15 + Duration 164.59s (transform 1.49s, setup 1.03s, import 907ms, tests 162.51s, environment 0ms) + + +exit: 0 + +$ pnpm exec tsc -p tsconfig.server.json + +exit: 0 + +$ pnpm exec tsc -p tsconfig.json + +exit: 0 + +$ pnpm exec oxlint --deny-warnings scripts/testing/key-readback.e2e.test.ts server/config.test.ts server/config.ts server/credential-env.ts server/index.ts server/routes/config.ts src/components/keys/key-catalog.test.ts src/components/keys/key-catalog.ts src/state/config-status.ts src/state/store.test.ts src/state/store.tsx + +exit: 0 + +$ git diff --check +docs/tasks/T-1200/T-1245-instabox-settings/report.md:97: new blank line at EOF. + +exit: 2 + +报告完成后的最终核验 +$ git diff --check +exit: 0 +report.md 第 3 轮文件列表与 git status 一致:13 个文件。 diff --git a/docs/tasks/T-1200/T-1245-instabox-settings/verification.txt b/docs/tasks/T-1200/T-1245-instabox-settings/verification.txt new file mode 100644 index 00000000..9ec72988 --- /dev/null +++ b/docs/tasks/T-1200/T-1245-instabox-settings/verification.txt @@ -0,0 +1,685 @@ + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 9 passed (9) + Start at 04:30:29 + Duration 2.84s (transform 1.59s, setup 1.11s, import 980ms, tests 582ms, environment 0ms) + + + RUN v4.1.11 . + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Restore snapshot, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Restore snapshot, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Restore snapshot, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Restore snapshot, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Restore snapshot, supports cancel, then refreshes +In HTML,

cannot be a descendant of

. +This will cause a hydration error. + + + +

+
+

+

    + } confirmLabel="Restore sn..." pending={false} ...> +
    + +
    +
    + +
    +

    +>

    +>

    + ... + ... + +

    cannot contain a nested

    . +See this log for the ancestor stack trace. + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Restore snapshot, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Delete, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Delete, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Delete, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Delete, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + +stderr | src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Delete, supports cancel, then refreshes +The current testing environment is not configured to support act(...) + + ❯ src/components/InstaboxSnapshots.test.tsx (6 tests | 2 failed) 61ms + × requires confirmation for Restore snapshot, supports cancel, then refreshes 16ms + × requires confirmation for Delete, supports cancel, then refreshes 5ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Restore snapshot, supports cancel, then refreshes + FAIL src/components/InstaboxSnapshots.test.tsx > InstaBox snapshots > requires confirmation for Delete, supports cancel, then refreshes +AssertionError: the given combination of arguments (undefined and string) is invalid for this assertion. You can use an array, a map, an object, a set, a string, or a weakset instead of a string + ❯ src/components/InstaboxSnapshots.test.tsx:46:68 + 44| await click(label); + 45| expect(fixture.api).toHaveBeenCalledTimes(1); + 46| expect(document.querySelector('[role="dialog"]')?.textContent).toC… + | ^ + 47| await click("Cancel", document); + 48| expect(document.querySelector('[role="dialog"]')).toBeNull(); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯ + + + Test Files 1 failed (1) + Tests 2 failed | 4 passed (6) + Start at 04:31:03 + Duration 2.04s (transform 900ms, setup 1.03s, import 220ms, tests 61ms, environment 558ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 8 passed (8) + Start at 04:31:26 + Duration 1.72s (transform 1.17s, setup 915ms, import 648ms, tests 21ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 04:31:36 + Duration 1.11s (transform 684ms, setup 851ms, import 105ms, tests 21ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 6 passed (6) + Start at 04:31:57 + Duration 1.67s (transform 868ms, setup 996ms, import 196ms, tests 73ms, environment 263ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 7 passed (7) + Start at 04:33:03 + Duration 2.79s (transform 2.04s, setup 915ms, import 1.69s, tests 45ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 16 passed (16) + Start at 04:35:14 + Duration 1.58s (transform 1.01s, setup 1.21s, import 139ms, tests 28ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 13 passed (13) + Start at 04:35:16 + Duration 2.04s (transform 1.39s, setup 1.10s, import 736ms, tests 39ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 1 passed (1) + Start at 04:35:19 + Duration 2.47s (transform 1.57s, setup 1.10s, import 956ms, tests 44ms, environment 187ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 24 passed (24) + Start at 04:35:22 + Duration 1.99s (transform 1.40s, setup 1.10s, import 717ms, tests 8ms, environment 0ms) + + + RUN v4.1.11 . + + ❯ src/components/keys/KeysPage.dom.test.ts (23 tests | 1 failed) 1806ms + × filters rows live by name, purpose and section, and says so when nothing matches 50ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL src/components/keys/KeysPage.dom.test.ts > the keys page > filters rows live by name, purpose and section, and says so when nothing matches +AssertionError: expected [ 'box', 'instabox', 'vps', …(1) ] to deeply equal [ 'box', 'vps', 'onePassword' ] + +- Expected ++ Received + + [ + "box", ++ "instabox", + "vps", + "onePassword", + ] + + ❯ src/components/keys/KeysPage.dom.test.ts:160:25 + 158| expect(rowsShown()).toEqual(["fishAudio"]); + 159| type(search, "Computers and browser"); + 160| expect(rowsShown()).toEqual(["box", "vps", "onePassword"]); + | ^ + 161| type(search, "research"); + 162| expect(rowsShown()).toEqual(["treg"]); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 22 passed (23) + Start at 04:35:25 + Duration 4.11s (transform 1.48s, setup 1.09s, import 853ms, tests 1.81s, environment 204ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 24 passed (24) + Start at 04:35:59 + Duration 4.48s (transform 1.86s, setup 1.38s, import 928ms, tests 1.75s, environment 224ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 3 passed (3) + Start at 04:36:05 + Duration 1.42s (transform 883ms, setup 1.06s, import 140ms, tests 78ms, environment 0ms) + + + RUN v4.1.11 . + + ❯ src/lib/i18n.test.ts (39 tests | 1 failed) 5844ms + × is true only for a pack other than English that has every English key 7ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL src/lib/i18n.test.ts > activePackComplete > is true only for a pack other than English that has every English key +AssertionError: expected false to be true // Object-is equality + +- Expected ++ Received + +- true ++ false + + ❯ src/lib/i18n.test.ts:137:34 + 135| expect(activePackComplete()).toBe(false); + 136| setLocale("pt-br"); + 137| expect(activePackComplete()).toBe(true); + | ^ + 138| locales["zz"] = { "approval.held.native": "x" }; + 139| try { + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 38 passed (39) + Start at 04:36:06 + Duration 6.95s (transform 3.14s, setup 927ms, import 43ms, tests 5.84s, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 5 passed (5) + Start at 04:36:49 + Duration 1.45s (transform 1.03s, setup 1.22s, import 43ms, tests 7ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 7 passed (7) + Start at 04:36:51 + Duration 3.30s (transform 2.44s, setup 988ms, import 2.13s, tests 40ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 9 passed (9) + Start at 04:36:54 + Duration 2.84s (transform 1.55s, setup 807ms, import 1.25s, tests 516ms, environment 141ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 7 passed (7) + Start at 04:36:58 + Duration 2.92s (transform 1.65s, setup 808ms, import 1.34s, tests 514ms, environment 140ms) + + + RUN v4.1.11 . + +AggregateError: + at internalConnectMultiple (node:net:1492:18) + at afterConnectMultiple (node:net:2161:7) { + [errors]: [ + at createConnectionError (node:net:2124:14) + at afterConnectMultiple (node:net:2154:16) { + errno: -111, + syscall: 'connect', + address: '::1', + port: 3000 + }, + at createConnectionError (node:net:2124:14) + at afterConnectMultiple (node:net:2154:16) { + errno: -111, + syscall: 'connect', + port: 3000 + } + ] +} +AggregateError: + at internalConnectMultiple (node:net:1492:18) + at afterConnectMultiple (node:net:2161:7) { + [errors]: [ + at createConnectionError (node:net:2124:14) + at afterConnectMultiple (node:net:2154:16) { + errno: -111, + syscall: 'connect', + address: '::1', + port: 3000 + }, + at createConnectionError (node:net:2124:14) + at afterConnectMultiple (node:net:2154:16) { + errno: -111, + syscall: 'connect', + port: 3000 + } + ] +} +AggregateError: + at internalConnectMultiple (node:net:1492:18) + at afterConnectMultiple (node:net:2161:7) { + [errors]: [ + at createConnectionError (node:net:2124:14) + at afterConnectMultiple (node:net:2154:16) { + errno: -111, + syscall: 'connect', + address: '::1', + port: 3000 + }, + at createConnectionError (node:net:2124:14) + at afterConnectMultiple (node:net:2154:16) { + errno: -111, + syscall: 'connect', + port: 3000 + } + ] +} + + Test Files 1 passed (1) + Tests 5 passed (5) + Start at 04:37:01 + Duration 2.55s (transform 1.65s, setup 845ms, import 1.33s, tests 89ms, environment 156ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 12 passed (12) + Start at 04:37:04 + Duration 2.92s (transform 1.56s, setup 794ms, import 1.27s, tests 582ms, environment 152ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 29 passed (29) + Start at 04:37:08 + Duration 26.00s (transform 1.43s, setup 732ms, import 1.15s, tests 23.86s, environment 138ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 11 passed (11) + Start at 04:37:34 + Duration 3.56s (transform 1.50s, setup 777ms, import 1.20s, tests 1.32s, environment 138ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 43 passed (43) + Start at 04:37:38 + Duration 2.05s (transform 1.32s, setup 673ms, import 1.07s, tests 188ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 11 passed (11) + Start at 04:38:16 + Duration 2.82s (transform 1.65s, setup 791ms, import 1.31s, tests 600ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 11 passed (11) + Start at 04:38:20 + Duration 2.79s (transform 1.62s, setup 722ms, import 1.35s, tests 592ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 11 passed (11) + Start at 04:38:23 + Duration 2.90s (transform 1.71s, setup 814ms, import 1.37s, tests 595ms, environment 0ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 6 passed (6) + Start at 04:39:15 + Duration 3.99s (transform 2.19s, setup 2.38s, import 501ms, tests 158ms, environment 502ms) + + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 1 passed (1) + Start at 04:39:21 + Duration 2.71s (transform 1.70s, setup 2.23s, import 26ms, tests 252ms, environment 0ms) + + +COMMAND: pnpm exec tsc -p tsconfig.server.json +EXIT: 0 + +COMMAND: pnpm exec tsc -p tsconfig.json +EXIT: 0 + +COMMAND: pnpm exec oxlint --deny-warnings +EXIT: 0 + +COMMAND: node scripts/generate-locale.mjs --check +de.json: 37% (3965/10628) +es.json: 61% (6481/10628) +fr.json: 36% (3794/10628) +hi.json: 34% (3648/10628) +it.json: 67% (7100/10628) +ja.json: 76% (8069/10628) +ko.json: 73% (7754/10628) +pl.json: 68% (7242/10628) +pt-br.json: 100% (10608/10628) +ru.json: 69% (7294/10628) +tr.json: 56% (5985/10628) +uk.json: 38% (4069/10628) +vi.json: 56% (5985/10628) +zh-tw.json: 96% (10246/10628) +zh.json: 76% (8034/10628) +locale catalogs valid (16 languages, 10628 English strings) +EXIT: 0 + +COMMAND: node --experimental-strip-types +Browser E2E 1: three backends / save / restore confirmation / cancel / restore / delete PASS +Browser E2E 2: three backends / save / restore confirmation / cancel / restore / delete PASS +Browser E2E 3: three backends / save / restore confirmation / cancel / restore / delete PASS +Layout 1280px and restore dialog: no horizontal overflow +Layout 390px and restore dialog: no horizontal overflow +Layout 360px and restore dialog: no horizontal overflow +Environment key: read-only PASS +EXIT: 0 + +COMMAND: node --experimental-strip-types --input-type=module +Isolated real saveConfig check: instabox field persisted = false +Integration prerequisite: task 1/5 must add instabox to the configuration schema and saveConfig section merge list. +EXIT: 0 + +FINAL TEST LEDGER (every Vitest invocation uses: pnpm exec vitest run --maxWorkers=1) +server/routes/instabox-snapshots.e2e.test.ts: 11/11 PASS, three consecutive final runs +server/routes/config-screens.test.ts: 7/7 PASS +src/components/CloudBackendPicker.test.ts: 8/8 PASS +src/components/InstaboxSnapshots.test.tsx: 6/6 PASS +src/components/keys/key-catalog.test.ts: 16/16 PASS +src/components/keys/KeyRow.test.ts: 13/13 PASS +src/components/keys/KeyRow.dom.test.ts: 1/1 PASS +src/components/keys/key-save.test.ts: 24/24 PASS +src/components/keys/KeysPage.dom.test.ts: 24/24 PASS +src/components/ComputerPanel.i18n.test.ts: 3/3 PASS +src/components/ComputerPanel.test.ts: 5/5 PASS +src/components/ComputerPanel.browser.test.ts: 7/7 PASS +src/components/ComputerPanel.lazy.test.ts: 9/9 PASS +src/components/ComputerPanel.android.test.ts: 7/7 PASS +src/components/ComputerPanel.live.test.ts: 5/5 PASS (existing fixture logs connection refusals on localhost:3000) +src/components/ComputerPanel.focus.test.ts: 12/12 PASS +src/components/ComputerPanel.takeover.test.ts: 29/29 PASS +src/components/ComputerPanel.tabs.test.ts: 11/11 PASS +src/components/ComputerPanel.simple.test.ts: 43/43 PASS +scripts/testing/file-size-ratchet.test.ts: 1/1 PASS +src/lib/i18n.test.ts: 38/39 PASS; activePackComplete assumes pt-br contains every English key. The 20 new English keys are deliberately added only to en/zh under the task scope. +The missing docs/verification/README.md could not be read; all HTTP/browser checks used isolated local fake servers and temporary data directories. +No real InstaBox API or live user application was used. No git commit was created. + +第 2 轮验收(仓库根目录 `.`) + +COMMAND: pnpm exec vitest run server/routes/instabox-snapshots.e2e.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 12 passed (12). 连续第 1 次。 + +COMMAND: pnpm exec vitest run server/routes/instabox-snapshots.e2e.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 12 passed (12). 连续第 2 次。 + +COMMAND: pnpm exec vitest run server/routes/instabox-snapshots.e2e.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 12 passed (12). 连续第 3 次。 + +COMMAND: pnpm exec vitest run src/components/InstaboxSnapshots.test.tsx --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 6 passed (6). + +COMMAND: pnpm exec vitest run src/components/CloudBackendPicker.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 8 passed (8). + +COMMAND: pnpm exec vitest run src/components/keys/key-catalog.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 16 passed (16). + +COMMAND: pnpm exec vitest run src/components/keys/KeysPage.dom.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 24 passed (24). + +COMMAND: pnpm exec vitest run src/lib/i18n.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 39 passed (39). + +COMMAND: pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1 +RESULT: Test Files 1 passed; Tests 1 passed (1). + +COMMAND: pnpm exec tsc -b --pretty false +EXIT: 0 + +COMMAND: pnpm exec tsc -p tsconfig.server.json --pretty false +EXIT: 0 + +COMMAND: pnpm exec oxlint --deny-warnings server/routes/instabox-snapshots.e2e.test.ts server/routes/instabox-snapshots.ts server/testing/fake-instabox-snapshots.ts +EXIT: 0 + +COMMAND: node scripts/generate-locale.mjs --check +RESULT: locale catalogs valid (16 languages, 10627 English strings); pt-br 100% (10627/10627). + +COMMAND: git diff --check +EXIT: 0 + +PUBLIC API CHECK: InstaBox 公共 OpenAPI 文档 returned 200. Its `POST /v1/machines/{id}/snapshots` 201 and 202 responses are documented as `Snapshot`; the route also accepts the operation shape required by this task. + +FULL COMMAND: pnpm exec vitest run server/routes/instabox-snapshots.e2e.test.ts --maxWorkers=1 (run 1) + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 12 passed (12) + Start at 05:15:50 + Duration 3.20s (transform 1.93s, setup 877ms, import 1.56s, tests 622ms, environment 0ms) + + +FULL COMMAND: pnpm exec vitest run server/routes/instabox-snapshots.e2e.test.ts --maxWorkers=1 (run 2) + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 12 passed (12) + Start at 05:15:54 + Duration 3.22s (transform 1.96s, setup 896ms, import 1.59s, tests 607ms, environment 0ms) + + +FULL COMMAND: pnpm exec vitest run server/routes/instabox-snapshots.e2e.test.ts --maxWorkers=1 (run 3) + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 12 passed (12) + Start at 05:15:58 + Duration 3.32s (transform 2.04s, setup 864ms, import 1.72s, tests 613ms, environment 0ms) + + +FULL COMMAND: pnpm exec vitest run src/components/InstaboxSnapshots.test.tsx --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 6 passed (6) + Start at 05:16:02 + Duration 1.40s (transform 762ms, setup 848ms, import 190ms, tests 62ms, environment 151ms) + + +FULL COMMAND: pnpm exec vitest run src/components/CloudBackendPicker.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 8 passed (8) + Start at 05:16:04 + Duration 1.50s (transform 997ms, setup 832ms, import 508ms, tests 22ms, environment 0ms) + + +FULL COMMAND: pnpm exec vitest run src/components/keys/key-catalog.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 16 passed (16) + Start at 05:16:06 + Duration 1.22s (transform 775ms, setup 945ms, import 117ms, tests 19ms, environment 0ms) + + +FULL COMMAND: pnpm exec vitest run src/components/keys/KeysPage.dom.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 24 passed (24) + Start at 05:16:08 + Duration 3.64s (transform 1.29s, setup 885ms, import 821ms, tests 1.65s, environment 143ms) + + +FULL COMMAND: pnpm exec vitest run src/lib/i18n.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 39 passed (39) + Start at 05:16:12 + Duration 6.58s (transform 2.89s, setup 929ms, import 44ms, tests 5.48s, environment 0ms) + + +FULL COMMAND: pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 1 passed (1) + Start at 05:16:19 + Duration 1.16s (transform 702ms, setup 926ms, import 10ms, tests 89ms, environment 0ms) + + +FULL COMMAND: pnpm exec tsc -b --pretty false + +FULL COMMAND: pnpm exec tsc -p tsconfig.server.json --pretty false + +FULL COMMAND: pnpm exec oxlint --deny-warnings server/routes/instabox-snapshots.e2e.test.ts server/routes/instabox-snapshots.ts server/testing/fake-instabox-snapshots.ts + +FULL COMMAND: node scripts/generate-locale.mjs --check +de.json: 37% (3965/10627) +es.json: 61% (6481/10627) +fr.json: 36% (3794/10627) +hi.json: 34% (3648/10627) +it.json: 67% (7100/10627) +ja.json: 76% (8069/10627) +ko.json: 73% (7754/10627) +pl.json: 68% (7242/10627) +pt-br.json: 100% (10627/10627) +ru.json: 69% (7294/10627) +tr.json: 56% (5985/10627) +uk.json: 38% (4069/10627) +vi.json: 56% (5985/10627) +zh-tw.json: 96% (10246/10627) +zh.json: 76% (8033/10627) +locale catalogs valid (16 languages, 10627 English strings) + +FULL COMMAND: git diff --check + +FULL COMMAND: git status --short --untracked-files=all + M docs/tasks/T-1200/T-1245-instabox-settings/report.md + M docs/tasks/T-1200/T-1245-instabox-settings/verification.txt + M server/routes/instabox-snapshots.e2e.test.ts + M server/routes/instabox-snapshots.ts + M server/testing/fake-instabox-snapshots.ts + M src/locales/en.json + M src/locales/pt-br.json + M src/locales/zh.json diff --git a/electron/diagnostics.mjs b/electron/diagnostics.mjs index d05393a3..988275d8 100644 --- a/electron/diagnostics.mjs +++ b/electron/diagnostics.mjs @@ -21,6 +21,7 @@ export const CREDENTIAL_ENV_NAMES = [ "CRYBOT_OPENAI_API_KEY", "CRYBOT_OPENROUTER_API_KEY", "BOX_TOKEN", + "INSTABOX_API_KEY", "OPENCODE_API_KEY", "CRYBOT_TTS_KEY", "CRYBOT_FISH_AUDIO_API_KEY", diff --git a/scripts/public-scan/allow-domains.txt b/scripts/public-scan/allow-domains.txt index cf27b8dd..eea2f21d 100644 --- a/scripts/public-scan/allow-domains.txt +++ b/scripts/public-scan/allow-domains.txt @@ -1,4 +1,6 @@ # Public domains needed by open-source licenses and official documentation. +snapshots.save # 文案键名 computer.instabox.snapshots.save,不是域名。 +instabox.sh # InstaBox 云电脑公共 API(第三方公开服务)。 apple.com developer.apple.com swift.org diff --git a/scripts/testing/key-readback.e2e.test.ts b/scripts/testing/key-readback.e2e.test.ts index 6071060d..c8897800 100644 --- a/scripts/testing/key-readback.e2e.test.ts +++ b/scripts/testing/key-readback.e2e.test.ts @@ -23,6 +23,7 @@ vi.mock("@/state/store", async (original) => { const { KEY_CATALOG, savedState } = await import("@/components/keys/key-catalog"); const { KeyCatalogRow } = await import("@/components/keys/KeysPage"); const { setLocale } = await import("@/lib/i18n"); +const { configStatusFromFrame } = await import("@/state/store"); const ROOT = new URL("../..", import.meta.url); const ACCOUNT_ID = "0123456789abcdef0123456789abcdef"; @@ -81,6 +82,7 @@ beforeAll(async () => { } if (url.startsWith("/eleven/voices")) return reply(200, { voices: [] }); if (url.startsWith("/fish/model")) return reply(200, { items: [], total: 0 }); + if (url === "/jev/v1/systemone" || url === "/alpha/decisions") return reply(200, { answers: { answer: { type: "noul", noul: 0.9 } } }); return reply(404, { error: "not in the stand-in" }); }); await new Promise((resolve) => stub.listen(0, "127.0.0.1", resolve)); @@ -120,7 +122,7 @@ it("saves every kind of credential, reads it back and shows it masked to its las setLocale("en"); expect(saveds.map((entry) => entry.id)).toEqual([ "openai", "anthropic", "xai", "openrouter", "mistral", "cerebras", "groq", "greenference", "modelgo", "meta", "deepseek", "opencodeGo", "openaiCompat", - "liveKey", "elevenlabs", "geminiTts", "fishAudio", "box", "composio", "treg", "postiz", "jev", "openrouterHelper", "workersAi", "imageOpenai", "imageCustom", + "liveKey", "elevenlabs", "geminiTts", "fishAudio", "box", "instabox", "composio", "treg", "postiz", "jev", "openrouterHelper", "workersAi", "imageOpenai", "imageCustom", ]); for (const storage of ["", "?secretStorage=external"]) { for (const entry of saveds) { @@ -131,13 +133,14 @@ it("saves every kind of credential, reads it back and shows it masked to its las geminiModelKeys.length = 0; const saved = await call("PUT", `/api/config${storage}`, patch(key)); expect(saved.status, `${entry.id}${storage}: ${JSON.stringify(saved.body)}`).toBe(200); + expect(JSON.stringify(saved.body), entry.id).not.toContain(key); for (const sent of geminiModelKeys) expect(sent, `${entry.id}${storage} verification key`).toBe(key); const config = (await call("GET", "/api/config")).body; expect(savedState(entry, config as never), `${entry.id}${storage}`).toEqual({ configured: true, last4 }); if (storage) expect(readFileSync(join(fixture.info.dataDir, "config.json"), "utf8"), `${entry.id} config.json`).not.toContain(key); expect(JSON.stringify(config), entry.id).not.toContain(key); - view.config = config; + view.config = configStatusFromFrame(config as never) as unknown as Record; const html = renderToStaticMarkup(createElement(KeyCatalogRow, { entry })); expect(html, entry.id).toContain(`••••••••${last4}`); expect(html, entry.id).toMatch(/>(Connected|Saved) { describe("credential env preference", () => { const VARS = [ + "INSTABOX_API_KEY", "XAI_API_KEY", "CRYBOT_GROQ_API_KEY", "CRYBOT_META_API_KEY", @@ -1593,6 +1594,7 @@ describe("credential env preference", () => { JSON.stringify({ xai: { key: "file-xai", url: "https://api.example.test/v1" }, box: { token: "file-box" }, + instabox: { apiKey: "file-instabox" }, opencodeGo: { apiKey: "file-ocg" }, tts: { key: "file-tts", fishKey: "file-fish", voice: "narrator" }, imageGen: { key: "file-image" }, @@ -1600,6 +1602,7 @@ describe("credential env preference", () => { ); process.env.XAI_API_KEY = "env-xai"; process.env.BOX_TOKEN = "env-box"; + process.env.INSTABOX_API_KEY = " env-instabox "; process.env.OPENCODE_API_KEY = "env-ocg"; process.env.CRYBOT_TTS_KEY = "env-tts"; process.env.CRYBOT_FISH_AUDIO_API_KEY = "env-fish"; @@ -1607,11 +1610,25 @@ describe("credential env preference", () => { const cfg = loadConfig(); expect(cfg.xai).toEqual({ key: "env-xai", url: "https://api.example.test/v1" }); expect(cfg.box).toEqual({ token: "env-box" }); + expect(cfg.instabox).toEqual({ apiKey: "env-instabox" }); expect(cfg.opencodeGo).toEqual({ apiKey: "env-ocg" }); expect(cfg.tts).toEqual({ key: "env-tts", fishKey: "env-fish", voice: "narrator" }); expect(cfg.imageGen).toEqual({ key: "env-image" }); }); + it("persists and clears the InstaBox key without turning a saved key into an environment override", () => { + saveConfig({ instabox: { apiKey: " fixture-instabox-key " } }); + syncCredentialEnv({ instabox: { apiKey: "fixture-instabox-key" } }); + expect(process.env.INSTABOX_API_KEY).toBeUndefined(); + expect(loadConfig().instabox).toEqual({ apiKey: "fixture-instabox-key" }); + saveConfig({ language: "en" }); + expect(loadConfig().instabox).toEqual({ apiKey: "fixture-instabox-key" }); + process.env.INSTABOX_API_KEY = " "; + expect(loadConfig().instabox).toEqual({ apiKey: "fixture-instabox-key" }); + saveConfig({ instabox: { apiKey: "" } }); + expect(loadConfig().instabox).toEqual({ apiKey: "" }); + }); + it("uses a preset voice only when the person has not chosen one or another provider", () => { process.env.CRYBOT_TTS_DEFAULT_VOICE = " preset-voice "; expect(loadConfig().tts?.voice).toBe("preset-voice"); @@ -2026,6 +2043,7 @@ describe("workspace credential env strip", () => { it("covers in-process secrets and private app-state paths", () => { expect(WORKSPACE_CREDENTIAL_ENV).toContain("BOX_TOKEN"); + expect(WORKSPACE_CREDENTIAL_ENV).toContain("INSTABOX_API_KEY"); expect(WORKSPACE_CREDENTIAL_ENV).toContain("CRYBOT_TTS_KEY"); expect(WORKSPACE_CREDENTIAL_ENV).toContain("CRYBOT_CLOUD_BOAT_TOKEN"); expect(WORKSPACE_CREDENTIAL_ENV).toContain("CRYBOT_CLOUD_VOICE_TOKEN"); diff --git a/server/config.ts b/server/config.ts index 5222995e..a604f217 100644 --- a/server/config.ts +++ b/server/config.ts @@ -347,6 +347,7 @@ const appConfigSchema = z.object({ /** Composio project key; `userId`/`sessionId` reuse one Composio Session. */ composio: z.object({ apiKey: optionalText, userId: optionalText, sessionId: optionalText }).optional(), box: z.object({ token: optionalText }).optional(), + instabox: z.object({ apiKey: z.string().trim().max(8192) }).strict().optional(), vps: vpsConfigSchema.optional(), /** OpenCode key, plus `providerKeys` for its other providers by the env name OpenCode reads; both write-only and only for its child. */ opencodeGo: z.object({ apiKey: optionalText, providerKeys: z.record(z.string(), z.string()).optional() }).optional(), @@ -454,6 +455,7 @@ export interface AppConfig extends HelperConfig { composio?: { apiKey?: string; userId?: string; sessionId?: string }; /** Boat token (ascii.dev renamed Box to Boat); config key "box", env BOX_TOKEN. */ box?: { token?: string }; + instabox?: { apiKey?: string }; /** A named host from the user's SSH config. Authentication stays with SSH. */ vps?: { sshAlias?: string }; opencodeGo?: { apiKey?: string; providerKeys?: Record }; @@ -737,6 +739,7 @@ export function loadConfig(): AppConfig { if (process.env.COMPOSIO_API_KEY !== undefined) cfg.composio.apiKey = process.env.COMPOSIO_API_KEY; cfg.box = { ...cfg.box }; if (process.env.BOX_TOKEN !== undefined) cfg.box.token = process.env.BOX_TOKEN; + if (process.env.INSTABOX_API_KEY?.trim()) cfg.instabox = { apiKey: process.env.INSTABOX_API_KEY.trim() }; cfg.opencodeGo = { ...cfg.opencodeGo }; if (process.env.OPENCODE_API_KEY !== undefined) cfg.opencodeGo.apiKey = process.env.OPENCODE_API_KEY; cfg.tts = { ...cfg.tts }; @@ -894,7 +897,7 @@ export function saveConfig( const keepImageModels = keepKeysOutOfImageModels(disk, checkedPatch.imageGen); const storedProfiles = storedBrowserProfilesSchema.safeParse(disk.browserProfiles); if (storedProfiles.success) disk.browserProfiles = storedProfiles.data; - for (const key of ["xai", "anthropic", "mistral", "cerebras", "treg", "postiz", "groq", "greenference", "modelgo", "meta", "deepseek", "openai", "openrouter", "openaiCompat", "composio", "box", "opencodeGo", "tts", "decider", "imageGen", "live", "profile", "rooms", "mcp", "threads", "context", "memory", "localVm", "features", "budgets", "billing", "decisions", "loopGuard", "onboarding", "browserEngine", "newBots", "safetyFloor"] as const) { + for (const key of ["xai", "anthropic", "mistral", "cerebras", "treg", "postiz", "groq", "greenference", "modelgo", "meta", "deepseek", "openai", "openrouter", "openaiCompat", "composio", "box", "instabox", "opencodeGo", "tts", "decider", "imageGen", "live", "profile", "rooms", "mcp", "threads", "context", "memory", "localVm", "features", "budgets", "billing", "decisions", "loopGuard", "onboarding", "browserEngine", "newBots", "safetyFloor"] as const) { const section = checkedPatch[key]; if (!section) continue; const current = jsonObjectSchema.safeParse(disk[key]); diff --git a/server/credential-env.ts b/server/credential-env.ts index a2b5fc44..c4032535 100644 --- a/server/credential-env.ts +++ b/server/credential-env.ts @@ -20,6 +20,7 @@ export const WORKSPACE_CREDENTIAL_ENV = [ "CRYBOT_OPENAI_API_KEY", "CRYBOT_OPENROUTER_API_KEY", "BOX_TOKEN", + "INSTABOX_API_KEY", "OPENCODE_API_KEY", "CRYBOT_TTS_KEY", "CRYBOT_FISH_AUDIO_API_KEY", diff --git a/server/index.ts b/server/index.ts index a01c190e..10316c25 100644 --- a/server/index.ts +++ b/server/index.ts @@ -11738,6 +11738,7 @@ function configStatus() { }, box: providerLockEnabled() ? { configured: false } : { ...boat.describeBoatAccount(cfg), ...(boat.boatAccount(cfg)?.included ? {} : keyHint(cfg.box?.token)) }, vps: { configured: Boolean(vpsSshAlias(cfg)), sshAlias: vpsSshAlias(cfg) ?? "" }, + instabox: { ...keyStatus(cfg.instabox?.apiKey), fromEnv: !!process.env.INSTABOX_API_KEY?.trim() }, opencodeGo: { ...keyStatus(cfg.opencodeGo?.apiKey), providerKeys: Object.keys(openCodeProviderKeys(cfg)) }, tts: tts.describeVoice(cfg), decider: describeDecider(cfg), helpers: describeHelpers(cfg), diff --git a/server/routes/config-instabox.test.ts b/server/routes/config-instabox.test.ts new file mode 100644 index 00000000..57af0576 --- /dev/null +++ b/server/routes/config-instabox.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { loadConfig, saveConfig } from "../config.ts"; +import { keyStatus, withoutKeyHints } from "../key-hint.ts"; +import { createConfigRoutes, type ConfigRouteDeps } from "./config.ts"; +import type { RouteContext } from "./table.ts"; + +beforeEach(() => vi.stubEnv("INSTABOX_API_KEY", "")); +afterEach(() => vi.unstubAllEnvs()); + +function fixture(reported?: unknown) { + saveConfig({ instabox: { apiKey: "fixture-instabox-key-1234" } }); + const cfg = loadConfig(), broadcast = vi.fn(); + const handler = createConfigRoutes({ + cfg, store: { bots: [] }, hostedModels: false, cloudHome: false, + browserRuntime: { heldBy: () => false }, providerConfigBusy: { get: () => false, set: vi.fn() }, + computerProviderConfigTransitions: new Set(), providerOperationConflict: () => null, + providerConfigs: () => ({}), registry: { forgetSnapshots: vi.fn() }, lendingEnabled: () => true, + revokeEngineCapabilities: vi.fn(), broadcast, + configStatus: () => ({ instabox: reported ?? { ...keyStatus(cfg.instabox?.apiKey), fromEnv: false } }), + configForAccess: (status, auth) => auth.scopes.includes("admin") ? status : withoutKeyHints(status), + } as unknown as ConfigRouteDeps); + return { cfg, broadcast, request: async (method = "GET", body?: unknown, admin = true) => { + let response!: { status: number; body: Record }; + await handler({ req: {}, res: {}, url: new URL("http://fixture/api/config"), path: "/api/config", method, + auth: { kind: "loopback", scopes: admin ? ["admin", "client"] : ["client"] }, + readBody: async () => body, + json: (_res: unknown, status: number, value: unknown) => { response = { status, body: value as Record }; }, + } as unknown as RouteContext); + return response; + } }; +} + +it.each(["PUT", "PATCH"])("strips raw credentials from %s responses and broadcasts on save and clear", async (method) => { + const secret = "fixture-new-instabox-key-5678"; + const f = fixture({ apiKey: secret, last4: secret, extra: { secret } }); + expect((await f.request()).body).toEqual({ instabox: { configured: true, fromEnv: false } }); + for (const apiKey of [secret, ""]) { + const response = await f.request(method, { instabox: { apiKey } }); + expect(response.status).toBe(200); + expect(response.body).toEqual({ instabox: { configured: !!apiKey, fromEnv: false } }); + expect(loadConfig().instabox?.apiKey).toBe(apiKey); + expect(f.broadcast).toHaveBeenLastCalledWith({ kind: "config", ...response.body }); + expect(JSON.stringify(f.broadcast.mock.calls)).not.toContain(secret); + expect((await f.request()).body).toEqual(response.body); + } +}); + +it("preserves validated admin hints, strips client hints, and never hints a short key", async () => { + const f = fixture(); + expect((await f.request()).body.instabox).toEqual({ configured: true, fromEnv: false, last4: "1234" }); + expect((await f.request("GET", undefined, false)).body.instabox).toEqual({ configured: true, fromEnv: false }); + for (const method of ["PUT", "PATCH"]) { + expect((await f.request(method, { instabox: { apiKey: "fixture-new-instabox-key-5678" } })).body.instabox) + .toEqual({ configured: true, fromEnv: false, last4: "5678" }); + expect((await f.request(method, { instabox: { apiKey: "tiny" } })).body.instabox) + .toEqual({ configured: true, fromEnv: false }); + } +}); + +it("rejects stale or forged hints even if the reported status says configured", async () => { + for (const last4 of ["wrong-secret", "nope", "tiny"]) { + const f = fixture({ configured: true, fromEnv: false, last4 }); + expect((await f.request()).body.instabox).toEqual({ configured: true, fromEnv: false }); + f.cfg.instabox = { apiKey: "tiny" }; + expect((await f.request()).body.instabox).toEqual({ configured: true, fromEnv: false }); + } +}); + +it.each(["PUT", "PATCH"])("keeps environment overrides and invalid %s input out of error responses", async (method) => { + const f = fixture(), secret = "fixture-secret-must-not-escape"; + const invalid = await f.request(method, { instabox: { apiKey: secret, extra: secret } }); + expect(invalid.status).toBe(400); + expect(invalid.body).toEqual({ error: "Invalid InstaBox key", code: "instabox_key_invalid" }); + vi.stubEnv("INSTABOX_API_KEY", secret); + expect((await f.request()).body.instabox).toEqual({ configured: true, fromEnv: true }); + const refused = await f.request(method, { instabox: { apiKey: secret } }); + expect(refused.status).toBe(409); + expect(refused.body).toEqual({ error: "InstaBox key is provided by the environment", code: "instabox_key_env" }); + expect(f.broadcast).not.toHaveBeenCalled(); +}); diff --git a/server/routes/config.ts b/server/routes/config.ts index 42f2005a..5c9415cc 100644 --- a/server/routes/config.ts +++ b/server/routes/config.ts @@ -1,3 +1,4 @@ +import { z } from "zod"; import { localVmConfigSchema, localVmScreens } from "../local-vm-settings.ts"; import { liveSavePatch } from "../live-config.ts"; import { signInEnvRefusal } from "../sign-in-env.ts"; @@ -34,6 +35,7 @@ import { DECIDER_KEY_ERROR, deciderIncludedHere, deciderPatchKey, deciderSavePat import type { ProviderRegistry } from "../harness/registry.ts"; import { HOSTED_PROVIDER_SETTINGS_ERROR } from "../hosted-models.ts"; import { forgetKey } from "../key-rejections.ts"; +import { keyHint } from "../key-hint.ts"; import type { ComputerIdleTimer } from "../computer-idle.ts"; import { PROVIDER_KEY_KINDS } from "../provider-key-check.ts"; import type { SessionRegistry } from "../sessions.ts"; @@ -53,7 +55,7 @@ export interface BusyFlag { set(busy: boolean): void; } -export type RemoteComputerProvider = "box" | "vps"; +export type RemoteComputerProvider = "box" | "vps" | "instabox"; export type ModelSelectionCheck = { ok: true; selection: ModelSelection } | ({ ok: false; status: number } & ServerErrorBody); @@ -122,9 +124,17 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler { closeBrowser, browserEngineSwitched, sharedComputers, sharedComputerControl, hostedModels, cloudHome: CLOUD_HOME, sharedMembership, lendingEnabled, providerConfigs, localVmIdleMs, localVmIdles, localVmActiveThreads, localVmLifecycleBusy, localVmImageBusy, localVmModeChangeBusy, localVmModeChanging, providerConfigBusy, computerProviderConfigTransitions, managedBoatOwners, providerOperationConflict, - perBotLocalVmCountForModeChange, checkedModelSelection, policyModelRefusal, browserSessionSpec, configStatus, + perBotLocalVmCountForModeChange, checkedModelSelection, policyModelRefusal, browserSessionSpec, configForAccess, resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, ownProfile, ownHints, postiz, } = deps; + const configStatus = () => { + const status = deps.configStatus(), reported = status.instabox; + const fromEnv = !!process.env.INSTABOX_API_KEY?.trim(), key = process.env.INSTABOX_API_KEY?.trim() || cfg.instabox?.apiKey?.trim(); + const hint = keyHint(key); + const safeHint = reported && typeof reported === "object" && "configured" in reported && reported.configured === true + && "last4" in reported && reported.last4 === hint.last4 ? hint : {}; + return { ...status, instabox: { configured: !!key, fromEnv, ...safeHint } }; + }; return async ({ req, res, url, path, method, auth, json, readBody }) => { // API keys are never echoed back: booleans only. if (method === "GET" && path === "/api/config") { @@ -133,6 +143,11 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler { if ((method === "PUT" || method === "PATCH") && path === "/api/config") { const body = await readBody(req); if (hostedModels && ["instances", "anthropic", "openai", "openrouter", "openaiCompat", "xai", "mistral", "cerebras", "groq", "greenference", "modelgo", "meta", "opencodeGo"].some(key => Object.hasOwn(body, key))) return json(res, 403, { error: HOSTED_PROVIDER_SETTINGS_ERROR }); + if (Object.hasOwn(body, "instabox")) { + if (process.env.INSTABOX_API_KEY?.trim()) return json(res, 409, { error: "InstaBox key is provided by the environment", code: "instabox_key_env" }); + const key = z.object({ apiKey: z.string().trim().max(8192) }).strict().safeParse(body.instabox); + if (!key.success) return json(res, 400, { error: "Invalid InstaBox key", code: "instabox_key_invalid" }); + } const patch = parseConfigPatchForPerson(body); if (patch.localVm) localVmConfigSchema.parse({ ...cfg.localVm, ...patch.localVm }); if (patch.profile && ownProfile) { @@ -263,7 +278,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler { const changingVpsAlias = patch.vps !== undefined && nextVpsAlias !== currentVpsAlias; const transitioningProviders: RemoteComputerProvider[] = [ ...(changingBoatToken ? ["box" as const] : []), - ...(changingVpsAlias ? ["vps" as const] : []), + ...(changingVpsAlias ? ["vps" as const] : []), ...(patch.instabox ? ["instabox" as const] : []), ]; providerConfigBusy.set(true); const nextVmConfig = { ...cfg, localVm: { ...cfg.localVm, ...patch.localVm } }; diff --git a/server/routes/instabox-snapshots.e2e.test.ts b/server/routes/instabox-snapshots.e2e.test.ts new file mode 100644 index 00000000..fcbba34f --- /dev/null +++ b/server/routes/instabox-snapshots.e2e.test.ts @@ -0,0 +1,165 @@ +import { createServer, type Server } from "node:http"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { InstaboxMachines } from "../instabox/machine.ts"; +import { json, readBody } from "../harness/http.ts"; +import { fakeInstaboxSnapshots } from "../testing/fake-instabox-snapshots.ts"; +import { createInstaboxSnapshotRoutes } from "./instabox-snapshots.ts"; +import { createConfigRoutes, type ConfigRouteDeps } from "./config.ts"; +import { PASS } from "./table.ts"; + +const botId = "bot-snapshots-one"; +const basePath = `/api/bots/${botId}/instabox/snapshots`; +let fake: Awaited>; +let server: Server; +let base: string; +let configured = true; +let machineId: string | null = "machine-one"; +const ensureRunning = vi.fn(async () => ({ id: "machine-one", name: "fixture", state: "running" as const, template: "linux" as const })); + +beforeEach(async () => { + vi.stubEnv("INSTABOX_API_KEY", ""); + configured = true; + machineId = "machine-one"; + ensureRunning.mockClear(); + fake = await fakeInstaboxSnapshots(); + const route = createInstaboxSnapshotRoutes({ + request: () => configured ? fake.request : null, + machines: () => configured ? { ensureRunning } as unknown as InstaboxMachines : null, + machineIdFor: async () => machineId, + botExists: (id) => id === botId, + }); + const configRoute = createConfigRoutes({ cfg: { instabox: { apiKey: "fixture-only-key" } }, configStatus: () => ({ instabox: { apiKey: "never-return-this", last4: "this" } }), configForAccess: (status: unknown) => status } as unknown as ConfigRouteDeps); + server = createServer(async (req, res) => { + const url = new URL(req.url!, base); + const result = await (url.pathname === "/api/config" ? configRoute : route)({ req, res, url, path: url.pathname, method: req.method!, json, readBody, + auth: { kind: "loopback", scopes: req.headers["x-fixture-role"] === "client" ? ["client"] : ["admin", "client"] } }); + if (result === PASS) json(res, 404, { error: "no route" }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No fixture address"); + base = `http://127.0.0.1:${address.port}`; +}); +afterEach(async () => { + await new Promise((resolve, reject) => { server.close((error) => error ? reject(error) : resolve()); server.closeAllConnections(); }); + await fake.close(); + vi.unstubAllEnvs(); +}); + +const send = (path = basePath, method = "GET", body?: unknown, headers?: Record) => fetch(base + path, { + method, headers: { origin: base, "content-type": "application/json", ...headers }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), +}); +const ownSnapshot = () => fake.snapshots.set("own", { id: "own", name: "crybot-bot-snapshot-backup", state: "ready" }); + +describe("isolated InstaBox snapshot HTTP routes", () => { + it("lists only owned snapshots by metadata or prefix and never relays metadata", async () => { + ownSnapshot(); + fake.snapshots.set("meta", { id: "meta", name: "backup", state: "ready", metadata: { app: "crybot", botId } }); + fake.snapshots.set("other", { id: "other", name: "crybot-bot-snapshot-spoof", state: "ready", metadata: { botId: "other-bot" } }); + const response = await send(); + expect(response.status).toBe(200); + const body = await response.json() as { snapshots: Array<{ id: string }> }; + expect(body.snapshots.map((s: { id: string }) => s.id)).toEqual(["own", "meta"]); + expect(JSON.stringify(body)).not.toContain("metadata"); + expect(response.headers.get("cache-control")).toContain("no-store"); + }); + + it("saves normalized unique names, waits for ready, restores then starts the desktop, and deletes", async () => { + const ids: string[] = []; + const names: string[] = []; + for (let n = 0; n < 2; n++) { + const response = await send(basePath, "POST", { name: "HELLO 世界 !!! ".repeat(10) }); + expect(response.status).toBe(201); + const { snapshot } = await response.json() as { snapshot: { id: string; name: string; state: string } }; + ids.push(snapshot.id); names.push(snapshot.name); + expect(snapshot.state).toBe("ready"); + expect(snapshot.name).toMatch(/^[a-z0-9-]{1,63}$/); + expect(snapshot.name.startsWith("crybot-bot-snapshot-")).toBe(true); + } + expect(names[0]).not.toBe(names[1]); + expect((await send(`${basePath}/${ids[0]}/restore`, "POST")).status).toBe(200); + expect(ensureRunning).toHaveBeenCalledWith(botId); + const restore = fake.calls.find((call) => call.path.endsWith("/restore")); + expect(restore?.body).toEqual({ snapshotId: ids[0], desiredState: "running" }); + expect(fake.calls.some((call) => call.path.startsWith("/v1/operations/"))).toBe(true); + expect((await send(`${basePath}/${ids[0]}`, "DELETE")).status).toBe(200); + expect(fake.snapshots.has(ids[0]!)).toBe(false); + expect(fake.calls.every((call) => !!call.idempotency)).toBe(true); + }); + + it("accepts a snapshot object when the create endpoint returns one", async () => { + fake.setCreateResponse("snapshot"); + const response = await send(basePath, "POST", { name: "direct-shape" }); + expect(response.status).toBe(201); + const { snapshot } = await response.json() as { snapshot: { id: string; name: string; state: string } }; + expect(snapshot.name).toContain("direct-shape"); + expect(snapshot.state).toBe("ready"); + expect(fake.calls.some((call) => call.path.startsWith("/v1/operations/"))).toBe(false); + }); + + it.each(["DELETE", "POST"])("refuses another bot's snapshot before %s", async (method) => { + fake.snapshots.set("other", { id: "other", name: "crybot-other-bot-backup", state: "ready", metadata: { botId: "other-bot" } }); + const response = await send(`${basePath}/other${method === "POST" ? "/restore" : ""}`, method); + expect(response.status).toBe(403); + expect(fake.calls).toHaveLength(1); + expect(fake.snapshots.has("other")).toBe(true); + expect(ensureRunning).not.toHaveBeenCalled(); + }); + + it("returns only configured/source flags for the shared key, including environment overrides", async () => { + expect(await (await send("/api/config")).json()).toEqual({ instabox: { configured: true, fromEnv: false } }); + vi.stubEnv("INSTABOX_API_KEY", "fixture-environment-key"); + expect(await (await send("/api/config")).json()).toEqual({ instabox: { configured: true, fromEnv: true } }); + for (const apiKey of ["", "replacement-fixture"]) { + const response = await send("/api/config", "PUT", { instabox: { apiKey } }); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ code: "instabox_key_env" }); + } + }); + + it("rejects malformed InstaBox key patches before attempting to save", async () => { + for (const instabox of [null, { apiKey: 2 }, { apiKey: "fixture", unexpected: true }]) { + expect((await send("/api/config", "PUT", { instabox })).status).toBe(400); + } + }); + + it("rejects a missing key clearly without provider calls", async () => { + configured = false; + const response = await send(); + expect(response.status).toBe(503); + expect(await response.json()).toMatchObject({ code: "instabox_key_missing" }); + expect(fake.calls).toHaveLength(0); + }); + + it("requires admin and same origin even for reads", async () => { + expect((await send(basePath, "GET", undefined, { "x-fixture-role": "client" })).status).toBe(403); + expect((await send(basePath, "POST", {}, { origin: "https://example.org" })).status).toBe(403); + expect(fake.calls).toHaveLength(0); + }); + + it("rejects unknown bots, invalid names and absent machines", async () => { + expect((await send("/api/bots/unknown/instabox/snapshots")).status).toBe(404); + expect((await send(basePath, "POST", { name: 5 })).status).toBe(400); + machineId = null; + expect((await send(basePath, "POST", {})).status).toBe(409); + expect(fake.calls).toHaveLength(0); + }); + + it("does not expose provider errors and unlocks for retry", async () => { + fake.failNext(); + const response = await send(basePath, "POST", {}); + expect(response.status).toBe(502); + expect(await response.text()).not.toContain("sensitive-upstream-detail"); + expect((await send(basePath, "POST", {})).status).toBe(201); + }); + + it("reports failed snapshots and restore operations without starting the desktop", async () => { + fake.failSnapshot(); + expect((await send(basePath, "POST", {})).status).toBe(502); + ownSnapshot(); + fake.failOperation(); + expect((await send(`${basePath}/own/restore`, "POST")).status).toBe(502); + expect(ensureRunning).not.toHaveBeenCalled(); + }); +}); diff --git a/server/routes/instabox-snapshots.ts b/server/routes/instabox-snapshots.ts new file mode 100644 index 00000000..70f7c184 --- /dev/null +++ b/server/routes/instabox-snapshots.ts @@ -0,0 +1,162 @@ +import { randomUUID } from "node:crypto"; +import { setTimeout as delay } from "node:timers/promises"; +import { z } from "zod"; +import type { InstaboxMachines, InstaboxRequest } from "../instabox/machine.ts"; +import { isSameOrigin } from "../request-auth.ts"; +import { PASS, type RouteHandler } from "./table.ts"; + +const snapshotSchema = z.object({ + id: z.string().min(1), name: z.string(), state: z.string().optional(), status: z.string().optional(), + metadata: z.object({ app: z.string().optional(), botId: z.string().optional() }).optional(), +}).refine((snapshot) => snapshot.state !== undefined || snapshot.status !== undefined).transform((snapshot) => ({ ...snapshot, state: snapshot.state ?? snapshot.status! })); +type Snapshot = z.infer; +const createSchema = z.object({ name: z.string().max(200).optional() }); +const operationSchema = z.object({ id: z.string().min(1), state: z.string() }); +const snapshotListSchema = z.union([z.array(snapshotSchema), z.object({ snapshots: z.array(snapshotSchema), nextCursor: z.string().nullish() })]); +const prefixFor = (botId: string) => `crybot-${botId.slice(0, 12).toLowerCase()}-`; + +function belongsTo(snapshot: Snapshot, botId: string): boolean { + if (snapshot.metadata?.botId !== undefined) { + return snapshot.metadata.botId === botId && (!snapshot.metadata.app || snapshot.metadata.app === "crybot"); + } + return (!snapshot.metadata?.app || snapshot.metadata.app === "crybot") && snapshot.name.startsWith(prefixFor(botId)); +} + +function snapshotName(botId: string, name = "snapshot"): string { + const prefix = prefixFor(botId); + const suffix = `-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`; + const label = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "snapshot"; + return prefix + label.slice(0, 63 - prefix.length - suffix.length).replace(/-+$/, "") + suffix; +} + +class SnapshotError extends Error { + readonly status: number; + readonly code: string; + constructor(status: number, code: string) { super(code); this.status = status; this.code = code; } +} + +async function call(request: InstaboxRequest, method: string, path: string, body?: unknown, query?: Record): Promise { + const response = await request(method, path, { body, query, idempotent: true }); + if (!response.ok) throw new SnapshotError(response.status === 404 ? 404 : 502, "upstream"); + return response; +} + +async function readySnapshot(request: InstaboxRequest, id: string): Promise { + const deadline = Date.now() + 180_000; + while (Date.now() < deadline) { + const snapshot = snapshotSchema.parse(await (await call(request, "GET", `/v1/snapshots/${encodeURIComponent(id)}`)).json()); + if (snapshot.state === "ready") return snapshot; + if (["failed", "error", "deleted"].includes(snapshot.state)) throw new SnapshotError(502, "failed"); + await delay(500); + } + throw new SnapshotError(504, "timeout"); +} + +async function listSnapshots(request: InstaboxRequest): Promise { + const snapshots: Snapshot[] = []; + let cursor: string | undefined; + const seen = new Set(); + do { + const response = await call(request, "GET", "/v1/snapshots", undefined, cursor ? { cursor } : undefined); + const page = snapshotListSchema.parse(await response.json()); + snapshots.push(...(Array.isArray(page) ? page : page.snapshots)); + cursor = Array.isArray(page) ? undefined : page.nextCursor || undefined; + if (cursor && (seen.has(cursor) || seen.size >= 100)) throw new SnapshotError(502, "upstream"); + if (cursor) seen.add(cursor); + } while (cursor); + return snapshots; +} + +async function findSnapshotByName(request: InstaboxRequest, name: string): Promise { + const deadline = Date.now() + 180_000; + while (Date.now() < deadline) { + const snapshot = (await listSnapshots(request)).find((candidate) => candidate.name === name); + if (snapshot) return snapshot; + await delay(500); + } + throw new SnapshotError(504, "timeout"); +} + +async function finishOperation(request: InstaboxRequest, response: Response): Promise { + if (response.status === 204) return; + await waitOperation(request, await response.json()); +} + +async function waitOperation(request: InstaboxRequest, initial: unknown): Promise { + let operation = operationSchema.parse(initial); + const deadline = Date.now() + 180_000; + while (operation.state !== "succeeded") { + if (["failed", "cancelled", "canceled"].includes(operation.state)) throw new SnapshotError(502, "failed"); + if (Date.now() >= deadline) throw new SnapshotError(504, "timeout"); + const next = await call(request, "GET", `/v1/operations/${encodeURIComponent(operation.id)}`, undefined, { wait: "25s" }); + operation = operationSchema.parse(await next.json()); + if (operation.state !== "succeeded") await delay(500); + } +} + +export function createInstaboxSnapshotRoutes(deps: { machines(): InstaboxMachines | null; request(): InstaboxRequest | null; machineIdFor(botId: string): Promise; botExists(botId: string): boolean }): RouteHandler { + const busy = new Set(); + return async ({ req, res, path, method, auth, json, readBody }) => { + const match = /^\/api\/bots\/([\w-]+)\/instabox\/snapshots(?:\/([\w-]+)(\/restore)?)?$/.exec(path); + if (!match) return PASS; + const botId = match[1]!, snapshotId = match[2], restore = match[3]; + const listing = !snapshotId && method === "GET"; + const saving = !snapshotId && method === "POST"; + const restoring = !!snapshotId && !!restore && method === "POST"; + const deleting = !!snapshotId && !restore && method === "DELETE"; + if (!listing && !saving && !restoring && !deleting) return PASS; + if (!auth.scopes.includes("admin") || !isSameOrigin(req)) return json(res, 403, { error: "Forbidden", code: "forbidden" }); + if (!deps.botExists(botId)) return json(res, 404, { error: "Bot not found", code: "bot_missing" }); + const request = deps.request(), machines = deps.machines(); + if (!request || !machines) return json(res, 503, { error: "InstaBox key is not set", code: "instabox_key_missing" }); + if (!listing && busy.has(botId)) return json(res, 409, { error: "Snapshot operation in progress", code: "instabox_snapshot_busy" }); + res.setHeader("cache-control", "private, no-store"); + if (!listing) busy.add(botId); + try { + if (listing) { + const snapshots = await listSnapshots(request); + return json(res, 200, { snapshots: snapshots.filter((snapshot) => belongsTo(snapshot, botId)).map(({ id, name, state }) => ({ id, name, state })) }); + } + if (saving) { + if (!String(req.headers["content-type"] ?? "").startsWith("application/json")) throw new SnapshotError(415, "invalid"); + const parsed = createSchema.safeParse(await readBody(req).catch(() => { throw new SnapshotError(400, "invalid"); })); + if (!parsed.success) throw new SnapshotError(400, "invalid"); + const machineId = await deps.machineIdFor(botId); + if (!machineId) throw new SnapshotError(409, "machine_missing"); + const name = snapshotName(botId, parsed.data.name); + const response = await call(request, "POST", `/v1/machines/${encodeURIComponent(machineId)}/snapshots`, { + name, description: `Cry Bot snapshot for ${botId}`, + }); + const createdPayload: unknown = await response.json(); + const isOperation = typeof createdPayload === "object" && createdPayload !== null && ("type" in createdPayload || "phase" in createdPayload || "machineId" in createdPayload); + let created: Snapshot; + if (isOperation) { + await waitOperation(request, createdPayload); + created = await findSnapshotByName(request, name); + } else { + created = snapshotSchema.parse(createdPayload); + } + const { id, name: readyName, state } = await readySnapshot(request, created.id); + return json(res, 201, { snapshot: { id, name: readyName, state } }); + } + const response = await call(request, "GET", `/v1/snapshots/${encodeURIComponent(snapshotId!)}`); + const snapshot = snapshotSchema.parse(await response.json()); + if (!belongsTo(snapshot, botId)) throw new SnapshotError(403, "ownership"); + if (restoring) { + if (snapshot.state !== "ready") throw new SnapshotError(409, "not_ready"); + const machineId = await deps.machineIdFor(botId); + if (!machineId) throw new SnapshotError(409, "machine_missing"); + await finishOperation(request, await call(request, "POST", `/v1/machines/${encodeURIComponent(machineId)}/restore`, { snapshotId, desiredState: "running" })); + await machines.ensureRunning(botId); + } else { + await finishOperation(request, await call(request, "DELETE", `/v1/snapshots/${encodeURIComponent(snapshotId!)}`)); + } + return json(res, 200, { ok: true }); + } catch (error) { + const known = error instanceof SnapshotError; + return json(res, known ? error.status : 502, { error: "InstaBox snapshot request failed", code: `instabox_snapshot_${known ? error.code : "upstream"}` }); + } finally { + if (!listing) busy.delete(botId); + } + }; +} diff --git a/server/testing/fake-instabox-snapshots.ts b/server/testing/fake-instabox-snapshots.ts new file mode 100644 index 00000000..3fa1efa9 --- /dev/null +++ b/server/testing/fake-instabox-snapshots.ts @@ -0,0 +1,70 @@ +import { createServer } from "node:http"; +import { randomUUID } from "node:crypto"; +import { json, readBody } from "../harness/http.ts"; +import type { InstaboxRequest } from "../instabox/machine.ts"; + +export interface FakeSnapshot { id: string; name: string; state: string; metadata?: { app?: string; botId?: string } } +type CreateResponseShape = "operation" | "snapshot"; + +export async function fakeInstaboxSnapshots(options: { createResponse?: CreateResponseShape } = {}) { + const snapshots = new Map(); + const calls: Array<{ method: string; path: string; body: unknown; idempotency: string | undefined }> = []; + const operations = new Map(); + let failNext = false; + let snapshotFails = false; + let operationFails = false; + let createResponse = options.createResponse ?? "operation"; + const server = createServer(async (req, res) => { + const url = new URL(req.url!, "http://localhost"); + const body = await readBody(req); + const method = req.method!; + const idempotency = req.headers["idempotency-key"] as string | undefined; + calls.push({ method, path: url.pathname, body, idempotency }); + if (!idempotency) return json(res, 400, { error: "Idempotency-Key required" }); + if (failNext) { failNext = false; return json(res, 500, { error: "sensitive-upstream-detail" }); } + if (url.pathname === "/v1/snapshots") return json(res, 200, { snapshots: [...snapshots.values()] }); + const id = url.pathname.split("/").at(-1)!; + if (method === "POST" && url.pathname.endsWith("/snapshots")) { + const snapshot = { id: randomUUID(), name: body.name, state: "creating" }; + snapshots.set(snapshot.id, snapshot); + if (createResponse === "snapshot") return json(res, 202, snapshot); + const operation = { id: randomUUID(), machineId: "machine-one", type: "create", state: "pending", phase: "snapshotting", error: null }; + operations.set(operation.id, operation); + return json(res, 202, operation); + } + if (method === "GET" && url.pathname.startsWith("/v1/snapshots/")) { + const snapshot = snapshots.get(id); + if (!snapshot) return json(res, 404, { error: "not found" }); + if (snapshot.state === "creating") snapshot.state = snapshotFails ? "failed" : "ready"; + return json(res, 200, snapshot); + } + if (method === "DELETE" || (method === "POST" && url.pathname.endsWith("/restore"))) { + if (method === "DELETE") snapshots.delete(id); + const operation = { id: randomUUID(), state: "pending" }; + operations.set(operation.id, operation); + return json(res, 202, operation); + } + if (method === "GET" && url.pathname.startsWith("/v1/operations/")) { + const operation = operations.get(id); + return json(res, 200, { ...operation, state: operationFails ? "failed" : "succeeded" }); + } + return json(res, 404, { error: "unexpected request" }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No fixture address"); + const base = `http://127.0.0.1:${address.port}`; + const request: InstaboxRequest = (method, path, opts) => { + const url = new URL(path, base); + for (const [key, value] of Object.entries(opts?.query ?? {})) url.searchParams.set(key, value); + return fetch(url, { method, headers: { "content-type": "application/json", ...(opts?.idempotent ? { "Idempotency-Key": randomUUID() } : {}) }, + ...(opts?.body === undefined ? {} : { body: JSON.stringify(opts.body) }) }); + }; + return { request, calls, snapshots, + setCreateResponse: (shape: CreateResponseShape) => { createResponse = shape; }, + failNext: () => { failNext = true; }, + failSnapshot: () => { snapshotFails = true; }, + failOperation: () => { operationFails = true; }, + close: () => new Promise((resolve, reject) => { server.close((error) => error ? reject(error) : resolve()); server.closeAllConnections(); }), + }; +} diff --git a/src/components/CloudBackendPicker.test.ts b/src/components/CloudBackendPicker.test.ts index 2ce9a411..b9ffeb7d 100644 --- a/src/components/CloudBackendPicker.test.ts +++ b/src/components/CloudBackendPicker.test.ts @@ -11,7 +11,7 @@ vi.mock("@/state/store", async (importOriginal) => { }); const { CloudBackendPicker } = await import("./CloudBackendPicker"); -const picker = (value: "box" | "vps" = "box") => renderToStaticMarkup(createElement(CloudBackendPicker, { value, onChange: () => {} })); +const picker = (value: "box" | "vps" | "instabox" = "box") => renderToStaticMarkup(createElement(CloudBackendPicker, { value, onChange: () => {} })); describe("CloudBackendPicker", () => { afterEach(() => { fixture.config = null; }); @@ -31,9 +31,10 @@ describe("CloudBackendPicker", () => { expect(picker("vps")).toBe(""); }); - it.each(["box", "vps"] as const)("offers both backends whichever is chosen (%s)", (value) => { + it.each(["box", "vps", "instabox"] as const)("offers all three backends whichever is chosen (%s)", (value) => { const markup = picker(value); expect(markup).toContain("Boat"); + expect(markup).toContain("InstaBox"); expect(markup).toContain("Self-hosted VPS"); expect(markup).not.toContain("disabled"); expect(markup).not.toMatch(/ACP model provider/); @@ -44,3 +45,9 @@ describe("CloudBackendPicker", () => { expect(Object.values(en).filter((value) => /switch the cloud backend to Boat/i.test(value))).toEqual([]); }); }); + +it("prompts for an InstaBox key without disabling selection", () => { + expect(picker("instabox")).toContain("Add your InstaBox key in Settings first"); + fixture.config = { instabox: { configured: true } }; + expect(picker("instabox")).not.toContain("Add your InstaBox key in Settings first"); +}); diff --git a/src/components/CloudBackendPicker.tsx b/src/components/CloudBackendPicker.tsx index 4c9aa241..cae784a1 100644 --- a/src/components/CloudBackendPicker.tsx +++ b/src/components/CloudBackendPicker.tsx @@ -1,3 +1,4 @@ +import { instaboxKeyStatus } from "./keys/key-catalog"; import type { CloudBackend } from "../../shared/wire"; import { cn } from "@/lib/cn"; import { useStore } from "@/state/store"; @@ -18,16 +19,18 @@ export function CloudBackendPicker({

    {compact ? t("botAccess.cloud.provider") : t("botAccess.cloud.backend")}
    - {compact + {value === "instabox" ? t("botAccess.cloud.instaboxDescription") : compact ? value === "vps" ? t("botAccess.cloud.vpsDescription") : t("botAccess.cloud.hostedDescription") : value === "vps" ? t("botAccess.cloud.vpsAutoDescription") : t("botAccess.cloud.hostedBackendDescription")}
    - {(["box", "vps"] as const).map((backend, i) => ( + {(["box", "vps", "instabox"] as const).map((backend, i) => ( ))}
    + {value === "instabox" && !instaboxKeyStatus(state.config).configured &&

    {t("botAccess.cloud.instaboxKeyHint")}

    }
    ); } diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsx index 2503036c..727c6f9d 100644 --- a/src/components/ComputerPanel.tsx +++ b/src/components/ComputerPanel.tsx @@ -1,3 +1,4 @@ +import { InstaboxSnapshots } from "./InstaboxSnapshots"; import { boatCapableEngine, cloudEngineOf } from "@/lib/remote-desktop"; import { canWorkOnCloud } from "../../shared/cloud-computer"; import { ComputerBrowserSwitch } from "./ComputerBrowserSwitch"; @@ -1508,6 +1509,7 @@ export function ComputerPanel({ />

    )} + {cloudBackend === "instabox" && profileBot.computer === "cloud" && phase !== "team-boat" && } {advanced && phase === "vps-unconfigured" && (
    diff --git a/src/components/InstaboxSnapshots.test.tsx b/src/components/InstaboxSnapshots.test.tsx new file mode 100644 index 00000000..ffcb9a9a --- /dev/null +++ b/src/components/InstaboxSnapshots.test.tsx @@ -0,0 +1,80 @@ +// @vitest-environment happy-dom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ApiError } from "@/state/api"; +import { setLocale } from "@/lib/i18n"; +import { InstaboxSnapshots } from "./InstaboxSnapshots"; + +const fixture = vi.hoisted(() => ({ api: vi.fn() })); +vi.mock("@/state/api", async (original) => ({ ...await original(), api: fixture.api })); +let host: HTMLDivElement; +let root: Root; +const snapshot = { id: "snapshot-one", name: "crybot-bot-one-backup", state: "ready" }; +const render = async (botId = "bot-one") => { await act(async () => root.render()); }; +const click = async (text: string, parent: ParentNode = host) => { + const button = [...parent.querySelectorAll("button")].find((button) => button.textContent === text); + expect(button).toBeDefined(); + await act(async () => button!.click()); +}; + +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + setLocale("en"); + fixture.api.mockReset().mockResolvedValue({ snapshots: [] }); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(async () => { await act(async () => root.unmount()); host.remove(); vi.unstubAllGlobals(); }); + +describe("InstaBox snapshots", () => { + it("shows the empty state and saves then refreshes", async () => { + await render(); + expect(host.textContent).toContain("No snapshots yet"); + fixture.api.mockResolvedValueOnce({ snapshot }).mockResolvedValueOnce({ snapshots: [snapshot] }); + await click("Save a snapshot"); + expect(fixture.api).toHaveBeenCalledWith("/api/bots/bot-one/instabox/snapshots", { method: "POST", body: "{}" }); + expect(host.textContent).toContain(snapshot.name); + expect(host.textContent).not.toContain("No snapshots yet"); + }); + + it.each(["Restore snapshot", "Delete"])("requires confirmation for %s, supports cancel, then refreshes", async (label) => { + fixture.api.mockResolvedValue({ snapshots: [snapshot] }); + await render(); + await click(label); + expect(fixture.api).toHaveBeenCalledTimes(1); + expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain(label === "Delete" ? "cannot be recovered" : "cold starts"); + await click("Cancel", document); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); + expect(fixture.api).toHaveBeenCalledTimes(1); + await click(label); + await click(label, document.querySelector('[role="alertdialog"]')!); + expect(fixture.api).toHaveBeenCalledWith(`/api/bots/bot-one/instabox/snapshots/snapshot-one${label === "Delete" ? "" : "/restore"}`, { method: label === "Delete" ? "DELETE" : "POST" }); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); + expect(fixture.api).toHaveBeenCalledTimes(3); + }); + + it("disables restore for unfinished snapshots", async () => { + fixture.api.mockResolvedValue({ snapshots: [{ ...snapshot, state: "creating" }] }); + await render(); + expect([...host.querySelectorAll("button")].find((b) => b.textContent === "Restore snapshot")?.disabled).toBe(true); + }); + + it("shows a localized missing-key error without provider detail", async () => { + fixture.api.mockRejectedValue(new ApiError("private-provider-detail", 503, { code: "instabox_key_missing" })); + await render(); + expect(host.querySelector('[role="alert"]')?.textContent).toBe("InstaBox key is not set"); + expect(host.textContent).not.toContain("private-provider-detail"); + }); + + it("clears a pending confirmation when switching bots and ignores the old list", async () => { + fixture.api.mockResolvedValueOnce({ snapshots: [snapshot] }); + await render(); + await click("Delete"); + await render("bot-two"); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); + expect(host.textContent).not.toContain(snapshot.name); + expect(fixture.api.mock.calls.at(-1)?.[0]).toBe("/api/bots/bot-two/instabox/snapshots"); + }); +}); diff --git a/src/components/InstaboxSnapshots.tsx b/src/components/InstaboxSnapshots.tsx new file mode 100644 index 00000000..7ec19892 --- /dev/null +++ b/src/components/InstaboxSnapshots.tsx @@ -0,0 +1,90 @@ +import { useEffect, useRef, useState } from "react"; +import { Loader2 } from "lucide-react"; +import { api, ApiError } from "@/state/api"; +import { t } from "@/lib/i18n"; +import { ConfirmDialog } from "./ConfirmDialog"; + +interface Snapshot { id: string; name: string; state: string } +type Action = { kind: "restore" | "delete"; snapshot: Snapshot }; +const button = "rounded-lg bg-control px-3 py-2 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-50"; + +function snapshotError(error: unknown): string { + const code = error instanceof ApiError ? error.body?.code : undefined; + if (code === "instabox_key_missing") return t("computer.instabox.keyMissing"); + if (code === "instabox_snapshot_machine_missing") return t("computer.instabox.snapshots.machineMissing"); + if (code === "instabox_snapshot_busy") return t("computer.instabox.snapshots.busy"); + return t("computer.instabox.snapshots.error"); +} + +export function InstaboxSnapshots({ botId }: { botId: string }) { + return ; +} + +function SnapshotPanel({ botId }: { botId: string }) { + const [snapshots, setSnapshots] = useState([]); + const [loading, setLoading] = useState(true); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + const [action, setAction] = useState(null); + const mounted = useRef(true); + const busy = useRef(false); + const base = `/api/bots/${encodeURIComponent(botId)}/instabox/snapshots`; + + useEffect(() => { + mounted.current = true; + const controller = new AbortController(); + void api<{ snapshots: Snapshot[] }>(base, { signal: controller.signal }).then((data) => { + if (!controller.signal.aborted) setSnapshots(data.snapshots); + }).catch((cause: unknown) => { + if (!controller.signal.aborted) setError(snapshotError(cause)); + }).finally(() => { if (!controller.signal.aborted) setLoading(false); }); + return () => { mounted.current = false; controller.abort(); }; + }, [base]); + + const run = async (chosen?: Action) => { + if (busy.current) return; + busy.current = true; + setPending(true); + setError(null); + try { + const path = chosen ? `${base}/${encodeURIComponent(chosen.snapshot.id)}${chosen.kind === "restore" ? "/restore" : ""}` : base; + await api(path, { method: chosen?.kind === "delete" ? "DELETE" : "POST", ...(!chosen ? { body: "{}" } : {}) }); + const data = await api<{ snapshots: Snapshot[] }>(base); + if (mounted.current) { setSnapshots(data.snapshots); setAction(null); } + } catch (cause) { + if (mounted.current) { setError(snapshotError(cause)); setAction(null); } + } finally { + busy.current = false; + if (mounted.current) setPending(false); + } + }; + + return ( +
    +
    +

    {t("computer.instabox.snapshots.title")}

    + +
    +

    {t("computer.instabox.snapshots.hint")}

    + {(loading || pending) &&

    {t("computer.instabox.snapshots.busy")}

    } + {error &&

    {error}

    } + {!loading && !error && snapshots.length === 0 &&

    {t("computer.instabox.snapshots.empty")}

    } +
      + {snapshots.map((snapshot) => ( +
    • + {snapshot.name} + + + + +
    • + ))} +
    + {action?.snapshot.name}{t(action?.kind === "restore" ? "computer.instabox.snapshots.restoreConfirm" : "computer.instabox.snapshots.deleteConfirm")}} + confirmLabel={t(action?.kind === "restore" ? "computer.instabox.snapshots.restore" : "common.delete")} + pending={pending} onCancel={() => { if (!busy.current) setAction(null); }} onConfirm={() => { if (action) void run(action); }} /> +
    + ); +} diff --git a/src/components/keys/KeysPage.dom.test.ts b/src/components/keys/KeysPage.dom.test.ts index f030b050..1e5f4835 100644 --- a/src/components/keys/KeysPage.dom.test.ts +++ b/src/components/keys/KeysPage.dom.test.ts @@ -157,7 +157,7 @@ describe("the keys page", () => { type(search, "fish"); expect(rowsShown()).toEqual(["fishAudio"]); type(search, "Computers and browser"); - expect(rowsShown()).toEqual(["box", "vps", "onePassword"]); + expect(rowsShown()).toEqual(["box", "instabox", "vps", "onePassword"]); type(search, "research"); expect(rowsShown()).toEqual(["treg"]); type(search, "zzz"); @@ -364,3 +364,14 @@ it.each([false, true])("uses a Chinese computers purpose without cloud desktops expect(host.textContent?.includes("云端桌面")).toBe(!providerLock); if (providerLock) expect(host.textContent).toContain("你自己的服务器和网站登录信息。"); }); + +it("shows the shared InstaBox environment key without editing controls or key characters", () => { + setConfig({ instabox: { configured: true, fromEnv: true, apiKey: "fixture-secret", last4: "cret" } }); + page(); + expect(row("instabox")).toBeNull(); + const readOnly = row("instaboxEnv")!; + expect(readOnly.textContent).toContain("INSTABOX_API_KEY"); + expect(readOnly.querySelector("input, button")).toBeNull(); + expect(readOnly.textContent).not.toContain("fixture-secret"); + expect(readOnly.textContent).not.toContain("cret"); +}); diff --git a/src/components/keys/key-catalog.test.ts b/src/components/keys/key-catalog.test.ts index d522bced..c40dd830 100644 --- a/src/components/keys/key-catalog.test.ts +++ b/src/components/keys/key-catalog.test.ts @@ -105,12 +105,12 @@ describe("every credential has one home on the keys page", () => { }); describe("searching the keys", () => { - const found = (query: string) => KEY_CATALOG.filter((entry) => keyMatches(entry, query)).map((entry) => entry.id); + const found = (query: string) => KEY_CATALOG.filter((entry) => !keyHidden(entry.id, null) && keyMatches(entry, query)).map((entry) => entry.id); it("matches a provider's name, what the key is for, and its section's title", () => { expect(found("fish")).toEqual(["fishAudio"]); expect(found("ElevenLabs")).toEqual(["elevenlabs"]); - expect(found("Computers and browser")).toEqual(["box", "vps", "onePassword"]); + expect(found("Computers and browser")).toEqual(["box", "instabox", "vps", "onePassword"]); expect(found("voice")).toEqual(expect.arrayContaining(["liveCalls", "liveKey", "elevenlabs", "fishAudio"])); expect(found("openai")).toEqual(expect.arrayContaining(["openai", "liveCalls", "liveKey", "imageOpenai"])); expect(found("gmail")).toEqual(["composio"]); @@ -165,6 +165,31 @@ describe("engines that run on a key", () => { it.each([false, true])("hides only the Boat computer key when provider lock is %s", (providerLock) => { const config = { providerLock } as ConfigStatus; const computers = KEY_CATALOG.filter((entry) => entry.section === "computers" && !keyHidden(entry.id, config)); - expect(computers.map((entry) => entry.id)).toEqual(providerLock ? ["vps", "onePassword"] : ["box", "vps", "onePassword"]); + expect(computers.map((entry) => entry.id)).toEqual(providerLock ? ["instabox", "vps", "onePassword"] : ["box", "instabox", "vps", "onePassword"]); expect(computers.filter((entry) => keyMatches(entry, "boat", config)).map((entry) => entry.id)).toEqual(providerLock ? [] : ["box"]); }); + +it("shows only the saved InstaBox key's last four and saves and clears its agreed config field", () => { + const entry = keyEntry("instabox"); + expect(entry.env).toEqual(["INSTABOX_API_KEY"]); + expect(entry.target?.patch("fixture-key", true)).toEqual({ instabox: { apiKey: "fixture-key" } }); + expect(entry.target?.patch("", false)).toEqual({ instabox: { apiKey: "" } }); + expect(savedState(entry, { instabox: { configured: true, last4: "nope", apiKey: "never-display", fromEnv: true } } as unknown as ConfigStatus)) + .toEqual({ configured: true }); + expect(savedState(entry, { instabox: { configured: true, last4: "play", apiKey: "never-display", fromEnv: false } } as unknown as ConfigStatus)) + .toEqual({ configured: true, last4: "play" }); +}); + +it("shows exactly one InstaBox row and makes the environment variant read-only", () => { + for (const fromEnv of [false, true]) { + const config = { instabox: { configured: true, fromEnv } } as unknown as ConfigStatus; + const entries = KEY_CATALOG.filter((entry) => entry.name === "InstaBox" && !keyHidden(entry.id, config)); + expect(entries).toHaveLength(1); + expect(entries[0]?.kind).toBe(fromEnv ? "elsewhere" : "key"); + if (fromEnv) { + expect(entries[0]?.target).toBeUndefined(); + expect(entries[0]?.opens).toBeUndefined(); + expect(t(entries[0]!.whereKey!)).toContain("INSTABOX_API_KEY"); + } + } +}); diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts index 5bfa9391..e40bd3f6 100644 --- a/src/components/keys/key-catalog.ts +++ b/src/components/keys/key-catalog.ts @@ -38,7 +38,7 @@ export interface KeyTarget { href?: string; test?: TestableProvider; verifiedOnSave?: boolean; - analytics: KeyProvider; + analytics: KeyProvider | "instabox"; shape?: RegExp; warningKey?: LocaleKey; noteKey?: LocaleKey; @@ -48,7 +48,7 @@ export interface KeyTarget { export type KeyId = | "openai" | "anthropic" | "xai" | "openrouter" | "mistral" | "cerebras" | "groq" | "greenference" | "modelgo" | "meta" | "deepseek" | "opencodeGo" | "opencodeProviders" - | "ollama" | "lmStudio" | "openaiCompat" | "liveCalls" | "liveKey" | "elevenlabs" | "fishAudio" | "geminiTts" | "box" | "vps" | "onePassword" | "composio" | "treg" | "postiz" + | "ollama" | "lmStudio" | "openaiCompat" | "liveCalls" | "liveKey" | "elevenlabs" | "fishAudio" | "geminiTts" | "box" | "instabox" | "instaboxEnv" | "vps" | "onePassword" | "composio" | "treg" | "postiz" | "jev" | "openrouterHelper" | "workersAi" | "imageOpenai" | "imageGemini" | "imageCustom"; export type KeyMark = { driverKind: string; preset?: ProviderIconPreset } | { icon: LucideIcon }; @@ -74,6 +74,11 @@ function flag(saved: SavedKey | undefined): SavedState { return { configured: saved?.configured === true, ...(saved?.configured && saved.last4 ? { last4: saved.last4 } : {}) }; } +export function instaboxKeyStatus(config: ConfigStatus | null | undefined): SavedState & { fromEnv: boolean } { + const status = config?.instabox; + return { ...flag(status?.fromEnv ? { configured: status.configured } : status), fromEnv: status?.fromEnv === true }; +} + type TopLevelKey = "openai" | "openrouter" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "modelgo" | "meta" | "deepseek" | "treg"; function providerKey(name: TopLevelKey, rest: Omit): KeyTarget { @@ -162,6 +167,13 @@ export const KEY_CATALOG: readonly KeyEntry[] = [ target: { patch: (value) => ({ box: { token: value } }), slot: "boxToken", verifiedOnSave: true, saved: (config) => ({ ...flag(config.box?.included ? undefined : config.box), ...(config.box?.included ? { included: true } : {}) }), placeholder: "boat_…", href: "https://docs.boat.dev/api-keys", analytics: "boat", shape: /^(boat|box)_/, warningKey: "keys.boat.warning" } }, + { id: "instabox", section: "computers", labelKey: "keys.instabox.label", purposeKey: "keys.purpose.instabox", name: "InstaBox", env: ["INSTABOX_API_KEY"], + words: ["instabox", "cloud computer", "snapshot", "android"], mark: { icon: Monitor }, kind: "key", + target: { patch: (value) => ({ instabox: { apiKey: value } }), saved: (config) => flag(instaboxKeyStatus(config)), + placeholder: "…", analytics: "instabox" } }, + { id: "instaboxEnv", section: "computers", labelKey: "keys.instabox.label", purposeKey: "keys.purpose.instabox", name: "InstaBox", env: [], + words: ["instabox", "cloud computer", "environment", "INSTABOX_API_KEY"], mark: { icon: Monitor }, kind: "elsewhere", + status: instaboxKeyStatus, whereKey: "keys.instabox.environment" }, { id: "vps", section: "computers", labelKey: "keys.vps.label", purposeKey: "keys.purpose.vps", name: "VPS", env: [], words: ["vps", "ssh", "server", "self-hosted", "computer", "docker"], mark: { icon: Server }, kind: "panel", status: (config) => ({ configured: config.vps?.configured === true }) }, @@ -242,6 +254,8 @@ export function savedState(entry: KeyEntry, config: ConfigStatus | null | undefi /** With Azure or Fish Audio chosen, Live calls do not use the OpenAI key the Live calls row points at, so that row is hidden. */ export function keyHidden(id: KeyId, config: ConfigStatus | null | undefined): boolean { + if (id === "instabox") return instaboxKeyStatus(config).fromEnv; + if (id === "instaboxEnv") return !instaboxKeyStatus(config).fromEnv; if (config?.providerLock && (id === "box" || KEY_CATALOG.find((entry) => entry.id === id)?.section === "ai")) return true; const provider = config?.live?.provider; return id === "liveCalls" && (provider === "azure" || provider === "fish"); diff --git a/src/locales/en.json b/src/locales/en.json index 09435657..7d4e8757 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -10609,5 +10609,24 @@ "vm.screens.count": "Number of screens", "vm.screens.resources": "Shared defaults: 8 GB memory · 3 CPUs, limited by the host.", "serverError.secret.saving": "This credential is being saved.", - "serverError.secret.screenUnavailable": "This bot no longer has access to the screen for this credential. Ask it to request the credential again." + "serverError.secret.screenUnavailable": "This bot no longer has access to the screen for this credential. Ask it to request the credential again.", + "keys.instabox.label": "InstaBox key", + "keys.purpose.instabox": "Cloud computer (InstaBox) key, shared by all agents", + "keys.instabox.environment": "Provided by INSTABOX_API_KEY; cannot be edited here", + "botAccess.cloud.instaboxDescription": "An InstaBox cloud computer with Linux desktop or Android and disk snapshots.", + "botAccess.cloud.instaboxKeyHint": "Add your InstaBox key in Settings first", + "computer.instabox.keyMissing": "InstaBox key is not set", + "computer.instabox.starting": "Starting the cloud computer", + "computer.instabox.suspended": "The cloud computer is asleep and wakes when needed", + "computer.instabox.snapshots.title": "Disk snapshots", + "computer.instabox.snapshots.save": "Save a snapshot", + "computer.instabox.snapshots.hint": "Snapshots save disk contents only, without running programs or memory.", + "computer.instabox.snapshots.empty": "No snapshots yet", + "computer.instabox.snapshots.restore": "Restore snapshot", + "computer.instabox.snapshots.deleteTitle": "Delete snapshot", + "computer.instabox.snapshots.restoreConfirm": "Restoring replaces the current disk and cold starts the cloud computer. Only disk contents are kept; running programs and memory are not restored. Continue?", + "computer.instabox.snapshots.deleteConfirm": "This snapshot cannot be recovered after deletion. Delete it?", + "computer.instabox.snapshots.busy": "Working on snapshots, please wait", + "computer.instabox.snapshots.error": "Snapshot request failed. Please try again.", + "computer.instabox.snapshots.machineMissing": "Start this agent’s InstaBox cloud computer first" } diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json index 8e7e26fc..ba9a76cb 100644 --- a/src/locales/pt-br.json +++ b/src/locales/pt-br.json @@ -10606,5 +10606,24 @@ "settings.island.width": "Largura do notch", "settings.island.widthHint": "Ajuste a área invisível de passar o mouse (120–320 px).", "serverError.secret.saving": "Esta credencial está sendo salva.", - "serverError.secret.screenUnavailable": "Este bot não tem mais acesso à tela destinada a esta credencial. Peça a ele que solicite a credencial novamente." + "serverError.secret.screenUnavailable": "Este bot não tem mais acesso à tela destinada a esta credencial. Peça a ele que solicite a credencial novamente.", + "keys.instabox.label": "Chave do InstaBox", + "keys.purpose.instabox": "Chave do computador em nuvem (InstaBox), compartilhada por todos os bots", + "keys.instabox.environment": "Fornecida por INSTABOX_API_KEY; não pode ser editada aqui", + "botAccess.cloud.instaboxDescription": "Um computador em nuvem InstaBox com Linux ou Android e instantâneos de disco.", + "botAccess.cloud.instaboxKeyHint": "Adicione primeiro sua chave do InstaBox em Configurações", + "computer.instabox.keyMissing": "A chave do InstaBox não está configurada", + "computer.instabox.starting": "Iniciando o computador em nuvem", + "computer.instabox.suspended": "O computador em nuvem está suspenso e desperta quando necessário", + "computer.instabox.snapshots.title": "Instantâneos de disco", + "computer.instabox.snapshots.save": "Salvar um instantâneo", + "computer.instabox.snapshots.hint": "Os instantâneos salvam apenas o conteúdo do disco, sem programas em execução ou memória.", + "computer.instabox.snapshots.empty": "Nenhum instantâneo ainda", + "computer.instabox.snapshots.restore": "Restaurar instantâneo", + "computer.instabox.snapshots.deleteTitle": "Excluir instantâneo", + "computer.instabox.snapshots.restoreConfirm": "A restauração substitui o disco atual e inicia o computador em nuvem a frio. Apenas o conteúdo do disco é mantido; programas em execução e memória não são restaurados. Continuar?", + "computer.instabox.snapshots.deleteConfirm": "Este instantâneo não poderá ser recuperado depois da exclusão. Excluir?", + "computer.instabox.snapshots.busy": "Processando instantâneos, aguarde", + "computer.instabox.snapshots.error": "Não foi possível processar o instantâneo. Tente novamente.", + "computer.instabox.snapshots.machineMissing": "Inicie primeiro o computador em nuvem InstaBox deste agente" } diff --git a/src/locales/zh.json b/src/locales/zh.json index 1ae8f2ed..d23a3783 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -8015,5 +8015,24 @@ "vm.screens.count": "屏数", "vm.screens.resources": "共享模式默认:8 GB 内存 · 3 核,不超过宿主机上限。", "serverError.secret.saving": "此凭据正在保存中。", - "serverError.secret.screenUnavailable": "此机器人已无法访问接收该凭据的屏幕。请让机器人重新请求凭据。" + "serverError.secret.screenUnavailable": "此机器人已无法访问接收该凭据的屏幕。请让机器人重新请求凭据。", + "keys.instabox.label": "InstaBox 钥匙", + "keys.purpose.instabox": "云电脑(InstaBox)钥匙,所有智能体共用", + "keys.instabox.environment": "由环境变量 INSTABOX_API_KEY 提供,不可在页面修改", + "botAccess.cloud.instaboxDescription": "InstaBox 云电脑,支持 Linux 桌面和 Android,可保存和恢复磁盘快照。", + "botAccess.cloud.instaboxKeyHint": "先在设置里填 InstaBox 钥匙", + "computer.instabox.keyMissing": "InstaBox 钥匙未配置", + "computer.instabox.starting": "云电脑开机中", + "computer.instabox.suspended": "云电脑已休眠,用到时自动唤醒", + "computer.instabox.snapshots.title": "磁盘快照", + "computer.instabox.snapshots.save": "存一个快照", + "computer.instabox.snapshots.hint": "快照只保存磁盘内容,不保存运行中的程序和内存。", + "computer.instabox.snapshots.empty": "还没有快照", + "computer.instabox.snapshots.restore": "恢复快照", + "computer.instabox.snapshots.deleteTitle": "删除快照", + "computer.instabox.snapshots.restoreConfirm": "恢复会替换当前磁盘并冷启动云电脑。快照只保留磁盘内容,运行中的程序和内存不会恢复。确定恢复吗?", + "computer.instabox.snapshots.deleteConfirm": "删除后无法找回这个快照。确定删除吗?", + "computer.instabox.snapshots.busy": "正在处理快照,请稍候", + "computer.instabox.snapshots.error": "快照操作失败,请稍后重试", + "computer.instabox.snapshots.machineMissing": "请先启动该智能体的 InstaBox 云电脑" } diff --git a/src/state/config-status.ts b/src/state/config-status.ts index e16b4ed3..f239ddd1 100644 --- a/src/state/config-status.ts +++ b/src/state/config-status.ts @@ -51,6 +51,7 @@ export interface ConfigStatus { composio: SavedKey & { mode?: "managed" | "self-hosted" | "unavailable" }; /** `included`: cloud computers come with Cloud Pro, no key is saved. */ box: SavedKey & { included?: boolean }; + instabox?: SavedKey & { fromEnv: boolean }; vps: { configured: boolean; sshAlias: string }; rooms: { turnTimeoutMinutes: number }; /** Per-call ceiling (minutes) for a bot's MCP tools. Absent from servers diff --git a/src/state/store.test.ts b/src/state/store.test.ts index 22331b6e..3fc1ddfb 100644 --- a/src/state/store.test.ts +++ b/src/state/store.test.ts @@ -1032,10 +1032,12 @@ describe("config status frames", () => { const status = configStatusFromFrame({ openai: { configured: true, last4: "a1b2" }, box: { configured: true, last4: "c3d4" }, + instabox: { configured: true, last4: "i7j8", fromEnv: false }, savedKeys: { ttsKey: { configured: true, last4: "e5f6" }, openaiLiveKey: { configured: false } }, } as ConfigStatusFrame); expect(status.openai).toEqual({ configured: true, last4: "a1b2" }); expect(status.box).toEqual({ configured: true, last4: "c3d4" }); + expect(status.instabox).toEqual({ configured: true, last4: "i7j8", fromEnv: false }); expect(status.savedKeys).toEqual({ ttsKey: { configured: true, last4: "e5f6" }, openaiLiveKey: { configured: false } }); }); diff --git a/src/state/store.tsx b/src/state/store.tsx index ca714026..e2269c4f 100644 --- a/src/state/store.tsx +++ b/src/state/store.tsx @@ -399,7 +399,7 @@ export type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicyS // A section left out here is wiped from state.config whenever a config frame lands. export type ConfigStatusFrame = Pick< ConfigStatus, - "providerLock" | "awakeLimit" | "pausedBots" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "modelgo" | "meta" | "deepseek" | "xResearch" | "treg" | "postiz" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "everyBotRules" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team" | "workspaceBanner" + "providerLock" | "awakeLimit" | "pausedBots" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "modelgo" | "meta" | "deepseek" | "xResearch" | "treg" | "postiz" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "instabox" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "everyBotRules" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team" | "workspaceBanner" >; export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus { @@ -416,7 +416,7 @@ export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus { openaiCompat: frame.openaiCompat, fleet: frame.fleet, composio: frame.composio, - box: frame.box, + box: frame.box, instabox: frame.instabox, vps: frame.vps, rooms: frame.rooms, mcp: frame.mcp,