remoteSkillSyncDialog.test.ts 18 KB

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