remotePromptAttachments.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { describe, expect, it, vi } from "vitest";
  2. import { PassThrough } from "node:stream";
  3. import type { IDisposable, Event } from "@zcode/rpc";
  4. import type { ZCodePromptAttachment } from "@zcode/shared";
  5. import {
  6. REMOTE_PROMPT_ATTACHMENT_ROOT,
  7. buildRemotePromptAttachmentPath,
  8. createRemotePromptAttachmentSessionService,
  9. createRemotePromptAttachmentTaskService,
  10. materializeRemotePromptAttachments,
  11. } from "../src/host/remotePromptAttachments.js";
  12. function createClosedStream(stdoutText = "") {
  13. const stdin = new PassThrough();
  14. const stdout = new PassThrough();
  15. const stderr = new PassThrough();
  16. const onClose: Event<number> = (
  17. listener: (code: number) => void,
  18. ): IDisposable => {
  19. queueMicrotask(() => {
  20. if (stdoutText) {
  21. stdout.write(stdoutText);
  22. }
  23. stdout.end();
  24. listener(0);
  25. });
  26. return { dispose() {} };
  27. };
  28. return { stdin, stdout, stderr, onClose };
  29. }
  30. describe("remote prompt attachment materialization", () => {
  31. it("uploads host localPath attachments and rewrites prompt paths", async () => {
  32. const upload = vi.fn(
  33. async (_localPath: string, _remotePath: string) => undefined,
  34. );
  35. const exec = vi
  36. .fn()
  37. .mockResolvedValueOnce(createClosedStream("/home/tester"))
  38. .mockResolvedValueOnce(createClosedStream())
  39. .mockResolvedValueOnce(createClosedStream());
  40. const hostPath =
  41. "C:\\Users\\tester\\.zcode\\tmp\\paste-attachments\\pasted-text.txt";
  42. const attachments: ZCodePromptAttachment[] = [
  43. {
  44. kind: "file",
  45. filename: "pasted text.txt",
  46. localPath: hostPath,
  47. mimeType: "text/plain",
  48. sizeBytes: 8192,
  49. sourceKind: "clipboard-text",
  50. },
  51. {
  52. kind: "image",
  53. filename: "inline.png",
  54. mimeType: "image/png",
  55. dataBase64: "aW1hZ2U=",
  56. sizeBytes: 5,
  57. },
  58. ];
  59. const result = await materializeRemotePromptAttachments(
  60. {
  61. content: `请读取 ${hostPath}`,
  62. traceId: "trace:abc/123",
  63. attachments,
  64. },
  65. { backend: { exec, upload } },
  66. );
  67. const remotePath = upload.mock.calls[0]?.[1] ?? "";
  68. expect(remotePath).toMatch(
  69. /^\/home\/tester\/\.zcode\/tmp\/prompt-attachments\/trace-abc-123\/[A-Za-z0-9._-]+\/01-pasted-text\.txt$/,
  70. );
  71. expect(upload).toHaveBeenCalledWith(hostPath, remotePath);
  72. expect(exec.mock.calls[0]?.[0]).toBe('printf %s "$HOME"');
  73. expect(exec.mock.calls[1]?.[0]).toContain("mkdir -p");
  74. expect(exec.mock.calls[1]?.[0]).toContain("command chmod 700");
  75. expect(exec.mock.calls[1]?.[0]).not.toContain('"$HOME"');
  76. expect(exec.mock.calls[2]?.[0]).toContain("command chmod 600");
  77. expect(exec.mock.calls[2]?.[0]).not.toContain('"$HOME"');
  78. expect(result.uploadedCount).toBe(1);
  79. expect(result.content).toBe(`请读取 ${remotePath}`);
  80. expect(result.attachments?.[0]).toEqual({
  81. ...attachments[0],
  82. localPath: remotePath,
  83. });
  84. expect(result.attachments?.[1]).toBe(attachments[1]);
  85. });
  86. it("skips attachments that already point at the remote materialization directory", async () => {
  87. const upload = vi.fn(
  88. async (_localPath: string, _remotePath: string) => undefined,
  89. );
  90. const exec = vi.fn(async (_command: string) => createClosedStream());
  91. const remotePath = `${REMOTE_PROMPT_ATTACHMENT_ROOT}/trace/01-image.png`;
  92. const attachments: ZCodePromptAttachment[] = [
  93. {
  94. kind: "image",
  95. filename: "image.png",
  96. localPath: remotePath,
  97. mimeType: "image/png",
  98. },
  99. ];
  100. const result = await materializeRemotePromptAttachments(
  101. { content: remotePath, traceId: "trace", attachments },
  102. { backend: { exec, upload } },
  103. );
  104. expect(exec).not.toHaveBeenCalled();
  105. expect(upload).not.toHaveBeenCalled();
  106. expect(result.uploadedCount).toBe(0);
  107. expect(result.attachments).toBe(attachments);
  108. expect(result.content).toBe(remotePath);
  109. });
  110. it("skips attachments that already point at the resolved remote materialization directory", async () => {
  111. const upload = vi.fn(
  112. async (_localPath: string, _remotePath: string) => undefined,
  113. );
  114. const exec = vi.fn(async (_command: string) => createClosedStream("/home/tester"));
  115. const remotePath = "/home/tester/.zcode/tmp/prompt-attachments/trace/01-image.png";
  116. const attachments: ZCodePromptAttachment[] = [
  117. {
  118. kind: "image",
  119. filename: "image.png",
  120. localPath: remotePath,
  121. mimeType: "image/png",
  122. },
  123. ];
  124. const result = await materializeRemotePromptAttachments(
  125. { content: remotePath, traceId: "trace", attachments },
  126. { backend: { exec, upload } },
  127. );
  128. expect(exec).toHaveBeenCalledTimes(1);
  129. expect(upload).not.toHaveBeenCalled();
  130. expect(result.uploadedCount).toBe(0);
  131. expect(result.attachments).toBe(attachments);
  132. expect(result.content).toBe(remotePath);
  133. });
  134. it("fails before sending a prompt with an unreadable host attachment path", async () => {
  135. const upload = vi.fn(async (_localPath: string, _remotePath: string) => {
  136. throw new Error("EACCES");
  137. });
  138. const exec = vi
  139. .fn()
  140. .mockResolvedValueOnce(createClosedStream("/home/tester"))
  141. .mockResolvedValueOnce(createClosedStream());
  142. await expect(
  143. materializeRemotePromptAttachments(
  144. {
  145. content: "inspect",
  146. traceId: "trace",
  147. attachments: [
  148. {
  149. kind: "file",
  150. filename: "secret.txt",
  151. localPath: "C:\\secret.txt",
  152. mimeType: "text/plain",
  153. sizeBytes: 1,
  154. },
  155. ],
  156. },
  157. { backend: { exec, upload } },
  158. ),
  159. ).rejects.toThrow("远端附件上传失败:secret.txt");
  160. });
  161. it("builds private safe remote paths", () => {
  162. expect(
  163. buildRemotePromptAttachmentPath({
  164. filename: "../../api 文档.txt",
  165. index: 2,
  166. nonce: "nonce:with/slash",
  167. traceId: "trace/id:456",
  168. }),
  169. ).toBe(
  170. `${REMOTE_PROMPT_ATTACHMENT_ROOT}/trace-id-456/nonce-with-slash/03-api-.txt`,
  171. );
  172. });
  173. it("materializes desktop-continuous session prompts before calling the remote session service", async () => {
  174. const remoteAttachment: ZCodePromptAttachment = {
  175. kind: "file",
  176. filename: "pasted.txt",
  177. localPath: "/home/tester/.zcode/tmp/prompt-attachments/input/01-pasted.txt",
  178. mimeType: "text/plain",
  179. sizeBytes: 5,
  180. sourceKind: "clipboard-text",
  181. };
  182. const sendPrompt = vi.fn(async () => ({ accepted: true }));
  183. const service = createRemotePromptAttachmentSessionService(
  184. { sendPrompt },
  185. {
  186. materializePromptAttachments: async (params) => ({
  187. content: params.content.replace("/tmp/host-paste.txt", remoteAttachment.localPath!),
  188. attachments: [remoteAttachment],
  189. }),
  190. },
  191. );
  192. await service.sendPrompt({
  193. sessionId: "task-1",
  194. inputId: "input-1",
  195. content: "read /tmp/host-paste.txt",
  196. attachments: [
  197. {
  198. kind: "file",
  199. filename: "pasted.txt",
  200. localPath: "/tmp/host-paste.txt",
  201. mimeType: "text/plain",
  202. sizeBytes: 5,
  203. sourceKind: "clipboard-text",
  204. },
  205. ],
  206. });
  207. expect(sendPrompt).toHaveBeenCalledWith({
  208. sessionId: "task-1",
  209. inputId: "input-1",
  210. content:
  211. "read /home/tester/.zcode/tmp/prompt-attachments/input/01-pasted.txt",
  212. attachments: [remoteAttachment],
  213. });
  214. });
  215. it("materializes web-remote queued task commands before calling the remote task service", async () => {
  216. const remoteAttachment: ZCodePromptAttachment = {
  217. kind: "file",
  218. filename: "pasted.txt",
  219. localPath: "/home/tester/.zcode/tmp/prompt-attachments/input/01-pasted.txt",
  220. mimeType: "text/plain",
  221. sizeBytes: 5,
  222. sourceKind: "clipboard-text",
  223. };
  224. const enqueueTaskCommand = vi.fn(async () => ({ accepted: true }));
  225. const service = createRemotePromptAttachmentTaskService(
  226. { enqueueTaskCommand },
  227. {
  228. materializePromptAttachments: async (params) => ({
  229. content: params.content.replace("/tmp/host-paste.txt", remoteAttachment.localPath!),
  230. attachments: [remoteAttachment],
  231. }),
  232. },
  233. );
  234. await service.enqueueTaskCommand({
  235. taskId: "task-1",
  236. commandId: "command-1",
  237. traceId: "input-1",
  238. type: "send_prompt",
  239. content: "read /tmp/host-paste.txt",
  240. attachments: [
  241. {
  242. kind: "file",
  243. filename: "pasted.txt",
  244. localPath: "/tmp/host-paste.txt",
  245. mimeType: "text/plain",
  246. sizeBytes: 5,
  247. sourceKind: "clipboard-text",
  248. },
  249. ],
  250. });
  251. expect(enqueueTaskCommand).toHaveBeenCalledWith({
  252. taskId: "task-1",
  253. commandId: "command-1",
  254. traceId: "input-1",
  255. type: "send_prompt",
  256. content:
  257. "read /home/tester/.zcode/tmp/prompt-attachments/input/01-pasted.txt",
  258. attachments: [remoteAttachment],
  259. });
  260. });
  261. });