zcodeAgentConnectionScope.test.ts 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  1. import type { ZCodeMcpResourceSample } from "@zcode/shared";
  2. import { Emitter } from "@zcode/rpc";
  3. import type { ZCodeMcpTelemetryEvent, ZCodeProcessResourceSample } from "@zcode/shared";
  4. import type {
  5. ConversationTopicFrame,
  6. ConversationTopicWireFrame,
  7. ConversationTelemetryFact,
  8. CuaPermissionObservation,
  9. SessionsIndexTopicFrame,
  10. SessionsIndexTopicWireFrame,
  11. TopicWireFrame,
  12. WorkspaceConfigTopicFrame,
  13. WorkspaceConfigTopicWireFrame,
  14. } from "@zcode/shared/zcode-protocol-v4";
  15. import { sessionsIndexTopic, workspaceConfigTopic } from "@zcode/shared/zcode-protocol-v4";
  16. import { describe, expect, it, vi } from "vitest";
  17. import type {
  18. IZCodeAgentService,
  19. ZCodeAgentRuntimeLifecycleEvent,
  20. ZCodeAgentCuaPermissionObservation,
  21. } from "../src/zcode-agent/zcodeAgent.js";
  22. import {
  23. createZCodeAgentConnectionScope,
  24. readTrustedZCodeAgentV4Connection,
  25. readTrustedZCodeAgentV4UnsubscribeRoute,
  26. } from "../src/zcode-agent/zcodeAgentConnectionScope.js";
  27. function makeFrame(topic: string, subscriptionId: string): ConversationTopicFrame {
  28. return {
  29. topic,
  30. subscriptionId,
  31. fromSeq: 1,
  32. toSeq: 1,
  33. sentAt: 1,
  34. payload: { kind: "deltas", deltas: [] },
  35. };
  36. }
  37. function completeWire<F extends { topic: string; subscriptionId: string }>(
  38. frame: F,
  39. logicalFrameId = `logical-${frame.subscriptionId}`,
  40. logicalFrameOrdinal = 1,
  41. ): TopicWireFrame<F> {
  42. return {
  43. wireVersion: 3,
  44. kind: "complete",
  45. logicalFrameId,
  46. logicalFrameOrdinal,
  47. topic: frame.topic,
  48. subscriptionId: frame.subscriptionId,
  49. frame,
  50. };
  51. }
  52. function setupBase() {
  53. const conversationFrames = new Emitter<ConversationTopicWireFrame>();
  54. const telemetryFacts = new Emitter<ConversationTelemetryFact>();
  55. const cuaPermissionObservations = new Emitter<ZCodeAgentCuaPermissionObservation>();
  56. const processResourceSamples = new Emitter<ZCodeProcessResourceSample>();
  57. const mcpResourceSamples = new Emitter<ZCodeMcpResourceSample[]>();
  58. const mcpTelemetryEvents = new Emitter<ZCodeMcpTelemetryEvent>();
  59. const sessionsIndexFrames = new Emitter<SessionsIndexTopicWireFrame>();
  60. const workspaceConfigFrames = new Emitter<WorkspaceConfigTopicWireFrame>();
  61. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  62. const nextSerialByConnection = new Map<string, number>();
  63. const nextId = (params: unknown) => {
  64. const connection = readTrustedZCodeAgentV4Connection(params);
  65. if (!connection) throw new Error("missing trusted connection");
  66. const serial = (nextSerialByConnection.get(connection.connectionId) ?? 0) + 1;
  67. nextSerialByConnection.set(connection.connectionId, serial);
  68. return `sub-${connection.connectionId}-${serial}`;
  69. };
  70. const base = {
  71. helloConversationV4: vi.fn(),
  72. initializeConversationV4: vi.fn(),
  73. subscribeConversationV4: vi.fn(async (params: unknown) => ({
  74. ack: {
  75. subscriptionId: nextId(params),
  76. mode: "snapshot" as const,
  77. logEpoch: "epoch-1",
  78. },
  79. })),
  80. unsubscribeConversationV4: vi.fn(async () => {}),
  81. resyncConversationV4: vi.fn(async (params: { subscriptionId: string }) => ({
  82. ack: {
  83. subscriptionId: params.subscriptionId,
  84. mode: "resume" as const,
  85. logEpoch: "epoch-1",
  86. },
  87. })),
  88. onDynamicConversationFrame: vi.fn(() => conversationFrames.event),
  89. onDynamicConversationTelemetryFact: vi.fn(() => telemetryFacts.event),
  90. onDynamicCuaPermissionObservation: vi.fn(() => cuaPermissionObservations.event),
  91. onDynamicProcessResourceSample: vi.fn(() => processResourceSamples.event),
  92. onDynamicMcpResourceSamples: vi.fn(() => mcpResourceSamples.event),
  93. onDynamicMcpTelemetry: vi.fn(() => mcpTelemetryEvents.event),
  94. subscribeSessionsIndexV4: vi.fn(async (params: unknown) => ({
  95. ack: {
  96. subscriptionId: nextId(params),
  97. mode: "snapshot" as const,
  98. logEpoch: "epoch-1",
  99. },
  100. })),
  101. unsubscribeSessionsIndexV4: vi.fn(async () => {}),
  102. onDynamicSessionsIndexFrame: vi.fn(() => sessionsIndexFrames.event),
  103. subscribeWorkspaceConfigV4: vi.fn(async (params: unknown) => ({
  104. ack: {
  105. subscriptionId: nextId(params),
  106. mode: "snapshot" as const,
  107. logEpoch: "epoch-1",
  108. },
  109. })),
  110. unsubscribeWorkspaceConfigV4: vi.fn(async () => {}),
  111. onDynamicWorkspaceConfigFrame: vi.fn(() => workspaceConfigFrames.event),
  112. onAgentRuntimeRestarted: vi.fn((listener: (event: { workspaceKey: string }) => void) =>
  113. runtimeRestarts.event(listener),
  114. ),
  115. sendConversationCommandV4: vi.fn(async (params: { envelope: { commandId: string } }) => ({
  116. commandId: params.envelope.commandId,
  117. status: "accepted" as const,
  118. revisionAtDecision: 1,
  119. })),
  120. queryConversationCommandsV4: vi.fn(
  121. async (params: { commands: Array<{ commandId: string }> }) => ({
  122. results: params.commands.map((key) => ({ key, result: "unknown" as const })),
  123. }),
  124. ),
  125. backgroundBashOutputV4: vi.fn(async () => ({ kind: "unavailable", workId: "work" })),
  126. conversationRowsRangeV4: vi.fn(async () => ({
  127. rows: [],
  128. atSeq: 1,
  129. atLogEpoch: "epoch-1",
  130. hasMore: false,
  131. })),
  132. attachmentBeginV4: vi.fn(async (params: { uploadId: string }) => ({
  133. uploadId: params.uploadId,
  134. state: "staging" as const,
  135. nextChunkIndex: 0,
  136. })),
  137. attachmentChunkV4: vi.fn(async (params: { uploadId: string; chunkIndex: number }) => ({
  138. uploadId: params.uploadId,
  139. nextChunkIndex: params.chunkIndex + 1,
  140. })),
  141. attachmentCommitV4: vi.fn(async () => ({ ref: "zcode-artifact://attachment/test" })),
  142. attachmentAbortV4: vi.fn(async () => {}),
  143. attachmentReadV4: vi.fn(async () => ({
  144. dataBase64: "",
  145. mediaType: "image/png",
  146. totalBytes: 0,
  147. nextOffset: null,
  148. })),
  149. setConnectionFlowStateV4: vi.fn(async () => {}),
  150. } as unknown as IZCodeAgentService;
  151. return {
  152. base,
  153. conversationFrames,
  154. telemetryFacts,
  155. cuaPermissionObservations,
  156. processResourceSamples,
  157. mcpResourceSamples,
  158. mcpTelemetryEvents,
  159. sessionsIndexFrames,
  160. workspaceConfigFrames,
  161. runtimeRestarts,
  162. };
  163. }
  164. function attachRuntimeLifecycle(
  165. base: IZCodeAgentService,
  166. ): Emitter<ZCodeAgentRuntimeLifecycleEvent> {
  167. const runtimeLifecycle = new Emitter<ZCodeAgentRuntimeLifecycleEvent>();
  168. Object.assign(base, {
  169. onAgentRuntimeLifecycle: vi.fn((listener: (event: ZCodeAgentRuntimeLifecycleEvent) => void) =>
  170. runtimeLifecycle.event(listener),
  171. ),
  172. });
  173. return runtimeLifecycle;
  174. }
  175. function makeRuntimeLifecycleEvent(
  176. target: { workspacePath: string; workspaceIdentity?: string },
  177. generation: number,
  178. state: ZCodeAgentRuntimeLifecycleEvent["state"],
  179. ): ZCodeAgentRuntimeLifecycleEvent {
  180. const workspaceKey = target.workspaceIdentity?.trim() || target.workspacePath;
  181. return {
  182. ...target,
  183. workspaceKey,
  184. runtimeIdentity: {
  185. generation,
  186. identity: `${workspaceKey}:${generation}:100`,
  187. processId: 100,
  188. workspaceKey,
  189. },
  190. state,
  191. };
  192. }
  193. describe("ZCodeAgent connection-scoped service facade", () => {
  194. it("desktop continuous 与 web replayable 都宣告 Host review domain capability", async () => {
  195. const { base } = setupBase();
  196. const desktop = createZCodeAgentConnectionScope(base, {
  197. connectionId: "desktop-hook-capability",
  198. clientMode: "desktop-continuous",
  199. });
  200. const mobile = createZCodeAgentConnectionScope(base, {
  201. connectionId: "mobile-hook-capability",
  202. clientMode: "web-remote-replayable",
  203. });
  204. await expect(desktop.service.helloConversationV4()).resolves.toMatchObject({
  205. clientMode: "desktop-continuous",
  206. capabilities: { workspaceHookReview: true },
  207. });
  208. await expect(mobile.service.helloConversationV4()).resolves.toMatchObject({
  209. clientMode: "web-remote-replayable",
  210. deliveryProfile: "replayable",
  211. capabilities: { workspaceHookReview: true },
  212. });
  213. });
  214. // 增量能力是一条**单向**握手(shared transport.ts):Host 先在 hello 里宣告,客户端才敢在
  215. // `.strict()` 的 clientHello capabilities 里回声明;host 再把这条连接的声明当可信位注入订阅。
  216. it("hello 宣告 workflowRunDeltas,clientHello 声明后才成为订阅上的可信位", async () => {
  217. const { base } = setupBase();
  218. const declared = createZCodeAgentConnectionScope(base, {
  219. connectionId: "deltas-declared",
  220. clientMode: "desktop-continuous",
  221. });
  222. const silent = createZCodeAgentConnectionScope(base, {
  223. connectionId: "deltas-silent",
  224. clientMode: "web-remote-replayable",
  225. });
  226. await expect(declared.service.helloConversationV4()).resolves.toMatchObject({
  227. capabilities: { workflowRunDeltas: true },
  228. });
  229. await silent.service.helloConversationV4();
  230. await declared.service.initializeConversationV4({
  231. kind: "clientHello",
  232. protocolVersion: 3,
  233. clientId: "deltas-client",
  234. appVersion: "4.0.0",
  235. capabilities: { workflowRunDeltas: true },
  236. });
  237. await silent.service.initializeConversationV4({
  238. kind: "clientHello",
  239. protocolVersion: 3,
  240. clientId: "deltas-client",
  241. appVersion: "4.0.0",
  242. capabilities: { workspaceHookReviewUi: true },
  243. });
  244. await declared.service.subscribeConversationV4({
  245. workspacePath: "/repo",
  246. sessionId: "session-1",
  247. // UI 面自报的同名字段:facade 先清后写,伪造不了能力。
  248. workflowRunDeltas: false,
  249. } as never);
  250. await silent.service.subscribeConversationV4({
  251. workspacePath: "/repo",
  252. sessionId: "session-1",
  253. workflowRunDeltas: true,
  254. } as never);
  255. const calls = vi.mocked(base.subscribeConversationV4).mock.calls;
  256. expect(readTrustedZCodeAgentV4Connection(calls[0]?.[0])).toEqual({
  257. connectionId: "deltas-declared",
  258. clientMode: "desktop-continuous",
  259. workflowRunDeltas: true,
  260. });
  261. expect(calls[0]?.[0]).not.toHaveProperty("workflowRunDeltas");
  262. expect(readTrustedZCodeAgentV4Connection(calls[1]?.[0])).toEqual({
  263. connectionId: "deltas-silent",
  264. clientMode: "web-remote-replayable",
  265. });
  266. expect(calls[1]?.[0]).not.toHaveProperty("workflowRunDeltas");
  267. });
  268. it("trusted relay 把下游 clientHello 的 workflowRunDeltas 原样带到上游订阅", async () => {
  269. const { base } = setupBase();
  270. const relay = createZCodeAgentConnectionScope(base, {
  271. connectionId: "server-upstream",
  272. clientMode: "desktop-continuous",
  273. role: "trusted-host-relay",
  274. });
  275. const mobile = createZCodeAgentConnectionScope(relay.service, {
  276. connectionId: "mobile-downstream",
  277. clientMode: "web-remote-replayable",
  278. });
  279. await mobile.service.helloConversationV4();
  280. await mobile.service.initializeConversationV4({
  281. kind: "clientHello",
  282. protocolVersion: 3,
  283. clientId: "mobile-client",
  284. appVersion: "4.0.0",
  285. capabilities: { workflowRunDeltas: true },
  286. });
  287. await mobile.service.subscribeConversationV4({
  288. workspacePath: "/repo",
  289. sessionId: "session-1",
  290. });
  291. // relay 自己没有 clientHello(它不消费帧):这个位只能是下游那一端的事实。
  292. const forwarded = readTrustedZCodeAgentV4Connection(
  293. vi.mocked(base.subscribeConversationV4).mock.calls[0]?.[0],
  294. );
  295. expect(forwarded).toMatchObject({
  296. clientMode: "web-remote-replayable",
  297. workflowRunDeltas: true,
  298. });
  299. expect(forwarded?.connectionId).toContain("mobile-downstream");
  300. });
  301. it("rows/range forwards the connection-owned Desktop/Web mode as trusted metadata", async () => {
  302. const { base } = setupBase();
  303. const desktop = createZCodeAgentConnectionScope(base, {
  304. connectionId: "desktop-rows",
  305. clientMode: "desktop-continuous",
  306. });
  307. const mobile = createZCodeAgentConnectionScope(base, {
  308. connectionId: "mobile-rows",
  309. clientMode: "web-remote-replayable",
  310. });
  311. for (const scope of [desktop, mobile]) {
  312. await scope.service.helloConversationV4();
  313. await scope.service.initializeConversationV4({
  314. kind: "clientHello",
  315. protocolVersion: 3,
  316. clientId: "rows-client",
  317. appVersion: "4.0.0",
  318. });
  319. await scope.service.conversationRowsRangeV4({
  320. workspacePath: "/repo",
  321. sessionId: "session-1",
  322. limit: 20,
  323. });
  324. }
  325. const calls = vi.mocked(base.conversationRowsRangeV4).mock.calls;
  326. expect(readTrustedZCodeAgentV4Connection(calls[0]?.[0])).toEqual({
  327. connectionId: "desktop-rows",
  328. clientMode: "desktop-continuous",
  329. });
  330. expect(readTrustedZCodeAgentV4Connection(calls[1]?.[0])).toEqual({
  331. connectionId: "mobile-rows",
  332. clientMode: "web-remote-replayable",
  333. });
  334. });
  335. it("只有 trusted Host relay 能跨连接订阅 CLI 进程资源样本", () => {
  336. const { base, processResourceSamples } = setupBase();
  337. const relay = createZCodeAgentConnectionScope(base, {
  338. connectionId: "server-upstream",
  339. clientMode: "desktop-continuous",
  340. role: "trusted-host-relay",
  341. });
  342. const desktop = createZCodeAgentConnectionScope(relay.service, {
  343. connectionId: "desktop-downstream",
  344. clientMode: "desktop-continuous",
  345. });
  346. const mobile = createZCodeAgentConnectionScope(relay.service, {
  347. connectionId: "mobile-downstream",
  348. clientMode: "web-remote-replayable",
  349. });
  350. const relaySeen: ZCodeProcessResourceSample[] = [];
  351. const desktopSeen: ZCodeProcessResourceSample[] = [];
  352. const mobileSeen: ZCodeProcessResourceSample[] = [];
  353. relay.service.onDynamicProcessResourceSample()((sample) => relaySeen.push(sample));
  354. desktop.service.onDynamicProcessResourceSample()((sample) => desktopSeen.push(sample));
  355. mobile.service.onDynamicProcessResourceSample()((sample) => mobileSeen.push(sample));
  356. const sample: ZCodeProcessResourceSample = {
  357. arch: "x64",
  358. cpuCores: 1,
  359. cpuPercent: 12.5,
  360. intervalMs: 60_000,
  361. logicalCpuCount: 8,
  362. platform: "linux",
  363. rssKb: 64_000,
  364. };
  365. processResourceSamples.fire(sample);
  366. expect(relaySeen).toEqual([sample]);
  367. expect(desktopSeen).toEqual([]);
  368. expect(mobileSeen).toEqual([]);
  369. expect(base.onDynamicProcessResourceSample).toHaveBeenCalledTimes(1);
  370. });
  371. it("只有 trusted Host relay 能订阅 MCP 遥测", () => {
  372. const { base, mcpTelemetryEvents } = setupBase();
  373. const relay = createZCodeAgentConnectionScope(base, {
  374. connectionId: "server-upstream",
  375. clientMode: "desktop-continuous",
  376. role: "trusted-host-relay",
  377. });
  378. const desktop = createZCodeAgentConnectionScope(relay.service, {
  379. connectionId: "desktop-downstream",
  380. clientMode: "desktop-continuous",
  381. });
  382. const mobile = createZCodeAgentConnectionScope(relay.service, {
  383. connectionId: "mobile-downstream",
  384. clientMode: "web-remote-replayable",
  385. });
  386. const sample: ZCodeMcpTelemetryEvent = {
  387. arch: "x64",
  388. kind: "process_start",
  389. mcpId: "builtin:node_repl",
  390. mcpInstanceId: "mcp-instance-1",
  391. mcpIsolation: "workspace",
  392. mcpSource: "builtin",
  393. occurredAt: 1,
  394. platform: "linux",
  395. };
  396. const relaySeen: ZCodeMcpTelemetryEvent[] = [];
  397. const desktopSeen: ZCodeMcpTelemetryEvent[] = [];
  398. const mobileSeen: ZCodeMcpTelemetryEvent[] = [];
  399. relay.service.onDynamicMcpTelemetry()((event) => relaySeen.push(event));
  400. desktop.service.onDynamicMcpTelemetry()((event) => desktopSeen.push(event));
  401. mobile.service.onDynamicMcpTelemetry()((event) => mobileSeen.push(event));
  402. mcpTelemetryEvents.fire(sample);
  403. expect(relaySeen).toEqual([sample]);
  404. expect(desktopSeen).toEqual([]);
  405. expect(mobileSeen).toEqual([]);
  406. expect(base.onDynamicMcpTelemetry).toHaveBeenCalledTimes(1);
  407. });
  408. it("只有 trusted Host relay 能订阅 MCP 资源数组", () => {
  409. const { base, mcpResourceSamples } = setupBase();
  410. const relay = createZCodeAgentConnectionScope(base, {
  411. connectionId: "server-upstream",
  412. clientMode: "desktop-continuous",
  413. role: "trusted-host-relay",
  414. });
  415. const desktop = createZCodeAgentConnectionScope(relay.service, {
  416. connectionId: "desktop-downstream",
  417. clientMode: "desktop-continuous",
  418. });
  419. const mobile = createZCodeAgentConnectionScope(relay.service, {
  420. connectionId: "mobile-downstream",
  421. clientMode: "web-remote-replayable",
  422. });
  423. const sample: ZCodeMcpResourceSample[] = [
  424. {
  425. mcpId: "builtin:node_repl",
  426. instanceToken: "cli-instance-01",
  427. sampledAt: 300000,
  428. intervalMs: 300000,
  429. processCount: 1,
  430. rssKbTotal: 100,
  431. rssKbMaxProcess: 100,
  432. cpuTimeMsDelta: 0,
  433. uptimeMinutes: 5,
  434. platform: "linux",
  435. arch: "x64",
  436. logicalCpuCount: 8,
  437. totalMemoryGb: 32,
  438. },
  439. ];
  440. const relaySeen: ZCodeMcpResourceSample[][] = [];
  441. const desktopSeen: ZCodeMcpResourceSample[][] = [];
  442. const mobileSeen: ZCodeMcpResourceSample[][] = [];
  443. relay.service.onDynamicMcpResourceSamples()((event) => relaySeen.push(event));
  444. desktop.service.onDynamicMcpResourceSamples()((event) => desktopSeen.push(event));
  445. mobile.service.onDynamicMcpResourceSamples()((event) => mobileSeen.push(event));
  446. mcpResourceSamples.fire(sample);
  447. expect(relaySeen).toEqual([sample]);
  448. expect(desktopSeen).toEqual([]);
  449. expect(mobileSeen).toEqual([]);
  450. expect(base.onDynamicMcpResourceSamples).toHaveBeenCalledTimes(1);
  451. });
  452. it("只有可信 desktop-continuous attachment 能订阅 workspace telemetry fact", async () => {
  453. const { base, telemetryFacts } = setupBase();
  454. const desktop = createZCodeAgentConnectionScope(base, {
  455. connectionId: "desktop-telemetry",
  456. clientMode: "desktop-continuous",
  457. });
  458. const mobile = createZCodeAgentConnectionScope(base, {
  459. connectionId: "mobile-telemetry",
  460. clientMode: "web-remote-replayable",
  461. });
  462. const desktopSeen: ConversationTelemetryFact[] = [];
  463. const mobileSeen: ConversationTelemetryFact[] = [];
  464. // Root supervisor 在协议握手前挂载;可信 desktop 的只读 emitter 订阅必须可提前建立。
  465. desktop.service.onDynamicConversationTelemetryFact({ workspacePath: "/repo" })((fact) =>
  466. desktopSeen.push(fact),
  467. );
  468. mobile.service.onDynamicConversationTelemetryFact({ workspacePath: "/repo" })((fact) =>
  469. mobileSeen.push(fact),
  470. );
  471. for (const scope of [desktop, mobile]) {
  472. await scope.service.helloConversationV4();
  473. await scope.service.initializeConversationV4({
  474. kind: "clientHello",
  475. protocolVersion: 3,
  476. clientId: `${scope === desktop ? "desktop" : "mobile"}-client`,
  477. appVersion: "4.0.0",
  478. });
  479. }
  480. telemetryFacts.fire({
  481. version: 1,
  482. eventId: "event-1",
  483. eventSeq: 1,
  484. occurredAt: 1,
  485. sessionId: "session-1",
  486. kind: "turn.started",
  487. sourceCommandId: "command-1",
  488. });
  489. expect(desktopSeen).toHaveLength(1);
  490. expect(mobileSeen).toHaveLength(0);
  491. expect(base.onDynamicConversationTelemetryFact).toHaveBeenCalledTimes(1);
  492. });
  493. it("trusted host relay 只向 desktop-continuous 下游转发 telemetry fact", () => {
  494. const { base, telemetryFacts } = setupBase();
  495. const relay = createZCodeAgentConnectionScope(base, {
  496. connectionId: "server-telemetry-relay",
  497. clientMode: "desktop-continuous",
  498. role: "trusted-host-relay",
  499. });
  500. const desktop = createZCodeAgentConnectionScope(relay.service, {
  501. connectionId: "desktop-telemetry-downstream",
  502. clientMode: "desktop-continuous",
  503. });
  504. const mobile = createZCodeAgentConnectionScope(relay.service, {
  505. connectionId: "mobile-telemetry-downstream",
  506. clientMode: "web-remote-replayable",
  507. });
  508. const relaySeen: ConversationTelemetryFact[] = [];
  509. const desktopSeen: ConversationTelemetryFact[] = [];
  510. const mobileSeen: ConversationTelemetryFact[] = [];
  511. relay.service.onDynamicConversationTelemetryFact({ workspacePath: "/repo" })((fact) =>
  512. relaySeen.push(fact),
  513. );
  514. desktop.service.onDynamicConversationTelemetryFact({ workspacePath: "/repo" })((fact) =>
  515. desktopSeen.push(fact),
  516. );
  517. mobile.service.onDynamicConversationTelemetryFact({ workspacePath: "/repo" })((fact) =>
  518. mobileSeen.push(fact),
  519. );
  520. const fact: ConversationTelemetryFact = {
  521. version: 1,
  522. eventId: "relay-event-1",
  523. eventSeq: 1,
  524. occurredAt: 1,
  525. sessionId: "session-1",
  526. kind: "turn.started",
  527. sourceCommandId: "command-1",
  528. };
  529. telemetryFacts.fire(fact);
  530. expect(relaySeen).toHaveLength(0);
  531. expect(desktopSeen).toEqual([fact]);
  532. expect(mobileSeen).toHaveLength(0);
  533. expect(base.onDynamicConversationTelemetryFact).toHaveBeenCalledOnce();
  534. expect(
  535. readTrustedZCodeAgentV4Connection(
  536. vi.mocked(base.onDynamicConversationTelemetryFact).mock.calls[0]?.[0],
  537. ),
  538. ).toEqual({
  539. connectionId: "relay:22:server-telemetry-relay28:desktop-telemetry-downstream",
  540. clientMode: "desktop-continuous",
  541. });
  542. });
  543. it("只有可信 desktop-continuous attachment 能订阅窗口级 CUA 权限观察", () => {
  544. const { base, cuaPermissionObservations } = setupBase();
  545. const desktop = createZCodeAgentConnectionScope(base, {
  546. connectionId: "desktop-cua-permission",
  547. clientMode: "desktop-continuous",
  548. });
  549. const mobile = createZCodeAgentConnectionScope(base, {
  550. connectionId: "mobile-cua-permission",
  551. clientMode: "web-remote-replayable",
  552. });
  553. const desktopSeen: ZCodeAgentCuaPermissionObservation[] = [];
  554. const mobileSeen: ZCodeAgentCuaPermissionObservation[] = [];
  555. desktop.service.onDynamicCuaPermissionObservation()((event) => desktopSeen.push(event));
  556. mobile.service.onDynamicCuaPermissionObservation()((event) => mobileSeen.push(event));
  557. const observation: CuaPermissionObservation = {
  558. schemaVersion: 1,
  559. eventId: "event-1",
  560. eventSeq: 1,
  561. occurredAt: 1,
  562. sessionId: "session-1",
  563. turnId: "turn-1",
  564. toolCallId: "tool-1",
  565. permissionStatus: {
  566. schemaVersion: 1,
  567. platform: "darwin",
  568. grantOwner: "dev.zcode.cua-helper.dev",
  569. accessibility: "denied",
  570. screenRecording: "granted",
  571. },
  572. };
  573. cuaPermissionObservations.fire({ ...observation, workspacePath: "/repo" });
  574. expect(desktopSeen).toHaveLength(1);
  575. expect(mobileSeen).toHaveLength(0);
  576. expect(base.onDynamicCuaPermissionObservation).toHaveBeenCalledTimes(1);
  577. });
  578. it("physical ACK staging 超 1024 片时清空整批、拒绝 subscribe 并反向退订", async () => {
  579. const { base, conversationFrames } = setupBase();
  580. let resolveSubscribe!: (value: {
  581. ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string };
  582. }) => void;
  583. vi.mocked(base.subscribeConversationV4).mockImplementationOnce(
  584. () => new Promise((resolve) => (resolveSubscribe = resolve)),
  585. );
  586. const scope = createZCodeAgentConnectionScope(base, {
  587. connectionId: "physical-overflow",
  588. clientMode: "desktop-continuous",
  589. });
  590. await scope.service.helloConversationV4();
  591. await scope.service.initializeConversationV4({
  592. kind: "clientHello",
  593. protocolVersion: 3,
  594. clientId: "physical-overflow-client",
  595. appVersion: "4.0.0",
  596. });
  597. const seen: ConversationTopicWireFrame[] = [];
  598. scope.service.onDynamicConversationFrame({ workspacePath: "/repo" })((wire) => seen.push(wire));
  599. const subscribing = scope.service.subscribeConversationV4({
  600. workspacePath: "/repo",
  601. sessionId: "physical-overflow-session",
  602. });
  603. for (let fragmentIndex = 0; fragmentIndex < 1_025; fragmentIndex += 1) {
  604. conversationFrames.fire({
  605. wireVersion: 3,
  606. kind: "fragment",
  607. logicalFrameId: "logical-overflow",
  608. logicalFrameOrdinal: 1,
  609. topic: "conversation/physical-overflow-session",
  610. subscriptionId: "sub-physical-overflow",
  611. fragmentIndex: fragmentIndex % 1_024,
  612. fragmentCount: 1_024,
  613. logicalBytes: 1_024,
  614. checksum: { algorithm: "crc32", value: "00000000" },
  615. dataBase64: "AA==",
  616. });
  617. }
  618. resolveSubscribe({
  619. ack: {
  620. subscriptionId: "sub-physical-overflow",
  621. mode: "snapshot",
  622. logEpoch: "epoch-overflow",
  623. },
  624. });
  625. await expect(subscribing).rejects.toThrow("fault.subscription.initialFrameStagingOverflow");
  626. expect(seen).toEqual([]);
  627. expect(base.unsubscribeConversationV4).toHaveBeenCalled();
  628. await scope.dispose();
  629. });
  630. it("host mode 决定 hello/profile,双端同 session 只收到 owned subscription", async () => {
  631. const { base, conversationFrames } = setupBase();
  632. const desktop = createZCodeAgentConnectionScope(base, {
  633. connectionId: "desktop-a",
  634. clientMode: "desktop-continuous",
  635. });
  636. const mobile = createZCodeAgentConnectionScope(base, {
  637. connectionId: "mobile-b",
  638. clientMode: "web-remote-replayable",
  639. });
  640. await expect(
  641. desktop.service.subscribeConversationV4({
  642. workspacePath: "/repo",
  643. sessionId: "before-handshake",
  644. }),
  645. ).rejects.toThrow("fault.connection.handshakeRequired");
  646. const desktopHello = await desktop.service.helloConversationV4();
  647. await desktop.service.initializeConversationV4({
  648. kind: "clientHello",
  649. protocolVersion: 3,
  650. clientId: "same-client-metadata",
  651. clientKind: "mobileRemote",
  652. appVersion: "4.0.0",
  653. });
  654. const mobileHello = await mobile.service.helloConversationV4();
  655. await mobile.service.initializeConversationV4({
  656. kind: "clientHello",
  657. protocolVersion: 3,
  658. clientId: "same-client-metadata",
  659. clientKind: "desktop",
  660. appVersion: "4.0.0",
  661. });
  662. expect(desktopHello).toMatchObject({
  663. connectionId: "desktop-a",
  664. clientMode: "desktop-continuous",
  665. deliveryProfile: "continuous",
  666. });
  667. expect(mobileHello).toMatchObject({
  668. connectionId: "mobile-b",
  669. clientMode: "web-remote-replayable",
  670. deliveryProfile: "replayable",
  671. });
  672. const desktopSeen: string[] = [];
  673. const mobileSeen: string[] = [];
  674. desktop.service.onDynamicConversationFrame({
  675. workspacePath: "/repo",
  676. workspaceIdentity: "local:repo",
  677. })((frame) => desktopSeen.push(frame.subscriptionId));
  678. mobile.service.onDynamicConversationFrame({
  679. workspacePath: "/repo",
  680. workspaceIdentity: "local:repo",
  681. })((frame) => mobileSeen.push(frame.subscriptionId));
  682. const desktopSub = await desktop.service.subscribeConversationV4({
  683. workspacePath: "/repo",
  684. workspaceIdentity: "local:repo",
  685. sessionId: "session-1",
  686. });
  687. const mobileSub = await mobile.service.subscribeConversationV4({
  688. workspacePath: "/repo",
  689. workspaceIdentity: "local:repo",
  690. sessionId: "session-1",
  691. });
  692. conversationFrames.fire(
  693. completeWire(makeFrame("conversation/session-1", desktopSub.ack.subscriptionId)),
  694. );
  695. conversationFrames.fire(
  696. completeWire(makeFrame("conversation/session-1", mobileSub.ack.subscriptionId)),
  697. );
  698. expect(desktopSeen).toEqual([desktopSub.ack.subscriptionId]);
  699. expect(mobileSeen).toEqual([mobileSub.ack.subscriptionId]);
  700. const desktopForwarded = vi.mocked(base.subscribeConversationV4).mock.calls[0]?.[0];
  701. expect(desktopForwarded).toMatchObject({
  702. workspacePath: "/repo",
  703. workspaceIdentity: "local:repo",
  704. sessionId: "session-1",
  705. });
  706. expect(readTrustedZCodeAgentV4Connection(desktopForwarded)).toEqual({
  707. connectionId: "desktop-a",
  708. clientMode: "desktop-continuous",
  709. });
  710. expect(desktopForwarded).not.toHaveProperty("deliveryProfile");
  711. });
  712. it("same-sub resync 只允许 owner,并从 registry 注入 topic/trusted connection", async () => {
  713. const { base } = setupBase();
  714. const desktop = createZCodeAgentConnectionScope(base, {
  715. connectionId: "desktop-resync",
  716. clientMode: "desktop-continuous",
  717. });
  718. const mobile = createZCodeAgentConnectionScope(base, {
  719. connectionId: "mobile-resync",
  720. clientMode: "web-remote-replayable",
  721. });
  722. for (const [scope, clientId] of [
  723. [desktop, "desktop-client"],
  724. [mobile, "mobile-client"],
  725. ] as const) {
  726. await scope.service.helloConversationV4();
  727. await scope.service.initializeConversationV4({
  728. kind: "clientHello",
  729. protocolVersion: 3,
  730. clientId,
  731. appVersion: "4.0.0",
  732. });
  733. }
  734. const subscribed = await mobile.service.subscribeConversationV4({
  735. workspacePath: "/repo",
  736. sessionId: "session-resync",
  737. });
  738. await expect(
  739. desktop.service.resyncConversationV4({
  740. workspacePath: "/repo",
  741. subscriptionId: subscribed.ack.subscriptionId,
  742. base: null,
  743. }),
  744. ).rejects.toThrow("fault.subscription.notOwned");
  745. const result = await mobile.service.resyncConversationV4({
  746. workspacePath: "/repo",
  747. subscriptionId: subscribed.ack.subscriptionId,
  748. base: { logEpoch: "epoch-1", seq: 4 },
  749. });
  750. expect(result.ack.subscriptionId).toBe(subscribed.ack.subscriptionId);
  751. const forwarded = vi.mocked(base.resyncConversationV4).mock.calls[0]?.[0];
  752. expect(forwarded).toMatchObject({
  753. workspacePath: "/repo",
  754. subscriptionId: subscribed.ack.subscriptionId,
  755. base: { logEpoch: "epoch-1", seq: 4 },
  756. });
  757. expect(readTrustedZCodeAgentV4UnsubscribeRoute(forwarded)).toEqual({
  758. topic: "conversation/session-resync",
  759. connectionId: "mobile-resync",
  760. });
  761. });
  762. it("双端同 topic 同时 pending 时,ACK 前帧只在对应 ACK owner 激活后释放", async () => {
  763. const { base, conversationFrames } = setupBase();
  764. const resolvers = new Map<
  765. string,
  766. (value: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } }) => void
  767. >();
  768. vi.mocked(base.subscribeConversationV4).mockImplementation(
  769. (params: unknown) =>
  770. new Promise((resolve) => {
  771. const connection = readTrustedZCodeAgentV4Connection(params);
  772. if (!connection) throw new Error("missing trusted connection");
  773. resolvers.set(connection.connectionId, resolve);
  774. }),
  775. );
  776. const desktop = createZCodeAgentConnectionScope(base, {
  777. connectionId: "desktop-pending",
  778. clientMode: "desktop-continuous",
  779. });
  780. const mobile = createZCodeAgentConnectionScope(base, {
  781. connectionId: "mobile-pending",
  782. clientMode: "web-remote-replayable",
  783. });
  784. for (const [scope, clientId] of [
  785. [desktop, "desktop-client"],
  786. [mobile, "mobile-client"],
  787. ] as const) {
  788. await scope.service.helloConversationV4();
  789. await scope.service.initializeConversationV4({
  790. kind: "clientHello",
  791. protocolVersion: 3,
  792. clientId,
  793. appVersion: "4.0.0",
  794. });
  795. }
  796. const desktopSeen: string[] = [];
  797. const mobileSeen: string[] = [];
  798. desktop.service.onDynamicConversationFrame({ workspacePath: "/repo" })((frame) =>
  799. desktopSeen.push(frame.subscriptionId),
  800. );
  801. mobile.service.onDynamicConversationFrame({ workspacePath: "/repo" })((frame) =>
  802. mobileSeen.push(frame.subscriptionId),
  803. );
  804. const desktopSubscribe = desktop.service.subscribeConversationV4({
  805. workspacePath: "/repo",
  806. sessionId: "session-pending",
  807. });
  808. const mobileSubscribe = mobile.service.subscribeConversationV4({
  809. workspacePath: "/repo",
  810. sessionId: "session-pending",
  811. });
  812. await vi.waitFor(() => expect(resolvers.size).toBe(2));
  813. conversationFrames.fire(
  814. completeWire(makeFrame("conversation/session-pending", "sub-desktop-pending")),
  815. );
  816. conversationFrames.fire(
  817. completeWire(makeFrame("conversation/session-pending", "sub-mobile-pending")),
  818. );
  819. expect(desktopSeen).toEqual([]);
  820. expect(mobileSeen).toEqual([]);
  821. resolvers.get("mobile-pending")?.({
  822. ack: {
  823. subscriptionId: "sub-mobile-pending",
  824. mode: "snapshot",
  825. logEpoch: "epoch-mobile",
  826. },
  827. });
  828. await mobileSubscribe;
  829. expect(desktopSeen).toEqual([]);
  830. expect(mobileSeen).toEqual(["sub-mobile-pending"]);
  831. resolvers.get("desktop-pending")?.({
  832. ack: {
  833. subscriptionId: "sub-desktop-pending",
  834. mode: "snapshot",
  835. logEpoch: "epoch-desktop",
  836. },
  837. });
  838. await desktopSubscribe;
  839. expect(desktopSeen).toEqual(["sub-desktop-pending"]);
  840. expect(mobileSeen).toEqual(["sub-mobile-pending"]);
  841. });
  842. it("unowned unsubscribe 不越权,dispose 清理本连接全部 topic", async () => {
  843. const { base, sessionsIndexFrames, workspaceConfigFrames } = setupBase();
  844. const desktop = createZCodeAgentConnectionScope(base, {
  845. connectionId: "desktop-a",
  846. clientMode: "desktop-continuous",
  847. });
  848. const mobile = createZCodeAgentConnectionScope(base, {
  849. connectionId: "mobile-b",
  850. clientMode: "web-remote-replayable",
  851. });
  852. const target = { workspacePath: "/repo", workspaceIdentity: "ssh:repo" };
  853. await mobile.service.helloConversationV4();
  854. await mobile.service.initializeConversationV4({
  855. kind: "clientHello",
  856. protocolVersion: 3,
  857. clientId: "mobile-client",
  858. appVersion: "4.0.0",
  859. });
  860. const conversation = await mobile.service.subscribeConversationV4({
  861. ...target,
  862. sessionId: "session-1",
  863. });
  864. const index = await mobile.service.subscribeSessionsIndexV4(target);
  865. const config = await mobile.service.subscribeWorkspaceConfigV4(target);
  866. const indexSeen: string[] = [];
  867. const configSeen: string[] = [];
  868. mobile.service.onDynamicSessionsIndexFrame(target)((frame) =>
  869. indexSeen.push(frame.subscriptionId),
  870. );
  871. mobile.service.onDynamicWorkspaceConfigFrame(target)((frame) =>
  872. configSeen.push(frame.subscriptionId),
  873. );
  874. sessionsIndexFrames.fire(
  875. completeWire({
  876. topic: sessionsIndexTopic("ssh:repo"),
  877. subscriptionId: "foreign-index",
  878. } as SessionsIndexTopicFrame),
  879. );
  880. sessionsIndexFrames.fire(
  881. completeWire({
  882. topic: sessionsIndexTopic("ssh:repo"),
  883. subscriptionId: index.ack.subscriptionId,
  884. } as SessionsIndexTopicFrame),
  885. );
  886. workspaceConfigFrames.fire(
  887. completeWire({
  888. topic: workspaceConfigTopic("ssh:repo"),
  889. subscriptionId: "foreign-config",
  890. } as WorkspaceConfigTopicFrame),
  891. );
  892. workspaceConfigFrames.fire(
  893. completeWire({
  894. topic: workspaceConfigTopic("ssh:repo"),
  895. subscriptionId: config.ack.subscriptionId,
  896. } as WorkspaceConfigTopicFrame),
  897. );
  898. expect(indexSeen).toEqual([index.ack.subscriptionId]);
  899. expect(configSeen).toEqual([config.ack.subscriptionId]);
  900. await desktop.service.unsubscribeConversationV4({
  901. ...target,
  902. subscriptionId: conversation.ack.subscriptionId,
  903. });
  904. expect(base.unsubscribeConversationV4).not.toHaveBeenCalled();
  905. await mobile.dispose();
  906. expect(base.unsubscribeConversationV4).toHaveBeenCalledWith(
  907. expect.objectContaining({
  908. ...target,
  909. subscriptionId: conversation.ack.subscriptionId,
  910. }),
  911. );
  912. expect(base.unsubscribeSessionsIndexV4).toHaveBeenCalledWith(
  913. expect.objectContaining({
  914. ...target,
  915. subscriptionId: index.ack.subscriptionId,
  916. }),
  917. );
  918. expect(base.unsubscribeWorkspaceConfigV4).toHaveBeenCalledWith(
  919. expect.objectContaining({
  920. ...target,
  921. subscriptionId: config.ack.subscriptionId,
  922. }),
  923. );
  924. expect(
  925. readTrustedZCodeAgentV4UnsubscribeRoute(
  926. vi.mocked(base.unsubscribeConversationV4).mock.calls[0]?.[0],
  927. ),
  928. ).toEqual({
  929. topic: "conversation/session-1",
  930. connectionId: "mobile-b",
  931. });
  932. });
  933. it("port close 与迟到 subscribe ACK 竞态时立即反向 unsubscribe", async () => {
  934. const { base } = setupBase();
  935. let resolveSubscribe!: (value: {
  936. ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string };
  937. }) => void;
  938. vi.mocked(base.subscribeConversationV4).mockImplementationOnce(
  939. () =>
  940. new Promise((resolve) => {
  941. resolveSubscribe = resolve;
  942. }),
  943. );
  944. const mobile = createZCodeAgentConnectionScope(base, {
  945. connectionId: "mobile-race",
  946. clientMode: "web-remote-replayable",
  947. });
  948. await mobile.service.helloConversationV4();
  949. await mobile.service.initializeConversationV4({
  950. kind: "clientHello",
  951. protocolVersion: 3,
  952. clientId: "mobile-race-client",
  953. appVersion: "4.0.0",
  954. });
  955. const subscribing = mobile.service.subscribeConversationV4({
  956. workspacePath: "/repo",
  957. sessionId: "session-race",
  958. });
  959. await mobile.dispose();
  960. resolveSubscribe({
  961. ack: {
  962. subscriptionId: "sub-race-late",
  963. mode: "snapshot",
  964. logEpoch: "epoch-race",
  965. },
  966. });
  967. await expect(subscribing).rejects.toThrow("fault.connection.closed");
  968. expect(base.unsubscribeConversationV4).toHaveBeenCalledWith(
  969. expect.objectContaining({
  970. workspacePath: "/repo",
  971. subscriptionId: "sub-race-late",
  972. }),
  973. );
  974. expect(
  975. readTrustedZCodeAgentV4UnsubscribeRoute(
  976. vi.mocked(base.unsubscribeConversationV4).mock.calls[0]?.[0],
  977. ),
  978. ).toEqual({
  979. topic: "conversation/session-race",
  980. connectionId: "mobile-race",
  981. });
  982. });
  983. it("首次 runtime available 先于冷启动 subscribe ACK 时保留当前 ownership", async () => {
  984. const { base } = setupBase();
  985. const runtimeLifecycle = attachRuntimeLifecycle(base);
  986. const resolvers: Array<
  987. (value: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } }) => void
  988. > = [];
  989. vi.mocked(base.subscribeConversationV4).mockImplementation(
  990. () => new Promise((resolve) => resolvers.push(resolve)),
  991. );
  992. const scope = createZCodeAgentConnectionScope(base, {
  993. connectionId: "mobile-cold-start",
  994. clientMode: "web-remote-replayable",
  995. });
  996. await scope.service.helloConversationV4();
  997. await scope.service.initializeConversationV4({
  998. kind: "clientHello",
  999. protocolVersion: 3,
  1000. clientId: "mobile-cold-start-client",
  1001. appVersion: "4.0.0",
  1002. });
  1003. const target = {
  1004. workspacePath: "/repo",
  1005. workspaceIdentity: "ssh://cold-start/repo",
  1006. };
  1007. const subscribing = scope.service.subscribeConversationV4({
  1008. ...target,
  1009. sessionId: "session-cold-start",
  1010. });
  1011. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  1012. runtimeLifecycle.fire(makeRuntimeLifecycleEvent(target, 1, "available"));
  1013. resolvers[0]!({
  1014. ack: {
  1015. subscriptionId: "sub-cold-start",
  1016. mode: "snapshot",
  1017. logEpoch: "epoch-cold-start",
  1018. },
  1019. });
  1020. await expect(subscribing).resolves.toEqual(
  1021. expect.objectContaining({
  1022. ack: expect.objectContaining({ subscriptionId: "sub-cold-start" }),
  1023. }),
  1024. );
  1025. await scope.service.unsubscribeConversationV4({
  1026. ...target,
  1027. subscriptionId: "sub-cold-start",
  1028. });
  1029. expect(base.unsubscribeConversationV4).toHaveBeenCalledTimes(1);
  1030. await scope.dispose();
  1031. runtimeLifecycle.dispose();
  1032. });
  1033. it("runtime unavailable 失效旧 ACK,但换代 available 不误伤边界后的新 subscribe", async () => {
  1034. const { base } = setupBase();
  1035. const runtimeLifecycle = attachRuntimeLifecycle(base);
  1036. const resolvers: Array<
  1037. (value: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } }) => void
  1038. > = [];
  1039. vi.mocked(base.subscribeConversationV4).mockImplementation(
  1040. () => new Promise((resolve) => resolvers.push(resolve)),
  1041. );
  1042. const scope = createZCodeAgentConnectionScope(base, {
  1043. connectionId: "desktop-lifecycle-boundary",
  1044. clientMode: "desktop-continuous",
  1045. });
  1046. await scope.service.helloConversationV4();
  1047. await scope.service.initializeConversationV4({
  1048. kind: "clientHello",
  1049. protocolVersion: 3,
  1050. clientId: "desktop-lifecycle-boundary-client",
  1051. appVersion: "4.0.0",
  1052. });
  1053. const target = { workspacePath: "/repo" };
  1054. runtimeLifecycle.fire(makeRuntimeLifecycleEvent(target, 1, "available"));
  1055. const oldPending = scope.service.subscribeConversationV4({
  1056. ...target,
  1057. sessionId: "session-lifecycle-boundary",
  1058. });
  1059. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  1060. runtimeLifecycle.fire(makeRuntimeLifecycleEvent(target, 1, "unavailable"));
  1061. const fresh = scope.service.subscribeConversationV4({
  1062. ...target,
  1063. sessionId: "session-lifecycle-boundary",
  1064. });
  1065. await vi.waitFor(() => expect(resolvers).toHaveLength(2));
  1066. runtimeLifecycle.fire(makeRuntimeLifecycleEvent(target, 2, "available"));
  1067. resolvers[1]!({
  1068. ack: { subscriptionId: "sub-new", mode: "snapshot", logEpoch: "epoch-new" },
  1069. });
  1070. await expect(fresh).resolves.toEqual(
  1071. expect.objectContaining({ ack: expect.objectContaining({ subscriptionId: "sub-new" }) }),
  1072. );
  1073. resolvers[0]!({
  1074. ack: { subscriptionId: "sub-old", mode: "snapshot", logEpoch: "epoch-old" },
  1075. });
  1076. await expect(oldPending).rejects.toThrow("fault.subscription.runtimeRestarted");
  1077. expect(base.unsubscribeConversationV4).not.toHaveBeenCalled();
  1078. await scope.dispose();
  1079. runtimeLifecycle.dispose();
  1080. });
  1081. it("runtime restart 清旧 ownership;迟到旧 ACK 不 remember 也不误退新 runtime 同名 sub", async () => {
  1082. const { base, conversationFrames, runtimeRestarts } = setupBase();
  1083. const resolvers: Array<
  1084. (value: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } }) => void
  1085. > = [];
  1086. vi.mocked(base.subscribeConversationV4).mockImplementation(
  1087. () => new Promise((resolve) => resolvers.push(resolve)),
  1088. );
  1089. const scope = createZCodeAgentConnectionScope(base, {
  1090. connectionId: "restart-scope",
  1091. clientMode: "desktop-continuous",
  1092. });
  1093. await scope.service.helloConversationV4();
  1094. await scope.service.initializeConversationV4({
  1095. kind: "clientHello",
  1096. protocolVersion: 3,
  1097. clientId: "restart-client",
  1098. appVersion: "4.0.0",
  1099. });
  1100. const seen: string[] = [];
  1101. scope.service.onDynamicConversationFrame({ workspacePath: "/repo" })((wire) =>
  1102. seen.push(wire.logicalFrameId),
  1103. );
  1104. const oldPending = scope.service.subscribeConversationV4({
  1105. workspacePath: "/repo",
  1106. sessionId: "session-restart",
  1107. });
  1108. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  1109. runtimeRestarts.fire({ workspaceKey: "/repo" });
  1110. conversationFrames.fire(
  1111. completeWire(makeFrame("conversation/session-restart", "sub-reused"), "old-runtime-wire"),
  1112. );
  1113. expect(seen).toEqual([]);
  1114. const fresh = scope.service.subscribeConversationV4({
  1115. workspacePath: "/repo",
  1116. sessionId: "session-restart",
  1117. });
  1118. await vi.waitFor(() => expect(resolvers).toHaveLength(2));
  1119. resolvers[1]!({
  1120. ack: { subscriptionId: "sub-reused", mode: "snapshot", logEpoch: "epoch-new" },
  1121. });
  1122. await fresh;
  1123. resolvers[0]!({
  1124. ack: { subscriptionId: "sub-reused", mode: "snapshot", logEpoch: "epoch-old" },
  1125. });
  1126. await expect(oldPending).rejects.toThrow("fault.subscription.runtimeRestarted");
  1127. expect(base.unsubscribeConversationV4).not.toHaveBeenCalled();
  1128. conversationFrames.fire(
  1129. completeWire(makeFrame("conversation/session-restart", "sub-reused"), "new-runtime-wire"),
  1130. );
  1131. expect(seen).toEqual(["new-runtime-wire"]);
  1132. await scope.dispose();
  1133. });
  1134. it("workspace A restart 不清 workspace B 的 owner/pending", async () => {
  1135. const { base, conversationFrames, runtimeRestarts } = setupBase();
  1136. const resolvers = new Map<
  1137. string,
  1138. (value: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } }) => void
  1139. >();
  1140. vi.mocked(base.subscribeConversationV4).mockImplementation(
  1141. (params: { sessionId: string }) =>
  1142. new Promise((resolve) => resolvers.set(params.sessionId, resolve)),
  1143. );
  1144. const scope = createZCodeAgentConnectionScope(base, {
  1145. connectionId: "workspace-isolation",
  1146. clientMode: "desktop-continuous",
  1147. });
  1148. await scope.service.helloConversationV4();
  1149. await scope.service.initializeConversationV4({
  1150. kind: "clientHello",
  1151. protocolVersion: 3,
  1152. clientId: "workspace-client",
  1153. appVersion: "4.0.0",
  1154. });
  1155. const seen: string[] = [];
  1156. scope.service.onDynamicConversationFrame({ workspacePath: "/workspace-b" })((wire) =>
  1157. seen.push(wire.logicalFrameId),
  1158. );
  1159. const pendingA = scope.service.subscribeConversationV4({
  1160. workspacePath: "/workspace-a",
  1161. sessionId: "session-a",
  1162. });
  1163. const pendingB = scope.service.subscribeConversationV4({
  1164. workspacePath: "/workspace-b",
  1165. sessionId: "session-b",
  1166. });
  1167. await vi.waitFor(() => expect(resolvers.size).toBe(2));
  1168. runtimeRestarts.fire({ workspaceKey: "/workspace-a" });
  1169. resolvers.get("session-b")?.({
  1170. ack: { subscriptionId: "sub-b", mode: "snapshot", logEpoch: "epoch-b" },
  1171. });
  1172. await pendingB;
  1173. resolvers.get("session-a")?.({
  1174. ack: { subscriptionId: "sub-a", mode: "snapshot", logEpoch: "epoch-a" },
  1175. });
  1176. await expect(pendingA).rejects.toThrow("fault.subscription.runtimeRestarted");
  1177. conversationFrames.fire(
  1178. completeWire(makeFrame("conversation/session-b", "sub-b"), "workspace-b-wire"),
  1179. );
  1180. expect(seen).toEqual(["workspace-b-wire"]);
  1181. await scope.dispose();
  1182. });
  1183. it("trusted host relay 为 desktop/mobile 下游保留 mode 并 namespace connectionId", async () => {
  1184. const { base } = setupBase();
  1185. const relay = createZCodeAgentConnectionScope(base, {
  1186. connectionId: "server-upstream",
  1187. clientMode: "desktop-continuous",
  1188. role: "trusted-host-relay",
  1189. });
  1190. const desktop = createZCodeAgentConnectionScope(relay.service, {
  1191. connectionId: "desktop-downstream",
  1192. clientMode: "desktop-continuous",
  1193. });
  1194. const mobile = createZCodeAgentConnectionScope(relay.service, {
  1195. connectionId: "mobile-downstream",
  1196. clientMode: "web-remote-replayable",
  1197. });
  1198. for (const scope of [desktop, mobile]) {
  1199. await scope.service.helloConversationV4();
  1200. await scope.service.initializeConversationV4({
  1201. kind: "clientHello",
  1202. protocolVersion: 3,
  1203. clientId: "downstream-client",
  1204. appVersion: "4.0.0",
  1205. });
  1206. }
  1207. await desktop.service.subscribeConversationV4({
  1208. workspacePath: "/repo",
  1209. sessionId: "session-1",
  1210. });
  1211. await mobile.service.subscribeConversationV4({
  1212. workspacePath: "/repo",
  1213. sessionId: "session-1",
  1214. });
  1215. const forwarded = vi.mocked(base.subscribeConversationV4).mock.calls;
  1216. expect(readTrustedZCodeAgentV4Connection(forwarded[0]?.[0])).toEqual({
  1217. connectionId: "relay:15:server-upstream18:desktop-downstream",
  1218. clientMode: "desktop-continuous",
  1219. });
  1220. expect(readTrustedZCodeAgentV4Connection(forwarded[1]?.[0])).toEqual({
  1221. connectionId: "relay:15:server-upstream17:mobile-downstream",
  1222. clientMode: "web-remote-replayable",
  1223. });
  1224. });
  1225. it("stores pre-subscribe flow state, forwards one trusted route, and serializes edges", async () => {
  1226. const { base } = setupBase();
  1227. const scope = createZCodeAgentConnectionScope(base, {
  1228. connectionId: "mobile-flow",
  1229. clientMode: "web-remote-replayable",
  1230. });
  1231. await scope.service.helloConversationV4();
  1232. await scope.service.initializeConversationV4({
  1233. kind: "clientHello",
  1234. protocolVersion: 3,
  1235. clientId: "mobile-flow-client",
  1236. appVersion: "4.0.0",
  1237. });
  1238. await scope.setTransportFlowState("saturated");
  1239. expect(base.setConnectionFlowStateV4).not.toHaveBeenCalled();
  1240. await scope.service.subscribeConversationV4({
  1241. workspacePath: "/repo",
  1242. sessionId: "session-flow",
  1243. });
  1244. expect(base.setConnectionFlowStateV4).toHaveBeenCalledTimes(1);
  1245. const first = vi.mocked(base.setConnectionFlowStateV4).mock.calls[0]?.[0];
  1246. expect(first).toMatchObject({ workspacePath: "/repo", state: "saturated" });
  1247. expect(readTrustedZCodeAgentV4Connection(first)).toEqual({
  1248. connectionId: "mobile-flow",
  1249. clientMode: "web-remote-replayable",
  1250. });
  1251. await scope.service.subscribeSessionsIndexV4({ workspacePath: "/repo" });
  1252. expect(base.setConnectionFlowStateV4).toHaveBeenCalledTimes(1);
  1253. await Promise.all([
  1254. scope.setTransportFlowState("drained"),
  1255. scope.setTransportFlowState("saturated"),
  1256. scope.setTransportFlowState("drained"),
  1257. scope.setTransportFlowState("drained"),
  1258. ]);
  1259. expect(
  1260. vi
  1261. .mocked(base.setConnectionFlowStateV4)
  1262. .mock.calls.map(([params]) => (params as { state: string }).state),
  1263. ).toEqual(["saturated", "drained", "saturated", "drained"]);
  1264. await expect(
  1265. scope.service.setConnectionFlowStateV4({
  1266. workspacePath: "/repo",
  1267. state: "saturated",
  1268. }),
  1269. ).rejects.toThrow("fault.connection.flowControlForbidden");
  1270. await scope.dispose();
  1271. expect(
  1272. vi
  1273. .mocked(base.setConnectionFlowStateV4)
  1274. .mock.calls.map(([params]) => (params as { state: string }).state),
  1275. ).toEqual(["saturated", "drained", "saturated", "drained", "closed"]);
  1276. await scope.setTransportFlowState("saturated");
  1277. expect(base.setConnectionFlowStateV4).toHaveBeenCalledTimes(5);
  1278. });
  1279. it("trusted relay namespaces downstream flow control and rejects terminal injection", async () => {
  1280. const { base } = setupBase();
  1281. const relay = createZCodeAgentConnectionScope(base, {
  1282. connectionId: "server-upstream",
  1283. clientMode: "desktop-continuous",
  1284. role: "trusted-host-relay",
  1285. });
  1286. const mobile = createZCodeAgentConnectionScope(relay.service, {
  1287. connectionId: "mobile-downstream",
  1288. clientMode: "web-remote-replayable",
  1289. });
  1290. await mobile.service.helloConversationV4();
  1291. await mobile.service.initializeConversationV4({
  1292. kind: "clientHello",
  1293. protocolVersion: 3,
  1294. clientId: "mobile-client",
  1295. appVersion: "4.0.0",
  1296. });
  1297. const subscribed = await mobile.service.subscribeConversationV4({
  1298. workspacePath: "/repo",
  1299. sessionId: "session-flow",
  1300. });
  1301. await mobile.setTransportFlowState("saturated");
  1302. const forwarded = vi.mocked(base.setConnectionFlowStateV4).mock.calls[0]?.[0];
  1303. expect(readTrustedZCodeAgentV4Connection(forwarded)).toEqual({
  1304. connectionId: "relay:15:server-upstream17:mobile-downstream",
  1305. clientMode: "web-remote-replayable",
  1306. });
  1307. expect(forwarded).toMatchObject({ workspacePath: "/repo", state: "saturated" });
  1308. await expect(
  1309. mobile.service.setConnectionFlowStateV4({
  1310. workspacePath: "/repo",
  1311. state: "drained",
  1312. }),
  1313. ).rejects.toThrow("fault.connection.flowControlForbidden");
  1314. await mobile.service.unsubscribeConversationV4({
  1315. workspacePath: "/repo",
  1316. subscriptionId: subscribed.ack.subscriptionId,
  1317. });
  1318. expect(
  1319. vi
  1320. .mocked(base.setConnectionFlowStateV4)
  1321. .mock.calls.map(([params]) => (params as { state: string }).state),
  1322. ).toEqual(["saturated", "closed"]);
  1323. expect(base.unsubscribeConversationV4).toHaveBeenCalledOnce();
  1324. expect(vi.mocked(base.setConnectionFlowStateV4).mock.invocationCallOrder.at(-1)).toBeLessThan(
  1325. vi.mocked(base.unsubscribeConversationV4).mock.invocationCallOrder[0]!,
  1326. );
  1327. await mobile.dispose();
  1328. await relay.dispose();
  1329. });
  1330. it("trusted relay 允许 attachment-only downstream close 清理 namespaced staging", async () => {
  1331. const { base } = setupBase();
  1332. const relay = createZCodeAgentConnectionScope(base, {
  1333. connectionId: "server-attachment",
  1334. clientMode: "desktop-continuous",
  1335. role: "trusted-host-relay",
  1336. });
  1337. const mobile = createZCodeAgentConnectionScope(relay.service, {
  1338. connectionId: "mobile-attachment",
  1339. clientMode: "web-remote-replayable",
  1340. });
  1341. await mobile.service.helloConversationV4();
  1342. await mobile.service.initializeConversationV4({
  1343. kind: "clientHello",
  1344. protocolVersion: 3,
  1345. clientId: "mobile-attachment-client",
  1346. appVersion: "4.0.0",
  1347. });
  1348. await mobile.service.attachmentBeginV4({
  1349. workspacePath: "/repo",
  1350. sessionId: "session-attachment",
  1351. uploadId: "upload-remote",
  1352. fileName: "remote.bin",
  1353. mime: "application/octet-stream",
  1354. totalBytes: 1,
  1355. totalChunks: 1,
  1356. checksum: `sha256:${"0".repeat(64)}`,
  1357. });
  1358. await mobile.dispose();
  1359. const closed = vi
  1360. .mocked(base.setConnectionFlowStateV4)
  1361. .mock.calls.map(([params]) => params)
  1362. .find((params) => params.state === "closed");
  1363. expect(readTrustedZCodeAgentV4Connection(closed)).toEqual({
  1364. connectionId: "relay:17:server-attachment17:mobile-attachment",
  1365. clientMode: "web-remote-replayable",
  1366. });
  1367. expect(closed).toMatchObject({ workspacePath: "/repo", state: "closed" });
  1368. await relay.dispose();
  1369. });
  1370. it("trusted relay 对相同裸 subId 使用下游 topic/connection 精确退订", async () => {
  1371. const { base } = setupBase();
  1372. vi.mocked(base.subscribeConversationV4).mockImplementation(async () => ({
  1373. ack: {
  1374. subscriptionId: "sub-shared",
  1375. mode: "snapshot" as const,
  1376. logEpoch: "epoch-shared",
  1377. },
  1378. }));
  1379. const relay = createZCodeAgentConnectionScope(base, {
  1380. connectionId: "server-upstream",
  1381. clientMode: "desktop-continuous",
  1382. role: "trusted-host-relay",
  1383. });
  1384. const desktop = createZCodeAgentConnectionScope(relay.service, {
  1385. connectionId: "desktop-downstream",
  1386. clientMode: "desktop-continuous",
  1387. });
  1388. const mobile = createZCodeAgentConnectionScope(relay.service, {
  1389. connectionId: "mobile-downstream",
  1390. clientMode: "web-remote-replayable",
  1391. });
  1392. for (const [scope, clientId] of [
  1393. [desktop, "desktop-client"],
  1394. [mobile, "mobile-client"],
  1395. ] as const) {
  1396. await scope.service.helloConversationV4();
  1397. await scope.service.initializeConversationV4({
  1398. kind: "clientHello",
  1399. protocolVersion: 3,
  1400. clientId,
  1401. appVersion: "4.0.0",
  1402. });
  1403. }
  1404. await desktop.service.subscribeConversationV4({
  1405. workspacePath: "/repo",
  1406. sessionId: "desktop-session",
  1407. });
  1408. await mobile.service.subscribeConversationV4({
  1409. workspacePath: "/repo",
  1410. sessionId: "mobile-session",
  1411. });
  1412. await mobile.service.unsubscribeConversationV4({
  1413. workspacePath: "/repo",
  1414. subscriptionId: "sub-shared",
  1415. });
  1416. const firstRoute = readTrustedZCodeAgentV4UnsubscribeRoute(
  1417. vi.mocked(base.unsubscribeConversationV4).mock.calls[0]?.[0],
  1418. );
  1419. expect(firstRoute).toEqual({
  1420. topic: "conversation/mobile-session",
  1421. connectionId: "relay:15:server-upstream17:mobile-downstream",
  1422. });
  1423. await desktop.service.unsubscribeConversationV4({
  1424. workspacePath: "/repo",
  1425. subscriptionId: "sub-shared",
  1426. });
  1427. const secondRoute = readTrustedZCodeAgentV4UnsubscribeRoute(
  1428. vi.mocked(base.unsubscribeConversationV4).mock.calls[1]?.[0],
  1429. );
  1430. expect(secondRoute).toEqual({
  1431. topic: "conversation/desktop-session",
  1432. connectionId: "relay:15:server-upstream18:desktop-downstream",
  1433. });
  1434. });
  1435. it("connectionId 拒绝空值/超长值,relay namespace 不使用可歧义分隔符拼接", () => {
  1436. const { base } = setupBase();
  1437. expect(() =>
  1438. createZCodeAgentConnectionScope(base, {
  1439. connectionId: "",
  1440. clientMode: "desktop-continuous",
  1441. }),
  1442. ).toThrow("fault.connection.invalidConnectionId");
  1443. expect(() =>
  1444. createZCodeAgentConnectionScope(base, {
  1445. connectionId: "x".repeat(257),
  1446. clientMode: "desktop-continuous",
  1447. }),
  1448. ).toThrow("fault.connection.invalidConnectionId");
  1449. });
  1450. it("terminal command/attachment 受握手门禁约束,且 command clientId 必须匹配绑定身份", async () => {
  1451. const { base } = setupBase();
  1452. const scope = createZCodeAgentConnectionScope(base, {
  1453. connectionId: "terminal-command",
  1454. clientMode: "desktop-continuous",
  1455. });
  1456. const command = {
  1457. workspacePath: "/repo",
  1458. envelope: {
  1459. commandId: "cmd-1",
  1460. clientId: "client-bound",
  1461. sessionId: "session-1",
  1462. type: "sendText" as const,
  1463. payload: { text: "hello" },
  1464. issuedAt: 1,
  1465. },
  1466. };
  1467. await expect(scope.service.sendConversationCommandV4(command)).rejects.toThrow(
  1468. "fault.connection.handshakeRequired",
  1469. );
  1470. await expect(
  1471. scope.service.attachmentBeginV4({
  1472. workspacePath: "/repo",
  1473. sessionId: "session-1",
  1474. uploadId: "upload-1",
  1475. fileName: "test.txt",
  1476. mime: "text/plain",
  1477. totalBytes: 1,
  1478. totalChunks: 1,
  1479. checksum: `sha256:${"0".repeat(64)}`,
  1480. }),
  1481. ).rejects.toThrow("fault.connection.handshakeRequired");
  1482. await scope.service.helloConversationV4();
  1483. await scope.service.initializeConversationV4({
  1484. kind: "clientHello",
  1485. protocolVersion: 3,
  1486. clientId: "client-bound",
  1487. appVersion: "4.0.0",
  1488. });
  1489. await expect(
  1490. scope.service.sendConversationCommandV4({
  1491. ...command,
  1492. envelope: { ...command.envelope, clientId: "client-forged" },
  1493. }),
  1494. ).rejects.toThrow("fault.command.clientMismatch");
  1495. expect(base.sendConversationCommandV4).not.toHaveBeenCalled();
  1496. await expect(scope.service.sendConversationCommandV4(command)).resolves.toMatchObject({
  1497. commandId: "cmd-1",
  1498. status: "accepted",
  1499. });
  1500. const forwardedCommand = vi.mocked(base.sendConversationCommandV4).mock.calls.at(-1)?.[0];
  1501. expect(forwardedCommand).toMatchObject(command);
  1502. expect(readTrustedZCodeAgentV4Connection(forwardedCommand)).toEqual({
  1503. connectionId: "terminal-command",
  1504. clientMode: "desktop-continuous",
  1505. });
  1506. await scope.service.attachmentBeginV4({
  1507. workspacePath: "/repo",
  1508. sessionId: "session-1",
  1509. uploadId: "upload-1",
  1510. fileName: "test.txt",
  1511. mime: "text/plain",
  1512. totalBytes: 1,
  1513. totalChunks: 1,
  1514. checksum: `sha256:${"0".repeat(64)}`,
  1515. });
  1516. const forwardedAttachment = vi.mocked(base.attachmentBeginV4).mock.calls.at(-1)?.[0];
  1517. expect(readTrustedZCodeAgentV4Connection(forwardedAttachment)).toEqual({
  1518. connectionId: "terminal-command",
  1519. clientMode: "desktop-continuous",
  1520. });
  1521. });
  1522. it("手机 replayable command 原样透传 canonical plugin link,不新增 selection state", async () => {
  1523. const { base } = setupBase();
  1524. const scope = createZCodeAgentConnectionScope(base, {
  1525. connectionId: "mobile-plugin-reference",
  1526. clientMode: "web-remote-replayable",
  1527. });
  1528. await scope.service.helloConversationV4();
  1529. await scope.service.initializeConversationV4({
  1530. kind: "clientHello",
  1531. protocolVersion: 3,
  1532. clientId: "mobile-plugin-client",
  1533. appVersion: "4.0.0",
  1534. });
  1535. const canonicalText = "请使用 [@Demo](plugin://demo@mkt-a) 完成任务";
  1536. const command = {
  1537. workspacePath: "/remote/work",
  1538. workspaceIdentity: "ssh://host/remote/work",
  1539. remoteSessionId: "remote-runtime-1",
  1540. // renderer/mobile 传入的 mode 不可信;facade 必须用 host 绑定的 replayable 真值覆盖。
  1541. clientMode: "desktop-continuous" as const,
  1542. envelope: {
  1543. commandId: "cmd-plugin-reference",
  1544. clientId: "mobile-plugin-client",
  1545. sessionId: "session-plugin",
  1546. type: "sendText" as const,
  1547. payload: { text: canonicalText },
  1548. issuedAt: 1,
  1549. },
  1550. };
  1551. await scope.service.sendConversationCommandV4(command);
  1552. const forwarded = vi.mocked(base.sendConversationCommandV4).mock.calls[0]?.[0];
  1553. expect(forwarded).toMatchObject({
  1554. workspacePath: command.workspacePath,
  1555. workspaceIdentity: command.workspaceIdentity,
  1556. remoteSessionId: command.remoteSessionId,
  1557. envelope: command.envelope,
  1558. });
  1559. expect(forwarded).not.toHaveProperty("clientMode");
  1560. expect(forwarded?.envelope.payload).toEqual({ text: canonicalText });
  1561. expect(readTrustedZCodeAgentV4Connection(forwarded)).toEqual({
  1562. connectionId: "mobile-plugin-reference",
  1563. clientMode: "web-remote-replayable",
  1564. });
  1565. await scope.dispose();
  1566. });
  1567. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  1568. "Bash output query preserves remote routing and trusted %s mode",
  1569. async (clientMode) => {
  1570. const { base } = setupBase();
  1571. const scope = createZCodeAgentConnectionScope(base, {
  1572. connectionId: "bash-output",
  1573. clientMode,
  1574. });
  1575. const query = {
  1576. workspacePath: "/remote/repo",
  1577. workspaceIdentity: "remote:ssh:host:/remote/repo",
  1578. remoteSessionId: "remote-session",
  1579. sessionId: "child-session",
  1580. workId: "work",
  1581. };
  1582. await expect(scope.service.backgroundBashOutputV4(query)).rejects.toThrow();
  1583. expect(base.backgroundBashOutputV4).not.toHaveBeenCalled();
  1584. await scope.service.helloConversationV4();
  1585. await scope.service.initializeConversationV4({
  1586. kind: "clientHello",
  1587. protocolVersion: 3,
  1588. clientId: "bash-output",
  1589. appVersion: "test",
  1590. });
  1591. await scope.service.backgroundBashOutputV4(query);
  1592. const forwarded = vi.mocked(base.backgroundBashOutputV4).mock.calls[0]?.[0];
  1593. expect(forwarded).toMatchObject(query);
  1594. expect(readTrustedZCodeAgentV4Connection(forwarded)).toEqual({
  1595. connectionId: "bash-output",
  1596. clientMode,
  1597. });
  1598. expect(base.sendConversationCommandV4).not.toHaveBeenCalled();
  1599. await scope.dispose();
  1600. },
  1601. );
  1602. it("commands/query 必须握手、注入 trusted connection,并拒绝跨 workspace 复用", async () => {
  1603. const { base } = setupBase();
  1604. const scope = createZCodeAgentConnectionScope(base, {
  1605. connectionId: "terminal-query",
  1606. clientMode: "desktop-continuous",
  1607. });
  1608. const query = {
  1609. workspacePath: "/repo",
  1610. workspaceIdentity: "remote:ssh:a:/repo",
  1611. commands: [{ sessionId: "session-1", commandId: "command-1" }],
  1612. };
  1613. await expect(scope.service.queryConversationCommandsV4(query)).rejects.toThrow(
  1614. "fault.connection.handshakeRequired",
  1615. );
  1616. await scope.service.helloConversationV4();
  1617. await scope.service.initializeConversationV4({
  1618. kind: "clientHello",
  1619. protocolVersion: 3,
  1620. clientId: "query-client",
  1621. appVersion: "4.0.0",
  1622. });
  1623. await scope.service.queryConversationCommandsV4({
  1624. workspacePath: "/clock-only",
  1625. clock: true,
  1626. commands: [{ sessionId: null, commandId: "ttft-clock-probe" }],
  1627. });
  1628. await expect(scope.service.queryConversationCommandsV4(query)).resolves.toMatchObject({
  1629. results: [{ result: "unknown" }],
  1630. });
  1631. const forwarded = vi.mocked(base.queryConversationCommandsV4).mock.calls.at(-1)?.[0];
  1632. expect(readTrustedZCodeAgentV4Connection(forwarded)).toEqual({
  1633. connectionId: "terminal-query",
  1634. clientMode: "desktop-continuous",
  1635. });
  1636. await expect(
  1637. scope.service.queryConversationCommandsV4({
  1638. ...query,
  1639. workspaceIdentity: "remote:ssh:b:/repo",
  1640. }),
  1641. ).rejects.toThrow("fault.command.queryForeignWorkspace");
  1642. });
  1643. it("attachment staging 即使没有 subscription,scope dispose 也向该 trusted connection 发 closed", async () => {
  1644. const { base } = setupBase();
  1645. const scope = createZCodeAgentConnectionScope(base, {
  1646. connectionId: "attachment-only",
  1647. clientMode: "web-remote-replayable",
  1648. });
  1649. await scope.service.helloConversationV4();
  1650. await scope.service.initializeConversationV4({
  1651. kind: "clientHello",
  1652. protocolVersion: 3,
  1653. clientId: "attachment-client",
  1654. appVersion: "4.0.0",
  1655. });
  1656. await scope.service.attachmentBeginV4({
  1657. workspacePath: "/repo",
  1658. sessionId: "session-1",
  1659. uploadId: "upload-only",
  1660. fileName: "only.bin",
  1661. mime: "application/octet-stream",
  1662. totalBytes: 1,
  1663. totalChunks: 1,
  1664. checksum: `sha256:${"0".repeat(64)}`,
  1665. });
  1666. await scope.dispose();
  1667. const closed = vi.mocked(base.setConnectionFlowStateV4).mock.calls.at(-1)?.[0];
  1668. expect(closed?.state).toBe("closed");
  1669. expect(readTrustedZCodeAgentV4Connection(closed)).toEqual({
  1670. connectionId: "attachment-only",
  1671. clientMode: "web-remote-replayable",
  1672. });
  1673. });
  1674. it("迟到的 attachment begin ACK 在 scope close 后立即 abort,不遗留 staging", async () => {
  1675. const { base } = setupBase();
  1676. let resolveBegin!: (value: {
  1677. uploadId: string;
  1678. state: "staging";
  1679. nextChunkIndex: number;
  1680. }) => void;
  1681. vi.mocked(base.attachmentBeginV4).mockImplementationOnce(
  1682. () =>
  1683. new Promise((resolve) => {
  1684. resolveBegin = resolve;
  1685. }),
  1686. );
  1687. const scope = createZCodeAgentConnectionScope(base, {
  1688. connectionId: "attachment-late",
  1689. clientMode: "web-remote-replayable",
  1690. });
  1691. await scope.service.helloConversationV4();
  1692. await scope.service.initializeConversationV4({
  1693. kind: "clientHello",
  1694. protocolVersion: 3,
  1695. clientId: "attachment-late-client",
  1696. appVersion: "4.0.0",
  1697. });
  1698. const pending = scope.service.attachmentBeginV4({
  1699. workspacePath: "/repo",
  1700. sessionId: "session-1",
  1701. uploadId: "upload-late",
  1702. fileName: "late.bin",
  1703. mime: "application/octet-stream",
  1704. totalBytes: 1,
  1705. totalChunks: 1,
  1706. checksum: `sha256:${"0".repeat(64)}`,
  1707. });
  1708. await vi.waitFor(() => expect(base.attachmentBeginV4).toHaveBeenCalledTimes(1));
  1709. await scope.dispose();
  1710. resolveBegin({ uploadId: "upload-late", state: "staging", nextChunkIndex: 0 });
  1711. await expect(pending).rejects.toThrow("fault.connection.closed");
  1712. expect(base.attachmentAbortV4).toHaveBeenCalledTimes(1);
  1713. expect(
  1714. readTrustedZCodeAgentV4Connection(vi.mocked(base.attachmentAbortV4).mock.calls[0][0]),
  1715. ).toEqual({
  1716. connectionId: "attachment-late",
  1717. clientMode: "web-remote-replayable",
  1718. });
  1719. });
  1720. it("已发送媒体精确 row target 沿当前 mobile connection 注入可信 workspace 路由", async () => {
  1721. const { base } = setupBase();
  1722. const scope = createZCodeAgentConnectionScope(base, {
  1723. connectionId: "mobile-preview",
  1724. clientMode: "web-remote-replayable",
  1725. });
  1726. await scope.service.helloConversationV4();
  1727. await scope.service.initializeConversationV4({
  1728. kind: "clientHello",
  1729. protocolVersion: 3,
  1730. clientId: "mobile-preview-client",
  1731. appVersion: "4.0.0",
  1732. });
  1733. const params = {
  1734. workspacePath: "/remote/work",
  1735. workspaceIdentity: "ssh://host/remote/work",
  1736. sessionId: "session-video",
  1737. ref: "/remote/work/demo.mov",
  1738. target: { rowId: 42, entityId: "message-42" },
  1739. attachmentIndex: 1,
  1740. offset: 0,
  1741. limit: 512 * 1024,
  1742. };
  1743. await scope.service.attachmentReadV4(params);
  1744. const forwarded = vi.mocked(base.attachmentReadV4).mock.calls[0]?.[0];
  1745. expect(forwarded).toMatchObject(params);
  1746. expect(readTrustedZCodeAgentV4Connection(forwarded)).toEqual({
  1747. connectionId: "mobile-preview",
  1748. clientMode: "web-remote-replayable",
  1749. });
  1750. await scope.dispose();
  1751. });
  1752. it("trusted relay 保留下游 terminal 已校验的 command envelope", async () => {
  1753. const { base } = setupBase();
  1754. const relay = createZCodeAgentConnectionScope(base, {
  1755. connectionId: "server-relay",
  1756. clientMode: "desktop-continuous",
  1757. role: "trusted-host-relay",
  1758. });
  1759. const params = {
  1760. workspacePath: "/repo",
  1761. envelope: {
  1762. commandId: "cmd-relay",
  1763. clientId: "downstream-client",
  1764. sessionId: "session-1",
  1765. type: "sendText" as const,
  1766. payload: { text: "relay" },
  1767. issuedAt: 1,
  1768. },
  1769. };
  1770. await relay.service.sendConversationCommandV4(params);
  1771. const forwarded = vi.mocked(base.sendConversationCommandV4).mock.calls.at(-1)?.[0];
  1772. expect(forwarded).toMatchObject(params);
  1773. expect(readTrustedZCodeAgentV4Connection(forwarded)).toEqual({
  1774. connectionId: "server-relay",
  1775. clientMode: "desktop-continuous",
  1776. });
  1777. });
  1778. it("subscriptionId 跨 topic 碰撞时仍按 topic 隔离端口", async () => {
  1779. const { base, conversationFrames } = setupBase();
  1780. vi.mocked(base.subscribeConversationV4).mockResolvedValue({
  1781. ack: {
  1782. subscriptionId: "sub-collision",
  1783. mode: "snapshot",
  1784. logEpoch: "epoch-collision",
  1785. },
  1786. });
  1787. const desktop = createZCodeAgentConnectionScope(base, {
  1788. connectionId: "desktop-collision",
  1789. clientMode: "desktop-continuous",
  1790. });
  1791. const mobile = createZCodeAgentConnectionScope(base, {
  1792. connectionId: "mobile-collision",
  1793. clientMode: "web-remote-replayable",
  1794. });
  1795. for (const [scope, clientId] of [
  1796. [desktop, "desktop-client"],
  1797. [mobile, "mobile-client"],
  1798. ] as const) {
  1799. await scope.service.helloConversationV4();
  1800. await scope.service.initializeConversationV4({
  1801. kind: "clientHello",
  1802. protocolVersion: 3,
  1803. clientId,
  1804. appVersion: "4.0.0",
  1805. });
  1806. }
  1807. await desktop.service.subscribeConversationV4({
  1808. workspacePath: "/repo",
  1809. sessionId: "session-desktop",
  1810. });
  1811. await mobile.service.subscribeConversationV4({
  1812. workspacePath: "/repo",
  1813. sessionId: "session-mobile",
  1814. });
  1815. const desktopSeen: string[] = [];
  1816. const mobileSeen: string[] = [];
  1817. desktop.service.onDynamicConversationFrame({ workspacePath: "/repo" })((frame) =>
  1818. desktopSeen.push(frame.topic),
  1819. );
  1820. mobile.service.onDynamicConversationFrame({ workspacePath: "/repo" })((frame) =>
  1821. mobileSeen.push(frame.topic),
  1822. );
  1823. conversationFrames.fire(
  1824. completeWire(makeFrame("conversation/session-desktop", "sub-collision")),
  1825. );
  1826. conversationFrames.fire(
  1827. completeWire(makeFrame("conversation/session-mobile", "sub-collision")),
  1828. );
  1829. expect(desktopSeen).toEqual(["conversation/session-desktop"]);
  1830. expect(mobileSeen).toEqual(["conversation/session-mobile"]);
  1831. });
  1832. it("被动 topic 清理保留 existing-only,runtime unavailable 后直接丢弃 attachment owner", async () => {
  1833. const { base } = setupBase();
  1834. const runtimeLifecycle = attachRuntimeLifecycle(base);
  1835. const scope = createZCodeAgentConnectionScope(base, {
  1836. connectionId: "desktop-passive-runtime",
  1837. clientMode: "desktop-continuous",
  1838. });
  1839. await scope.service.helloConversationV4();
  1840. await scope.service.initializeConversationV4({
  1841. kind: "clientHello",
  1842. protocolVersion: 3,
  1843. clientId: "desktop-passive-runtime-client",
  1844. appVersion: "4.0.0",
  1845. });
  1846. const target = { workspacePath: "/repo", workspaceIdentity: "ssh:repo" };
  1847. const first = await scope.service.subscribeSessionsIndexV4({
  1848. ...target,
  1849. runtimePolicy: "existing-only",
  1850. });
  1851. await scope.service.unsubscribeSessionsIndexV4({
  1852. ...target,
  1853. subscriptionId: first.ack.subscriptionId,
  1854. runtimePolicy: "existing-only",
  1855. });
  1856. expect(base.unsubscribeSessionsIndexV4).toHaveBeenLastCalledWith(
  1857. expect.objectContaining({ runtimePolicy: "existing-only" }),
  1858. );
  1859. const second = await scope.service.subscribeSessionsIndexV4({
  1860. ...target,
  1861. runtimePolicy: "existing-only",
  1862. });
  1863. runtimeLifecycle.fire(makeRuntimeLifecycleEvent(target, 1, "unavailable"));
  1864. await scope.service.unsubscribeSessionsIndexV4({
  1865. ...target,
  1866. subscriptionId: second.ack.subscriptionId,
  1867. runtimePolicy: "existing-only",
  1868. });
  1869. expect(base.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  1870. await scope.dispose();
  1871. runtimeLifecycle.dispose();
  1872. });
  1873. });
  1874. it("本地 TTFT 检查点只向本地 desktop continuous attachment 暴露", () => {
  1875. const { base } = setupBase();
  1876. const facts = new Emitter<import("@zcode/shared").LocalTtftFacts>();
  1877. base.onDynamicLocalTtftFacts = vi.fn(() => facts.event);
  1878. const desktop = createZCodeAgentConnectionScope(base, {
  1879. connectionId: "desktop",
  1880. clientMode: "desktop-continuous",
  1881. });
  1882. const mobile = createZCodeAgentConnectionScope(base, {
  1883. connectionId: "mobile",
  1884. clientMode: "web-remote-replayable",
  1885. });
  1886. const localSeen = vi.fn();
  1887. const remoteSeen = vi.fn();
  1888. const mobileSeen = vi.fn();
  1889. desktop.service.onDynamicLocalTtftFacts({ workspacePath: "/same" })(localSeen);
  1890. desktop.service.onDynamicLocalTtftFacts({
  1891. workspacePath: "/same",
  1892. workspaceIdentity: "ssh:remote",
  1893. remoteSessionId: "remote",
  1894. })(remoteSeen);
  1895. mobile.service.onDynamicLocalTtftFacts({ workspacePath: "/same" })(mobileSeen);
  1896. facts.fire({
  1897. version: 1,
  1898. observationId: "e0b15fc2-3a50-4d73-854d-61fa148cbfd0",
  1899. commandId: "input",
  1900. instanceId: "cli",
  1901. receivedAt: 100,
  1902. });
  1903. expect(localSeen).toHaveBeenCalledOnce();
  1904. expect(remoteSeen).not.toHaveBeenCalled();
  1905. expect(mobileSeen).not.toHaveBeenCalled();
  1906. expect(base.onDynamicLocalTtftFacts).toHaveBeenCalledOnce();
  1907. desktop.dispose();
  1908. mobile.dispose();
  1909. });