custom-status-command.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import { spawn } from 'node:child_process';
  2. import { win32 } from 'node:path';
  3. import type { TuiCustomStatusLineConfig } from '@mavis/config';
  4. import { parseTuiExternalEditorCommand } from './external-editor.js';
  5. export type { TuiCustomStatusLineConfig } from '@mavis/config';
  6. /**
  7. * Custom status command runner.
  8. *
  9. * Executes the user-configured `tui.customStatusLine.command` and surfaces the
  10. * bounded stdout as the `custom-command` inline item or multiline block. The command is
  11. * a user-owned integration point (environment, build status, usage probes, …), so the
  12. * runner is deliberately defensive:
  13. *
  14. * - It only exists when `tui.statusLine` names `custom-command` without
  15. * `build-mode`; the owner enforces that gate before construction, so a
  16. * build-mode TUI never spawns the command at all.
  17. * - One run in flight at a time. Triggers that arrive while a run is active
  18. * collapse into a single trailing rerun (latest event wins), so a slow
  19. * command can never queue unbounded work.
  20. * - A failed or timed-out run reports nothing: the owner keeps the last
  21. * successful text instead of flickering the item.
  22. *
  23. * Stdin carries a small JSON payload describing why the run happened; the
  24. * field names are snake_case to match common external statusline protocols.
  25. */
  26. export const TUI_CUSTOM_STATUS_PROTOCOL_VERSION = 1;
  27. const DEFAULT_TIMEOUT_MS = 5_000;
  28. const MIN_TIMEOUT_MS = 500;
  29. const MAX_TIMEOUT_MS = 30_000;
  30. const MIN_INTERVAL_SECONDS = 10;
  31. /** Stdout beyond this UTF-16 code-unit budget is discarded before rendering. */
  32. const MAX_STDOUT_LENGTH = 8 * 1024;
  33. export type TuiCustomStatusEvent =
  34. | 'startup'
  35. | 'turn-end'
  36. | 'session-change'
  37. | 'workspace-change'
  38. | 'interval';
  39. /** Facts about the active Session at the moment a run starts. */
  40. export interface TuiCustomStatusContext {
  41. readonly sessionId?: string;
  42. readonly workspaceDir: string;
  43. readonly model?: string;
  44. readonly sessionTitle?: string;
  45. }
  46. export interface TuiCustomStatusProcessInvocation {
  47. readonly executable: string;
  48. readonly args: readonly string[];
  49. readonly cwd: string;
  50. readonly shell: boolean;
  51. /** JSON payload written to the child's stdin before it is closed. */
  52. readonly stdin: string;
  53. readonly timeoutMs: number;
  54. }
  55. export interface TuiCustomStatusProcessResult {
  56. readonly exitCode: number | null;
  57. readonly stdout: string;
  58. readonly timedOut: boolean;
  59. }
  60. export type TuiCustomStatusProcessRunner = (
  61. invocation: TuiCustomStatusProcessInvocation,
  62. ) => Promise<TuiCustomStatusProcessResult>;
  63. export interface CreateTuiCustomStatusCommandRunnerOptions {
  64. readonly config: TuiCustomStatusLineConfig;
  65. /** TUI version reported to the command as `tui_version`. */
  66. readonly version: string;
  67. /** Snapshot provider; read at run start so interval runs see fresh facts. */
  68. readonly getContext: () => TuiCustomStatusContext;
  69. /** Called with bounded stdout (the first line in inline display) after a successful run. */
  70. readonly onText: (text: string) => void;
  71. readonly platform?: NodeJS.Platform;
  72. readonly runProcess?: TuiCustomStatusProcessRunner;
  73. }
  74. export class TuiCustomStatusCommandRunner {
  75. private readonly parsed: { executable: string; args: readonly string[] } | undefined;
  76. private readonly timeoutMs: number;
  77. private readonly intervalMs: number;
  78. private readonly shell: boolean;
  79. private readonly runProcess: TuiCustomStatusProcessRunner;
  80. private intervalTimer: ReturnType<typeof setInterval> | undefined;
  81. private running = false;
  82. private trailing: TuiCustomStatusEvent | undefined;
  83. private disposed = false;
  84. private paused = false;
  85. private contextGeneration = 0;
  86. constructor(private readonly options: CreateTuiCustomStatusCommandRunnerOptions) {
  87. this.parsed = parseCustomStatusCommand(options.config.command);
  88. this.timeoutMs = normalizeTimeoutMs(options.config.timeoutMs);
  89. this.intervalMs = normalizeIntervalMs(options.config.intervalSeconds);
  90. // Same Windows path as the external editor: an async shell child keeps
  91. // console handling out of the TUI's raw-mode input loop.
  92. this.shell = (options.platform ?? process.platform) === 'win32';
  93. this.runProcess = options.runProcess ?? runCustomStatusProcess;
  94. }
  95. /** Runs the startup refresh and arms the optional interval timer. */
  96. start(): void {
  97. if (this.disposed || this.paused || !this.parsed) return;
  98. this.trigger('startup');
  99. if (this.intervalMs > 0) {
  100. this.intervalTimer = setInterval(() => this.trigger('interval'), this.intervalMs);
  101. this.intervalTimer.unref?.();
  102. }
  103. }
  104. /**
  105. * Requests a refresh for `event`. Coalesces while a run is in flight: the
  106. * latest trigger becomes one trailing rerun after the active run settles.
  107. */
  108. trigger(event: TuiCustomStatusEvent): void {
  109. if (this.disposed || this.paused || !this.parsed) return;
  110. if (event === 'session-change' || event === 'workspace-change') this.contextGeneration += 1;
  111. if (this.running) {
  112. this.trailing = event;
  113. return;
  114. }
  115. void this.run(event);
  116. }
  117. dispose(): void {
  118. this.disposed = true;
  119. this.pause();
  120. }
  121. /** Disable future work without losing the in-flight process serialization guard. */
  122. pause(): void {
  123. if (this.paused) return;
  124. this.paused = true;
  125. this.contextGeneration += 1;
  126. this.trailing = undefined;
  127. if (this.intervalTimer) clearInterval(this.intervalTimer);
  128. this.intervalTimer = undefined;
  129. }
  130. resume(): void {
  131. if (!this.paused || this.disposed) return;
  132. this.paused = false;
  133. this.start();
  134. }
  135. private async run(event: TuiCustomStatusEvent): Promise<void> {
  136. if (!this.parsed) return;
  137. this.running = true;
  138. const contextGeneration = this.contextGeneration;
  139. try {
  140. const context = this.options.getContext();
  141. const result = await this.runProcess({
  142. executable: this.parsed.executable,
  143. args: this.parsed.args,
  144. cwd: context.workspaceDir,
  145. shell: this.shell,
  146. stdin: buildCustomStatusPayload(event, context, this.options.version),
  147. timeoutMs: this.timeoutMs,
  148. });
  149. if (this.disposed || contextGeneration !== this.contextGeneration) return;
  150. if (!result.timedOut && result.exitCode === 0) {
  151. this.options.onText(
  152. extractCustomStatusText(result.stdout, this.options.config.display === 'block'),
  153. );
  154. }
  155. } catch {
  156. // A crashing or unspawnable command keeps the last successful text.
  157. } finally {
  158. this.running = false;
  159. const next = this.trailing;
  160. this.trailing = undefined;
  161. if (next !== undefined && !this.disposed && !this.paused) void this.run(next);
  162. }
  163. }
  164. }
  165. /**
  166. * Creates the runner only when every gate holds: `custom-command` is actually
  167. * configured to render, `build-mode` does not own the line, and a command
  168. * exists. Returns `undefined` otherwise so callers get the zero-spawn
  169. * guarantee for free.
  170. */
  171. export function createTuiCustomStatusCommandRunner(
  172. statusLineItems: readonly string[] | undefined,
  173. options: CreateTuiCustomStatusCommandRunnerOptions,
  174. ): TuiCustomStatusCommandRunner | undefined {
  175. if (!statusLineItems?.includes('custom-command')) return undefined;
  176. if (statusLineItems.includes('build-mode')) return undefined;
  177. if (!options.config.command?.trim()) return undefined;
  178. return new TuiCustomStatusCommandRunner(options);
  179. }
  180. function parseCustomStatusCommand(
  181. command: string | undefined,
  182. ): { executable: string; args: readonly string[] } | undefined {
  183. if (!command?.trim()) return undefined;
  184. try {
  185. return parseTuiExternalEditorCommand(command);
  186. } catch {
  187. // A malformed command (unbalanced quote, …) disables the item instead of
  188. // failing TUI startup.
  189. return undefined;
  190. }
  191. }
  192. function buildCustomStatusPayload(
  193. event: TuiCustomStatusEvent,
  194. context: TuiCustomStatusContext,
  195. version: string,
  196. ): string {
  197. return `${JSON.stringify({
  198. protocol: TUI_CUSTOM_STATUS_PROTOCOL_VERSION,
  199. event,
  200. ...(context.sessionId ? { session_id: context.sessionId } : {}),
  201. workspace_dir: context.workspaceDir,
  202. ...(context.model ? { model: context.model } : {}),
  203. ...(context.sessionTitle ? { session_title: context.sessionTitle } : {}),
  204. tui_version: version,
  205. })}\n`;
  206. }
  207. /** Preserve bounded stdout for block display; sanitization happens at render time. */
  208. function extractCustomStatusText(stdout: string, block: boolean): string {
  209. const bounded = stdout.slice(0, MAX_STDOUT_LENGTH);
  210. if (block) return bounded;
  211. const firstLine = bounded.split(/\r?\n/u, 1)[0] ?? '';
  212. return firstLine.trim();
  213. }
  214. function normalizeTimeoutMs(value: number | undefined): number {
  215. if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_TIMEOUT_MS;
  216. return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, Math.floor(value)));
  217. }
  218. function normalizeIntervalMs(value: number | undefined): number {
  219. if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return 0;
  220. return Math.max(MIN_INTERVAL_SECONDS, Math.floor(value)) * 1_000;
  221. }
  222. function runCustomStatusProcess(
  223. invocation: TuiCustomStatusProcessInvocation,
  224. ): Promise<TuiCustomStatusProcessResult> {
  225. return new Promise((resolve) => {
  226. let stdout = '';
  227. let timedOut = false;
  228. let settled = false;
  229. let timer: ReturnType<typeof setTimeout> | undefined;
  230. let child: ReturnType<typeof spawn> | undefined;
  231. const settle = (result: TuiCustomStatusProcessResult) => {
  232. if (settled) return;
  233. settled = true;
  234. if (timer) clearTimeout(timer);
  235. child?.stdin?.destroy();
  236. child?.stdout?.destroy();
  237. resolve(result);
  238. };
  239. try {
  240. child = spawn(invocation.executable, [...invocation.args], {
  241. cwd: invocation.cwd,
  242. shell: invocation.shell,
  243. stdio: ['pipe', 'pipe', 'ignore'],
  244. windowsHide: true,
  245. detached: process.platform !== 'win32',
  246. });
  247. } catch {
  248. settle({ exitCode: null, stdout: '', timedOut: false });
  249. return;
  250. }
  251. timer = setTimeout(() => {
  252. timedOut = true;
  253. if (child) terminateCustomStatusProcess(child);
  254. // A descendant may hold stdout open even after the command exits. Never
  255. // depend on close to release the runner's single in-flight slot.
  256. settle({ exitCode: null, stdout, timedOut: true });
  257. }, invocation.timeoutMs);
  258. timer.unref?.();
  259. child.once('error', () => settle({ exitCode: null, stdout: '', timedOut }));
  260. child.stdout?.setEncoding('utf8');
  261. child.stdout?.on('data', (chunk: string) => {
  262. if (stdout.length >= MAX_STDOUT_LENGTH) return;
  263. stdout += chunk.slice(0, MAX_STDOUT_LENGTH - stdout.length);
  264. });
  265. // The command may exit without reading stdin; ignore the EPIPE.
  266. child.stdin?.on('error', () => {});
  267. child.stdin?.end(invocation.stdin);
  268. child.once('close', (exitCode) => settle({ exitCode, stdout, timedOut }));
  269. });
  270. }
  271. function terminateCustomStatusProcess(child: ReturnType<typeof spawn>): void {
  272. const killRoot = () => {
  273. try {
  274. child.kill('SIGKILL');
  275. } catch {
  276. // The command may already have exited.
  277. }
  278. };
  279. if (!child.pid) return killRoot();
  280. try {
  281. if (process.platform !== 'win32') {
  282. process.kill(-child.pid, 'SIGKILL');
  283. return;
  284. }
  285. const root = process.env.SystemRoot ?? process.env.WINDIR;
  286. const taskkill = root ? win32.join(root, 'System32', 'taskkill.exe') : 'taskkill.exe';
  287. const killer = spawn(taskkill, ['/PID', String(child.pid), '/T', '/F'], {
  288. windowsHide: true,
  289. stdio: 'ignore',
  290. });
  291. killer.once('error', killRoot);
  292. killer.once('close', (code) => {
  293. if (code !== 0) killRoot();
  294. });
  295. killer.unref();
  296. } catch {
  297. killRoot();
  298. }
  299. }