tui.unit.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import { SessionEventType, type SessionEvent } from "@zcode/contracts";
  4. import { getZCodeCopy } from "@zcode/i18n";
  5. import { LoginRequiredPanel } from "../src/app-components.js";
  6. import { ContentPane, MessageRow } from "../src/app-transcript-components.js";
  7. import { EmptyTranscriptLogo, ZCODE_LOGO_LINES } from "../src/app-empty-transcript.js";
  8. import { SHIMMER_SWEEP_PERIOD_MS, shimmerTextSegments } from "../src/app-motion.js";
  9. import {
  10. ShikiDiffView,
  11. buildDiffRows,
  12. buildSplitDiffRows,
  13. } from "../src/app-shiki-diff-view.js";
  14. import {
  15. highlightShikiCodeLines,
  16. inferShikiLanguage,
  17. resetShikiHighlighterForTest,
  18. } from "../src/app-shiki-highlighter.js";
  19. import { SIDEBAR_CONTENT_WIDTH, Sidebar } from "../src/app-sidebar.js";
  20. import { moveInputCursorToEnd } from "../src/app-input-pane.js";
  21. import { createSelectionCopyHandler, hasCopyableSelectionText } from "../src/app-copy.js";
  22. import { modelNetworkRequestTargetFromPayload } from "../src/app-event-data.js";
  23. import { appendAgentResult } from "../src/app-submit.js";
  24. import type { Message, SidebarState, ToolTranscriptPart } from "../src/app-model.js";
  25. import {
  26. applyToolTranscriptEvent,
  27. formatFileDiffDisplay,
  28. summarizeToolInput,
  29. } from "../src/app-tool-transcript.js";
  30. import { ToolTranscriptPartView } from "../src/app-tool-components.js";
  31. import { visibleSlashCommandWindow } from "../src/app-input.js";
  32. import { createSelectionState } from "../src/app-selection-state.js";
  33. import { describeSessionEvent, normalizePromptInput } from "../src/state.js";
  34. import type { TuiSlashCommandSuggestion } from "../src/types.js";
  35. const EN_COPY = getZCodeCopy("en-US").tui;
  36. const ZH_COPY = getZCodeCopy("zh-CN").tui;
  37. test("normalizes prompt input for the shell", () => {
  38. assert.deepEqual(normalizePromptInput("hello"), {
  39. attachmentCount: 0,
  40. text: "hello",
  41. });
  42. assert.deepEqual(
  43. normalizePromptInput({
  44. attachments: [
  45. {
  46. path: "/tmp/a.png",
  47. type: "image",
  48. },
  49. ],
  50. text: "with image",
  51. }),
  52. {
  53. attachmentCount: 1,
  54. text: "with image",
  55. },
  56. );
  57. });
  58. test("describes session events without coupling the shell to business logic", () => {
  59. assert.equal(describeSessionEvent({ type: "turn_started" } as never), "turn started");
  60. });
  61. test("renders a ZCODE logo placeholder for an empty transcript", () => {
  62. const [child] = reactElementChildren(
  63. ContentPane({ copy: EN_COPY, focused: false, messages: [] }),
  64. );
  65. const lines = collectTextLines(EmptyTranscriptLogo());
  66. assert.equal(child?.type, EmptyTranscriptLogo);
  67. assert.deepEqual(lines, [...ZCODE_LOGO_LINES]);
  68. });
  69. test("centers the empty transcript logo within the available viewport", () => {
  70. const style = reactElementStyle(EmptyTranscriptLogo());
  71. assert.equal(style.flexGrow, 1);
  72. assert.equal(style.justifyContent, "center");
  73. assert.equal(style.minHeight, ZCODE_LOGO_LINES.length);
  74. });
  75. test("projects logo shimmer without changing the source text", () => {
  76. const sourceText = ZCODE_LOGO_LINES[0];
  77. const segments = shimmerTextSegments(sourceText, SHIMMER_SWEEP_PERIOD_MS / 2, {
  78. baseColor: "#000000",
  79. highlightColor: "#ffffff",
  80. });
  81. assert.equal(segments.map((segment) => segment.text).join(""), sourceText);
  82. const highlightedSegment = segments.find((segment) => segment.highlighted);
  83. assert.ok(highlightedSegment);
  84. assert.notEqual(highlightedSegment.color, "#000000");
  85. });
  86. test("renders the transcript as a borderless surface", () => {
  87. const style = reactElementStyle(ContentPane({ copy: EN_COPY, focused: false, messages: [] }));
  88. assert.equal(style.border, false);
  89. assert.equal(style.backgroundColor, "#0f1419");
  90. });
  91. test("hides the empty transcript logo when messages are present", () => {
  92. const message: Message = { content: "hello", role: "user" };
  93. const [child] = reactElementChildren(
  94. ContentPane({ copy: EN_COPY, focused: false, messages: [message] }),
  95. );
  96. const lines = collectTextLines(MessageRow({ copy: EN_COPY, index: 0, message }));
  97. assert.equal(child?.type, MessageRow);
  98. assert.notEqual(child?.type, EmptyTranscriptLogo);
  99. assert.equal(lines.includes(ZCODE_LOGO_LINES[0]), false);
  100. assert.ok(lines.some((line) => line.includes("hello")));
  101. assert.equal(
  102. lines.some((line) => line.includes("User:")),
  103. false,
  104. );
  105. });
  106. test("renders a prominent non-modal login notice", () => {
  107. const lines = collectTextLines(LoginRequiredPanel());
  108. const textNodes = collectTextNodes(LoginRequiredPanel());
  109. // 登录提示改为“没有可用模型”,引导用 /model 查看模型或 /login 连接账号。
  110. assert.ok(lines.some((line) => line.includes("No available models")));
  111. assert.ok(lines.some((line) => line.includes("/model")));
  112. assert.ok(textNodes.some((node) => node.style.fg === "#fbbf24"));
  113. });
  114. test("renders localized Chinese login notice copy", () => {
  115. const lines = collectTextLines(LoginRequiredPanel({ copy: ZH_COPY }));
  116. assert.ok(lines.some((line) => line.includes("没有可用模型")));
  117. assert.ok(lines.some((line) => line.includes("输入 /model 查看模型")));
  118. });
  119. test("clears the transcript when a session reset has no restored messages", () => {
  120. const messages = appendAgentResult(
  121. [
  122. { content: "old prompt", role: "user" },
  123. { content: "old answer", role: "agent" },
  124. { content: "/new", role: "user" },
  125. ],
  126. {
  127. resetSessionProjection: true,
  128. response: "Started new session sess_new.",
  129. },
  130. );
  131. assert.deepEqual(messages, [
  132. {
  133. content: "Started new session sess_new.",
  134. role: "agent",
  135. },
  136. ]);
  137. });
  138. test("uses restored messages when a session reset carries resumed history", () => {
  139. const messages = appendAgentResult(
  140. [
  141. { content: "old prompt", role: "user" },
  142. { content: "old answer", role: "agent" },
  143. ],
  144. {
  145. resetSessionProjection: true,
  146. response: "Resumed session sess_prev.",
  147. restoredMessages: [
  148. { content: "resumed prompt", role: "user" },
  149. { content: "resumed answer", role: "agent" },
  150. ],
  151. },
  152. );
  153. assert.deepEqual(messages, [
  154. { content: "resumed prompt", role: "user" },
  155. { content: "resumed answer", role: "agent" },
  156. { content: "Resumed session sess_prev.", role: "agent" },
  157. ]);
  158. });
  159. test("restores resumed thought and tool transcript parts", () => {
  160. const messages = appendAgentResult(
  161. [],
  162. {
  163. resetSessionProjection: true,
  164. response: "Resumed session sess_prev.",
  165. restoredMessages: [
  166. {
  167. content: "resumed answer",
  168. parts: [
  169. {
  170. text: "private reasoning",
  171. type: "thought",
  172. },
  173. {
  174. text: "visible answer",
  175. type: "text",
  176. },
  177. {
  178. input: { file_path: "/workspace/project/src/app.ts" },
  179. output: "file contents",
  180. status: "completed",
  181. toolCallId: "call-1",
  182. toolName: "Read",
  183. type: "tool",
  184. },
  185. ],
  186. role: "agent",
  187. },
  188. ],
  189. },
  190. { workspaceDirectory: "/workspace/project" },
  191. );
  192. assert.deepEqual(messages, [
  193. {
  194. content: "resumed answer",
  195. parts: [
  196. {
  197. contentCharCount: "private reasoning".length,
  198. status: "thought",
  199. text: "private reasoning",
  200. type: "thought",
  201. },
  202. {
  203. text: "visible answer",
  204. type: "text",
  205. },
  206. {
  207. detailLines: [],
  208. output: "file contents",
  209. status: "completed",
  210. title: "Read src/app.ts",
  211. toolCallId: "call-1",
  212. toolName: "Read",
  213. type: "tool",
  214. },
  215. ],
  216. role: "agent",
  217. },
  218. {
  219. content: "Resumed session sess_prev.",
  220. role: "agent",
  221. },
  222. ]);
  223. });
  224. test("restores resumed file diff display payloads", () => {
  225. const messages = appendAgentResult(
  226. [],
  227. {
  228. resetSessionProjection: true,
  229. response: "",
  230. restoredMessages: [
  231. {
  232. content: "",
  233. parts: [
  234. {
  235. input: {
  236. file_path: "/workspace/project/src/app.ts",
  237. new_string: "new",
  238. old_string: "old",
  239. },
  240. output: "The file has been updated successfully.",
  241. resultDisplay: {
  242. additions: 1,
  243. deletions: 1,
  244. filePath: "/workspace/project/src/app.ts",
  245. kind: "file_diff",
  246. structuredPatch: [
  247. {
  248. oldStart: 1,
  249. oldLines: 1,
  250. newStart: 1,
  251. newLines: 1,
  252. lines: ["-old", "+new"],
  253. },
  254. ],
  255. truncated: false,
  256. },
  257. status: "completed",
  258. toolCallId: "call-edit",
  259. toolName: "Edit",
  260. type: "tool",
  261. },
  262. ],
  263. role: "agent",
  264. },
  265. ],
  266. },
  267. { workspaceDirectory: "/workspace/project" },
  268. );
  269. const toolPart = messages[0]?.parts?.[0] as ToolTranscriptPart | undefined;
  270. assert.equal(toolPart?.title, "Edit src/app.ts");
  271. assert.equal(toolPart?.resultDisplay?.filePath, "/workspace/project/src/app.ts");
  272. assert.ok(toolPart?.resultDisplay?.diff?.includes("@@ -1,1 +1,1 @@"));
  273. assert.ok(toolPart?.resultDisplay?.lines.some((line) => line.text.includes(" 1 -old")));
  274. });
  275. test("renders the product version header and workspace directory footer", () => {
  276. const workspaceDirectory = `/workspace/${"deep/".repeat(20)}project`;
  277. const lines = collectTextLines(
  278. Sidebar({
  279. ...baseSidebarState,
  280. copy: EN_COPY,
  281. workspaceDirectory,
  282. }),
  283. );
  284. const workspaceLine = lines.find((line) => line.startsWith("/workspace/"));
  285. assert.ok(workspaceLine);
  286. assert.equal(workspaceLine.length, SIDEBAR_CONTENT_WIDTH);
  287. assert.match(workspaceLine, /\.\.\.$/);
  288. assert.ok(lines.includes("ZCode"));
  289. assert.ok(lines.includes(" 0.0.0"));
  290. });
  291. test("renders localized Chinese TUI copy", () => {
  292. const lines = collectTextLines(
  293. Sidebar({
  294. ...baseSidebarState,
  295. copy: ZH_COPY,
  296. status: ZH_COPY.status.ready,
  297. }),
  298. );
  299. assert.ok(lines.includes("状态"));
  300. assert.ok(lines.some((line) => line.includes("就绪。")));
  301. });
  302. test("moves recalled input history to the buffer end", () => {
  303. let movedToEnd = false;
  304. moveInputCursorToEnd({
  305. gotoBufferEnd: () => {
  306. movedToEnd = true;
  307. },
  308. });
  309. assert.equal(movedToEnd, true);
  310. });
  311. test("copies selected text exactly and clears OpenTUI selection", async () => {
  312. let copied = "";
  313. let clearCount = 0;
  314. const copySelection = createSelectionCopyHandler({
  315. clearSelection: () => {
  316. clearCount += 1;
  317. },
  318. getSelectionText: () => "hello\nworld\n",
  319. writeClipboardText: (text) => {
  320. copied = text;
  321. },
  322. });
  323. assert.deepEqual(await copySelection(), {
  324. characterCount: "hello\nworld\n".length,
  325. kind: "copied",
  326. });
  327. assert.equal(copied, "hello\nworld\n");
  328. assert.equal(clearCount, 1);
  329. });
  330. test("ignores empty selected text and clears the selection", async () => {
  331. let clearCount = 0;
  332. const copySelection = createSelectionCopyHandler({
  333. clearSelection: () => {
  334. clearCount += 1;
  335. },
  336. getSelectionText: () => " \n\t",
  337. writeClipboardText: () => {
  338. throw new Error("empty selection should not be copied");
  339. },
  340. });
  341. assert.deepEqual(await copySelection(), { kind: "empty" });
  342. assert.equal(clearCount, 1);
  343. assert.equal(hasCopyableSelectionText(" \n\t"), false);
  344. });
  345. test("reports unavailable text clipboard writer", async () => {
  346. let clearCount = 0;
  347. const copySelection = createSelectionCopyHandler({
  348. clearSelection: () => {
  349. clearCount += 1;
  350. },
  351. getSelectionText: () => "copy me",
  352. });
  353. assert.deepEqual(await copySelection(), { kind: "unavailable" });
  354. assert.equal(clearCount, 1);
  355. });
  356. test("keeps the selected slash command inside the visible window", () => {
  357. const commands: TuiSlashCommandSuggestion[] = Array.from({ length: 8 }, (_, index) => ({
  358. name: `command-${index}`,
  359. summary: `summary ${index}`,
  360. usage: `/command-${index}`,
  361. }));
  362. assert.deepEqual(visibleSlashCommandWindow(commands, 5, 6), {
  363. commands: commands.slice(0, 6),
  364. selectedIndex: 5,
  365. startIndex: 0,
  366. });
  367. assert.deepEqual(visibleSlashCommandWindow(commands, 6, 6), {
  368. commands: commands.slice(1, 7),
  369. selectedIndex: 5,
  370. startIndex: 1,
  371. });
  372. assert.deepEqual(visibleSlashCommandWindow(commands, 99, 6), {
  373. commands: commands.slice(2, 8),
  374. selectedIndex: 5,
  375. startIndex: 2,
  376. });
  377. });
  378. test("initializes local selection state from command selected index", () => {
  379. const selection = createSelectionState({
  380. emptyMessage: "No modes.",
  381. items: [
  382. { command: "/mode plan", id: "plan", primary: "Plan" },
  383. { command: "/mode build", id: "build", primary: "Build" },
  384. ],
  385. prompt: "Choose a mode.",
  386. selectedIndex: 1,
  387. title: "Switch Mode",
  388. });
  389. assert.equal(selection?.filter, "");
  390. assert.equal(selection?.selectedIndex, 1);
  391. });
  392. test("uses provider endpoint as the model network request target", () => {
  393. assert.deepEqual(
  394. modelNetworkRequestTargetFromPayload({
  395. baseURL: "https://api.deepseek.com",
  396. model: {
  397. modelId: "deepseek-chat",
  398. providerId: "deepseek",
  399. },
  400. }),
  401. {
  402. model: "deepseek-chat",
  403. provider: "deepseek",
  404. url: "https://api.deepseek.com",
  405. },
  406. );
  407. });
  408. test("falls back to provider and model when endpoint context is absent", () => {
  409. assert.deepEqual(
  410. modelNetworkRequestTargetFromPayload({
  411. model: {
  412. modelId: "model-a",
  413. providerId: "test",
  414. },
  415. url: "model",
  416. }),
  417. {
  418. model: "model-a",
  419. provider: "test",
  420. url: "test/model-a",
  421. },
  422. );
  423. });
  424. test("summarizes Bash tool input without leaking environment values", () => {
  425. assert.deepEqual(
  426. summarizeToolInput("Bash", {
  427. command: "npm test",
  428. cwd: "packages/tui",
  429. env: {
  430. set: {
  431. API_KEY: "secret-value",
  432. },
  433. unset: ["DEBUG"],
  434. },
  435. }),
  436. ["command: npm test", "cwd: packages/tui", "env: set API_KEY; unset DEBUG"],
  437. );
  438. });
  439. test("summarizes Read tool input with file range", () => {
  440. assert.deepEqual(
  441. summarizeToolInput("Read", {
  442. file_path: "packages/tui/src/app.tsx",
  443. limit: 40,
  444. offset: 10,
  445. }),
  446. ["offset: 10", "limit: 40"],
  447. );
  448. });
  449. test("redacts unknown tool input and keeps detail blocks bounded", () => {
  450. const lines = summarizeToolInput("mcp_server_tool", {
  451. content: "x".repeat(200),
  452. nested: { value: true },
  453. pattern: "needle",
  454. token: "super-secret",
  455. url: "https://example.com",
  456. });
  457. assert.equal(lines.length, 4);
  458. assert.equal(lines[0], "content: [200 chars]");
  459. assert.equal(lines[3], "token: [redacted]");
  460. });
  461. test("projects tool lifecycle events into one transcript part", () => {
  462. const state = createToolProjectionState();
  463. state.apply(
  464. sessionEvent(SessionEventType.ToolCallScheduled, {
  465. input: {
  466. command: "npm test",
  467. cwd: "packages/tui",
  468. },
  469. toolCallId: "call-1",
  470. toolName: "Bash",
  471. }),
  472. );
  473. state.apply(
  474. sessionEvent(SessionEventType.ToolCallStarted, {
  475. toolCallId: "call-1",
  476. }),
  477. );
  478. state.apply(
  479. sessionEvent(SessionEventType.ToolCallResult, {
  480. duration: 12,
  481. result: {
  482. content: "ok",
  483. success: true,
  484. },
  485. toolCallId: "call-1",
  486. }),
  487. );
  488. assert.equal(state.messages.length, 1);
  489. const part = onlyToolPart(state.messages);
  490. assert.equal(part.status, "completed");
  491. assert.equal(part.toolName, "Bash");
  492. assert.deepEqual(part.detailLines, ["command: npm test", "cwd: packages/tui"]);
  493. });
  494. test("renders file diff with the Shiki diff renderer", () => {
  495. const resultDisplay = formatFileDiffDisplay({
  496. additions: 1,
  497. deletions: 1,
  498. filePath: "packages/tui/src/app.tsx",
  499. kind: "file_diff",
  500. structuredPatch: [
  501. {
  502. lines: ["-old", "+new", " context"],
  503. newLines: 2,
  504. newStart: 4,
  505. oldLines: 2,
  506. oldStart: 4,
  507. },
  508. ],
  509. });
  510. const view = ToolTranscriptPartView({
  511. part: {
  512. detailLines: [],
  513. resultDisplay,
  514. status: "completed",
  515. title: "Edit packages/tui/src/app.tsx",
  516. toolCallId: "call-1",
  517. toolName: "Edit",
  518. type: "tool",
  519. },
  520. });
  521. const lines = collectTextNodes(view);
  522. const [diffElement] = collectElementsByType(view, ShikiDiffView);
  523. assert.equal(lines[0]?.text, "Edit packages/tui/src/app.tsx");
  524. assert.equal(
  525. lines.some((line) => line.text.startsWith("ok Tool")),
  526. false,
  527. );
  528. assert.equal(
  529. lines.some((line) => line.text.includes("diff:")),
  530. false,
  531. );
  532. assert.equal(
  533. lines.some((line) => line.text.includes("@@")),
  534. false,
  535. );
  536. assert.equal(
  537. lines.some((line) => line.text.includes("file_path:")),
  538. false,
  539. );
  540. assert.equal(diffElement?.props.view, "unified");
  541. assert.equal(diffElement?.props.filePath, "packages/tui/src/app.tsx");
  542. assert.deepEqual(diffElement?.props.structuredPatch, resultDisplay.structuredPatch);
  543. assert.equal(diffElement?.props.truncated, false);
  544. assert.ok(String(resultDisplay.diff).includes("@@ -4,2 +4,2 @@"));
  545. assert.ok(resultDisplay.lines.some((line) => line.text.includes(" 4 -old")));
  546. assert.ok(resultDisplay.lines.some((line) => line.text.includes(" 4 +new")));
  547. });
  548. test("infers Shiki languages from file diff paths", () => {
  549. assert.equal(inferShikiLanguage("src/Scene3D.jsx"), "jsx");
  550. assert.equal(inferShikiLanguage("src/App.tsx"), "tsx");
  551. assert.equal(inferShikiLanguage("TodoList/TodoItem.swift"), "swift");
  552. assert.equal(inferShikiLanguage("Dockerfile"), "dockerfile");
  553. assert.equal(inferShikiLanguage("file.unknown-ext"), undefined);
  554. });
  555. test("highlights Swift file diff content through Shiki", async () => {
  556. resetShikiHighlighterForTest();
  557. const highlighted = await highlightShikiCodeLines({
  558. filePath: "TodoList/TodoItem.swift",
  559. lines: ["struct TodoItem {", " var title: String"],
  560. mode: "dark",
  561. });
  562. assert.ok(highlighted);
  563. assert.equal(highlighted.length, 2);
  564. assert.ok(highlighted[0]?.some((segment) => segment.text === "struct" && segment.color));
  565. });
  566. test("falls back when Shiki cannot infer a language", async () => {
  567. const highlighted = await highlightShikiCodeLines({
  568. filePath: "notes.unknown-ext",
  569. lines: ["plain text"],
  570. mode: "dark",
  571. });
  572. assert.equal(highlighted, undefined);
  573. });
  574. test("builds split diff rows by pairing adjacent deletions and additions", () => {
  575. const rows = buildDiffRows([
  576. {
  577. lines: [" context", "-old a", "-old b", "+new a", " next"],
  578. newLines: 3,
  579. newStart: 10,
  580. oldLines: 4,
  581. oldStart: 10,
  582. },
  583. ]);
  584. const splitRows = buildSplitDiffRows(rows);
  585. assert.equal(splitRows.length, 4);
  586. assert.equal(splitRows[0]?.left?.content, "context");
  587. assert.equal(splitRows[1]?.left?.content, "old a");
  588. assert.equal(splitRows[1]?.right?.content, "new a");
  589. assert.equal(splitRows[2]?.left?.content, "old b");
  590. assert.equal(splitRows[2]?.right, undefined);
  591. });
  592. test("renders wide file diff with split view and no text separator", () => {
  593. const resultDisplay = formatFileDiffDisplay({
  594. additions: 1,
  595. deletions: 1,
  596. filePath: "packages/tui/src/app.tsx",
  597. kind: "file_diff",
  598. structuredPatch: [
  599. {
  600. lines: ["-old", "+new"],
  601. newLines: 1,
  602. newStart: 4,
  603. oldLines: 1,
  604. oldStart: 4,
  605. },
  606. ],
  607. });
  608. const view = ToolTranscriptPartView({
  609. part: {
  610. detailLines: [],
  611. resultDisplay,
  612. status: "completed",
  613. title: "Edit packages/tui/src/app.tsx",
  614. toolCallId: "call-1",
  615. toolName: "Edit",
  616. type: "tool",
  617. },
  618. terminalWidth: 140,
  619. });
  620. const lines = collectTextNodes(view);
  621. const [diffElement] = collectElementsByType(view, ShikiDiffView);
  622. assert.equal(diffElement?.props.view, "split");
  623. assert.equal(
  624. lines.some((line) => line.text.includes("|")),
  625. false,
  626. );
  627. });
  628. const baseSidebarState: SidebarState = {
  629. busy: false,
  630. contextUsage: {},
  631. draft: "",
  632. lastEvent: "idle",
  633. messageCount: 1,
  634. mcpStatus: {
  635. loading: false,
  636. servers: {},
  637. },
  638. mode: "build",
  639. model: "openai/gpt-test",
  640. modifiedFiles: [],
  641. networkRequests: [],
  642. status: "Ready.",
  643. statusDetails: [],
  644. thoughtLevel: "medium",
  645. todos: [],
  646. };
  647. function collectTextLines(node: unknown): string[] {
  648. const lines: string[] = [];
  649. const visit = (value: unknown) => {
  650. if (typeof value === "string") {
  651. lines.push(value);
  652. return;
  653. }
  654. if (Array.isArray(value)) {
  655. for (const child of value) visit(child);
  656. return;
  657. }
  658. if (typeof value === "object" && value !== null && "props" in value) {
  659. const element = value as { props?: { children?: unknown } };
  660. visit(element.props?.children);
  661. }
  662. };
  663. visit(node);
  664. return lines;
  665. }
  666. function collectTextNodes(node: unknown): Array<{ style: Record<string, unknown>; text: string }> {
  667. const lines: ReturnType<typeof collectTextNodes> = [];
  668. const visit = (value: unknown) => {
  669. if (Array.isArray(value)) {
  670. for (const child of value) visit(child);
  671. return;
  672. }
  673. if (typeof value !== "object" || value === null || !("props" in value)) return;
  674. const element = value as {
  675. props?: {
  676. children?: unknown;
  677. style?: Record<string, unknown>;
  678. };
  679. type?: unknown;
  680. };
  681. if (element.type === "text") {
  682. const text = collectTextLines(element.props?.children).join("");
  683. lines.push({ style: element.props?.style ?? {}, text });
  684. }
  685. visit(element.props?.children);
  686. };
  687. visit(node);
  688. return lines;
  689. }
  690. function collectElementsByType(
  691. node: unknown,
  692. type: unknown,
  693. ): Array<{ props: Record<string, unknown>; type?: unknown }> {
  694. const elements: ReturnType<typeof collectElementsByType> = [];
  695. const visit = (value: unknown) => {
  696. if (Array.isArray(value)) {
  697. for (const child of value) visit(child);
  698. return;
  699. }
  700. if (typeof value !== "object" || value === null || !("props" in value)) return;
  701. const element = value as {
  702. props?: {
  703. children?: unknown;
  704. } & Record<string, unknown>;
  705. type?: unknown;
  706. };
  707. if (element.type === type) {
  708. elements.push({ props: element.props ?? {}, type: element.type });
  709. }
  710. visit(element.props?.children);
  711. };
  712. visit(node);
  713. return elements;
  714. }
  715. function reactElementChildren(node: unknown): Array<{ type?: unknown }> {
  716. if (typeof node !== "object" || node === null || !("props" in node)) return [];
  717. const element = node as { props?: { children?: unknown } };
  718. const children = element.props?.children;
  719. if (children === undefined) return [];
  720. return (Array.isArray(children) ? children : [children]).filter(
  721. (child): child is { type?: unknown } => typeof child === "object" && child !== null,
  722. );
  723. }
  724. function reactElementStyle(node: unknown): Record<string, unknown> {
  725. assert.ok(typeof node === "object" && node !== null && "props" in node);
  726. const element = node as { props?: { style?: Record<string, unknown> } };
  727. return element.props?.style ?? {};
  728. }
  729. function createToolProjectionState(): {
  730. apply: (event: SessionEvent) => void;
  731. messages: Message[];
  732. } {
  733. const state: { messages: Message[] } = { messages: [] };
  734. const toolNamesById = new Map<string, string>();
  735. return {
  736. apply: (event) => {
  737. applyToolTranscriptEvent(event, {
  738. setMessages: (updater) => {
  739. state.messages = typeof updater === "function" ? updater(state.messages) : updater;
  740. },
  741. toolNamesById,
  742. });
  743. },
  744. get messages() {
  745. return state.messages;
  746. },
  747. };
  748. }
  749. function onlyToolPart(messages: Message[]): ToolTranscriptPart {
  750. const part = messages[0]?.parts?.[0];
  751. assert.equal(part?.type, "tool");
  752. return part;
  753. }
  754. function sessionEvent(type: SessionEventType, payload: unknown): SessionEvent {
  755. return {
  756. id: "event-1",
  757. payload,
  758. sequenceNumber: 1,
  759. sessionId: "session-1",
  760. timestamp: new Date(0),
  761. traceId: "trace-1",
  762. type,
  763. } as SessionEvent;
  764. }