agentV4ConnectionTransports.test.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. import { LocalTtftObserver, setLocalTtftObserver } from "../src/v4/telemetry/localTtftObserver.js";
  2. import { Emitter } from "@zcode/rpc";
  3. import type {
  4. ConversationTopicFrame,
  5. ConversationTopicWireFrame,
  6. SessionsIndexTopicFrame,
  7. SessionsIndexTopicWireFrame,
  8. TopicFrameDeliveryKind,
  9. } from "@zcode/shared/zcode-protocol-v4";
  10. import {
  11. PROTOCOL_V4_LIMITS,
  12. TopicWireFrameAssembler,
  13. conversationTopicFrameSchema,
  14. encodeTopicWireFrames,
  15. utf8JsonByteLength,
  16. } from "@zcode/shared/zcode-protocol-v4";
  17. import { describe, expect, it, vi } from "vitest";
  18. import { createAgentConversationTransport } from "../src/v4/agentConversationTransport.js";
  19. import { createAgentSessionsIndexTransport } from "../src/v4/agentSessionsIndexTransport.js";
  20. import { ensureAgentV4ConnectionHandshake } from "../src/v4/agentV4ConnectionHandshake.js";
  21. import { createCommandEnvelope, getV4ClientId } from "../src/v4/commandFactory.js";
  22. import { createTopicWireDecoder } from "../src/v4/topicWireDecoder.js";
  23. import { logger } from "../src/logger.js";
  24. function setupAgent() {
  25. const conversationFrames = new Emitter<ConversationTopicWireFrame>();
  26. const sessionsIndexFrames = new Emitter<SessionsIndexTopicWireFrame>();
  27. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  28. return {
  29. helloConversationV4: vi.fn(async () => ({
  30. kind: "hello" as const,
  31. protocolVersion: 3 as const,
  32. connectionId: "host-rpc-1",
  33. clientMode: "desktop-continuous" as const,
  34. deliveryProfile: "continuous" as const,
  35. serverTime: 1,
  36. capabilities: {
  37. nativeDialogs: true,
  38. localTerminal: true,
  39. binaryFrames: false,
  40. compression: "none" as const,
  41. },
  42. auth: {},
  43. })),
  44. initializeConversationV4: vi.fn(async () => {}),
  45. subscribeConversationV4: vi.fn(async () => ({
  46. ack: {
  47. subscriptionId: "sub-conversation",
  48. mode: "snapshot" as const,
  49. logEpoch: "epoch-1",
  50. },
  51. })),
  52. unsubscribeConversationV4: vi.fn(async () => {}),
  53. resyncConversationV4: vi.fn(
  54. async (params: { subscriptionId: string; forceSnapshot?: boolean }) => ({
  55. ack: {
  56. subscriptionId: params.subscriptionId,
  57. mode: params.forceSnapshot ? ("snapshot" as const) : ("resume" as const),
  58. logEpoch: "epoch-1",
  59. },
  60. }),
  61. ),
  62. sendConversationCommandV4: vi.fn(async (params: { envelope: { commandId: string } }) => ({
  63. commandId: params.envelope.commandId,
  64. status: "accepted" as const,
  65. revisionAtDecision: 1,
  66. })),
  67. queryConversationCommandsV4: vi.fn(
  68. async (params: { commands: Array<{ commandId: string }> }) => ({
  69. results: params.commands.map((key) => ({ key, result: "unknown" as const })),
  70. }),
  71. ),
  72. conversationRowsRangeV4: vi.fn(),
  73. conversationPlansV4: vi.fn(),
  74. conversationFileChangesV4: vi.fn(),
  75. conversationFileRewindPreviewV4: vi.fn(),
  76. attachmentBeginV4: vi.fn(),
  77. attachmentChunkV4: vi.fn(),
  78. attachmentCommitV4: vi.fn(),
  79. attachmentAbortV4: vi.fn(),
  80. attachmentPreviewSourceV4: vi.fn(),
  81. attachmentReadV4: vi.fn(),
  82. onDynamicConversationFrame: vi.fn(() => conversationFrames.event),
  83. subscribeSessionsIndexV4: vi.fn(async () => ({
  84. ack: {
  85. subscriptionId: "sub-index",
  86. mode: "snapshot" as const,
  87. logEpoch: "epoch-1",
  88. },
  89. })),
  90. unsubscribeSessionsIndexV4: vi.fn(async () => {}),
  91. resyncSessionsIndexV4: vi.fn(
  92. async (params: { subscriptionId: string; forceSnapshot?: boolean }) => ({
  93. ack: {
  94. subscriptionId: params.subscriptionId,
  95. mode: params.forceSnapshot ? ("snapshot" as const) : ("resume" as const),
  96. logEpoch: "epoch-1",
  97. },
  98. }),
  99. ),
  100. onDynamicSessionsIndexFrame: vi.fn(() => sessionsIndexFrames.event),
  101. onAgentRuntimeRestarted: vi.fn((listener: (event: { workspaceKey: string }) => void) =>
  102. runtimeRestarts.event(listener),
  103. ),
  104. conversationFrames,
  105. sessionsIndexFrames,
  106. runtimeRestarts,
  107. };
  108. }
  109. it("Plan 请求不发给会剥掉 Plan 字段的旧 Host;普通请求仍兼容", async () => {
  110. const agent = setupAgent();
  111. const transport = createAgentConversationTransport(agent as never, { workspacePath: "/work" });
  112. const envelope = createCommandEnvelope({
  113. type: "sendText",
  114. sessionId: "session",
  115. payload: { text: "plan", mode: "yolo", planEnabled: true },
  116. });
  117. await expect(transport.sendCommand(envelope)).rejects.toThrow("proto.independentPlanUnsupported");
  118. expect(agent.sendConversationCommandV4).not.toHaveBeenCalled();
  119. await transport.sendCommand({
  120. ...envelope,
  121. payload: { text: "build", mode: "yolo", planEnabled: false },
  122. });
  123. expect(agent.sendConversationCommandV4).toHaveBeenCalledOnce();
  124. });
  125. function emptyFrame(topic: string, subscriptionId: string): ConversationTopicFrame {
  126. return {
  127. topic,
  128. subscriptionId,
  129. fromSeq: 0,
  130. toSeq: 0,
  131. sentAt: 1,
  132. payload: { kind: "deltas", deltas: [] },
  133. };
  134. }
  135. function completeConversationWire(
  136. frame: ConversationTopicFrame,
  137. logicalFrameId = "logical-conversation-complete",
  138. logicalFrameOrdinal = 1,
  139. deliveryKind: TopicFrameDeliveryKind = "online",
  140. ): ConversationTopicWireFrame {
  141. return {
  142. wireVersion: 3,
  143. kind: "complete",
  144. deliveryKind,
  145. logicalFrameId,
  146. logicalFrameOrdinal,
  147. topic: frame.topic,
  148. subscriptionId: frame.subscriptionId,
  149. frame,
  150. };
  151. }
  152. function completeSessionsIndexWire(
  153. frame: SessionsIndexTopicFrame,
  154. logicalFrameId = "logical-index-complete",
  155. logicalFrameOrdinal = 1,
  156. deliveryKind: TopicFrameDeliveryKind = "online",
  157. ): SessionsIndexTopicWireFrame {
  158. return {
  159. wireVersion: 3,
  160. kind: "complete",
  161. deliveryKind,
  162. logicalFrameId,
  163. logicalFrameOrdinal,
  164. topic: frame.topic,
  165. subscriptionId: frame.subscriptionId,
  166. frame,
  167. };
  168. }
  169. describe("agent V4 connection transports", () => {
  170. it("assembles sent media chunks and preserves the exact row attachment target", async () => {
  171. const agent = setupAgent();
  172. agent.attachmentReadV4
  173. .mockResolvedValueOnce({
  174. dataBase64: Buffer.from("abc").toString("base64"),
  175. mediaType: "video/quicktime",
  176. totalBytes: 5,
  177. nextOffset: 3,
  178. })
  179. .mockResolvedValueOnce({
  180. dataBase64: Buffer.from("de").toString("base64"),
  181. mediaType: "video/quicktime",
  182. totalBytes: 5,
  183. nextOffset: null,
  184. });
  185. const transport = createAgentConversationTransport(agent as never, {
  186. workspacePath: "/remote/work",
  187. workspaceIdentity: "ssh://host/remote/work",
  188. });
  189. await expect(
  190. transport.attachmentRead({
  191. sessionId: "session-video",
  192. ref: "/remote/work/demo.mov",
  193. target: { rowId: 42, entityId: "message-42" },
  194. attachmentIndex: 1,
  195. }),
  196. ).resolves.toEqual({
  197. bytes: new Uint8Array(Buffer.from("abcde")),
  198. mediaType: "video/quicktime",
  199. });
  200. expect(agent.attachmentReadV4).toHaveBeenNthCalledWith(
  201. 1,
  202. expect.objectContaining({
  203. workspacePath: "/remote/work",
  204. workspaceIdentity: "ssh://host/remote/work",
  205. sessionId: "session-video",
  206. ref: "/remote/work/demo.mov",
  207. target: { rowId: 42, entityId: "message-42" },
  208. attachmentIndex: 1,
  209. offset: 0,
  210. }),
  211. );
  212. expect(agent.attachmentReadV4).toHaveBeenNthCalledWith(
  213. 2,
  214. expect.objectContaining({
  215. target: { rowId: 42, entityId: "message-42" },
  216. attachmentIndex: 1,
  217. offset: 3,
  218. }),
  219. );
  220. });
  221. it("uses an authorized Desktop local video URL without requesting chunks", async () => {
  222. const agent = setupAgent();
  223. agent.attachmentPreviewSourceV4.mockResolvedValue({
  224. kind: "local_path",
  225. path: "/Users/test/.zcode/cli/video-cache/session/demo.mov",
  226. mediaType: "video/quicktime",
  227. });
  228. const createLocalMediaPreviewUrl = vi.fn(
  229. (path: string) => `zcode-media://local/${encodeURIComponent(path)}`,
  230. );
  231. const transport = createAgentConversationTransport(agent as never, {
  232. workspacePath: "/repo",
  233. createLocalMediaPreviewUrl,
  234. });
  235. await expect(
  236. transport.attachmentRead({
  237. sessionId: "session-video",
  238. ref: "/repo/demo.mov",
  239. mediaType: "video/quicktime",
  240. target: { rowId: 42, entityId: "message-42" },
  241. attachmentIndex: 1,
  242. }),
  243. ).resolves.toEqual({
  244. url: expect.stringMatching(/^zcode-media:\/\/local\//u),
  245. mediaType: "video/quicktime",
  246. });
  247. expect(agent.attachmentPreviewSourceV4).toHaveBeenCalledWith(
  248. expect.objectContaining({
  249. workspacePath: "/repo",
  250. sessionId: "session-video",
  251. target: { rowId: 42, entityId: "message-42" },
  252. attachmentIndex: 1,
  253. }),
  254. );
  255. expect(createLocalMediaPreviewUrl).toHaveBeenCalledWith(
  256. "/Users/test/.zcode/cli/video-cache/session/demo.mov",
  257. );
  258. expect(agent.attachmentReadV4).not.toHaveBeenCalled();
  259. });
  260. it("keeps remote and local-source fallback previews on the existing chunk path", async () => {
  261. const remoteAgent = setupAgent();
  262. remoteAgent.attachmentReadV4.mockResolvedValue({
  263. dataBase64: Buffer.from("remote").toString("base64"),
  264. mediaType: "video/mp4",
  265. totalBytes: 6,
  266. nextOffset: null,
  267. });
  268. const remoteTransport = createAgentConversationTransport(remoteAgent as never, {
  269. workspacePath: "/remote/work",
  270. });
  271. await expect(
  272. remoteTransport.attachmentRead({ sessionId: "remote", ref: "/remote/work/demo.mp4" }),
  273. ).resolves.toEqual({ bytes: new Uint8Array(Buffer.from("remote")), mediaType: "video/mp4" });
  274. expect(remoteAgent.attachmentPreviewSourceV4).not.toHaveBeenCalled();
  275. const localAgent = setupAgent();
  276. localAgent.attachmentPreviewSourceV4.mockResolvedValue({ kind: "chunked" });
  277. localAgent.attachmentReadV4.mockResolvedValue({
  278. dataBase64: Buffer.from("local").toString("base64"),
  279. mediaType: "video/mp4",
  280. totalBytes: 5,
  281. nextOffset: null,
  282. });
  283. const localTransport = createAgentConversationTransport(localAgent as never, {
  284. workspacePath: "/repo",
  285. createLocalMediaPreviewUrl: vi.fn(),
  286. });
  287. await expect(
  288. localTransport.attachmentRead({
  289. sessionId: "local",
  290. ref: "zcode-artifact://video",
  291. mediaType: "video/mp4",
  292. }),
  293. ).resolves.toEqual({ bytes: new Uint8Array(Buffer.from("local")), mediaType: "video/mp4" });
  294. expect(localAgent.attachmentPreviewSourceV4).toHaveBeenCalledOnce();
  295. expect(localAgent.attachmentReadV4).toHaveBeenCalledOnce();
  296. });
  297. it("keeps Desktop image previews on the existing chunk path", async () => {
  298. const agent = setupAgent();
  299. agent.attachmentReadV4.mockResolvedValue({
  300. dataBase64: Buffer.from("image").toString("base64"),
  301. mediaType: "image/png",
  302. totalBytes: 5,
  303. nextOffset: null,
  304. });
  305. const transport = createAgentConversationTransport(agent as never, {
  306. workspacePath: "/repo",
  307. createLocalMediaPreviewUrl: vi.fn(),
  308. });
  309. await expect(
  310. transport.attachmentRead({
  311. sessionId: "image",
  312. ref: "zcode-artifact://image",
  313. mediaType: "image/png",
  314. }),
  315. ).resolves.toEqual({ bytes: new Uint8Array(Buffer.from("image")), mediaType: "image/png" });
  316. expect(agent.attachmentPreviewSourceV4).not.toHaveBeenCalled();
  317. expect(agent.attachmentReadV4).toHaveBeenCalledOnce();
  318. });
  319. it("stops requesting sent media chunks after the caller aborts", async () => {
  320. const agent = setupAgent();
  321. const abortController = new AbortController();
  322. agent.attachmentReadV4
  323. .mockImplementationOnce(async () => {
  324. abortController.abort();
  325. return {
  326. dataBase64: Buffer.from("a").toString("base64"),
  327. mediaType: "video/mp4",
  328. totalBytes: 2,
  329. nextOffset: 1,
  330. };
  331. })
  332. .mockResolvedValueOnce({
  333. dataBase64: Buffer.from("b").toString("base64"),
  334. mediaType: "video/mp4",
  335. totalBytes: 2,
  336. nextOffset: null,
  337. });
  338. const transport = createAgentConversationTransport(agent as never, {
  339. workspacePath: "/remote/work",
  340. });
  341. await expect(
  342. transport.attachmentRead({
  343. sessionId: "session-aborted-video",
  344. ref: "zcode-artifact://aborted-video",
  345. signal: abortController.signal,
  346. }),
  347. ).rejects.toMatchObject({ name: "AbortError" });
  348. expect(agent.attachmentReadV4).toHaveBeenCalledOnce();
  349. });
  350. it("allows sent video preview to use more chunks than the upload byte limit", async () => {
  351. const agent = setupAgent();
  352. const uploadByteLimitChunks = Math.floor(
  353. PROTOCOL_V4_LIMITS.attachmentMaxBytes / PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  354. );
  355. const chunkCount = uploadByteLimitChunks + 2;
  356. expect(chunkCount).toBeLessThanOrEqual(PROTOCOL_V4_LIMITS.attachmentPreviewMaxChunks);
  357. for (let index = 0; index < chunkCount; index += 1) {
  358. agent.attachmentReadV4.mockResolvedValueOnce({
  359. dataBase64: Buffer.from("x").toString("base64"),
  360. mediaType: "video/mp4",
  361. totalBytes: chunkCount,
  362. nextOffset: index + 1 < chunkCount ? index + 1 : null,
  363. });
  364. }
  365. const transport = createAgentConversationTransport(agent as never, {
  366. workspacePath: "/remote/work",
  367. });
  368. await expect(
  369. transport.attachmentRead({
  370. sessionId: "session-large-video",
  371. ref: "zcode-artifact://large-video",
  372. }),
  373. ).resolves.toEqual({
  374. bytes: new Uint8Array(Buffer.alloc(chunkCount, "x")),
  375. mediaType: "video/mp4",
  376. });
  377. expect(agent.attachmentReadV4).toHaveBeenCalledTimes(chunkCount);
  378. });
  379. it("route A timeout 与 route B complete 同批时只 fail-close A,不误丢 B", () => {
  380. vi.useFakeTimers();
  381. vi.setSystemTime(0);
  382. try {
  383. const delivered: ConversationTopicFrame[] = [];
  384. const decoder = createTopicWireDecoder(
  385. new TopicWireFrameAssembler(conversationTopicFrameSchema),
  386. (frame) => delivered.push(frame),
  387. );
  388. const routeA: ConversationTopicFrame = {
  389. ...emptyFrame("conversation/session-a", "sub-a"),
  390. toSeq: 1,
  391. payload: {
  392. kind: "deltas",
  393. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "A".repeat(2_000) }],
  394. },
  395. };
  396. const routeAWires = encodeTopicWireFrames(routeA, {
  397. deliveryKind: "online",
  398. topic: routeA.topic,
  399. subscriptionId: routeA.subscriptionId,
  400. logicalFrameId: "logical-route-a-timeout",
  401. logicalFrameOrdinal: 1,
  402. maxPhysicalFrameBytes: 500,
  403. measurePhysicalFrameBytes: utf8JsonByteLength,
  404. }) as ConversationTopicWireFrame[];
  405. expect(routeAWires.length).toBeGreaterThan(1);
  406. decoder.accept(routeAWires[0]!);
  407. vi.setSystemTime(30_000);
  408. const routeB = emptyFrame("conversation/session-b", "sub-b");
  409. decoder.accept(completeConversationWire(routeB, "logical-route-b", 1));
  410. expect(delivered).toEqual([routeB]);
  411. decoder.clear();
  412. } finally {
  413. vi.useRealTimers();
  414. }
  415. });
  416. it("旧 online 残片恰在 recovery complete 同次 accept 超时时,权威 recovery 原子治愈", () => {
  417. vi.useFakeTimers();
  418. vi.setSystemTime(0);
  419. try {
  420. const topic = "conversation/session-timeout-heal";
  421. const subscriptionId = "sub-timeout-heal";
  422. const delivered: Array<{
  423. frame: ConversationTopicFrame;
  424. deliveryKind: TopicFrameDeliveryKind;
  425. }> = [];
  426. const faults: string[] = [];
  427. const decoder = createTopicWireDecoder(
  428. new TopicWireFrameAssembler(conversationTopicFrameSchema),
  429. (frame, deliveryKind) => delivered.push({ frame, deliveryKind }),
  430. (fault) => faults.push(fault.reasonCode),
  431. );
  432. const old = encodeTopicWireFrames(
  433. {
  434. ...emptyFrame(topic, subscriptionId),
  435. toSeq: 1,
  436. payload: {
  437. kind: "deltas",
  438. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "old".repeat(2_000) }],
  439. },
  440. },
  441. {
  442. deliveryKind: "online",
  443. topic,
  444. subscriptionId,
  445. logicalFrameId: "logical-timeout-online",
  446. logicalFrameOrdinal: 1,
  447. maxPhysicalFrameBytes: 500,
  448. measurePhysicalFrameBytes: utf8JsonByteLength,
  449. },
  450. ) as ConversationTopicWireFrame[];
  451. decoder.accept(old[0]!);
  452. vi.setSystemTime(30_000);
  453. const recovery = emptyFrame(topic, subscriptionId);
  454. decoder.accept(completeConversationWire(recovery, "logical-timeout-recovery", 2, "recovery"));
  455. expect(faults).toEqual([]);
  456. expect(delivered).toEqual([{ frame: recovery, deliveryKind: "recovery" }]);
  457. decoder.clear();
  458. } finally {
  459. vi.useRealTimers();
  460. }
  461. });
  462. it("旧 online 残片恰在 fragmented recovery 首片到达时超时,不丢 recovery 已收分片", () => {
  463. vi.useFakeTimers();
  464. vi.setSystemTime(0);
  465. try {
  466. const topic = "conversation/session-timeout-fragment-heal";
  467. const subscriptionId = "sub-timeout-fragment-heal";
  468. const delivered: ConversationTopicFrame[] = [];
  469. const faults: string[] = [];
  470. const decoder = createTopicWireDecoder(
  471. new TopicWireFrameAssembler(conversationTopicFrameSchema),
  472. (frame) => delivered.push(frame),
  473. (fault) => faults.push(fault.reasonCode),
  474. );
  475. const old = encodeTopicWireFrames(
  476. {
  477. ...emptyFrame(topic, subscriptionId),
  478. toSeq: 1,
  479. payload: {
  480. kind: "deltas",
  481. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "old".repeat(2_000) }],
  482. },
  483. },
  484. {
  485. deliveryKind: "online",
  486. topic,
  487. subscriptionId,
  488. logicalFrameId: "logical-timeout-online-fragment",
  489. logicalFrameOrdinal: 1,
  490. maxPhysicalFrameBytes: 500,
  491. measurePhysicalFrameBytes: utf8JsonByteLength,
  492. },
  493. ) as ConversationTopicWireFrame[];
  494. decoder.accept(old[0]!);
  495. const recovery: ConversationTopicFrame = {
  496. ...emptyFrame(topic, subscriptionId),
  497. payload: {
  498. kind: "deltas",
  499. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "recovery".repeat(2_000) }],
  500. },
  501. };
  502. const recoveryWires = encodeTopicWireFrames(recovery, {
  503. deliveryKind: "recovery",
  504. topic,
  505. subscriptionId,
  506. logicalFrameId: "logical-timeout-recovery-fragmented",
  507. logicalFrameOrdinal: 2,
  508. maxPhysicalFrameBytes: 500,
  509. measurePhysicalFrameBytes: utf8JsonByteLength,
  510. }) as ConversationTopicWireFrame[];
  511. expect(recoveryWires.length).toBeGreaterThan(1);
  512. vi.setSystemTime(30_000);
  513. for (const wire of recoveryWires) decoder.accept(wire);
  514. expect(faults).toEqual([]);
  515. expect(delivered).toEqual([recovery]);
  516. decoder.clear();
  517. } finally {
  518. vi.useRealTimers();
  519. }
  520. });
  521. it("assembly fault 后 same-sub recover 保留 ordinal tombstone 并接受更高 recovery frame", () => {
  522. const delivered: ConversationTopicFrame[] = [];
  523. const decoder = createTopicWireDecoder(
  524. new TopicWireFrameAssembler(conversationTopicFrameSchema),
  525. (frame) => delivered.push(frame),
  526. );
  527. const topic = "conversation/session-recover";
  528. const subscriptionId = "sub-recover";
  529. const partial = encodeTopicWireFrames(
  530. {
  531. ...emptyFrame(topic, subscriptionId),
  532. toSeq: 1,
  533. payload: {
  534. kind: "deltas",
  535. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "x".repeat(2_000) }],
  536. },
  537. },
  538. {
  539. deliveryKind: "online",
  540. topic,
  541. subscriptionId,
  542. logicalFrameId: "logical-faulted",
  543. logicalFrameOrdinal: 1,
  544. maxPhysicalFrameBytes: 500,
  545. measurePhysicalFrameBytes: utf8JsonByteLength,
  546. },
  547. ) as ConversationTopicWireFrame[];
  548. decoder.accept(partial[0]!);
  549. decoder.accept(
  550. completeConversationWire(
  551. { ...emptyFrame(topic, subscriptionId), fromSeq: 1, toSeq: 2 },
  552. "logical-supersede",
  553. 2,
  554. ),
  555. );
  556. expect(delivered).toEqual([]);
  557. decoder.recover(topic, subscriptionId);
  558. // fault ordinal tombstone 仍在,旧片不能复活;更高 recovery ordinal 可以原子进入。
  559. decoder.accept(partial[1]!);
  560. decoder.accept(
  561. completeConversationWire(
  562. emptyFrame(topic, subscriptionId),
  563. "logical-recovery",
  564. 3,
  565. "recovery",
  566. ),
  567. );
  568. expect(delivered).toEqual([emptyFrame(topic, subscriptionId)]);
  569. });
  570. it("resync RPC Promise continuation 前到达的更高 ordinal physical recovery 不被 fault 门吞掉", async () => {
  571. const agent = setupAgent();
  572. const transport = createAgentConversationTransport(agent as never, { workspacePath: "/repo" });
  573. const seen: Array<{ frame: ConversationTopicFrame; deliveryKind?: TopicFrameDeliveryKind }> =
  574. [];
  575. transport.onFrame((frame, context) => {
  576. seen.push({ frame, deliveryKind: context?.deliveryKind });
  577. });
  578. const subscribed = await transport.subscribe({ topic: "conversation/session-1" });
  579. transport.activate(subscribed.ack.subscriptionId);
  580. const old = encodeTopicWireFrames(
  581. {
  582. ...emptyFrame("conversation/session-1", subscribed.ack.subscriptionId),
  583. toSeq: 1,
  584. payload: {
  585. kind: "deltas",
  586. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "x".repeat(2_000) }],
  587. },
  588. },
  589. {
  590. deliveryKind: "online",
  591. topic: "conversation/session-1",
  592. subscriptionId: subscribed.ack.subscriptionId,
  593. logicalFrameId: "logical-old",
  594. logicalFrameOrdinal: 1,
  595. maxPhysicalFrameBytes: 500,
  596. measurePhysicalFrameBytes: utf8JsonByteLength,
  597. },
  598. ) as ConversationTopicWireFrame[];
  599. agent.conversationFrames.fire(old[0]!);
  600. agent.conversationFrames.fire(
  601. completeConversationWire(
  602. { ...emptyFrame("conversation/session-1", subscribed.ack.subscriptionId), toSeq: 2 },
  603. "logical-fault",
  604. 2,
  605. ),
  606. );
  607. expect(seen).toEqual([]);
  608. const recovery = emptyFrame("conversation/session-1", subscribed.ack.subscriptionId);
  609. const lateOnline = encodeTopicWireFrames(
  610. {
  611. ...recovery,
  612. toSeq: 3,
  613. payload: {
  614. kind: "deltas",
  615. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "late".repeat(2_000) }],
  616. },
  617. },
  618. {
  619. deliveryKind: "online",
  620. topic: recovery.topic,
  621. subscriptionId: recovery.subscriptionId,
  622. logicalFrameId: "logical-late-online-partial",
  623. logicalFrameOrdinal: 4,
  624. maxPhysicalFrameBytes: 500,
  625. measurePhysicalFrameBytes: utf8JsonByteLength,
  626. },
  627. ) as ConversationTopicWireFrame[];
  628. agent.resyncConversationV4.mockImplementationOnce(async (params) => {
  629. // 模拟 response 与 notification 同 read:request Promise continuation 尚未执行。
  630. // 迟到 online duplicate 不能消费 recovery 身份;真正 recovery 由信封证明。
  631. agent.conversationFrames.fire(
  632. completeConversationWire(recovery, "logical-stale-online", 3, "online"),
  633. );
  634. // in-flight resync 期间迟到 online 残片 fault 不得永久关掉 recovery gate。
  635. agent.conversationFrames.fire(lateOnline[0]!);
  636. agent.conversationFrames.fire(
  637. completeConversationWire({ ...recovery, toSeq: 4 }, "logical-online-fault", 5, "online"),
  638. );
  639. agent.conversationFrames.fire(
  640. completeConversationWire(recovery, "logical-recovery-early", 6, "recovery"),
  641. );
  642. return {
  643. ack: { subscriptionId: params.subscriptionId, mode: "resume", logEpoch: "epoch-1" },
  644. };
  645. });
  646. await transport.resync({
  647. subscriptionId: subscribed.ack.subscriptionId,
  648. base: { logEpoch: "epoch-1", seq: 0 },
  649. });
  650. expect(seen).toEqual([
  651. { frame: recovery, deliveryKind: "online" },
  652. { frame: recovery, deliveryKind: "recovery" },
  653. ]);
  654. });
  655. it("runtime restart 清 barrier/assembler,允许相同 subId 与 ordinal=1 的新 initial", async () => {
  656. const agent = setupAgent();
  657. const transport = createAgentConversationTransport(agent as never, {
  658. workspacePath: "/repo",
  659. });
  660. const seen: string[] = [];
  661. transport.onFrame((frame) => seen.push(String(frame.sentAt)));
  662. const restarted = vi.fn();
  663. transport.onRuntimeRestart(restarted);
  664. const first = await transport.subscribe({ topic: "conversation/session-1" });
  665. transport.activate(first.ack.subscriptionId);
  666. agent.conversationFrames.fire(
  667. completeConversationWire(
  668. { ...emptyFrame("conversation/session-1", first.ack.subscriptionId), sentAt: 1 },
  669. "logical-old-runtime",
  670. 1,
  671. ),
  672. );
  673. agent.runtimeRestarts.fire({ workspaceKey: "/repo" });
  674. expect(restarted).toHaveBeenCalledTimes(1);
  675. const second = await transport.subscribe({ topic: "conversation/session-1" });
  676. expect(second.ack.subscriptionId).toBe(first.ack.subscriptionId);
  677. transport.activate(second.ack.subscriptionId);
  678. agent.conversationFrames.fire(
  679. completeConversationWire(
  680. { ...emptyFrame("conversation/session-1", second.ack.subscriptionId), sentAt: 2 },
  681. "logical-new-runtime",
  682. 1,
  683. ),
  684. );
  685. expect(seen).toEqual(["1", "2"]);
  686. });
  687. it("记录生产包可见的订阅生命周期阶段,不记录消息内容", async () => {
  688. const agent = setupAgent();
  689. const info = vi.spyOn(logger.lifecycle, "info").mockImplementation(() => {});
  690. const warn = vi.spyOn(logger.lifecycle, "warn").mockImplementation(() => {});
  691. try {
  692. const transport = createAgentConversationTransport(agent as never, {
  693. workspacePath: "/repo",
  694. workspaceIdentity: "ssh:repo",
  695. });
  696. const subscribed = await transport.subscribe({ topic: "conversation/session-1" });
  697. transport.activate(subscribed.ack.subscriptionId);
  698. await transport.unsubscribe(subscribed.ack.subscriptionId);
  699. const events = info.mock.calls
  700. .map(([, context]) => (context as { event?: string } | undefined)?.event)
  701. .filter((event): event is string => Boolean(event));
  702. expect(events).toEqual(
  703. expect.arrayContaining([
  704. "v4.conversation.subscribe.started",
  705. "v4.conversation.subscribe.acknowledged",
  706. "v4.conversation.subscribe.activated",
  707. "v4.conversation.unsubscribe.started",
  708. "v4.conversation.unsubscribe.completed",
  709. ]),
  710. );
  711. expect(warn).not.toHaveBeenCalled();
  712. expect(info.mock.calls.flat().join(" ")).not.toContain("prompt");
  713. } finally {
  714. info.mockRestore();
  715. warn.mockRestore();
  716. }
  717. });
  718. it("同一 RPC service 只握手一次,subscribe 不透传 UI 自报 profile", async () => {
  719. const agent = setupAgent();
  720. const target = { workspacePath: "/repo", workspaceIdentity: "ssh:repo" };
  721. const conversation = createAgentConversationTransport(agent as never, target);
  722. const sessionsIndex = createAgentSessionsIndexTransport(agent as never, target);
  723. await Promise.all([
  724. conversation.subscribe({
  725. topic: "conversation/session-1",
  726. deliveryProfile: "replayable",
  727. } as never),
  728. sessionsIndex.subscribe({ visibility: "foreground" }),
  729. ]);
  730. expect(agent.initializeConversationV4).toHaveBeenCalledTimes(1);
  731. expect(agent.initializeConversationV4).toHaveBeenCalledWith(
  732. expect.objectContaining({
  733. kind: "clientHello",
  734. protocolVersion: 3,
  735. clientId: expect.any(String),
  736. }),
  737. );
  738. expect(agent.subscribeConversationV4).toHaveBeenCalledWith({
  739. ...target,
  740. sessionId: "session-1",
  741. });
  742. expect(agent.subscribeSessionsIndexV4).toHaveBeenCalledWith({
  743. ...target,
  744. runtimePolicy: "existing-only",
  745. visibility: "foreground",
  746. });
  747. });
  748. // `workflowRunDeltas` 的声明是单向的(shared transport.ts):clientHello 的 capabilities 是
  749. // `.strict()` 的,向一台没宣告这个位的旧 Host 发它 = 整条 clientHello 解析失败、连接握不上手。
  750. // 两条用例把「只在宣告之后才回声明」钉住,因为出错的代价不是降级而是会话打不开。
  751. it("Host 未宣告 workflowRunDeltas 时 clientHello 不带这个键", async () => {
  752. const agent = setupAgent();
  753. await ensureAgentV4ConnectionHandshake(agent as never);
  754. const clientHello = agent.initializeConversationV4.mock.calls[0]?.[0] as
  755. | { capabilities?: Record<string, unknown> }
  756. | undefined;
  757. expect(clientHello?.capabilities).toEqual({ workspaceHookReviewUi: true });
  758. });
  759. it("Host 宣告 workflowRunDeltas 后 clientHello 回声明,与既有 review 能力并存", async () => {
  760. const agent = setupAgent();
  761. const hello = await agent.helloConversationV4();
  762. agent.helloConversationV4.mockResolvedValue({
  763. ...hello,
  764. capabilities: { ...hello.capabilities, workflowRunDeltas: true },
  765. });
  766. await ensureAgentV4ConnectionHandshake(agent as never);
  767. const clientHello = agent.initializeConversationV4.mock.calls[0]?.[0] as
  768. | { capabilities?: Record<string, unknown> }
  769. | undefined;
  770. expect(clientHello?.capabilities).toEqual({
  771. workspaceHookReviewUi: true,
  772. workflowRunDeltas: true,
  773. });
  774. });
  775. it("非法 server hello 时不允许发送 subscribe", async () => {
  776. const agent = setupAgent();
  777. agent.helloConversationV4.mockResolvedValueOnce({
  778. ...(await agent.helloConversationV4()),
  779. deliveryProfile: "replayable",
  780. });
  781. agent.helloConversationV4.mockClear();
  782. const transport = createAgentConversationTransport(agent as never, {
  783. workspacePath: "/repo",
  784. });
  785. await expect(transport.subscribe({ topic: "conversation/session-1" })).rejects.toThrow();
  786. expect(agent.subscribeConversationV4).not.toHaveBeenCalled();
  787. });
  788. it("conversation transport 在 subscribe ACK 前暂存通知,显式 activate 后恰好释放一次", async () => {
  789. const agent = setupAgent();
  790. let resolveSubscribe!: (value: {
  791. ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string };
  792. }) => void;
  793. agent.subscribeConversationV4.mockImplementationOnce(
  794. () => new Promise((resolve) => (resolveSubscribe = resolve)),
  795. );
  796. const transport = createAgentConversationTransport(agent as never, {
  797. workspacePath: "/repo",
  798. });
  799. const seen: string[] = [];
  800. transport.onFrame((frame) => seen.push(frame.subscriptionId));
  801. const subscribing = transport.subscribe({ topic: "conversation/session-1" });
  802. await vi.waitFor(() => expect(agent.subscribeConversationV4).toHaveBeenCalledTimes(1));
  803. agent.conversationFrames.fire(
  804. completeConversationWire(emptyFrame("conversation/session-1", "sub-conversation-early")),
  805. );
  806. expect(seen).toEqual([]);
  807. resolveSubscribe({
  808. ack: {
  809. subscriptionId: "sub-conversation-early",
  810. mode: "snapshot",
  811. logEpoch: "epoch-1",
  812. },
  813. });
  814. const result = await subscribing;
  815. expect(seen).toEqual([]);
  816. const activatable = transport as typeof transport & {
  817. activate(subscriptionId: string): void;
  818. };
  819. expect(typeof activatable.activate).toBe("function");
  820. activatable.activate(result.ack.subscriptionId);
  821. activatable.activate(result.ack.subscriptionId);
  822. expect(seen).toEqual(["sub-conversation-early"]);
  823. });
  824. it("sessions-index transport 在 subscribe ACK 前暂存通知,显式 activate 后恰好释放一次", async () => {
  825. const agent = setupAgent();
  826. let resolveSubscribe!: (value: {
  827. ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string };
  828. }) => void;
  829. agent.subscribeSessionsIndexV4.mockImplementationOnce(
  830. () => new Promise((resolve) => (resolveSubscribe = resolve)),
  831. );
  832. const transport = createAgentSessionsIndexTransport(agent as never, {
  833. workspacePath: "/repo",
  834. });
  835. const seen: string[] = [];
  836. transport.onFrame((frame) => seen.push(frame.subscriptionId));
  837. const subscribing = transport.subscribe({});
  838. await vi.waitFor(() => expect(agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  839. agent.sessionsIndexFrames.fire(
  840. completeSessionsIndexWire({
  841. ...emptyFrame("sessions-index//repo", "sub-index-early"),
  842. payload: {
  843. kind: "deltas",
  844. deltas: [],
  845. },
  846. } as SessionsIndexTopicFrame),
  847. );
  848. expect(seen).toEqual([]);
  849. resolveSubscribe({
  850. ack: {
  851. subscriptionId: "sub-index-early",
  852. mode: "snapshot",
  853. logEpoch: "epoch-1",
  854. },
  855. });
  856. const result = await subscribing;
  857. expect(seen).toEqual([]);
  858. const activatable = transport as typeof transport & {
  859. activate(subscriptionId: string): void;
  860. };
  861. expect(typeof activatable.activate).toBe("function");
  862. activatable.activate(result.ack.subscriptionId);
  863. activatable.activate(result.ack.subscriptionId);
  864. expect(seen).toEqual(["sub-index-early"]);
  865. });
  866. it("conversation physical 分片只在最后一片后原子交付 logical frame", async () => {
  867. const agent = setupAgent();
  868. const transport = createAgentConversationTransport(agent as never, {
  869. workspacePath: "/repo",
  870. });
  871. const seen: ConversationTopicFrame[] = [];
  872. transport.onFrame((frame) => seen.push(frame));
  873. const result = await transport.subscribe({ topic: "conversation/session-1" });
  874. transport.activate(result.ack.subscriptionId);
  875. const append = "中文🙂".repeat(400);
  876. const logical: ConversationTopicFrame = {
  877. topic: "conversation/session-1",
  878. subscriptionId: result.ack.subscriptionId,
  879. fromSeq: 0,
  880. toSeq: 1,
  881. sentAt: 1,
  882. payload: {
  883. kind: "deltas",
  884. deltas: [{ op: "row.delta", rowId: 1, path: "text", append }],
  885. },
  886. };
  887. const wires = encodeTopicWireFrames(logical, {
  888. deliveryKind: "initial",
  889. topic: logical.topic,
  890. subscriptionId: logical.subscriptionId,
  891. logicalFrameId: "logical-conversation-fragmented",
  892. logicalFrameOrdinal: 1,
  893. maxPhysicalFrameBytes: 500,
  894. measurePhysicalFrameBytes: utf8JsonByteLength,
  895. }) as ConversationTopicWireFrame[];
  896. expect(wires.length).toBeGreaterThan(2);
  897. for (const wire of wires.slice(0, -1)) agent.conversationFrames.fire(wire);
  898. expect(seen).toEqual([]);
  899. agent.conversationFrames.fire(wires.at(-1)!);
  900. expect(seen).toHaveLength(1);
  901. expect(seen[0]).toEqual(logical);
  902. });
  903. it("conversation 同批 superseded fault + newer complete 时 fail closed 不交付", async () => {
  904. const agent = setupAgent();
  905. const transport = createAgentConversationTransport(agent as never, {
  906. workspacePath: "/repo",
  907. });
  908. const seen: ConversationTopicFrame[] = [];
  909. transport.onFrame((frame) => seen.push(frame));
  910. const result = await transport.subscribe({ topic: "conversation/session-1" });
  911. transport.activate(result.ack.subscriptionId);
  912. const old: ConversationTopicFrame = {
  913. ...emptyFrame("conversation/session-1", result.ack.subscriptionId),
  914. toSeq: 1,
  915. payload: {
  916. kind: "deltas",
  917. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: "old".repeat(500) }],
  918. },
  919. };
  920. const oldWires = encodeTopicWireFrames(old, {
  921. deliveryKind: "online",
  922. topic: old.topic,
  923. subscriptionId: old.subscriptionId,
  924. logicalFrameId: "logical-old-partial",
  925. logicalFrameOrdinal: 1,
  926. maxPhysicalFrameBytes: 500,
  927. measurePhysicalFrameBytes: utf8JsonByteLength,
  928. }) as ConversationTopicWireFrame[];
  929. expect(oldWires.length).toBeGreaterThan(1);
  930. agent.conversationFrames.fire(oldWires[0]!);
  931. const newer: ConversationTopicFrame = {
  932. ...emptyFrame("conversation/session-1", result.ack.subscriptionId),
  933. fromSeq: 1,
  934. toSeq: 2,
  935. };
  936. agent.conversationFrames.fire(completeConversationWire(newer, "logical-newer", 2));
  937. expect(seen).toEqual([]);
  938. });
  939. it("sessions-index physical 分片只在最后一片后原子交付 logical frame", async () => {
  940. const agent = setupAgent();
  941. const transport = createAgentSessionsIndexTransport(agent as never, {
  942. workspacePath: "/repo",
  943. });
  944. const seen: SessionsIndexTopicFrame[] = [];
  945. transport.onFrame((frame) => seen.push(frame));
  946. const result = await transport.subscribe({});
  947. transport.activate(result.ack.subscriptionId);
  948. const logical: SessionsIndexTopicFrame = {
  949. topic: "sessions-index//repo",
  950. subscriptionId: result.ack.subscriptionId,
  951. fromSeq: 0,
  952. toSeq: 1,
  953. sentAt: 1,
  954. payload: {
  955. kind: "deltas",
  956. deltas: [
  957. {
  958. op: "session.upserted",
  959. session: {
  960. sessionId: "session-1",
  961. workspaceId: "/repo",
  962. title: "中文🙂".repeat(400),
  963. phase: "completedSuccess",
  964. sessionEnded: true,
  965. hasBackgroundWork: false,
  966. lastActivityAt: 1,
  967. createdAt: 1,
  968. },
  969. },
  970. ],
  971. },
  972. };
  973. const wires = encodeTopicWireFrames(logical, {
  974. deliveryKind: "initial",
  975. topic: logical.topic,
  976. subscriptionId: logical.subscriptionId,
  977. logicalFrameId: "logical-index-fragmented",
  978. logicalFrameOrdinal: 1,
  979. maxPhysicalFrameBytes: 500,
  980. measurePhysicalFrameBytes: utf8JsonByteLength,
  981. }) as SessionsIndexTopicWireFrame[];
  982. expect(wires.length).toBeGreaterThan(2);
  983. for (const wire of wires.slice(0, -1)) agent.sessionsIndexFrames.fire(wire);
  984. expect(seen).toEqual([]);
  985. agent.sessionsIndexFrames.fire(wires.at(-1)!);
  986. expect(seen).toEqual([logical]);
  987. });
  988. it("subscribe ACK 前物理 staging 第 1025 帧整批失败,不丢头部继续激活", async () => {
  989. const agent = setupAgent();
  990. let resolveSubscribe!: (value: {
  991. ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string };
  992. }) => void;
  993. agent.subscribeConversationV4.mockImplementationOnce(
  994. () => new Promise((resolve) => (resolveSubscribe = resolve)),
  995. );
  996. const transport = createAgentConversationTransport(agent as never, {
  997. workspacePath: "/repo",
  998. });
  999. const seen: ConversationTopicFrame[] = [];
  1000. transport.onFrame((frame) => seen.push(frame));
  1001. const subscribing = transport.subscribe({ topic: "conversation/session-1" });
  1002. await vi.waitFor(() => expect(agent.subscribeConversationV4).toHaveBeenCalledTimes(1));
  1003. for (let index = 0; index < 1025; index += 1) {
  1004. agent.conversationFrames.fire(
  1005. completeConversationWire(
  1006. emptyFrame("conversation/session-1", "sub-conversation-overflow"),
  1007. `logical-overflow-${index}`,
  1008. ),
  1009. );
  1010. }
  1011. resolveSubscribe({
  1012. ack: {
  1013. subscriptionId: "sub-conversation-overflow",
  1014. mode: "snapshot",
  1015. logEpoch: "epoch-1",
  1016. },
  1017. });
  1018. await expect(subscribing).rejects.toThrow("fault.subscription.initialFrameStagingOverflow");
  1019. expect(seen).toEqual([]);
  1020. expect(agent.unsubscribeConversationV4).toHaveBeenCalledWith({
  1021. workspacePath: "/repo",
  1022. subscriptionId: "sub-conversation-overflow",
  1023. });
  1024. });
  1025. it("UI handshake 与 commandFactory 复用同一个稳定 clientId", async () => {
  1026. const agent = setupAgent();
  1027. const transport = createAgentConversationTransport(agent as never, {
  1028. workspacePath: "/repo",
  1029. });
  1030. const envelope = createCommandEnvelope({
  1031. type: "sendText",
  1032. sessionId: "session-1",
  1033. payload: { text: "hello" },
  1034. });
  1035. await expect(transport.sendCommand(envelope)).resolves.toMatchObject({
  1036. commandId: envelope.commandId,
  1037. status: "accepted",
  1038. });
  1039. expect(envelope.clientId).toBe(getV4ClientId());
  1040. expect(agent.initializeConversationV4).toHaveBeenCalledWith(
  1041. expect.objectContaining({ clientId: envelope.clientId }),
  1042. );
  1043. });
  1044. it("commands/query 先完成 handshake,并保留 workspaceIdentity 与 key 顺序", async () => {
  1045. const agent = setupAgent();
  1046. const transport = createAgentConversationTransport(agent as never, {
  1047. workspacePath: "/repo",
  1048. workspaceIdentity: "remote:ssh:host:/repo",
  1049. });
  1050. const commands = [
  1051. { sessionId: "session-1", commandId: "command-1" },
  1052. { sessionId: null, commandId: "create-command" },
  1053. ];
  1054. await expect(transport.queryCommands({ commands })).resolves.toEqual({
  1055. results: commands.map((key) => ({ key, result: "unknown" })),
  1056. });
  1057. expect(agent.initializeConversationV4).toHaveBeenCalledTimes(1);
  1058. expect(agent.queryConversationCommandsV4).toHaveBeenCalledWith({
  1059. workspacePath: "/repo",
  1060. workspaceIdentity: "remote:ssh:host:/repo",
  1061. commands,
  1062. });
  1063. });
  1064. it("plans query 通过同一 shared-host 身份路由转发", async () => {
  1065. const agent = setupAgent();
  1066. agent.conversationPlansV4.mockResolvedValue({
  1067. plans: [],
  1068. atSeq: 12,
  1069. atLogEpoch: "epoch-1",
  1070. });
  1071. const transport = createAgentConversationTransport(agent as never, {
  1072. workspacePath: "/repo",
  1073. workspaceIdentity: "remote:ssh:host:/repo",
  1074. });
  1075. await expect(transport.plans({ sessionId: "session-1" })).resolves.toEqual({
  1076. plans: [],
  1077. atSeq: 12,
  1078. atLogEpoch: "epoch-1",
  1079. });
  1080. expect(agent.initializeConversationV4).toHaveBeenCalledTimes(1);
  1081. expect(agent.conversationPlansV4).toHaveBeenCalledWith({
  1082. workspacePath: "/repo",
  1083. workspaceIdentity: "remote:ssh:host:/repo",
  1084. sessionId: "session-1",
  1085. });
  1086. });
  1087. });
  1088. it("runtime unavailable 结束对应 workspace 的 TTFT,保留其他 workspace", () => {
  1089. const agent = setupAgent();
  1090. const lifecycle = new Emitter<{ workspaceKey: string; state: "available" | "unavailable" }>();
  1091. const service = {
  1092. ...agent,
  1093. onDynamicLocalTtftFacts: () => new Emitter<import("@zcode/shared").LocalTtftFacts>().event,
  1094. onAgentRuntimeLifecycle: (
  1095. listener: (event: { workspaceKey: string; state: "available" | "unavailable" }) => void,
  1096. ) => lifecycle.event(listener),
  1097. };
  1098. const records: import("@zcode/shared").LocalTtftRecord[] = [];
  1099. const observer = new LocalTtftObserver((record) => records.push(record));
  1100. observer.enabled = true;
  1101. setLocalTtftObserver(observer);
  1102. const a = observer.start("/a", false)!;
  1103. observer.start("/b", false);
  1104. const transport = createAgentConversationTransport(service, { workspacePath: "/a" });
  1105. const off = transport.onRuntimeLifecycle!(() => {});
  1106. try {
  1107. lifecycle.fire({ workspaceKey: "/b", state: "unavailable" });
  1108. expect(records.filter((record) => record.kind === "excluded")).toHaveLength(0);
  1109. lifecycle.fire({ workspaceKey: "/a", state: "unavailable" });
  1110. expect(records.filter((record) => record.kind === "excluded")).toMatchObject([
  1111. { observationId: a.observationId, outcome: "interrupted" },
  1112. ]);
  1113. } finally {
  1114. off();
  1115. setLocalTtftObserver(undefined);
  1116. }
  1117. });
  1118. it("校准过期后收到 CLI 检查点或内容帧会重新探测时钟,有效期内不重复", async () => {
  1119. const agent = setupAgent();
  1120. const facts = new Emitter<import("@zcode/shared").LocalTtftFacts>();
  1121. const service = { ...agent, onDynamicLocalTtftFacts: () => facts.event };
  1122. let now = 100_000;
  1123. const observer = new LocalTtftObserver(
  1124. () => {},
  1125. () => now,
  1126. () => now,
  1127. );
  1128. observer.enabled = true;
  1129. setLocalTtftObserver(observer);
  1130. const context = observer.start("/a", true)!;
  1131. observer.dispatch(context, "/a", "c", "s");
  1132. // 发送时已校准;排队等待期间没有任何传输调用,旧逻辑不会再刷新校准。
  1133. observer.calibrate("/a", { instanceId: "cli", offsetMs: 0, errorMs: 1, measuredAt: now });
  1134. const transport = createAgentConversationTransport(service, { workspacePath: "/a" });
  1135. const off = transport.onFrame(() => {});
  1136. const clockProbes = () =>
  1137. agent.queryConversationCommandsV4.mock.calls.filter(
  1138. ([params]) => (params as { clock?: true }).clock === true,
  1139. ).length;
  1140. try {
  1141. const checkpoint = {
  1142. ...context,
  1143. instanceId: "cli",
  1144. commandId: "c",
  1145. sessionId: "s",
  1146. receivedAt: 100_000,
  1147. admittedAt: 100_010,
  1148. };
  1149. facts.fire(checkpoint);
  1150. expect(clockProbes()).toBe(0);
  1151. now += 61_000;
  1152. facts.fire({ ...checkpoint, executionAt: now });
  1153. await Promise.resolve();
  1154. expect(clockProbes()).toBe(1);
  1155. // 同一在途探测未返回前,再多检查点也只保留一次探测。
  1156. facts.fire({ ...checkpoint, executionAt: now, requestAt: now + 1 });
  1157. expect(clockProbes()).toBe(1);
  1158. } finally {
  1159. off();
  1160. setLocalTtftObserver(undefined);
  1161. }
  1162. });