@0xkahi/pi-qol 1.1.2 → 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.
- package/README.md +12 -3
- package/assets/config.schema.json +2 -18
- package/package.json +4 -4
- package/src/extensions/custom-footer/codemap.md +5 -6
- package/src/extensions/custom-footer/constants.ts +0 -1
- package/src/extensions/custom-footer/footer-component.ts +19 -9
- package/src/extensions/custom-footer/index.ts +3 -1
- package/src/extensions/custom-footer/token-stats.ts +25 -17
- package/src/extensions/custom-footer/types.ts +3 -1
- package/src/extensions/model-select/codemap.md +8 -4
- package/src/extensions/model-select/index.ts +35 -29
- package/src/extensions/model-select/model-select-dialog.ts +9 -25
- package/src/extensions/model-select/model-select-modal.ts +66 -0
- package/src/extensions/model-select/usage-section/codemap.md +14 -0
- package/src/extensions/model-select/usage-section/index.ts +37 -0
- package/src/extensions/model-select/usage-section/usage-provider-tab.ts +166 -0
- package/src/index.ts +7 -3
- package/src/libs/modal/README.md +46 -2
- package/src/libs/modal/codemap.md +4 -1
- package/src/libs/modal/index.ts +2 -0
- package/src/libs/modal/label-window.ts +32 -0
- package/src/libs/modal/modal-dialog.ts +16 -2
- package/src/libs/modal/section-strip.ts +33 -0
- package/src/libs/modal/sectioned-modal.ts +105 -0
- package/src/libs/modal/tab-strip.ts +2 -26
- package/src/libs/subscription-usage/codemap.md +10 -21
- package/src/libs/subscription-usage/credential-resolver.ts +44 -0
- package/src/libs/subscription-usage/index.ts +8 -0
- package/src/libs/subscription-usage/pace.ts +28 -0
- package/src/libs/subscription-usage/progress-bar.ts +13 -0
- package/src/libs/subscription-usage/provider-color.ts +10 -0
- package/src/libs/subscription-usage/strategy/anthropic-oauth-usage.strategy.ts +5 -5
- package/src/libs/subscription-usage/strategy/codemap.md +5 -41
- package/src/libs/subscription-usage/strategy/openai-codex-usage.strategy.ts +7 -8
- package/src/libs/subscription-usage/subscription-usage-api.util.ts +45 -66
- package/src/libs/subscription-usage/subscription-usage-cache.ts +89 -0
- package/src/schemas/codemap.md +1 -1
- package/src/schemas/custom-footer-config.schema.ts +0 -4
- package/src/extensions/custom-footer/progress-bar.ts +0 -16
- 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.
|
|
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.
|
|
49
|
-
"@earendil-works/pi-coding-agent": "^0.
|
|
50
|
-
"@earendil-works/pi-tui": "^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
|
-
- **
|
|
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 `
|
|
42
|
-
8. **Async refresh**:
|
|
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
|
|
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.
|
|
@@ -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
|
|
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
|
|
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.
|
|
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
|
}
|
|
@@ -111,7 +112,7 @@ export class CustomFooterComponent implements Component {
|
|
|
111
112
|
|
|
112
113
|
private renderStatsLine(width: number, config: CustomFooterConfig): string {
|
|
113
114
|
const model = this.deps.ctx.model;
|
|
114
|
-
const usingSubscription = model ? this.
|
|
115
|
+
const usingSubscription = model ? this.isUsingSubscription(model) : false;
|
|
115
116
|
const contextUsage = this.deps.ctx.getContextUsage();
|
|
116
117
|
const contextWindow = contextUsage?.contextWindow ?? model?.contextWindow ?? 0;
|
|
117
118
|
const subscriptionUsageSegment = this.renderSubscriptionUsageSegment(config, usingSubscription);
|
|
@@ -158,6 +159,14 @@ export class CustomFooterComponent implements Component {
|
|
|
158
159
|
return `${statsLeft}${' '.repeat(Math.max(0, width - statsLeftWidth - truncatedRightWidth))}${truncatedRight}`;
|
|
159
160
|
}
|
|
160
161
|
|
|
162
|
+
private isUsingSubscription(model: NonNullable<CustomFooterComponentDeps['ctx']['model']>): boolean {
|
|
163
|
+
if (model.provider === 'kimi-coding') return true;
|
|
164
|
+
|
|
165
|
+
return (
|
|
166
|
+
this.deps.ctx.modelRegistry.isUsingOAuth(model) && this.deps.ctx.modelRegistry.getProvider(model.provider)?.auth?.oauth?.isSubscription === true
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
161
170
|
private buildModelNameSegment(config: CustomFooterConfig): string {
|
|
162
171
|
const model = this.deps.ctx.model;
|
|
163
172
|
const modelName = model?.id ?? 'no-model';
|
|
@@ -179,14 +188,15 @@ export class CustomFooterComponent implements Component {
|
|
|
179
188
|
const provider = resolveSupportedProvider(model.provider);
|
|
180
189
|
if (!provider) return undefined;
|
|
181
190
|
|
|
182
|
-
const
|
|
183
|
-
|
|
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;
|
|
184
194
|
|
|
185
|
-
const
|
|
195
|
+
const windows = response.status === 'ok' ? response.windows : entry?.lastSuccess?.windows;
|
|
196
|
+
const window = pickSubscriptionUsageWindow(windows ?? []);
|
|
186
197
|
if (!window) return undefined;
|
|
187
198
|
|
|
188
199
|
return buildSubscriptionUsageSegment({
|
|
189
|
-
colors: config.colors,
|
|
190
200
|
icons: config.icons,
|
|
191
201
|
theme: this.deps.theme,
|
|
192
202
|
usage: {
|
|
@@ -194,7 +204,7 @@ export class CustomFooterComponent implements Component {
|
|
|
194
204
|
responseLabel: response.label,
|
|
195
205
|
windowLabel: window.label,
|
|
196
206
|
usedPercent: window.usedPercent,
|
|
197
|
-
resetDescription: window.resetAt ? this.
|
|
207
|
+
resetDescription: window.resetAt ? this.deps.usageCache.formatResetDescription(window.resetAt) : undefined,
|
|
198
208
|
},
|
|
199
209
|
});
|
|
200
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,7 +1,9 @@
|
|
|
1
1
|
import { dye } from '@0xkahi/cli-dye';
|
|
2
|
+
import type { Usage } from '@earendil-works/pi-ai';
|
|
2
3
|
import type { ContextUsage, SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
import { clampPercent, renderProgressBar } from '
|
|
4
|
-
import
|
|
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';
|
|
5
7
|
|
|
6
8
|
export type SubscriptionUsageSegmentInput = {
|
|
7
9
|
provider: SupportedProvider;
|
|
@@ -40,37 +42,43 @@ export function calculateUsageTotals(entries: readonly SessionEntry[]): UsageTot
|
|
|
40
42
|
};
|
|
41
43
|
|
|
42
44
|
for (const entry of entries) {
|
|
43
|
-
if (entry.type
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
45
|
+
if (entry.type === 'message' && entry.message.role === 'assistant') {
|
|
46
|
+
const usage = entry.message.usage;
|
|
47
|
+
addUsageToTotals(totals, usage);
|
|
48
|
+
|
|
49
|
+
const latestPromptTokens = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
50
|
+
totals.latestCacheHitRate = latestPromptTokens > 0 ? (usage.cacheRead / latestPromptTokens) * 100 : undefined;
|
|
51
|
+
} else if (entry.type === 'message' && entry.message.role === 'toolResult' && entry.message.usage) {
|
|
52
|
+
addUsageToTotals(totals, entry.message.usage);
|
|
53
|
+
} else if ((entry.type === 'usage' || entry.type === 'branch_summary' || entry.type === 'compaction') && entry.usage) {
|
|
54
|
+
addUsageToTotals(totals, entry.usage);
|
|
55
|
+
}
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
return totals;
|
|
57
59
|
}
|
|
58
60
|
|
|
61
|
+
function addUsageToTotals(totals: UsageTotals, usage: Usage): void {
|
|
62
|
+
totals.totalInput += usage.input;
|
|
63
|
+
totals.totalOutput += usage.output;
|
|
64
|
+
totals.totalCacheRead += usage.cacheRead;
|
|
65
|
+
totals.totalCacheWrite += usage.cacheWrite;
|
|
66
|
+
totals.totalCost += usage.cost.total;
|
|
67
|
+
}
|
|
68
|
+
|
|
59
69
|
export function buildSubscriptionUsageSegment({
|
|
60
|
-
colors,
|
|
61
70
|
icons,
|
|
62
71
|
theme,
|
|
63
72
|
usage,
|
|
64
73
|
}: {
|
|
65
|
-
colors: Pick<CustomFooterColors, 'anthropicUsage' | 'codexUsage'>;
|
|
66
74
|
icons: Pick<CustomFooterIcons, 'refresh'>;
|
|
67
75
|
theme: FooterTheme;
|
|
68
76
|
usage: SubscriptionUsageSegmentInput;
|
|
69
77
|
}): string {
|
|
70
|
-
const providerColor = usage.provider
|
|
78
|
+
const providerColor = providerUsageColor(usage.provider);
|
|
71
79
|
const pct = clampPercent(usage.usedPercent);
|
|
72
80
|
const roundedPercent = Math.round(pct).toString();
|
|
73
|
-
const bar = renderProgressBar(pct);
|
|
81
|
+
const bar = renderProgressBar(pct, SUBSCRIPTION_BAR_WIDTH, { filled: FILLED_BAR_ICON, empty: EMPTY_BAR_ICON });
|
|
74
82
|
const foreground = dye.hex(providerColor);
|
|
75
83
|
|
|
76
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 =
|
|
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`:
|
|
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**: `
|
|
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 `
|
|
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 {
|
|
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(
|
|
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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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, {
|
|
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 {
|
|
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
|
-
*
|
|
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
|
|
15
|
-
|
|
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:
|
|
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
|
+
}
|