maxpool 1.24.94 → 1.24.96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tui.js CHANGED
@@ -1,14 +1,19 @@
1
1
  import { createInterface } from 'node:readline';
2
+ import { spawn } from 'node:child_process';
2
3
  import { readFileSync, writeSync } from 'node:fs';
3
4
  import { isatty } from 'node:tty';
4
5
  import { homedir } from 'node:os';
5
- import { fetchProfile, loginOAuth, tokenFingerprint, isLoginCancelled } from './oauth.js';
6
+ import { fetchProfile, loginOAuth, tokenFingerprint, isLoginCancelled, sameUser, sameAccountIdentity, organizationUnknownMatch, resolveOrganizations, suggestAccountName, knownDifferentOrg } from './oauth.js';
6
7
  import { appendEventLog, setConsoleStdoutSuppressed } from './event-log.js';
7
8
  import { sendLoginToPool } from './cloud-login.js';
8
9
  import { describeLinkError } from './pool-link.js';
9
- import { normalizeRemoteResets } from './account-manager.js';
10
+ import { normalizeRemoteResets, resolveStickyBusyBudget } from './account-manager.js';
10
11
  import { appliesTo } from './claude-reset-grants.js';
11
12
  import { LISTING_FRESH_MS } from './reset-timing.js';
13
+ import { cacheUsageLabel, cacheUsageState } from './usage-label.js';
14
+
15
+ // Running as the background service (tools/pool-service): set by its launchd plist.
16
+ const serviceMode = () => process.env.MAXPOOL_SERVICE === '1';
12
17
 
13
18
  // ── ANSI helpers ─────────────────────────────────────────────
14
19
 
@@ -27,6 +32,8 @@ const red = s => fg(31, s);
27
32
  const cyan = s => fg(36, s);
28
33
  const gray = s => fg(90, s);
29
34
  const dimUnderline = s => `${ESC}2;4m${s}${RESET}`;
35
+ // The cache figures of a request line, by whether the cache held (#642 port, 2026-11-15).
36
+ const CACHE_PAINT = { hit: green, partial: yellow, miss: red, none: dim };
30
37
 
31
38
  // Terminal output budget (2026-11-12: the pool froze for up to 60s inside a synchronous
32
39
  // TTY write() — a full-screen redraw per log line, 4.9 GB in 12h49m). Frames are
@@ -140,14 +147,16 @@ const vw = s => strip(s).length;
140
147
  // ── Accounts-table columns ───────────────────────────────────
141
148
  // Fixed column widths shared by the header row (acctHeader) AND every data row, so
142
149
  // the header labels stay aligned with the columns they name. The Account/Provider/
143
- // Status/Quota start offsets (4/25/35/49) are pure functions of these widths + the
144
- // 4-col row prefix, independent of the quota-bar width.
150
+ // Status/MRst/ARst/Quota start offsets are pure functions of these widths +
151
+ // the 4-col row prefix, independent of the quota-bar width.
145
152
  const NAME_W = 20; // a.name.slice(0, NAME_W).padEnd(NAME_W) — fits a full email like 2solarmax@gmail.com (19)
146
153
  const WHERE_W = 5; // 'Local' / 'Cloud' — where the account is provisioned
147
154
  const PROVIDER_W = 9; // providerLabel(a).padEnd(PROVIDER_W) — fits "Anthropic"
148
155
  const STATUS_W = 13; // rpad(status, STATUS_W) — fits "throttled 59s"
149
- const RESETS_W = 13; // 'Rst' column — FIXED width (fits '1+3Fable~118d': count AND expiry, owner 2026-11-11); a variable
150
- // width ('0' vs '1~21d') shifted every quota bar per row.
156
+ const MRST_W = 11; // 'MRst' column (model resets) — FIXED width (fits '2Fable~118d': count AND expiry, owner 2026-11-11);
157
+ // a variable width ('0' vs '1~21d') shifted every quota bar per row.
158
+ const ARST_W = 7; // 'ARst' column (account-level resets) — FIXED width (fits '1~118d?'); owner 2026-11-15: model and
159
+ // account resets in ONE mixed cell read as confusing, so they are two aligned columns.
151
160
  const ROW_PREFIX = ' '; // ' ' + sel(1) + cur(1) + ' ' — 4 cols before the name
152
161
 
153
162
  // Human provider name for the accounts-table "Provider" column. account.provider
