zcodeAgentService.v4.test.ts 76 KB

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