mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-06 07:29:42 +02:00
feat(tabs,header): group tabs by state and add header stats styles (#426)
Two directions from Discussion #426, each a per-device setting and the new default. Tab Grouping (tabGrouping: 'state' | 'none', default 'state', option C): tabs are grouped needs you (red, plus failed sessions), waiting (yellow), working and idle (also ended, exited panes and web tabs), most urgent on top. The desktop header strip draws a row per group with its label and count in a left gutter; the flat vertical rail and the sidebar draw a section per group; tablets keep their scrolling row with inline dividers; phones keep the chip row in group order without headings. Classification is the home screens' own (_mobileOverviewState/_mobileOverviewExit), the fold into four groups is pure in CodemanTabTriage (constants.js). It is flex `order` plus aria-hidden heading/break elements reconciled in place after both render paths, never a DOM reorder, so Alt+N, the keyboard walk and drag keep reading tab order; a drop is refused across groups. Named groups in the vertical rail take precedence. Header Stats Style (headerStatsStyle: 'classic' | 'compact' | 'tiles', default 'tiles', option G): tiles give WS, CPU, MEM and each plan window a label-over-value tile with a bar underneath; compact is one WS/CPU/MEM pill with sparklines plus a plan-ring pill; classic is the header as before. Desktop only (classic below 768px and in solo windows). The clustered styles move #connectionIndicator into #headerSystemStats and #planUsageChip after it, and classic moves them back to comment anchors; WS stays out of a hidden System Stats pill. The extra parts are always rendered and hidden by default in CSS, so classic is unchanged. Tests: test/tab-triage.test.ts, test/header-stats-style.test.ts; three source pins in test/tab-rail-order.test.ts follow renamed lines. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* @fileoverview The header-stats styles (`headerStatsStyle`, Discussion #426
|
||||
* option G): 'classic' (as before), 'compact' (one system pill with sparklines
|
||||
* plus a plan-ring pill) and 'tiles' (label over value, bar underneath; the
|
||||
* default).
|
||||
*
|
||||
* Pinned here:
|
||||
* - The default is 'tiles', and only the three known values are honoured.
|
||||
* - The two clustered styles move the connection indicator INTO the system
|
||||
* stats pill and the plan chip right after it, on the REAL header markup
|
||||
* from index.html, and 'classic' puts both back exactly where the template
|
||||
* had them.
|
||||
* - The WS readout never disappears with a hidden System Stats pill.
|
||||
* - The parts only the new styles draw (sparklines, rings, meters, tile words)
|
||||
* are rendered with sane values and hidden by default in CSS, which is what
|
||||
* keeps 'classic' looking exactly as before.
|
||||
*
|
||||
* The real modules run INSIDE a JSDOM window (runScripts: 'outside-only').
|
||||
*
|
||||
* Port: none.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const PUBLIC = join(process.cwd(), 'src/web/public');
|
||||
const read = (name: string) => readFileSync(join(PUBLIC, name), 'utf8');
|
||||
const INDEX = read('index.html');
|
||||
const HEADER = INDEX.slice(INDEX.indexOf('<header class="header">'), INDEX.indexOf('</header>') + '</header>'.length);
|
||||
|
||||
let CodemanApp: { prototype: Record<string, any> };
|
||||
let window: any;
|
||||
let document: Document;
|
||||
|
||||
beforeAll(async () => {
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
|
||||
url: 'https://localhost/',
|
||||
runScripts: 'outside-only',
|
||||
});
|
||||
if (dom.window.document.readyState !== 'complete') {
|
||||
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
|
||||
}
|
||||
window = dom.window;
|
||||
document = window.document;
|
||||
window.setInterval = () => 0;
|
||||
window.requestAnimationFrame = () => 0;
|
||||
window.eval(
|
||||
'var MobileDetection = { isTouchDevice: () => false, isHandheldDevice: () => false, getDeviceType: () => "desktop" }, ' +
|
||||
'KeyboardHandler = {}, SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
|
||||
read('constants.js') +
|
||||
'\n' +
|
||||
read('app.js') +
|
||||
'\n' +
|
||||
read('settings-ui.js') +
|
||||
'\n' +
|
||||
read('panels-ui.js') +
|
||||
'\n;window.__HeaderStatsCodemanApp = CodemanApp;'
|
||||
);
|
||||
CodemanApp = window.__HeaderStatsCodemanApp;
|
||||
});
|
||||
|
||||
function makeApp() {
|
||||
const app = Object.create(CodemanApp.prototype) as Record<string, any>;
|
||||
app.$ = (id: string) => document.getElementById(id);
|
||||
return app;
|
||||
}
|
||||
|
||||
/** Element children of the header's right side, by id (or first class). */
|
||||
const rightSide = () =>
|
||||
[...document.getElementById('headerRight')!.children].map((el) => el.id || el.classList[0]);
|
||||
const statsChildren = () =>
|
||||
[...document.getElementById('headerSystemStats')!.children].map((el) => el.id || el.classList[0]);
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = HEADER;
|
||||
delete document.documentElement.dataset.headerStats;
|
||||
});
|
||||
|
||||
describe('resolveHeaderStatsStyle', () => {
|
||||
it("defaults to 'tiles' and honours only the three known styles", () => {
|
||||
const app = makeApp();
|
||||
expect(app.resolveHeaderStatsStyle({})).toBe('tiles');
|
||||
expect(app.resolveHeaderStatsStyle(undefined)).toBe('tiles');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'classic' })).toBe('classic');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'compact' })).toBe('compact');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'tiles' })).toBe('tiles');
|
||||
expect(app.resolveHeaderStatsStyle({ headerStatsStyle: 'neon' })).toBe('tiles');
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyHeaderStatsStyle', () => {
|
||||
it('clusters WS, the system stats and the plan chip for tiles and compact', () => {
|
||||
for (const style of ['tiles', 'compact']) {
|
||||
document.body.innerHTML = HEADER;
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style, showSystemStats: true });
|
||||
expect(document.documentElement.dataset.headerStats).toBe(style);
|
||||
expect(statsChildren()[0]).toBe('connectionIndicator');
|
||||
const right = rightSide();
|
||||
expect(right[right.indexOf('headerSystemStats') + 1]).toBe('planUsageChip');
|
||||
expect(right).not.toContain('connectionIndicator');
|
||||
}
|
||||
});
|
||||
|
||||
it("'classic' puts both back exactly where the template had them", () => {
|
||||
const template = rightSide();
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
app.applyHeaderStatsStyle({ style: 'compact', showSystemStats: true });
|
||||
app.applyHeaderStatsStyle({ style: 'classic', showSystemStats: true });
|
||||
expect(rightSide()).toEqual(template);
|
||||
expect(statsChildren()).not.toContain('connectionIndicator');
|
||||
expect(document.documentElement.dataset.headerStats).toBe('classic');
|
||||
});
|
||||
|
||||
it('keeps WS out of a hidden System Stats pill', () => {
|
||||
const template = rightSide();
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: false });
|
||||
expect(statsChildren()).not.toContain('connectionIndicator');
|
||||
expect(rightSide().indexOf('connectionIndicator')).toBe(template.indexOf('connectionIndicator'));
|
||||
});
|
||||
|
||||
it('is idempotent: re-applying the same style moves nothing', () => {
|
||||
const app = makeApp();
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
const once = document.getElementById('headerRight')!.innerHTML;
|
||||
app.applyHeaderStatsStyle({ style: 'tiles', showSystemStats: true });
|
||||
expect(document.getElementById('headerRight')!.innerHTML).toBe(once);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the parts the new styles draw', () => {
|
||||
it('gives every plan window a ring and a meter with a clamped fill, the label the real number', () => {
|
||||
const app = makeApp();
|
||||
app.updatePlanUsageChip({ fiveHour: { usedPercentage: 28 }, sevenDay: { usedPercentage: 104 } });
|
||||
const wins = [...document.querySelectorAll<HTMLElement>('#planUsageChip .pu-win')];
|
||||
expect(wins).toHaveLength(2);
|
||||
expect(wins[0].querySelector<HTMLElement>('.pu-ring')!.style.getPropertyValue('--pu')).toBe('28');
|
||||
expect(wins[0].querySelector<HTMLElement>('.pu-meter > i')!.style.width).toBe('28%');
|
||||
expect(wins[0].querySelector('.pu-ring')!.classList.contains('pu-green')).toBe(true);
|
||||
expect(wins[1].querySelector('.pu-val')!.textContent).toBe('104%');
|
||||
expect(wins[1].querySelector<HTMLElement>('.pu-meter > i')!.style.width).toBe('100%');
|
||||
expect(wins[1].querySelector('.pu-meter')!.classList.contains('pu-red')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps an idle Claude window as a dimmed slot with an empty ring and meter', () => {
|
||||
const app = makeApp();
|
||||
app.updatePlanUsageChip({ sevenDay: { usedPercentage: 35 } });
|
||||
const idle = document.querySelector<HTMLElement>('#planUsageChip .pu-win-idle')!;
|
||||
expect(idle.querySelector('.pu-val')!.textContent).toBe('—');
|
||||
expect(idle.querySelector<HTMLElement>('.pu-ring')!.style.getPropertyValue('--pu')).toBe('0');
|
||||
expect(idle.querySelector<HTMLElement>('.pu-meter > i')!.style.width).toBe('0%');
|
||||
});
|
||||
|
||||
it('names the connection state in two short words per dot state', () => {
|
||||
const app = makeApp();
|
||||
const words = (dotClass: string, text = '') => app._connectionTileWords({ dotClass, text });
|
||||
expect(words('connection-dot connected', 'WS')).toMatchObject({ label: 'WS', value: 'live', state: 'connected' });
|
||||
expect(words('connection-dot fallback', 'HTTP')).toMatchObject({ label: 'HTTP', value: 'fallback' });
|
||||
expect(words('connection-dot offline', 'Offline')).toMatchObject({ label: 'NET', value: 'offline' });
|
||||
expect(words('connection-dot draining', 'Sending...')).toMatchObject({ label: 'SEND', value: 'queued' });
|
||||
expect(words('connection-dot reconnecting', 'WS…')).toMatchObject({ label: 'WS', value: 'retry' });
|
||||
expect(words('connection-dot reconnecting', 'Reconnecting...')).toMatchObject({ label: 'SSE', value: 'retry' });
|
||||
});
|
||||
|
||||
it('writes the tile words beside the classic text, which stays as it was', () => {
|
||||
const app = makeApp();
|
||||
app._computeConnectionDescriptor = () => ({
|
||||
display: 'flex',
|
||||
dotClass: 'connection-dot connected',
|
||||
text: 'WS · 2.0KB queued',
|
||||
title: 'Terminal connected over WebSocket',
|
||||
});
|
||||
app._updateConnectionIndicator();
|
||||
expect(document.getElementById('connectionText')!.textContent).toBe('WS · 2.0KB queued');
|
||||
expect(document.getElementById('connectionTileLabel')!.textContent).toBe('WS');
|
||||
expect(document.getElementById('connectionTileValue')!.textContent).toBe('live');
|
||||
expect(document.getElementById('connectionTileValue')!.className).toBe('connection-tile-value connected');
|
||||
});
|
||||
|
||||
it('draws the sparkline newest-right, with a 10% floor and only real samples', () => {
|
||||
const app = makeApp();
|
||||
const bars = () =>
|
||||
[...document.querySelectorAll<HTMLElement>('#statCpuSpark > i')].map((bar) => bar.style.height);
|
||||
app._pushStatSpark('cpu', 40);
|
||||
expect(bars()).toEqual(['', '', '', '40%']);
|
||||
app._pushStatSpark('cpu', 2);
|
||||
app._pushStatSpark('cpu', 250);
|
||||
app._pushStatSpark('cpu', 60);
|
||||
app._pushStatSpark('cpu', 70);
|
||||
expect(bars()).toEqual(['10%', '100%', '60%', '70%']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('header stats wiring (static)', () => {
|
||||
const css = read('styles.css');
|
||||
|
||||
it('hides the new-style parts by default, so classic looks exactly as before', () => {
|
||||
expect(css).toMatch(
|
||||
/\.stat-spark,\s*\.connection-tile-label,\s*\.connection-tile-value,\s*\.header-plan-usage \.pu-ring,\s*\.header-plan-usage \.pu-meter \{\s*display: none;/
|
||||
);
|
||||
});
|
||||
|
||||
it('stamps data-header-stats before first paint, tiles by default and classic on narrow screens', () => {
|
||||
expect(INDEX).toContain(
|
||||
"dataset.headerStats=(window.innerWidth<768||solo)?'classic':(H==='classic'||H==='compact')?H:'tiles'"
|
||||
);
|
||||
});
|
||||
|
||||
it('offers the three styles with tiles marked as the default', () => {
|
||||
expect(INDEX).toMatch(
|
||||
/<select id="appSettingsHeaderStatsStyle"[^>]*>\s*<option value="classic">[^<]+<\/option>\s*<option value="compact">[^<]+<\/option>\s*<option value="tiles">Tiles \(default\)<\/option>/
|
||||
);
|
||||
});
|
||||
});
|
||||
+11
-10
@@ -205,10 +205,11 @@ describe('vertical tab rail row order', () => {
|
||||
it('keeps the Alt+N badge on the tab index while the cards are sorted', () => {
|
||||
// `_tabIdx` counts the loop over sessionOrder, and only `style="order:…"`
|
||||
// moves the card — so the badge names a shortcut, not a row position.
|
||||
expect(appJs).toContain(
|
||||
'const railSortOrder = this._tabRailSortOrder(tabOrder.filter((id) => this.sessions.has(id)));'
|
||||
);
|
||||
expect(appJs).toContain('` style="order:${railSortOrder.get(id)}"`');
|
||||
// `listOrder` is the rail sort's map, or the state grouping's when that is
|
||||
// on (test/tab-triage.test.ts); either way it only sets the inline order.
|
||||
expect(appJs).toContain('const liveIds = tabOrder.filter((id) => this.sessions.has(id));');
|
||||
expect(appJs).toContain('const railSortOrder = this._tabRailSortOrder(liveIds);');
|
||||
expect(appJs).toContain('` style="order:${listOrder.get(id)}"`');
|
||||
expect(appJs).toMatch(/_tabIdx < 9 \? '<span class="tab-number">' \+ \(_tabIdx \+ 1\)/);
|
||||
// The loop itself still walks the user's order, which is what makes the
|
||||
// badge, drag-and-drop and the arrow-key walk agree with each other.
|
||||
@@ -219,12 +220,11 @@ describe('vertical tab rail row order', () => {
|
||||
// A session going working→idle never adds or removes a tab, so the full
|
||||
// rebuild is not reached — and a rebuild here would restart every card's
|
||||
// animation on every SSE tick anyway.
|
||||
expect(appJs).toContain(
|
||||
'const railSortOrder = this._tabRailSortOrder(this.sessionOrder.filter((sid) => this.sessions.has(sid)));'
|
||||
);
|
||||
expect(appJs).toContain('const liveIds = this.sessionOrder.filter((sid) => this.sessions.has(sid));');
|
||||
expect(appJs).toContain('const railSortOrder = this._tabRailSortOrder(liveIds);');
|
||||
expect(appJs).toContain('if (tab.style.order !== railOrder) tab.style.order = railOrder;');
|
||||
// An empty string is what clears the property when the rail stops sorting.
|
||||
expect(appJs).toContain("const railOrder = railSortOrder?.has(id) ? String(railSortOrder.get(id)) : '';");
|
||||
expect(appJs).toContain("const railOrder = listOrder?.has(id) ? String(listOrder.get(id)) : '';");
|
||||
});
|
||||
|
||||
it('drops the drag affordance while sorting, so a card cannot snap back', () => {
|
||||
@@ -280,9 +280,10 @@ describe('vertical tab rail sort setting', () => {
|
||||
expect(html).toContain("document.documentElement.dataset.tabRailSort='activity';");
|
||||
expect(settingsUi).toContain('root.dataset.tabRailSort = sort;');
|
||||
// A sort flip leaves orientation on 'vertical' both times, so it has to
|
||||
// count as a change of its own or nothing re-renders.
|
||||
// count as a change of its own or nothing re-renders. The same holds for a
|
||||
// grouping flip (tabGrouping, test/tab-triage.test.ts).
|
||||
expect(settingsUi).toContain(
|
||||
'const changed = orientationChanged || previousDetail !== detail || previousSort !== sort;'
|
||||
'const changed = orientationChanged || previousDetail !== detail || previousSort !== sort || previousGrouping !== grouping;'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
/**
|
||||
* @fileoverview Tab grouping by state (`tabGrouping: 'state'`, Discussion #426
|
||||
* option C): the pure layout in constants.js and the render paths in app.js.
|
||||
*
|
||||
* What is pinned, and why it matters:
|
||||
* - The four groups and their order (needs you, waiting, working, idle) and
|
||||
* which home-screen state lands in which, including the two folds that are
|
||||
* easy to get wrong: a failed session joins "needs you", and an agent that
|
||||
* exited inside a live pane (#446) is idle even while its status says busy.
|
||||
* - It is applied as flex `order` only. The DOM stays in tab order, so Alt+N
|
||||
* badges, drag and the keyboard walk keep reading the list they always read.
|
||||
* - A state change is an INCREMENTAL pass: the tab element survives, only its
|
||||
* `order` and the heading counts move, and a group that empties loses its
|
||||
* heading.
|
||||
* - `tabGrouping: 'none'` leaves no trace (no headings, no inline order, no
|
||||
* class), and named groups in the vertical rail win over it.
|
||||
*
|
||||
* The real modules run INSIDE a JSDOM window (runScripts: 'outside-only'), so
|
||||
* `document` below is that window's.
|
||||
*
|
||||
* Port: none.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PUBLIC = join(process.cwd(), 'src/web/public');
|
||||
const read = (name: string) => readFileSync(join(PUBLIC, name), 'utf8');
|
||||
|
||||
type Row = { id: string; state: string; exited?: boolean; pos?: number };
|
||||
type Layout = {
|
||||
order: Map<string, number>;
|
||||
webOrder: Map<string, number>;
|
||||
groups: Array<{ key: string; label: string; count: number; headOrder: number; breakOrder: number }>;
|
||||
};
|
||||
type Triage = {
|
||||
GROUPS: Array<{ key: string; label: string }>;
|
||||
STRIDE: number;
|
||||
groupFor: (state: string, exited: boolean) => string;
|
||||
layout: (rows: Row[], webviewIds?: string[]) => Layout;
|
||||
};
|
||||
|
||||
function loadTriage(): Triage {
|
||||
const context = vm.createContext({ window: {}, globalThis: {} });
|
||||
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
|
||||
return (context.window as { CodemanTabTriage: Triage }).CodemanTabTriage;
|
||||
}
|
||||
|
||||
describe('CodemanTabTriage (pure)', () => {
|
||||
const triage = loadTriage();
|
||||
|
||||
it('has four groups, most urgent first', () => {
|
||||
expect(triage.GROUPS.map((g) => g.key)).toEqual(['needs', 'waiting', 'working', 'idle']);
|
||||
expect(triage.GROUPS.map((g) => g.label)).toEqual(['Needs you', 'Waiting', 'Working', 'Idle']);
|
||||
});
|
||||
|
||||
it('folds the six home-screen states into the four groups', () => {
|
||||
expect(triage.groupFor('needs', false)).toBe('needs');
|
||||
expect(triage.groupFor('error', false)).toBe('needs');
|
||||
expect(triage.groupFor('waiting', false)).toBe('waiting');
|
||||
expect(triage.groupFor('working', false)).toBe('working');
|
||||
expect(triage.groupFor('idle', false)).toBe('idle');
|
||||
expect(triage.groupFor('done', false)).toBe('idle');
|
||||
expect(triage.groupFor('something-new', false)).toBe('idle');
|
||||
});
|
||||
|
||||
it('puts an exited agent with idle, never with working', () => {
|
||||
expect(triage.groupFor('working', true)).toBe('idle');
|
||||
expect(triage.groupFor('idle', true)).toBe('idle');
|
||||
// A human being blocked still outranks the agent having exited.
|
||||
expect(triage.groupFor('needs', true)).toBe('needs');
|
||||
expect(triage.groupFor('waiting', true)).toBe('waiting');
|
||||
});
|
||||
|
||||
it('gives each group a band of order values and lists only non-empty groups', () => {
|
||||
const out = triage.layout([
|
||||
{ id: 'a', state: 'idle', pos: 0 },
|
||||
{ id: 'b', state: 'needs', pos: 1 },
|
||||
{ id: 'c', state: 'idle', pos: 2 },
|
||||
]);
|
||||
expect(out.groups.map((g) => [g.key, g.count])).toEqual([
|
||||
['needs', 1],
|
||||
['idle', 2],
|
||||
]);
|
||||
const needs = out.groups[0];
|
||||
const idle = out.groups[1];
|
||||
expect(out.order.get('b')).toBeGreaterThan(needs.headOrder);
|
||||
expect(out.order.get('b')).toBeLessThan(needs.breakOrder);
|
||||
// Rows keep their relative position inside a group.
|
||||
expect(out.order.get('a')).toBeLessThan(out.order.get('c')!);
|
||||
expect(out.order.get('a')).toBeGreaterThan(idle.headOrder);
|
||||
// A heading opens its band, the break closes it, and bands never overlap.
|
||||
expect(needs.breakOrder).toBeLessThan(idle.headOrder);
|
||||
expect(Math.floor(out.order.get('b')! / triage.STRIDE)).toBe(Math.floor(needs.headOrder / triage.STRIDE));
|
||||
});
|
||||
|
||||
it('ranks rows inside a group by `pos`, stably', () => {
|
||||
const out = triage.layout([
|
||||
{ id: 'x', state: 'working', pos: 5 },
|
||||
{ id: 'y', state: 'working', pos: 1 },
|
||||
{ id: 'z', state: 'working', pos: 1 },
|
||||
]);
|
||||
const sorted = [...out.order.entries()].sort((p, q) => p[1] - q[1]).map(([id]) => id);
|
||||
expect(sorted).toEqual(['y', 'z', 'x']);
|
||||
});
|
||||
|
||||
it('closes the idle group with the web tabs and counts them', () => {
|
||||
const out = triage.layout([{ id: 's', state: 'idle', pos: 0 }], ['w1', 'w2']);
|
||||
expect(out.groups).toHaveLength(1);
|
||||
expect(out.groups[0]).toMatchObject({ key: 'idle', count: 3 });
|
||||
expect(out.webOrder.get('w1')).toBeGreaterThan(out.order.get('s')!);
|
||||
expect(out.webOrder.get('w2')).toBeGreaterThan(out.webOrder.get('w1')!);
|
||||
expect(out.webOrder.get('w2')).toBeLessThan(out.groups[0].breakOrder);
|
||||
});
|
||||
|
||||
it('shows the idle group for web tabs alone, and nothing for nothing', () => {
|
||||
expect(triage.layout([], ['w1']).groups.map((g) => g.key)).toEqual(['idle']);
|
||||
expect(triage.layout([], []).groups).toEqual([]);
|
||||
expect(triage.layout(undefined as unknown as Row[], undefined).groups).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tab grouping in the render paths (app.js)', () => {
|
||||
let CodemanApp: { prototype: Record<string, any> };
|
||||
let window: any;
|
||||
let document: Document;
|
||||
|
||||
beforeAll(async () => {
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
|
||||
url: 'https://localhost/',
|
||||
runScripts: 'outside-only',
|
||||
});
|
||||
if (dom.window.document.readyState !== 'complete') {
|
||||
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
|
||||
}
|
||||
window = dom.window;
|
||||
document = window.document;
|
||||
window.setInterval = () => 0;
|
||||
window.requestAnimationFrame = () => 0;
|
||||
window.CSS = { escape: (value: string) => value };
|
||||
window.eval(
|
||||
'var MobileDetection = { isTouchDevice: () => false, getDeviceType: () => "desktop" }, KeyboardHandler = {}, ' +
|
||||
'SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
|
||||
read('constants.js') +
|
||||
'\n' +
|
||||
read('tab-layout-browser.js') +
|
||||
'\n' +
|
||||
read('app.js') +
|
||||
'\n' +
|
||||
read('mobile-overview.js') +
|
||||
'\n' +
|
||||
read('webview-tabs.js') +
|
||||
'\n;window.__TriageCodemanApp = CodemanApp;'
|
||||
);
|
||||
CodemanApp = window.__TriageCodemanApp;
|
||||
});
|
||||
|
||||
function makeApp(grouping: 'state' | 'none' = 'state') {
|
||||
const app = Object.create(CodemanApp.prototype) as Record<string, any>;
|
||||
const root = document.documentElement;
|
||||
root.setAttribute('data-tab-orientation', 'horizontal');
|
||||
root.dataset.tabRailSort = 'activity';
|
||||
root.dataset.tabGrouping = grouping;
|
||||
document.body.innerHTML = '<div class="session-tabs-host"><div id="sessionTabs" class="session-tabs"></div></div>';
|
||||
app.$ = (id: string) => document.getElementById(id);
|
||||
app.sessions = new Map([
|
||||
['s1', { id: 's1', name: 'w1-alpha', status: 'idle' }],
|
||||
['s2', { id: 's2', name: 'w2-beta', status: 'busy' }],
|
||||
['s3', { id: 's3', name: 'w3-gamma', status: 'idle' }],
|
||||
['s4', { id: 's4', name: 'w4-delta', status: 'busy' }],
|
||||
]);
|
||||
app.sessionOrder = ['s1', 's2', 's3', 's4'];
|
||||
app.pendingHooks = new Map([
|
||||
['s3', new Set(['permission_prompt'])],
|
||||
['s1', new Set(['idle_prompt'])],
|
||||
]);
|
||||
app.webviews = new Map([['w1', { id: 'w1', name: 'Dashboard', url: 'https://example.test' }]]);
|
||||
app.webviewOrder = ['w1'];
|
||||
app.activeSessionId = 's2';
|
||||
app.activeWebviewId = null;
|
||||
app.tabLayout = null;
|
||||
app.collapsedTabGroupIds = new Set();
|
||||
app._hiddenTabGroupByRef = new Map();
|
||||
app._lastTabGroupStructureKey = null;
|
||||
app._inlineRenameActive = false;
|
||||
app.tabAlerts = new Map();
|
||||
app.terminalLoadStates = new Map();
|
||||
app.minimizedSubagents = new Map();
|
||||
app.hasTabDetachOverride = () => false;
|
||||
app.renderSubagentTabBadge = () => '';
|
||||
app.cancelHideSubagentDropdown = () => {};
|
||||
app.updateTabOverflowMode = () => {};
|
||||
app.updateConnectionLines = vi.fn();
|
||||
app._applyTabEntrances = () => {};
|
||||
app._scrollActiveTabIntoView = () => {};
|
||||
app._refreshMobileOverviewIfVisible = () => {};
|
||||
app._refreshHomeSessionsIfVisible = () => {};
|
||||
app.applySidebarFilter = () => {};
|
||||
return app;
|
||||
}
|
||||
|
||||
const container = () => document.getElementById('sessionTabs')!;
|
||||
const tab = (id: string) => container().querySelector<HTMLElement>(`.session-tab[data-id="${id}"]`)!;
|
||||
const orderOf = (el: HTMLElement) => Number(el.style.order);
|
||||
/** What the eye sees: every ordered child, by `order`, as `head:<key>` / `<id>`. */
|
||||
const visual = () =>
|
||||
[...container().children]
|
||||
.filter((el) => !(el as HTMLElement).classList.contains('tab-triage-break'))
|
||||
.sort((a, b) => orderOf(a as HTMLElement) - orderOf(b as HTMLElement))
|
||||
.map((el) => {
|
||||
const h = el as HTMLElement;
|
||||
if (h.classList.contains('tab-triage-head')) return `head:${h.dataset.triageGroup}`;
|
||||
return h.dataset.webviewId ? `web:${h.dataset.webviewId}` : h.dataset.id!;
|
||||
});
|
||||
const heads = () =>
|
||||
[...container().querySelectorAll<HTMLElement>(':scope > .tab-triage-head')]
|
||||
.sort((a, b) => orderOf(a) - orderOf(b))
|
||||
.map((h) => `${h.querySelector('.tab-triage-label')!.textContent}:${h.querySelector('.tab-triage-count')!.textContent}`);
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('draws a heading per non-empty state and places every tab in its group', () => {
|
||||
makeApp()._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('tabs-triage')).toBe(true);
|
||||
expect(heads()).toEqual(['Needs you:1', 'Waiting:1', 'Working:2', 'Idle:1']);
|
||||
expect(visual()).toEqual([
|
||||
'head:needs',
|
||||
's3',
|
||||
'head:waiting',
|
||||
's1',
|
||||
'head:working',
|
||||
's2',
|
||||
's4',
|
||||
'head:idle',
|
||||
'web:w1',
|
||||
]);
|
||||
// One row break per heading; headings and breaks stay out of the tablist.
|
||||
expect(container().querySelectorAll(':scope > .tab-triage-break')).toHaveLength(4);
|
||||
for (const el of container().querySelectorAll(':scope > .tab-triage-head, :scope > .tab-triage-break')) {
|
||||
expect(el.getAttribute('aria-hidden')).toBe('true');
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the DOM, and with it the Alt+N badges, in tab order', () => {
|
||||
makeApp()._fullRenderSessionTabs();
|
||||
const domOrder = [...container().querySelectorAll<HTMLElement>('.session-tab[data-id]')].map((t) => t.dataset.id);
|
||||
expect(domOrder).toEqual(['s1', 's2', 's3', 's4']);
|
||||
expect(tab('s3').querySelector('.tab-number')?.textContent).toBe('3');
|
||||
});
|
||||
|
||||
it('moves a tab between groups on an incremental pass, without rebuilding it', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
const s2 = tab('s2');
|
||||
const fullRender = vi.spyOn(app, '_fullRenderSessionTabs');
|
||||
// s2 finishes its turn; the dialog on s3 is answered.
|
||||
app.sessions.get('s2').status = 'idle';
|
||||
app.pendingHooks.delete('s3');
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(fullRender).not.toHaveBeenCalled();
|
||||
expect(tab('s2')).toBe(s2);
|
||||
expect(heads()).toEqual(['Waiting:1', 'Working:1', 'Idle:3']);
|
||||
expect(container().querySelector('.tab-triage-head[data-triage-group="needs"]')).toBeNull();
|
||||
expect(container().querySelector('.tab-triage-break[data-triage-group="needs"]')).toBeNull();
|
||||
expect(visual()).toEqual(['head:waiting', 's1', 'head:working', 's4', 'head:idle', 's2', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it('reconciles headings in place: an unchanged pass rewrites nothing', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
app._renderSessionTabsImmediate();
|
||||
const head = container().querySelector('.tab-triage-head[data-triage-group="working"]');
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(container().querySelector('.tab-triage-head[data-triage-group="working"]')).toBe(head);
|
||||
expect(container().querySelectorAll(':scope > .tab-triage-head')).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('files an agent that exited in a live pane under idle, a failed session under needs you', () => {
|
||||
const app = makeApp();
|
||||
app.pendingHooks = new Map();
|
||||
app.sessions.get('s2').paneExit = { at: 1, status: 0 };
|
||||
app.sessions.get('s1').status = 'error';
|
||||
app._fullRenderSessionTabs();
|
||||
expect(visual()).toEqual(['head:needs', 's1', 'head:working', 's4', 'head:idle', 's2', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it("leaves no trace with tabGrouping 'none'", () => {
|
||||
makeApp('none')._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
expect(container().querySelector('.tab-triage-head, .tab-triage-break')).toBeNull();
|
||||
expect(container().innerHTML).not.toContain('order:');
|
||||
expect(container().querySelector<HTMLElement>('.session-tab[data-webview-id]')!.style.order).toBe('');
|
||||
});
|
||||
|
||||
it('switching off removes the headings and every inline order it wrote', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
document.documentElement.dataset.tabGrouping = 'none';
|
||||
app._renderSessionTabsImmediate();
|
||||
expect(container().querySelector('.tab-triage-head, .tab-triage-break')).toBeNull();
|
||||
for (const el of container().querySelectorAll<HTMLElement>('.session-tab')) expect(el.style.order).toBe('');
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
});
|
||||
|
||||
it('ranks rows inside each section by the activity sort on a sorted rail', () => {
|
||||
const app = makeApp();
|
||||
document.documentElement.setAttribute('data-tab-orientation', 'vertical');
|
||||
app.pendingHooks = new Map();
|
||||
// Both working; s4 has been running longer, so the activity sort puts it first.
|
||||
app.sessions.get('s2').lastSubmitAt = 2_000;
|
||||
app.sessions.get('s4').lastSubmitAt = 1_000;
|
||||
app._fullRenderSessionTabs();
|
||||
expect(visual()).toEqual(['head:working', 's4', 's2', 'head:idle', 's1', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it('keeps tab order inside each row on the header strip', () => {
|
||||
const app = makeApp();
|
||||
app.pendingHooks = new Map();
|
||||
app.sessions.get('s2').lastSubmitAt = 2_000;
|
||||
app.sessions.get('s4').lastSubmitAt = 1_000;
|
||||
app._fullRenderSessionTabs();
|
||||
expect(visual()).toEqual(['head:working', 's2', 's4', 'head:idle', 's1', 's3', 'web:w1']);
|
||||
});
|
||||
|
||||
it('lets named groups in the vertical rail win', () => {
|
||||
const app = makeApp();
|
||||
document.documentElement.setAttribute('data-tab-orientation', 'vertical');
|
||||
app.tabLayout = {
|
||||
version: 1,
|
||||
groups: [{ id: 'g1', name: 'Core', refs: [{ kind: 'session', id: 's1' }] }],
|
||||
ungrouped: [],
|
||||
};
|
||||
app._fullRenderSessionTabs();
|
||||
expect(container().classList.contains('session-tabs--grouped')).toBe(true);
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
expect(container().querySelector('.tab-triage-head')).toBeNull();
|
||||
});
|
||||
|
||||
it('refuses a drop into another group and allows one inside the same group', () => {
|
||||
const app = makeApp();
|
||||
app._fullRenderSessionTabs();
|
||||
app.draggedTabId = 's2';
|
||||
expect(app._isTabDropAcrossTriageGroups(tab('s4'))).toBe(false);
|
||||
expect(app._isTabDropAcrossTriageGroups(tab('s1'))).toBe(true);
|
||||
expect(app._isTabDropAcrossTriageGroups(tab('s3'))).toBe(true);
|
||||
document.documentElement.dataset.tabGrouping = 'none';
|
||||
app._fullRenderSessionTabs();
|
||||
expect(app._isTabDropAcrossTriageGroups(tab('s1'))).toBe(false);
|
||||
});
|
||||
|
||||
it('degrades to the flat strip when mobile-overview.js is stale or missing', () => {
|
||||
const app = makeApp();
|
||||
app._mobileOverviewState = undefined;
|
||||
app._fullRenderSessionTabs();
|
||||
expect(container().querySelector('.tab-triage-head')).toBeNull();
|
||||
expect(container().classList.contains('tabs-triage')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tab grouping wiring (static)', () => {
|
||||
const html = read('index.html');
|
||||
const css = read('styles.css');
|
||||
const mobileCss = read('mobile.css');
|
||||
|
||||
it('stamps data-tab-grouping before first paint, defaulting to state', () => {
|
||||
expect(html).toContain("dataset.tabGrouping=(A.tabGrouping==='none')?'none':'state'");
|
||||
// The catch branch (localStorage threw) must set it too.
|
||||
expect(html).toContain("document.documentElement.dataset.tabGrouping='state';");
|
||||
});
|
||||
|
||||
it('offers the setting with "By state" as the default', () => {
|
||||
expect(html).toMatch(/<select id="appSettingsTabGrouping"[^>]*>\s*<option value="state">By state \(default\)<\/option>\s*<option value="none">/);
|
||||
});
|
||||
|
||||
it('only shows row breaks in a wrapping header strip', () => {
|
||||
expect(css).toMatch(/\.tab-triage-break \{\s*display: none;/);
|
||||
expect(css).toContain(
|
||||
'.session-tabs-host > .session-tabs.tabs-triage:is(.tabs-auto-wrap, .tabs-two-rows) > .tab-triage-break'
|
||||
);
|
||||
});
|
||||
|
||||
it('hides the headings on phones, whose strip stays one scrolling row', () => {
|
||||
expect(mobileCss).toMatch(/:where\(\.header\) \.tab-triage-head \{\s*display: none;/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user