remoteSkillSyncDialog.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. // @vitest-environment jsdom
  2. import { cleanup, render, screen, waitFor } from "@testing-library/react";
  3. import { createElement, isValidElement } from "react";
  4. import { renderToStaticMarkup } from "react-dom/server";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { SKILL_SYNC_SIZE_LIMIT_ERROR_CODE } from "@zcode/shared";
  7. import type { ISkillSyncService } from "@zcode/services";
  8. import {
  9. buildRemoteSkillSyncRows,
  10. filterRemoteSkillSyncRows,
  11. formatRemoteSkillSyncTarget,
  12. getRemoteSkillSyncBulkSelectionState,
  13. RemoteSkillSyncBulkSelectionCheckbox,
  14. RemoteSkillSyncDialog,
  15. RemoteSkillSyncExistingFilterCheckbox,
  16. RemoteSkillSyncSelectionList,
  17. RemoteSkillSyncTargetRow,
  18. formatRemoteSkillSyncError,
  19. resolveDefaultRemoteSkillSyncSelection,
  20. shouldToggleRemoteSkillSyncCardSelection,
  21. } from "../src/settings/RemoteSkillSyncDialog.js";
  22. import enUS from "../src/i18n/locales/en-US.js";
  23. import zhCN from "../src/i18n/locales/zh-CN.js";
  24. const controlHintTooltipMockState = vi.hoisted(() => ({
  25. latest: null as null | {
  26. hasOnMouseEnter: boolean;
  27. hasOnMouseLeave: boolean;
  28. open: boolean | undefined;
  29. tabIndex: unknown;
  30. },
  31. }));
  32. const remoteSkillSyncIntlMockState = vi.hoisted(() => ({
  33. locale: "en-US" as "en-US" | "zh-CN",
  34. }));
  35. vi.mock("@/ControlHintTooltip.js", () => ({
  36. ControlHintTooltip: ({
  37. children,
  38. description,
  39. open,
  40. title,
  41. }: {
  42. children: unknown;
  43. description?: string;
  44. open?: boolean;
  45. title: string;
  46. }) => {
  47. const triggerProps = isValidElement<{
  48. onMouseEnter?: unknown;
  49. onMouseLeave?: unknown;
  50. tabIndex?: unknown;
  51. }>(children)
  52. ? children.props
  53. : {};
  54. controlHintTooltipMockState.latest = {
  55. hasOnMouseEnter: typeof triggerProps.onMouseEnter === "function",
  56. hasOnMouseLeave: typeof triggerProps.onMouseLeave === "function",
  57. open,
  58. tabIndex: triggerProps.tabIndex,
  59. };
  60. return createElement(
  61. "span",
  62. {
  63. "data-tooltip-open": String(open),
  64. "data-tooltip-description": description,
  65. "data-tooltip-title": title,
  66. },
  67. children,
  68. );
  69. },
  70. }));
  71. vi.mock("@/components/ui/button.js", () => ({
  72. Button: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  73. createElement("button", props, children),
  74. }));
  75. vi.mock("@/components/ui/dialog.js", () => ({
  76. Dialog: ({ open, children }: { open: boolean; children: unknown }) =>
  77. open ? createElement("div", { "data-dialog-open": true }, children) : null,
  78. DialogContent: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  79. createElement("div", props, children),
  80. DialogHeader: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  81. createElement("div", props, children),
  82. DialogTitle: ({ children, ...props }: { children: unknown; [key: string]: unknown }) =>
  83. createElement("h2", props, children),
  84. }));
  85. vi.mock("@/i18n/IntlProvider.js", () => ({
  86. useZCodeIntl: () => {
  87. const locale = remoteSkillSyncIntlMockState.locale;
  88. return {
  89. intl: {
  90. formatMessage: (
  91. { id }: { id: string },
  92. values?: Record<string, string | number>,
  93. ) => {
  94. const messages: Record<string, string> = {
  95. "settings.skills.remoteSync.title": "Sync Skills to remote target",
  96. "settings.skills.remoteSync.warningTitle": "Skill data and environment availability",
  97. "settings.skills.remoteSync.warningDescription":
  98. "Sync migrates local user-level Skills to the remote host, but not all dependent data and system environment capabilities can be guaranteed. If a Skill is unavailable because of the remote environment, permissions, or missing dependencies, install it or add the dependencies on the remote server.",
  99. "settings.skills.remoteSync.target": `Target: ${values?.target ?? ""}`,
  100. "settings.skills.remoteSync.loading": "Loading local Skills...",
  101. "settings.skills.remoteSync.empty": "No local user skills found.",
  102. "settings.skills.remoteSync.selectAll": "Select all",
  103. "settings.skills.remoteSync.clearAll": "Clear all",
  104. "settings.skills.remoteSync.start": "Sync selected",
  105. "settings.skills.remoteSync.syncing": "Syncing skills...",
  106. "settings.remoteSync.preflighting": "Checking remote write access...",
  107. "settings.skills.remoteSync.existing": "Already exists on remote",
  108. "settings.skills.remoteSync.showExisting": "Show existing remote skills",
  109. "settings.skills.remoteSync.expandDescription": "Show more",
  110. "settings.skills.remoteSync.collapseDescription": "Show less",
  111. "settings.skills.remoteSync.synced": "Synced",
  112. "settings.skills.remoteSync.skipped": "Skipped",
  113. "settings.skills.remoteSync.failed": "Failed",
  114. "settings.skills.remoteSync.complete": "Skill sync complete.",
  115. "settings.skills.remoteSync.selectionCount": `${values?.selected ?? 0}/${values?.total ?? 0} selected`,
  116. "settings.skills.remoteSync.noSelection": "Select at least one missing skill.",
  117. "settings.skills.remoteSync.sizeLimit.selectedContent":
  118. locale === "zh-CN"
  119. ? "同步失败:所选 Skills 的内容总大小约为 {actualSize},超过单次同步上限 {maxSize}。请取消选择部分 Skills 后重试;远端未写入任何内容。"
  120. : "Sync failed: the selected Skills contain about {actualSize} of content, exceeding the {maxSize} per-sync limit. Deselect some Skills and try again. Nothing was written to the remote host.",
  121. };
  122. let message = messages[id] ?? id;
  123. for (const [key, value] of Object.entries(values ?? {})) {
  124. message = message.replaceAll(`{${key}}`, String(value));
  125. }
  126. return message;
  127. },
  128. },
  129. };
  130. },
  131. }));
  132. afterEach(() => {
  133. cleanup();
  134. remoteSkillSyncIntlMockState.locale = "en-US";
  135. });
  136. function createSkillSyncServiceStub(): ISkillSyncService {
  137. return {
  138. listLocalUserSkillCandidates: vi.fn(async () => ({
  139. maxArchiveBytes: 1024 * 1024,
  140. candidates: [],
  141. })),
  142. listRemoteUserSkillStatuses: vi.fn(async () => ({ statuses: [] })),
  143. exportSkillsArchive: vi.fn(async () => ({
  144. archive: new Uint8Array(),
  145. archiveBytes: 0,
  146. skills: [],
  147. })),
  148. checkRemoteUserSkillWriteAccess: vi.fn(async () => ({
  149. ok: true,
  150. path: "/home/dev/.zcode/skills",
  151. })),
  152. importSkillsArchive: vi.fn(async () => ({ results: [] })),
  153. };
  154. }
  155. describe("RemoteSkillSyncDialog helpers", () => {
  156. it("provides size-limit copy in both supported locales", () => {
  157. const messageIds = [
  158. "settings.skills.remoteSync.sizeLimit.selectedContent",
  159. "settings.skills.remoteSync.sizeLimit.archive",
  160. "settings.skills.remoteSync.sizeLimit.extractedContent",
  161. ];
  162. for (const messageId of messageIds) {
  163. expect(enUS[messageId]).toBeTruthy();
  164. expect(zhCN[messageId]).toBeTruthy();
  165. }
  166. });
  167. it("localizes structured selected-content size limit errors", () => {
  168. const error = Object.assign(new Error("skill sync size limit exceeded"), {
  169. code: SKILL_SYNC_SIZE_LIMIT_ERROR_CODE,
  170. data: {
  171. actualBytes: 56_220_152,
  172. maxBytes: 20 * 1024 * 1024,
  173. phase: "selected-content",
  174. },
  175. });
  176. expect(
  177. formatRemoteSkillSyncError(error, {
  178. formatMessage: ({ id }, values) => {
  179. const messages: Record<string, string> = {
  180. "settings.skills.remoteSync.sizeLimit.selectedContent":
  181. "Sync failed: the selected Skills contain about {actualSize} of content, exceeding the {maxSize} per-sync limit. Deselect some Skills and try again. Nothing was written to the remote host.",
  182. };
  183. let message = messages[id] ?? id;
  184. for (const [key, value] of Object.entries(values ?? {})) {
  185. message = message.replaceAll(`{${key}}`, String(value));
  186. }
  187. return message;
  188. },
  189. }),
  190. ).toBe(
  191. "Sync failed: the selected Skills contain about 53.6 MiB of content, exceeding the 20 MiB per-sync limit. Deselect some Skills and try again. Nothing was written to the remote host.",
  192. );
  193. });
  194. it("marks remote existing skills and selects only missing ones by default", () => {
  195. const rows = buildRemoteSkillSyncRows(
  196. [
  197. {
  198. id: "missing-id",
  199. name: "review",
  200. directoryName: "review",
  201. description: "Review code",
  202. path: "/Users/me/.zcode/skills/review/SKILL.md",
  203. sizeBytes: 128,
  204. },
  205. {
  206. id: "existing-id",
  207. name: "docs",
  208. directoryName: "docs",
  209. description: "Write docs",
  210. path: "/Users/me/.zcode/skills/docs/SKILL.md",
  211. sizeBytes: 64,
  212. },
  213. ],
  214. [{ directoryName: "docs", exists: true }],
  215. );
  216. expect(rows.map((row) => ({ id: row.candidate.id, exists: row.exists }))).toEqual([
  217. { id: "missing-id", exists: false },
  218. { id: "existing-id", exists: true },
  219. ]);
  220. expect(Array.from(resolveDefaultRemoteSkillSyncSelection(rows))).toEqual(["missing-id"]);
  221. });
  222. it("formats SSH target with workspace path when available", () => {
  223. expect(
  224. formatRemoteSkillSyncTarget(
  225. { kind: "ssh", host: "dev.example.com", username: "alice", port: 22 },
  226. "/home/alice/project",
  227. ),
  228. ).toBe("alice@dev.example.com:22 · /home/alice/project");
  229. });
  230. it("formats WSL target with distro, user, and workspace path", () => {
  231. expect(
  232. formatRemoteSkillSyncTarget(
  233. { kind: "wsl", distro: "Ubuntu-24.04", user: "alice" },
  234. "/home/alice/project",
  235. ),
  236. ).toBe("WSL · Ubuntu-24.04 · alice · /home/alice/project");
  237. });
  238. it("toggles selection only from non-action card clicks on missing skills", () => {
  239. const plainCardTarget = { closest: vi.fn(() => null) } as unknown as EventTarget;
  240. const actionTarget = { closest: vi.fn(() => ({})) } as unknown as EventTarget;
  241. expect(
  242. shouldToggleRemoteSkillSyncCardSelection({
  243. exists: false,
  244. target: plainCardTarget,
  245. }),
  246. ).toBe(true);
  247. expect(
  248. shouldToggleRemoteSkillSyncCardSelection({
  249. exists: false,
  250. target: actionTarget,
  251. }),
  252. ).toBe(false);
  253. expect(
  254. shouldToggleRemoteSkillSyncCardSelection({
  255. exists: true,
  256. target: plainCardTarget,
  257. }),
  258. ).toBe(false);
  259. });
  260. it("derives the bulk selection checkbox state", () => {
  261. expect(
  262. getRemoteSkillSyncBulkSelectionState({
  263. selectedCount: 0,
  264. totalSelectable: 0,
  265. }),
  266. ).toEqual({ checked: false, disabled: true, indeterminate: false });
  267. expect(
  268. getRemoteSkillSyncBulkSelectionState({
  269. selectedCount: 1,
  270. totalSelectable: 3,
  271. }),
  272. ).toEqual({ checked: false, disabled: false, indeterminate: true });
  273. expect(
  274. getRemoteSkillSyncBulkSelectionState({
  275. selectedCount: 3,
  276. totalSelectable: 3,
  277. }),
  278. ).toEqual({ checked: true, disabled: false, indeterminate: false });
  279. });
  280. it("filters remote existing rows when the existing filter is disabled", () => {
  281. const rows = buildRemoteSkillSyncRows(
  282. [
  283. {
  284. id: "missing-id",
  285. name: "review",
  286. directoryName: "review",
  287. description: "Review code",
  288. path: "/Users/me/.zcode/skills/review/SKILL.md",
  289. sizeBytes: 128,
  290. },
  291. {
  292. id: "existing-id",
  293. name: "docs",
  294. directoryName: "docs",
  295. description: "Write docs",
  296. path: "/Users/me/.zcode/skills/docs/SKILL.md",
  297. sizeBytes: 64,
  298. },
  299. ],
  300. [{ directoryName: "docs", exists: true }],
  301. );
  302. expect(filterRemoteSkillSyncRows(rows, true).map((row) => row.candidate.id)).toEqual([
  303. "missing-id",
  304. "existing-id",
  305. ]);
  306. expect(filterRemoteSkillSyncRows(rows, false).map((row) => row.candidate.id)).toEqual([
  307. "missing-id",
  308. ]);
  309. });
  310. });
  311. describe("RemoteSkillSyncDialog", () => {
  312. it("uses the current locale when a pending load later fails", async () => {
  313. let rejectFirstLoad: (error: unknown) => void = () => undefined;
  314. const firstLoad = new Promise<never>((_, reject) => {
  315. rejectFirstLoad = reject;
  316. });
  317. const sizeLimitError = Object.assign(new Error("skill sync size limit exceeded"), {
  318. code: SKILL_SYNC_SIZE_LIMIT_ERROR_CODE,
  319. data: {
  320. actualBytes: 56_220_152,
  321. maxBytes: 20 * 1024 * 1024,
  322. phase: "selected-content",
  323. },
  324. });
  325. const service = createSkillSyncServiceStub();
  326. service.listLocalUserSkillCandidates = vi.fn().mockReturnValueOnce(firstLoad);
  327. const props = {
  328. open: true,
  329. onOpenChange: () => undefined,
  330. localSkillSyncService: service,
  331. remoteSkillSyncService: service,
  332. remoteTarget: {
  333. kind: "ssh" as const,
  334. host: "dev.example.com",
  335. username: "alice",
  336. port: 22,
  337. },
  338. workspacePath: "/home/alice/project",
  339. onSynced: async () => undefined,
  340. };
  341. const view = render(createElement(RemoteSkillSyncDialog, props));
  342. remoteSkillSyncIntlMockState.locale = "zh-CN";
  343. view.rerender(createElement(RemoteSkillSyncDialog, props));
  344. rejectFirstLoad(sizeLimitError);
  345. await waitFor(() => {
  346. expect(
  347. screen.getByText(
  348. "同步失败:所选 Skills 的内容总大小约为 53.6 MiB,超过单次同步上限 20 MiB。请取消选择部分 Skills 后重试;远端未写入任何内容。",
  349. ),
  350. ).toBeTruthy();
  351. });
  352. });
  353. it("renders SSH target in the loading state", () => {
  354. const service = createSkillSyncServiceStub();
  355. const html = renderToStaticMarkup(
  356. createElement(RemoteSkillSyncDialog, {
  357. open: true,
  358. onOpenChange: () => undefined,
  359. localSkillSyncService: service,
  360. remoteSkillSyncService: service,
  361. remoteTarget: {
  362. kind: "ssh",
  363. host: "dev.example.com",
  364. username: "alice",
  365. port: 22,
  366. },
  367. workspacePath: "/home/alice/project",
  368. workspaceIdentity: "ssh://alice@dev.example.com/home/alice/project",
  369. onSynced: async () => undefined,
  370. }),
  371. );
  372. expect(html).toContain("Sync Skills to remote target");
  373. expect(html).toContain("alice@dev.example.com:22");
  374. expect(html).toContain("/home/alice/project");
  375. });
  376. it("renders a warning tooltip next to the sync title", () => {
  377. const service = createSkillSyncServiceStub();
  378. controlHintTooltipMockState.latest = null;
  379. const html = renderToStaticMarkup(
  380. createElement(RemoteSkillSyncDialog, {
  381. open: true,
  382. onOpenChange: () => undefined,
  383. localSkillSyncService: service,
  384. remoteSkillSyncService: service,
  385. remoteTarget: {
  386. kind: "ssh",
  387. host: "dev.example.com",
  388. username: "alice",
  389. port: 22,
  390. },
  391. workspacePath: "/home/alice/project",
  392. onSynced: async () => undefined,
  393. }),
  394. );
  395. expect(html).toContain("Sync Skills to remote target");
  396. expect(html).toContain('data-tooltip-title="Skill data and environment availability"');
  397. expect(html).toContain("not all dependent data and system environment capabilities");
  398. expect(html).toContain("install it or add the dependencies on the remote server");
  399. expect(html).toContain('aria-label="Skill data and environment availability"');
  400. });
  401. it("keeps the warning tooltip closed until mouse hover", () => {
  402. const service = createSkillSyncServiceStub();
  403. controlHintTooltipMockState.latest = null;
  404. const html = renderToStaticMarkup(
  405. createElement(RemoteSkillSyncDialog, {
  406. open: true,
  407. onOpenChange: () => undefined,
  408. localSkillSyncService: service,
  409. remoteSkillSyncService: service,
  410. remoteTarget: {
  411. kind: "ssh",
  412. host: "dev.example.com",
  413. username: "alice",
  414. port: 22,
  415. },
  416. workspacePath: "/home/alice/project",
  417. onSynced: async () => undefined,
  418. }),
  419. );
  420. expect(html).toContain('data-tooltip-open="false"');
  421. expect(html).not.toContain('tabIndex="0"');
  422. expect(html).not.toContain('tabindex="0"');
  423. expect(controlHintTooltipMockState.latest).toEqual({
  424. hasOnMouseEnter: true,
  425. hasOnMouseLeave: true,
  426. open: false,
  427. tabIndex: undefined,
  428. });
  429. });
  430. it("keeps the dialog size stable while the skill list scrolls", () => {
  431. const service = createSkillSyncServiceStub();
  432. const html = renderToStaticMarkup(
  433. createElement(RemoteSkillSyncDialog, {
  434. open: true,
  435. onOpenChange: () => undefined,
  436. localSkillSyncService: service,
  437. remoteSkillSyncService: service,
  438. remoteTarget: {
  439. kind: "ssh",
  440. host: "dev.example.com",
  441. username: "alice",
  442. port: 22,
  443. },
  444. workspacePath: "/home/alice/project",
  445. onSynced: async () => undefined,
  446. }),
  447. );
  448. const dialogContentClass =
  449. html.match(/<div class="([^"]*max-h-\[min\(720px,calc\(100dvh-2rem\)\)\][^"]*)"/u)?.[1] ??
  450. "";
  451. expect(dialogContentClass.split(/\s+/u)).toEqual(
  452. expect.arrayContaining([
  453. "h-[min(720px,calc(100dvh-2rem))]",
  454. "flex",
  455. "flex-col",
  456. "overflow-hidden",
  457. ]),
  458. );
  459. expect(html).toContain("min-h-0 flex-1 overflow-y-auto");
  460. });
  461. it("collapses skill descriptions by default with an expand control", () => {
  462. const rows = buildRemoteSkillSyncRows(
  463. [
  464. {
  465. id: "lark-apps-id",
  466. name: "lark-apps",
  467. directoryName: "lark-apps",
  468. description:
  469. "A long skill description that should not take multiple lines in the default sync picker view.",
  470. path: "/Users/me/.agents/skills/lark-apps/SKILL.md",
  471. sizeBytes: 128,
  472. },
  473. ],
  474. [],
  475. );
  476. const html = renderToStaticMarkup(
  477. createElement(RemoteSkillSyncSelectionList, {
  478. rows,
  479. selectedIds: new Set(["lark-apps-id"]),
  480. onToggle: () => undefined,
  481. }),
  482. );
  483. expect(html).toContain("line-clamp-1");
  484. const descriptionClass =
  485. html.match(/class="([^"]*line-clamp-1[^"]*)"/u)?.[1] ?? "";
  486. expect(descriptionClass.split(/\s+/u)).not.toContain("block");
  487. expect(html).toContain('aria-expanded="false"');
  488. expect(html).toContain('aria-label="Show more"');
  489. expect(html).toContain("data-remote-skill-sync-card-action");
  490. expect(html).not.toContain(">Show more</button>");
  491. });
  492. it("renders bulk selection as a single checkbox control", () => {
  493. const html = renderToStaticMarkup(
  494. createElement(RemoteSkillSyncBulkSelectionCheckbox, {
  495. selectedCount: 1,
  496. totalSelectable: 3,
  497. onSelectAll: () => undefined,
  498. onClearAll: () => undefined,
  499. }),
  500. );
  501. expect(html).toContain('type="checkbox"');
  502. expect(html).toContain('aria-checked="mixed"');
  503. expect(html).toContain("Select all");
  504. expect(html).not.toContain("Clear all");
  505. });
  506. it("renders the existing remote skills filter as a checkbox control", () => {
  507. const html = renderToStaticMarkup(
  508. createElement(RemoteSkillSyncExistingFilterCheckbox, {
  509. checked: false,
  510. onCheckedChange: () => undefined,
  511. }),
  512. );
  513. expect(html).toContain('type="checkbox"');
  514. expect(html).toContain("Show existing remote skills");
  515. });
  516. it("places the existing filter on the same row as the target", () => {
  517. const html = renderToStaticMarkup(
  518. createElement(RemoteSkillSyncTargetRow, {
  519. targetLabel: "alice@dev.example.com:22 · /home/alice/project",
  520. showExistingRemoteSkills: true,
  521. showExistingFilter: true,
  522. onShowExistingRemoteSkillsChange: () => undefined,
  523. }),
  524. );
  525. expect(html).toContain("sm:flex-row");
  526. expect(html).toContain("sm:justify-between");
  527. expect(html.indexOf("Target: alice@dev.example.com:22")).toBeLessThan(
  528. html.indexOf("Show existing remote skills"),
  529. );
  530. });
  531. });