sourceServerUpdateNotifications.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import { Emitter } from "@zcode/rpc";
  2. import type {
  3. SourceServerManagementSnapshot,
  4. SourceServerManagementStateDelta,
  5. RemoteTarget,
  6. } from "@zcode/shared";
  7. import type { ISourceServerManagementService } from "@zcode/services";
  8. import { describe, expect, it, vi } from "vitest";
  9. import { createSourceServerUpdateNotificationController } from "@/root/sourceServerUpdateNotifications.js";
  10. import { createSourceServerUpdatePreferences } from "@/lib/sourceServerUpdatePreferences.js";
  11. import type { ToastOptions } from "@/components/ui/toast.js";
  12. const profileId = "17ef20b3-622d-4a53-98c1-0cdff29f3e6d";
  13. const sourceServerId = "3cd4f9da-cd79-426c-9d70-75f36e9f6a87";
  14. function createSnapshot(
  15. availableVersion = "3.9.0",
  16. overrides: Partial<SourceServerManagementSnapshot["states"][number]> = {},
  17. ): SourceServerManagementSnapshot {
  18. return {
  19. generation: 1,
  20. profiles: [
  21. {
  22. profileId,
  23. sourceServerId,
  24. transport: "ssh",
  25. target: { kind: "ssh", host: "example.com", username: "alice" },
  26. createdAt: 1,
  27. lifecycleState: "active",
  28. },
  29. ],
  30. servers: [
  31. {
  32. sourceServerId,
  33. displayName: "Build Server",
  34. installState: "installed",
  35. },
  36. ],
  37. workspaceHistory: [],
  38. states: [
  39. {
  40. profileId,
  41. sourceServerId,
  42. state: "online",
  43. updateAvailability: "available",
  44. currentVersion: "3.8.0",
  45. availableVersion,
  46. minimumVersion: "3.8.0",
  47. upgradeTarget: "server",
  48. updatedAt: 1,
  49. ...overrides,
  50. },
  51. ],
  52. failedPathCount: 0,
  53. abandonedPathCount: 0,
  54. migrationCounts: [],
  55. };
  56. }
  57. describe("Source Server update notifications", () => {
  58. it("可选更新在连接和版本变化后均不弹 toast", async () => {
  59. const emitter = new Emitter<SourceServerManagementStateDelta>();
  60. let snapshot = createSnapshot();
  61. const management = {
  62. onDidChangeState: emitter.event,
  63. getSnapshot: vi.fn(async () => snapshot),
  64. } as unknown as ISourceServerManagementService;
  65. const showToast = vi.fn();
  66. const formatMessage = vi.fn(
  67. (id: string, values?: Record<string, string | number>) =>
  68. `${id}:${values?.source ?? ""}:${values?.current ?? ""}:${values?.available ?? ""}`,
  69. );
  70. const controller = createSourceServerUpdateNotificationController({
  71. preferences: createSourceServerUpdatePreferences(null),
  72. management,
  73. formatMessage,
  74. showToast,
  75. });
  76. await new Promise((resolve) => setTimeout(resolve, 0));
  77. expect(showToast).not.toHaveBeenCalled();
  78. snapshot = createSnapshot("3.10.0");
  79. emitter.fire({ generation: 3, state: snapshot.states[0]! });
  80. await new Promise((resolve) => setTimeout(resolve, 0));
  81. expect(showToast).not.toHaveBeenCalled();
  82. controller.dispose();
  83. });
  84. it("断线重连、切换连接和重启通知控制器不重复提示同设备同版本", async () => {
  85. const data = new Map<string, string>();
  86. const storage = {
  87. getItem: (key: string) => data.get(key) ?? null,
  88. setItem: (key: string, value: string) => {
  89. data.set(key, value);
  90. },
  91. };
  92. let snapshot = createSnapshot("4.0", {
  93. state: "needs-upgrade",
  94. updateAvailability: "required",
  95. });
  96. const emitter = new Emitter<SourceServerManagementStateDelta>();
  97. const showToast = vi.fn();
  98. const options = {
  99. management: {
  100. getSnapshot: async () => snapshot,
  101. onDidChangeState: emitter.event,
  102. } as unknown as ISourceServerManagementService,
  103. showToast,
  104. formatMessage: (id: string) => id,
  105. };
  106. const first = createSourceServerUpdateNotificationController({
  107. ...options,
  108. preferences: createSourceServerUpdatePreferences(storage),
  109. });
  110. await vi.waitFor(() => expect(showToast).toHaveBeenCalledOnce());
  111. snapshot = { ...snapshot, states: [] };
  112. emitter.fire({ generation: 2, state: createSnapshot().states[0]! });
  113. await new Promise((resolve) => setTimeout(resolve, 0));
  114. snapshot = createSnapshot("4.0", {
  115. state: "needs-upgrade",
  116. updateAvailability: "required",
  117. profileId: "alternate",
  118. });
  119. emitter.fire({ generation: 3, state: snapshot.states[0]! });
  120. await new Promise((resolve) => setTimeout(resolve, 0));
  121. expect(showToast).toHaveBeenCalledOnce();
  122. first.dispose();
  123. const restarted = createSourceServerUpdateNotificationController({
  124. ...options,
  125. preferences: createSourceServerUpdatePreferences(storage),
  126. });
  127. await new Promise((resolve) => setTimeout(resolve, 0));
  128. expect(showToast).toHaveBeenCalledOnce();
  129. snapshot = createSnapshot("4.1", { state: "needs-upgrade", updateAvailability: "required" });
  130. restarted.refresh();
  131. await vi.waitFor(() => expect(showToast).toHaveBeenCalledTimes(2));
  132. restarted.dispose();
  133. });
  134. it("版本不兼容时在启动提示中直接提供 Server 更新动作", async () => {
  135. const snapshot = createSnapshot("3.9.0", {
  136. state: "needs-upgrade",
  137. updateAvailability: "required",
  138. minimumVersion: "3.9.0",
  139. });
  140. const management = {
  141. onDidChangeState: new Emitter<SourceServerManagementStateDelta>().event,
  142. getSnapshot: vi.fn(async () => snapshot),
  143. updateSource: vi.fn(async () => snapshot),
  144. } as unknown as ISourceServerManagementService;
  145. const showToast = vi.fn();
  146. const controller = createSourceServerUpdateNotificationController({
  147. preferences: createSourceServerUpdatePreferences(null),
  148. management,
  149. formatMessage: (id) => id,
  150. showToast,
  151. });
  152. await vi.waitFor(() => expect(showToast).toHaveBeenCalledOnce());
  153. expect(showToast).toHaveBeenCalledWith(
  154. "sourceServer.updateRequiredToast",
  155. expect.objectContaining({
  156. variant: "source-server-update",
  157. position: "top-center",
  158. actionLabel: "settings.source.updateNow",
  159. onAction: expect.any(Function),
  160. }),
  161. );
  162. const onAction = showToast.mock.calls[0]?.[1]?.onAction as (() => void) | undefined;
  163. onAction?.();
  164. await vi.waitFor(() =>
  165. expect(management.updateSource).toHaveBeenCalledWith({
  166. profileId,
  167. force: false,
  168. }),
  169. );
  170. controller.dispose();
  171. });
  172. });
  173. function createNotificationHarness() {
  174. const emitter = new Emitter<SourceServerManagementStateDelta>();
  175. let snapshot = createSnapshot("3.12.2", {
  176. state: "needs-upgrade",
  177. updateAvailability: "required",
  178. currentVersion: "3.12.1",
  179. });
  180. let connectionTarget: RemoteTarget | null = null;
  181. let nextId = 0;
  182. const active = new Map<number, { message: string; options?: ToastOptions }>();
  183. const showToast = vi.fn((message: string, options?: ToastOptions) => {
  184. const id = ++nextId;
  185. active.set(id, { message, options });
  186. return id;
  187. });
  188. const dismissToast = vi.fn((id: unknown) => active.delete(id as number));
  189. const management = {
  190. onDidChangeState: emitter.event,
  191. getSnapshot: vi.fn(async () => snapshot),
  192. updateSource: vi.fn(async () => snapshot),
  193. } as unknown as ISourceServerManagementService;
  194. const controller = createSourceServerUpdateNotificationController({
  195. preferences: createSourceServerUpdatePreferences(null),
  196. management,
  197. showToast,
  198. dismissToast,
  199. formatMessage: (id) => id,
  200. getConnectionTarget: () => connectionTarget,
  201. });
  202. return {
  203. controller,
  204. management,
  205. active,
  206. showToast,
  207. dismissToast,
  208. publish(next: SourceServerManagementSnapshot) {
  209. snapshot = next;
  210. emitter.fire({ generation: next.generation, state: next.states[0]! });
  211. },
  212. handleTarget(target: RemoteTarget | null) {
  213. connectionTarget = target;
  214. controller.refresh();
  215. },
  216. readSnapshot: () => snapshot,
  217. };
  218. }
  219. describe("Source Server 更新提示与连接向导协调", () => {
  220. it.each(["controller"])("向导不抑制 %s 正常提示", async (kind) => {
  221. const h = createNotificationHarness();
  222. try {
  223. h.handleTarget({ kind: "ssh", host: "example.com", username: "alice" });
  224. h.publish(
  225. createSnapshot(
  226. "3.12.2",
  227. kind === "available"
  228. ? {}
  229. : {
  230. state: "needs-upgrade",
  231. updateAvailability: "required",
  232. upgradeTarget: "controller",
  233. },
  234. ),
  235. );
  236. await vi.waitFor(() => expect(h.active.size).toBe(1));
  237. expect(h.active.get(1)?.message).toBe(
  238. kind === "available"
  239. ? "sourceServer.updateAvailableToast"
  240. : "sourceServer.controllerUpdateAvailableToast",
  241. );
  242. if (kind === "controller") expect(h.active.get(1)?.options?.onAction).toBeUndefined();
  243. } finally {
  244. h.controller.dispose();
  245. }
  246. });
  247. it.each(["updating", "online", "removed"])(
  248. "进入 %s 时撤销旧的立即更新提示",
  249. async (nextState) => {
  250. const h = createNotificationHarness();
  251. try {
  252. await vi.waitFor(() => expect(h.active.size).toBe(1));
  253. const snapshot = h.readSnapshot();
  254. h.publish({
  255. ...snapshot,
  256. states:
  257. nextState === "removed"
  258. ? []
  259. : [
  260. {
  261. ...snapshot.states[0]!,
  262. state: nextState === "updating" ? "updating" : "online",
  263. updateAvailability: nextState === "updating" ? "required" : "none",
  264. },
  265. ],
  266. });
  267. await vi.waitFor(() => expect(h.active.size).toBe(0));
  268. expect(h.dismissToast).toHaveBeenCalledWith(1);
  269. } finally {
  270. h.controller.dispose();
  271. }
  272. },
  273. );
  274. it("向导同步接管目标;同设备多个连接与失败重连均不重复提示", async () => {
  275. const h = createNotificationHarness();
  276. try {
  277. // 在初始 getSnapshot 返回之前接管,覆盖先发布 needs-upgrade、后启动自动更新的时序。
  278. h.handleTarget({ kind: "ssh", host: "example.com", username: "alice" });
  279. const snapshot = h.readSnapshot();
  280. h.publish({
  281. ...snapshot,
  282. profiles: [
  283. ...snapshot.profiles,
  284. {
  285. ...snapshot.profiles[0]!,
  286. profileId: "other",
  287. target: { kind: "ssh", host: "other.example.com", username: "alice" },
  288. },
  289. ],
  290. states: [...snapshot.states, { ...snapshot.states[0]!, profileId: "other" }],
  291. });
  292. await vi.waitFor(() => expect(h.showToast).toHaveBeenCalledOnce());
  293. expect(h.active.size).toBe(1);
  294. h.handleTarget(null);
  295. await new Promise((resolve) => setTimeout(resolve, 0));
  296. expect(h.showToast).toHaveBeenCalledOnce();
  297. h.publish({ ...snapshot, states: [{ ...snapshot.states[0]!, state: "updating" }] });
  298. await vi.waitFor(() => expect(h.active.size).toBe(0));
  299. h.publish(snapshot);
  300. await new Promise((resolve) => setTimeout(resolve, 0));
  301. expect(h.active.size).toBe(0);
  302. expect(h.showToast).toHaveBeenCalledOnce();
  303. } finally {
  304. h.controller.dispose();
  305. }
  306. });
  307. it("接管已有提示后立即撤销,已捕获按钮也不能再提交更新", async () => {
  308. const h = createNotificationHarness();
  309. try {
  310. await vi.waitFor(() => expect(h.active.size).toBe(1));
  311. const action = h.active.get(1)!.options!.onAction!;
  312. h.handleTarget({ kind: "ssh", host: "example.com", username: "alice" });
  313. await vi.waitFor(() => expect(h.active.size).toBe(0));
  314. action();
  315. await new Promise((resolve) => setTimeout(resolve, 0));
  316. expect(h.management.updateSource).not.toHaveBeenCalled();
  317. } finally {
  318. h.controller.dispose();
  319. }
  320. });
  321. it("点击时重新核对 Host 快照,更新中的过期按钮不再次请求更新", async () => {
  322. const h = createNotificationHarness();
  323. try {
  324. await vi.waitFor(() => expect(h.active.size).toBe(1));
  325. const action = h.active.get(1)!.options!.onAction!;
  326. const snapshot = h.readSnapshot();
  327. vi.mocked(h.management.getSnapshot).mockResolvedValue({
  328. ...snapshot,
  329. states: [{ ...snapshot.states[0]!, state: "updating" }],
  330. });
  331. action();
  332. await new Promise((resolve) => setTimeout(resolve, 0));
  333. expect(h.management.updateSource).not.toHaveBeenCalled();
  334. } finally {
  335. h.controller.dispose();
  336. }
  337. });
  338. it("快速重复点击同一提示只提交一次,并在销毁时清理提示", async () => {
  339. const h = createNotificationHarness();
  340. try {
  341. await vi.waitFor(() => expect(h.active.size).toBe(1));
  342. const action = h.active.get(1)!.options!.onAction!;
  343. action();
  344. action();
  345. await vi.waitFor(() => expect(h.management.updateSource).toHaveBeenCalledOnce());
  346. } finally {
  347. h.controller.dispose();
  348. }
  349. expect(h.dismissToast).toHaveBeenCalledWith(1);
  350. });
  351. });
  352. it("开始更新只定位进度,失败 toast 的显式详情动作才打开错误详情", async () => {
  353. const snapshot = createSnapshot("4.0.0", {
  354. state: "needs-upgrade",
  355. updateAvailability: "required",
  356. });
  357. const completion = Promise.withResolvers<SourceServerManagementSnapshot>();
  358. const onProgress = vi.fn();
  359. const onDetails = vi.fn();
  360. const showToast = vi.fn((_message: string, _options?: ToastOptions) => 1);
  361. const controller = createSourceServerUpdateNotificationController({
  362. management: {
  363. getSnapshot: async () => snapshot,
  364. onDidChangeState: new Emitter<SourceServerManagementStateDelta>().event,
  365. updateSource: () => completion.promise,
  366. } as never,
  367. preferences: createSourceServerUpdatePreferences(null),
  368. formatMessage: (id) => id,
  369. showToast,
  370. onProgress,
  371. onDetails,
  372. });
  373. try {
  374. await vi.waitFor(() => expect(showToast).toHaveBeenCalledOnce());
  375. showToast.mock.calls[0]![1]!.onAction!();
  376. await vi.waitFor(() => expect(onProgress).toHaveBeenCalledWith(sourceServerId));
  377. expect(onDetails).not.toHaveBeenCalled();
  378. completion.reject(new Error("update failed"));
  379. await vi.waitFor(() =>
  380. expect(
  381. showToast.mock.calls.some(([message]) => message === "sourceServer.updateFailedToast"),
  382. ).toBe(true),
  383. );
  384. showToast.mock.calls.find(([message]) => message === "sourceServer.updateFailedToast")![1]!
  385. .onAction!();
  386. expect(onDetails).toHaveBeenCalledWith(sourceServerId);
  387. } finally {
  388. controller.dispose();
  389. }
  390. });