zcodeSessionContentProfile.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. deriveZCodeTaskStatusFromSessionSnapshot,
  4. elideSessionSnapshotForIndex,
  5. getConversationMessageProjectionPolicy,
  6. getZCodeUserVisibleMessages,
  7. resolveZCodeVisibleSessionTitle,
  8. zcodeMessageWithPartsSchema,
  9. zcodeSessionReadParamsSchema,
  10. type ZCodeMessageWithParts,
  11. type ZCodeSessionStateSnapshot,
  12. } from "../src/index.js";
  13. const SESSION_ID = "sess_idx";
  14. const model = { providerId: "glm", modelId: "glm-4.6" };
  15. const BIG = "x".repeat(2 * 1024 * 1024);
  16. function user(
  17. messageId: string,
  18. created: number,
  19. parts: ZCodeMessageWithParts["parts"],
  20. patch: Record<string, unknown> = {},
  21. ): ZCodeMessageWithParts {
  22. return {
  23. info: {
  24. messageId,
  25. sessionId: SESSION_ID,
  26. role: "user",
  27. time: { created },
  28. agent: "build",
  29. model,
  30. ...patch,
  31. },
  32. parts,
  33. } as ZCodeMessageWithParts;
  34. }
  35. function assistant(
  36. messageId: string,
  37. created: number,
  38. parts: ZCodeMessageWithParts["parts"],
  39. patch: Record<string, unknown> = {},
  40. ): ZCodeMessageWithParts {
  41. return {
  42. info: {
  43. messageId,
  44. sessionId: SESSION_ID,
  45. role: "assistant",
  46. time: { created, completed: created + 1 },
  47. parentMessageId: "m_u1",
  48. agent: "build",
  49. model,
  50. path: { cwd: "/repo", root: "/repo" },
  51. cost: 0,
  52. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  53. finish: "stop",
  54. ...patch,
  55. },
  56. parts,
  57. } as ZCodeMessageWithParts;
  58. }
  59. function base(messageId: string, partId: string) {
  60. return { partId, sessionId: SESSION_ID, messageId };
  61. }
  62. /** 覆盖 task index 所有判定分支会看的 part 类型与 metadata 形态。 */
  63. function fixtureMessages(): ZCodeMessageWithParts[] {
  64. return [
  65. user("m_u1", 10, [
  66. { ...base("m_u1", "p1"), type: "text", text: "帮我实现订单查询" },
  67. {
  68. ...base("m_u1", "p2"),
  69. type: "file",
  70. mime: "image/png",
  71. url: `data:image/png;base64,${BIG}`,
  72. },
  73. ]),
  74. assistant("m_a1", 20, [
  75. { ...base("m_a1", "p3"), type: "step-start", snapshot: "abc123" },
  76. { ...base("m_a1", "p4"), type: "reasoning", text: BIG },
  77. {
  78. ...base("m_a1", "p5"),
  79. type: "tool",
  80. callId: "call_1",
  81. tool: "bash",
  82. state: {
  83. status: "completed",
  84. input: { command: "cat big.log", content: BIG },
  85. output: BIG,
  86. title: "cat big.log",
  87. metadata: { output: BIG, exit: 0 },
  88. startedAt: 21,
  89. completedAt: 22,
  90. },
  91. metadata: { source: "tool-source-marker" },
  92. },
  93. {
  94. ...base("m_a1", "p6"),
  95. type: "tool",
  96. callId: "call_2",
  97. tool: "write",
  98. state: {
  99. status: "error",
  100. input: { content: BIG },
  101. error: BIG,
  102. startedAt: 23,
  103. completedAt: 24,
  104. },
  105. },
  106. {
  107. ...base("m_a1", "p7"),
  108. type: "tool",
  109. callId: "call_3",
  110. tool: "read",
  111. state: { status: "pending", input: { path: "a" }, raw: BIG },
  112. },
  113. {
  114. ...base("m_a1", "p8"),
  115. type: "tool",
  116. callId: "call_4",
  117. tool: "bash",
  118. state: {
  119. status: "running",
  120. input: { command: BIG },
  121. startedAt: 25,
  122. metadata: { output: BIG },
  123. },
  124. },
  125. { ...base("m_a1", "p9"), type: "text", text: "订单查询在 orderService 里" },
  126. ]),
  127. // compact summary(compaction 无 timelineStatus)必须仍被识别为不可见。
  128. user("m_u2", 30, [
  129. { ...base("m_u2", "p10"), type: "compaction", auto: true },
  130. { ...base("m_u2", "p11"), type: "text", text: "summary of history" },
  131. ]),
  132. // model-only tool part metadata 让整条消息变成 providerContextOnly。
  133. user("m_u3", 40, [
  134. {
  135. ...base("m_u3", "p12"),
  136. type: "tool",
  137. callId: "call_5",
  138. tool: "bash",
  139. state: {
  140. status: "completed",
  141. input: { command: BIG },
  142. output: BIG,
  143. title: "t",
  144. metadata: {},
  145. startedAt: 41,
  146. completedAt: 42,
  147. },
  148. metadata: { visibility: "model-only" },
  149. },
  150. { ...base("m_u3", "p13"), type: "text", text: "hidden context" },
  151. ]),
  152. user("m_u4", 50, [
  153. {
  154. ...base("m_u4", "p14"),
  155. type: "text",
  156. text: '<system-reminder source="goal-continuation">Continue working toward the active session goal.',
  157. },
  158. ]),
  159. assistant("m_a2", 60, [
  160. {
  161. ...base("m_a2", "p15"),
  162. type: "timeline",
  163. timelineType: "context_compaction",
  164. display: "separator",
  165. status: "completed",
  166. },
  167. {
  168. ...base("m_a2", "p16"),
  169. type: "subagent",
  170. prompt: "explore",
  171. description: "探索",
  172. agent: "explore",
  173. },
  174. { ...base("m_a2", "p17"), type: "text", text: "最后一段回复" },
  175. ]),
  176. ];
  177. }
  178. function fixtureSnapshot(): ZCodeSessionStateSnapshot {
  179. return {
  180. session: {
  181. sessionId: SESSION_ID,
  182. title: "",
  183. status: "completed",
  184. workspace: { workspacePath: "/repo" },
  185. },
  186. projection: { target: null, lastError: null, pendingPermissions: [], activeToolCalls: [] },
  187. runtime: {},
  188. settings: { model: { current: model } },
  189. messages: fixtureMessages(),
  190. } as unknown as ZCodeSessionStateSnapshot;
  191. }
  192. function structureOf(snapshot: ZCodeSessionStateSnapshot) {
  193. return snapshot.messages.map((message) => ({
  194. info: message.info,
  195. parts: message.parts.map((part) => ({
  196. partId: part.partId,
  197. type: part.type,
  198. metadata: "metadata" in part ? part.metadata : undefined,
  199. text: part.type === "text" ? part.text : undefined,
  200. status: part.type === "tool" ? part.state.status : undefined,
  201. title: part.type === "tool" && "title" in part.state ? part.state.title : undefined,
  202. })),
  203. }));
  204. }
  205. describe("elideSessionSnapshotForIndex", () => {
  206. it("剥离 tool/reasoning/data URL 大载荷,同时保留 message 与 part 结构", () => {
  207. const full = fixtureSnapshot();
  208. const elided = elideSessionSnapshotForIndex(full);
  209. expect(structureOf(elided)).toEqual(structureOf(full));
  210. expect(JSON.stringify(elided).length).toBeLessThan(10_000);
  211. expect(JSON.stringify(full).length).toBeGreaterThan(BIG.length * 10);
  212. for (const message of elided.messages) {
  213. expect(() => zcodeMessageWithPartsSchema.parse(message)).not.toThrow();
  214. }
  215. const parts = elided.messages.flatMap((message) => message.parts);
  216. const byId = new Map(parts.map((part) => [part.partId, part]));
  217. expect(byId.get("p2")).toMatchObject({ type: "file", url: "data:," });
  218. expect(byId.get("p4")).toMatchObject({ type: "reasoning", text: "" });
  219. expect(byId.get("p5")).toMatchObject({
  220. state: { status: "completed", input: {}, output: "", metadata: {}, title: "cat big.log" },
  221. });
  222. expect(byId.get("p6")).toMatchObject({ state: { status: "error", input: {}, error: "" } });
  223. expect(byId.get("p7")).toMatchObject({ state: { status: "pending", input: {}, raw: "" } });
  224. expect(byId.get("p8")).toMatchObject({ state: { status: "running", input: {}, metadata: {} } });
  225. // 非大载荷 part 原样保留(同一引用即可证明未改写)。
  226. expect(byId.get("p3")).toBe(full.messages[1]?.parts[0]);
  227. expect(byId.get("p16")).toBe(full.messages[5]?.parts[1]);
  228. });
  229. it("不修改入参 snapshot(CLI 侧 messages 可能来自共享缓存)", () => {
  230. const full = fixtureSnapshot();
  231. const before = JSON.stringify(full);
  232. elideSessionSnapshotForIndex(full);
  233. expect(JSON.stringify(full)).toBe(before);
  234. });
  235. it("task index 依赖的全部派生结果与 full snapshot 一致", () => {
  236. const full = fixtureSnapshot();
  237. const elided = elideSessionSnapshotForIndex(full);
  238. const visibleIds = (snapshot: ZCodeSessionStateSnapshot) =>
  239. getZCodeUserVisibleMessages(snapshot.messages).map((message) => message.info.messageId);
  240. expect(visibleIds(elided)).toEqual(visibleIds(full));
  241. expect(visibleIds(full)).toEqual(["m_u1", "m_a1", "m_a2"]);
  242. expect(elided.messages.map(getConversationMessageProjectionPolicy)).toEqual(
  243. full.messages.map(getConversationMessageProjectionPolicy),
  244. );
  245. const title = (snapshot: ZCodeSessionStateSnapshot) =>
  246. resolveZCodeVisibleSessionTitle({ title: "", messages: snapshot.messages, target: null });
  247. expect(title(elided)).toBe(title(full));
  248. expect(title(full)).toBe("帮我实现订单查询");
  249. expect(deriveZCodeTaskStatusFromSessionSnapshot(elided)).toBe(
  250. deriveZCodeTaskStatusFromSessionSnapshot(full),
  251. );
  252. });
  253. it("非 data: 的 file URL 原样保留", () => {
  254. const full = fixtureSnapshot();
  255. const filePart = full.messages[0]?.parts[1];
  256. if (filePart?.type !== "file") throw new Error("fixture file part missing");
  257. filePart.url = "file:///repo/a.png";
  258. const elided = elideSessionSnapshotForIndex(full);
  259. expect(elided.messages[0]?.parts[1]).toBe(filePart);
  260. });
  261. });
  262. describe("session/read contentProfile", () => {
  263. it("接受 full / index,缺省兼容旧调用,拒绝未知值", () => {
  264. expect(zcodeSessionReadParamsSchema.parse({ sessionId: "s" })).toEqual({ sessionId: "s" });
  265. expect(
  266. zcodeSessionReadParamsSchema.parse({ sessionId: "s", contentProfile: "index" })
  267. .contentProfile,
  268. ).toBe("index");
  269. expect(
  270. zcodeSessionReadParamsSchema.parse({ sessionId: "s", contentProfile: "full" }).contentProfile,
  271. ).toBe("full");
  272. expect(() =>
  273. zcodeSessionReadParamsSchema.parse({ sessionId: "s", contentProfile: "tiny" }),
  274. ).toThrow();
  275. });
  276. });