sourceServerManagementPanel.test.ts 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import { Emitter } from "@zcode/rpc";
  6. import type {
  7. SourceServerConnectionStateSnapshot,
  8. SourceServerManagementSnapshot,
  9. } from "@zcode/shared";
  10. import {
  11. getProjectCount,
  12. SourceServerManagementPanel,
  13. } from "@/settings/SourceServerManagementPanel.js";
  14. vi.mock("@/i18n/IntlProvider.js", () => ({
  15. useZCodeIntl: () => ({
  16. intl: {
  17. formatMessage: ({ id }: { id: string }, values?: Record<string, number | string>) =>
  18. values?.projects
  19. ? `${id}:${values.projects}`
  20. : values?.attempt !== undefined
  21. ? `${id}:${values.attempt}/${values.limit}`
  22. : id,
  23. },
  24. }),
  25. }));
  26. const showToast = vi.hoisted(() => vi.fn());
  27. vi.mock("@/components/ui/toast.js", () => ({ toast: showToast }));
  28. const confirmDialog = vi.hoisted(() => vi.fn(async () => true));
  29. vi.mock("@/hooks/useConfirmDialog.js", () => ({ useConfirmDialog: () => confirmDialog }));
  30. beforeEach(() => confirmDialog.mockReset().mockResolvedValue(true));
  31. const platform = vi.hoisted(() => ({
  32. listSSHConfigAliases: vi.fn(async () => []),
  33. selectFile: vi.fn(),
  34. }));
  35. vi.mock("@/hooks/usePlatform.js", () => ({
  36. usePlatform: () => platform,
  37. useOptionalPlatform: () => platform,
  38. }));
  39. function identityPendingSnapshot(
  40. installState: "installed" | "uninstalled",
  41. pendingProfileId: string,
  42. ): SourceServerManagementSnapshot {
  43. const profileIds =
  44. pendingProfileId === "preferred" ? ["preferred"] : ["preferred", pendingProfileId];
  45. return {
  46. generation: 1,
  47. profiles: profileIds.map((profileId) => ({
  48. profileId,
  49. sourceServerId: "old-source",
  50. transport: "ssh",
  51. target: { kind: "ssh", host: `${profileId}.example.com`, username: "dev" },
  52. createdAt: 1,
  53. lifecycleState: "active",
  54. })),
  55. servers: [
  56. {
  57. sourceServerId: "old-source",
  58. displayName: "Reinstalled server",
  59. preferredProfileId: "preferred",
  60. installState,
  61. declaredWorkspaces: [],
  62. },
  63. ],
  64. workspaceHistory: [],
  65. states: profileIds.map((profileId) => ({
  66. profileId,
  67. sourceServerId: "old-source",
  68. state: profileId === pendingProfileId ? "identity-change-pending" : "offline",
  69. ...(profileId === pendingProfileId ? { pendingSourceServerId: "new-source" } : {}),
  70. updatedAt: 1,
  71. })),
  72. failedPathCount: 0,
  73. abandonedPathCount: 0,
  74. migrationCounts: [],
  75. };
  76. }
  77. afterEach(() => {
  78. cleanup();
  79. vi.clearAllMocks();
  80. });
  81. describe("SourceServerManagementPanel", () => {
  82. it("当前连接在第二行,默认连接留在其他连接;最近项目按打开时间倒序且可展开全部", async () => {
  83. const snapshot = identityPendingSnapshot("installed", "other");
  84. snapshot.states[0]!.state = "offline";
  85. snapshot.states[1]!.state = "online";
  86. snapshot.workspaceHistory = (
  87. [
  88. ["alpha", 1],
  89. ["beta", 4],
  90. ["gamma", 3],
  91. ["delta", 2],
  92. ] as const
  93. ).map(([name, lastOpenedAt]) => ({
  94. sourceServerId: "old-source",
  95. profileId: "other",
  96. workspacePath: `/work/${name}`,
  97. workspaceIdentity: `remote:${name}`,
  98. lastOpenedAt,
  99. }));
  100. const open = vi.fn(async () => {});
  101. const setPreferredProfile = vi.fn(async () => snapshot);
  102. const { container } = render(
  103. createElement(SourceServerManagementPanel, {
  104. management: {
  105. getSnapshot: async () => snapshot,
  106. onDidChangeState: new Emitter().event,
  107. setPreferredProfile,
  108. } as never,
  109. onOpenProject: open,
  110. workspaceTabs: [
  111. {
  112. id: "beta-tab",
  113. kind: "workspace",
  114. label: "beta",
  115. workspacePath: "/work/beta",
  116. workspaceIdentity: "remote:server:old-source:/work/beta",
  117. },
  118. ],
  119. }),
  120. );
  121. await screen.findByText("Reinstalled server");
  122. const line = container.querySelector("[data-device-connection]")!;
  123. expect(line.textContent).toContain("other.example.com");
  124. expect(line.textContent).toContain("settings.source.currentProfile");
  125. expect(line.textContent).not.toContain("settings.source.defaultProfile");
  126. fireEvent.click(screen.getByRole("button", { name: "settings.source.setDefault" }));
  127. await waitFor(() => expect(setPreferredProfile).toHaveBeenCalledWith("old-source", "other"));
  128. const projectNames = () =>
  129. [...container.querySelectorAll("[data-device-project]")].map((row) =>
  130. row.getAttribute("aria-label"),
  131. );
  132. // 最近打开的排前面,默认只露出三行;不能再出现无法点击的 +N。
  133. expect(projectNames()).toEqual(["beta", "gamma", "delta"]);
  134. expect(screen.queryByText("+1")).toBeNull();
  135. const betaRow = container.querySelector('[data-device-project][aria-label="beta"]')!;
  136. expect(betaRow.textContent).toContain("/work/beta");
  137. expect(betaRow.textContent).toContain("settings.source.projectOpened");
  138. expect(
  139. container.querySelector('[data-device-project][aria-label="gamma"]')!.textContent,
  140. ).not.toContain("settings.source.projectOpened");
  141. fireEvent.click(screen.getByRole("button", { name: "settings.source.showAllProjects" }));
  142. expect(projectNames()).toEqual(["beta", "gamma", "delta", "alpha"]);
  143. fireEvent.click(screen.getByRole("button", { name: "alpha" }));
  144. await waitFor(() => expect(open).toHaveBeenCalledWith("old-source", "/work/alpha", "other"));
  145. fireEvent.click(screen.getByRole("button", { name: "settings.source.showLessProjects" }));
  146. expect(projectNames()).toHaveLength(3);
  147. fireEvent.click(screen.getByRole("button", { name: "settings.source.otherSavedConnections" }));
  148. expect(screen.getByText("dev@preferred.example.com:22")).toBeTruthy();
  149. expect(screen.getByText("settings.source.defaultProfile")).toBeTruthy();
  150. });
  151. it("单条连接不显示当前/默认标签,连接行展示远端版本", async () => {
  152. const snapshot = identityPendingSnapshot("installed", "preferred");
  153. snapshot.states[0]!.state = "online";
  154. snapshot.servers[0]!.lastSeenVersion = "v1.4.2";
  155. const { container } = render(
  156. createElement(SourceServerManagementPanel, {
  157. management: {
  158. getSnapshot: async () => snapshot,
  159. onDidChangeState: new Emitter().event,
  160. } as never,
  161. }),
  162. );
  163. await screen.findByText("Reinstalled server");
  164. const line = container.querySelector("[data-device-connection]")!;
  165. expect(line.textContent).toContain("dev@preferred.example.com:22");
  166. expect(line.textContent).toContain("1.4.2");
  167. expect(line.textContent).not.toContain("settings.source.currentProfile");
  168. expect(line.textContent).not.toContain("settings.source.defaultProfile");
  169. expect(container.querySelector("[data-device-projects]")?.textContent).toContain(
  170. "settings.source.projectCount",
  171. );
  172. });
  173. it("可选更新稍后在面板重挂和重连后保持隐藏,新版本重新显示", async () => {
  174. const snapshot = identityPendingSnapshot("installed", "preferred");
  175. snapshot.states[0] = {
  176. ...snapshot.states[0]!,
  177. state: "online",
  178. updateAvailability: "available",
  179. availableVersion: "defer-test-1",
  180. upgradeTarget: "server",
  181. };
  182. const management = {
  183. getSnapshot: async () => snapshot,
  184. onDidChangeState: new Emitter().event,
  185. } as never;
  186. const first = render(createElement(SourceServerManagementPanel, { management }));
  187. fireEvent.click(await screen.findByRole("button", { name: "updateDialog.later" }));
  188. expect(screen.queryByText("settings.source.updateAvailableVersion")).toBeNull();
  189. first.unmount();
  190. const second = render(createElement(SourceServerManagementPanel, { management }));
  191. await screen.findByText("Reinstalled server");
  192. expect(screen.queryByText("settings.source.updateAvailableVersion")).toBeNull();
  193. second.unmount();
  194. snapshot.states[0]!.availableVersion = "defer-test-2";
  195. render(createElement(SourceServerManagementPanel, { management }));
  196. expect(await screen.findByRole("button", { name: "updateDialog.later" })).toBeTruthy();
  197. });
  198. it("强制更新确认列出 Host 返回的运行任务,取消不发送 force=true", async () => {
  199. const snapshot = identityPendingSnapshot("installed", "preferred");
  200. snapshot.states[0] = {
  201. ...snapshot.states[0]!,
  202. state: "needs-upgrade",
  203. updateAvailability: "required",
  204. upgradeTarget: "server",
  205. runningTasks: [{ sessionId: "running-session", workspacePath: "/work/alpha" }],
  206. };
  207. const updateSource = vi
  208. .fn()
  209. .mockRejectedValue(
  210. Object.assign(new Error("busy"), { code: "source-server-update-running-tasks" }),
  211. );
  212. confirmDialog.mockResolvedValue(false);
  213. render(
  214. createElement(SourceServerManagementPanel, {
  215. management: {
  216. getSnapshot: async () => snapshot,
  217. onDidChangeState: new Emitter().event,
  218. updateSource,
  219. } as never,
  220. }),
  221. );
  222. fireEvent.click(await screen.findByRole("button", { name: "remote.action.update-server" }));
  223. await waitFor(() =>
  224. expect(confirmDialog).toHaveBeenCalledWith(
  225. expect.objectContaining({
  226. description: expect.stringContaining("running-session — /work/alpha"),
  227. }),
  228. ),
  229. );
  230. expect(updateSource.mock.calls).toEqual([[{ profileId: "preferred", force: false }]]);
  231. });
  232. it("离开设置后更新失败,toast 详情通过稳定导航重新打开设备", async () => {
  233. const snapshot = identityPendingSnapshot("installed", "preferred");
  234. snapshot.states[0] = {
  235. ...snapshot.states[0]!,
  236. state: "needs-upgrade",
  237. updateAvailability: "required",
  238. upgradeTarget: "server",
  239. };
  240. const pending = Promise.withResolvers<SourceServerManagementSnapshot>();
  241. const updateSource = vi.fn(() => pending.promise);
  242. const onShowUpdateDetails = vi.fn();
  243. const view = render(
  244. createElement(SourceServerManagementPanel, {
  245. management: {
  246. getSnapshot: async () => snapshot,
  247. onDidChangeState: new Emitter().event,
  248. updateSource,
  249. } as never,
  250. onShowUpdateDetails,
  251. }),
  252. );
  253. fireEvent.click(await screen.findByRole("button", { name: "remote.action.update-server" }));
  254. await waitFor(() => expect(updateSource).toHaveBeenCalledOnce());
  255. view.unmount();
  256. await act(async () => pending.reject(new Error("update failed")));
  257. await waitFor(() =>
  258. expect(showToast).toHaveBeenCalledWith(
  259. "sourceServer.updateFailedToast",
  260. expect.objectContaining({ actionLabel: "remote.action.details" }),
  261. ),
  262. );
  263. showToast.mock.calls.at(-1)![1].onAction();
  264. expect(onShowUpdateDetails).toHaveBeenCalledWith("old-source");
  265. });
  266. it("未完成连接展开后可读取最近日志,清理时跳过刚识别的设备", async () => {
  267. const snapshot = identityPendingSnapshot("installed", "preferred");
  268. snapshot.servers = [];
  269. snapshot.profiles[0]!.profileId = "17ef20b3-622d-4a53-98c1-0cdff29f3e6d";
  270. delete snapshot.profiles[0]!.sourceServerId;
  271. snapshot.states[0] = {
  272. profileId: "17ef20b3-622d-4a53-98c1-0cdff29f3e6d",
  273. state: "failed",
  274. updatedAt: 1,
  275. errorCode: "remote-host-unreachable",
  276. };
  277. let current = snapshot;
  278. const removeProfile = vi.fn();
  279. render(
  280. createElement(SourceServerManagementPanel, {
  281. management: {
  282. getSnapshot: async () => current,
  283. onDidChangeState: new Emitter().event,
  284. removeProfile,
  285. getRecentOperationLogs: async () => [
  286. {
  287. timestamp: 1,
  288. level: "error",
  289. phase: "connect",
  290. operation: "connect",
  291. message: "Connection refused",
  292. profileId: "17ef20b3-622d-4a53-98c1-0cdff29f3e6d",
  293. },
  294. ],
  295. } as never,
  296. }),
  297. );
  298. fireEvent.click(await screen.findByText("settings.source.unfinishedConnections"));
  299. fireEvent.click(await screen.findByRole("button", { name: "settings.source.recentLog" }));
  300. expect(await screen.findByText("Connection refused")).toBeTruthy();
  301. current = identityPendingSnapshot("installed", "preferred");
  302. fireEvent.click(screen.getByRole("button", { name: "settings.source.clearUnfinished" }));
  303. await waitFor(() => expect(confirmDialog).toHaveBeenCalled());
  304. expect(removeProfile).not.toHaveBeenCalled();
  305. });
  306. it("更新中覆盖连接记录保留的旧错误", async () => {
  307. const snapshot = identityPendingSnapshot("installed", "preferred");
  308. snapshot.states[0]!.state = "updating";
  309. snapshot.profiles[0]!.lastConnectError = "OLD_INSTALL_FAILURE";
  310. const emitter = new Emitter();
  311. render(
  312. createElement(SourceServerManagementPanel, {
  313. management: { getSnapshot: async () => snapshot, onDidChangeState: emitter.event } as never,
  314. }),
  315. );
  316. expect(await screen.findByText("remote.status.updating")).toBeTruthy();
  317. expect(screen.queryByText("settings.source.lastConnectError")).toBeNull();
  318. });
  319. it("设备卡修复产生错误的连接,而不是离线的首选连接", async () => {
  320. const snapshot = identityPendingSnapshot("installed", "other");
  321. snapshot.states[1] = {
  322. profileId: "other",
  323. sourceServerId: "old-source",
  324. state: "failed",
  325. error: "host not found",
  326. errorCode: "remote-host-not-found",
  327. updatedAt: 2,
  328. };
  329. const emitter = new Emitter();
  330. const management = {
  331. getSnapshot: async () => snapshot,
  332. onDidChangeState: emitter.event,
  333. } as never;
  334. render(createElement(SourceServerManagementPanel, { management, onConnectProfile: vi.fn() }));
  335. fireEvent.click(await screen.findByRole("button", { name: "remote.action.edit-host" }));
  336. expect((screen.getByLabelText("ssh.host") as HTMLInputElement).value).toBe("other.example.com");
  337. });
  338. it.each(["remote-permission-denied", "remote-host-not-found"] as const)(
  339. "%s 的主操作查看详情或编辑主机,不会盲目重连",
  340. async (errorCode) => {
  341. const snapshot = identityPendingSnapshot("installed", "preferred");
  342. snapshot.states[0] = {
  343. profileId: "preferred",
  344. sourceServerId: "old-source",
  345. state: "failed",
  346. error: "diagnostic details",
  347. errorCode,
  348. updatedAt: 2,
  349. };
  350. const emitter = new Emitter();
  351. const management = {
  352. getSnapshot: async () => snapshot,
  353. onDidChangeState: emitter.event,
  354. } as never;
  355. const onConnectProfile = vi.fn();
  356. render(createElement(SourceServerManagementPanel, { management, onConnectProfile }));
  357. fireEvent.click(
  358. await screen.findByRole("button", {
  359. name:
  360. errorCode === "remote-permission-denied"
  361. ? "remote.action.details"
  362. : "remote.action.edit-host",
  363. }),
  364. );
  365. expect(await screen.findByRole("dialog")).toBeTruthy();
  366. expect(onConnectProfile).not.toHaveBeenCalled();
  367. if (errorCode === "remote-host-not-found")
  368. expect(screen.getByLabelText("ssh.host").getAttribute("aria-invalid")).toBe("true");
  369. else
  370. expect(screen.getByRole("dialog").textContent).toContain(
  371. "remote.error.permissionDenied.reason",
  372. );
  373. },
  374. );
  375. it("本机过旧时显示更新桌面端,仍可打开连接配置", async () => {
  376. const snapshot = identityPendingSnapshot("installed", "preferred");
  377. snapshot.states[0] = {
  378. profileId: "preferred",
  379. sourceServerId: "old-source",
  380. state: "needs-upgrade",
  381. updateAvailability: "required",
  382. upgradeTarget: "controller",
  383. updatedAt: 2,
  384. };
  385. const stateEmitter = new Emitter();
  386. const management = {
  387. getSnapshot: async () => snapshot,
  388. onDidChangeState: stateEmitter.event,
  389. } as never;
  390. const onConnectProfile = vi.fn();
  391. render(createElement(SourceServerManagementPanel, { management, onConnectProfile }));
  392. await waitFor(() =>
  393. expect(
  394. screen.getAllByRole("button", { name: "remote.action.update-desktop" }).length,
  395. ).toBeGreaterThan(0),
  396. );
  397. expect(screen.getByText("remote.status.needsUpdate")).toBeTruthy();
  398. fireEvent.click(screen.getByRole("button", { name: "remote.action.connect" }));
  399. expect(onConnectProfile).toHaveBeenCalledWith("preferred");
  400. expect(screen.queryByRole("button", { name: "remote.action.update-server" })).toBeNull();
  401. });
  402. it("更新桌面提示旁的备用连接也防重,并接住异步失败", async () => {
  403. const snapshot = identityPendingSnapshot("installed", "preferred");
  404. snapshot.states[0] = {
  405. profileId: "preferred",
  406. sourceServerId: "old-source",
  407. state: "needs-upgrade",
  408. updateAvailability: "required",
  409. upgradeTarget: "controller",
  410. updatedAt: 2,
  411. };
  412. let reject!: (error: Error) => void;
  413. const connect = vi.fn(
  414. () =>
  415. new Promise<void>((_resolve, fail) => {
  416. reject = fail;
  417. }),
  418. );
  419. render(
  420. createElement(SourceServerManagementPanel, {
  421. management: {
  422. getSnapshot: async () => snapshot,
  423. onDidChangeState: new Emitter().event,
  424. } as never,
  425. onConnectProfile: connect,
  426. }),
  427. );
  428. const button = await screen.findByRole("button", { name: "remote.action.connect" });
  429. fireEvent.click(button);
  430. fireEvent.click(button);
  431. expect(connect).toHaveBeenCalledOnce();
  432. expect(button.getAttribute("aria-busy")).toBe("true");
  433. await act(async () => reject(new Error("connection failed")));
  434. expect(screen.getByRole("alert").textContent).toContain("settings.source.operationFailed");
  435. });
  436. it("关闭再打开设置仍可查询设备最近一次失败日志", async () => {
  437. const snapshot = identityPendingSnapshot("installed", "preferred");
  438. snapshot.states[0]!.state = "failed";
  439. const stateEmitter = new Emitter();
  440. const getRecentOperationLogs = vi.fn(async () => [
  441. {
  442. profileId: "17ef20b3-622d-4a53-98c1-0cdff29f3e6d",
  443. operation: "connect",
  444. phase: "probe",
  445. level: "error",
  446. message: "Connection refused",
  447. timestamp: 10,
  448. },
  449. ]);
  450. const management = {
  451. getSnapshot: async () => snapshot,
  452. getRecentOperationLogs,
  453. onDidChangeState: stateEmitter.event,
  454. } as never;
  455. // 失败设备的最近日志默认展开;用户手动收起后以用户选择为准。
  456. const first = render(createElement(SourceServerManagementPanel, { management }));
  457. await waitFor(() => expect(screen.getByText("Connection refused")).toBeTruthy());
  458. fireEvent.click(screen.getByText("settings.source.recentLog"));
  459. expect(screen.queryByText("Connection refused")).toBeNull();
  460. first.unmount();
  461. render(createElement(SourceServerManagementPanel, { management }));
  462. await waitFor(() => expect(screen.getByText("Connection refused")).toBeTruthy());
  463. expect(getRecentOperationLogs).toHaveBeenCalledWith("preferred");
  464. });
  465. it.each([
  466. ["installed", "preferred"],
  467. ["uninstalled", "preferred"],
  468. ["installed", "alternative"],
  469. ["uninstalled", "alternative"],
  470. ] as const)(
  471. "%s 设备的 %s 线路换代确认始终可达;取消无副作用,确认使用原服务",
  472. async (installState, pendingProfileId) => {
  473. const snapshot = identityPendingSnapshot(installState, pendingProfileId);
  474. let complete!: (value: SourceServerManagementSnapshot) => void;
  475. const confirmIdentityChange = vi.fn(
  476. () =>
  477. new Promise<SourceServerManagementSnapshot>((resolve) => {
  478. complete = resolve;
  479. }),
  480. );
  481. const onCreateConnection = vi.fn();
  482. const onConnectProfile = vi.fn();
  483. render(
  484. createElement(SourceServerManagementPanel, {
  485. management: {
  486. getSnapshot: vi.fn(async () => snapshot),
  487. onDidChangeState: new Emitter().event,
  488. confirmIdentityChange,
  489. } as never,
  490. onCreateConnection,
  491. onConnectProfile,
  492. }),
  493. );
  494. const button = await screen.findByRole("button", {
  495. name: "settings.source.identityChangeConfirm",
  496. });
  497. expect(confirmIdentityChange).not.toHaveBeenCalled();
  498. confirmDialog.mockResolvedValueOnce(false);
  499. fireEvent.click(button);
  500. await waitFor(() => expect(confirmDialog).toHaveBeenCalledOnce());
  501. expect(confirmIdentityChange).not.toHaveBeenCalled();
  502. fireEvent.click(button);
  503. await waitFor(() =>
  504. expect(confirmIdentityChange).toHaveBeenCalledExactlyOnceWith(pendingProfileId),
  505. );
  506. expect(button.hasAttribute("disabled")).toBe(true);
  507. expect(onCreateConnection).not.toHaveBeenCalled();
  508. expect(onConnectProfile).not.toHaveBeenCalled();
  509. await act(async () => complete({ ...snapshot, generation: 2, states: [] }));
  510. await waitFor(() =>
  511. expect(
  512. screen.queryByRole("button", { name: "settings.source.identityChangeConfirm" }),
  513. ).toBeNull(),
  514. );
  515. },
  516. );
  517. it("已卸载设备的多条待确认线路无需展开即可分别操作,首选线路优先", async () => {
  518. const snapshot = identityPendingSnapshot("uninstalled", "alternative");
  519. snapshot.states = snapshot.states.map((state) => ({
  520. ...state,
  521. state: "identity-change-pending",
  522. pendingSourceServerId: "new-source",
  523. }));
  524. const confirmIdentityChange = vi.fn(async () => snapshot);
  525. render(
  526. createElement(SourceServerManagementPanel, {
  527. management: {
  528. getSnapshot: vi.fn(async () => snapshot),
  529. onDidChangeState: new Emitter().event,
  530. confirmIdentityChange,
  531. } as never,
  532. }),
  533. );
  534. await screen.findByText("Reinstalled server");
  535. const buttons = screen.getAllByRole("button", {
  536. name: "settings.source.identityChangeConfirm",
  537. });
  538. expect(buttons).toHaveLength(2);
  539. fireEvent.click(buttons[0]!);
  540. await waitFor(() => expect(confirmIdentityChange).toHaveBeenCalledWith("preferred"));
  541. fireEvent.click(buttons[1]!);
  542. await waitFor(() => expect(confirmIdentityChange).toHaveBeenLastCalledWith("alternative"));
  543. });
  544. it("身份确认失败显示错误并保留入口,不自动重试或伪装已恢复", async () => {
  545. const snapshot = identityPendingSnapshot("uninstalled", "preferred");
  546. const confirmIdentityChange = vi.fn(async () => {
  547. throw new Error("connection lost");
  548. });
  549. render(
  550. createElement(SourceServerManagementPanel, {
  551. management: {
  552. getSnapshot: vi.fn(async () => snapshot),
  553. onDidChangeState: new Emitter().event,
  554. confirmIdentityChange,
  555. } as never,
  556. }),
  557. );
  558. fireEvent.click(
  559. await screen.findByRole("button", { name: "settings.source.identityChangeConfirm" }),
  560. );
  561. expect(await screen.findByText("settings.source.operationFailed")).toBeTruthy();
  562. expect(
  563. screen
  564. .getByRole("button", { name: "settings.source.identityChangeConfirm" })
  565. .hasAttribute("disabled"),
  566. ).toBe(false);
  567. expect(confirmIdentityChange).toHaveBeenCalledExactlyOnceWith("preferred");
  568. });
  569. it("only exposes startup reconnect as a global connection preference", async () => {
  570. const onUpdateSettings = vi.fn(async () => undefined);
  571. const snapshot: SourceServerManagementSnapshot = {
  572. generation: 0,
  573. profiles: [],
  574. servers: [],
  575. workspaceHistory: [],
  576. states: [],
  577. failedPathCount: 0,
  578. abandonedPathCount: 0,
  579. migrationCounts: [],
  580. };
  581. render(
  582. createElement(SourceServerManagementPanel, {
  583. management: {
  584. getSnapshot: vi.fn(async () => snapshot),
  585. onDidChangeState: new Emitter().event,
  586. } as never,
  587. settings: { remoteStartupAutoReconnectEnabled: false },
  588. onUpdateSettings,
  589. }),
  590. );
  591. expect(await screen.findByText("settings.source.connectionPreferences")).toBeTruthy();
  592. const toggle = screen.getByRole("switch", {
  593. name: "settings.source.startupAutoReconnect",
  594. });
  595. expect(toggle.getAttribute("aria-checked")).toBe("false");
  596. fireEvent.click(toggle);
  597. await waitFor(() =>
  598. expect(onUpdateSettings).toHaveBeenCalledWith({
  599. remoteStartupAutoReconnectEnabled: true,
  600. }),
  601. );
  602. });
  603. it("加载完成前只有加载态,完成后空态可新建连接", async () => {
  604. let complete!: (snapshot: SourceServerManagementSnapshot) => void;
  605. const create = vi.fn();
  606. render(
  607. createElement(SourceServerManagementPanel, {
  608. management: {
  609. getSnapshot: () =>
  610. new Promise<SourceServerManagementSnapshot>((resolve) => {
  611. complete = resolve;
  612. }),
  613. onDidChangeState: new Emitter().event,
  614. } as never,
  615. onCreateConnection: create,
  616. }),
  617. );
  618. expect(screen.getByRole("status").textContent).toContain("common.loading");
  619. expect(screen.queryByText("settings.source.empty")).toBeNull();
  620. const empty = identityPendingSnapshot("installed", "preferred");
  621. await act(async () => complete({ ...empty, servers: [], profiles: [], states: [] }));
  622. expect(screen.getByText("settings.source.empty")).toBeTruthy();
  623. fireEvent.click(screen.getByRole("button", { name: "settings.source.newConnection" }));
  624. expect(create).toHaveBeenCalledOnce();
  625. });
  626. it("开关等待保存时禁止重复提交,失败回滚并提示", async () => {
  627. let reject!: (cause: Error) => void;
  628. const save = vi.fn(
  629. () =>
  630. new Promise<void>((_resolve, fail) => {
  631. reject = fail;
  632. }),
  633. );
  634. render(
  635. createElement(SourceServerManagementPanel, {
  636. management: {
  637. getSnapshot: async () => identityPendingSnapshot("installed", "preferred"),
  638. onDidChangeState: new Emitter().event,
  639. } as never,
  640. settings: { remoteStartupAutoReconnectEnabled: true },
  641. onUpdateSettings: save,
  642. }),
  643. );
  644. const toggle = screen.getByRole("switch");
  645. fireEvent.click(toggle);
  646. expect(toggle.getAttribute("aria-checked")).toBe("false");
  647. expect(toggle.hasAttribute("disabled")).toBe(true);
  648. fireEvent.click(toggle);
  649. expect(save).toHaveBeenCalledOnce();
  650. await act(async () => reject(new Error("disk full")));
  651. expect(toggle.getAttribute("aria-checked")).toBe("true");
  652. expect(screen.getByRole("alert").textContent).toContain("settings.source.operationFailed");
  653. });
  654. it("断开无确认并显示任务继续提示,等待期间拒绝第二次断开", async () => {
  655. const snapshot = identityPendingSnapshot("installed", "preferred");
  656. snapshot.states[0]!.state = "online";
  657. let complete!: () => void;
  658. const disconnect = vi.fn(
  659. () =>
  660. new Promise<void>((resolve) => {
  661. complete = resolve;
  662. }),
  663. );
  664. render(
  665. createElement(SourceServerManagementPanel, {
  666. management: {
  667. getSnapshot: async () => snapshot,
  668. onDidChangeState: new Emitter().event,
  669. } as never,
  670. onDisconnectSource: disconnect,
  671. }),
  672. );
  673. const button = await screen.findByRole("button", { name: "remote.action.disconnect" });
  674. // 任务继续提示只在断开按钮上说明,不再常驻占一行。
  675. expect(button.getAttribute("title")).toBe("settings.source.disconnectHint");
  676. expect(screen.queryByText("settings.source.disconnectHint")).toBeNull();
  677. fireEvent.click(button);
  678. fireEvent.click(button);
  679. expect(disconnect).toHaveBeenCalledExactlyOnceWith("old-source");
  680. expect(button.getAttribute("aria-busy")).toBe("true");
  681. expect(confirmDialog).not.toHaveBeenCalled();
  682. await act(async () => complete());
  683. });
  684. it("移除设备只列出该 Source 的已打开项目,定位回调携带 Source 身份", async () => {
  685. const snapshot = identityPendingSnapshot("installed", "preferred");
  686. snapshot.states[0]!.state = "offline";
  687. const reveal = vi.fn();
  688. render(
  689. createElement(SourceServerManagementPanel, {
  690. management: {
  691. getSnapshot: async () => snapshot,
  692. onDidChangeState: new Emitter().event,
  693. } as never,
  694. onShowInSidebar: reveal,
  695. workspaceTabs: [
  696. {
  697. id: "a",
  698. kind: "workspace",
  699. label: "Project A",
  700. workspacePath: "/same-path",
  701. workspaceIdentity: "remote:server:old-source:/same-path",
  702. },
  703. {
  704. id: "b",
  705. kind: "workspace",
  706. label: "Project B",
  707. workspacePath: "/same-path",
  708. workspaceIdentity: "remote:server:other-source:/same-path",
  709. },
  710. ],
  711. }),
  712. );
  713. await screen.findByText("Reinstalled server");
  714. fireEvent.pointerDown(screen.getByRole("button", { name: "common.more" }));
  715. fireEvent.click(await screen.findByText("settings.source.showInSidebar"));
  716. expect(reveal).toHaveBeenCalledExactlyOnceWith("old-source");
  717. fireEvent.pointerDown(screen.getByRole("button", { name: "common.more" }));
  718. confirmDialog.mockResolvedValueOnce(false);
  719. fireEvent.click(await screen.findByText("settings.source.removeSourceServer"));
  720. const request = confirmDialog.mock.calls.at(-1)?.[0] as unknown as {
  721. title: string;
  722. confirmLabel: string;
  723. description: string;
  724. };
  725. expect(request.title).toBe(request.confirmLabel);
  726. expect(request.description).toContain("Project A (/same-path)");
  727. expect(request.description).not.toContain("Project B");
  728. });
  729. it("重新安装沿用此设备的连接档案,不打开空白新建表单", async () => {
  730. const snapshot = identityPendingSnapshot("uninstalled", "preferred");
  731. snapshot.states = [];
  732. const connect = vi.fn();
  733. const create = vi.fn();
  734. render(
  735. createElement(SourceServerManagementPanel, {
  736. management: {
  737. getSnapshot: async () => snapshot,
  738. onDidChangeState: new Emitter().event,
  739. } as never,
  740. onConnectProfile: connect,
  741. onCreateConnection: create,
  742. }),
  743. );
  744. fireEvent.click(
  745. await screen.findByRole("button", { name: "settings.source.reinstallAndConnect" }),
  746. );
  747. expect(connect).toHaveBeenCalledExactlyOnceWith("preferred");
  748. expect(create).not.toHaveBeenCalled();
  749. });
  750. it("更新失败只出现一次错误说明", async () => {
  751. const snapshot = identityPendingSnapshot("installed", "preferred");
  752. snapshot.states[0] = {
  753. profileId: "preferred",
  754. sourceServerId: "old-source",
  755. state: "failed",
  756. errorCode: "remote-host-unreachable",
  757. error: "Connection refused",
  758. updateAvailability: "required",
  759. updatedAt: 2,
  760. };
  761. render(
  762. createElement(SourceServerManagementPanel, {
  763. management: {
  764. getSnapshot: async () => snapshot,
  765. onDidChangeState: new Emitter().event,
  766. } as never,
  767. }),
  768. );
  769. await screen.findByText("Reinstalled server");
  770. expect(screen.getAllByText("remote.error.hostUnreachable")).toHaveLength(1);
  771. });
  772. it("项目数量过滤 Source 级 conversation backing workspace", () => {
  773. expect(
  774. getProjectCount(
  775. {
  776. workspaceHistory: [
  777. {
  778. sourceServerId: "source-1",
  779. workspacePath: "/remote/project",
  780. workspaceIdentity: "remote:server:source-1:/remote/project",
  781. },
  782. {
  783. sourceServerId: "source-1",
  784. workspacePath: "/remote/.zcode/workspace/default",
  785. workspaceIdentity: "remote:server:source-1:/remote/.zcode/workspace/default",
  786. },
  787. ],
  788. } as never,
  789. "source-1",
  790. {
  791. "source-1": {
  792. workspacePath: "/remote/.zcode/workspace/default",
  793. lastResolvedAt: 1,
  794. },
  795. },
  796. ),
  797. ).toBe(1);
  798. });
  799. it("reloads the authoritative directory snapshot after a state delta", async () => {
  800. const stateEmitter = new Emitter<{
  801. generation: number;
  802. state: SourceServerConnectionStateSnapshot;
  803. }>();
  804. const snapshot = (displayName: string, generation: number): SourceServerManagementSnapshot => ({
  805. generation,
  806. profiles: [],
  807. servers: [
  808. {
  809. sourceServerId: "3cd4f9da-cd79-426c-9d70-75f36e9f6a87",
  810. displayName,
  811. installState: "installed",
  812. },
  813. ],
  814. workspaceHistory: [],
  815. states: [],
  816. failedPathCount: 0,
  817. abandonedPathCount: 0,
  818. migrationCounts: [],
  819. });
  820. const getSnapshot = vi
  821. .fn()
  822. .mockResolvedValueOnce(snapshot("Server A", 0))
  823. .mockResolvedValueOnce(snapshot("Server B", 1));
  824. const management = {
  825. getSnapshot,
  826. onDidChangeState: stateEmitter.event,
  827. } as never;
  828. render(createElement(SourceServerManagementPanel, { management }));
  829. expect(await screen.findByText("Server A")).toBeTruthy();
  830. stateEmitter.fire({
  831. generation: 1,
  832. state: {
  833. profileId: "17ef20b3-622d-4a53-98c1-0cdff29f3e6d",
  834. state: "online",
  835. updatedAt: 1,
  836. },
  837. });
  838. await waitFor(() => expect(screen.getByText("Server B")).toBeTruthy());
  839. expect(getSnapshot).toHaveBeenCalledTimes(2);
  840. });
  841. it("coalesces burst deltas while refresh is in flight", async () => {
  842. const stateEmitter = new Emitter<{
  843. generation: number;
  844. state: SourceServerConnectionStateSnapshot;
  845. }>();
  846. const empty: SourceServerManagementSnapshot = {
  847. generation: 0,
  848. profiles: [],
  849. servers: [],
  850. workspaceHistory: [],
  851. states: [],
  852. failedPathCount: 0,
  853. abandonedPathCount: 0,
  854. migrationCounts: [],
  855. };
  856. let resolveRefresh!: (snapshot: SourceServerManagementSnapshot) => void;
  857. const getSnapshot = vi
  858. .fn()
  859. .mockResolvedValueOnce(empty)
  860. .mockImplementationOnce(
  861. async () =>
  862. await new Promise<SourceServerManagementSnapshot>((resolve) => {
  863. resolveRefresh = resolve;
  864. }),
  865. )
  866. .mockResolvedValue(empty);
  867. render(
  868. createElement(SourceServerManagementPanel, {
  869. management: { getSnapshot, onDidChangeState: stateEmitter.event } as never,
  870. }),
  871. );
  872. await waitFor(() => expect(getSnapshot).toHaveBeenCalledOnce());
  873. const state = { profileId: "p", state: "retrying", updatedAt: 1 } as const;
  874. stateEmitter.fire({ generation: 1, state });
  875. stateEmitter.fire({ generation: 2, state });
  876. await Promise.resolve();
  877. expect(getSnapshot).toHaveBeenCalledTimes(2);
  878. resolveRefresh(empty);
  879. await waitFor(() => expect(getSnapshot).toHaveBeenCalledTimes(3));
  880. });
  881. it("does not render an unstructured Host error", async () => {
  882. const snapshot: SourceServerManagementSnapshot = {
  883. generation: 1,
  884. profiles: [
  885. {
  886. profileId: "p",
  887. transport: "docker",
  888. target: { kind: "docker", container: "dev" },
  889. sourceServerId: "s",
  890. createdAt: 1,
  891. },
  892. ],
  893. servers: [{ sourceServerId: "s", displayName: "Dev", installState: "installed" }],
  894. workspaceHistory: [],
  895. states: [
  896. {
  897. profileId: "p",
  898. sourceServerId: "s",
  899. state: "failed",
  900. updatedAt: 1,
  901. error: "raw host detail",
  902. },
  903. ],
  904. failedPathCount: 0,
  905. abandonedPathCount: 0,
  906. migrationCounts: [],
  907. };
  908. render(
  909. createElement(SourceServerManagementPanel, {
  910. management: {
  911. getSnapshot: vi.fn(async () => snapshot),
  912. onDidChangeState: new Emitter().event,
  913. } as never,
  914. }),
  915. );
  916. expect(await screen.findByText("remote.error.unknown")).toBeTruthy();
  917. expect(screen.queryByText("raw host detail")).toBeNull();
  918. });
  919. it("renders concrete recovery attempt values after the retry budget is exhausted", async () => {
  920. const snapshot: SourceServerManagementSnapshot = {
  921. generation: 1,
  922. profiles: [
  923. {
  924. profileId: "p",
  925. transport: "docker",
  926. target: { kind: "docker", container: "dev" },
  927. sourceServerId: "s",
  928. createdAt: 1,
  929. },
  930. ],
  931. servers: [{ sourceServerId: "s", displayName: "Dev", installState: "installed" }],
  932. workspaceHistory: [],
  933. states: [
  934. {
  935. profileId: "p",
  936. sourceServerId: "s",
  937. state: "offline",
  938. updatedAt: 1,
  939. error: "network unavailable",
  940. errorCode: "remote-recovery-budget-exhausted",
  941. recoveryAttempt: 3,
  942. recoveryLimit: 3,
  943. recoveryBudgetExhausted: true,
  944. retryable: true,
  945. },
  946. ],
  947. failedPathCount: 0,
  948. abandonedPathCount: 0,
  949. migrationCounts: [],
  950. };
  951. render(
  952. createElement(SourceServerManagementPanel, {
  953. management: {
  954. getSnapshot: vi.fn(async () => snapshot),
  955. onDidChangeState: new Emitter().event,
  956. } as never,
  957. }),
  958. );
  959. expect(await screen.findByText(/remote\.error\.recoveryBudgetExhausted:3\/3/u)).toBeTruthy();
  960. });
  961. it("shows version details and server update instead of reconnect when upgrade is required", async () => {
  962. const snapshot: SourceServerManagementSnapshot = {
  963. generation: 1,
  964. profiles: [
  965. {
  966. profileId: "p",
  967. transport: "docker",
  968. target: { kind: "docker", container: "dev" },
  969. sourceServerId: "s",
  970. createdAt: 1,
  971. },
  972. ],
  973. servers: [{ sourceServerId: "s", displayName: "Dev", installState: "installed" }],
  974. workspaceHistory: [],
  975. states: [
  976. {
  977. profileId: "p",
  978. sourceServerId: "s",
  979. state: "needs-upgrade",
  980. updateAvailability: "required",
  981. currentVersion: "3.6.0",
  982. minimumVersion: "3.7.0",
  983. availableVersion: "3.8.0",
  984. upgradeTarget: "server",
  985. updatedAt: 1,
  986. },
  987. ],
  988. failedPathCount: 0,
  989. abandonedPathCount: 0,
  990. migrationCounts: [],
  991. };
  992. render(
  993. createElement(SourceServerManagementPanel, {
  994. management: {
  995. getSnapshot: vi.fn(async () => snapshot),
  996. onDidChangeState: new Emitter().event,
  997. } as never,
  998. }),
  999. );
  1000. expect(await screen.findByText("settings.source.versionDetails")).toBeTruthy();
  1001. expect(screen.queryByRole("button", { name: "remote.action.connect" })).toBeNull();
  1002. screen.getByRole("button", {
  1003. name: "remote.action.update-server",
  1004. });
  1005. screen.getByRole("button", {
  1006. name: "settings.source.editConnection",
  1007. });
  1008. screen.getByRole("button", { name: "common.more" });
  1009. });
  1010. it("更新中覆盖旧的必须更新文案并展示明确进度", async () => {
  1011. const operationLogEmitter = new Emitter<{
  1012. profileId: string;
  1013. operation: "update";
  1014. phase: string;
  1015. level: "info";
  1016. message: string;
  1017. progress?: number;
  1018. timestamp: number;
  1019. }>();
  1020. const snapshot: SourceServerManagementSnapshot = {
  1021. generation: 2,
  1022. profiles: [
  1023. {
  1024. profileId: "p",
  1025. transport: "ssh",
  1026. target: { kind: "ssh", host: "h", username: "u" },
  1027. sourceServerId: "s",
  1028. createdAt: 1,
  1029. },
  1030. ],
  1031. servers: [{ sourceServerId: "s", displayName: "Dev", installState: "installed" }],
  1032. workspaceHistory: [],
  1033. states: [
  1034. {
  1035. profileId: "p",
  1036. sourceServerId: "s",
  1037. state: "updating",
  1038. updateAvailability: "required",
  1039. currentVersion: "3.8.1",
  1040. minimumVersion: "3.9.0",
  1041. availableVersion: "3.9.0",
  1042. upgradeTarget: "server",
  1043. updatedAt: 2,
  1044. },
  1045. ],
  1046. failedPathCount: 0,
  1047. abandonedPathCount: 0,
  1048. migrationCounts: [],
  1049. };
  1050. let operationLogs: unknown[] = [];
  1051. operationLogEmitter.event((entry) => {
  1052. operationLogs = [{ ...entry, profileId: "17ef20b3-622d-4a53-98c1-0cdff29f3e6d" }];
  1053. });
  1054. render(
  1055. createElement(SourceServerManagementPanel, {
  1056. management: {
  1057. getSnapshot: vi.fn(async () => snapshot),
  1058. getRecentOperationLogs: vi.fn(async () => operationLogs),
  1059. onDidChangeState: new Emitter().event,
  1060. onDidAppendOperationLog: operationLogEmitter.event,
  1061. } as never,
  1062. }),
  1063. );
  1064. expect(await screen.findByText("settings.source.updateInProgress")).toBeTruthy();
  1065. expect(screen.queryByText("settings.source.updateRequired")).toBeNull();
  1066. expect(screen.getByRole("progressbar").getAttribute("aria-valuenow")).toBeNull();
  1067. act(() => {
  1068. operationLogEmitter.fire({
  1069. profileId: "p",
  1070. operation: "update",
  1071. phase: "upload",
  1072. level: "info",
  1073. message: "upload archive",
  1074. progress: 0.5,
  1075. timestamp: 3,
  1076. });
  1077. });
  1078. expect(await screen.findByText("upload archive")).toBeTruthy();
  1079. expect(screen.getByRole("progressbar").getAttribute("aria-valuenow")).toBe("50");
  1080. for (const [phase, messageId] of [
  1081. ["extract", "remote.phaseSub.extracting"],
  1082. ["verify-archive", "remote.phaseSub.verifyingArchive"],
  1083. ["verify", "remote.phaseSub.verifyingFiles"],
  1084. ["restart", "remote.phaseSub.restarting"],
  1085. ]) {
  1086. act(() =>
  1087. operationLogEmitter.fire({
  1088. profileId: "p",
  1089. operation: "update",
  1090. phase: phase!,
  1091. level: "info",
  1092. message: phase!,
  1093. timestamp: 4,
  1094. }),
  1095. );
  1096. expect(await screen.findByText(messageId!)).toBeTruthy();
  1097. expect(screen.getByRole("progressbar").getAttribute("aria-valuenow")).toBeNull();
  1098. }
  1099. });
  1100. it("edits the preferred connection in a dialog instead of inline", async () => {
  1101. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  1102. const snapshot: SourceServerManagementSnapshot = {
  1103. generation: 1,
  1104. profiles: [
  1105. {
  1106. profileId: "p",
  1107. transport: "docker",
  1108. displayName: "old name",
  1109. target: { kind: "docker", container: "dev" },
  1110. sourceServerId: "s",
  1111. createdAt: 1,
  1112. },
  1113. ],
  1114. servers: [{ sourceServerId: "s", displayName: "Dev", installState: "installed" }],
  1115. workspaceHistory: [],
  1116. states: [],
  1117. failedPathCount: 0,
  1118. abandonedPathCount: 0,
  1119. migrationCounts: [],
  1120. };
  1121. const getSnapshot = vi.fn(async () => snapshot);
  1122. render(
  1123. createElement(SourceServerManagementPanel, {
  1124. management: { getSnapshot, onDidChangeState: stateEmitter.event } as never,
  1125. }),
  1126. );
  1127. expect(await screen.findByText("Dev")).toBeTruthy();
  1128. expect(screen.queryByDisplayValue("Dev")).toBeNull();
  1129. fireEvent.click(screen.getByRole("button", { name: "settings.source.editConnection" }));
  1130. expect(screen.getByRole("dialog")).toBeTruthy();
  1131. expect(screen.getByDisplayValue("Dev")).toBeTruthy();
  1132. });
  1133. it("启动尚未连接时,不把历史失败重新显示为当前故障", async () => {
  1134. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  1135. const snapshot: SourceServerManagementSnapshot = {
  1136. generation: 1,
  1137. profiles: [
  1138. {
  1139. profileId: "p",
  1140. transport: "ssh",
  1141. displayName: "line",
  1142. target: { kind: "ssh", host: "h", username: "u" },
  1143. sourceServerId: "s",
  1144. lastConnectError: "auth rejected",
  1145. createdAt: 1,
  1146. },
  1147. ],
  1148. servers: [{ sourceServerId: "s", displayName: "Dev", installState: "installed" }],
  1149. workspaceHistory: [],
  1150. states: [],
  1151. failedPathCount: 0,
  1152. abandonedPathCount: 0,
  1153. migrationCounts: [],
  1154. };
  1155. render(
  1156. createElement(SourceServerManagementPanel, {
  1157. management: {
  1158. getSnapshot: vi.fn(async () => snapshot),
  1159. onDidChangeState: stateEmitter.event,
  1160. } as never,
  1161. }),
  1162. );
  1163. expect(await screen.findByText("remote.status.offline")).toBeTruthy();
  1164. expect(screen.queryByText("settings.source.lastConnectError")).toBeNull();
  1165. });
  1166. it("shows one primary connection and collapses other saved connections", async () => {
  1167. const snapshot: SourceServerManagementSnapshot = {
  1168. generation: 1,
  1169. profiles: [
  1170. {
  1171. profileId: "primary",
  1172. transport: "ssh",
  1173. displayName: "primary connection",
  1174. target: { kind: "ssh", host: "primary.example.com", username: "dev" },
  1175. sourceServerId: "source",
  1176. createdAt: 1,
  1177. lifecycleState: "active",
  1178. },
  1179. {
  1180. profileId: "backup",
  1181. transport: "ssh",
  1182. displayName: "backup connection",
  1183. target: { kind: "ssh", host: "backup.example.com", username: "dev" },
  1184. sourceServerId: "source",
  1185. createdAt: 2,
  1186. lifecycleState: "active",
  1187. },
  1188. ],
  1189. servers: [
  1190. {
  1191. sourceServerId: "source",
  1192. displayName: "Build server",
  1193. preferredProfileId: "primary",
  1194. installState: "installed",
  1195. declaredWorkspaces: [],
  1196. },
  1197. ],
  1198. workspaceHistory: [],
  1199. states: [],
  1200. failedPathCount: 0,
  1201. abandonedPathCount: 0,
  1202. migrationCounts: [],
  1203. };
  1204. render(
  1205. createElement(SourceServerManagementPanel, {
  1206. management: {
  1207. getSnapshot: vi.fn(async () => snapshot),
  1208. onDidChangeState: new Emitter().event,
  1209. updateProfile: vi.fn(),
  1210. } as never,
  1211. }),
  1212. );
  1213. expect(await screen.findByText("Build server")).toBeTruthy();
  1214. expect(document.querySelector('[data-remote-connection-status="offline"]')).toBeTruthy();
  1215. expect(document.querySelector('[data-remote-connection-kind="ssh"]')).toBeTruthy();
  1216. expect(screen.getByText("dev@primary.example.com:22")).toBeTruthy();
  1217. expect(screen.queryByText("dev@backup.example.com:22")).toBeNull();
  1218. expect(
  1219. screen.getAllByRole("button", {
  1220. name: "settings.source.editConnection",
  1221. }),
  1222. ).toHaveLength(1);
  1223. fireEvent.click(
  1224. screen.getByRole("button", {
  1225. name: "settings.source.otherSavedConnections",
  1226. }),
  1227. );
  1228. screen.getByText("dev@backup.example.com:22");
  1229. expect(screen.getByRole("button", { name: "settings.source.setDefault" })).toBeTruthy();
  1230. });
  1231. it("未识别连接只出现在默认折叠的未完成区域", async () => {
  1232. const snapshot: SourceServerManagementSnapshot = {
  1233. generation: 1,
  1234. profiles: [
  1235. {
  1236. profileId: "unbound-profile",
  1237. transport: "ssh",
  1238. displayName: "linux-arm64-dev",
  1239. target: {
  1240. kind: "ssh",
  1241. host: "localhost",
  1242. port: 2223,
  1243. username: "dev",
  1244. sshConfigAlias: "linux-arm64-dev",
  1245. },
  1246. createdAt: 1,
  1247. lifecycleState: "active",
  1248. },
  1249. ],
  1250. servers: [],
  1251. workspaceHistory: [],
  1252. states: [
  1253. {
  1254. profileId: "unbound-profile",
  1255. state: "offline",
  1256. updatedAt: 1,
  1257. },
  1258. ],
  1259. failedPathCount: 0,
  1260. abandonedPathCount: 0,
  1261. migrationCounts: [],
  1262. };
  1263. const { container } = render(
  1264. createElement(SourceServerManagementPanel, {
  1265. management: {
  1266. getSnapshot: vi.fn(async () => snapshot),
  1267. onDidChangeState: new Emitter().event,
  1268. removeProfile: vi.fn(),
  1269. } as never,
  1270. }),
  1271. );
  1272. expect(await screen.findByText("settings.source.unfinishedConnections")).toBeTruthy();
  1273. const unfinished = container.querySelector("[data-unfinished-connections]");
  1274. expect(unfinished?.tagName).toBe("DETAILS");
  1275. expect(unfinished?.hasAttribute("open")).toBe(false);
  1276. expect(container.querySelector("[data-source-server-card]")).toBeNull();
  1277. fireEvent.click(screen.getByText("settings.source.unfinishedConnections"));
  1278. expect(screen.getByText("linux-arm64-dev")).toBeTruthy();
  1279. expect(container.querySelector('[data-remote-connection-status="offline"]')).toBeTruthy();
  1280. expect(screen.getByText("dev@localhost:2223")).toBeTruthy();
  1281. const preferences = screen.getByText("settings.source.connectionPreferences");
  1282. expect(
  1283. unfinished!.compareDocumentPosition(preferences) & Node.DOCUMENT_POSITION_FOLLOWING,
  1284. ).toBeTruthy();
  1285. // 没有已识别设备时不显示设备列表标题。
  1286. expect(screen.queryByText("settings.source.devicesHeading")).toBeNull();
  1287. });
  1288. it("does not expose migration diagnostics in the regular connection menu", async () => {
  1289. const snapshot: SourceServerManagementSnapshot = {
  1290. generation: 1,
  1291. profiles: [
  1292. {
  1293. profileId: "profile-a",
  1294. sourceServerId: "source-a",
  1295. transport: "ssh",
  1296. target: { kind: "ssh", host: "example.com", username: "dev" },
  1297. createdAt: 1,
  1298. lifecycleState: "active",
  1299. },
  1300. ],
  1301. servers: [
  1302. {
  1303. sourceServerId: "source-a",
  1304. displayName: "Build server",
  1305. preferredProfileId: "profile-a",
  1306. installState: "installed",
  1307. declaredWorkspaces: [],
  1308. },
  1309. ],
  1310. workspaceHistory: [],
  1311. states: [
  1312. {
  1313. profileId: "profile-a",
  1314. sourceServerId: "source-a",
  1315. state: "online",
  1316. updatedAt: 1,
  1317. },
  1318. ],
  1319. failedPathCount: 0,
  1320. abandonedPathCount: 0,
  1321. migrationCounts: [
  1322. {
  1323. sourceServerId: "source-a",
  1324. status: "available",
  1325. failedPathCount: 0,
  1326. abandonedPathCount: 0,
  1327. },
  1328. ],
  1329. };
  1330. const getMigrationReport = vi.fn();
  1331. const exportMigrationReport = vi.fn();
  1332. render(
  1333. createElement(SourceServerManagementPanel, {
  1334. management: {
  1335. getSnapshot: vi.fn(async () => snapshot),
  1336. onDidChangeState: new Emitter().event,
  1337. getMigrationReport,
  1338. exportMigrationReport,
  1339. } as never,
  1340. }),
  1341. );
  1342. expect(await screen.findByText("Build server")).toBeTruthy();
  1343. fireEvent.pointerDown(screen.getByRole("button", { name: "common.more" }));
  1344. expect(screen.queryByText("settings.source.migrationReport")).toBeNull();
  1345. expect(screen.queryByText("settings.source.exportMigrationJson")).toBeNull();
  1346. expect(getMigrationReport).not.toHaveBeenCalled();
  1347. expect(exportMigrationReport).not.toHaveBeenCalled();
  1348. });
  1349. it("keeps a user-facing connection-history alert for pending migration work", async () => {
  1350. const snapshot: SourceServerManagementSnapshot = {
  1351. generation: 1,
  1352. profiles: [
  1353. {
  1354. profileId: "profile-a",
  1355. sourceServerId: "source-a",
  1356. transport: "ssh",
  1357. target: { kind: "ssh", host: "example.com", username: "dev" },
  1358. createdAt: 1,
  1359. lifecycleState: "active",
  1360. },
  1361. ],
  1362. servers: [
  1363. {
  1364. sourceServerId: "source-a",
  1365. displayName: "Build server",
  1366. preferredProfileId: "profile-a",
  1367. installState: "installed",
  1368. declaredWorkspaces: [],
  1369. },
  1370. ],
  1371. workspaceHistory: [],
  1372. states: [
  1373. {
  1374. profileId: "profile-a",
  1375. sourceServerId: "source-a",
  1376. state: "online",
  1377. updatedAt: 1,
  1378. },
  1379. ],
  1380. failedPathCount: 1,
  1381. abandonedPathCount: 0,
  1382. migrationCounts: [
  1383. {
  1384. sourceServerId: "source-a",
  1385. status: "available",
  1386. failedPathCount: 1,
  1387. abandonedPathCount: 0,
  1388. },
  1389. ],
  1390. };
  1391. const getMigrationReport = vi.fn(async () => ({ rows: [] }));
  1392. render(
  1393. createElement(SourceServerManagementPanel, {
  1394. management: {
  1395. getSnapshot: vi.fn(async () => snapshot),
  1396. onDidChangeState: new Emitter().event,
  1397. getMigrationReport,
  1398. } as never,
  1399. }),
  1400. );
  1401. expect(await screen.findByText("settings.source.connectionHistoryNeedsAttention")).toBeTruthy();
  1402. expect(screen.queryByText(/产品边界/u)).toBeNull();
  1403. expect(screen.queryByText("settings.source.migrationReport")).toBeNull();
  1404. expect(screen.queryByText("settings.source.exportMigrationJson")).toBeNull();
  1405. fireEvent.click(screen.getByText("settings.source.connectionHistoryNeedsAttention"));
  1406. expect(await screen.findByText("settings.source.noMigrationIssues")).toBeTruthy();
  1407. expect(getMigrationReport).toHaveBeenCalledWith("source-a");
  1408. expect(screen.queryByRole("button", { name: /exportMigrationReport/u })).toBeNull();
  1409. });
  1410. it("routes every user connection action through the global dialog profile intent", async () => {
  1411. const snapshot: SourceServerManagementSnapshot = {
  1412. generation: 1,
  1413. profiles: [
  1414. {
  1415. profileId: "bound-profile",
  1416. sourceServerId: "source-a",
  1417. transport: "ssh",
  1418. target: { kind: "ssh", host: "bound.example.com", username: "dev" },
  1419. createdAt: 1,
  1420. lifecycleState: "active",
  1421. },
  1422. {
  1423. profileId: "unbound-profile",
  1424. transport: "docker",
  1425. target: { kind: "docker", container: "pending-dev" },
  1426. createdAt: 2,
  1427. lifecycleState: "active",
  1428. },
  1429. ],
  1430. servers: [
  1431. {
  1432. sourceServerId: "source-a",
  1433. displayName: "Build server",
  1434. preferredProfileId: "bound-profile",
  1435. installState: "installed",
  1436. declaredWorkspaces: [],
  1437. },
  1438. ],
  1439. workspaceHistory: [],
  1440. states: [],
  1441. failedPathCount: 0,
  1442. abandonedPathCount: 0,
  1443. migrationCounts: [],
  1444. };
  1445. const connectProfile = vi.fn();
  1446. const onConnectProfile = vi.fn();
  1447. render(
  1448. createElement(SourceServerManagementPanel, {
  1449. management: {
  1450. getSnapshot: vi.fn(async () => snapshot),
  1451. onDidChangeState: new Emitter().event,
  1452. connectProfile,
  1453. } as never,
  1454. onConnectProfile,
  1455. }),
  1456. );
  1457. expect(await screen.findByText("Build server")).toBeTruthy();
  1458. fireEvent.click(screen.getByText("settings.source.unfinishedConnections"));
  1459. const connectButtons = screen.getAllByRole("button", {
  1460. name: "remote.action.connect",
  1461. });
  1462. expect(connectButtons).toHaveLength(2);
  1463. await act(async () => fireEvent.click(connectButtons[0]!));
  1464. await act(async () => fireEvent.click(connectButtons[1]!));
  1465. expect(onConnectProfile.mock.calls).toEqual([["bound-profile"], ["unbound-profile"]]);
  1466. expect(connectProfile).not.toHaveBeenCalled();
  1467. });
  1468. it("routes device disconnect through the injected remote controller adapter", async () => {
  1469. const snapshot: SourceServerManagementSnapshot = {
  1470. generation: 1,
  1471. profiles: [
  1472. {
  1473. profileId: "profile-a",
  1474. sourceServerId: "source-a",
  1475. transport: "ssh",
  1476. target: { kind: "ssh", host: "example.com", username: "dev" },
  1477. createdAt: 1,
  1478. lifecycleState: "active",
  1479. },
  1480. ],
  1481. servers: [
  1482. {
  1483. sourceServerId: "source-a",
  1484. displayName: "Build server",
  1485. installState: "installed",
  1486. declaredWorkspaces: [],
  1487. },
  1488. ],
  1489. workspaceHistory: [],
  1490. states: [
  1491. {
  1492. profileId: "profile-a",
  1493. sourceServerId: "source-a",
  1494. state: "online",
  1495. updatedAt: 1,
  1496. },
  1497. ],
  1498. failedPathCount: 0,
  1499. abandonedPathCount: 0,
  1500. migrationCounts: [],
  1501. };
  1502. const onDisconnectSource = vi.fn(async () => undefined);
  1503. render(
  1504. createElement(SourceServerManagementPanel, {
  1505. management: {
  1506. getSnapshot: vi.fn(async () => snapshot),
  1507. onDidChangeState: new Emitter().event,
  1508. } as never,
  1509. onDisconnectSource,
  1510. }),
  1511. );
  1512. expect(await screen.findByText("Build server")).toBeTruthy();
  1513. fireEvent.click(screen.getByRole("button", { name: "remote.action.disconnect" }));
  1514. await waitFor(() => expect(onDisconnectSource).toHaveBeenCalledWith("source-a"));
  1515. });
  1516. it("离线设备的更多菜单仍提供「移除全部连接」并调用 Host 移除", async () => {
  1517. const snapshot: SourceServerManagementSnapshot = {
  1518. generation: 1,
  1519. profiles: [
  1520. {
  1521. profileId: "profile-a",
  1522. sourceServerId: "source-a",
  1523. transport: "ssh",
  1524. target: { kind: "ssh", host: "example.com", username: "dev" },
  1525. createdAt: 1,
  1526. lifecycleState: "active",
  1527. },
  1528. ],
  1529. servers: [
  1530. {
  1531. sourceServerId: "source-a",
  1532. displayName: "Build server",
  1533. preferredProfileId: "profile-a",
  1534. installState: "installed",
  1535. declaredWorkspaces: [],
  1536. },
  1537. ],
  1538. workspaceHistory: [],
  1539. states: [
  1540. {
  1541. profileId: "profile-a",
  1542. sourceServerId: "source-a",
  1543. state: "offline",
  1544. updatedAt: 1,
  1545. },
  1546. ],
  1547. failedPathCount: 0,
  1548. abandonedPathCount: 0,
  1549. migrationCounts: [],
  1550. };
  1551. const removeSourceServer = vi.fn(async () => ({
  1552. ...snapshot,
  1553. generation: 2,
  1554. profiles: [],
  1555. servers: [],
  1556. states: [],
  1557. }));
  1558. render(
  1559. createElement(SourceServerManagementPanel, {
  1560. management: {
  1561. getSnapshot: vi.fn(async () => snapshot),
  1562. onDidChangeState: new Emitter().event,
  1563. removeSourceServer,
  1564. } as never,
  1565. onShowInSidebar: vi.fn(),
  1566. }),
  1567. );
  1568. expect(await screen.findByText("Build server")).toBeTruthy();
  1569. fireEvent.pointerDown(screen.getByRole("button", { name: "common.more" }));
  1570. // 离线设备不在侧边栏展示,但移除只删本机记录,不依赖连接。
  1571. expect(await screen.findByText("settings.source.removeSourceServer")).toBeTruthy();
  1572. expect(screen.queryByText("settings.source.showInSidebar")).toBeNull();
  1573. const menu = document.querySelector<HTMLElement>('[data-slot="dropdown-menu-content"]');
  1574. expect(screen.getByText("settings.source.copyDeviceId")).toBeTruthy();
  1575. expect(menu?.querySelector("[data-device-info]")?.textContent).toContain("source-a");
  1576. fireEvent.click(screen.getByText("settings.source.removeSourceServer"));
  1577. await waitFor(() => expect(removeSourceServer).toHaveBeenCalledWith("source-a"));
  1578. });
  1579. });
  1580. it("管理入口在快照到达后定位设备卡并消费一次意图,普通重挂不抢焦点", async () => {
  1581. const snapshot = identityPendingSnapshot("installed", "preferred");
  1582. const pending = Promise.withResolvers<typeof snapshot>();
  1583. const management = {
  1584. getSnapshot: () => pending.promise,
  1585. onDidChangeState: new Emitter().event,
  1586. } as never;
  1587. const consumed = vi.fn();
  1588. const scroll = vi.fn();
  1589. Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
  1590. configurable: true,
  1591. value: scroll,
  1592. });
  1593. const view = render(
  1594. createElement(SourceServerManagementPanel, {
  1595. management,
  1596. targetSourceServerId: "old-source",
  1597. onTargetSourceServerFocused: consumed,
  1598. }),
  1599. );
  1600. expect(consumed).not.toHaveBeenCalled();
  1601. await act(async () => pending.resolve(snapshot));
  1602. await waitFor(() =>
  1603. expect(document.activeElement?.getAttribute("data-source-server-card")).toBe("old-source"),
  1604. );
  1605. expect(consumed).toHaveBeenCalledOnce();
  1606. expect(scroll).toHaveBeenCalledWith({ block: "center" });
  1607. view.unmount();
  1608. render(createElement(SourceServerManagementPanel, { management }));
  1609. await screen.findByText("Reinstalled server");
  1610. expect(scroll).toHaveBeenCalledOnce();
  1611. expect(document.activeElement?.getAttribute("data-source-server-card")).toBeNull();
  1612. });
  1613. it("设备操作按 Source 防重,无关设备与只读展开可继续,反序快照不回滚", async () => {
  1614. const snapshot = identityPendingSnapshot("installed", "other");
  1615. snapshot.states.forEach((state) => {
  1616. state.state = "online";
  1617. state.updateAvailability = "available";
  1618. state.availableVersion = "2.0.0";
  1619. });
  1620. snapshot.servers.push({
  1621. ...snapshot.servers[0]!,
  1622. sourceServerId: "second",
  1623. displayName: "Second",
  1624. preferredProfileId: "second",
  1625. });
  1626. snapshot.profiles.push({
  1627. ...snapshot.profiles[0]!,
  1628. sourceServerId: "second",
  1629. profileId: "second",
  1630. });
  1631. snapshot.states.push({
  1632. ...snapshot.states[0]!,
  1633. sourceServerId: "second",
  1634. profileId: "second",
  1635. state: "online",
  1636. });
  1637. snapshot.states[1] = {
  1638. ...snapshot.states[1]!,
  1639. state: "failed",
  1640. errorCode: "remote-permission-denied",
  1641. };
  1642. const first = Promise.withResolvers<SourceServerManagementSnapshot>();
  1643. const second = Promise.withResolvers<SourceServerManagementSnapshot>();
  1644. const updateSource = vi.fn(({ profileId }: { profileId: string }) =>
  1645. profileId === "second" ? second.promise : first.promise,
  1646. );
  1647. const management = {
  1648. getSnapshot: async () => snapshot,
  1649. onDidChangeState: new Emitter().event,
  1650. updateSource,
  1651. } as never;
  1652. const { container } = render(
  1653. createElement(SourceServerManagementPanel, {
  1654. management,
  1655. onDisconnectSource: vi.fn(async () => {}),
  1656. }),
  1657. );
  1658. await screen.findByText("Second");
  1659. const card = (id: string) => container.querySelector(`[data-source-server-card="${id}"]`)!;
  1660. const action = (id: string) =>
  1661. Array.from(card(id).querySelectorAll("button")).find(
  1662. (button) => button.textContent === "remote.action.update-server",
  1663. )!;
  1664. fireEvent.click(action("old-source"));
  1665. fireEvent.click(action("old-source"));
  1666. expect(updateSource).toHaveBeenCalledTimes(1);
  1667. expect(
  1668. card("second")
  1669. .querySelector('button[aria-label="settings.source.editConnection"]')!
  1670. .matches(":disabled"),
  1671. ).toBe(false);
  1672. const expand = card("old-source").querySelector(
  1673. 'button[aria-label="settings.source.otherSavedConnections"]',
  1674. )!;
  1675. expect(expand.matches(":disabled")).toBe(false);
  1676. fireEvent.click(expand);
  1677. const otherLine = screen.getByText("dev@other.example.com:22").parentElement!;
  1678. const lineButton = (name: string) =>
  1679. Array.from(otherLine.querySelectorAll("button")).find((button) => button.textContent === name)!;
  1680. expect(lineButton("remote.action.details").matches(":disabled")).toBe(false);
  1681. expect(lineButton("settings.source.setDefault").matches(":disabled")).toBe(true);
  1682. expect(lineButton("settings.source.removeProfile").matches(":disabled")).toBe(true);
  1683. expect(
  1684. card("old-source")
  1685. .querySelector('button[aria-label="settings.source.editConnection"]')!
  1686. .matches(":disabled"),
  1687. ).toBe(true);
  1688. fireEvent.click(action("second"));
  1689. expect(updateSource).toHaveBeenCalledTimes(2);
  1690. await act(async () =>
  1691. second.resolve({
  1692. ...snapshot,
  1693. generation: 3,
  1694. servers: snapshot.servers.map((server) => ({
  1695. ...server,
  1696. displayName: `${server.displayName} latest`,
  1697. })),
  1698. }),
  1699. );
  1700. await screen.findByText("Second latest");
  1701. await act(async () => first.resolve({ ...snapshot, generation: 2 }));
  1702. expect(screen.queryByText("Second")).toBeNull();
  1703. expect(screen.getByText("Second latest")).toBeTruthy();
  1704. });
  1705. it("管理失败设备只定位,显式详情意图才打开对话框且同设备可再次消费", async () => {
  1706. Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
  1707. configurable: true,
  1708. value: vi.fn(),
  1709. });
  1710. const snapshot = identityPendingSnapshot("installed", "preferred");
  1711. snapshot.states[0] = {
  1712. ...snapshot.states[0]!,
  1713. state: "failed",
  1714. errorCode: "remote-host-unreachable",
  1715. error: "connect ECONNREFUSED",
  1716. };
  1717. const management = {
  1718. getSnapshot: async () => snapshot,
  1719. onDidChangeState: new Emitter().event,
  1720. } as never;
  1721. const view = render(
  1722. createElement(SourceServerManagementPanel, { management, targetSourceServerId: "old-source" }),
  1723. );
  1724. await screen.findByText("Reinstalled server");
  1725. expect(screen.queryByRole("dialog")).toBeNull();
  1726. view.rerender(createElement(SourceServerManagementPanel, { management }));
  1727. view.rerender(
  1728. createElement(SourceServerManagementPanel, {
  1729. management,
  1730. targetSourceServerId: "old-source",
  1731. targetSourceServerDetails: true,
  1732. }),
  1733. );
  1734. expect(await screen.findByRole("dialog")).toBeTruthy();
  1735. });
  1736. it.each([false, true])("可选更新不吞同设备连接失败原因(同 Profile:%s)", async (sameProfile) => {
  1737. const snapshot = identityPendingSnapshot("installed", "other");
  1738. snapshot.states[0] = {
  1739. ...snapshot.states[0]!,
  1740. state: "failed",
  1741. errorCode: "remote-host-unreachable",
  1742. error: "connect ECONNREFUSED",
  1743. updatedAt: 2,
  1744. };
  1745. snapshot.states[1] = { ...snapshot.states[1]!, state: "offline" };
  1746. Object.assign(snapshot.states[sameProfile ? 0 : 1]!, {
  1747. updateAvailability: "available",
  1748. availableVersion: "2.0.0",
  1749. });
  1750. render(
  1751. createElement(SourceServerManagementPanel, {
  1752. management: {
  1753. getSnapshot: async () => snapshot,
  1754. onDidChangeState: new Emitter().event,
  1755. } as never,
  1756. }),
  1757. );
  1758. await screen.findByText("Reinstalled server");
  1759. expect(screen.getByText("remote.error.hostUnreachable")).toBeTruthy();
  1760. if (!sameProfile) expect(screen.getByText("settings.source.updateAvailableVersion")).toBeTruthy();
  1761. });
  1762. it("同连接的可选更新稍后隐藏后仍展示连接失败原因", async () => {
  1763. const snapshot = identityPendingSnapshot("installed", "preferred");
  1764. snapshot.states[0] = {
  1765. ...snapshot.states[0]!,
  1766. state: "failed",
  1767. errorCode: "remote-host-unreachable",
  1768. updateAvailability: "available",
  1769. availableVersion: "deferred-regression",
  1770. };
  1771. render(
  1772. createElement(SourceServerManagementPanel, {
  1773. management: {
  1774. getSnapshot: async () => snapshot,
  1775. onDidChangeState: new Emitter().event,
  1776. } as never,
  1777. }),
  1778. );
  1779. await screen.findByText("remote.error.hostUnreachable");
  1780. fireEvent.click(screen.getByRole("button", { name: "updateDialog.later" }));
  1781. expect(screen.getByText("remote.error.hostUnreachable")).toBeTruthy();
  1782. expect(screen.queryByRole("button", { name: "updateDialog.later" })).toBeNull();
  1783. });