useComposerAttachmentsUpload.test.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. import { act, createElement, type DragEvent } from "react";
  2. import { createRoot } from "react-dom/client";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import type { IPromptAttachmentTransferService } from "@zcode/services";
  5. import type { PromptAttachmentTransferProgress } from "@zcode/services";
  6. import {
  7. OversizedInlineImageAttachmentError,
  8. OversizedInlineVideoAttachmentError,
  9. } from "@/lib/chatAttachments.js";
  10. import { useComposerAttachmentUploadStore } from "@/store/composerAttachmentUploadStore.js";
  11. import {
  12. COMPOSER_ATTACHMENT_COMPLETE_VISIBLE_MS,
  13. isTransientAttachmentUploadError,
  14. useComposerAttachments,
  15. type ComposerAttachmentsApi,
  16. } from "@/v4/composer/useComposerAttachments.js";
  17. const mocks = vi.hoisted(() => ({
  18. platform: {
  19. canSelectFilePath: true,
  20. createTempTextAttachment: vi.fn(),
  21. getPathForFile: vi.fn(),
  22. selectFiles: vi.fn(async () => [] as string[]),
  23. },
  24. service: null as IPromptAttachmentTransferService | null,
  25. toast: vi.fn(),
  26. }));
  27. vi.mock("@/components/ui/toast.js", () => ({ toast: mocks.toast }));
  28. vi.mock("@/hooks/usePlatform.js", () => ({
  29. usePlatform: () => mocks.platform,
  30. }));
  31. vi.mock("@/hooks/useServices.js", () => ({
  32. useServices: () => ({ promptAttachmentTransferService: mocks.service }),
  33. }));
  34. vi.mock("@/i18n/IntlProvider.js", () => ({
  35. useZCodeIntl: () => ({
  36. intl: {
  37. formatMessage: ({ id }: { id: string }) => id,
  38. },
  39. }),
  40. }));
  41. interface Deferred<T> {
  42. promise: Promise<T>;
  43. reject(error: unknown): void;
  44. resolve(value: T): void;
  45. }
  46. function deferred<T>(): Deferred<T> {
  47. let resolve!: (value: T) => void;
  48. let reject!: (error: unknown) => void;
  49. const promise = new Promise<T>((onResolve, onReject) => {
  50. resolve = onResolve;
  51. reject = onReject;
  52. });
  53. return { promise, reject, resolve };
  54. }
  55. function createTransferService() {
  56. const listeners = new Map<string, Set<(event: PromptAttachmentTransferProgress) => void>>();
  57. const stage = vi.fn<IPromptAttachmentTransferService["stage"]>();
  58. const service: IPromptAttachmentTransferService = {
  59. adopt: vi.fn(async () => {}),
  60. cancel: vi.fn(async () => {}),
  61. cleanup: vi.fn(async () => {}),
  62. onDynamicProgress: (operationId) => (listener) => {
  63. const operationListeners = listeners.get(operationId) ?? new Set();
  64. operationListeners.add(listener);
  65. listeners.set(operationId, operationListeners);
  66. return { dispose: () => operationListeners.delete(listener) };
  67. },
  68. stage,
  69. };
  70. return {
  71. fire(operationId: string, event: Omit<PromptAttachmentTransferProgress, "operationId">) {
  72. for (const listener of listeners.get(operationId) ?? []) {
  73. listener({ operationId, ...event });
  74. }
  75. },
  76. service,
  77. stage,
  78. };
  79. }
  80. function createMinimalElement(ownerDocument: Document) {
  81. const element = {
  82. addEventListener: () => {},
  83. appendChild: (child: Node) => {
  84. Object.assign(child, { parentNode: element });
  85. element.childNodes.push(child);
  86. return child;
  87. },
  88. attributes: new Map<string, string>(),
  89. childNodes: [] as Node[],
  90. getAttribute: (name: string) => element.attributes.get(name) ?? null,
  91. insertBefore: (child: Node) => element.appendChild(child),
  92. nodeName: "DIV",
  93. nodeType: 1,
  94. ownerDocument,
  95. parentNode: null,
  96. removeAttribute: (name: string) => element.attributes.delete(name),
  97. removeChild: (child: Node) => {
  98. element.childNodes = element.childNodes.filter((item) => item !== child);
  99. return child;
  100. },
  101. removeEventListener: () => {},
  102. setAttribute: (name: string, value: string) => element.attributes.set(name, value),
  103. style: {},
  104. tagName: "DIV",
  105. };
  106. return element as unknown as Element;
  107. }
  108. function installMinimalDom() {
  109. const windowTarget = new EventTarget();
  110. const documentTarget = new EventTarget();
  111. const documentMock = {
  112. addEventListener: documentTarget.addEventListener.bind(documentTarget),
  113. createComment: () => ({ nodeType: 8, parentNode: null }),
  114. createElement: () => createMinimalElement(documentMock as unknown as Document),
  115. createTextNode: (nodeValue: string) => ({ nodeType: 3, nodeValue, parentNode: null }),
  116. defaultView: null as unknown,
  117. nodeType: 9,
  118. removeEventListener: documentTarget.removeEventListener.bind(documentTarget),
  119. };
  120. const windowMock = {
  121. addEventListener: windowTarget.addEventListener.bind(windowTarget),
  122. clearTimeout,
  123. document: documentMock,
  124. HTMLIFrameElement: function HTMLIFrameElement() {},
  125. HTMLElement: function HTMLElement() {},
  126. Node: function Node() {},
  127. removeEventListener: windowTarget.removeEventListener.bind(windowTarget),
  128. setTimeout,
  129. };
  130. documentMock.defaultView = windowMock;
  131. Object.defineProperty(globalThis, "document", { configurable: true, value: documentMock });
  132. Object.defineProperty(globalThis, "window", { configurable: true, value: windowMock });
  133. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  134. configurable: true,
  135. value: true,
  136. });
  137. return createMinimalElement(documentMock as unknown as Document);
  138. }
  139. interface ProbeOptions {
  140. attachmentSessionId: string | null;
  141. localDesktop?: boolean;
  142. onRuntimeRestart?: (listener: () => void) => () => void;
  143. onRuntimeLifecycle?: (listener: (state: "available" | "unavailable") => void) => () => void;
  144. remoteSessionId?: string | null;
  145. scopeId: string;
  146. workspaceIdentity?: string;
  147. }
  148. let latestApi: ComposerAttachmentsApi | null = null;
  149. function Probe(options: ProbeOptions) {
  150. const remoteSessionId = options.localDesktop
  151. ? undefined
  152. : options.remoteSessionId === null
  153. ? undefined
  154. : (options.remoteSessionId ?? "remote-session-1");
  155. latestApi = useComposerAttachments({
  156. attachmentPut: vi.fn(),
  157. attachmentSessionId: options.attachmentSessionId,
  158. onRuntimeRestart: options.onRuntimeRestart,
  159. onRuntimeLifecycle: options.onRuntimeLifecycle,
  160. remoteSessionId,
  161. scopeId: options.scopeId,
  162. workspaceIdentity: options.localDesktop
  163. ? undefined
  164. : (options.workspaceIdentity ?? "remote:ssh:host:22:user:/workspace"),
  165. workspacePath: "/workspace",
  166. });
  167. return null;
  168. }
  169. function renderProbe(options: ProbeOptions) {
  170. const root = createRoot(installMinimalDom());
  171. act(() => root.render(createElement(Probe, options)));
  172. return {
  173. rerender(next: ProbeOptions) {
  174. act(() => root.render(createElement(Probe, next)));
  175. },
  176. root,
  177. };
  178. }
  179. async function addPaths(paths: string[]) {
  180. mocks.platform.selectFiles.mockResolvedValueOnce(paths);
  181. act(() => latestApi?.openAttachmentPicker());
  182. await vi.waitFor(() => expect(latestApi?.attachments).toHaveLength(paths.length));
  183. }
  184. function resultFor(operationId: string) {
  185. return {
  186. bytes: 100,
  187. operationId,
  188. ref: `/remote/${operationId}`,
  189. staged: true,
  190. };
  191. }
  192. beforeEach(() => {
  193. latestApi = null;
  194. mocks.platform.createTempTextAttachment.mockReset();
  195. mocks.platform.getPathForFile.mockReset();
  196. mocks.platform.selectFiles.mockReset();
  197. mocks.toast.mockClear();
  198. useComposerAttachmentUploadStore.setState({ scopes: {} });
  199. });
  200. afterEach(async () => {
  201. vi.useRealTimers();
  202. useComposerAttachmentUploadStore.setState({ scopes: {} });
  203. // React 19 的 scheduler 可能在 root.unmount() 后仍留有一个 setImmediate 回调。
  204. // 必须先让它在 DOM shim 仍存在时排空,否则测试结束删除 window 后会产生 unhandled error。
  205. await new Promise<void>((resolve) => setImmediate(resolve));
  206. delete (globalThis as { document?: unknown }).document;
  207. delete (globalThis as { window?: unknown }).window;
  208. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  209. });
  210. describe("useComposerAttachments eager upload", () => {
  211. it("restores draft files into the target owner without reusing source upload references", async () => {
  212. mocks.service = createTransferService().service;
  213. const { root } = renderProbe({ attachmentSessionId: null, scopeId: "new-project" });
  214. const file = new File(["content"], "draft.txt", { type: "text/plain" });
  215. act(() =>
  216. latestApi?.restoreDraftAttachments([
  217. {
  218. id: "source-id",
  219. file,
  220. filename: file.name,
  221. mimeType: file.type,
  222. sizeBytes: file.size,
  223. attachmentRef: { ref: "/old-session/upload" },
  224. uploadStatus: "ready",
  225. } as never,
  226. ]),
  227. );
  228. expect(latestApi?.attachments).toHaveLength(1);
  229. expect(latestApi?.attachments[0]).toMatchObject({
  230. file,
  231. filename: "draft.txt",
  232. uploadStatus: "waitingSession",
  233. });
  234. expect(latestApi?.attachments[0]?.id).not.toBe("source-id");
  235. expect(latestApi?.attachments[0]?.attachmentRef).toBeUndefined();
  236. act(() => root.unmount());
  237. });
  238. it("满 8 个后每次粘贴都提示,且点击添加不再打开文件选择器", async () => {
  239. mocks.service = createTransferService().service;
  240. const { root } = renderProbe({
  241. attachmentSessionId: null,
  242. scopeId: "full-limit",
  243. localDesktop: true,
  244. });
  245. mocks.platform.selectFiles.mockResolvedValueOnce(
  246. Array.from({ length: 8 }, (_, index) => `/workspace/${index}.txt`),
  247. );
  248. await act(async () => latestApi?.openAttachmentPicker());
  249. mocks.platform.selectFiles.mockClear();
  250. act(() => latestApi?.openAttachmentPicker());
  251. expect(mocks.platform.selectFiles).not.toHaveBeenCalled();
  252. expect(mocks.toast).toHaveBeenCalledWith(
  253. "chat.attachments.maxFiles",
  254. expect.objectContaining({ variant: "warning" }),
  255. );
  256. for (let index = 0; index < 2; index++) {
  257. act(() =>
  258. latestApi?.handlePaste({
  259. clipboardData: {
  260. files: [new File(["extra"], "extra.txt")],
  261. types: ["Files"],
  262. getData: () => "",
  263. } as unknown as DataTransfer,
  264. preventDefault: vi.fn(),
  265. }),
  266. );
  267. }
  268. expect(mocks.toast).toHaveBeenCalledTimes(3);
  269. expect(latestApi?.attachments).toHaveLength(8);
  270. expect(latestApi?.attachments.some((item) => item.filename === "extra.txt")).toBe(false);
  271. act(() => latestApi?.removeAttachment(latestApi.attachments[0]!.id));
  272. mocks.platform.selectFiles.mockResolvedValueOnce(["/workspace/replacement.txt"]);
  273. await act(async () => latestApi?.openAttachmentPicker());
  274. await vi.waitFor(() => expect(latestApi?.attachments).toHaveLength(8));
  275. expect(mocks.platform.selectFiles).toHaveBeenCalledTimes(1);
  276. expect(mocks.toast).toHaveBeenCalledTimes(3);
  277. act(() => root.unmount());
  278. });
  279. it("剩 1 个名额时选择 2 个,只接收第 1 个并弹出超限提示", async () => {
  280. mocks.service = createTransferService().service;
  281. const { root } = renderProbe({
  282. attachmentSessionId: null,
  283. scopeId: "partial-limit",
  284. localDesktop: true,
  285. });
  286. mocks.platform.selectFiles.mockResolvedValueOnce(
  287. Array.from({ length: 7 }, (_, index) => `/workspace/${index}.txt`),
  288. );
  289. await act(async () => latestApi?.openAttachmentPicker());
  290. mocks.platform.selectFiles.mockResolvedValueOnce([
  291. "/workspace/accepted.txt",
  292. "/workspace/rejected.txt",
  293. ]);
  294. await act(async () => latestApi?.openAttachmentPicker());
  295. await vi.waitFor(() => expect(latestApi?.attachments).toHaveLength(8));
  296. expect(latestApi?.attachments.at(-1)?.filename).toBe("accepted.txt");
  297. expect(mocks.toast).toHaveBeenCalledTimes(1);
  298. expect(mocks.toast).toHaveBeenCalledWith(
  299. "chat.attachments.maxFiles",
  300. expect.objectContaining({ variant: "warning" }),
  301. );
  302. act(() => root.unmount());
  303. });
  304. it("只把 video inline 超限视为不可重试,不改变 image 的既有重试判定", () => {
  305. const options = { filename: "media.bin", maxSizeBytes: 1, sizeBytes: 2 };
  306. expect(isTransientAttachmentUploadError(new OversizedInlineVideoAttachmentError(options))).toBe(
  307. false,
  308. );
  309. expect(isTransientAttachmentUploadError(new OversizedInlineImageAttachmentError(options))).toBe(
  310. true,
  311. );
  312. });
  313. it("Excel 多表示剪贴板优先保留文本,不把合成 PNG 加为附件", () => {
  314. const transfer = createTransferService();
  315. mocks.service = transfer.service;
  316. const { root } = renderProbe({ attachmentSessionId: null, scopeId: "excel-paste" });
  317. const preventDefault = vi.fn();
  318. const stopPropagation = vi.fn();
  319. const image = new File(["preview"], "image.png", { type: "image/png" });
  320. act(() =>
  321. latestApi?.handlePaste({
  322. clipboardData: {
  323. files: [image],
  324. getData: (type: string) => {
  325. if (type === "text/plain") return "姓名\t数量\n苹果\t2";
  326. if (type === "text/html") {
  327. return '<html xmlns:x="urn:schemas-microsoft-com:office:excel"><table></table>';
  328. }
  329. return "";
  330. },
  331. types: ["text/plain", "text/html", "Files"],
  332. } as unknown as DataTransfer,
  333. preventDefault,
  334. stopPropagation,
  335. }),
  336. );
  337. expect(preventDefault).not.toHaveBeenCalled();
  338. expect(stopPropagation).not.toHaveBeenCalled();
  339. expect(latestApi?.attachments).toEqual([]);
  340. act(() => root.unmount());
  341. });
  342. it("Excel 超长文本仍转 clipboard-text 附件,不退回合成 PNG", async () => {
  343. const transfer = createTransferService();
  344. mocks.service = transfer.service;
  345. mocks.platform.createTempTextAttachment.mockResolvedValue({
  346. filename: "pasted-text.txt",
  347. localPath: "/tmp/pasted-text.txt",
  348. mimeType: "text/plain",
  349. sizeBytes: 15_361,
  350. });
  351. const { root } = renderProbe({ attachmentSessionId: null, scopeId: "excel-long-paste" });
  352. const preventDefault = vi.fn();
  353. const text = `${"A".repeat(15_359)}\tB`;
  354. act(() =>
  355. latestApi?.handlePaste({
  356. clipboardData: {
  357. files: [new File(["preview"], "image.png", { type: "image/png" })],
  358. getData: (type: string) => (type === "text/plain" ? text : ""),
  359. types: ["text/plain", "Files"],
  360. } as unknown as DataTransfer,
  361. preventDefault,
  362. stopPropagation: vi.fn(),
  363. }),
  364. );
  365. await vi.waitFor(() => expect(latestApi?.attachments).toHaveLength(1));
  366. expect(preventDefault).toHaveBeenCalledOnce();
  367. expect(latestApi?.attachments[0]).toMatchObject({
  368. filename: "pasted-text.txt",
  369. mimeType: "text/plain",
  370. sourceKind: "clipboard-text",
  371. });
  372. act(() => root.unmount());
  373. });
  374. it("截图和真实 xlsx 文件仍按附件处理", () => {
  375. const transfer = createTransferService();
  376. mocks.service = transfer.service;
  377. const { root } = renderProbe({ attachmentSessionId: null, scopeId: "real-file-paste" });
  378. const screenshotPreventDefault = vi.fn();
  379. act(() =>
  380. latestApi?.handlePaste({
  381. clipboardData: {
  382. files: [new File(["png"], "screenshot.png", { type: "image/png" })],
  383. getData: () => "",
  384. types: ["Files"],
  385. } as unknown as DataTransfer,
  386. preventDefault: screenshotPreventDefault,
  387. stopPropagation: vi.fn(),
  388. }),
  389. );
  390. expect(screenshotPreventDefault).toHaveBeenCalledOnce();
  391. expect(latestApi?.attachments.map((item) => item.filename)).toEqual(["screenshot.png"]);
  392. act(() => latestApi?.clearAttachments());
  393. const xlsxPreventDefault = vi.fn();
  394. act(() =>
  395. latestApi?.handlePaste({
  396. clipboardData: {
  397. files: [
  398. new File(["xlsx"], "book.xlsx", {
  399. type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  400. }),
  401. ],
  402. getData: (type: string) => (type === "text/plain" ? "/tmp/book.xlsx" : ""),
  403. types: ["text/plain", "Files"],
  404. } as unknown as DataTransfer,
  405. preventDefault: xlsxPreventDefault,
  406. stopPropagation: vi.fn(),
  407. }),
  408. );
  409. expect(xlsxPreventDefault).toHaveBeenCalledOnce();
  410. expect(latestApi?.attachments.map((item) => item.filename)).toEqual(["book.xlsx"]);
  411. act(() => root.unmount());
  412. });
  413. it("兼容只暴露 Files type 的 dragover,并保留 workspace/attachment 分类", () => {
  414. const transfer = createTransferService();
  415. mocks.service = transfer.service;
  416. const { root } = renderProbe({ attachmentSessionId: null, scopeId: "task-a" });
  417. const preventDefault = vi.fn();
  418. const attachmentTransfer = {
  419. dropEffect: "none",
  420. items: [],
  421. types: ["Files"],
  422. };
  423. act(() =>
  424. latestApi?.handleDragOverComposer({
  425. dataTransfer: attachmentTransfer,
  426. preventDefault,
  427. } as unknown as DragEvent<HTMLElement>),
  428. );
  429. expect(preventDefault).toHaveBeenCalledTimes(1);
  430. expect(attachmentTransfer.dropEffect).toBe("copy");
  431. expect(latestApi?.composerDragKind).toBe("attachment");
  432. act(() =>
  433. latestApi?.handleDragOverComposer({
  434. dataTransfer: {
  435. dropEffect: "none",
  436. items: [],
  437. types: ["application/x-zcode-workspace-file"],
  438. },
  439. preventDefault,
  440. } as unknown as DragEvent<HTMLElement>),
  441. );
  442. expect(latestApi?.composerDragKind).toBe("workspace");
  443. act(() =>
  444. latestApi?.handleDropComposer({
  445. dataTransfer: {
  446. files: [],
  447. types: ["application/x-zcode-workspace-file"],
  448. },
  449. preventDefault,
  450. } as unknown as DragEvent<HTMLElement>),
  451. );
  452. expect(latestApi?.composerDragKind).toBeNull();
  453. act(() => root.unmount());
  454. });
  455. it("本地桌面 localPath 零拷贝直接 ready,不显示虚假完成进度", async () => {
  456. const transfer = createTransferService();
  457. mocks.service = transfer.service;
  458. const { root } = renderProbe({
  459. attachmentSessionId: "session-1",
  460. localDesktop: true,
  461. scopeId: "task-a",
  462. });
  463. await addPaths(["/tmp/local.png"]);
  464. expect(transfer.stage).not.toHaveBeenCalled();
  465. expect(latestApi?.attachments[0]).toMatchObject({
  466. attachmentRef: {
  467. fileName: "local.png",
  468. ref: "/tmp/local.png",
  469. },
  470. localZeroCopy: true,
  471. referenceOwnership: "composer",
  472. showComplete: false,
  473. uploadProgress: 100,
  474. uploadStatus: "ready",
  475. });
  476. act(() => root.unmount());
  477. });
  478. it("session 尚未预热时停在 waitingSession,session ready 后再进入上传", async () => {
  479. const transfer = createTransferService();
  480. mocks.service = transfer.service;
  481. transfer.stage.mockResolvedValue(resultFor("waited"));
  482. const { rerender, root } = renderProbe({
  483. attachmentSessionId: null,
  484. scopeId: "task-a",
  485. });
  486. await addPaths(["/tmp/a.png"]);
  487. expect(latestApi?.attachments[0]?.uploadStatus).toBe("waitingSession");
  488. expect(transfer.stage).not.toHaveBeenCalled();
  489. rerender({ attachmentSessionId: "session-1", scopeId: "task-a" });
  490. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(1));
  491. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  492. act(() => root.unmount());
  493. });
  494. it("远端 identity 已知但 remoteSessionId 暂缺时等待,注入后再物化", async () => {
  495. const transfer = createTransferService();
  496. mocks.service = transfer.service;
  497. transfer.stage.mockResolvedValue(resultFor("remote-session-ready"));
  498. const { rerender, root } = renderProbe({
  499. attachmentSessionId: "session-1",
  500. remoteSessionId: null,
  501. scopeId: "remote-session-wait",
  502. });
  503. await addPaths(["C:\\Users\\tester\\attachment.png"]);
  504. expect(latestApi?.attachments[0]).toMatchObject({
  505. localZeroCopy: false,
  506. uploadStatus: "waitingSession",
  507. });
  508. expect(transfer.stage).not.toHaveBeenCalled();
  509. rerender({
  510. attachmentSessionId: "session-1",
  511. remoteSessionId: "remote-session-1",
  512. scopeId: "remote-session-wait",
  513. });
  514. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(1));
  515. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  516. expect(latestApi?.attachments[0]?.attachmentRef?.ref).toBe("/remote/remote-session-ready");
  517. act(() => root.unmount());
  518. });
  519. it("非规范远端 identity 在 remoteSessionId 注入前也保持等待而不走本地零复制", async () => {
  520. const transfer = createTransferService();
  521. mocks.service = transfer.service;
  522. transfer.stage.mockResolvedValue(resultFor("noncanonical-remote-identity"));
  523. const workspaceIdentity = "remote:wsl:Debian:user:relative/path";
  524. const { rerender, root } = renderProbe({
  525. attachmentSessionId: "session-1",
  526. remoteSessionId: null,
  527. scopeId: "noncanonical-remote-session-wait",
  528. workspaceIdentity,
  529. });
  530. await addPaths(["C:\\Users\\tester\\attachment.png"]);
  531. expect(latestApi?.attachments[0]).toMatchObject({
  532. localZeroCopy: false,
  533. uploadStatus: "waitingSession",
  534. });
  535. expect(transfer.stage).not.toHaveBeenCalled();
  536. rerender({
  537. attachmentSessionId: "session-1",
  538. remoteSessionId: "remote-session-1",
  539. scopeId: "noncanonical-remote-session-wait",
  540. workspaceIdentity,
  541. });
  542. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(1));
  543. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  544. expect(latestApi?.attachments[0]?.attachmentRef?.ref).toBe(
  545. "/remote/noncanonical-remote-identity",
  546. );
  547. act(() => root.unmount());
  548. });
  549. it("远端 stage 未物化路径时永久失败并保持发送门禁", async () => {
  550. const transfer = createTransferService();
  551. mocks.service = transfer.service;
  552. transfer.stage.mockImplementation(async (params) => ({
  553. bytes: 100,
  554. operationId: params.operationId,
  555. ref: "C:\\Users\\tester\\attachment.png",
  556. staged: false,
  557. }));
  558. const { root } = renderProbe({ attachmentSessionId: "session-1", scopeId: "fail-closed" });
  559. await addPaths(["C:\\Users\\tester\\attachment.png"]);
  560. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("failed"));
  561. expect(transfer.stage).toHaveBeenCalledTimes(1);
  562. expect(latestApi?.attachments[0]).toMatchObject({
  563. autoRetryCount: 0,
  564. uploadError: "chat.attachments.upload.remoteMaterializationRequired",
  565. uploadErrorKind: "permanent",
  566. uploadProgress: 0,
  567. });
  568. await expect(latestApi?.prepareForSend()).resolves.toBeNull();
  569. act(() => root.unmount());
  570. });
  571. it("最多并发 2 路,并在一个完成后启动队列中的第三个", async () => {
  572. const transfer = createTransferService();
  573. mocks.service = transfer.service;
  574. const pending = new Map<string, Deferred<ReturnType<typeof resultFor>>>();
  575. transfer.stage.mockImplementation((params) => {
  576. const request = deferred<ReturnType<typeof resultFor>>();
  577. pending.set(params.operationId, request);
  578. return request.promise;
  579. });
  580. const { root } = renderProbe({ attachmentSessionId: "session-1", scopeId: "task-a" });
  581. await addPaths(["/tmp/a.png", "/tmp/b.png", "/tmp/c.png"]);
  582. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(2));
  583. expect(latestApi?.attachments.map((item) => item.uploadStatus)).toEqual([
  584. "uploading",
  585. "uploading",
  586. "queued",
  587. ]);
  588. const firstOperation = transfer.stage.mock.calls[0]?.[0].operationId ?? "";
  589. await act(async () => pending.get(firstOperation)?.resolve(resultFor(firstOperation)));
  590. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(3));
  591. for (const [operationId, request] of pending) {
  592. request.resolve(resultFor(operationId));
  593. }
  594. await vi.waitFor(() =>
  595. expect(latestApi?.attachments.every((item) => item.uploadStatus === "ready")).toBe(true),
  596. );
  597. act(() => root.unmount());
  598. });
  599. it("任务切换不取消后台上传,切回后恢复 ready 状态", async () => {
  600. const transfer = createTransferService();
  601. mocks.service = transfer.service;
  602. const pending = deferred<ReturnType<typeof resultFor>>();
  603. transfer.stage.mockImplementation(() => pending.promise);
  604. const runtime = { listener: null as (() => void) | null };
  605. const onRuntimeRestart = (listener: () => void) => {
  606. runtime.listener = listener;
  607. return () => {
  608. runtime.listener = null;
  609. };
  610. };
  611. const { rerender, root } = renderProbe({
  612. attachmentSessionId: "session-1",
  613. onRuntimeRestart,
  614. scopeId: "task-a",
  615. });
  616. await addPaths(["/tmp/a.png"]);
  617. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(1));
  618. const operationId = transfer.stage.mock.calls[0]?.[0].operationId ?? "";
  619. rerender({ attachmentSessionId: "session-2", onRuntimeRestart, scopeId: "task-b" });
  620. expect(latestApi?.attachments).toEqual([]);
  621. await act(async () => pending.resolve(resultFor(operationId)));
  622. rerender({ attachmentSessionId: "session-1", onRuntimeRestart, scopeId: "task-a" });
  623. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  624. expect(transfer.service.cancel).not.toHaveBeenCalled();
  625. await expect(latestApi?.prepareForSend()).resolves.toHaveLength(1);
  626. expect(transfer.service.adopt).not.toHaveBeenCalled();
  627. await latestApi?.adoptSentAttachments(latestApi.attachments.map((item) => item.id));
  628. expect(transfer.service.adopt).toHaveBeenCalledWith(operationId);
  629. act(() => root.unmount());
  630. });
  631. it("发送接纳只移交和清理本次附件,等待期间新增的附件仍属于草稿", async () => {
  632. const transfer = createTransferService();
  633. mocks.service = transfer.service;
  634. transfer.stage.mockImplementation(async ({ operationId }) => resultFor(operationId));
  635. const { root } = renderProbe({ attachmentSessionId: "session-1", scopeId: "task-a" });
  636. await addPaths(["/tmp/sent.png"]);
  637. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  638. const submitted = latestApi!.attachments.map((item) => item.id);
  639. const submittedOperation = latestApi!.attachments[0]!.operationId;
  640. mocks.platform.selectFiles.mockResolvedValueOnce(["/tmp/next.png"]);
  641. act(() => latestApi!.openAttachmentPicker());
  642. await vi.waitFor(() => expect(latestApi!.attachments).toHaveLength(2));
  643. await vi.waitFor(() => expect(latestApi!.attachments[1]!.uploadStatus).toBe("ready"));
  644. await act(async () => {
  645. await latestApi!.adoptSentAttachments(submitted);
  646. latestApi!.clearAttachments(submitted);
  647. });
  648. expect(transfer.service.adopt).toHaveBeenCalledTimes(1);
  649. expect(transfer.service.adopt).toHaveBeenCalledWith(submittedOperation);
  650. expect(transfer.service.cleanup).not.toHaveBeenCalled();
  651. expect(latestApi!.attachments).toHaveLength(1);
  652. expect(latestApi!.attachments[0]).toMatchObject({ filename: "next.png", adopted: false });
  653. act(() => root.unmount());
  654. });
  655. it("composer 局部卸载后上传继续,重新挂载从 renderer store 恢复", async () => {
  656. const transfer = createTransferService();
  657. mocks.service = transfer.service;
  658. const pending = deferred<ReturnType<typeof resultFor>>();
  659. transfer.stage.mockImplementation(() => pending.promise);
  660. const firstMount = renderProbe({ attachmentSessionId: "session-1", scopeId: "task-a" });
  661. await addPaths(["/tmp/a.png"]);
  662. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(1));
  663. const operationId = transfer.stage.mock.calls[0]?.[0].operationId ?? "";
  664. act(() => firstMount.root.unmount());
  665. expect(transfer.service.cancel).not.toHaveBeenCalled();
  666. await act(async () => pending.resolve(resultFor(operationId)));
  667. await vi.waitFor(() =>
  668. expect(
  669. Object.values(useComposerAttachmentUploadStore.getState().scopes)[0]?.[0]?.uploadStatus,
  670. ).toBe("ready"),
  671. );
  672. const secondMount = renderProbe({ attachmentSessionId: "session-1", scopeId: "task-a" });
  673. expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready");
  674. act(() => secondMount.root.unmount());
  675. });
  676. it("进度只增不减,committing 最高 99%,完成后 300ms 淡出", async () => {
  677. vi.useFakeTimers();
  678. const transfer = createTransferService();
  679. mocks.service = transfer.service;
  680. const pending = deferred<ReturnType<typeof resultFor>>();
  681. transfer.stage.mockImplementation(() => pending.promise);
  682. const { root } = renderProbe({ attachmentSessionId: "session-1", scopeId: "task-a" });
  683. mocks.platform.selectFiles.mockResolvedValueOnce(["/tmp/a.png"]);
  684. act(() => latestApi?.openAttachmentPicker());
  685. await act(async () => Promise.resolve());
  686. const operationId = latestApi?.attachments[0]?.operationId ?? "";
  687. act(() => {
  688. transfer.fire(operationId, { phase: "uploading", uploadedBytes: 50, totalBytes: 100 });
  689. transfer.fire(operationId, { phase: "uploading", uploadedBytes: 20, totalBytes: 100 });
  690. transfer.fire(operationId, { phase: "committing", uploadedBytes: 100, totalBytes: 100 });
  691. });
  692. expect(latestApi?.attachments[0]).toMatchObject({
  693. uploadProgress: 99,
  694. uploadStatus: "committing",
  695. });
  696. await act(async () => pending.resolve(resultFor(operationId)));
  697. expect(latestApi?.attachments[0]).toMatchObject({
  698. showComplete: true,
  699. uploadProgress: 100,
  700. uploadStatus: "ready",
  701. });
  702. await act(async () => vi.advanceTimersByTimeAsync(COMPOSER_ATTACHMENT_COMPLETE_VISIBLE_MS));
  703. expect(latestApi?.attachments[0]?.showComplete).toBe(false);
  704. act(() => root.unmount());
  705. });
  706. it("瞬时失败仅自动重试一次,手动重试开启新的预算", async () => {
  707. vi.useFakeTimers();
  708. const transfer = createTransferService();
  709. mocks.service = transfer.service;
  710. transfer.stage
  711. .mockRejectedValueOnce(new Error("ECONNRESET"))
  712. .mockRejectedValueOnce(new Error("ECONNRESET"))
  713. .mockResolvedValueOnce(resultFor("manual"));
  714. const { root } = renderProbe({ attachmentSessionId: "session-1", scopeId: "task-a" });
  715. mocks.platform.selectFiles.mockResolvedValueOnce(["/tmp/a.png"]);
  716. act(() => latestApi?.openAttachmentPicker());
  717. await act(async () => Promise.resolve());
  718. await act(async () => vi.advanceTimersByTimeAsync(500));
  719. await act(async () => Promise.resolve());
  720. expect(transfer.stage).toHaveBeenCalledTimes(2);
  721. expect(latestApi?.attachments[0]).toMatchObject({
  722. autoRetryCount: 1,
  723. uploadErrorKind: "transient",
  724. uploadStatus: "failed",
  725. });
  726. act(() => latestApi?.retryAttachment(latestApi.attachments[0]?.id ?? ""));
  727. await act(async () => Promise.resolve());
  728. expect(transfer.stage).toHaveBeenCalledTimes(3);
  729. expect(latestApi?.attachments[0]).toMatchObject({
  730. autoRetryCount: 0,
  731. uploadStatus: "ready",
  732. });
  733. act(() => root.unmount());
  734. });
  735. it("不可重试错误直接进入 permanent failed,不消耗自动重试预算", async () => {
  736. const transfer = createTransferService();
  737. mocks.service = transfer.service;
  738. transfer.stage.mockRejectedValue(new Error("EACCES permission denied"));
  739. const { root } = renderProbe({ attachmentSessionId: "session-1", scopeId: "task-a" });
  740. await addPaths(["/tmp/secret.png"]);
  741. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("failed"));
  742. expect(transfer.stage).toHaveBeenCalledTimes(1);
  743. expect(latestApi?.attachments[0]).toMatchObject({
  744. autoRetryCount: 0,
  745. uploadErrorKind: "permanent",
  746. });
  747. act(() => root.unmount());
  748. });
  749. it("删除立即取消上传;runtime restart 使 ready 远端 ref 按剩余预算重传", async () => {
  750. const transfer = createTransferService();
  751. mocks.service = transfer.service;
  752. const first = deferred<ReturnType<typeof resultFor>>();
  753. transfer.stage
  754. .mockImplementationOnce(() => first.promise)
  755. .mockResolvedValueOnce(resultFor("ready-before-restart"))
  756. .mockResolvedValueOnce(resultFor("restarted"));
  757. let restart: (() => void) | null = null;
  758. const onRuntimeRestart = (listener: () => void) => {
  759. restart = listener;
  760. return () => {
  761. restart = null;
  762. };
  763. };
  764. const { root } = renderProbe({
  765. attachmentSessionId: "session-1",
  766. onRuntimeRestart,
  767. scopeId: "task-a",
  768. });
  769. await addPaths(["/tmp/a.png"]);
  770. const firstItem = latestApi?.attachments[0];
  771. act(() => latestApi?.removeAttachment(firstItem?.id ?? ""));
  772. expect(transfer.service.cancel).toHaveBeenCalledWith(firstItem?.operationId);
  773. await act(async () => first.resolve(resultFor(firstItem?.operationId ?? "")));
  774. await addPaths(["/tmp/b.png"]);
  775. const readyOperation = transfer.stage.mock.calls[1]?.[0].operationId ?? "";
  776. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  777. act(() => restart?.());
  778. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(3));
  779. expect(transfer.service.cleanup).toHaveBeenCalledWith(readyOperation);
  780. expect(latestApi?.attachments[0]).toMatchObject({
  781. // 换代重传不再消耗上传失败重试配额,改记在 runtimeRebuildRetryCount 上。
  782. autoRetryCount: 0,
  783. runtimeRebuildRetryCount: 1,
  784. uploadStatus: "ready",
  785. });
  786. act(() => root.unmount());
  787. });
  788. it("queue 撤回的 session-owned refs 保序 ready,重发/restart/删除均不重复处理", async () => {
  789. const transfer = createTransferService();
  790. mocks.service = transfer.service;
  791. let restart: (() => void) | null = null;
  792. const onRuntimeRestart = (listener: () => void) => {
  793. restart = listener;
  794. return () => {
  795. restart = null;
  796. };
  797. };
  798. const { root } = renderProbe({
  799. attachmentSessionId: "session-1",
  800. onRuntimeRestart,
  801. scopeId: "task-a",
  802. });
  803. const refs = [
  804. {
  805. ref: "session-ref-b",
  806. fileName: "b.png",
  807. mime: "image/png",
  808. bytes: 2,
  809. previewRef: "preview-b",
  810. },
  811. {
  812. ref: "session-ref-a",
  813. fileName: "a.txt",
  814. mime: "text/plain",
  815. bytes: 1,
  816. sourceKind: "topic-history" as const,
  817. messageCount: 2,
  818. },
  819. ];
  820. act(() => expect(latestApi?.restoreSessionOwnedAttachments(refs)).toBe(true));
  821. expect(latestApi?.attachments.map((item) => item.filename)).toEqual(["b.png", "a.txt"]);
  822. expect(latestApi?.attachments[1]).toMatchObject({
  823. sourceKind: "topic-history",
  824. messageCount: 2,
  825. });
  826. expect(latestApi?.attachments).toEqual(
  827. refs.map((ref) =>
  828. expect.objectContaining({
  829. adopted: true,
  830. attachmentRef: ref,
  831. referenceOwnership: "session",
  832. staged: false,
  833. uploadProgress: 100,
  834. uploadStatus: "ready",
  835. }),
  836. ),
  837. );
  838. await expect(latestApi?.prepareForSend()).resolves.toEqual(refs);
  839. await latestApi?.adoptSentAttachments(latestApi.attachments.map((item) => item.id));
  840. expect(transfer.service.adopt).not.toHaveBeenCalled();
  841. act(() => restart?.());
  842. expect(transfer.stage).not.toHaveBeenCalled();
  843. expect(transfer.service.cleanup).not.toHaveBeenCalled();
  844. expect(latestApi?.attachments.every((item) => item.uploadStatus === "ready")).toBe(true);
  845. act(() => latestApi?.removeAttachment(latestApi.attachments[0]?.id ?? ""));
  846. expect(transfer.service.cancel).not.toHaveBeenCalled();
  847. expect(transfer.service.cleanup).not.toHaveBeenCalled();
  848. expect(latestApi?.attachments.map((item) => item.filename)).toEqual(["a.txt"]);
  849. act(() => root.unmount());
  850. });
  851. it("换代后清空旧 ref;会话尚未重建时不入队,新会话到达才重传", async () => {
  852. const transfer = createTransferService();
  853. mocks.service = transfer.service;
  854. transfer.stage
  855. .mockResolvedValueOnce(resultFor("before-rebuild"))
  856. .mockResolvedValueOnce(resultFor("after-rebuild"));
  857. let restart: (() => void) | null = null;
  858. const onRuntimeRestart = (listener: () => void) => {
  859. restart = listener;
  860. return () => {
  861. restart = null;
  862. };
  863. };
  864. const probe = renderProbe({
  865. attachmentSessionId: "draft-1",
  866. onRuntimeRestart,
  867. scopeId: "rebuild-requeue",
  868. });
  869. await addPaths(["/tmp/a.png"]);
  870. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  871. expect(transfer.stage).toHaveBeenCalledTimes(1);
  872. // 预热会话被 retire:effectiveSessionId 回落 null,此时换代不能拿任何 id 去入队。
  873. probe.rerender({ attachmentSessionId: null, onRuntimeRestart, scopeId: "rebuild-requeue" });
  874. act(() => restart?.());
  875. expect(latestApi?.attachments[0]?.uploadStatus).toBe("waitingSession");
  876. expect(latestApi?.attachments[0]?.attachmentRef).toBeUndefined();
  877. expect(transfer.stage).toHaveBeenCalledTimes(1);
  878. // 新预热会话到达 → 唤醒重传。
  879. probe.rerender({
  880. attachmentSessionId: "draft-2",
  881. onRuntimeRestart,
  882. scopeId: "rebuild-requeue",
  883. });
  884. await vi.waitFor(() => expect(transfer.stage).toHaveBeenCalledTimes(2));
  885. probe.root.unmount();
  886. });
  887. it("换代重传独立计数:连传 5 次仍重传,第 6 次判失败,且不消耗 autoRetryCount", async () => {
  888. const transfer = createTransferService();
  889. mocks.service = transfer.service;
  890. transfer.stage.mockImplementation(async () =>
  891. resultFor(`rebuild-${transfer.stage.mock.calls.length}`),
  892. );
  893. let restart: (() => void) | null = null;
  894. const onRuntimeRestart = (listener: () => void) => {
  895. restart = listener;
  896. return () => {
  897. restart = null;
  898. };
  899. };
  900. const { root } = renderProbe({
  901. attachmentSessionId: "draft-1",
  902. onRuntimeRestart,
  903. scopeId: "rebuild-quota",
  904. });
  905. await addPaths(["/tmp/c.png"]);
  906. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  907. for (let round = 1; round <= 5; round += 1) {
  908. act(() => restart?.());
  909. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  910. expect(latestApi?.attachments[0]).toMatchObject({
  911. autoRetryCount: 0,
  912. runtimeRebuildRetryCount: round,
  913. });
  914. }
  915. // 第 6 次换代超出兜底上限 → 判失败,交给用户手动重试。
  916. act(() => restart?.());
  917. expect(latestApi?.attachments[0]?.uploadStatus).toBe("failed");
  918. act(() => root.unmount());
  919. });
  920. // Bug 回归:CUA Helper 就绪走 workspace-dispose,而 onRuntimeRestart 只在新 agent 进程
  921. // spawn 时才发。agent 是懒启动——那一刻没人拉起它,换代通知永不到达,附件卡在
  922. // waitingSession 直到用户手动点一次发送才被踹活(生产实测间隔 2.3s/6.0s/26.3s,
  923. // 全等于用户点击时刻)。dispose 当场唯一可观测的信号是 lifecycle unavailable。
  924. it("lifecycle unavailable → 静默作废;新预热会话到达即自动重传,无需任何用户操作", async () => {
  925. const transfer = createTransferService();
  926. mocks.service = transfer.service;
  927. transfer.stage.mockImplementation(async () =>
  928. resultFor(`lifecycle-${transfer.stage.mock.calls.length}`),
  929. );
  930. let lifecycle: ((state: "available" | "unavailable") => void) | null = null;
  931. const onRuntimeLifecycle = (listener: (state: "available" | "unavailable") => void) => {
  932. lifecycle = listener;
  933. return () => {
  934. lifecycle = null;
  935. };
  936. };
  937. const probe = renderProbe({
  938. attachmentSessionId: "draft-1",
  939. onRuntimeLifecycle,
  940. scopeId: "lifecycle-rebuild",
  941. });
  942. await addPaths(["/tmp/a.png"]);
  943. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  944. expect(transfer.stage).toHaveBeenCalledTimes(1);
  945. // dispose 当场作废,但不入队:旧 CLI 已死、新的还没起来。
  946. act(() => lifecycle?.("unavailable"));
  947. expect(latestApi?.attachments[0]).toMatchObject({
  948. runtimeRebuildRetryCount: 1,
  949. uploadStatus: "waitingSession",
  950. });
  951. expect(latestApi?.attachments[0]?.attachmentRef).toBeUndefined();
  952. // 静默:这是一次全自动恢复,chip 只显示「正在等待会话」,不该报错。
  953. expect(latestApi?.attachments[0]?.uploadError).toBeUndefined();
  954. expect(latestApi?.attachments[0]?.uploadErrorKind).toBeUndefined();
  955. expect(transfer.stage).toHaveBeenCalledTimes(1);
  956. // 预热重建产出新会话 → 自动重传(这正是原来必须手动点发送才发生的事)。
  957. probe.rerender({
  958. attachmentSessionId: "draft-2",
  959. onRuntimeLifecycle,
  960. scopeId: "lifecycle-rebuild",
  961. });
  962. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  963. expect(transfer.stage).toHaveBeenCalledTimes(2);
  964. probe.root.unmount();
  965. });
  966. it("lifecycle available → 会话 id 原地不变也能唤醒重传(正式会话态兜底)", async () => {
  967. const transfer = createTransferService();
  968. mocks.service = transfer.service;
  969. transfer.stage.mockImplementation(async () =>
  970. resultFor(`lifecycle-live-${transfer.stage.mock.calls.length}`),
  971. );
  972. let lifecycle: ((state: "available" | "unavailable") => void) | null = null;
  973. const onRuntimeLifecycle = (listener: (state: "available" | "unavailable") => void) => {
  974. lifecycle = listener;
  975. return () => {
  976. lifecycle = null;
  977. };
  978. };
  979. const { root } = renderProbe({
  980. attachmentSessionId: "session-1",
  981. onRuntimeLifecycle,
  982. scopeId: "lifecycle-live",
  983. });
  984. await addPaths(["/tmp/b.png"]);
  985. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  986. act(() => lifecycle?.("unavailable"));
  987. expect(latestApi?.attachments[0]?.uploadStatus).toBe("waitingSession");
  988. expect(transfer.stage).toHaveBeenCalledTimes(1);
  989. // 正式会话态 sessionId 不变,唤醒只能靠 available(= 新进程已 spawn,入队才安全)。
  990. act(() => lifecycle?.("available"));
  991. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  992. expect(transfer.stage).toHaveBeenCalledTimes(2);
  993. act(() => root.unmount());
  994. });
  995. it("两条通道都在时只订阅 lifecycle:restart 不再重复作废、不多烧一次重传配额", async () => {
  996. const transfer = createTransferService();
  997. mocks.service = transfer.service;
  998. transfer.stage.mockImplementation(async () =>
  999. resultFor(`lifecycle-dedup-${transfer.stage.mock.calls.length}`),
  1000. );
  1001. let lifecycle: ((state: "available" | "unavailable") => void) | null = null;
  1002. let restart: (() => void) | null = null;
  1003. const onRuntimeLifecycle = (listener: (state: "available" | "unavailable") => void) => {
  1004. lifecycle = listener;
  1005. return () => {
  1006. lifecycle = null;
  1007. };
  1008. };
  1009. const onRuntimeRestart = (listener: () => void) => {
  1010. restart = listener;
  1011. return () => {
  1012. restart = null;
  1013. };
  1014. };
  1015. const { root } = renderProbe({
  1016. attachmentSessionId: "draft-1",
  1017. onRuntimeLifecycle,
  1018. onRuntimeRestart,
  1019. scopeId: "lifecycle-dedup",
  1020. });
  1021. await addPaths(["/tmp/c.png"]);
  1022. await vi.waitFor(() => expect(latestApi?.attachments[0]?.uploadStatus).toBe("ready"));
  1023. act(() => lifecycle?.("unavailable"));
  1024. // 真实时序里 restarted 紧跟新进程 spawn 到达;两条都处理会白烧一次重传配额。
  1025. act(() => restart?.());
  1026. expect(latestApi?.attachments[0]?.runtimeRebuildRetryCount).toBe(1);
  1027. expect(restart).toBeNull();
  1028. act(() => root.unmount());
  1029. });
  1030. });