topic-resource-port.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import type { TraceContext } from "@zcode/contracts";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { zcodeProtocolMethods, zcodeProtocolMessageSchema } from "@zcode/shared";
  4. import { createProtocolTopicResourcePort } from "../src/zcode-protocol/topic-resource-port.js";
  5. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  6. const request = {
  7. taskId: "task-a",
  8. inputId: "input-a",
  9. authorizationId: "auth-a",
  10. messageId: "file-a",
  11. resourceIndex: 0,
  12. };
  13. describe("topic resource protocol port", () => {
  14. it("sends a strict channel reply and trace through the existing Host reverse port", async () => {
  15. const requestClient = vi.fn(async (method, params, _schema, options) => {
  16. expect(
  17. zcodeProtocolMessageSchema.parse({ id: "reply-1", method, params, trace: options.trace }),
  18. ).toMatchObject({
  19. method: zcodeProtocolMethods.channelReply,
  20. trace: { traceId: "trace-reply" },
  21. });
  22. return { status: "unknown", deliveryId: "reply-delivery" };
  23. });
  24. const port = createProtocolTopicResourcePort({
  25. requestClient,
  26. } as unknown as ZCodeProtocolAgentServerContext);
  27. const controller = new AbortController();
  28. expect(
  29. await port.reply!(
  30. {
  31. taskId: "task-a",
  32. inputId: "input-a",
  33. toolCallId: "call-a",
  34. parts: [{ type: "mention", refId: "m1" }],
  35. },
  36. { signal: controller.signal, trace: { traceId: "trace-reply" } as TraceContext },
  37. ),
  38. ).toEqual({ status: "unknown", deliveryId: "reply-delivery" });
  39. controller.abort();
  40. await expect(
  41. port.reply!(
  42. {
  43. taskId: "task-a",
  44. inputId: "input-a",
  45. toolCallId: "call-b",
  46. parts: [{ type: "text", text: "hello" }],
  47. },
  48. { signal: controller.signal },
  49. ),
  50. ).rejects.toThrow();
  51. expect(requestClient).toHaveBeenCalledTimes(1);
  52. });
  53. it("propagates source identity and cancellation using the same request id", async () => {
  54. let finish!: (value: unknown) => void;
  55. const requestClient = vi.fn(
  56. (method: string, _params?: Record<string, unknown>, _schema?: unknown, _options?: unknown) =>
  57. method === zcodeProtocolMethods.topicResourceRead
  58. ? new Promise((resolve) => {
  59. finish = resolve;
  60. })
  61. : Promise.resolve({ cancelled: true }),
  62. );
  63. const port = createProtocolTopicResourcePort({
  64. requestClient,
  65. } as unknown as ZCodeProtocolAgentServerContext);
  66. const controller = new AbortController();
  67. const pending = port.read(request, { signal: controller.signal });
  68. controller.abort();
  69. const readParams = requestClient.mock.calls[0]![1]!;
  70. expect(readParams).toMatchObject(request);
  71. expect(requestClient.mock.calls[1]).toEqual(
  72. expect.arrayContaining([
  73. zcodeProtocolMethods.topicResourceCancel,
  74. { requestId: readParams.requestId, taskId: "task-a" },
  75. ]),
  76. );
  77. finish({ ref: "artifact://a", fileName: "a.txt", mime: "text/plain", bytes: 0 });
  78. await expect(pending).rejects.toThrow();
  79. });
  80. it("maps runtime trace into valid strict wire frames for reads and cancellation", async () => {
  81. let finish: ((value: unknown) => void) | undefined;
  82. const frames: unknown[] = [];
  83. const requestClient = vi.fn(
  84. (method: string, params: unknown, _schema: unknown, options: { trace?: unknown }) => {
  85. const frame = { id: "server-1", method, params, trace: options.trace };
  86. frames.push(frame);
  87. zcodeProtocolMessageSchema.parse(frame);
  88. return method === zcodeProtocolMethods.topicResourceRead
  89. ? new Promise((resolve) => {
  90. finish = resolve;
  91. })
  92. : Promise.resolve({ cancelled: true });
  93. },
  94. );
  95. const port = createProtocolTopicResourcePort({
  96. requestClient,
  97. } as unknown as ZCodeProtocolAgentServerContext);
  98. const controller = new AbortController();
  99. const trace = {
  100. traceId: "trace-a",
  101. spanId: "span-a",
  102. parentSpanId: "parent-a",
  103. sessionId: "sess_a",
  104. turnId: "turn-a",
  105. queryId: "query-a",
  106. attributes: { source: "bot" },
  107. } as TraceContext;
  108. const pending = port.read(request, { signal: controller.signal, trace });
  109. await Promise.resolve();
  110. if (finish) {
  111. controller.abort();
  112. finish({ ref: "artifact://a", fileName: "a.txt", mime: "text/plain", bytes: 0 });
  113. }
  114. await expect(pending).rejects.toThrow();
  115. expect(frames).toHaveLength(2);
  116. for (const frame of frames)
  117. expect(zcodeProtocolMessageSchema.parse(frame)).toMatchObject({
  118. trace: { traceId: "trace-a", spanId: "span-a", parentId: "parent-a" },
  119. });
  120. });
  121. it("contains synchronous disconnect errors from cancellation notification", async () => {
  122. let finish!: (value: unknown) => void;
  123. const requestClient = vi.fn((method: string) => {
  124. if (method === zcodeProtocolMethods.topicResourceCancel)
  125. throw new Error("Client already disconnected");
  126. return new Promise((resolve) => {
  127. finish = resolve;
  128. });
  129. });
  130. const controller = new AbortController();
  131. const listen = vi.spyOn(controller.signal, "addEventListener");
  132. const port = createProtocolTopicResourcePort({
  133. requestClient,
  134. } as unknown as ZCodeProtocolAgentServerContext);
  135. const pending = port.read(request, { signal: controller.signal });
  136. const cancel = listen.mock.calls[0]![1] as EventListener;
  137. // 直接调用实际 listener,以免旧实现的同步异常被 Node 转为全局 uncaughtException。
  138. controller.signal.removeEventListener("abort", cancel);
  139. controller.abort();
  140. expect(() => cancel.call(controller.signal, new Event("abort"))).not.toThrow();
  141. finish({ ref: "artifact://a", fileName: "a.txt", mime: "text/plain", bytes: 0 });
  142. await expect(pending).rejects.toThrow();
  143. expect(requestClient).toHaveBeenCalledTimes(2);
  144. });
  145. it("does not turn unsupported hosts into a URL fallback", async () => {
  146. const requestClient = vi.fn(async () => {
  147. throw new Error("Method not found");
  148. });
  149. const port = createProtocolTopicResourcePort({
  150. requestClient,
  151. } as unknown as ZCodeProtocolAgentServerContext);
  152. await expect(port.read(request, { signal: new AbortController().signal })).rejects.toThrow(
  153. "Method not found",
  154. );
  155. expect(requestClient).toHaveBeenCalledOnce();
  156. });
  157. });