跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

macos-login-fullscreen-smoke.mjs

197 行 · 11.5 KB历史下载
1import assert from "node:assert/strict";
2import { createWorkbench } from "./workbench-fixture.mjs";
3
4for (const viewport of [{ width: 1280, height: 900 }, { width: 1920, height: 1080 }, { width: 390, height: 700 }]) {
5 const nativeCalls = [], inputs = [], closed = [];
6 let finish = false, sessionID = 0, frameMime = "image/jpeg";
7 const fixture = await createWorkbench({
8 viewport,
9 nativeRequest: (message) => nativeCalls.push(message),
10 async beforeNavigate(page, state) {
11 state.status.ready = true; state.status.vm_running = true;
12 const images = await page.evaluate(() => {
13 const canvas = document.createElement("canvas");
14 canvas.width = 1920; canvas.height = 1200;
15 const ctx = canvas.getContext("2d");
16 ctx.fillStyle = "#526482"; ctx.fillRect(0, 0, 1920, 1200);
17 ctx.fillStyle = "#ddd"; ctx.beginPath(); ctx.arc(960, 1000, 32, 0, Math.PI*2); ctx.fill();
18 ctx.fillStyle = "white"; ctx.font = "20px sans-serif"; ctx.textAlign = "center";
19 ctx.fillText("Cage", 960, 1050);
20 ctx.fillStyle = "#ffffff88"; ctx.fillRect(880, 1070, 160, 30);
21 ctx.fillStyle = "white"; ctx.font = "14px sans-serif";
22 ctx.fillText("Enter Password", 960, 1091);
23 return Object.fromEntries(["image/jpeg", "image/png"].map((m) => [m, canvas.toDataURL(m).split(",")[1]]));
24 });
25 await page.route("**/api/account", (r) => r.fulfill({json:{exists:true, unlocked:true, trusted_local:true, guest_system:"macos"}}));
26 await page.route("**/api/terminals", (r) => r.fulfill({json:[]}));
27 await page.route("**/api/macos/login", (r) => {
28 const q = r.request().postDataJSON();
29 if (q.action === "open") return r.fulfill({json:{session:"trial-" + (++sessionID)}});
30 if (q.action === "close") { closed.push(q.session); return r.fulfill({json:{closed:true}}); }
31 if (q.action === "frame") return r.fulfill({json:finish ? {closed:true} :
32 {image:images[frameMime], ...(frameMime === "image/jpeg" ? {mime:frameMime} : {})}});
33 inputs.push(q);
34 return r.fulfill({json:{}});
35 });
36 },
37 });
38 const { page, browser, errors } = fixture;
39 async function waitInput(count) {
40 for (let i=0; inputs.length < count && i<150; i++) await new Promise((r) => setTimeout(r, 20));
41 assert.equal(inputs.length, count);
42 }
43 try {
44 if (viewport.width < 600) await page.getByRole("button",{name:"收起侧栏",exact:true}).click();
45 const trigger=page.getByRole("button",{name:"登录客机账户"});
46 await trigger.click({timeout:7000});
47 const screen=page.getByRole("dialog",{name:"登录虚拟 Mac"});
48 const img=screen.getByRole("img");
49 const input=screen.getByLabel(/^客机登录键盘/);
50 await img.waitFor();
51 await page.waitForFunction(() => document.activeElement?.classList.contains("mac-login-keyboard") &&
52 document.querySelector(".mac-login-canvas img")?.naturalWidth === 1920);
53 assert.equal(await screen.evaluate((el) => el.parentElement === document.body),true);
54 assert.equal(await page.locator("#root").evaluate((el) => el.inert),true);
55 const panel=await screen.locator(".mac-login-panel").boundingBox();
56 assert.ok(panel.width < viewport.width && panel.height < viewport.height, "login should use a compact panel");
57 const stage=screen.locator(".mac-login-stage");
58 const area=await stage.boundingBox();
59 const focus=screen.getByRole("button",{name:"登录区域", exact:true});
60 assert.equal(await focus.getAttribute("aria-pressed"),"true");
61 const initial=await img.boundingBox();
62 // Avatar, password and the lower login message must all remain in the crop.
63 for (const [x,y] of [[.5,.82],[.5,.9],[.5,.96]]) {
64 assert.ok(initial.x+initial.width*x >= area.x && initial.x+initial.width*x < area.x+area.width);
65 assert.ok(initial.y+initial.height*y >= area.y && initial.y+initial.height*y < area.y+area.height);
66 }
67 const passwordX=Math.round(initial.x+initial.width*.5), passwordY=Math.round(initial.y+initial.height*.9);
68 await page.mouse.click(passwordX,passwordY);
69 await waitInput(1);
70 assert.ok(Math.abs(inputs[0].x-512)<=1 && Math.abs(inputs[0].y-576)<=1);
71 inputs.length=0;
72 if (process.env.CAGE_LOGIN_SCREENSHOTS) await page.screenshot({path:`${process.env.CAGE_LOGIN_SCREENSHOTS}/login-${viewport.width}.png`});
73 assert.equal(await page.evaluate(() => window.cageEditAction("paste")),false);
74 await screen.getByRole("button",{name:"完整画面"}).click();
75 const fit=await img.boundingBox();
76 assert.ok(Math.abs(fit.width/fit.height - 1.6)<.005);
77 if (fit.x > area.x+1) await page.mouse.click((area.x+fit.x)/2,area.y+area.height/2);
78 else await page.mouse.click(area.x+area.width/2,(area.y+area.height+fit.y+fit.height)/2);
79 assert.equal(inputs.length,0,"letterbox click leaked");
80 const fitX=Math.round(fit.x+fit.width/2), fitY=Math.round(fit.y+fit.height/2);
81 await page.mouse.click(fitX,fitY);
82 await waitInput(1);
83 assert.equal(inputs[0].x,Math.floor((fitX-fit.x)*1024/fit.width));
84 assert.equal(inputs[0].y,Math.floor((fitY-fit.y)*640/fit.height));
85 await focus.click();
86 const zoom=await img.boundingBox();
87 assert.ok(zoom.width > 3*fit.width);
88 await page.mouse.move(area.x+area.width/2,area.y+area.height/2);
89 await page.mouse.down(); await page.mouse.move(area.x+area.width/2+90,area.y+area.height/2+55,{steps:5}); await page.mouse.up();
90 const pan=await img.boundingBox();
91 assert.ok(pan.x>zoom.x+60 && pan.y>zoom.y+30);
92 const x=Math.round(area.x+area.width*.65), y=Math.round(area.y+area.height*.6);
93 await page.mouse.click(x,y);
94 await waitInput(2);
95 assert.equal(inputs[1].x,Math.floor((x-pan.x)*1024/pan.width));
96 assert.equal(inputs[1].y,Math.floor((y-pan.y)*640/pan.height));
97 await input.press("Enter"); await waitInput(3); assert.equal(inputs[2].code,36);
98 assert.equal(await screen.isVisible(), true, "Return must wait for the guest to confirm login");
99 await input.evaluate((el) => {
100 const data=new DataTransfer(); data.setData("text/plain","Z7");
101 el.dispatchEvent(new ClipboardEvent("paste",{bubbles:true,cancelable:true,clipboardData:data}));
102 });
103 await waitInput(5);
104 assert.deepEqual(inputs.slice(-2).map(({code,shift})=>[code,shift]),[[6,true],[26,false]]);
105 assert.equal(await input.inputValue(),"");
106 await screen.getByRole("button",{name:"完整画面"}).click();
107 assert.deepEqual(await img.boundingBox(),fit);
108 await page.evaluate(() => window.cageNativeAction("closeTab"));
109 await screen.waitFor({state:"detached"});
110 await page.waitForFunction(() => document.activeElement?.textContent === "登录客机账户");
111 assert.ok(!await page.locator("#root").evaluate((el)=>el.inert));
112 frameMime="image/png";
113 await trigger.click();
114 await page.waitForFunction(() => document.querySelector(".mac-login-canvas img")?.src.startsWith("data:image/png;"));
115 assert.equal(await focus.getAttribute("aria-pressed"),"true", "reopening should restore the login crop");
116 finish=true;
117 await screen.waitFor({state:"detached"});
118 assert.deepEqual(closed, ["trial-1","trial-2"]);
119 assert.deepEqual(nativeCalls.filter((m)=>/fullscreen/i.test(m.action)),[]);
120 assert.equal(await page.evaluate(()=>document.fullscreenElement),null);
121 assert.deepEqual(errors,[]);
122 console.log(`${viewport.width}×${viewport.height}: default login crop, compact panel, coordinate mapping, fit, pan, paste, native close and completion passed.`);
123 } catch (error) { console.error("page:",(await page.locator("body").innerText()).slice(0,700), "errors:", errors); throw error; } finally { await browser.close(); }
124}
125
126// Exercise the first-setup password button through the normal page entry.
127// Frame polling must preserve an operation error until a user action succeeds.
128{
129 let operationError = "请先点选系统授权窗口的密码框,再点击填写授权密码";
130 let frameError = "", frames = 0, latestFrame = "";
131 const fixture = await createWorkbench({
132 async beforeNavigate(page, state) {
133 Object.assign(state.account, {initial_mac_setup:true, guest_system:"macos", macos_guest_user:"cage"});
134 Object.assign(state.status, {ready:true, vm_running:true});
135 const images = await page.evaluate(() => {
136 const canvas = document.createElement("canvas");
137 canvas.width = 160; canvas.height = 100;
138 const paint = canvas.getContext("2d");
139 return ["#526482", "#627492"].map(color => {
140 paint.fillStyle = color; paint.fillRect(0, 0, canvas.width, canvas.height);
141 return canvas.toDataURL("image/png").split(",")[1];
142 });
143 });
144 await page.route("**/api/macos/first-setup", async route => {
145 const request = route.request().postDataJSON();
146 if (request.action === "permissions") return route.fulfill({json:{screen:false, input:false, projects:false, managed_credential:true}});
147 if (request.action === "open") return route.fulfill({json:{session:"error-persistence-fixture"}});
148 if (request.action === "frame") {
149 frames++;
150 if (frameError) return route.fulfill({json:{error:frameError}});
151 latestFrame = images[frames % images.length];
152 return route.fulfill({json:{image:latestFrame}});
153 }
154 if (request.action === "fill-password") {
155 assert.equal(request.password, undefined, "browser supplied a credential");
156 return route.fulfill({json:operationError ? {error:operationError} : {}});
157 }
158 return route.fulfill({json:{}});
159 });
160 },
161 });
162 const {page, browser, errors} = fixture;
163 try {
164 const screen = page.getByRole("dialog", {name:"首次设置虚拟 Mac"});
165 const fill = screen.getByRole("button", {name:"填写授权密码", exact:true});
166 await screen.getByRole("img").waitFor();
167 await fill.click();
168 await screen.getByRole("alert").filter({hasText:operationError}).waitFor();
169 const observed = frames;
170 for (let attempts = 0; frames < observed + 2 && attempts < 150; attempts++)
171 await new Promise(resolve => setTimeout(resolve, 20));
172 assert.ok(frames >= observed + 2, "frame polling stopped after an input error");
173 await page.waitForFunction(image => document.querySelector(".mac-login-canvas img")?.src.endsWith(image), latestFrame);
174 assert.equal(await screen.getByRole("alert").isVisible(), true, "a successful frame erased the password error");
175 assert.equal(await screen.getByRole("alert").innerText(), operationError);
176
177 frameError = "授权画面暂时无法读取";
178 await page.waitForResponse(async response => response.url().endsWith("/api/macos/first-setup") &&
179 response.request().postDataJSON()?.action === "frame" && (await response.json()).error === frameError);
180 operationError = "";
181 await fill.click();
182 await screen.getByRole("alert").filter({hasText:frameError}).waitFor();
183 frameError = "";
184 await screen.getByRole("alert").waitFor({state:"hidden"});
185
186 operationError = "系统授权窗口或密码框已变化,填写已停止,请重新选择";
187 await fill.click();
188 await screen.getByRole("alert").filter({hasText:operationError}).waitFor();
189 await screen.getByRole("button", {name:"返回设置指引"}).click();
190 await screen.waitFor({state:"detached"});
191 await page.getByRole("button", {name:"打开客机系统设置", exact:true}).click();
192 await screen.getByRole("img").waitFor();
193 assert.equal(await screen.getByRole("alert").count(), 0, "reopening retained an old operation error");
194 assert.deepEqual(errors, []);
195 console.log("First-setup password error persistence, independent frame recovery and close/reopen cleanup passed.");
196 } finally { await browser.close(); }
197}