composer-status-capsules.test.mjs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. // ST01–ST12:胶囊布局、真实状态详情与控制回调的可重复浏览器场景。
  2. import { registerActivityHistoryCases, workflowQueryFixture } from "./activity-history-cases.mjs";
  3. import assert from "node:assert/strict";
  4. import { before, after, test } from "node:test";
  5. import { fileURLToPath } from "node:url";
  6. import { mkdir, writeFile } from "node:fs/promises";
  7. import { join } from "node:path";
  8. import { createServer } from "vite";
  9. import react from "@vitejs/plugin-react";
  10. import tailwindcss from "@tailwindcss/vite";
  11. import { chromium } from "playwright-core";
  12. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  13. const entry = join(root, "composer-status-fixture.tsx");
  14. const artifacts = join(root, "packages/desktop/.e2e-artifacts/composer-status-capsules-browser");
  15. const fixture = `
  16. import { useState } from "react";
  17. import { AgentToolCallBlock } from "@/ToolCallBlocks/renderers/agent.js";
  18. import { ToolPresentationCapabilitiesProvider } from "@/ToolCallBlocks/presentationCapabilities.js";
  19. import { V4ConversationContext } from "@/v4/V4ConversationContext.js";
  20. import { useWorkflowRunJournalSummaries } from "@/hooks/useWorkflowRunJournalSummaries.js";
  21. import { subagentProjectionStateSchema } from "@zcode/shared/zcode-protocol-v4";
  22. import { createRoot } from "react-dom/client";
  23. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  24. import { ComposerStatusRow, StatusCapsule, ConversationStatusPanel } from "@/v4/ConversationStatusPanel.js";
  25. import { GitStatusRepositoryContext } from "@/hooks/useGitRepository.js";
  26. import { ChatErrorBanner } from "@/ChatErrorBanner.js";
  27. import { TooltipProvider } from "@/components/ui/tooltip.js";
  28. import "@/styles.css";
  29. const query = new URLSearchParams(location.search);
  30. const theme = query.get("theme");
  31. document.documentElement.className = theme + " theme-zai-" + theme;
  32. ${workflowQueryFixture}
  33. function Fixture() {
  34. const [session, setSession] = useState("a");
  35. const [goalStatus, setGoalStatus] = useState("active");
  36. const [todoVisible, setTodoVisible] = useState(true);
  37. const [todoState, setTodoState] = useState("pending");
  38. const [gitVisible, setGitVisible] = useState(true);
  39. const [result, setResult] = useState("");
  40. const [activityEnded, setActivityEnded] = useState(query.has("endedOnly"));
  41. const [workflowStatus, setWorkflowStatus] = useState(query.has("actorParentEnd") ? "running" : query.get("runStatus"));
  42. const [activityDismissed, setActivityDismissed] = useState(false);
  43. const [newTerminal, setNewTerminal] = useState(false);
  44. const [terminalRunning, setTerminalRunning] = useState(false);
  45. const real = query.has("real");
  46. if(query.has("journalQuery")) return <V4ConversationContext.Provider value={queryContext}><QueryProbe/></V4ConversationContext.Provider>;
  47. return <ZCodeIntlProvider initialLocale={query.get("locale")}>
  48. <ToolPresentationCapabilitiesProvider value={query.has("configuredColor") ? {agentColor:()=>"blue"} : {}}><TooltipProvider><main className="h-screen bg-background text-foreground p-3">
  49. <button data-testid="outside">Outside</button><button data-testid="toggle" onClick={()=>setTodoVisible(v=>!v)}>Toggle</button><output>{result}</output>
  50. <button data-testid="todo-running" onClick={()=>setTodoState("inProgress")}>Run todo</button>
  51. <button data-testid="todo-complete" onClick={()=>setTodoState("completed")}>Complete todo</button>
  52. <button data-testid="clear-git" onClick={()=>setGitVisible(false)}>Clear git</button>
  53. <button data-testid="dismiss-activity" onClick={()=>setActivityDismissed(true)}>Accept next input</button>
  54. <button data-testid="start-terminal" onClick={()=>{setNewTerminal(true);setTerminalRunning(true)}}>Start terminal</button>
  55. <button data-testid="new-terminal" onClick={()=>{setNewTerminal(true);setTerminalRunning(false)}}>Complete new terminal</button>
  56. <button data-testid="settle-workflow" onClick={()=>setWorkflowStatus(query.get("runStatus"))}>Settle workflow</button>
  57. <button data-testid="end-activity" onClick={()=>setActivityEnded(true)}>End activity</button>
  58. <button data-testid="session" onClick={()=>setSession(value=>value === "a" ? "b" : "a")}>Session</button>
  59. {query.has("configuredColor") ? <section data-testid="message-agent"><AgentToolCallBlock toolCallNode={{toolCall:{toolId:"identity",name:"Agent",title:"Agent",status:"pending",input:{subagent_type:"reviewer",description:"Still running"}},childToolCalls:[]}} workspacePath="/example" isRunning={true} statusLabel="Running" nestedToolRenderer={()=>null}/></section> : null}
  60. <div className="fixed bottom-4 left-4 right-4">
  61. {query.has("banner") ? <ChatErrorBanner error={{code:"LAYOUT_SAMPLE",message:"Current model unavailable"}} /> : null}
  62. <GitStatusRepositoryContext.Provider value={{workspacePath:"/example",openChange:(path,source)=>setResult(source+":"+path),state:{datasets:{
  63. unstaged:{sections:gitVisible ? [{changes:query.has("manyFiles") ? Array.from({length:40},(_,i)=>({path:"file-"+i+".txt",added:1,removed:0})) : [{path:"shared.txt",added:2,removed:1},{path:"image.png",added:0,removed:0}]}] : []},
  64. staged:{sections:gitVisible ? [{changes:[{path:"shared.txt",added:1,removed:0}]}] : []}
  65. }}}}>
  66. <ComposerStatusRow key={session}>
  67. {real ? <ConversationStatusPanel workspacePath="/example" parentSessionId="parent"
  68. goal={{targetId:"g",objective:"Full objective for capsule verification",summaryTitle:query.has("long") ? "Long objective title for verifying capsule responsive shrinking and trailing mask" : "Short objective",status:goalStatus,summaryHidden:query.has("goalHidden"),timeUsedSeconds:12,activeRunStartedAtMs:null,iteration:0,verifications:[],iterations:[]}}
  69. gitSummary={{isRepository:true,branchName:"feature/current-branch-with-a-long-name-for-overflow",headRefType:"branch"}} gitWorktreeChangeSummary={{added:3,removed:1}}
  70. sessionPlans={[{rowId:1,toolCallId:"p1",toolName:"ExitPlanMode",status:"success",input:{plan:"# Older plan"}},{rowId:2,toolCallId:"p2",toolName:"ExitPlanMode",status:"success",input:{plan:query.has("long") ? "# Latest plan with a very long title for responsive layout verification" : "# Latest plan"}}]}
  71. onPauseGoal={()=>setGoalStatus("paused")} onResumeGoal={()=>setGoalStatus("active")}
  72. plan={todoVisible ? {items:[{id:"first",content:"First completed step",status:"completed"},{id:"second",content:"Second pending step",status:todoState}]} : null}
  73. workflowRuns={query.has("workflow") ? [{runId:"run",toolCallId:"wf",status:workflowStatus || (activityEnded ? "completed" : "running"),actors:[{sessionId:"child",siteId:"explorer",ordinal:0,status:query.has("mixedActors") ? "completed" : "running"},{sessionId:"child-2",siteId:"reviewer",ordinal:1,status:query.has("allActorsDone") ? "completed" : "running"},{sessionId:"child-3",siteId:"tester",ordinal:2,status:query.has("allActorsDone") ? "completed" : query.has("mixedActors") ? "waiting" : "running"}].map(actor=>query.has("waitingActors") ? {...actor,status:"waiting"} : actor),nodes:[],usage:{}}] : []}
  74. backgroundWorks={[...(query.has("resultMix") ? query.get("resultMix").split(",").map((status,i)=>({workId:"mixed-"+i,kind:"bash",title:"Result "+i,status,startedAt:1,endedAt:4})) : []), ...(query.has("actorParentEnd") ? [{workId:"run",kind:"workflow",title:"Workflow inspection",status:workflowStatus === "running" ? "running" : workflowStatus === "stopped" ? "cancelled" : "failed",startedAt:2}] : query.has("workflow") ? [{workId:"run",kind:"workflow",title:"Workflow inspection",status:activityEnded ? "resultPending" : "running",startedAt:2},{workId:"shell",kind:"bash",title:"Build project",status:activityEnded ? "resultPending" : "running",startedAt:3}] : []), ...(newTerminal ? [{workId:"new-shell",kind:"bash",title:"Current round terminal",status:terminalRunning ? "running" : "resultPending",startedAt:11,endedAt:15}] : [])]}
  75. onOpenBackgroundBash={()=>setResult("bash-details")} onOpenGitReview={()=>setResult("git-details")} onOpenWorkflowRun={()=>setResult("workflow-details")} onCancelBackgroundWork={id=>setResult("stop:"+id)}
  76. activitySummaryDismissed={activityDismissed ? {at:10,workIds:["shell","run"],subagentIds:["child"],workflowRunIds:query.has("onlySubagentHistory") ? [] : ["run"]} : undefined}
  77. completedActivityCount={query.get("completedTotal") === "unknown" ? null : query.has("completedTotal") ? Number(query.get("completedTotal")) : undefined}
  78. endedSubagents={activityEnded && !query.has("resultMix") ? subagentProjectionStateSchema.shape.ended.unwrap().parse([{childSessionId:"child",subagentType:"explorer",title:"Inspect files",summary:query.get("agentSummary") ?? "Inspection complete",status:query.get("agentStatus") || "success",startedAt:1,endedAt:Number(query.get("childEndedAt") || 4)}]) : []}
  79. runningSubagents={query.has("mixedAgents") ? Array.from({length:Number(query.get("runningCount") || 1)},(_,i)=>({childSessionId:"live-child-"+i,subagentType:"reviewer",title:"Still running "+i,status:"running",startedAt:2+i})) : activityEnded ? [] : [{childSessionId:"child",subagentType:"explorer",title:"Inspect files",status:"running",startedAt:1,stopControl:{taskId:"task",executionId:"execution"}}]}
  80. onStopSubagent={control=>setResult(control.taskId + ":" + control.executionId)}
  81. onOpenSubagentSession={()=>setResult("agent-details")}
  82. endedSubagentCount={query.has("noHistory") ? 0 : 2} onOpenSubagentDirectory={query.has("noDirectoryHost") ? undefined : request=>setResult("agent-history:"+request.parentSessionId)}
  83. endedWorkflowRunCount={query.has("noHistory") ? 0 : 3} onOpenWorkflowRunDirectory={query.has("noDirectoryHost") ? undefined : request=>setResult("workflow-history:"+request.parentSessionId)}
  84. /> : ["goal", "todo", "git", "activity"].map(id=>
  85. <StatusCapsule key={id} id={id} label={id} icon={<span>•</span>}>
  86. <div data-testid={id + "-detail"}>{id} detail</div>
  87. </StatusCapsule>)}
  88. </ComposerStatusRow></GitStatusRepositoryContext.Provider>
  89. <textarea aria-label="Composer" className="w-full" />
  90. </div>
  91. </main></TooltipProvider></ToolPresentationCapabilitiesProvider>
  92. </ZCodeIntlProvider>;
  93. }
  94. createRoot(document.getElementById("root")).render(<Fixture />);
  95. `;
  96. let server, browser, origin;
  97. before(async () => {
  98. await mkdir(artifacts, { recursive: true });
  99. server = await createServer({
  100. root,
  101. configFile: false,
  102. plugins: [
  103. {
  104. name: "composer-status-fixture",
  105. resolveId(id) {
  106. if (id === "/composer-status-fixture.tsx") return entry;
  107. },
  108. load(id) {
  109. if (id === entry) return fixture;
  110. },
  111. configureServer(vite) {
  112. vite.middlewares.use(async (req, res, next) => {
  113. if (!req.url?.startsWith("/fixture?")) return next();
  114. res.setHeader("Content-Type", "text/html");
  115. res.end(
  116. await vite.transformIndexHtml(
  117. req.url,
  118. '<html><head><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="/composer-status-fixture.tsx"></script></body></html>',
  119. ),
  120. );
  121. });
  122. },
  123. },
  124. react(),
  125. tailwindcss(),
  126. ],
  127. resolve: {
  128. alias: {
  129. "@": join(root, "packages/ui/src"),
  130. "@zcode/shared/zcode-protocol-v4": join(
  131. root,
  132. "packages/shared/src/zcode-protocol-v4/index.ts",
  133. ),
  134. },
  135. },
  136. optimizeDeps: {
  137. entries: [],
  138. include: [
  139. "react",
  140. "react-dom/client",
  141. "react/jsx-runtime",
  142. "class-variance-authority",
  143. "clsx",
  144. "lucide-react",
  145. "radix-ui",
  146. "tailwind-merge",
  147. "zod",
  148. "zustand",
  149. ],
  150. },
  151. server: { host: "127.0.0.1", port: 0, hmr: false },
  152. });
  153. await server.listen();
  154. origin = server.resolvedUrls.local[0];
  155. // 半像素边框需要真实 2x 栅格;仅设置页面 deviceScaleFactor 仍可能按 1x 取整。
  156. browser = await chromium.launch(
  157. process.env.CHROME_EXECUTABLE_PATH
  158. ? {
  159. executablePath: process.env.CHROME_EXECUTABLE_PATH,
  160. args: ["--force-device-scale-factor=2"],
  161. }
  162. : { channel: "chrome", args: ["--force-device-scale-factor=2"] },
  163. );
  164. });
  165. after(async () => {
  166. await browser?.close();
  167. await server?.close();
  168. });
  169. for (const mobile of [false, true])
  170. for (const theme of ["light", "dark"])
  171. for (const locale of ["zh-CN", "en-US"])
  172. test(`capsules ${mobile ? "touch" : "desktop"}/${theme}/${locale}`, async () => {
  173. const page = await browser.newPage({
  174. viewport: { width: mobile ? 390 : 1200, height: 844 },
  175. isMobile: mobile,
  176. hasTouch: mobile,
  177. });
  178. const errors = [];
  179. page.on("pageerror", (e) => errors.push(String(e)));
  180. try {
  181. await page.goto(`${origin}fixture?theme=${theme}&locale=${locale}`);
  182. const triggers = page.locator("[data-status-capsule]");
  183. await triggers.first().waitFor();
  184. assert.deepEqual(
  185. await triggers.evaluateAll((nodes) => nodes.map((n) => n.dataset.statusCapsule)),
  186. ["goal", "todo", "git", "activity"],
  187. );
  188. for (const id of ["goal", "todo", "activity"]) {
  189. await page.locator(`[data-status-capsule="${id}"]`).click();
  190. await page.getByTestId(id + "-detail").waitFor();
  191. assert.equal(await page.locator("[data-status-capsule-content]").count(), 1);
  192. const box = await page.locator("[data-status-capsule-content]").boundingBox();
  193. assert.ok(box.x >= 0 && box.x + box.width <= (mobile ? 390 : 1200) && box.y >= 0);
  194. }
  195. await page.screenshot({ path: join(artifacts, `${mobile}-${theme}-${locale}.png`) });
  196. await page.keyboard.press("Escape");
  197. await page.locator("[data-status-capsule-content]").waitFor({ state: "hidden" });
  198. await page.locator('[data-status-capsule="todo"]').click();
  199. await page.getByTestId("session").click();
  200. await page.locator("[data-status-capsule-content]").waitFor({ state: "hidden" });
  201. assert.deepEqual(errors, []);
  202. } finally {
  203. await page.close();
  204. }
  205. });
  206. test("real Goal, Todo and activity controls preserve their owners", async () => {
  207. const page = await browser.newPage();
  208. const errors = [];
  209. page.on("pageerror", (e) => errors.push(String(e)));
  210. try {
  211. await page.goto(origin + "fixture?theme=light&locale=en-US&real=1");
  212. const todo = page.locator('[data-status-capsule="todo"]');
  213. await todo.waitFor();
  214. assert.match(await todo.innerText(), /Pending\s*1\/2/);
  215. await todo.click();
  216. assert.deepEqual(await page.locator("[data-plan-status]").allTextContents(), [
  217. "First completed step",
  218. "Second pending step",
  219. ]);
  220. await page.getByTestId("toggle").click();
  221. await todo.waitFor({ state: "hidden" });
  222. await page.getByTestId("toggle").click();
  223. await todo.waitFor();
  224. assert.equal(await page.locator("[data-status-capsule-content]").count(), 0);
  225. await page.locator('[data-status-capsule="goal"]').click();
  226. await page.locator('[data-goal-action="pause"]').click();
  227. await page.locator('[data-goal-action="resume"]').waitFor();
  228. assert.match(await page.locator('[data-status-capsule="goal"]').innerText(), /Paused/);
  229. await page.locator('[data-goal-action="resume"]').click();
  230. await page.locator('[data-goal-action="pause"]').waitFor();
  231. await page.locator('[data-status-capsule="activity"]').click();
  232. await page.getByTestId("v4-running-subagent-stop").click();
  233. assert.equal(await page.locator("output").innerText(), "task:execution");
  234. await page.locator("[data-running-subagent-session-trigger]").click();
  235. assert.equal(await page.locator("output").innerText(), "agent-details");
  236. assert.equal(await page.locator("summary").count(), 0);
  237. assert.deepEqual(errors, []);
  238. } finally {
  239. await page.close();
  240. }
  241. });
  242. test("Plan capsule is absent and staged Git source keeps stable identity", async () => {
  243. const page = await browser.newPage();
  244. try {
  245. await page.goto(origin + "fixture?theme=dark&locale=en-US&real=1");
  246. await page.locator('[data-status-capsule="git"]').waitFor();
  247. assert.equal(await page.locator('[data-status-capsule="plans"]').count(), 0);
  248. const git = page.locator('[data-status-capsule="git"]');
  249. assert.match(await git.innerText(), /2 files changed/);
  250. await git.click();
  251. const content = page.locator('[data-status-capsule-content="git"]');
  252. await content.getByRole("button", { name: /shared.txt Staged/ }).click();
  253. assert.equal(await page.locator("output").innerText(), "staged:shared.txt");
  254. await content.waitFor({ state: "hidden" });
  255. await git.click();
  256. await content.getByRole("button", { name: /image.png Unstaged Changed/ }).click();
  257. assert.equal(await page.locator("output").innerText(), "unstaged:image.png");
  258. } finally {
  259. await page.close();
  260. }
  261. });
  262. for (const width of [390, 1200])
  263. for (const theme of ["light", "dark"])
  264. for (const locale of ["zh-CN", "en-US"])
  265. test(`restored error banner ${width}/${theme}/${locale}`, async () => {
  266. const page = await browser.newPage({
  267. viewport: { width, height: 844 },
  268. deviceScaleFactor: 2,
  269. });
  270. try {
  271. await page.goto(origin + `fixture?theme=${theme}&locale=${locale}&real=1&banner=1`);
  272. const banner = page.locator('[data-error-code="LAYOUT_SAMPLE"]');
  273. await banner.waitFor();
  274. assert.equal(await page.locator('[data-status-capsule="alerts"]').count(), 0);
  275. assert.equal(await page.locator("[data-status-capsule-content]").count(), 0);
  276. assert.equal(await banner.getByRole("button").count(), 2);
  277. assert.equal(await banner.evaluate((el) => getComputedStyle(el).borderTopWidth), "0.5px");
  278. await page.screenshot({
  279. path: join(artifacts, `restored-error-${width}-${theme}-${locale}.png`),
  280. });
  281. } finally {
  282. await page.close();
  283. }
  284. });
  285. // Todo 没有可聚焦按钮,键盘打开后焦点落在面板,曾被全局焦点重置清掉外投影。
  286. for (const theme of ["light", "dark"])
  287. test(`status panel keeps shadow and center alignment on focus/${theme}`, async () => {
  288. const page = await browser.newPage({ viewport: { width: 1200, height: 844 } });
  289. try {
  290. await page.goto(origin + `fixture?theme=${theme}&locale=en-US&real=1`);
  291. const trigger = page.locator('[data-status-capsule="todo"]');
  292. await trigger.focus();
  293. await page.keyboard.press("Enter");
  294. const panel = page.locator('[data-status-capsule-content="todo"]');
  295. await panel.waitFor();
  296. await panel.evaluate(async (el) => {
  297. await Promise.all(el.getAnimations().map((animation) => animation.finished));
  298. });
  299. assert.equal(await panel.evaluate((el) => el === document.activeElement), true);
  300. assert.notEqual(await panel.evaluate((el) => getComputedStyle(el).boxShadow), "none");
  301. assert.equal(await panel.getAttribute("data-align"), "center");
  302. } finally {
  303. await page.close();
  304. }
  305. });
  306. test("legacy hidden Goal remains visible as session state", async () => {
  307. const page = await browser.newPage();
  308. try {
  309. await page.goto(origin + "fixture?theme=light&locale=en-US&real=1&goalHidden=1");
  310. await page.locator('[data-status-capsule="todo"]').waitFor();
  311. assert.equal(await page.locator('[data-status-capsule="goal"]').count(), 1);
  312. assert.equal(await page.locator('[data-status-capsule="plans"]').count(), 0);
  313. } finally {
  314. await page.close();
  315. }
  316. });
  317. for (const width of [390, 1200]) {
  318. for (const theme of ["light", "dark"]) {
  319. test(`activity changes from result to history on accepted input ${width}/${theme}`, async () => {
  320. const page = await browser.newPage({ viewport: { width, height: 900 } });
  321. try {
  322. await page.goto(origin + `fixture?theme=${theme}&locale=en-US&real=1`);
  323. const capsule = page.locator('[data-status-capsule="activity"]');
  324. await capsule.click();
  325. assert.equal(await page.locator("summary").count(), 0);
  326. await page.getByTestId("end-activity").click();
  327. assert.equal(await capsule.locator("[data-status-capsule-secondary]").innerText(), "1");
  328. await capsule.click();
  329. assert.equal(await page.locator('[data-activity-result="completed"]').count(), 1);
  330. assert.equal(await page.getByRole("button", { name: /Stop/ }).count(), 0);
  331. assert.equal(await page.getByTestId("activity-subagent-directory").count(), 0);
  332. await page.getByTestId("dismiss-activity").click();
  333. await capsule.waitFor({ state: "visible" });
  334. assert.equal(await capsule.locator("[data-status-capsule-secondary]").innerText(), "1");
  335. await capsule.click();
  336. await page.getByTestId("activity-subagent-directory").waitFor();
  337. assert.equal(await page.locator("[data-activity-result]").count(), 0);
  338. assert.equal(await capsule.locator("[data-subagent-avatar]").count(), 1);
  339. await page.goto(origin + `fixture?theme=${theme}&locale=en-US&real=1&endedOnly=1`);
  340. await page.locator('[data-status-capsule="todo"]').waitFor();
  341. await capsule.waitFor();
  342. } finally {
  343. await page.close();
  344. }
  345. });
  346. }
  347. }
  348. // 使用真实四类内容;逐项保存测量证据,不能以空标签夹具代替窄屏验收。
  349. for (const width of [390, 600, 1200]) {
  350. for (const theme of ["light", "dark"]) {
  351. for (const locale of ["zh-CN", "en-US"]) {
  352. test(`real capsule geometry ${width}/${theme}/${locale}`, async () => {
  353. const page = await browser.newPage({
  354. viewport: { width, height: 900 },
  355. hasTouch: width === 390,
  356. isMobile: width === 390,
  357. });
  358. page.setDefaultTimeout(10000);
  359. const name = `geometry-${width}-${theme}-${locale}`;
  360. try {
  361. await page.goto(
  362. `${origin}fixture?theme=${theme}&locale=${locale}&real=1&workflow=1&long=1`,
  363. );
  364. await page.locator('[data-status-capsule="activity"]').waitFor();
  365. const result = await page
  366. .locator('[data-testid="composer-status-row"]')
  367. .evaluate((row) => {
  368. const probe = document.createElement("span");
  369. probe.style.cssText =
  370. "background:var(--color-input);border:0.5px solid var(--color-input-border);";
  371. probe.className = "shadow-(--shadow-composer-soft)";
  372. row.append(probe);
  373. const probeStyle = getComputedStyle(probe);
  374. const expected = {
  375. background: probeStyle.backgroundColor,
  376. borderColor: probeStyle.borderTopColor,
  377. shadow: probeStyle.boxShadow,
  378. };
  379. probe.remove();
  380. const rect = row.getBoundingClientRect();
  381. return {
  382. expected,
  383. row: {
  384. left: rect.left,
  385. right: rect.right,
  386. width: rect.width,
  387. scrollWidth: row.scrollWidth,
  388. },
  389. items: [...row.querySelectorAll("[data-status-capsule]")].map((el) => {
  390. const box = el.getBoundingClientRect(),
  391. css = getComputedStyle(el),
  392. title = el.children[1],
  393. info = el.querySelector("[data-status-capsule-secondary]");
  394. const icon = el.children[0].querySelector("svg");
  395. const iconBox = icon?.getBoundingClientRect();
  396. return {
  397. id: el.dataset.statusCapsule,
  398. left: box.left,
  399. right: box.right,
  400. top: box.top,
  401. height: box.height,
  402. paddingLeft: css.paddingLeft,
  403. paddingRight: css.paddingRight,
  404. gap: css.columnGap,
  405. border: css.borderTopWidth,
  406. background: css.backgroundColor,
  407. borderColor: css.borderTopColor,
  408. shadow: css.boxShadow,
  409. titleFont: getComputedStyle(title).fontSize,
  410. titleWidth: title.getBoundingClientRect().width,
  411. secondary: info
  412. ? {
  413. left: info.getBoundingClientRect().left,
  414. right: info.getBoundingClientRect().right,
  415. font: getComputedStyle(info).fontSize,
  416. width: info.clientWidth,
  417. scrollWidth: info.scrollWidth,
  418. }
  419. : null,
  420. icon: iconBox ? { width: iconBox.width, height: iconBox.height } : null,
  421. };
  422. }),
  423. };
  424. });
  425. await writeFile(join(artifacts, name + ".json"), JSON.stringify(result, null, 2));
  426. await page.screenshot({ path: join(artifacts, name + ".png") });
  427. assert.deepEqual(
  428. result.items.map((x) => x.id),
  429. ["goal", "todo", "git", "activity"],
  430. );
  431. for (const item of result.items) {
  432. assert.equal(item.height, 32, `${item.id} height`);
  433. assert.equal(item.paddingLeft, "8px");
  434. assert.equal(item.paddingRight, "10px");
  435. assert.equal(item.gap, width <= 640 ? "4px" : "6px");
  436. assert.equal(item.border, "0.5px");
  437. assert.equal(item.background, result.expected.background);
  438. assert.equal(item.borderColor, result.expected.borderColor);
  439. assert.equal(item.shadow, result.expected.shadow);
  440. assert.equal(item.titleFont, "14px");
  441. assert.equal(item.icon.width, 16);
  442. assert.equal(item.icon.height, 16);
  443. assert.ok(
  444. item.left >= result.row.left - 0.5 && item.right <= result.row.right + 0.5,
  445. `${item.id} outside row`,
  446. );
  447. if (item.secondary) {
  448. assert.equal(item.secondary.font, "12px");
  449. assert.ok(
  450. item.secondary.left >= item.left && item.secondary.right <= item.right,
  451. `${item.id} fixed slot outside capsule`,
  452. );
  453. assert.ok(
  454. item.secondary.scrollWidth <= item.secondary.width + 1,
  455. `${item.id} secondary clipped`,
  456. );
  457. }
  458. }
  459. assert.ok(
  460. Math.max(...result.items.map((x) => x.top)) -
  461. Math.min(...result.items.map((x) => x.top)) <
  462. 1,
  463. );
  464. assert.ok(result.row.scrollWidth <= result.row.width + 1, "row overflows horizontally");
  465. const rowPadding = await page.getByTestId("composer-status-row").evaluate((node) => ({
  466. top: getComputedStyle(node).paddingTop,
  467. bottom: getComputedStyle(node).paddingBottom,
  468. }));
  469. assert.deepEqual(rowPadding, { top: "0px", bottom: "16px" });
  470. const body = page.locator('[data-status-capsule="activity"] .wf-face-body').first();
  471. assert.equal(await body.getAttribute("rx"), "7");
  472. assert.equal(await body.getAttribute("paint-order"), "stroke fill");
  473. assert.equal(await body.getAttribute("vector-effect"), "non-scaling-stroke");
  474. const title = page.locator('[data-status-capsule="goal"] [class*="mask-image"]');
  475. if (width < 1200) assert.equal(await title.count(), 1, "long title must fade");
  476. for (const id of ["todo", "git", "activity"]) {
  477. const label = await page
  478. .locator(`[data-status-capsule="${id}"] [data-capsule-label]`)
  479. .evaluate((node) => ({
  480. position: getComputedStyle(node).position,
  481. visibility: getComputedStyle(node).visibility,
  482. }));
  483. if (label.visibility === "hidden") assert.equal(label.position, "absolute");
  484. }
  485. for (const id of ["goal", "todo", "git", "activity"]) {
  486. const capsule = page.locator(`[data-status-capsule="${id}"]`);
  487. await capsule.click();
  488. const panel = page.locator(`[data-status-capsule-content="${id}"]`);
  489. await panel.waitFor();
  490. assert.equal(await page.locator("[data-status-capsule-content]").count(), 1);
  491. assert.equal(await panel.getAttribute("data-align"), "center");
  492. const box = await panel.boundingBox();
  493. assert.ok(box.width <= 320.5 && box.x >= 0 && box.x + box.width <= width + 0.5);
  494. await page.waitForFunction(() =>
  495. document
  496. .querySelector("[data-status-capsule-content]")
  497. ?.contains(document.activeElement),
  498. );
  499. const tooltipCount = await page.getByRole("tooltip").count();
  500. await writeFile(
  501. join(artifacts, `${name}-${id}-focus.json`),
  502. JSON.stringify({
  503. tooltipCount,
  504. active: await page.evaluate(() => document.activeElement?.outerHTML),
  505. }),
  506. );
  507. await page.keyboard.press("Escape");
  508. if (tooltipCount > 0) {
  509. await page.getByRole("tooltip").waitFor({ state: "hidden" });
  510. await page.keyboard.press("Escape");
  511. }
  512. await panel.waitFor({ state: "hidden" });
  513. }
  514. } finally {
  515. await page.close();
  516. }
  517. });
  518. }
  519. }
  520. }
  521. test("Todo states and Git clearing follow supplied projections", async () => {
  522. const page = await browser.newPage();
  523. try {
  524. await page.goto(`${origin}fixture?theme=light&locale=en-US&real=1`);
  525. const todo = page.locator('[data-status-capsule="todo"]');
  526. await todo.waitFor();
  527. await page.getByTestId("todo-running").click();
  528. assert.match(await todo.innerText(), /In progress/);
  529. await todo.click();
  530. assert.equal(await page.locator('[data-plan-status="inProgress"]').count(), 1);
  531. await page.getByTestId("todo-complete").click();
  532. assert.match(await todo.innerText(), /Completed/);
  533. assert.equal(await todo.locator("[data-status-capsule-secondary]").innerText(), "2/2");
  534. const git = page.locator('[data-status-capsule="git"]');
  535. await git.click();
  536. await page.getByTestId("clear-git").click();
  537. await git.waitFor({ state: "hidden" });
  538. assert.equal(await page.locator('[data-status-capsule-content="git"]').count(), 0);
  539. } finally {
  540. await page.close();
  541. }
  542. });
  543. test("completed workflow and resultPending terminal preserve Activity", async () => {
  544. const page = await browser.newPage();
  545. try {
  546. await page.goto(`${origin}fixture?theme=dark&locale=en-US&real=1&workflow=1`);
  547. const activity = page.locator('[data-status-capsule="activity"]');
  548. await activity.click();
  549. await page.getByTestId("end-activity").click();
  550. assert.equal(await activity.locator("[data-status-capsule-secondary]").innerText(), "2");
  551. await activity.click();
  552. assert.equal(await page.locator('[data-activity-result="completed"]').count(), 2);
  553. await page.getByTestId("dismiss-activity").click();
  554. await activity.waitFor({ state: "visible" });
  555. } finally {
  556. await page.close();
  557. }
  558. });
  559. // 只验收结束徽标的真实 SVG 和布局,不改变产品状态或模拟控制命令。
  560. for (const width of [390, 1200]) {
  561. for (const theme of ["light", "dark"]) {
  562. for (const [status, result] of [
  563. ["success", "completed"],
  564. ["cancelled", "stopped"],
  565. ["failed", "failed"],
  566. ]) {
  567. test(`activity badge parity ${result}/${width}/${theme}`, async () => {
  568. const page = await browser.newPage({
  569. viewport: { width, height: 900 },
  570. isMobile: width === 390,
  571. hasTouch: width === 390,
  572. });
  573. try {
  574. await page.goto(
  575. origin + `fixture?theme=${theme}&locale=en-US&real=1&agentStatus=${status}`,
  576. );
  577. const capsule = page.locator('[data-status-capsule="activity"]');
  578. await capsule.waitFor();
  579. await page.getByTestId("end-activity").click();
  580. await capsule.click();
  581. const panel = page.locator('[data-status-capsule-content="activity"]');
  582. await panel.waitFor();
  583. // 面板有入场缩放,等真实动画完成后再测量,不能把动画中尺寸当成布局尺寸。
  584. await panel.evaluate(async (el) => {
  585. await Promise.all(
  586. el
  587. .getAnimations({ subtree: true })
  588. .filter((animation) => animation.effect?.getTiming().iterations !== Infinity)
  589. .map((animation) => animation.finished.catch(() => {})),
  590. );
  591. });
  592. const expectedExpression =
  593. result === "stopped" ? "pill" : result === "failed" ? "sad" : "happy";
  594. for (const owner of [capsule, panel]) {
  595. const avatar = owner.locator("[data-subagent-avatar]").first();
  596. assert.equal(await avatar.getAttribute("data-expression"), expectedExpression);
  597. if (result === "stopped")
  598. assert.equal(await avatar.getAttribute("data-motion"), "idle");
  599. }
  600. const selector = `[data-agent-result-badge="${result}"]`;
  601. const triggerBadge = capsule.locator(selector);
  602. const panelBadge = panel.locator(selector);
  603. assert.equal(await triggerBadge.count(), 1);
  604. assert.equal(await panelBadge.count(), 1);
  605. assert.equal(await triggerBadge.innerHTML(), await panelBadge.innerHTML());
  606. for (const badge of [triggerBadge, panelBadge]) {
  607. const geometry = await badge.evaluate((el) => {
  608. const badgeRect = el.getBoundingClientRect();
  609. const svgRect = el.ownerSVGElement.getBoundingClientRect();
  610. return {
  611. svgWidth: svgRect.width,
  612. svgHeight: svgRect.height,
  613. cx: badgeRect.x + badgeRect.width / 2 - svgRect.x,
  614. cy: badgeRect.y + badgeRect.height / 2 - svgRect.y,
  615. width: badgeRect.width,
  616. };
  617. });
  618. assert.equal(geometry.svgWidth, 16);
  619. assert.equal(geometry.svgHeight, 16);
  620. assert.ok(geometry.cx < 8 && geometry.cy > 8, JSON.stringify(geometry));
  621. assert.ok(Math.abs(geometry.width - 8.8) < 0.3, JSON.stringify(geometry));
  622. }
  623. if (result === "stopped") {
  624. assert.equal(await triggerBadge.locator('rect[width="4"][height="4"]').count(), 1);
  625. }
  626. await page.screenshot({ path: join(artifacts, `badge-${result}-${width}-${theme}.png`) });
  627. } finally {
  628. await page.close();
  629. }
  630. });
  631. }
  632. }
  633. }
  634. for (const width of [390, 1280]) {
  635. for (const theme of ["light", "dark"]) {
  636. test(`activity directory navigation ${width}/${theme}`, async () => {
  637. const page = await browser.newPage({ viewport: { width, height: 900 } });
  638. try {
  639. await page.goto(origin + `fixture?real=1&theme=${theme}&locale=en-US`);
  640. await page.getByTestId("end-activity").click();
  641. await page.getByTestId("dismiss-activity").click();
  642. await page.locator('[data-status-capsule="activity"]').click();
  643. await page.screenshot({
  644. path: join(artifacts, `activity-directory-${width}-${theme}.png`),
  645. });
  646. for (const kind of ["subagent", "workflow"]) {
  647. if (kind === "workflow") await page.locator('[data-status-capsule="activity"]').click();
  648. await page.getByTestId(`activity-${kind}-directory`).click();
  649. assert.equal(
  650. await page.locator("output").textContent(),
  651. `${kind === "subagent" ? "agent" : "workflow"}-history:parent`,
  652. );
  653. await page
  654. .locator('[data-status-capsule-content="activity"]')
  655. .waitFor({ state: "hidden" });
  656. }
  657. await page.goto(origin + `fixture?real=1&theme=${theme}&locale=en-US&noDirectoryHost=1`);
  658. await page.locator('[data-status-capsule="activity"]').click();
  659. assert.equal(
  660. await page.locator('[data-testid^="activity-"][data-testid$="-directory"]').count(),
  661. 0,
  662. );
  663. } finally {
  664. await page.close();
  665. }
  666. });
  667. }
  668. }
  669. for (const theme of ["light", "dark"])
  670. for (const width of [390, 1200])
  671. test(`current Git branch ${theme}/${width}`, async () => {
  672. const page = await browser.newPage({ viewport: { width, height: 844 } });
  673. try {
  674. await page.goto(`${origin}fixture?real=1&theme=${theme}&locale=en-US`);
  675. await page.locator('[data-status-capsule="git"]').click();
  676. const row = page.getByTestId("status-git-current-branch");
  677. const review = page.getByTestId("status-git-view-all");
  678. assert.equal(await review.locator("span").last().textContent(), "2");
  679. assert.equal(
  680. await review.evaluate((node) =>
  681. Boolean(
  682. node.compareDocumentPosition(
  683. document.querySelector('[data-testid="status-git-current-branch"]'),
  684. ) & Node.DOCUMENT_POSITION_FOLLOWING,
  685. ),
  686. ),
  687. true,
  688. );
  689. await page.locator('[data-status-capsule-content="git"]').evaluate(async (node) => {
  690. await Promise.all(
  691. node
  692. .getAnimations({ subtree: true })
  693. .map((animation) => animation.finished.catch(() => {})),
  694. );
  695. });
  696. assert.equal(
  697. await row.textContent(),
  698. "feature/current-branch-with-a-long-name-for-overflow",
  699. );
  700. assert.equal(await row.getAttribute("title"), await row.textContent());
  701. const geometry = await row.evaluate((node) => ({
  702. height: node.getBoundingClientRect().height,
  703. icon: node.querySelector("svg").getBoundingClientRect().width,
  704. overflow: node.scrollWidth > node.clientWidth,
  705. }));
  706. assert.ok(Math.abs(geometry.height - 32) < 1, JSON.stringify(geometry));
  707. assert.ok(Math.abs(geometry.icon - 16) < 1, JSON.stringify(geometry));
  708. assert.equal(geometry.overflow, false);
  709. const label = row.locator("span").last();
  710. const textStyle = await label.evaluate((node) => ({
  711. mask: getComputedStyle(node).maskImage,
  712. ellipsis: getComputedStyle(node).textOverflow,
  713. }));
  714. assert.notEqual(textStyle.mask, "none");
  715. assert.notEqual(textStyle.ellipsis, "ellipsis");
  716. } finally {
  717. await page.close();
  718. }
  719. });
  720. for (const theme of ["light", "dark"])
  721. for (const width of [390, 1200])
  722. test(`Git scroll mask ${theme}/${width}`, async () => {
  723. const page = await browser.newPage({ viewport: { width, height: 844 } });
  724. try {
  725. await page.goto(`${origin}fixture?real=1&manyFiles=1&theme=${theme}&locale=en-US`);
  726. await page.locator('[data-status-capsule="git"]').click();
  727. const viewport = page.getByTestId("status-git-files");
  728. await page.waitForFunction(
  729. () =>
  730. document
  731. .querySelector('[data-testid="status-git-files"]')
  732. ?.getAttribute("data-scroll-mask") === "bottom",
  733. );
  734. const branch = page.getByTestId("status-git-current-branch");
  735. await page.locator('[data-status-capsule-content="git"]').evaluate(async (node) => {
  736. await Promise.all(
  737. node.getAnimations({ subtree: true }).map((a) => a.finished.catch(() => {})),
  738. );
  739. });
  740. const initial = await branch.boundingBox();
  741. const edge = await viewport.evaluate((node) => ({
  742. right: node.getBoundingClientRect().right,
  743. panelRight: node.closest("[data-status-capsule-content]").getBoundingClientRect().right,
  744. overscroll: getComputedStyle(node).overscrollBehaviorY,
  745. }));
  746. assert.ok(Math.abs(edge.right - edge.panelRight) < 2, JSON.stringify(edge));
  747. assert.equal(edge.overscroll, "contain");
  748. await viewport.evaluate((node) => {
  749. node.scrollTop = 100;
  750. });
  751. await page.waitForFunction(
  752. () =>
  753. document
  754. .querySelector('[data-testid="status-git-files"]')
  755. ?.getAttribute("data-scroll-mask") === "both",
  756. );
  757. await viewport.evaluate((node) => {
  758. node.scrollTop = node.scrollHeight;
  759. });
  760. await page.waitForFunction(
  761. () =>
  762. document
  763. .querySelector('[data-testid="status-git-files"]')
  764. ?.getAttribute("data-scroll-mask") === "top",
  765. );
  766. assert.deepEqual(await branch.boundingBox(), initial);
  767. } finally {
  768. await page.close();
  769. }
  770. });
  771. for (const suffix of ["noDirectoryHost=1", "noHistory=1"]) {
  772. test(`archived Activity without usable directories disappears ${suffix}`, async () => {
  773. const page = await browser.newPage();
  774. try {
  775. await page.goto(`${origin}fixture?real=1&theme=dark&locale=en-US&endedOnly=1&${suffix}`);
  776. const capsule = page.locator('[data-status-capsule="activity"]');
  777. await capsule.click();
  778. assert.equal(await page.locator("[data-activity-result]").count(), 1);
  779. await page.getByTestId("dismiss-activity").click();
  780. await capsule.waitFor({ state: "hidden" });
  781. assert.equal(await page.locator('[data-status-capsule-content="activity"]').count(), 0);
  782. } finally {
  783. await page.close();
  784. }
  785. });
  786. }
  787. registerActivityHistoryCases({ getBrowser: () => browser, getOrigin: () => origin, artifacts });