git-action-lifecycle.test.mjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // CR-01/CR-02:真实 Git 控制器与受控服务响应下的弹窗生命周期回归。
  2. import assert from "node:assert/strict";
  3. import { before, after, test } from "node:test";
  4. import { fileURLToPath } from "node:url";
  5. import { mkdir } from "node:fs/promises";
  6. import { join } from "node:path";
  7. import { createServer } from "vite";
  8. import react from "@vitejs/plugin-react";
  9. import tailwindcss from "@tailwindcss/vite";
  10. import { chromium } from "playwright-core";
  11. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  12. const entry = join(root, "composer-status-fixture.tsx");
  13. const artifacts = join(root, "packages/desktop/.e2e-artifacts/git-action-lifecycle-browser");
  14. const fixture = `
  15. import { useState, useCallback } from "react";
  16. import { createRoot } from "react-dom/client";
  17. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  18. import { ServiceProvider } from "@/hooks/useServices.js";
  19. import { GitBranchActionsHost } from "@/GitBranchSwitcher.js";
  20. import { ComposerStatusRow, ConversationStatusPanel } from "@/v4/ConversationStatusPanel.js";
  21. import { GitStatusRepositoryContext } from "@/hooks/useGitRepository.js";
  22. import { TooltipProvider } from "@/components/ui/tooltip.js";
  23. import "@/styles.css";
  24. const query = new URLSearchParams(location.search);
  25. document.documentElement.className="theme-zai-"+query.get("theme")+" "+query.get("theme");
  26. const summary={isGitAvailable:true,isRepository:true,branchName:"main",headRefType:"branch"};
  27. let committed=false, releaseFailure;
  28. const graphRequests=[];
  29. window.graphRequests=graphRequests;
  30. const graphResult=(name,hasMore=false)=>({commits:[{hash:name,parents:[],refs:[],subject:name,authorName:"Example",authoredAtMs:0}],hasMore});
  31. const services={gitService:{
  32. getLocalBranches:async()=>({currentBranchName:"main",branches:[{name:"main",isCurrent:true},{name:"feature",isCurrent:false}]}),
  33. getChanges:async()=>[],getIdentity:async()=>null,
  34. switchBranch:async()=>{if(committed){await new Promise(r=>releaseFailure=r);throw new Error("E2E_SWITCH_FAILURE");}return {ok:false,branchName:"feature",action:"switch",summary,issues:[{code:"tracked-changes-would-be-overwritten",message:"blocked",paths:["file.txt"]}]};},
  35. stagePaths:async()=>{},commit:async()=>{committed=true;},
  36. createBranchAndSwitch:async()=>({ok:true,branchName:"new",summary,issues:[],didChange:true}),
  37. getCommitGraph:async(args)=>query.has("graphRace")?new Promise((resolve,reject)=>graphRequests.push({args,resolve:(name,more)=>resolve(graphResult(name,more)),reject})):graphResult("Retained commit")
  38. }};
  39. function Fixture(){
  40. const [hidden,setHidden]=useState(false),[dirty,setDirty]=useState(true),[session,setSession]=useState("a"),[cwd,setCwd]=useState("/example");
  41. const refresh=useCallback(()=>{if(committed)setDirty(false)},[]);
  42. return <ZCodeIntlProvider initialLocale={query.get("locale")??"en-US"}><ServiceProvider services={services}><TooltipProvider>
  43. <button data-testid="hide-error" onClick={()=>setHidden(true)}>Error</button>
  44. <button data-testid="hide-quota" onClick={()=>setHidden(true)}>Quota</button>
  45. <button data-testid="release" onClick={()=>releaseFailure?.()}>Release failure</button>
  46. <button data-testid="session" onClick={()=>{setSession(s=>s==="a"?"b":"a");setDirty(true)}}>Session</button>
  47. <button data-testid="cwd" onClick={()=>setCwd("/example/worktree")}>Cwd</button>
  48. <GitBranchActionsHost scopeKey={session} workspacePath={cwd} gitSummary={summary} dirtyFileCount={dirty?1:0} onRefreshGit={refresh}>
  49. <input data-testid="retained-editor" defaultValue="draft"/><GitStatusRepositoryContext.Provider value={{state:{datasets:{unstaged:{sections:dirty?[{changes:[{path:"file.txt",added:1,removed:0}]}]:[]},staged:{sections:[]}}}}}>
  50. {!hidden ? <div className="fixed bottom-4 left-4 right-4"><ComposerStatusRow><ConversationStatusPanel workspacePath="/example" gitSummary={summary} gitDirtyFileCount={dirty?1:0} onRefreshGit={refresh} /></ComposerStatusRow></div>:null}
  51. </GitStatusRepositoryContext.Provider></GitBranchActionsHost>
  52. </TooltipProvider></ServiceProvider></ZCodeIntlProvider>
  53. }
  54. createRoot(document.getElementById("root")).render(<Fixture/>);
  55. `;
  56. let server, browser, origin;
  57. before(async () => {
  58. await mkdir(artifacts, { recursive: true });
  59. server = await createServer({
  60. root,
  61. configFile: false,
  62. plugins: [
  63. {
  64. name: "composer-status-fixture",
  65. resolveId(id) {
  66. if (id === "/composer-status-fixture.tsx") return entry;
  67. },
  68. load(id) {
  69. if (id === entry) return fixture;
  70. },
  71. configureServer(vite) {
  72. vite.middlewares.use(async (req, res, next) => {
  73. if (!req.url?.startsWith("/fixture?")) return next();
  74. res.setHeader("Content-Type", "text/html");
  75. res.end(
  76. await vite.transformIndexHtml(
  77. req.url,
  78. '<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>',
  79. ),
  80. );
  81. });
  82. },
  83. },
  84. react(),
  85. tailwindcss(),
  86. ],
  87. resolve: { alias: { "@": join(root, "packages/ui/src") } },
  88. optimizeDeps: {
  89. entries: [],
  90. include: [
  91. "react",
  92. "react-dom/client",
  93. "react/jsx-runtime",
  94. "class-variance-authority",
  95. "clsx",
  96. "lucide-react",
  97. "radix-ui",
  98. "tailwind-merge",
  99. "zod",
  100. "zustand",
  101. ],
  102. },
  103. server: { host: "127.0.0.1", port: 0, hmr: false },
  104. });
  105. await server.listen();
  106. origin = server.resolvedUrls.local[0];
  107. // 半像素边框需要真实 2x 栅格;仅设置页面 deviceScaleFactor 仍可能按 1x 取整。
  108. browser = await chromium.launch(
  109. process.env.CHROME_EXECUTABLE_PATH
  110. ? {
  111. executablePath: process.env.CHROME_EXECUTABLE_PATH,
  112. args: ["--force-device-scale-factor=2"],
  113. }
  114. : { channel: "chrome", args: ["--force-device-scale-factor=2"] },
  115. );
  116. });
  117. after(async () => {
  118. await browser?.close();
  119. await server?.close();
  120. });
  121. async function openBranch(page) {
  122. await page.locator('[data-status-capsule="git"]').click();
  123. await page.getByTestId("status-git-current-branch").getByRole("button").click();
  124. await page.locator("[cmdk-input]").waitFor();
  125. }
  126. for (const theme of ["light", "dark"])
  127. for (const width of [390, 1200]) {
  128. test(`graph survives status removal ${theme}/${width}`, async () => {
  129. const page = await browser.newPage({ viewport: { width, height: 844 } });
  130. try {
  131. await page.goto(origin + `fixture?theme=${theme}`);
  132. await openBranch(page);
  133. await page.getByRole("button", { name: "Git Graph", exact: true }).click();
  134. await page.getByText("Retained commit", { exact: true }).waitFor();
  135. await page.locator('[data-status-capsule-content="git"]').waitFor({ state: "detached" });
  136. const row = page.getByText("Retained commit", { exact: true });
  137. await row.evaluate((node) => node.setAttribute("data-retained", "yes"));
  138. await page
  139. .getByTestId(width === 390 ? "hide-error" : "hide-quota")
  140. .evaluate((node) => node.click());
  141. assert.equal(await row.getAttribute("data-retained"), "yes");
  142. await page.screenshot({ path: join(artifacts, `graph-${theme}-${width}.png`) });
  143. await page.keyboard.press("Escape");
  144. await page.getByRole("dialog").waitFor({ state: "detached" });
  145. } finally {
  146. await page.close();
  147. }
  148. });
  149. test(`create survives capsule close ${theme}/${width}`, async () => {
  150. const page = await browser.newPage({ viewport: { width, height: 844 } });
  151. try {
  152. await page.goto(origin + `fixture?theme=${theme}`);
  153. await openBranch(page);
  154. await page.getByRole("button", { name: /Create.*branch/i }).click();
  155. await page.getByRole("dialog").waitFor();
  156. await page.locator('[data-status-capsule-content="git"]').waitFor({ state: "detached" });
  157. await page.locator("#git-branch-switcher-create-input").fill("new");
  158. await page.getByTestId("hide-error").evaluate((node) => node.click());
  159. assert.equal(await page.locator("#git-branch-switcher-create-input").inputValue(), "new");
  160. await page
  161. .getByTestId("retained-editor")
  162. .evaluate((node) => node.setAttribute("data-retained", "yes"));
  163. await page.getByTestId("session").evaluate((node) => node.click());
  164. assert.equal(
  165. await page.getByTestId("retained-editor").getAttribute("data-retained"),
  166. "yes",
  167. );
  168. await page.getByRole("dialog").waitFor({ state: "detached" });
  169. } finally {
  170. await page.close();
  171. }
  172. });
  173. }
  174. for (const theme of ["light", "dark"]) {
  175. test(`partial commit failure survives clean files ${theme}`, async () => {
  176. const page = await browser.newPage({ viewport: { width: 1200, height: 844 } });
  177. try {
  178. await page.goto(origin + `fixture?theme=${theme}`);
  179. await openBranch(page);
  180. await page.getByRole("option", { name: "feature", exact: true }).click();
  181. await page.getByRole("dialog").waitFor();
  182. await page.locator('[data-status-capsule-content="git"]').waitFor({ state: "detached" });
  183. await page.getByRole("button", { name: "Cancel", exact: true }).click();
  184. await page.getByRole("dialog").waitFor({ state: "detached" });
  185. await openBranch(page);
  186. await page.getByRole("option", { name: "feature", exact: true }).click();
  187. await page.getByRole("button", { name: "Commit and switch branch...", exact: true }).click();
  188. await page.getByRole("button", { name: "Commit and switch branch", exact: true }).click();
  189. await page.locator('[data-status-capsule="git"]').waitFor({ state: "detached" });
  190. assert.equal(await page.getByRole("dialog").count(), 1);
  191. await page.getByTestId("release").evaluate((node) => node.click());
  192. await page.getByText("Commit failed: E2E_SWITCH_FAILURE", { exact: true }).waitFor();
  193. await page.screenshot({ path: join(artifacts, `partial-${theme}.png`) });
  194. await page.getByRole("button", { name: "Cancel", exact: true }).click();
  195. await page.getByRole("dialog").waitFor({ state: "detached" });
  196. } finally {
  197. await page.close();
  198. }
  199. });
  200. }
  201. for (const transition of ["session", "cwd"]) {
  202. test(`scope ${transition} keeps editor and rejects late switch failure`, async () => {
  203. const page = await browser.newPage({ viewport: { width: 1200, height: 844 } });
  204. try {
  205. await page.goto(origin + "fixture?theme=light");
  206. await page.getByTestId("retained-editor").fill("keep my draft");
  207. await page
  208. .getByTestId("retained-editor")
  209. .evaluate((n) => n.setAttribute("data-retained", "yes"));
  210. await openBranch(page);
  211. await page.getByRole("option", { name: "feature", exact: true }).click();
  212. await page.getByRole("button", { name: "Commit and switch branch...", exact: true }).click();
  213. await page.getByRole("button", { name: "Commit and switch branch", exact: true }).click();
  214. await page.locator('[data-status-capsule="git"]').waitFor({ state: "detached" });
  215. await page.getByTestId(transition).evaluate((n) => n.click());
  216. await page.getByRole("dialog").waitFor({ state: "detached" });
  217. if (transition === "session") await page.getByTestId("session").evaluate((n) => n.click());
  218. await page.getByTestId("release").evaluate((n) => n.click());
  219. await page.evaluate(() => new Promise(requestAnimationFrame));
  220. assert.equal(await page.getByRole("dialog").count(), 0);
  221. assert.equal(await page.getByTestId("retained-editor").getAttribute("data-retained"), "yes");
  222. assert.equal(await page.getByTestId("retained-editor").inputValue(), "keep my draft");
  223. } finally {
  224. await page.close();
  225. }
  226. });
  227. }
  228. for (const locale of ["zh-CN", "en-US"]) {
  229. test(`create submit is language independent ${locale}`, async () => {
  230. const page = await browser.newPage({ viewport: { width: 1200, height: 844 } });
  231. try {
  232. await page.goto(origin + `fixture?theme=light&locale=${locale}`);
  233. await openBranch(page);
  234. await page
  235. .getByRole("button", {
  236. name: locale === "zh-CN" ? "创建并检出新分支..." : "Create and switch to new branch...",
  237. exact: true,
  238. })
  239. .click();
  240. await page.locator("#git-branch-switcher-create-input").fill("new");
  241. const submit = page.locator(
  242. '[role="dialog"] form:has(#git-branch-switcher-create-input) button[type="submit"]',
  243. );
  244. assert.equal(
  245. await submit.textContent(),
  246. locale === "zh-CN" ? "创建并切换" : "Create and switch",
  247. );
  248. await submit.click();
  249. await page.getByRole("dialog").waitFor({ state: "detached" });
  250. } finally {
  251. await page.close();
  252. }
  253. });
  254. }
  255. // 真实图谱组件使用可控服务 Promise,明确安排新响应先返回、旧响应后返回。
  256. for (const scenario of ["initial", "initial-error", "refresh-error", "page", "cwd", "reopen"]) {
  257. test(`graph rejects stale ${scenario} response`, async () => {
  258. const page = await browser.newPage({ viewport: { width: 1200, height: 844 } });
  259. const openGraph = async () => {
  260. await openBranch(page);
  261. await page.getByRole("button", { name: "Git Graph", exact: true }).click();
  262. };
  263. const waitRequests = (count) =>
  264. page.waitForFunction((n) => window.graphRequests.length === n, count);
  265. const release = (index, name, more = false) =>
  266. page.evaluate(({ index, name, more }) => window.graphRequests[index].resolve(name, more), {
  267. index,
  268. name,
  269. more,
  270. });
  271. try {
  272. await page.goto(origin + "fixture?theme=light&graphRace=1");
  273. await page
  274. .getByTestId("retained-editor")
  275. .evaluate((n) => n.setAttribute("data-retained", "yes"));
  276. await openGraph();
  277. await waitRequests(1);
  278. let stale = 0;
  279. if (scenario === "refresh-error" || scenario === "page") {
  280. await release(0, "Old initial", scenario === "page");
  281. await page.getByText("Old initial", { exact: true }).waitFor();
  282. if (scenario === "page") await page.getByRole("button", { name: /Load more/i }).click();
  283. else await page.getByRole("button", { name: /Refresh/i }).click();
  284. await waitRequests(2);
  285. stale = 1;
  286. }
  287. await page.keyboard.press("Escape");
  288. await page.getByRole("dialog").waitFor({ state: "detached" });
  289. if (scenario !== "reopen") {
  290. await page.getByTestId(scenario === "cwd" ? "cwd" : "session").click();
  291. if (scenario !== "cwd") await page.getByTestId("session").click();
  292. }
  293. await openGraph();
  294. await waitRequests(stale + 2);
  295. await release(stale + 1, "Current history");
  296. const current = page.getByText("Current history", { exact: true });
  297. await current.waitFor();
  298. const before = await page.getByRole("dialog").innerHTML();
  299. if (scenario.endsWith("error")) {
  300. await page.evaluate(
  301. (i) => window.graphRequests[i].reject(new Error("STALE_GRAPH_ERROR")),
  302. stale,
  303. );
  304. } else await release(stale, "Stale history", true);
  305. await page.evaluate(
  306. () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
  307. );
  308. assert.equal(await page.getByRole("dialog").innerHTML(), before);
  309. assert.equal(await page.getByText(/STALE_GRAPH_ERROR/).count(), 0);
  310. assert.equal(await page.getByRole("button", { name: /Load more/i }).count(), 0);
  311. assert.equal(await page.getByTestId("retained-editor").getAttribute("data-retained"), "yes");
  312. await page.screenshot({ path: join(artifacts, `graph-race-${scenario}.png`) });
  313. } finally {
  314. await page.close();
  315. }
  316. });
  317. }