@0xkahi/pi-qol 1.1.3 → 1.2.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.
Files changed (40) hide show
  1. package/README.md +12 -3
  2. package/assets/config.schema.json +2 -18
  3. package/package.json +4 -4
  4. package/src/extensions/custom-footer/codemap.md +5 -6
  5. package/src/extensions/custom-footer/constants.ts +0 -1
  6. package/src/extensions/custom-footer/footer-component.ts +10 -8
  7. package/src/extensions/custom-footer/index.ts +3 -1
  8. package/src/extensions/custom-footer/token-stats.ts +5 -6
  9. package/src/extensions/custom-footer/types.ts +3 -1
  10. package/src/extensions/model-select/codemap.md +8 -4
  11. package/src/extensions/model-select/index.ts +35 -29
  12. package/src/extensions/model-select/model-select-dialog.ts +9 -25
  13. package/src/extensions/model-select/model-select-modal.ts +66 -0
  14. package/src/extensions/model-select/usage-section/codemap.md +14 -0
  15. package/src/extensions/model-select/usage-section/index.ts +37 -0
  16. package/src/extensions/model-select/usage-section/usage-provider-tab.ts +166 -0
  17. package/src/index.ts +7 -3
  18. package/src/libs/modal/README.md +46 -2
  19. package/src/libs/modal/codemap.md +4 -1
  20. package/src/libs/modal/index.ts +2 -0
  21. package/src/libs/modal/label-window.ts +32 -0
  22. package/src/libs/modal/modal-dialog.ts +16 -2
  23. package/src/libs/modal/section-strip.ts +33 -0
  24. package/src/libs/modal/sectioned-modal.ts +105 -0
  25. package/src/libs/modal/tab-strip.ts +2 -26
  26. package/src/libs/subscription-usage/codemap.md +10 -21
  27. package/src/libs/subscription-usage/credential-resolver.ts +44 -0
  28. package/src/libs/subscription-usage/index.ts +8 -0
  29. package/src/libs/subscription-usage/pace.ts +28 -0
  30. package/src/libs/subscription-usage/progress-bar.ts +13 -0
  31. package/src/libs/subscription-usage/provider-color.ts +10 -0
  32. package/src/libs/subscription-usage/strategy/anthropic-oauth-usage.strategy.ts +7 -15
  33. package/src/libs/subscription-usage/strategy/codemap.md +5 -41
  34. package/src/libs/subscription-usage/strategy/openai-codex-usage.strategy.ts +8 -15
  35. package/src/libs/subscription-usage/subscription-usage-api.util.ts +44 -67
  36. package/src/libs/subscription-usage/subscription-usage-cache.ts +89 -0
  37. package/src/schemas/codemap.md +1 -1
  38. package/src/schemas/custom-footer-config.schema.ts +0 -4
  39. package/src/extensions/custom-footer/progress-bar.ts +0 -16
  40. package/src/extensions/custom-footer/subscription-usage-manager.ts +0 -91
package/README.md CHANGED
@@ -44,6 +44,16 @@ Favourites, ordered custom group tabs, provider filtering, and inline or overlay
44
44
  - **shared filtering** across Favourites, group, and Search tabs
45
45
  - **bidirectional tab navigation** with Tab and Shift+Tab
46
46
  - **provider filtering** for Search without removing models from favourite tabs
47
+ - **sections**: opens on Select Model; `Ctrl+]` switches to the next section and
48
+ `Ctrl+[` to the previous (both wrap). Without the Kitty keyboard protocol,
49
+ `Ctrl+[` acts as Esc instead. Tab/Shift+Tab stay within the active section.
50
+ - **Usage**: `[Claude]` and `[Codex]` tabs show every subscription rate window,
51
+ separated by blank lines, with a progress bar, used percentage, reset time,
52
+ pace, and data freshness. Fixed provider colors match the custom footer. Missing
53
+ credentials and request failures are shown explicitly. Usage shares the footer
54
+ cache and fetches only when visited; press `r` to refresh the active provider.
55
+ Navigate rows with `j`/`k`, arrows, `gg`/`G`; `q` or Esc closes without changing
56
+ the model. In Select Model, `q` still types in the filter.
47
57
 
48
58
  allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with eventId of `pi.vimKeys.event:pi-qol.model_select`
49
59
 
@@ -52,7 +62,8 @@ allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with
52
62
  Replaces pi's built-in interactive footer with the same three-line layout, but
53
63
  shows the current directory as an icon plus basename, supports hex color overrides,
54
64
  can hide token/cache clusters, and adds an OAuth subscription-usage progress bar
55
- for supported providers (Anthropic and OpenAI Codex).
65
+ for supported providers (Anthropic and OpenAI Codex). Usage colors are fixed:
66
+ Claude `#D97706` and Codex `#10B981`; former usage-color overrides are ignored.
56
67
 
57
68
  - **Directory line** — optional inverse-styled agent badge followed by the
58
69
  directory icon + basename, with optional git branch and session name. The badge
@@ -197,8 +208,6 @@ Context View is a fork of Dmitry Makarov's [pi-context-view](https://github.com/
197
208
  | `colors.directory` | `hex` | — | Color the directory icon and basename. |
198
209
  | `colors.modelName` | `hex` | — | Color the right-aligned model name. |
199
210
  | `colors.agentName` | `hex` | — | Agent badge foreground color before inversion. |
