tui-input.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import React, { act } from "react";
  4. import { testRender } from "@mbears/opentui-react/test-utils";
  5. import { getZCodeCopy } from "@zcode/i18n";
  6. import { shouldHandleInputHistoryNavigation } from "../src/app-keyboard.js";
  7. import {
  8. InputPane,
  9. INPUT_DEFAULT_EDITOR_ROWS,
  10. INPUT_PANE_BORDER,
  11. INPUT_PANE_MAX_HEIGHT,
  12. INPUT_PANE_MIN_HEIGHT,
  13. INPUT_PANE_STATUS_ROWS,
  14. INPUT_PANE_STATUS_SPACER_STYLE,
  15. INPUT_MAX_EDITOR_ROWS,
  16. INPUT_MIN_EDITOR_ROWS,
  17. INPUT_PANE_BORDER_STYLE,
  18. PROMPT_TEXTAREA_KEY_BINDINGS,
  19. inputPaneContainerStyle,
  20. inputPaneEditorRows,
  21. inputPaneHeight,
  22. inputPanePlaceholder,
  23. inputPaneTextareaStyle,
  24. inputPaneTitle,
  25. syncTextareaValue,
  26. type PromptInputEditor,
  27. } from "../src/app-input-pane.js";
  28. import {
  29. InputActiveStatus,
  30. InputComposerStatus,
  31. inputActiveStatusRow,
  32. inputComposerStatusParts,
  33. inputComposerStatusRow,
  34. inputContextUsageBadge,
  35. } from "../src/app-input-status.js";
  36. import { SPINNER_FRAME_INTERVAL_MS, SPINNER_WIDTH, spinnerFrame } from "../src/app-motion.js";
  37. import { palette } from "../src/app-model.js";
  38. import { modelDisplayParts } from "../src/app-model-ref.js";
  39. const TEST_STATUS_PROPS = { model: "default-deepseek/deepseek-v4-pro", thoughtLevel: "max" };
  40. test("prompt textarea binds Enter to submit and Shift+Enter to newline", () => {
  41. assert.deepEqual(PROMPT_TEXTAREA_KEY_BINDINGS, [
  42. { name: "return", action: "submit" },
  43. { name: "linefeed", action: "submit" },
  44. { name: "return", shift: true, action: "newline" },
  45. { name: "linefeed", shift: true, action: "newline" },
  46. ]);
  47. assert.equal(INPUT_DEFAULT_EDITOR_ROWS, 2);
  48. assert.equal(INPUT_PANE_STATUS_ROWS, 1);
  49. assert.deepEqual(INPUT_PANE_STATUS_SPACER_STYLE, { flexGrow: 1, minHeight: 0 });
  50. assert.equal(INPUT_PANE_BORDER, true);
  51. });
  52. test("sizes prompt textarea from draft content up to six visible rows", () => {
  53. assert.equal(inputPaneEditorRows("", 40), INPUT_MIN_EDITOR_ROWS);
  54. assert.equal(inputPaneEditorRows("one\ntwo\nthree", 40), 3);
  55. assert.equal(inputPaneEditorRows("123456789 123456789 123456789", 10), 3);
  56. assert.equal(inputPaneEditorRows("1\n2\n3\n4\n5\n6\n7", 40), INPUT_MAX_EDITOR_ROWS);
  57. const maxContainerStyle = inputPaneContainerStyle(true, INPUT_MAX_EDITOR_ROWS);
  58. const maxTextareaStyle = inputPaneTextareaStyle(INPUT_MAX_EDITOR_ROWS);
  59. assert.equal(maxContainerStyle.height, inputPaneHeight(INPUT_MAX_EDITOR_ROWS));
  60. assert.equal(maxContainerStyle.height, INPUT_PANE_MAX_HEIGHT);
  61. assert.equal(maxTextareaStyle.height, INPUT_MAX_EDITOR_ROWS);
  62. assert.equal(maxTextareaStyle.maxHeight, INPUT_MAX_EDITOR_ROWS);
  63. assert.equal(maxTextareaStyle.minHeight, INPUT_MIN_EDITOR_ROWS);
  64. });
  65. test("uses a complete border for the prompt container", () => {
  66. const style = inputPaneContainerStyle(true);
  67. assert.equal(style.border, INPUT_PANE_BORDER);
  68. assert.equal(style.borderColor, "#7dd3fc");
  69. assert.equal(style.borderStyle, INPUT_PANE_BORDER_STYLE);
  70. assert.equal(style.height, INPUT_PANE_MIN_HEIGHT);
  71. });
  72. test("uses localized prompt title and placeholder copy", () => {
  73. const copy = getZCodeCopy("zh-CN").tui;
  74. assert.equal(inputPaneTitle(copy), " 输入 ");
  75. assert.equal(inputPaneTitle(copy, "yolo"), " Yolo ");
  76. assert.equal(inputPanePlaceholder(copy, false), "输入提示词");
  77. assert.equal(inputPanePlaceholder(copy, true), "输入内容会排队");
  78. assert.equal(copy.input.queuedTitle(2), " 队列(2) ");
  79. assert.equal(copy.input.queuedSubmitHint, "下一次工具调用后提交。");
  80. assert.equal(copy.input.queuedMore(3), "还有 3 条排队中");
  81. assert.equal(copy.input.activeStatusHint, "esc to interrupt");
  82. });
  83. test("projects the active status spinner as a braille spinner", () => {
  84. const firstFrame = "⠋";
  85. const secondFrame = "⠙";
  86. const thirdFrame = "⠹";
  87. assert.equal(Array.from(firstFrame).length, SPINNER_WIDTH);
  88. assert.equal(spinnerFrame(0), firstFrame);
  89. assert.equal(spinnerFrame(SPINNER_FRAME_INTERVAL_MS), secondFrame);
  90. assert.equal(spinnerFrame(SPINNER_FRAME_INTERVAL_MS * 2), thirdFrame);
  91. });
  92. test("splits model refs consistently for composer and sidebar status", () => {
  93. assert.deepEqual(modelDisplayParts("default-deepseek/deepseek-v4-pro"), {
  94. model: "deepseek-v4-pro",
  95. provider: "default-deepseek",
  96. });
  97. assert.deepEqual(modelDisplayParts("gateway/openai/gpt-5.5"), {
  98. model: "openai/gpt-5.5",
  99. provider: "gateway",
  100. });
  101. assert.deepEqual(inputComposerStatusParts("glm-4.6", "max"), {
  102. model: "glm-4.6",
  103. provider: "-",
  104. thought: "max",
  105. });
  106. });
  107. test("renders model, muted provider, and thought in the composer status row", () => {
  108. const nodes = collectTextNodes(
  109. inputComposerStatusRow({
  110. model: "default-deepseek/deepseek-v4-pro",
  111. thoughtLevel: "max",
  112. }),
  113. );
  114. assert.equal(nodes.map((node) => node.text).join(""), "deepseek-v4-pro default-deepseek | max");
  115. assert.deepEqual(nodes.find((node) => node.text === "deepseek-v4-pro")?.style, {
  116. fg: palette.text,
  117. flexShrink: 1,
  118. });
  119. assert.deepEqual(nodes.find((node) => node.text === " default-deepseek | ")?.style, {
  120. fg: palette.muted,
  121. });
  122. assert.deepEqual(nodes.find((node) => node.text === "max")?.style, {
  123. fg: palette.warning,
  124. flexShrink: 0,
  125. });
  126. });
  127. test("renders the shared composer status row while idle", () => {
  128. const text = collectTextNodes(
  129. InputComposerStatus({
  130. model: "default-deepseek/deepseek-v4-pro",
  131. thoughtLevel: "max",
  132. }),
  133. )
  134. .map((node) => node.text)
  135. .join("");
  136. assert.equal(text, "deepseek-v4-pro default-deepseek | max");
  137. });
  138. test("formats and renders the active status context meter on the right", () => {
  139. const copy = getZCodeCopy("en-US").tui;
  140. const contextUsage = { contextUsed: 24_100, contextWindow: 1_000_000 };
  141. const row = inputActiveStatusRow(copy, undefined, {
  142. contentWidth: 80,
  143. contextUsage,
  144. });
  145. const nodes = collectTextNodes(row);
  146. assert.equal(inputContextUsageBadge(contextUsage), "24.1K (2%)");
  147. assert.equal(inputContextUsageBadge({ contextUsed: 999 }), "999");
  148. assert.equal(
  149. inputContextUsageBadge({ contextUsed: 2_000_000, contextWindow: 10_000_000 }),
  150. "2M (20%)",
  151. );
  152. assert.equal(inputContextUsageBadge({ contextWindow: 1_000_000 }), undefined);
  153. assert.equal(nodes.at(-1)?.text, "24.1K (2%)");
  154. assert.deepEqual(nodes.at(-1)?.style, {
  155. fg: palette.muted,
  156. flexShrink: 0,
  157. });
  158. assert.ok(
  159. collectElementStyles(row).some((style) => style?.flexGrow === 1 && style.minWidth === 1),
  160. );
  161. });
  162. test("reserves one active status row while idle and empty", () => {
  163. const copy = getZCodeCopy("en-US").tui;
  164. const row = InputActiveStatus({ active: false, copy });
  165. assert.deepEqual(collectTextNodes(row), []);
  166. assert.ok(collectElementStyles(row).some((style) => style?.height === 1));
  167. });
  168. test("renders the active status outside the composer status row while busy", () => {
  169. const copy = getZCodeCopy("en-US").tui;
  170. const frame = spinnerFrame(0);
  171. const contextUsage = { contextUsed: 11_100, contextWindow: 185_000 };
  172. const activeNodes = collectTextNodes(inputActiveStatusRow(copy, frame, { contextUsage }));
  173. const composerText = collectTextNodes(
  174. InputComposerStatus({
  175. model: "default-deepseek/deepseek-v4-pro",
  176. thoughtLevel: "max",
  177. }),
  178. )
  179. .map((node) => node.text)
  180. .join("");
  181. assert.equal(
  182. activeNodes.map((node) => node.text).join(""),
  183. `${frame} esc to interrupt11.1K (6%)`,
  184. );
  185. assert.equal(composerText, "deepseek-v4-pro default-deepseek | max");
  186. assert.equal(
  187. collectTextNodes(InputActiveStatus({ active: false, contextUsage, copy })!).at(-1)?.text,
  188. "11.1K (6%)",
  189. );
  190. assert.deepEqual(activeNodes.find((node) => node.text === frame)?.style, {
  191. fg: palette.accent,
  192. flexShrink: 0,
  193. width: SPINNER_WIDTH,
  194. });
  195. });
  196. test("syncs external draft replacement into the textarea buffer", () => {
  197. let plainText = "old draft";
  198. let cursorMoved = 0;
  199. const changed = syncTextareaValue(
  200. {
  201. get plainText() {
  202. return plainText;
  203. },
  204. gotoBufferEnd: () => {
  205. cursorMoved += 1;
  206. },
  207. setText: (value) => {
  208. plainText = value;
  209. },
  210. },
  211. "new draft",
  212. );
  213. assert.equal(changed, true);
  214. assert.equal(plainText, "new draft");
  215. assert.equal(cursorMoved, 1);
  216. });
  217. test("does not resync an unchanged textarea draft", () => {
  218. const changed = syncTextareaValue(
  219. {
  220. plainText: "same draft",
  221. gotoBufferEnd: () => {
  222. throw new Error("cursor should not move when the draft is unchanged");
  223. },
  224. setText: () => {
  225. throw new Error("text should not be reset when the draft is unchanged");
  226. },
  227. },
  228. "same draft",
  229. );
  230. assert.equal(changed, false);
  231. });
  232. test("captures history navigation only when the editor is not actively drafting", () => {
  233. assert.equal(
  234. shouldHandleInputHistoryNavigation({
  235. draftValue: "",
  236. inputHistoryActive: false,
  237. }),
  238. true,
  239. );
  240. assert.equal(
  241. shouldHandleInputHistoryNavigation({
  242. draftValue: "line one\nline two",
  243. inputHistoryActive: false,
  244. }),
  245. false,
  246. );
  247. assert.equal(
  248. shouldHandleInputHistoryNavigation({
  249. draftValue: "recalled draft",
  250. inputHistoryActive: true,
  251. }),
  252. true,
  253. );
  254. });
  255. test("Shift+Enter inserts a newline while Enter submits the textarea draft", async () => {
  256. const inputs: string[] = [];
  257. const submitted: string[] = [];
  258. let view: Awaited<ReturnType<typeof testRender>> | undefined;
  259. await act(async () => {
  260. view = await testRender(
  261. React.createElement(InputPane, {
  262. busy: false,
  263. focused: true,
  264. ...TEST_STATUS_PROPS,
  265. onInput: (value) => {
  266. inputs.push(value);
  267. },
  268. onSubmit: (value) => {
  269. submitted.push(value);
  270. },
  271. resetCursorToEndVersion: 0,
  272. value: "",
  273. }),
  274. {
  275. height: 12,
  276. kittyKeyboard: true,
  277. otherModifiersMode: true,
  278. width: 50,
  279. },
  280. );
  281. await view.renderOnce();
  282. });
  283. try {
  284. await act(async () => {
  285. assert.ok(view);
  286. await view.mockInput.typeText("hello");
  287. view.mockInput.pressEnter({ shift: true });
  288. await view.mockInput.typeText("world");
  289. view.mockInput.pressEnter();
  290. await view.renderOnce();
  291. });
  292. assert.equal(inputs.at(-1), "hello\nworld");
  293. assert.deepEqual(submitted, ["hello\nworld"]);
  294. } finally {
  295. await act(async () => {
  296. view?.renderer.destroy();
  297. });
  298. }
  299. });
  300. test("keeps the shared prompt editor ref live after title updates", async () => {
  301. const editorRef = { current: null } as React.MutableRefObject<PromptInputEditor | null>;
  302. let setMode: React.Dispatch<React.SetStateAction<string>> | undefined;
  303. let view: Awaited<ReturnType<typeof testRender>> | undefined;
  304. function Harness(): React.ReactElement {
  305. const [mode, applyMode] = React.useState("build");
  306. setMode = applyMode;
  307. return React.createElement(InputPane, {
  308. busy: false,
  309. editorRef,
  310. focused: true,
  311. mode,
  312. ...TEST_STATUS_PROPS,
  313. onInput: () => undefined,
  314. onSubmit: () => undefined,
  315. resetCursorToEndVersion: 0,
  316. value: "",
  317. });
  318. }
  319. await act(async () => {
  320. view = await testRender(React.createElement(Harness), {
  321. height: 12,
  322. kittyKeyboard: true,
  323. otherModifiersMode: true,
  324. width: 50,
  325. });
  326. await view.renderOnce();
  327. });
  328. try {
  329. assert.ok(editorRef.current);
  330. assert.ok(setMode);
  331. await act(async () => {
  332. setMode?.("yolo");
  333. await view?.renderOnce();
  334. });
  335. assert.doesNotThrow(() => editorRef.current?.cursorOffset);
  336. } finally {
  337. await act(async () => {
  338. view?.renderer.destroy();
  339. });
  340. }
  341. });
  342. function collectElementStyles(node: unknown): Array<Record<string, unknown> | undefined> {
  343. if (Array.isArray(node)) return node.flatMap(collectElementStyles);
  344. if (typeof node !== "object" || node === null || !("props" in node)) return [];
  345. const element = node as { props?: { children?: unknown; style?: unknown } };
  346. const style = element.props?.style;
  347. const styleValue =
  348. style !== null && typeof style === "object" ? (style as Record<string, unknown>) : undefined;
  349. return [styleValue, ...collectElementStyles(element.props?.children)];
  350. }
  351. function collectTextNodes(node: unknown): Array<{ style?: unknown; text: string }> {
  352. if (Array.isArray(node)) return node.flatMap(collectTextNodes);
  353. if (typeof node !== "object" || node === null || !("props" in node)) return [];
  354. const element = node as { props?: { children?: unknown; style?: unknown }; type?: unknown };
  355. const children = element.props?.children;
  356. const current =
  357. element.type === "text" && typeof children === "string"
  358. ? [{ style: element.props?.style, text: children }]
  359. : [];
  360. return [...current, ...collectTextNodes(children)];
  361. }