zcodeAgentService.v4.test.ts 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  1. import { channelReplyHostRequestSchema, type ChannelReplyHostRequest } from "@zcode/shared";
  2. // v4 conversation 通道 host 转发面测试(M3 竖切,docs/v4-refactor/01-topology §host 通道层)。
  3. // 验证 host 只做透传:subscribe/unsubscribe/command 转发给 CLI v4 方法,
  4. // v4/conversation/frame 通知按 workspace fan-out 给 onDynamicConversationFrame 订阅者。
  5. import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  6. import { tmpdir } from "node:os";
  7. import { join } from "node:path";
  8. import { afterEach, describe, expect, it, vi } from "vitest";
  9. import {
  10. TopicWireFrameAssembler,
  11. conversationTopicFrameSchema,
  12. type ConversationTopicWireCandidate,
  13. type ConversationTopicWireFrame,
  14. type SessionsIndexTopicWireCandidate,
  15. type WorkspaceConfigTopicWireCandidate,
  16. } from "@zcode/shared/zcode-protocol-v4";
  17. import { createZCodeAgentConnectionScope } from "../src/zcode-agent/zcodeAgentConnectionScope.js";
  18. import {
  19. createZCodeAgentService,
  20. supportsLegacyRemoteTaskAllowlist,
  21. } from "../src/zcode-agent/zcodeAgentService.js";
  22. import { setDataBaseDir } from "../src/paths.js";
  23. import { TaskIndexRepo } from "../src/session/taskIndexRepo.js";
  24. // 最小 v4 fake agent:
  25. // - v4/conversation/subscribe → 一次 stdout.write 连续写 ACK-only response + initial notification;
  26. // - v4/conversation/unsubscribe → 返回 {};
  27. // - v4/command → 返回 CommandAck accepted。
  28. // 所有入站请求写入 logPath 供断言转发参数。
  29. const V4_FAKE_AGENT = `
  30. const fs = require("node:fs");
  31. const logPath = process.argv[2];
  32. let buf = "";
  33. function send(obj) { process.stdout.write(JSON.stringify(obj) + "\\n"); }
  34. process.stdin.on("data", (chunk) => {
  35. buf += chunk.toString("utf8");
  36. let idx;
  37. while ((idx = buf.indexOf("\\n")) >= 0) {
  38. const line = buf.slice(0, idx);
  39. buf = buf.slice(idx + 1);
  40. if (!line.trim()) continue;
  41. let msg;
  42. try { msg = JSON.parse(line); } catch { continue; }
  43. if (logPath && msg.method) fs.appendFileSync(logPath, line + "\\n");
  44. if (msg.method === "session/debug" && msg.id !== undefined) {
  45. send({ id: msg.id, result: { sessionId: msg.params.sessionId, rounds: [], networkEntries: [], cache: null } });
  46. continue;
  47. }
  48. if (msg.method === "v4/conversation/backgroundBashOutput" && msg.id !== undefined) {
  49. if (msg.params.workId === "unsupported") send({ id: msg.id, error: { code: -32601, message: "Method not found" } });
  50. else send({ id: msg.id, result: { kind: "unavailable", workId: msg.params.workId } });
  51. continue;
  52. }
  53. if (msg.method === "v4/conversation/subscribe" && msg.params.topic.endsWith("/channel-reply-source")) {
  54. send({ id: "reverse-reply", method: "bot/channel/reply", trace: { traceId: "trace-native" }, params: { taskId: "channel-reply-source", inputId: "input-a", toolCallId: "call-a", parts: [{type:"mention",refId:"m1"}] } });
  55. }
  56. if (msg.method === "v4/conversation/subscribe" && msg.params.topic.endsWith("/topic-resource-source")) {
  57. send({ id: "reverse-resource", method: "topic/resource/read", params: { requestId: "resource-a", taskId: "topic-resource-source", inputId: "input-a", authorizationId: "auth-a", messageId: "message-a", resourceIndex: 0 } });
  58. }
  59. if (msg.method === "v4/conversation/subscribe" && msg.id !== undefined) {
  60. const response = {
  61. id: msg.id,
  62. result: {
  63. ack: { subscriptionId: "sub-1", mode: "snapshot", logEpoch: "epoch-1" },
  64. },
  65. };
  66. const route = {
  67. wireVersion: 3,
  68. logicalFrameOrdinal: 1,
  69. topic: msg.params.topic,
  70. subscriptionId: "sub-1",
  71. deliveryKind: "online",
  72. };
  73. let params;
  74. if (msg.params.topic.endsWith("/missing-delivery-kind")) {
  75. params = {
  76. ...route,
  77. deliveryKind: undefined,
  78. kind: "complete",
  79. logicalFrameId: "logical-missing-delivery-kind",
  80. frame: {
  81. topic: msg.params.topic,
  82. subscriptionId: "sub-1",
  83. fromSeq: 0,
  84. toSeq: 0,
  85. sentAt: 1700000000000,
  86. payload: { kind: "deltas", deltas: [] },
  87. },
  88. };
  89. } else if (msg.params.topic.endsWith("/invalid-delivery-kind")) {
  90. params = {
  91. ...route,
  92. deliveryKind: "guessed-recovery",
  93. kind: "complete",
  94. logicalFrameId: "logical-invalid-delivery-kind",
  95. frame: {
  96. topic: msg.params.topic,
  97. subscriptionId: "sub-1",
  98. fromSeq: 0,
  99. toSeq: 0,
  100. sentAt: 1700000000000,
  101. payload: { kind: "deltas", deltas: [] },
  102. },
  103. };
  104. } else if (msg.params.topic.endsWith("/invalid-base64")) {
  105. params = {
  106. ...route,
  107. wireVersion: 3,
  108. kind: "fragment",
  109. logicalFrameId: "logical-invalid",
  110. fragmentIndex: 0,
  111. fragmentCount: 1,
  112. logicalBytes: 1,
  113. checksum: { algorithm: "crc32", value: "00000000" },
  114. dataBase64: "%%%="
  115. };
  116. } else if (msg.params.topic.endsWith("/fragment-count-1025")) {
  117. params = {
  118. ...route,
  119. kind: "fragment",
  120. logicalFrameId: "logical-too-many-fragments",
  121. fragmentIndex: 0,
  122. fragmentCount: 1025,
  123. logicalBytes: 1025,
  124. checksum: { algorithm: "crc32", value: "00000000" },
  125. dataBase64: "AA=="
  126. };
  127. } else if (msg.params.topic.endsWith("/missing-checksum")) {
  128. params = {
  129. ...route,
  130. kind: "fragment",
  131. logicalFrameId: "logical-missing-checksum",
  132. fragmentIndex: 0,
  133. fragmentCount: 1,
  134. logicalBytes: 1,
  135. dataBase64: "AA=="
  136. };
  137. } else if (msg.params.topic.endsWith("/checksum-value-number")) {
  138. params = {
  139. ...route,
  140. kind: "fragment",
  141. logicalFrameId: "logical-checksum-value-number",
  142. fragmentIndex: 0,
  143. fragmentCount: 1,
  144. logicalBytes: 1,
  145. checksum: { algorithm: "crc32", value: 1 },
  146. dataBase64: "AA=="
  147. };
  148. } else if (msg.params.topic.endsWith("/data-base64-number")) {
  149. params = {
  150. ...route,
  151. kind: "fragment",
  152. logicalFrameId: "logical-data-base64-number",
  153. fragmentIndex: 0,
  154. fragmentCount: 1,
  155. logicalBytes: 1,
  156. checksum: { algorithm: "crc32", value: "00000000" },
  157. dataBase64: 1
  158. };
  159. } else if (msg.params.topic.endsWith("/extra-inner-field")) {
  160. params = {
  161. ...route,
  162. kind: "fragment",
  163. logicalFrameId: "logical-extra-inner-field",
  164. fragmentIndex: 0,
  165. fragmentCount: 1,
  166. logicalBytes: 1,
  167. checksum: { algorithm: "crc32", value: "00000000" },
  168. dataBase64: "AA==",
  169. unexpected: true
  170. };
  171. } else if (msg.params.topic.endsWith("/invalid-complete")) {
  172. params = {
  173. ...route,
  174. kind: "complete",
  175. logicalFrameId: "logical-invalid-complete",
  176. frame: { topic: msg.params.topic, subscriptionId: "sub-1" },
  177. };
  178. } else if (msg.params.topic.endsWith("/invalid-checksum-algorithm")) {
  179. params = {
  180. ...route,
  181. kind: "fragment",
  182. logicalFrameId: "logical-invalid-checksum-algorithm",
  183. fragmentIndex: 0,
  184. fragmentCount: 1,
  185. logicalBytes: 1,
  186. checksum: { algorithm: "sha256", value: "00000000" },
  187. dataBase64: "AA=="
  188. };
  189. } else if (msg.params.topic.endsWith("/invalid-checksum-value")) {
  190. params = {
  191. ...route,
  192. kind: "fragment",
  193. logicalFrameId: "logical-invalid-checksum-value",
  194. fragmentIndex: 0,
  195. fragmentCount: 1,
  196. logicalBytes: 1,
  197. checksum: { algorithm: "crc32", value: "not-crc32" },
  198. dataBase64: "AA=="
  199. };
  200. } else {
  201. params = {
  202. ...route,
  203. kind: "complete",
  204. logicalFrameId: "logical-initial",
  205. frame: {
  206. topic: msg.params.topic,
  207. subscriptionId: "sub-1",
  208. fromSeq: 0,
  209. toSeq: 0,
  210. sentAt: 1700000000000,
  211. payload: { kind: "deltas", deltas: [] },
  212. },
  213. };
  214. }
  215. const initial = {
  216. method: "v4/conversation/frame",
  217. params,
  218. };
  219. process.stdout.write(JSON.stringify(response) + "\\n" + JSON.stringify(initial) + "\\n");
  220. }
  221. if (msg.method === "v4/conversation/unsubscribe" && msg.id !== undefined) {
  222. const reply = () => send({ id: msg.id, result: {} });
  223. if (msg.params.topic.endsWith("/delayed-unsubscribe")) setTimeout(reply, 200);
  224. else reply();
  225. }
  226. if (msg.method === "v4/connection/flow" && msg.id !== undefined) {
  227. send({ id: msg.id, result: {} });
  228. }
  229. if (msg.method === "v4/attachment/begin" && msg.id !== undefined) {
  230. send({ id: msg.id, result: { uploadId: msg.params.uploadId, state: "staging", nextChunkIndex: 0 } });
  231. }
  232. if (msg.method === "v4/attachment/chunk" && msg.id !== undefined) {
  233. send({ id: msg.id, result: { uploadId: msg.params.uploadId, nextChunkIndex: msg.params.chunkIndex + 1 } });
  234. }
  235. if (msg.method === "v4/attachment/commit" && msg.id !== undefined) {
  236. send({ id: msg.id, result: { ref: "zcode-artifact://upload/one" } });
  237. }
  238. if (msg.method === "v4/attachment/abort" && msg.id !== undefined) {
  239. send({ id: msg.id, result: {} });
  240. }
  241. if (msg.method === "v4/attachment/previewSource" && msg.id !== undefined) {
  242. send({ id: msg.id, result: {
  243. kind: "local_path",
  244. path: "/tmp/.zcode/video-cache/demo.mp4",
  245. mediaType: "video/mp4"
  246. } });
  247. }
  248. if (msg.method === "v4/conversation/resync" && msg.id !== undefined) {
  249. const response = {
  250. id: msg.id,
  251. result: {
  252. ack: {
  253. subscriptionId: msg.params.subscriptionId,
  254. mode: msg.params.forceSnapshot ? "snapshot" : "resume",
  255. logEpoch: "epoch-1",
  256. },
  257. },
  258. };
  259. const recovery = {
  260. method: "v4/conversation/frame",
  261. params: {
  262. wireVersion: 3,
  263. kind: "complete",
  264. logicalFrameId: "logical-recovery",
  265. logicalFrameOrdinal: 2,
  266. topic: msg.params.topic,
  267. subscriptionId: msg.params.subscriptionId,
  268. deliveryKind: "recovery",
  269. frame: {
  270. topic: msg.params.topic,
  271. subscriptionId: msg.params.subscriptionId,
  272. fromSeq: 0,
  273. toSeq: 0,
  274. sentAt: 1700000000001,
  275. payload: { kind: "deltas", deltas: [] },
  276. },
  277. },
  278. };
  279. const reply = () =>
  280. process.stdout.write(JSON.stringify(response) + "\\n" + JSON.stringify(recovery) + "\\n");
  281. if (msg.params.topic.endsWith("/delayed-resync")) setTimeout(reply, 200);
  282. else reply();
  283. }
  284. if (msg.method === "v4/command" && msg.id !== undefined) {
  285. const status = "accepted";
  286. const acceptedInput = {
  287. delivery: "startNow",
  288. inputId: msg.params.commandId,
  289. messageId: "msg-" + msg.params.commandId,
  290. };
  291. const createSessionResult = msg.params.type === "createSession"
  292. ? { result: { type: "createSession", sessionId: "created-session", input: acceptedInput } }
  293. : msg.params.type === "sendText"
  294. ? { result: { type: "inputAccepted", ...acceptedInput } }
  295. : {};
  296. send({
  297. id: msg.id,
  298. result: {
  299. commandId: msg.params.commandId,
  300. status,
  301. revisionAtDecision: 3,
  302. ...createSessionResult,
  303. },
  304. });
  305. }
  306. if (msg.method === "v4/commands/query" && msg.id !== undefined) {
  307. send({
  308. id: msg.id,
  309. result: {
  310. results: msg.params.commands.map((key) => ({ key, result: "unknown" })),
  311. },
  312. });
  313. }
  314. }
  315. });
  316. `;
  317. function readRequests(logPath: string): Array<{ method: string; params: Record<string, unknown> }> {
  318. if (!existsSync(logPath)) {
  319. return [];
  320. }
  321. return readFileSync(logPath, "utf8")
  322. .trim()
  323. .split("\n")
  324. .filter(Boolean)
  325. .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> });
  326. }
  327. describe("zcodeAgentService v4 conversation channel", () => {
  328. const createdDirs: string[] = [];
  329. afterEach(() => {
  330. setDataBaseDir(null);
  331. for (const dir of createdDirs.splice(0).reverse()) {
  332. // 根因:Windows 不允许删除仍有打开句柄的目录,而 runtime/子进程与 watcher 的句柄
  333. // 是异步收口的;`force: true` 只吞 ENOENT,不做任何重试。于是 afterEach 稳定抛
  334. // `EPERM, Permission denied: \\?\C:\...\Temp\zcode-agent-v4-xxxx`,把已经通过断言
  335. // 的用例判成失败(POSIX 允许删除仍被打开的 inode,所以只在 Windows 上出现)。
  336. // 先用 rm 自带的有界重试等句柄释放;真的等不到也不该让清理决定用例成败,
  337. // 临时目录由操作系统回收。
  338. try {
  339. rmSync(dir, {
  340. recursive: true,
  341. force: true,
  342. maxRetries: 20,
  343. retryDelay: 100,
  344. });
  345. } catch {
  346. /* 清理失败不影响断言结论,交给操作系统回收临时目录。 */
  347. }
  348. }
  349. });
  350. function setupService(
  351. options: {
  352. providerReady?: boolean;
  353. authorizeLocalMediaPreviewPath?: (path: string) => Promise<string>;
  354. channelReplyExecutor?: NonNullable<
  355. Parameters<typeof createZCodeAgentService>[0]
  356. >["channelReplyExecutor"];
  357. topicResourceExecutor?: NonNullable<
  358. Parameters<typeof createZCodeAgentService>[0]
  359. >["topicResourceExecutor"];
  360. } = {},
  361. ) {
  362. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-agent-v4-"));
  363. createdDirs.push(workspacePath);
  364. setDataBaseDir(workspacePath);
  365. const scriptPath = join(workspacePath, "v4-fake-agent.cjs");
  366. const logPath = join(workspacePath, "protocol.log");
  367. writeFileSync(scriptPath, V4_FAKE_AGENT);
  368. const commandResolver = vi.fn(() => ({
  369. command: process.execPath,
  370. args: [scriptPath, logPath],
  371. }));
  372. const service = createZCodeAgentService({
  373. commandResolver,
  374. topicResourceExecutor: options.topicResourceExecutor,
  375. channelReplyExecutor: options.channelReplyExecutor,
  376. authorizeLocalMediaPreviewPath: options.authorizeLocalMediaPreviewPath,
  377. modelSelectionReadinessSource: {
  378. async getView() {
  379. return {
  380. revision: 1,
  381. providers:
  382. options.providerReady === false
  383. ? []
  384. : [
  385. {
  386. providerId: "glm",
  387. config: {
  388. kind: "api" as const,
  389. api: {
  390. type: "openai-chat-completions" as const,
  391. baseUrl: "https://provider.test/v1",
  392. },
  393. models: ["glm-4.6"],
  394. },
  395. models: [{ modelId: "glm-4.6", config: {} }],
  396. },
  397. ],
  398. };
  399. },
  400. },
  401. });
  402. return { service, workspacePath, logPath, commandResolver };
  403. }
  404. it.each([false, true])(
  405. "projects only channel reply scope from a live V4 connection (remote=%s)",
  406. async (remote) => {
  407. const reply = vi.fn(async (value: ChannelReplyHostRequest) => {
  408. // 与实际 Host executor 一样执行严格校验,不能用宽松 spy 掩盖额外连接字段。
  409. channelReplyHostRequestSchema.parse(value);
  410. return { status: "sent" as const, deliveryId: "delivery", providerMessageId: "om_sent" };
  411. });
  412. const { service, workspacePath } = setupService({ channelReplyExecutor: reply });
  413. const scope = remote
  414. ? { workspaceIdentity: "ssh://host/work", remoteSessionId: "logical-session" }
  415. : {};
  416. const target = {
  417. workspacePath,
  418. ...scope,
  419. sessionId: "channel-reply-source",
  420. envelope: { requestId: "transport-request" },
  421. __zcodeTrustedV4Connection: { connectionId: "test-connection" },
  422. };
  423. try {
  424. await service.subscribeConversationV4(target);
  425. await vi.waitFor(() => expect(reply).toHaveBeenCalled());
  426. const received = reply.mock.calls[0]![0];
  427. expect(() => channelReplyHostRequestSchema.parse(received)).not.toThrow();
  428. expect(received).toEqual({
  429. workspacePath,
  430. workspaceIdentity: scope.workspaceIdentity,
  431. remoteSessionId: scope.remoteSessionId,
  432. taskId: "channel-reply-source",
  433. inputId: "input-a",
  434. toolCallId: "call-a",
  435. trace: { traceId: "trace-native" },
  436. parts: [{ type: "mention", refId: "m1" }],
  437. });
  438. } finally {
  439. await service.disposeAllAndWait();
  440. }
  441. },
  442. );
  443. it("carries the active remote session on reverse resource requests after cold warmup", async () => {
  444. const read = vi.fn(async () => {
  445. throw new Error("download intentionally stopped after route capture");
  446. });
  447. const { service, workspacePath } = setupService({ topicResourceExecutor: read });
  448. try {
  449. await service.subscribeConversationV4({
  450. workspacePath,
  451. workspaceIdentity: "ssh://host/work",
  452. sessionId: "warmup",
  453. });
  454. await service.subscribeConversationV4({
  455. workspacePath,
  456. workspaceIdentity: "ssh://host/work",
  457. remoteSessionId: "logical-session",
  458. sessionId: "topic-resource-source",
  459. });
  460. await vi.waitFor(() =>
  461. expect(read).toHaveBeenCalledWith(
  462. expect.objectContaining({
  463. workspaceIdentity: "ssh://host/work",
  464. remoteSessionId: "logical-session",
  465. taskId: "topic-resource-source",
  466. }),
  467. expect.any(AbortSignal),
  468. ),
  469. );
  470. } finally {
  471. await service.disposeAllAndWait();
  472. }
  473. });
  474. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  475. "session debug remains read-only and workspace-scoped on %s",
  476. async (clientMode) => {
  477. const { service, workspacePath, commandResolver, logPath } = setupService();
  478. const scope = createZCodeAgentConnectionScope(service, { connectionId: "debug", clientMode });
  479. const target = {
  480. workspacePath,
  481. workspaceIdentity: "ssh://debug/workspace",
  482. sessionId: "debug-session",
  483. };
  484. try {
  485. await expect(scope.service.readSessionDebug(target)).rejects.toThrow();
  486. expect(commandResolver).not.toHaveBeenCalled();
  487. await scope.service.helloConversationV4();
  488. await scope.service.initializeConversationV4({
  489. kind: "clientHello",
  490. protocolVersion: 3,
  491. clientId: "debug",
  492. appVersion: "test",
  493. });
  494. await scope.service.subscribeConversationV4(target);
  495. expect(await scope.service.readSessionDebug(target)).toEqual({
  496. sessionId: "debug-session",
  497. rounds: [],
  498. networkEntries: [],
  499. cache: null,
  500. });
  501. const lines = readFileSync(logPath, "utf8")
  502. .trim()
  503. .split("\n")
  504. .map((line) => JSON.parse(line));
  505. expect(
  506. lines.filter((line) => line.method === "session/debug").map((line) => line.params),
  507. ).toEqual([{ sessionId: "debug-session" }]);
  508. expect(
  509. lines.some(
  510. (line) => line.method === "session/resume" || line.method === "session/subscribe",
  511. ),
  512. ).toBe(false);
  513. } finally {
  514. scope.dispose();
  515. await service.disposeAllAndWait();
  516. }
  517. },
  518. );
  519. it.each([undefined, { text: "Guarded work" }, { text: "Guarded work", mode: "guarded" }])(
  520. "Guarded create forwards the original payload once (firstInput=%j)",
  521. async (firstInput) => {
  522. const { service, workspacePath, logPath } = setupService();
  523. try {
  524. const payload = {
  525. workspaceId: workspacePath,
  526. config: { mode: "guarded" },
  527. ...(firstInput ? { firstInput } : {}),
  528. };
  529. const ack = await service.sendConversationCommandV4({
  530. workspacePath,
  531. envelope: {
  532. commandId: "guarded-create",
  533. clientId: "guarded-client",
  534. issuedAt: 1,
  535. sessionId: null,
  536. type: "createSession",
  537. payload,
  538. },
  539. });
  540. expect(ack).toMatchObject({
  541. status: "accepted",
  542. result: { type: "createSession", sessionId: "created-session" },
  543. });
  544. const commands = readRequests(logPath).filter((item) => item.method === "v4/command");
  545. // 根因:为不存在的版本错配补写 mode、补发无 revision 的模式命令,改变了原创建合同。
  546. expect(commands).toHaveLength(1);
  547. expect(commands[0]?.params.type).toBe("createSession");
  548. expect(commands[0]?.params.payload).toEqual(payload);
  549. } finally {
  550. await service.disposeAllAndWait();
  551. }
  552. },
  553. );
  554. it("keeps history topics readable without letting the active client bypass provider readiness", async () => {
  555. const { service, workspacePath, logPath, commandResolver } = setupService({
  556. providerReady: false,
  557. });
  558. try {
  559. const sessionsIndex = await service.subscribeSessionsIndexV4({ workspacePath });
  560. const conversation = await service.subscribeConversationV4({
  561. workspacePath,
  562. sessionId: "persisted-session",
  563. });
  564. expect(sessionsIndex.ack.subscriptionId).toBe("sub-1");
  565. expect(conversation.ack.subscriptionId).toBe("sub-1");
  566. expect(conversation.ack.openTiming).toMatchObject({
  567. version: 1,
  568. hostPrepareMs: expect.any(Number),
  569. providerRegistrySyncMs: expect.any(Number),
  570. taskMetaReadMs: expect.any(Number),
  571. cliRequestMs: expect.any(Number),
  572. });
  573. expect(commandResolver).toHaveBeenCalledTimes(1);
  574. // 修复原因:只读 topic 已经登记 active client,旧 fast path 会直接返回它并绕过
  575. // provider/model 门禁。createSession 必须仍在写入协议前确定性拒绝。
  576. await expect(service.createSession({ workspacePath })).rejects.toMatchObject({
  577. code: "ZCODE_AGENT_PROVIDER_NOT_READY",
  578. data: expect.objectContaining({ reason: "provider_not_ready" }),
  579. });
  580. const requests = readRequests(logPath);
  581. expect(
  582. requests
  583. .filter((entry) => entry.method === "v4/conversation/subscribe")
  584. .map((entry) => entry.params.topic),
  585. ).toEqual([`sessions-index/${workspacePath}`, "conversation/persisted-session"]);
  586. expect(requests.some((entry) => entry.method === "session/create")).toBe(false);
  587. } finally {
  588. await service.disposeAllAndWait();
  589. }
  590. });
  591. it("uses the registry view only as a readiness gate for a cold conversation subscription", async () => {
  592. const { service, workspacePath, logPath } = setupService();
  593. try {
  594. await service.subscribeConversationV4({
  595. workspacePath,
  596. sessionId: "cold-registry-session",
  597. });
  598. // Worker 已经持有进程级 Registry;Host 读取 Registry View 只用于启动门禁,
  599. // 不能把完整 Registry 下发成另一份执行事实源。
  600. expect(readRequests(logPath).map((entry) => entry.method)).toEqual([
  601. "v4/conversation/subscribe",
  602. ]);
  603. expect(
  604. readRequests(logPath).find((entry) => entry.method === "v4/conversation/subscribe")?.params,
  605. ).toMatchObject({
  606. workspace: {
  607. workspaceKey: workspacePath,
  608. workspacePath,
  609. },
  610. });
  611. } finally {
  612. await service.disposeAllAndWait();
  613. }
  614. });
  615. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  616. "background Bash query stays existing-only on %s",
  617. async (clientMode) => {
  618. const { service, workspacePath, commandResolver, logPath } = setupService();
  619. const scope = createZCodeAgentConnectionScope(service, {
  620. connectionId: "bash-query",
  621. clientMode,
  622. });
  623. const target = {
  624. workspacePath,
  625. workspaceIdentity: "ssh://bash-query/workspace",
  626. sessionId: "child",
  627. workId: "work",
  628. };
  629. try {
  630. await scope.service.helloConversationV4();
  631. await scope.service.initializeConversationV4({
  632. kind: "clientHello",
  633. protocolVersion: 3,
  634. clientId: "bash-query",
  635. appVersion: "test",
  636. });
  637. expect(await scope.service.backgroundBashOutputV4(target)).toEqual({
  638. kind: "unavailable",
  639. workId: "work",
  640. });
  641. expect(commandResolver).not.toHaveBeenCalled();
  642. await scope.service.subscribeConversationV4(target);
  643. expect(await scope.service.backgroundBashOutputV4(target)).toEqual({
  644. kind: "unavailable",
  645. workId: "work",
  646. });
  647. expect(commandResolver).toHaveBeenCalledTimes(1);
  648. const requests = readRequests(logPath);
  649. expect(
  650. requests
  651. .filter((entry) => entry.method === "v4/conversation/backgroundBashOutput")
  652. .map((entry) => entry.params),
  653. ).toEqual([{ sessionId: "child", workId: "work" }]);
  654. expect(requests.some((entry) => entry.method === "v4/command")).toBe(false);
  655. expect(
  656. await scope.service.backgroundBashOutputV4({ ...target, workId: "unsupported" }),
  657. ).toEqual({ kind: "unsupported", workId: "unsupported" });
  658. } finally {
  659. scope.dispose();
  660. await service.disposeAllAndWait();
  661. }
  662. },
  663. );
  664. it("existing-only subscriptions stay dormant until another operation starts the runtime", async () => {
  665. const { service, workspacePath, commandResolver } = setupService();
  666. const lifecycle: Array<{ state: "available" | "unavailable"; generation: number }> = [];
  667. const disposable = service.onAgentRuntimeLifecycle?.((event) => {
  668. lifecycle.push({
  669. state: event.state,
  670. generation: event.runtimeIdentity.generation,
  671. });
  672. });
  673. try {
  674. await expect(
  675. service.subscribeSessionsIndexV4({
  676. workspacePath,
  677. runtimePolicy: "existing-only",
  678. }),
  679. ).rejects.toMatchObject({ code: "ZCODE_AGENT_RUNTIME_UNAVAILABLE" });
  680. expect(commandResolver).not.toHaveBeenCalled();
  681. expect(lifecycle).toEqual([]);
  682. await service.subscribeConversationV4({
  683. workspacePath,
  684. sessionId: "explicit-user-session",
  685. });
  686. await service.subscribeSessionsIndexV4({
  687. workspacePath,
  688. runtimePolicy: "existing-only",
  689. });
  690. expect(commandResolver).toHaveBeenCalledTimes(1);
  691. expect(lifecycle).toEqual([{ state: "available", generation: 1 }]);
  692. await service.disposeWorkspace({ workspacePath });
  693. expect(lifecycle).toEqual([
  694. { state: "available", generation: 1 },
  695. { state: "unavailable", generation: 1 },
  696. ]);
  697. } finally {
  698. disposable?.dispose();
  699. await service.disposeAllAndWait();
  700. }
  701. });
  702. // `workflowRunDeltas` 与 `clientMode` 同族(10 §3.1):可信 host 从连接的 clientHello 注入,
  703. // UI 面的 subscribe 入参碰不到它——一个客户端认不认得 `workflowRun.*` 增量是**连接**的事实。
  704. it.each([true, false])(
  705. "subscribe 的 workflowRunDeltas 只由 clientHello 声明决定(declared=%s)",
  706. async (declared) => {
  707. const { service, workspacePath, logPath } = setupService();
  708. const scope = createZCodeAgentConnectionScope(service, {
  709. connectionId: "workflow-run-deltas",
  710. clientMode: "desktop-continuous",
  711. });
  712. try {
  713. const hello = await scope.service.helloConversationV4();
  714. expect(hello.capabilities.workflowRunDeltas).toBe(true);
  715. await scope.service.initializeConversationV4({
  716. kind: "clientHello",
  717. protocolVersion: 3,
  718. clientId: "workflow-run-deltas",
  719. appVersion: "test",
  720. ...(declared ? { capabilities: { workflowRunDeltas: true } } : {}),
  721. });
  722. await scope.service.subscribeConversationV4({
  723. workspacePath,
  724. sessionId: "workflow-run-deltas-session",
  725. // 调用方自报的同名字段:必须被可信值整个顶掉,两种声明下都不能生效。
  726. workflowRunDeltas: !declared,
  727. } as never);
  728. const params = readRequests(logPath).find(
  729. (entry) => entry.method === "v4/conversation/subscribe",
  730. )?.params;
  731. if (declared) {
  732. expect(params).toMatchObject({ workflowRunDeltas: true });
  733. } else {
  734. expect(params).not.toHaveProperty("workflowRunDeltas");
  735. }
  736. } finally {
  737. scope.dispose();
  738. await service.disposeAllAndWait();
  739. }
  740. },
  741. );
  742. it("forwards task-local thought only as a V4 cold-resume hint", async () => {
  743. const { service, workspacePath, logPath } = setupService();
  744. const repo = new TaskIndexRepo();
  745. try {
  746. await repo.syncTaskMeta({
  747. meta: {
  748. taskId: "persisted-thought-session",
  749. traceId: "trace-persisted-thought-session",
  750. title: "persisted thought session",
  751. workspacePath,
  752. createdAt: 1,
  753. updatedAt: 2,
  754. mode: "build",
  755. provider: "glm",
  756. model: "glm/GLM-5.2",
  757. thoughtLevel: "max",
  758. },
  759. });
  760. await service.subscribeConversationV4({
  761. workspacePath,
  762. sessionId: "persisted-thought-session",
  763. });
  764. const request = readRequests(logPath).find(
  765. (entry) => entry.method === "v4/conversation/subscribe",
  766. );
  767. expect(request?.params).toMatchObject({
  768. topic: "conversation/persisted-thought-session",
  769. clientMode: "desktop-continuous",
  770. resumeThoughtLevel: "max",
  771. });
  772. } finally {
  773. repo.close();
  774. await service.disposeAllAndWait();
  775. }
  776. });
  777. it("forwards trusted continuous connection context and fans out frames per workspace", async () => {
  778. const { service, workspacePath, logPath } = setupService();
  779. try {
  780. const frames: ConversationTopicWireFrame[] = [];
  781. const disposable = service.onDynamicConversationFrame({ workspacePath })((frame) => {
  782. frames.push(frame);
  783. });
  784. const hello = await service.helloConversationV4();
  785. await service.initializeConversationV4({
  786. kind: "clientHello",
  787. protocolVersion: 3,
  788. clientId: "client-1",
  789. appVersion: "4.0.0",
  790. });
  791. expect(hello).toMatchObject({
  792. clientMode: "desktop-continuous",
  793. deliveryProfile: "continuous",
  794. });
  795. const result = await service.subscribeConversationV4({
  796. workspacePath,
  797. sessionId: "s1",
  798. });
  799. expect(result.ack).toMatchObject({
  800. subscriptionId: "sub-1",
  801. mode: "snapshot",
  802. logEpoch: "epoch-1",
  803. });
  804. expect(result.ack.openTiming).toMatchObject({
  805. version: 1,
  806. hostPrepareMs: expect.any(Number),
  807. cliProcessState: "spawned",
  808. });
  809. expect(result).toEqual({ ack: result.ack });
  810. await vi.waitFor(() => {
  811. expect(frames).toHaveLength(1);
  812. });
  813. expect(frames[0]).toMatchObject({
  814. topic: "conversation/s1",
  815. subscriptionId: "sub-1",
  816. kind: "complete",
  817. frame: { payload: { kind: "deltas", deltas: [] } },
  818. });
  819. const subscribeRequest = readRequests(logPath).find(
  820. (entry) => entry.method === "v4/conversation/subscribe",
  821. );
  822. expect(subscribeRequest?.params.topic).toBe("conversation/s1");
  823. expect(subscribeRequest?.params.clientMode).toBe("desktop-continuous");
  824. expect(subscribeRequest?.params).not.toHaveProperty("deliveryProfile");
  825. // 这条 clientHello 没有 capabilities:订阅就不能带增量位,CLI 按旧消费者发整键 patch。
  826. expect(subscribeRequest?.params).not.toHaveProperty("workflowRunDeltas");
  827. expect(typeof subscribeRequest?.params.connectionId).toBe("string");
  828. expect(String(subscribeRequest?.params.connectionId)).toMatch(/^host-/);
  829. disposable.dispose();
  830. } finally {
  831. await service.disposeAllAndWait();
  832. }
  833. });
  834. it("labels mobile input from the trusted attachment instead of caller metadata", async () => {
  835. const { service, workspacePath, logPath } = setupService();
  836. const scope = createZCodeAgentConnectionScope(service, {
  837. connectionId: "group-mobile-origin",
  838. clientMode: "web-remote-replayable",
  839. });
  840. try {
  841. await scope.service.helloConversationV4();
  842. await scope.service.initializeConversationV4({
  843. kind: "clientHello",
  844. protocolVersion: 3,
  845. clientId: "origin-client",
  846. appVersion: "4.0.0",
  847. });
  848. await scope.service.sendConversationCommandV4({
  849. workspacePath,
  850. clientMode: "desktop-continuous",
  851. envelope: {
  852. commandId: "origin-command",
  853. clientId: "origin-client",
  854. sessionId: "origin-session",
  855. type: "sendText",
  856. issuedAt: 1,
  857. payload: { text: "hello", inputOrigin: "desktop" },
  858. },
  859. });
  860. expect(
  861. readRequests(logPath).find((entry) => entry.method === "v4/command")?.params,
  862. ).toMatchObject({ payload: { text: "hello", inputOrigin: "mobile" } });
  863. } finally {
  864. await scope.dispose();
  865. await service.disposeAllAndWait();
  866. }
  867. });
  868. it("does not carry runtime preferences on v4 create, send, or subscribe", async () => {
  869. const { service, workspacePath, logPath } = setupService();
  870. try {
  871. await service.sendConversationCommandV4({
  872. workspacePath,
  873. envelope: {
  874. commandId: "cmd-runtime-preferences-create",
  875. clientId: "client-runtime-preferences",
  876. sessionId: null,
  877. type: "createSession",
  878. payload: { workspaceId: workspacePath },
  879. issuedAt: 1_700_000_000_000,
  880. },
  881. });
  882. await service.sendConversationCommandV4({
  883. workspacePath,
  884. envelope: {
  885. commandId: "cmd-runtime-preferences-send",
  886. clientId: "client-runtime-preferences",
  887. sessionId: "s-runtime-preferences",
  888. type: "sendText",
  889. payload: { text: "continue" },
  890. issuedAt: 1_700_000_000_001,
  891. },
  892. });
  893. await service.subscribeConversationV4({
  894. workspacePath,
  895. sessionId: "s-runtime-preferences",
  896. });
  897. const requests = readRequests(logPath);
  898. const commands = requests.filter((entry) => entry.method === "v4/command");
  899. expect(commands[0]?.params).toMatchObject({
  900. type: "createSession",
  901. payload: { workspaceId: workspacePath },
  902. });
  903. expect(commands[1]?.params).toMatchObject({
  904. type: "sendText",
  905. payload: { text: "continue" },
  906. });
  907. for (const command of commands) {
  908. expect(command.params.payload).not.toHaveProperty("nativeSearchEnhancementsEnabled");
  909. expect(command.params.payload).not.toHaveProperty("memoryEnabled");
  910. expect(command.params.payload).not.toHaveProperty("integratedTerminalShell");
  911. }
  912. const subscribe = requests.find((entry) => entry.method === "v4/conversation/subscribe");
  913. expect(subscribe?.params).not.toHaveProperty("nativeSearchEnhancementsEnabled");
  914. expect(subscribe?.params).not.toHaveProperty("memoryEnabled");
  915. expect(subscribe?.params).not.toHaveProperty("integratedTerminalShell");
  916. } finally {
  917. await service.disposeAllAndWait();
  918. }
  919. });
  920. it("SSH sessions-index 只传递当前 identity 的 GLM task-index 归属证明", async () => {
  921. const { service, workspacePath, logPath } = setupService();
  922. const repo = new TaskIndexRepo();
  923. const workspaceIdentity = `remote:ssh:example.test:22:coder:${workspacePath}`;
  924. const foreignWorkspaceIdentity = `remote:ssh:other.example.test:22:coder:${workspacePath}`;
  925. try {
  926. await repo.syncTaskMeta({
  927. meta: {
  928. taskId: "legacy-current-ssh",
  929. traceId: "trace-legacy-current-ssh",
  930. title: "current SSH legacy task",
  931. workspacePath,
  932. workspaceIdentity,
  933. createdAt: 1,
  934. updatedAt: 2,
  935. mode: "build",
  936. provider: "glm",
  937. },
  938. });
  939. await repo.syncTaskMeta({
  940. meta: {
  941. taskId: "legacy-foreign-ssh",
  942. traceId: "trace-legacy-foreign-ssh",
  943. title: "foreign SSH legacy task",
  944. workspacePath,
  945. workspaceIdentity: foreignWorkspaceIdentity,
  946. createdAt: 1,
  947. updatedAt: 3,
  948. mode: "build",
  949. provider: "glm",
  950. },
  951. });
  952. await service.subscribeSessionsIndexV4({ workspacePath, workspaceIdentity });
  953. const subscribeRequest = readRequests(logPath).find(
  954. (entry) => entry.method === "v4/conversation/subscribe",
  955. );
  956. expect(subscribeRequest?.params).toMatchObject({
  957. topic: `sessions-index/${workspaceIdentity}`,
  958. legacyTaskIds: ["legacy-current-ssh"],
  959. });
  960. } finally {
  961. repo.close();
  962. await service.disposeAllAndWait();
  963. }
  964. });
  965. it("历史任务 allowlist 只开放 SSH 与 WSL identity", () => {
  966. expect(supportsLegacyRemoteTaskAllowlist("remote:ssh:host:22:user:/repo")).toBe(true);
  967. expect(supportsLegacyRemoteTaskAllowlist("remote:wsl:Ubuntu-24.04:user:/repo")).toBe(true);
  968. expect(supportsLegacyRemoteTaskAllowlist("remote:docker:container:/repo")).toBe(false);
  969. expect(supportsLegacyRemoteTaskAllowlist("/repo")).toBe(false);
  970. });
  971. it("forwards connection flow only through the non-RPC trusted scope control", async () => {
  972. const { service, workspacePath, logPath } = setupService();
  973. const scope = createZCodeAgentConnectionScope(service, {
  974. connectionId: "mobile-flow",
  975. clientMode: "web-remote-replayable",
  976. });
  977. try {
  978. await scope.service.helloConversationV4();
  979. await scope.service.initializeConversationV4({
  980. kind: "clientHello",
  981. protocolVersion: 3,
  982. clientId: "mobile-flow-client",
  983. appVersion: "4.0.0",
  984. });
  985. await scope.service.subscribeConversationV4({ workspacePath, sessionId: "s-flow" });
  986. await scope.setTransportFlowState("saturated");
  987. const flowRequest = readRequests(logPath).find(
  988. (entry) => entry.method === "v4/connection/flow",
  989. );
  990. expect(flowRequest?.params).toEqual({
  991. connectionId: "mobile-flow",
  992. state: "saturated",
  993. });
  994. await expect(
  995. scope.service.setConnectionFlowStateV4({ workspacePath, state: "drained" }),
  996. ).rejects.toThrow("fault.connection.flowControlForbidden");
  997. } finally {
  998. await scope.dispose();
  999. await service.disposeAllAndWait();
  1000. }
  1001. });
  1002. it("forwards chunked attachment methods with trusted connection and <=1MiB NDJSON", async () => {
  1003. const { service, workspacePath, logPath } = setupService();
  1004. await expect(
  1005. service.attachmentBeginV4({
  1006. workspacePath,
  1007. sessionId: "s-upload",
  1008. uploadId: "untrusted",
  1009. fileName: "nope.bin",
  1010. mime: "application/octet-stream",
  1011. totalBytes: 0,
  1012. totalChunks: 0,
  1013. checksum: `sha256:${"0".repeat(64)}`,
  1014. }),
  1015. ).rejects.toThrow("fault.attachment.connectionUntrusted");
  1016. const scope = createZCodeAgentConnectionScope(service, {
  1017. connectionId: "mobile-upload",
  1018. clientMode: "web-remote-replayable",
  1019. });
  1020. try {
  1021. await scope.service.helloConversationV4();
  1022. await scope.service.initializeConversationV4({
  1023. kind: "clientHello",
  1024. protocolVersion: 3,
  1025. clientId: "mobile-upload-client",
  1026. appVersion: "4.0.0",
  1027. });
  1028. const common = { workspacePath, sessionId: "s-upload", uploadId: "upload-1" };
  1029. await scope.service.attachmentBeginV4({
  1030. ...common,
  1031. fileName: "big.bin",
  1032. mime: "application/octet-stream",
  1033. totalBytes: 512 * 1024,
  1034. totalChunks: 1,
  1035. checksum: `sha256:${"0".repeat(64)}`,
  1036. });
  1037. await scope.service.attachmentChunkV4({
  1038. ...common,
  1039. chunkIndex: 0,
  1040. dataBase64: Buffer.alloc(512 * 1024).toString("base64"),
  1041. });
  1042. await expect(scope.service.attachmentCommitV4(common)).resolves.toEqual({
  1043. ref: "zcode-artifact://upload/one",
  1044. });
  1045. await scope.service.attachmentAbortV4(common);
  1046. const attachmentLines = readFileSync(logPath, "utf8")
  1047. .split("\n")
  1048. .filter((line) => line.includes('"method":"v4/attachment/'));
  1049. expect(attachmentLines).toHaveLength(4);
  1050. for (const line of attachmentLines) {
  1051. expect(Buffer.byteLength(`${line}\n`, "utf8")).toBeLessThanOrEqual(1024 * 1024);
  1052. expect(JSON.parse(line).params.connectionId).toBe("mobile-upload");
  1053. }
  1054. } finally {
  1055. await scope.dispose();
  1056. await service.disposeAllAndWait();
  1057. }
  1058. });
  1059. it("only queries a local video source for Desktop local connections", async () => {
  1060. const authorizeLocalMediaPreviewPath = vi.fn(async () => "/real/video-cache/demo.mp4");
  1061. const { service, workspacePath, logPath } = setupService({
  1062. authorizeLocalMediaPreviewPath,
  1063. });
  1064. const desktop = createZCodeAgentConnectionScope(service, {
  1065. connectionId: "desktop-preview",
  1066. clientMode: "desktop-continuous",
  1067. });
  1068. const mobile = createZCodeAgentConnectionScope(service, {
  1069. connectionId: "mobile-preview",
  1070. clientMode: "web-remote-replayable",
  1071. });
  1072. try {
  1073. for (const [scope, clientId] of [
  1074. [desktop, "desktop-preview-client"],
  1075. [mobile, "mobile-preview-client"],
  1076. ] as const) {
  1077. await scope.service.helloConversationV4();
  1078. await scope.service.initializeConversationV4({
  1079. kind: "clientHello",
  1080. protocolVersion: 3,
  1081. clientId,
  1082. appVersion: "4.0.0",
  1083. });
  1084. }
  1085. const input = {
  1086. workspacePath,
  1087. sessionId: "s-preview",
  1088. ref: "/tmp/demo.mp4",
  1089. target: { rowId: 2, entityId: "message-preview" },
  1090. attachmentIndex: 0,
  1091. };
  1092. await expect(desktop.service.attachmentPreviewSourceV4(input)).resolves.toEqual({
  1093. kind: "local_path",
  1094. path: "/real/video-cache/demo.mp4",
  1095. mediaType: "video/mp4",
  1096. });
  1097. expect(authorizeLocalMediaPreviewPath).toHaveBeenCalledOnce();
  1098. expect(authorizeLocalMediaPreviewPath).toHaveBeenCalledWith(
  1099. "/tmp/.zcode/video-cache/demo.mp4",
  1100. );
  1101. await expect(mobile.service.attachmentPreviewSourceV4(input)).resolves.toEqual({
  1102. kind: "chunked",
  1103. });
  1104. await expect(
  1105. desktop.service.attachmentPreviewSourceV4({
  1106. ...input,
  1107. remoteSessionId: "remote-session",
  1108. }),
  1109. ).resolves.toEqual({ kind: "chunked" });
  1110. const sourceLines = readFileSync(logPath, "utf8")
  1111. .split("\n")
  1112. .filter((line) => line.includes('"method":"v4/attachment/previewSource"'));
  1113. expect(sourceLines).toHaveLength(1);
  1114. expect(JSON.parse(sourceLines[0]!).params).toMatchObject({
  1115. clientMode: "desktop-continuous",
  1116. sessionId: "s-preview",
  1117. attachmentIndex: 0,
  1118. });
  1119. } finally {
  1120. await desktop.dispose();
  1121. await mobile.dispose();
  1122. await service.disposeAllAndWait();
  1123. }
  1124. });
  1125. it("fails closed when Main cannot authorize a Desktop local preview path", async () => {
  1126. const { service, workspacePath } = setupService({
  1127. authorizeLocalMediaPreviewPath: async () => {
  1128. throw new Error("preview path authorization failed");
  1129. },
  1130. });
  1131. const desktop = createZCodeAgentConnectionScope(service, {
  1132. connectionId: "desktop-preview-failed",
  1133. clientMode: "desktop-continuous",
  1134. });
  1135. try {
  1136. await desktop.service.helloConversationV4();
  1137. await desktop.service.initializeConversationV4({
  1138. kind: "clientHello",
  1139. protocolVersion: 3,
  1140. clientId: "desktop-preview-failed-client",
  1141. appVersion: "4.0.0",
  1142. });
  1143. await expect(
  1144. desktop.service.attachmentPreviewSourceV4({
  1145. workspacePath,
  1146. sessionId: "s-preview",
  1147. ref: "/tmp/demo.mp4",
  1148. target: { rowId: 2, entityId: "message-preview" },
  1149. attachmentIndex: 0,
  1150. }),
  1151. ).rejects.toThrow("preview path authorization failed");
  1152. } finally {
  1153. await desktop.dispose();
  1154. await service.disposeAllAndWait();
  1155. }
  1156. });
  1157. it.each([
  1158. ["missing-delivery-kind", "proto.frameAssemblyMetadataMismatch"],
  1159. ["invalid-delivery-kind", "proto.frameAssemblyMetadataMismatch"],
  1160. ["invalid-base64", "proto.frameAssemblyInvalidBase64"],
  1161. ["fragment-count-1025", "proto.frameFragmentCountExceeded"],
  1162. ["missing-checksum", "proto.frameAssemblyMetadataMismatch"],
  1163. ["checksum-value-number", "proto.frameAssemblyMetadataMismatch"],
  1164. ["data-base64-number", "proto.frameAssemblyMetadataMismatch"],
  1165. ["extra-inner-field", "proto.frameAssemblyMetadataMismatch"],
  1166. ["invalid-complete", "proto.frameAssemblyInvalidPayload"],
  1167. ["invalid-checksum-algorithm", "proto.frameAssemblyMetadataMismatch"],
  1168. ["invalid-checksum-value", "proto.frameAssemblyMetadataMismatch"],
  1169. ] as const)(
  1170. "routes %s through service → owned facade → assembler typed fault",
  1171. async (sessionId, reasonCode) => {
  1172. const { service, workspacePath } = setupService();
  1173. const scope = createZCodeAgentConnectionScope(service, {
  1174. connectionId: `test-${sessionId}`,
  1175. clientMode: "desktop-continuous",
  1176. });
  1177. try {
  1178. await scope.service.helloConversationV4();
  1179. await scope.service.initializeConversationV4({
  1180. kind: "clientHello",
  1181. protocolVersion: 3,
  1182. clientId: "owned-consumer",
  1183. appVersion: "4.0.0",
  1184. });
  1185. const candidates: ConversationTopicWireCandidate[] = [];
  1186. const disposable = scope.service.onDynamicConversationFrame({ workspacePath })((wire) =>
  1187. candidates.push(wire),
  1188. );
  1189. await scope.service.subscribeConversationV4({ workspacePath, sessionId });
  1190. await vi.waitFor(() => expect(candidates).toHaveLength(1));
  1191. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  1192. expect(assembler.accept(candidates[0]!)).toMatchObject([
  1193. { kind: "fault", fault: { reasonCode } },
  1194. ]);
  1195. disposable.dispose();
  1196. } finally {
  1197. await scope.dispose();
  1198. await service.disposeAllAndWait();
  1199. }
  1200. },
  1201. );
  1202. it("records subscribe route and forwards exact topic/subscription/connection on unsubscribe", async () => {
  1203. const { service, workspacePath, logPath } = setupService();
  1204. try {
  1205. const ack = await service.sendConversationCommandV4({
  1206. workspacePath,
  1207. envelope: {
  1208. commandId: "cmd-1",
  1209. clientId: "client-1",
  1210. sessionId: "s1",
  1211. type: "sendText",
  1212. payload: { text: "hello" },
  1213. issuedAt: 1700000000000,
  1214. },
  1215. });
  1216. expect(ack).toEqual({
  1217. commandId: "cmd-1",
  1218. status: "accepted",
  1219. revisionAtDecision: 3,
  1220. result: {
  1221. type: "inputAccepted",
  1222. delivery: "startNow",
  1223. inputId: "cmd-1",
  1224. messageId: "msg-cmd-1",
  1225. },
  1226. });
  1227. await service.subscribeConversationV4({
  1228. workspacePath,
  1229. sessionId: "s1",
  1230. });
  1231. await service.unsubscribeConversationV4({ workspacePath, subscriptionId: "sub-1" });
  1232. const requests = readRequests(logPath);
  1233. const commandRequest = requests.find((entry) => entry.method === "v4/command");
  1234. expect(commandRequest?.params).toMatchObject({
  1235. commandId: "cmd-1",
  1236. type: "sendText",
  1237. payload: { text: "hello" },
  1238. });
  1239. const unsubscribeRequest = requests.find(
  1240. (entry) => entry.method === "v4/conversation/unsubscribe",
  1241. );
  1242. const subscribeRequest = requests.find(
  1243. (entry) => entry.method === "v4/conversation/subscribe",
  1244. );
  1245. expect(unsubscribeRequest?.params).toEqual({
  1246. topic: "conversation/s1",
  1247. subscriptionId: "sub-1",
  1248. connectionId: subscribeRequest?.params.connectionId,
  1249. });
  1250. } finally {
  1251. await service.disposeAllAndWait();
  1252. }
  1253. });
  1254. it("keeps automation mutation tools for desktop user turns in cron-owned sessions", async () => {
  1255. const { service, workspacePath, logPath } = setupService();
  1256. const repo = new TaskIndexRepo();
  1257. try {
  1258. await repo.syncTaskMeta({
  1259. meta: {
  1260. taskId: "cron-session",
  1261. traceId: "trace-cron-session",
  1262. title: "cron session",
  1263. workspacePath,
  1264. createdAt: 1,
  1265. updatedAt: 2,
  1266. mode: "build",
  1267. provider: "glm",
  1268. cronAutomationId: "automation-cron",
  1269. },
  1270. });
  1271. await service.sendConversationCommandV4({
  1272. workspacePath,
  1273. envelope: {
  1274. commandId: "cmd-followup",
  1275. clientId: "desktop-client",
  1276. sessionId: "cron-session",
  1277. type: "sendText",
  1278. payload: { text: "再帮我建一个每5分钟提醒" },
  1279. issuedAt: 1700000000000,
  1280. },
  1281. });
  1282. const commandRequest = readRequests(logPath).find((entry) => entry.method === "v4/command");
  1283. expect(commandRequest?.params).toMatchObject({
  1284. commandId: "cmd-followup",
  1285. type: "sendText",
  1286. payload: {
  1287. text: "再帮我建一个每5分钟提醒",
  1288. },
  1289. });
  1290. expect(commandRequest?.params.payload).not.toHaveProperty("automationId");
  1291. expect(commandRequest?.params.payload).not.toHaveProperty("toolDisallowlist");
  1292. } finally {
  1293. repo.close();
  1294. await service.disposeAllAndWait();
  1295. }
  1296. });
  1297. it("hides automation mutation tools only for the current automation execution turn", async () => {
  1298. const { service, workspacePath, logPath } = setupService();
  1299. try {
  1300. await service.sendConversationCommandV4({
  1301. workspacePath,
  1302. envelope: {
  1303. commandId: "cmd-automation-run",
  1304. clientId: "desktop-client",
  1305. sessionId: "cron-session",
  1306. type: "sendText",
  1307. payload: {
  1308. text: "执行定时任务",
  1309. automationId: "automation-cron",
  1310. toolDisallowlist: ["ExistingDeniedTool"],
  1311. },
  1312. issuedAt: 1700000000000,
  1313. },
  1314. });
  1315. const commandRequest = readRequests(logPath).find((entry) => entry.method === "v4/command");
  1316. expect(commandRequest?.params.payload).toEqual({
  1317. inputOrigin: "desktop",
  1318. text: "执行定时任务",
  1319. automationId: "automation-cron",
  1320. toolDisallowlist: ["ExistingDeniedTool", "CronCreate", "CronUpdate", "CronDelete"],
  1321. });
  1322. } finally {
  1323. await service.disposeAllAndWait();
  1324. }
  1325. });
  1326. it("does not consult cron ownership metadata for a normal desktop user turn", async () => {
  1327. const { service, workspacePath, logPath } = setupService();
  1328. const getTaskMeta = vi
  1329. .spyOn(TaskIndexRepo.prototype, "getTaskMeta")
  1330. .mockRejectedValueOnce(new Error("task index unavailable"));
  1331. try {
  1332. await service.sendConversationCommandV4({
  1333. workspacePath,
  1334. envelope: {
  1335. commandId: "cmd-ownership-unknown",
  1336. clientId: "desktop-client",
  1337. sessionId: "unknown-session",
  1338. type: "sendText",
  1339. payload: { text: "继续正常对话" },
  1340. issuedAt: 1700000000000,
  1341. },
  1342. });
  1343. const commandRequest = readRequests(logPath).find((entry) => entry.method === "v4/command");
  1344. expect(commandRequest?.params).toMatchObject({
  1345. commandId: "cmd-ownership-unknown",
  1346. type: "sendText",
  1347. payload: {
  1348. text: "继续正常对话",
  1349. },
  1350. });
  1351. expect(commandRequest?.params.payload).not.toHaveProperty("toolDisallowlist");
  1352. expect(getTaskMeta).not.toHaveBeenCalled();
  1353. } finally {
  1354. getTaskMeta.mockRestore();
  1355. await service.disposeAllAndWait();
  1356. }
  1357. });
  1358. it("PV4-24 web-remote replayable 在 shared host 原样透传组合 rewind 命令", async () => {
  1359. const { service, workspacePath, logPath, commandResolver } = setupService();
  1360. const workspaceIdentity = "ssh://rewind-e2e/workspace";
  1361. const scope = createZCodeAgentConnectionScope(service, {
  1362. connectionId: "mobile-rewind",
  1363. clientMode: "web-remote-replayable",
  1364. });
  1365. try {
  1366. await scope.service.helloConversationV4();
  1367. await scope.service.initializeConversationV4({
  1368. kind: "clientHello",
  1369. protocolVersion: 3,
  1370. clientId: "mobile-rewind-client",
  1371. appVersion: "4.0.0",
  1372. });
  1373. await scope.service.subscribeConversationV4({
  1374. workspacePath,
  1375. workspaceIdentity,
  1376. sessionId: "s-mobile-rewind",
  1377. });
  1378. const ack = await scope.service.sendConversationCommandV4({
  1379. workspacePath,
  1380. workspaceIdentity,
  1381. envelope: {
  1382. commandId: "cmd-mobile-rewind",
  1383. clientId: "mobile-rewind-client",
  1384. sessionId: "s-mobile-rewind",
  1385. type: "editUserQuery",
  1386. baseRevision: 12,
  1387. baseLogEpoch: "epoch-mobile",
  1388. payload: {
  1389. target: { rowId: 18, entityId: "msg-mobile-user" },
  1390. newText: "mobile edited query",
  1391. workspaceMode: "rewind",
  1392. },
  1393. issuedAt: 1700000000000,
  1394. },
  1395. });
  1396. expect(ack).toMatchObject({
  1397. commandId: "cmd-mobile-rewind",
  1398. status: "accepted",
  1399. });
  1400. const requests = readRequests(logPath);
  1401. expect(
  1402. requests.find((entry) => entry.method === "v4/conversation/subscribe")?.params,
  1403. ).toMatchObject({
  1404. clientMode: "web-remote-replayable",
  1405. connectionId: "mobile-rewind",
  1406. topic: "conversation/s-mobile-rewind",
  1407. });
  1408. expect(requests.find((entry) => entry.method === "v4/command")?.params).toEqual({
  1409. commandId: "cmd-mobile-rewind",
  1410. clientId: "mobile-rewind-client",
  1411. sessionId: "s-mobile-rewind",
  1412. type: "editUserQuery",
  1413. baseRevision: 12,
  1414. baseLogEpoch: "epoch-mobile",
  1415. payload: {
  1416. target: { rowId: 18, entityId: "msg-mobile-user" },
  1417. newText: "mobile edited query",
  1418. workspaceMode: "rewind",
  1419. },
  1420. issuedAt: 1700000000000,
  1421. });
  1422. // 同一 workspaceIdentity 的 subscribe + command 复用同一 host child,
  1423. // 手机端不单独创建 Agent runtime,relay/main 也不持有 rewind 状态。
  1424. expect(commandResolver).toHaveBeenCalledTimes(1);
  1425. } finally {
  1426. await scope.dispose();
  1427. await service.disposeAllAndWait();
  1428. }
  1429. });
  1430. it("commands/query 经真实 child process wire 保序,且 64 cap/可信 scope 在 service 边界执行", async () => {
  1431. const { service, workspacePath, logPath } = setupService();
  1432. const commands = Array.from({ length: 64 }, (_, index) => ({
  1433. sessionId: index === 0 ? null : "s1",
  1434. commandId: `command-${index}`,
  1435. }));
  1436. const scope = createZCodeAgentConnectionScope(service, {
  1437. connectionId: "query-wire",
  1438. clientMode: "web-remote-replayable",
  1439. });
  1440. try {
  1441. await expect(
  1442. service.queryConversationCommandsV4({ workspacePath, commands: [commands[0]!] }),
  1443. ).rejects.toThrow("fault.command.queryConnectionUntrusted");
  1444. await scope.service.helloConversationV4();
  1445. await scope.service.initializeConversationV4({
  1446. kind: "clientHello",
  1447. protocolVersion: 3,
  1448. clientId: "query-wire-client",
  1449. appVersion: "4.0.0",
  1450. });
  1451. const result = await scope.service.queryConversationCommandsV4({ workspacePath, commands });
  1452. expect(result.results.map((item) => item.key.commandId)).toEqual(
  1453. commands.map((key) => key.commandId),
  1454. );
  1455. expect(result.results.every((item) => item.result === "unknown")).toBe(true);
  1456. await expect(
  1457. scope.service.queryConversationCommandsV4({
  1458. workspacePath,
  1459. commands: [...commands, { sessionId: "s1", commandId: "command-64" }],
  1460. }),
  1461. ).rejects.toThrow();
  1462. const requests = readRequests(logPath).filter(
  1463. (entry) => entry.method === "v4/commands/query",
  1464. );
  1465. expect(requests).toHaveLength(1);
  1466. expect(requests[0]?.params).toEqual({ commands });
  1467. } finally {
  1468. await scope.dispose();
  1469. await service.disposeAllAndWait();
  1470. }
  1471. });
  1472. it("forwards same-sub resync with the recorded exact route and client base", async () => {
  1473. const { service, workspacePath, logPath } = setupService();
  1474. try {
  1475. const subscribed = await service.subscribeConversationV4({
  1476. workspacePath,
  1477. sessionId: "s-resync",
  1478. });
  1479. const result = await service.resyncConversationV4({
  1480. workspacePath,
  1481. subscriptionId: subscribed.ack.subscriptionId,
  1482. base: { logEpoch: "epoch-1", seq: 0 },
  1483. forceSnapshot: true,
  1484. });
  1485. expect(result.ack).toEqual({
  1486. subscriptionId: subscribed.ack.subscriptionId,
  1487. mode: "snapshot",
  1488. logEpoch: "epoch-1",
  1489. });
  1490. const requests = readRequests(logPath);
  1491. const subscribeRequest = requests.find(
  1492. (entry) =>
  1493. entry.method === "v4/conversation/subscribe" &&
  1494. entry.params.topic === "conversation/s-resync",
  1495. );
  1496. const resyncRequest = requests.find((entry) => entry.method === "v4/conversation/resync");
  1497. expect(resyncRequest?.params).toEqual({
  1498. topic: "conversation/s-resync",
  1499. connectionId: subscribeRequest?.params.connectionId,
  1500. subscriptionId: subscribed.ack.subscriptionId,
  1501. base: { logEpoch: "epoch-1", seq: 0 },
  1502. forceSnapshot: true,
  1503. });
  1504. } finally {
  1505. await service.disposeAllAndWait();
  1506. }
  1507. });
  1508. it("迟到 unsubscribe response 不删除同 key 的新 route", async () => {
  1509. const { service, workspacePath, logPath } = setupService();
  1510. try {
  1511. const first = await service.subscribeConversationV4({
  1512. workspacePath,
  1513. sessionId: "delayed-unsubscribe",
  1514. });
  1515. const staleUnsubscribe = service.unsubscribeConversationV4({
  1516. workspacePath,
  1517. subscriptionId: first.ack.subscriptionId,
  1518. });
  1519. await vi.waitFor(() => {
  1520. expect(
  1521. readRequests(logPath).some((entry) => entry.method === "v4/conversation/unsubscribe"),
  1522. ).toBe(true);
  1523. });
  1524. const replacement = await service.subscribeConversationV4({
  1525. workspacePath,
  1526. sessionId: "delayed-unsubscribe",
  1527. });
  1528. expect(replacement.ack.subscriptionId).toBe(first.ack.subscriptionId);
  1529. await staleUnsubscribe;
  1530. await expect(
  1531. service.resyncConversationV4({
  1532. workspacePath,
  1533. subscriptionId: replacement.ack.subscriptionId,
  1534. base: { logEpoch: replacement.ack.logEpoch, seq: 0 },
  1535. }),
  1536. ).resolves.toMatchObject({ ack: { subscriptionId: replacement.ack.subscriptionId } });
  1537. } finally {
  1538. await service.disposeAllAndWait();
  1539. }
  1540. });
  1541. it("route 换代后迟到 resync response 必须拒绝 stale success", async () => {
  1542. const { service, workspacePath, logPath } = setupService();
  1543. try {
  1544. const first = await service.subscribeConversationV4({
  1545. workspacePath,
  1546. sessionId: "delayed-resync",
  1547. });
  1548. const staleResync = service.resyncConversationV4({
  1549. workspacePath,
  1550. subscriptionId: first.ack.subscriptionId,
  1551. base: { logEpoch: first.ack.logEpoch, seq: 0 },
  1552. });
  1553. await vi.waitFor(() => {
  1554. expect(
  1555. readRequests(logPath).some((entry) => entry.method === "v4/conversation/resync"),
  1556. ).toBe(true);
  1557. });
  1558. const replacement = await service.subscribeConversationV4({
  1559. workspacePath,
  1560. sessionId: "delayed-resync",
  1561. });
  1562. expect(replacement.ack.subscriptionId).toBe(first.ack.subscriptionId);
  1563. await expect(staleResync).rejects.toThrow("fault.subscription.notOwned");
  1564. } finally {
  1565. await service.disposeAllAndWait();
  1566. }
  1567. });
  1568. it("disposeWorkspace runtime invalidation 后三类 pre-restart listener 均接收新 runtime initial", async () => {
  1569. const { service, workspacePath } = setupService();
  1570. try {
  1571. const frames: ConversationTopicWireCandidate[] = [];
  1572. const indexFrames: SessionsIndexTopicWireCandidate[] = [];
  1573. const configFrames: WorkspaceConfigTopicWireCandidate[] = [];
  1574. const disposables = [
  1575. service.onDynamicConversationFrame({ workspacePath })((frame) => frames.push(frame)),
  1576. service.onDynamicSessionsIndexFrame({ workspacePath })((frame) => indexFrames.push(frame)),
  1577. service.onDynamicWorkspaceConfigFrame({ workspacePath })((frame) =>
  1578. configFrames.push(frame),
  1579. ),
  1580. ];
  1581. await Promise.all([
  1582. service.subscribeConversationV4({ workspacePath, sessionId: "before-restart" }),
  1583. service.subscribeSessionsIndexV4({ workspacePath }),
  1584. service.subscribeWorkspaceConfigV4({ workspacePath }),
  1585. ]);
  1586. await vi.waitFor(() => {
  1587. expect(frames).toHaveLength(1);
  1588. expect(indexFrames).toHaveLength(1);
  1589. expect(configFrames).toHaveLength(1);
  1590. });
  1591. await service.disposeWorkspace({ workspacePath });
  1592. await Promise.all([
  1593. service.subscribeConversationV4({ workspacePath, sessionId: "after-restart" }),
  1594. service.subscribeSessionsIndexV4({ workspacePath }),
  1595. service.subscribeWorkspaceConfigV4({ workspacePath }),
  1596. ]);
  1597. await vi.waitFor(() => {
  1598. expect(frames).toHaveLength(2);
  1599. expect(indexFrames).toHaveLength(2);
  1600. expect(configFrames).toHaveLength(2);
  1601. });
  1602. expect(frames.map((frame) => frame.topic)).toEqual([
  1603. "conversation/before-restart",
  1604. "conversation/after-restart",
  1605. ]);
  1606. expect(indexFrames.every((frame) => frame.topic.startsWith("sessions-index/"))).toBe(true);
  1607. expect(configFrames.every((frame) => frame.topic.startsWith("workspace-config/"))).toBe(true);
  1608. for (const disposable of disposables) disposable.dispose();
  1609. } finally {
  1610. await service.disposeAllAndWait();
  1611. }
  1612. });
  1613. it("conversation/sessions-index/workspace-config 相同裸 subId 各自使用记录的精确 route", async () => {
  1614. const { service, workspacePath, logPath } = setupService();
  1615. try {
  1616. const conversation = await service.subscribeConversationV4({
  1617. workspacePath,
  1618. sessionId: "s1",
  1619. });
  1620. const sessionsIndex = await service.subscribeSessionsIndexV4({
  1621. workspacePath,
  1622. });
  1623. const workspaceConfig = await service.subscribeWorkspaceConfigV4({
  1624. workspacePath,
  1625. });
  1626. expect([
  1627. conversation.ack.subscriptionId,
  1628. sessionsIndex.ack.subscriptionId,
  1629. workspaceConfig.ack.subscriptionId,
  1630. ]).toEqual(["sub-1", "sub-1", "sub-1"]);
  1631. await service.unsubscribeConversationV4({
  1632. workspacePath,
  1633. subscriptionId: "sub-1",
  1634. });
  1635. await service.unsubscribeSessionsIndexV4({
  1636. workspacePath,
  1637. subscriptionId: "sub-1",
  1638. });
  1639. await service.unsubscribeWorkspaceConfigV4({
  1640. workspacePath,
  1641. subscriptionId: "sub-1",
  1642. });
  1643. const requests = readRequests(logPath);
  1644. const subscribeRequests = requests.filter(
  1645. (entry) => entry.method === "v4/conversation/subscribe",
  1646. );
  1647. const unsubscribeRequests = requests.filter(
  1648. (entry) => entry.method === "v4/conversation/unsubscribe",
  1649. );
  1650. expect(unsubscribeRequests.map((entry) => entry.params)).toEqual(
  1651. subscribeRequests.map((entry) => ({
  1652. topic: entry.params.topic,
  1653. subscriptionId: "sub-1",
  1654. connectionId: entry.params.connectionId,
  1655. })),
  1656. );
  1657. } finally {
  1658. await service.disposeAllAndWait();
  1659. }
  1660. });
  1661. it("trusted unsubscribe route 不能跨越调用方法的 topic 域", async () => {
  1662. const { service, workspacePath, logPath } = setupService();
  1663. try {
  1664. const config = await service.subscribeWorkspaceConfigV4({
  1665. workspacePath,
  1666. });
  1667. const configSubscribe = readRequests(logPath).find(
  1668. (entry) =>
  1669. entry.method === "v4/conversation/subscribe" &&
  1670. String(entry.params.topic).startsWith("workspace-config/"),
  1671. );
  1672. expect(configSubscribe).toBeDefined();
  1673. await service.unsubscribeConversationV4({
  1674. workspacePath,
  1675. subscriptionId: config.ack.subscriptionId,
  1676. __zcodeTrustedV4UnsubscribeRoute: {
  1677. topic: configSubscribe?.params.topic,
  1678. connectionId: configSubscribe?.params.connectionId,
  1679. },
  1680. } as never);
  1681. expect(
  1682. readRequests(logPath).filter((entry) => entry.method === "v4/conversation/unsubscribe"),
  1683. ).toHaveLength(0);
  1684. } finally {
  1685. await service.disposeAllAndWait();
  1686. }
  1687. });
  1688. });