200
- | `colors.anthropicUsage` | `hex` | `#D97706` | Color the Claude subscription usage segment (bar + percentage). |
201
- | `colors.codexUsage` | `hex` | `#10B981` | Color the Codex subscription usage segment (bar + percentage). |
202
211
  | `icons.directory` | `string` | nerd font | Glyph shown before the directory basename. |
203
212
  | `icons.cache` | `string` | nerd font | Glyph for the cache cluster. |
204
213
  | `icons.cacheRead` | `string` | nerd font | Glyph for cache-read tokens. |
@@ -155,10 +155,7 @@
155
155
  "custom_footer": {
156
156
  "default": {
157
157
  "enabled": false,
158
- "colors": {
159
- "anthropicUsage": "#D97706",
160
- "codexUsage": "#10B981"
161
- },
158
+ "colors": {},
162
159
  "icons": {
163
160
  "directory": " ",
164
161
  "refresh": "",
@@ -180,10 +177,7 @@
180
177
  "type": "boolean"
181
178
  },
182
179
  "colors": {
183
- "default": {
184
- "anthropicUsage": "#D97706",
185
- "codexUsage": "#10B981"
186
- },
180
+ "default": {},
187
181
  "type": "object",
188
182
  "properties": {
189
183
  "directory": {
@@ -197,16 +191,6 @@
197
191
  "agentName": {
198
192
  "type": "string",
199
193
  "pattern": "^#[0-9a-fA-F]{6}$"
200
- },
201
- "anthropicUsage": {
202
- "default": "#D97706",
203
- "type": "string",
204
- "pattern": "^#[0-9a-fA-F]{6}$"
205
- },
206
- "codexUsage": {
207
- "default": "#10B981",
208
- "type": "string",
209
- "pattern": "^#[0-9a-fA-F]{6}$"
210
194
  }
211
195
  }
212
196
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.1.3",
3
+ "version": "1.2.0",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -45,9 +45,9 @@
45
45
  "devDependencies": {
46
46
  "@biomejs/biome": "^2.4.15",
47
47
  "@changesets/cli": "^2.31.0",
48
- "@earendil-works/pi-ai": "^0.87.0",
49
- "@earendil-works/pi-coding-agent": "^0.87.0",
50
- "@earendil-works/pi-tui": "^0.87.0",
48
+ "@earendil-works/pi-ai": "^0.99.2",
49
+ "@earendil-works/pi-coding-agent": "^0.99.2",
50
+ "@earendil-works/pi-tui": "^0.99.2",
51
51
  "@types/bun": "latest",
52
52
  "@types/node": "^24.0.0",
53
53
  "bun-types": "latest",
@@ -21,11 +21,10 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
21
21
  - **Component pattern**: `CustomFooterComponent` implements the `Component` interface (`render`, `invalidate`, `dispose`) so the TUI can call it on every frame.
22
22
  - **Dependency injection**: The component receives its dependencies (`tui`, `theme`, `footerData`, `ctx`, `config`, `getThinkingLevel`) in a single `CustomFooterComponentDeps` object, keeping rendering logic decoupled from construction.
23
23
  - **Data provider abstraction**: `FooterDataProvider` isolates footer-specific data (git branch, extension statuses, provider count, branch-change notifications) from the broader `ExtensionContext`.
24
- - **Cache manager**: `SubscriptionUsageManager` caches OAuth usage responses with a TTL and coalesces in-flight requests per provider.
25
- - **Strategy pattern**: Provider-specific OAuth usage fetch strategies (`AnthropicOauthUsageStrategy`, `OpenAiCodexUsageStrategy`) are selected at runtime inside `SubscriptionUsageManager`.
24
+ - **Shared cache**: root injects one `SubscriptionUsageCache`; the component subscribes for renders and unsubscribes in `dispose`. Provider strategies and TTL/in-flight deduplication live in the shared library.
26
25
  - **Provider normalization**: `resolveSupportedProvider` maps provider aliases (`codex`, `openai`, `chatgpt`) to the internal `SupportedProvider` union.
27
26
  - **Window selection**: `pickSubscriptionUsageWindow` chooses the rate window with the nearest reset, falling back to the first window when no resets are available.
28
- - **Pure formatting helpers**: `token-stats.ts` and `progress-bar.ts` contain stateless functions for number formatting, usage aggregation, subscription segment construction, and progress-bar rendering, making them easy to test.
27
+ - **Pure formatting helpers**: `token-stats.ts` and the shared library's `progress-bar.ts` contain stateless functions for number formatting, usage aggregation, subscription segment construction, and progress-bar rendering, making them easy to test.
29
28
 
30
29
  ## Data & Control Flow
31
30
 
@@ -38,8 +37,8 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
38
37
  - Extension status line (only when statuses exist).
39
38
  5. **Usage aggregation**: `calculateUsageTotals` in `token-stats.ts` sums assistant-message token counts and computes the latest cache hit rate from `sessionManager.getEntries()`.
40
39
  6. **Stats composition**: `buildStatsLeft` receives the pre-computed totals, display toggles, context usage, context window, subscription segment, and theme; it returns the left-hand stats string.
41
- 7. **Subscription usage**: `renderSubscriptionUsageSegment` resolves the provider, asks `SubscriptionUsageManager.ensureFresh(provider)` for cached data, picks the rate window with the nearest reset via `pickSubscriptionUsageWindow`, and builds a colored progress segment via `buildSubscriptionUsageSegment` in `token-stats.ts`.
42
- 8. **Async refresh**: `SubscriptionUsageManager` fetches usage asynchronously when the cached entry is older than `SUBSCRIPTION_USAGE_TTL_MS`. On success it calls `tui.requestRender()` via the `onUpdate` callback to update the footer.
40
+ 7. **Subscription usage**: `renderSubscriptionUsageSegment` resolves the provider, asks the injected `SubscriptionUsageCache.ensureFresh(provider)` for cached data (`ok` windows or last-success windows for temporary failures), picks the rate window with the nearest reset via `pickSubscriptionUsageWindow`, and builds a colored progress segment via `buildSubscriptionUsageSegment` in `token-stats.ts`.
41
+ 8. **Async refresh**: the shared cache fetches asynchronously after its TTL. Completion notifications call `tui.requestRender()` through the component subscription; network/http-error/unavailable retain last-success windows, while no-auth/expired hide usage. Temporary failures without earlier successful windows also hide usage.
43
42
  9. **Git branch updates**: `footerData.onBranchChange` registers a render request callback that is cleaned up in `dispose`.
44
43
 
45
44
  ## Integration Points
@@ -48,5 +47,5 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
48
47
  - **`@earendil-works/pi-tui`**: Implements the `Component` contract and uses `truncateToWidth`, `visibleWidth`, and `TUI.requestRender`.
49
48
  - **`../../config-loader`**: Reads the `custom_footer` feature flag and full footer config (colors, icons, display toggles) via `ConfigLoader`.
50
49
  - **`../../schemas/config.schema`**: `CustomFooterConfig` is derived from the `Config` schema's `custom_footer` shape.
51
- - **`@0xkahi/cli-dye`**: Applies configured truecolor ANSI styling to directory text, model name, subscription usage labels, and progress-bar fill.
50
+ - **`@0xkahi/cli-dye`**: Applies configured truecolor ANSI styling to directory text and model name. Subscription labels, filled progress and percentages use fixed provider colors from the shared usage library; no footer usage-color configuration remains.
52
51
  - **`../../libs/subscription-usage/**`**: Delegates OAuth usage fetching and reset formatting to `SubscriptionUsageApi` and provider-specific strategies.
@@ -1,4 +1,3 @@
1
1
  export const FILLED_BAR_ICON = '█';
2
2
  export const EMPTY_BAR_ICON = '░';
3
3
  export const SUBSCRIPTION_BAR_WIDTH = 10;
4
- export const SUBSCRIPTION_USAGE_TTL_MS = 60_000;
@@ -2,7 +2,7 @@ import { basename } from 'node:path';
2
2
  import { dye } from '@0xkahi/cli-dye';
3
3
  import type { Component } from '@earendil-works/pi-tui';
4
4
  import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
5
- import { pickSubscriptionUsageWindow, resolveSupportedProvider, SubscriptionUsageManager } from './subscription-usage-manager';
5
+ import { pickSubscriptionUsageWindow, resolveSupportedProvider } from '../../libs/subscription-usage';
6
6
  import { buildStatsLeft, buildSubscriptionUsageSegment, calculateUsageTotals } from './token-stats';
7
7
  import type { CustomFooterComponentDeps, CustomFooterConfig } from './types';
8
8
 
@@ -16,14 +16,14 @@ function sanitizeStatusText(text: string): string {
16
16
  }
17
17
 
18
18
  export class CustomFooterComponent implements Component {
19
- private readonly usageManager: SubscriptionUsageManager;
19
+ private readonly unsubscribeUsage: () => void;
20
20
  private readonly unsubscribeBranch: () => void;
21
21
  private readonly unsubscribeAgentDisplay: () => void;
22
22
  private restoredDefaultFooter = false;
23
23
  private disposed = false;
24
24
 
25
25
  constructor(private readonly deps: CustomFooterComponentDeps) {
26
- this.usageManager = new SubscriptionUsageManager(undefined, () => {
26
+ this.unsubscribeUsage = deps.usageCache.subscribe(() => {
27
27
  if (!this.disposed) deps.tui.requestRender();
28
28
  });
29
29
  this.unsubscribeBranch = deps.footerData.onBranchChange(() => deps.tui.requestRender());
@@ -38,6 +38,7 @@ export class CustomFooterComponent implements Component {
38
38
 
39
39
  dispose(): void {
40
40
  this.disposed = true;
41
+ this.unsubscribeUsage();
41
42
  this.unsubscribeBranch();
42
43
  this.unsubscribeAgentDisplay();
43
44
  }
@@ -187,14 +188,15 @@ export class CustomFooterComponent implements Component {
187
188
  const provider = resolveSupportedProvider(model.provider);
188
189
  if (!provider) return undefined;
189
190
 
190
- const response = this.usageManager.ensureFresh(provider);
191
- if (!response) return undefined;
191
+ const entry = this.deps.usageCache.ensureFresh(provider);
192
+ const response = entry?.result;
193
+ if (!response || response.status === 'no-auth' || response.status === 'expired') return undefined;
192
194
 
193
- const window = pickSubscriptionUsageWindow(response.rateWindow);
195
+ const windows = response.status === 'ok' ? response.windows : entry?.lastSuccess?.windows;
196
+ const window = pickSubscriptionUsageWindow(windows ?? []);
194
197
  if (!window) return undefined;
195
198
 
196
199
  return buildSubscriptionUsageSegment({
197
- colors: config.colors,
198
200
  icons: config.icons,
199
201
  theme: this.deps.theme,
200
202
  usage: {
@@ -202,7 +204,7 @@ export class CustomFooterComponent implements Component {
202
204
  responseLabel: response.label,
203
205
  windowLabel: window.label,
204
206
  usedPercent: window.usedPercent,
205
- resetDescription: window.resetAt ? this.usageManager.formatResetDescription(window.resetAt) : undefined,
207
+ resetDescription: window.resetAt ? this.deps.usageCache.formatResetDescription(window.resetAt) : undefined,
206
208
  },
207
209
  });
208
210
  }
@@ -1,10 +1,11 @@
1
1
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
3
  import { SET_AGENT_NAME_EVENT_ID } from '../../constants';
4
+ import type { SubscriptionUsageCache } from '../../libs/subscription-usage';
4
5
  import { AgentDisplayState } from './agent-display-state';
5
6
  import { CustomFooterComponent } from './footer-component';
6
7
 
7
- export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoader }): void {
8
+ export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoader; usageCache: SubscriptionUsageCache }): void {
8
9
  let installed = false;
9
10
  const agentDisplayState = new AgentDisplayState('DEFAULT');
10
11
 
@@ -25,6 +26,7 @@ export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoa
25
26
  footerData,
26
27
  ctx,
27
28
  config: deps.config,
29
+ usageCache: deps.usageCache,
28
30
  agentDisplayState,
29
31
  getThinkingLevel: () => pi.getThinkingLevel(),
30
32
  }),
@@ -1,8 +1,9 @@
1
1
  import { dye } from '@0xkahi/cli-dye';
2
2
  import type { Usage } from '@earendil-works/pi-ai';
3
3
  import type { ContextUsage, SessionEntry } from '@earendil-works/pi-coding-agent';
4
- import { clampPercent, renderProgressBar } from './progress-bar';
5
- import type { CustomFooterColors, CustomFooterDisplay, CustomFooterIcons, FooterTheme, SupportedProvider, UsageTotals } from './types';
4
+ import { clampPercent, providerUsageColor, renderProgressBar } from '../../libs/subscription-usage';
5
+ import { EMPTY_BAR_ICON, FILLED_BAR_ICON, SUBSCRIPTION_BAR_WIDTH } from './constants';
6
+ import type { CustomFooterDisplay, CustomFooterIcons, FooterTheme, SupportedProvider, UsageTotals } from './types';
6
7
 
7
8
  export type SubscriptionUsageSegmentInput = {
8
9
  provider: SupportedProvider;
@@ -66,20 +67,18 @@ function addUsageToTotals(totals: UsageTotals, usage: Usage): void {
66
67
  }
67
68
 
68
69
  export function buildSubscriptionUsageSegment({
69
- colors,
70
70
  icons,
71
71
  theme,
72
72
  usage,
73
73
  }: {
74
- colors: Pick<CustomFooterColors, 'anthropicUsage' | 'codexUsage'>;
75
74
  icons: Pick<CustomFooterIcons, 'refresh'>;
76
75
  theme: FooterTheme;
77
76
  usage: SubscriptionUsageSegmentInput;
78
77
  }): string {
79
- const providerColor = usage.provider === 'anthropic' ? colors.anthropicUsage : colors.codexUsage;
78
+ const providerColor = providerUsageColor(usage.provider);
80
79
  const pct = clampPercent(usage.usedPercent);
81
80
  const roundedPercent = Math.round(pct).toString();
82
- const bar = renderProgressBar(pct);
81
+ const bar = renderProgressBar(pct, SUBSCRIPTION_BAR_WIDTH, { filled: FILLED_BAR_ICON, empty: EMPTY_BAR_ICON });
83
82
  const foreground = dye.hex(providerColor);
84
83
 
85
84
  const resetParts = usage.resetDescription ? [icons.refresh, usage.resetDescription].filter(Boolean).join(' ') : '';
@@ -1,10 +1,11 @@
1
1
  import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import type { TUI } from '@earendil-works/pi-tui';
3
3
  import type { ConfigLoader } from '../../config-loader';
4
+ import type { SubscriptionProvider, SubscriptionUsageCache } from '../../libs/subscription-usage';
4
5
  import type { Config } from '../../schemas/config.schema';
5
6
  import type { AgentDisplayState } from './agent-display-state';
6
7
 
7
- export type SupportedProvider = 'anthropic' | 'openai-codex';
8
+ export type SupportedProvider = SubscriptionProvider;
8
9
 
9
10
  export type CustomFooterConfig = Config['custom_footer'];
10
11
  export type CustomFooterColors = CustomFooterConfig['colors'];
@@ -29,6 +30,7 @@ export type CustomFooterComponentDeps = {
29
30
  ctx: ExtensionContext;
30
31
  config: ConfigLoader;
31
32
  agentDisplayState: AgentDisplayState;
33
+ usageCache: SubscriptionUsageCache;
32
34
  getThinkingLevel: () => string;
33
35
  };
34
36
 
@@ -13,10 +13,12 @@ This extension implements the `/select-model` command and its interactive picker
13
13
  - `index.ts`: orchestrates activation, command handling, applying the selected model, setting default reasoning, and bridging registry errors into the dialog.
14
14
  - `model-lists.ts`: queries the registry and prepares favourite, grouped favourite, and searchable model lists; validates favourite entries against the registry and configured auth.
15
15
  - `model-formatter.ts`: pure static utilities for labels, descriptions, sorting, token formatting, capability detection, and search-text generation.
16
- - `model-select-dialog.ts`: thin `ModalDialog` (shared modal library) configuration: one `ListTab` per section (permanent Favourites, groups, Search), a shared filter input, notices for config warnings, and per-section row/empty-state/footer hooks. The shared presenter supplies its resolved inline or bordered frame.
16
+ - `model-select-dialog.ts`: `createSelectModelSection` builds an embedded `ModalDialog` with one `ListTab` per tab (permanent Favourites, groups, Search), shared filter, warnings, and row/empty-state/footer hooks.
17
+ - `model-select-modal.ts`: `ModelSelectModal` composes Select Model (initial) and Usage through `SectionedModal`, uses the presenter frame typed as `SectionFrame`, subscribes to the shared usage cache, and starts a 1s interval that requests renders only while Usage is active. Completion from either section and host `dispose()` share idempotent interval/subscription cleanup; `scheduleTick` can be injected for tests.
18
+ - `usage-section/`: [usage section map](usage-section/codemap.md); Claude/Codex provider tabs, explicit status and freshness, all window rows with progress/reset/pace, retained Vim row navigation, and `r` refresh.
17
19
  - `constants.ts`: command name, cross-extension event ID, and dialog rendering limits.
18
20
  - `types.ts`: shared item, list, tab, and dialog option types.
19
- - **Modal library delegation**: `ModelSelectDialog` implements `Component` and `Focusable` by delegating to a `ModalDialog` from `src/libs/modal/`; the shell owns the tab strip, tab cycling, keybinding-driven navigation (wrap-around selection via `ListTab`), the shared filter `Input`, and the help footer.
21
+ - **Modal library delegation**: `ModelSelectModal` extends `SectionedModal` from `src/libs/modal/`, containing retained embedded dialogs; Ctrl+] and disambiguated Ctrl+[ wrap sections, bare Esc stays dismissal, and Tab stays inside the active section. Each dialog shell owns the tab strip, tab cycling, keybinding-driven navigation (wrap-around selection via `ListTab`), the shared filter `Input`, and the help footer.
20
22
  - **Layout-aware presentation**: `showModelSelector` passes `model_select.layout` to the shared modal presenter, which coordinates the dialog's inline/bordered frame with normal or centered overlay mounting.
21
23
  - **Defensive guards**: checks feature enablement, UI availability, idle state (`waitForIdle`), exact-match short-circuit, and auth availability before applying a model.
22
24
 
@@ -42,14 +44,15 @@ This extension implements the `/select-model` command and its interactive picker
42
44
  - Favourites must exist in the registry and have configured auth; missing or unauthenticated entries are collected as warnings and omitted from the list.
43
45
  - Accepted favourites retain exact group memberships; the ordered `groups` config defines the visible group tabs. Duplicate favourite models are deduplicated by provider/id, and duplicate group names are collapsed while preserving configured order.
44
46
  - Any model-registry error is added to the dialog's `configWarnings` so it appears inside the picker.
45
- - The shared `presentModal` helper creates a `ModelSelectDialog` with favourite/group/search lists, tab visibility controls, the current model, warnings, `initialSearch`, resolved frame, `defaultReasoning`, and an `onDone` callback. The overlay layout remains centered at 85% width with a one-cell margin.
47
+ - The shared `presentModal` helper creates a `ModelSelectModal` with favourite/group/search lists, tab visibility controls, the current model, warnings, `initialSearch`, resolved frame, `defaultReasoning`, and an `onDone` callback. The overlay layout remains centered at 85% width with a one-cell margin.
46
48
  - The dialog always creates a Favourites tab, adds visible group tabs and optional Search, and renders a width-aware tab strip, shared filter input, warnings, and help footer. If `initialSearch` is non-empty and Search is visible, the dialog starts on the Search tab and seeds the input.
47
49
 
48
50
  5. **User interaction**
49
51
  - Keyboard input is mapped through `keybindings.matches` for navigation, ordered tab cycling (`tab`/`shift+tab`), page up/down, confirmation, and cancellation.
50
52
  - Typing updates one shared query and re-filters every visible tab via `fuzzyFilter`; each tab retains its own selection index.
51
53
  - The Search tab displays the active `provider_filter` above the query input.
52
- - Confirming a selection invokes `onDone` with the chosen `Model`; cancelling invokes `onDone(null)`.
54
+ - Confirming a selection invokes `onDone` with the chosen `Model`; cancelling from either section invokes `onDone(null)`, unsubscribing from usage cache updates first.
55
+ - Select Model alone makes no usage requests. First Usage activation calls `ensureFresh` for every supported provider; TTL and in-flight deduplication belong to the shared cache. Current provider preselection defaults to Claude when unsupported. Usage uses Vim navigation without a filter, and raw `r` forces active-provider refresh; cache completion requests re-render.
53
56
 
54
57
  6. **Apply result**
55
58
  - If a model is selected, `applySelectedModel` calls `pi.setModel`.
@@ -74,6 +77,7 @@ The `model_select` configuration is defined by `../../schemas/model-select.confi
74
77
  - **`ExtensionAPI` (`@earendil-works/pi-coding-agent`)**: used to register the command, listen to `session_start`, set the active model (`pi.setModel`), set the thinking level (`pi.setThinkingLevel`), and access the shared event bus (`pi.events`).
75
78
  - **`ExtensionContext` / `ExtensionCommandContext` (`@earendil-works/pi-coding-agent`)**: provides `modelRegistry`, `ui`, `hasUI`, `model`, `cwd`, and the optional `waitForIdle` guard.
76
79
  - **`ModelRegistry`**: refreshed and queried for available models, configured auth, lookup by `provider` + `modelId`, and error state (`getError`).
80
+ - **`SubscriptionUsageCache` (`../../libs/subscription-usage`)**: injected from the root, shared with the footer; statuses and last-success windows drive Usage content, pace and progress helpers format its rows.
77
81
  - **`ConfigLoader` (`../../config-loader`)**: provides feature toggle state (`isEnabled('model_select')`), the typed `model_select` configuration object, and merges global + project JSON config.
78
82
  - **`@earendil-works/pi-ai`**: supplies the `Model<Api>` type, `modelsAreEqual` for stable identity comparisons, and `getSupportedThinkingLevels` for reasoning-level validation.
79
83
  - **`@earendil-works/pi-tui`**: supplies the `Input` component, `fuzzyFilter`, `matchesKey`, theme helpers, and rendering utilities (`truncateToWidth`, `visibleWidth`) used by the dialog.
@@ -1,12 +1,13 @@
1
1
  import { type Api, getSupportedThinkingLevels, type Model } from '@earendil-works/pi-ai';
2
2
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from '@earendil-works/pi-coding-agent';
3
3
  import type { ConfigLoader } from '../../config-loader';
4
- import { presentModal } from '../../libs/modal';
4
+ import { presentModal, type SectionFrame } from '../../libs/modal';
5
+ import type { SubscriptionUsageCache } from '../../libs/subscription-usage';
5
6
  import type { ModelSelectConfig } from '../../schemas/model-select.config.schema';
6
7
  import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
7
8
  import { ModelFormatter } from './model-formatter';
8
9
  import { buildModelLists, findExactModel } from './model-lists';
9
- import { ModelSelectDialog } from './model-select-dialog';
10
+ import { ModelSelectModal } from './model-select-modal';
10
11
  import type { DialogResult } from './types';
11
12
 
12
13
  export async function applySelectedModel(pi: ExtensionAPI, ctx: ExtensionContext, model: Model<Api>, config: ModelSelectConfig): Promise<void> {
@@ -22,7 +23,13 @@ export async function applySelectedModel(pi: ExtensionAPI, ctx: ExtensionContext
22
23
  }
23
24
  }
24
25
 
25
- export async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionContext, configLoader: ConfigLoader): Promise<void> {
26
+ export async function showModelSelector(
27
+ pi: ExtensionAPI,
28
+ args: string,
29
+ ctx: ExtensionContext,
30
+ configLoader: ConfigLoader,
31
+ usageCache: SubscriptionUsageCache,
32
+ ): Promise<void> {
26
33
  // `waitForIdle` only exists on command contexts. When invoked from the event
27
34
  // bus we get a plain ExtensionContext, so fall back to a best-effort guard.
28
35
  if ('waitForIdle' in ctx && typeof ctx.waitForIdle === 'function') {
@@ -45,34 +52,33 @@ export async function showModelSelector(pi: ExtensionAPI, args: string, ctx: Ext
45
52
  const modelLists = await buildModelLists(ctx, config);
46
53
  const registryError = ctx.modelRegistry.getError();
47
54
 
48
- const selected = await presentModal<DialogResult>(
49
- ctx.ui,
50
- config.layout,
51
- (tui, theme, keybindings, done, frame) =>
52
- new ModelSelectDialog(tui, theme, keybindings, {
53
- currentModel: ctx.model,
54
- favouriteItems: modelLists.favouriteItems,
55
- favouriteLabel: config.favourite_label,
56
- favouriteWarnings: modelLists.favouriteWarnings,
57
- groupLists: modelLists.groupLists,
58
- searchItems: modelLists.searchItems,
59
- hideGroupTabs: config.hide_tabs.groups,
60
- hideSearchTab: config.hide_tabs.search,
61
- providerFilter: config.provider_filter,
62
- defaultReasoning: config.default_reasoning,
63
- configWarnings: registryError ? [`models.json: ${registryError}`] : [],
64
- initialSearch: args.trim(),
65
- frame,
66
- onDone: done,
67
- }),
68
- );
55
+ const selected = await presentModal<DialogResult>(ctx.ui, config.layout, (tui, theme, keybindings, done, frame) => {
56
+ const sectionFrame: SectionFrame = frame === 'bordered' ? 'bordered' : 'inline';
57
+ return new ModelSelectModal(tui, theme, keybindings, {
58
+ currentModel: ctx.model,
59
+ favouriteItems: modelLists.favouriteItems,
60
+ favouriteLabel: config.favourite_label,
61
+ favouriteWarnings: modelLists.favouriteWarnings,
62
+ groupLists: modelLists.groupLists,
63
+ searchItems: modelLists.searchItems,
64
+ hideGroupTabs: config.hide_tabs.groups,
65
+ hideSearchTab: config.hide_tabs.search,
66
+ providerFilter: config.provider_filter,
67
+ defaultReasoning: config.default_reasoning,
68
+ configWarnings: registryError ? [`models.json: ${registryError}`] : [],
69
+ initialSearch: args.trim(),
70
+ frame: sectionFrame,
71
+ usageCache,
72
+ onDone: done,
73
+ });
74
+ });
69
75
 
70
76
  if (selected) {
71
77
  await applySelectedModel(pi, ctx, selected, config);
72
78
  }
73
79
  }
74
80
 
75
- function activateModelSelect(pi: ExtensionAPI, deps: { config: ConfigLoader; initialCtx?: ExtensionContext }) {
81
+ function activateModelSelect(pi: ExtensionAPI, deps: { config: ConfigLoader; usageCache: SubscriptionUsageCache; initialCtx?: ExtensionContext }) {
76
82
  // Keep a reference to the latest context so the event-bus handler (which gets
77
83
  // no context of its own) can open the modal too. Lazy activation may happen
78
84
  // during session_start, so seed this with the context that triggered it.
@@ -90,7 +96,7 @@ function activateModelSelect(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
90
96
  ctx.ui.notify('(pi-qol) model_select is disabled', 'warning');
91
97
  return;
92
98
  }
93
- await showModelSelector(pi, args, ctx, deps.config);
99
+ await showModelSelector(pi, args, ctx, deps.config, deps.usageCache);
94
100
  },
95
101
  });
96
102
 
@@ -101,13 +107,13 @@ function activateModelSelect(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
101
107
  if (!ctx || !deps.config.isEnabled('model_select')) {
102
108
  return;
103
109
  }
104
- void showModelSelector(pi, '', ctx, deps.config).catch(error => {
110
+ void showModelSelector(pi, '', ctx, deps.config, deps.usageCache).catch(error => {
105
111
  ctx.ui.notify(`Failed to open model selector: ${error instanceof Error ? error.message : String(error)}`, 'error');
106
112
  });
107
113
  });
108
114
  }
109
115
 
110
- export function registerModelSelect(pi: ExtensionAPI, deps: { config: ConfigLoader }) {
116
+ export function registerModelSelect(pi: ExtensionAPI, deps: { config: ConfigLoader; usageCache: SubscriptionUsageCache }) {
111
117
  let modelSelectRegistered = false;
112
118
 
113
119
  pi.on('session_start', (_event, ctx) => {
@@ -115,7 +121,7 @@ export function registerModelSelect(pi: ExtensionAPI, deps: { config: ConfigLoad
115
121
  return;
116
122
  }
117
123
 
118
- activateModelSelect(pi, { config: deps.config, initialCtx: ctx });
124
+ activateModelSelect(pi, { ...deps, initialCtx: ctx });
119
125
  modelSelectRegistered = true;
120
126
  });
121
127
  }
@@ -1,6 +1,6 @@
1
1
  import { modelsAreEqual } from '@earendil-works/pi-ai';
2
2
  import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
3
- import type { Component, Focusable, TUI } from '@earendil-works/pi-tui';
3
+ import type { TUI } from '@earendil-works/pi-tui';
4
4
  import { ListTab, ModalDialog, type ModalTab } from '../../libs/modal';
5
5
  import { MAX_CONFIG_WARNING_LINES, MAX_VISIBLE_MODELS } from './constants';
6
6
  import { ModelFormatter } from './model-formatter';
@@ -8,11 +8,15 @@ import type { DialogOptions, DialogResult, ModelItem, TabIdentity } from './type
8
8
 
9
9
  /**
10
10
  * Model picker dialog: a `ModalDialog` configured with one `ListTab` per
11
- * section (permanent Favourites, configured groups, Search), a shared filter
11
+ * tab (permanent Favourites, configured groups, Search), a shared filter
12
12
  * input, and wrap-around picker navigation driven by the host keybindings.
13
13
  */
14
- export class ModelSelectDialog implements Component, Focusable {
15
- private readonly dialog: ModalDialog<DialogResult>;
14
+ export function createSelectModelSection(tui: TUI, theme: Theme, keybindings: KeybindingsManager, options: DialogOptions): ModalDialog<DialogResult> {
15
+ return new SelectModelSectionBuilder(tui, theme, keybindings, options).dialog;
16
+ }
17
+
18
+ class SelectModelSectionBuilder {
19
+ public readonly dialog: ModalDialog<DialogResult>;
16
20
 
17
21
  constructor(
18
22
  tui: TUI,
@@ -42,32 +46,12 @@ export class ModelSelectDialog implements Component, Focusable {
42
46
  notices: options.configWarnings,
43
47
  maxNoticeLines: MAX_CONFIG_WARNING_LINES,
44
48
  filter: { initialQuery: options.initialSearch },
45
- frame: options.frame,
49
+ frame: 'none',
46
50
  cancelValue: null,
47
51
  onComplete: result => options.onDone(result),
48
52
  });
49
53
  }
50
54
 
51
- get focused(): boolean {
52
- return this.dialog.focused;
53
- }
54
-
55
- set focused(value: boolean) {
56
- this.dialog.focused = value;
57
- }
58
-
59
- invalidate(): void {
60
- this.dialog.invalidate();
61
- }
62
-
63
- handleInput(data: string): void {
64
- this.dialog.handleInput(data);
65
- }
66
-
67
- render(width: number): string[] {
68
- return this.dialog.render(width);
69
- }
70
-
71
55
  private createTab(definition: { identity: TabIdentity; label: string; items: ModelItem[] }): ModalTab {
72
56
  const currentIndex = this.options.currentModel ? definition.items.findIndex(item => modelsAreEqual(item.model, this.options.currentModel)) : -1;
73
57
 
@@ -0,0 +1,66 @@
1
+ import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
2
+ import type { TUI } from '@earendil-works/pi-tui';
3
+ import { SectionedModal, type SectionFrame } from '../../libs/modal';
4
+ import type { SubscriptionUsageCache } from '../../libs/subscription-usage';
5
+ import { createSelectModelSection } from './model-select-dialog';
6
+ import type { DialogOptions, DialogResult } from './types';
7
+ import { createUsageSection } from './usage-section';
8
+
9
+ function scheduleTick(callback: () => void, intervalMs: number): () => void {
10
+ const timer = setInterval(callback, intervalMs);
11
+ timer.unref?.();
12
+ return () => clearInterval(timer);
13
+ }
14
+
15
+ export class ModelSelectModal extends SectionedModal<DialogResult> {
16
+ private readonly cleanup: () => void;
17
+
18
+ public constructor(
19
+ tui: TUI,
20
+ theme: Theme,
21
+ keybindings: KeybindingsManager,
22
+ options: DialogOptions & {
23
+ frame: SectionFrame;
24
+ usageCache: SubscriptionUsageCache;
25
+ now?: () => number;
26
+ scheduleTick?: (callback: () => void, intervalMs: number) => () => void;
27
+ },
28
+ ) {
29
+ let disposed = false;
30
+ let unsubscribe: () => void = () => undefined;
31
+ let cancelTick: () => void = () => undefined;
32
+ const cleanup = () => {
33
+ if (disposed) return;
34
+ disposed = true;
35
+ cancelTick();
36
+ unsubscribe();
37
+ };
38
+ const onDone = (result: DialogResult) => {
39
+ cleanup();
40
+ options.onDone(result);
41
+ };
42
+ super(tui, theme, {
43
+ frame: options.frame,
44
+ sections: [
45
+ { label: 'Select Model', dialog: createSelectModelSection(tui, theme, keybindings, { ...options, onDone }) },
46
+ createUsageSection(tui, theme, keybindings, {
47
+ cache: options.usageCache,
48
+ currentProvider: options.currentModel?.provider,
49
+ onDone,
50
+ now: options.now,
51
+ }),
52
+ ],
53
+ });
54
+ this.cleanup = cleanup;
55
+ unsubscribe = options.usageCache.subscribe(() => {
56
+ if (!disposed) tui.requestRender();
57
+ });
58
+ cancelTick = (options.scheduleTick ?? scheduleTick)(() => {
59
+ if (!disposed && this.activeSectionIndex === 1) tui.requestRender();
60
+ }, 1000);
61
+ }
62
+
63
+ public dispose(): void {
64
+ this.cleanup();
65
+ }
66
+ }
@@ -0,0 +1,14 @@
1
+ # src/extensions/model-select/usage-section/
2
+
3
+ ## Responsibility
4
+
5
+ Read-only subscription usage section of the model selector, consuming the same injected cache as the custom footer.
6
+
7
+ ## Modules
8
+
9
+ - `index.ts`: `createUsageSection` builds an embedded Vim-navigated dialog with bracketed `[Claude]`/`[Codex]` tabs, preselects the current supported provider (else Claude), and requests every provider on first activation through the section host.
10
+ - `usage-provider-tab.ts`: `UsageProviderTab` renders provider status, freshness, all rate windows, progress/reset/pace rows, and retained row navigation using `ListNavigator`. Failures preserve last-success windows and their original fetch time. Raw `r` forces active-provider refresh. The injected clock keeps relative times testable. Window rows have one blank separator, with `ListNavigator` still selecting windows rather than separator lines; bounded views budget two lines per visible window minus the final separator. Provider names, labels, bar fills, and percentages use the fixed `providerUsageColor` palette from the subscription-usage library and cli-dye; empty bars and reset text are dim. Model-select does not depend on footer internals or color configuration. The render cache keys on whole seconds, result, in-flight state, last success, and viewport, while navigation/theme changes invalidate it. In-flight fetches with displayed windows show `refreshing…` and retain the rows.
11
+
12
+ ## Lifecycle
13
+
14
+ `ModelSelectModal` owns the cache subscription and a 1s interval that requests renders only while Usage is active. Either section's completion or host `dispose()` clears both resources through idempotent cleanup. Select Model alone never fetches usage or requests timed renders. Cache completion requests a render; visible ticks update freshness and reset countdowns without input.
@@ -0,0 +1,37 @@
1
+ import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
2
+ import type { TUI } from '@earendil-works/pi-tui';
3
+ import { ModalDialog, type ModalSection, VimNavigationScheme } from '../../../libs/modal';
4
+ import { resolveSupportedProvider, SUBSCRIPTION_PROVIDERS, type SubscriptionUsageCache } from '../../../libs/subscription-usage';
5
+ import type { DialogResult } from '../types';
6
+ import { UsageProviderTab } from './usage-provider-tab';
7
+
8
+ export function createUsageSection(
9
+ tui: TUI,
10
+ theme: Theme,
11
+ keybindings: KeybindingsManager,
12
+ options: {
13
+ cache: SubscriptionUsageCache;
14
+ currentProvider?: string;
15
+ onDone: (result: DialogResult) => void;
16
+ now?: () => number;
17
+ },
18
+ ): ModalSection<DialogResult> {
19
+ const provider = resolveSupportedProvider(options.currentProvider);
20
+ return {
21
+ label: 'Usage',
22
+ dialog: new ModalDialog<DialogResult>(tui, theme, keybindings, {
23
+ tabs: SUBSCRIPTION_PROVIDERS.map(entry => new UsageProviderTab(theme, options.cache, entry.provider, entry.label, options.now)),
24
+ initialTabIndex: Math.max(
25
+ 0,
26
+ SUBSCRIPTION_PROVIDERS.findIndex(entry => entry.provider === provider),
27
+ ),
28
+ navigation: new VimNavigationScheme(),
29
+ frame: 'none',
30
+ cancelValue: null,
31
+ onComplete: options.onDone,
32
+ }),
33
+ onActivate: () => {
34
+ for (const entry of SUBSCRIPTION_PROVIDERS) options.cache.ensureFresh(entry.provider);
35
+ },
36
+ };
37
+ }