promptAttachmentTransferService.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import { PassThrough } from "node:stream";
  2. import { describe, expect, it, vi } from "vitest";
  3. import type { Event, IDisposable } from "@zcode/rpc";
  4. import type { RemoteUploadOptions } from "@zcode/server/remote";
  5. import { createRemotePromptAttachmentTransferService } from "../src/host/promptAttachmentTransferService.js";
  6. function createClosedStream(stdoutText = "") {
  7. const stdin = new PassThrough();
  8. const stdout = new PassThrough();
  9. const stderr = new PassThrough();
  10. const onClose: Event<number> = (listener: (code: number) => void): IDisposable => {
  11. queueMicrotask(() => {
  12. if (stdoutText) stdout.write(stdoutText);
  13. stdout.end();
  14. listener(0);
  15. });
  16. return { dispose() {} };
  17. };
  18. return { stdin, stdout, stderr, onClose };
  19. }
  20. function createExec() {
  21. return vi.fn(async (command: string) =>
  22. createClosedStream(command === 'printf %s "$HOME"' ? "/home/tester" : ""),
  23. );
  24. }
  25. function stageParams(operationId = "attachment-1") {
  26. return {
  27. operationId,
  28. sessionId: "session-1",
  29. workspacePath: "/workspace",
  30. workspaceIdentity: "remote:ssh:host:/workspace",
  31. remoteSessionId: "remote-session-1",
  32. localPath: "/Users/tester/image.png",
  33. fileName: "image.png",
  34. mime: "image/png",
  35. sizeBytes: 100,
  36. };
  37. }
  38. describe("remote prompt attachment transfer service", () => {
  39. it("上报单调上传进度,按 workspace/session identity 暂存并可 adopt", async () => {
  40. const exec = createExec();
  41. const upload = vi.fn(
  42. async (_localPath: string, _remotePath: string, options?: RemoteUploadOptions) => {
  43. options?.onProgress?.({ uploadedBytes: 20, totalBytes: 100 });
  44. options?.onProgress?.({ uploadedBytes: 75, totalBytes: 100 });
  45. // SFTP 回退 exec 时底层计数可能从 0 重新开始,host 不得让 UI 进度倒退。
  46. options?.onProgress?.({ uploadedBytes: 50, totalBytes: 100 });
  47. options?.onProgress?.({ uploadedBytes: 100, totalBytes: 100 });
  48. },
  49. );
  50. const service = createRemotePromptAttachmentTransferService({ exec, upload });
  51. const progress: Array<{ phase: string; uploadedBytes: number }> = [];
  52. const subscription = service.onDynamicProgress("attachment-1")((event) => {
  53. progress.push({ phase: event.phase, uploadedBytes: event.uploadedBytes });
  54. });
  55. const result = await service.stage(stageParams());
  56. await service.adopt("attachment-1");
  57. await service.cleanup("attachment-1");
  58. subscription.dispose();
  59. expect(result.ref).toContain("/remote-ssh-host-workspace-remote-session-1-attachment-1/");
  60. expect(progress.map((event) => event.uploadedBytes)).toEqual([20, 75, 100, 100, 100]);
  61. expect(progress.map((event) => event.phase)).toEqual([
  62. "uploading",
  63. "uploading",
  64. "uploading",
  65. "committing",
  66. "complete",
  67. ]);
  68. expect(exec.mock.calls.some(([command]) => String(command).startsWith("rm -f "))).toBe(false);
  69. });
  70. it("cancel 中止正在上传的 backend,并让 stage 进入 canceled", async () => {
  71. const exec = createExec();
  72. const upload = vi.fn(
  73. async (_localPath: string, _remotePath: string, options?: RemoteUploadOptions) =>
  74. new Promise<void>((_resolve, reject) => {
  75. options?.signal?.addEventListener("abort", () => {
  76. const error = new Error("canceled");
  77. error.name = "AbortError";
  78. reject(error);
  79. });
  80. }),
  81. );
  82. const service = createRemotePromptAttachmentTransferService({ exec, upload });
  83. const phases: string[] = [];
  84. service.onDynamicProgress("attachment-2")((event) => phases.push(event.phase));
  85. const staging = service.stage(stageParams("attachment-2"));
  86. await vi.waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
  87. await service.cancel("attachment-2");
  88. await expect(staging).rejects.toMatchObject({ name: "AbortError" });
  89. expect(phases).toContain("canceled");
  90. expect(vi.mocked(upload).mock.calls[0]?.[2]?.signal?.aborted).toBe(true);
  91. });
  92. it("未 adopt 的 ready 暂存内容在 cleanup 时立即删除", async () => {
  93. const exec = createExec();
  94. const upload = vi.fn(async () => {});
  95. const service = createRemotePromptAttachmentTransferService({ exec, upload });
  96. await service.stage(stageParams("attachment-3"));
  97. await service.cleanup("attachment-3");
  98. expect(exec.mock.calls.some(([command]) => String(command).startsWith("rm -f "))).toBe(true);
  99. });
  100. });
  101. it("R3 attachment 拒绝跨 workspace/session 的暂存请求", async () => {
  102. const upload = vi.fn(async () => {});
  103. const scope = stageParams();
  104. const service = createRemotePromptAttachmentTransferService(
  105. { exec: createExec(), upload },
  106. { scope },
  107. );
  108. for (const patch of [
  109. { workspaceIdentity: "remote:server:other:/workspace" },
  110. { workspacePath: "/other" },
  111. { remoteSessionId: "other-session" },
  112. ]) {
  113. await expect(service.stage({ ...scope, ...patch })).rejects.toThrow("attachment scope");
  114. }
  115. expect(upload).not.toHaveBeenCalled();
  116. await service.dispose();
  117. });
  118. it("关闭 attachment 时 abort,忽略晚成功并清理暂存;已 adopt 文件保留", async () => {
  119. const exec = createExec();
  120. let finish!: () => void;
  121. const upload = vi.fn(async (_local: string, _remote: string, _options?: RemoteUploadOptions) => {
  122. if (upload.mock.calls.length === 2)
  123. await new Promise<void>((resolve) => {
  124. finish = resolve;
  125. });
  126. });
  127. const service = createRemotePromptAttachmentTransferService({ exec, upload });
  128. const adopted = await service.stage(stageParams("adopted"));
  129. await service.adopt("adopted");
  130. const phases: string[] = [];
  131. service.onDynamicProgress("pending")((event) => phases.push(event.phase));
  132. const staging = service.stage(stageParams("pending"));
  133. const rejected = expect(staging).rejects.toMatchObject({ name: "AbortError" });
  134. await vi.waitFor(() => expect(upload).toHaveBeenCalledTimes(2));
  135. await service.dispose();
  136. expect(upload.mock.calls[1]?.[2]?.signal?.aborted).toBe(true);
  137. finish();
  138. await rejected;
  139. const uploadedPath = upload.mock.calls[1]![1];
  140. expect(
  141. exec.mock.calls.some(
  142. ([command]) => command.startsWith("rm -f ") && command.includes(uploadedPath),
  143. ),
  144. ).toBe(true);
  145. expect(
  146. exec.mock.calls.some(
  147. ([command]) => command.startsWith("rm -f ") && command.includes(adopted.ref),
  148. ),
  149. ).toBe(false);
  150. expect(phases).not.toContain("complete");
  151. await expect(service.stage(stageParams("late"))).rejects.toThrow("disposed");
  152. });
  153. it("同 operation 重试的旧结果不能删掉新 record,晚成功文件仍清理", async () => {
  154. const exec = createExec();
  155. let finish!: () => void;
  156. const upload = vi.fn(async () => {
  157. if (upload.mock.calls.length === 1)
  158. await new Promise<void>((resolve) => {
  159. finish = resolve;
  160. });
  161. });
  162. const service = createRemotePromptAttachmentTransferService({ exec, upload });
  163. const oldStage = service.stage(stageParams());
  164. const oldRejected = expect(oldStage).rejects.toMatchObject({ name: "AbortError" });
  165. await vi.waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
  166. const next = await service.stage(stageParams());
  167. finish();
  168. await oldRejected;
  169. await service.cleanup("attachment-1");
  170. expect(
  171. exec.mock.calls.some(([command]) => command.startsWith("rm -f ") && command.includes(next.ref)),
  172. ).toBe(true);
  173. await service.dispose();
  174. });