offPeakUiPresentation.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { readFileSync } from "node:fs";
  2. import { describe, expect, it } from "vitest";
  3. import {
  4. formatOffPeakRemainingWait,
  5. resolveFailedOffPeakQueueFooter,
  6. resolveOffPeakCreateBlockReason,
  7. resolveLocalizedOffPeakCreateTitle,
  8. resolveOffPeakStatusFooter,
  9. shouldShowOffPeakModelSelectionIssue,
  10. } from "@/settings/offPeakUiPresentation.js";
  11. const remainingWaitMessages: Record<string, string> = {
  12. "offPeak.create.remaining.hoursMinutes": "{hours} 小时 {minutes} 分钟",
  13. "offPeak.create.remaining.hours": "{hours} 小时",
  14. "offPeak.create.remaining.minutes": "{minutes} 分钟",
  15. "offPeak.create.remaining.lessThanMinute": "不到 1 分钟",
  16. };
  17. const remainingWaitIntl = {
  18. formatMessage(
  19. { id }: { id: string },
  20. values?: Record<string, string | number>,
  21. ) {
  22. let message = remainingWaitMessages[id] ?? id;
  23. for (const [key, value] of Object.entries(values ?? {})) {
  24. message = message.replaceAll(`{${key}}`, String(value));
  25. }
  26. return message;
  27. },
  28. };
  29. const offPeakTaskListSource = readFileSync(
  30. new URL("../src/settings/OffPeakTaskList.tsx", import.meta.url),
  31. "utf8",
  32. );
  33. const automationsSectionSource = readFileSync(
  34. new URL("../src/settings/AutomationsSection.tsx", import.meta.url),
  35. "utf8",
  36. );
  37. // 页标题自 docs/dynamic-workflow/launch.md 起就是「自动化 / 工作流」切换本身,30/34 的 Figma 标题层级
  38. // 随之搬到 AutomationsPageTitleSwitch;AutomationsSection 只保留紧凑说明段。
  39. const automationsPageTitleSwitchSource = readFileSync(
  40. new URL("../src/settings/saved-workflows/AutomationsPageTitleSwitch.tsx", import.meta.url),
  41. "utf8",
  42. );
  43. const automationScheduleBadgeSource = readFileSync(
  44. new URL("../src/settings/AutomationScheduleBadge.tsx", import.meta.url),
  45. "utf8",
  46. );
  47. const offPeakEditViewSource = readFileSync(
  48. new URL("../src/settings/OffPeakEditView.tsx", import.meta.url),
  49. "utf8",
  50. );
  51. const stylesSource = readFileSync(
  52. new URL("../src/styles.css", import.meta.url),
  53. "utf8",
  54. );
  55. describe("resolveLocalizedOffPeakCreateTitle", () => {
  56. it("updates an untouched localized default when the locale changes", () => {
  57. expect(
  58. resolveLocalizedOffPeakCreateTitle({
  59. currentTitle: "未命名",
  60. hasInitialTitle: false,
  61. isEditing: false,
  62. nextDefaultTitle: "Untitled",
  63. previousDefaultTitle: "未命名",
  64. titleTouched: false,
  65. }),
  66. ).toBe("Untitled");
  67. });
  68. it.each([
  69. { hasInitialTitle: false, isEditing: false, titleTouched: true },
  70. { hasInitialTitle: true, isEditing: false, titleTouched: false },
  71. { hasInitialTitle: false, isEditing: true, titleTouched: false },
  72. ])("preserves user, template, and persisted titles: %o", (state) => {
  73. expect(
  74. resolveLocalizedOffPeakCreateTitle({
  75. currentTitle: "用户标题",
  76. nextDefaultTitle: "Untitled",
  77. previousDefaultTitle: "未命名",
  78. ...state,
  79. }),
  80. ).toBe("用户标题");
  81. });
  82. });
  83. describe("resolveOffPeakCreateBlockReason", () => {
  84. it.each([
  85. ["idle", undefined, "unavailable"],
  86. ["loading", undefined, "unavailable"],
  87. ["error", undefined, "unavailable"],
  88. ["ready", false, "quota"],
  89. ["ready", true, null],
  90. ] as const)(
  91. "fails closed for availability status %s / %s",
  92. (availabilityStatus, canTakeNumber, expected) => {
  93. expect(
  94. resolveOffPeakCreateBlockReason({
  95. availabilityStatus,
  96. canTakeNumber,
  97. grayEnabled: true,
  98. noPlan: false,
  99. }),
  100. ).toBe(expected);
  101. },
  102. );
  103. it("prioritizes ineligibility and ignores admission when the feature is hidden", () => {
  104. expect(
  105. resolveOffPeakCreateBlockReason({
  106. availabilityStatus: "ready",
  107. canTakeNumber: true,
  108. grayEnabled: true,
  109. noPlan: true,
  110. }),
  111. ).toBe("plan");
  112. expect(
  113. resolveOffPeakCreateBlockReason({
  114. availabilityStatus: "error",
  115. canTakeNumber: undefined,
  116. grayEnabled: true,
  117. noPlan: true,
  118. }),
  119. ).toBe("unavailable");
  120. expect(
  121. resolveOffPeakCreateBlockReason({
  122. availabilityStatus: "error",
  123. canTakeNumber: undefined,
  124. grayEnabled: false,
  125. noPlan: false,
  126. }),
  127. ).toBeNull();
  128. });
  129. });
  130. describe("shouldShowOffPeakModelSelectionIssue", () => {
  131. it.each([
  132. ["queued", true],
  133. ["paused", true],
  134. ["running", true],
  135. ["completed", false],
  136. ["failed", false],
  137. ["cancelled", false],
  138. ] as const)("只对仍可能执行的 %s 任务显示修复提示", (status, expected) => {
  139. expect(shouldShowOffPeakModelSelectionIssue(status)).toBe(expected);
  140. });
  141. });
  142. describe("formatOffPeakRemainingWait", () => {
  143. const now = 1_000_000;
  144. it.each([
  145. [125 * 60_000, "2 小时 5 分钟"],
  146. [120 * 60_000, "2 小时"],
  147. [42 * 60_000, "42 分钟"],
  148. ])(
  149. "formats a %i ms wait with hour/minute granularity",
  150. (waitMs, expected) => {
  151. expect(
  152. formatOffPeakRemainingWait(now + waitMs, now, remainingWaitIntl),
  153. ).toBe(expected);
  154. },
  155. );
  156. it("rounds a positive partial minute up and avoids calendar dates", () => {
  157. const label = formatOffPeakRemainingWait(
  158. now + 60_001,
  159. now,
  160. remainingWaitIntl,
  161. );
  162. expect(label).toBe("2 分钟");
  163. expect(label).not.toMatch(/[年月日]/);
  164. });
  165. it("uses a sub-minute label once the recovery point is reached", () => {
  166. expect(formatOffPeakRemainingWait(now, now, remainingWaitIntl)).toBe(
  167. "不到 1 分钟",
  168. );
  169. });
  170. });
  171. describe("idle-time quota tooltip wiring", () => {
  172. it("uses the remote remaining-wait implementation and advances it by minute", () => {
  173. expect(automationsSectionSource).toContain(
  174. "time: formatOffPeakRemainingWait(",
  175. );
  176. expect(automationsSectionSource).toContain(
  177. "const remainderMs = remainingMs % minuteMs;",
  178. );
  179. expect(automationsSectionSource).not.toContain(
  180. "new Intl.DateTimeFormat(locale",
  181. );
  182. });
  183. });
  184. describe("resolveOffPeakStatusFooter", () => {
  185. it("uses pause for paused tasks even when a queue position is present", () => {
  186. expect(
  187. resolveOffPeakStatusFooter({ status: "paused", queuePosition: 1 }),
  188. ).toMatchObject({
  189. icon: "pause",
  190. className: "text-idle-task",
  191. labelId: "offPeak.badge.pausedPosition",
  192. });
  193. });
  194. it("keeps moon for queued tasks and warning for failures", () => {
  195. expect(
  196. resolveOffPeakStatusFooter({ status: "queued", queuePosition: 2 }).icon,
  197. ).toBe("moon");
  198. expect(resolveOffPeakStatusFooter({ status: "failed" }).icon).toBe(
  199. "warning",
  200. );
  201. });
  202. });
  203. describe("resolveFailedOffPeakQueueFooter", () => {
  204. it("retains a failed task's queue position as a secondary status", () => {
  205. expect(
  206. resolveFailedOffPeakQueueFooter({ status: "failed", queuePosition: 212 }),
  207. ).toMatchObject({
  208. icon: "moon",
  209. className: "text-idle-task",
  210. labelId: "offPeak.badge.queuePosition",
  211. labelValues: { position: "212" },
  212. });
  213. });
  214. it("does not add a secondary status without both failure and a queue position", () => {
  215. expect(resolveFailedOffPeakQueueFooter({ status: "failed" })).toBeNull();
  216. expect(
  217. resolveFailedOffPeakQueueFooter({ status: "queued", queuePosition: 212 }),
  218. ).toBeNull();
  219. });
  220. });
  221. describe("idle-time and scheduled tag colors", () => {
  222. it("uses the Figma purple semantic tokens for idle-time queue tags", () => {
  223. expect(offPeakTaskListSource).toContain(
  224. "bg-idle-task-surface py-0.5 pl-1 pr-2 text-idle-task",
  225. );
  226. expect(offPeakTaskListSource).not.toContain("bg-brand/15");
  227. expect(stylesSource).toContain("--color-idle-task: #9e77ed;");
  228. expect(stylesSource).toContain("--color-idle-task-surface: #f5f3ff;");
  229. expect(stylesSource).toContain("--color-idle-task: #7b5ce5;");
  230. expect(stylesSource).toContain("--color-idle-task-surface: #160d38;");
  231. });
  232. it("keeps scheduled task tags on the green success semantics", () => {
  233. expect(automationScheduleBadgeSource).toContain("bg-success/10");
  234. expect(automationScheduleBadgeSource).toContain("text-success");
  235. expect(automationScheduleBadgeSource).not.toContain("text-idle-task");
  236. });
  237. });
  238. describe("off-peak pause presentation", () => {
  239. it("shows the Pause queue hint and performs the action without confirmation", () => {
  240. const menuHintStart = offPeakTaskListSource.indexOf("function OffPeakMenuHint");
  241. const menuHintEnd = offPeakTaskListSource.indexOf(
  242. "const STATUS_ICON",
  243. menuHintStart,
  244. );
  245. const menuHintSource = offPeakTaskListSource.slice(menuHintStart, menuHintEnd);
  246. const pauseBlockStart = offPeakTaskListSource.indexOf("data-testid={TID_OFFPEAK_ACTION_PAUSE}");
  247. const pauseBlockEnd = offPeakTaskListSource.indexOf(
  248. 'task.status === "paused"',
  249. pauseBlockStart,
  250. );
  251. const pauseBlock = offPeakTaskListSource.slice(
  252. pauseBlockStart,
  253. pauseBlockEnd,
  254. );
  255. expect(menuHintStart).toBeGreaterThanOrEqual(0);
  256. expect(menuHintEnd).toBeGreaterThan(menuHintStart);
  257. // 修复原因:提示定位逻辑已抽到 OffPeakMenuHint,调用点不再直接包含底层 Tooltip 名称。
  258. expect(menuHintSource).toContain("<ControlHintTooltip");
  259. expect(pauseBlockStart).toBeGreaterThanOrEqual(0);
  260. expect(pauseBlockEnd).toBeGreaterThan(pauseBlockStart);
  261. expect(pauseBlock).toContain("<OffPeakMenuHint");
  262. expect(pauseBlock).toContain('id: "offPeak.action.pauseHint"');
  263. expect(automationsSectionSource).not.toContain('id: "offPeak.pause.title"');
  264. expect(automationsSectionSource).not.toContain("handleOffPeakPause");
  265. expect(
  266. automationsSectionSource.match(
  267. /onPause=\{\(task\) =>\s*void offPeakPause\(\s*task\.offPeakTaskId,\s*offPeakTaskService,?\s*\)\s*\}/g,
  268. ),
  269. ).toHaveLength(2);
  270. });
  271. });
  272. describe("off-peak permission recommendation", () => {
  273. it("uses a neutral info toast instead of warning semantics", () => {
  274. const hintStart = offPeakEditViewSource.indexOf(
  275. 'id: "offPeak.form.fullAccessHint"',
  276. );
  277. const hintEnd = offPeakEditViewSource.indexOf("});", hintStart);
  278. const hintToast = offPeakEditViewSource.slice(hintStart, hintEnd);
  279. expect(hintStart).toBeGreaterThanOrEqual(0);
  280. expect(hintEnd).toBeGreaterThan(hintStart);
  281. expect(hintToast).toContain('variant: "info"');
  282. expect(hintToast).not.toContain('variant: "warning"');
  283. expect(hintToast).toContain('position: "top-center"');
  284. });
  285. it("centers automation upgrade and running toasts", () => {
  286. const topCenterToastCount = automationsSectionSource.match(
  287. /position: "top-center"/g,
  288. )?.length;
  289. expect(topCenterToastCount).toBe(2);
  290. expect(automationsSectionSource).toContain(
  291. 'anchorId: AUTOMATIONS_TOAST_ANCHOR_ID',
  292. );
  293. });
  294. });
  295. describe("off-peak terminal status presentation", () => {
  296. it("dims completed cards while preserving hover and more-actions feedback", () => {
  297. expect(resolveOffPeakStatusFooter({ status: "completed" })).toMatchObject({
  298. icon: "success",
  299. className: "text-foreground-subtle",
  300. labelId: "offPeak.status.completed",
  301. });
  302. expect(offPeakTaskListSource).toMatch(
  303. /task\.status === "completed"\s*\?\s*"opacity-60 hover:bg-hover"\s*:\s*"hover:bg-hover"/,
  304. );
  305. const menuTriggerStart = offPeakTaskListSource.indexOf(
  306. "data-testid={TID_OFFPEAK_CARD_MENU}",
  307. );
  308. const menuTriggerEnd = offPeakTaskListSource.indexOf(
  309. "</button>",
  310. menuTriggerStart,
  311. );
  312. const menuTriggerSource = offPeakTaskListSource.slice(
  313. menuTriggerStart,
  314. menuTriggerEnd,
  315. );
  316. expect(menuTriggerStart).toBeGreaterThanOrEqual(0);
  317. expect(menuTriggerSource).toContain("disabled={busy}");
  318. expect(menuTriggerSource).not.toContain('task.status === "completed"');
  319. expect(menuTriggerSource).not.toContain("pointer-events-none");
  320. });
  321. it("uses the shared Lucide completed icon", () => {
  322. expect(offPeakTaskListSource).toMatch(
  323. /import\s+\{[^}]*CircleCheck[^}]*\}\s+from\s+"lucide-react"/,
  324. );
  325. expect(offPeakTaskListSource).toContain("success: CircleCheck");
  326. expect(offPeakTaskListSource).not.toContain("off-peak-completed-check.svg");
  327. expect(offPeakTaskListSource).not.toContain("maskImage");
  328. });
  329. it("does not append the file-change count to task-card footers", () => {
  330. expect(offPeakTaskListSource).not.toContain("task.filesChanged");
  331. expect(offPeakTaskListSource).not.toContain("offPeak.filesChanged");
  332. });
  333. });
  334. describe("Automations list fidelity", () => {
  335. it("keeps the empty-state order while moving keep-awake before populated lists", () => {
  336. // D47:keep-awake 是全局开关,两个 tab 都展示——列表态在任务卡前、空态在大空卡后。
  337. expect(automationsSectionSource).toContain("{hasAnyTasks ? (");
  338. expect(automationsSectionSource).toContain("{!hasAnyTasks ? (");
  339. });
  340. it("uses the Figma page-title scale and a compact description", () => {
  341. expect(automationsPageTitleSwitchSource).toContain(
  342. "text-[30px] font-medium leading-[34px] tracking-[0.114px]",
  343. );
  344. expect(automationsSectionSource).toContain(
  345. '<p className="text-ui-base leading-5 text-foreground-subtlest">',
  346. );
  347. });
  348. });