remoteConnect.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { PassThrough } from "node:stream";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { Emitter, ChannelClient, SocketProtocol, type IDisposable, type Event } from "@zcode/rpc";
  4. import { ZCODE_VERSION, TOPIC_RESOURCE_RELAY_CHANNEL } from "@zcode/shared";
  5. import { wrapStdioStream } from "../src/remote/stdio-socket.js";
  6. import { connectRemote, pickRemoteRuntimeEnv } from "../src/remote/connect.js";
  7. import type { IRemoteBackend, RemoteDisconnectEvent, StdioStream } from "../src/remote/backend.js";
  8. class FakeConnectBackend implements IRemoteBackend {
  9. stream?: StdioStream;
  10. readonly commands: string[] = [];
  11. disposeCount = 0;
  12. private readonly closeListeners: Array<(code: number) => void> = [];
  13. private readonly disconnectEmitter = new Emitter<RemoteDisconnectEvent>();
  14. readonly onDidDisconnect = this.disconnectEmitter.event;
  15. constructor(
  16. private readonly launchFailure?: {
  17. code: number;
  18. stderr: string;
  19. },
  20. ) {}
  21. dispose(): void {
  22. this.disposeCount += 1;
  23. this.disconnectEmitter.dispose();
  24. }
  25. async detect() {
  26. return { platform: "linux", arch: "arm64" };
  27. }
  28. async upload(): Promise<void> {}
  29. async exec(command: string): Promise<StdioStream> {
  30. this.commands.push(command);
  31. const stdin = new PassThrough();
  32. const stdout = new PassThrough();
  33. const stderr = new PassThrough();
  34. const onClose: Event<number> = (listener): IDisposable => {
  35. this.closeListeners.push(listener);
  36. return {
  37. dispose: () => {
  38. const index = this.closeListeners.indexOf(listener);
  39. if (index >= 0) {
  40. this.closeListeners.splice(index, 1);
  41. }
  42. },
  43. };
  44. };
  45. if (this.launchFailure) {
  46. setTimeout(() => {
  47. stderr.write(this.launchFailure?.stderr);
  48. this.fireStreamClose(this.launchFailure?.code ?? 1);
  49. }, 0);
  50. } else {
  51. queueMicrotask(() => {
  52. stdout.write(
  53. `${JSON.stringify({
  54. type: "zcode-hello",
  55. version: ZCODE_VERSION,
  56. platform: "linux",
  57. arch: "arm64",
  58. pid: 123,
  59. })}\n`,
  60. );
  61. });
  62. }
  63. this.stream = { stdin, stdout, stderr, onClose };
  64. return this.stream;
  65. }
  66. async exists(): Promise<boolean> {
  67. return true;
  68. }
  69. async readFile(): Promise<string> {
  70. return `${ZCODE_VERSION}\n`;
  71. }
  72. async resolveRuntimeProxy(proxyUrl: string): Promise<string> {
  73. return proxyUrl;
  74. }
  75. fireStreamClose(code: number): void {
  76. for (const listener of this.closeListeners) {
  77. listener(code);
  78. }
  79. }
  80. fireDisconnect(event: RemoteDisconnectEvent): void {
  81. this.disconnectEmitter.fire(event);
  82. }
  83. }
  84. describe("connectRemote", () => {
  85. it("serves a private reverse channel on the existing stdio connection", async () => {
  86. const backend = new FakeConnectBackend();
  87. const call = vi.fn(async () => ({ valid: true }));
  88. const connection = await connectRemote(backend, {
  89. clientId: "test-client",
  90. skipDeploy: true,
  91. topicResourceChannel: {
  92. call,
  93. listen() {
  94. throw new Error("No events");
  95. },
  96. },
  97. });
  98. const stream = backend.stream!;
  99. // hello-ack 是文本握手;反向 RPC 复用它之后的原始字节流。
  100. const stdin = stream.stdin as PassThrough;
  101. const buffered = stdin.read() as Buffer;
  102. const boundary = buffered.indexOf(10) + 1;
  103. const remaining = buffered.subarray(boundary);
  104. const inverse = wrapStdioStream({
  105. ...stream,
  106. stdin: stream.stdout as PassThrough,
  107. stdout: stdin,
  108. });
  109. const protocol = new SocketProtocol(inverse);
  110. const remote = new ChannelClient(protocol);
  111. if (remaining.length) stdin.unshift(remaining);
  112. try {
  113. expect(
  114. await remote.getChannel(TOPIC_RESOURCE_RELAY_CHANNEL).call("validate", { taskId: "task" }),
  115. ).toEqual({ valid: true });
  116. expect(call).toHaveBeenCalledOnce();
  117. } finally {
  118. remote.dispose();
  119. connection.dispose();
  120. }
  121. });
  122. it("透传 Desktop SP 灰度结果到远端 server,但不透传未列入白名单的变量", () => {
  123. expect(
  124. pickRemoteRuntimeEnv({
  125. ZCODE_DESKTOP_CONTEXT_PROMPT_ENABLED: "1",
  126. ZCODE_OAUTH_TOKEN: "secret",
  127. }),
  128. ).toEqual({
  129. ZCODE_DESKTOP_CONTEXT_PROMPT_ENABLED: "1",
  130. });
  131. });
  132. // DWG-06(docs/dynamic-workflow/launch.md「Gray release」):Dynamic Workflow 的档位由
  133. // Desktop Main 写定,远端 Host 必须拿到同一个值,preview 包的远程工作区才与本地一致。
  134. it("透传 Desktop Main 写定的 Dynamic Workflow 灰度档位", () => {
  135. expect(
  136. pickRemoteRuntimeEnv({
  137. ZCODE_DYNAMIC_WORKFLOW_MODE: "alwaysOn",
  138. ZCODE_OAUTH_TOKEN: "secret",
  139. }),
  140. ).toEqual({
  141. ZCODE_DYNAMIC_WORKFLOW_MODE: "alwaysOn",
  142. });
  143. // Main 在 production 包里已经删掉这个键,远端因此什么也收不到。
  144. expect(pickRemoteRuntimeEnv({})).toEqual({});
  145. });
  146. it("连接初始化失败时释放 backend", async () => {
  147. const backend = new FakeConnectBackend();
  148. vi.spyOn(backend, "detect").mockRejectedValueOnce(new Error("detect failed"));
  149. await expect(
  150. connectRemote(backend, { clientId: "test-client", skipDeploy: true }),
  151. ).rejects.toThrow("detect failed");
  152. expect(backend.disposeCount).toBe(1);
  153. });
  154. it("取消未完成的连接初始化时立即拒绝并释放 backend", async () => {
  155. const backend = new FakeConnectBackend();
  156. vi.spyOn(backend, "detect").mockImplementationOnce(() => new Promise(() => undefined));
  157. const controller = new AbortController();
  158. const outcome = connectRemote(backend, {
  159. clientId: "test-client",
  160. signal: controller.signal,
  161. skipDeploy: true,
  162. }).then(
  163. () => ({ kind: "resolved" as const }),
  164. (error: unknown) => ({
  165. kind: "rejected" as const,
  166. name: error instanceof Error ? error.name : "UnknownError",
  167. }),
  168. );
  169. controller.abort();
  170. await Promise.resolve();
  171. await Promise.resolve();
  172. await expect(
  173. Promise.race([
  174. outcome,
  175. new Promise<{ kind: "pending" }>((resolve) => {
  176. setTimeout(() => resolve({ kind: "pending" }), 10);
  177. }),
  178. ]),
  179. ).resolves.toEqual({ kind: "rejected", name: "AbortError" });
  180. expect(backend.disposeCount).toBe(1);
  181. });
  182. it("取消后迟到的 detect 结果不得继续启动远端 server", async () => {
  183. const backend = new FakeConnectBackend();
  184. let resolveDetect!: (value: { platform: string; arch: string }) => void;
  185. vi.spyOn(backend, "detect").mockImplementationOnce(
  186. () =>
  187. new Promise((resolve) => {
  188. resolveDetect = resolve;
  189. }),
  190. );
  191. const controller = new AbortController();
  192. const connecting = connectRemote(backend, {
  193. clientId: "test-client",
  194. signal: controller.signal,
  195. skipDeploy: true,
  196. });
  197. controller.abort();
  198. await expect(connecting).rejects.toMatchObject({ name: "AbortError" });
  199. resolveDetect({ platform: "linux", arch: "arm64" });
  200. await new Promise<void>((resolve) => {
  201. setTimeout(resolve, 0);
  202. });
  203. expect(backend.commands).toEqual([]);
  204. });
  205. it("disposeAndWait 先关闭 stdin,再等待远端 stdio close", async () => {
  206. const backend = new FakeConnectBackend();
  207. const connection = await connectRemote(backend, {
  208. clientId: "test-client",
  209. skipDeploy: true,
  210. });
  211. let settled = false;
  212. const disposing = connection.disposeAndWait({ timeoutMs: 1_000 }).then(() => {
  213. settled = true;
  214. });
  215. await Promise.resolve();
  216. expect(settled).toBe(false);
  217. expect(backend.disposeCount).toBe(0);
  218. backend.fireStreamClose(0);
  219. await disposing;
  220. expect(settled).toBe(true);
  221. expect(backend.disposeCount).toBe(1);
  222. });
  223. it("disposeAndWait 等待超时后强制释放 backend", async () => {
  224. vi.useFakeTimers();
  225. try {
  226. const backend = new FakeConnectBackend();
  227. const connection = await connectRemote(backend, {
  228. clientId: "test-client",
  229. skipDeploy: true,
  230. });
  231. const disposing = connection.disposeAndWait({ timeoutMs: 250 });
  232. await vi.advanceTimersByTimeAsync(250);
  233. await disposing;
  234. expect(backend.disposeCount).toBe(1);
  235. } finally {
  236. vi.useRealTimers();
  237. }
  238. });
  239. it("启动远端 server 时不再注入退役 proxy runtime 环境变量", async () => {
  240. const backend = new FakeConnectBackend();
  241. const retiredProxyEnvName = ["ZCODE", `${"A"}${"CP"}`, "PROXY", "RUNTIME", "PATH"].join("_");
  242. const connection = await connectRemote(backend, {
  243. clientId: "test-client",
  244. skipDeploy: true,
  245. });
  246. connection.dispose();
  247. expect(backend.commands[0]).toContain('ZCODE_SERVER_RUNTIME_ROOT="$HOME/.zcode/server"');
  248. expect(backend.commands[0]).not.toContain(retiredProxyEnvName);
  249. });
  250. it("启动 desktop attached 远端 server 时注入服务权威模式", async () => {
  251. const backend = new FakeConnectBackend();
  252. const connection = await connectRemote(backend, {
  253. clientId: "test-client",
  254. skipDeploy: true,
  255. });
  256. connection.dispose();
  257. expect(backend.commands[0]).toContain('ZCODE_SERVICE_AUTHORITY_MODE="desktop-attached-remote"');
  258. });
  259. it("启动远端 server 时 shell quote 注入 app version", async () => {
  260. const backend = new FakeConnectBackend();
  261. const connection = await connectRemote(backend, {
  262. appVersion: "2.13.1+build'7",
  263. clientId: "test-client",
  264. skipDeploy: true,
  265. });
  266. connection.dispose();
  267. expect(backend.commands[0]).toContain(`ZCODE_APP_VERSION='2.13.1+build'"'"'7'`);
  268. });
  269. it("启动远端 server 时只注入受控的测试环境 endpoint 变量", async () => {
  270. const backend = new FakeConnectBackend();
  271. const connection = await connectRemote(backend, {
  272. clientId: "test-client",
  273. skipDeploy: true,
  274. remoteRuntimeEnv: {
  275. ZCODE_ENV: "test",
  276. ZCODE_BASE_URL: "https://zcode.z.ai/api/v1",
  277. ZAI_OAUTH_ORIGIN: "https://chat.z.ai",
  278. ZAI_OAUTH_CLIENT_ID: "client_'test",
  279. ZAI_OAUTH_APP_SECRET: "must-not-cross-ssh",
  280. },
  281. });
  282. connection.dispose();
  283. expect(backend.commands[0]).toContain("ZCODE_ENV='test'");
  284. expect(backend.commands[0]).toContain("ZCODE_BASE_URL='https://zcode.z.ai/api/v1'");
  285. expect(backend.commands[0]).toContain("ZAI_OAUTH_ORIGIN='https://chat.z.ai'");
  286. expect(backend.commands[0]).toContain(`ZAI_OAUTH_CLIENT_ID='client_'"'"'test'`);
  287. expect(backend.commands[0]).not.toContain("ZAI_OAUTH_APP_SECRET");
  288. expect(backend.commands[0]).not.toContain("must-not-cross-ssh");
  289. });
  290. it("只把显式 WSL 运行时代理注入远端 server 命令", async () => {
  291. const backend = new FakeConnectBackend();
  292. const resolveRuntimeProxy = vi
  293. .spyOn(backend, "resolveRuntimeProxy")
  294. .mockResolvedValue("http://172.21.240.1:7890/");
  295. const connection = await connectRemote(backend, {
  296. clientId: "test-client",
  297. skipDeploy: true,
  298. remoteRuntimeNetwork: {
  299. authoritative: true,
  300. httpProxy: "http://127.0.0.1:7890",
  301. noProxy: "localhost,127.0.0.1",
  302. },
  303. });
  304. connection.dispose();
  305. expect(resolveRuntimeProxy).toHaveBeenCalledWith("http://127.0.0.1:7890");
  306. expect(backend.commands[0]).toContain("ZCODE_REMOTE_RUNTIME_NETWORK_AUTHORITY='1'");
  307. expect(backend.commands[0]).toContain("ZCODE_REMOTE_HTTP_PROXY='http://172.21.240.1:7890/'");
  308. expect(backend.commands[0]).toContain("ZCODE_REMOTE_NO_PROXY='localhost,127.0.0.1'");
  309. });
  310. it("backend 断连时即使 stdio 未关闭也应上报远端关闭", async () => {
  311. const backend = new FakeConnectBackend();
  312. const closeEvents: Array<{ code: number }> = [];
  313. const connection = await connectRemote(backend, {
  314. clientId: "test-client",
  315. skipDeploy: true,
  316. onDidRemoteClose: (event) => {
  317. closeEvents.push(event);
  318. },
  319. });
  320. backend.fireDisconnect({ reason: "close" });
  321. expect(closeEvents).toEqual([{ code: -1 }]);
  322. connection.dispose();
  323. });
  324. it("backend 断连和 stdio close 同时到达时只上报一次", async () => {
  325. const backend = new FakeConnectBackend();
  326. const closeEvents: Array<{ code: number }> = [];
  327. const connection = await connectRemote(backend, {
  328. clientId: "test-client",
  329. skipDeploy: true,
  330. onDidRemoteClose: (event) => {
  331. closeEvents.push(event);
  332. },
  333. });
  334. backend.fireDisconnect({ reason: "error", error: new Error("socket reset") });
  335. backend.fireStreamClose(7);
  336. expect(closeEvents).toEqual([{ code: -1 }]);
  337. connection.dispose();
  338. });
  339. it("backend error 断连时应记录错误详情", async () => {
  340. const backend = new FakeConnectBackend();
  341. const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
  342. const connection = await connectRemote(backend, {
  343. clientId: "test-client",
  344. skipDeploy: true,
  345. });
  346. try {
  347. backend.fireDisconnect({ reason: "error", error: new Error("socket reset") });
  348. expect(logSpy).toHaveBeenCalledWith(
  349. expect.stringContaining("[connectRemote]"),
  350. expect.stringContaining("socket reset"),
  351. );
  352. } finally {
  353. connection.dispose();
  354. logSpy.mockRestore();
  355. }
  356. });
  357. it("远端 server 握手前退出时应把 stderr 和退出码带到错误信息", async () => {
  358. const backend = new FakeConnectBackend({
  359. code: 126,
  360. stderr: "/bin/sh: 1: /root/.zcode/server/node: Text file busy\n",
  361. });
  362. await expect(
  363. connectRemote(backend, {
  364. clientId: "test-client",
  365. skipDeploy: true,
  366. }),
  367. ).rejects.toThrow(/Stream closed before handshake completed.*exit code 126.*Text file busy/s);
  368. });
  369. });