tui-events.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import { SessionEventType, type SessionEvent } from "@zcode/contracts";
  4. import { applySessionEventToState } from "../src/app-events.js";
  5. import {
  6. appendAgentResult,
  7. redactSensitivePromptForTranscript,
  8. submitDuringActiveTurn,
  9. submitIdleTurn,
  10. } from "../src/app-submit.js";
  11. import type { Message, ModifiedFileStat, QueuedInput } from "../src/app-model.js";
  12. import type { TuiOptions, TuiSubmitPromptResult } from "../src/types.js";
  13. test("does not render streamed tool input JSON as assistant text", () => {
  14. const state = createSessionEventState();
  15. state.apply(
  16. sessionEvent(SessionEventType.ModelStreaming, {
  17. delta: '{"description":"Explore project purpose"}',
  18. kind: "tool_input_delta",
  19. toolName: "Agent",
  20. }),
  21. );
  22. assert.equal(state.liveModelText, "");
  23. assert.equal(state.status, "Preparing tool Agent...");
  24. });
  25. test("keeps streamed text and tool parts in assistant message order", () => {
  26. const state = createSessionEventState();
  27. state.apply(
  28. sessionEvent(SessionEventType.ModelStreaming, {
  29. assistantMessageId: "assistant-1",
  30. delta: "先看看 package。",
  31. kind: "text_delta",
  32. }),
  33. );
  34. state.apply(
  35. sessionEvent(SessionEventType.ModelStreaming, {
  36. assistantMessageId: "assistant-1",
  37. delta: "",
  38. kind: "tool_call",
  39. toolCallId: "call-1",
  40. toolName: "Read",
  41. }),
  42. );
  43. state.apply(
  44. sessionEvent(SessionEventType.ToolCallScheduled, {
  45. input: { file_path: "package.json" },
  46. toolCallId: "call-1",
  47. toolName: "Read",
  48. }),
  49. );
  50. state.apply(
  51. sessionEvent(SessionEventType.ToolCallResult, {
  52. duration: 5,
  53. result: { content: "{}", success: true },
  54. toolCallId: "call-1",
  55. }),
  56. );
  57. state.apply(
  58. sessionEvent(SessionEventType.ModelStreaming, {
  59. assistantMessageId: "assistant-1",
  60. delta: "",
  61. done: true,
  62. kind: "finish",
  63. }),
  64. );
  65. assert.equal(state.liveModelText, "");
  66. assert.equal(state.messages.length, 1);
  67. assert.equal(state.messages[0]?.streaming, false);
  68. assert.deepEqual(
  69. state.messages[0]?.parts?.map((part) => part.type),
  70. ["text", "tool"],
  71. );
  72. assert.equal(state.messages[0]?.parts?.[0]?.type, "text");
  73. assert.equal(state.messages[0]?.parts?.[0]?.text, "先看看 package。");
  74. assert.equal(state.messages[0]?.parts?.[1]?.type, "tool");
  75. assert.equal(state.messages[0]?.parts?.[1]?.toolCallId, "call-1");
  76. });
  77. test("does not append a duplicate final response after streamed projection", () => {
  78. const next = appendAgentResult(
  79. [
  80. {
  81. content: "",
  82. id: "assistant-1",
  83. parts: [{ streamProjected: true, text: "完成了。", type: "text" }],
  84. role: "agent",
  85. streamProjected: true,
  86. streaming: true,
  87. },
  88. ],
  89. { response: "完成了。" },
  90. );
  91. assert.equal(next.length, 1);
  92. assert.equal(next[0]?.streaming, false);
  93. assert.equal(next[0]?.parts?.[0]?.type, "text");
  94. assert.equal(next[0]?.parts?.[0]?.text, "完成了。");
  95. });
  96. test("does not invent an assistant placeholder for empty final response", () => {
  97. const next = appendAgentResult([{ content: "你好", role: "user" }], { response: "" });
  98. assert.deepEqual(next, [{ content: "你好", role: "user" }]);
  99. });
  100. test("renders turn errors into the transcript", () => {
  101. const state = createSessionEventState();
  102. state.apply(
  103. sessionEvent(SessionEventType.TurnError, {
  104. error: {
  105. message: "Model returned no text.",
  106. type: "model_error",
  107. },
  108. turnPhase: "streaming",
  109. }),
  110. );
  111. assert.equal(state.status, "Turn failed.");
  112. assert.equal(state.lastError, "Model returned no text.");
  113. assert.deepEqual(state.messages, [
  114. {
  115. content: "Error: Model returned no text.",
  116. role: "system",
  117. },
  118. ]);
  119. });
  120. test("renders local assistant messages into the transcript", () => {
  121. const state = createSessionEventState();
  122. state.apply(
  123. sessionEvent(SessionEventType.AssistantMessage, {
  124. content: "Open this URL:\nhttps://chat.z.ai/oauth/authorize",
  125. }),
  126. );
  127. assert.deepEqual(state.messages, [
  128. {
  129. content: "Open this URL:\nhttps://chat.z.ai/oauth/authorize",
  130. role: "agent",
  131. },
  132. ]);
  133. });
  134. test("keeps busy sendInput user row before streamed response", async () => {
  135. const state = createSessionEventState();
  136. const response = "你好!";
  137. const options: TuiOptions = {
  138. noColor: true,
  139. stderr: process.stderr,
  140. stdin: process.stdin,
  141. stdout: process.stdout,
  142. submitPrompt: async () => ({ response: "unused" }),
  143. sendInput: async (_input, submitOptions) => {
  144. submitOptions.onEvent?.(
  145. sessionEvent(SessionEventType.ModelStreaming, {
  146. assistantMessageId: "assistant-1",
  147. delta: response,
  148. kind: "text_delta",
  149. }),
  150. );
  151. submitOptions.onEvent?.(
  152. sessionEvent(SessionEventType.ModelStreaming, {
  153. assistantMessageId: "assistant-1",
  154. done: true,
  155. kind: "finish",
  156. }),
  157. );
  158. return {
  159. kind: "started_turn",
  160. result: { response },
  161. };
  162. },
  163. };
  164. await submitDuringActiveTurn({
  165. activeTurnId: "turn-1" as never,
  166. applyResult: (result: TuiSubmitPromptResult) => {
  167. state.setMessages((current) => appendAgentResult(current, result));
  168. },
  169. applySessionEvent: state.apply,
  170. draftAttachments: [],
  171. messageInsertIndex: state.messages.length,
  172. options,
  173. requestPermission: async () => {
  174. throw new Error("permission should not be requested");
  175. },
  176. setDraftValue: () => {},
  177. setLastError: () => {},
  178. setMessages: state.setMessages,
  179. setQueuedInputs: state.setQueuedInputs,
  180. setStatus: (status) => {
  181. state.status = status;
  182. },
  183. text: "你好",
  184. });
  185. assert.deepEqual(
  186. state.messages.map((message) => message.role),
  187. ["user", "agent"],
  188. );
  189. assert.equal(state.messages[0]?.content, "你好");
  190. assert.equal(state.messages[1]?.parts?.[0]?.type, "text");
  191. assert.equal(state.messages[1]?.parts?.[0]?.text, response);
  192. });
  193. test("keeps queued busy input out of the transcript projection", async () => {
  194. const state = createSessionEventState();
  195. const options: TuiOptions = {
  196. noColor: true,
  197. stderr: process.stderr,
  198. stdin: process.stdin,
  199. stdout: process.stdout,
  200. submitPrompt: async () => ({ response: "unused" }),
  201. sendInput: async () => ({
  202. kind: "queued",
  203. pendingInputId: "pending-1",
  204. queueLength: 1,
  205. turnId: "turn-1" as never,
  206. }),
  207. };
  208. await submitDuringActiveTurn({
  209. activeTurnId: "turn-1" as never,
  210. applyResult: () => {
  211. throw new Error("queued input should not start a turn result");
  212. },
  213. applySessionEvent: state.apply,
  214. draftAttachments: [],
  215. messageInsertIndex: state.messages.length,
  216. options,
  217. requestPermission: async () => {
  218. throw new Error("permission should not be requested");
  219. },
  220. setDraftValue: () => {},
  221. setLastError: () => {},
  222. setMessages: state.setMessages,
  223. setQueuedInputs: state.setQueuedInputs,
  224. setStatus: (status) => {
  225. state.status = status;
  226. },
  227. text: "queued follow-up",
  228. });
  229. assert.deepEqual(state.messages, []);
  230. assert.deepEqual(state.queuedInputs, [{ id: "pending-1", text: "queued follow-up" }]);
  231. assert.equal(state.status, "Input queued.");
  232. });
  233. test("tracks queued turn steering events outside transcript messages", () => {
  234. const state = createSessionEventState();
  235. state.apply(
  236. sessionEvent(SessionEventType.TurnSteerQueued, {
  237. input: "full queued input",
  238. inputPreview: "full queued input",
  239. inputSize: 17,
  240. pendingInputId: "pending-1",
  241. queueLength: 1,
  242. targetTurnId: "turn-1",
  243. }),
  244. );
  245. assert.deepEqual(state.messages, []);
  246. assert.deepEqual(state.queuedInputs, [{ id: "pending-1", text: "full queued input" }]);
  247. state.apply(
  248. sessionEvent(SessionEventType.TurnSteerDrained, {
  249. injectedMessageIds: ["message-1"],
  250. pendingInputIds: ["pending-1"],
  251. targetTurnId: "turn-1",
  252. }),
  253. );
  254. assert.deepEqual(state.queuedInputs, []);
  255. });
  256. test("renders compact lifecycle events as a single timeline row", () => {
  257. const state = createSessionEventState();
  258. state.apply(
  259. sessionEvent(SessionEventType.CompactStarted, {
  260. messageId: "msg-compact-1",
  261. operationId: "cmp-1",
  262. status: "started",
  263. trigger: "manual",
  264. }),
  265. );
  266. state.apply(
  267. sessionEvent(SessionEventType.CompactCompleted, {
  268. messageId: "msg-compact-1",
  269. operationId: "cmp-1",
  270. status: "completed",
  271. trigger: "manual",
  272. }),
  273. );
  274. assert.equal(state.status, "Conversation compacted.");
  275. assert.equal(state.messages.length, 1);
  276. assert.equal(state.messages[0]?.role, "timeline");
  277. assert.equal(state.messages[0]?.timeline?.status, "completed");
  278. });
  279. test("renders compact retrying events as the same running timeline row", () => {
  280. const state = createSessionEventState();
  281. state.apply(
  282. sessionEvent(SessionEventType.CompactStarted, {
  283. attempt: 1,
  284. maxAttempts: 3,
  285. messageId: "msg-compact-retry",
  286. operationId: "cmp-retry",
  287. status: "started",
  288. trigger: "auto",
  289. }),
  290. );
  291. state.apply(
  292. sessionEvent(SessionEventType.CompactStarted, {
  293. attempt: 2,
  294. maxAttempts: 3,
  295. messageId: "msg-compact-retry",
  296. operationId: "cmp-retry",
  297. reason: "Failed to generate compact summary",
  298. status: "retrying",
  299. trigger: "auto",
  300. }),
  301. );
  302. assert.equal(state.status, "Retrying context compression (2/3)");
  303. assert.equal(state.messages.length, 1);
  304. assert.equal(state.messages[0]?.timeline?.status, "retrying");
  305. assert.equal(state.messages[0]?.timeline?.attempt, 2);
  306. assert.equal(state.messages[0]?.timeline?.maxAttempts, 3);
  307. state.apply(
  308. sessionEvent(SessionEventType.CompactFailed, {
  309. attempt: 3,
  310. maxAttempts: 3,
  311. messageId: "msg-compact-retry",
  312. operationId: "cmp-retry",
  313. reason: "Failed to generate compact summary",
  314. status: "failed",
  315. trigger: "auto",
  316. }),
  317. );
  318. assert.equal(state.status, "Context compression failed.");
  319. assert.equal(state.lastError, "Failed to generate compact summary");
  320. assert.equal(state.messages.length, 1);
  321. assert.equal(state.messages[0]?.timeline?.status, "failed");
  322. assert.equal(state.messages[0]?.timeline?.reason, "Failed to generate compact summary");
  323. assert.equal(state.messages[0]?.timeline?.attempt, 3);
  324. });
  325. test("renders skipped compact events without a failure state", () => {
  326. const state = createSessionEventState();
  327. state.apply(
  328. sessionEvent(SessionEventType.CompactCompleted, {
  329. messageId: "msg-compact-skipped",
  330. operationId: "cmp-skipped",
  331. status: "skipped",
  332. trigger: "manual",
  333. }),
  334. );
  335. assert.equal(state.status, "Context is up to date; no compression needed");
  336. assert.equal(state.lastError, undefined);
  337. assert.equal(state.messages.length, 1);
  338. assert.equal(state.messages[0]?.role, "timeline");
  339. assert.equal(state.messages[0]?.timeline?.status, "skipped");
  340. });
  341. test("renders compact turn errors on the timeline instead of system transcript errors", () => {
  342. const state = createSessionEventState();
  343. state.apply(
  344. sessionEvent(SessionEventType.CompactStarted, {
  345. messageId: "msg-compact-1",
  346. operationId: "cmp-1",
  347. status: "started",
  348. trigger: "manual",
  349. }),
  350. );
  351. state.apply(
  352. sessionEvent(SessionEventType.TurnError, {
  353. error: {
  354. message: "No summary produced.",
  355. type: "compact_failed",
  356. },
  357. turnPhase: "compact",
  358. }),
  359. );
  360. assert.equal(state.status, "Context compression failed.");
  361. assert.equal(state.lastError, "No summary produced.");
  362. assert.equal(state.messages.length, 1);
  363. assert.equal(state.messages[0]?.role, "timeline");
  364. assert.equal(state.messages[0]?.timeline?.status, "failed");
  365. assert.equal(state.messages[0]?.timeline?.reason, "No summary produced.");
  366. });
  367. test("submitting compact slash command creates timeline row without a user row", async () => {
  368. const state = createSessionEventState();
  369. const options: TuiOptions = {
  370. noColor: true,
  371. stderr: process.stderr,
  372. stdin: process.stdin,
  373. stdout: process.stdout,
  374. submitPrompt: async () => ({ response: "" }),
  375. };
  376. await submitIdleTurn({
  377. applyResult: (result: TuiSubmitPromptResult) => {
  378. state.setMessages((current) => appendAgentResult(current, result));
  379. },
  380. applySessionEvent: state.apply,
  381. draftAttachments: [],
  382. options,
  383. requestPermission: async () => {
  384. throw new Error("permission should not be requested");
  385. },
  386. setBusy: () => {},
  387. setDraftAttachments: () => {},
  388. setDraftValue: () => {},
  389. setLastError: () => {},
  390. setLiveModelText: () => {},
  391. setMessages: state.setMessages,
  392. setSelection: () => {},
  393. setSlashSelection: () => {},
  394. setStatus: (status) => {
  395. state.status = status;
  396. },
  397. setStatusDetails: () => {},
  398. text: "/compact keep failures",
  399. turnRef: { current: undefined },
  400. });
  401. assert.equal(state.messages.length, 1);
  402. assert.equal(state.messages[0]?.role, "timeline");
  403. assert.equal(state.messages[0]?.timeline?.status, "started");
  404. assert.equal(state.messages[0]?.timeline?.command, "/compact keep failures");
  405. });
  406. test("redacts manual coding plan api keys from local transcript rows", () => {
  407. assert.equal(
  408. redactSensitivePromptForTranscript("/login zai-coding-plan-api-key zai-secret-key"),
  409. "/login zai-coding-plan-api-key <redacted>",
  410. );
  411. assert.equal(
  412. redactSensitivePromptForTranscript("/login bigmodel-coding-plan-api-key bm-secret-key"),
  413. "/login bigmodel-coding-plan-api-key <redacted>",
  414. );
  415. assert.equal(
  416. redactSensitivePromptForTranscript("/login zai-coding-plan-api-key"),
  417. "/login zai-coding-plan-api-key",
  418. );
  419. });
  420. test("updates the model projection from model selected events", () => {
  421. const state = createSessionEventState();
  422. state.apply(
  423. sessionEvent(SessionEventType.ModelSelected, {
  424. modelSelection: {
  425. modelId: "openai/gpt-5.5",
  426. providerId: "gateway",
  427. },
  428. }),
  429. );
  430. assert.equal(state.model, "gateway/openai/gpt-5.5");
  431. });
  432. test("aggregates current-session modified files from file diff displays", () => {
  433. const state = createSessionEventState("/workspace/project");
  434. const display = {
  435. additions: 3,
  436. deletions: 1,
  437. filePath: "/workspace/project/src/App.jsx",
  438. kind: "file_diff",
  439. structuredPatch: [],
  440. };
  441. state.apply(
  442. sessionEvent(SessionEventType.ToolCallResult, {
  443. duration: 5,
  444. result: { content: "ok", display, success: true },
  445. toolCallId: "call-1",
  446. }),
  447. );
  448. state.apply(
  449. sessionEvent(SessionEventType.ToolCallResult, {
  450. duration: 5,
  451. result: { content: "ok", display, success: true },
  452. toolCallId: "call-1",
  453. }),
  454. );
  455. state.apply(
  456. sessionEvent(SessionEventType.ToolCallResult, {
  457. duration: 5,
  458. result: {
  459. content: "ok",
  460. display: { ...display, additions: 2, deletions: 4 },
  461. success: true,
  462. },
  463. toolCallId: "call-2",
  464. }),
  465. );
  466. assert.deepEqual(state.modifiedFiles, [
  467. {
  468. additions: 5,
  469. deletions: 5,
  470. filePath: "src/App.jsx",
  471. },
  472. ]);
  473. });
  474. function createSessionEventState(workspaceDirectory?: string): {
  475. apply: (event: SessionEvent) => void;
  476. lastError: string | undefined;
  477. liveModelText: string;
  478. model: string | undefined;
  479. modifiedFiles: ModifiedFileStat[];
  480. messages: Message[];
  481. queuedInputs: QueuedInput[];
  482. setMessages: (updater: Message[] | ((current: Message[]) => Message[])) => void;
  483. setQueuedInputs: (updater: QueuedInput[] | ((current: QueuedInput[]) => QueuedInput[])) => void;
  484. status: string;
  485. } {
  486. const state: {
  487. lastError: string | undefined;
  488. liveModelText: string;
  489. messages: Message[];
  490. model: string | undefined;
  491. modifiedFiles: ModifiedFileStat[];
  492. queuedInputs: QueuedInput[];
  493. status: string;
  494. } = {
  495. lastError: undefined,
  496. liveModelText: "",
  497. messages: [],
  498. model: undefined,
  499. modifiedFiles: [],
  500. queuedInputs: [],
  501. status: "",
  502. };
  503. const assistantMessageIdsByToolCallId = new Map<string, string>();
  504. const modifiedFileToolCallIds = new Set<string>();
  505. const toolNamesById = new Map<string, string>();
  506. return {
  507. apply: (event) => {
  508. applySessionEventToState(event, {
  509. assistantMessageIdsByToolCallId,
  510. setActiveTurnId: () => {},
  511. setCacheStats: () => {},
  512. setContextUsage: () => {},
  513. setLastError: (message) => {
  514. state.lastError = message;
  515. },
  516. setLiveModelText: (updater) => {
  517. state.liveModelText =
  518. typeof updater === "function" ? updater(state.liveModelText) : updater;
  519. },
  520. setMessages: (updater) => {
  521. state.messages = typeof updater === "function" ? updater(state.messages) : updater;
  522. },
  523. setModel: (model) => {
  524. state.model = model;
  525. },
  526. setModifiedFiles: (updater) => {
  527. state.modifiedFiles =
  528. typeof updater === "function" ? updater(state.modifiedFiles) : updater;
  529. },
  530. setNetworkRequests: () => {},
  531. setQueuedInputs: (updater) => {
  532. state.queuedInputs =
  533. typeof updater === "function" ? updater(state.queuedInputs) : updater;
  534. },
  535. setStatus: (next) => {
  536. state.status = next;
  537. },
  538. setTodos: () => {},
  539. setUsage: () => {},
  540. toolNamesById,
  541. modifiedFileToolCallIds,
  542. workspaceDirectory,
  543. });
  544. },
  545. get lastError() {
  546. return state.lastError;
  547. },
  548. get liveModelText() {
  549. return state.liveModelText;
  550. },
  551. get model() {
  552. return state.model;
  553. },
  554. get modifiedFiles() {
  555. return state.modifiedFiles;
  556. },
  557. get messages() {
  558. return state.messages;
  559. },
  560. get queuedInputs() {
  561. return state.queuedInputs;
  562. },
  563. setMessages: (updater) => {
  564. state.messages = typeof updater === "function" ? updater(state.messages) : updater;
  565. },
  566. setQueuedInputs: (updater) => {
  567. state.queuedInputs = typeof updater === "function" ? updater(state.queuedInputs) : updater;
  568. },
  569. get status() {
  570. return state.status;
  571. },
  572. set status(nextStatus: string) {
  573. state.status = nextStatus;
  574. },
  575. };
  576. }
  577. function sessionEvent(type: SessionEventType, payload: unknown): SessionEvent {
  578. return {
  579. id: "event-1",
  580. payload,
  581. sequenceNumber: 1,
  582. sessionId: "session-1",
  583. timestamp: new Date(0),
  584. traceId: "trace-1",
  585. type,
  586. } as SessionEvent;
  587. }