tui-input.test.ts 12 KB

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