tui.unit.test.ts 23 KB

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