tui-startup.test.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import assert from "node:assert/strict";
  2. import { test } from "node:test";
  3. import { execFile } from "node:child_process";
  4. import { promisify } from "node:util";
  5. import { fileURLToPath } from "node:url";
  6. import React from "react";
  7. import { createTestRenderer } from "@mbears/opentui-core/testing";
  8. import { CliRenderEvents } from "@mbears/opentui-core";
  9. import type { UiThemeMode } from "@zcode/contracts";
  10. import { runTuiWithRenderer } from "../../tui/src/tui.js";
  11. import { getActiveTuiThemeMode } from "../../tui/src/theme/state.js";
  12. import type { TuiOptions, TuiStartupOptions } from "../../tui/src/types.js";
  13. import { runTuiCommand } from "../src/tui-command.js";
  14. import type { RunDependencies } from "../src/cli-types.js";
  15. function deferred<T>() {
  16. let resolve!: (value: T) => void;
  17. let reject!: (error: unknown) => void;
  18. const promise = new Promise<T>((res, rej) => {
  19. resolve = res;
  20. reject = rej;
  21. });
  22. return { promise, resolve, reject };
  23. }
  24. const baseOptions: TuiOptions = {
  25. noColor: true,
  26. locale: "en-US",
  27. stdin: process.stdin,
  28. stdout: process.stdout,
  29. stderr: process.stderr,
  30. workspaceDirectory: "/test/workspace",
  31. submitPrompt: async () => ({ response: "" }),
  32. };
  33. async function terminalFixture(
  34. options: Partial<TuiOptions>,
  35. configure?: (terminal: Awaited<ReturnType<typeof createTestRenderer>>) => void,
  36. closeBeforePaint = false,
  37. ) {
  38. const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
  39. const previous = environment.IS_REACT_ACT_ENVIRONMENT;
  40. environment.IS_REACT_ACT_ENVIRONMENT = true;
  41. const terminal = await createTestRenderer({
  42. width: 110,
  43. height: 32,
  44. targetFps: 30,
  45. screenMode: "alternate-screen",
  46. useThread: false,
  47. });
  48. const theme = deferred<UiThemeMode>();
  49. terminal.renderer.waitForThemeMode = () => theme.promise;
  50. configure?.(terminal);
  51. let outcome!: Promise<number | Error>;
  52. await React.act(async () => {
  53. outcome = runTuiWithRenderer({ ...baseOptions, ...options }, terminal.renderer).catch(
  54. (error: Error) => error,
  55. );
  56. if (closeBeforePaint) terminal.renderer.destroy();
  57. });
  58. return {
  59. ...terminal,
  60. theme,
  61. outcome,
  62. async action(work: () => void | Promise<void>) {
  63. await React.act(async () => {
  64. await work();
  65. });
  66. if (!terminal.renderer.isDestroyed) {
  67. await React.act(async () => {
  68. await terminal.renderOnce();
  69. });
  70. }
  71. },
  72. async close() {
  73. await React.act(async () => {
  74. theme.resolve("dark");
  75. if (!terminal.renderer.isDestroyed) terminal.renderer.destroy();
  76. });
  77. await outcome;
  78. environment.IS_REACT_ACT_ENVIRONMENT = previous;
  79. },
  80. };
  81. }
  82. test("native first paint precedes initialization and theme detection; ready options reach the app", async () => {
  83. const startup = deferred<TuiStartupOptions>();
  84. let frameAtStartup = "";
  85. let capture = () => "";
  86. let calls = 0;
  87. const terminal = await terminalFixture(
  88. {
  89. loadStartupOptions: () => {
  90. calls += 1;
  91. frameAtStartup = capture();
  92. return startup.promise;
  93. },
  94. },
  95. (created) => {
  96. capture = created.captureCharFrame;
  97. },
  98. );
  99. try {
  100. await terminal.action(() => terminal.renderOnce());
  101. assert.equal(calls, 1);
  102. assert.match(frameAtStartup, /Starting ZCode/);
  103. assert.match(terminal.captureCharFrame(), /\/test\/workspace/);
  104. assert.doesNotMatch(terminal.captureCharFrame(), /Type a prompt/);
  105. await terminal.action(() =>
  106. startup.resolve({
  107. initialModel: "personal/startup-model",
  108. initialThoughtLevel: "high",
  109. initialMode: "plan",
  110. theme: "dark",
  111. loginRequired: false,
  112. slashCommands: [
  113. { name: "startup-command", summary: "Loaded command", usage: "/startup-command" },
  114. ],
  115. }),
  116. );
  117. assert.doesNotMatch(terminal.captureCharFrame(), /Starting ZCode/);
  118. assert.match(terminal.captureCharFrame(), /startup-model/);
  119. assert.match(terminal.captureCharFrame(), /personal \| high/);
  120. await terminal.action(() => terminal.mockInput.typeText("/startup"));
  121. assert.match(terminal.captureCharFrame(), /startup-command/);
  122. await terminal.action(() => terminal.theme.resolve("light"));
  123. assert.equal(
  124. getActiveTuiThemeMode(),
  125. "dark",
  126. "late terminal detection preserves explicit theme",
  127. );
  128. assert.equal(calls, 1);
  129. } finally {
  130. await terminal.close();
  131. }
  132. });
  133. test("Ctrl+C closes the startup screen and ignores late completion", async () => {
  134. const startup = deferred<TuiStartupOptions>();
  135. let appQueries = 0;
  136. const terminal = await terminalFixture({
  137. loadStartupOptions: () => startup.promise,
  138. listMcpServers: async () => {
  139. appQueries += 1;
  140. return {};
  141. },
  142. });
  143. try {
  144. await terminal.action(() => terminal.renderOnce());
  145. await terminal.action(() => terminal.mockInput.pressCtrlC());
  146. assert.equal(await terminal.outcome, 130);
  147. await terminal.action(() => startup.resolve({ initialModel: "late/model" }));
  148. assert.equal(appQueries, 0);
  149. assert.equal(terminal.renderer.listenerCount(CliRenderEvents.FRAME), 0);
  150. } finally {
  151. await terminal.close();
  152. }
  153. });
  154. test("fatal startup errors restore the terminal and propagate the original failure", async () => {
  155. const startup = deferred<TuiStartupOptions>();
  156. const terminal = await terminalFixture({ loadStartupOptions: () => startup.promise });
  157. const failure = new Error("Storage migration failed");
  158. failure.name = "SqliteSessionMigrationError";
  159. try {
  160. await terminal.action(() => terminal.renderOnce());
  161. await terminal.action(() => startup.reject(failure));
  162. assert.equal(await terminal.outcome, failure);
  163. assert.equal(terminal.renderer.isDestroyed, true);
  164. } finally {
  165. await terminal.close();
  166. }
  167. });
  168. test("closing before the first paint never starts runtime initialization", async () => {
  169. let calls = 0;
  170. const terminal = await terminalFixture(
  171. {
  172. loadStartupOptions: async () => {
  173. calls += 1;
  174. return {};
  175. },
  176. },
  177. undefined,
  178. true,
  179. );
  180. await terminal.close();
  181. assert.equal(calls, 0);
  182. });
  183. test("CLI defers initialization to the renderer and discovers commands and Git concurrently", async () => {
  184. const created = deferred<unknown>();
  185. const observed: string[] = [];
  186. let closed = 0;
  187. const app = {
  188. getModel: () => "personal/ready",
  189. getThoughtLevel: () => "high",
  190. getLocale: () => "en-US",
  191. getTheme: () => "dark",
  192. listModels: () => [],
  193. listThoughtLevels: () => ["high"],
  194. close: async () => {
  195. closed += 1;
  196. },
  197. };
  198. const deps = {
  199. env: {},
  200. cwd: () => process.cwd(),
  201. skipUserConfig: true,
  202. loadDotenv: () => ({ keys: [], loaded: false, path: "" }),
  203. createZCodeApp: async () => {
  204. observed.push("app");
  205. return created.promise;
  206. },
  207. startProcessProviderRegistryRuntime: async () => ({
  208. runtime: { registryService: {} },
  209. dispose() {},
  210. }),
  211. resolveWorkspaceGitBranch: async () => {
  212. observed.push("git");
  213. return "test-branch";
  214. },
  215. listCustomCommands: async () => {
  216. observed.push("commands");
  217. return { commands: [], diagnostics: [], totalDiscovered: 0 };
  218. },
  219. runTui: async (options: TuiOptions) => {
  220. assert.deepEqual(observed, []);
  221. const ready = options.loadStartupOptions!();
  222. assert.ok(observed.includes("commands"));
  223. assert.ok(observed.includes("git"));
  224. created.resolve(app);
  225. const startup = await ready;
  226. assert.equal(startup.initialModel, "personal/ready");
  227. assert.equal(startup.initialThoughtLevel, "high");
  228. assert.equal(startup.workspaceGitBranch, "test-branch");
  229. assert.equal(startup.theme, "dark");
  230. return 0;
  231. },
  232. } as unknown as RunDependencies;
  233. assert.equal(
  234. await runTuiCommand(
  235. { argv: [], stdin: process.stdin, stdout: process.stdout, stderr: process.stderr },
  236. { noColor: true, force: false, json: false, verbose: false, locale: "en-US" },
  237. deps,
  238. "test",
  239. ),
  240. 0,
  241. );
  242. assert.equal(observed.filter((entry) => entry === "app").length, 1);
  243. assert.equal(closed, 1);
  244. });
  245. test("built TUI loads in plain Node without a TypeScript loader", async () => {
  246. const entry = new URL("../../tui/dist/index.js", import.meta.url);
  247. const { stdout } = await promisify(execFile)(
  248. process.execPath,
  249. [
  250. "--input-type=module",
  251. "-e",
  252. `const tui = await import(${JSON.stringify(entry.href)}); console.log(typeof tui.runTui);`,
  253. ],
  254. {
  255. cwd: fileURLToPath(new URL("../../tui", import.meta.url)),
  256. env: { ...process.env, NODE_OPTIONS: "" },
  257. },
  258. );
  259. assert.equal(stdout.trim(), "function");
  260. });