| 1 | |
| 2 | import { createRequire } from "node:module"; |
| 3 | import { defaultAppearance, presets } from "../src/appearance-state.mjs"; |
| 4 | const require = createRequire(import.meta.url); |
| 5 | export async function createWorkbench({ |
| 6 | viewport = { width: 1280, height: 850 }, |
| 7 | recordVideo, |
| 8 | deviceScaleFactor = 1, |
| 9 | favoritesRequest, |
| 10 | browserRequest, |
| 11 | mockWebSockets = true, |
| 12 | url, |
| 13 | nativeRequest, |
| 14 | clientRequest, |
| 15 | cliRequest, |
| 16 | beforeNavigate, |
| 17 | launchOptions = {}, |
| 18 | startupFailure = false, |
| 19 | waitForReady = true, |
| 20 | initialization = { required: false }, |
| 21 | clientContext = { mode: "local", connection_id: "local", client_platform: "darwin", server_platform: "darwin", connection: { state: "disconnected" } }, |
| 22 | } = {}) { |
| 23 | const engines = require( |
| 24 | process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", |
| 25 | ); |
| 26 | const browser = await engines[process.env.CAGE_TEST_BROWSER || "chromium"].launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH, ...launchOptions }); |
| 27 | const context = await browser.newContext({ viewport, recordVideo, deviceScaleFactor }); |
| 28 | const page = await context.newPage(); |
| 29 | const errors = []; |
| 30 | page.on("pageerror", (error) => errors.push(error.message)); |
| 31 | const state = { |
| 32 | appearance: structuredClone(defaultAppearance), |
| 33 | codexAppearance: { |
| 34 | ...structuredClone(defaultAppearance), |
| 35 | uiFontSize: 16, |
| 36 | codeFontSize: 13, |
| 37 | lightTheme: { |
| 38 | ...structuredClone(defaultAppearance.lightTheme), |
| 39 | ...presets.light.solarized, |
| 40 | preset: "solarized", |
| 41 | }, |
| 42 | darkTheme: { |
| 43 | ...structuredClone(defaultAppearance.darkTheme), |
| 44 | ...presets.dark.ayu, |
| 45 | preset: "ayu", |
| 46 | }, |
| 47 | }, |
| 48 | failAppearance: false, |
| 49 | chosenFolder: "/Users/shihao/Projects/design-lab", |
| 50 | failSave: false, |
| 51 | failJob: false, |
| 52 | hostGit: { |
| 53 | state: "ok", |
| 54 | ready: true, |
| 55 | can_enable: false, |
| 56 | message: "本机 Git 安全保护已启用。", |
| 57 | }, |
| 58 | failHostGit: false, |
| 59 | saves: [], |
| 60 | requests: [], |
| 61 | terminalConnections: 0, |
| 62 | initialization: structuredClone(initialization), |
| 63 | account: { exists: true, unlocked: true, username: "林间工作室", avatar: "" }, |
| 64 | accountPassword: "fixture-password", |
| 65 | failAccountSave: false, |
| 66 | settings: { |
| 67 | workspace: "/Users/shihao/.claude-cage-workspace", |
| 68 | browser_home_url: "https://www.bing.com/", |
| 69 | dns_url: "https://cloudflare-dns.com/dns-query", |
| 70 | timezone: "Asia/Shanghai", |
| 71 | locale: "zh_CN.UTF-8", |
| 72 | browser_language: "zh-CN", |
| 73 | auto_timezone: true, |
| 74 | auto_language: false, |
| 75 | keyboard: "mac", |
| 76 | exit_policy: { mode: "dynamic", scope: "country", country_code: "US" }, |
| 77 | }, |
| 78 | status: { |
| 79 | environment_directory: "/Users/shihao/.claude-cage-workspace", |
| 80 | environment_workspace: true, |
| 81 | projects: ["/Users/shihao/.claude-cage-workspace"], |
| 82 | ready: false, |
| 83 | vm_running: false, |
| 84 | keyboard: "mac", |
| 85 | job: { running: false }, |
| 86 | can_restore: true, |
| 87 | }, |
| 88 | tabs: [], |
| 89 | terminals: [], |
| 90 | active: "", |
| 91 | sequence: 0, |
| 92 | }; |
| 93 | await page.exposeFunction("chooseTestFolder", () => state.chosenFolder); |
| 94 | await page.exposeFunction("requestNativeForTest", async (body) => nativeRequest ? nativeRequest(body) : null); |
| 95 | await page.addInitScript(() => { |
| 96 | window.webkit = { |
| 97 | messageHandlers: { |
| 98 | cage: { |
| 99 | postMessage: async (body) => { |
| 100 | const { action } = body; |
| 101 | if (action === "chooseFolder") return window.chooseTestFolder(); |
| 102 | if (action === "clipboardRead") return "fixture clipboard"; |
| 103 | return window.requestNativeForTest(body); |
| 104 | }, |
| 105 | }, |
| 106 | }, |
| 107 | }; |
| 108 | }); |
| 109 | if (mockWebSockets) await page.routeWebSocket("**/api/**", (socket) => { |
| 110 | if (socket.url().includes("/terminals/")) { |
| 111 | state.terminalConnections++; |
| 112 | socket.send( |
| 113 | Buffer.from( |
| 114 | "\r\n\u001b[1mCage\u001b[0m · Linux terminal\r\n\r\n~/Projects/design-lab $ ", |
| 115 | ), |
| 116 | ); |
| 117 | } else socket.close(); |
| 118 | }); |
| 119 | await page.route("**/api/**", async (route) => { |
| 120 | const request = route.request(); |
| 121 | const path = new URL(request.url()).pathname.replace("/api", ""); |
| 122 | const body = request.headers()["content-type"]?.includes("application/json") ? request.postDataJSON() : undefined; |
| 123 | state.requests.push({ path, method: request.method(), body: path.startsWith("/account") ? undefined : body }); |
| 124 | if (clientRequest && path.startsWith("/client/")) return clientRequest(route, path, body); |
| 125 | if (path === "/client/context") return route.fulfill({ json: clientContext }); |
| 126 | if (path === "/environment/initialization") { |
| 127 | if (body?.action === "install") state.initialization.started = true; |
| 128 | if (body?.action === "complete") state.initialization.required = false; |
| 129 | return route.fulfill({ json: state.initialization }); |
| 130 | } |
| 131 | const accountView = () => ({ ...state.account, background_running: state.status.vm_running }); |
| 132 | if (path === "/account") return route.fulfill({ json: accountView() }); |
| 133 | if (path.startsWith("/account/")) { |
| 134 | const action = path.split("/").at(-1); |
| 135 | if (!["create", "unlock"].includes(action) && !state.account.unlocked) return route.fulfill({ status: 423, body: "请先解锁 Cage" }); |
| 136 | if (action === "create") { |
| 137 | if (state.account.exists || !body.username?.trim() || body.password?.length < 8 || body.password !== body.confirm_password) return route.fulfill({ status: 400, body: "账户信息无效" }); |
| 138 | Object.assign(state.account, { exists: true, unlocked: true, username: body.username.trim(), avatar: body.avatar || "" }); |
| 139 | state.accountPassword = body.password; |
| 140 | } else if (action === "unlock") { |
| 141 | if (body.password !== state.accountPassword) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", body: "密码不正确" }); |
| 142 | state.account.unlocked = true; |
| 143 | state.account.require_authentication = false; |
| 144 | } else if (action === "profile") { |
| 145 | if (state.failAccountSave) return route.fulfill({ status: 400, body: "资料未能保存,请重试" }); |
| 146 | Object.assign(state.account, { username: body.username.trim(), avatar: body.avatar }); |
| 147 | } else if (action === "password") { |
| 148 | if (body.old_password !== state.accountPassword) return route.fulfill({ status: 400, body: "密码不正确" }); |
| 149 | if (body.password?.length < 8 || body.password !== body.confirm_password) return route.fulfill({ status: 400, body: "新密码无效" }); |
| 150 | state.accountPassword = body.password; |
| 151 | } else if (action === "lock") { state.account.unlocked = false; state.account.require_authentication = true; } |
| 152 | else if (action === "suspend") state.account.unlocked = false; |
| 153 | else if (action === "logout") { |
| 154 | Object.assign(state.status, { ready: false, vm_running: false }); |
| 155 | state.account.unlocked = false; |
| 156 | state.account.devices = {}; |
| 157 | state.account.require_authentication = true; |
| 158 | state.terminals = []; |
| 159 | state.status.job = { id: "account-logout", kind: "stop", running: false }; |
| 160 | return route.fulfill({ json: state.status.job }); |
| 161 | } |
| 162 | return route.fulfill({ json: accountView() }); |
| 163 | } |
| 164 | if (!state.account.unlocked && !["/session", "/launch", "/appearance"].includes(path)) return route.fulfill({ status: 423, body: "Cage 已锁定,请先登录" }); |
| 165 | if (browserRequest && path.startsWith("/browser/") && path !== "/browser/events") return browserRequest(route, path, body); |
| 166 | if (path.startsWith("/cli/")) { |
| 167 | if (cliRequest) return cliRequest(route, path, body); |
| 168 | const account = path.match(/^\/cli\/sessions\/([^/]+)\/account$/); |
| 169 | if (account) return route.fulfill({ json: { session: { id: account[1] }, supported: false, candidates: [] } }); |
| 170 | return route.fulfill({ json: { sessions: [], notice: "" } }); |
| 171 | } |
| 172 | if (startupFailure && path === "/status") return route.fulfill({ status: 503, body: "测试:控制服务暂不可用" }); |
| 173 | let result = {}; |
| 174 | if (path === "/favorites") { |
| 175 | if (favoritesRequest) return route.fulfill(await favoritesRequest(request)); |
| 176 | return route.fulfill({ json: { items: [], folders: [] } }); |
| 177 | } |
| 178 | if (path === "/host/git") { |
| 179 | if (request.method() === "POST") { |
| 180 | if (!body?.confirm) |
| 181 | return route.fulfill({ status: 400, body: "请先确认启用保护" }); |
| 182 | if (state.failHostGit) |
| 183 | return route.fulfill({ |
| 184 | status: 500, |
| 185 | body: "未能保存 Git 安全设置,请检查写入权限后重试。", |
| 186 | }); |
| 187 | state.hostGit = { |
| 188 | state: "ok", |
| 189 | ready: true, |
| 190 | can_enable: false, |
| 191 | message: "本机 Git 安全保护已启用。", |
| 192 | }; |
| 193 | } |
| 194 | return route.fulfill({ json: state.hostGit }); |
| 195 | } |
| 196 | if (path === "/appearance/codex") |
| 197 | return route.fulfill({ json: state.codexAppearance }); |
| 198 | if (path === "/appearance") { |
| 199 | if (request.method() === "POST") { |
| 200 | if (state.failAppearance) |
| 201 | return route.fulfill({ |
| 202 | status: 500, |
| 203 | body: "外观设置未能保存,请重试", |
| 204 | }); |
| 205 | state.appearance = structuredClone(body); |
| 206 | } |
| 207 | return route.fulfill({ json: state.appearance }); |
| 208 | } |
| 209 | if (path === "/proxy") |
| 210 | result = { |
| 211 | active: true, |
| 212 | selected: "fixture-node", |
| 213 | sources: [ |
| 214 | { |
| 215 | id: "fixture-source", |
| 216 | name: "测试来源", |
| 217 | nodes: [{ id: "fixture-node", name: "测试节点", type: "http" }], |
| 218 | remote: false, |
| 219 | interval_hours: 0, |
| 220 | }, |
| 221 | ], |
| 222 | port: 17896, |
| 223 | core_available: true, |
| 224 | running: true, |
| 225 | state: state.status.vm_running ? "ready" : "prepared", |
| 226 | state_label: state.status.vm_running ? "已联网" : "待启动环境", |
| 227 | network_open: Boolean(state.status.vm_running), |
| 228 | }; |
| 229 | else if (path === "/settings" && request.method() === "GET") |
| 230 | result = state.settings; |
| 231 | else if (path === "/status") |
| 232 | result = { ...state.status, workspace: state.settings.workspace }; |
| 233 | else if (path === "/projects/remove") { |
| 234 | if (!body.workspace || body.workspace === state.status.environment_directory) return route.fulfill({ status: 400, body: "默认工作区保留" }); |
| 235 | if (state.failRemove || state.terminals.some(terminal => terminal.workspace === body.workspace && !terminal.closed) || state.tabs.some(tab => tab.kind === "editor" && tab.workspace === body.workspace)) return route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: "请先关闭此项目的终端和编辑器,再移除项目" }); |
| 236 | state.status.projects = state.status.projects.filter(path => path !== body.workspace); |
| 237 | if (state.settings.workspace === body.workspace) state.settings.workspace = state.status.environment_directory; |
| 238 | result = { workspace: state.settings.workspace }; |
| 239 | } |
| 240 | else if (path === "/projects/open") { |
| 241 | if (state.failJob) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", body: "项目文件夹连接失败,原项目保持不变" }); |
| 242 | if (!body.add && !state.status.projects.includes(body.workspace)) return route.fulfill({ status: 400, body: "请选择已授权的项目" }); |
| 243 | if (body.add && !state.status.projects.includes(body.workspace)) state.status.projects.push(body.workspace); |
| 244 | if (body.activate) { |
| 245 | state.settings.workspace = body.workspace; |
| 246 | state.status.environment_workspace = body.workspace === state.status.environment_directory; |
| 247 | } |
| 248 | result = { workspace: body.workspace }; |
| 249 | } |
| 250 | else if (path === "/settings") { |
| 251 | state.saves.push(body); |
| 252 | if (state.failSave) |
| 253 | return route.fulfill({ |
| 254 | status: 400, |
| 255 | contentType: "text/plain; charset=utf-8", |
| 256 | body: "保存失败,请重试", |
| 257 | }); |
| 258 | const id = "job-" + ++state.sequence; |
| 259 | const switching = state.settings.workspace !== body.workspace; |
| 260 | if (!state.failJob) { |
| 261 | Object.assign(state.settings, body); |
| 262 | state.status.keyboard = body.keyboard; |
| 263 | if (switching) { |
| 264 | if (!state.status.projects.includes(body.workspace)) |
| 265 | state.status.projects.push(body.workspace); |
| 266 | state.status.environment_workspace = body.workspace.endsWith( |
| 267 | "/.claude-cage-workspace", |
| 268 | ); |
| 269 | } |
| 270 | } |
| 271 | state.status.job = { |
| 272 | id, |
| 273 | kind: switching ? "project" : "settings", |
| 274 | running: false, |
| 275 | error: state.failJob ? "项目文件夹连接失败,原项目保持不变" : "", |
| 276 | }; |
| 277 | result = { id }; |
| 278 | } else if (path === "/start") { |
| 279 | state.status.job = { id: "start", kind: "start", running: false }; |
| 280 | state.settings.workspace = "/Users/shihao/.claude-cage-workspace"; |
| 281 | state.status.environment_workspace = true; |
| 282 | state.status.ready = true; |
| 283 | state.status.vm_running = true; |
| 284 | state.status.safety = { |
| 285 | gate: { |
| 286 | mode: "open", |
| 287 | until: new Date(Date.now() + 3600000).toISOString(), |
| 288 | }, |
| 289 | }; |
| 290 | result = { id: "start" }; |
| 291 | } else if (path === "/stop") { |
| 292 | state.status.ready = false; |
| 293 | state.status.vm_running = false; |
| 294 | } else if (path === "/browser/tabs") |
| 295 | result = { tabs: state.tabs, active: state.active, split: state.split || null }; |
| 296 | else if (path === "/browser/split") { |
| 297 | state.split = body.left ? { left: body.left, right: body.right, fraction: 0.5 } : null; |
| 298 | result = { split: state.split }; |
| 299 | } |
| 300 | else if (path === "/browser/events") |
| 301 | return route.fulfill({ |
| 302 | contentType: "text/event-stream", |
| 303 | body: ": fixture\n\n", |
| 304 | }); |
| 305 | else if (path === "/browser/preferences") { |
| 306 | if (request.method() === "POST") { |
| 307 | if (state.failSave) return route.fulfill({ status: 500, body: "浏览器设置保存失败,请重试" }); |
| 308 | state.settings.browser_home_url = body.browser_home_url; |
| 309 | } |
| 310 | result = { browser_home_url: state.settings.browser_home_url }; |
| 311 | } |
| 312 | else if (path === "/browser/settings") { |
| 313 | let tab = state.tabs.find(tab => tab.kind === "browser-settings"); |
| 314 | if (!tab) { tab = { id: "browser-settings", kind: "browser-settings", title: "设置", url: "cage://settings#general" }; state.tabs.push(tab); } |
| 315 | tab.url = "cage://settings#" + (body?.mode || "general"); state.active = tab.id; result = tab; |
| 316 | } |
| 317 | else if (path === "/browser/extensions") result = { items: [] }; |
| 318 | else if (path === "/vnc-credentials") result = { password: "fixture-only" }; |
| 319 | else if (path === "/terminals" && request.method() === "GET") |
| 320 | result = state.terminals; |
| 321 | else if (path === "/terminals") { |
| 322 | if ( |
| 323 | !state.status.projects.includes( |
| 324 | body?.workspace || state.settings.workspace, |
| 325 | ) |
| 326 | ) |
| 327 | return route.fulfill({ |
| 328 | status: 400, |
| 329 | body: "请先通过打开项目添加该文件夹", |
| 330 | }); |
| 331 | const tab = { |
| 332 | id: "term-" + ++state.sequence, |
| 333 | title: "终端 " + (state.terminals.length + 1), |
| 334 | workspace: body?.workspace || state.settings.workspace, |
| 335 | }; |
| 336 | state.terminals.push(tab); |
| 337 | result = tab; |
| 338 | } else if ( |
| 339 | path.startsWith("/terminals/") && |
| 340 | request.method() === "DELETE" |
| 341 | ) { |
| 342 | state.terminals = state.terminals.filter( |
| 343 | (tab) => tab.id !== path.split("/").at(-1), |
| 344 | ); |
| 345 | } else if (path === "/browser/new" || path === "/browser/editor") { |
| 346 | const workspace = body?.workspace || state.settings.workspace; |
| 347 | if (path.endsWith("editor") && !state.status.projects.includes(workspace)) |
| 348 | return route.fulfill({ |
| 349 | status: 400, |
| 350 | body: "请先通过打开项目添加该文件夹", |
| 351 | }); |
| 352 | let tab = |
| 353 | path.endsWith("editor") && |
| 354 | state.tabs.find( |
| 355 | (tab) => tab.kind === "editor" && tab.workspace === workspace, |
| 356 | ); |
| 357 | if (!tab) { |
| 358 | tab = { |
| 359 | id: "web-" + ++state.sequence, |
| 360 | kind: path.endsWith("editor") ? "editor" : "web", |
| 361 | workspace: path.endsWith("editor") ? workspace : undefined, |
| 362 | title: path.endsWith("editor") ? "文件编辑器" : "新标签页", |
| 363 | url: body?.url || state.settings.browser_home_url, |
| 364 | }; |
| 365 | state.tabs.push(tab); |
| 366 | } |
| 367 | state.active = tab.id; |
| 368 | result = tab; |
| 369 | } else if (path === "/browser/activate") state.active = body.id; |
| 370 | else if (path === "/browser/close") { |
| 371 | state.tabs = state.tabs.filter((tab) => tab.id !== body.id); |
| 372 | if (state.active === body.id) state.active = state.tabs.at(-1)?.id || ""; |
| 373 | } else if (path === "/browser/navigate") |
| 374 | Object.assign( |
| 375 | state.tabs.find((tab) => tab.id === body.id), |
| 376 | { url: body.url, title: "本地预览" }, |
| 377 | ); |
| 378 | else if (path === "/settings/probe") |
| 379 | result = { |
| 380 | country: "United States", |
| 381 | city: "Los Angeles", |
| 382 | ip: "192.0.2.10", |
| 383 | timezone: "America/Los_Angeles", |
| 384 | checked_at: new Date().toISOString(), |
| 385 | }; |
| 386 | return route.fulfill({ json: result }); |
| 387 | }); |
| 388 | if (beforeNavigate) await beforeNavigate(page, state); |
| 389 | await page.goto(url || process.env.CAGE_UI_URL || "http://127.0.0.1:5198"); |
| 390 | if (waitForReady && !startupFailure && !state.status.vm_running && clientContext.mode !== "none") await page.getByRole("heading", { name: state.initialization.required ? state.initialization.started ? "安装并检查客机环境" : "为 Cage 准备独立环境" : "先启动 Cage 环境" }).waitFor(); |
| 391 | return { browser, context, page, state, errors }; |
| 392 | } |
| 393 | |
| 394 | export async function chooseInline(picker, value) { |
| 395 | await picker.click(); |
| 396 | await picker.page().getByRole("option").and(picker.page().locator(`[data-value=${JSON.stringify(String(value))}]`)).click(); |
| 397 | } |