tui-workspace-status-line.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import { describe, expect, it, vi } from 'vitest';
  2. import type {
  3. TuiCustomStatusLineConfig,
  4. TuiCustomStatusProcessInvocation,
  5. TuiCustomStatusProcessResult,
  6. } from '../../src/host/custom-status-command.js';
  7. import type { TuiWorkspaceGitMetadata } from '../../src/runtime/port.js';
  8. import {
  9. TuiWorkspaceStatusLine,
  10. createTuiWorkspaceStatusLine,
  11. } from '../../src/tui/shell/workspace-status-line.js';
  12. describe('TuiWorkspaceStatusLine', () => {
  13. it('starts and stops Git refreshes with the selected dependencies, including late results', async () => {
  14. vi.useFakeTimers();
  15. const resolvers: Array<(metadata: TuiWorkspaceGitMetadata) => void> = [];
  16. const runtime = { getWorkspaceGitMetadata: vi.fn(() => new Promise<TuiWorkspaceGitMetadata>((resolve) => { resolvers.push(resolve); })) };
  17. const state = { version: '0.1', workspace: '/repo', runtimeStatus: 'ready' as const };
  18. const status = new TuiWorkspaceStatusLine({ ...state, statusLineItems: ['model'] }, runtime, vi.fn());
  19. try {
  20. status.preview(['git-branch'], 80, 3);
  21. await vi.advanceTimersByTimeAsync(20_000);
  22. expect(runtime.getWorkspaceGitMetadata).not.toHaveBeenCalled();
  23. status.setConfiguredItems(['git-branch']);
  24. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledTimes(1);
  25. status.setConfiguredItems([]);
  26. resolvers[0]?.({ isGitRepo: true, branch: 'stale', detached: false, isWorktree: false });
  27. await vi.advanceTimersByTimeAsync(20_000);
  28. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledTimes(1);
  29. expect(status.render(80)).toEqual([]);
  30. status.setState({ ...state, workspace: '/other', busy: true });
  31. status.setState({ ...state, workspace: '/other', busy: false });
  32. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledTimes(1);
  33. status.setConfiguredItems(['review-link']);
  34. expect(runtime.getWorkspaceGitMetadata).toHaveBeenLastCalledWith('/other');
  35. expect(status.preview(['git-branch'], 80, 3).lines.join('')).not.toContain('stale');
  36. await vi.advanceTimersByTimeAsync(10_000);
  37. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledTimes(3);
  38. status.dispose();
  39. await vi.advanceTimersByTimeAsync(20_000);
  40. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledTimes(3);
  41. } finally { status.dispose(); vi.useRealTimers(); }
  42. });
  43. it('applies an empty selection across projections and restores adaptive default context behavior', () => {
  44. const runtime = { getWorkspaceGitMetadata: vi.fn(async () => ({ isGitRepo: false, branch: '', detached: false, isWorktree: false })) };
  45. const state = { version: '0.1', workspace: '/repo', runtimeStatus: 'ready' as const, contextUsage: { usedTokens: 20, contextWindowTokens: 100 } };
  46. const status = new TuiWorkspaceStatusLine(state, runtime, vi.fn());
  47. try {
  48. status.setConfiguredItems([]);
  49. status.setState(state);
  50. expect(status.render(80)).toEqual([]);
  51. status.setConfiguredItems(['context-remaining']);
  52. const explicit = status.render(80).join('');
  53. expect(explicit).toContain('80%');
  54. status.setConfiguredItems(undefined);
  55. status.setState(state);
  56. expect(status.getConfiguredItems()).toBeUndefined();
  57. const restored = status.render(80).join('');
  58. expect(restored).toContain('80%');
  59. expect(restored).not.toContain('Context 100');
  60. expect(restored).toContain('/repo');
  61. } finally { status.dispose(); }
  62. });
  63. it('rejects changing machine mode in either direction', () => {
  64. const runtime = { getWorkspaceGitMetadata: vi.fn(async () => ({ isGitRepo: false, branch: '', detached: false, isWorktree: false })) };
  65. for (const items of [[], ['build-mode']] as const) {
  66. const status = new TuiWorkspaceStatusLine({ version: '0.1', workspace: '/repo', runtimeStatus: 'ready', statusLineItems: items }, runtime, vi.fn());
  67. try {
  68. expect(() => status.setConfiguredItems(items.length ? [] : ['build-mode'])).toThrow('startup-only');
  69. expect(status.getConfiguredItems()).toEqual(items);
  70. } finally { status.dispose(); }
  71. }
  72. expect(runtime.getWorkspaceGitMetadata).not.toHaveBeenCalled();
  73. });
  74. it('clears stale Git metadata and refreshes immediately when the Session workspace changes', async () => {
  75. const resolvers: Array<(metadata: TuiWorkspaceGitMetadata) => void> = [];
  76. const runtime = {
  77. getWorkspaceGitMetadata: vi.fn(
  78. async () =>
  79. await new Promise<TuiWorkspaceGitMetadata>((resolve) => {
  80. resolvers.push(resolve);
  81. }),
  82. ),
  83. };
  84. const initialState = {
  85. version: '0.1.0',
  86. workspace: '/repo-a',
  87. runtimeStatus: 'ready' as const,
  88. };
  89. const status = new TuiWorkspaceStatusLine(initialState, runtime, vi.fn());
  90. try {
  91. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  92. resolvers[0]?.({
  93. isGitRepo: true,
  94. branch: 'repo-a-branch',
  95. detached: false,
  96. isWorktree: false,
  97. });
  98. await vi.waitFor(() => expect(status.render(120).join('\n')).toContain('repo-a-branch'));
  99. status.setState({ ...initialState, workspace: '/repo-b' });
  100. expect(status.render(120).join('\n')).not.toContain('repo-a-branch');
  101. await vi.waitFor(() => expect(resolvers).toHaveLength(2));
  102. expect(runtime.getWorkspaceGitMetadata).toHaveBeenLastCalledWith('/repo-b');
  103. } finally {
  104. status.dispose();
  105. }
  106. });
  107. it('does not let an older Git refresh replace newer branch metadata', async () => {
  108. const resolvers: Array<(metadata: TuiWorkspaceGitMetadata) => void> = [];
  109. const runtime = {
  110. getWorkspaceGitMetadata: vi.fn(
  111. async () =>
  112. await new Promise<TuiWorkspaceGitMetadata>((resolve) => {
  113. resolvers.push(resolve);
  114. }),
  115. ),
  116. };
  117. const initialState = {
  118. version: '0.1.0',
  119. workspace: '/workspace',
  120. runtimeStatus: 'ready' as const,
  121. busy: true,
  122. };
  123. const requestRender = vi.fn();
  124. const status = new TuiWorkspaceStatusLine(initialState, runtime, requestRender);
  125. try {
  126. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  127. status.setState({ ...initialState, busy: false });
  128. await vi.waitFor(() => expect(resolvers).toHaveLength(2));
  129. resolvers[1]?.({
  130. isGitRepo: true,
  131. branch: 'new-branch',
  132. detached: false,
  133. isWorktree: false,
  134. });
  135. await vi.waitFor(() => expect(status.render(120).join('\n')).toContain('new-branch'));
  136. resolvers[0]?.({
  137. isGitRepo: true,
  138. branch: 'old-branch',
  139. detached: false,
  140. isWorktree: false,
  141. });
  142. await vi.waitFor(() => expect(requestRender).toHaveBeenCalledTimes(1));
  143. expect(status.render(120).join('\n')).toContain('new-branch');
  144. expect(status.render(120).join('\n')).not.toContain('old-branch');
  145. } finally {
  146. status.dispose();
  147. }
  148. });
  149. it('preserves the configured status line items across Runtime shell projections', async () => {
  150. const runtime = {
  151. getWorkspaceGitMetadata: vi.fn(async () => ({
  152. isGitRepo: true,
  153. branch: 'feat/pinned',
  154. detached: false,
  155. isWorktree: false,
  156. })),
  157. };
  158. const status = createTuiWorkspaceStatusLine(
  159. {
  160. runtime,
  161. workspaceDir: '/workspace',
  162. version: '0.1.0',
  163. // `workspace` is a legacy alias for `current-dir`; `nope` must be ignored.
  164. statusLineItems: ['workspace', 'nope'],
  165. },
  166. vi.fn(),
  167. );
  168. try {
  169. // The per-frame projection carries no item order, so the configured list
  170. // must survive a plain shell state update.
  171. status.setState({
  172. version: '0.1.0',
  173. workspace: '/workspace',
  174. runtimeStatus: 'ready',
  175. model: 'minimax/m2',
  176. });
  177. const line = status.render(120).join('\n');
  178. expect(line).toContain('/workspace');
  179. // Only the configured item renders: the model was not configured.
  180. expect(line).not.toContain('m2');
  181. } finally {
  182. status.dispose();
  183. }
  184. });
  185. it('preserves the configured status protocol across Runtime shell projections', () => {
  186. const runtime = {
  187. getWorkspaceGitMetadata: vi.fn(async () => ({
  188. isGitRepo: false,
  189. branch: '',
  190. detached: false,
  191. isWorktree: false,
  192. })),
  193. };
  194. const status = createTuiWorkspaceStatusLine(
  195. {
  196. runtime,
  197. workspaceDir: '/workspace',
  198. version: '0.1.0',
  199. statusLineItems: ['build-mode', 'current-dir'],
  200. },
  201. vi.fn(),
  202. );
  203. try {
  204. status.setState({
  205. version: '0.1.0',
  206. workspace: '/workspace',
  207. runtimeStatus: 'ready',
  208. agentStatus: 'run',
  209. agentRunId: 'turn_550e8400-e29b-41d4-a716-446655440000',
  210. });
  211. expect(status.render(80).join('\n').trim()).toMatch(
  212. /^\[V\] seq=0 state=run session=none turn=[a-z0-9]{6} request=none agents=0\/0$/u,
  213. );
  214. } finally {
  215. status.dispose();
  216. }
  217. });
  218. });
  219. describe('TuiWorkspaceStatusLine custom status command', () => {
  220. const quietGitRuntime = () => ({
  221. getWorkspaceGitMetadata: vi.fn(async () => ({
  222. isGitRepo: false,
  223. branch: '',
  224. detached: false,
  225. isWorktree: false,
  226. })),
  227. });
  228. function createCustomStatus(overrides?: {
  229. statusLineItems?: readonly string[];
  230. customStatusLine?: TuiCustomStatusLineConfig;
  231. runProcess?: (
  232. invocation: TuiCustomStatusProcessInvocation,
  233. ) => Promise<TuiCustomStatusProcessResult>;
  234. }) {
  235. const runProcess = vi.fn(
  236. overrides?.runProcess ??
  237. (async () => ({ exitCode: 0, stdout: 'Cost $1.23\nignored', timedOut: false })),
  238. );
  239. const status = createTuiWorkspaceStatusLine(
  240. {
  241. runtime: quietGitRuntime(),
  242. workspaceDir: '/workspace',
  243. version: '0.1.0',
  244. statusLineItems: overrides?.statusLineItems ?? ['custom-command'],
  245. customStatusLine: { command: 'cost-probe --fast', ...overrides?.customStatusLine },
  246. runCustomStatusProcess: runProcess,
  247. },
  248. vi.fn(),
  249. );
  250. return { status, runProcess };
  251. }
  252. it('runs the command at startup and renders its first stdout line', async () => {
  253. const { status, runProcess } = createCustomStatus();
  254. try {
  255. await vi.waitFor(() => expect(status.render(120).join('\n')).toContain('Cost $1.23'));
  256. expect(status.render(120).join('\n')).not.toContain('ignored');
  257. expect(runProcess).toHaveBeenCalledTimes(1);
  258. const invocation = runProcess.mock.calls[0]?.[0] as TuiCustomStatusProcessInvocation;
  259. expect(invocation.executable).toBe('cost-probe');
  260. expect(invocation.args).toEqual(['--fast']);
  261. expect(JSON.parse(invocation.stdin)).toMatchObject({
  262. protocol: 1,
  263. event: 'startup',
  264. workspace_dir: '/workspace',
  265. tui_version: '0.1.0',
  266. });
  267. } finally {
  268. status.dispose();
  269. }
  270. });
  271. it('never starts a command for preview and discards results after disabling and re-enabling it', async () => {
  272. const resolvers: Array<(result: TuiCustomStatusProcessResult) => void> = [];
  273. const { status, runProcess } = createCustomStatus({
  274. statusLineItems: ['model'],
  275. runProcess: () => new Promise((resolve) => { resolvers.push(resolve); }),
  276. });
  277. try {
  278. const preview = status.preview(['custom-command'], 80, 3);
  279. expect(preview.unavailable).toContain('custom-command');
  280. expect(runProcess).not.toHaveBeenCalled();
  281. status.setConfiguredItems(['custom-command']);
  282. expect(runProcess).toHaveBeenCalledTimes(1);
  283. status.setConfiguredItems(['model']);
  284. status.setConfiguredItems(['custom-command']);
  285. status.setConfiguredItems(['model']);
  286. status.setConfiguredItems(['custom-command']);
  287. expect(runProcess).toHaveBeenCalledTimes(1);
  288. resolvers[0]?.({ exitCode: 0, timedOut: false, stdout: 'stale-command-result' });
  289. await vi.waitFor(() => expect(runProcess).toHaveBeenCalledTimes(2));
  290. expect(status.render(80).join('')).not.toContain('stale-command-result');
  291. resolvers[1]?.({ exitCode: 0, timedOut: false, stdout: 'new-command-result' });
  292. await vi.waitFor(() => expect(status.render(80).join('')).toContain('new-command-result'));
  293. expect(status.render(80).join('')).toContain('new-command-result');
  294. } finally { status.dispose(); }
  295. });
  296. it('retains block settings across shell projections and clears on successful empty output', async () => {
  297. const runProcess = vi
  298. .fn()
  299. .mockResolvedValueOnce({
  300. exitCode: 0,
  301. stdout: 'Context ready\nCI passed\nThird',
  302. timedOut: false,
  303. })
  304. .mockResolvedValueOnce({ exitCode: 1, stdout: 'broken', timedOut: false })
  305. .mockResolvedValueOnce({ exitCode: 0, stdout: '', timedOut: false });
  306. const { status } = createCustomStatus({
  307. statusLineItems: ['current-dir', 'custom-command'],
  308. customStatusLine: { display: 'block', maxLines: 2 },
  309. runProcess,
  310. });
  311. const state = { version: '0.1.0', workspace: '/workspace', runtimeStatus: 'ready' as const };
  312. try {
  313. await vi.waitFor(() => expect(status.render(120)).toHaveLength(4));
  314. status.setState({ ...state, busy: true });
  315. expect(status.render(120).join('\n')).toContain('CI passed');
  316. expect(status.render(120).join('\n')).not.toContain('Third');
  317. status.setState({ ...state, busy: false });
  318. await vi.waitFor(() => expect(runProcess).toHaveBeenCalledTimes(2));
  319. expect(status.render(120).join('\n')).toContain('CI passed');
  320. status.setState({ ...state, busy: true });
  321. status.setState({ ...state, busy: false });
  322. await vi.waitFor(() => expect(status.render(120)).toHaveLength(2));
  323. expect(status.render(120).join('\n')).toContain('/workspace');
  324. } finally {
  325. status.dispose();
  326. }
  327. });
  328. it.each(['session', 'workspace', 'cleared-session'] as const)(
  329. 'discards pending block output after a %s change',
  330. async (change) => {
  331. const resolvers: Array<(result: TuiCustomStatusProcessResult) => void> = [];
  332. const { status, runProcess } = createCustomStatus({
  333. customStatusLine: { display: 'block' },
  334. runProcess: () => new Promise((resolve) => resolvers.push(resolve)),
  335. });
  336. const state = {
  337. version: '0.1.0',
  338. workspace: '/workspace',
  339. runtimeStatus: 'ready' as const,
  340. agentSessionId: 'session-a',
  341. };
  342. try {
  343. status.setState(state);
  344. resolvers[0]?.({ exitCode: 0, stdout: 'startup\nignored', timedOut: false });
  345. await vi.waitFor(() => expect(runProcess).toHaveBeenCalledTimes(2));
  346. status.setState({
  347. ...state,
  348. workspace: change === 'workspace' ? '/another-workspace' : state.workspace,
  349. agentSessionId: change === 'cleared-session' ? undefined : 'session-b',
  350. });
  351. // Returning to the old identity must not resurrect its in-flight result.
  352. if (change === 'session') status.setState(state);
  353. resolvers[1]?.({ exitCode: 0, stdout: 'stale first\nstale second', timedOut: false });
  354. await vi.waitFor(() => expect(runProcess).toHaveBeenCalledTimes(3));
  355. expect(status.render(120)).toEqual([]);
  356. resolvers[2]?.({ exitCode: 0, stdout: 'fresh first\nfresh second', timedOut: false });
  357. await vi.waitFor(() => expect(status.render(120).join('\n')).toContain('fresh second'));
  358. } finally {
  359. status.dispose();
  360. }
  361. },
  362. );
  363. it('refreshes on turn end and keeps the last text when the rerun fails', async () => {
  364. const results: TuiCustomStatusProcessResult[] = [
  365. { exitCode: 0, stdout: 'v1', timedOut: false },
  366. { exitCode: 1, stdout: 'broken', timedOut: false },
  367. ];
  368. const { status, runProcess } = createCustomStatus({
  369. runProcess: async () => results.shift() ?? { exitCode: 1, stdout: '', timedOut: false },
  370. });
  371. const baseState = {
  372. version: '0.1.0',
  373. workspace: '/workspace',
  374. runtimeStatus: 'ready' as const,
  375. };
  376. try {
  377. await vi.waitFor(() => expect(status.render(120).join('\n')).toContain('v1'));
  378. status.setState({ ...baseState, busy: true });
  379. expect(runProcess).toHaveBeenCalledTimes(1);
  380. status.setState({ ...baseState, busy: false });
  381. await vi.waitFor(() => expect(runProcess).toHaveBeenCalledTimes(2));
  382. const invocation = runProcess.mock.calls[1]?.[0] as TuiCustomStatusProcessInvocation;
  383. expect(JSON.parse(invocation.stdin)).toMatchObject({ event: 'turn-end' });
  384. // The failed rerun must not clear the previously rendered value.
  385. expect(status.render(120).join('\n')).toContain('v1');
  386. } finally {
  387. status.dispose();
  388. }
  389. });
  390. it('clears the cached text and reruns when the Session changes', async () => {
  391. const results: TuiCustomStatusProcessResult[] = [
  392. { exitCode: 0, stdout: 'old-session-cost', timedOut: false },
  393. { exitCode: 0, stdout: 'new-session-cost', timedOut: false },
  394. ];
  395. const { status, runProcess } = createCustomStatus({
  396. runProcess: async () => results.shift() ?? { exitCode: 1, stdout: '', timedOut: false },
  397. });
  398. try {
  399. await vi.waitFor(() => expect(status.render(120).join('\n')).toContain('old-session-cost'));
  400. status.setState({
  401. version: '0.1.0',
  402. workspace: '/workspace',
  403. runtimeStatus: 'ready',
  404. agentSessionId: 'session-2',
  405. });
  406. // Stale output disappears immediately: a wrong figure is worse than none.
  407. expect(status.render(120).join('\n')).not.toContain('old-session-cost');
  408. await vi.waitFor(() => expect(status.render(120).join('\n')).toContain('new-session-cost'));
  409. const invocation = runProcess.mock.calls[1]?.[0] as TuiCustomStatusProcessInvocation;
  410. expect(JSON.parse(invocation.stdin)).toMatchObject({
  411. event: 'session-change',
  412. session_id: 'session-2',
  413. });
  414. } finally {
  415. status.dispose();
  416. }
  417. });
  418. it.each(['inline', 'block'] as const)(
  419. 'never spawns in build-mode with display %s',
  420. async (display) => {
  421. const { status, runProcess } = createCustomStatus({
  422. statusLineItems: ['build-mode', 'custom-command'],
  423. customStatusLine: { display, maxLines: 5, intervalSeconds: 10 },
  424. });
  425. try {
  426. status.setState({
  427. version: '0.1.0',
  428. workspace: '/workspace',
  429. runtimeStatus: 'ready',
  430. busy: true,
  431. });
  432. status.setState({
  433. version: '0.1.0',
  434. workspace: '/workspace',
  435. runtimeStatus: 'ready',
  436. busy: false,
  437. });
  438. await new Promise((resolve) => setImmediate(resolve));
  439. expect(runProcess).not.toHaveBeenCalled();
  440. expect(status.render(120).join('\n')).toContain('[V]');
  441. } finally {
  442. status.dispose();
  443. }
  444. },
  445. );
  446. it('never spawns when custom-command is not in the configured items', async () => {
  447. const { status, runProcess } = createCustomStatus({ statusLineItems: ['current-dir'] });
  448. try {
  449. await new Promise((resolve) => setImmediate(resolve));
  450. expect(runProcess).not.toHaveBeenCalled();
  451. } finally {
  452. status.dispose();
  453. }
  454. });
  455. it('stops triggering after dispose', async () => {
  456. const { status, runProcess } = createCustomStatus();
  457. await vi.waitFor(() => expect(runProcess).toHaveBeenCalledTimes(1));
  458. status.dispose();
  459. status.setState({
  460. version: '0.1.0',
  461. workspace: '/workspace',
  462. runtimeStatus: 'ready',
  463. agentSessionId: 'session-after-dispose',
  464. });
  465. await new Promise((resolve) => setImmediate(resolve));
  466. expect(runProcess).toHaveBeenCalledTimes(1);
  467. });
  468. });