// Requested 2026-11-28: every account list sorts by the provider it SHOWS, then by // the account name it SHOWS, alphabetical and case-insensitive. Local rows stay // before cloud rows (owner 2026-10-29) and the sort applies inside each group. // Display-only: the canonical am.accounts array is never reordered, so routing and // every index-keyed action keep addressing the original row. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import vm from 'node:vm'; import { TUI, __tuiTest } from '../src/tui.js'; import { AccountManager } from '../src/account-manager.js'; import { PoolLink, remoteIdentities } from '../src/pool-link.js'; const { strip, providerLabel } = __tuiTest; // Synthetic names only. Deliberately unsorted, mixed case, and with the provider // families in reverse-alphabetical array order (Moonshot rows before Anthropic). const LOCAL = [ { name: 'zeta api', type: 'apikey', apiKey: 'k-z', accountUuid: 'UZ' }, { name: 'Kimi team', type: 'provider', provider: 'kimi', authToken: 'key-1', upstream: 'http://x', profiles: ['all'] }, { name: 'alpha claude', type: 'oauth', accessToken: 't1', refreshToken: 'r1', expiresAt: Date.now() + 36e5, accountUuid: 'UA' }, { name: 'glm beta', type: 'provider', provider: 'zai', authToken: 'key-2', upstream: 'http://x', profiles: ['all'] }, { name: 'Z.ai alpha', type: 'provider', provider: 'zai', authToken: 'key-3', upstream: 'http://x', profiles: ['all'] }, { name: 'mid claude', type: 'oauth', accessToken: 't2', refreshToken: 'r2', expiresAt: Date.now() + 36e5, accountUuid: 'UM' }, { name: 'codex one', type: 'provider', provider: 'codex', authToken: 'key-4', upstream: 'http://x', profiles: ['all'] }, ]; function build() { const am = new AccountManager(structuredClone(LOCAL), 0.9); const link = new PoolLink({ name: 'team', url: 'http://x', key: 'k' }); link.lastOkAt = 1; link.lastError = null; const ra = (name, type, provider, extra = {}) => ({ name, type, provider, enabled: true, status: 'active', inFlight: 0, quota: {}, ...extra }); link.status = { accounts: [ ra('cloud kimi', 'provider', 'kimi'), ra('cloud Anthropic', 'oauth', 'anthropic', { accountUuid: 'UC1' }), ra('cloud glm', 'provider', 'zai'), ra('Cloud claude', 'oauth', 'anthropic', { accountUuid: 'UC2' }), ] }; link.identities = remoteIdentities(link.status); am.setPoolLinks([link]); const tui = new TUI({ accountManager: am, config: {} }); return { am, tui }; } const shownName = (am, i) => { const a = am.accounts[i]; return a.remote ? a.remote.remoteName : a.name; }; const shownRows = (am, tui) => tui._displayOrder().map(i => `${providerLabel(am.accounts[i])}|${shownName(am, i)}`); // Alphabetical by the DISPLAYED provider label, then by the displayed name, case-insensitive. // Terminal labels: Anthropic, Codex, Moonshot (Kimi), z.ai. const EXPECTED = [ 'Anthropic|alpha claude', 'Anthropic|mid claude', 'Anthropic|zeta api', 'Codex|codex one', 'Moonshot|Kimi team', 'z.ai|glm beta', 'z.ai|Z.ai alpha', 'Anthropic|cloud Anthropic', 'Anthropic|Cloud claude', 'Moonshot|cloud kimi', 'z.ai|cloud glm', ]; test('display order: provider as shown, then name as shown, case-insensitive, local before cloud', () => { const { am, tui } = build(); assert.deepEqual(shownRows(am, tui), EXPECTED); }); test('display order is a view: the canonical account array and its indices are untouched', () => { const { am, tui } = build(); const before = am.accounts.map(a => a.name); tui._displayOrder(); assert.deepEqual(am.accounts.map(a => a.name), before); assert.deepEqual(am.accounts.map(a => a.index), before.map((_, i) => i), 'account.index still equals the array position'); // The order is NOT the array order, i.e. the test above is not passing vacuously. assert.notDeepEqual(tui._displayOrder(), am.accounts.map((_, i) => i)); }); test('stable on re-login: a fresh account array rebuilt in a different add order shows the same rows', () => { const a = build(); const b_am = new AccountManager(structuredClone(LOCAL).reverse(), 0.9); const link = a.am.poolLinks[0]; b_am.setPoolLinks([link]); const b = new TUI({ accountManager: b_am, config: {} }); const localOnly = rows => rows.filter(r => !r.includes('☁')); assert.notDeepEqual(b_am.accounts.map(x => x.name), a.am.accounts.map(x => x.name), 'sanity: the arrays really differ'); assert.deepEqual(localOnly(shownRows(b_am, b)), localOnly(shownRows(a.am, a.tui))); }); test('selection walks the visible order and acts on the ORIGINAL index', () => { const { am, tui } = build(); const order = tui._displayOrder(); const toggle = tui._selectableIndexes('toggle'); assert.deepEqual(toggle, order, 'nav order is the display order'); // Step down twice from the top: the third visible row must be the account shown third. tui.mode = 'select'; tui.selAction = 'toggle'; tui.selIdx = toggle[0]; tui._keySelect('down'); tui._keySelect('down'); assert.equal(shownName(am, tui.selIdx), 'zeta api', 'the highlight is on the third visible row'); assert.equal(am.accounts[tui.selIdx].name, 'zeta api', 'and it resolves to that row\'s real account object'); // An index-keyed action targets the same row it addressed before the sort. const target = am.accounts.findIndex(a => a.name === 'Kimi team'); assert.equal(providerLabel(am.accounts[target]), 'Moonshot'); assert.ok(order.includes(target), 'the Kimi row is still addressed by its canonical index'); // "prefer" never offers a provider and stays in display order. assert.deepEqual(tui._selectableIndexes('prefer').map(i => shownName(am, i)), ['alpha claude', 'mid claude', 'zeta api', 'cloud Anthropic', 'Cloud claude']); assert.ok(tui._selectableIndexes('prefer').every(i => am.accounts[i].type !== 'provider' && am.accounts[i].enabled)); }); test('the rendered terminal table lists rows in that order', () => { const { tui } = build(); const ow = process.stdout.write; const cols = Object.getOwnPropertyDescriptor(process.stdout, 'columns'); const rows = Object.getOwnPropertyDescriptor(process.stdout, 'rows'); let buf = ''; try { Object.defineProperty(process.stdout, 'columns', { value: 200, configurable: true }); Object.defineProperty(process.stdout, 'rows', { value: 60, configurable: true }); process.stdout.write = s => { buf += s; return true; }; tui._render(); } finally { process.stdout.write = ow; cols ? Object.defineProperty(process.stdout, 'columns', cols) : delete process.stdout.columns; rows ? Object.defineProperty(process.stdout, 'rows', rows) : delete process.stdout.rows; } const text = strip(buf); const at = name => text.indexOf(name); const seq = ['alpha claude', 'mid claude', 'zeta api', 'codex one', 'Kimi team', 'glm beta', 'Z.ai alpha', 'cloud Anthropic', 'Cloud claude', 'cloud kimi', 'cloud glm']; for (const n of seq) assert.ok(at(n) >= 0, `"${n}" renders`); for (let k = 1; k < seq.length; k++) { assert.ok(at(seq[k - 1]) < at(seq[k]), `"${seq[k - 1]}" renders above "${seq[k]}"`); } }); // ── Web dashboard (src/screen.html): the same sort on both of its lists ───────── const html = readFileSync(new URL('../src/screen.html', import.meta.url), 'utf8'); const script = html.slice(html.indexOf('')); async function renderScreen(status) { const app = { innerHTML: '' }; const stub = { onclick: null, onkeydown: null, value: '' }; vm.runInNewContext(script, { document: { getElementById: id => (id === 'app' ? app : stub) }, localStorage: { getItem: () => 'k', setItem() {}, removeItem() {} }, fetch: async () => ({ status: 200, ok: true, json: async () => status }), setTimeout: () => 0, clearTimeout: () => {}, console, Date, Object, String, Math, isFinite, }); await new Promise(r => setImmediate(r)); await new Promise(r => setImmediate(r)); return app.innerHTML; } const webStatus = () => ({ accounts: [ { name: 'zeta api', type: 'apikey', provider: 'anthropic', quota: {} }, { name: 'Kimi team', type: 'provider', provider: 'kimi', quota: {} }, { name: 'alpha claude', type: 'oauth', provider: 'anthropic', quota: {} }, { name: 'glm beta', type: 'provider', provider: 'zai', quota: {} }, { name: 'Z.ai alpha', type: 'provider', provider: 'zai', quota: {} }, { name: 'mid claude', type: 'oauth', provider: 'anthropic', quota: {} }, { name: 'codex one', type: 'provider', provider: 'codex', quota: {} }, ], pools: [{ name: 'team', ok: true, accounts: [ { name: 'cloud kimi', type: 'provider', provider: 'kimi', quota: {} }, { name: 'cloud Anthropic', type: 'oauth', provider: 'anthropic', quota: {} }, { name: 'cloud glm', type: 'provider', provider: 'zai', quota: {} }, { name: 'Cloud claude', type: 'oauth', provider: 'anthropic', quota: {} }, ] }], }); // Read the names back out of the rendered cards, in page order. function cardOrder(out) { return [...out.matchAll(/