tui-status-line-items.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. import { afterEach, describe, expect, it } from 'vitest';
  2. import { applyTuiRenderTheme, getTuiThemeSnapshot, tuiChalk, tuiColors } from '../../src/tui/theme/runtime.js';
  3. import { MINIMAX_CODE_DARK_THEME, MINIMAX_CODE_LIGHT_THEME } from '../../src/tui/theme/palettes.js';
  4. import { TuiStatusLine } from '../../src/tui/shell/chrome.js';
  5. import { stripAnsi, visibleWidth } from '../../src/tui/rendering/text.js';
  6. import { setCapabilityOverrides } from '../../src/tui/engine/public.js';
  7. import type { TuiShellState } from '../../src/tui/shell/contracts.js';
  8. import { resolveTuiAgentRef } from '../../src/tui/shell/status-protocol.js';
  9. import {
  10. TUI_STATUS_LINE_DEFAULT_ITEMS,
  11. parseTuiStatusLineItem,
  12. parseTuiStatusLineItems,
  13. } from '../../src/tui/shell/status-line-items.js';
  14. const BASE_STATE: TuiShellState = {
  15. version: '0.1.0',
  16. workspace: '/home/dev/repo',
  17. homeDir: '/home/dev',
  18. runtimeStatus: 'ready',
  19. sessionTitle: 'Ship status line',
  20. model: 'minimax/m2',
  21. thinking: 'on',
  22. permissionMode: 'auto',
  23. workspaceGit: {
  24. isGitRepo: true,
  25. branch: 'feat/status-line',
  26. detached: false,
  27. isWorktree: false,
  28. },
  29. };
  30. function render(state: TuiShellState, width = 200): string {
  31. return new TuiStatusLine(state).render(width).join('\n');
  32. }
  33. describe('status line item parsing', () => {
  34. it('resolves canonical ids and known aliases', () => {
  35. expect(parseTuiStatusLineItem('current-dir')).toBe('current-dir');
  36. expect(parseTuiStatusLineItem('workspace')).toBe('current-dir');
  37. expect(parseTuiStatusLineItem('permissions')).toBe('approval-mode');
  38. expect(parseTuiStatusLineItem('context')).toBe('context-remaining');
  39. expect(parseTuiStatusLineItem('context-window')).toBe('context-window');
  40. expect(parseTuiStatusLineItem('cache-read')).toBe('cache-read-ratio');
  41. expect(parseTuiStatusLineItem('build-mode')).toBe('build-mode');
  42. expect(parseTuiStatusLineItem('status-protocol')).toBe('build-mode');
  43. expect(parseTuiStatusLineItem('vela')).toBe('build-mode');
  44. expect(parseTuiStatusLineItem('custom-command')).toBe('custom-command');
  45. expect(parseTuiStatusLineItem('custom')).toBe('custom-command');
  46. expect(parseTuiStatusLineItem('tips')).toBeUndefined();
  47. });
  48. it('is case and whitespace insensitive', () => {
  49. expect(parseTuiStatusLineItem(' Model-With-Reasoning ')).toBe('model-with-reasoning');
  50. });
  51. it('ignores unknown ids instead of failing', () => {
  52. expect(parseTuiStatusLineItem('five-hour-limit')).toBeUndefined();
  53. expect(parseTuiStatusLineItems(['current-dir', 'not-a-real-item', 'git-branch'])).toEqual([
  54. 'current-dir',
  55. 'git-branch',
  56. ]);
  57. });
  58. it('preserves configured order and drops duplicates', () => {
  59. expect(parseTuiStatusLineItems(['git-branch', 'current-dir', 'branch'])).toEqual([
  60. 'git-branch',
  61. 'current-dir',
  62. ]);
  63. });
  64. });
  65. describe('TuiStatusLine default items', () => {
  66. it('keeps build-mode and cache diagnostics out of the default order', () => {
  67. expect(TUI_STATUS_LINE_DEFAULT_ITEMS).not.toContain('build-mode');
  68. expect(TUI_STATUS_LINE_DEFAULT_ITEMS).toContain('context-remaining');
  69. expect(TUI_STATUS_LINE_DEFAULT_ITEMS).not.toContain('custom-command');
  70. expect(TUI_STATUS_LINE_DEFAULT_ITEMS).not.toContain('tips');
  71. expect(TUI_STATUS_LINE_DEFAULT_ITEMS).not.toContain('cache-read-ratio');
  72. });
  73. it('replaces capacity with live context headroom while preserving explicit configuration', () => {
  74. const state = {
  75. ...BASE_STATE,
  76. sessionCacheReadRatio: 0.9,
  77. contextUsage: { usedTokens: 80_000, contextWindowTokens: 100_000 },
  78. };
  79. const lowContext = stripAnsi(render(state));
  80. expect(lowContext).toContain('Context 20% left');
  81. expect(lowContext).not.toContain('Context 100K');
  82. expect(lowContext).not.toContain('Cache');
  83. const healthyContext = stripAnsi(
  84. render({
  85. ...state,
  86. contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
  87. }),
  88. );
  89. expect(healthyContext).toContain('Context 50% left');
  90. expect(healthyContext).not.toContain('Context 100K');
  91. expect(render({ ...state, statusLineItems: ['model'] })).not.toContain('Context');
  92. expect(render({ ...state, statusLineItems: ['cache-read-ratio'] })).toContain('Cache 90%');
  93. expect(
  94. render({
  95. ...state,
  96. contextUsage: { usedTokens: Number.NaN, contextWindowTokens: 100_000 },
  97. }),
  98. ).not.toContain('NaN');
  99. });
  100. it('keeps explicitly configured capacity and headroom independent', () => {
  101. const explicit = stripAnsi(
  102. render({
  103. ...BASE_STATE,
  104. statusLineItems: ['context-window', 'context-remaining'],
  105. contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
  106. }),
  107. );
  108. expect(explicit).toContain('Context 100K');
  109. expect(explicit).toContain('Context 50% left');
  110. });
  111. it('keeps rotating prose out of the stable status rail', () => {
  112. expect(render(BASE_STATE)).not.toContain('Tip:');
  113. });
  114. it('lets build-mode own the line when conditional items are also configured', () => {
  115. const line = render({
  116. ...BASE_STATE,
  117. statusLineItems: ['build-mode', 'context-remaining'],
  118. agentStatus: 'ready',
  119. contextUsage: { usedTokens: 40_000, contextWindowTokens: 200_000 },
  120. });
  121. expect(line).toContain('[V]');
  122. expect(line).not.toContain('Context 80% left');
  123. });
  124. });
  125. describe('context window capacity', () => {
  126. it.each([
  127. [1_000_000, '1M'],
  128. [512_000, '512K'],
  129. [128_001, '128001'],
  130. ] as const)('shows %d tokens by default before any usage is available', (tokens, label) => {
  131. expect(stripAnsi(render({ ...BASE_STATE, contextWindowTokens: tokens }))).toContain(
  132. `Context ${label}`,
  133. );
  134. });
  135. it('uses the Runtime usage window before the model fallback', () => {
  136. const line = stripAnsi(
  137. render({
  138. ...BASE_STATE,
  139. statusLineItems: ['context-window'],
  140. contextWindowTokens: 1_000_000,
  141. contextUsage: { usedTokens: 1_000, contextWindowTokens: 512_000 },
  142. }),
  143. );
  144. expect(line).toContain('Context 512K');
  145. expect(line).not.toContain('Context 1M');
  146. expect(line).not.toContain('% left');
  147. });
  148. it.each([undefined, 0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
  149. 'hides unavailable capacity %s',
  150. (tokens) => {
  151. expect(
  152. render({
  153. ...BASE_STATE,
  154. statusLineItems: ['context-window'],
  155. contextWindowTokens: tokens,
  156. }).trim(),
  157. ).toBe('');
  158. },
  159. );
  160. it('honours configured items and keeps capacity readable at common widths', () => {
  161. const state = { ...BASE_STATE, contextWindowTokens: 1_000_000 };
  162. expect(render({ ...state, statusLineItems: ['model'] })).not.toContain('Context');
  163. expect(stripAnsi(render({ ...state, statusLineItems: ['context-window'] }))).toContain(
  164. 'Context 1M',
  165. );
  166. for (const width of [80, 120]) {
  167. const line = render(state, width);
  168. expect(stripAnsi(line)).toMatch(/(?:Context|Ctx) 1M/u);
  169. expect(line.split('\n').every((row) => visibleWidth(row) <= width)).toBe(true);
  170. }
  171. });
  172. });
  173. describe('agent ref', () => {
  174. it('is stable, bounded, and opaque', () => {
  175. const firstTurn = 'turn_550e8400-e29b-41d4-a716-446655440000';
  176. const secondTurn = 'turn_6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  177. const firstRef = resolveTuiAgentRef(firstTurn);
  178. expect(firstRef).toMatch(/^[a-z0-9]{6}$/u);
  179. expect(resolveTuiAgentRef(firstTurn)).toBe(firstRef);
  180. expect(resolveTuiAgentRef(secondTurn)).toMatch(/^[a-z0-9]{6}$/u);
  181. expect(resolveTuiAgentRef(secondTurn)).not.toBe(firstRef);
  182. expect(firstRef).not.toContain('550e8400');
  183. });
  184. it('uses none when no Runtime turn id is available', () => {
  185. expect(resolveTuiAgentRef(undefined)).toBe('none');
  186. expect(resolveTuiAgentRef(' ')).toBe('none');
  187. });
  188. });
  189. describe('TuiStatusLine configured items', () => {
  190. it('renders only the configured items, in the configured order', () => {
  191. const line = render({
  192. ...BASE_STATE,
  193. statusLineItems: ['model-with-reasoning', 'current-dir'],
  194. });
  195. // The model label keeps only its last path segment, matching existing behaviour.
  196. expect(line).toContain('m2');
  197. expect(line).toContain('~/repo');
  198. // Git and session title are omitted because they were not configured.
  199. expect(line).not.toContain('feat/status-line');
  200. expect(line).not.toContain('Ship status line');
  201. expect(line.indexOf('m2')).toBeLessThan(line.indexOf('~/repo'));
  202. });
  203. it('honours an empty configured list as a blank status line', () => {
  204. expect(render({ ...BASE_STATE, statusLineItems: [] }).trim()).toBe('');
  205. });
  206. it('renders the model without the reasoning suffix for the model item', () => {
  207. const line = render({ ...BASE_STATE, statusLineItems: ['model'] });
  208. expect(line).toContain('m2');
  209. expect(line).not.toContain('Thinking');
  210. });
  211. });
  212. describe('context-remaining item', () => {
  213. const items: TuiShellState['statusLineItems'] = ['context-remaining'];
  214. it('falls back to the model context window when usage omits one', () => {
  215. const line = render({
  216. ...BASE_STATE,
  217. statusLineItems: items,
  218. contextUsage: { usedTokens: 50_000 },
  219. contextWindowTokens: 100_000,
  220. });
  221. expect(line).toContain('Context 50% left');
  222. });
  223. it('renders nothing when no context window can be resolved', () => {
  224. const line = render({
  225. ...BASE_STATE,
  226. statusLineItems: items,
  227. contextUsage: { usedTokens: 1_000 },
  228. });
  229. expect(line.trim()).toBe('');
  230. });
  231. it('clamps overflow to zero rather than reporting negative headroom', () => {
  232. const line = render({
  233. ...BASE_STATE,
  234. statusLineItems: items,
  235. contextUsage: { usedTokens: 150_000, contextWindowTokens: 100_000 },
  236. });
  237. expect(line).toContain('Context 0% left');
  238. });
  239. it('shrinks to a compact label on a narrow terminal', () => {
  240. const state: TuiShellState = {
  241. ...BASE_STATE,
  242. statusLineItems: ['current-dir', 'context-remaining'],
  243. contextUsage: { usedTokens: 25_000, contextWindowTokens: 100_000 },
  244. };
  245. expect(render(state)).toContain('Context 75% left');
  246. const narrow = render(state, 16);
  247. expect(narrow).not.toContain('Context 75% left');
  248. expect(narrow).toContain('75%');
  249. });
  250. });
  251. describe('cache-read-ratio item', () => {
  252. it('renders the Session-wide cache read ratio when prompt usage is available', () => {
  253. const line = render({
  254. ...BASE_STATE,
  255. statusLineItems: ['cache-read-ratio'],
  256. sessionCacheReadRatio: 0.8,
  257. });
  258. expect(line).toContain('Cache 80%');
  259. });
  260. it('renders nothing before the Runtime supplies a Session metric', () => {
  261. expect(render({ ...BASE_STATE, statusLineItems: ['cache-read-ratio'] }).trim()).toBe('');
  262. });
  263. it('shrinks to a compact label without changing the percentage', () => {
  264. const state: TuiShellState = {
  265. ...BASE_STATE,
  266. statusLineItems: ['current-dir', 'cache-read-ratio'],
  267. sessionCacheReadRatio: 0.923,
  268. };
  269. expect(render(state)).toContain('Cache 92%');
  270. expect(render(state, 16)).toContain('92%');
  271. });
  272. });
  273. describe('custom-command block display', () => {
  274. const blockState: TuiShellState = {
  275. ...BASE_STATE,
  276. statusLineItems: ['current-dir', 'custom-command', 'model'],
  277. customStatusText:
  278. 'Context ready\nCI passed\nEnvironment test\nTasks idle\nExtra status\nToo many',
  279. };
  280. it.each([undefined, 'above', 'below'] as const)(
  281. 'places custom rows %s without changing the original footer at any width',
  282. (position) => {
  283. const status = new TuiStatusLine(blockState, { display: 'block', maxLines: 2, position });
  284. const original = new TuiStatusLine({
  285. ...blockState,
  286. statusLineItems: ['current-dir', 'model'],
  287. });
  288. for (const width of [160, 40, 1]) {
  289. const lines = status.render(width).map(stripAnsi);
  290. const originalLines = original.render(width).slice(1).map(stripAnsi);
  291. expect(lines).toHaveLength(3 + originalLines.length);
  292. expect(
  293. position === 'below' ? lines.slice(1, 1 + originalLines.length) : lines.slice(3),
  294. ).toEqual(originalLines);
  295. expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
  296. }
  297. const lines = status.render(160).map(stripAnsi);
  298. expect(position === 'below' ? lines.slice(-2) : lines.slice(1, 3)).toEqual([
  299. 'Context ready',
  300. 'CI passed',
  301. ]);
  302. },
  303. );
  304. it.each([
  305. [undefined, 3],
  306. [Number.NaN, 3],
  307. [0, 1],
  308. [2.9, 2],
  309. [100, 5],
  310. ])('bounds maxLines %s to %s visible rows', (maxLines, expected) => {
  311. const status = new TuiStatusLine(blockState, { display: 'block', maxLines });
  312. expect(status.render(120)).toHaveLength(expected + 2);
  313. });
  314. it('sanitizes multiline controls, discards blank rows and truncates wide Unicode text', () => {
  315. const status = new TuiStatusLine(
  316. {
  317. ...blockState,
  318. statusLineItems: ['custom-command'],
  319. customStatusText:
  320. '\u001b[31m中文状态很长\u001b[0m\r\n\n\u0007\nCI\tpassed\rOK\n\u001b]0;title\u0007ready',
  321. },
  322. { display: 'block' },
  323. );
  324. const lines = status.render(10).map(stripAnsi);
  325. expect(lines).toEqual(['', '中文状态…', 'CI passed…', 'ready']);
  326. expect(lines.every((line) => visibleWidth(line) <= 10)).toBe(true);
  327. expect(lines.join('')).not.toMatch(/[\r\n\t\u0007\u001b]/u);
  328. });
  329. it.each(['above', 'below'] as const)(
  330. 'shrinks custom rows %s first and restores them when the viewport grows',
  331. (position) => {
  332. const status = new TuiStatusLine(blockState, { display: 'block', maxLines: 5, position });
  333. const original = new TuiStatusLine({
  334. ...blockState,
  335. statusLineItems: ['current-dir', 'model'],
  336. });
  337. const lines = status.renderViewport(120, 3).map(stripAnsi);
  338. expect(position === 'below' ? lines.slice(-1) : lines.slice(1, -1)).toEqual([
  339. 'Context ready',
  340. ]);
  341. expect(status.renderViewport(120, 2)).toEqual(original.render(120));
  342. expect(status.renderViewport(120, 0)).toEqual(original.render(120));
  343. expect(status.renderViewport(120, 20)).toHaveLength(7);
  344. },
  345. );
  346. it('does not reserve rows for empty or control-only output', () => {
  347. const original = new TuiStatusLine({
  348. ...blockState,
  349. statusLineItems: ['current-dir', 'model'],
  350. });
  351. for (const text of ['', '\n\u0007\u001b[0m\n', undefined]) {
  352. const status = new TuiStatusLine(
  353. { ...blockState, customStatusText: text },
  354. { display: 'block' },
  355. );
  356. expect(status.render(120)).toEqual(original.render(120));
  357. }
  358. });
  359. it('keeps an explicit custom-only block empty when there is no output or room', () => {
  360. const status = new TuiStatusLine(
  361. { ...blockState, statusLineItems: ['custom-command'] },
  362. { display: 'block' },
  363. );
  364. expect(status.renderViewport(120, 1)).toEqual([]);
  365. status.setState({ ...blockState, statusLineItems: ['custom-command'], customStatusText: '' });
  366. expect(status.render(120)).toEqual([]);
  367. });
  368. it('does not enable custom output through the block settings alone', () => {
  369. for (const statusLineItems of [undefined, [], ['model']] as const) {
  370. const state = { ...blockState, statusLineItems };
  371. expect(new TuiStatusLine(state, { display: 'block' }).render(120)).toEqual(
  372. new TuiStatusLine(state).render(120),
  373. );
  374. }
  375. });
  376. });
  377. describe('custom-command item', () => {
  378. it('ignores block position in inline mode and keeps only the first line', () => {
  379. const state: TuiShellState = {
  380. ...BASE_STATE,
  381. statusLineItems: ['current-dir', 'custom-command', 'model'],
  382. customStatusText: 'first\nsecond',
  383. };
  384. const above = new TuiStatusLine(state, { position: 'above' }).render(200);
  385. const below = new TuiStatusLine(state, { display: 'inline', position: 'below' }).render(200);
  386. expect(below).toEqual(above);
  387. expect(above.join('')).toContain('first');
  388. expect(above.join('')).not.toContain('second');
  389. expect(stripAnsi(above[1] ?? '')).toMatch(/repo.*first.*m2/u);
  390. });
  391. it('renders the latest command output as one ordinary muted segment', () => {
  392. const line = stripAnsi(
  393. render({
  394. ...BASE_STATE,
  395. statusLineItems: ['custom-command'],
  396. customStatusText: 'Cost $1.23',
  397. }),
  398. );
  399. expect(line).toContain('Cost $1.23');
  400. });
  401. it('renders nothing before the first successful command run', () => {
  402. expect(render({ ...BASE_STATE, statusLineItems: ['custom-command'] }).trim()).toBe('');
  403. });
  404. it('renders nothing when the last run deliberately blanked the item', () => {
  405. expect(
  406. render({ ...BASE_STATE, statusLineItems: ['custom-command'], customStatusText: '' }).trim(),
  407. ).toBe('');
  408. });
  409. it('strips ANSI and control characters from untrusted command output', () => {
  410. const line = render({
  411. ...BASE_STATE,
  412. statusLineItems: ['custom-command'],
  413. customStatusText: '\u001b[31mCost\u001b[0m \u0007$1.23',
  414. });
  415. expect(line).not.toContain('\u001b[31m');
  416. expect(line).not.toContain('\u0007');
  417. expect(stripAnsi(line)).toContain('Cost $1.23');
  418. });
  419. it('truncates long output instead of flooding the rail', () => {
  420. const line = stripAnsi(
  421. render({
  422. ...BASE_STATE,
  423. statusLineItems: ['custom-command'],
  424. customStatusText: 'x'.repeat(100),
  425. }),
  426. );
  427. expect(line).toContain('…');
  428. expect(line).not.toContain('x'.repeat(61));
  429. });
  430. it('yields the whole line to build-mode when both are configured', () => {
  431. const line = render({
  432. ...BASE_STATE,
  433. statusLineItems: ['build-mode', 'custom-command'],
  434. agentStatus: 'ready',
  435. customStatusText: 'Cost $1.23',
  436. });
  437. expect(line).toContain('[V]');
  438. expect(line).not.toContain('Cost $1.23');
  439. });
  440. });
  441. describe('review link status item', () => {
  442. afterEach(() => {
  443. setCapabilityOverrides({});
  444. });
  445. const withReview = (
  446. reviewLink: NonNullable<TuiShellState['workspaceGit']>['reviewLink'],
  447. ): TuiShellState => ({
  448. ...BASE_STATE,
  449. statusLineItems: ['review-link'],
  450. workspaceGit: { ...BASE_STATE.workspaceGit!, reviewLink },
  451. });
  452. it('resolves the vendor-neutral aliases users are likely to configure', () => {
  453. expect(parseTuiStatusLineItem('review-link')).toBe('review-link');
  454. expect(parseTuiStatusLineItem('pr')).toBe('review-link');
  455. expect(parseTuiStatusLineItem('mr')).toBe('review-link');
  456. expect(parseTuiStatusLineItem('merge-request')).toBe('review-link');
  457. });
  458. it('renders a GitLab merge request with its ! shorthand', () => {
  459. const line = stripAnsi(
  460. render(withReview({ vendor: 'gitlab', url: 'https://x/-/merge_requests/312', number: 312 })),
  461. );
  462. expect(line).toContain('MR');
  463. expect(line).toContain('!312');
  464. });
  465. it('renders a GitHub pull request with its # shorthand', () => {
  466. const line = stripAnsi(
  467. render(withReview({ vendor: 'github', url: 'https://x/pull/88', number: 88 })),
  468. );
  469. expect(line).toContain('PR');
  470. expect(line).toContain('#88');
  471. });
  472. it('renders nothing when the branch has no recorded review', () => {
  473. // The whole line collapses because `review-link` was the only item
  474. // configured — an unrecorded branch must not reserve a blank rail.
  475. expect(render({ ...BASE_STATE, statusLineItems: ['review-link'] })).toBe('');
  476. });
  477. it('stays in the default order next to the branch it belongs to', () => {
  478. expect(TUI_STATUS_LINE_DEFAULT_ITEMS).toContain('review-link');
  479. expect(TUI_STATUS_LINE_DEFAULT_ITEMS.indexOf('review-link')).toBe(
  480. TUI_STATUS_LINE_DEFAULT_ITEMS.indexOf('git-branch') + 1,
  481. );
  482. });
  483. it('wraps the segment in an OSC 8 hyperlink so the review can be opened', () => {
  484. setCapabilityOverrides({ hyperlinks: true });
  485. const url = 'https://github.com/acme/widgets/pull/50';
  486. const line = render(withReview({ vendor: 'github', url, number: 50 }));
  487. expect(line).toContain(`\u001b]8;;${url}\u001b\\`);
  488. expect(line).toContain('\u001b]8;;\u001b\\');
  489. expect(stripAnsi(line)).toContain('#50');
  490. });
  491. it('emits no escape where the terminal does not forward hyperlinks', () => {
  492. // tmux and screen without passthrough would render the escape as garbage.
  493. setCapabilityOverrides({ hyperlinks: false });
  494. const line = render(
  495. withReview({ vendor: 'github', url: 'https://github.com/acme/widgets/pull/50', number: 50 }),
  496. );
  497. expect(line).not.toContain(']8;;');
  498. expect(stripAnsi(line)).toContain('#50');
  499. });
  500. it('does not let the hyperlink escape count toward the line width', () => {
  501. setCapabilityOverrides({ hyperlinks: true });
  502. const url = 'https://github.com/acme/widgets/pull/50';
  503. const linked = stripAnsi(render(withReview({ vendor: 'github', url, number: 50 })));
  504. setCapabilityOverrides({ hyperlinks: false });
  505. const plain = stripAnsi(render(withReview({ vendor: 'github', url, number: 50 })));
  506. expect(linked).toBe(plain);
  507. });
  508. it('keeps the number visible when the line is too narrow for the vendor label', () => {
  509. const narrow = stripAnsi(
  510. render(
  511. withReview({ vendor: 'gitlab', url: 'https://x/-/merge_requests/312', number: 312 }),
  512. 24,
  513. ),
  514. );
  515. expect(narrow).toContain('!312');
  516. });
  517. });
  518. describe('context meter item', () => {
  519. it('resolves the canonical id and its aliases', () => {
  520. expect(parseTuiStatusLineItem('context-meter')).toBe('context-meter');
  521. expect(parseTuiStatusLineItem('context-bar')).toBe('context-meter');
  522. expect(parseTuiStatusLineItem('context-gauge')).toBe('context-meter');
  523. });
  524. it('stays out of the default status line', () => {
  525. expect(TUI_STATUS_LINE_DEFAULT_ITEMS).toEqual([
  526. 'current-dir', 'session-title', 'git-branch', 'review-link', 'plan-mode',
  527. 'approval-mode', 'model-with-reasoning', 'context-window', 'subagent',
  528. 'token-quota', 'context-remaining',
  529. ]);
  530. const state = {
  531. ...BASE_STATE,
  532. contextUsage: { usedTokens: 20_000, contextWindowTokens: 100_000 },
  533. };
  534. expect(stripAnsi(render(state))).not.toContain('▕');
  535. });
  536. it('renders the remaining-headroom gauge when configured explicitly', () => {
  537. const state = {
  538. ...BASE_STATE,
  539. statusLineItems: ['context-meter'],
  540. contextUsage: { usedTokens: 20_000, contextWindowTokens: 100_000 },
  541. };
  542. expect(stripAnsi(render(state))).toContain('Context ▕██████░░▏ 80% left');
  543. });
  544. it('drains the gauge with the remaining headroom', () => {
  545. const state = {
  546. ...BASE_STATE,
  547. statusLineItems: ['context-meter'],
  548. contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
  549. };
  550. expect(stripAnsi(render(state))).toContain('▕████░░░░▏ 50% left');
  551. });
  552. it('shrinks to a shorter gauge in narrow terminals', () => {
  553. const state = {
  554. ...BASE_STATE,
  555. statusLineItems: ['context-meter'],
  556. contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
  557. };
  558. const narrow = stripAnsi(render(state, 20));
  559. expect(narrow).toContain('Ctx');
  560. expect(narrow).toContain('50%');
  561. expect(narrow).not.toContain('left');
  562. expect(narrow).not.toContain('▕████░░░░▏');
  563. });
  564. it('is hidden without usage and never shows NaN', () => {
  565. expect(render({ ...BASE_STATE, statusLineItems: ['context-meter'], contextWindowTokens: 100_000 })).toBe('');
  566. expect(
  567. stripAnsi(
  568. render({
  569. ...BASE_STATE,
  570. statusLineItems: ['context-meter'],
  571. contextUsage: { usedTokens: Number.NaN, contextWindowTokens: 100_000 },
  572. }),
  573. ),
  574. ).not.toContain('NaN');
  575. });
  576. });
  577. describe('context meter presentation contract', () => {
  578. it.each([
  579. ['context-remaining', 'model', 'context-bar', 'context-gauge'],
  580. ['context-gauge', 'model', 'context-left'],
  581. ])('prefers the meter at its configured position for %j', (...configured) => {
  582. const statusLineItems = parseTuiStatusLineItems(configured);
  583. const line = stripAnsi(render({
  584. ...BASE_STATE,
  585. statusLineItems,
  586. contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
  587. }));
  588. expect(line.match(/50%/gu)).toHaveLength(1);
  589. expect(line).toContain('Context ▕████░░░░▏ 50% left');
  590. expect(line.indexOf('Context') < line.indexOf('m2')).toBe(configured[0] === 'context-gauge');
  591. });
  592. });
  593. describe('context meter boundaries', () => {
  594. it.each([
  595. [undefined, 100_000, 50],
  596. [200_000, 100_000, 75],
  597. [Number.NaN, 100_000, 50],
  598. [0, 100_000, 50],
  599. [-1, 100_000, 50],
  600. [Number.POSITIVE_INFINITY, 100_000, 50],
  601. ])('resolves snapshot window %s before model window %s', (snapshot, model, remaining) => {
  602. for (const item of ['context-meter', 'context-remaining'] as const) {
  603. const line = stripAnsi(render({
  604. ...BASE_STATE,
  605. statusLineItems: [item],
  606. contextWindowTokens: model,
  607. contextUsage: { usedTokens: 50_000, contextWindowTokens: snapshot },
  608. }));
  609. expect(line).toContain(`${remaining}% left`);
  610. }
  611. });
  612. it.each([undefined, 0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
  613. 'hides the meter when neither window is usable (%s)', (window) => {
  614. expect(render({
  615. ...BASE_STATE,
  616. statusLineItems: ['context-meter'],
  617. contextWindowTokens: window,
  618. contextUsage: { usedTokens: 1, contextWindowTokens: window },
  619. })).toBe('');
  620. },
  621. );
  622. it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(
  623. 'hides invalid usage %s even with valid model capacity', (usedTokens) => {
  624. expect(render({
  625. ...BASE_STATE,
  626. statusLineItems: ['context-meter'],
  627. contextWindowTokens: 100_000,
  628. contextUsage: { usedTokens },
  629. })).toBe('');
  630. },
  631. );
  632. it.each([
  633. [-1, '▕████████▏ 100% left'],
  634. [0, '▕████████▏ 100% left'],
  635. [100, '▕░░░░░░░░▏ 0% left'],
  636. [150, '▕░░░░░░░░▏ 0% left'],
  637. ])('clamps used tokens %d to a valid gauge', (usedTokens, expected) => {
  638. expect(stripAnsi(render({
  639. ...BASE_STATE,
  640. statusLineItems: ['context-meter'],
  641. contextUsage: { usedTokens, contextWindowTokens: 100 },
  642. }))).toContain(expected);
  643. });
  644. it.each([
  645. [30, 'Context ▕████░░░░▏ 50% left'],
  646. [20, 'Ctx ▕███░░░▏ 50%'],
  647. [7, 'Ctx 50%'],
  648. [6, ''],
  649. ])('fits a width of %d with the expected presentation', (width, expected) => {
  650. const line = render({
  651. ...BASE_STATE,
  652. statusLineItems: ['context-meter'],
  653. contextUsage: { usedTokens: 50, contextWindowTokens: 100 },
  654. }, width);
  655. expect(stripAnsi(line).trim()).toBe(expected);
  656. expect(line.split('\n').every((row) => visibleWidth(row) <= width)).toBe(true);
  657. });
  658. it('uses the same warning and error boundaries as the percentage item', () => {
  659. const previous = getTuiThemeSnapshot();
  660. applyTuiRenderTheme(MINIMAX_CODE_DARK_THEME, 3);
  661. try {
  662. for (const [remaining, color] of [
  663. [26, tuiColors.muted], [25, tuiColors.warning],
  664. [11, tuiColors.warning], [10, tuiColors.error], [0, tuiColors.error],
  665. ] as const) {
  666. for (const item of ['context-meter', 'context-remaining'] as const) {
  667. const line = render({
  668. ...BASE_STATE,
  669. statusLineItems: [item],
  670. contextUsage: { usedTokens: 100 - remaining, contextWindowTokens: 100 },
  671. }).trim();
  672. expect(line).not.toBe(stripAnsi(line));
  673. expect(line).toBe(tuiChalk.hex(color)(stripAnsi(line)));
  674. }
  675. }
  676. } finally {
  677. applyTuiRenderTheme(
  678. previous.appearance === 'light' ? MINIMAX_CODE_LIGHT_THEME : MINIMAX_CODE_DARK_THEME,
  679. previous.colorLevel,
  680. );
  681. }
  682. });
  683. it('keeps build-mode in control when the meter is selected', () => {
  684. const line = stripAnsi(render({
  685. ...BASE_STATE,
  686. statusLineItems: ['context-meter', 'build-mode', 'context-remaining'],
  687. contextUsage: { usedTokens: 50, contextWindowTokens: 100 },
  688. }));
  689. expect(line).toContain('[V]');
  690. expect(line).not.toContain('Context');
  691. });
  692. });