promptAttachmentTransferService.test.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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.toThrow("远端附件上传失败");
  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. });