@cortexkit/common-auth 0.32.0 → 0.33.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.
@@ -244,8 +244,8 @@ export async function acquireRefreshFileLockWithClock(options) {
244
244
  }
245
245
  catch (readError) {
246
246
  // The holder can release after exclusive creation reports a collision.
247
- // Only absence permits another acquisition attempt; security and sharing
248
- // refusals must still escape rather than being treated as contention.
247
+ // Only absence permits acquisition to continue here. Sharing failures
248
+ // escape to withLock's deadline-bounded retry, never to stale eviction.
249
249
  if (readError.code !== 'ENOENT')
250
250
  throw readError;
251
251
  }
@@ -1,3 +1,5 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { PrivateFileError, windowsPrivateFiles } from './private-files.js';
1
3
  import { acquireRefreshFileLock } from './refresh-file-lock.js';
2
4
  export function lockPathFor(target, name) {
3
5
  return `${target}.${name}.lock`;
@@ -18,20 +20,42 @@ export class LockOwnershipError extends Error {
18
20
  this.details = details;
19
21
  }
20
22
  }
23
+ function isChangingLockRead(error, target, name) {
24
+ if (!windowsPrivateFiles ||
25
+ !(error instanceof PrivateFileError) ||
26
+ error.reason !== 'io-error' ||
27
+ (error.win32Code !== 32 && error.win32Code !== 303) ||
28
+ (error.stage !== 'read' && error.stage !== 'verify'))
29
+ return false;
30
+ const path = resolve(lockPathFor(target, name));
31
+ return error.path === path || error.path === join(path, 'owner.json');
32
+ }
21
33
  export async function withLock(target, options, fn) {
22
34
  const started = performance.now();
23
35
  for (;;) {
24
36
  options.signal?.throwIfAborted();
25
- const lock = await acquireRefreshFileLock({
26
- path: target,
27
- name: options.name,
28
- ttlMs: options.ttlMs,
29
- renew: options.renew ?? false,
30
- ...(options.onStep ? { onStep: options.onStep } : {}),
31
- ...(options.onRenewalTimer
32
- ? { onRenewalTimer: options.onRenewalTimer }
33
- : {}),
34
- });
37
+ let lock;
38
+ let changingReadError;
39
+ try {
40
+ lock = await acquireRefreshFileLock({
41
+ path: target,
42
+ name: options.name,
43
+ ttlMs: options.ttlMs,
44
+ renew: options.renew ?? false,
45
+ ...(options.onStep ? { onStep: options.onStep } : {}),
46
+ ...(options.onRenewalTimer
47
+ ? { onRenewalTimer: options.onRenewalTimer }
48
+ : {}),
49
+ });
50
+ }
51
+ catch (error) {
52
+ if (!isChangingLockRead(error, target, options.name))
53
+ throw error;
54
+ // Sharing violations (32) and delete-pending opens (303) do not reveal
55
+ // ownership or expiry. Retry exclusive creation, never infer a stale lock.
56
+ lock = null;
57
+ changingReadError = error;
58
+ }
35
59
  if (lock) {
36
60
  try {
37
61
  options.signal?.throwIfAborted();
@@ -43,6 +67,9 @@ export async function withLock(target, options, fn) {
43
67
  }
44
68
  const remaining = options.timeoutMs - (performance.now() - started);
45
69
  if (remaining <= 0) {
70
+ // Keep persistent native IO failures distinguishable from a live holder.
71
+ if (changingReadError)
72
+ throw changingReadError;
46
73
  throw new LockContentionError({
47
74
  target,
48
75
  name: options.name,
@@ -30,6 +30,8 @@ export interface QuotaTextOptions {
30
30
  }
31
31
  export interface QuotaWindowPart {
32
32
  kind: 'window' | 'budget';
33
+ /** Unknown windows have no dated percentage; budgets retain their own wording. */
34
+ reading: 'known' | 'unknown';
33
35
  /** The display name of a quota window, or `credits` for the budget. */
34
36
  name: string;
35
37
  /**
@@ -45,7 +47,8 @@ export interface QuotaWindowPart {
45
47
  remainingPercent?: number;
46
48
  /** A bare relative reset span such as `4d`, only when the reset is future. */
47
49
  resetIn?: string;
48
- checkedAt: number;
50
+ /** The reading time, omitted for a window with no reading. */
51
+ checkedAt?: number;
49
52
  /** Whether the reset followed this reading and has arrived by `now`. */
50
53
  resetSinceReading: boolean;
51
54
  }
@@ -64,9 +67,11 @@ export interface QuotaParts {
64
67
  */
65
68
  export declare function quotaWindowName(limit: Pick<ProjectedLimit, 'scope' | 'label' | 'windowMinutes'>): string;
66
69
  /**
67
- * Structured quota wording for layouts that need one row per window. The
68
- * windows use the same filtering and order as `quotaTextParts`; future resets
69
- * and the optional age keep the shared formatter's wording.
70
+ * Structured quota wording for layouts that need one row per window.
71
+ * Windows without a dated percentage remain as explicit unknown parts. Limits
72
+ * marked absent (not reported) or retired (no longer tracked) remain omitted.
73
+ * Reported windows, future resets and the optional age keep the shared
74
+ * formatter's wording and order.
70
75
  */
71
76
  export declare function quotaWindowParts(quota: ProjectedQuota | undefined, options: QuotaTextOptions): QuotaParts;
72
77
  /**
@@ -5,10 +5,10 @@
5
5
  //
6
6
  // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
7
  // that binds only one model family, by the label the plugin stored it under.
8
- // Every figure is "% left". A window the provider did not report (an absence
9
- // record or a retirement tombstone) is left out rather than written as "not
10
- // reported". A reset is a short time from now (`resets 2h`). A reading older
11
- // than fifteen minutes says how old it is (`checked 3h ago`).
8
+ // Every reported window figure is "% left". A window the provider did not
9
+ // report (an absence record or a retirement tombstone) is left out rather than
10
+ // written as "not reported". A reset is a short time from now (`resets 2h`).
11
+ // A reading older than fifteen minutes says how old it is (`checked 3h ago`).
12
12
  //
13
13
  // Like the rest of this module it reads no clock: `now` is a parameter.
14
14
  import { ALL_SCOPE } from './map.js';
@@ -97,12 +97,14 @@ function displayOrder(left, right) {
97
97
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
98
98
  }
99
99
  /**
100
- * Structured quota wording for layouts that need one row per window. The
101
- * windows use the same filtering and order as `quotaTextParts`; future resets
102
- * and the optional age keep the shared formatter's wording.
100
+ * Structured quota wording for layouts that need one row per window.
101
+ * Windows without a dated percentage remain as explicit unknown parts. Limits
102
+ * marked absent (not reported) or retired (no longer tracked) remain omitted.
103
+ * Reported windows, future resets and the optional age keep the shared
104
+ * formatter's wording and order.
103
105
  */
104
106
  export function quotaWindowParts(quota, options) {
105
- const { windows, age } = scopedWindowParts(quota, options);
107
+ const { windows, age } = scopedWindowParts(quota, options, true);
106
108
  const parts = windows.map(({ part }) => part);
107
109
  return age === undefined ? { windows: parts } : { windows: parts, age };
108
110
  }
@@ -125,34 +127,47 @@ function withShortNames(windows) {
125
127
  }
126
128
  return windows;
127
129
  }
130
+ function hasWindowReading(limit) {
131
+ return (Number.isFinite(limit.remainingPercent) && Number.isFinite(limit.checkedAt));
132
+ }
128
133
  /**
129
134
  * `quotaWindowParts` with each window's scope kept beside it. The narrow form
130
135
  * needs the scope to name and pick model-scoped windows; the public parts do
131
- * not carry it, so their shape stays as it was.
136
+ * not carry the scope.
132
137
  */
133
- function scopedWindowParts(quota, options) {
138
+ function scopedWindowParts(quota, options, includeUnknown = false) {
134
139
  if (!quota)
135
140
  return { windows: [] };
136
141
  const { now } = options;
137
142
  const readings = quota.limits
138
- .filter((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined)
143
+ .filter((limit) => limit.kind === 'reading' && (includeUnknown || hasWindowReading(limit)))
139
144
  .sort(displayOrder);
140
145
  const windows = readings.map((limit) => {
141
- const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
142
- return {
143
- scope: limit.scope,
144
- ...(limit.windowMinutes === undefined
145
- ? {}
146
- : { windowMinutes: limit.windowMinutes }),
147
- part: {
146
+ const part = hasWindowReading(limit)
147
+ ? {
148
148
  kind: 'window',
149
+ reading: 'known',
149
150
  name: quotaWindowName(limit),
150
151
  short: '',
151
- figure: percentLeft(limit.remainingPercent ?? 0),
152
- remainingPercent,
152
+ figure: percentLeft(limit.remainingPercent),
153
+ remainingPercent: clampPercent(limit.remainingPercent),
153
154
  checkedAt: limit.checkedAt,
154
155
  ...resetDetails(limit.resetsAt, limit.checkedAt, now),
155
- },
156
+ }
157
+ : {
158
+ kind: 'window',
159
+ reading: 'unknown',
160
+ name: quotaWindowName(limit),
161
+ short: '',
162
+ figure: 'no reading',
163
+ resetSinceReading: false,
164
+ };
165
+ return {
166
+ scope: limit.scope,
167
+ ...(limit.windowMinutes === undefined
168
+ ? {}
169
+ : { windowMinutes: limit.windowMinutes }),
170
+ part,
156
171
  };
157
172
  });
158
173
  const budget = quota.budget;
@@ -168,6 +183,7 @@ function scopedWindowParts(quota, options) {
168
183
  spent: budget.reached,
169
184
  part: {
170
185
  kind: 'budget',
186
+ reading: 'known',
171
187
  name: 'credits',
172
188
  short: '',
173
189
  figure,
@@ -180,8 +196,11 @@ function scopedWindowParts(quota, options) {
180
196
  });
181
197
  }
182
198
  withShortNames(windows);
183
- if (windows.length > 0) {
184
- const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
199
+ const readingTimes = windows.flatMap(({ part }) => part.reading === 'known' && part.checkedAt !== undefined
200
+ ? [part.checkedAt]
201
+ : []);
202
+ if (readingTimes.length > 0) {
203
+ const age = now - Math.min(...readingTimes);
185
204
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
186
205
  return { windows, age: `checked ${shortSpan(age)} ago` };
187
206
  }
@@ -357,13 +376,13 @@ function narrowTextParts(quota, options) {
357
376
  export function quotaTextParts(quota, options) {
358
377
  if (options.form === 'narrow')
359
378
  return narrowTextParts(quota, options);
360
- const parts = quotaWindowParts(quota, options);
379
+ const { windows, age } = scopedWindowParts(quota, options);
361
380
  const full = (options.form ?? 'full') === 'full';
362
- const text = parts.windows.map((part) => {
381
+ const text = windows.map(({ part }) => {
363
382
  const reset = full && part.resetIn ? `, resets ${part.resetIn}` : '';
364
383
  return `${part.kind === 'budget' ? '' : `${part.name} `}${part.figure}${reset}`;
365
384
  });
366
- return parts.age === undefined ? text : [...text, parts.age];
385
+ return age === undefined ? text : [...text, age];
367
386
  }
368
387
  /**
369
388
  * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
@@ -1,4 +1,4 @@
1
- import { createContext, createMemo, createSignal, For, mergeProps, 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() {
@@ -76,18 +76,20 @@ function barSegments(used, appearance, pace) {
76
76
  const cells = (pct) => Math.max(0, Math.min(Math.round((pct / 100) * width), width));
77
77
  const usedCells = cells(used);
78
78
  const tone = usageTone(used, appearance);
79
+ // Keep the overlay's slot even when empty so live pacing changes reuse nodes.
79
80
  const plain = [
80
81
  { text: appearance.barFilledChar.repeat(usedCells), tone },
82
+ { text: '', tone },
81
83
  { text: appearance.barEmptyChar.repeat(width - usedCells), tone },
82
84
  ];
83
85
  const overlay = pace?.overlay;
84
86
  if (!overlay)
85
- return plain.filter((segment) => segment.text.length > 0);
87
+ return plain;
86
88
  const paceCells = cells(overlay.percent);
87
89
  const lo = Math.min(usedCells, paceCells);
88
90
  const hi = Math.max(usedCells, paceCells);
89
91
  if (lo === hi)
90
- return plain.filter((segment) => segment.text.length > 0);
92
+ return plain;
91
93
  return [
92
94
  { text: appearance.barFilledChar.repeat(lo), tone },
93
95
  {
@@ -95,7 +97,7 @@ function barSegments(used, appearance, pace) {
95
97
  tone: overlay.kind === 'deficit' ? 'error' : 'success',
96
98
  },
97
99
  { text: appearance.barEmptyChar.repeat(width - hi), tone },
98
- ].filter((segment) => segment.text.length > 0);
100
+ ];
99
101
  }
100
102
  function QuotaRow(props) {
101
103
  const context = frameContext();
@@ -104,7 +106,18 @@ function QuotaRow(props) {
104
106
  const label = () => props.part.name +
105
107
  ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)));
106
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}`;
109
+ const hasReading = () => props.part.reading === 'known';
107
110
  const used = () => 100 - (props.part.remainingPercent ?? 100);
111
+ // Size notifications can recompute an unchanged fit after text has been flushed
112
+ // for the frame. Keep equal segments, and update fixed slots in place when the
113
+ // bar changes, rather than replacing text nodes during layout.
114
+ const segments = createMemo(() => hasReading()
115
+ ? barSegments(used(), { ...context.appearance, barWidth: props.barCells }, props.pace)
116
+ : [], undefined, {
117
+ equals: (previous, next) => previous.length === next.length &&
118
+ previous.every((segment, index) => segment.text === next[index]?.text &&
119
+ segment.tone === next[index]?.tone),
120
+ });
108
121
  const paceLine = () => {
109
122
  const text = props.pace?.text;
110
123
  if (!text || columns() <= 0)
@@ -121,20 +134,27 @@ function QuotaRow(props) {
121
134
  {label()}
122
135
  </text>
123
136
  </Show>
124
- <Show when={!props.part.resetSinceReading} fallback={<text fg={context.theme.textMuted} wrapMode='none'>
125
- reset since last check
137
+ <Show when={hasReading()} fallback={<text fg={context.theme.textMuted} wrapMode='none'>
138
+ no reading
126
139
  </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>
140
+ <Show when={!props.part.resetSinceReading} fallback={<text fg={context.theme.textMuted} wrapMode='none'>
141
+ reset since last check
142
+ </text>}>
143
+ <Show when={props.barCells > 0}>
144
+ {/* Text nodes clear omitted theme colours; empty slots must not reserve a cell. */}
145
+ <Index each={segments()}>
146
+ {(segment) => (<text fg={context.theme[segment().tone]} wrapMode='none' width={segment().text ? undefined : 0}>
147
+ {segment().text}
148
+ </text>)}
149
+ </Index>
150
+ </Show>
151
+ <text fg={context.theme[usageTone(used(), context.appearance)]} wrapMode='none'>
152
+ {figure()}
153
+ </text>
154
+ </Show>
135
155
  </Show>
136
156
  </box>
137
- <Show when={props.showReset && !props.part.resetSinceReading}>
157
+ <Show when={hasReading() && props.showReset && !props.part.resetSinceReading}>
138
158
  <box width={props.resetWidth} flexShrink={0} flexDirection='row' justifyContent='flex-end'>
139
159
  <Show when={props.part.resetIn}>
140
160
  <text fg={context.theme.textMuted} wrapMode='none'>
@@ -145,7 +165,7 @@ function QuotaRow(props) {
145
165
  </Show>
146
166
  </box>
147
167
  {/* A changed fitted line needs a fresh text node to draw at its new width. */}
148
- <Show when={!props.part.resetSinceReading && paceLine()} keyed>
168
+ <Show when={hasReading() && !props.part.resetSinceReading && paceLine()} keyed>
149
169
  {(line) => (<box width='100%' flexDirection='row'>
150
170
  <Show when={props.labelWidth > 0}>
151
171
  <text fg={context.theme.textMuted}>
@@ -163,8 +183,7 @@ function CollapsedAccountRow(props) {
163
183
  const context = frameContext();
164
184
  const [width, setWidth] = createSignal(0);
165
185
  let row;
166
- const hasQuota = () => quotaWindowParts(props.account.quota, { now: context.now }).windows.length >
167
- 0;
186
+ const hasQuota = () => quotaWindowParts(props.account.quota, { now: context.now }).windows.some((part) => part.reading === 'known');
168
187
  const text = () => hasQuota()
169
188
  ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
170
189
  : (props.account.emptyQuotaText?.collapsed ?? '\u2014');
@@ -206,9 +225,11 @@ function AccountBlock(props) {
206
225
  let block;
207
226
  const rows = () => props.account.groups.flatMap((group) => group.rows);
208
227
  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 ?? '')));
228
+ const resetWidth = () => Math.max(0, ...rows().map(({ part }) => part.reading === 'unknown' || part.resetSinceReading
229
+ ? 0
230
+ : displayWidth(part.resetIn ?? '')));
210
231
  const figureWidth = createMemo(() => Math.max(10, ...rows()
211
- .filter(({ part }) => !part.resetSinceReading)
232
+ .filter(({ part }) => part.reading === 'known' && !part.resetSinceReading)
212
233
  .map(({ part }) => displayWidth(` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`))));
213
234
  const fit = (rowLabelWidth) => {
214
235
  const desired = context.appearance.barWidth;
@@ -36,8 +36,14 @@ export type ReportRoutingInput = RoutingReportIdentity & ({
36
36
  headers: Readonly<Record<string, string>>;
37
37
  } | {
38
38
  outcome: 'exhausted';
39
- /** A quota window such as `5h`, `7d` or a scoped window id. */
40
- window: string;
39
+ /** The exhausted quota window; keep scoped quota groups in `pool`. */
40
+ window: '5h' | '7d';
41
+ /**
42
+ * Scoped quota group, such as `non-gemini`.
43
+ * Must be a non-empty string without `:`. Omit to block the whole
44
+ * account; include to block only this pool.
45
+ */
46
+ pool?: string;
41
47
  /** Optional reset time in epoch milliseconds. */
42
48
  resetsAt?: number;
43
49
  });
@@ -94,16 +94,25 @@ export function reportRouting(input) {
94
94
  case 'served':
95
95
  payload = { ...identity, outcome: 'served', headers: input.headers };
96
96
  break;
97
- case 'exhausted':
97
+ case 'exhausted': {
98
+ const { window, pool } = input;
99
+ if (window !== '5h' && window !== '7d')
100
+ return;
101
+ // An undefined pool means the whole account, as an omitted one does.
102
+ if (pool !== undefined &&
103
+ (typeof pool !== 'string' || pool.length === 0 || pool.includes(':')))
104
+ return;
98
105
  payload = {
99
106
  ...identity,
100
107
  outcome: 'exhausted',
101
- window: input.window,
108
+ window,
109
+ ...(pool ? { pool } : {}),
102
110
  ...(input.resetsAt !== undefined
103
111
  ? { resets_at: input.resetsAt }
104
112
  : {}),
105
113
  };
106
114
  break;
115
+ }
107
116
  default:
108
117
  return;
109
118
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.32.0",
3
+ "version": "0.33.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": {
@@ -5,10 +5,10 @@
5
5
  //
6
6
  // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
7
  // that binds only one model family, by the label the plugin stored it under.
8
- // Every figure is "% left". A window the provider did not report (an absence
9
- // record or a retirement tombstone) is left out rather than written as "not
10
- // reported". A reset is a short time from now (`resets 2h`). A reading older
11
- // than fifteen minutes says how old it is (`checked 3h ago`).
8
+ // Every reported window figure is "% left". A window the provider did not
9
+ // report (an absence record or a retirement tombstone) is left out rather than
10
+ // written as "not reported". A reset is a short time from now (`resets 2h`).
11
+ // A reading older than fifteen minutes says how old it is (`checked 3h ago`).
12
12
  //
13
13
  // Like the rest of this module it reads no clock: `now` is a parameter.
14
14
 
@@ -54,6 +54,8 @@ export interface QuotaTextOptions {
54
54
 
55
55
  export interface QuotaWindowPart {
56
56
  kind: 'window' | 'budget'
57
+ /** Unknown windows have no dated percentage; budgets retain their own wording. */
58
+ reading: 'known' | 'unknown'
57
59
  /** The display name of a quota window, or `credits` for the budget. */
58
60
  name: string
59
61
  /**
@@ -69,7 +71,8 @@ export interface QuotaWindowPart {
69
71
  remainingPercent?: number
70
72
  /** A bare relative reset span such as `4d`, only when the reset is future. */
71
73
  resetIn?: string
72
- checkedAt: number
74
+ /** The reading time, omitted for a window with no reading. */
75
+ checkedAt?: number
73
76
  /** Whether the reset followed this reading and has arrived by `now`. */
74
77
  resetSinceReading: boolean
75
78
  }
@@ -164,15 +167,17 @@ function displayOrder(left: ProjectedLimit, right: ProjectedLimit): number {
164
167
  }
165
168
 
166
169
  /**
167
- * Structured quota wording for layouts that need one row per window. The
168
- * windows use the same filtering and order as `quotaTextParts`; future resets
169
- * and the optional age keep the shared formatter's wording.
170
+ * Structured quota wording for layouts that need one row per window.
171
+ * Windows without a dated percentage remain as explicit unknown parts. Limits
172
+ * marked absent (not reported) or retired (no longer tracked) remain omitted.
173
+ * Reported windows, future resets and the optional age keep the shared
174
+ * formatter's wording and order.
170
175
  */
171
176
  export function quotaWindowParts(
172
177
  quota: ProjectedQuota | undefined,
173
178
  options: QuotaTextOptions,
174
179
  ): QuotaParts {
175
- const { windows, age } = scopedWindowParts(quota, options)
180
+ const { windows, age } = scopedWindowParts(quota, options, true)
176
181
  const parts = windows.map(({ part }) => part)
177
182
  return age === undefined ? { windows: parts } : { windows: parts, age }
178
183
  }
@@ -211,39 +216,58 @@ interface ScopedWindowPart {
211
216
  spent?: boolean
212
217
  }
213
218
 
219
+ function hasWindowReading(
220
+ limit: ProjectedLimit,
221
+ ): limit is ProjectedLimit & { remainingPercent: number } {
222
+ return (
223
+ Number.isFinite(limit.remainingPercent) && Number.isFinite(limit.checkedAt)
224
+ )
225
+ }
226
+
214
227
  /**
215
228
  * `quotaWindowParts` with each window's scope kept beside it. The narrow form
216
229
  * needs the scope to name and pick model-scoped windows; the public parts do
217
- * not carry it, so their shape stays as it was.
230
+ * not carry the scope.
218
231
  */
219
232
  function scopedWindowParts(
220
233
  quota: ProjectedQuota | undefined,
221
234
  options: QuotaTextOptions,
235
+ includeUnknown = false,
222
236
  ): { windows: ScopedWindowPart[]; age?: string } {
223
237
  if (!quota) return { windows: [] }
224
238
  const { now } = options
225
239
  const readings = quota.limits
226
240
  .filter(
227
241
  (limit) =>
228
- limit.kind === 'reading' && limit.remainingPercent !== undefined,
242
+ limit.kind === 'reading' && (includeUnknown || hasWindowReading(limit)),
229
243
  )
230
244
  .sort(displayOrder)
231
245
  const windows: ScopedWindowPart[] = readings.map((limit) => {
232
- const remainingPercent = clampPercent(limit.remainingPercent ?? 0)
246
+ const part: QuotaWindowPart = hasWindowReading(limit)
247
+ ? {
248
+ kind: 'window',
249
+ reading: 'known',
250
+ name: quotaWindowName(limit),
251
+ short: '',
252
+ figure: percentLeft(limit.remainingPercent),
253
+ remainingPercent: clampPercent(limit.remainingPercent),
254
+ checkedAt: limit.checkedAt,
255
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now),
256
+ }
257
+ : {
258
+ kind: 'window',
259
+ reading: 'unknown',
260
+ name: quotaWindowName(limit),
261
+ short: '',
262
+ figure: 'no reading',
263
+ resetSinceReading: false,
264
+ }
233
265
  return {
234
266
  scope: limit.scope,
235
267
  ...(limit.windowMinutes === undefined
236
268
  ? {}
237
269
  : { windowMinutes: limit.windowMinutes }),
238
- part: {
239
- kind: 'window',
240
- name: quotaWindowName(limit),
241
- short: '',
242
- figure: percentLeft(limit.remainingPercent ?? 0),
243
- remainingPercent,
244
- checkedAt: limit.checkedAt,
245
- ...resetDetails(limit.resetsAt, limit.checkedAt, now),
246
- },
270
+ part,
247
271
  }
248
272
  })
249
273
  const budget = quota.budget
@@ -259,6 +283,7 @@ function scopedWindowParts(
259
283
  spent: budget.reached,
260
284
  part: {
261
285
  kind: 'budget',
286
+ reading: 'known',
262
287
  name: 'credits',
263
288
  short: '',
264
289
  figure,
@@ -272,8 +297,13 @@ function scopedWindowParts(
272
297
  }
273
298
 
274
299
  withShortNames(windows)
275
- if (windows.length > 0) {
276
- const age = now - Math.min(...windows.map(({ part }) => part.checkedAt))
300
+ const readingTimes = windows.flatMap(({ part }) =>
301
+ part.reading === 'known' && part.checkedAt !== undefined
302
+ ? [part.checkedAt]
303
+ : [],
304
+ )
305
+ if (readingTimes.length > 0) {
306
+ const age = now - Math.min(...readingTimes)
277
307
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
278
308
  return { windows, age: `checked ${shortSpan(age)} ago` }
279
309
  }
@@ -478,13 +508,13 @@ export function quotaTextParts(
478
508
  options: QuotaTextOptions,
479
509
  ): string[] {
480
510
  if (options.form === 'narrow') return narrowTextParts(quota, options)
481
- const parts = quotaWindowParts(quota, options)
511
+ const { windows, age } = scopedWindowParts(quota, options)
482
512
  const full = (options.form ?? 'full') === 'full'
483
- const text = parts.windows.map((part) => {
513
+ const text = windows.map(({ part }) => {
484
514
  const reset = full && part.resetIn ? `, resets ${part.resetIn}` : ''
485
515
  return `${part.kind === 'budget' ? '' : `${part.name} `}${part.figure}${reset}`
486
516
  })
487
- return parts.age === undefined ? text : [...text, parts.age]
517
+ return age === undefined ? text : [...text, age]
488
518
  }
489
519
 
490
520
  /**
@@ -5,6 +5,7 @@ import {
5
5
  createMemo,
6
6
  createSignal,
7
7
  For,
8
+ Index,
8
9
  mergeProps,
9
10
  Show,
10
11
  useContext,
@@ -198,16 +199,18 @@ function barSegments(
198
199
  Math.max(0, Math.min(Math.round((pct / 100) * width), width))
199
200
  const usedCells = cells(used)
200
201
  const tone = usageTone(used, appearance)
202
+ // Keep the overlay's slot even when empty so live pacing changes reuse nodes.
201
203
  const plain = [
202
204
  { text: appearance.barFilledChar.repeat(usedCells), tone },
205
+ { text: '', tone },
203
206
  { text: appearance.barEmptyChar.repeat(width - usedCells), tone },
204
207
  ]
205
208
  const overlay = pace?.overlay
206
- if (!overlay) return plain.filter((segment) => segment.text.length > 0)
209
+ if (!overlay) return plain
207
210
  const paceCells = cells(overlay.percent)
208
211
  const lo = Math.min(usedCells, paceCells)
209
212
  const hi = Math.max(usedCells, paceCells)
210
- if (lo === hi) return plain.filter((segment) => segment.text.length > 0)
213
+ if (lo === hi) return plain
211
214
  return [
212
215
  { text: appearance.barFilledChar.repeat(lo), tone },
213
216
  {
@@ -216,7 +219,7 @@ function barSegments(
216
219
  overlay.kind === 'deficit' ? ('error' as const) : ('success' as const),
217
220
  },
218
221
  { text: appearance.barEmptyChar.repeat(width - hi), tone },
219
- ].filter((segment) => segment.text.length > 0)
222
+ ]
220
223
  }
221
224
 
222
225
  function QuotaRow(props: {
@@ -235,7 +238,31 @@ function QuotaRow(props: {
235
238
  ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)))
236
239
  const figure = () =>
237
240
  ` ${props.part.kind === 'budget' && props.part.figure.startsWith(`${props.part.name} `) ? props.part.figure.slice(props.part.name.length + 1) : props.part.figure}`
241
+ const hasReading = () => props.part.reading === 'known'
238
242
  const used = () => 100 - (props.part.remainingPercent ?? 100)
243
+ // Size notifications can recompute an unchanged fit after text has been flushed
244
+ // for the frame. Keep equal segments, and update fixed slots in place when the
245
+ // bar changes, rather than replacing text nodes during layout.
246
+ const segments = createMemo(
247
+ () =>
248
+ hasReading()
249
+ ? barSegments(
250
+ used(),
251
+ { ...context.appearance, barWidth: props.barCells },
252
+ props.pace,
253
+ )
254
+ : [],
255
+ undefined,
256
+ {
257
+ equals: (previous, next) =>
258
+ previous.length === next.length &&
259
+ previous.every(
260
+ (segment, index) =>
261
+ segment.text === next[index]?.text &&
262
+ segment.tone === next[index]?.tone,
263
+ ),
264
+ },
265
+ )
239
266
  const paceLine = () => {
240
267
  const text = props.pace?.text
241
268
  if (!text || columns() <= 0) return text
@@ -262,35 +289,49 @@ function QuotaRow(props: {
262
289
  </text>
263
290
  </Show>
264
291
  <Show
265
- when={!props.part.resetSinceReading}
292
+ when={hasReading()}
266
293
  fallback={
267
294
  <text fg={context.theme.textMuted} wrapMode='none'>
268
- reset since last check
295
+ no reading
269
296
  </text>
270
297
  }
271
298
  >
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}
299
+ <Show
300
+ when={!props.part.resetSinceReading}
301
+ fallback={
302
+ <text fg={context.theme.textMuted} wrapMode='none'>
303
+ reset since last check
282
304
  </text>
283
- )}
284
- </For>
285
- <text
286
- fg={context.theme[usageTone(used(), context.appearance)]}
287
- wrapMode='none'
305
+ }
288
306
  >
289
- {figure()}
290
- </text>
307
+ <Show when={props.barCells > 0}>
308
+ {/* Text nodes clear omitted theme colours; empty slots must not reserve a cell. */}
309
+ <Index each={segments()}>
310
+ {(segment) => (
311
+ <text
312
+ fg={context.theme[segment().tone]}
313
+ wrapMode='none'
314
+ width={segment().text ? undefined : 0}
315
+ >
316
+ {segment().text}
317
+ </text>
318
+ )}
319
+ </Index>
320
+ </Show>
321
+ <text
322
+ fg={context.theme[usageTone(used(), context.appearance)]}
323
+ wrapMode='none'
324
+ >
325
+ {figure()}
326
+ </text>
327
+ </Show>
291
328
  </Show>
292
329
  </box>
293
- <Show when={props.showReset && !props.part.resetSinceReading}>
330
+ <Show
331
+ when={
332
+ hasReading() && props.showReset && !props.part.resetSinceReading
333
+ }
334
+ >
294
335
  <box
295
336
  width={props.resetWidth}
296
337
  flexShrink={0}
@@ -306,7 +347,10 @@ function QuotaRow(props: {
306
347
  </Show>
307
348
  </box>
308
349
  {/* A changed fitted line needs a fresh text node to draw at its new width. */}
309
- <Show when={!props.part.resetSinceReading && paceLine()} keyed>
350
+ <Show
351
+ when={hasReading() && !props.part.resetSinceReading && paceLine()}
352
+ keyed
353
+ >
310
354
  {(line: string) => (
311
355
  <box width='100%' flexDirection='row'>
312
356
  <Show when={props.labelWidth > 0}>
@@ -332,8 +376,9 @@ function CollapsedAccountRow(props: { account: AccountView }) {
332
376
  const [width, setWidth] = createSignal(0)
333
377
  let row: { width: number } | undefined
334
378
  const hasQuota = () =>
335
- quotaWindowParts(props.account.quota, { now: context.now }).windows.length >
336
- 0
379
+ quotaWindowParts(props.account.quota, { now: context.now }).windows.some(
380
+ (part) => part.reading === 'known',
381
+ )
337
382
  const text = () =>
338
383
  hasQuota()
339
384
  ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
@@ -406,14 +451,18 @@ function AccountBlock(props: { account: AccountView; marginTop: number }) {
406
451
  Math.max(
407
452
  0,
408
453
  ...rows().map(({ part }) =>
409
- part.resetSinceReading ? 0 : displayWidth(part.resetIn ?? ''),
454
+ part.reading === 'unknown' || part.resetSinceReading
455
+ ? 0
456
+ : displayWidth(part.resetIn ?? ''),
410
457
  ),
411
458
  )
412
459
  const figureWidth = createMemo(() =>
413
460
  Math.max(
414
461
  10,
415
462
  ...rows()
416
- .filter(({ part }) => !part.resetSinceReading)
463
+ .filter(
464
+ ({ part }) => part.reading === 'known' && !part.resetSinceReading,
465
+ )
417
466
  .map(({ part }) =>
418
467
  displayWidth(
419
468
  ` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`,