@cortexkit/common-auth 0.31.0 → 0.32.0

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, 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)
@@ -99,27 +101,10 @@ function QuotaRow(props) {
99
101
  const context = frameContext();
100
102
  const [columns, setColumns] = createSignal(0);
101
103
  let row;
102
- const label = () => props.part.name.padEnd(props.labelWidth);
104
+ const label = () => props.part.name +
105
+ ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)));
103
106
  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
107
  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);
123
108
  const paceLine = () => {
124
109
  const text = props.pace?.text;
125
110
  if (!text || columns() <= 0)
@@ -130,31 +115,43 @@ function QuotaRow(props) {
130
115
  <box ref={(element) => {
131
116
  row = element;
132
117
  }} 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>
118
+ <box flexDirection='row' flexShrink={props.part.resetSinceReading ? 1 : 0}>
119
+ <Show when={props.labelWidth > 0}>
120
+ <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
121
+ {label()}
122
+ </text>
123
+ </Show>
124
+ <Show when={!props.part.resetSinceReading} fallback={<text fg={context.theme.textMuted} wrapMode='none'>
125
+ reset since last check
126
+ </text>}>
127
+ <For each={barSegments(used(), { ...context.appearance, barWidth: props.barCells }, props.pace)}>
128
+ {(segment) => (<text fg={context.theme[segment.tone]} wrapMode='none'>
129
+ {segment.text}
130
+ </text>)}
131
+ </For>
132
+ <text fg={context.theme[usageTone(used(), context.appearance)]} wrapMode='none'>
133
+ {figure()}
134
+ </text>
135
+ </Show>
145
136
  </box>
146
- <Show when={showReset()}>
147
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
148
- {reset()}
149
- </text>
137
+ <Show when={props.showReset && !props.part.resetSinceReading}>
138
+ <box width={props.resetWidth} flexShrink={0} flexDirection='row' justifyContent='flex-end'>
139
+ <Show when={props.part.resetIn}>
140
+ <text fg={context.theme.textMuted} wrapMode='none'>
141
+ {props.part.resetIn}
142
+ </text>
143
+ </Show>
144
+ </box>
150
145
  </Show>
151
146
  </box>
152
147
  {/* A changed fitted line needs a fresh text node to draw at its new width. */}
153
- <Show when={paceLine()} keyed>
148
+ <Show when={!props.part.resetSinceReading && paceLine()} keyed>
154
149
  {(line) => (<box width='100%' flexDirection='row'>
155
- <text fg={context.theme.textMuted}>
156
- {''.padEnd(props.labelWidth)}
157
- </text>
150
+ <Show when={props.labelWidth > 0}>
151
+ <text fg={context.theme.textMuted}>
152
+ {''.padEnd(props.labelWidth)}
153
+ </text>
154
+ </Show>
158
155
  <text fg={context.theme[props.pace?.tone ?? 'textMuted']} wrapMode='none'>
159
156
  {line}
160
157
  </text>
@@ -170,70 +167,102 @@ function CollapsedAccountRow(props) {
170
167
  0;
171
168
  const text = () => hasQuota()
172
169
  ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
173
- : null;
170
+ : (props.account.emptyQuotaText?.collapsed ?? '\u2014');
171
+ // Reserve an ellipsis, a separator and the trailing indicator before keeping quota.
172
+ const showQuota = () => width() <= 0 || displayWidth(text()) + 4 <= width();
174
173
  const label = () => {
175
174
  if (width() <= 0)
176
175
  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);
176
+ return fitText(props.account.label, width() - (showQuota() ? displayWidth(text()) + 3 : 2));
181
177
  };
182
178
  const muted = () => props.account.collapsed?.muted ?? false;
183
179
  const quotaTone = () => muted() ? 'textMuted' : (props.account.collapsed?.quotaTone ?? 'success');
184
180
  return (<box ref={(element) => {
185
181
  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>}>
182
+ }} onSizeChange={() => setWidth(row?.width ?? 0)} width='100%' flexDirection='row' justifyContent='space-between' columnGap={label() ? 1 : 0}>
183
+ <Show when={label()}>
184
+ <text fg={context.theme[muted() ? 'textMuted' : 'text']} wrapMode='none' flexShrink={1}>
185
+ {label()}
186
+ </text>
187
+ </Show>
188
+ <box flexDirection='row' flexShrink={0}>
189
+ <Show when={showQuota()}>
190
+ <Show when={hasQuota() && !muted()} fallback={<text fg={context.theme.textMuted}>{text()}</text>}>
195
191
  <text fg={context.theme[quotaTone()]}>
196
192
  <b>{text()}</b>
197
193
  </text>
198
194
  </Show>
199
- <text fg={context.theme[props.account.indicatorTone]}>
200
- {props.account.blocked ? ' \u2298' : ' \u25cf'}
201
- </text>
202
- </box>
203
- </Show>
195
+ </Show>
196
+ <text fg={context.theme[props.account.indicatorTone]}>
197
+ {showQuota() ? ' ' : ''}
198
+ {props.account.blocked ? '\u2298' : '\u25cf'}
199
+ </text>
200
+ </box>
204
201
  </box>);
205
202
  }
206
203
  function AccountBlock(props) {
207
204
  const context = frameContext();
205
+ const [columns, setColumns] = createSignal(0);
206
+ let block;
207
+ const rows = () => props.account.groups.flatMap((group) => group.rows);
208
+ const labelWidth = () => Math.max(0, ...rows().map(({ part }) => part.name ? Math.max(3, displayWidth(part.name) + 1) : 0));
209
+ const resetWidth = () => Math.max(0, ...rows().map(({ part }) => part.resetSinceReading ? 0 : displayWidth(part.resetIn ?? '')));
210
+ const figureWidth = createMemo(() => Math.max(10, ...rows()
211
+ .filter(({ part }) => !part.resetSinceReading)
212
+ .map(({ part }) => displayWidth(` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`))));
213
+ const fit = (rowLabelWidth) => {
214
+ const desired = context.appearance.barWidth;
215
+ // Four cells still distinguish quarters of a window without sacrificing its reset.
216
+ const minimum = Math.min(4, desired);
217
+ if (columns() <= 0)
218
+ return { barCells: desired, showReset: resetWidth() > 0 };
219
+ const room = columns() - rowLabelWidth - figureWidth();
220
+ const withReset = room - resetWidth() - 1;
221
+ const showReset = resetWidth() > 0 && withReset >= minimum;
222
+ const available = showReset ? withReset : room;
223
+ return {
224
+ barCells: available >= minimum ? Math.min(desired, available) : 0,
225
+ showReset,
226
+ };
227
+ };
228
+ const label = () => {
229
+ const full = `${props.account.label}${props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}`;
230
+ return columns() <= 0
231
+ ? full
232
+ : fitText(full, columns() - displayWidth(props.account.status.text) - 1);
233
+ };
208
234
  const age = () => quotaWindowParts(props.account.quota, { now: context.now }).age;
209
235
  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>
236
+ return (<box ref={(element) => {
237
+ block = element;
238
+ }} onSizeChange={() => setColumns(block?.width ?? 0)} width='100%' flexDirection='column' marginTop={props.marginTop}>
239
+ <box width='100%' flexDirection='row' justifyContent='space-between' columnGap={1}>
240
+ <text fg={context.theme.text} wrapMode='none' flexShrink={1}>
241
+ <b>{label()}</b>
217
242
  </text>
218
- <text fg={context.theme[props.account.status.tone]}>
243
+ <text fg={context.theme[props.account.status.tone]} wrapMode='none' flexShrink={0}>
219
244
  <b>{props.account.status.text}</b>
220
245
  </text>
221
246
  </box>
222
247
  {context.beforeQuota?.(props.account)}
223
- <Show when={hasRows()} fallback={<SidebarTextRow text={props.account.emptyQuotaText?.expanded ?? '\u2014'}/>}>
248
+ <Show when={hasRows()} fallback={<SidebarTextRow text={props.account.emptyQuotaText?.expanded ?? '\u2014'} wrapMode='none'/>}>
224
249
  <For each={props.account.groups}>
225
250
  {(group) => (<>
226
251
  <Show when={group.title}>
227
- <SidebarTextRow text={group.title ?? ''} tone='text'/>
252
+ <SidebarTextRow text={group.title ?? ''} tone='text' wrapMode='none'/>
228
253
  </Show>
229
254
  <For each={group.rows}>
230
- {(row) => (<QuotaRow part={row.part} pace={row.pace} labelWidth={props.labelWidth}/>)}
255
+ {(row) => {
256
+ const rowLabelWidth = () => (row.part.name ? labelWidth() : 0);
257
+ const rowFit = createMemo(() => fit(rowLabelWidth()));
258
+ return (<QuotaRow part={row.part} pace={row.pace} labelWidth={rowLabelWidth()} barCells={rowFit().barCells} resetWidth={resetWidth()} showReset={rowFit().showReset}/>);
259
+ }}
231
260
  </For>
232
261
  </>)}
233
262
  </For>
234
263
  </Show>
235
264
  <Show when={age()}>
236
- {(text) => <SidebarTextRow text={text()}/>}
265
+ {(text) => (<SidebarTextRow text={text()} wrapMode='none'/>)}
237
266
  </Show>
238
267
  {context.afterQuota?.(props.account)}
239
268
  </box>);
@@ -244,34 +273,50 @@ export function SidebarFrame(props) {
244
273
  const headerLabel = () => !hasData()
245
274
  ? props.header.badge
246
275
  : `${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}>
276
+ // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
277
+ const context = mergeProps(props, {
278
+ get theme() {
279
+ const theme = props.theme;
280
+ return {
281
+ ...theme,
282
+ textMuted: theme?.textMuted ?? theme?.text,
283
+ accent: theme?.accent ?? theme?.text,
284
+ success: theme?.success ?? theme?.text,
285
+ warning: theme?.warning ?? theme?.text,
286
+ error: theme?.error ?? theme?.text,
287
+ };
288
+ },
289
+ });
290
+ // Inverting an incomplete badge palette can put light text on a light background.
291
+ const invertBadge = () => props.theme?.accent !== undefined && props.theme?.background !== undefined;
292
+ return (<FrameContext.Provider value={context}>
293
+ <box width='100%' flexDirection='column'>
250
294
  {/* Blocked accounts retain their own indicators; the header always keeps its version. */}
251
295
  {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI terminal widgets do not have DOM roles */}
252
296
  <box width='100%' flexDirection='row' justifyContent='space-between' alignItems='center' onMouseDown={() => {
253
297
  if (hasData())
254
298
  props.onToggle();
255
299
  }}>
256
- <box paddingLeft={1} paddingRight={1} backgroundColor={props.theme.accent}>
257
- <text fg={props.theme.background}>
300
+ <box paddingLeft={1} paddingRight={1} backgroundColor={invertBadge() ? props.theme?.accent : undefined}>
301
+ <text fg={invertBadge() ? props.theme?.background : context.theme.accent}>
258
302
  <b>{headerLabel()}</b>
259
303
  </text>
260
304
  </box>
261
305
  <Show when={props.header.version}>
262
- <text fg={props.theme.textMuted}>{props.header.version}</text>
306
+ <text fg={context.theme.textMuted}>{props.header.version}</text>
263
307
  </Show>
264
308
  </box>
265
309
  <Show when={props.collapsed && hasData()}>
266
310
  <For each={props.accounts}>
267
311
  {(account) => <CollapsedAccountRow account={account}/>}
268
312
  </For>
313
+ {props.collapsedSections?.()}
269
314
  </Show>
270
315
  <Show when={!props.collapsed || !hasData()}>
271
316
  <Show when={props.showQuota && hasData()}>
272
317
  <SidebarSection title='Quota'>
273
318
  <For each={props.accounts}>
274
- {(account, index) => (<AccountBlock account={account} labelWidth={labelWidth()} marginTop={index() === 0 ? 0 : 1}/>)}
319
+ {(account, index) => (<AccountBlock account={account} marginTop={index() === 0 ? 0 : 1}/>)}
275
320
  </For>
276
321
  </SidebarSection>
277
322
  </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.0",
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,7 @@ import {
5
5
  createMemo,
6
6
  createSignal,
7
7
  For,
8
+ mergeProps,
8
9
  Show,
9
10
  useContext,
10
11
  } from 'solid-js'
@@ -21,7 +22,9 @@ export type Tone =
21
22
  | 'error'
22
23
 
23
24
  export type SidebarTheme = Readonly<
24
- Record<Tone | 'background' | 'borderActive', RGBA>
25
+ Partial<
26
+ Record<Tone | 'background' | 'borderActive', RGBA | string | undefined>
27
+ >
25
28
  >
26
29
 
27
30
  export interface SidebarAppearance {
@@ -61,7 +64,7 @@ export interface AccountView {
61
64
  export interface SidebarFrameProps {
62
65
  header: { badge: string; version?: string }
63
66
  accounts: readonly AccountView[]
64
- theme: SidebarTheme
67
+ theme?: SidebarTheme
65
68
  appearance: SidebarAppearance
66
69
  showQuota: boolean
67
70
  now: number
@@ -70,11 +73,16 @@ export interface SidebarFrameProps {
70
73
  beforeQuota?: (account: AccountView) => JSX.Element
71
74
  afterQuota?: (account: AccountView) => JSX.Element
72
75
  sections?: () => JSX.Element
76
+ collapsedSections?: () => JSX.Element
77
+ }
78
+
79
+ type FrameContextProps = Omit<SidebarFrameProps, 'theme'> & {
80
+ theme: SidebarTheme
73
81
  }
74
82
 
75
- const FrameContext = createContext<SidebarFrameProps>()
83
+ const FrameContext = createContext<FrameContextProps>()
76
84
 
77
- function frameContext(): SidebarFrameProps {
85
+ function frameContext(): FrameContextProps {
78
86
  const context = useContext(FrameContext)
79
87
  if (!context)
80
88
  throw new Error('Sidebar primitives must be inside SidebarFrame')
@@ -158,9 +166,20 @@ export function SidebarStatRow(props: {
158
166
  )
159
167
  }
160
168
 
161
- export function SidebarTextRow(props: { text: string; tone?: Tone }) {
169
+ export function SidebarTextRow(props: {
170
+ text: string
171
+ tone?: Tone
172
+ wrapMode?: JSX.IntrinsicElements['text']['wrapMode']
173
+ }) {
162
174
  const context = frameContext()
163
- return <text fg={context.theme[props.tone ?? 'textMuted']}>{props.text}</text>
175
+ return (
176
+ <text
177
+ fg={context.theme[props.tone ?? 'textMuted']}
178
+ wrapMode={props.wrapMode}
179
+ >
180
+ {props.text}
181
+ </text>
182
+ )
164
183
  }
165
184
 
166
185
  function usageTone(used: number, appearance: SidebarAppearance): Tone {
@@ -204,32 +223,19 @@ function QuotaRow(props: {
204
223
  part: QuotaWindowPart
205
224
  pace?: PaceView
206
225
  labelWidth: number
226
+ barCells: number
227
+ resetWidth: number
228
+ showReset: boolean
207
229
  }) {
208
230
  const context = frameContext()
209
231
  const [columns, setColumns] = createSignal(0)
210
232
  let row: { width: number } | undefined
211
- const label = () => props.part.name.padEnd(props.labelWidth)
233
+ const label = () =>
234
+ props.part.name +
235
+ ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)))
212
236
  const figure = () =>
213
237
  ` ${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
238
  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)
233
239
  const paceLine = () => {
234
240
  const text = props.pace?.text
235
241
  if (!text || columns() <= 0) return text
@@ -246,43 +252,68 @@ function QuotaRow(props: {
246
252
  flexDirection='row'
247
253
  justifyContent='space-between'
248
254
  >
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}
255
+ <box
256
+ flexDirection='row'
257
+ flexShrink={props.part.resetSinceReading ? 1 : 0}
258
+ >
259
+ <Show when={props.labelWidth > 0}>
260
+ <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
261
+ {label()}
262
+ </text>
263
+ </Show>
264
+ <Show
265
+ when={!props.part.resetSinceReading}
266
+ fallback={
267
+ <text fg={context.theme.textMuted} wrapMode='none'>
268
+ reset since last check
263
269
  </text>
264
- )}
265
- </For>
266
- <text
267
- fg={context.theme[usageTone(used(), context.appearance)]}
268
- wrapMode='none'
270
+ }
269
271
  >
270
- {figure()}
271
- </text>
272
+ <For
273
+ each={barSegments(
274
+ used(),
275
+ { ...context.appearance, barWidth: props.barCells },
276
+ props.pace,
277
+ )}
278
+ >
279
+ {(segment) => (
280
+ <text fg={context.theme[segment.tone]} wrapMode='none'>
281
+ {segment.text}
282
+ </text>
283
+ )}
284
+ </For>
285
+ <text
286
+ fg={context.theme[usageTone(used(), context.appearance)]}
287
+ wrapMode='none'
288
+ >
289
+ {figure()}
290
+ </text>
291
+ </Show>
272
292
  </box>
273
- <Show when={showReset()}>
274
- <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
275
- {reset()}
276
- </text>
293
+ <Show when={props.showReset && !props.part.resetSinceReading}>
294
+ <box
295
+ width={props.resetWidth}
296
+ flexShrink={0}
297
+ flexDirection='row'
298
+ justifyContent='flex-end'
299
+ >
300
+ <Show when={props.part.resetIn}>
301
+ <text fg={context.theme.textMuted} wrapMode='none'>
302
+ {props.part.resetIn}
303
+ </text>
304
+ </Show>
305
+ </box>
277
306
  </Show>
278
307
  </box>
279
308
  {/* A changed fitted line needs a fresh text node to draw at its new width. */}
280
- <Show when={paceLine()} keyed>
309
+ <Show when={!props.part.resetSinceReading && paceLine()} keyed>
281
310
  {(line: string) => (
282
311
  <box width='100%' flexDirection='row'>
283
- <text fg={context.theme.textMuted}>
284
- {''.padEnd(props.labelWidth)}
285
- </text>
312
+ <Show when={props.labelWidth > 0}>
313
+ <text fg={context.theme.textMuted}>
314
+ {''.padEnd(props.labelWidth)}
315
+ </text>
316
+ </Show>
286
317
  <text
287
318
  fg={context.theme[props.pace?.tone ?? 'textMuted']}
288
319
  wrapMode='none'
@@ -306,14 +337,15 @@ function CollapsedAccountRow(props: { account: AccountView }) {
306
337
  const text = () =>
307
338
  hasQuota()
308
339
  ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
309
- : null
340
+ : (props.account.emptyQuotaText?.collapsed ?? '\u2014')
341
+ // Reserve an ellipsis, a separator and the trailing indicator before keeping quota.
342
+ const showQuota = () => width() <= 0 || displayWidth(text()) + 4 <= width()
310
343
  const label = () => {
311
344
  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)
345
+ return fitText(
346
+ props.account.label,
347
+ width() - (showQuota() ? displayWidth(text()) + 3 : 2),
348
+ )
317
349
  }
318
350
  const muted = () => props.account.collapsed?.muted ?? false
319
351
  const quotaTone = () =>
@@ -327,60 +359,117 @@ function CollapsedAccountRow(props: { account: AccountView }) {
327
359
  width='100%'
328
360
  flexDirection='row'
329
361
  justifyContent='space-between'
362
+ columnGap={label() ? 1 : 0}
330
363
  >
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}>
364
+ <Show when={label()}>
365
+ <text
366
+ fg={context.theme[muted() ? 'textMuted' : 'text']}
367
+ wrapMode='none'
368
+ flexShrink={1}
369
+ >
370
+ {label()}
371
+ </text>
372
+ </Show>
373
+ <box flexDirection='row' flexShrink={0}>
374
+ <Show when={showQuota()}>
347
375
  <Show
348
- when={!muted()}
376
+ when={hasQuota() && !muted()}
349
377
  fallback={<text fg={context.theme.textMuted}>{text()}</text>}
350
378
  >
351
379
  <text fg={context.theme[quotaTone()]}>
352
380
  <b>{text()}</b>
353
381
  </text>
354
382
  </Show>
355
- <text fg={context.theme[props.account.indicatorTone]}>
356
- {props.account.blocked ? ' \u2298' : ' \u25cf'}
357
- </text>
358
- </box>
359
- </Show>
383
+ </Show>
384
+ <text fg={context.theme[props.account.indicatorTone]}>
385
+ {showQuota() ? ' ' : ''}
386
+ {props.account.blocked ? '\u2298' : '\u25cf'}
387
+ </text>
388
+ </box>
360
389
  </box>
361
390
  )
362
391
  }
363
392
 
364
- function AccountBlock(props: {
365
- account: AccountView
366
- labelWidth: number
367
- marginTop: number
368
- }) {
393
+ function AccountBlock(props: { account: AccountView; marginTop: number }) {
369
394
  const context = frameContext()
395
+ const [columns, setColumns] = createSignal(0)
396
+ let block: { width: number } | undefined
397
+ const rows = () => props.account.groups.flatMap((group) => group.rows)
398
+ const labelWidth = () =>
399
+ Math.max(
400
+ 0,
401
+ ...rows().map(({ part }) =>
402
+ part.name ? Math.max(3, displayWidth(part.name) + 1) : 0,
403
+ ),
404
+ )
405
+ const resetWidth = () =>
406
+ Math.max(
407
+ 0,
408
+ ...rows().map(({ part }) =>
409
+ part.resetSinceReading ? 0 : displayWidth(part.resetIn ?? ''),
410
+ ),
411
+ )
412
+ const figureWidth = createMemo(() =>
413
+ Math.max(
414
+ 10,
415
+ ...rows()
416
+ .filter(({ part }) => !part.resetSinceReading)
417
+ .map(({ part }) =>
418
+ displayWidth(
419
+ ` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`,
420
+ ),
421
+ ),
422
+ ),
423
+ )
424
+ const fit = (rowLabelWidth: number) => {
425
+ const desired = context.appearance.barWidth
426
+ // Four cells still distinguish quarters of a window without sacrificing its reset.
427
+ const minimum = Math.min(4, desired)
428
+ if (columns() <= 0)
429
+ return { barCells: desired, showReset: resetWidth() > 0 }
430
+ const room = columns() - rowLabelWidth - figureWidth()
431
+ const withReset = room - resetWidth() - 1
432
+ const showReset = resetWidth() > 0 && withReset >= minimum
433
+ const available = showReset ? withReset : room
434
+ return {
435
+ barCells: available >= minimum ? Math.min(desired, available) : 0,
436
+ showReset,
437
+ }
438
+ }
439
+ const label = () => {
440
+ const full = `${props.account.label}${props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}`
441
+ return columns() <= 0
442
+ ? full
443
+ : fitText(full, columns() - displayWidth(props.account.status.text) - 1)
444
+ }
370
445
  const age = () =>
371
446
  quotaWindowParts(props.account.quota, { now: context.now }).age
372
447
  const hasRows = () =>
373
448
  props.account.groups.some((group) => group.rows.length > 0)
374
449
  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>
450
+ <box
451
+ ref={(element: { width: number }) => {
452
+ block = element
453
+ }}
454
+ onSizeChange={() => setColumns(block?.width ?? 0)}
455
+ width='100%'
456
+ flexDirection='column'
457
+ marginTop={props.marginTop}
458
+ >
459
+ <box
460
+ width='100%'
461
+ flexDirection='row'
462
+ justifyContent='space-between'
463
+ columnGap={1}
464
+ >
465
+ <text fg={context.theme.text} wrapMode='none' flexShrink={1}>
466
+ <b>{label()}</b>
382
467
  </text>
383
- <text fg={context.theme[props.account.status.tone]}>
468
+ <text
469
+ fg={context.theme[props.account.status.tone]}
470
+ wrapMode='none'
471
+ flexShrink={0}
472
+ >
384
473
  <b>{props.account.status.text}</b>
385
474
  </text>
386
475
  </box>
@@ -390,6 +479,7 @@ function AccountBlock(props: {
390
479
  fallback={
391
480
  <SidebarTextRow
392
481
  text={props.account.emptyQuotaText?.expanded ?? '\u2014'}
482
+ wrapMode='none'
393
483
  />
394
484
  }
395
485
  >
@@ -397,23 +487,36 @@ function AccountBlock(props: {
397
487
  {(group) => (
398
488
  <>
399
489
  <Show when={group.title}>
400
- <SidebarTextRow text={group.title ?? ''} tone='text' />
490
+ <SidebarTextRow
491
+ text={group.title ?? ''}
492
+ tone='text'
493
+ wrapMode='none'
494
+ />
401
495
  </Show>
402
496
  <For each={group.rows}>
403
- {(row) => (
404
- <QuotaRow
405
- part={row.part}
406
- pace={row.pace}
407
- labelWidth={props.labelWidth}
408
- />
409
- )}
497
+ {(row) => {
498
+ const rowLabelWidth = () => (row.part.name ? labelWidth() : 0)
499
+ const rowFit = createMemo(() => fit(rowLabelWidth()))
500
+ return (
501
+ <QuotaRow
502
+ part={row.part}
503
+ pace={row.pace}
504
+ labelWidth={rowLabelWidth()}
505
+ barCells={rowFit().barCells}
506
+ resetWidth={resetWidth()}
507
+ showReset={rowFit().showReset}
508
+ />
509
+ )
510
+ }}
410
511
  </For>
411
512
  </>
412
513
  )}
413
514
  </For>
414
515
  </Show>
415
516
  <Show when={age()}>
416
- {(text: () => string) => <SidebarTextRow text={text()} />}
517
+ {(text: () => string) => (
518
+ <SidebarTextRow text={text()} wrapMode='none' />
519
+ )}
417
520
  </Show>
418
521
  {context.afterQuota?.(props.account)}
419
522
  </box>
@@ -427,25 +530,26 @@ export function SidebarFrame(props: SidebarFrameProps) {
427
530
  !hasData()
428
531
  ? props.header.badge
429
532
  : `${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
- )
533
+ // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
534
+ const context = mergeProps(props, {
535
+ get theme(): SidebarTheme {
536
+ const theme = props.theme
537
+ return {
538
+ ...theme,
539
+ textMuted: theme?.textMuted ?? theme?.text,
540
+ accent: theme?.accent ?? theme?.text,
541
+ success: theme?.success ?? theme?.text,
542
+ warning: theme?.warning ?? theme?.text,
543
+ error: theme?.error ?? theme?.text,
544
+ }
545
+ },
546
+ })
547
+ // Inverting an incomplete badge palette can put light text on a light background.
548
+ const invertBadge = () =>
549
+ props.theme?.accent !== undefined && props.theme?.background !== undefined
439
550
  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
- >
551
+ <FrameContext.Provider value={context}>
552
+ <box width='100%' flexDirection='column'>
449
553
  {/* Blocked accounts retain their own indicators; the header always keeps its version. */}
450
554
  {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI terminal widgets do not have DOM roles */}
451
555
  <box
@@ -460,20 +564,25 @@ export function SidebarFrame(props: SidebarFrameProps) {
460
564
  <box
461
565
  paddingLeft={1}
462
566
  paddingRight={1}
463
- backgroundColor={props.theme.accent}
567
+ backgroundColor={invertBadge() ? props.theme?.accent : undefined}
464
568
  >
465
- <text fg={props.theme.background}>
569
+ <text
570
+ fg={
571
+ invertBadge() ? props.theme?.background : context.theme.accent
572
+ }
573
+ >
466
574
  <b>{headerLabel()}</b>
467
575
  </text>
468
576
  </box>
469
577
  <Show when={props.header.version}>
470
- <text fg={props.theme.textMuted}>{props.header.version}</text>
578
+ <text fg={context.theme.textMuted}>{props.header.version}</text>
471
579
  </Show>
472
580
  </box>
473
581
  <Show when={props.collapsed && hasData()}>
474
582
  <For each={props.accounts}>
475
583
  {(account) => <CollapsedAccountRow account={account} />}
476
584
  </For>
585
+ {props.collapsedSections?.()}
477
586
  </Show>
478
587
  <Show when={!props.collapsed || !hasData()}>
479
588
  <Show when={props.showQuota && hasData()}>
@@ -482,7 +591,6 @@ export function SidebarFrame(props: SidebarFrameProps) {
482
591
  {(account, index) => (
483
592
  <AccountBlock
484
593
  account={account}
485
- labelWidth={labelWidth()}
486
594
  marginTop={index() === 0 ? 0 : 1}
487
595
  />
488
596
  )}