tui-events.test.ts 18 KB

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