tui-startup.test.ts 9.3 KB

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