跳到主要内容

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

浏览文件

shared-cli-live-smoke.mjs

146 行 · 8.5 KB历史下载
1import process from "node:process";
2import assert from "node:assert/strict";
3import {mkdir, readFile} from "node:fs/promises";
4import path from "node:path";
5
6const parts = [];
7for await (const chunk of process.stdin) parts.push(chunk);
8const entry = Buffer.concat(parts).toString("utf8").trim();
9const engine = process.env.CAGE_TEST_CHANNEL_BROWSER;
10const playwright = await import(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
11const browser = await playwright[engine].launch({headless:true});
12let page;
13const snapshots = [];
14try {
15 page = await browser.newPage({viewport:{width:390,height:844},isMobile:true,hasTouch:true});
16 await page.addInitScript(() => {
17 window.fixtureInputEvents = [];
18 for (const kind of ["input","change"]) document.addEventListener(kind,event=>{
19 if (event.target.tagName === "TEXTAREA") window.fixtureInputEvents.push({kind,value:event.target.value});
20 },true);
21 });
22 page.on("response", async response => {
23 if (!/\/api\/mobile\/cli\/sessions\/[^/]+(\/open)?(?:\?|$)/.test(response.url())) return;
24 try {
25 const value = await response.json();
26 snapshots.push({path:new URL(response.url()).pathname,status:response.status(),id:value.id,revision:value.revision,can_send:value.can_send,terminal_available:value.terminal_available,connection_notice:value.connection_notice});
27 } catch { /* Incremental reads may have no response body. */ }
28 });
29 page.setDefaultTimeout(25000);
30 let sentRequests = 0, interruptedReads = 0;
31 let persistentReadFailure = false, persistentReadAttempts = 0;
32 const recovering = process.env.CAGE_TEST_SESSION_RECOVERY === "1";
33 if (recovering) {
34 await page.route("**/api/mobile/cli/sessions/*/messages", async route => {
35 sentRequests++;
36 if (sentRequests === 1) {
37 await route.fetch();
38 // The guest accepted the message, but its HTTP receipt is lost.
39 await route.fulfill({status:503,contentType:"text/plain",body:"电脑暂时无法连接运行环境,聊天记录已保留。"});
40 } else await route.continue();
41 });
42 await page.route(/\/api\/mobile\/cli\/sessions\/[^/?]+(?:\?.*)?$/, async route => {
43 if (route.request().method() === "GET" && persistentReadFailure) {
44 persistentReadAttempts++;
45 await route.fulfill({status:503,contentType:"text/plain",body:"电脑暂时无法连接运行环境,聊天记录已保留。"});
46 } else if (route.request().method() === "GET" && sentRequests && interruptedReads++ < 2) {
47 await route.fulfill({status:503,contentType:"text/plain",body:"电脑暂时无法连接运行环境,聊天记录已保留。"});
48 } else await route.continue();
49 });
50 }
51 await page.goto(entry);
52 await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name:/ 新建会话$/}).first().click();
53 await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
54 const message = page.getByRole("textbox",{name:"消息"});
55 await message.fill("initial mobile prompt");
56 await page.getByRole("button",{name:"发送",exact:true}).click();
57 const approve = page.getByRole("button",{name:"允许一次"});
58 await approve.waitFor();
59 if (recovering) {
60 assert.equal(sentRequests,1,"a lost receipt replayed an accepted message");
61 assert.ok(interruptedReads >= 2);
62 assert.equal(await page.getByText(/尚未收到主机确认|同一编号|已自动重连5次/).count(),0);
63 assert.equal(await page.getByRole("alert").count(),0,"a recovered interruption left a failure card");
64 }
65 assert.equal(await page.getByRole("button",{name:"在电脑打开会话",exact:true}).count(),0);
66 assert.equal(await page.getByRole("alert").count(),0,"normal startup displayed an extra notice");
67 assert.match(await page.getByLabel("工具参数预览").innerText(), /mobile-approved\.txt/);
68 await assert.rejects(readFile(process.env.CAGE_TEST_MOBILE_MARKER),{code:"ENOENT"});
69 await page.reload();
70 await approve.waitFor();
71 const capture = process.env.CAGE_TEST_MOBILE_CAPTURE;
72 if (capture) {
73 await mkdir(capture,{recursive:true});
74 await page.screenshot({path:path.join(capture,engine+"-shared-approval.png")});
75 }
76 await approve.click();
77 await page.getByText("isolated tool completed",{exact:true}).waitFor();
78 await page.getByText("follow-up",{exact:true}).waitFor();
79 await page.getByText("isolated continuation",{exact:true}).waitFor();
80 assert.equal(await readFile(process.env.CAGE_TEST_MOBILE_MARKER,"utf8"),"approved");
81 await page.reload();
82 await page.getByText("isolated continuation",{exact:true}).waitFor();
83 assert.equal(await page.getByLabel("会话消息").getByText("initial mobile prompt",{exact:true}).count(),1);
84 if (capture) await page.screenshot({path:path.join(capture,engine+"-shared-history.png")});
85 const title = await page.locator(".chat-header h1").innerText();
86 // Prepare an ended history through the real archive/restore API. The user
87 // then opens it from the actual phone list, with no desktop helper.
88 await page.evaluate(async () => {
89 const selected = history.state.cageCLI;
90 const root = "/api/mobile/cli/sessions/" + selected.session;
91 for (const operation of ["archive", "restore"]) {
92 const result = await fetch(root+"/"+operation,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});
93 if (!result.ok) throw Error("history setup failed: "+result.status);
94 }
95 history.replaceState({...history.state,cageCLI:{tool:"code",project:selected.project,session:""}},"");
96 });
97 await page.reload();
98 await page.getByRole("button",{name:"展开侧栏",exact:true}).click();
99 await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name:title,exact:true}).click();
100 await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
101 await message.fill("after reopen");
102 await page.getByRole("button",{name:"发送",exact:true}).click();
103 await page.getByLabel("会话消息").getByText("after reopen",{exact:true}).waitFor();
104 await page.waitForFunction(() => document.querySelectorAll('.message:not(.user)').length === 3 &&
105 document.querySelectorAll('.message:not(.user)')[2].textContent.includes("isolated continuation"));
106 assert.equal(await page.getByRole("alert").count(),0,"history restore displayed an extra notice");
107 if (capture) await page.screenshot({path:path.join(capture,engine+"-seamless-resume.png")});
108 await page.getByRole("button",{name:"展开侧栏",exact:true}).click();
109 await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name:/ 新建会话$/}).first().click();
110 await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
111 await message.fill("draft for second");
112 const secondTitle = await page.locator(".chat-header h1").innerText();
113 const select = async name => {
114 await page.getByRole("button",{name:"展开侧栏",exact:true}).click();
115 await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name,exact:true}).click();
116 await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
117 };
118 await select(title);
119 assert.equal(await message.inputValue(),"");
120 await message.fill("draft for first");
121 await select(secondTitle);
122 assert.equal(await message.inputValue(),"draft for second");
123 await select(title);
124 assert.equal(await message.inputValue(),"draft for first");
125 assert.equal(await page.getByRole("alert").count(),0,"session switching displayed an extra notice");
126 if (recovering) {
127 persistentReadFailure = true;
128 await page.getByRole("alert").filter({hasText:"已自动重连5次"}).waitFor({timeout:40000});
129 assert.equal(persistentReadAttempts,6,"initial failure must be followed by five retries");
130 assert.equal(await message.inputValue(),"draft for first");
131 if (capture) await page.screenshot({path:path.join(capture,engine+"-reconnect-exhausted.png")});
132 persistentReadFailure = false;
133 await page.getByRole("button",{name:"再次连接",exact:true}).click();
134 await page.getByRole("alert").waitFor({state:"hidden"});
135 assert.equal(await message.inputValue(),"draft for first");
136 assert.equal(sentRequests,2,"reconnection replayed a user message");
137 }
138} catch (error) {
139 console.error(JSON.stringify(snapshots.slice(-12)));
140 console.error(await page?.locator("body").innerText());
141 console.error(await page?.getByRole("textbox",{name:"消息"}).evaluate(el=>({value:el.value,disabled:el.disabled})));
142 console.error(await page?.evaluate(()=>window.fixtureInputEvents));
143 throw Error(String(error).replace(/(link-bootstrap)#[A-Za-z0-9_-]+/g,"$1#[redacted]"));
144} finally {
145 await browser.close();
146}