remoteI18nPlaceholderValues.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. // @vitest-environment jsdom
  2. import { resolveRemoteConnectionPresentation } from "@/lib/remoteConnectionPresentation.js";
  3. import { createElement } from "react";
  4. import { cleanup, render, screen } from "@testing-library/react";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { Emitter } from "@zcode/rpc";
  7. import type { SourceServerManagementSnapshot } from "@zcode/shared";
  8. import zhCN from "@/i18n/locales/zh-CN.js";
  9. import { SourceServerManagementPanel } from "@/settings/SourceServerManagementPanel.js";
  10. /**
  11. * §9 门禁 1:本轮触达的带占位符 i18n key 必须有「渲染含实值」断言,防 {time} 类回归。
  12. * mock 复刻 IntlProvider.createIntl 的真实语义(真实 zh-CN 消息 + {key} replaceAll 插值),
  13. * 断言渲染结果含具体值且不残留任何 `{placeholder}` 字面量。
  14. */
  15. function formatZhMessage({ id }: { id: string }, values?: Record<string, string | number>): string {
  16. let message = zhCN[id] ?? id;
  17. if (values) {
  18. for (const [key, value] of Object.entries(values)) {
  19. message = message.replaceAll(`{${key}}`, String(value));
  20. }
  21. }
  22. return message;
  23. }
  24. vi.mock("@/i18n/IntlProvider.js", () => ({
  25. useZCodeIntl: () => ({
  26. intl: { formatMessage: formatZhMessage },
  27. locale: "zh-CN",
  28. }),
  29. }));
  30. vi.mock("@/hooks/useConfirmDialog.js", () => ({
  31. useConfirmDialog: () => vi.fn(async () => true),
  32. }));
  33. afterEach(() => {
  34. cleanup();
  35. vi.clearAllMocks();
  36. });
  37. const sourceServerId = "3cd4f9da-cd79-426c-9d70-75f36e9f6a87";
  38. const profileId = "17ef20b3-622d-4a53-98c1-0cdff29f3e6d";
  39. function baseSnapshot(
  40. overrides: Partial<SourceServerManagementSnapshot>,
  41. ): SourceServerManagementSnapshot {
  42. return {
  43. generation: 1,
  44. profiles: [
  45. {
  46. profileId,
  47. transport: "docker",
  48. target: { kind: "docker", container: "dev" },
  49. sourceServerId,
  50. createdAt: 1,
  51. },
  52. ],
  53. servers: [
  54. {
  55. sourceServerId,
  56. displayName: "devbox",
  57. installState: "installed",
  58. lastSeenVersion: "3.8.1",
  59. },
  60. ],
  61. workspaceHistory: [],
  62. states: [],
  63. failedPathCount: 0,
  64. abandonedPathCount: 0,
  65. migrationCounts: [],
  66. ...overrides,
  67. } as SourceServerManagementSnapshot;
  68. }
  69. function renderPanel(snapshot: SourceServerManagementSnapshot) {
  70. return render(
  71. createElement(SourceServerManagementPanel, {
  72. management: {
  73. getSnapshot: vi.fn(async () => snapshot),
  74. onDidChangeState: new Emitter().event,
  75. onDidChangeDirectory: new Emitter().event,
  76. } as never,
  77. }),
  78. );
  79. }
  80. function expectNoRawPlaceholders(container: HTMLElement) {
  81. expect(container.textContent ?? "").not.toMatch(/\{\w+\}/u);
  82. }
  83. describe("SourceServerManagementPanel placeholder values", () => {
  84. it("renders version, offline relative time and at most three deduplicated project names", async () => {
  85. const identityA = `remote:server:${sourceServerId}:/srv/a`;
  86. const identityE = `remote:server:${sourceServerId}:/srv/c-alt`;
  87. const snapshot = baseSnapshot({
  88. servers: [
  89. {
  90. sourceServerId,
  91. displayName: "devbox",
  92. installState: "installed",
  93. lastSeenVersion: "3.8.1",
  94. lastOnlineAt: Date.now() - 16.5 * 60_000,
  95. },
  96. ],
  97. // §9 门禁 5:项目数按 workspaceKey 去重——同 identity 合并(A/B)、
  98. // 缺 identity 按路径回退合并(C/D)、同路径不同 identity 不合并(E)→ 共 3 个项目。
  99. workspaceHistory: [
  100. {
  101. workspacePath: "/srv/a",
  102. workspaceIdentity: identityA,
  103. profileId,
  104. sourceServerId,
  105. lastOpenedAt: 1,
  106. },
  107. {
  108. workspacePath: "/srv/b",
  109. workspaceIdentity: identityA,
  110. profileId,
  111. sourceServerId,
  112. lastOpenedAt: 2,
  113. },
  114. {
  115. workspacePath: "/srv/c",
  116. profileId,
  117. sourceServerId,
  118. lastOpenedAt: 3,
  119. },
  120. {
  121. workspacePath: "/srv/c",
  122. profileId,
  123. sourceServerId,
  124. lastOpenedAt: 4,
  125. },
  126. {
  127. workspacePath: "/srv/c",
  128. workspaceIdentity: identityE,
  129. profileId,
  130. sourceServerId,
  131. lastOpenedAt: 5,
  132. },
  133. ],
  134. });
  135. const { container } = renderPanel(snapshot);
  136. expect(await screen.findByRole("button", { name: "b" })).toBeTruthy();
  137. expect(container.querySelectorAll("[data-device-project]")).toHaveLength(3);
  138. expect(screen.queryByText("+2")).toBeNull();
  139. expect(screen.queryByText("显示全部 (3)")).toBeNull();
  140. const connection = container.querySelector("[data-device-connection]")?.textContent ?? "";
  141. expect(connection).toContain("v3.8.1");
  142. expect(connection).toContain("最近在线 16 分钟前");
  143. expectNoRawPlaceholders(container);
  144. });
  145. it("renders a single connection and empty project count without raw placeholders", async () => {
  146. const snapshot = baseSnapshot({
  147. states: [
  148. {
  149. profileId,
  150. sourceServerId,
  151. state: "online",
  152. updateAvailability: "none",
  153. updatedAt: 10,
  154. },
  155. ],
  156. });
  157. const { container } = renderPanel(snapshot);
  158. expect(await screen.findByText("0 个项目")).toBeTruthy();
  159. // 单条连接时“当前 / 默认”没有区分意义,不显示。
  160. expect(screen.queryByText("当前")).toBeNull();
  161. expectNoRawPlaceholders(container);
  162. });
  163. it("interpolates the available version banner and the current/minimum details", async () => {
  164. const snapshot = baseSnapshot({
  165. states: [
  166. {
  167. profileId,
  168. sourceServerId,
  169. state: "online",
  170. updateAvailability: "available",
  171. currentVersion: "3.8.1",
  172. availableVersion: "3.8.2",
  173. minimumVersion: "3.7.0",
  174. updatedAt: 10,
  175. },
  176. ],
  177. });
  178. const { container } = renderPanel(snapshot);
  179. expect(await screen.findByText("可更新到 v3.8.2")).toBeTruthy();
  180. expect(
  181. screen.getByText("当前 v3.8.1 · 最低兼容 v3.7.0 · 更新期间远程任务会短暂中断"),
  182. ).toBeTruthy();
  183. expectNoRawPlaceholders(container);
  184. });
  185. });
  186. describe("remote recovery projection payload", () => {
  187. it("passes attempt and limit in the recovery projection payload", async () => {
  188. const presentation = resolveRemoteConnectionPresentation({
  189. state: "retrying",
  190. recoveryAttempt: 2,
  191. recoveryLimit: 3,
  192. });
  193. expect(presentation.recovery).toEqual({
  194. messageId: "workspaceSidebar.recoveringAutomaticAttempt",
  195. shortMessageId: "workspaceSidebar.recoveringAutomaticShort",
  196. values: { attempt: 2, limit: 3 },
  197. });
  198. });
  199. });