From ae77d89f07b06f408e0563938847a4f69048f480 Mon Sep 17 00:00:00 2001 From: tangzhixiong613-jpg <340458552+tangzhixiong613-jpg@users.noreply.github.com> Date: Sun, 15 Nov 2026 07:14:25 +0000 Subject: [PATCH 1/3] =?UTF-8?q?T-1242=20InstaBox=20=E6=A0=B8=E5=BF=83?= =?UTF-8?q?=EF=BC=9A=E6=9C=BA=E5=99=A8=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= =?UTF-8?q?=E3=80=81=E5=9B=9E=E5=90=88=E6=8E=A5=E5=85=A5=E3=80=81=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E4=B8=8E=E5=88=A0=E9=99=A4=EF=BC=9B=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E9=92=A5=E5=8C=99=E5=8F=AA=E9=9A=8F=E5=9B=9E=E7=8E=AF=E5=81=87?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E4=BC=A0=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../T-1200/T-1242-instabox-core/brief.md | 95 ++++ docs/tasks/T-1200/T-1242-instabox-core/r2.md | 27 ++ docs/tasks/T-1200/T-1242-instabox-core/r3.md | 25 ++ docs/tasks/T-1200/T-1242-instabox-core/r4.md | 25 ++ docs/tasks/T-1200/T-1242-instabox-core/r5.md | 27 ++ .../T-1200/T-1242-instabox-core/report.md | 119 +++++ .../T-1242-instabox-core/verification.txt | 349 +++++++++++++++ scripts/control-cry.test.ts | 13 + scripts/control-cry.ts | 9 +- scripts/public-scan/allow-domains.txt | 1 + server/cloud-backend.test.ts | 9 + server/cloud-backend.ts | 11 + server/config.ts | 11 +- server/index.ts | 93 ++-- server/instabox/client.test.ts | 58 +++ server/instabox/client.ts | 82 ++++ server/instabox/core.e2e.test.ts | 419 ++++++++++++++++++ server/instabox/key.test.ts | 29 ++ server/instabox/key.ts | 13 + server/instabox/machine.ts | 24 + server/instabox/machines.test.ts | 114 +++++ server/instabox/machines.ts | 115 +++++ server/instabox/persistence.test.ts | 10 + server/instabox/power.test.ts | 75 ++++ server/instabox/power.ts | 90 ++++ server/routes/bot-patch.test.ts | 18 + server/routes/bot-patch.ts | 4 +- server/store.ts | 2 +- server/testing/desktop-parent.mjs | 8 + server/testing/fake-instabox-core.ts | 79 ++++ shared/wire.ts | 2 +- 31 files changed, 1924 insertions(+), 32 deletions(-) create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/brief.md create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/r2.md create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/r3.md create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/r4.md create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/r5.md create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/report.md create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/verification.txt create mode 100644 server/instabox/client.test.ts create mode 100644 server/instabox/client.ts create mode 100644 server/instabox/core.e2e.test.ts create mode 100644 server/instabox/key.test.ts create mode 100644 server/instabox/key.ts create mode 100644 server/instabox/machine.ts create mode 100644 server/instabox/machines.test.ts create mode 100644 server/instabox/machines.ts create mode 100644 server/instabox/persistence.test.ts create mode 100644 server/instabox/power.test.ts create mode 100644 server/instabox/power.ts create mode 100644 server/testing/fake-instabox-core.ts diff --git a/docs/tasks/T-1200/T-1242-instabox-core/brief.md b/docs/tasks/T-1200/T-1242-instabox-core/brief.md new file mode 100644 index 00000000..8b91fb98 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/brief.md @@ -0,0 +1,95 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1242 云电脑①:核心客户端、开机/挂起、后端切换接线 + +(本任务是 T-1239 的第 1 块,与 ②③④ 并行开发。下面「共同约定」必须遵守。) + +## 本任务负责的文件(只改这些;别的任务的文件不要碰) +- 新建:`server/instabox/machine.ts`(共享契约,按约定原样)、`server/instabox/client.ts`、`server/instabox/machines.ts`、`server/instabox/power.ts`、`server/instabox/key.ts`,以及它们的测试和你自己的假服务 `server/testing/fake-instabox-core.ts`。 +- 修改:`shared/wire.ts:62`(按约定原样改那一行)、`server/config.ts`(加 `instabox?: { apiKey?: string }`,余量 10 行)、`server/store.ts:336`(允许 `cloudBackend: "instabox"`)、`server/routes/bot-patch.ts:389-390`(接受 instabox,错误文案改为 box, vps or instabox)、`server/cloud-backend.ts`(集中放后端判断小函数)、`server/index.ts`(余量约 110 行,你最多用 80 行,给 ⑤ 留 30 行)。 + +## 要做 +1. `client.ts`:`createInstaboxRequest(apiKey: string, baseUrl = "https://api.instabox.sh"): InstaboxRequest`。带 X-API-Key;`idempotent: true` 时加随机 Idempotency-Key;非 2xx 抛带状态码和 错误码的错误(不得把钥匙写进错误或日志)。另导出 `waitOperation(request, opId, timeoutMs)`:`?wait=25s` 长轮询到 succeeded/failed。 +2. `key.ts`:`instaboxApiKey(cfg)`:环境变量 `INSTABOX_API_KEY` 优先,否则 `cfg.instabox?.apiKey`,空串当未配置。`instaboxConfigured(cfg)`。 +3. `machines.ts`:`createInstaboxMachines(request: InstaboxRequest): InstaboxMachines`,完整实现契约: + - 机器名 `crybot-`,metadata `{app:"crybot",botId}`;`find` 按名字查(`deleted` 视为没有)。 + - `ensureRunning`:没有就建(linux→`agent-browser`,android→`android`,4 核 8G,autoSuspend 600);`suspended` 就 resume;`stopped` 就 start;`error` 抛错;中间态等到稳定;然后 `POST /desktop {"action":"start","width":1280,"height":800}`(桌面已在跑时接口返回的情况要容错)。同一 botId 并发调用只发一次创建(进程内单飞)。 + - `suspend`、`remove`(带 X-Confirm-Delete)、`exec`(409 machine_not_running 时先 resume 再重试一次)、`readFile`、`writeFile`、`vncUpstream`(返回 `wss://api.instabox.sh/v1/machines/{id}/vnc` 和含钥匙的头;基址跟随 client 的 baseUrl,http→ws、https→wss,便于测试)。 +4. `power.ts`:智能体回合结束、空闲时挂起机器(自身的 600 秒自动挂起是兜底,不必另写定时器的话可以只在删智能体/切走后端时处理);删除智能体时删除其机器;把智能体的后端从 instabox 切走时挂起(不删,留着可切回)。说明清楚你的选择。 +5. `server/index.ts` 接线(只做本任务的部分): + - 现在很多地方写的是 `bot.cloudBackend === "vps" ? "vps" : "box"`。在 `cloud-backend.ts` 加一个小函数(如 `cloudKindOf(bot)` 返回 `"box" | "vps" | "instabox"`),把 index.ts 里涉及「这个智能体用哪种云电脑」的判断(约 2518、2915、4617、5955-6043、7902-8243、14995-15111 这些位置)改成三分支:instabox 智能体不走 Boat、不走 VPS,云电脑请求走 `createInstaboxMachines(...).ensureRunning(botId)`。 + - 钥匙没配置时,选 instabox 的智能体要明确报「钥匙未配置」,不能悄悄回退到 Boat。 + - 共用电脑(team computer)、本地 VM、多屏路径一律不动:继承共用电脑的智能体照旧走 Boat。 + - 状态接口(约 14995 行 `backend:` 字段)返回 `"instabox"`。 + - 智能体操作电脑的工具、远程画面、快照路由由 ②③④ 实现、⑤ 接进来;你这里**不要**引用它们的文件,只保证 `InstaboxMachines` 实例能被拿到:在 index.ts 里留一个函数 `instaboxMachinesFor(cfg)`(钥匙变了要换新实例,未配置返回 null),⑤ 会用它。 +6. 测试:假服务覆盖创建→等操作单→开桌面、挂起中 exec 先 resume、并发 ensureRunning 只建一次、删除带确认头、错误里不含钥匙;后端判断函数的单测;bot-patch 接受 instabox;store 读回 instabox 不被删。e2e(用假服务把一个 instabox 智能体从无到开机)连跑 3 次。 + +## 验收 +按「共同约定 · 测试」执行;report.md 只写实际改过的文件,并单独列出你在 index.ts 用了多少行、`instaboxMachinesFor` 的签名、需要 ④ 加的文案键(中英文)。 + +--- + +# 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-1242-instabox-core/r2.md b/docs/tasks/T-1200/T-1242-instabox-core/r2.md new file mode 100644 index 00000000..72e576f8 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/r2.md @@ -0,0 +1,27 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1242 第 2 轮:恢复 run_on=cloud 走 Boat、管理策略覆盖 instabox、删除路径不留孤儿也不被 卡住 + +原任务见本文件夹 brief.md(含共同约定),工作区里上一轮改动保留,在此基础上改。第 1 轮审核:需要返工;安全审查:1 个中危(与必改 2 是同一个问题)。 + +## 必改 +1. server/index.ts:5958-5963、:7915:恢复 routine `run_on="cloud"` 固定走 Boat 的语义(turnProvider 首行、beginTurn 的 cloudBackend 都要),与 turnSurfacePlan:5949 的 `forcedBoat`、cloudRoutineReadiness:8971-8975 的文案一致。写法如 `cloudKindOf(bot, Boolean(teamComputer) || opts?.runOn === "cloud")`。补回归测试:VPS 智能体、instabox 智能体跑 run_on=cloud 时都走 box。 +2. 管理策略不能被 instabox 绕过(安全中危):server/cloud-backend.ts:58-61 `cloudPolicyKindOf` 对 instabox 不能返回 undefined。策略判断时把 instabox 归到 "box"(ComputerKind 里 box 的文案就是 "cloud computers"),默认拒绝;提示词种类可继续返回 null。用到的地方 index.ts:6056(selectableComputers)、:7931-7932(beginTurn wantedKind)、:9984(群聊 roomKind)都要生效;并在 `requireInstabox(...).ensureRunning(...)` 之前先过 `computerPlaceRefusal`。补测试:策略禁 box 时 instabox 智能体被拒、不调 ensureRunning;CLOUD_HOME 不提供 cloud 时同样被拒。 +3. server/index.ts:9095、:9105:删除智能体时 Boat 和 VPS 两份清单照常列、照常删本智能体名下机器(从 box/vps 切到 instabox 后再删不能留孤儿);instabox 只是额外再删 机器。补测试。 +4. server/index.ts:9117-9119:不是 instabox 的智能体,`instabox.remove()` 失败只降级成 notice(参照 vpsLeftOn 的做法),不挡删除;只有 instabox 智能体删机器失败时才保留智能体并返回 503,报错文案说明是 那边失败。补测试(假服务返回 5xx/网络错误时,Boat 智能体照样删得掉)。 + +## 一起改 +5. server/instabox/power.ts:273-281:PATCH 切走后端时的 suspend 改成后台执行,不阻塞响应;失败只记 notice。 +6. server/instabox/machines.ts:125-130:`find` 除名字外核对 `metadata.botId` 与本智能体一致,不一致不认(防止前 12 位相同的 id 共用、误删)。 +7. server/instabox/machines.ts:169-175:已有机器的模板与请求不一致时明确报错,不要悄悄返回别的模板的机器。 +8. server/instabox/machines.ts:161、198:不读的响应体 `await response.body?.cancel()`,别占着连接。 +9. server/index.ts:15016-15019:状态接口里 instaboxStatus 出错时与 Boat/VPS 分支对齐,返回 problem 字段,不抛 500。 +10. 文档位置:report.md、verification.txt 挪到 docs/tasks/T-1200/T-1242-instabox-core/(与 brief.md 同处),删掉 docs/tasks/T-1242/;verification.txt 里的沙箱绝对路径一律改成仓库相对路径。 + +## 验收 +改动相关测试逐文件跑(含 cloud-backend、bot-patch、server/instabox/*、新增回归测试),core e2e 连跑 3 次;`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`;文件行数门禁通过(index.ts 净增仍要尽量少,shared/wire.ts 不超 1000 行)。report.md 追加第 2 轮一节,只写实际改过的文件。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/r3.md b/docs/tasks/T-1200/T-1242-instabox-core/r3.md new file mode 100644 index 00000000..dac81a8e --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/r3.md @@ -0,0 +1,25 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1242 第 3 轮:只修复审必改项 + +原任务见本文件夹 brief.md、r2.md,工作区里上一轮改动保留。第 2 轮复审:需要返工。本轮只做下面几条,别的不动。 + +## 必改 +1. server/index.ts beginTurn 的策略判断(约 :7933):`wantedKind` 现在用 `cloudPolicyKindOf(bot, Boolean(teamComputer))`,漏了 run_on=cloud。VPS 智能体跑 run_on=cloud 时实际挂 Boat,却按 "vps" 判,策略「禁 box、允许 vps」可被绕过。改成从已算好的 `cloudBackend` 推出(或给 `cloudPolicyKindOf` 传 `Boolean(teamComputer) || opts?.runOn === "cloud"`),保证实际用哪种电脑就按哪种判。 +2. 补齐 r2 第 1–4 条要求的回归测试(放在能驱动 turnProvider/beginTurn 和删除流程的 index 层或 e2e 测试里,不只测纯函数): + - VPS / instabox 智能体跑 run_on=cloud 时走 box,且策略按 box 判(覆盖上面第 1 条); + - 策略禁 box、CLOUD_HOME 不提供 cloud 时,instabox 智能体被拒,且不调 ensureRunning; + - 从 box/vps 切到 instabox 后删除智能体,Boat/VPS 上的机器照样被删; + - 假服务返回 5xx 或网络错误时,Boat 智能体照样能删并带 notice;instabox 智能体保留并返回 503。 +3. docs/tasks/T-1200/T-1242-instabox-core/report.md 追加「第 2、3 轮」一节:只写实际改过的文件;文件清单去掉已删的旧目录;index.ts 行数按实际重算;文案键表删掉代码里已不用的 `computer.instabox.suspendFailed`。verification.txt 重新生成本轮测试结果(不要写 IP、内网地址、域名)。 + +## 顺手改 +4. server/index.ts 约 :9125:instabox 智能体删机器失败时不要直接 `return deletionResponse(503, …)`,改为照原写法 `throw Object.assign(new Error(...), { status: 503 })`,让外层 catch 里的 browserCleanup.abort 照常执行。 + +## 验收 +改动相关测试逐文件跑;`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/r4.md b/docs/tasks/T-1200/T-1242-instabox-core/r4.md new file mode 100644 index 00000000..4d7ee1b6 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/r4.md @@ -0,0 +1,25 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1242 第 4 轮:只修复审必改项(回归测试第二次没补到位,这次按下面写法逐条落实) + +原任务见本文件夹 brief.md、r2.md、r3.md,工作区里上一轮改动保留。第 3 轮复审(Codex 只读审):需要返工。本轮只做下面三条。 + +## 必改 +1. server/instabox/machines.ts:81 — 未传模板时直接默认 linux,第 57 行对已有 Android 机器抛模板不匹配;index.ts 的普通回合和群聊调用都不传模板,所以 Android 智能体建好后发消息就失败。改为:未指定模板时沿用已有机器的模板,只有新建机器才默认 Linux;显式指定且不匹配时仍拒绝。power.ts:62 同样保留「未指定」语义。补回归测试:建 Android 机器后进入普通回合不报错。 +2. server/instabox/core.e2e.test.ts — 策略回归测试必须真正走到 beginTurn 的后端选择和策略判断: + - fixture 配一个可用的假 Boat(参照仓库里已有的 Boat 假服务/测试写法),让流程越过 cloudRoutineReadiness; + - 断言 VPS 智能体、智能体跑 run_on=cloud 时用的是 box,并且策略「禁 box、允许 vps」时被拒; + - 智能体在管理策略禁止、以及 CLOUD_HOME 不提供 cloud 时被拒,且假 完全没收到 ensureRunning 相关请求。 + 自检:临时把第 3 轮修过的策略判断改回旧写法,确认这组测试会失败,再改回来(报告里写明做过这一步)。 +3. 同文件删除用例方向改对:分别预置归属该智能体的 Boat 机器、VPS 机器,把智能体切到 后删除智能体,断言 Boat/VPS 上的机器收到删除调用;另补 智能体删除时假服务返回网络错误 → 返回 503 且智能体保留。 + +## 一起改 +4. report.md 追加第 4 轮一节,并补完整交接信息:完整改动文件清单(按 git status)、index.ts 净增行数(实测)、`instaboxMachinesFor` 签名、仍在用的文案键及中英文、依赖 600 秒自动挂起的说明。verification.txt 重新生成(不要写 IP、内网地址、域名)。 + +## 验收 +改动相关测试逐文件跑,core e2e 连跑 3 次;`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/r5.md b/docs/tasks/T-1200/T-1242-instabox-core/r5.md new file mode 100644 index 00000000..a52b4b71 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/r5.md @@ -0,0 +1,27 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1242 第 5 轮:只修复第 4 轮审核的 2 条必改 + +原任务见本文件夹 brief.md、r2.md、r3.md、r4.md,工作区里上一轮改动保留。第 4 轮复审(Codex 只读审):需要返工。本轮只做下面两条,不改别的。 + +## 为什么前三轮都没补到位(先读) +之前的策略用例全部用「例程 runOn: "cloud"」触发,因为例程接口好调;但 cloudKindOf(bot, runOn === "cloud") 在 runOn cloud 时走的是另一条分支,测不到「普通对话回合 + 」。另外从来没有在测试里真正启用 CLOUD_HOME。本轮两条都必须走**普通对话回合**(不经例程、不带 runOn),并真实启用 CLOUD_HOME。 + +## 必改 +1. scripts/control-cry.ts 约 221 行:现在无条件把宿主的 INSTABOX_API_KEY 传给子进程。改为:只有 CRYBOT_TEST_INSTABOX_API 通过同一个回环地址校验(上一行的正则)时才传钥匙,否则子进程环境里不能有 INSTABOX_API_KEY。补一个隔离测试:父环境有 INSTABOX_API_KEY、没有(或无效的)CRYBOT_TEST_INSTABOX_API → 子环境不含该钥匙;地址有效 → 含钥匙。参照该文件现有的环境过滤测试写法。 + +2. server/instabox/core.e2e.test.ts:新增两个**普通对话回合**用例(智能体 cloudBackend: "instabox"、computer: "cloud",用仓库其他 e2e 里发普通聊天消息的同一接口触发一轮,不建例程): + a. 管理策略禁 box(参照本文件现有 CRYBOT_TEST_DESKTOP_POLICY 写法,computers 里 box 设为 false):断言这一轮被拒、拒绝原因是 managed_policy 对应的文案,且假 服务没收到任何 /v1/machines 相关请求(即没走到 ensureRunning)。 + b. 真实启用 CLOUD_HOME:照 server/cloud-personal.e2e.test.ts 等现有云端家 e2e 的启动方式(CRYBOT_CLOUD_ROLE 等环境)起服务;在该环境下 cloud 不可用的情形让 智能体发一轮普通消息,断言明确拒绝原因、假 没收到启动相关请求。若读代码后确认云端家下 本就应当允许(cloudHomePlaceRefusal("cloud") 不拒),则改为断言「允许且走 不走 Boat」,并在报告里写清依据(引用代码行)。 + 自检:临时把 server/index.ts 约 7933 行 wantedKind 对 cloud 的判断改成 undefined,确认用例 a 失败,再改回来;报告写明做过。 + +## 一起改 +3. report.md 追加第 5 轮一节(改了什么、自检结果、测试命令和结果);verification.txt 重新生成(不要写 IP、内网地址、域名、错误里的连接地址)。 + +## 验收 +改动相关测试逐文件跑,core e2e 连跑 3 次全过;`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/report.md b/docs/tasks/T-1200/T-1242-instabox-core/report.md new file mode 100644 index 00000000..92d56904 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/report.md @@ -0,0 +1,119 @@ +1. 改了什么 + +第 2、3 轮实际改动文件(历史记录): + +```text + M docs/tasks/T-1200/T-1242-instabox-core/report.md + M docs/tasks/T-1200/T-1242-instabox-core/verification.txt + M server/index.ts + M server/instabox/core.e2e.test.ts +``` + +`server/index.ts` 当前 15449 行。本轮 `beginTurn` 的云策略判定改用已解析的 `cloudBackend`,因此 `run_on=cloud` 的 instabox 按 box 策略检查;instabox 删除失败改为抛出 503,外层 catch 仍会执行 browser cleanup abort。新增 index 层 e2e 回归覆盖 `run_on=cloud`、切换后删除、Boat 侧 5xx/网络错误降级、instabox 删除失败保留智能体。 + +2. 为什么 + +确保实际使用的云电脑类型与管理策略一致,避免 `run_on=cloud` 绕过 box 禁止策略;删除时保留 Boat/VPS 清理流程,并让 失败只在 instabox 智能体上阻止最终删除,同时保持浏览器清理回滚。 + +3. 测试命令与结果摘要 + +依赖准备脚本 已运行。仓库未提供 `docs/verification/README.md`;本轮使用临时目录、假引擎和 loopback 假 服务,未连接真实服务。 + +- `pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1`:7 项通过,连续 3 次通过。 +- `pnpm exec vitest run server/cloud-backend.test.ts --maxWorkers=1`:12 项通过。 +- `pnpm exec vitest run server/index.test.ts --maxWorkers=1`:338 项通过。 +- `pnpm exec tsc -p tsconfig.server.json`:通过。 +- `pnpm exec oxlint --deny-warnings server/index.ts server/instabox/core.e2e.test.ts`:通过。 +- `git diff --check`:通过。 + +完整输出见 [verification.txt](verification.txt)。 + +## 第 4 轮 + +1. 改了什么 + +本轮最终 `git status --short` 文件清单: + +```text + M docs/tasks/T-1200/T-1242-instabox-core/report.md + M docs/tasks/T-1200/T-1242-instabox-core/verification.txt + M scripts/control-cry.ts + M server/instabox/core.e2e.test.ts + M server/instabox/machines.test.ts + M server/instabox/machines.ts + M server/instabox/power.test.ts + M server/instabox/power.ts + M server/testing/desktop-parent.mjs +``` + +模板未指定时复用已有 机器的模板,新建机器仍默认 Linux;补充 Android 普通回合、Boat/VPS 归属机器删除、策略拒绝和 删除失败保留智能体的真实回合回归。`server/index.ts` 本轮净增 0 行,当前及基线均为 15449 行。`instaboxMachinesFor` 签名为 `function instaboxMachinesFor(cfg: AppConfig): InstaboxMachines | null`。 + +仍在用的文案键及中英文: + +| 键 | 中文 | English | +| --- | --- | --- | +| `serverError.instabox.keyMissing` | 钥匙未配置 | API key is not configured | +| `serverError.instabox.template` | 模板必须是 linux 或 android | template must be linux or android | +| `serverError.instabox.unavailable` | 电脑访问不可用 | computer access is unavailable | + +`autoSuspendAfterSeconds: 600` 是 自动挂起兜底,本轮没有另写定时器。 + +2. 为什么 + +让 Android 机器在普通回合未传模板时继续可用,并保持群聊调用所需的未指定模板语义;让策略判断真正覆盖 `beginTurn` 的后端选择,删除时按机器归属清理 Boat/VPS,删除网络错误返回 503 并保留智能体。 + +3. 测试命令与结果摘要 + +依赖准备脚本 已运行。旧策略判断临时恢复后,VPS 策略回合测试按预期失败,随后恢复正确实现。使用 loopback 假服务和临时目录,未连接真实服务。 + +- `pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1`:13 项通过,最终连续 3 次通过。 +- `pnpm exec vitest run server/instabox/machines.test.ts --maxWorkers=1`:13 项通过。 +- `pnpm exec vitest run server/instabox/power.test.ts --maxWorkers=1`:7 项通过。 +- `pnpm exec vitest run scripts/control-cry.test.ts --maxWorkers=1`:9 项通过。 +- `pnpm exec vitest run server/cloud-backend.test.ts --maxWorkers=1`:12 项通过。 +- `pnpm exec vitest run server/index.test.ts --maxWorkers=1`:338 项通过。 +- `pnpm exec tsc -p tsconfig.server.json`:通过。 +- `pnpm exec oxlint --deny-warnings`(本轮改动文件):通过。 +- `git diff --check`:通过。 + +完整输出见 [verification.txt](verification.txt)。 + +## 第 5 轮 + +1. 改了什么 + +本轮最终 `git status --short` 文件清单: + +```text + M docs/tasks/T-1200/T-1242-instabox-core/report.md + M docs/tasks/T-1200/T-1242-instabox-core/verification.txt + M scripts/control-cry.test.ts + M scripts/control-cry.ts + M server/instabox/core.e2e.test.ts +``` + +启动器只在假 地址通过原有回环正则时传入钥匙;环境过滤测试覆盖地址缺失、无效、有效及无钥匙。新增两个普通消息回合(不建例程、不带 `runOn`):管理策略禁 box 时校验失败回合及准确拒绝文案,且无任何机器请求;真实云端家通过签名配对,并断言 `cloudHome: true`、回合成功、创建与桌面启动、该回合无 Boat 请求。追加本节并重新生成脱敏验证记录;未提交 git。 + +2. 为什么 + +避免宿主钥匙在未指定隔离假服务时进入子进程,并覆盖此前例程用例未经过的普通回合策略分支。云端家按允许分支验收:`server/cloud-home.ts:134` 的 `cloudHomePlaceRefusal` 只拒绝 local/vm,cloud 返回 undefined(第 137 行);`server/index.ts:1540` 将云电脑传作 cloud,随后在第 8205 行调用 `ensureRunning`。 + +3. 测试命令与结果摘要 + +已运行 依赖准备脚本。仓库缺少 `docs/verification/README.md`;全部服务验证使用隔离临时目录和假服务。 + +自检:临时把 `server/index.ts:7933` 的 cloud 分支改成 undefined,运行 `pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'refuses a normal turn'`,用例按预期失败(普通回合成功回复,缺少应有的策略拒绝);随后恢复,`server/index.ts` 最终无 diff。 + +| 命令 | 结果 | +| --- | --- | +| `pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1` | 最终连续 3 次,每次 15 项全过 | +| `pnpm exec vitest run scripts/control-cry.test.ts --maxWorkers=1` | 10 项通过 | +| `pnpm exec vitest run server/cloud-backend.test.ts --maxWorkers=1` | 12 项通过 | +| `pnpm exec vitest run server/index.test.ts --maxWorkers=1` | 338 项通过 | +| `pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1` | 1 项通过 | +| `pnpm exec tsc -p tsconfig.server.json` | 通过 | +| `pnpm exec oxlint --deny-warnings scripts/control-cry.ts scripts/control-cry.test.ts server/instabox/core.e2e.test.ts` | 通过 | +| `git diff --check` | 通过 | +| `pnpm exec vitest run server/control-cry.test.ts --maxWorkers=1` | 19 过、1 失败;第 261 行预期仅 claude,实际还有 chatgpt。临时恢复 HEAD 中的启动器后复跑仍同样失败,确认是基线问题,未扩展修复,也未重复跑三次 | + +完整输出(含预期失败的自检与基线复跑)见 [verification.txt](verification.txt)。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/verification.txt b/docs/tasks/T-1200/T-1242-instabox-core/verification.txt new file mode 100644 index 00000000..855f80e1 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/verification.txt @@ -0,0 +1,349 @@ +T-1242 第 5 轮验证 +所有服务使用隔离临时目录、假引擎和本地假服务。 +docs/verification/README.md 在仓库中不存在。 +地址、主机名及仓库绝对路径已脱敏;下列保留完整命令输出。 + +$ crybot-link-deps +crybot-link-deps: linked 73 entries into worktree node_modules + +===== new-cases ===== +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'normal InstaBox turn' + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 2 passed | 13 skipped (15) + Start at 06:54:50 + Duration 11.59s (transform 1.52s, setup 954ms, import 1.10s, tests 9.39s, environment 0ms) + + +===== mutation ===== +Mutation: replace wantedKind cloud branch with undefined. +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t refuses a normal InstaBox turn + + RUN v4.1.11 . + + ❯ server/instabox/core.e2e.test.ts (15 tests | 1 failed | 14 skipped) 26570ms + × refuses a normal InstaBox turn under the managed box policy before any machine request 26568ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL server/instabox/core.e2e.test.ts > refuses a normal InstaBox turn under the managed box policy before any machine request +AssertionError: expected [ { …(8) }, { …(7) }, { …(12) }, …(2) ] to deeply equal ArrayContaining{…} + +- Expected ++ Received + +- ArrayContaining [ +- ObjectContaining { ++ [ ++ { ++ "at": 1794725725956, ++ "kind": "text", ++ "parentId": null, ++ "role": "bot", ++ "setupChoices": [ ++ "Research and digging into topics", ++ "Keeping an eye on things for me", ++ "Email, calendar and messages", ++ "Bookings, shopping and errands", ++ "Data, spreadsheets and reports", ++ ], ++ "setupOffer": true, ++ "text": "Hi, I'm Churro. What would you like me to do?", ++ }, ++ { ++ "at": 1794725730551, ++ "kind": "text", ++ "requestPending": false, ++ "role": "user", ++ "text": "Use the cloud computer.", ++ }, ++ { ++ "at": 1794725730720, ++ "kind": "text", ++ "role": "bot", ++ "text": "hello from fake claude", ++ "turnCompletedAt": 1794725730733, ++ "turnSucceeded": true, ++ "turnTerminal": true, ++ }, ++ { ++ "at": 1794725730723, + "kind": "activity", + "role": "bot", +- "tool": ObjectContaining { +- "name": "error: Fixture Agency does not allow bots to use cloud computers.", +- "ok": false, ++ "tool": { ++ "input": "{ ++ \"command\": \"echo hi\" ++ }", ++ "itemId": "tu-13183-1", ++ "name": "Bash", ++ "ok": true, ++ "output": "[ ++ { ++ \"type\": \"text\", ++ \"text\": \"hi\" ++ } ++ ]", ++ "spoken": "running a command", ++ "step": { ++ "activity": "command", ++ "target": "echo hi", ++ }, ++ "summary": "echo hi", ++ }, ++ }, ++ { ++ "at": 1794725730735, ++ "digest": { ++ "at": 1794725730735, ++ "durationMs": 83, ++ "hookCoverage": "preview", ++ "memory": [], ++ "reply": "hello from fake claude", ++ "toolCalls": 1, ++ "tools": [ ++ { ++ "count": 1, ++ "failed": 0, ++ "name": "Bash", ++ "sample": "echo hi", + }, +- "turnSucceeded": false, ++ ], ++ "usage": { ++ "cachedInput": 2, ++ "costUsd": 0.01, ++ "input": 12, ++ "output": 5, ++ }, ++ }, ++ "kind": "digest", ++ "role": "bot", ++ "text": "[digest] · tools: Bash ×1 (from tool previews) · reply: hello from fake claude", ++ "turnSucceeded": true, + }, + ] + + ❯ server/instabox/core.e2e.test.ts:215:8 + 213| expect((await request("POST", `/api/bots/${bot.id}/messages`, { te… + 214| await expect.poll(async () => (await request("GET", `/api/threads/… + 215| .toEqual(expect.arrayContaining([expect.objectContaining({ role:… + | ^ + 216| tool: expect.objectContaining({ ok: false, name: "error: Fixtu… + 217| expect(fake.calls.filter(call => call.path.startsWith("/v1/machine… + +Caused by: Error: Matcher did not succeed in time. + ❯ server/instabox/core.e2e.test.ts:214:5 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 14 skipped (15) + Start at 06:55:22 + Duration 28.38s (transform 1.26s, setup 740ms, import 948ms, tests 26.57s, environment 0ms) + + +Exit code: 1 (expected 1) + +===== core-1 ===== +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 06:56:09 + Duration 59.36s (transform 1.50s, setup 952ms, import 1.04s, tests 57.24s, environment 0ms) + + +Exit code: 0 + +===== core-2 ===== +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 06:57:09 + Duration 63.22s (transform 2.06s, setup 1.26s, import 1.43s, tests 60.38s, environment 0ms) + + +Exit code: 0 + +===== core-3 ===== +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 06:58:13 + Duration 68.61s (transform 2.74s, setup 1.58s, import 1.90s, tests 64.91s, environment 0ms) + + +Exit code: 0 + +===== environment ===== +$ pnpm exec vitest run scripts/control-cry.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 10 passed (10) + Start at 06:59:22 + Duration 3.07s (transform 2.20s, setup 1.48s, import 1.33s, tests 16ms, environment 0ms) + + +Exit code: 0 + +===== launcher-1 ===== +$ pnpm exec vitest run server/control-cry.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + ❯ server/control-cry.test.ts (20 tests | 1 failed) 11244ms + × launches, drives a real fake-engine turn, and removes only its test data 2624ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL server/control-cry.test.ts > control-cry isolated verification loop > launches, drives a real fake-engine turn, and removes only its test data +AssertionError: expected [ 'claude', 'chatgpt' ] to deeply equal [ 'claude' ] + +- Expected ++ Received + + [ + "claude", ++ "chatgpt", + ] + + ❯ server/control-cry.test.ts:261:39 + 259| const doctor = await runControlCry(["doctor"], { env }) as any; + 260| expect(doctor.ok).toBe(true); + 261| expect(doctor.availableEngines).toEqual(["claude"]); + | ^ + 262| + 263| const created = await runControlCry(["new-bot", "--name", "Verif… + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 19 passed (20) + Start at 06:59:26 + Duration 14.03s (transform 2.06s, setup 1.33s, import 1.28s, tests 11.24s, environment 0ms) + + +Exit code: 1 + +===== launcher-baseline ===== +Baseline check: scripts/control-cry.ts temporarily restored from HEAD. +$ pnpm exec vitest run server/control-cry.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + ❯ server/control-cry.test.ts (20 tests | 1 failed) 10821ms + × launches, drives a real fake-engine turn, and removes only its test data 2617ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL server/control-cry.test.ts > control-cry isolated verification loop > launches, drives a real fake-engine turn, and removes only its test data +AssertionError: expected [ 'claude', 'chatgpt' ] to deeply equal [ 'claude' ] + +- Expected ++ Received + + [ + "claude", ++ "chatgpt", + ] + + ❯ server/control-cry.test.ts:261:39 + 259| const doctor = await runControlCry(["doctor"], { env }) as any; + 260| expect(doctor.ok).toBe(true); + 261| expect(doctor.availableEngines).toEqual(["claude"]); + | ^ + 262| + 263| const created = await runControlCry(["new-bot", "--name", "Verif… + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 19 passed (20) + Start at 07:00:07 + Duration 13.83s (transform 2.24s, setup 1.44s, import 1.37s, tests 10.82s, environment 0ms) + + +Exit code: 1 + +===== backend ===== +$ pnpm exec vitest run server/cloud-backend.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 12 passed (12) + Start at 07:00:22 + Duration 1.50s (transform 1.02s, setup 1.29s, import 39ms, tests 5ms, environment 0ms) + + +Exit code: 0 + +===== index ===== +$ 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 07:00:24 + Duration 161.98s (transform 2.15s, setup 1.18s, import 1.91s, tests 158.71s, environment 0ms) + + +Exit code: 0 + +===== size ===== +$ 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 07:03:07 + Duration 1.49s (transform 699ms, setup 903ms, import 9ms, tests 441ms, environment 0ms) + + +Exit code: 0 + +===== tsc ===== +$ pnpm exec tsc -p tsconfig.server.json + +Exit code: 0 + +===== oxlint ===== +$ pnpm exec oxlint --deny-warnings scripts/control-cry.ts scripts/control-cry.test.ts server/instabox/core.e2e.test.ts + +Exit code: 0 + +===== diff-check ===== +$ git diff --check + +Exit code: 0 + +Mutation self-check: expected refusal assertion failed after replacing the cloud wantedKind branch with undefined. server/index.ts restored; no final diff. +Launcher baseline check: the same extra chatgpt engine failed the exact same assertion with scripts/control-cry.ts restored from HEAD. Round 5 changes restored afterward. diff --git a/scripts/control-cry.test.ts b/scripts/control-cry.test.ts index 43d4f6be..06a8c6af 100644 --- a/scripts/control-cry.test.ts +++ b/scripts/control-cry.test.ts @@ -42,6 +42,19 @@ describe("the fixture's Netlify stand-in", () => { }); }); +describe("the fixture's InstaBox stand-in", () => { + it("passes the key only with a validated loopback API address", () => { + expect(childEnv({ CRYBOT_TEST_INSTABOX_API: " http://127.0.0.1:4100 ", INSTABOX_API_KEY: "instabox-fixture-key" })) + .toMatchObject({ CRYBOT_TEST_INSTABOX_API: "http://127.0.0.1:4100", INSTABOX_API_KEY: "instabox-fixture-key" }); + for (const url of [undefined, "", "https://api.instabox.sh", "http://localhost:4100", "http://127.0.0.1:4100/v1", "http://127.0.0.1:4100@evil.test", "http://192.0.2.1:4100"]) { + const env = childEnv({ CRYBOT_TEST_INSTABOX_API: url, INSTABOX_API_KEY: "must-not-reach-the-fixture" }); + expect(env, url).not.toHaveProperty("CRYBOT_TEST_INSTABOX_API"); + expect(env, url).not.toHaveProperty("INSTABOX_API_KEY"); + } + expect(childEnv({ CRYBOT_TEST_INSTABOX_API: "http://127.0.0.1:4100" })).not.toHaveProperty("INSTABOX_API_KEY"); + }); +}); + describe("the fixture's Live call environment", () => { it("passes a loopback fake GPT-Live and its key through", () => { expect(childEnv({ CRYBOT_OPENAI_LIVE_URL: " http://127.0.0.1:4100 ", CRYBOT_OPENAI_LIVE_KEY: "sk-fake" })) diff --git a/scripts/control-cry.ts b/scripts/control-cry.ts index 77727e62..b4b41928 100644 --- a/scripts/control-cry.ts +++ b/scripts/control-cry.ts @@ -216,6 +216,11 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data // @devs reports reach a loopback fake only, else a closed port: never the CryBot team. const bugReportUrl = parentEnv.CRYBOT_BUG_REPORT_URL?.trim() ?? ""; childEnv.CRYBOT_BUG_REPORT_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/[A-Za-z0-9/_-]*$/.test(bugReportUrl) ? bugReportUrl : "http://127.0.0.1:9/api/bug-reports"; + const instaboxFixture = parentEnv.CRYBOT_TEST_INSTABOX_API?.trim() ?? ""; + if (/^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(instaboxFixture)) { + childEnv.CRYBOT_TEST_INSTABOX_API = instaboxFixture; + if (parentEnv.INSTABOX_API_KEY) childEnv.INSTABOX_API_KEY = parentEnv.INSTABOX_API_KEY; + } const tregUrl = parentEnv.CRYBOT_TREG_URL?.trim() ?? ""; if (/^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(tregUrl)) childEnv.CRYBOT_TREG_URL = tregUrl; // Loopback only, for harness mechanics: a fake ElevenLabs the measurement @@ -254,6 +259,8 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data childEnv.CRYBOT_DESKTOP_PARENT = "1"; if (parentEnv.CRYBOT_TEST_DESKTOP_PAGES_ACCESS) childEnv.CRYBOT_TEST_DESKTOP_PAGES_ACCESS = parentEnv.CRYBOT_TEST_DESKTOP_PAGES_ACCESS; if (parentEnv.CRYBOT_TEST_DESKTOP_TAILNET_SHARE) childEnv.CRYBOT_TEST_DESKTOP_TAILNET_SHARE = parentEnv.CRYBOT_TEST_DESKTOP_TAILNET_SHARE; + if (parentEnv.CRYBOT_TEST_DESKTOP_POLICY) childEnv.CRYBOT_TEST_DESKTOP_POLICY = parentEnv.CRYBOT_TEST_DESKTOP_POLICY; + if (parentEnv.CRYBOT_TEST_DESKTOP_POLICY_DELAY_MS) childEnv.CRYBOT_TEST_DESKTOP_POLICY_DELAY_MS = parentEnv.CRYBOT_TEST_DESKTOP_POLICY_DELAY_MS; } // The driver record the app hands its own server: without it, no server may use this computer. if (parentEnv.CRYBOT_TEST_DESKTOP_CUA_CONNECTION) childEnv.CRYBOT_TEST_DESKTOP_CUA_CONNECTION = parentEnv.CRYBOT_TEST_DESKTOP_CUA_CONNECTION; @@ -432,7 +439,7 @@ export async function launchVerificationServer( const renameTimeout = AbortSignal.timeout(Math.max(1, deadline - Date.now())); const rename = await fetch(`${url}/api/bots/${seeded[0].id}/profile`, { method: "PATCH", - headers: { "content-type": "application/json", origin: url }, + headers: { "content-type": "application/json", origin: url, ...(parentEnv.CRYBOT_TEST_DESKTOP_OWNER_TOKEN ? { "x-crybot-desktop-owner": parentEnv.CRYBOT_TEST_DESKTOP_OWNER_TOKEN } : {}) }, body: JSON.stringify({ name: FIXTURE_STARTER_BOT_NAME }), signal: signal ? AbortSignal.any([signal, renameTimeout]) : renameTimeout, }); diff --git a/scripts/public-scan/allow-domains.txt b/scripts/public-scan/allow-domains.txt index a081eed8..c5a6c029 100644 --- a/scripts/public-scan/allow-domains.txt +++ b/scripts/public-scan/allow-domains.txt @@ -1,4 +1,5 @@ # Public domains needed by open-source licenses and official documentation. +instabox.sh # InstaBox 云电脑公共 API(第三方公开服务)。 apple.com developer.apple.com swift.org diff --git a/server/cloud-backend.test.ts b/server/cloud-backend.test.ts index bf41ed85..3d489188 100644 --- a/server/cloud-backend.test.ts +++ b/server/cloud-backend.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { + cloudKindOf, cloudPolicyKindOf, BOAT_ACCOUNT_RESOURCES_ERROR, CLOUD_BACKEND_CHANGE_ERROR, VPS_ALIAS_RESOURCES_ERROR, @@ -47,3 +48,11 @@ describe("cloud backend switching", () => { expect(vpsBotAliasChangeError(false, false)).toBeNull(); }); }); + +describe("cloud kind selection", () => { + it.each([undefined, "box", "vps", "instabox"] as const)("selects %s without falling back and preserves team Boat", backend => { + expect(cloudKindOf({ cloudBackend: backend })).toBe(backend ?? "box"); + expect(cloudKindOf({ cloudBackend: backend }, true)).toBe("box"); + expect(cloudPolicyKindOf({ cloudBackend: backend })).toBe(backend === "instabox" ? "box" : backend ?? "box"); + }); +}); diff --git a/server/cloud-backend.ts b/server/cloud-backend.ts index 2873c464..b31d362a 100644 --- a/server/cloud-backend.ts +++ b/server/cloud-backend.ts @@ -1,3 +1,9 @@ +import type { CloudBackend } from "../shared/wire.ts"; + +export function cloudKindOf(bot: { cloudBackend?: CloudBackend }, teamComputer = false): CloudBackend { + return teamComputer ? "box" : bot.cloudBackend ?? "box"; +} + export const CLOUD_BACKEND_CHANGE_ERROR = "stop the active turn before changing the cloud backend"; export const BOAT_ACCOUNT_RESOURCES_ERROR = "remove this installation's cloud computers before changing or clearing the Boat account"; @@ -48,3 +54,8 @@ export function boatAccountResourceChangeError( export function vpsAliasResourceChangeError(instanceCount: number): string | null { return instanceCount > 0 ? VPS_ALIAS_RESOURCES_ERROR : null; } + +export function cloudPolicyKindOf(bot: { cloudBackend?: CloudBackend }, teamComputer = false): "box" | "vps" { + const kind = cloudKindOf(bot, teamComputer); + return kind === "instabox" ? "box" : kind; +} diff --git a/server/config.ts b/server/config.ts index 5222995e..dea0a0fe 100644 --- a/server/config.ts +++ b/server/config.ts @@ -348,6 +348,7 @@ const appConfigSchema = z.object({ composio: z.object({ apiKey: optionalText, userId: optionalText, sessionId: optionalText }).optional(), box: z.object({ token: optionalText }).optional(), vps: vpsConfigSchema.optional(), + instabox: z.object({ apiKey: z.string().optional() }).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(), /** `provider`: "elevenlabs" (default, `key`), "fish" (`fishKey`, `fishModel`), "system", "xai" (`xai.key`), "gemini" (`geminiKey`, `model`), "openai" (`openai.key`) or "chatterbox" (local; `baseUrl`, `model`). */ @@ -456,6 +457,7 @@ export interface AppConfig extends HelperConfig { box?: { token?: string }; /** A named host from the user's SSH config. Authentication stays with SSH. */ vps?: { sshAlias?: string }; + instabox?: { apiKey?: string }; opencodeGo?: { apiKey?: string; providerKeys?: Record }; tts?: { key?: string; fishKey?: string; geminiKey?: string; voice?: string; provider?: "elevenlabs" | "fish" | "system" | "chatterbox" | "xai" | "gemini" | "openai"; baseUrl?: string; model?: string; fishModel?: FishTtsModel; everyReply?: boolean }; decider?: DeciderConfig; @@ -816,7 +818,12 @@ export function syncCredentialEnv(patch: Partial): void { stripBaseControlPlaneEnv(env); stripInstaboxCredentialEnv(env); } +function stripWorkspaceCredentialEnv(env: Record): void { stripBaseWorkspaceCredentialEnv(env); stripInstaboxCredentialEnv(env); } export { WORKSPACE_CREDENTIAL_ENV, CONTROL_PLANE_ENV, CONTROL_PLANE_ENV_PREFIX, stripControlPlaneEnv, stripWorkspaceCredentialEnv, PROVIDER_CREDENTIAL_ENV, OPENCODE_PROVIDER_ENV }; export const OPENCODE_PROVIDER_KEY_LIMIT = 20; @@ -894,7 +901,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/index.ts b/server/index.ts index 6013db48..6fae2e1b 100644 --- a/server/index.ts +++ b/server/index.ts @@ -124,14 +124,18 @@ import { createDataRoutes } from "./data/routes.ts"; import { DataSheetRegistry } from "./data/sheet.ts"; import { DataFailure } from "./data/types.ts"; import { TeamComputers, teamComputerOwner, type TeamComputerRecord } from "./team-computers.ts"; -import { isEffortLevel, type CardAnswerer, type ResolvedSender, type SignInRequestCardData, type WireBot, type WireGroup, type WireTask } from "../shared/wire.ts"; +import { isEffortLevel, type CloudBackend, type CardAnswerer, type ResolvedSender, type SignInRequestCardData, type WireBot, type WireGroup, type WireTask } from "../shared/wire.ts"; import { isPersistentQuestionCard, shouldSettleRequestCard } from "../shared/ask-question.ts"; import { parseToolScope } from "../shared/tool-scope.ts"; import type { TeamComputersPayload } from "../shared/team-computer.ts"; import { boatCreateRecoverySnapshot } from "./boat-create-idempotency.ts"; import { boatDeletionSnapshot } from "./boat-delete-journal.ts"; import { liveDecisionRefusal } from "../shared/live-approval.ts"; import type { PersonWaitKind } from "../shared/person-wait.ts"; -import { vpsLeftBehindNotice } from "./cloud-backend.ts"; +import { cloudKindOf, cloudPolicyKindOf, vpsLeftBehindNotice } from "./cloud-backend.ts"; +import { createInstaboxRequest } from "./instabox/client.ts"; +import { instaboxConfigured } from "./instabox/key.ts"; +import type { InstaboxMachines } from "./instabox/machine.ts"; +import { createInstaboxMachineCache, instaboxComputerAction, instaboxFailureResponse, instaboxStatus, requireInstabox, withInstaboxBackendPower } from "./instabox/power.ts"; import * as composio from "./composio.ts"; import { appSandboxRule, connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts"; import { signInCardText } from "./connector-card-text.ts"; @@ -1888,12 +1892,12 @@ function clearFailedAutoPin(botId: string, threadId: string, place: Surface): bo } async function asPlaceFailure( - error: unknown, place: Surface, source: PlaceSource, bot: { id: string; name: string }, backend: "box" | "vps" = "box", + error: unknown, place: Surface, source: PlaceSource, bot: { id: string; name: string }, backend: "box" | "vps" | "instabox" = "box", ): Promise { if (error instanceof DirectTurnSetupCancelled || error instanceof ComputerWaitParked || error instanceof PlaceUnavailableError) return error; const failure = error instanceof Error ? error : new Error(String(error)); const cause = failure.message.trim().replace(/[\s.]+$/, ""); - if (place !== "cloud" || backend === "vps" || (failure as { code?: unknown }).code === "managed_policy") { + if (place !== "cloud" || backend !== "box" || (failure as { code?: unknown }).code === "managed_policy") { return placeUnavailable(place, { state: "place-failed", params: { bot: bot.name, cause: `${cause.charAt(0).toUpperCase()}${cause.slice(1)}.` }, source, }, Boolean(CLOUD_HOME)); @@ -2515,7 +2519,7 @@ async function moveOffComputerEngine(): Promise { const moves = store.retireInstances(removed, replacement, { driverKind: instance?.driverKind, canWorkOnCloud: canWorkOnCloud(cloudEngine(instance)), - keepCloud: (bot) => boat.boatConfigured(cfg) && bot.cloudBackend !== "vps" && !inheritedTeamComputer(bot), + keepCloud: (bot) => !inheritedTeamComputer(bot) && (cloudKindOf(bot) === "instabox" ? instaboxConfigured(cfg) : cloudKindOf(bot) === "box" && boat.boatConfigured(cfg)), }); writeComputerEngineMoveLines(moves, (move) => { const bot = store.bot(move.botId); @@ -2912,7 +2916,7 @@ function previewSystemPrompt(bot: BotRecord) { const previewComputer = teamComputer ? "cloud" : bot.computer; const computerPromptKind = resolveComputerPromptKind({ kind: previewComputer === "vm" ? "vm" : previewComputer === "cloud" - ? bot.cloudBackend === "vps" ? "vps" : "box" : previewComputer === "local" ? "local" : null, + ? cloudPolicyKindOf(bot, Boolean(teamComputer)) ?? null : previewComputer === "local" ? "local" : null, vmPrivate: localVmMode(cfg) === "per-bot", }); const peers = reachablePeers(store.bots, bot); @@ -5615,6 +5619,9 @@ const computerPreviews = createComputerPreviews(); const vpsJoinRequests = new Map>(); const orphanBoatLifecycleBusyIds = new Set(); const boatInventoryRequestsBusyIds = new Set(); +const cachedInstaboxMachines = createInstaboxMachineCache(key => createInstaboxRequest(key, + /^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}$/.test(process.env.CRYBOT_TEST_INSTABOX_API ?? "") ? process.env.CRYBOT_TEST_INSTABOX_API : undefined)); +function instaboxMachinesFor(cfg: AppConfig): InstaboxMachines | null { return cachedInstaboxMachines(cfg); } type RemoteComputerProvider = "box" | "vps"; const computerProviderConfigTransitions = new Set(); const localVmIdleMs = () => localVmIdleTimeoutMinutes(cfg) * 60_000; @@ -5948,11 +5955,12 @@ function turnSurfacePlan(bot: BotRecord, runOn?: RoutineRunOn, threadId?: string }); } -function turnProvider(bot: BotRecord, runOn?: RoutineRunOn, threadId?: string): RemoteComputerProvider | null { - if (runOn === "cloud" || inheritedTeamComputer(bot)) return "box"; +function turnProvider(bot: BotRecord, runOn?: RoutineRunOn, threadId?: string): CloudBackend | null { + if (inheritedTeamComputer(bot)) return "box"; + const cloudBackend = cloudKindOf(bot, Boolean(inheritedTeamComputer(bot)) || runOn === "cloud"); const wants = turnSurfacePlan(bot, runOn, threadId).computer; if (wants !== undefined && wants !== "cloud") return null; - return bot.cloudBackend === "vps" ? "vps" : wants === "cloud" ? "box" : null; + return cloudBackend !== "box" || wants === "cloud" ? cloudBackend : null; } /** A query never grants lifecycle authority. */ @@ -5968,6 +5976,7 @@ async function computerPreviewSurface(bot: BotRecord, threadId?: string) { const plan = turnSurfacePlan(bot, undefined, threadId); if (plan.computer !== undefined) return plan.computer === "off" && plan.browser ? "browser" : plan.computer; const instance = registry.get(bot.modelSelection.instanceId); + if (cloudKindOf(bot) === "instabox") return "cloud"; if (bot.cloudBackend === "vps") { const remote = await vps.vpsComputerStatus(vpsConfigForBot(cfg, bot), bot.id); if (remote.ready || vpsDesktopOutdated(remote)) return "cloud"; @@ -5990,7 +5999,7 @@ async function selectableComputers(bot: BotRecord) { const caps = instance?.adapter.capabilities; const off = bot.computer === "off"; const toolsLeaveOut = computerToolsRefusal(bot.toolScope, "works-on", bot.name)?.message; - const surfaces = (["cloud", "vm", "local", "browser"] as const).filter(surface => (surface !== "cloud" || bot.cloudBackend === "vps" || !providerLockEnabled()) && (!CLOUD_HOME || cloudHomeOffersPlace(surface))); + const surfaces = (["cloud", "vm", "local", "browser"] as const).filter(surface => (surface !== "cloud" || cloudKindOf(bot, Boolean(inheritedTeamComputer(bot))) !== "box" || !providerLockEnabled()) && (!CLOUD_HOME || cloudHomeOffersPlace(surface))); let ownDesktopAwaitsUpdate = false; return withoutHostWhileUpdating(await Promise.all(surfaces.map(async surface => { let ready = false; @@ -6003,7 +6012,12 @@ async function selectableComputers(bot: BotRecord) { if (off) reason = "Computer access is Off in this bot's settings."; else if (toolsLeaveOut && surface !== "browser") reason = toolsLeaveOut; else if (surface === "cloud") { - if (bot.cloudBackend === "vps") { + if (cloudKindOf(bot, Boolean(inheritedTeamComputer(bot))) === "instabox") { + const status = await instaboxStatus(instaboxMachinesFor(cfg), bot.id); + ready = status.ready; canCreate = status.configured && !status.machine; + canStart = status.machine?.state === "suspended" || status.machine?.state === "stopped"; + reason = status.problem ?? reason; + } else if (bot.cloudBackend === "vps") { const status = canWorkOnCloud(cloudEngine(instance)) ? await vps.vpsComputerStatus(vpsConfigForBot(cfg, bot), bot.id) : null; ready = status?.ready === true; canStart = Boolean(status?.daemonUp && status.managed && status.container === "stopped" && @@ -6040,7 +6054,7 @@ async function selectableComputers(bot: BotRecord) { reason = "The built-in browser is disabled, not installed, or unsupported by this model."; } } catch (error) { reason = error instanceof Error ? error.message : String(error); } - const kind = surface === "local" ? "thisComputer" : surface === "vm" ? "localVm" : surface === "cloud" ? (bot.cloudBackend === "vps" ? "vps" : "box") : undefined; + const kind = surface === "local" ? "thisComputer" : surface === "vm" ? "localVm" : surface === "cloud" ? cloudPolicyKindOf(bot, Boolean(inheritedTeamComputer(bot))) : undefined; const managed = kind && managedPolicy.computerRefusal(kind); if (managed) return { surface, label: surfaceLabel(surface), available: false, ready: false, canStart: false, canCreate: false, reason: managed }; const available = ready || canStart || canCreate; @@ -6106,7 +6120,7 @@ function providerTransitionForTurn( threadId?: string, ): string | null { const provider = turnProvider(bot, runOn, threadId); - return provider && computerProviderConfigTransitions.has(provider) + return provider && provider !== "instabox" && computerProviderConfigTransitions.has(provider) ? providerTransitionMessage(provider) : null; } @@ -7899,7 +7913,7 @@ async function beginTurn( const dwebUrl = process.env.DWEB_URL?.trim(); if (dwebUrl) integrations.dweb = { url: dwebUrl }; let teamComputer = computerSkipped || proactive.fence.confines(threadId) || botApiThread(threadId) ? undefined : inheritedTeamComputer(bot); - const cloudBackend = teamComputer || opts?.runOn === "cloud" || bot.cloudBackend !== "vps" ? "box" : "vps"; + const cloudBackend = cloudKindOf(bot, Boolean(teamComputer) || opts?.runOn === "cloud"); const mountsComputerMcp = instance.adapter.capabilities.computerMcp === true; const mountsLocalComputer = instance.adapter.capabilities.localComputerMcp === true; const dispatchTask = store.taskByThread(bot.id, threadId); @@ -7916,7 +7930,7 @@ async function beginTurn( releaseTurnComputer(resourceOwner); }; const wantedKind = teamComputer ? "box" : wants === "local" ? "thisComputer" : wants === "vm" ? "localVm" - : wants === "cloud" ? (cloudBackend === "vps" ? "vps" : "box") : undefined; + : wants === "cloud" ? cloudPolicyKindOf({ cloudBackend }) : undefined; const placeRefusal = wantedKind && computerPlaceRefusal(wantedKind); if (placeRefusal) skipComputer(Object.assign(new Error(placeRefusal.message), { status: 409, code: placeRefusal.code })); const namedPlace = teamComputer || wants === undefined || wants === "off" ? undefined : wants; @@ -8187,6 +8201,9 @@ async function beginTurn( integrations.localComputer = mountTeamBoat(teamComputer, bot.id, resourceOwner, canWorkOnCloud(cloudEngine(instance)), { onClaimed: adoptClaimedCapture, onRejected: surfaceLazyClaimRejection("the team's cloud computer") }); computerKind = "box"; } + if (!teamComputer && cloudBackend === "instabox" && wants === "cloud") { + await requireInstabox(instaboxMachinesFor(cfg)).ensureRunning(bot.id); + } if (!teamComputer && cloudBackend === "box" && boat.boatOffered(cfg) && wants === "cloud") { integrations.localComputer = mountBotBoat(bot, resourceOwner, { source: placeSource, @@ -9028,7 +9045,7 @@ async function deleteBotWithLifecycle(botId: string, revalidate: () => void = () error: `stop this bot's work in channel ${activeGroup.group.name} before deleting the bot`, }); } - if ((boat.boatConfigured(cfg) || vpsSshAliasForBot(cfg, bot)) && (bot.busy || hasDirectDispatch(bot.id))) { + if ((cloudKindOf(bot) === "instabox" || boat.boatConfigured(cfg) || vpsSshAliasForBot(cfg, bot)) && (bot.busy || hasDirectDispatch(bot.id))) { return deletionResponse( 409, { error: "stop this bot's work before checking and deleting its cloud computer" }); } const botBoatRecovery = boatCreateRecoverySnapshot().filter((entry) => entry.botId === bot.id); @@ -9097,7 +9114,19 @@ async function deleteBotWithLifecycle(botId: string, revalidate: () => void = () // Revalidate, re-check a person's holds (one may have come through another bot meanwhile) and record the browser cleanup intent before the first irreversible provider mutation. revalidate(); const heldNow = sharedVm.deletionRefusal(bot.id); if (heldNow) return deletionResponse(409, { error: heldNow }); const browserCleanupRequest = browserCleanup.prepare("bot", bot.id); + let instaboxNotice: string | undefined; try { + const instabox = instaboxMachinesFor(cfg); + const botCloudKind = cloudKindOf(bot); + try { + if (botCloudKind === "instabox") await requireInstabox(instabox).remove(bot.id); + else await instabox?.remove(bot.id); + } catch (error) { + if (botCloudKind === "instabox") { + throw Object.assign(new Error(`InstaBox failed to delete this bot's machine: ${error instanceof Error ? error.message : String(error)}. The bot was kept so deletion can be retried`), { status: 503 }); + } + instaboxNotice = `InstaBox could not be reached, so this bot's InstaBox machine, if it is still there, was left as it is.`; + } for (const instance of ownedBoatComputers) { const removed = await boat.deleteManagedBoat(cfg, managedBoatOwners(), instance.boxId, instance.name); if (removed.pending) { @@ -9159,7 +9188,11 @@ async function deleteBotWithLifecycle(botId: string, revalidate: () => void = () const acknowledged = await browserCleanup.ensure(committedCleanup); requireBrowserCleanupAcknowledged(acknowledged, `Browser data for ${bot.name}`); } - return deletionResponse(200, { ok: true, ...(vpsLeftOn ? { notice: vpsLeftBehindNotice("Deleted", vpsLeftOn, vps.vpsContainerName(bot.id)) } : {}) }); + const notices = [ + vpsLeftOn ? vpsLeftBehindNotice("Deleted", vpsLeftOn, vps.vpsContainerName(bot.id)) : undefined, + instaboxNotice, + ].filter((notice): notice is string => Boolean(notice)); + return deletionResponse(200, { ok: true, ...(notices.length ? { notice: notices.join(" ") } : {}) }); } finally { if (claimedLocalVmTarget) localVmLifecycleBusy.delete(claimedLocalVmTarget.key); releaseComputerLifecycle(); @@ -9963,7 +9996,7 @@ async function runClaimedGroupMemberTurn( instance.adapter.capabilities.browserMcp === true, }); const roomKind = roomTeamComputer ? "box" : roomPlan.computer === "local" ? "thisComputer" : readyBot.computer === "vm" ? "localVm" - : roomPlan.computer === "cloud" ? (turnProvider(readyBot) === "vps" ? "vps" : "box") : undefined; + : roomPlan.computer === "cloud" ? cloudPolicyKindOf(readyBot, Boolean(roomTeamComputer)) : undefined; const roomPlaceRefusal = roomKind && computerPlaceRefusal(roomKind); if (roomPlaceRefusal) throw Object.assign(new Error(roomPlaceRefusal.message), { code: roomPlaceRefusal.code }); if (!roomTeamComputer && roomPlan.computer === "cloud") { @@ -10029,7 +10062,9 @@ async function runClaimedGroupMemberTurn( roomComputerKind = "local"; } if (!roomTeamComputer && roomPlan.computer === "cloud") { - if (turnProvider(readyBot) === "vps") { + if (turnProvider(readyBot) === "instabox") { + await requireInstabox(instaboxMachinesFor(cfg)).ensureRunning(readyBot.id); + } else if (turnProvider(readyBot) === "vps") { vpsThreadStarted(readyBot.id, threadId); roomVpsBotId = readyBot.id; const mounted = await mountBotVps(readyBot, resourceOwner, { start: true, onClaimed: showClaimedScreen }); @@ -10087,7 +10122,7 @@ async function runClaimedGroupMemberTurn( } catch (error) { const place = roomPlan.computer; if (place !== "cloud" && place !== "vm" && place !== "local") throw error; - throw await asPlaceFailure(error, place, "room", readyBot, turnProvider(readyBot) === "vps" ? "vps" : "box"); + throw await asPlaceFailure(error, place, "room", readyBot, turnProvider(readyBot) ?? "box"); } const roomMembers = readyGroup.memberIds @@ -12134,14 +12169,14 @@ ROUTES.push(createBotSettingsRoutes({ canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread, })); ROUTES.push(createGroupOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)) }), createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }), createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), shared: createShareNotice({ people: () => teamOwners.people?.list() ?? [], profileName: (email) => sessionNameForEmail(email) ?? teamHost.people.profile(personKey({ id: "", email })).name, store: () => store, inbox: () => teamMessages.inbox }) }), accessRequests.routes); -ROUTES.push(createBotPatchRoutes({ +ROUTES.push(withInstaboxBackendPower(createBotPatchRoutes({ store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode, routines: () => routines, activeVpsThreads, hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED, broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot, checkedModelSelection, engineSwitchNeedsAsk, currentBrowserSession, interruptAllDirectThreads, cancelGroupTurnOperations, revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser, levelOf, team: Boolean(CLOUD_TEAM), mainThreadTasks, chiefChanged: (changed) => chiefRooms.moved(changed), ...(personRooms.personMarkThread ? { personMarkThread: personRooms.personMarkThread, shownThread: (auth: RequestAuth, bot: BotRecord) => memberBot(wireBot(bot), visibleTo(viewerFor(auth))).threadId } : {}), -})); +}), { bot: id => store.bot(id), machines: () => instaboxMachinesFor(cfg) })); ROUTES.push(createBotLifecycleRoutes({ store, routines: () => routines, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread, activeGroupTurnForBot, cancelGroupTurnOperations, runningTurnInstance, closeOpenApprovals, deleteBotWithLifecycle, deleteRefusal: (auth, botId) => memberDeleteRefusal(auth, store.bot(botId), Boolean(CLOUD_TEAM)), @@ -14992,9 +15027,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => { const bot = computerPreviewBot(m[1], url); if (!bot) return json(res, 404, { error: "no such bot" }); const surface = url.searchParams.has("threadId") ? await computerPreviewSurface(bot, bot.threadId) : "cloud"; - if (surface !== "cloud") return json(res, 200, { surface, configured: false, backend: bot.cloudBackend === "vps" ? "vps" : "box" }); + if (surface !== "cloud") return json(res, 200, { surface, configured: false, backend: cloudKindOf(bot, Boolean(inheritedTeamComputer(bot))) }); const teamComputer = inheritedTeamComputer(bot); if (teamComputer) return json(res, 200, { surface, backend: "box", teamComputer: { id: teamComputer.id, name: teamComputer.name }, ...(await boat.boatStatus(cfg, teamComputerOwner(teamComputer.id))) }); + if (cloudKindOf(bot) === "instabox") return json(res, 200, { surface, ...await instaboxStatus(instaboxMachinesFor(cfg), bot.id) }); return bot.cloudBackend === "vps" ? json(res, 200, { surface, backend: "vps", ...(await vps.vpsComputerStatus(vpsConfigForBot(cfg, bot), bot.id)) }) : json(res, 200, { surface, backend: "box", ...(await boat.boatStatus(cfg, bot.id)) }); @@ -15083,8 +15119,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => { if (m[2] === "join" && bot.cloudBackend === "vps") { for (let pending; (pending = vpsJoinRequests.get(botId));) await pending; } - const remoteProvider: RemoteComputerProvider = bot.cloudBackend === "vps" ? "vps" : "box"; - if (computerProviderConfigTransitions.has(remoteProvider)) { + const remoteProvider = cloudKindOf(bot, Boolean(inheritedTeamComputer(bot))); + if (remoteProvider !== "instabox" && computerProviderConfigTransitions.has(remoteProvider)) { return json(res, 409, { error: providerTransitionMessage(remoteProvider) }); } if (boatLifecycleBusyBots.has(botId)) { @@ -15108,6 +15144,13 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => { return json(res, 200, await boat.sleepBoat(cfg, key)); } finally { release(); if (m[2] !== "sleep") cloudComputerPower.used(key); } } + if (remoteProvider === "instabox") { + if (botHasActiveTurn(botId) && ["provision", "sleep", "remove"].includes(m[2])) return json(res, 409, { error: CLOUD_COMPUTER_BUSY_ERROR }); + const release = claimBotComputerLifecycle(botId, m[2] === "join"); + try { return json(res, 200, await instaboxComputerAction(instaboxMachinesFor(cfg), botId, m[2], await readBody(req))); } + catch (error) { const failure = instaboxFailureResponse(error); return json(res, failure.status, failure.body); } + finally { release(); } + } if (bot.cloudBackend === "vps") { if (m[2] === "screenshot") { res.setHeader("cache-control", "private, no-store"); diff --git a/server/instabox/client.test.ts b/server/instabox/client.test.ts new file mode 100644 index 00000000..28ee62b4 --- /dev/null +++ b/server/instabox/client.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { fakeInstaboxCore } from "../testing/fake-instabox-core.ts"; +import { createInstaboxRequest, InstaboxError, instaboxVncUpstream, waitOperation } from "./client.ts"; + +let fake: Awaited>; +beforeEach(async () => { fake = await fakeInstaboxCore(); }); +afterEach(async () => { vi.restoreAllMocks(); await fake.close(); }); + +it("authenticates and gives each lifecycle call its own idempotency key", async () => { + const request = createInstaboxRequest("fixture-key", fake.url); + await request("GET", "/v1/machines", { query: { name: "crybot-test" } }); + await request("POST", "/v1/machines", { body: { name: "a" }, idempotent: true }); + await request("POST", "/v1/machines", { body: { name: "b" }, idempotent: true }); + expect(fake.calls[0].headers["x-api-key"]).toBe("fixture-key"); + expect(fake.calls[0].headers["idempotency-key"]).toBeUndefined(); + expect(fake.calls[0].query.get("name")).toBe("crybot-test"); + expect(fake.calls[1].headers["idempotency-key"]).toMatch(/^[a-f0-9-]{36}$/); + expect(fake.calls[1].headers["idempotency-key"]).not.toBe(fake.calls[2].headers["idempotency-key"]); +}); + +it("reports HTTP status and safe error codes without reflecting secrets or remote messages", async () => { + const request = createInstaboxRequest("fixture_secret", fake.url); + fake.failNext({ status: 403, code: "permission_denied", message: "fixture_secret" }); + await expect(request("GET", "/v1/machines")).rejects.toMatchObject({ status: 403, code: "permission_denied", message: "InstaBox HTTP 403: permission_denied" }); + fake.failNext({ status: 400, code: "fixture_secret" }); + await expect(request("GET", "/v1/machines")).rejects.toThrow("InstaBox HTTP 400: request_failed"); + vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("fixture_secret")); + await expect(request("GET", "/v1/machines")).rejects.toThrow(new InstaboxError(0, "network_error")); +}); + +it("rejects foreign origins before sending the key and refuses redirects", async () => { + const request = createInstaboxRequest("fixture-key", fake.url); + await expect(request("GET", "https://example.com")).rejects.toThrow("Invalid InstaBox API path"); + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}")); + await request("GET", "/v1/machines"); + expect(fetchSpy.mock.calls[0][1]?.redirect).toBe("error"); +}); + +it("waits with 25s polling, reports failure, and bounds a stalled request", async () => { + const request = createInstaboxRequest("fixture-key", fake.url); + const operation = await (await request("POST", "/v1/machines", { body: { name: "a" }, idempotent: true })).json() as { id: string }; + await waitOperation(request, operation.id, 1000); + expect(fake.calls.filter(call => call.path.includes("operations")).map(call => call.query.get("wait"))).toEqual(["25s", "25s"]); + fake.failOperations(); + await expect(waitOperation(request, operation.id, 1000)).rejects.toThrow("InstaBox operation failed"); + await expect(waitOperation(() => new Promise(() => {}), "op-stalled", 20)).rejects.toThrow("InstaBox operation timed out"); +}); + +it("keeps VNC credentials server-side and follows HTTPS and HTTP origins", () => { + expect(instaboxVncUpstream(createInstaboxRequest("fixture-key"), "a/b")).toEqual({ + url: "wss://api.instabox.sh/v1/machines/a%2Fb/vnc", headers: { "X-API-Key": "fixture-key" }, + }); + expect(instaboxVncUpstream(createInstaboxRequest("fixture-key", fake.url), "a").url).toBe(`${fake.url.replace("http:", "ws:")}/v1/machines/a/vnc`); +}); + +it("rejects malformed keys without including their value in errors", () => { + expect(() => createInstaboxRequest("fixture-secret\n" )).toThrow("Invalid InstaBox API key"); +}); diff --git a/server/instabox/client.ts b/server/instabox/client.ts new file mode 100644 index 00000000..b351f6f4 --- /dev/null +++ b/server/instabox/client.ts @@ -0,0 +1,82 @@ +import { randomUUID } from "node:crypto"; +import type { InstaboxRequest } from "./machine.ts"; + +const connections = new WeakMap(); + +export class InstaboxError extends Error { + readonly status: number; + readonly code: string; + constructor(status: number, code: string) { + super(`InstaBox HTTP ${status}: ${code}`); + this.name = "InstaboxError"; + this.status = status; + this.code = code; + } +} + +function errorCode(value: unknown, apiKey?: string): string { + return typeof value === "string" && /^[a-z][a-z0-9_]{0,79}$/.test(value) && (!apiKey || !value.includes(apiKey)) + ? value : "request_failed"; +} + +export function createInstaboxRequest(apiKey: string, baseUrl = "https://api.instabox.sh"): InstaboxRequest { + if (!apiKey || /[^\x21-\x7e]/.test(apiKey)) throw new Error("Invalid InstaBox API key"); + const origin = new URL(baseUrl); + const request: InstaboxRequest = async (method, path, opts = {}) => { + const url = new URL(path, origin); + if (url.origin !== origin.origin || url.username || url.password) throw new Error("Invalid InstaBox API path"); + for (const [name, value] of Object.entries(opts.query ?? {})) url.searchParams.set(name, value); + const headers = new Headers(opts.headers); + headers.set("X-API-Key", apiKey); + if (opts.idempotent) headers.set("Idempotency-Key", randomUUID()); + let body: string | Buffer | undefined; + if (opts.raw !== undefined) { + body = Buffer.from(opts.raw); + headers.set("Content-Type", "application/octet-stream"); + } else if (opts.body !== undefined) { + body = JSON.stringify(opts.body); + headers.set("Content-Type", "application/json"); + } + let response: Response; + try { + response = await fetch(url, { method: method.toUpperCase(), headers, ...(body === undefined ? {} : { body }), redirect: "error", signal: AbortSignal.timeout(650_000) }); + } catch { + throw new InstaboxError(0, "network_error"); + } + if (!response.ok) { + const detail = await response.json().catch(() => null) as { error?: { code?: unknown } | string; code?: unknown } | null; + throw new InstaboxError(response.status, errorCode((typeof detail?.error === "object" ? detail.error?.code : detail?.error) ?? detail?.code, apiKey)); + } + return response; + }; + connections.set(request, { baseUrl: origin.href, apiKey }); + return request; +} + +export function instaboxVncUpstream(request: InstaboxRequest, machineId: string) { + const connection = connections.get(request); + if (!connection) throw new Error("InstaBox connection metadata is unavailable"); + const url = new URL(`/v1/machines/${encodeURIComponent(machineId)}/vnc`, connection.baseUrl); + url.protocol = url.protocol === "http:" ? "ws:" : "wss:"; + return { url: url.href, headers: { "X-API-Key": connection.apiKey } }; +} + +export async function waitOperation(request: InstaboxRequest, opId: string, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + let timer: ReturnType | undefined; + try { + const operation = await Promise.race([ + request("GET", `/v1/operations/${encodeURIComponent(opId)}`, { query: { wait: "25s" } }).then(response => response.json()), + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error("InstaBox operation timed out")), deadline - Date.now()); + }), + ]) as { state: string }; + if (operation.state === "succeeded") return; + if (operation.state === "failed") throw new Error("InstaBox operation failed"); + } finally { + clearTimeout(timer); + } + } + throw new Error("InstaBox operation timed out"); +} diff --git a/server/instabox/core.e2e.test.ts b/server/instabox/core.e2e.test.ts new file mode 100644 index 00000000..62f716fd --- /dev/null +++ b/server/instabox/core.e2e.test.ts @@ -0,0 +1,419 @@ +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { randomBytes } from "node:crypto"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { expect, it } from "vitest"; +import { launchVerificationServer } from "../../scripts/control-cry.ts"; +import { launchRestartableServer } from "../testing/restartable-server.ts"; +import { fakeInstaboxCore } from "../testing/fake-instabox-core.ts"; +import { cloudPairingSignature } from "../cloud-home.ts"; +import { VPS_CONTAINER_LABEL, VPS_ENVIRONMENT_LABEL, VPS_MANAGED_LABEL, vpsContainerName } from "../vps-computer.ts"; + +const JPEG = Buffer.from("/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEA", "base64"); + +async function fakeBoatCore() { + const boats = new Map(); + const calls: Array<{ method: string; path: string; body: unknown }> = []; + let sequence = 0; + const server = createServer(async (req, res) => { + const url = new URL(req.url ?? "/", "http://fixture"); + let raw = ""; + for await (const chunk of req) raw += chunk; + const body = raw ? JSON.parse(raw) : undefined; + calls.push({ method: req.method ?? "GET", path: url.pathname, body }); + res.setHeader("content-type", "application/json"); + const reply = (status: number, value: unknown) => { res.writeHead(status); res.end(JSON.stringify(value)); }; + if (url.pathname === "/sandboxes" && req.method === "GET") return reply(200, { sandboxes: [...boats.values()] }); + if (url.pathname === "/sandboxes" && req.method === "POST") { + const id = ["bx_23456789", "bx_abcdefgh", "bx_jkmnpqrs"][sequence++] ?? "bx_23456789"; + boats.set(id, { id, name: `fixture-${id}`, state: "ready" }); + return reply(202, { sandbox: boats.get(id) }); + } + const match = /^\/sandboxes\/([^/]+)(?:\/(.*))?$/.exec(url.pathname); + if (!match) return reply(404, { error: "not found" }); + const boat = boats.get(match[1]!); + if (!boat) return reply(404, { error: "not found" }); + if (!match?.[2] && req.method === "GET") return reply(200, { sandbox: boat }); + if (!match?.[2] && req.method === "PATCH") { boat.name = String((body as { name?: unknown })?.name ?? boat.name); return reply(200, { sandbox: boat }); } + if (!match?.[2] && req.method === "DELETE") { boats.delete(boat.id); return reply(202, { ok: true }); } + if (match[2] === "desktop") return reply(200, { desktopUrl: "https://fixture.invalid/desktop" }); + if (match[2] === "commands") return reply(200, { exitCode: 0, stdout: "captured", stderr: "" }); + if (match[2] === "artifacts") { res.writeHead(200, { "content-type": "image/jpeg" }); return res.end(JPEG); } + if (match[2] === "files") return reply(200, { content: JPEG.toString("base64") }); + return reply(404, { error: "not found" }); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Fake Boat failed to listen"); + return { + url: `http://127.0.0.1:${address.port}`, + calls, + boats, + close: () => new Promise((resolve, reject) => { server.close(error => error ? reject(error) : resolve()); server.closeAllConnections(); }), + }; +} + +it("boots an isolated InstaBox bot, persists its backend, suspends on switching, and deletes its retained machine", async () => { + const fake = await fakeInstaboxCore(); + const env = { INSTABOX_API_KEY: "instabox-e2e-fixture", CRYBOT_TEST_INSTABOX_API: fake.url }; + const fixture = await launchRestartableServer({ env }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.url + path, { method, + headers: { origin: fixture.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(20_000), + }); + const result = { status: response.status, body: await response.json() as any }; + expect(JSON.stringify(result)).not.toContain("instabox-e2e-fixture"); + return result; + }; + try { + const created = await request("POST", "/api/bots", { name: "InstaBox fixture", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } }); + expect(created.status).toBe(201); + const bot = created.body.bot; + const path = `/api/bots/${bot.id}`; + expect((await request("PATCH", path, { cloudBackend: "instabox", computer: "cloud" })).status).toBe(200); + expect((await request("GET", `${path}/computer`)).body).toMatchObject({ backend: "instabox", configured: true, ready: false, machine: null }); + expect((await request("POST", `${path}/messages`, { text: "Say hello.", threadId: bot.threadId })).status).toBe(202); + await expect.poll(() => fake.desktop.size, { timeout: 20_000 }).toBe(1); + await expect.poll(async () => (await request("GET", "/api/bots")).body.bots.find((entry: { id: string }) => entry.id === bot.id)?.busy, { timeout: 20_000 }).toBe(false); + expect((await request("POST", `${path}/computer/provision`, {})).body.machine).toMatchObject({ state: "running", template: "linux" }); + expect(fake.desktop.size).toBe(1); + expect(readFileSync(join(fixture.dataDir, "fake-claude-dump.json"), "utf8")).not.toContain("instabox-e2e-fixture"); + expect((await request("GET", `${path}/computer`)).body).toMatchObject({ backend: "instabox", ready: true }); + await fixture.stop(); + await fixture.start(); + expect((await request("GET", `${path}/computer`)).body.backend).toBe("instabox"); + expect((await request("PATCH", path, { cloudBackend: "box" })).status).toBe(200); + await expect.poll(() => [...fake.machines.values()][0]?.state, { timeout: 20_000 }).toBe("suspended"); + expect((await request("PATCH", path, { cloudBackend: "instabox" })).status).toBe(200); + const provisioned = await request("POST", `${path}/computer/provision`, {}); + expect(provisioned.status, JSON.stringify(provisioned.body)).toBe(200); + expect(fake.machines.size).toBe(1); + expect((await request("DELETE", path)).status).toBe(200); + expect([...fake.machines.values()][0].state).toBe("deleted"); + expect(fake.calls.find(call => call.method === "DELETE")?.headers["x-confirm-delete"]).toBe("machine-1"); + const missing = await request("POST", "/api/bots", { name: "No key fixture", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } }); + const missingPath = `/api/bots/${missing.body.bot.id}`; + await request("PATCH", missingPath, { cloudBackend: "instabox", computer: "cloud" }); + await fixture.stop(); + env.INSTABOX_API_KEY = ""; + await fixture.start(); + expect((await request("GET", `${missingPath}/computer`)).body).toMatchObject({ backend: "instabox", configured: false, problem: "InstaBox 钥匙未配置" }); + const callsBeforeMissingProvision = fake.calls.length; + expect(await request("POST", `${missingPath}/computer/provision`, {})).toMatchObject({ status: 409, body: { error: "InstaBox 钥匙未配置", errorKey: "serverError.instabox.keyMissing" } }); + expect(fake.calls.slice(callsBeforeMissingProvision).some(call => call.path === "/v1/machines")).toBe(false); + expect(readFileSync(fixture.logPath, "utf8")).not.toContain("instabox-e2e-fixture"); + } finally { await fixture.close(); await fake.close(); } +}, 90_000); + +it.each(["vps", "instabox"] as const)("forces %s onto Boat for a run_on=cloud routine", async backend => { + const fake = await fakeInstaboxCore(); + const boat = await fakeBoatCore(); + const fixture = await launchVerificationServer({ + INSTABOX_API_KEY: "run-on-fixture", CRYBOT_TEST_INSTABOX_API: fake.url, FAKE_CLAUDE_USES_CLOUD_COMPUTER: "1", + }, undefined, undefined, undefined, undefined, [], boat.url); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.info.url + path, { method, headers: { origin: fixture.info.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const bot = (await request("POST", "/api/bots", { modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot; + expect((await request("PATCH", `/api/bots/${bot.id}`, { cloudBackend: backend, computer: "cloud" })).status).toBe(200); + const routine = (await request("POST", "/api/routines", { + name: `${backend} cloud fixture`, prompt: "Use the cloud computer.", botId: bot.id, runOn: "cloud", + schedule: { type: "once", at: Date.now() + 60_000 }, + })).body.routine; + expect((await request("POST", `/api/routines/${routine.id}/run`)).status).toBe(201); + await expect.poll(async () => (await request("GET", "/api/routines")).body.runs.find((run: { routineId: string }) => run.routineId === routine.id)?.status, + { timeout: 20_000 }).toBe("completed"); + expect(boat.calls.some(call => call.method === "POST" && call.path === "/sandboxes")).toBe(true); + expect(fake.calls.some(call => call.method === "POST" && call.path === "/v1/machines")).toBe(false); + await request("DELETE", `/api/bots/${bot.id}`); + } finally { await fixture.close(); await fake.close(); await boat.close(); } +}, 60_000); + +it("refuses an InstaBox cloud routine when the fixture offers no cloud provider", async () => { + const fake = await fakeInstaboxCore(); + const fixture = await launchRestartableServer({ env: { INSTABOX_API_KEY: "no-cloud-fixture", CRYBOT_TEST_INSTABOX_API: fake.url } }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.url + path, { method, headers: { origin: fixture.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const bot = (await request("POST", "/api/bots")).body.bot; + const path = `/api/bots/${bot.id}`; + expect((await request("PATCH", path, { cloudBackend: "instabox", computer: "cloud" })).status).toBe(200); + const routine = (await request("POST", "/api/routines", { name: "No cloud fixture", prompt: "Use the cloud computer.", botId: bot.id, + runOn: "cloud", schedule: { type: "once", at: Date.now() + 60_000 } })).body.routine; + expect((await request("POST", `/api/routines/${routine.id}/run`)).status).toBe(201); + await expect.poll(async () => (await request("GET", "/api/routines")).body.runs.find((run: { routineId: string }) => run.routineId === routine.id)?.status, + { timeout: 20_000 }).toBe("failed"); + expect(fake.calls.some(call => call.path === "/v1/machines")).toBe(false); + } finally { await fixture.close(); await fake.close(); } +}, 60_000); + +it.each(["vps", "instabox"] as const)("checks run_on=cloud %s turns against the box policy before mounting cloud computers", async backend => { + const fake = await fakeInstaboxCore(); + const boat = await fakeBoatCore(); + const fixture = await launchVerificationServer({ + INSTABOX_API_KEY: "policy-fixture", CRYBOT_TEST_INSTABOX_API: fake.url, + CRYBOT_TEST_DESKTOP_OWNER_TOKEN: "a".repeat(43), + CRYBOT_TEST_DESKTOP_POLICY_DELAY_MS: "5000", + CRYBOT_TEST_DESKTOP_POLICY: JSON.stringify({ organizationId: "fixture-org", organizationName: "Fixture Agency", expiresAt: null, + version: 1, companyModelsOnly: false, allowedEngines: "all", mcp: { allowCustom: true, allowlist: [] }, + computers: { thisComputer: true, localVm: true, box: false, vps: true }, remoteAccess: true }), + }, undefined, undefined, undefined, undefined, [], boat.url); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.info.url + path, { method, headers: { origin: fixture.info.url, "Content-Type": "application/json", "x-crybot-desktop-owner": "a".repeat(43) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const created = await request("POST", "/api/bots", { computer: "off" }); + expect(created.status, JSON.stringify(created.body)).toBe(201); + const bot = created.body.bot; + const path = `/api/bots/${bot.id}`; + expect((await request("PATCH", path, { cloudBackend: backend, computer: "cloud" })).status).toBe(200); + await new Promise(resolve => setTimeout(resolve, 6_000)); + const routine = (await request("POST", "/api/routines", { name: "Policy fixture", prompt: "Use the cloud computer.", botId: bot.id, + runOn: "cloud", schedule: { type: "once", at: Date.now() + 60_000 } })).body.routine; + expect((await request("POST", `/api/routines/${routine.id}/run`)).status).toBe(201); + await expect.poll(async () => (await request("GET", "/api/routines")).body.runs.find((run: { routineId: string }) => run.routineId === routine.id)?.status, + { timeout: 20_000 }).toBe("failed"); + expect(fake.calls.some(call => call.path === "/v1/machines")).toBe(false); + expect(boat.calls.some(call => call.method === "POST" && call.path === "/sandboxes")).toBe(false); + } finally { await fixture.close(); await fake.close(); await boat.close(); } +}, 60_000); + +it("refuses a normal InstaBox turn under the managed box policy before any machine request", async () => { + const fake = await fakeInstaboxCore(); + const owner = "a".repeat(43); + const fixture = await launchVerificationServer({ + INSTABOX_API_KEY: "normal-policy-fixture", CRYBOT_TEST_INSTABOX_API: fake.url, + CRYBOT_TEST_DESKTOP_OWNER_TOKEN: owner, CRYBOT_TEST_DESKTOP_POLICY_DELAY_MS: "5000", + CRYBOT_TEST_DESKTOP_POLICY: JSON.stringify({ organizationId: "fixture-org", organizationName: "Fixture Agency", expiresAt: null, + version: 1, companyModelsOnly: false, allowedEngines: "all", mcp: { allowCustom: true, allowlist: [] }, + computers: { thisComputer: true, localVm: true, box: false, vps: true }, remoteAccess: true }), + }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.info.url + path, { method, + headers: { origin: fixture.info.url, "Content-Type": "application/json", "x-crybot-desktop-owner": owner }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const created = await request("POST", "/api/bots", { computer: "off", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } }); + expect(created.status).toBe(201); + const bot = created.body.bot; + expect((await request("PATCH", `/api/bots/${bot.id}`, { cloudBackend: "instabox", computer: "cloud" })).status).toBe(200); + await expect.poll(async () => (await request("GET", "/api/config")).body.managedPolicy?.computers?.box, { timeout: 10_000 }).toBe(false); + expect((await request("POST", `/api/bots/${bot.id}/messages`, { text: "Use the cloud computer.", threadId: bot.threadId })).status).toBe(202); + await expect.poll(async () => (await request("GET", `/api/threads/${bot.threadId}/messages`)).body.messages, { timeout: 20_000 }) + .toEqual(expect.arrayContaining([expect.objectContaining({ role: "bot", kind: "activity", turnSucceeded: false, + tool: expect.objectContaining({ ok: false, name: "error: Fixture Agency does not allow bots to use cloud computers." }) })])); + expect(fake.calls.filter(call => call.path.startsWith("/v1/machines"))).toEqual([]); + } finally { await fixture.close(); await fake.close(); } +}, 60_000); + +it("allows a normal InstaBox turn in a real Cloud home without using Boat", async () => { + const fake = await fakeInstaboxCore(); + const boat = await fakeBoatCore(); + const secret = randomBytes(32).toString("base64url"); + const host = "cloud-home.example.test"; + const offlinePrelude = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`; + const fixture = await launchRestartableServer({ env: { + INSTABOX_API_KEY: "cloud-home-fixture", CRYBOT_TEST_INSTABOX_API: fake.url, CRYBOT_BOAT_API: boat.url, + CRYBOT_CLOUD_ROLE: "home", CRYBOT_CLOUD_MACHINE_ID: "instabox-cloud-home-fixture", + CRYBOT_CLOUD_ADMIN_URL: "https://cloud.example.test", CRYBOT_CLOUD_BOOTSTRAP_SECRET: secret, + CRYBOT_PUBLIC_URL: `https://${host}`, NODE_OPTIONS: `--import=${offlinePrelude}`, + } }); + let token = ""; + const headers = { host, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${host}`, "Content-Type": "application/json" }; + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.url + path, { method, headers: { ...headers, ...(token ? { authorization: `Bearer ${token}` } : {}) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const body = JSON.stringify({ label: "Cloud fixture owner", ttlSeconds: 300 }); + const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url"); + const pairing = await fetch(`${fixture.url}/api/cloud/pairing`, { method: "POST", body, headers: { ...headers, + "x-cry-cloud-timestamp": timestamp, "x-cry-cloud-nonce": nonce, "x-cry-cloud-signature": `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}` } }); + expect(pairing.status).toBe(200); + const paired = await request("POST", "/api/auth/pair", { code: (await pairing.json() as { code: string }).code }); + expect(paired.status).toBe(200); + token = paired.body.token; + expect((await request("GET", "/api/auth/session")).body.cloudHome).toBe(true); + expect((await request("PATCH", "/api/config", { box: { token: "box_cloud_home_fixture" } })).status).toBe(200); + const created = await request("POST", "/api/bots", { modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } }); + expect(created.status).toBe(201); + const bot = created.body.bot; + expect((await request("PATCH", `/api/bots/${bot.id}`, { cloudBackend: "instabox", computer: "cloud" })).status).toBe(200); + const boatCallsBeforeTurn = boat.calls.length; + expect((await request("POST", `/api/bots/${bot.id}/messages`, { text: "Say hello from the cloud computer.", threadId: bot.threadId })).status).toBe(202); + await expect.poll(() => fake.desktop.size, { timeout: 20_000 }).toBe(1); + await expect.poll(async () => (await request("GET", "/api/bots")).body.bots.find((entry: { id: string }) => entry.id === bot.id)?.busy, + { timeout: 20_000 }).toBe(false); + const messages = (await request("GET", `/api/threads/${bot.threadId}/messages`)).body.messages; + expect(messages).toEqual(expect.arrayContaining([expect.objectContaining({ role: "bot", kind: "text" })])); + expect(messages.some((message: { turnSucceeded?: boolean }) => message.turnSucceeded === false)).toBe(false); + expect(fake.calls.filter(call => call.method === "POST" && call.path === "/v1/machines")).toHaveLength(1); + expect(boat.calls.slice(boatCallsBeforeTurn)).toEqual([]); + } finally { await fixture.close(); await fake.close(); await boat.close(); } +}, 60_000); + +it("keeps an Android agent usable when a normal turn does not specify a template", async () => { + const fake = await fakeInstaboxCore(); + const fixture = await launchRestartableServer({ env: { + INSTABOX_API_KEY: "android-turn-fixture", CRYBOT_TEST_INSTABOX_API: fake.url, FAKE_CLAUDE_USES_CLOUD_COMPUTER: "1", + } }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.url + path, { method, headers: { origin: fixture.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const bot = (await request("POST", "/api/bots", { modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot; + const path = `/api/bots/${bot.id}`; + expect((await request("PATCH", path, { cloudBackend: "instabox", computer: "cloud" })).status).toBe(200); + expect((await request("POST", `${path}/computer/provision`, { template: "android" })).body.machine.template).toBe("android"); + expect((await request("POST", `${path}/messages`, { text: "Use the cloud computer.", threadId: bot.threadId })).status).toBe(202); + await expect.poll(async () => (await request("GET", "/api/bots")).body.bots.find((entry: { id: string }) => entry.id === bot.id)?.busy, + { timeout: 20_000 }).toBe(false); + expect((await request("GET", `${path}/computer`)).body.machine.template).toBe("android"); + expect(fake.calls.filter(call => call.method === "POST" && call.path === "/v1/machines")).toHaveLength(1); + } finally { await fixture.close(); await fake.close(); } +}, 60_000); + +it("deletes a Boat machine owned by an agent switched to InstaBox", async () => { + const fake = await fakeInstaboxCore(); + const boat = await fakeBoatCore(); + const fixture = await launchVerificationServer({ INSTABOX_API_KEY: "delete-boat-fixture", CRYBOT_TEST_INSTABOX_API: fake.url }, + undefined, undefined, undefined, undefined, [], boat.url); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.info.url + path, { method, headers: { origin: fixture.info.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const bot = (await request("POST", "/api/bots")).body.bot; + const path = `/api/bots/${bot.id}`; + expect((await request("PATCH", path, { cloudBackend: "box", computer: "cloud" })).status).toBe(200); + const provisioned = await request("POST", `${path}/computer/provision`, {}); + expect(provisioned.status, JSON.stringify(provisioned.body)).toBe(200); + expect(boat.boats.size).toBe(1); + expect((await request("PATCH", path, { cloudBackend: "instabox" })).status).toBe(200); + expect((await request("DELETE", path)).status).toBe(200); + expect(boat.calls.some(call => call.method === "DELETE" && call.path.startsWith("/sandboxes/"))).toBe(true); + } finally { await fixture.close(); await fake.close(); await boat.close(); } +}, 60_000); + +it("deletes a VPS machine owned by an agent switched to InstaBox", async () => { + const fake = await fakeInstaboxCore(); + const root = mkdtempSync(join(tmpdir(), "crybot-fake-vps-")); + const binDir = join(root, "bin"); + mkdirSync(binDir); + const detailPath = join(root, "detail.json"); + const deleteLog = join(root, "deleted.log"); + const docker = join(binDir, "docker"); + const ssh = join(binDir, "ssh"); + writeFileSync(ssh, "#!/bin/sh\nexit 0\n"); + chmodSync(ssh, 0o755); + writeFileSync(docker, `#!/bin/sh +case "$*" in + *"container ls"*) printf '%s\\n' "${"a".repeat(64)}" ;; + *"container inspect"*) /bin/cat "${detailPath}" ;; + *"rm -f"*) printf '%s\\n' "$*" >> "${deleteLog}" ;; + *) : ;; +esac +`); + chmodSync(docker, 0o755); + const sshKey = join(root, "fixture-key"); writeFileSync(sshKey, "fixture"); + const fixture = await launchVerificationServer({ INSTABOX_API_KEY: "delete-vps-fixture", CRYBOT_TEST_INSTABOX_API: fake.url }, + undefined, { binDir, host: "ssh://127.0.0.1", sshKey, staticDir: root }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.info.url + path, { method, headers: { origin: fixture.info.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + expect((await request("PATCH", "/api/config", { vps: { sshAlias: "fixture-vps" } })).status).toBe(200); + expect((await request("GET", "/api/config")).body.vps).toMatchObject({ configured: true, sshAlias: "fixture-vps" }); + const bot = (await request("POST", "/api/bots")).body.bot; + const containerName = vpsContainerName(bot.id); + const environmentId = readFileSync(join(fixture.info.dataDir, "environment-id"), "utf8").trim(); + writeFileSync(detailPath, JSON.stringify([{ Id: "a".repeat(64), Name: `/${containerName}`, Config: { Labels: { + [VPS_MANAGED_LABEL]: "1", [VPS_CONTAINER_LABEL]: containerName, [VPS_ENVIRONMENT_LABEL]: environmentId, + } }, State: { Status: "running", Running: true } }])); + const path = `/api/bots/${bot.id}`; + expect((await request("PATCH", path, { cloudBackend: "vps", computer: "cloud", vpsAlias: "fixture-vps" })).status).toBe(200); + expect((await request("GET", "/api/bots")).body.bots.find((entry: { id: string }) => entry.id === bot.id)?.vpsAlias).toBe("fixture-vps"); + const vpsInventory = await request("GET", "/api/computers/vps"); + expect(vpsInventory.body, JSON.stringify(vpsInventory.body)).toMatchObject({ available: true }); + expect(vpsInventory.body.instances).toEqual([expect.objectContaining({ name: containerName, ownerBotId: bot.id })]); + expect((await request("PATCH", path, { cloudBackend: "instabox" })).status).toBe(200); + expect((await request("GET", "/api/bots")).body.bots.find((entry: { id: string }) => entry.id === bot.id)?.vpsAlias).toBe("fixture-vps"); + expect((await request("DELETE", path)).status).toBe(200); + const removals = (() => { try { return readFileSync(deleteLog, "utf8"); } catch { return ""; } })(); + expect(removals).toContain("rm -f"); + } finally { await fixture.close(); await fake.close(); } +}, 60_000); + +it("deletes a retained InstaBox machine after switching backend", async () => { + const fake = await fakeInstaboxCore(); + const fixture = await launchRestartableServer({ env: { INSTABOX_API_KEY: "delete-leftovers-fixture", CRYBOT_TEST_INSTABOX_API: fake.url } }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.url + path, { method, headers: { origin: fixture.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const bot = (await request("POST", "/api/bots")).body.bot; + expect((await request("PATCH", `/api/bots/${bot.id}`, { cloudBackend: "instabox", computer: "cloud" })).status).toBe(200); + expect((await request("POST", `/api/bots/${bot.id}/computer/provision`, {})).status).toBe(200); + expect((await request("PATCH", `/api/bots/${bot.id}`, { cloudBackend: "box" })).status).toBe(200); + const deleted = await request("DELETE", `/api/bots/${bot.id}`); + expect(deleted.status).toBe(200); + expect([...fake.machines.values()][0]?.state).toBe("deleted"); + } finally { await fixture.close(); await fake.close(); } +}, 60_000); + +it.each(["http", "network"] as const)("keeps deletion independent of InstaBox %s failures for Boat bots", async mode => { + const fake = await fakeInstaboxCore(); + const fixture = await launchRestartableServer({ env: { INSTABOX_API_KEY: "delete-failure-fixture", CRYBOT_TEST_INSTABOX_API: fake.url } }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.url + path, { method, headers: { origin: fixture.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const bot = (await request("POST", "/api/bots")).body.bot; + expect((await request("PATCH", `/api/bots/${bot.id}`, { cloudBackend: "box" })).status).toBe(200); + if (mode === "http") fake.failNext({ status: 503, code: "fixture_unavailable" }); + else await fake.close(); + const deleted = await request("DELETE", `/api/bots/${bot.id}`); + expect(deleted).toMatchObject({ status: 200, body: { ok: true, notice: expect.stringMatching(/InstaBox/) } }); + } finally { await fixture.close(); if (mode === "http") await fake.close(); } +}, 60_000); + +it("keeps an InstaBox bot when deleting its machine fails", async () => { + const fake = await fakeInstaboxCore(); + const fixture = await launchRestartableServer({ env: { INSTABOX_API_KEY: "delete-failure-fixture", CRYBOT_TEST_INSTABOX_API: fake.url } }); + const request = async (method: string, path: string, body?: unknown) => { + const response = await fetch(fixture.url + path, { method, headers: { origin: fixture.url, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return { status: response.status, body: await response.json() as any }; + }; + try { + const bot = (await request("POST", "/api/bots")).body.bot; + expect((await request("PATCH", `/api/bots/${bot.id}`, { cloudBackend: "instabox", computer: "cloud" })).status).toBe(200); + expect((await request("POST", `/api/bots/${bot.id}/computer/provision`, {})).status).toBe(200); + await fake.close(); + const deleted = await request("DELETE", `/api/bots/${bot.id}`); + expect(deleted.status).toBe(503); + expect((await request("GET", "/api/bots")).body.bots.some((entry: { id: string }) => entry.id === bot.id)).toBe(true); + } finally { await fixture.close(); } +}, 60_000); diff --git a/server/instabox/key.test.ts b/server/instabox/key.test.ts new file mode 100644 index 00000000..18100eaf --- /dev/null +++ b/server/instabox/key.test.ts @@ -0,0 +1,29 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { instaboxApiKey, instaboxConfigured } from "./key.ts"; +import { parseStoredConfig, saveConfig, loadConfig, stripControlPlaneEnv, stripWorkspaceCredentialEnv } from "../config.ts"; + +afterEach(() => { vi.unstubAllEnvs(); }); + +it("prefers a nonempty environment key, then config, treating blanks as unconfigured", () => { + vi.stubEnv("INSTABOX_API_KEY", " env-fixture "); + expect(instaboxApiKey({ instabox: { apiKey: "config-fixture" } })).toBe("env-fixture"); + vi.stubEnv("INSTABOX_API_KEY", " "); + expect(instaboxApiKey({ instabox: { apiKey: " config-fixture " } })).toBe("config-fixture"); + expect(instaboxConfigured({ instabox: { apiKey: " " } })).toBe(false); + expect(instaboxConfigured({})).toBe(false); +}); + +it("parses and persists the server config section", () => { + expect(parseStoredConfig({ instabox: { apiKey: "config-fixture" } }).instabox).toEqual({ apiKey: "config-fixture" }); + saveConfig({ instabox: { apiKey: "saved-fixture" } }); + expect(loadConfig().instabox?.apiKey).toBe("saved-fixture"); + saveConfig({ instabox: { apiKey: "" } }); + expect(loadConfig().instabox?.apiKey).toBe(""); +}); + + +it.each([stripControlPlaneEnv, stripWorkspaceCredentialEnv])("keeps InstaBox credentials out of child environments", strip => { + const env = { INSTABOX_API_KEY: "fixture-secret", instabox_api_key: "fixture-secret", PATH: "/fixture/bin" }; + strip(env); + expect(env).toEqual({ PATH: "/fixture/bin" }); +}); diff --git a/server/instabox/key.ts b/server/instabox/key.ts new file mode 100644 index 00000000..1c96bf3c --- /dev/null +++ b/server/instabox/key.ts @@ -0,0 +1,13 @@ +import type { AppConfig } from "../config.ts"; + +export function instaboxApiKey(cfg: Pick): string | null { + return process.env.INSTABOX_API_KEY?.trim() || cfg.instabox?.apiKey?.trim() || null; +} + +export function instaboxConfigured(cfg: Pick): boolean { + return instaboxApiKey(cfg) !== null; +} + +export function stripInstaboxCredentialEnv(env: Record): void { + for (const key of Object.keys(env)) if (key.toUpperCase() === "INSTABOX_API_KEY") delete env[key]; +} diff --git a/server/instabox/machine.ts b/server/instabox/machine.ts new file mode 100644 index 00000000..215b0b00 --- /dev/null +++ b/server/instabox/machine.ts @@ -0,0 +1,24 @@ +/** InstaBox 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 InstaBox 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 }>; +} diff --git a/server/instabox/machines.test.ts b/server/instabox/machines.test.ts new file mode 100644 index 00000000..69505f00 --- /dev/null +++ b/server/instabox/machines.test.ts @@ -0,0 +1,114 @@ +import { afterEach, beforeEach, expect, it } from "vitest"; +import { fakeInstaboxCore } from "../testing/fake-instabox-core.ts"; +import { createInstaboxRequest } from "./client.ts"; +import { createInstaboxMachines } from "./machines.ts"; +import type { InstaboxMachines } from "./machine.ts"; + +let fake: Awaited>; +let service: InstaboxMachines; +const botId = "123456789012-more"; +beforeEach(async () => { fake = await fakeInstaboxCore(); service = createInstaboxMachines(createInstaboxRequest("fixture-key", fake.url)); }); +afterEach(async () => { await fake.close(); }); + +it.each(["linux", "android"] as const)("creates %s with the shared naming/spec contract, waits, then starts desktop", async template => { + const machine = await service.ensureRunning(botId, { template }); + expect(machine).toMatchObject({ name: "crybot-123456789012", state: "running", template }); + expect(fake.calls.find(call => call.method === "POST" && call.path === "/v1/machines")?.body).toEqual({ + name: "crybot-123456789012", templateId: template === "linux" ? "agent-browser" : "android", + spec: { vcpus: 4, memoryGiB: 8 }, autoSuspendAfterSeconds: 600, metadata: { app: "crybot", botId }, + }); + expect(fake.calls.at(-1)?.body).toEqual({ action: "start", width: 1280, height: 800 }); + expect(fake.calls.filter(call => call.path.includes("operations"))).toHaveLength(2); + expect(await service.find(botId)).toEqual(machine); + expect(await service.find("unrelated-bot")).toBeNull(); +}); + +it("single-flights concurrent starts and tolerates an already running desktop", async () => { + const machines = await Promise.all(Array.from({ length: 12 }, () => service.ensureRunning(botId))); + expect(new Set(machines.map(machine => machine.id)).size).toBe(1); + expect(fake.calls.filter(call => call.method === "POST" && call.path === "/v1/machines")).toHaveLength(1); + await expect(service.ensureRunning(botId)).resolves.toEqual(machines[0]); + fake.failNext({ status: 503, code: "unavailable" }); + await expect(service.ensureRunning(botId)).rejects.toThrow("unavailable"); + await expect(service.ensureRunning(botId)).resolves.toEqual(machines[0]); +}); + +it.each(["suspended", "stopped"] as const)("wakes a %s machine and retries exec exactly once", async state => { + const machine = await service.ensureRunning(botId); + fake.machines.get(machine.id)!.state = state; + const result = await service.exec(machine.id, { argv: ["printf", "fixture"], timeoutSeconds: 12 }); + expect(result.stdout).toBe("fixture output"); + expect(fake.calls.filter(call => call.path.endsWith("/exec"))).toHaveLength(2); + expect(fake.calls.some(call => call.path.endsWith(state === "suspended" ? "/resume" : "/start"))).toBe(true); +}); + +it("suspends, resumes, deletes with confirmation, and ignores deleted machines", async () => { + const machine = await service.ensureRunning(botId); + await service.suspend(botId); + expect((await service.find(botId))?.state).toBe("suspended"); + await service.suspend(botId); + expect(fake.calls.filter(call => call.path.endsWith("/suspend"))).toHaveLength(1); + await service.ensureRunning(botId); + await service.remove(botId); + expect(fake.calls.find(call => call.method === "DELETE")?.headers["x-confirm-delete"]).toBe(machine.id); + expect(await service.find(botId)).toBeNull(); + await service.remove(botId); + await service.suspend(botId); + expect((await service.ensureRunning(botId)).id).not.toBe(machine.id); +}); + +it("waits for intermediate state before deciding whether to resume and refuses error state", async () => { + const machine = await service.ensureRunning(botId); + fake.machines.get(machine.id)!.state = "suspending"; + const timer = setTimeout(() => { fake.machines.get(machine.id)!.state = "suspended"; }, 150); + try { await expect(service.ensureRunning(botId)).resolves.toMatchObject({ state: "running" }); } + finally { clearTimeout(timer); } + fake.machines.get(machine.id)!.state = "error"; + await expect(service.ensureRunning(botId)).rejects.toThrow("InstaBox machine is in error state"); +}); + +it("uploads and downloads exact bytes and encodes file parameters", async () => { + const machine = await service.ensureRunning(botId); + const bytes = new Uint8Array([0, 255, 128, 13, 10]); + await service.writeFile(machine.id, "/tmp/a & b", bytes, { mode: "0600" }); + expect(await service.readFile(machine.id, "/tmp/a & b")).toEqual(bytes); + const write = fake.calls.find(call => call.method === "PUT")!; + expect(Object.fromEntries(write.query)).toEqual({ path: "/tmp/a & b", mode: "0600", parents: "true" }); + expect(write.body).toEqual(Buffer.from(bytes)); + expect((await service.vncUpstream(machine.id)).url).toContain(`/v1/machines/${machine.id}/vnc`); +}); + +it("does not retry unrelated exec failures", async () => { + const machine = await service.ensureRunning(botId); + fake.failNext({ status: 409, code: "quota_exceeded" }); + await expect(service.exec(machine.id, { cmd: "true" })).rejects.toThrow("quota_exceeded"); + expect(fake.calls.filter(call => call.path.endsWith("/exec"))).toHaveLength(1); +}); + +it("does not claim a same-name machine with another bot's metadata", async () => { + const machine = await service.ensureRunning(botId); + fake.machines.get(machine.id)!.metadata.botId = "another-bot"; + expect(await service.find(botId)).toBeNull(); +}); + +it("rejects an existing machine when the requested template changes", async () => { + await service.ensureRunning(botId, { template: "android" }); + await expect(service.ensureRunning(botId, { template: "linux" })).rejects.toThrow("template mismatch"); +}); + +it("reuses an existing Android machine when an ordinary turn omits the template", async () => { + const android = await service.ensureRunning(botId, { template: "android" }); + await expect(service.ensureRunning(botId)).resolves.toMatchObject({ id: android.id, template: "android" }); + expect(fake.calls.filter(call => call.method === "POST" && call.path === "/v1/machines")).toHaveLength(1); +}); + + +it("resumes manual suspension before file uploads and downloads", async () => { + const machine = await service.ensureRunning(botId); + const data = new Uint8Array([1, 2, 3]); + await service.suspend(botId); + await service.writeFile(machine.id, "/tmp/resume", data); + await service.suspend(botId); + expect(await service.readFile(machine.id, "/tmp/resume")).toEqual(data); + expect(fake.calls.filter(call => call.path.endsWith("/resume"))).toHaveLength(2); +}); diff --git a/server/instabox/machines.ts b/server/instabox/machines.ts new file mode 100644 index 00000000..82ba788c --- /dev/null +++ b/server/instabox/machines.ts @@ -0,0 +1,115 @@ +import { setTimeout as delay } from "node:timers/promises"; +import { InstaboxError, instaboxVncUpstream, waitOperation } from "./client.ts"; +import type { InstaboxExecResult, InstaboxMachine, InstaboxMachines, InstaboxRequest, InstaboxTemplate } from "./machine.ts"; + +const LIFECYCLE_TIMEOUT = 180_000; +const stableStates = new Set(["running", "stopped", "suspended", "deleted", "error"]); + +function machineOf(row: InstaboxMachine & { templateId?: string }): InstaboxMachine { + return { id: row.id, name: row.name, state: row.state, template: row.templateId === "android" || row.template === "android" ? "android" : "linux" }; +} + +export function createInstaboxMachines(request: InstaboxRequest): InstaboxMachines { + const pending = new Map>(); + const pathOf = (id: string) => `/v1/machines/${encodeURIComponent(id)}`; + const read = async (id: string) => machineOf(await (await request("GET", pathOf(id))).json() as InstaboxMachine & { templateId?: string }); + const lifecycle = async (method: string, path: string, opts: Parameters[2] = {}) => { + const operation = await (await request(method, path, { ...opts, idempotent: true })).json() as { id: string; machineId: string }; + await waitOperation(request, operation.id, LIFECYCLE_TIMEOUT); + return operation; + }; + const stable = async (machine: InstaboxMachine, deadline = Date.now() + LIFECYCLE_TIMEOUT): Promise => { + while (!stableStates.has(machine.state)) { + if (Date.now() >= deadline) throw new Error("InstaBox machine timed out"); + await delay(100); + machine = await read(machine.id); + } + if (machine.state === "error") throw new Error("InstaBox machine is in error state"); + return machine; + }; + const find = async (botId: string) => { + const name = `crybot-${botId.slice(0, 12)}`; + const result = await (await request("GET", "/v1/machines", { query: { name } })).json() as Array }> | { machines?: Array }>; items?: Array }> }; + const rows = Array.isArray(result) ? result : result.machines ?? result.items ?? []; + const found = rows.find(row => row.name === name && row.metadata?.botId === botId && row.state !== "deleted"); + return found ? machineOf(found) : null; + }; + const wake = async (machine: InstaboxMachine): Promise => { + machine = await stable(machine); + if (machine.state === "suspended" || machine.state === "stopped") { + await lifecycle("POST", `${pathOf(machine.id)}/${machine.state === "suspended" ? "resume" : "start"}`); + machine = await stable(await read(machine.id)); + } + if (machine.state !== "running") throw new Error("InstaBox machine is not running"); + return machine; + }; + const whileRunning = async (machineId: string, run: () => Promise): Promise => { + try { return await run(); } + catch (error) { + if (!(error instanceof InstaboxError && error.status === 409 && error.code === "machine_not_running")) throw error; + await wake(await read(machineId)); + return run(); + } + }; + const start = async (botId: string, requestedTemplate?: InstaboxTemplate) => { + let machine = await find(botId); + if (machine) machine = await stable(machine); + const template = requestedTemplate ?? machine?.template ?? "linux"; + if (machine && requestedTemplate !== undefined && machine.template !== requestedTemplate) { + throw new Error(`InstaBox machine template mismatch: expected ${requestedTemplate}, found ${machine.template}`); + } + if (!machine || machine.state === "deleted") { + const operation = await lifecycle("POST", "/v1/machines", { body: { + name: `crybot-${botId.slice(0, 12)}`, templateId: template === "android" ? "android" : "agent-browser", + spec: { vcpus: 4, memoryGiB: 8 }, autoSuspendAfterSeconds: 600, metadata: { app: "crybot", botId }, + } }); + machine = await read(operation.machineId); + } + machine = await wake(machine); + try { + const response = await request("POST", `${pathOf(machine.id)}/desktop`, { body: { action: "start", width: 1280, height: 800 } }); + await response.body?.cancel(); + } catch (error) { + if (!(error instanceof InstaboxError && error.status === 409 && ["desktop_already_running", "desktop_running"].includes(error.code))) throw error; + } + return machine; + }; + return { + find, + ensureRunning(botId, opts) { + const current = pending.get(botId); + if (current) return current; + const task = start(botId, opts?.template).finally(() => { pending.delete(botId); }); + pending.set(botId, task); + return task; + }, + async suspend(botId) { + await pending.get(botId); + const found = await find(botId); + if (!found) return; + const machine = await stable(found); + if (machine.state === "running") await lifecycle("POST", `${pathOf(machine.id)}/suspend`); + }, + async remove(botId) { + await pending.get(botId); + const machine = await find(botId); + if (machine) await lifecycle("DELETE", pathOf(machine.id), { headers: { "X-Confirm-Delete": machine.id } }); + }, + async exec(machineId, req) { + return whileRunning(machineId, async () => (await request("POST", `${pathOf(machineId)}/exec`, { body: req })).json() as Promise); + }, + async readFile(machineId, path) { + return whileRunning(machineId, async () => { + const response = await request("GET", `${pathOf(machineId)}/files/content`, { query: { path } }); + return new Uint8Array(await response.arrayBuffer()); + }); + }, + async writeFile(machineId, path, data, opts) { + await whileRunning(machineId, async () => { + const response = await request("PUT", `${pathOf(machineId)}/files`, { raw: data, query: { path, mode: opts?.mode ?? "0644", parents: "true" } }); + await response.body?.cancel(); + }); + }, + async vncUpstream(machineId) { return instaboxVncUpstream(request, machineId); }, + }; +} diff --git a/server/instabox/persistence.test.ts b/server/instabox/persistence.test.ts new file mode 100644 index 00000000..f296803a --- /dev/null +++ b/server/instabox/persistence.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from "vitest"; +import { Store } from "../store.ts"; + +it("retains an InstaBox backend when reloading the bot store", () => { + const selection = () => ({ instanceId: "claude", model: "claude-sonnet-5" }); + const store = new Store(selection); + const bot = store.createBot({ name: "Fixture bot" }); + store.patchBot(bot.id, { cloudBackend: "instabox" }); + expect(new Store(selection).bot(bot.id)?.cloudBackend).toBe("instabox"); +}); diff --git a/server/instabox/power.test.ts b/server/instabox/power.test.ts new file mode 100644 index 00000000..257e397e --- /dev/null +++ b/server/instabox/power.test.ts @@ -0,0 +1,75 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { createInstaboxMachineCache, instaboxComputerAction, instaboxFailureResponse, instaboxStatus, requireInstabox, withInstaboxBackendPower } from "./power.ts"; +import { createInstaboxRequest } from "./client.ts"; +import type { InstaboxMachines } from "./machine.ts"; +import type { RouteContext } from "../routes/table.ts"; +import type { BotRecord } from "../store.ts"; + +afterEach(() => vi.unstubAllEnvs()); + +it("reuses machines for the same key and replaces the instance after key rotation or clearing", () => { + vi.stubEnv("INSTABOX_API_KEY", ""); + const factory = vi.fn(createInstaboxRequest); + const machinesFor = createInstaboxMachineCache(factory); + expect(machinesFor({})).toBeNull(); + const first = machinesFor({ instabox: { apiKey: "fixture-one" } }); + expect(machinesFor({ instabox: { apiKey: "fixture-one" } })).toBe(first); + expect(machinesFor({ instabox: { apiKey: "fixture-two" } })).not.toBe(first); + expect(factory).toHaveBeenCalledTimes(2); + expect(machinesFor({})).toBeNull(); + expect(machinesFor({ instabox: { apiKey: "fixture-one" } })).not.toBe(first); +}); + +it("makes missing credentials explicit in status and lifecycle actions", async () => { + expect(() => requireInstabox(null)).toThrow("InstaBox 钥匙未配置"); + expect(await instaboxStatus(null, "bot")).toMatchObject({ backend: "instabox", configured: false, problem: "InstaBox 钥匙未配置" }); + await expect(instaboxComputerAction(null, "bot", "provision", {})).rejects.toThrow("InstaBox 钥匙未配置"); +}); + +it.each([200, 400])("suspends after a successful backend switch only (status %s)", async status => { + let bot = { id: "bot", cloudBackend: "instabox" } as BotRecord; + const suspend = vi.fn().mockResolvedValue(undefined); + const json = vi.fn(); + const route = withInstaboxBackendPower(async ctx => { + if (status === 200) bot = { ...bot, cloudBackend: "box" }; + ctx.json(ctx.res, status, {}); + }, { bot: () => bot, machines: () => ({ suspend }) as unknown as InstaboxMachines }); + await route({ path: "/api/bots/bot", method: "PATCH", json } as unknown as RouteContext); + expect(suspend).toHaveBeenCalledTimes(status === 200 ? 1 : 0); + expect(json).toHaveBeenCalledOnce(); +}); + + +it("runs failed suspension in the background without misreporting a saved backend switch as a failed patch", async () => { + let bot = { id: "bot", cloudBackend: "instabox" } as BotRecord; + const json = vi.fn(); + const route = withInstaboxBackendPower(async ctx => { + bot = { ...bot, cloudBackend: "box" }; + ctx.json(ctx.res, 200, { bot }); + }, { bot: () => bot, machines: () => null }); + await route({ path: "/api/bots/bot", method: "PATCH", json } as unknown as RouteContext); + expect(json.mock.calls[0][1]).toBe(200); + expect(json.mock.calls[0][2]).toMatchObject({ bot: { cloudBackend: "box" } }); +}); + + +it("sends translation keys for user errors while preserving provider failures", async () => { + try { requireInstabox(null); } + catch (error) { + expect(instaboxFailureResponse(error)).toEqual({ status: 409, + body: { error: "InstaBox 钥匙未配置", errorKey: "serverError.instabox.keyMissing" } }); + } + const service = {} as InstaboxMachines; + await expect(instaboxComputerAction(service, "bot", "provision", { template: "apple" })).rejects.toMatchObject({ status: 400, errorKey: "serverError.instabox.template" }); + await expect(instaboxComputerAction(service, "bot", "join", {})).rejects.toMatchObject({ status: 501, errorKey: "serverError.instabox.unavailable" }); + const providerFailure = new Error("provider failed"); + expect(() => instaboxFailureResponse(providerFailure)).toThrow(providerFailure); +}); + +it("leaves the template unspecified when provisioning an existing machine", async () => { + const ensureRunning = vi.fn().mockResolvedValue({ id: "machine", template: "android", state: "running" }); + await expect(instaboxComputerAction({ ensureRunning } as unknown as InstaboxMachines, "bot", "provision", {})).resolves.toEqual({ + machine: { id: "machine", template: "android", state: "running" }, + }); + expect(ensureRunning).toHaveBeenCalledWith("bot", undefined); +}); diff --git a/server/instabox/power.ts b/server/instabox/power.ts new file mode 100644 index 00000000..03216709 --- /dev/null +++ b/server/instabox/power.ts @@ -0,0 +1,90 @@ +import type { AppConfig } from "../config.ts"; +import type { RouteHandler } from "../routes/table.ts"; +import type { BotRecord } from "../store.ts"; +import { createInstaboxRequest } from "./client.ts"; +import { instaboxApiKey } from "./key.ts"; +import type { InstaboxMachines, InstaboxRequest } from "./machine.ts"; +import { createInstaboxMachines } from "./machines.ts"; + +export const INSTABOX_KEY_MISSING = "InstaBox 钥匙未配置"; + +class InstaboxUserError extends Error { + readonly status: number; + readonly errorKey: string; + constructor(status: number, errorKey: string, message: string) { + super(message); + this.status = status; + this.errorKey = errorKey; + } +} + +export function instaboxFailureResponse(error: unknown) { + if (!(error instanceof InstaboxUserError)) throw error; + return { status: error.status, body: { error: error.message, errorKey: error.errorKey } }; +} + +export function createInstaboxMachineCache(makeRequest: (key: string) => InstaboxRequest = createInstaboxRequest) { + let cached: { key: string; machines: InstaboxMachines } | undefined; + return (cfg: AppConfig): InstaboxMachines | null => { + const key = instaboxApiKey(cfg); + if (!key) { cached = undefined; return null; } + if (cached?.key !== key) cached = { key, machines: createInstaboxMachines(makeRequest(key)) }; + return cached.machines; + }; +} + +export function requireInstabox(machines: InstaboxMachines | null): InstaboxMachines { + if (!machines) throw new InstaboxUserError(409, "serverError.instabox.keyMissing", INSTABOX_KEY_MISSING); + return machines; +} + +export async function instaboxStatus(machines: InstaboxMachines | null, botId: string) { + if (!machines) { + return { backend: "instabox" as const, configured: false, ready: false, machine: null, + problem: INSTABOX_KEY_MISSING, problemKey: "serverError.instabox.keyMissing" }; + } + try { + const machine = await machines.find(botId); + return { backend: "instabox" as const, configured: true, ready: machine?.state === "running", machine }; + } catch (error) { + return { backend: "instabox" as const, configured: true, ready: false, machine: null, + problem: error instanceof Error ? error.message : String(error) }; + } +} + +export async function instaboxComputerAction(machines: InstaboxMachines | null, botId: string, action: string, body: unknown) { + const service = requireInstabox(machines); + if (action === "provision") { + const template = (body as { template?: unknown } | null)?.template; + if (template !== undefined && template !== "linux" && template !== "android") { + throw new InstaboxUserError(400, "serverError.instabox.template", "InstaBox template must be linux or android"); + } + return { machine: await service.ensureRunning(botId, template === undefined ? undefined : { template }) }; + } + if (action === "sleep") { await service.suspend(botId); return { ok: true }; } + if (action === "remove") { await service.remove(botId); return { ok: true }; } + throw new InstaboxUserError(501, "serverError.instabox.unavailable", "InstaBox computer access is unavailable"); +} + +export function withInstaboxBackendPower(handler: RouteHandler, deps: { + bot(id: string): BotRecord | null; + machines(): InstaboxMachines | null; +}): RouteHandler { + return async ctx => { + const match = ctx.method === "PATCH" && /^\/api\/bots\/([\w-]+)$/.exec(ctx.path); + const before = match ? deps.bot(match[1]) : null; + if (before?.cloudBackend !== "instabox") return handler(ctx); + const botId = before.id; + let response: Parameters | undefined; + const result = await handler({ ...ctx, json: (...args) => { response = args; } }); + if (response) { + if (response[1] >= 200 && response[1] < 300 && deps.bot(botId)?.cloudBackend !== "instabox") { + void Promise.resolve().then(() => requireInstabox(deps.machines()).suspend(botId)).catch(error => { + console.warn("InstaBox machine could not be suspended after a backend change", error instanceof Error ? error.message : String(error)); + }); + } + ctx.json(...response); + } + return result; + }; +} diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.ts index 8d9b4bc5..a683a30c 100644 --- a/server/routes/bot-patch.test.ts +++ b/server/routes/bot-patch.test.ts @@ -375,3 +375,21 @@ describe("PATCH /api/bots/:id mainThreadChoice", () => { expect(store.bot(bot.id)?.mainThreadChoice).toBeUndefined(); }); }); + + +describe("PATCH cloudBackend", () => { + it("accepts instabox and keeps it across store reload", async () => { + const { bot, patch } = fixture(); + const result = await patch(bot.id, { cloudBackend: "instabox" }); + expect(result.status).toBe(200); + expect(result.body.bot.cloudBackend).toBe("instabox"); + expect(new Store(() => sonnet).bot(bot.id)?.cloudBackend).toBe("instabox"); + }); + + it("lists all three valid backends when rejecting unknown values", async () => { + const { bot, patch } = fixture(); + expect(await patch(bot.id, { cloudBackend: "unknown" })).toMatchObject({ + status: 400, body: { error: "cloudBackend must be box, vps or instabox" }, + }); + }); +}); diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts index cc904946..4929ad41 100644 --- a/server/routes/bot-patch.ts +++ b/server/routes/bot-patch.ts @@ -386,8 +386,8 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler { patch.browserProfile = requestedProfile; } else return json(res, 400, { error: "browserProfile must name an existing browser profile" }); } - if (body.cloudBackend !== undefined && !["box", "vps"].includes(String(body.cloudBackend))) { - return json(res, 400, { error: "cloudBackend must be box or vps" }); + if (body.cloudBackend !== undefined && !["box", "vps", "instabox"].includes(String(body.cloudBackend))) { + return json(res, 400, { error: "cloudBackend must be box, vps or instabox" }); } if (body.autoStartVps !== undefined) { if (typeof body.autoStartVps !== "boolean") return json(res, 400, { error: "autoStartVps must be true or false" }); diff --git a/server/store.ts b/server/store.ts index 8c3def03..35158fee 100644 --- a/server/store.ts +++ b/server/store.ts @@ -333,7 +333,7 @@ export class Store { botsMigrated = true; } } - if (b.cloudBackend !== undefined && b.cloudBackend !== "box" && b.cloudBackend !== "vps") { + if (b.cloudBackend !== undefined && b.cloudBackend !== "box" && b.cloudBackend !== "vps" && b.cloudBackend !== "instabox") { delete b.cloudBackend; botsMigrated = true; } diff --git a/server/testing/desktop-parent.mjs b/server/testing/desktop-parent.mjs index b722cb68..c9179b81 100644 --- a/server/testing/desktop-parent.mjs +++ b/server/testing/desktop-parent.mjs @@ -11,7 +11,10 @@ const token = process.env.CRYBOT_TEST_DESKTOP_OWNER_TOKEN; const pages = process.env.CRYBOT_TEST_DESKTOP_PAGES_ACCESS; const cuaFile = process.env.CRYBOT_TEST_DESKTOP_CUA_CONNECTION; const tailnetShare = process.env.CRYBOT_TEST_DESKTOP_TAILNET_SHARE; +const policy = process.env.CRYBOT_TEST_DESKTOP_POLICY; +const policyDelay = Number(process.env.CRYBOT_TEST_DESKTOP_POLICY_DELAY_MS) || 0; delete process.env.CRYBOT_TEST_DESKTOP_TAILNET_SHARE; +delete process.env.CRYBOT_TEST_DESKTOP_POLICY; delete process.env.CRYBOT_TEST_DESKTOP_OWNER_TOKEN; delete process.env.CRYBOT_TEST_DESKTOP_PAGES_ACCESS; delete process.env.CRYBOT_TEST_DESKTOP_CUA_CONNECTION; @@ -39,6 +42,11 @@ if (token || cuaFile) { if (event !== "message") return; listeners.push(listener); if (token) queueMicrotask(() => listener({ data: { type: "crybot:desktop-mutation-token", token } })); + if (policy) { + const deliver = () => listener({ data: { type: "crybot:managed-desktop-policy", policy: JSON.parse(policy) } }); + if (policyDelay > 0) setTimeout(deliver, policyDelay).unref?.(); + else queueMicrotask(deliver); + } if (pages) queueMicrotask(() => listener({ data: { type: "crybot:included-pages", access: JSON.parse(pages) } })); if (cuaFile) queueMicrotask(() => listener({ data: cuaGrant() })); if (tailnetShare) queueMicrotask(() => listener({ data: { type: "crybot:tailnet-share", share: JSON.parse(tailnetShare) } })); diff --git a/server/testing/fake-instabox-core.ts b/server/testing/fake-instabox-core.ts new file mode 100644 index 00000000..f48381bb --- /dev/null +++ b/server/testing/fake-instabox-core.ts @@ -0,0 +1,79 @@ +import { createServer, type IncomingHttpHeaders } from "node:http"; +import type { InstaboxMachineState } from "../instabox/machine.ts"; + +export async function fakeInstaboxCore() { + const machines = new Map }>(); + const operations = new Map(); + const files = new Map(); + const desktop = new Set(); + const calls: Array<{ method: string; path: string; query: URLSearchParams; headers: IncomingHttpHeaders; body: any }> = []; + let failure: { status: number; code: string; message?: string } | undefined; + let operationFailure = false; + const server = createServer(async (req, res) => { + const url = new URL(req.url!, "http://localhost"); + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(Buffer.from(chunk)); + const raw = Buffer.concat(chunks); + const body = req.headers["content-type"] === "application/json" && raw.length ? JSON.parse(raw.toString()) : raw; + calls.push({ method: req.method!, path: url.pathname, query: url.searchParams, headers: req.headers, body }); + const send = (status: number, value: unknown) => { + res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(value)); + }; + if (failure) { const next = failure; failure = undefined; return send(next.status, { error: next }); } + if (!req.headers["x-api-key"]) return send(401, { error: { code: "unauthorized" } }); + const op = url.pathname.match(/^\/v1\/operations\/(.+)$/); + if (op) { + const operation = operations.get(op[1]); + if (!operation) return send(404, { error: { code: "not_found" } }); + if (operation.polls++ > 0) { + operation.state = operationFailure ? "failed" : "succeeded"; + if (!operationFailure) machines.get(operation.machineId)!.state = operation.finalState; + } + return send(200, operation); + } + const finish = (machineId: string, finalState: InstaboxMachineState) => { + if (!req.headers["idempotency-key"]) return send(400, { error: { code: "idempotency_required" } }); + const operation = { id: `op-${operations.size + 1}`, machineId, state: "pending", finalState, polls: 0 }; + operations.set(operation.id, operation); + send(202, operation); + }; + if (url.pathname === "/v1/machines") { + if (req.method === "GET") return send(200, { machines: [...machines.values()] }); + const id = `machine-${machines.size + 1}`; + machines.set(id, { id, name: body.name, state: "creating", templateId: body.templateId, metadata: body.metadata ?? {} }); + return finish(id, "running"); + } + const match = url.pathname.match(/^\/v1\/machines\/([^/]+)(?:\/(.+))?$/); + const machine = match && machines.get(match[1]); + if (!machine) return send(404, { error: { code: "not_found" } }); + const action = match![2]; + if (!action && req.method === "GET") return send(200, machine); + if (!action && req.method === "DELETE") { + if (req.headers["x-confirm-delete"] !== machine.id) return send(400, { error: { code: "confirmation_required" } }); + machine.state = "deleting"; + return finish(machine.id, "deleted"); + } + if (action === "resume" || action === "start" || action === "suspend") { + machine.state = action === "resume" ? "resuming" : action === "start" ? "starting" : "suspending"; + return finish(machine.id, action === "suspend" ? "suspended" : "running"); + } + if (machine.state !== "running") return send(409, { error: { code: "machine_not_running" } }); + if (action === "desktop") { + if (desktop.has(machine.id)) return send(409, { error: { code: "desktop_already_running" } }); + desktop.add(machine.id); return send(200, { running: true }); + } + if (action === "exec") return send(200, { stdout: "fixture output", stderr: "", exitCode: 0, timedOut: false, truncated: false }); + const fileKey = `${machine.id}:${url.searchParams.get("path")}`; + if (action === "files" && req.method === "PUT") { files.set(fileKey, raw); res.writeHead(204); return res.end(); } + if (action === "files/content") { res.writeHead(200); return res.end(files.get(fileKey) ?? Buffer.alloc(0)); } + send(404, { error: { code: "not_found" } }); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Fake InstaBox failed to listen"); + return { url: `http://127.0.0.1:${address.port}`, calls, machines, operations, desktop, + failNext: (next: NonNullable) => { failure = next; }, + failOperations: () => { operationFailure = true; }, + close: () => new Promise((resolve, reject) => { server.close(error => error ? reject(error) : resolve()); server.closeAllConnections(); }), + }; +} diff --git a/shared/wire.ts b/shared/wire.ts index 979ca5d3..b73ea304 100644 --- a/shared/wire.ts +++ b/shared/wire.ts @@ -59,7 +59,7 @@ export interface ModelSelection { } /** Which cloud computer backs computer: "cloud"; absent means Boat. */ -export type CloudBackend = "box" | "vps"; +export type CloudBackend = "box" | "vps" | "instabox"; /** A place a bot can act. `cloud` covers both cloud backends. */ export type Surface = "cloud" | "vm" | "local" | "browser"; From bd2a810a5cffb507218cd15a46864f39bda0ddec Mon Sep 17 00:00:00 2001 From: tangzhixiong613-jpg <340458552+tangzhixiong613-jpg@users.noreply.github.com> Date: Sun, 15 Nov 2026 07:59:18 +0000 Subject: [PATCH 2/3] =?UTF-8?q?T-1242=20InstaBox=20=E6=A0=B8=E5=BF=83?= =?UTF-8?q?=EF=BC=9A=E6=9C=BA=E5=99=A8=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= =?UTF-8?q?=E3=80=81=E5=9B=9E=E5=90=88=E6=8E=A5=E5=85=A5=E3=80=81=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E4=B8=8E=E5=88=A0=E9=99=A4=EF=BC=9BreadFile=20?= =?UTF-8?q?=E6=B5=81=E5=BC=8F=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/tasks/T-1200/T-1242-instabox-core/r6.md | 17 + docs/tasks/T-1200/T-1242-instabox-core/r7.md | 21 + .../T-1200/T-1242-instabox-core/report.md | 71 +++ .../T-1242-instabox-core/verification.txt | 436 +++++++++--------- scripts/public-scan/allow-domains.txt | 2 +- server/bot-box/env.test.ts | 2 +- server/instabox/client.ts | 33 ++ server/instabox/machine.ts | 2 +- server/instabox/machines.test.ts | 48 ++ server/instabox/machines.ts | 8 +- server/testing/fake-instabox-core.ts | 29 +- src/locales/en.json | 3 + src/locales/zh.json | 3 + 13 files changed, 451 insertions(+), 224 deletions(-) create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/r6.md create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/r7.md diff --git a/docs/tasks/T-1200/T-1242-instabox-core/r6.md b/docs/tasks/T-1200/T-1242-instabox-core/r6.md new file mode 100644 index 00000000..715ada57 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/r6.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-1242 第 6 轮:只修 CI 上两个分支独有的失败 + +原任务见本文件夹 brief.md、r2.md–r5.md,工作区是最新分支(已合入 origin/main)。只做下面两条,不改别的。 + +## 必改 +1. src/locales/sent-keys.test.ts:38 失败:server/instabox/power.ts 发出的 `serverError.instabox.keyMissing`、`serverError.instabox.template`、`serverError.instabox.unavailable` 不在英文目录里。把这三个键补进 src/locales/en.json 和 zh.json(文案简洁、面向用户;中文用中文),其他语言目录按仓库现有做法处理(看 sent-keys / 目录一致性测试怎么要求)。 +2. server/bot-box/env.test.ts:185 失败:`CRYBOT_TEST_INSTABOX_API` 没有归类。它是只给服务端测试用的假服务地址,不应传进智能体的 box,加到该测试的 SERVER_ONLY_CRYBOT 列表。 + +## 验收 +逐文件跑 src/locales/sent-keys.test.ts、server/bot-box/env.test.ts、server/instabox/ 下改动相关测试;`tsc -p tsconfig.server.json`。report.md 追加第 6 轮一节(短);verification.txt 不写 IP、地址、域名、uuid。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/r7.md b/docs/tasks/T-1200/T-1242-instabox-core/r7.md new file mode 100644 index 00000000..fab97f10 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/r7.md @@ -0,0 +1,21 @@ +## 运行环境(云沙箱,必读) +- 开工先在 worktree 根目录运行 依赖准备脚本(镜像自带,把预装依赖链进 node_modules),之后 `pnpm exec vitest` / `pnpm exec tsc` 才可用。 +- 这里**没有** systemd、Docker,说明里出现的 `systemd-run --scope ... --` 前缀一律去掉直接运行;机器 8G/4 核,一次只跑一个测试文件。 +- 若本轮沙箱已放开(能联网、能监听端口),交回前必须把改动相关的测试全部跑过,包括需要端口的 e2e;涉及的 e2e 连跑 3 次都要过。跑不了的写明原因。 +- 报告只写三样:改了什么(文件列表与 git status 一致)、为什么、测试命令与结果摘要。不要写长篇分析;完整输出放 verification 文本文件即可。 +- 不提交 git。 + +# T-1242 第 7 轮:readFile 加大小上限(配合任务 ② 的安全审查中级问题) + +原任务见本文件夹 brief.md、r2.md–r6.md,工作区里上一轮改动保留。只做下面一条。 + +## 必改 +任务 ②(智能体操作电脑工具)的安全审查指出:machines.readFile 会把整个文件读进内存,大小检查在读完之后,智能体可把文件换成几 GB 拖垮共享服务进程。本任务提供 readFile 的真实实现,所以在这里堵: +1. server/instabox/machine.ts 第 20 行接口**一字不差**改为: + `readFile(machineId: string, path: string, options?: { maxBytes?: number }): Promise;` + (任务 ② 同步改了同一行,两边必须完全相同,避免合并冲突。) +2. server/instabox/machines.ts 的 readFile 实现(及其调用的 client 层):maxBytes 缺省 256 MiB;先看响应 Content-Length,超过直接拒绝并取消响应体;再按流式读取累计字节,超限立刻中止读取(取消 reader / abort),不得先缓冲完整内容再判断。错误要清楚(含 maxBytes 数值,不含钥匙、地址)。 +3. 补测试(用本仓库假 服务):Content-Length 超限被拒;无 Content-Length 的分块响应超限时中途中止,且测试能证明没有读完全部内容(例如假服务记录被取消/只发出部分块);正常大小文件读取不变。 + +## 验收 +改动相关测试逐文件跑,core e2e 跑 1 次;`tsc -p tsconfig.server.json`、改动文件 `oxlint --deny-warnings`。report.md 追加第 7 轮一节(短);verification.txt 不写 IP、地址、域名、uuid。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/report.md b/docs/tasks/T-1200/T-1242-instabox-core/report.md index 92d56904..06eae995 100644 --- a/docs/tasks/T-1200/T-1242-instabox-core/report.md +++ b/docs/tasks/T-1200/T-1242-instabox-core/report.md @@ -117,3 +117,74 @@ | `pnpm exec vitest run server/control-cry.test.ts --maxWorkers=1` | 19 过、1 失败;第 261 行预期仅 claude,实际还有 chatgpt。临时恢复 HEAD 中的启动器后复跑仍同样失败,确认是基线问题,未扩展修复,也未重复跑三次 | 完整输出(含预期失败的自检与基线复跑)见 [verification.txt](verification.txt)。 + + +## 第 6 轮 + +1. 改了什么 + +- `src/locales/en.json`、`src/locales/zh.json`:补齐 `serverError.instabox.keyMissing`、`serverError.instabox.template`、`serverError.instabox.unavailable` 的简洁用户文案。 +- `server/bot-box/env.test.ts`:将 `CRYBOT_TEST_INSTABOX_API` 加入 `SERVER_ONLY_CRYBOT`。 +- `docs/tasks/T-1200/T-1242-instabox-core/report.md`、`docs/tasks/T-1200/T-1242-instabox-core/verification.txt`:追加本节并更新脱敏验证输出。以上五个文件与最终 git status 一致;未提交 git。 + +2. 为什么 + +修复 CI 的缺失翻译键和环境变量未分类失败。其他语言按现有部分目录规则回退英文;假服务地址仅供服务端测试使用,现有分类测试同时检查它不能传入智能体 box。 + +3. 测试命令与结果摘要 + +已执行 依赖准备脚本。仓库缺少 `docs/verification/README.md`;服务验证全部使用隔离 fixture 和假服务。以下 Vitest 命令均逐文件执行。 + +| 命令 | 结果 | +| --- | --- | +| `pnpm exec vitest run src/locales/sent-keys.test.ts --maxWorkers=1` | 2 项通过 | +| `pnpm exec vitest run server/bot-box/env.test.ts --maxWorkers=1` | 11 项通过 | +| `pnpm exec vitest run src/lib/i18n.test.ts --maxWorkers=1` | 39 项通过 | +| `pnpm exec vitest run scripts/generate-locale.test.mjs --maxWorkers=1` | 23 项通过 | +| `pnpm exec vitest run server/instabox/.test.ts --maxWorkers=1` | client、key、machines、persistence、power 分别 6、4、13、1、7 项通过 | +| `pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1` | 连续 3 次,每次 15 项通过 | +| `pnpm exec tsc -p tsconfig.server.json`、`pnpm exec tsc -p tsconfig.json` | 均通过 | +| `pnpm exec oxlint --deny-warnings server/bot-box/env.test.ts src/locales/en.json src/locales/zh.json` | 通过 | +| `git diff --check` | 通过 | + +完整输出见 [verification.txt](verification.txt),已检查不含 IP、连接地址、域名或 UUID。 + + +## 第 7 轮 + +1. 改了什么 + +本轮文件清单与 `git status --short` 一致;未提交 git。 + +```text + M docs/tasks/T-1200/T-1242-instabox-core/report.md + M docs/tasks/T-1200/T-1242-instabox-core/verification.txt + M server/instabox/client.ts + M server/instabox/machine.ts + M server/instabox/machines.test.ts + M server/instabox/machines.ts + M server/testing/fake-instabox-core.ts +``` + +接口按要求原样增加 `options?: { maxBytes?: number }`;默认上限 256 MiB,先检查 Content-Length,再逐块累计,超限立即取消响应体或 reader。错误包含上限数值、不含钥匙或地址;拒绝无效上限。假服务记录发送块数及取消状态,测试覆盖提前拒绝、中途取消、正常及边界大小读取。 + +2. 为什么 + +防止文件被替换成超大内容后,在大小检查前完整读入共享服务内存。 + +3. 测试命令与结果摘要 + +已执行 依赖准备脚本。仓库仍缺少 `docs/verification/README.md`;所有服务验证使用隔离 fixture 和假服务。Vitest 均以 `pnpm exec vitest run <文件> --maxWorkers=1` 逐文件执行。 + +| 文件或命令 | 结果 | +| --- | --- | +| `server/instabox/machines.test.ts` | 24 项通过 | +| `server/instabox/client.test.ts` | 6 项通过 | +| `server/instabox/power.test.ts` | 7 项通过 | +| `server/instabox/core.e2e.test.ts` | 最终连续 3 次,每次 15 项通过 | +| `scripts/testing/file-size-ratchet.test.ts` | 1 项通过 | +| `pnpm exec tsc -p tsconfig.server.json` | 通过 | +| `pnpm exec oxlint --deny-warnings`(上述 5 个 TS 文件) | 通过 | +| `git diff --check` | 通过 | + +此前两次完整 e2e 在 `core.e2e.test.ts:380` 出现间歇失败(期望 deleted,实际 suspended)。临时恢复 HEAD 的全部 5 个代码文件后,单独用例 6 次、完整 e2e 2 次均未复现,未确认原因;恢复本轮改动后最终三连过。完整命令、失败及成功输出均见 [verification.txt](verification.txt),已检查不含 IP、连接地址、域名或 UUID。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/verification.txt b/docs/tasks/T-1200/T-1242-instabox-core/verification.txt index 855f80e1..60ddc2b2 100644 --- a/docs/tasks/T-1200/T-1242-instabox-core/verification.txt +++ b/docs/tasks/T-1200/T-1242-instabox-core/verification.txt @@ -1,157 +1,55 @@ -T-1242 第 5 轮验证 -所有服务使用隔离临时目录、假引擎和本地假服务。 +T-1242 第 7 轮验证 +所有服务验证使用隔离 fixture 和假服务。 docs/verification/README.md 在仓库中不存在。 -地址、主机名及仓库绝对路径已脱敏;下列保留完整命令输出。 +输出中的仓库绝对路径及连接信息已脱敏。 $ crybot-link-deps crybot-link-deps: linked 73 entries into worktree node_modules +Exit code: 0 -===== new-cases ===== -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'normal InstaBox turn' +Run: machines +$ pnpm exec vitest run server/instabox/machines.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 2 passed | 13 skipped (15) - Start at 06:54:50 - Duration 11.59s (transform 1.52s, setup 954ms, import 1.10s, tests 9.39s, environment 0ms) + Tests 24 passed (24) + Start at 07:38:54 + Duration 2.37s (transform 1.04s, setup 1.34s, import 37ms, tests 787ms, environment 0ms) + +Exit code: 0 -===== mutation ===== -Mutation: replace wantedKind cloud branch with undefined. -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t refuses a normal InstaBox turn +Run: client +$ pnpm exec vitest run server/instabox/client.test.ts --maxWorkers=1 RUN v4.1.11 . - ❯ server/instabox/core.e2e.test.ts (15 tests | 1 failed | 14 skipped) 26570ms - × refuses a normal InstaBox turn under the managed box policy before any machine request 26568ms -⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + Test Files 1 passed (1) + Tests 6 passed (6) + Start at 07:39:21 + Duration 1.77s (transform 1.14s, setup 1.46s, import 30ms, tests 88ms, environment 0ms) - FAIL server/instabox/core.e2e.test.ts > refuses a normal InstaBox turn under the managed box policy before any machine request -AssertionError: expected [ { …(8) }, { …(7) }, { …(12) }, …(2) ] to deeply equal ArrayContaining{…} - -- Expected -+ Received - -- ArrayContaining [ -- ObjectContaining { -+ [ -+ { -+ "at": 1794725725956, -+ "kind": "text", -+ "parentId": null, -+ "role": "bot", -+ "setupChoices": [ -+ "Research and digging into topics", -+ "Keeping an eye on things for me", -+ "Email, calendar and messages", -+ "Bookings, shopping and errands", -+ "Data, spreadsheets and reports", -+ ], -+ "setupOffer": true, -+ "text": "Hi, I'm Churro. What would you like me to do?", -+ }, -+ { -+ "at": 1794725730551, -+ "kind": "text", -+ "requestPending": false, -+ "role": "user", -+ "text": "Use the cloud computer.", -+ }, -+ { -+ "at": 1794725730720, -+ "kind": "text", -+ "role": "bot", -+ "text": "hello from fake claude", -+ "turnCompletedAt": 1794725730733, -+ "turnSucceeded": true, -+ "turnTerminal": true, -+ }, -+ { -+ "at": 1794725730723, - "kind": "activity", - "role": "bot", -- "tool": ObjectContaining { -- "name": "error: Fixture Agency does not allow bots to use cloud computers.", -- "ok": false, -+ "tool": { -+ "input": "{ -+ \"command\": \"echo hi\" -+ }", -+ "itemId": "tu-13183-1", -+ "name": "Bash", -+ "ok": true, -+ "output": "[ -+ { -+ \"type\": \"text\", -+ \"text\": \"hi\" -+ } -+ ]", -+ "spoken": "running a command", -+ "step": { -+ "activity": "command", -+ "target": "echo hi", -+ }, -+ "summary": "echo hi", -+ }, -+ }, -+ { -+ "at": 1794725730735, -+ "digest": { -+ "at": 1794725730735, -+ "durationMs": 83, -+ "hookCoverage": "preview", -+ "memory": [], -+ "reply": "hello from fake claude", -+ "toolCalls": 1, -+ "tools": [ -+ { -+ "count": 1, -+ "failed": 0, -+ "name": "Bash", -+ "sample": "echo hi", - }, -- "turnSucceeded": false, -+ ], -+ "usage": { -+ "cachedInput": 2, -+ "costUsd": 0.01, -+ "input": 12, -+ "output": 5, -+ }, -+ }, -+ "kind": "digest", -+ "role": "bot", -+ "text": "[digest] · tools: Bash ×1 (from tool previews) · reply: hello from fake claude", -+ "turnSucceeded": true, - }, - ] - - ❯ server/instabox/core.e2e.test.ts:215:8 - 213| expect((await request("POST", `/api/bots/${bot.id}/messages`, { te… - 214| await expect.poll(async () => (await request("GET", `/api/threads/… - 215| .toEqual(expect.arrayContaining([expect.objectContaining({ role:… - | ^ - 216| tool: expect.objectContaining({ ok: false, name: "error: Fixtu… - 217| expect(fake.calls.filter(call => call.path.startsWith("/v1/machine… - -Caused by: Error: Matcher did not succeed in time. - ❯ server/instabox/core.e2e.test.ts:214:5 -⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ +Exit code: 0 +Run: power +$ pnpm exec vitest run server/instabox/power.test.ts --maxWorkers=1 - Test Files 1 failed (1) - Tests 1 failed | 14 skipped (15) - Start at 06:55:22 - Duration 28.38s (transform 1.26s, setup 740ms, import 948ms, tests 26.57s, environment 0ms) + RUN v4.1.11 . -Exit code: 1 (expected 1) + Test Files 1 passed (1) + Tests 7 passed (7) + Start at 07:39:24 + Duration 1.25s (transform 830ms, setup 1.04s, import 35ms, tests 8ms, environment 0ms) + -===== core-1 ===== +Exit code: 0 + +Run: core-1 $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . @@ -159,164 +57,231 @@ $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 Test Files 1 passed (1) Tests 15 passed (15) - Start at 06:56:09 - Duration 59.36s (transform 1.50s, setup 952ms, import 1.04s, tests 57.24s, environment 0ms) + Start at 07:39:25 + Duration 62.74s (transform 1.90s, setup 1.11s, import 1.48s, tests 59.98s, environment 0ms) Exit code: 0 -===== core-2 ===== +Run: core-2 $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . + ❯ server/instabox/core.e2e.test.ts (15 tests | 1 failed) 58941ms + × deletes a retained InstaBox machine after switching backend 2513ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL server/instabox/core.e2e.test.ts > deletes a retained InstaBox machine after switching backend +AssertionError: expected 'suspended' to be 'deleted' // Object-is equality + +Expected: "deleted" +Received: "suspended" + + ❯ server/instabox/core.e2e.test.ts:380:51 + 378| const deleted = await request("DELETE", `/api/bots/${bot.id}`); + 379| expect(deleted.status).toBe(200); + 380| expect([...fake.machines.values()][0]?.state).toBe("deleted"); + | ^ + 381| } finally { await fixture.close(); await fake.close(); } + 382| }, 60_000); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed (1) + Tests 1 failed | 14 passed (15) + Start at 07:40:29 + Duration 61.62s (transform 1.92s, setup 1.17s, import 1.36s, tests 58.94s, environment 0ms) + + +Exit code: 1 + +Run: baseline-core-1 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' + + RUN v4.1.11 . + Test Files 1 passed (1) - Tests 15 passed (15) - Start at 06:57:09 - Duration 63.22s (transform 2.06s, setup 1.26s, import 1.43s, tests 60.38s, environment 0ms) + Tests 1 passed | 14 skipped (15) + Start at 07:42:25 + Duration 4.41s (transform 1.57s, setup 920ms, import 1.16s, tests 2.19s, environment 0ms) Exit code: 0 -===== core-3 ===== -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +Run: baseline-core-2 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' RUN v4.1.11 . Test Files 1 passed (1) - Tests 15 passed (15) - Start at 06:58:13 - Duration 68.61s (transform 2.74s, setup 1.58s, import 1.90s, tests 64.91s, environment 0ms) + Tests 1 passed | 14 skipped (15) + Start at 07:42:30 + Duration 4.67s (transform 1.64s, setup 979ms, import 1.19s, tests 2.34s, environment 0ms) Exit code: 0 -===== environment ===== -$ pnpm exec vitest run scripts/control-cry.test.ts --maxWorkers=1 +Run: baseline-core-3 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' RUN v4.1.11 . Test Files 1 passed (1) - Tests 10 passed (10) - Start at 06:59:22 - Duration 3.07s (transform 2.20s, setup 1.48s, import 1.33s, tests 16ms, environment 0ms) + Tests 1 passed | 14 skipped (15) + Start at 07:42:35 + Duration 4.60s (transform 1.71s, setup 1.00s, import 1.25s, tests 2.21s, environment 0ms) Exit code: 0 -===== launcher-1 ===== -$ pnpm exec vitest run server/control-cry.test.ts --maxWorkers=1 +Run: baseline-core-4 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' RUN v4.1.11 . - ❯ server/control-cry.test.ts (20 tests | 1 failed) 11244ms - × launches, drives a real fake-engine turn, and removes only its test data 2624ms -⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + Test Files 1 passed (1) + Tests 1 passed | 14 skipped (15) + Start at 07:42:40 + Duration 4.46s (transform 1.62s, setup 935ms, import 1.19s, tests 2.20s, environment 0ms) - FAIL server/control-cry.test.ts > control-cry isolated verification loop > launches, drives a real fake-engine turn, and removes only its test data -AssertionError: expected [ 'claude', 'chatgpt' ] to deeply equal [ 'claude' ] -- Expected -+ Received +Exit code: 0 - [ - "claude", -+ "chatgpt", - ] +Run: baseline-core-5 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' - ❯ server/control-cry.test.ts:261:39 - 259| const doctor = await runControlCry(["doctor"], { env }) as any; - 260| expect(doctor.ok).toBe(true); - 261| expect(doctor.availableEngines).toEqual(["claude"]); - | ^ - 262| - 263| const created = await runControlCry(["new-bot", "--name", "Verif… + RUN v4.1.11 . -⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + Test Files 1 passed (1) + Tests 1 passed | 14 skipped (15) + Start at 07:42:45 + Duration 4.35s (transform 1.56s, setup 881ms, import 1.17s, tests 2.18s, environment 0ms) - Test Files 1 failed (1) - Tests 1 failed | 19 passed (20) - Start at 06:59:26 - Duration 14.03s (transform 2.06s, setup 1.33s, import 1.28s, tests 11.24s, environment 0ms) +Exit code: 0 -Exit code: 1 +Run: baseline-core-6 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' -===== launcher-baseline ===== -Baseline check: scripts/control-cry.ts temporarily restored from HEAD. -$ pnpm exec vitest run server/control-cry.test.ts --maxWorkers=1 + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 1 passed | 14 skipped (15) + Start at 07:42:50 + Duration 4.51s (transform 1.63s, setup 962ms, import 1.20s, tests 2.20s, environment 0ms) + + +Exit code: 0 + +Run: core-final-1 +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . - ❯ server/control-cry.test.ts (20 tests | 1 failed) 10821ms - × launches, drives a real fake-engine turn, and removes only its test data 2617ms -⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 07:43:19 + Duration 63.42s (transform 2.02s, setup 1.17s, import 1.49s, tests 60.60s, environment 0ms) - FAIL server/control-cry.test.ts > control-cry isolated verification loop > launches, drives a real fake-engine turn, and removes only its test data -AssertionError: expected [ 'claude', 'chatgpt' ] to deeply equal [ 'claude' ] -- Expected -+ Received +Exit code: 0 - [ - "claude", -+ "chatgpt", - ] +Run: core-final-2 +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 - ❯ server/control-cry.test.ts:261:39 - 259| const doctor = await runControlCry(["doctor"], { env }) as any; - 260| expect(doctor.ok).toBe(true); - 261| expect(doctor.availableEngines).toEqual(["claude"]); - | ^ - 262| - 263| const created = await runControlCry(["new-bot", "--name", "Verif… + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 07:44:23 + Duration 61.97s (transform 2.04s, setup 1.18s, import 1.50s, tests 59.14s, environment 0ms) + + +Exit code: 0 + +Run: core-final-3 +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + ❯ server/instabox/core.e2e.test.ts (15 tests | 1 failed) 56599ms + × deletes a retained InstaBox machine after switching backend 2335ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL server/instabox/core.e2e.test.ts > deletes a retained InstaBox machine after switching backend +AssertionError: expected 'suspended' to be 'deleted' // Object-is equality + +Expected: "deleted" +Received: "suspended" + + ❯ server/instabox/core.e2e.test.ts:380:51 + 378| const deleted = await request("DELETE", `/api/bots/${bot.id}`); + 379| expect(deleted.status).toBe(200); + 380| expect([...fake.machines.values()][0]?.state).toBe("deleted"); + | ^ + 381| } finally { await fixture.close(); await fake.close(); } + 382| }, 60_000); ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ Test Files 1 failed (1) - Tests 1 failed | 19 passed (20) - Start at 07:00:07 - Duration 13.83s (transform 2.24s, setup 1.44s, import 1.37s, tests 10.82s, environment 0ms) + Tests 1 failed | 14 passed (15) + Start at 07:45:25 + Duration 59.19s (transform 1.86s, setup 1.11s, import 1.33s, tests 56.60s, environment 0ms) Exit code: 1 -===== backend ===== -$ pnpm exec vitest run server/cloud-backend.test.ts --maxWorkers=1 +Run: baseline-full-1 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 12 passed (12) - Start at 07:00:22 - Duration 1.50s (transform 1.02s, setup 1.29s, import 39ms, tests 5ms, environment 0ms) + Tests 15 passed (15) + Start at 07:46:56 + Duration 62.86s (transform 2.36s, setup 1.29s, import 1.76s, tests 59.63s, environment 0ms) Exit code: 0 -===== index ===== -$ pnpm exec vitest run server/index.test.ts --maxWorkers=1 +Run: baseline-full-2 +HEAD baseline; all five code files temporarily restored +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 338 passed (338) - Start at 07:00:24 - Duration 161.98s (transform 2.15s, setup 1.18s, import 1.91s, tests 158.71s, environment 0ms) + Tests 15 passed (15) + Start at 07:48:00 + Duration 64.03s (transform 2.00s, setup 1.26s, import 1.37s, tests 61.24s, environment 0ms) Exit code: 0 -===== size ===== +Run: ratchet $ pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1 RUN v4.1.11 . @@ -324,26 +289,63 @@ $ pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1 Test Files 1 passed (1) Tests 1 passed (1) - Start at 07:03:07 - Duration 1.49s (transform 699ms, setup 903ms, import 9ms, tests 441ms, environment 0ms) + Start at 07:49:05 + Duration 2.06s (transform 1.01s, setup 1.27s, import 12ms, tests 604ms, environment 0ms) Exit code: 0 -===== tsc ===== +Run: tsc $ pnpm exec tsc -p tsconfig.server.json Exit code: 0 -===== oxlint ===== -$ pnpm exec oxlint --deny-warnings scripts/control-cry.ts scripts/control-cry.test.ts server/instabox/core.e2e.test.ts +Run: lint +$ pnpm exec oxlint --deny-warnings server/instabox/client.ts server/instabox/machine.ts server/instabox/machines.ts server/instabox/machines.test.ts server/testing/fake-instabox-core.ts Exit code: 0 -===== diff-check ===== -$ git diff --check +Run: core-confirm-1 +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 07:49:37 + Duration 63.91s (transform 2.12s, setup 1.22s, import 1.61s, tests 60.94s, environment 0ms) + + +Exit code: 0 + +Run: core-confirm-2 +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 07:50:41 + Duration 60.53s (transform 1.87s, setup 1.13s, import 1.33s, tests 57.90s, environment 0ms) + Exit code: 0 -Mutation self-check: expected refusal assertion failed after replacing the cloud wantedKind branch with undefined. server/index.ts restored; no final diff. -Launcher baseline check: the same extra chatgpt engine failed the exact same assertion with scripts/control-cry.ts restored from HEAD. Round 5 changes restored afterward. +Run: core-confirm-3 +$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 + + RUN v4.1.11 . + + + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 07:51:43 + Duration 58.85s (transform 1.38s, setup 830ms, import 1.02s, tests 56.87s, environment 0ms) + + +Exit code: 0 + +$ git diff --check +Exit code: 0 diff --git a/scripts/public-scan/allow-domains.txt b/scripts/public-scan/allow-domains.txt index 42bd2b38..91598a87 100644 --- a/scripts/public-scan/allow-domains.txt +++ b/scripts/public-scan/allow-domains.txt @@ -1,4 +1,5 @@ # 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 @@ -22,4 +23,3 @@ r2.md # 返工说明文件名,不是域名。 usercustomize.py # Python 启动钩子文件名,不是域名。 linux-test.sh # 脚本文件名,不是域名。 r3.md # 返工说明文件名,不是域名。 -instabox.sh # InstaBox 云电脑公共 API(第三方公开服务)。 diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts index e7db6169..0741c14f 100644 --- a/server/bot-box/env.test.ts +++ b/server/bot-box/env.test.ts @@ -61,7 +61,7 @@ const SERVER_ONLY_CRYBOT: ReadonlySet = new Set([ "CRYBOT_SHARED_WORKSPACE_FULL_ACCESS", "CRYBOT_SIGNIN_EMAILS", "CRYBOT_SIGNIN_MEMBER_EMAILS", "CRYBOT_SIGNIN_SMTP_FROM", "CRYBOT_SIGNIN_SMTP_URL", "CRYBOT_SKILLS_DIR", "CRYBOT_SMOKE_BUNDLED_CUA", "CRYBOT_SMOKE_CUA", "CRYBOT_SMOKE_KEEP_OPEN", "CRYBOT_SMOKE_TEST", "CRYBOT_SSE_HEARTBEAT_MS", "CRYBOT_STATIC_DIR", "CRYBOT_SYNC_ROOT", "CRYBOT_TAILNET_ADDRESSES", "CRYBOT_TAILNET_NAME", "CRYBOT_TAILNET_SERVED", "CRYBOT_TEAM_AWAY_WINDOW_MS", - "CRYBOT_TEAM_PRESENCE_GRACE_MS", "CRYBOT_TEST_INTERNAL_CAPABILITY_KEY", "CRYBOT_TEST_ORG_LIBRARY_KEY", + "CRYBOT_TEAM_PRESENCE_GRACE_MS", "CRYBOT_TEST_INSTABOX_API", "CRYBOT_TEST_INTERNAL_CAPABILITY_KEY", "CRYBOT_TEST_ORG_LIBRARY_KEY", "CRYBOT_TEST_PLAN_USAGE_FILE", "CRYBOT_TEST_TAILNET_STAND_IN", "CRYBOT_TOOL_STALL_MS", "CRYBOT_TREG_KEY", "CRYBOT_TREG_URL", "CRYBOT_TTS_DEFAULT_VOICE", "CRYBOT_TTS_KEY", "CRYBOT_TUNNEL_ORIGIN_PORT", "CRYBOT_TUNNEL_SOCKET", "CRYBOT_TURN_STALL_MS", "CRYBOT_UPDATE_CHANNEL", "CRYBOT_UPDATE_INSTALL", "CRYBOT_USER_DATA", "CRYBOT_WARM_SUMMARY", "CRYBOT_WARM_SUMMARY_TIME_SCALE", "CRYBOT_WEBHOOK_PORT", "CRYBOT_WEBHOOK_PUBLIC_URL", "CRYBOT_WEBHOOK_SOCKET", diff --git a/server/instabox/client.ts b/server/instabox/client.ts index b351f6f4..2108ecdd 100644 --- a/server/instabox/client.ts +++ b/server/instabox/client.ts @@ -53,6 +53,39 @@ export function createInstaboxRequest(apiKey: string, baseUrl = "https://api.ins return request; } +export async function readInstaboxFile(response: Response, maxBytes: number): Promise { + const tooLarge = () => new Error(`InstaBox readFile exceeds maxBytes=${maxBytes}`); + if (Number(response.headers.get("content-length")) > maxBytes) { + await response.body?.cancel().catch(() => {}); + throw tooLarge(); + } + if (!response.body) return new Uint8Array(); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const { done, value } = await reader.read().catch(() => { throw new InstaboxError(0, "network_error"); }); + if (done) break; + total += value.byteLength; + if (total > maxBytes) throw tooLarge(); + chunks.push(value); + } + const result = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + result.set(chunk, offset); + offset += chunk.byteLength; + } + return result; + } catch (error) { + await reader.cancel().catch(() => {}); + throw error; + } finally { + reader.releaseLock(); + } +} + export function instaboxVncUpstream(request: InstaboxRequest, machineId: string) { const connection = connections.get(request); if (!connection) throw new Error("InstaBox connection metadata is unavailable"); diff --git a/server/instabox/machine.ts b/server/instabox/machine.ts index 215b0b00..31ea32e1 100644 --- a/server/instabox/machine.ts +++ b/server/instabox/machine.ts @@ -17,7 +17,7 @@ export interface InstaboxMachines { suspend(botId: string): Promise; remove(botId: string): Promise; exec(machineId: string, req: InstaboxExecRequest): Promise; - readFile(machineId: string, path: string): Promise; + readFile(machineId: string, path: string, options?: { maxBytes?: number }): 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 }>; diff --git a/server/instabox/machines.test.ts b/server/instabox/machines.test.ts index 69505f00..de758bc9 100644 --- a/server/instabox/machines.test.ts +++ b/server/instabox/machines.test.ts @@ -78,6 +78,54 @@ it("uploads and downloads exact bytes and encodes file parameters", async () => expect((await service.vncUpstream(machine.id)).url).toContain(`/v1/machines/${machine.id}/vnc`); }); +it.each([undefined, 128])("rejects excessive Content-Length and cancels the body with maxBytes=%s", async maxBytes => { + const machine = await service.ensureRunning(botId); + const limit = maxBytes ?? 256 * 1024 * 1024; + const stream = fake.streamFile(machine.id, "/tmp/large", { + chunk: Buffer.alloc(64), chunkCount: 100, contentLength: limit + 1, + }); + await expect(service.readFile(machine.id, "/tmp/large", maxBytes === undefined ? undefined : { maxBytes })).rejects.toThrow( + new Error(`InstaBox readFile exceeds maxBytes=${limit}`), + ); + await expect.poll(() => stream.cancelled).toBe(true); + expect(stream.completed).toBe(false); + expect(stream.chunksSent * 64).toBeLessThan(limit + 1); +}); + +it("cancels an oversized chunked download before the server sends the entire file", async () => { + const machine = await service.ensureRunning(botId); + const stream = fake.streamFile(machine.id, "/tmp/chunked", { chunk: Buffer.alloc(64), chunkCount: 100 }); + await expect(service.readFile(machine.id, "/tmp/chunked", { maxBytes: 128 })).rejects.toThrow( + new Error("InstaBox readFile exceeds maxBytes=128"), + ); + await expect.poll(() => stream.cancelled).toBe(true); + expect(stream.chunksSent).toBeGreaterThanOrEqual(3); + expect(stream.chunksSent).toBeLessThan(stream.chunkCount); + expect(stream.completed).toBe(false); +}); + +it.each([undefined, 12])("reads exact bytes up to the limit with Content-Length=%s", async contentLength => { + const machine = await service.ensureRunning(botId); + const chunk = Buffer.from([0, 255, 128, 10]); + const stream = fake.streamFile(machine.id, "/tmp/bounded", { chunk, chunkCount: 3, contentLength }); + expect(await service.readFile(machine.id, "/tmp/bounded", { maxBytes: 12 })).toEqual(new Uint8Array(Buffer.concat([chunk, chunk, chunk]))); + expect(stream.completed).toBe(true); + expect(stream.cancelled).toBe(false); +}); + +it("allows an empty file with a zero-byte limit and rejects nonempty files", async () => { + const machine = await service.ensureRunning(botId); + await service.writeFile(machine.id, "/tmp/empty", new Uint8Array()); + expect(await service.readFile(machine.id, "/tmp/empty", { maxBytes: 0 })).toEqual(new Uint8Array()); + await service.writeFile(machine.id, "/tmp/nonempty", new Uint8Array([1])); + await expect(service.readFile(machine.id, "/tmp/nonempty", { maxBytes: 0 })).rejects.toThrow("maxBytes=0"); +}); + +it.each([-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])("rejects invalid maxBytes=%s before requesting a file", async maxBytes => { + await expect(service.readFile("unused", "/tmp/file", { maxBytes })).rejects.toThrow("maxBytes must be a non-negative safe integer"); + expect(fake.calls).toHaveLength(0); +}); + it("does not retry unrelated exec failures", async () => { const machine = await service.ensureRunning(botId); fake.failNext({ status: 409, code: "quota_exceeded" }); diff --git a/server/instabox/machines.ts b/server/instabox/machines.ts index 82ba788c..5bf8b582 100644 --- a/server/instabox/machines.ts +++ b/server/instabox/machines.ts @@ -1,5 +1,5 @@ import { setTimeout as delay } from "node:timers/promises"; -import { InstaboxError, instaboxVncUpstream, waitOperation } from "./client.ts"; +import { InstaboxError, instaboxVncUpstream, readInstaboxFile, waitOperation } from "./client.ts"; import type { InstaboxExecResult, InstaboxMachine, InstaboxMachines, InstaboxRequest, InstaboxTemplate } from "./machine.ts"; const LIFECYCLE_TIMEOUT = 180_000; @@ -98,10 +98,12 @@ export function createInstaboxMachines(request: InstaboxRequest): InstaboxMachin async exec(machineId, req) { return whileRunning(machineId, async () => (await request("POST", `${pathOf(machineId)}/exec`, { body: req })).json() as Promise); }, - async readFile(machineId, path) { + async readFile(machineId, path, options) { + const maxBytes = options?.maxBytes ?? 256 * 1024 * 1024; + if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new Error("InstaBox readFile maxBytes must be a non-negative safe integer"); return whileRunning(machineId, async () => { const response = await request("GET", `${pathOf(machineId)}/files/content`, { query: { path } }); - return new Uint8Array(await response.arrayBuffer()); + return readInstaboxFile(response, maxBytes); }); }, async writeFile(machineId, path, data, opts) { diff --git a/server/testing/fake-instabox-core.ts b/server/testing/fake-instabox-core.ts index f48381bb..4546584d 100644 --- a/server/testing/fake-instabox-core.ts +++ b/server/testing/fake-instabox-core.ts @@ -5,6 +5,10 @@ export async function fakeInstaboxCore() { const machines = new Map }>(); const operations = new Map(); const files = new Map(); + const fileStreams = new Map(); const desktop = new Set(); const calls: Array<{ method: string; path: string; query: URLSearchParams; headers: IncomingHttpHeaders; body: any }> = []; let failure: { status: number; code: string; message?: string } | undefined; @@ -65,13 +69,36 @@ export async function fakeInstaboxCore() { if (action === "exec") return send(200, { stdout: "fixture output", stderr: "", exitCode: 0, timedOut: false, truncated: false }); const fileKey = `${machine.id}:${url.searchParams.get("path")}`; if (action === "files" && req.method === "PUT") { files.set(fileKey, raw); res.writeHead(204); return res.end(); } - if (action === "files/content") { res.writeHead(200); return res.end(files.get(fileKey) ?? Buffer.alloc(0)); } + if (action === "files/content") { + const stream = fileStreams.get(fileKey); + if (stream) { + res.writeHead(200, stream.contentLength === undefined ? {} : { "Content-Length": stream.contentLength }); + res.flushHeaders(); + const timer = setInterval(() => { + res.write(stream.chunk); + stream.chunksSent++; + if (stream.chunksSent === stream.chunkCount) { + clearInterval(timer); + stream.completed = true; + res.end(); + } + }, 20); + res.on("close", () => { clearInterval(timer); stream.cancelled = !stream.completed; }); + return; + } + res.writeHead(200); return res.end(files.get(fileKey) ?? Buffer.alloc(0)); + } send(404, { error: { code: "not_found" } }); }); await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); const address = server.address(); if (!address || typeof address === "string") throw new Error("Fake InstaBox failed to listen"); return { url: `http://127.0.0.1:${address.port}`, calls, machines, operations, desktop, + streamFile: (machineId: string, path: string, options: { chunk: Buffer; chunkCount: number; contentLength?: number }) => { + const stream = { ...options, chunksSent: 0, cancelled: false, completed: false }; + fileStreams.set(`${machineId}:${path}`, stream); + return stream; + }, failNext: (next: NonNullable) => { failure = next; }, failOperations: () => { operationFailure = true; }, close: () => new Promise((resolve, reject) => { server.close(error => error ? reject(error) : resolve()); server.closeAllConnections(); }), diff --git a/src/locales/en.json b/src/locales/en.json index 09435657..2cadd6df 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -10608,6 +10608,9 @@ "vm.screens.take": "Take control of this screen", "vm.screens.count": "Number of screens", "vm.screens.resources": "Shared defaults: 8 GB memory · 3 CPUs, limited by the host.", + "serverError.instabox.keyMissing": "Add an InstaBox API key to use this computer.", + "serverError.instabox.template": "Choose a Linux or Android computer.", + "serverError.instabox.unavailable": "This InstaBox computer is unavailable.", "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." } diff --git a/src/locales/zh.json b/src/locales/zh.json index 1ae8f2ed..ac19f876 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -8014,6 +8014,9 @@ "vm.screens.take": "接管这块屏", "vm.screens.count": "屏数", "vm.screens.resources": "共享模式默认:8 GB 内存 · 3 核,不超过宿主机上限。", + "serverError.instabox.keyMissing": "请添加 InstaBox 钥匙以使用此电脑。", + "serverError.instabox.template": "请选择 Linux 或安卓电脑。", + "serverError.instabox.unavailable": "此 InstaBox 电脑暂时不可用。", "serverError.secret.saving": "此凭据正在保存中。", "serverError.secret.screenUnavailable": "此机器人已无法访问接收该凭据的屏幕。请让机器人重新请求凭据。" } From 61f1d11c52e078b1382ff8abf86cc734a3106531 Mon Sep 17 00:00:00 2001 From: tangzhixiong613-jpg <340458552+tangzhixiong613-jpg@users.noreply.github.com> Date: Sun, 15 Nov 2026 08:24:42 +0000 Subject: [PATCH 3/3] =?UTF-8?q?T-1242=20InstaBox=20=E6=A0=B8=E5=BF=83?= =?UTF-8?q?=EF=BC=9A=E6=9C=BA=E5=99=A8=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= =?UTF-8?q?=E3=80=81=E5=9B=9E=E5=90=88=E6=8E=A5=E5=85=A5=E3=80=81=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E4=B8=8E=E5=88=A0=E9=99=A4=EF=BC=9BreadFile=20?= =?UTF-8?q?=E6=B5=81=E5=BC=8F=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/tasks/T-1200/T-1242-instabox-core/r8.md | 17 ++ .../T-1200/T-1242-instabox-core/report.md | 41 +++ .../T-1242-instabox-core/verification.txt | 281 +++++++----------- server/config.ts | 2 - server/instabox/core.e2e.test.ts | 4 +- server/instabox/key.test.ts | 7 +- server/instabox/power.test.ts | 12 +- server/instabox/power.ts | 17 +- server/user-errors.ts | 3 + 9 files changed, 182 insertions(+), 202 deletions(-) create mode 100644 docs/tasks/T-1200/T-1242-instabox-core/r8.md diff --git a/docs/tasks/T-1200/T-1242-instabox-core/r8.md b/docs/tasks/T-1200/T-1242-instabox-core/r8.md new file mode 100644 index 00000000..88387449 --- /dev/null +++ b/docs/tasks/T-1200/T-1242-instabox-core/r8.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-1242 第 8 轮:合入 main(含 ④ T-1245)后两条 CI 分支独有失败 + +原任务见本文件夹 brief.md、r2–r7.md,工作区里已提交的改动保留。第 7 轮审核和安全审查都已通过。分支已合入最新 origin/main(④ T-1245 已在 main 上),GitHub Actions 只剩下面两条分支独有失败,只修这两条,不做别的改动。 + +## 必改 +1. `server/user-errors.test.ts` > 「the catalog's server errors are exactly the ones the server sends」:en.json 里有 `serverError.instabox.keyMissing`、`serverError.instabox.template`、`serverError.instabox.unavailable` 三个键,但服务端 `USER_ERROR` 目录里没有。按该测试的约定,把这三个键接进服务端错误目录(服务端实际发出这三种错误的地方都用这些键);不要删文案、不要改测试的判定方式。 +2. `server/config.test.ts` > 「credential env preference > persists and clears the key without turning a saved key into an environment override」:保存 `" fixture-instabox-key "` 后 `loadConfig().instabox` 得到带空格的原值,测试期望去掉首尾空白。找出 ① 和 ④ 两边对 `instabox.apiKey` 的保存/加载谁覆盖了谁,统一为:保存和环境变量读取都去掉首尾空白,空串视为未设置;不要把已保存的钥匙变成环境变量覆盖。 + +## 验收 +`server/user-errors.test.ts`、`server/config.test.ts`、`server/instabox/` 下全部测试、`server/bot-box/env.test.ts`、`scripts/testing/file-size-ratchet.test.ts` 逐文件跑过;`pnpm exec tsc -p tsconfig.server.json`;改动文件 `oxlint --deny-warnings`。report.md 追加第 8 轮一节(短);verification.txt 不写 IP、地址、域名、uuid、Object 相等判定写法。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/report.md b/docs/tasks/T-1200/T-1242-instabox-core/report.md index 06eae995..eaa01152 100644 --- a/docs/tasks/T-1200/T-1242-instabox-core/report.md +++ b/docs/tasks/T-1200/T-1242-instabox-core/report.md @@ -188,3 +188,44 @@ | `git diff --check` | 通过 | 此前两次完整 e2e 在 `core.e2e.test.ts:380` 出现间歇失败(期望 deleted,实际 suspended)。临时恢复 HEAD 的全部 5 个代码文件后,单独用例 6 次、完整 e2e 2 次均未复现,未确认原因;恢复本轮改动后最终三连过。完整命令、失败及成功输出均见 [verification.txt](verification.txt),已检查不含 IP、连接地址、域名或 UUID。 + + +## 第 8 轮 + +1. 改了什么 + +本轮文件清单与 `git status --short` 一致;未提交 git。 + +```text + M docs/tasks/T-1200/T-1242-instabox-core/report.md + M docs/tasks/T-1200/T-1242-instabox-core/verification.txt + M server/config.ts + M server/instabox/core.e2e.test.ts + M server/instabox/key.test.ts + M server/instabox/power.test.ts + M server/instabox/power.ts + M server/user-errors.ts +``` + +三种 错误接入 `USER_ERROR`,实际错误和状态提示使用目录文案与键;更新相关断言。删除重复配置定义,补充保存、读取去空白及纯空白清除回归。 + +2. 为什么 + +①的宽松 `instabox` schema 排在④的 `.trim().max(8192)` 严格 schema 后,覆盖了保存和加载校验;现保留④的定义,环境读取继续去空白、空白回退文件配置,保存不写入环境变量。错误目录与现有英文文案一致,未修改目录测试的判定方式。 + +3. 测试命令与结果摘要 + +已执行 依赖准备脚本。仓库缺少验证说明;全部服务测试使用隔离 fixture 和假服务。Vitest 均以 `pnpm exec vitest run <文件> --maxWorkers=1` 逐文件执行。 + +| 文件或命令 | 结果 | +| --- | --- | +| `server/user-errors.test.ts`、`server/config.test.ts` | 分别 5、257 项通过 | +| `server/instabox/{client,key,machines,persistence,power,vnc}.test.ts` | 分别 6、4、24、1、7、2 项通过 | +| `server/bot-box/env.test.ts`、`server/routes/config-instabox.test.ts`、`scripts/testing/file-size-ratchet.test.ts` | 分别 11、6、1 项通过 | +| `server/instabox/core.e2e.test.ts` | 连续 3 次,每次 15 项通过 | +| `CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1` | 完整连续 3 次,每次 32 项通过;此前未指定浏览器的三轮各跳过 1 项 | +| `pnpm exec tsc -p tsconfig.server.json` | 失败:未改动的 `server/routes/config-instabox.test.ts:20` 中 `status`、`auth` 两处 TS7006;临时恢复全部源码改动后同样复现,基线另有本轮已修的重复定义错误 | +| `pnpm exec oxlint --deny-warnings server/config.ts server/instabox/core.e2e.test.ts server/instabox/key.test.ts server/instabox/power.test.ts server/instabox/power.ts server/user-errors.ts` | 通过,0 警告、0 错误 | +| `git diff --check` | 通过 | + +完整脱敏输出见 [verification.txt](verification.txt)。 diff --git a/docs/tasks/T-1200/T-1242-instabox-core/verification.txt b/docs/tasks/T-1200/T-1242-instabox-core/verification.txt index 60ddc2b2..27ec2896 100644 --- a/docs/tasks/T-1200/T-1242-instabox-core/verification.txt +++ b/docs/tasks/T-1200/T-1242-instabox-core/verification.txt @@ -1,194 +1,145 @@ -T-1242 第 7 轮验证 -所有服务验证使用隔离 fixture 和假服务。 -docs/verification/README.md 在仓库中不存在。 -输出中的仓库绝对路径及连接信息已脱敏。 +T-1242 第 8 轮验证 +所有测试逐文件串行执行,服务验证使用临时目录、隔离 fixture 和假服务。 +仓库缺少 docs/verification/README.md。 +VNC 初始三轮未指定浏览器,各跳过一项;指定 Chromium 后完整三轮全过。 +服务端类型检查剩余两处隐式 any;恢复 HEAD 的对照检查同样复现,未扩展修复范围。 $ crybot-link-deps -crybot-link-deps: linked 73 entries into worktree node_modules +crybot-link-deps: linked 73 entries from /opt/crybot-deps/node_modules into ./node_modules Exit code: 0 -Run: machines -$ pnpm exec vitest run server/instabox/machines.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/user-errors.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 24 passed (24) - Start at 07:38:54 - Duration 2.37s (transform 1.04s, setup 1.34s, import 37ms, tests 787ms, environment 0ms) - + Tests 5 passed (5) + Start at 08:16:20 + Duration 1.95s (transform 1.18s, setup 1.59s, import 86ms, tests 12ms, environment 0ms) Exit code: 0 -Run: client -$ pnpm exec vitest run server/instabox/client.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/config.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 6 passed (6) - Start at 07:39:21 - Duration 1.77s (transform 1.14s, setup 1.46s, import 30ms, tests 88ms, environment 0ms) - + Tests 257 passed (257) + Start at 08:16:22 + Duration 2.49s (transform 958ms, setup 1.08s, import 164ms, tests 1.10s, environment 0ms) Exit code: 0 -Run: power -$ pnpm exec vitest run server/instabox/power.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/instabox/client.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 7 passed (7) - Start at 07:39:24 - Duration 1.25s (transform 830ms, setup 1.04s, import 35ms, tests 8ms, environment 0ms) - + Tests 6 passed (6) + Start at 08:16:25 + Duration 1.33s (transform 856ms, setup 1.07s, import 32ms, tests 88ms, environment 0ms) Exit code: 0 -Run: core-1 -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/instabox/key.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 15 passed (15) - Start at 07:39:25 - Duration 62.74s (transform 1.90s, setup 1.11s, import 1.48s, tests 59.98s, environment 0ms) - + Tests 4 passed (4) + Start at 08:16:27 + Duration 1.26s (transform 849ms, setup 1.08s, import 10ms, tests 17ms, environment 0ms) Exit code: 0 -Run: core-2 -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/instabox/machines.test.ts --maxWorkers=1 RUN v4.1.11 . - ❯ server/instabox/core.e2e.test.ts (15 tests | 1 failed) 58941ms - × deletes a retained InstaBox machine after switching backend 2513ms - -⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ - - FAIL server/instabox/core.e2e.test.ts > deletes a retained InstaBox machine after switching backend -AssertionError: expected 'suspended' to be 'deleted' // Object-is equality - -Expected: "deleted" -Received: "suspended" - - ❯ server/instabox/core.e2e.test.ts:380:51 - 378| const deleted = await request("DELETE", `/api/bots/${bot.id}`); - 379| expect(deleted.status).toBe(200); - 380| expect([...fake.machines.values()][0]?.state).toBe("deleted"); - | ^ - 381| } finally { await fixture.close(); await fake.close(); } - 382| }, 60_000); - -⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ - - - Test Files 1 failed (1) - Tests 1 failed | 14 passed (15) - Start at 07:40:29 - Duration 61.62s (transform 1.92s, setup 1.17s, import 1.36s, tests 58.94s, environment 0ms) + Test Files 1 passed (1) + Tests 24 passed (24) + Start at 08:16:29 + Duration 1.93s (transform 780ms, setup 983ms, import 35ms, tests 782ms, environment 0ms) -Exit code: 1 +Exit code: 0 -Run: baseline-core-1 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' +$ pnpm exec vitest run server/instabox/persistence.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 1 passed | 14 skipped (15) - Start at 07:42:25 - Duration 4.41s (transform 1.57s, setup 920ms, import 1.16s, tests 2.19s, environment 0ms) - + Tests 1 passed (1) + Start at 08:16:32 + Duration 1.81s (transform 1.10s, setup 1.02s, import 400ms, tests 258ms, environment 0ms) Exit code: 0 -Run: baseline-core-2 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' +$ pnpm exec vitest run server/instabox/power.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 1 passed | 14 skipped (15) - Start at 07:42:30 - Duration 4.67s (transform 1.64s, setup 979ms, import 1.19s, tests 2.34s, environment 0ms) - + Tests 7 passed (7) + Start at 08:16:34 + Duration 1.16s (transform 773ms, setup 978ms, import 36ms, tests 9ms, environment 0ms) Exit code: 0 -Run: baseline-core-3 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' +$ pnpm exec vitest run server/instabox/vnc.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 1 passed | 14 skipped (15) - Start at 07:42:35 - Duration 4.60s (transform 1.71s, setup 1.00s, import 1.25s, tests 2.21s, environment 0ms) - + Tests 2 passed (2) + Start at 08:16:36 + Duration 1.17s (transform 802ms, setup 1.01s, import 18ms, tests 7ms, environment 0ms) Exit code: 0 -Run: baseline-core-4 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' +$ pnpm exec vitest run server/bot-box/env.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 1 passed | 14 skipped (15) - Start at 07:42:40 - Duration 4.46s (transform 1.62s, setup 935ms, import 1.19s, tests 2.20s, environment 0ms) - + Tests 11 passed (11) + Start at 08:16:37 + Duration 1.35s (transform 901ms, setup 1.14s, import 24ms, tests 49ms, environment 0ms) Exit code: 0 -Run: baseline-core-5 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' +$ pnpm exec vitest run server/routes/config-instabox.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 1 passed | 14 skipped (15) - Start at 07:42:45 - Duration 4.35s (transform 1.56s, setup 881ms, import 1.17s, tests 2.18s, environment 0ms) - + Tests 6 passed (6) + Start at 08:16:39 + Duration 3.47s (transform 2.56s, setup 1.17s, import 2.08s, tests 74ms, environment 0ms) Exit code: 0 -Run: baseline-core-6 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 -t 'deletes a retained InstaBox machine after switching backend' +$ 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 | 14 skipped (15) - Start at 07:42:50 - Duration 4.51s (transform 1.63s, setup 962ms, import 1.20s, tests 2.20s, environment 0ms) - + Tests 1 passed (1) + Start at 08:16:43 + Duration 1.32s (transform 838ms, setup 1.08s, import 12ms, tests 87ms, environment 0ms) Exit code: 0 -Run: core-final-1 $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . @@ -196,13 +147,11 @@ $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 Test Files 1 passed (1) Tests 15 passed (15) - Start at 07:43:19 - Duration 63.42s (transform 2.02s, setup 1.17s, import 1.49s, tests 60.60s, environment 0ms) - + Start at 08:16:45 + Duration 61.15s (transform 1.76s, setup 1.01s, import 1.58s, tests 58.41s, environment 0ms) Exit code: 0 -Run: core-final-2 $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . @@ -210,142 +159,114 @@ $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 Test Files 1 passed (1) Tests 15 passed (15) - Start at 07:44:23 - Duration 61.97s (transform 2.04s, setup 1.18s, import 1.50s, tests 59.14s, environment 0ms) - + Start at 08:17:47 + Duration 55.14s (transform 1.65s, setup 986ms, import 1.18s, tests 52.84s, environment 0ms) Exit code: 0 -Run: core-final-3 $ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . - ❯ server/instabox/core.e2e.test.ts (15 tests | 1 failed) 56599ms - × deletes a retained InstaBox machine after switching backend 2335ms - -⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ - - FAIL server/instabox/core.e2e.test.ts > deletes a retained InstaBox machine after switching backend -AssertionError: expected 'suspended' to be 'deleted' // Object-is equality - -Expected: "deleted" -Received: "suspended" - - ❯ server/instabox/core.e2e.test.ts:380:51 - 378| const deleted = await request("DELETE", `/api/bots/${bot.id}`); - 379| expect(deleted.status).toBe(200); - 380| expect([...fake.machines.values()][0]?.state).toBe("deleted"); - | ^ - 381| } finally { await fixture.close(); await fake.close(); } - 382| }, 60_000); - -⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ - - - Test Files 1 failed (1) - Tests 1 failed | 14 passed (15) - Start at 07:45:25 - Duration 59.19s (transform 1.86s, setup 1.11s, import 1.33s, tests 56.60s, environment 0ms) + Test Files 1 passed (1) + Tests 15 passed (15) + Start at 08:18:43 + Duration 57.75s (transform 1.43s, setup 829ms, import 1.07s, tests 55.73s, environment 0ms) -Exit code: 1 +Exit code: 0 -Run: baseline-full-1 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 15 passed (15) - Start at 07:46:56 - Duration 62.86s (transform 2.36s, setup 1.29s, import 1.76s, tests 59.63s, environment 0ms) - + Tests 31 passed | 1 skipped (32) + Start at 08:19:41 + Duration 3.22s (transform 1.32s, setup 911ms, import 790ms, tests 1.39s, environment 0ms) Exit code: 0 -Run: baseline-full-2 -HEAD baseline; all five code files temporarily restored -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 15 passed (15) - Start at 07:48:00 - Duration 64.03s (transform 2.00s, setup 1.26s, import 1.37s, tests 61.24s, environment 0ms) - + Tests 31 passed | 1 skipped (32) + Start at 08:19:45 + Duration 3.19s (transform 1.30s, setup 891ms, import 793ms, tests 1.38s, environment 0ms) Exit code: 0 -Run: ratchet -$ pnpm exec vitest run scripts/testing/file-size-ratchet.test.ts --maxWorkers=1 +$ pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 1 passed (1) - Start at 07:49:05 - Duration 2.06s (transform 1.01s, setup 1.27s, import 12ms, tests 604ms, environment 0ms) - + Tests 31 passed | 1 skipped (32) + Start at 08:19:48 + Duration 3.21s (transform 1.29s, setup 875ms, import 781ms, tests 1.41s, environment 0ms) Exit code: 0 -Run: tsc $ pnpm exec tsc -p tsconfig.server.json +server/routes/config-instabox.test.ts(20,23): error TS7006: Parameter 'status' implicitly has an 'any' type. +server/routes/config-instabox.test.ts(20,31): error TS7006: Parameter 'auth' implicitly has an 'any' type. +Exit code: 1 -Exit code: 0 - -Run: lint -$ pnpm exec oxlint --deny-warnings server/instabox/client.ts server/instabox/machine.ts server/instabox/machines.ts server/instabox/machines.test.ts server/testing/fake-instabox-core.ts - -Exit code: 0 +Baseline check: temporarily restored all changed source files to HEAD. +$ pnpm exec tsc -p tsconfig.server.json +server/config.ts(352,3): error TS1117: An object literal cannot have multiple properties with the same name. +server/config.ts(459,3): error TS2300: Duplicate identifier 'instabox'. +server/config.ts(462,3): error TS2300: Duplicate identifier 'instabox'. +server/routes/config-instabox.test.ts(20,23): error TS7006: Parameter 'status' implicitly has an 'any' type. +server/routes/config-instabox.test.ts(20,31): error TS7006: Parameter 'auth' implicitly has an 'any' type. +Exit code: 1 +Restored round 8 changes. -Run: core-confirm-1 -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 15 passed (15) - Start at 07:49:37 - Duration 63.91s (transform 2.12s, setup 1.22s, import 1.61s, tests 60.94s, environment 0ms) - + Tests 32 passed (32) + Start at 08:21:00 + Duration 3.78s (transform 1.24s, setup 864ms, import 732ms, tests 2.05s, environment 0ms) Exit code: 0 -Run: core-confirm-2 -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 15 passed (15) - Start at 07:50:41 - Duration 60.53s (transform 1.87s, setup 1.13s, import 1.33s, tests 57.90s, environment 0ms) - + Tests 32 passed (32) + Start at 08:21:05 + Duration 3.58s (transform 1.17s, setup 737ms, import 759ms, tests 1.96s, environment 0ms) Exit code: 0 -Run: core-confirm-3 -$ pnpm exec vitest run server/instabox/core.e2e.test.ts --maxWorkers=1 +$ CRYBOT_CDP_CHROME=/usr/bin/chromium pnpm exec vitest run server/instabox/vnc.e2e.test.ts --maxWorkers=1 RUN v4.1.11 . Test Files 1 passed (1) - Tests 15 passed (15) - Start at 07:51:43 - Duration 58.85s (transform 1.38s, setup 830ms, import 1.02s, tests 56.87s, environment 0ms) + Tests 32 passed (32) + Start at 08:21:09 + Duration 3.53s (transform 1.12s, setup 783ms, import 643ms, tests 1.99s, environment 0ms) +Exit code: 0 +$ pnpm exec oxlint --deny-warnings server/config.ts server/instabox/core.e2e.test.ts server/instabox/key.test.ts server/instabox/power.test.ts server/instabox/power.ts server/user-errors.ts Exit code: 0 $ git diff --check Exit code: 0 + +Verification redaction and report file list checks: passed. diff --git a/server/config.ts b/server/config.ts index 4228e99c..445e503d 100644 --- a/server/config.ts +++ b/server/config.ts @@ -349,7 +349,6 @@ const appConfigSchema = z.object({ box: z.object({ token: optionalText }).optional(), instabox: z.object({ apiKey: z.string().trim().max(8192) }).strict().optional(), vps: vpsConfigSchema.optional(), - instabox: z.object({ apiKey: z.string().optional() }).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(), /** `provider`: "elevenlabs" (default, `key`), "fish" (`fishKey`, `fishModel`), "system", "xai" (`xai.key`), "gemini" (`geminiKey`, `model`), "openai" (`openai.key`) or "chatterbox" (local; `baseUrl`, `model`). */ @@ -459,7 +458,6 @@ export interface AppConfig extends HelperConfig { instabox?: { apiKey?: string }; /** A named host from the user's SSH config. Authentication stays with SSH. */ vps?: { sshAlias?: string }; - instabox?: { apiKey?: string }; opencodeGo?: { apiKey?: string; providerKeys?: Record }; tts?: { key?: string; fishKey?: string; geminiKey?: string; voice?: string; provider?: "elevenlabs" | "fish" | "system" | "chatterbox" | "xai" | "gemini" | "openai"; baseUrl?: string; model?: string; fishModel?: FishTtsModel; everyReply?: boolean }; decider?: DeciderConfig; diff --git a/server/instabox/core.e2e.test.ts b/server/instabox/core.e2e.test.ts index 62f716fd..b0c58b9b 100644 --- a/server/instabox/core.e2e.test.ts +++ b/server/instabox/core.e2e.test.ts @@ -99,9 +99,9 @@ it("boots an isolated InstaBox bot, persists its backend, suspends on switching, await fixture.stop(); env.INSTABOX_API_KEY = ""; await fixture.start(); - expect((await request("GET", `${missingPath}/computer`)).body).toMatchObject({ backend: "instabox", configured: false, problem: "InstaBox 钥匙未配置" }); + expect((await request("GET", `${missingPath}/computer`)).body).toMatchObject({ backend: "instabox", configured: false, problem: "Add an InstaBox API key to use this computer." }); const callsBeforeMissingProvision = fake.calls.length; - expect(await request("POST", `${missingPath}/computer/provision`, {})).toMatchObject({ status: 409, body: { error: "InstaBox 钥匙未配置", errorKey: "serverError.instabox.keyMissing" } }); + expect(await request("POST", `${missingPath}/computer/provision`, {})).toMatchObject({ status: 409, body: { error: "Add an InstaBox API key to use this computer.", errorKey: "serverError.instabox.keyMissing" } }); expect(fake.calls.slice(callsBeforeMissingProvision).some(call => call.path === "/v1/machines")).toBe(false); expect(readFileSync(fixture.logPath, "utf8")).not.toContain("instabox-e2e-fixture"); } finally { await fixture.close(); await fake.close(); } diff --git a/server/instabox/key.test.ts b/server/instabox/key.test.ts index 18100eaf..89b94881 100644 --- a/server/instabox/key.test.ts +++ b/server/instabox/key.test.ts @@ -14,11 +14,12 @@ it("prefers a nonempty environment key, then config, treating blanks as unconfig }); it("parses and persists the server config section", () => { - expect(parseStoredConfig({ instabox: { apiKey: "config-fixture" } }).instabox).toEqual({ apiKey: "config-fixture" }); - saveConfig({ instabox: { apiKey: "saved-fixture" } }); + expect(parseStoredConfig({ instabox: { apiKey: " config-fixture " } }).instabox).toEqual({ apiKey: "config-fixture" }); + saveConfig({ instabox: { apiKey: " saved-fixture " } }); expect(loadConfig().instabox?.apiKey).toBe("saved-fixture"); - saveConfig({ instabox: { apiKey: "" } }); + saveConfig({ instabox: { apiKey: " " } }); expect(loadConfig().instabox?.apiKey).toBe(""); + expect(instaboxConfigured(loadConfig())).toBe(false); }); diff --git a/server/instabox/power.test.ts b/server/instabox/power.test.ts index 257e397e..3052b559 100644 --- a/server/instabox/power.test.ts +++ b/server/instabox/power.test.ts @@ -21,9 +21,9 @@ it("reuses machines for the same key and replaces the instance after key rotatio }); it("makes missing credentials explicit in status and lifecycle actions", async () => { - expect(() => requireInstabox(null)).toThrow("InstaBox 钥匙未配置"); - expect(await instaboxStatus(null, "bot")).toMatchObject({ backend: "instabox", configured: false, problem: "InstaBox 钥匙未配置" }); - await expect(instaboxComputerAction(null, "bot", "provision", {})).rejects.toThrow("InstaBox 钥匙未配置"); + expect(() => requireInstabox(null)).toThrow("Add an InstaBox API key to use this computer."); + expect(await instaboxStatus(null, "bot")).toMatchObject({ backend: "instabox", configured: false, problem: "Add an InstaBox API key to use this computer." }); + await expect(instaboxComputerAction(null, "bot", "provision", {})).rejects.toThrow("Add an InstaBox API key to use this computer."); }); it.each([200, 400])("suspends after a successful backend switch only (status %s)", async status => { @@ -57,11 +57,11 @@ it("sends translation keys for user errors while preserving provider failures", try { requireInstabox(null); } catch (error) { expect(instaboxFailureResponse(error)).toEqual({ status: 409, - body: { error: "InstaBox 钥匙未配置", errorKey: "serverError.instabox.keyMissing" } }); + body: { error: "Add an InstaBox API key to use this computer.", errorKey: "serverError.instabox.keyMissing" } }); } const service = {} as InstaboxMachines; - await expect(instaboxComputerAction(service, "bot", "provision", { template: "apple" })).rejects.toMatchObject({ status: 400, errorKey: "serverError.instabox.template" }); - await expect(instaboxComputerAction(service, "bot", "join", {})).rejects.toMatchObject({ status: 501, errorKey: "serverError.instabox.unavailable" }); + await expect(instaboxComputerAction(service, "bot", "provision", { template: "apple" })).rejects.toMatchObject({ status: 400, message: "Choose a Linux or Android computer.", errorKey: "serverError.instabox.template" }); + await expect(instaboxComputerAction(service, "bot", "join", {})).rejects.toMatchObject({ status: 501, message: "This InstaBox computer is unavailable.", errorKey: "serverError.instabox.unavailable" }); const providerFailure = new Error("provider failed"); expect(() => instaboxFailureResponse(providerFailure)).toThrow(providerFailure); }); diff --git a/server/instabox/power.ts b/server/instabox/power.ts index 03216709..38f48a8a 100644 --- a/server/instabox/power.ts +++ b/server/instabox/power.ts @@ -1,18 +1,17 @@ import type { AppConfig } from "../config.ts"; import type { RouteHandler } from "../routes/table.ts"; import type { BotRecord } from "../store.ts"; +import { USER_ERROR, type UserErrorKey } from "../user-errors.ts"; import { createInstaboxRequest } from "./client.ts"; import { instaboxApiKey } from "./key.ts"; import type { InstaboxMachines, InstaboxRequest } from "./machine.ts"; import { createInstaboxMachines } from "./machines.ts"; -export const INSTABOX_KEY_MISSING = "InstaBox 钥匙未配置"; - class InstaboxUserError extends Error { readonly status: number; - readonly errorKey: string; - constructor(status: number, errorKey: string, message: string) { - super(message); + readonly errorKey: UserErrorKey; + constructor(status: number, errorKey: UserErrorKey) { + super(USER_ERROR[errorKey]); this.status = status; this.errorKey = errorKey; } @@ -34,14 +33,14 @@ export function createInstaboxMachineCache(makeRequest: (key: string) => Instabo } export function requireInstabox(machines: InstaboxMachines | null): InstaboxMachines { - if (!machines) throw new InstaboxUserError(409, "serverError.instabox.keyMissing", INSTABOX_KEY_MISSING); + if (!machines) throw new InstaboxUserError(409, "serverError.instabox.keyMissing"); return machines; } export async function instaboxStatus(machines: InstaboxMachines | null, botId: string) { if (!machines) { return { backend: "instabox" as const, configured: false, ready: false, machine: null, - problem: INSTABOX_KEY_MISSING, problemKey: "serverError.instabox.keyMissing" }; + problem: USER_ERROR["serverError.instabox.keyMissing"], problemKey: "serverError.instabox.keyMissing" }; } try { const machine = await machines.find(botId); @@ -57,13 +56,13 @@ export async function instaboxComputerAction(machines: InstaboxMachines | null, if (action === "provision") { const template = (body as { template?: unknown } | null)?.template; if (template !== undefined && template !== "linux" && template !== "android") { - throw new InstaboxUserError(400, "serverError.instabox.template", "InstaBox template must be linux or android"); + throw new InstaboxUserError(400, "serverError.instabox.template"); } return { machine: await service.ensureRunning(botId, template === undefined ? undefined : { template }) }; } if (action === "sleep") { await service.suspend(botId); return { ok: true }; } if (action === "remove") { await service.remove(botId); return { ok: true }; } - throw new InstaboxUserError(501, "serverError.instabox.unavailable", "InstaBox computer access is unavailable"); + throw new InstaboxUserError(501, "serverError.instabox.unavailable"); } export function withInstaboxBackendPower(handler: RouteHandler, deps: { diff --git a/server/user-errors.ts b/server/user-errors.ts index 34a2b5f5..156a96fd 100644 --- a/server/user-errors.ts +++ b/server/user-errors.ts @@ -4,6 +4,9 @@ import { formatServerText, type ServerErrorBody, type ServerTextParams } from ". /** The client translates by key and falls back to this English, which the server keeps sending for older clients. */ export const USER_ERROR = { + "serverError.instabox.keyMissing": "Add an InstaBox API key to use this computer.", + "serverError.instabox.template": "Choose a Linux or Android computer.", + "serverError.instabox.unavailable": "This InstaBox computer is unavailable.", "serverError.pair.codeWrong": "pairing code is wrong or has expired; create a new one on the server", "serverError.pair.tooMany": "Too many wrong codes. Try again at {time}.", ...PAIRING_INPUT_PROBLEM_TEXT,