conversation-session-remote-data-sync-demo-walkthrough.test.ts 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  1. /* eslint-disable max-lines -- 演示走查按真实用户顺序串起数据同步的全部功能,拆散会丢失章节的连续性。 */
  2. import { execFile } from "node:child_process";
  3. import { mkdir, readFile, symlink, writeFile } from "node:fs/promises";
  4. import { dirname, join, resolve } from "node:path";
  5. import { promisify } from "node:util";
  6. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  7. import {
  8. TID_PROMPT_SUGGESTION_PANEL,
  9. TID_SETTINGS_BACK_BUTTON,
  10. TID_SETTINGS_PAGE,
  11. TID_SETTINGS_SECTION_NAV,
  12. TID_TASK_SETTINGS_BUTTON,
  13. TID_V4_COMPOSER_INPUT,
  14. TID_VIRTUAL_PROJECT_MENU,
  15. testId,
  16. virtualProjectActionTestId,
  17. } from "@zcode/shared/test-ids";
  18. import {
  19. clearAppData,
  20. getE2EAppDataPaths,
  21. setInputValueByTestIdDom,
  22. waitForTestIdByDom,
  23. } from "#e2e/helpers/desktop-app";
  24. import {
  25. startElectronWindowRecording,
  26. type ElectronWindowRecordingSession,
  27. } from "#e2e/helpers/electron-window-recorder";
  28. import { createAndConfigurePersonalProvider } from "#e2e/helpers/personal-provider-settings";
  29. import {
  30. addMarketplaceSourceThroughAgent,
  31. createPluginLifecycleFixture,
  32. installMarketplacePluginThroughAgent,
  33. PLUGIN_LIFECYCLE_ID,
  34. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  35. PLUGIN_LIFECYCLE_NAME,
  36. } from "#e2e/helpers/plugin-management-lifecycle";
  37. import { hoverProjectRow, projectSectionSelector } from "#e2e/helpers/project-sidebar";
  38. import {
  39. bringRemoteDeviceOnline,
  40. chmodRemoteContainerPath,
  41. readRemoteContainerFile,
  42. readRemoteDockerContainer,
  43. remoteContainerPathExists,
  44. takeRemoteDeviceOffline,
  45. writeRemoteContainerFile,
  46. } from "#e2e/helpers/remote-docker-target";
  47. import {
  48. connectSSHWorkspace,
  49. prepareSSHConnectionPage,
  50. readSSHRuntimeConfig,
  51. } from "#e2e/helpers/ssh-remote-p0";
  52. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  53. /**
  54. * DSYNC-DEMO:数据同步功能演示走查(docs/remote/data-sync.md)。不是断言型用例:在本机 Docker 远端上
  55. * 按用户顺序走完数据同步的全部功能,每章录一段窗口视频(页面内叠加字幕、点击前高亮目标),最后拼成
  56. * 一个 mp4。断言只保留「流程确实到达了该状态」;某一章失败只记一条失败并继续后面的章节,最终仍判失败。
  57. * 长时间等待(连接、安装、离线判定)不进视频。
  58. */
  59. const MARKER = "E2E_DSYNC_DEMO_WALKTHROUGH";
  60. const artifact = resolve(
  61. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/data-sync-demo",
  62. "data-sync-demo",
  63. );
  64. const run = promisify(execFile);
  65. const FFMPEG = process.env.ZCODE_E2E_FFMPEG_PATH?.trim() || "ffmpeg";
  66. const FFPROBE = process.env.ZCODE_E2E_FFPROBE_PATH?.trim() || "ffprobe";
  67. const WINDOW = { width: 1440, height: 900 };
  68. const NARROW_WIDTH = 720;
  69. const FRAME_INTERVAL_MS = 200;
  70. const BEAT_MS = 2_200;
  71. const LONG_BEAT_MS = 3_200;
  72. const CLICK_LEAD_MS = 700;
  73. const REMOTE_HOME = "/home/dev";
  74. const REMOTE_CLI_CONFIG = `${REMOTE_HOME}/.zcode/cli/config.json`;
  75. const SCOPE_TRIGGER = '[data-plugin-scope-trigger="true"]';
  76. const DIALOG = '[data-testid="remote-sync-dialog"]';
  77. const DIALOG_CLOSE = `${DIALOG} [data-slot="dialog-close"]`;
  78. const SKILL = {
  79. push: "demo-code-review",
  80. agentsDir: "demo-agents-dir",
  81. update: "demo-api-design",
  82. older: "demo-legacy-tips",
  83. differs: "demo-release-notes",
  84. synced: "demo-style-guide",
  85. blocked: "demo-linked-assets",
  86. remoteOnly: "remote-only-notes",
  87. conflict: "demo-conflict",
  88. } as const;
  89. const AGENT = { push: "demo-reviewer", synced: "demo-planner" } as const;
  90. const MCP = { push: "demo-search", filesystem: "filesystem", differs: "demo-docs" } as const;
  91. const PLUGIN = {
  92. update: "demo-toolkit",
  93. older: "demo-formatter",
  94. marketplace: PLUGIN_LIFECYCLE_ID.toLowerCase(),
  95. } as const;
  96. const COMMAND = { nested: "/demo/commit", agentsDir: "/demo-review", synced: "/demo-standup" };
  97. const HOOK = {
  98. push: "echo demo: lint after bash",
  99. unchecked: "echo demo: guard writes",
  100. synced: "echo demo: check before edit",
  101. remoteOnly: "echo remote-only: format after edit",
  102. };
  103. const DEPENDENCY_HINT_BOTH = `远端缺少 MCP:${MCP.push};远端缺少技能:${SKILL.push}`;
  104. const DEPENDENCY_HINT_MCP = `远端缺少 MCP:${MCP.push}`;
  105. const PROVIDER = {
  106. providerName: "Demo Provider",
  107. baseURL: "https://api.example.com/v1",
  108. apiKey: "sk-demo-0123456789abcd",
  109. };
  110. const SECOND_PROVIDER = {
  111. providerName: "Demo Provider Backup",
  112. baseURL: "https://backup.example.com/v1",
  113. apiKey: "sk-demo-backup-9876543210wxyz",
  114. };
  115. interface ClipEntry {
  116. chapter: string;
  117. title: string;
  118. file: string;
  119. durationSec?: number;
  120. error?: string;
  121. }
  122. const clips: ClipEntry[] = [];
  123. const failures: string[] = [];
  124. let activeRecording: { session: ElectronWindowRecordingSession; entry: ClipEntry } | null = null;
  125. const tid = (id: string) => `[data-testid="${id}"]`;
  126. const rowSelector = (key: string) => tid(`remote-sync-row-${key}`);
  127. const ANY_ROW = '[data-testid^="remote-sync-row-"]:not([data-testid^="remote-sync-row-hint-"])';
  128. // ---------- 录制 ----------
  129. /** 按窗口逻辑尺寸采帧:Retina 屏 capturePage 返回 2 倍图,缩回逻辑尺寸以减小帧体积与编码耗时。 */
  130. async function captureLogicalFrame(): Promise<Buffer> {
  131. const pngBase64 = await browser.electron.execute(async (electron) => {
  132. const windows = electron.BrowserWindow.getAllWindows()
  133. .filter((win) => !win.isDestroyed())
  134. .sort((left, right) => Number(right.isFocused()) - Number(left.isFocused()));
  135. const target = windows.find((win) => win.isVisible()) ?? windows[0];
  136. if (!target) throw new Error("No Electron BrowserWindow is available for recording");
  137. const image = await target.webContents.capturePage();
  138. if (image.isEmpty())
  139. throw new Error("Electron BrowserWindow capturePage returned an empty image");
  140. const { width, height } = target.getContentBounds();
  141. const sized =
  142. image.getSize().width > width ? image.resize({ width, height, quality: "good" }) : image;
  143. return sized.toPNG().toString("base64");
  144. });
  145. return Buffer.from(String(pngBase64), "base64");
  146. }
  147. async function startPart(chapter: string, title: string): Promise<void> {
  148. const file = `clip-${String(clips.length + 1).padStart(2, "0")}-${chapter}.webm`;
  149. const entry: ClipEntry = { chapter, title, file };
  150. const session = await startElectronWindowRecording({
  151. browser,
  152. captureFrame: captureLogicalFrame,
  153. frameIntervalMs: FRAME_INTERVAL_MS,
  154. outputPath: resolve(artifact, file),
  155. encodeTimeoutMs: 5 * 60_000,
  156. stopTimeoutMs: 5 * 60_000,
  157. });
  158. clips.push(entry);
  159. activeRecording = { session, entry };
  160. }
  161. async function stopPart(): Promise<void> {
  162. const current = activeRecording;
  163. activeRecording = null;
  164. if (!current) return;
  165. try {
  166. await current.session.stop({ tailDurationMs: 400 });
  167. } catch (error) {
  168. current.entry.error = String(error instanceof Error ? error.message : error);
  169. }
  170. }
  171. /** 长时间等待不进视频:停止当前片段,等待结束后在同一章节继续录制。 */
  172. async function offCamera<T>(fn: () => Promise<T>): Promise<T> {
  173. const current = activeRecording;
  174. if (!current) return await fn();
  175. await stopPart();
  176. try {
  177. return await fn();
  178. } finally {
  179. await startPart(current.entry.chapter, current.entry.title);
  180. }
  181. }
  182. // ---------- 页面内叠加层:字幕、章节卡、点击高亮 ----------
  183. async function caption(text: string | null): Promise<void> {
  184. await browser.execute((value) => {
  185. const id = "zcode-demo-caption";
  186. let node = document.getElementById(id);
  187. if (!value) {
  188. node?.remove();
  189. return;
  190. }
  191. if (!node) {
  192. node = document.createElement("div");
  193. node.id = id;
  194. Object.assign(node.style, {
  195. position: "fixed",
  196. left: "50%",
  197. bottom: "26px",
  198. transform: "translateX(-50%)",
  199. maxWidth: "min(1120px, 88vw)",
  200. padding: "10px 22px",
  201. borderRadius: "12px",
  202. background: "rgba(17, 17, 20, 0.9)",
  203. color: "#ffffff",
  204. font: "500 17px/1.55 -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Segoe UI', sans-serif",
  205. boxShadow: "0 10px 30px rgba(0, 0, 0, 0.35)",
  206. textAlign: "center",
  207. whiteSpace: "pre-line",
  208. zIndex: "2147483647",
  209. pointerEvents: "none",
  210. });
  211. document.body.appendChild(node);
  212. }
  213. node.textContent = value;
  214. }, text);
  215. }
  216. async function titleCard(title: string, bullets: readonly string[], ms = 4_200): Promise<void> {
  217. await browser.execute(
  218. (heading, items) => {
  219. document.getElementById("zcode-demo-title")?.remove();
  220. const node = document.createElement("div");
  221. node.id = "zcode-demo-title";
  222. Object.assign(node.style, {
  223. position: "fixed",
  224. inset: "0",
  225. display: "flex",
  226. flexDirection: "column",
  227. alignItems: "center",
  228. justifyContent: "center",
  229. gap: "22px",
  230. background: "rgba(12, 12, 16, 0.95)",
  231. color: "#ffffff",
  232. font: "-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Segoe UI', sans-serif",
  233. zIndex: "2147483647",
  234. pointerEvents: "none",
  235. });
  236. const headingNode = document.createElement("div");
  237. headingNode.textContent = heading;
  238. Object.assign(headingNode.style, { font: "600 36px/1.3 inherit", letterSpacing: "0.5px" });
  239. node.appendChild(headingNode);
  240. if (items.length > 0) {
  241. const list = document.createElement("div");
  242. Object.assign(list.style, {
  243. display: "flex",
  244. flexDirection: "column",
  245. gap: "10px",
  246. maxWidth: "min(980px, 86vw)",
  247. font: "400 19px/1.6 inherit",
  248. color: "#d4d4d8",
  249. });
  250. for (const item of items) {
  251. const line = document.createElement("div");
  252. line.textContent = `· ${item}`;
  253. list.appendChild(line);
  254. }
  255. node.appendChild(list);
  256. }
  257. document.body.appendChild(node);
  258. },
  259. title,
  260. [...bullets],
  261. );
  262. await browser.pause(ms);
  263. await browser.execute(() => document.getElementById("zcode-demo-title")?.remove());
  264. }
  265. type LocateAction = "ring" | "ring-enabled" | "click";
  266. /**
  267. * 在页面里找目标并高亮或点击:只取可见元素,给出 match 时取文本包含它的最小元素;
  268. * query 为 "*" 时按文本定位,再上溯到行级祖先(列表行没有 test id 时使用)。
  269. * 叠加层自身(字幕里也可能出现 match)和包含叠加层的 body/html 不参与匹配。
  270. */
  271. async function locate(selector: string, match: string | undefined, action: LocateAction) {
  272. return await browser.execute(
  273. (query, text, mode) => {
  274. const overlays = ["zcode-demo-caption", "zcode-demo-title", "zcode-demo-spotlight"]
  275. .map((id) => document.getElementById(id))
  276. .filter((node): node is HTMLElement => Boolean(node));
  277. const area = (element: Element) => {
  278. const rect = element.getBoundingClientRect();
  279. return rect.width * rect.height;
  280. };
  281. const candidates = Array.from(document.querySelectorAll<HTMLElement>(query)).filter(
  282. (element) =>
  283. element.getClientRects().length > 0 &&
  284. !overlays.some(
  285. (node) => node === element || node.contains(element) || element.contains(node),
  286. ) &&
  287. (!text || (element.textContent ?? "").includes(text)) &&
  288. (mode === "ring" ||
  289. (!(element as HTMLButtonElement).disabled &&
  290. element.getAttribute("aria-disabled") !== "true")),
  291. );
  292. let target = text
  293. ? candidates.reduce<HTMLElement | undefined>(
  294. (best, element) => (!best || area(element) < area(best) ? element : best),
  295. undefined,
  296. )
  297. : candidates[0];
  298. if (!target) return false;
  299. if (query === "*") {
  300. const row = target.closest<HTMLElement>(
  301. 'li, [role="row"], [role="listitem"], [role="option"], button, a, label, [data-testid]',
  302. );
  303. if (row && area(row) < (window.innerWidth * window.innerHeight) / 6) target = row;
  304. }
  305. document.getElementById("zcode-demo-spotlight")?.remove();
  306. if (mode === "click") {
  307. target.click();
  308. return true;
  309. }
  310. target.scrollIntoView({ block: "nearest", inline: "nearest" });
  311. const rect = target.getBoundingClientRect();
  312. const ring = document.createElement("div");
  313. ring.id = "zcode-demo-spotlight";
  314. Object.assign(ring.style, {
  315. position: "fixed",
  316. left: `${rect.left - 5}px`,
  317. top: `${rect.top - 5}px`,
  318. width: `${rect.width + 10}px`,
  319. height: `${rect.height + 10}px`,
  320. border: "3px solid #f59e0b",
  321. borderRadius: "10px",
  322. boxShadow: "0 0 0 5px rgba(245, 158, 11, 0.28)",
  323. zIndex: "2147483646",
  324. pointerEvents: "none",
  325. });
  326. document.body.appendChild(ring);
  327. return true;
  328. },
  329. selector,
  330. match ?? null,
  331. action,
  332. );
  333. }
  334. async function spotlight(selector: string, match?: string): Promise<boolean> {
  335. return await locate(selector, match, "ring");
  336. }
  337. async function clearSpotlight(): Promise<void> {
  338. await browser.execute(() => document.getElementById("zcode-demo-spotlight")?.remove());
  339. }
  340. async function beat(ms = BEAT_MS): Promise<void> {
  341. if (activeRecording) await browser.pause(ms);
  342. }
  343. async function say(text: string, ms = BEAT_MS): Promise<void> {
  344. await caption(text);
  345. await beat(ms);
  346. }
  347. /** 带字幕地指向一个元素(只在录制时停留);元素不存在视为该段失败。 */
  348. async function point(
  349. selector: string,
  350. text?: string,
  351. options: { match?: string; ms?: number } = {},
  352. ): Promise<void> {
  353. if (text) await caption(text);
  354. await browser.waitUntil(async () => await spotlight(selector, options.match), {
  355. timeout: 30_000,
  356. timeoutMsg: `${MARKER}: 找不到要指向的元素 ${selector}${options.match ? `(${options.match})` : ""}`,
  357. });
  358. await beat(options.ms ?? BEAT_MS);
  359. await clearSpotlight();
  360. }
  361. /** 点击可见、可用的目标;录制时先高亮停留,再点击。 */
  362. async function demoClick(
  363. selector: string,
  364. options: { match?: string; leadMs?: number } = {},
  365. ): Promise<void> {
  366. const label = `${selector}${options.match ? `(${options.match})` : ""}`;
  367. await browser.waitUntil(
  368. async () =>
  369. activeRecording
  370. ? await locate(selector, options.match, "ring-enabled")
  371. : await locate(selector, options.match, "click"),
  372. { timeout: 30_000, timeoutMsg: `${MARKER}: 没有可点击的 ${label}` },
  373. );
  374. if (!activeRecording) return;
  375. await browser.pause(options.leadMs ?? CLICK_LEAD_MS);
  376. const clicked = await locate(selector, options.match, "click");
  377. await clearSpotlight();
  378. if (!clicked) throw new Error(`${MARKER}: 点击前 ${label} 消失了`);
  379. await browser.pause(300);
  380. }
  381. // ---------- 页面导航 ----------
  382. async function setLocaleAndTheme(locale: "zh-CN" | "en-US", theme: "light" | "dark") {
  383. await browser.execute(
  384. (language, color) => {
  385. const actions = (
  386. window as Window & {
  387. __testActions?: { setLocale(locale: string): void; setTheme(theme: string): void };
  388. }
  389. ).__testActions;
  390. if (!actions) throw new Error("Missing locale/theme test actions");
  391. actions.setLocale(language);
  392. actions.setTheme(color);
  393. },
  394. locale,
  395. theme,
  396. );
  397. await browser.executeAsync((done) =>
  398. requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(done, 120))),
  399. );
  400. }
  401. async function setWindowWidth(width: number) {
  402. await browser.electron.execute(
  403. (electron, size) => {
  404. const window = electron.BrowserWindow.getAllWindows().find((item) => !item.isDestroyed());
  405. window?.setMinimumSize(360, 600);
  406. window?.setSize(size.width, size.height);
  407. },
  408. { width, height: WINDOW.height },
  409. );
  410. await browser.pause(500);
  411. }
  412. async function parkPointer() {
  413. await browser.performActions([
  414. {
  415. type: "pointer",
  416. id: "park",
  417. parameters: { pointerType: "mouse" },
  418. actions: [{ type: "pointerMove", x: 2, y: 2, duration: 0 }],
  419. },
  420. ]);
  421. await browser.releaseActions();
  422. }
  423. async function isPresent(selector: string): Promise<boolean> {
  424. return await browser.execute((query) => Boolean(document.querySelector(query)), selector);
  425. }
  426. async function openSettingsSection(section: string): Promise<void> {
  427. if (!(await isPresent(tid(TID_SETTINGS_PAGE)))) {
  428. await demoClick(tid(TID_TASK_SETTINGS_BUTTON));
  429. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 30_000 });
  430. }
  431. await demoClick(tid(testId(TID_SETTINGS_SECTION_NAV, section)));
  432. }
  433. async function leaveSettings(): Promise<void> {
  434. if (!(await isPresent(tid(TID_SETTINGS_PAGE)))) return;
  435. await demoClick(tid(TID_SETTINGS_BACK_BUTTON));
  436. await browser.waitUntil(async () => !(await isPresent(tid(TID_SETTINGS_PAGE))), {
  437. timeout: 30_000,
  438. timeoutMsg: `${MARKER}: 设置页没有关闭`,
  439. });
  440. }
  441. async function openDataSyncPage(): Promise<void> {
  442. await openSettingsSection("dataSync");
  443. await waitForTestIdByDom("remote-sync-section", { timeout: 30_000 });
  444. }
  445. async function readDeviceRow() {
  446. return await browser.execute(() => {
  447. const row = document.querySelector<HTMLElement>(
  448. '[data-testid="remote-sync-device-list"] [data-source-server-id]',
  449. );
  450. return {
  451. state: row?.dataset.deviceState ?? null,
  452. status:
  453. row?.querySelector('[data-testid="remote-sync-device-status"]')?.textContent?.trim() ?? "",
  454. action:
  455. row?.querySelector('[data-testid="remote-sync-device-action"]')?.textContent?.trim() ?? "",
  456. };
  457. });
  458. }
  459. async function waitForDevice(
  460. predicate: (row: Awaited<ReturnType<typeof readDeviceRow>>) => boolean,
  461. timeoutMsg: string,
  462. timeout = 60_000,
  463. ) {
  464. let last: Awaited<ReturnType<typeof readDeviceRow>> | undefined;
  465. await browser
  466. .waitUntil(
  467. async () => {
  468. last = await readDeviceRow();
  469. return predicate(last);
  470. },
  471. { timeout, interval: 500 },
  472. )
  473. .catch((error: unknown) => {
  474. throw new Error(`${MARKER}: ${timeoutMsg}(${JSON.stringify(last)})`, { cause: error });
  475. });
  476. }
  477. async function waitForOverviewLoaded(): Promise<void> {
  478. await browser.waitUntil(
  479. () =>
  480. browser.execute(() => {
  481. const table = document.querySelector('[data-testid="remote-sync-overview-table"]');
  482. return Boolean(table && !(table.textContent ?? "").includes("加载中"));
  483. }),
  484. { timeout: 90_000, interval: 300, timeoutMsg: `${MARKER}: 概览没有加载完成` },
  485. );
  486. }
  487. async function openDataSyncDialog(): Promise<void> {
  488. await openDataSyncPage();
  489. await waitForDevice((row) => row.action === "同步配置" || row.action === "重试", "设备不能同步");
  490. await demoClick(tid("remote-sync-device-action"));
  491. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  492. }
  493. /** 关闭数据同步弹窗:概览页用底部「关闭」,分类页用右上角关闭按钮。 */
  494. async function closeDataSyncDialog(): Promise<void> {
  495. if (!(await isPresent(DIALOG))) return;
  496. if (await isPresent(tid("remote-sync-close"))) await demoClick(tid("remote-sync-close"));
  497. else await demoClick(DIALOG_CLOSE);
  498. await browser.waitUntil(async () => !(await isPresent(DIALOG)), {
  499. timeout: 30_000,
  500. timeoutMsg: `${MARKER}: 数据同步弹窗没有关闭`,
  501. });
  502. }
  503. /** 切换弹窗分类;给出 text 时同时更新字幕,避免上一步的字幕停留在新分类上。 */
  504. async function openTab(id: string, text?: string, leadMs?: number): Promise<void> {
  505. if (text) await caption(text);
  506. await demoClick(tid(`remote-sync-tab-${id}`), { leadMs });
  507. }
  508. async function readRowState(key: string) {
  509. return await browser.execute((rowTestId) => {
  510. const row = Array.from(document.querySelectorAll<HTMLButtonElement>("[data-testid]")).find(
  511. (element) => element.dataset.testid === rowTestId,
  512. );
  513. return row
  514. ? { status: row.dataset.syncStatus ?? null, checked: row.getAttribute("aria-checked") }
  515. : null;
  516. }, `remote-sync-row-${key}`);
  517. }
  518. async function waitForRow(key: string, status: string, timeout = 90_000): Promise<void> {
  519. let last: Awaited<ReturnType<typeof readRowState>> = null;
  520. await browser.waitUntil(
  521. async () => {
  522. last = await readRowState(key);
  523. return last?.status === status;
  524. },
  525. {
  526. timeout,
  527. interval: 300,
  528. timeoutMsg: `${MARKER}: ${key} 没有变为 ${status}(${JSON.stringify(last)})`,
  529. },
  530. );
  531. }
  532. async function setRowChecked(key: string, checked: boolean): Promise<void> {
  533. if ((await readRowState(key))?.checked === String(checked)) return;
  534. await demoClick(rowSelector(key));
  535. await browser.waitUntil(async () => (await readRowState(key))?.checked === String(checked), {
  536. timeout: 10_000,
  537. timeoutMsg: `${MARKER}: ${key} 勾选状态没有变为 ${checked}`,
  538. });
  539. }
  540. async function readText(selector: string): Promise<string> {
  541. return await browser.execute(
  542. (query) => document.querySelector(query)?.textContent?.trim() ?? "",
  543. selector,
  544. );
  545. }
  546. async function waitForText(selector: string, expected: string, timeout = 120_000): Promise<void> {
  547. await browser.waitUntil(async () => (await readText(selector)).includes(expected), {
  548. timeout,
  549. interval: 300,
  550. timeoutMsg: `${MARKER}: ${selector} 没有出现「${expected}」(当前「${await readText(selector)}」)`,
  551. });
  552. }
  553. async function pushActiveCategory(): Promise<void> {
  554. await demoClick(tid("remote-sync-push"));
  555. await waitForText(tid("remote-sync-push"), "再次同步", 5 * 60_000);
  556. }
  557. async function readHint(key: string): Promise<string | null> {
  558. return await browser.execute(
  559. (hintId) => document.querySelector(`[data-testid="${hintId}"]`)?.textContent ?? null,
  560. `remote-sync-row-hint-${key}`,
  561. );
  562. }
  563. async function waitForHint(key: string, hint: string | null): Promise<void> {
  564. await browser.waitUntil(async () => (await readHint(key)) === hint, {
  565. timeout: 90_000,
  566. interval: 300,
  567. timeoutMsg: `${MARKER}: ${key} 的依赖提示没有变为 ${hint}(当前 ${await readHint(key)})`,
  568. });
  569. }
  570. /** Radix 菜单需要 pointerdown 打开;只操作当前可见的触发器。 */
  571. async function openPointerMenu(trigger: string, menu = '[role="menu"]'): Promise<void> {
  572. await browser.waitUntil(
  573. () =>
  574. browser.execute(
  575. (triggerQuery, menuQuery) => {
  576. if (document.querySelector(menuQuery)) return true;
  577. const element = Array.from(document.querySelectorAll<HTMLElement>(triggerQuery)).find(
  578. (item) => item.getClientRects().length > 0,
  579. );
  580. element?.dispatchEvent(
  581. new PointerEvent("pointerdown", {
  582. bubbles: true,
  583. cancelable: true,
  584. button: 0,
  585. pointerId: 1,
  586. pointerType: "mouse",
  587. }),
  588. );
  589. return false;
  590. },
  591. trigger,
  592. menu,
  593. ),
  594. { timeout: 15_000, interval: 400, timeoutMsg: `${MARKER}: 菜单打不开 ${trigger}` },
  595. );
  596. }
  597. async function readScopeKey(): Promise<string | null> {
  598. return await browser.execute((selector) => {
  599. const trigger = Array.from(document.querySelectorAll<HTMLElement>(selector)).find(
  600. (element) => element.getClientRects().length > 0,
  601. );
  602. return trigger?.dataset.pluginScopeKey ?? null;
  603. }, SCOPE_TRIGGER);
  604. }
  605. async function selectScopeKey(key: string): Promise<void> {
  606. await openPointerMenu(SCOPE_TRIGGER, '[role="menuitemradio"]');
  607. await demoClick(`[role="menuitemradio"][data-plugin-scope-key="${key}"]`);
  608. await browser.waitUntil(async () => (await readScopeKey()) === key, {
  609. timeout: 30_000,
  610. timeoutMsg: `${MARKER}: scope 没有切到 ${key}`,
  611. });
  612. }
  613. async function readActiveTab(): Promise<string | null> {
  614. return await browser.execute(
  615. () =>
  616. document
  617. .querySelector('[data-testid^="remote-sync-tab-"][aria-current="page"]')
  618. ?.getAttribute("data-testid")
  619. ?.replace("remote-sync-tab-", "") ?? null,
  620. );
  621. }
  622. async function waitForDialogTab(tab: string): Promise<void> {
  623. await browser.waitUntil(
  624. async () => (await isPresent(DIALOG)) && (await readActiveTab()) === tab,
  625. {
  626. timeout: 30_000,
  627. timeoutMsg: `${MARKER}: 数据同步弹窗没有定位到 ${tab}`,
  628. },
  629. );
  630. }
  631. /** 段落失败后把界面收回:关掉菜单和非推送中的弹窗。 */
  632. async function recover(): Promise<void> {
  633. await caption(null).catch(() => undefined);
  634. await clearSpotlight().catch(() => undefined);
  635. await browser.keys("Escape").catch(() => undefined);
  636. await browser.pause(300);
  637. if ((await isPresent(DIALOG)) && (await isPresent(DIALOG_CLOSE))) {
  638. await browser
  639. .execute((query) => document.querySelector<HTMLElement>(query)?.click(), DIALOG_CLOSE)
  640. .catch(() => undefined);
  641. await browser.pause(500);
  642. }
  643. }
  644. interface ChapterSpec {
  645. key: string;
  646. title: string;
  647. bullets: readonly string[];
  648. setup?: () => Promise<void>;
  649. run: () => Promise<void>;
  650. cleanup?: () => Promise<void>;
  651. }
  652. /** 每章一段视频:先离线完成 setup,再开始录制,章节卡 → 演示 → 停止;失败只记录、不中断走查。 */
  653. async function chapter(spec: ChapterSpec): Promise<void> {
  654. try {
  655. await spec.setup?.();
  656. await startPart(spec.key, spec.title);
  657. await titleCard(spec.title, spec.bullets);
  658. await spec.run();
  659. await caption(null);
  660. await beat(900);
  661. } catch (error) {
  662. const detail = String(error instanceof Error ? error.message : error).slice(0, 400);
  663. failures.push(`${spec.title}:${detail}`);
  664. await browser
  665. .saveScreenshot(resolve(artifact, `FAILED-${spec.key}.png`))
  666. .catch(() => undefined);
  667. await recover();
  668. } finally {
  669. await caption(null).catch(() => undefined);
  670. await clearSpotlight().catch(() => undefined);
  671. await stopPart();
  672. await spec.cleanup?.().catch((error: unknown) => {
  673. failures.push(`${spec.title}(收尾):${String(error)}`);
  674. });
  675. }
  676. }
  677. // ---------- 本机与远端内容 ----------
  678. function skillMarkdown(name: string, description: string, body: string): string {
  679. return `---\nname: ${name}\ndescription: ${description}\n---\n${body}\n`;
  680. }
  681. function agentMarkdown(name: string, extra: string[], body: string): string {
  682. return [
  683. "---",
  684. `name: ${name}`,
  685. `description: ${name} for the data sync demo`,
  686. ...extra,
  687. "---",
  688. body,
  689. "",
  690. ].join("\n");
  691. }
  692. function pluginManifest(name: string, version: string): string {
  693. return `${JSON.stringify({ name, version, description: `${name} for the data sync demo` }, null, 2)}\n`;
  694. }
  695. const STYLE_GUIDE = skillMarkdown(SKILL.synced, "Team style guide", "Follow the team style guide.");
  696. const PLANNER = agentMarkdown(AGENT.synced, [], "Plan the work before writing code.");
  697. const STANDUP = "---\ndescription: Summarize yesterday and today\n---\nWrite the standup notes.\n";
  698. const SYNCED_HOOK = { matcher: "Edit", hooks: [{ type: "command", command: HOOK.synced }] };
  699. async function writeText(path: string, content: string): Promise<void> {
  700. await mkdir(dirname(path), { recursive: true });
  701. await writeFile(path, content);
  702. }
  703. async function readJson(path: string): Promise<Record<string, unknown>> {
  704. try {
  705. return JSON.parse(await readFile(path, "utf-8")) as Record<string, unknown>;
  706. } catch {
  707. return {};
  708. }
  709. }
  710. /** 本机六类内容:每类都有「推送」项,另配「更新 / 差异 / 已同步 / 不能同步」所需的对照项。 */
  711. async function writeLocalContent(home: string): Promise<void> {
  712. const zcode = join(home, ".zcode");
  713. const skills = join(zcode, "skills");
  714. await writeText(
  715. join(skills, SKILL.push, "SKILL.md"),
  716. skillMarkdown(
  717. SKILL.push,
  718. "Review code with the team checklist",
  719. "Check tests, naming, errors.",
  720. ),
  721. );
  722. await writeText(
  723. join(home, ".agents", "skills", SKILL.agentsDir, "SKILL.md"),
  724. skillMarkdown(SKILL.agentsDir, "Skill from the ~/.agents compat directory", "Compat skill."),
  725. );
  726. await writeText(
  727. join(skills, SKILL.update, "SKILL.md"),
  728. skillMarkdown(SKILL.update, "API design rules", "Use nouns for resources. v1.2"),
  729. );
  730. await writeText(join(skills, SKILL.update, "_meta.json"), '{ "version": "1.2.0" }\n');
  731. await writeText(
  732. join(skills, SKILL.older, "SKILL.md"),
  733. skillMarkdown(SKILL.older, "Legacy migration tips", "Old tips."),
  734. );
  735. await writeText(join(skills, SKILL.older, "_meta.json"), '{ "version": "1.0.0" }\n');
  736. await writeText(
  737. join(skills, SKILL.differs, "SKILL.md"),
  738. skillMarkdown(SKILL.differs, "Release notes format", "Local release notes format."),
  739. );
  740. await writeText(join(skills, SKILL.synced, "SKILL.md"), STYLE_GUIDE);
  741. const blocked = join(skills, SKILL.blocked);
  742. await writeText(
  743. join(blocked, "SKILL.md"),
  744. skillMarkdown(SKILL.blocked, "Skill that links shared assets", "Uses linked assets."),
  745. );
  746. await symlink("SKILL.md", join(blocked, "linked.md"));
  747. await writeText(
  748. join(zcode, "agents", `${AGENT.push}.md`),
  749. agentMarkdown(
  750. AGENT.push,
  751. ["tools: [Read, Grep, Glob]", `skills: [${SKILL.push}]`, `mcpServers: [${MCP.push}]`],
  752. "Review the change against the team checklist.",
  753. ),
  754. );
  755. await writeText(join(zcode, "agents", `${AGENT.synced}.md`), PLANNER);
  756. await writeText(
  757. join(zcode, "commands", "demo", "commit.md"),
  758. "---\ndescription: Write a commit message\n---\nWrite a commit message for the staged diff.\n",
  759. );
  760. await writeText(join(zcode, "commands", "demo-standup.md"), STANDUP);
  761. await writeText(
  762. join(home, ".agents", "commands", "demo-review.md"),
  763. "---\ndescription: Review the diff (compat directory)\n---\nReview the diff.\n",
  764. );
  765. const pluginDirs: string[] = [];
  766. for (const [name, version] of [
  767. [PLUGIN.update, "1.1.0"],
  768. [PLUGIN.older, "1.0.0"],
  769. ] as const) {
  770. const dir = join(zcode, "plugins", name);
  771. await writeText(join(dir, ".zcode-plugin", "plugin.json"), pluginManifest(name, version));
  772. await writeText(join(dir, "README.md"), `${name} ${version}\n`);
  773. pluginDirs.push(dir);
  774. }
  775. const configPath = join(zcode, "cli", "config.json");
  776. const config = await readJson(configPath);
  777. const plugins = (config.plugins ?? {}) as Record<string, unknown>;
  778. const mcp = (config.mcp ?? {}) as Record<string, unknown>;
  779. await writeText(
  780. configPath,
  781. `${JSON.stringify(
  782. {
  783. ...config,
  784. plugins: { ...plugins, dirs: [...((plugins.dirs as string[]) ?? []), ...pluginDirs] },
  785. mcp: {
  786. ...mcp,
  787. servers: {
  788. ...(mcp.servers as Record<string, unknown> | undefined),
  789. [MCP.push]: {
  790. command: "node",
  791. args: ["-e", "process.exit(0)", "search-server.js"],
  792. env: { SEARCH_API_KEY: "demo-search-key" },
  793. },
  794. [MCP.filesystem]: {
  795. command: "node",
  796. args: ["-e", "process.exit(0)", join(home, "projects")],
  797. },
  798. [MCP.differs]: { command: "node", args: ["-e", "process.exit(0)", "--local-docs"] },
  799. },
  800. },
  801. hooks: {
  802. enabled: true,
  803. events: {
  804. PostToolUse: [
  805. { matcher: "Bash", hooks: [{ type: "command", command: HOOK.push, timeout: 30 }] },
  806. ],
  807. PreToolUse: [
  808. SYNCED_HOOK,
  809. { matcher: "Write", hooks: [{ type: "command", command: HOOK.unchecked }] },
  810. ],
  811. },
  812. },
  813. },
  814. null,
  815. 2,
  816. )}\n`,
  817. );
  818. }
  819. /** 远端已有内容:差异、已同步与远端独有项;config.json 读改写,保留连接时写入的字段。 */
  820. async function seedRemote(container: string): Promise<void> {
  821. const write = (path: string, content: string) =>
  822. writeRemoteContainerFile(container, `${REMOTE_HOME}/${path}`, content);
  823. await write(
  824. `.zcode/skills/${SKILL.update}/SKILL.md`,
  825. skillMarkdown(SKILL.update, "API design rules", "Use nouns for resources. v1.1"),
  826. );
  827. await write(`.zcode/skills/${SKILL.update}/_meta.json`, '{ "version": "1.1.0" }\n');
  828. await write(
  829. `.zcode/skills/${SKILL.older}/SKILL.md`,
  830. skillMarkdown(SKILL.older, "Legacy migration tips", "Newer tips on the remote."),
  831. );
  832. await write(`.zcode/skills/${SKILL.older}/_meta.json`, '{ "version": "2.0.0" }\n');
  833. await write(
  834. `.zcode/skills/${SKILL.differs}/SKILL.md`,
  835. skillMarkdown(SKILL.differs, "Release notes format", "Remote release notes format."),
  836. );
  837. await write(`.zcode/skills/${SKILL.synced}/SKILL.md`, STYLE_GUIDE);
  838. await write(
  839. `.zcode/skills/${SKILL.remoteOnly}/SKILL.md`,
  840. skillMarkdown(SKILL.remoteOnly, "Notes that only exist on the remote", "Remote only."),
  841. );
  842. await write(`.zcode/agents/${AGENT.synced}.md`, PLANNER);
  843. await write(".zcode/commands/demo-standup.md", STANDUP);
  844. const remotePluginDirs: string[] = [];
  845. for (const [name, version] of [
  846. [PLUGIN.update, "1.0.0"],
  847. [PLUGIN.older, "2.0.0"],
  848. ] as const) {
  849. await write(`.zcode/plugins/${name}/.zcode-plugin/plugin.json`, pluginManifest(name, version));
  850. await write(`.zcode/plugins/${name}/README.md`, `${name} ${version}\n`);
  851. await write(`.zcode/plugins/${name}/data/state.json`, '{ "remote": true }\n');
  852. remotePluginDirs.push(`${REMOTE_HOME}/.zcode/plugins/${name}`);
  853. }
  854. const config = (await remoteContainerPathExists(container, REMOTE_CLI_CONFIG))
  855. ? (JSON.parse(await readRemoteContainerFile(container, REMOTE_CLI_CONFIG)) as Record<
  856. string,
  857. unknown
  858. >)
  859. : {};
  860. const plugins = (config.plugins ?? {}) as Record<string, unknown>;
  861. const mcp = (config.mcp ?? {}) as Record<string, unknown>;
  862. await writeRemoteContainerFile(
  863. container,
  864. REMOTE_CLI_CONFIG,
  865. `${JSON.stringify(
  866. {
  867. ...config,
  868. plugins: {
  869. ...plugins,
  870. dirs: [...((plugins.dirs as string[]) ?? []), ...remotePluginDirs],
  871. },
  872. mcp: {
  873. ...mcp,
  874. servers: {
  875. ...(mcp.servers as Record<string, unknown> | undefined),
  876. [MCP.filesystem]: {
  877. command: "node",
  878. args: ["-e", "process.exit(0)", `${REMOTE_HOME}/projects`],
  879. },
  880. [MCP.differs]: { command: "node", args: ["-e", "process.exit(0)", "--remote-docs"] },
  881. "remote-only-mcp": { command: "node", args: ["-e", "process.exit(0)"] },
  882. },
  883. },
  884. hooks: {
  885. enabled: true,
  886. events: {
  887. PreToolUse: [SYNCED_HOOK],
  888. PostToolUse: [
  889. { matcher: "Edit", hooks: [{ type: "command", command: HOOK.remoteOnly }] },
  890. ],
  891. },
  892. },
  893. },
  894. null,
  895. 2,
  896. )}\n`,
  897. );
  898. }
  899. // ---------- 拼接 ----------
  900. async function probeDuration(path: string): Promise<number | undefined> {
  901. try {
  902. const { stdout } = await run(FFPROBE, [
  903. "-v",
  904. "error",
  905. "-show_entries",
  906. "format=duration",
  907. "-of",
  908. "default=noprint_wrappers=1:nokey=1",
  909. path,
  910. ]);
  911. const value = Number.parseFloat(stdout.trim());
  912. return Number.isFinite(value) ? value : undefined;
  913. } catch {
  914. return undefined;
  915. }
  916. }
  917. function formatTimestamp(seconds: number): string {
  918. const whole = Math.floor(seconds);
  919. return `${String(Math.floor(whole / 60)).padStart(2, "0")}:${String(whole % 60).padStart(2, "0")}`;
  920. }
  921. /** 各段统一缩放到同一画布后拼接为 H.264 mp4,并按段时长写出章节时间点。 */
  922. async function assembleDemoVideo(): Promise<{ video?: string; error?: string }> {
  923. const usable = clips.filter((clip) => !clip.error);
  924. if (usable.length === 0) return { error: "没有可用的视频片段" };
  925. for (const clip of usable) clip.durationSec = await probeDuration(resolve(artifact, clip.file));
  926. const output = resolve(artifact, "data-sync-demo.mp4");
  927. const args = ["-y", "-loglevel", "error"];
  928. for (const clip of usable) args.push("-i", resolve(artifact, clip.file));
  929. const { width, height } = WINDOW;
  930. const filters = usable.map(
  931. (_, index) =>
  932. `[${index}:v]scale=${width}:${height}:force_original_aspect_ratio=decrease,` +
  933. `pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2:color=0x18181b,setsar=1,fps=10[v${index}]`,
  934. );
  935. const concat = `${usable.map((_, index) => `[v${index}]`).join("")}concat=n=${usable.length}:v=1:a=0[out]`;
  936. args.push(
  937. "-filter_complex",
  938. [...filters, concat].join(";"),
  939. "-map",
  940. "[out]",
  941. "-c:v",
  942. "libx264",
  943. "-pix_fmt",
  944. "yuv420p",
  945. "-crf",
  946. "20",
  947. "-preset",
  948. "medium",
  949. "-movflags",
  950. "+faststart",
  951. output,
  952. );
  953. try {
  954. await run(FFMPEG, args, { maxBuffer: 16 * 1024 * 1024, timeout: 15 * 60_000 });
  955. } catch (error) {
  956. return { error: String(error instanceof Error ? error.message : error).slice(0, 400) };
  957. }
  958. let offset = 0;
  959. let previous = "";
  960. const lines: string[] = [];
  961. for (const clip of usable) {
  962. if (clip.title !== previous) lines.push(`${formatTimestamp(offset)} ${clip.title}`);
  963. previous = clip.title;
  964. offset += clip.durationSec ?? 0;
  965. }
  966. await writeFile(resolve(artifact, "chapters.txt"), `${lines.join("\n")}\n`);
  967. return { video: output };
  968. }
  969. describe(`${MARKER}: 数据同步功能演示走查`, () => {
  970. let container = "";
  971. let offlineTarget: { host: string; port: number } | null = null;
  972. let providerDirLocked = false;
  973. after(async () => {
  974. if (offlineTarget)
  975. await bringRemoteDeviceOnline(container, offlineTarget).catch(() => undefined);
  976. if (providerDirLocked)
  977. await chmodRemoteContainerPath(container, "u+w", `${REMOTE_HOME}/.zcode/v2`).catch(
  978. () => undefined,
  979. );
  980. await browser.electron.restoreAllMocks();
  981. await clearAppData();
  982. });
  983. it("DSYNC-DEMO 按用户顺序演示数据同步全部功能并录制视频", async function () {
  984. this.timeout(90 * 60_000);
  985. await mkdir(artifact, { recursive: true });
  986. const config = readSSHRuntimeConfig(MARKER);
  987. container = readRemoteDockerContainer(MARKER);
  988. const workspacePath = config.workspacePaths[0]!;
  989. const { homeDir } = getE2EAppDataPaths();
  990. // ---------- 离线准备:本机内容、marketplace 插件、模型提供商 ----------
  991. await writeLocalContent(homeDir);
  992. await prepareSSHConnectionPage(MARKER);
  993. await prepareV4ConversationE2E({ skipProvider: true });
  994. await setWindowWidth(WINDOW.width);
  995. await setLocaleAndTheme("zh-CN", "light");
  996. const fixture = await createPluginLifecycleFixture("1.0.0");
  997. await addMarketplaceSourceThroughAgent(fixture.marketplaceRoot);
  998. await installMarketplacePluginThroughAgent(
  999. PLUGIN_LIFECYCLE_NAME,
  1000. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  1001. );
  1002. await openSettingsSection("modelProvider");
  1003. await createAndConfigurePersonalProvider(PROVIDER);
  1004. await leaveSettings();
  1005. await parkPointer();
  1006. await chapter({
  1007. key: "intro",
  1008. title: "ZCode 数据同步 · 功能演示",
  1009. bullets: [
  1010. "把本机的用户级配置推送到远端设备(SSH / WSL / Docker)",
  1011. "六类内容:子智能体、插件、MCP 服务器、技能、命令、钩子;模型提供商只读",
  1012. "推送永不删除远端独有的条目;远端较新或内容不同的项默认不勾选",
  1013. "本次演示的远端是本机 Docker 容器模拟的 Linux 设备",
  1014. ],
  1015. run: async () => {
  1016. await beat(1_200);
  1017. },
  1018. });
  1019. await chapter({
  1020. key: "entry",
  1021. title: "① 入口:设置 → 数据与统计 → 数据同步",
  1022. bullets: [
  1023. "没有远端设备时显示空状态和「连接远端设备」",
  1024. "「迁移」直接进入迁移向导第一步「会话」",
  1025. "设置侧栏不再有单独的「引导」入口",
  1026. ],
  1027. run: async () => {
  1028. await caption("从设置进入");
  1029. await openSettingsSection("dataSync");
  1030. await waitForTestIdByDom("remote-sync-empty", { timeout: 30_000 });
  1031. await point(
  1032. tid(testId(TID_SETTINGS_SECTION_NAV, "dataSync")),
  1033. "「数据与统计」分组下新增「数据同步」;侧栏不再有单独的「引导」入口",
  1034. );
  1035. await point(tid("remote-sync-empty"), "还没有远端设备:显示空状态和「连接远端设备」按钮", {
  1036. ms: LONG_BEAT_MS,
  1037. });
  1038. await caption("右上角「迁移」:从其他 AI 工具导入本机");
  1039. await demoClick(tid("remote-sync-migrate"));
  1040. await waitForTestIdByDom("onboarding-migration-dialog", { timeout: 30_000 });
  1041. await say("直接进入迁移向导第一步「会话」,不再经过欢迎页;左下角是「取消」", LONG_BEAT_MS);
  1042. await demoClick(tid("onboarding-wizard-cancel"));
  1043. await browser.waitUntil(
  1044. async () => !(await isPresent(tid("onboarding-migration-dialog"))),
  1045. {
  1046. timeout: 15_000,
  1047. timeoutMsg: `${MARKER}: 迁移向导没有关闭`,
  1048. },
  1049. );
  1050. await say("「取消」直接关闭向导,回到数据同步页");
  1051. },
  1052. });
  1053. // ---------- 离线准备:连接设备并打开远端项目,预置远端内容 ----------
  1054. await leaveSettings();
  1055. const remoteTab = await connectSSHWorkspace({ caseMarker: MARKER, config, workspacePath });
  1056. const sourceServerId =
  1057. parseRemoteWorkspaceIdentity(remoteTab.workspaceIdentity ?? "")?.sourceServerId ?? "";
  1058. expect(sourceServerId).toBeTruthy();
  1059. await seedRemote(container);
  1060. await parkPointer();
  1061. await chapter({
  1062. key: "devices",
  1063. title: "② 设备列表与同步弹窗",
  1064. bullets: [
  1065. "设备行:状态点、名称、传输方式、目标地址、上次同步状态",
  1066. "弹窗:顶部是目标设备;左侧分类导航;底部固定操作栏",
  1067. "概览:每类的本机数量、远端数量,以及「N 项变更」或「已一致」",
  1068. ],
  1069. run: async () => {
  1070. await caption("连接远端设备并打开项目后,回到「设置 → 数据同步」");
  1071. await openDataSyncPage();
  1072. await waitForDevice((row) => row.action === "同步配置", "设备行没有「同步配置」按钮");
  1073. await point(
  1074. tid("remote-sync-device-list"),
  1075. "设备行:绿色状态点、名称、传输方式与目标地址;还没同步过,显示「尚未同步」",
  1076. { ms: LONG_BEAT_MS },
  1077. );
  1078. await caption("点「同步配置」打开该设备的数据同步弹窗");
  1079. await demoClick(tid("remote-sync-device-action"));
  1080. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  1081. await say("打开时先显示概览;各分类分别加载,算好一类显示一类");
  1082. await waitForOverviewLoaded();
  1083. await point(tid("remote-sync-dialog-device"), "顶部显示推送目标:状态点、设备名和目标地址");
  1084. await point(
  1085. tid("remote-sync-overview-table"),
  1086. "概览:每类的本机数量、远端数量,以及「N 项变更」或「已一致」",
  1087. { ms: LONG_BEAT_MS },
  1088. );
  1089. await point(
  1090. tid("remote-sync-overview-providers"),
  1091. "模型提供商是只读分类:勾选框不可用,不参与「推送全部」",
  1092. );
  1093. await say("点行前的勾选框只改变选择;点整行进入该分类");
  1094. },
  1095. });
  1096. await chapter({
  1097. key: "subagents",
  1098. title: "③ 子智能体:按原文件推送,提示缺失依赖",
  1099. bullets: [
  1100. "按名称对齐、按原文件推送:模型、工具、技能等字段原样保留",
  1101. "引用的 MCP 或技能在远端不存在时,行内提示缺失项",
  1102. "提示不影响勾选和推送,由你决定是否一并推送依赖",
  1103. ],
  1104. run: async () => {
  1105. await demoClick(tid("remote-sync-overview-subagents"));
  1106. await waitForRow(AGENT.push, "push");
  1107. await waitForHint(AGENT.push, DEPENDENCY_HINT_BOTH);
  1108. await point(rowSelector(AGENT.push), "只在本机的子智能体:绿色「推送」,默认勾选");
  1109. await point(
  1110. tid(`remote-sync-row-hint-${AGENT.push}`),
  1111. "它引用的 MCP「demo-search」和技能「demo-code-review」远端都没有:行内提示缺失项",
  1112. { ms: LONG_BEAT_MS },
  1113. );
  1114. await point(rowSelector(AGENT.synced), "两端内容一致:灰色「已同步」,不可勾选");
  1115. },
  1116. });
  1117. await chapter({
  1118. key: "skills",
  1119. title: "④ 技能:条目状态、选择与推送",
  1120. bullets: [
  1121. "推送(绿)· 更新(蓝)· 差异(黄)· 已同步(灰)· 不能同步(写明原因)",
  1122. "列表按「推送 → 更新 → 差异 → 已同步」排序",
  1123. "推送完成后列表自动刷新;主动勾选差异项才会覆盖远端",
  1124. ],
  1125. run: async () => {
  1126. await openTab("skills");
  1127. await waitForRow(SKILL.push, "push");
  1128. await waitForRow(SKILL.update, "update");
  1129. await say("列表按「推送 → 更新 → 差异 → 已同步」排序,需要处理的项在前");
  1130. await point(rowSelector(SKILL.push), "绿色「推送」:只在本机,默认勾选");
  1131. await point(
  1132. rowSelector(SKILL.agentsDir),
  1133. "兼容目录 ~/.agents/skills 的技能也会同步,统一写入远端 ~/.zcode/skills",
  1134. );
  1135. await point(
  1136. rowSelector(SKILL.update),
  1137. "蓝色「更新」:本机版本较新(1.1.0 → 1.2.0),默认勾选",
  1138. );
  1139. await point(
  1140. rowSelector(SKILL.older),
  1141. "黄色「差异」:远端版本较新(本机版本较旧),默认不勾选,不会无意中降级远端",
  1142. );
  1143. await point(rowSelector(SKILL.differs), "黄色「差异」:没有版本号且内容不同,默认不勾选");
  1144. await point(rowSelector(SKILL.synced), "灰色「已同步」:两端一致,不可勾选");
  1145. await point(
  1146. rowSelector(SKILL.blocked),
  1147. "不能同步的条目不可选,并写明原因(这里是目录内含软链)",
  1148. );
  1149. await say("远端独有的技能(remote-only-notes)不出现在列表中,推送也永远不会删除它");
  1150. await point(tid("remote-sync-selection-summary"), "底部显示本次将同步的数量");
  1151. await caption("「全选」会连黄色差异项一起选中");
  1152. await demoClick(tid("remote-sync-select-all"));
  1153. await beat();
  1154. await caption("「取消选择」:显示「未选择任何内容」,推送按钮不可用");
  1155. await demoClick(tid("remote-sync-clear"));
  1156. await beat(LONG_BEAT_MS);
  1157. await caption("逐项勾选:只选默认项");
  1158. for (const key of [SKILL.push, SKILL.agentsDir, SKILL.update]) {
  1159. await setRowChecked(key, true);
  1160. }
  1161. await beat(1_200);
  1162. await caption("推送技能:按钮显示「同步中…」,推送期间弹窗不能关闭");
  1163. await pushActiveCategory();
  1164. await waitForRow(SKILL.push, "synced");
  1165. await say(
  1166. "完成后显示「再次同步」,列表自动刷新:刚推送的条目变为「已同步」;未勾选的差异项保持不变",
  1167. LONG_BEAT_MS,
  1168. );
  1169. await caption("主动勾选黄色差异项,用本机内容覆盖远端");
  1170. await setRowChecked(SKILL.differs, true);
  1171. await pushActiveCategory();
  1172. await waitForRow(SKILL.differs, "synced");
  1173. await point(rowSelector(SKILL.differs), "覆盖完成,该项变为「已同步」");
  1174. await caption("回到子智能体:缺失提示随两端列表更新");
  1175. await openTab("subagents");
  1176. await waitForHint(AGENT.push, DEPENDENCY_HINT_MCP);
  1177. await point(
  1178. tid(`remote-sync-row-hint-${AGENT.push}`),
  1179. "技能「demo-code-review」已推送到远端,提示只剩缺少的 MCP",
  1180. { ms: LONG_BEAT_MS },
  1181. );
  1182. },
  1183. });
  1184. await chapter({
  1185. key: "categories",
  1186. title: "⑤ 插件 · MCP 服务器 · 命令 · 钩子",
  1187. bullets: [
  1188. "插件:inline 插件按版本比较;marketplace 插件在远端按同一来源重新安装",
  1189. "MCP:filesystem 类的本机 home 路径改写为远端 home",
  1190. "命令:按相对路径对齐,包含 ~/.agents/commands 兼容目录",
  1191. "钩子:每条定义单独一行,推送只合并选中的定义",
  1192. ],
  1193. run: async () => {
  1194. await openTab("plugins");
  1195. await waitForRow(`${PLUGIN.update}@inline`, "update");
  1196. await point(
  1197. rowSelector(`${PLUGIN.update}@inline`),
  1198. "inline 插件:1.0.0 → 1.1.0,蓝色「更新」;远端插件目录里的 data/ 运行数据保留",
  1199. );
  1200. await point(
  1201. rowSelector(`${PLUGIN.older}@inline`),
  1202. "远端版本更高:黄色「差异」·「本机版本较旧」",
  1203. );
  1204. await point(
  1205. rowSelector(PLUGIN.marketplace),
  1206. "marketplace 插件:推送时在远端按同一来源重新安装;本地目录来源会先镜像到远端",
  1207. { ms: LONG_BEAT_MS },
  1208. );
  1209. await openTab("mcp", "切到「MCP 服务器」");
  1210. await waitForRow(MCP.push, "push");
  1211. await point(rowSelector(MCP.push), "MCP 服务器:命令、参数、环境变量原样同步");
  1212. await point(
  1213. rowSelector(MCP.filesystem),
  1214. "filesystem 类 MCP:本机 home 路径改写成远端 home 后再比较,两端一致,显示「已同步」",
  1215. { ms: LONG_BEAT_MS },
  1216. );
  1217. await point(rowSelector(MCP.differs), "远端同名 MCP 的配置不同:黄色「差异」");
  1218. await openTab("commands", "切到「命令」");
  1219. await waitForRow(COMMAND.nested, "push");
  1220. await point(rowSelector(COMMAND.nested), "命令按相对路径对齐,子目录结构保持不变");
  1221. await point(
  1222. rowSelector(COMMAND.agentsDir),
  1223. "兼容目录 ~/.agents/commands 的命令统一写入远端 ~/.zcode/commands",
  1224. );
  1225. await openTab("hooks", "切到「钩子」");
  1226. await browser.waitUntil(async () => await spotlight(ANY_ROW, HOOK.push), {
  1227. timeout: 60_000,
  1228. timeoutMsg: `${MARKER}: 钩子分类没有显示本机钩子`,
  1229. });
  1230. await clearSpotlight();
  1231. await point(
  1232. ANY_ROW,
  1233. "每条钩子定义单独一行:显示事件、matcher 和完整命令,清楚知道将在远端执行什么",
  1234. { match: HOOK.push, ms: LONG_BEAT_MS },
  1235. );
  1236. await point(ANY_ROW, "与远端一致的定义显示「已同步」", { match: HOOK.synced });
  1237. await say("推送只合并选中的定义;远端已有的其他钩子(这里有一条远端独有的)保持不变");
  1238. await caption("取消勾选其中一条");
  1239. await demoClick(ANY_ROW, { match: HOOK.unchecked });
  1240. await beat();
  1241. },
  1242. });
  1243. await chapter({
  1244. key: "push-all",
  1245. title: "⑥ 推送全部",
  1246. bullets: [
  1247. "概览勾选框有全选、部分选、未选三种状态,与分类页同步",
  1248. "「推送全部」只推送已勾选条目的分类",
  1249. "推送期间按钮显示「全部同步中…」,完成后显示「已全部同步」",
  1250. ],
  1251. run: async () => {
  1252. await openTab("overview");
  1253. await waitForOverviewLoaded();
  1254. await point(
  1255. tid("remote-sync-overview-checkbox-hooks"),
  1256. "钩子分类刚取消了一条:概览勾选框显示「部分选」",
  1257. { ms: LONG_BEAT_MS },
  1258. );
  1259. await caption("点「推送全部」:按分类依次推送已勾选的条目");
  1260. await demoClick(tid("remote-sync-push-all"));
  1261. // 插件是第二个推送的分类,远端安装 marketplace 插件只需几秒:立即切过去,才能看到按行「停止」。
  1262. await openTab("plugins", "切到插件分类查看推送进度", 150);
  1263. // 插件推送已结束(按钮变为「再次同步」)就不再等「停止」按钮,避免画面空等。
  1264. let stoppable = false;
  1265. await browser
  1266. .waitUntil(
  1267. async () => {
  1268. stoppable = await spotlight('[data-testid^="remote-sync-row-stop-"]');
  1269. return stoppable || (await readText(tid("remote-sync-push"))).includes("再次同步");
  1270. },
  1271. { timeout: 20_000, interval: 100 },
  1272. )
  1273. .catch(() => undefined);
  1274. if (stoppable) {
  1275. await say("marketplace 插件在远端添加或安装期间,可以按行「停止」", LONG_BEAT_MS);
  1276. await clearSpotlight();
  1277. }
  1278. await openTab("overview", "回到概览", 300);
  1279. if ((await readText(tid("remote-sync-push-all"))).includes("全部同步中")) {
  1280. await point(
  1281. tid("remote-sync-push-all"),
  1282. "推送全部期间按钮显示「全部同步中…」,弹窗不能关闭",
  1283. );
  1284. }
  1285. await offCamera(() => waitForText(tid("remote-sync-push-all"), "已全部同步", 10 * 60_000));
  1286. await waitForOverviewLoaded();
  1287. await say(
  1288. "完成后显示「已全部同步」:处理完的分类变为「已一致」;未勾选的差异项仍然保留",
  1289. LONG_BEAT_MS,
  1290. );
  1291. await caption("回到子智能体:依赖都已在远端,缺失提示消失");
  1292. await openTab("subagents");
  1293. await waitForHint(AGENT.push, null);
  1294. await point(rowSelector(AGENT.push), "子智能体已同步,没有缺失依赖提示");
  1295. },
  1296. });
  1297. await chapter({
  1298. key: "conflict",
  1299. title: "⑦ 冲突保护与设备同步状态",
  1300. bullets: [
  1301. "列表加载后远端又被修改:推送不覆盖,提示「远端已变化,请刷新后重试」",
  1302. "部分失败时失败项行内显示原因,底部汇总失败数量",
  1303. "设备行显示「上次同步失败」+「重试」,成功后显示「今天 HH:MM 已同步」",
  1304. ],
  1305. setup: async () => {
  1306. await writeText(
  1307. join(homeDir, ".zcode", "skills", SKILL.conflict, "SKILL.md"),
  1308. skillMarkdown(SKILL.conflict, "Skill created on this machine", "Local version."),
  1309. );
  1310. await closeDataSyncDialog();
  1311. await demoClick(tid("remote-sync-device-action"));
  1312. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  1313. await openTab("skills");
  1314. await waitForRow(SKILL.conflict, "push");
  1315. },
  1316. run: async () => {
  1317. await point(rowSelector(SKILL.conflict), "本机新建了技能 demo-conflict:列表显示「推送」");
  1318. await caption("列表加载之后,远端另一处也写入了同名技能");
  1319. await writeRemoteContainerFile(
  1320. container,
  1321. `${REMOTE_HOME}/.zcode/skills/${SKILL.conflict}/SKILL.md`,
  1322. skillMarkdown(SKILL.conflict, "Skill created on the remote", "Remote version."),
  1323. );
  1324. await beat();
  1325. await caption("推送技能");
  1326. await demoClick(tid("remote-sync-push"));
  1327. await waitForText(tid(`remote-sync-row-error-${SKILL.conflict}`), "远端已变化", 120_000);
  1328. await point(
  1329. rowSelector(SKILL.conflict),
  1330. "推送前校验远端基线:远端已变化时不覆盖,行内提示「远端已变化,请刷新后重试」",
  1331. { ms: LONG_BEAT_MS },
  1332. );
  1333. await point(tid("remote-sync-failure-summary"), "底部汇总失败数量");
  1334. await openTab("overview");
  1335. await closeDataSyncDialog();
  1336. await waitForDevice((row) => row.status === "上次同步失败", "设备行没有显示同步失败");
  1337. await point(
  1338. tid("remote-sync-device-list"),
  1339. "设备行显示红点「上次同步失败」,按钮变为「重试」",
  1340. { ms: LONG_BEAT_MS },
  1341. );
  1342. await caption("点「重试」重新打开该设备的同步弹窗");
  1343. await demoClick(tid("remote-sync-device-action"));
  1344. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  1345. await openTab("skills");
  1346. await waitForRow(SKILL.conflict, "difference");
  1347. await point(
  1348. rowSelector(SKILL.conflict),
  1349. "重新加载后按最新远端比较:该项变为黄色「差异」,默认不勾选",
  1350. );
  1351. await caption("确认用本机内容覆盖:勾选后推送");
  1352. await setRowChecked(SKILL.conflict, true);
  1353. await pushActiveCategory();
  1354. await waitForRow(SKILL.conflict, "synced");
  1355. await openTab("overview");
  1356. await closeDataSyncDialog();
  1357. await waitForDevice((row) => row.status.includes("已同步"), "设备行没有显示同步时间");
  1358. await point(tid("remote-sync-device-list"), "同步成功:设备行显示「今天 HH:MM 已同步」", {
  1359. ms: LONG_BEAT_MS,
  1360. });
  1361. },
  1362. });
  1363. await chapter({
  1364. key: "providers",
  1365. title: "⑧ 模型提供商:只读、自动同步失败与重试",
  1366. bullets: [
  1367. "列出本机的模型提供商,API Key 只显示掩码",
  1368. "显示上次自动同步的时间和结果;失败时显示原因和「重试」",
  1369. "不参与勾选和「推送全部」,模型配置始终以本机为准整体下发",
  1370. ],
  1371. setup: async () => {
  1372. // 远端模型配置目录只读:本机新增提供商后自动下发失败(与 DSYNC-13 相同的故障注入)。
  1373. await chmodRemoteContainerPath(container, "a-w", `${REMOTE_HOME}/.zcode/v2`);
  1374. providerDirLocked = true;
  1375. await openSettingsSection("modelProvider");
  1376. await createAndConfigurePersonalProvider(SECOND_PROVIDER);
  1377. await openDataSyncPage();
  1378. await parkPointer();
  1379. },
  1380. run: async () => {
  1381. await caption("本机刚新增了一个模型提供商,自动下发到远端时写入失败");
  1382. await demoClick(tid("remote-sync-device-action"));
  1383. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  1384. await point(
  1385. tid("remote-sync-overview-providers"),
  1386. "概览中「模型提供商」一行显示「同步失败」",
  1387. );
  1388. await openTab("providers");
  1389. await browser.waitUntil(
  1390. async () =>
  1391. (await browser.execute(
  1392. () =>
  1393. document.querySelector<HTMLElement>('[data-testid="remote-sync-providers-status"]')
  1394. ?.dataset.provisioningState ?? null,
  1395. )) === "failed",
  1396. { timeout: 120_000, interval: 500, timeoutMsg: `${MARKER}: 模型提供商没有显示失败` },
  1397. );
  1398. await point(
  1399. tid("remote-sync-resource-list"),
  1400. "只读列表:本机的模型提供商与地址,API Key 只显示掩码",
  1401. { ms: LONG_BEAT_MS },
  1402. );
  1403. await point(
  1404. tid("remote-sync-providers-status"),
  1405. "显示上次自动同步的时间和失败原因,并提供「重试」",
  1406. { ms: LONG_BEAT_MS },
  1407. );
  1408. await chmodRemoteContainerPath(container, "u+w", `${REMOTE_HOME}/.zcode/v2`);
  1409. providerDirLocked = false;
  1410. await caption("远端恢复可写后点「重试」");
  1411. await demoClick(tid("remote-sync-providers-retry"));
  1412. await browser.waitUntil(
  1413. async () =>
  1414. (await browser.execute(
  1415. () =>
  1416. document.querySelector<HTMLElement>('[data-testid="remote-sync-providers-status"]')
  1417. ?.dataset.provisioningState ?? null,
  1418. )) === "success",
  1419. { timeout: 120_000, interval: 500, timeoutMsg: `${MARKER}: 重试后没有显示成功` },
  1420. );
  1421. await point(tid("remote-sync-providers-status"), "重试成功:显示「HH:MM 已自动同步」", {
  1422. ms: LONG_BEAT_MS,
  1423. });
  1424. },
  1425. cleanup: async () => {
  1426. if (providerDirLocked) {
  1427. await chmodRemoteContainerPath(container, "u+w", `${REMOTE_HOME}/.zcode/v2`);
  1428. providerDirLocked = false;
  1429. }
  1430. },
  1431. });
  1432. await chapter({
  1433. key: "runtime",
  1434. title: "⑨ 推送后在远程项目中立即可用",
  1435. bullets: ["推送后自动刷新远端的技能、子智能体、命令、MCP、插件", "不需要重开远程项目"],
  1436. setup: async () => {
  1437. await closeDataSyncDialog();
  1438. await leaveSettings();
  1439. await parkPointer();
  1440. },
  1441. run: async () => {
  1442. await caption("回到远程项目,在输入框输入「/」");
  1443. for (const value of ["/", "/d", "/de", "/dem", "/demo"]) {
  1444. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, value, { timeout: 30_000 });
  1445. await browser.pause(220);
  1446. }
  1447. await browser.waitUntil(
  1448. async () => (await readText(tid(TID_PROMPT_SUGGESTION_PANEL))).includes(COMMAND.nested),
  1449. {
  1450. timeout: 60_000,
  1451. interval: 500,
  1452. timeoutMsg: `${MARKER}: / 建议没有出现推送的命令`,
  1453. },
  1454. );
  1455. await point(
  1456. tid(TID_PROMPT_SUGGESTION_PANEL),
  1457. "刚推送的命令(含子目录命令 /demo/commit 和兼容目录的 /demo-review)立即出现在 / 建议中",
  1458. { ms: LONG_BEAT_MS + 600 },
  1459. );
  1460. await caption("向下滚动:推送的技能($demo-…)和子智能体也在");
  1461. // 建议列表是虚拟列表,只渲染可见行:边滚动边累计文字,再判断技能和子智能体是否出现。
  1462. let seen = "";
  1463. for (let step = 0; step < 30; step += 1) {
  1464. const result = await browser.execute((panelId) => {
  1465. const list = document.querySelector<HTMLElement>(
  1466. `[data-testid="${panelId}"] [role="listbox"]`,
  1467. );
  1468. if (!list) return null;
  1469. const atEnd = list.scrollTop + list.clientHeight >= list.scrollHeight - 2;
  1470. const text = list.textContent ?? "";
  1471. list.scrollBy({ top: 96, behavior: "smooth" });
  1472. return { atEnd, text };
  1473. }, TID_PROMPT_SUGGESTION_PANEL);
  1474. if (!result) break;
  1475. seen += result.text;
  1476. if (result.atEnd) break;
  1477. await browser.pause(activeRecording ? 650 : 150);
  1478. }
  1479. expect(seen).toContain(SKILL.push);
  1480. expect(seen).toContain(AGENT.push);
  1481. await beat(LONG_BEAT_MS);
  1482. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "");
  1483. },
  1484. });
  1485. await chapter({
  1486. key: "legacy-entries",
  1487. title: "⑩ 旧同步入口统一打开数据同步弹窗",
  1488. bullets: [
  1489. "侧栏远端项目菜单、技能 / MCP / 插件设置页、Header 更多菜单的同步入口",
  1490. "都打开同一个数据同步弹窗,并定位到对应的设备和分类",
  1491. ],
  1492. run: async () => {
  1493. await caption("侧栏远端项目的「更多」菜单");
  1494. await hoverProjectRow(workspacePath);
  1495. await openPointerMenu(
  1496. `${projectSectionSelector(workspacePath)} [data-testid="${TID_VIRTUAL_PROJECT_MENU}"]`,
  1497. );
  1498. await caption("「同步插件」");
  1499. await demoClick(tid(virtualProjectActionTestId("sync-plugins-0")));
  1500. await waitForDialogTab("plugins");
  1501. await parkPointer();
  1502. await point(DIALOG, "打开的是同一个数据同步弹窗,直接定位到该设备的「插件」分类", {
  1503. ms: LONG_BEAT_MS,
  1504. });
  1505. await demoClick(DIALOG_CLOSE);
  1506. await caption("技能设置页的「同步」按钮");
  1507. await openSettingsSection("skill");
  1508. await demoClick(tid("data-sync-entry-skills"));
  1509. await waitForDialogTab("skills");
  1510. await point(DIALOG, "同样打开数据同步弹窗,定位到「技能」分类", { ms: LONG_BEAT_MS });
  1511. await demoClick(DIALOG_CLOSE);
  1512. },
  1513. });
  1514. await chapter({
  1515. key: "scope-menu",
  1516. title: "⑪ 设置页 Scope 菜单按设备分组",
  1517. bullets: [
  1518. "「本机」下是用户和本机项目;每台在线远端设备下是用户和该设备的项目",
  1519. "触发器显示「设备 · 用户」或「设备 · 项目」",
  1520. "不打开远程项目也能直接编辑远端 ~/.zcode;插件、MCP、技能、子智能体、命令、钩子同一规则",
  1521. ],
  1522. setup: async () => {
  1523. await openSettingsSection("skill");
  1524. },
  1525. run: async () => {
  1526. const remoteUserKey = `source-user:${sourceServerId}`;
  1527. await browser.waitUntil(async () => (await readScopeKey()) === remoteUserKey, {
  1528. timeout: 60_000,
  1529. timeoutMsg: `${MARKER}: 技能页没有默认选中远端设备的「用户」`,
  1530. });
  1531. await point(
  1532. SCOPE_TRIGGER,
  1533. "当前 workspace 在远端设备上:默认选中该设备的「用户」,触发器显示「设备 · 用户」",
  1534. { ms: LONG_BEAT_MS },
  1535. );
  1536. await caption("菜单按设备分组:「本机」下是用户和本机项目;远端设备下是用户和该设备的项目");
  1537. await openPointerMenu(SCOPE_TRIGGER, '[role="menuitemradio"]');
  1538. await beat(LONG_BEAT_MS + 800);
  1539. await browser.keys("Escape");
  1540. await point(
  1541. "*",
  1542. "列表就是远端 ~/.zcode/skills:远端独有的 remote-only-notes 仍在,推送从不删除远端条目",
  1543. { match: SKILL.remoteOnly, ms: LONG_BEAT_MS },
  1544. );
  1545. await caption("切到「本机 · 用户」");
  1546. await selectScopeKey("user");
  1547. await say("同一页面直接切换要编辑的设备:现在列表是本机技能", LONG_BEAT_MS);
  1548. await caption("MCP 页遵循同一规则");
  1549. await openSettingsSection("mcp");
  1550. await point(SCOPE_TRIGGER, "MCP 页同样按设备分组,默认是当前 workspace 所在设备的「用户」");
  1551. },
  1552. });
  1553. await chapter({
  1554. key: "theme-locale",
  1555. title: "⑫ 深色主题与英文界面",
  1556. bullets: ["所有状态标签在浅色和深色主题下都清晰可读", "所有文案都有英文翻译"],
  1557. setup: async () => {
  1558. await openDataSyncDialog();
  1559. await openTab("plugins");
  1560. await waitForRow(`${PLUGIN.older}@inline`, "difference");
  1561. },
  1562. run: async () => {
  1563. await setLocaleAndTheme("zh-CN", "dark");
  1564. await say("深色主题:推送、更新、差异、已同步标签都清晰可读", LONG_BEAT_MS);
  1565. await openTab("skills");
  1566. await beat();
  1567. await setLocaleAndTheme("en-US", "dark");
  1568. await say("英文界面", LONG_BEAT_MS);
  1569. await openTab("overview");
  1570. await beat();
  1571. await setLocaleAndTheme("en-US", "light");
  1572. await say("English · light theme", BEAT_MS);
  1573. },
  1574. cleanup: async () => {
  1575. await setLocaleAndTheme("zh-CN", "light");
  1576. await closeDataSyncDialog();
  1577. },
  1578. });
  1579. await chapter({
  1580. key: "narrow",
  1581. title: "⑬ 窄窗口",
  1582. bullets: ["分类导航变为顶部可横向滚动的标签"],
  1583. setup: async () => {
  1584. await setWindowWidth(NARROW_WIDTH);
  1585. await demoClick(tid("remote-sync-device-action"));
  1586. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  1587. },
  1588. run: async () => {
  1589. await point(tid("remote-sync-sidebar-frame"), "窄窗口:分类导航变为顶部横向标签", {
  1590. ms: LONG_BEAT_MS,
  1591. });
  1592. await browser.execute(() =>
  1593. document
  1594. .querySelector('[data-testid="remote-sync-sidebar-frame"] nav')
  1595. ?.scrollTo({ left: 600, behavior: "smooth" }),
  1596. );
  1597. await say("可以横向滚动");
  1598. await openTab("hooks");
  1599. await beat();
  1600. },
  1601. cleanup: async () => {
  1602. await closeDataSyncDialog();
  1603. await setWindowWidth(WINDOW.width);
  1604. },
  1605. });
  1606. await chapter({
  1607. key: "offline",
  1608. title: "⑭ 设备离线与恢复",
  1609. bullets: [
  1610. "设备断开后弹窗显示离线,并禁用全部操作",
  1611. "远端恢复后,打开中的远程项目自动重连",
  1612. "设备重新上线后,弹窗自动重新加载列表",
  1613. ],
  1614. setup: async () => {
  1615. await openDataSyncDialog();
  1616. await waitForOverviewLoaded();
  1617. },
  1618. run: async () => {
  1619. await caption("弹窗打开时,远端设备断开(这里停止了远端容器)");
  1620. offlineTarget = { host: config.host, port: config.port };
  1621. await takeRemoteDeviceOffline(container);
  1622. await offCamera(() =>
  1623. browser.waitUntil(async () => await isPresent(tid("remote-sync-offline")), {
  1624. timeout: 5 * 60_000,
  1625. interval: 500,
  1626. timeoutMsg: `${MARKER}: 设备离线后弹窗没有显示离线`,
  1627. }),
  1628. );
  1629. await point(
  1630. tid("remote-sync-offline"),
  1631. "弹窗显示「设备已离线,操作已禁用」;顶部状态点变为空心",
  1632. { ms: LONG_BEAT_MS },
  1633. );
  1634. await point(tid("remote-sync-push-all"), "「推送全部」等操作全部禁用");
  1635. await caption("远端恢复:打开中的远程项目会自动重连");
  1636. await bringRemoteDeviceOnline(container, offlineTarget);
  1637. offlineTarget = null;
  1638. await beat(1_200);
  1639. await offCamera(async () => {
  1640. await browser.waitUntil(async () => !(await isPresent(tid("remote-sync-offline"))), {
  1641. timeout: 5 * 60_000,
  1642. interval: 500,
  1643. timeoutMsg: `${MARKER}: 设备恢复后弹窗仍显示离线`,
  1644. });
  1645. await waitForOverviewLoaded();
  1646. });
  1647. await point(
  1648. tid("remote-sync-overview-table"),
  1649. "设备重新上线:离线提示消失,弹窗按最新远端状态自动重新加载列表",
  1650. { ms: LONG_BEAT_MS },
  1651. );
  1652. await closeDataSyncDialog();
  1653. await waitForDevice((row) => row.action === "同步配置", "设备行没有恢复为「同步配置」");
  1654. await point(tid("remote-sync-device-list"), "设备行恢复为绿色状态点和「同步配置」", {
  1655. ms: LONG_BEAT_MS,
  1656. });
  1657. },
  1658. cleanup: async () => {
  1659. if (offlineTarget) {
  1660. await bringRemoteDeviceOnline(container, offlineTarget);
  1661. offlineTarget = null;
  1662. }
  1663. await closeDataSyncDialog().catch(() => undefined);
  1664. },
  1665. });
  1666. await chapter({
  1667. key: "outro",
  1668. title: "演示结束",
  1669. bullets: [
  1670. "数据同步页:设备列表、同步状态、迁移入口",
  1671. "同步弹窗:概览、六类推送、模型提供商只读、冲突保护、离线保护",
  1672. "旧入口统一打开同一个弹窗;Scope 菜单按设备分组",
  1673. ],
  1674. run: async () => {
  1675. await beat(1_000);
  1676. },
  1677. });
  1678. const assembled = await assembleDemoVideo();
  1679. await writeFile(
  1680. resolve(artifact, "index.json"),
  1681. JSON.stringify(
  1682. { marker: MARKER, capturedAt: new Date().toISOString(), assembled, clips, failures },
  1683. null,
  1684. 2,
  1685. ),
  1686. );
  1687. expect(assembled.error).toBeUndefined();
  1688. expect(clips.filter((clip) => clip.error).map((clip) => clip.file)).toEqual([]);
  1689. // 章节失败可以继续录后面的章节,但不能把未完成的演示汇总为 PASS。
  1690. expect(failures).toEqual([]);
  1691. });
  1692. });