tui-events.test.ts 18 KB

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