conversation-session-plugin-remote-explicit-sync-workspace.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import { Buffer } from "node:buffer";
  2. import { readFile } from "node:fs/promises";
  3. import { join, posix } from "node:path";
  4. import { TID_WORKSPACE_HEADER, TID_WORKSPACE_MORE_BUTTON, TID_WORKSPACE_PATH } from "@zcode/shared";
  5. import { clearAppData, getE2EAppDataPaths } from "../../../helpers/desktop-app.js";
  6. import {
  7. addMarketplaceSourceThroughAgent,
  8. createPluginLifecycleFixture,
  9. getPluginOverview,
  10. getPluginList,
  11. installMarketplacePluginThroughAgent,
  12. PLUGIN_LIFECYCLE_ID,
  13. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  14. PLUGIN_LIFECYCLE_MCP_TOOL_NAME,
  15. PLUGIN_LIFECYCLE_NAME,
  16. PLUGIN_LIFECYCLE_RUNTIME_MARKER,
  17. pluginStoragePath,
  18. } from "../../../helpers/plugin-management-lifecycle.js";
  19. import {
  20. getUpstreamRequestRecordCount,
  21. getUpstreamRequestToolNames,
  22. waitForUpstreamRequest,
  23. } from "../../../helpers/conversation-session-network.js";
  24. import { waitForToolCallBlockByToolName } from "../../../helpers/conversation-session-tool.js";
  25. import {
  26. ensureToolCrossProductFullAccessMode,
  27. respondToToolCrossProductBlockers,
  28. } from "../../../helpers/conversation-session-tool-cross-product.js";
  29. import {
  30. connectSSHWorkspaceAndSendFirstTurn,
  31. createSSHLifecycleProvider,
  32. type SSHLifecycleProvider,
  33. } from "../../../helpers/ssh-remote-lifecycle.js";
  34. import {
  35. readSingleSSHWorkspaceRuntimeConfig,
  36. runSSHCommand,
  37. type SSHConnectionConfig,
  38. } from "../../../helpers/ssh-remote-p0.js";
  39. import {
  40. prepareV4ConversationE2E,
  41. sendV4PromptAndWaitAccepted,
  42. startNewV4Draft,
  43. waitForV4AssistantMessageContaining,
  44. } from "../../../helpers/v4-conversation.js";
  45. const CASE_MARKER = "E2E_WPL_011_REMOTE_EXPLICIT_SYNC";
  46. const RUNTIME_MARKER = `${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_1.0.0`;
  47. const RUNTIME_PROMPT = `${CASE_MARKER}_RUNTIME_PROMPT`;
  48. const RUNTIME_REPLY = "WPL_011_REMOTE_EXPLICIT_SYNC_REPLY";
  49. describe("WPL-011 remote Workspace Plugin explicit sync E2E", () => {
  50. let provider: SSHLifecycleProvider | null = null;
  51. let target: SSHConnectionConfig | null = null;
  52. let workspacePath = "";
  53. after(async () => {
  54. await provider?.tunnel.close().catch(() => undefined);
  55. if (target && workspacePath) {
  56. await cleanupRemoteWorkspace(target, workspacePath).catch(() => undefined);
  57. }
  58. await browser.electron.restoreAllMocks();
  59. await clearAppData();
  60. });
  61. it("does not copy a local package on connect, then materializes it only through Sync Plugin", async function () {
  62. this.timeout(45 * 60_000);
  63. const remote = readSingleSSHWorkspaceRuntimeConfig(CASE_MARKER);
  64. target = remote;
  65. workspacePath = remote.workspacePath;
  66. await seedRemoteWorkspace(target, workspacePath);
  67. await prepareV4ConversationE2E({ skipProvider: true });
  68. await ensureToolCrossProductFullAccessMode();
  69. const fixture = await createPluginLifecycleFixture("1.0.0");
  70. await addMarketplaceSourceThroughAgent(fixture.marketplaceRoot);
  71. await installMarketplacePluginThroughAgent(
  72. PLUGIN_LIFECYCLE_NAME,
  73. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  74. );
  75. const localOverview = await getPluginOverview();
  76. expect(localOverview.installedPlugins).toEqual(
  77. expect.arrayContaining([
  78. expect.objectContaining({
  79. id: PLUGIN_LIFECYCLE_ID,
  80. scope: "user",
  81. version: "1.0.0",
  82. }),
  83. ]),
  84. );
  85. const localConfigPath = join(getE2EAppDataPaths().storageRoot, "cli", "config.json");
  86. const localInstalledPath = pluginStoragePath("installed_plugins.json");
  87. const localConfigBefore = await readFile(localConfigPath, "utf8");
  88. const localInstalledBefore = await readFile(localInstalledPath, "utf8");
  89. const workspaceConfigBefore = await readRemoteFile(
  90. target,
  91. posix.join(workspacePath, ".zcode", "config.json"),
  92. );
  93. provider = await createSSHLifecycleProvider(target, CASE_MARKER);
  94. const task = await connectSSHWorkspaceAndSendFirstTurn({
  95. caseMarker: CASE_MARKER,
  96. config: target,
  97. label: "A",
  98. provider,
  99. workspacePath,
  100. });
  101. expect(
  102. await getUpstreamRequestToolNames({
  103. lastUserMessageIncludes: [task.firstPrompt],
  104. }),
  105. ).not.toContain(PLUGIN_LIFECYCLE_MCP_TOOL_NAME);
  106. expect(await readRemotePluginStorageState(target)).toEqual({
  107. cacheContainsPlugin: false,
  108. installedContainsPlugin: false,
  109. marketplaceContainsPlugin: false,
  110. });
  111. const missingRemotePlugin = (await getPluginList(workspacePath, task.identity)).plugins.find(
  112. (plugin) => plugin.id === PLUGIN_LIFECYCLE_ID,
  113. );
  114. expect(missingRemotePlugin).toMatchObject({
  115. enabled: true,
  116. enabledSource: "workspace",
  117. id: PLUGIN_LIFECYCLE_ID,
  118. packageStatus: "missing",
  119. source: "missing",
  120. });
  121. expect(await readRemoteFile(target, posix.join(workspacePath, ".zcode", "config.json"))).toBe(
  122. workspaceConfigBefore,
  123. );
  124. await openRemotePluginSyncDialog(workspacePath);
  125. await waitForRemotePluginCandidate(`marketplace:${PLUGIN_LIFECYCLE_ID}`);
  126. await startRemotePluginSync();
  127. await waitForRemotePluginSyncComplete();
  128. await browser.waitUntil(
  129. async () => {
  130. const state = await readRemotePluginStorageState(target!);
  131. return (
  132. state.cacheContainsPlugin &&
  133. state.installedContainsPlugin &&
  134. state.marketplaceContainsPlugin
  135. );
  136. },
  137. {
  138. timeout: 180_000,
  139. timeoutMsg: `${CASE_MARKER}: 显式同步完成后 remote package/cache 没有物化`,
  140. },
  141. );
  142. expect(await readRemoteFile(target, posix.join(workspacePath, ".zcode", "config.json"))).toBe(
  143. workspaceConfigBefore,
  144. );
  145. expect(await readFile(localConfigPath, "utf8")).toBe(localConfigBefore);
  146. expect(await readFile(localInstalledPath, "utf8")).toBe(localInstalledBefore);
  147. await browser.waitUntil(
  148. async () =>
  149. (await getPluginList(workspacePath, task.identity)).plugins.some(
  150. (plugin) =>
  151. plugin.id === PLUGIN_LIFECYCLE_ID &&
  152. plugin.enabled &&
  153. plugin.enabledSource === "workspace",
  154. ),
  155. {
  156. timeout: 120_000,
  157. timeoutMsg: `${CASE_MARKER}: remote Plugin list 没有刷新为 Workspace enabled`,
  158. },
  159. );
  160. await startNewV4Draft();
  161. const requestStart = await getUpstreamRequestRecordCount();
  162. await sendV4PromptAndWaitAccepted(
  163. `${RUNTIME_PROMPT}: Call ${PLUGIN_LIFECYCLE_MCP_TOOL_NAME} exactly once, then reply with exactly ${RUNTIME_REPLY}.`,
  164. RUNTIME_PROMPT,
  165. `${CASE_MARKER}: 显式同步后的 remote 新 Session prompt 没有被接受`,
  166. );
  167. await waitForUpstreamRequest(
  168. {
  169. includes: [RUNTIME_MARKER],
  170. lastUserMessageIncludes: [RUNTIME_PROMPT],
  171. },
  172. `${CASE_MARKER}: 显式同步后的 remote 新 Session 没有暴露 Plugin MCP`,
  173. 120_000,
  174. { afterIndex: requestStart - 1 },
  175. );
  176. expect(
  177. await getUpstreamRequestToolNames({
  178. lastUserMessageIncludes: [RUNTIME_PROMPT],
  179. }),
  180. ).toContain(PLUGIN_LIFECYCLE_MCP_TOOL_NAME);
  181. await browser.waitUntil(
  182. async () => {
  183. await respondToToolCrossProductBlockers();
  184. return Boolean(
  185. await waitForToolCallBlockByToolName(PLUGIN_LIFECYCLE_MCP_TOOL_NAME, 2_000).catch(
  186. () => null,
  187. ),
  188. );
  189. },
  190. {
  191. timeout: 120_000,
  192. timeoutMsg: `${CASE_MARKER}: Plugin MCP tool-call block 没有出现`,
  193. },
  194. );
  195. await waitForV4AssistantMessageContaining(RUNTIME_REPLY, 120_000);
  196. });
  197. });
  198. async function seedRemoteWorkspace(
  199. target: SSHConnectionConfig,
  200. workspacePath: string,
  201. ): Promise<void> {
  202. if (workspacePath !== "/root/workspace") {
  203. throw new Error(`${CASE_MARKER}: refusing to reset unexpected remote path ${workspacePath}`);
  204. }
  205. const config = {
  206. plugins: {
  207. enabledPlugins: {
  208. [PLUGIN_LIFECYCLE_ID]: true,
  209. },
  210. },
  211. };
  212. const command = [
  213. "set -eu",
  214. `rm -rf -- /root/.zcode ${quoteShell(workspacePath)}`,
  215. `mkdir -p -- ${quoteShell(posix.join(workspacePath, ".zcode"))}`,
  216. writeBase64Command(
  217. posix.join(workspacePath, ".zcode", "config.json"),
  218. `${JSON.stringify(config, null, 2)}\n`,
  219. ),
  220. ].join(" && ");
  221. const result = await runSSHCommand(target, command);
  222. expect(result.code).toBe(0);
  223. expect(result.stderr).toBe("");
  224. }
  225. async function cleanupRemoteWorkspace(
  226. target: SSHConnectionConfig,
  227. workspacePath: string,
  228. ): Promise<void> {
  229. if (workspacePath !== "/root/workspace") {
  230. throw new Error(`${CASE_MARKER}: refusing to clean unexpected remote path ${workspacePath}`);
  231. }
  232. await runSSHCommand(target, `rm -rf -- ${quoteShell(workspacePath)}`);
  233. }
  234. async function readRemotePluginStorageState(target: SSHConnectionConfig): Promise<{
  235. cacheContainsPlugin: boolean;
  236. installedContainsPlugin: boolean;
  237. marketplaceContainsPlugin: boolean;
  238. }> {
  239. const command = [
  240. "installed=false",
  241. `if test -f "$HOME/.zcode/cli/plugins/installed_plugins.json" && grep -Fq -- ${quoteShell(PLUGIN_LIFECYCLE_ID)} "$HOME/.zcode/cli/plugins/installed_plugins.json"; then installed=true; fi`,
  242. "cached=false",
  243. `if test -d "$HOME/.zcode/cli/plugins/cache" && find "$HOME/.zcode/cli/plugins/cache" -path ${quoteShell(`*${PLUGIN_LIFECYCLE_NAME}*`)} -print -quit | grep -q .; then cached=true; fi`,
  244. "marketplace=false",
  245. `if test -f "$HOME/.zcode/cli/plugins/known_marketplaces.json" && grep -Fq -- ${quoteShell(PLUGIN_LIFECYCLE_MARKETPLACE_ID)} "$HOME/.zcode/cli/plugins/known_marketplaces.json"; then marketplace=true; fi`,
  246. "printf '%s\\n' \"$installed $cached $marketplace\"",
  247. ].join("; ");
  248. const result = await runSSHCommand(target, command);
  249. expect(result.code).toBe(0);
  250. const [installed, cached, marketplace] = result.stdout.trim().split(/\s+/u);
  251. return {
  252. cacheContainsPlugin: cached === "true",
  253. installedContainsPlugin: installed === "true",
  254. marketplaceContainsPlugin: marketplace === "true",
  255. };
  256. }
  257. async function readRemoteFile(target: SSHConnectionConfig, path: string): Promise<string> {
  258. const result = await runSSHCommand(target, `cat -- ${quoteShell(path)}`);
  259. expect(result.code).toBe(0);
  260. return result.stdout;
  261. }
  262. async function openRemotePluginSyncDialog(workspacePath: string): Promise<void> {
  263. await browser.waitUntil(
  264. () =>
  265. browser.execute(
  266. (headerTestId, moreTestId, pathTestId, expectedPath) => {
  267. const headers = Array.from(
  268. document.querySelectorAll<HTMLElement>(`[data-testid="${headerTestId}"]`),
  269. );
  270. const header = headers.find((candidate) => {
  271. if (candidate.getClientRects().length === 0) return false;
  272. const path = candidate.querySelector<HTMLElement>(`[data-testid="${pathTestId}"]`);
  273. return path?.title.startsWith(expectedPath);
  274. });
  275. const button = header?.querySelector<HTMLButtonElement>(`[data-testid="${moreTestId}"]`);
  276. if (!button || button.disabled) return false;
  277. button.dispatchEvent(
  278. new PointerEvent("pointerdown", {
  279. bubbles: true,
  280. cancelable: true,
  281. button: 0,
  282. pointerId: 1,
  283. pointerType: "mouse",
  284. }),
  285. );
  286. button.click();
  287. return true;
  288. },
  289. TID_WORKSPACE_HEADER,
  290. TID_WORKSPACE_MORE_BUTTON,
  291. TID_WORKSPACE_PATH,
  292. workspacePath,
  293. ),
  294. {
  295. timeout: 30_000,
  296. timeoutMsg: `${CASE_MARKER}: remote task header 没有更多菜单`,
  297. },
  298. );
  299. let visibleMenuItems: string[] = [];
  300. await browser.waitUntil(
  301. async () => {
  302. const result = await browser.execute(() => {
  303. const visibleItems = Array.from(
  304. document.querySelectorAll<HTMLElement>('[role="menuitem"]'),
  305. ).filter((candidate) => candidate.getClientRects().length > 0);
  306. const item = Array.from(visibleItems).find((candidate) => {
  307. const text = candidate.innerText.trim();
  308. return text === "同步 Plugin" || text === "Sync Plugin";
  309. });
  310. if (!item) {
  311. return {
  312. clicked: false,
  313. visibleItems: visibleItems.map((candidate) => candidate.innerText.trim()),
  314. };
  315. }
  316. item.click();
  317. return {
  318. clicked: true,
  319. visibleItems: visibleItems.map((candidate) => candidate.innerText.trim()),
  320. };
  321. });
  322. visibleMenuItems = result.visibleItems;
  323. return result.clicked;
  324. },
  325. {
  326. timeout: 30_000,
  327. timeoutMsg: `${CASE_MARKER}: remote task menu 没有“同步 Plugin”入口,visible=${JSON.stringify(visibleMenuItems)}`,
  328. },
  329. );
  330. }
  331. async function waitForRemotePluginCandidate(candidateId: string): Promise<void> {
  332. await browser.waitUntil(
  333. () =>
  334. browser.execute((id) => {
  335. const checkbox = document.getElementById(
  336. `remote-plugin-sync-${id}`,
  337. ) as HTMLInputElement | null;
  338. return Boolean(checkbox && !checkbox.disabled && checkbox.checked);
  339. }, candidateId),
  340. {
  341. timeout: 120_000,
  342. timeoutMsg: `${CASE_MARKER}: remote Plugin sync 没有默认选中 ${candidateId}`,
  343. },
  344. );
  345. }
  346. async function startRemotePluginSync(): Promise<void> {
  347. await browser.waitUntil(
  348. () =>
  349. browser.execute(() => {
  350. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  351. (candidate) => {
  352. const text = candidate.innerText.trim();
  353. return !candidate.disabled && (text === "同步已选项" || text === "Sync selected");
  354. },
  355. );
  356. if (!button) return false;
  357. button.click();
  358. return true;
  359. }),
  360. {
  361. timeout: 30_000,
  362. timeoutMsg: `${CASE_MARKER}: “同步已选项”不可点击`,
  363. },
  364. );
  365. }
  366. async function waitForRemotePluginSyncComplete(): Promise<void> {
  367. let observedBusy = false;
  368. let latestState: {
  369. dialogText: string;
  370. failed: boolean;
  371. syncButtonEnabled: boolean;
  372. synced: boolean;
  373. } = {
  374. dialogText: "",
  375. failed: false,
  376. syncButtonEnabled: false,
  377. synced: false,
  378. };
  379. await browser.waitUntil(
  380. async () => {
  381. latestState = await browser.execute(() => {
  382. const synced = Array.from(document.querySelectorAll<HTMLElement>("span")).some(
  383. (candidate) => {
  384. const text = candidate.innerText.trim();
  385. return text === "已同步" || text === "Synced";
  386. },
  387. );
  388. const failed = Array.from(document.querySelectorAll<HTMLElement>("span")).some(
  389. (candidate) => {
  390. const text = candidate.innerText.trim();
  391. return text === "失败" || text === "Failed";
  392. },
  393. );
  394. const syncButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  395. (candidate) => {
  396. const text = candidate.innerText.trim();
  397. return text === "同步已选项" || text === "Sync selected";
  398. },
  399. );
  400. const dialog = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"]')).find(
  401. (candidate) => candidate.getClientRects().length > 0,
  402. );
  403. return {
  404. dialogText: dialog?.innerText.trim() ?? "",
  405. failed,
  406. syncButtonEnabled: Boolean(syncButton && !syncButton.disabled),
  407. synced,
  408. };
  409. });
  410. if (!latestState.syncButtonEnabled) {
  411. observedBusy = true;
  412. }
  413. return (
  414. latestState.synced || latestState.failed || (observedBusy && latestState.syncButtonEnabled)
  415. );
  416. },
  417. {
  418. timeout: 240_000,
  419. timeoutMsg: `${CASE_MARKER}: remote Plugin sync 没有进入“已同步”`,
  420. },
  421. );
  422. if (!latestState.synced) {
  423. throw new Error(
  424. `${CASE_MARKER}: remote Plugin sync 回退到选择阶段,dialog=${JSON.stringify(latestState.dialogText)}`,
  425. );
  426. }
  427. }
  428. function writeBase64Command(path: string, content: string): string {
  429. const encoded = Buffer.from(content, "utf8").toString("base64");
  430. return `printf '%s' ${quoteShell(encoded)} | base64 -d > ${quoteShell(path)}`;
  431. }
  432. function quoteShell(value: string): string {
  433. return `'${value.replaceAll("'", "'\\''")}'`;
  434. }