@cortexkit/common-auth 0.31.0 → 0.32.1

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.
@@ -1,3 +1,4 @@
1
+ import { channel } from 'node:diagnostics_channel';
1
2
  import { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
2
3
  import { createLogger } from '../logger/index.js';
3
4
  import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability.js';
@@ -27,6 +28,8 @@ function scopedRetryReason(served, current) {
27
28
  return 'rotated';
28
29
  }
29
30
  const defaultLogger = createLogger('claustrum');
31
+ // Opt-in diagnostics let tests retain wait phases without logging each vault read.
32
+ const phaseDiagnostics = channel('common-auth.claustrum.phases');
30
33
  /**
31
34
  * Decide whether a request that got a 401 should retry with the freshly
32
35
  * re-authorized receipt, and log the decision. The vault can refresh a
@@ -280,6 +283,11 @@ export class ClaustrumScopedCustody {
280
283
  }
281
284
  async #token(signal) {
282
285
  this.#check(signal);
286
+ if (phaseDiagnostics.hasSubscribers)
287
+ phaseDiagnostics.publish({
288
+ logger: this.#logger,
289
+ phase: 'token read begin',
290
+ });
283
291
  const pending = this.#readToken();
284
292
  this.#tokenReads.add(pending);
285
293
  let value;
@@ -288,6 +296,11 @@ export class ClaustrumScopedCustody {
288
296
  }
289
297
  finally {
290
298
  this.#tokenReads.delete(pending);
299
+ if (phaseDiagnostics.hasSubscribers)
300
+ phaseDiagnostics.publish({
301
+ logger: this.#logger,
302
+ phase: 'token read end',
303
+ });
291
304
  }
292
305
  this.#check(signal);
293
306
  if (!/^[0-9a-f]{64}$/.test(value.token) ||
@@ -359,6 +372,11 @@ export class ClaustrumScopedCustody {
359
372
  this.#kept.clear();
360
373
  throw error;
361
374
  }
375
+ if (phaseDiagnostics.hasSubscribers)
376
+ phaseDiagnostics.publish({
377
+ logger: this.#logger,
378
+ phase: 'list scoped begin',
379
+ });
362
380
  try {
363
381
  inventory = await this.#call(() => this.#client.listScoped(token), signal);
364
382
  }
@@ -366,6 +384,13 @@ export class ClaustrumScopedCustody {
366
384
  this.listFailed(error);
367
385
  throw error;
368
386
  }
387
+ finally {
388
+ if (phaseDiagnostics.hasSubscribers)
389
+ phaseDiagnostics.publish({
390
+ logger: this.#logger,
391
+ phase: 'list scoped end',
392
+ });
393
+ }
369
394
  const skipped = [];
370
395
  const refused = [];
371
396
  let notMine = 0;
@@ -11,6 +11,7 @@
11
11
  // different processes already share, plus the base-view rule, so a commit
12
12
  // never replaces a view another process committed after this hub listed.
13
13
  import { createHash } from 'node:crypto';
14
+ import { channel } from 'node:diagnostics_channel';
14
15
  import { readdir, stat } from 'node:fs/promises';
15
16
  import { dirname, join, resolve } from 'node:path';
16
17
  import { createLogger } from '../logger/index.js';
@@ -766,7 +767,25 @@ export class ClaustrumDiscoveryHub {
766
767
  throw base;
767
768
  // A member's first roster under this key carries the declines and
768
769
  // order of its newest roster under an older key.
769
- const seed = base.file ? undefined : await this.#seed(entry);
770
+ let seed;
771
+ if (!base.file) {
772
+ const phaseDiagnostics = channel('common-auth.claustrum.phases');
773
+ if (phaseDiagnostics.hasSubscribers)
774
+ phaseDiagnostics.publish({
775
+ logger: this.#logger,
776
+ phase: `seed read ${entry.provider} begin`,
777
+ });
778
+ try {
779
+ seed = await this.#seed(entry);
780
+ }
781
+ finally {
782
+ if (phaseDiagnostics.hasSubscribers)
783
+ phaseDiagnostics.publish({
784
+ logger: this.#logger,
785
+ phase: `seed read ${entry.provider} end`,
786
+ });
787
+ }
788
+ }
770
789
  const roster = await refreshVaultRoster({
771
790
  path: entry.path,
772
791
  custody: { discover: async () => share },
@@ -443,6 +443,12 @@ export class InsulaQuotaSource {
443
443
  ...(typeof entry.source === 'string' && { source: entry.source }),
444
444
  },
445
445
  };
446
+ // Kept usage must not trigger a provider poll after a non-local failure.
447
+ // Only an explicitly local failure permits fallback; unknown causes do not.
448
+ if (entry.stale !== undefined &&
449
+ (!record(entry.stale) ||
450
+ entry.stale.class !== 'local_source_unavailable'))
451
+ return { miss: 'upstream-failed', reading };
446
452
  return now >= fetchedAt + MAX_AGE || entry.stale !== undefined
447
453
  ? { miss: 'stale', reading }
448
454
  : { reading };
@@ -3,7 +3,7 @@ import type { JSX } from '@opentui/solid';
3
3
  import type { QuotaWindowPart } from '../quota/format.js';
4
4
  import type { ProjectedQuota } from '../quota/projection.js';
5
5
  export type Tone = 'text' | 'textMuted' | 'accent' | 'success' | 'warning' | 'error';
6
- export type SidebarTheme = Readonly<Record<Tone | 'background' | 'borderActive', RGBA>>;
6
+ export type SidebarTheme = Readonly<Partial<Record<Tone | 'background' | 'borderActive', RGBA | string | undefined>>>;
7
7
  export interface SidebarAppearance {
8
8
  barWidth: number;
9
9
  barFilledChar: string;
@@ -55,7 +55,7 @@ export interface SidebarFrameProps {
55
55
  version?: string;
56
56
  };
57
57
  accounts: readonly AccountView[];
58
- theme: SidebarTheme;
58
+ theme?: SidebarTheme;
59
59
  appearance: SidebarAppearance;
60
60
  showQuota: boolean;
61
61
  now: number;
@@ -64,6 +64,7 @@ export interface SidebarFrameProps {
64
64
  beforeQuota?: (account: AccountView) => JSX.Element;
65
65
  afterQuota?: (account: AccountView) => JSX.Element;
66
66
  sections?: () => JSX.Element;
67
+ collapsedSections?: () => JSX.Element;
67
68
  }
68
69
  /** A heading and its plugin-owned rows, with the frame's section spacing. */
69
70
  export declare function SidebarSection(props: {
@@ -79,6 +80,7 @@ export declare function SidebarStatRow(props: {
79
80
  export declare function SidebarTextRow(props: {
80
81
  text: string;
81
82
  tone?: Tone;
83
+ wrapMode?: JSX.IntrinsicElements['text']['wrapMode'];
82
84
  }): any;
83
85
  /** Borderless, controlled presentation; host registration and provider policy stay in the plugin. */
84
86
  export declare function SidebarFrame(props: SidebarFrameProps): any;
@@ -1,4 +1,4 @@
1
- import { createContext, createMemo, createSignal, For, Show, useContext, } from 'solid-js';
1
+ import { createContext, createMemo, createSignal, For, Index, mergeProps, Show, useContext, } from 'solid-js';
2
2
  import { formatQuota, quotaWindowParts } from '../quota/format.js';
3
3
  const FrameContext = createContext();
4
4
  function frameContext() {
@@ -60,7 +60,9 @@ export function SidebarStatRow(props) {
60
60
  }
61
61
  export function SidebarTextRow(props) {
62
62
  const context = frameContext();
63
- return <text fg={context.theme[props.tone ?? 'textMuted']}>{props.text}</text>;
63
+ return (<text fg={context.theme[props.tone ?? 'textMuted']} wrapMode={props.wrapMode}>
64
+ {props.text}
65
+ </text>);
64
66
  }
65
67
  function usageTone(used, appearance) {
66
68
  if (used >= appearance.errorThreshold)
@@ -74,18 +76,20 @@ function barSegments(used, appearance, pace) {
74
76
  const cells = (pct) => Math.max(0, Math.min(Math.round((pct / 100) * width), width));
75
77
  const usedCells = cells(used);
76
78
  const tone = usageTone(used, appearance);
79
+ // Keep the overlay's slot even when empty so live pacing changes reuse nodes.
77
80
  const plain = [
78
81
  { text: appearance.barFilledChar.repeat(usedCells), tone },
82
+ { text: '', tone },
79
83
  { text: appearance.barEmptyChar.repeat(width - usedCells), tone },
80
84
  ];
81
85
  const overlay = pace?.overlay;
82
86
  if (!overlay)
83
- return plain.filter((segment) => segment.text.length > 0);
87
+ return plain;
84
88
  const paceCells = cells(overlay.percent);
85
89
  const lo = Math.min(usedCells, paceCells);
86
90
  const hi = Math.max(usedCells, paceCells);
87
91
  if (lo === hi)
88
- return plain.filter((segment) => segment.text.length > 0);
92
+ return plain;
89
93
  return [
90
94
  { text: appearance.barFilledChar.repeat(lo), tone },
91
95
  {
@@ -93,33 +97,24 @@ function barSegments(used, appearance, pace) {
93
97
  tone: overlay.kind === 'deficit' ? 'error' : 'success',
94
98
  },
95
99
  { text: appearance.barEmptyChar.repeat(width - hi), tone },
96
- ].filter((segment) => segment.text.length > 0);
100
+ ];
97
101
  }
98
102
  function QuotaRow(props) {
99
103
  const context = frameContext();
100
104
  const [columns, setColumns] = createSignal(0);
101
105
  let row;
102
- const label = () => props.part.name.padEnd(props.labelWidth);
106
+ const label = () => props.part.name +
107
+ ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)));
103
108
  const figure = () => ` ${props.part.kind === 'budget' && props.part.figure.startsWith(`${props.part.name} `) ? props.part.figure.slice(props.part.name.length + 1) : props.part.figure}`;
104
- const reset = () => props.part.resetIn ?? (props.part.resetSinceReading ? 'reset' : undefined);
105
109
  const used = () => 100 - (props.part.remainingPercent ?? 100);
106
- const fit = () => {
107
- const barWidth = context.appearance.barWidth;
108
- const resetWidth = displayWidth(reset() ?? '');
109
- if (columns() <= 0)
110
- return { barCells: barWidth, showReset: resetWidth > 0 };
111
- const fixed = displayWidth(label()) + displayWidth(figure());
112
- if (resetWidth > 0 && fixed + barWidth + 1 + resetWidth <= columns())
113
- return { barCells: barWidth, showReset: true };
114
- const room = columns() - fixed;
115
- return {
116
- barCells: room >= barWidth ? barWidth : room >= 3 ? room : 0,
117
- showReset: false,
118
- };
119
- };
120
- // Stable fits keep existing bar nodes alive through the first measurement.
121
- const barCells = createMemo(() => fit().barCells);
122
- const showReset = createMemo(() => fit().showReset);
110
+ // Size notifications can recompute an unchanged fit after text has been flushed
111
+ // for the frame. Keep equal segments, and update fixed slots in place when the
112
+ // bar changes, rather than replacing text nodes during layout.
113
+ const segments = createMemo(() => barSegments(used(), { ...context.appearance, barWidth: props.barCells }, props.pace), undefined, {
114
+ equals: (previous, next) => previous.length === next.length &&
115
+ previous.every((segment, index) => segment.text === next[index]?.text &&
116
+ segment.tone === next[index]?.tone),
117
+ });
123
118
  const paceLine = () => {
124
119
  const text = props.pace?.text;
125
120
  if (!text || columns() <= 0)
@@ -130,31 +125,46 @@ function QuotaRow(props) {
130
125
  <box ref={(element) => {
131
126
  row = element;
132
127
  }} onSizeChange={() => setColumns(row?.width ?? 0)} width='100%' flexDirection='row' justifyContent='space-between'>
133
- <box flexDirection='row' flexShrink={0}>
134
- <text fg={context.theme.textMuted} wrapMode='none'>
135
- {label()}
136
- </text>
137
- <For each={barSegments(used(), { ...context.appearance, barWidth: barCells() }, props.pace)}>
138
- {(segment) => (<text fg={context.theme[segment.tone]} wrapMode='none'>
139
- {segment.text}
140
- </text>)}
141
- </For>
142
- <text fg={context.theme[usageTone(used(), context.appearance)]} wrapMode='none'>
143
- {figure()}
144
- </text>
128
+ <box flexDirection='row' flexShrink={props.part.resetSinceReading ? 1 : 0}>
129
+ <Show when={props.labelWidth > 0}>
130
+ <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
131
+ {label()}
132
+ </text>
133
+ </Show>
134
+ <Show when={!props.part.resetSinceReading} fallback={<text fg={context.theme.textMuted} wrapMode='none'>
135
+ reset since last check
136
+ </text>}>
137
+ <Show when={props.barCells > 0}>
138
+ {/* Text nodes clear omitted theme colours; empty slots must not reserve a cell. */}
139
+ <Index each={segments()}>
140
+ {(segment) => (<text fg={context.theme[segment().tone]} wrapMode='none' width={segment().text ? undefined : 0}>
141
+ {segment().text}
142
+ </text>)}
143
+ </Index>
144
+ </Show>
145
+ <text fg={context.theme[usageTone(used(), context.appearance)]} wrapMode='none'>
146
+ {figure()}
147
+ </text>
148
+ </Show>
145
149
  </box>
146
- <Show when={showReset()}>
147
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
148
- {reset()}
149
- </text>
150
+ <Show when={props.showReset && !props.part.resetSinceReading}>
151
+ <box width={props.resetWidth} flexShrink={0} flexDirection='row' justifyContent='flex-end'>
152
+ <Show when={props.part.resetIn}>
153
+ <text fg={context.theme.textMuted} wrapMode='none'>
154
+ {props.part.resetIn}
155
+ </text>
156
+ </Show>
157
+ </box>
150
158
  </Show>
151
159
  </box>
152
160
  {/* A changed fitted line needs a fresh text node to draw at its new width. */}
153
- <Show when={paceLine()} keyed>
161
+ <Show when={!props.part.resetSinceReading && paceLine()} keyed>
154
162
  {(line) => (<box width='100%' flexDirection='row'>
155
- <text fg={context.theme.textMuted}>
156
- {''.padEnd(props.labelWidth)}
157
- </text>
163
+ <Show when={props.labelWidth > 0}>
164
+ <text fg={context.theme.textMuted}>
165
+ {''.padEnd(props.labelWidth)}
166
+ </text>
167
+ </Show>
158
168
  <text fg={context.theme[props.pace?.tone ?? 'textMuted']} wrapMode='none'>
159
169
  {line}
160
170
  </text>
@@ -170,70 +180,102 @@ function CollapsedAccountRow(props) {
170
180
  0;
171
181
  const text = () => hasQuota()
172
182
  ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
173
- : null;
183
+ : (props.account.emptyQuotaText?.collapsed ?? '\u2014');
184
+ // Reserve an ellipsis, a separator and the trailing indicator before keeping quota.
185
+ const showQuota = () => width() <= 0 || displayWidth(text()) + 4 <= width();
174
186
  const label = () => {
175
187
  if (width() <= 0)
176
188
  return props.account.label;
177
- const value = text() === null
178
- ? displayWidth(props.account.emptyQuotaText?.collapsed ?? '\u2014')
179
- : displayWidth(text() ?? '') + 2;
180
- return fitText(props.account.label, width() - value - 1);
189
+ return fitText(props.account.label, width() - (showQuota() ? displayWidth(text()) + 3 : 2));
181
190
  };
182
191
  const muted = () => props.account.collapsed?.muted ?? false;
183
192
  const quotaTone = () => muted() ? 'textMuted' : (props.account.collapsed?.quotaTone ?? 'success');
184
193
  return (<box ref={(element) => {
185
194
  row = element;
186
- }} onSizeChange={() => setWidth(row?.width ?? 0)} width='100%' flexDirection='row' justifyContent='space-between'>
187
- <text fg={context.theme[muted() ? 'textMuted' : 'text']} wrapMode='none' flexShrink={1}>
188
- {label()}
189
- </text>
190
- <Show when={text() !== null} fallback={<text fg={context.theme.textMuted}>
191
- {props.account.emptyQuotaText?.collapsed ?? '\u2014'}
192
- </text>}>
193
- <box flexDirection='row' flexShrink={0}>
194
- <Show when={!muted()} fallback={<text fg={context.theme.textMuted}>{text()}</text>}>
195
+ }} onSizeChange={() => setWidth(row?.width ?? 0)} width='100%' flexDirection='row' justifyContent='space-between' columnGap={label() ? 1 : 0}>
196
+ <Show when={label()}>
197
+ <text fg={context.theme[muted() ? 'textMuted' : 'text']} wrapMode='none' flexShrink={1}>
198
+ {label()}
199
+ </text>
200
+ </Show>
201
+ <box flexDirection='row' flexShrink={0}>
202
+ <Show when={showQuota()}>
203
+ <Show when={hasQuota() && !muted()} fallback={<text fg={context.theme.textMuted}>{text()}</text>}>
195
204
  <text fg={context.theme[quotaTone()]}>
196
205
  <b>{text()}</b>
197
206
  </text>
198
207
  </Show>
199
- <text fg={context.theme[props.account.indicatorTone]}>
200
- {props.account.blocked ? ' \u2298' : ' \u25cf'}
201
- </text>
202
- </box>
203
- </Show>
208
+ </Show>
209
+ <text fg={context.theme[props.account.indicatorTone]}>
210
+ {showQuota() ? ' ' : ''}
211
+ {props.account.blocked ? '\u2298' : '\u25cf'}
212
+ </text>
213
+ </box>
204
214
  </box>);
205
215
  }
206
216
  function AccountBlock(props) {
207
217
  const context = frameContext();
218
+ const [columns, setColumns] = createSignal(0);
219
+ let block;
220
+ const rows = () => props.account.groups.flatMap((group) => group.rows);
221
+ const labelWidth = () => Math.max(0, ...rows().map(({ part }) => part.name ? Math.max(3, displayWidth(part.name) + 1) : 0));
222
+ const resetWidth = () => Math.max(0, ...rows().map(({ part }) => part.resetSinceReading ? 0 : displayWidth(part.resetIn ?? '')));
223
+ const figureWidth = createMemo(() => Math.max(10, ...rows()
224
+ .filter(({ part }) => !part.resetSinceReading)
225
+ .map(({ part }) => displayWidth(` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`))));
226
+ const fit = (rowLabelWidth) => {
227
+ const desired = context.appearance.barWidth;
228
+ // Four cells still distinguish quarters of a window without sacrificing its reset.
229
+ const minimum = Math.min(4, desired);
230
+ if (columns() <= 0)
231
+ return { barCells: desired, showReset: resetWidth() > 0 };
232
+ const room = columns() - rowLabelWidth - figureWidth();
233
+ const withReset = room - resetWidth() - 1;
234
+ const showReset = resetWidth() > 0 && withReset >= minimum;
235
+ const available = showReset ? withReset : room;
236
+ return {
237
+ barCells: available >= minimum ? Math.min(desired, available) : 0,
238
+ showReset,
239
+ };
240
+ };
241
+ const label = () => {
242
+ const full = `${props.account.label}${props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}`;
243
+ return columns() <= 0
244
+ ? full
245
+ : fitText(full, columns() - displayWidth(props.account.status.text) - 1);
246
+ };
208
247
  const age = () => quotaWindowParts(props.account.quota, { now: context.now }).age;
209
248
  const hasRows = () => props.account.groups.some((group) => group.rows.length > 0);
210
- return (<box width='100%' flexDirection='column' marginTop={props.marginTop}>
211
- <box width='100%' flexDirection='row' justifyContent='space-between'>
212
- <text fg={context.theme.text}>
213
- <b>
214
- {props.account.label}
215
- {props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}
216
- </b>
249
+ return (<box ref={(element) => {
250
+ block = element;
251
+ }} onSizeChange={() => setColumns(block?.width ?? 0)} width='100%' flexDirection='column' marginTop={props.marginTop}>
252
+ <box width='100%' flexDirection='row' justifyContent='space-between' columnGap={1}>
253
+ <text fg={context.theme.text} wrapMode='none' flexShrink={1}>
254
+ <b>{label()}</b>
217
255
  </text>
218
- <text fg={context.theme[props.account.status.tone]}>
256
+ <text fg={context.theme[props.account.status.tone]} wrapMode='none' flexShrink={0}>
219
257
  <b>{props.account.status.text}</b>
220
258
  </text>
221
259
  </box>
222
260
  {context.beforeQuota?.(props.account)}
223
- <Show when={hasRows()} fallback={<SidebarTextRow text={props.account.emptyQuotaText?.expanded ?? '\u2014'}/>}>
261
+ <Show when={hasRows()} fallback={<SidebarTextRow text={props.account.emptyQuotaText?.expanded ?? '\u2014'} wrapMode='none'/>}>
224
262
  <For each={props.account.groups}>
225
263
  {(group) => (<>
226
264
  <Show when={group.title}>
227
- <SidebarTextRow text={group.title ?? ''} tone='text'/>
265
+ <SidebarTextRow text={group.title ?? ''} tone='text' wrapMode='none'/>
228
266
  </Show>
229
267
  <For each={group.rows}>
230
- {(row) => (<QuotaRow part={row.part} pace={row.pace} labelWidth={props.labelWidth}/>)}
268
+ {(row) => {
269
+ const rowLabelWidth = () => (row.part.name ? labelWidth() : 0);
270
+ const rowFit = createMemo(() => fit(rowLabelWidth()));
271
+ return (<QuotaRow part={row.part} pace={row.pace} labelWidth={rowLabelWidth()} barCells={rowFit().barCells} resetWidth={resetWidth()} showReset={rowFit().showReset}/>);
272
+ }}
231
273
  </For>
232
274
  </>)}
233
275
  </For>
234
276
  </Show>
235
277
  <Show when={age()}>
236
- {(text) => <SidebarTextRow text={text()}/>}
278
+ {(text) => (<SidebarTextRow text={text()} wrapMode='none'/>)}
237
279
  </Show>
238
280
  {context.afterQuota?.(props.account)}
239
281
  </box>);
@@ -244,34 +286,50 @@ export function SidebarFrame(props) {
244
286
  const headerLabel = () => !hasData()
245
287
  ? props.header.badge
246
288
  : `${props.collapsed ? '\u25b6' : '\u25bc'} ${props.header.badge}`;
247
- const labelWidth = () => Math.max(3, ...props.accounts.flatMap((account) => account.groups.flatMap((group) => group.rows.map((row) => row.part.name.length + 1))));
248
- return (<FrameContext.Provider value={props}>
249
- <box width='100%' flexDirection='column' paddingTop={1} paddingBottom={1} paddingLeft={1} paddingRight={1}>
289
+ // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
290
+ const context = mergeProps(props, {
291
+ get theme() {
292
+ const theme = props.theme;
293
+ return {
294
+ ...theme,
295
+ textMuted: theme?.textMuted ?? theme?.text,
296
+ accent: theme?.accent ?? theme?.text,
297
+ success: theme?.success ?? theme?.text,
298
+ warning: theme?.warning ?? theme?.text,
299
+ error: theme?.error ?? theme?.text,
300
+ };
301
+ },
302
+ });
303
+ // Inverting an incomplete badge palette can put light text on a light background.
304
+ const invertBadge = () => props.theme?.accent !== undefined && props.theme?.background !== undefined;
305
+ return (<FrameContext.Provider value={context}>
306
+ <box width='100%' flexDirection='column'>
250
307
  {/* Blocked accounts retain their own indicators; the header always keeps its version. */}
251
308
  {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI terminal widgets do not have DOM roles */}
252
309
  <box width='100%' flexDirection='row' justifyContent='space-between' alignItems='center' onMouseDown={() => {
253
310
  if (hasData())
254
311
  props.onToggle();
255
312
  }}>
256
- <box paddingLeft={1} paddingRight={1} backgroundColor={props.theme.accent}>
257
- <text fg={props.theme.background}>
313
+ <box paddingLeft={1} paddingRight={1} backgroundColor={invertBadge() ? props.theme?.accent : undefined}>
314
+ <text fg={invertBadge() ? props.theme?.background : context.theme.accent}>
258
315
  <b>{headerLabel()}</b>
259
316
  </text>
260
317
  </box>
261
318
  <Show when={props.header.version}>
262
- <text fg={props.theme.textMuted}>{props.header.version}</text>
319
+ <text fg={context.theme.textMuted}>{props.header.version}</text>
263
320
  </Show>
264
321
  </box>
265
322
  <Show when={props.collapsed && hasData()}>
266
323
  <For each={props.accounts}>
267
324
  {(account) => <CollapsedAccountRow account={account}/>}
268
325
  </For>
326
+ {props.collapsedSections?.()}
269
327
  </Show>
270
328
  <Show when={!props.collapsed || !hasData()}>
271
329
  <Show when={props.showQuota && hasData()}>
272
330
  <SidebarSection title='Quota'>
273
331
  <For each={props.accounts}>
274
- {(account, index) => (<AccountBlock account={account} labelWidth={labelWidth()} marginTop={index() === 0 ? 0 : 1}/>)}
332
+ {(account, index) => (<AccountBlock account={account} marginTop={index() === 0 ? 0 : 1}/>)}
275
333
  </For>
276
334
  </SidebarSection>
277
335
  </Show>
@@ -0,0 +1,56 @@
1
+ /** An eligible vault route, not a local pool row. */
2
+ export interface RoutingCandidate {
3
+ /** Vault account id, not the plugin's route id. */
4
+ accountId: string;
5
+ credentialId: string;
6
+ }
7
+ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCandidate> {
8
+ sessionId: string;
9
+ provider: string;
10
+ modelId: string;
11
+ /** Only routes already eligible under the plugin's vault and killswitch rules. */
12
+ candidates: readonly Candidate[];
13
+ /** Defaults to 500 ms, clamped to 1–2000 ms. */
14
+ deadlineMs?: number;
15
+ }
16
+ export interface RoutingHold {
17
+ /** Uncapped advice from routing. The plugin must apply its own hold cap. */
18
+ retry_after_ms: number;
19
+ }
20
+ export interface RoutingSelection<Candidate extends RoutingCandidate = RoutingCandidate> {
21
+ /** The original eligible candidate, including any plugin-specific metadata. */
22
+ candidate: Candidate;
23
+ hold?: RoutingHold;
24
+ }
25
+ interface RoutingReportIdentity {
26
+ sessionId: string;
27
+ accountId: string;
28
+ credentialId?: string;
29
+ }
30
+ export type ReportRoutingInput = RoutingReportIdentity & ({
31
+ outcome: 'served';
32
+ /**
33
+ * Pass only rate-limit headers, never the whole response headers.
34
+ * Values are forwarded unchanged; do not include tokens, emails or labels.
35
+ */
36
+ headers: Readonly<Record<string, string>>;
37
+ } | {
38
+ outcome: 'exhausted';
39
+ /** A quota window such as `5h`, `7d` or a scoped window id. */
40
+ window: string;
41
+ /** Optional reset time in epoch milliseconds. */
42
+ resetsAt?: number;
43
+ });
44
+ /**
45
+ * Ask routing for an eligible vault route. Any failure or unfamiliar answer
46
+ * yields undefined so the plugin can keep its own choice. This does not admit
47
+ * routes: callers must exclude vault refusals and killswitch-blocked accounts.
48
+ */
49
+ export declare function askRouting<Candidate extends RoutingCandidate>(input: AskRoutingInput<Candidate>): Promise<RoutingSelection<Candidate> | undefined>;
50
+ /**
51
+ * Report a vault request without waiting for routing. Only contract fields are
52
+ * sent, and all accessor failures are ignored. Headers must already be limited
53
+ * to rate-limit headers by the caller; values are not filtered or redacted here.
54
+ */
55
+ export declare function reportRouting(input: ReportRoutingInput): void;
56
+ export {};
@@ -0,0 +1,119 @@
1
+ // Optional THALAMUS routing for vault mode only. Account ids here are vault
2
+ // account ids; local pool rows are not known to the routing engine.
3
+ function isObject(value) {
4
+ return typeof value === 'object' && value !== null;
5
+ }
6
+ function routingHandle(sessionId) {
7
+ // The bridge can load after the auth plugin, so never cache the accessor.
8
+ const routing = Reflect.get(globalThis, Symbol.for('cortexkit.routing'));
9
+ if (typeof routing !== 'function')
10
+ return undefined;
11
+ const handle = routing(sessionId);
12
+ return isObject(handle) ? handle : undefined;
13
+ }
14
+ function selectionFor(answer, candidates) {
15
+ if (!isObject(answer))
16
+ return undefined;
17
+ const accountId = answer.account_id;
18
+ const credentialId = answer.credential_id;
19
+ if (typeof accountId !== 'string')
20
+ return undefined;
21
+ if (credentialId !== undefined && typeof credentialId !== 'string') {
22
+ return undefined;
23
+ }
24
+ const candidate = candidates.find((route) => route.accountId === accountId &&
25
+ (credentialId === undefined || route.credentialId === credentialId));
26
+ if (!candidate)
27
+ return undefined;
28
+ const hold = answer.hold;
29
+ const retryAfterMs = isObject(hold) ? hold.retry_after_ms : undefined;
30
+ if (typeof retryAfterMs === 'number' &&
31
+ Number.isFinite(retryAfterMs) &&
32
+ retryAfterMs >= 0) {
33
+ return { candidate, hold: { retry_after_ms: retryAfterMs } };
34
+ }
35
+ return { candidate };
36
+ }
37
+ /**
38
+ * Ask routing for an eligible vault route. Any failure or unfamiliar answer
39
+ * yields undefined so the plugin can keep its own choice. This does not admit
40
+ * routes: callers must exclude vault refusals and killswitch-blocked accounts.
41
+ */
42
+ export async function askRouting(input) {
43
+ let timer;
44
+ try {
45
+ const handle = routingHandle(input.sessionId);
46
+ if (!handle)
47
+ return undefined;
48
+ const accountFor = handle.accountFor;
49
+ if (typeof accountFor !== 'function')
50
+ return undefined;
51
+ const requested = input.deadlineMs ?? 500;
52
+ const deadlineMs = Number.isNaN(requested)
53
+ ? 500
54
+ : Math.min(2000, Math.max(1, requested));
55
+ const expired = new Promise((resolve) => {
56
+ timer = setTimeout(() => resolve(undefined), deadlineMs);
57
+ timer.unref();
58
+ });
59
+ const pending = accountFor.call(handle, { provider: input.provider, modelId: input.modelId }, { deadlineMs });
60
+ if (!isObject(pending) || typeof pending.then !== 'function')
61
+ return undefined;
62
+ const answer = await Promise.race([pending, expired]);
63
+ return selectionFor(answer, input.candidates);
64
+ }
65
+ catch {
66
+ // The process-global bridge is optional and must not break authentication.
67
+ return undefined;
68
+ }
69
+ finally {
70
+ clearTimeout(timer);
71
+ }
72
+ }
73
+ /**
74
+ * Report a vault request without waiting for routing. Only contract fields are
75
+ * sent, and all accessor failures are ignored. Headers must already be limited
76
+ * to rate-limit headers by the caller; values are not filtered or redacted here.
77
+ */
78
+ export function reportRouting(input) {
79
+ try {
80
+ const handle = routingHandle(input.sessionId);
81
+ if (!handle)
82
+ return;
83
+ const report = handle.report;
84
+ if (typeof report !== 'function')
85
+ return;
86
+ const identity = {
87
+ account_id: input.accountId,
88
+ ...(input.credentialId !== undefined
89
+ ? { credential_id: input.credentialId }
90
+ : {}),
91
+ };
92
+ let payload;
93
+ switch (input.outcome) {
94
+ case 'served':
95
+ payload = { ...identity, outcome: 'served', headers: input.headers };
96
+ break;
97
+ case 'exhausted':
98
+ payload = {
99
+ ...identity,
100
+ outcome: 'exhausted',
101
+ window: input.window,
102
+ ...(input.resetsAt !== undefined
103
+ ? { resets_at: input.resetsAt }
104
+ : {}),
105
+ };
106
+ break;
107
+ default:
108
+ return;
109
+ }
110
+ // A broken bridge may return a rejected promise despite its void contract.
111
+ const pending = report.call(handle, payload);
112
+ if (isObject(pending) && typeof pending.then === 'function') {
113
+ void Promise.resolve(pending).catch(() => { });
114
+ }
115
+ }
116
+ catch {
117
+ // Reporting must never change the result of an auth request.
118
+ }
119
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.31.0",
3
+ "version": "0.32.1",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -72,6 +72,10 @@
72
72
  "types": "./dist/routing/index.d.ts",
73
73
  "import": "./dist/routing/index.js"
74
74
  },
75
+ "./routing-accessor": {
76
+ "types": "./dist/routing-accessor/index.d.ts",
77
+ "import": "./dist/routing-accessor/index.js"
78
+ },
75
79
  "./commands": {
76
80
  "types": "./dist/commands/index.d.ts",
77
81
  "import": "./dist/commands/index.js"
@@ -116,7 +120,8 @@
116
120
  "check:ranges": "bun scripts/check-installed-ranges.mjs",
117
121
  "check:claustrum-floor": "bun scripts/check-claustrum-floor.mjs",
118
122
  "check:insula-peer": "bun scripts/check-insula-peer.mjs",
119
- "check:opentui-0511": "bun scripts/check-opentui-0511.mjs"
123
+ "check:opentui-0511": "bun scripts/check-opentui-0511.mjs",
124
+ "check:quota-sidebar-floor": "bun scripts/check-quota-sidebar-floor.mjs"
120
125
  },
121
126
  "dependencies": {
122
127
  "@cortexkit/private-files": "^0.2.2",
@@ -126,8 +131,8 @@
126
131
  "@cortexkit/claustrum-client": ">=0.6.2",
127
132
  "@cortexkit/subc-client": "^0.16.0 || ^0.22.0",
128
133
  "@opencode/plugin": ">=2.0.21",
129
- "@opentui/core": ">=0.5.11",
130
- "@opentui/solid": ">=0.5.11",
134
+ "@opentui/core": ">=0.4.5",
135
+ "@opentui/solid": ">=0.4.5",
131
136
  "solid-js": "1.9.12"
132
137
  },
133
138
  "peerDependenciesMeta": {
@@ -5,6 +5,8 @@ import {
5
5
  createMemo,
6
6
  createSignal,
7
7
  For,
8
+ Index,
9
+ mergeProps,
8
10
  Show,
9
11
  useContext,
10
12
  } from 'solid-js'
@@ -21,7 +23,9 @@ export type Tone =
21
23
  | 'error'
22
24
 
23
25
  export type SidebarTheme = Readonly<
24
- Record<Tone | 'background' | 'borderActive', RGBA>
26
+ Partial<
27
+ Record<Tone | 'background' | 'borderActive', RGBA | string | undefined>
28
+ >
25
29
  >
26
30
 
27
31
  export interface SidebarAppearance {
@@ -61,7 +65,7 @@ export interface AccountView {
61
65
  export interface SidebarFrameProps {
62
66
  header: { badge: string; version?: string }
63
67
  accounts: readonly AccountView[]
64
- theme: SidebarTheme
68
+ theme?: SidebarTheme
65
69
  appearance: SidebarAppearance
66
70
  showQuota: boolean
67
71
  now: number
@@ -70,11 +74,16 @@ export interface SidebarFrameProps {
70
74
  beforeQuota?: (account: AccountView) => JSX.Element
71
75
  afterQuota?: (account: AccountView) => JSX.Element
72
76
  sections?: () => JSX.Element
77
+ collapsedSections?: () => JSX.Element
78
+ }
79
+
80
+ type FrameContextProps = Omit<SidebarFrameProps, 'theme'> & {
81
+ theme: SidebarTheme
73
82
  }
74
83
 
75
- const FrameContext = createContext<SidebarFrameProps>()
84
+ const FrameContext = createContext<FrameContextProps>()
76
85
 
77
- function frameContext(): SidebarFrameProps {
86
+ function frameContext(): FrameContextProps {
78
87
  const context = useContext(FrameContext)
79
88
  if (!context)
80
89
  throw new Error('Sidebar primitives must be inside SidebarFrame')
@@ -158,9 +167,20 @@ export function SidebarStatRow(props: {
158
167
  )
159
168
  }
160
169
 
161
- export function SidebarTextRow(props: { text: string; tone?: Tone }) {
170
+ export function SidebarTextRow(props: {
171
+ text: string
172
+ tone?: Tone
173
+ wrapMode?: JSX.IntrinsicElements['text']['wrapMode']
174
+ }) {
162
175
  const context = frameContext()
163
- return <text fg={context.theme[props.tone ?? 'textMuted']}>{props.text}</text>
176
+ return (
177
+ <text
178
+ fg={context.theme[props.tone ?? 'textMuted']}
179
+ wrapMode={props.wrapMode}
180
+ >
181
+ {props.text}
182
+ </text>
183
+ )
164
184
  }
165
185
 
166
186
  function usageTone(used: number, appearance: SidebarAppearance): Tone {
@@ -179,16 +199,18 @@ function barSegments(
179
199
  Math.max(0, Math.min(Math.round((pct / 100) * width), width))
180
200
  const usedCells = cells(used)
181
201
  const tone = usageTone(used, appearance)
202
+ // Keep the overlay's slot even when empty so live pacing changes reuse nodes.
182
203
  const plain = [
183
204
  { text: appearance.barFilledChar.repeat(usedCells), tone },
205
+ { text: '', tone },
184
206
  { text: appearance.barEmptyChar.repeat(width - usedCells), tone },
185
207
  ]
186
208
  const overlay = pace?.overlay
187
- if (!overlay) return plain.filter((segment) => segment.text.length > 0)
209
+ if (!overlay) return plain
188
210
  const paceCells = cells(overlay.percent)
189
211
  const lo = Math.min(usedCells, paceCells)
190
212
  const hi = Math.max(usedCells, paceCells)
191
- if (lo === hi) return plain.filter((segment) => segment.text.length > 0)
213
+ if (lo === hi) return plain
192
214
  return [
193
215
  { text: appearance.barFilledChar.repeat(lo), tone },
194
216
  {
@@ -197,39 +219,47 @@ function barSegments(
197
219
  overlay.kind === 'deficit' ? ('error' as const) : ('success' as const),
198
220
  },
199
221
  { text: appearance.barEmptyChar.repeat(width - hi), tone },
200
- ].filter((segment) => segment.text.length > 0)
222
+ ]
201
223
  }
202
224
 
203
225
  function QuotaRow(props: {
204
226
  part: QuotaWindowPart
205
227
  pace?: PaceView
206
228
  labelWidth: number
229
+ barCells: number
230
+ resetWidth: number
231
+ showReset: boolean
207
232
  }) {
208
233
  const context = frameContext()
209
234
  const [columns, setColumns] = createSignal(0)
210
235
  let row: { width: number } | undefined
211
- const label = () => props.part.name.padEnd(props.labelWidth)
236
+ const label = () =>
237
+ props.part.name +
238
+ ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)))
212
239
  const figure = () =>
213
240
  ` ${props.part.kind === 'budget' && props.part.figure.startsWith(`${props.part.name} `) ? props.part.figure.slice(props.part.name.length + 1) : props.part.figure}`
214
- const reset = () =>
215
- props.part.resetIn ?? (props.part.resetSinceReading ? 'reset' : undefined)
216
241
  const used = () => 100 - (props.part.remainingPercent ?? 100)
217
- const fit = () => {
218
- const barWidth = context.appearance.barWidth
219
- const resetWidth = displayWidth(reset() ?? '')
220
- if (columns() <= 0) return { barCells: barWidth, showReset: resetWidth > 0 }
221
- const fixed = displayWidth(label()) + displayWidth(figure())
222
- if (resetWidth > 0 && fixed + barWidth + 1 + resetWidth <= columns())
223
- return { barCells: barWidth, showReset: true }
224
- const room = columns() - fixed
225
- return {
226
- barCells: room >= barWidth ? barWidth : room >= 3 ? room : 0,
227
- showReset: false,
228
- }
229
- }
230
- // Stable fits keep existing bar nodes alive through the first measurement.
231
- const barCells = createMemo(() => fit().barCells)
232
- const showReset = createMemo(() => fit().showReset)
242
+ // Size notifications can recompute an unchanged fit after text has been flushed
243
+ // for the frame. Keep equal segments, and update fixed slots in place when the
244
+ // bar changes, rather than replacing text nodes during layout.
245
+ const segments = createMemo(
246
+ () =>
247
+ barSegments(
248
+ used(),
249
+ { ...context.appearance, barWidth: props.barCells },
250
+ props.pace,
251
+ ),
252
+ undefined,
253
+ {
254
+ equals: (previous, next) =>
255
+ previous.length === next.length &&
256
+ previous.every(
257
+ (segment, index) =>
258
+ segment.text === next[index]?.text &&
259
+ segment.tone === next[index]?.tone,
260
+ ),
261
+ },
262
+ )
233
263
  const paceLine = () => {
234
264
  const text = props.pace?.text
235
265
  if (!text || columns() <= 0) return text
@@ -246,43 +276,69 @@ function QuotaRow(props: {
246
276
  flexDirection='row'
247
277
  justifyContent='space-between'
248
278
  >
249
- <box flexDirection='row' flexShrink={0}>
250
- <text fg={context.theme.textMuted} wrapMode='none'>
251
- {label()}
252
- </text>
253
- <For
254
- each={barSegments(
255
- used(),
256
- { ...context.appearance, barWidth: barCells() },
257
- props.pace,
258
- )}
259
- >
260
- {(segment) => (
261
- <text fg={context.theme[segment.tone]} wrapMode='none'>
262
- {segment.text}
279
+ <box
280
+ flexDirection='row'
281
+ flexShrink={props.part.resetSinceReading ? 1 : 0}
282
+ >
283
+ <Show when={props.labelWidth > 0}>
284
+ <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
285
+ {label()}
286
+ </text>
287
+ </Show>
288
+ <Show
289
+ when={!props.part.resetSinceReading}
290
+ fallback={
291
+ <text fg={context.theme.textMuted} wrapMode='none'>
292
+ reset since last check
263
293
  </text>
264
- )}
265
- </For>
266
- <text
267
- fg={context.theme[usageTone(used(), context.appearance)]}
268
- wrapMode='none'
294
+ }
269
295
  >
270
- {figure()}
271
- </text>
296
+ <Show when={props.barCells > 0}>
297
+ {/* Text nodes clear omitted theme colours; empty slots must not reserve a cell. */}
298
+ <Index each={segments()}>
299
+ {(segment) => (
300
+ <text
301
+ fg={context.theme[segment().tone]}
302
+ wrapMode='none'
303
+ width={segment().text ? undefined : 0}
304
+ >
305
+ {segment().text}
306
+ </text>
307
+ )}
308
+ </Index>
309
+ </Show>
310
+ <text
311
+ fg={context.theme[usageTone(used(), context.appearance)]}
312
+ wrapMode='none'
313
+ >
314
+ {figure()}
315
+ </text>
316
+ </Show>
272
317
  </box>
273
- <Show when={showReset()}>
274
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
275
- {reset()}
276
- </text>
318
+ <Show when={props.showReset && !props.part.resetSinceReading}>
319
+ <box
320
+ width={props.resetWidth}
321
+ flexShrink={0}
322
+ flexDirection='row'
323
+ justifyContent='flex-end'
324
+ >
325
+ <Show when={props.part.resetIn}>
326
+ <text fg={context.theme.textMuted} wrapMode='none'>
327
+ {props.part.resetIn}
328
+ </text>
329
+ </Show>
330
+ </box>
277
331
  </Show>
278
332
  </box>
279
333
  {/* A changed fitted line needs a fresh text node to draw at its new width. */}
280
- <Show when={paceLine()} keyed>
334
+ <Show when={!props.part.resetSinceReading && paceLine()} keyed>
281
335
  {(line: string) => (
282
336
  <box width='100%' flexDirection='row'>
283
- <text fg={context.theme.textMuted}>
284
- {''.padEnd(props.labelWidth)}
285
- </text>
337
+ <Show when={props.labelWidth > 0}>
338
+ <text fg={context.theme.textMuted}>
339
+ {''.padEnd(props.labelWidth)}
340
+ </text>
341
+ </Show>
286
342
  <text
287
343
  fg={context.theme[props.pace?.tone ?? 'textMuted']}
288
344
  wrapMode='none'
@@ -306,14 +362,15 @@ function CollapsedAccountRow(props: { account: AccountView }) {
306
362
  const text = () =>
307
363
  hasQuota()
308
364
  ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
309
- : null
365
+ : (props.account.emptyQuotaText?.collapsed ?? '\u2014')
366
+ // Reserve an ellipsis, a separator and the trailing indicator before keeping quota.
367
+ const showQuota = () => width() <= 0 || displayWidth(text()) + 4 <= width()
310
368
  const label = () => {
311
369
  if (width() <= 0) return props.account.label
312
- const value =
313
- text() === null
314
- ? displayWidth(props.account.emptyQuotaText?.collapsed ?? '\u2014')
315
- : displayWidth(text() ?? '') + 2
316
- return fitText(props.account.label, width() - value - 1)
370
+ return fitText(
371
+ props.account.label,
372
+ width() - (showQuota() ? displayWidth(text()) + 3 : 2),
373
+ )
317
374
  }
318
375
  const muted = () => props.account.collapsed?.muted ?? false
319
376
  const quotaTone = () =>
@@ -327,60 +384,117 @@ function CollapsedAccountRow(props: { account: AccountView }) {
327
384
  width='100%'
328
385
  flexDirection='row'
329
386
  justifyContent='space-between'
387
+ columnGap={label() ? 1 : 0}
330
388
  >
331
- <text
332
- fg={context.theme[muted() ? 'textMuted' : 'text']}
333
- wrapMode='none'
334
- flexShrink={1}
335
- >
336
- {label()}
337
- </text>
338
- <Show
339
- when={text() !== null}
340
- fallback={
341
- <text fg={context.theme.textMuted}>
342
- {props.account.emptyQuotaText?.collapsed ?? '\u2014'}
343
- </text>
344
- }
345
- >
346
- <box flexDirection='row' flexShrink={0}>
389
+ <Show when={label()}>
390
+ <text
391
+ fg={context.theme[muted() ? 'textMuted' : 'text']}
392
+ wrapMode='none'
393
+ flexShrink={1}
394
+ >
395
+ {label()}
396
+ </text>
397
+ </Show>
398
+ <box flexDirection='row' flexShrink={0}>
399
+ <Show when={showQuota()}>
347
400
  <Show
348
- when={!muted()}
401
+ when={hasQuota() && !muted()}
349
402
  fallback={<text fg={context.theme.textMuted}>{text()}</text>}
350
403
  >
351
404
  <text fg={context.theme[quotaTone()]}>
352
405
  <b>{text()}</b>
353
406
  </text>
354
407
  </Show>
355
- <text fg={context.theme[props.account.indicatorTone]}>
356
- {props.account.blocked ? ' \u2298' : ' \u25cf'}
357
- </text>
358
- </box>
359
- </Show>
408
+ </Show>
409
+ <text fg={context.theme[props.account.indicatorTone]}>
410
+ {showQuota() ? ' ' : ''}
411
+ {props.account.blocked ? '\u2298' : '\u25cf'}
412
+ </text>
413
+ </box>
360
414
  </box>
361
415
  )
362
416
  }
363
417
 
364
- function AccountBlock(props: {
365
- account: AccountView
366
- labelWidth: number
367
- marginTop: number
368
- }) {
418
+ function AccountBlock(props: { account: AccountView; marginTop: number }) {
369
419
  const context = frameContext()
420
+ const [columns, setColumns] = createSignal(0)
421
+ let block: { width: number } | undefined
422
+ const rows = () => props.account.groups.flatMap((group) => group.rows)
423
+ const labelWidth = () =>
424
+ Math.max(
425
+ 0,
426
+ ...rows().map(({ part }) =>
427
+ part.name ? Math.max(3, displayWidth(part.name) + 1) : 0,
428
+ ),
429
+ )
430
+ const resetWidth = () =>
431
+ Math.max(
432
+ 0,
433
+ ...rows().map(({ part }) =>
434
+ part.resetSinceReading ? 0 : displayWidth(part.resetIn ?? ''),
435
+ ),
436
+ )
437
+ const figureWidth = createMemo(() =>
438
+ Math.max(
439
+ 10,
440
+ ...rows()
441
+ .filter(({ part }) => !part.resetSinceReading)
442
+ .map(({ part }) =>
443
+ displayWidth(
444
+ ` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`,
445
+ ),
446
+ ),
447
+ ),
448
+ )
449
+ const fit = (rowLabelWidth: number) => {
450
+ const desired = context.appearance.barWidth
451
+ // Four cells still distinguish quarters of a window without sacrificing its reset.
452
+ const minimum = Math.min(4, desired)
453
+ if (columns() <= 0)
454
+ return { barCells: desired, showReset: resetWidth() > 0 }
455
+ const room = columns() - rowLabelWidth - figureWidth()
456
+ const withReset = room - resetWidth() - 1
457
+ const showReset = resetWidth() > 0 && withReset >= minimum
458
+ const available = showReset ? withReset : room
459
+ return {
460
+ barCells: available >= minimum ? Math.min(desired, available) : 0,
461
+ showReset,
462
+ }
463
+ }
464
+ const label = () => {
465
+ const full = `${props.account.label}${props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}`
466
+ return columns() <= 0
467
+ ? full
468
+ : fitText(full, columns() - displayWidth(props.account.status.text) - 1)
469
+ }
370
470
  const age = () =>
371
471
  quotaWindowParts(props.account.quota, { now: context.now }).age
372
472
  const hasRows = () =>
373
473
  props.account.groups.some((group) => group.rows.length > 0)
374
474
  return (
375
- <box width='100%' flexDirection='column' marginTop={props.marginTop}>
376
- <box width='100%' flexDirection='row' justifyContent='space-between'>
377
- <text fg={context.theme.text}>
378
- <b>
379
- {props.account.label}
380
- {props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}
381
- </b>
475
+ <box
476
+ ref={(element: { width: number }) => {
477
+ block = element
478
+ }}
479
+ onSizeChange={() => setColumns(block?.width ?? 0)}
480
+ width='100%'
481
+ flexDirection='column'
482
+ marginTop={props.marginTop}
483
+ >
484
+ <box
485
+ width='100%'
486
+ flexDirection='row'
487
+ justifyContent='space-between'
488
+ columnGap={1}
489
+ >
490
+ <text fg={context.theme.text} wrapMode='none' flexShrink={1}>
491
+ <b>{label()}</b>
382
492
  </text>
383
- <text fg={context.theme[props.account.status.tone]}>
493
+ <text
494
+ fg={context.theme[props.account.status.tone]}
495
+ wrapMode='none'
496
+ flexShrink={0}
497
+ >
384
498
  <b>{props.account.status.text}</b>
385
499
  </text>
386
500
  </box>
@@ -390,6 +504,7 @@ function AccountBlock(props: {
390
504
  fallback={
391
505
  <SidebarTextRow
392
506
  text={props.account.emptyQuotaText?.expanded ?? '\u2014'}
507
+ wrapMode='none'
393
508
  />
394
509
  }
395
510
  >
@@ -397,23 +512,36 @@ function AccountBlock(props: {
397
512
  {(group) => (
398
513
  <>
399
514
  <Show when={group.title}>
400
- <SidebarTextRow text={group.title ?? ''} tone='text' />
515
+ <SidebarTextRow
516
+ text={group.title ?? ''}
517
+ tone='text'
518
+ wrapMode='none'
519
+ />
401
520
  </Show>
402
521
  <For each={group.rows}>
403
- {(row) => (
404
- <QuotaRow
405
- part={row.part}
406
- pace={row.pace}
407
- labelWidth={props.labelWidth}
408
- />
409
- )}
522
+ {(row) => {
523
+ const rowLabelWidth = () => (row.part.name ? labelWidth() : 0)
524
+ const rowFit = createMemo(() => fit(rowLabelWidth()))
525
+ return (
526
+ <QuotaRow
527
+ part={row.part}
528
+ pace={row.pace}
529
+ labelWidth={rowLabelWidth()}
530
+ barCells={rowFit().barCells}
531
+ resetWidth={resetWidth()}
532
+ showReset={rowFit().showReset}
533
+ />
534
+ )
535
+ }}
410
536
  </For>
411
537
  </>
412
538
  )}
413
539
  </For>
414
540
  </Show>
415
541
  <Show when={age()}>
416
- {(text: () => string) => <SidebarTextRow text={text()} />}
542
+ {(text: () => string) => (
543
+ <SidebarTextRow text={text()} wrapMode='none' />
544
+ )}
417
545
  </Show>
418
546
  {context.afterQuota?.(props.account)}
419
547
  </box>
@@ -427,25 +555,26 @@ export function SidebarFrame(props: SidebarFrameProps) {
427
555
  !hasData()
428
556
  ? props.header.badge
429
557
  : `${props.collapsed ? '\u25b6' : '\u25bc'} ${props.header.badge}`
430
- const labelWidth = () =>
431
- Math.max(
432
- 3,
433
- ...props.accounts.flatMap((account) =>
434
- account.groups.flatMap((group) =>
435
- group.rows.map((row) => row.part.name.length + 1),
436
- ),
437
- ),
438
- )
558
+ // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
559
+ const context = mergeProps(props, {
560
+ get theme(): SidebarTheme {
561
+ const theme = props.theme
562
+ return {
563
+ ...theme,
564
+ textMuted: theme?.textMuted ?? theme?.text,
565
+ accent: theme?.accent ?? theme?.text,
566
+ success: theme?.success ?? theme?.text,
567
+ warning: theme?.warning ?? theme?.text,
568
+ error: theme?.error ?? theme?.text,
569
+ }
570
+ },
571
+ })
572
+ // Inverting an incomplete badge palette can put light text on a light background.
573
+ const invertBadge = () =>
574
+ props.theme?.accent !== undefined && props.theme?.background !== undefined
439
575
  return (
440
- <FrameContext.Provider value={props}>
441
- <box
442
- width='100%'
443
- flexDirection='column'
444
- paddingTop={1}
445
- paddingBottom={1}
446
- paddingLeft={1}
447
- paddingRight={1}
448
- >
576
+ <FrameContext.Provider value={context}>
577
+ <box width='100%' flexDirection='column'>
449
578
  {/* Blocked accounts retain their own indicators; the header always keeps its version. */}
450
579
  {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI terminal widgets do not have DOM roles */}
451
580
  <box
@@ -460,20 +589,25 @@ export function SidebarFrame(props: SidebarFrameProps) {
460
589
  <box
461
590
  paddingLeft={1}
462
591
  paddingRight={1}
463
- backgroundColor={props.theme.accent}
592
+ backgroundColor={invertBadge() ? props.theme?.accent : undefined}
464
593
  >
465
- <text fg={props.theme.background}>
594
+ <text
595
+ fg={
596
+ invertBadge() ? props.theme?.background : context.theme.accent
597
+ }
598
+ >
466
599
  <b>{headerLabel()}</b>
467
600
  </text>
468
601
  </box>
469
602
  <Show when={props.header.version}>
470
- <text fg={props.theme.textMuted}>{props.header.version}</text>
603
+ <text fg={context.theme.textMuted}>{props.header.version}</text>
471
604
  </Show>
472
605
  </box>
473
606
  <Show when={props.collapsed && hasData()}>
474
607
  <For each={props.accounts}>
475
608
  {(account) => <CollapsedAccountRow account={account} />}
476
609
  </For>
610
+ {props.collapsedSections?.()}
477
611
  </Show>
478
612
  <Show when={!props.collapsed || !hasData()}>
479
613
  <Show when={props.showQuota && hasData()}>
@@ -482,7 +616,6 @@ export function SidebarFrame(props: SidebarFrameProps) {
482
616
  {(account, index) => (
483
617
  <AccountBlock
484
618
  account={account}
485
- labelWidth={labelWidth()}
486
619
  marginTop={index() === 0 ? 0 : 1}
487
620
  />
488
621
  )}