@@ -171,8 +180,8 @@ function providerLabel(a) {
171
180
 
172
181
  /**
173
182
  * Aligned column header for the accounts table. Names the three columns that carry
174
- * NO inline label (Account / Type / Status) plus a group label over the two quota
175
- * bars (Quota). The per-bar naming (Ses/Wk for OAuth, Tok/Req for API keys) and the
183
+ * NO inline label (Account / Type / Status) plus a group label over the quota bars
184
+ * (Quota). The per-bar naming (Ses/Fbl/Wk for OAuth, Tok/Fbl/Req for API keys) and the
176
185
  * load fields (Now/15m/1h) stay inline per row — they're row-type-dependent and
177
186
  * begin at a variable offset — so the header stops after the Quota group label.
178
187
  */
@@ -183,7 +192,8 @@ function acctHeader(W) {
183
192
  + 'Where'.padEnd(WHERE_W) + ' '
184
193
  + 'Provider'.padEnd(PROVIDER_W) + ' '
185
194
  + 'Status'.padEnd(STATUS_W) + ' '
186
- + 'Rst'.padEnd(RESETS_W) + ' '
195
+ + 'MRst'.padEnd(MRST_W) + ' '
196
+ + 'ARst'.padEnd(ARST_W) + ' '
187
197
  + quota;
188
198
  }
189
199
 
@@ -193,6 +203,45 @@ function lpadVis(s, w) {
193
203
  return gap > 0 ? ' '.repeat(gap) + s : s;
194
204
  }
195
205
 
206
+ /**
207
+ * Which quota bars fit a terminal W columns wide, and how wide each bar is. The
208
+ * space before the first bar comes from the column widths above, never from a
209
+ * hard-coded number (the old number went stale when the reset columns were added).
210
+ * Each extra bar costs its label gap (" Fbl " or " Wk ") plus one bar width.
211
+ * Under 70 columns only the session bar shows, 5 to 20 wide; from 70 the weekly
212
+ * bar joins it, both 5 to 20 wide. The Fable bar joins only once all three can be
213
+ * 9 wide (118 columns), the narrowest bar that still shows "100% 2d5h", and three
214
+ * bars stop growing at 11 wide, so the row never passes column 124 and the tags
215
+ * after the bars (cap, prefer, staleness) keep the room they have with two bars.
216
+ * Narrower terminals keep today's two bars plus the "Fable NN%" tag.
217
+ * When no account reports a session window, the session bar is left out: the
218
+ * weekly bar always shows and the Fable bar joins it from 103 columns.
219
+ */
220
+ const BAR_START = ROW_PREFIX.length + NAME_W + 1 + WHERE_W + 1 + PROVIDER_W + 1 + STATUS_W + 1 + MRST_W + 1 + ARST_W + 1 + 'Ses '.length;
221
+ const BAR_GAP = ' Wk '.length;
222
+ const BAR_MIN_W = 5;
223
+ const BAR_MAX_W = 20;
224
+ const FABLE_BAR_MIN_W = 9;
225
+ const THREE_BAR_MAX_W = 11;
226
+ function barLayout(W, showSession = true) {
227
+ const showBoth = W >= 70 || !showSession;
228
+ const others = (showSession ? 1 : 0) + (showBoth ? 1 : 0);
229
+ const showFable = W >= BAR_START + (others + 1) * FABLE_BAR_MIN_W + others * BAR_GAP;
230
+ const bars = others + (showFable ? 1 : 0);
231
+ const free = W - BAR_START - (bars - 1) * BAR_GAP;
232
+ const fit = Math.floor(free / bars);
233
+ const maxW = bars === 3 ? THREE_BAR_MAX_W : BAR_MAX_W;
234
+ const bw = Math.max(BAR_MIN_W, Math.min(maxW, fit));
235
+ return { showSession, showBoth, showFable, bw };
236
+ }
237
+
238
+ /** True when the account's first bar (Ses, or Tok for an API key) has a reading. */
239
+ function hasSessionReading(a) {
240
+ const q = a?.quota || {};
241
+ if (a?.type === 'provider') return q.providerSes != null;
242
+ return q.unified5h != null || (q.tokensLimit != null && q.tokensRemaining != null);
243
+ }
244
+
196
245
  function rpad(s, w) {
197
246
  const gap = w - vw(s);
198
247
  return gap > 0 ? s + ' '.repeat(gap) : s;
@@ -219,6 +268,11 @@ function truncate(s, w) {
219
268
  }
220
269
 
221
270
  /** Fit a line to exactly w columns: truncate if too long, pad if too short. */
271
+ /** Truncate only when too wide (no padding) — for header lines. */
272
+ function truncLine(s, w) {
273
+ return vw(s) > w ? truncate(s, w) : s;
274
+ }
275
+
222
276
  function fitLine(s, w) {
223
277
  const v = vw(s);
224
278
  if (v > w) return truncate(s, w);
@@ -322,10 +376,19 @@ function loadText(load) {
322
376
  const hourReq = load?.last1h?.requests || 0;
323
377
  const failed = load?.last15m?.failed || 0;
324
378
  const linkFailed = load?.last15m?.linkFailed || 0;
325
- if (!inflight && !hourReq && !failed && !linkFailed) return '';
379
+ const bounced = load?.last15m?.bounced || 0;
380
+ const eff = load?.last15m?.efficiency;
381
+ // Dim below the volume floors (too few turns to mean much). A cloud row's figure is the
382
+ // serving pool's own, team-wide on that account — tagged (team).
383
+ const cacheTxt = eff && eff.hit != null ? `cache ${Math.round(eff.hit * 100)}%` : null;
384
+ const cache = cacheTxt
385
+ ? `${eff.lowVolume ? dim(cacheTxt) : cacheTxt}${load.last15m.team ? dim(' (team)') : ''}` : null;
386
+ if (!inflight && !hourReq && !failed && !linkFailed && !bounced && !cache) return '';
326
387
  const parts = [];
327
388
  if (inflight) parts.push(`${inflight} live`);
328
389
  if (hourReq) parts.push(`${hourReq} req/hr`);
390
+ if (cache) parts.push(cache);
391
+ if (bounced) parts.push(dim(`${bounced} bounced`));
329
392
  if (failed) parts.push(red(`${failed} failed`));
330
393
  if (linkFailed) parts.push(yellow(`${linkFailed} link drop${linkFailed === 1 ? '' : 's'}`));
331
394
  return parts.join(' · ');
@@ -541,6 +604,22 @@ function emptyBar(label, w = 10) {
541
604
  return `${ESC}100m${' '.repeat(lp)}${text}${' '.repeat(rp)}${RESET}`;
542
605
  }
543
606
 
607
+ /**
608
+ * The "Fbl" bar: one model family's weekly limit, which Anthropic counts separately
609
+ * from the account-wide weekly. Drawn with the same bar() as Ses and Wk, so it reads
610
+ * the same way (used% and time to reset). Shows the empty dash cell when there is
611
+ * nothing to show: a provider row, no probe result yet, or a limit Anthropic marks
612
+ * as inactive. Routing
613
+ * and the "Fable NN%" tag ignore an inactive limit too, so the bar stays quiet as well.
614
+ */
615
+ function scopedWeeklyBar(quota, family, w) {
616
+ const e = quota?.scopedWeekly?.[family];
617
+ // is_active=false still carries a REAL reading (percent + reset days out): the
618
+ // limit exists and counts. Only a MISSING reading dashes.
619
+ if (!e || e.utilization == null) return emptyBar('—', w);
620
+ return bar(e.utilization, w, e.resetAt);
621
+ }
622
+
544
623
  /** Write a provider's enabled flag into the CONFIG entry `loadConfigProviders` reads.
545
624
  *
546
625
  * A config-sourced provider is re-created from config on every reload
@@ -562,7 +641,7 @@ export function applyProviderEnabledToConfig(config, name, enabled) {
562
641
  return { changed: true, previous };
563
642
  }
564
643
 
565
- export const __tuiTest = { applyProviderEnabledToConfig, formatReset, quotaLabel, bar, emptyBar, strip, loadText, countdown, acctHeader, fitLine, providerLabel, weeklyPolicyText, capText, capEffectivePct };
644
+ export const __tuiTest = { applyProviderEnabledToConfig, formatReset, quotaLabel, bar, emptyBar, scopedWeeklyBar, barLayout, strip, loadText, countdown, acctHeader, fitLine, providerLabel, weeklyPolicyText, capText, capEffectivePct };
566
645
 
567
646
  function timestamp() {
568
647
  return new Date().toLocaleTimeString('en-US', { hour12: false });
@@ -593,13 +672,18 @@ export function decideLoginTarget({ mirror, links, existing, accountUuid }) {
593
672
  }
594
673
 
595
674
  export class TUI {
596
- constructor({ accountManager, config, saveConfig, syncAccounts, onQuit, onRestart }) {
675
+ constructor({ accountManager, config, saveConfig, syncAccounts, onQuit, onRestart, spawnDetached }) {
597
676
  this.am = accountManager;
677
+ // Runs the tmux detach for q in service mode; a seam so tests never start tmux.
678
+ this._spawnDetached = spawnDetached || ((cmd, args) => {
679
+ try { spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref(); } catch { /* no tmux */ }
680
+ });
598
681
  this.config = config;
599
682
  this.saveConfig = saveConfig;
600
683
  this.syncAccounts = syncAccounts;
601
684
  this.onQuit = onQuit;
602
685
  this.onRestart = onRestart;
686
+ this._startedAt = Date.now(); // the efficiency line's "since restart" window
603
687
  // Set by index.js after construction (a deferred closure, not a constructor literal —
604
688
  // avoids the const TDZ on applyUpdateIfReady, which is defined after `new TUI`).
605
689
  this.checkNow = null;
@@ -845,7 +929,13 @@ export class TUI {
845
929
  const ttfbTag = ttfbMs != null ? ` ttfb=${(Math.max(0, ttfbMs) / 1000).toFixed(1)}s` : '';
846
930
  // B8: ' ns' = a non-streaming request (strict false: the oauth relay carries no shape, so no tag).
847
931
  const nsTag = info.stream === false ? ' ns' : '';
848
- this._addLog(`${who}${info.method} ${info.path} → ${acct} (${info.status}, ${dur}s)${nsTag}${provTag}${cvTag}${ttfbTag}`);
932
+ // The served attempt's cache figures (~25B, well inside the 480B line cap): whether
933
+ // the cache held is the one thing a request line could not say (#642 port).
934
+ const cacheLabel = cacheUsageLabel(info.cacheUsage);
935
+ const cacheTag = cacheLabel ? ` ${CACHE_PAINT[cacheUsageState(info.cacheUsage)](cacheLabel)}` : '';
936
+ // ttfb= stays the LAST field — the request-line contract (reset-count-stale-and-ttfb
937
+ // test 13); the cache tag goes just before it.
938
+ this._addLog(`${who}${info.method} ${info.path} → ${acct} (${info.status}, ${dur}s)${nsTag}${provTag}${cvTag}${cacheTag}${ttfbTag}`);
849
939
  }
850
940
 
851
941
  _addLog(msg) {
@@ -919,8 +1009,19 @@ export class TUI {
919
1009
  this.forceRender();
920
1010
  }
921
1011
 
1012
+ /** Close every viewer of the service dashboard (viewers are view-only); the pool
1013
+ * keeps running. `-s pool` detaches all clients of the session, deterministically. */
1014
+ detachView() {
1015
+ const sock = process.env.MAXPOOL_TMUX_SOCK;
1016
+ this._spawnDetached('tmux', [...(sock ? ['-S', sock] : []), 'detach-client', '-s', 'pool']);
1017
+ }
1018
+
922
1019
  _keyNormal(k) {
923
- if (k === 'q') {
1020
+ if (k === 'q' && serviceMode()) {
1021
+ // Under the background service the pool lives in a tmux pane launchd owns:
1022
+ // stopping it here would only make launchd cold-restart it. q closes the view.
1023
+ this.detachView();
1024
+ } else if (k === 'q') {
924
1025
  this._confirm(
925
1026
  'Stop Maxpool?',
926
1027
  'New requests will stop; active requests will drain before the server exits.',
@@ -1076,6 +1177,71 @@ export class TUI {
1076
1177
  return ` Routing ${cyan(routing)}${xpText}`;
1077
1178
  }
1078
1179
 
1180
+ /** EFFICIENCY line (2026-11-15), directly under Routing: is the prompt cache holding,
1181
+ * and what are moves costing — Claude and GLM never blended. null with no traffic.
1182
+ * Colours are WARN-only proposals until a one-day baseline exists; a red names the
1183
+ * cause and the account. */
1184
+ _efficiencyLine(W = 80, now = Date.now()) {
1185
+ const eff = this.am.efficiencyOverall?.('last15m', now);
1186
+ if (!eff) return null;
1187
+ const { claude: c, glm: g } = eff;
1188
+ const served = c.served + g.served;
1189
+ const bounced = c.bounced + g.bounced;
1190
+ if (served + bounced === 0) return null;
1191
+ const sinceMs = now - (this._startedAt ?? now);
1192
+ const since = sinceMs < 15 * 60_000 ? dim(` since restart ${Math.max(1, Math.round(sinceMs / 60_000))}m`) : '';
1193
+ if (c.lowVolume && g.lowVolume) return truncLine(` Cache ${dim('— (little traffic)')}${since}`, W);
1194
+ const pctTxt = x => `${Math.round(x * 100)}%`;
1195
+ const parts = [];
1196
+ if (c.hit != null) parts.push(`Claude ${c.lowVolume ? dim(pctTxt(c.hit)) : pctTxt(c.hit)}`);
1197
+ if (g.hit != null) parts.push(`GLM ${g.lowVolume ? dim(pctTxt(g.hit)) : pctTxt(g.hit)}`);
1198
+ const miss = c.missTokens + g.missTokens;
1199
+ parts.push(`miss ${miss >= 1e6 ? `${(miss / 1e6).toFixed(1)}M` : `${Math.round(miss / 1000)}k`} tok`);
1200
+ const cause = k => c.movedByCause[k] + g.movedByCause[k];
1201
+ const per100 = n => (served ? Math.round(n * 100 / served) : 0);
1202
+ parts.push(`moves ${per100(c.moved + g.moved)}/100 (busy ${cause('busy')} · balance ${cause('balance')} · wall ${cause('wall')}${cause('link') ? ` · link ${cause('link')}` : ''}${cause('other') ? ` · other ${cause('other')}` : ''})`);
1203
+ const bounceShare = bounced / (served + bounced);
1204
+ if (bounced) parts.push(`bounced ${pctTxt(bounceShare)}`);
1205
+ const waited = c.waited + g.waited;
1206
+ if (waited) parts.push(`waited ${waited} (avg ${((c.waitMs + g.waitMs) / waited / 1000).toFixed(1)}s)`);
1207
+
1208
+ // RED — the first cause that applies, named with the account behind it.
1209
+ const forced = cause('busy') + cause('wall') + cause('link');
1210
+ const wtm = c.waitThenMoved + g.waitThenMoved;
1211
+ let red_ = null;
1212
+ if (!c.lowVolume && c.hit != null && c.hit < 0.5) red_ = `Claude ${pctTxt(c.hit)} on ${this._worstCacheAccount() || '?'}`;
1213
+ else if (per100(forced) > 2) red_ = `${per100(forced)} forced moves/100 — most refusals on ${this._mostBouncedAccount(now) || '?'}`;
1214
+ else if (bounceShare > 0.1) red_ = `${pctTxt(bounceShare)} bounced — most on ${this._mostBouncedAccount(now) || '?'}`;
1215
+ else if (wtm * 100 / Math.max(1, served) > 0.5) red_ = `${wtm} waits still moved — on ${this._mostBouncedAccount(now) || '?'}`;
1216
+ if (red_) return truncLine(` ${red('Cache')} ${red(`⚠ ${red_}`)} ${dim('·')} ${parts.join(' · ')} ${dim('[15m]')}${since}`, W);
1217
+ // YELLOW — Claude below 70%, drifting 15+ points under its hour, or waits are common.
1218
+ const hour = this.am.efficiencyOverall('last1h', now).claude;
1219
+ const drift = !c.lowVolume && !hour.lowVolume && c.hit != null && hour.hit != null && hour.hit - c.hit >= 0.15;
1220
+ const warn = (!c.lowVolume && c.hit != null && c.hit < 0.7) || drift || waited > 0.25 * served;
1221
+ return truncLine(` ${warn ? yellow('Cache') : green('Cache')} ${parts.join(' · ')} ${dim('[15m]')}${since}`, W);
1222
+ }
1223
+
1224
+ /** The Claude row with the lowest cache share in the window (enough volume only). */
1225
+ _worstCacheAccount() {
1226
+ let worst = null;
1227
+ for (const a of this.am.accounts) {
1228
+ if (a.enabled === false || a.type === 'provider') continue;
1229
+ const e = this._accountLoad(a)?.last15m?.efficiency;
1230
+ if (e && !e.lowVolume && e.hit != null && (!worst || e.hit < worst.hit)) worst = { name: a.name, hit: e.hit };
1231
+ }
1232
+ return worst?.name || null;
1233
+ }
1234
+
1235
+ /** The row with the most pinned refusals (bounces) seen by this pool in the window. */
1236
+ _mostBouncedAccount(now = Date.now()) {
1237
+ let best = null;
1238
+ for (const a of this.am.accounts) {
1239
+ const n = this.am._loadSummary(a, 15 * 60_000, now).bounced;
1240
+ if (n > 0 && (!best || n > best.n)) best = { name: a.name, n };
1241
+ }
1242
+ return best?.name || null;
1243
+ }
1244
+
1079
1245
  /** One line per unreachable team pool, so a lost connection reads as ONE cause
1080
1246
  * instead of every cloud row turning red. '' lines are skipped by the caller. */
1081
1247
  _cloudLinkLines(W = 80, now = Date.now()) {
@@ -1160,7 +1326,7 @@ export class TUI {
1160
1326
  } else if (k === 'l') {
1161
1327
  this._confirm(
1162
1328
  'Log in / re-authenticate via browser?',
1163
- 'Opens a browser. Logging into an account that\'s already added RE-AUTHENTICATES it in place (revives a reauth/error account) — no duplicate. Otherwise a new account is added.',
1329
+ 'Opens a browser. Logging into an account that\'s already added (same user, same organization) RE-AUTHENTICATES it in place (revives a reauth/error account) — no duplicate. Another organization of the same user, or a new user, is added as a new account.',
1164
1330
  () => this._doLogin(),
1165
1331
  );
1166
1332
  } else if (k === 'n' && this.am.accounts.length > 0) {
@@ -1200,7 +1366,7 @@ export class TUI {
1200
1366
  this.mode = 'accounts';
1201
1367
  this._confirm(
1202
1368
  'Log in / re-authenticate via browser?',
1203
- 'Opens a browser. Logging into an account that is already added RE-AUTHENTICATES it in place — no duplicate.',
1369
+ 'Opens a browser. Logging into an account that is already added (same user, same organization) RE-AUTHENTICATES it in place — no duplicate. Another organization of the same user is added as a new account.',
1204
1370
  () => this._doLogin(),
1205
1371
  );
1206
1372
  return;
@@ -1397,6 +1563,10 @@ export class TUI {
1397
1563
  // mode — under balance/prefer-* the mode itself controls eligibility. Still
1398
1564
  // safe to set (it'll apply if you switch back to sticky).
1399
1565
  this._cycleProviderClaudeFallback(k === 'g' ? 'zai' : 'kimi');
1566
+ } else if (k === 'b' || k === 'B') {
1567
+ // STICKY BUSY WAIT (2026-11-15): how long a conversation waits for its own busy
1568
+ // account before moving (a move re-writes its whole prompt cache).
1569
+ this._cycleStickyBusyBudget();
1400
1570
  } else if (k === 'w' || k === 'W') {
1401
1571
  // WEEKLY-AWARE SCORING (2026-09-16): fold weekly utilization into the routing
1402
1572
  // score, not just the 5h session. Without it, an account at 89% weekly with a
@@ -1517,6 +1687,42 @@ export class TUI {
1517
1687
  : 'Weekly-aware routing: OFF — score sees only the 5h session window again');
1518
1688
  }
1519
1689
 
1690
+ static STICKY_BUSY_STEPS = [15_000, 30_000, 60_000, 120_000, 0];
1691
+
1692
+ _stickyBusyLabel() {
1693
+ // The value IN FORCE — the server's own resolver, so an env override shows as such.
1694
+ const { ms, fromEnv } = resolveStickyBusyBudget(this.am.scheduler);
1695
+ const txt = ms > 0 ? `${Math.round(ms / 1000)}s` : 'off';
1696
+ return fromEnv ? `${txt} (env)` : txt;
1697
+ }
1698
+
1699
+ /** Cycle the busy-account wait. Live: the server reads it per request, so the next
1700
+ * request uses the new value; saved so it survives a restart. */
1701
+ async _cycleStickyBusyBudget() {
1702
+ if (resolveStickyBusyBudget(this.am.scheduler).fromEnv) {
1703
+ // Saving a setting the server ignores would make the screen lie about the wait.
1704
+ this._addLog('Wait for busy account is pinned by MAXPOOL_STICKY_BUSY_BUDGET_MS — unset it to change it here');
1705
+ return;
1706
+ }
1707
+ const steps = TUI.STICKY_BUSY_STEPS;
1708
+ const cur = this.am.scheduler.stickyBusyBudgetMs ?? 60_000;
1709
+ const next = steps[(steps.indexOf(cur) + 1) % steps.length];
1710
+ this.am.scheduler.stickyBusyBudgetMs = next;
1711
+ const prevSched = this.config.scheduler;
1712
+ this.config.scheduler = { ...(prevSched || {}), stickyBusyBudgetMs: next };
1713
+ try {
1714
+ await this.saveConfig(this.config);
1715
+ } catch (e) {
1716
+ this.am.scheduler.stickyBusyBudgetMs = cur;
1717
+ this.config.scheduler = prevSched;
1718
+ this._addLog(`Could not save: ${e.message}`);
1719
+ return;
1720
+ }
1721
+ this._addLog(next > 0
1722
+ ? `Wait for busy account: up to ${Math.round(next / 1000)}s before a conversation moves to another account`
1723
+ : 'Wait for busy account: off — a busy account moves the conversation at once');
1724
+ }
1725
+
1520
1726
  async _cycleRoutingMode() {
1521
1727
  const modes = TUI.ROUTING_MODES;
1522
1728
  const cur = this.am.scheduler?.routingMode || 'sticky';
@@ -1731,7 +1937,7 @@ export class TUI {
1731
1937
  }
1732
1938
 
1733
1939
  // Browser OAuth login — the SAME flow re-authenticates an existing account (matched
1734
- // by accountUuid) or adds a new one. When the login is for an account already added,
1940
+ // by user + organization) or adds a new one. When the login is for an account already added,
1735
1941
  // we say so, keep its name, and skip the "name this account" prompt — so it's clear
1736
1942
  // it's a RE-AUTH in place (revives a dead-refresh/reauth account), not a duplicate.
1737
1943
  async _doLogin() {
@@ -1771,12 +1977,9 @@ export class TUI {
1771
1977
  // a mirror match → that team pool; a brand-new account with a linked team pool →
1772
1978
  // ask once (default team pool); otherwise the local save path.
1773
1979
  async _routeLogin(creds, profile) {
1774
- const decision = decideLoginTarget({
1775
- mirror: this._findRemoteMirrorFor(profile),
1776
- links: this.am.poolLinks,
1777
- existing: this._findExistingOAuthAccount(profile),
1778
- accountUuid: profile?.accountUuid,
1779
- });
1980
+ const mirror = this._findRemoteMirrorFor(profile);
1981
+ const existing = mirror ? null : await this._matchLogin(profile);
1982
+ const decision = decideLoginTarget({ mirror, links: this.am.poolLinks, existing, accountUuid: profile?.accountUuid });
1780
1983
  if (decision.kind === 'no-uuid') {
1781
1984
  setConsoleStdoutSuppressed(false);
1782
1985
  process.stdout.write("\nCould not read this account's id — the team pool needs it. Nothing was saved; try again.\n");
@@ -1787,14 +1990,14 @@ export class TUI {
1787
1990
  await this._sendLoginToRemote(decision.mirror, creds, profile);
1788
1991
  return;
1789
1992
  }
1790
- const existing = this._findExistingOAuthAccount(profile);
1791
1993
  let name;
1792
1994
  if (existing) {
1793
1995
  process.stdout.write(`\nThis Claude account is already added as "${existing.name}" — re-authenticating it in place (no duplicate).\n`);
1794
1996
  name = existing.name;
1795
1997
  } else {
1796
- const suggested = profile?.email
1797
- || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1998
+ const sibling = this._oauthAccounts().find(a => sameUser(a, profile));
1999
+ if (sibling) process.stdout.write(`\nSame Claude user as "${sibling.name}": adding a second account.\n`);
2000
+ const suggested = suggestAccountName(this.config.accounts, profile);
1798
2001
  let toTeam = false;
1799
2002
  if (decision.kind === 'ask-team') {
1800
2003
  const where = String(await this._ask(`\nThis is a new account. Add it to the team pool "${decision.link.name}" (recommended) or this laptop only? [T/l]: `) || '').trim().toLowerCase();
@@ -1835,7 +2038,14 @@ export class TUI {
1835
2038
  // uuid-first matcher cannot alias onto a local account).
1836
2039
  _findRemoteMirrorFor(profile) {
1837
2040
  if (!profile?.accountUuid) return null;
1838
- return this.am.accounts.find(a => a.remote && a.remoteUuid === profile.accountUuid) || null;
2041
+ // Exact match first (user + org). A mirror whose org is unknown (the cloud
2042
+ // pool saved the account before organizations were recorded) still owns the
2043
+ // login when it is the only same-user mirror: re-authenticate it rather than
2044
+ // add a second row. Two known orgs never alias.
2045
+ const mirrors = this.am.accounts.filter(a => a.remote && a.enabled !== false && sameUser({ accountUuid: a.remoteUuid }, profile));
2046
+ return mirrors.find(a => sameAccountIdentity({ accountUuid: a.remoteUuid, organizationUuid: a.remoteOrganizationUuid }, profile))
2047
+ || (profile.organizationUuid && mirrors.filter(a => !a.remoteOrganizationUuid).length === 1
2048
+ ? mirrors.find(a => !a.remoteOrganizationUuid) : null);
1839
2049
  }
1840
2050
 
1841
2051
  // Send a fresh browser login to the linked team pool that OWNS this account
@@ -1955,24 +2165,23 @@ export class TUI {
1955
2165
  }
1956
2166
 
1957
2167
  // Upsert an OAuth account into config + the running manager. Dedupes by
1958
- // accountUuid, then name. Shared by import and browser login.
2168
+ // user + organization, then name. Shared by import and browser login.
1959
2169
  async _upsertOAuthAccount({ creds, profile, name, source, verb = 'Added' }) {
1960
- if (!name) {
1961
- name = profile?.email
1962
- || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1963
- }
2170
+ if (!name) name = suggestAccountName(this.config.accounts, profile);
1964
2171
  const entry = {
1965
2172
  name, type: 'oauth', source,
1966
2173
  accountUuid: profile?.accountUuid || null,
2174
+ organizationUuid: profile?.organizationUuid || null,
1967
2175
  accessToken: creds.accessToken,
1968
2176
  refreshToken: creds.refreshToken,
1969
2177
  expiresAt: creds.expiresAt,
1970
2178
  };
1971
2179
 
1972
- let idx = entry.accountUuid
1973
- ? this.config.accounts.findIndex(a => a.accountUuid === entry.accountUuid)
1974
- : -1;
1975
- if (idx < 0) idx = this.config.accounts.findIndex(a => a.name === name);
2180
+ // Identity first; the name only picks up rows that cannot carry an identity
2181
+ // (saved before uuids were stored). A row of the SAME USER with a KNOWN,
2182
+ // DIFFERENT organization never matches by name: its tokens are its own.
2183
+ let idx = this.config.accounts.findIndex(a => sameAccountIdentity(a, entry));
2184
+ if (idx < 0) idx = this.config.accounts.findIndex(a => a.name === name && !knownDifferentOrg(a, entry));
1976
2185
 
1977
2186
  if (idx >= 0) {
1978
2187
  const previous = this.config.accounts[idx];
@@ -1987,13 +2196,14 @@ export class TUI {
1987
2196
  // heal disk (persistTokenRefresh's generation guard skips a disk token that
1988
2197
  // != _refreshedFrom), so disk must be made correct right here.
1989
2198
  const amAcct = this.am.accounts.find(account =>
1990
- (entry.accountUuid && account.accountUuid === entry.accountUuid) || account.name === name
2199
+ sameAccountIdentity(account, entry) || (account.name === name && !knownDifferentOrg(account, entry))
1991
2200
  );
1992
2201
  if (amAcct) {
1993
2202
  amAcct.credential = creds.accessToken;
1994
2203
  amAcct.refreshToken = creds.refreshToken;
1995
2204
  amAcct.expiresAt = creds.expiresAt;
1996
2205
  amAcct.accountUuid = entry.accountUuid;
2206
+ amAcct.organizationUuid = entry.organizationUuid;
1997
2207
  amAcct.name = name;
1998
2208
  // Fresh tokens from re-auth revive a dead-refresh account. This in-place
1999
2209
  // update is the actual re-login path (the index.js reconcile sees no change
@@ -2035,15 +2245,84 @@ export class TUI {
2035
2245
  }
2036
2246
  }
2037
2247
 
2248
+ // Decide what a fresh browser-login profile is: an account already in the pool
2249
+ // (re-authenticate in place) or a new one. Same-user entries that do not know
2250
+ // their organization are read first; when one still cannot be read, the user decides.
2251
+ async _matchLogin(profile) {
2252
+ await this._resolveOrganizations(profile);
2253
+ const existing = this._findExistingOAuthAccount(profile);
2254
+ if (this._organizationUnknown(existing, profile)) return this._confirmReauth(existing);
2255
+ return existing;
2256
+ }
2257
+
2258
+ // Fill in the organization of same-user entries that lack one, reading each with
2259
+ // the running account's live token (read only, never refreshed), and mirror the
2260
+ // result to the manager. The upsert that follows persists it.
2261
+ async _resolveOrganizations(profile) {
2262
+ if (!profile?.accountUuid) return;
2263
+ await resolveOrganizations(this._oauthAccounts(), profile.accountUuid, entry => this._liveCredentials(entry));
2264
+ this._mirrorOrganizations(profile);
2265
+ }
2266
+
2267
+ _liveCredentials(entry) {
2268
+ const live = this._runningAccount(entry);
2269
+ return live ? { accessToken: live.credential, expiresAt: live.expiresAt } : entry;
2270
+ }
2271
+
2272
+ _mirrorOrganizations(profile) {
2273
+ const known = this._oauthAccounts().filter(a => sameUser(a, profile) && a.organizationUuid);
2274
+ for (const entry of known) this._mirrorOrganization(entry);
2275
+ }
2276
+
2277
+ _mirrorOrganization(entry) {
2278
+ const live = this._runningAccount(entry);
2279
+ if (live) live.organizationUuid = entry.organizationUuid;
2280
+ }
2281
+
2282
+ _runningAccount(entry) {
2283
+ return this.am.accounts.find(a => a.name === entry.name);
2284
+ }
2285
+
2286
+ _oauthAccounts() {
2287
+ return this.config.accounts.filter(a => a.type === 'oauth');
2288
+ }
2289
+
2038
2290
  // Find an already-configured OAuth account matching a fresh browser-login profile —
2039
- // by accountUuid (primary), then name===email — the SAME precedence _upsertOAuthAccount
2040
- // dedupes on, so the login flow can honestly say "re-authenticating" vs "adding new".
2291
+ // the same user in the same organization; else a same-user entry that does not know
2292
+ // its organization (the login then asks); else, for a profile without a uuid,
2293
+ // name===email; else an entry saved before uuids were stored. The SAME precedence
2294
+ // _upsertOAuthAccount dedupes on, so the login flow can honestly say
2295
+ // "re-authenticating" vs "adding new".
2041
2296
  _findExistingOAuthAccount(profile) {
2042
- const uuid = profile?.accountUuid || null;
2297
+ const accounts = this._oauthAccounts();
2043
2298
  const email = profile?.email || null;
2044
- let acct = uuid ? this.config.accounts.find(a => a.type === 'oauth' && a.accountUuid === uuid) : null;
2045
- if (!acct && email) acct = this.config.accounts.find(a => a.type === 'oauth' && a.name === email);
2046
- return acct || null;
2299
+ if (!profile?.accountUuid) return (email && accounts.find(a => a.name === email)) || null;
2300
+ return accounts.find(a => sameAccountIdentity(a, profile))
2301
+ || organizationUnknownMatch(accounts, profile)
2302
+ || accounts.find(a => !a.accountUuid && a.name === email)
2303
+ || null;
2304
+ }
2305
+
2306
+ // True when the match rests on the user alone: the entry's organization is unknown
2307
+ // while the login names one.
2308
+ _organizationUnknown(existing, profile) {
2309
+ return Boolean(existing?.accountUuid && profile?.organizationUuid && !existing.organizationUuid);
2310
+ }
2311
+
2312
+ // The user decides a same-user login whose organization could not be read: Enter
2313
+ // or r re-authenticates the entry, a adds a second account; anything else asks again.
2314
+ async _confirmReauth(existing) {
2315
+ const choice = await this._askReauthOrAdd(existing.name);
2316
+ if (choice === 'add') return null;
2317
+ if (choice === 'reauth') return existing;
2318
+ return this._confirmReauth(existing);
2319
+ }
2320
+
2321
+ async _askReauthOrAdd(name) {
2322
+ const raw = await this._ask(`Same Claude user as "${name}", organization unknown. Re-authenticate it (r) or add a second account (a)? [r] `);
2323
+ const answer = String(raw || '').trim().toLowerCase();
2324
+ if (['', 'r', 're-authenticate'].includes(answer)) return 'reauth';
2325
+ return ['a', 'add'].includes(answer) ? 'add' : null;
2047
2326
  }
2048
2327
 
2049
2328
  async _doAddKey(apiKey) {
@@ -2096,7 +2375,7 @@ export class TUI {
2096
2375
  _configAccountIndex(account) {
2097
2376
  if (!account) return -1;
2098
2377
  if (account.accountUuid) {
2099
- const byUuid = this.config.accounts.findIndex(candidate => candidate.accountUuid === account.accountUuid);
2378
+ const byUuid = this.config.accounts.findIndex(candidate => sameAccountIdentity(candidate, account));
2100
2379
  if (byUuid >= 0) return byUuid;
2101
2380
  }
2102
2381
  return this.config.accounts.findIndex(candidate => candidate.name === account.name);
@@ -2376,6 +2655,8 @@ export class TUI {
2376
2655
  if (provReq > 0) xpText += ` ${dim('·')} ${yellow(`providers: ${provReq} req/15m`)}`;
2377
2656
  }
2378
2657
  lines.push(this._routingLine(routing, xpText));
2658
+ const effLine = this._efficiencyLine(W);
2659
+ if (effLine != null) lines.push(effLine);
2379
2660
  lines.push(...this._cloudLinkLines(W));
2380
2661
  const queuedCount = this.am.queueState?.waiting?.length || 0;
2381
2662
  // Throttle and WAITING are different things and used to share one line labelled
@@ -2433,18 +2714,21 @@ export class TUI {
2433
2714
  } else {
2434
2715
  lines.push('');
2435
2716
  // Aligned column header (dim + underline so it reads as chrome, not data). It
2436
- // labels the fixed columns that have no inline label; the Ses/Wk/Tok/Req and
2717
+ // labels the fixed columns that have no inline label; the Ses/Fbl/Wk/Tok/Req and
2437
2718
  // Now/15m/1h labels stay inline per row. It sits DIRECTLY above the rows — the
2438
2719
  // abbreviation glossary is a FOOTER below the rows (a caption), never between
2439
2720
  // the header and the data (a left-aligned sentence there reads as a broken,
2440
2721
  // misaligned second header).
2441
2722
  lines.push(dimUnderline(acctHeader(W)));
2442
- const showBoth = W >= 70;
2443
- // 65/54 = the fixed pre-bar column span (prefix + Account + Provider + Status +
2444
- // gaps); grew by +4 with the wider 20-col Account column (was 61/50 at NAME_W 16).
2445
- const bw = showBoth
2446
- ? Math.max(5, Math.min(20, Math.floor((W - 65) / 2)))
2447
- : Math.max(5, Math.min(20, W - 54));
2723
+ // Sticky: once any account has reported a session window in this run, keep the
2724
+ // Ses column. A window that simply expires on an idle pool nulls its reading
2725
+ // until the next request or probe; dropping and re-adding the column then
2726
+ // would make every bar jump width. Pools that never report one keep it hidden.
2727
+ this._sessionColumnSeen = this._sessionColumnSeen || this.am.accounts.some(hasSessionReading);
2728
+ // Below 70 columns only ONE bar fits: Wk (real data) wins over a latched-but-
2729
+ // expired Ses, so the collapse logic still applies at narrow widths.
2730
+ const latch = W >= 70 ? this._sessionColumnSeen : this.am.accounts.some(hasSessionReading);
2731
+ const { showSession, showBoth, showFable, bw } = barLayout(W, latch);
2448
2732
 
2449
2733
  // Claude/OAuth accounts first, providers (GLM/Kimi fallback) last — a stable
2450
2734
  // display order over the canonical am.accounts array (which stays untouched so
@@ -2457,7 +2741,7 @@ export class TUI {
2457
2741
  // effectively off (owner 2026-10-29: "should it hide the local ones that are
2458
2742
  // in the cloud... they're effectively disabled as well"). No separate key.
2459
2743
  if (this.hideDisabled && this.am.accounts[i]?.poolBenchedBy) { hidden++; continue; }
2460
- lines.push(this._renderAcct(i, bw, showBoth));
2744
+ lines.push(this._renderAcct(i, bw, showBoth, showFable, showSession));
2461
2745
  }
2462
2746
  if (hidden > 0) {
2463
2747
  lines.push(` ${dim(`… ${hidden} disabled account${hidden === 1 ? '' : 's'} hidden — press h to show`)}`);
@@ -2573,7 +2857,7 @@ export class TUI {
2573
2857
  process.stdout.write(buf);
2574
2858
  }
2575
2859
 
2576
- _renderAcct(idx, bw, showBoth) {
2860
+ _renderAcct(idx, bw, showBoth, showFable = showBoth, showSession = true) {
2577
2861
  let a = this.am.accounts[idx];
2578
2862
  // A row benched by the duplicate guard renders the CLOUD's live copy (status,
2579
2863
  // bars, in-flight, request counts) — never the stale local snapshot. Identity
@@ -2739,17 +3023,16 @@ export class TUI {
2739
3023
  // Widened from 10 to fit "throttled 59s" so the quota bars stay column-aligned.
2740
3024
  status = rpad(status, STATUS_W);
2741
3025
 
2742
- // Rst column — banked limit resets (owner request 2026-09-30: a separate
3026
+ // MRst/ARst columns — banked limit resets (owner request 2026-09-30: a separate
2743
3027
  // column showing 0 or the count). z.ai cards + Claude cedar_ember grants,
2744
3028
  // not-yet-expired, on ENABLED accounts only: a disabled account's resets are
2745
3029
  // not ours to spend, and showing a count there would imply otherwise.
2746
3030
  //
2747
- // B3 grammar (2026-11-10), rendered width EXACTLY RESETS_W (6):
2748
- // general n~Xd e.g. 2~119d
2749
- // scoped nF~Xd e.g. 2F~4d (model-scoped, e.g. Fable)
2750
- // mixed g+sF e.g. 1+2F
2751
- // unknown n? scope unknown — count shown, never claimed
2752
- // not-fresh = gray + trailing '?' (stale listing, dead account, old check)
3031
+ // B3 grammar (2026-11-10), split into two cells 2026-11-15:
3032
+ // MRst (width MRST_W) model-scoped nFable~Xd e.g. 2Fable~114d ('-' when none)
3033
+ // ARst (width ARST_W) account-level n~Xd e.g. 1~29d ('0' when none)
3034
+ // unknown n? scope unknown (ARst only) — count shown, never claimed
3035
+ // not-fresh = gray + trailing '?' when it fits (stale listing, dead account, old check)
2753
3036
  // Count = SUM of resetsLeft over spendable grants + live cards (not entries).
2754
3037
  // Overflow order: drop the suffix first, then collapse to total+'*'.
2755
3038
  // Expiry is checked LIVE here: grants endsAt>now, cards !expired &&
@@ -2761,13 +3044,14 @@ export class TUI {
2761
3044
  let general = 0; // resetsLeft of general-weekly grants + live cards
2762
3045
  let scoped = 0; // resetsLeft of model-scoped grants (tagged F)
2763
3046
  let unknown = 0; // resetsLeft of scope-unknown grants
2764
- let soonest = Infinity;
3047
+ let soonestG = Infinity; // soonest expiry among account-level (general/unknown) resets
3048
+ let soonestS = Infinity; // soonest expiry among model-scoped resets
2765
3049
  if (a.enabled !== false) {
2766
3050
  const liveCard = c => c && !c.expired && (c.expiresAt == null || c.expiresAt > now);
2767
3051
  const rc = a.resetCards;
2768
3052
  if (rc) {
2769
3053
  for (const c of [...(rc.fiveHour || []), ...(rc.weekly || [])]) {
2770
- if (liveCard(c)) { general += 1; if (c.expiresAt != null && c.expiresAt < soonest) soonest = c.expiresAt; }
3054
+ if (liveCard(c)) { general += 1; if (c.expiresAt != null && c.expiresAt < soonestG) soonestG = c.expiresAt; }
2771
3055
  }
2772
3056
  }
2773
3057
  const rg = a.resetGrants;
@@ -2789,11 +3073,15 @@ export class TUI {
2789
3073
  const clearsWeekly = (Array.isArray(g.clears) ? g.clears : []).includes('seven_day');
2790
3074
  const hasScoped = scopes.some(x => x !== 'general' && x !== 'session');
2791
3075
  const left = Math.max(0, Math.floor(g.resetsLeft ?? 1));
3076
+ let isScoped = false;
2792
3077
  if (clearsWeekly) general += left;
2793
- else if (hasScoped) scoped += left;
3078
+ else if (hasScoped) { scoped += left; isScoped = true; }
2794
3079
  else if (scopes.includes('general')) general += left;
2795
3080
  else unknown += left;
2796
- if (g.endsAt != null && g.endsAt < soonest) soonest = g.endsAt;
3081
+ if (g.endsAt != null) {
3082
+ if (isScoped) { if (g.endsAt < soonestS) soonestS = g.endsAt; }
3083
+ else if (g.endsAt < soonestG) soonestG = g.endsAt;
3084
+ }
2797
3085
  }
2798
3086
  }
2799
3087
  }
@@ -2807,42 +3095,41 @@ export class TUI {
2807
3095
  && (a.resetCards.checkedAt == null || now - a.resetCards.checkedAt <= LISTING_FRESH_MS));
2808
3096
  const notFresh = total > 0 && (!freshGrants || !freshCards || a.refreshDead || a.subscriptionGone);
2809
3097
 
2810
- // Core text per the grammar.
2811
- let core;
2812
- if (total === 0) core = '0';
2813
- else if (unknown > 0 && general === 0 && scoped === 0) core = `${unknown}?`;
2814
- else if (general > 0 && scoped > 0) core = `${general}+${scoped}F`;
2815
- else if (scoped > 0) core = `${scoped}F`;
2816
- else core = `${general}`;
2817
-
2818
- // Expiry suffix (owner 2026-10-01: always show when a reset exists).
2819
- let suffix = '';
2820
- if (total > 0 && soonest !== Infinity) {
3098
+ // Two cells (owner 2026-11-15): MRst = model-scoped resets, ARst = account-level.
3099
+ // Each cell has its OWN count, expiry and fit; the staleness flag is shared.
3100
+ const expirySuffix = (n, soonest) => {
3101
+ if (!(n > 0) || soonest === Infinity) return '';
2821
3102
  const days = (soonest - now) / 86400_000;
2822
- suffix = days < 1 ? `~${Math.max(1, Math.round(days * 24))}h` : `~${Math.max(1, Math.round(days))}d`;
2823
- }
2824
-
2825
- // Fit to EXACTLY RESETS_W: full form, then drop the suffix, then total+'*'.
2826
- // OWNER READABILITY (2026-11-10: "What does the letter F mean? I have no
2827
- // idea"): a bare F is undecodable shorthand — the 2026-08-27 no-glossary
2828
- // rule says the cell says what it means in words. Model-scoped resets spell
2829
- // the model: '2Fable' / '1Opus'. RESETS_W grows to fit '99Fable' (8) so the
2830
- // word is never truncated into a mystery tag again; plain counts keep the
2831
- // compact n~Xd form.
2832
- const coreFable = core.replace(/F\b/, 'Fable');
2833
- let text = coreFable + suffix;
2834
- if (text.length > RESETS_W) text = coreFable;
2835
- if (text.length > RESETS_W) text = `${total}*`.slice(0, RESETS_W);
2836
- // Not-fresh: append '?' only when it fits. When it does not ('1+2Fable' is
2837
- // already 8), keep the breakdown and let the gray colour carry staleness —
2838
- // collapsing to '3?' made the cell flip 1+2Fable → 3? → 1+2Fable across every
2839
- // self-update (owner 2026-11-10: "the number of resets keeps changing").
2840
- if (notFresh && (text + '?').length <= RESETS_W) text += '?';
2841
- resetsCell = rpad(total > 0 && !notFresh ? green(text) : gray(text), RESETS_W);
3103
+ return days < 1 ? `~${Math.max(1, Math.round(days * 24))}h` : `~${Math.max(1, Math.round(days))}d`;
3104
+ };
3105
+ // Fit to EXACTLY w: full form, then drop the suffix, then n+'*'. Not-fresh:
3106
+ // append '?' only when it fits; otherwise gray carries the staleness (a
3107
+ // '1+2Fable' -> '3?' collapse flipped the count on every self-update,
3108
+ // owner 2026-11-10).
3109
+ const renderCell = (core, suffix, n, w, sticky) => {
3110
+ let text = core + suffix;
3111
+ if (text.length > w) text = core;
3112
+ if (text.length > w) text = `${n}*`.slice(0, w);
3113
+ if (notFresh && n > 0 && !sticky && (text + '?').length <= w) text += '?';
3114
+ return rpad(n > 0 && !notFresh ? green(text) : gray(text), w);
3115
+ };
3116
+ // MRst: model-scoped grants spell the model ('2Fable'), never a bare F
3117
+ // (owner 2026-11-10: "What does the letter F mean?"). Nothing -> a dim dash.
3118
+ const mCell = scoped > 0
3119
+ ? renderCell(`${scoped}Fable`, expirySuffix(scoped, soonestS), scoped, MRST_W, false)
3120
+ : rpad(gray('-'), MRST_W);
3121
+ // ARst: account-level count; scope-unknown grants show 'n?' when they are all there is.
3122
+ const unknownOnly = unknown > 0 && general === 0;
3123
+ const aN = unknownOnly ? unknown : general;
3124
+ const aCore = unknownOnly ? `${unknown}?` : `${general}`;
3125
+ const aCell = aN > 0
3126
+ ? renderCell(aCore, expirySuffix(aN, soonestG), aN, ARST_W, unknownOnly)
3127
+ : rpad(gray('0'), ARST_W);
3128
+ resetsCell = mCell + ' ' + aCell;
2842
3129
  }
2843
3130
 
2844
3131
  if (a.type === 'provider') {
2845
- return this._renderProviderAcct(sel, cur, name, type, status + ' ' + resetsCell, a, bw, showBoth);
3132
+ return this._renderProviderAcct(sel, cur, name, type, status + ' ' + resetsCell, a, bw, showBoth, showFable, showSession);
2846
3133
  }
2847
3134
 
2848
3135
  // Quota ratios — prefer unified (Claude Max), fall back to standard (API key)
@@ -2865,15 +3152,20 @@ export class TUI {
2865
3152
  t2 = t1;
2866
3153
  }
2867
3154
 
2868
- let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} ${resetsCell} ${l1} ${bar(r1, bw, t1)}`;
3155
+ const bars = [];
3156
+ // The Fable bar comes first, before the session and weekly bars, on every row
3157
+ // type, so each bar starts at the same offset on OAuth, API-key and provider rows.
3158
+ if (showFable) bars.push(`Fbl ${scopedWeeklyBar(q, 'fable', bw)}`);
3159
+ if (showSession) bars.push(`${l1} ${bar(r1, bw, t1)}`);
2869
3160
  if (showBoth) {
2870
3161
  // "no weekly cap on this plan" is a DIFFERENT state from "not read yet", and
2871
3162
  // both render as an empty bar. Say which, so a healthy uncapped account
2872
3163
  // (privacy@gomokka.com, measured 2026-08-06) doesn't read as broken.
2873
- line += (r2 == null && q.weeklyAbsent)
2874
- ? ` ${l2} ${emptyBar('none', bw)}`
2875
- : ` ${l2} ${bar(r2, bw, t2)}`;
3164
+ bars.push((r2 == null && q.weeklyAbsent)
3165
+ ? `${l2} ${emptyBar('none', bw)}`
3166
+ : `${l2} ${bar(r2, bw, t2)}`);
2876
3167
  }
3168
+ let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} ${resetsCell} ${bars.join(' ')}`;
2877
3169
  const weekly = weeklyPolicyText(this.am, a);
2878
3170
  if (weekly) line += ` ${weekly}`;
2879
3171
  // Per-account SETTINGS (preferred pin, usage cap), whatever the account is
@@ -2894,7 +3186,7 @@ export class TUI {
2894
3186
  const reserveFloor = this.am.scheduler?.weeklyReserveThreshold ?? 0.85;
2895
3187
  const scopedTags = [];
2896
3188
  for (const [fam, e] of Object.entries(q.scopedWeekly || {})) {
2897
- if (!e || e.isActive === false || e.utilization == null) continue;
3189
+ if (!e || e.utilization == null) continue;
2898
3190
  if (e.utilization < reserveFloor) continue;
2899
3191
  const Fam = fam.charAt(0).toUpperCase() + fam.slice(1);
2900
3192
  scopedTags.push(e.utilization >= exhaustedFloor
@@ -2906,7 +3198,7 @@ export class TUI {
2906
3198
  // headers don't carry them). If the probe has gone stale, say so — and name the
2907
3199
  // cause (e.g. rate-limited) when a probe failure is on record — rather than imply
2908
3200
  // the last-known value is current.
2909
- line += this._probeHealthNote(a);
3201
+ line += this._probeHealthNote(a, showFable);
2910
3202
  const act = loadText(this._accountLoad(a));
2911
3203
  if (act) line += ` ${dim(act)}`;
2912
3204
  return line;
@@ -2916,7 +3208,7 @@ export class TUI {
2916
3208
  * stale, names the cause from the last recorded probe failure (e.g. a 429 from
2917
3209
  * the usage endpoint) so a self-throttling probe reads as "rate-limited" rather
2918
3210
  * than an unexplained "stale". Leading spaces included so callers append raw. */
2919
- _probeHealthNote(a) {
3211
+ _probeHealthNote(a, showFable = false) {
2920
3212
  // A dead account (reauth / disabled) already surfaces its state in the status
2921
3213
  // column, and its quota reading is frozen and moot — the prober skips it, so a
2922
3214
  // "stale·probe 401" here is just the perpetual echo of the 401 that killed it.
@@ -2930,11 +3222,15 @@ export class TUI {
2930
3222
  // so a BUSY oauth account with a header-fresh reading and no probe-only scoped
2931
3223
  // cap is NOT stale, even if its background probe is 429-throttled. Provider bars
2932
3224
  // and per-model scoped caps ARE probe-only, so for those a stale probe genuinely
2933
- // means stale data → keep flagging.
3225
+ // means stale data → keep flagging. A scoped reading is DISPLAYED when its tag
3226
+ // shows (at or above the reserve floor) or, for Fable, whenever the Fbl bar is on
3227
+ // screen: the bar draws the reading at any level, so a stale low Fbl value must
3228
+ // carry the age marker too.
2934
3229
  const q = a.quota || {};
2935
3230
  const reserveFloor = this.am.scheduler?.weeklyReserveThreshold ?? 0.85; // mirrors _renderAcct's scoped-tag gate
2936
- const hasDisplayedScopedCap = Object.values(q.scopedWeekly || {}).some(
2937
- e => e && e.isActive !== false && e.utilization != null && e.utilization >= reserveFloor);
3231
+ const hasDisplayedScopedCap = Object.entries(q.scopedWeekly || {}).some(([family, e]) =>
3232
+ e && e.isActive !== false && e.utilization != null
3233
+ && (e.utilization >= reserveFloor || (showFable && family === 'fable')));
2938
3234
  if (a.type !== 'provider' && !hasDisplayedScopedCap) {
2939
3235
  const interval = this.am.quotaProbeIntervalMs; // > 0 here (else _quotaProbeStale returned false)
2940
3236
  const headerFresh = q.lastHeaderQuotaAt && (Date.now() - q.lastHeaderQuotaAt) <= Math.max(3 * interval, 180_000);
@@ -2971,7 +3267,7 @@ export class TUI {
2971
3267
  return interval > 0 ? `every ${formatAge(interval)}` : 'shortly';
2972
3268
  }
2973
3269
 
2974
- _renderProviderAcct(sel, cur, name, type, status, a, bw = 11, showBoth = true) {
3270
+ _renderProviderAcct(sel, cur, name, type, status, a, bw = 11, showBoth = true, showFable = showBoth, showSession = true) {
2975
3271
  const q = a.quota || {};
2976
3272
 
2977
3273
  // Ses/Wk bars in the SAME columns as OAuth rows (right after status) so the
@@ -3029,8 +3325,11 @@ export class TUI {
3029
3325
  // setting whenever the probe is quiet is how a shipped feature reads as absent.
3030
3326
  for (const tag of settingsTags(this.am, a)) note += ` ${tag}`;
3031
3327
 
3032
- let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} Ses ${sesCell}`;
3033
- if (showBoth) line += ` Wk ${wkCell}`;
3328
+ const bars = [];
3329
+ if (showFable) bars.push(`Fbl ${scopedWeeklyBar(q, 'fable', bw)}`);
3330
+ if (showSession) bars.push(`Ses ${sesCell}`);
3331
+ if (showBoth) bars.push(`Wk ${wkCell}`);
3332
+ let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} ${bars.join(' ')}`;
3034
3333
  line += note;
3035
3334
  // Same recent-load columns as OAuth (providers track inFlight + load events),
3036
3335
  // plus a compact Last <status> <ms> — the one signal that matters for a
@@ -3058,13 +3357,25 @@ export class TUI {
3058
3357
  if (account.load) return account.load;
3059
3358
  if (!this.am?._loadSummary) return null;
3060
3359
  const now = Date.now();
3360
+ const base = w => {
3361
+ const load = this.am._loadSummary(account, w, now);
3362
+ const key = w === 15 * 60_000 ? 'last15m' : 'last1h';
3363
+ // A cloud row merges both pools' halves (rowEfficiencySummary): cache + served
3364
+ // from the serving pool's export (team-wide on that account), bounces / waits /
3365
+ // moves from this Mac's own events — the parts the cloud cannot see.
3366
+ const team = Boolean(account.remote && account._remoteLoad?.[key]?.efficiency);
3367
+ const efficiency = this.am.rowEfficiencySummary
3368
+ ? this.am.rowEfficiencySummary(account, key, now)
3369
+ : this.am._efficiencySummary(account, w, now);
3370
+ return team ? { ...load, efficiency, team: true } : { ...load, efficiency };
3371
+ };
3061
3372
  return {
3062
3373
  current: {
3063
3374
  inFlight: account.inFlight,
3064
3375
  activeWeight: account.activeWeight,
3065
3376
  },
3066
- last15m: this.am._loadSummary(account, 15 * 60 * 1000, now),
3067
- last1h: this.am._loadSummary(account, 60 * 60 * 1000, now),
3377
+ last15m: base(15 * 60 * 1000),
3378
+ last1h: base(60 * 60 * 1000),
3068
3379
  };
3069
3380
  }
3070
3381
 
@@ -3304,6 +3615,7 @@ export class TUI {
3304
3615
  if (hasPeak) {
3305
3616
  out.push(` ${bold('c')} GLM peak cap ${dim('— GLM accounts only, in GLM peak hours. Not Claude.')}`);
3306
3617
  }
3618
+ out.push(` ${bold('b')} Wait for busy account ${cyan(this._stickyBusyLabel())}`);
3307
3619
  // Where the per-account cap actually is.
3308
3620
  out.push(` ${dim('Usage cap for ONE account:')} ${bold('Esc')} ${dim('then')} ${bold('a')} ${dim('→')} ${bold('u')} ${dim('(Claude or GLM)')}`);
3309
3621
  const capped = this.am.accounts.filter(a => a.capUtilization != null && a.enabled !== false);
@@ -3316,7 +3628,7 @@ export class TUI {
3316
3628
  _renderFooter() {
3317
3629
  switch (this.mode) {
3318
3630
  case 'normal':
3319
- return ` ${bold('a')} Accounts ${bold('m')} Routing ${bold('y')} Capacity ${bold('p')} People ${bold('h')} Hide disabled ${dim('│')} ${bold('u')} Updates ${bold('r')} Restart ${bold('q')} Stop server`;
3631
+ return ` ${bold('a')} Accounts ${bold('m')} Routing ${bold('y')} Capacity ${bold('p')} People ${bold('h')} Hide disabled ${dim('│')} ${bold('u')} Updates ${bold('r')} Restart ${bold('q')} ${serviceMode() ? 'Close view' : 'Stop server'}`;
3320
3632
  case 'capacity': {
3321
3633
  const other = this.capacityWindow === 'wk' ? '5h session' : 'weekly (7d)';
3322
3634
  return ` ${bold('w')} Show ${cyan(other)} ${bold('Esc')} Back`;