zcodeAgentConnectionScope.test.ts 76 KB

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