mirror of
https://github.com/getpaseo/paseo.git
synced 2026-10-21 16:52:40 +00:00
* refactor(usage): remove agent-to-usage wiring
* feat(plugins): screens, sidebar header and footer items
Plugins register screens with addScreen and contribute component-based
sidebar items with addSidebarHeaderItem and addSidebarFooterItem. Items get
currentScreen, openScreen and openPopover, and render the SidebarRow and
SidebarButton kit. The footer shares the header's ordering model through the
new sidebarFooterItems preference, and Settings > Sidebar gains a Footer card.
addSurface, openSurface and addSidebarItem stay as aliases with their
settings keys and routes.
* refactor(plugins): share resolvePluginPlatform and keep header remembered-host key
Consolidate the five resolvePlatform copies into plugins/platform.ts.
Header sidebar items keep the <pluginId>/sidebar/<id> remembered-host key
so existing users keep their remembered host; footer items use
<pluginId>/sidebar-footer/<id>.
* feat(usage): global usage summary, pins and used/remaining display
- Device-local usage preferences (displayAs, pinned windows) in app settings.
- Sidebar footer usage summary: pinned windows in pin order, one per account;
opens the expanded view as a popover on desktop and a sheet on compact.
- Pin checkboxes on window rows and a used/remaining toggle shared by the
summary, popover, Usage screen and Settings usage section.
- Usage screen shows one host with a selector when several are connected.
- Extract HostSwitcher and the sidebar popover host for reuse.
* fix(usage): render each usage report as its own card
* feat(usage): row pinning, one title row for usage controls, even sidebar footer
- Window rows are the pin toggle (checkbox role, checked state); pinned rows
get a surface2 highlight, unpinned rows an interactionHighlight hover.
- Usage screen, Settings section, popover and sheet put the title left and
the host selector, used/remaining toggle and Refresh right (UsageControls).
PageLayout gains an actions slot; the menu sheet header a trailing slot.
- Sidebar footer rows share 28px height, spacing[1] gaps and one leading rail.
* fix(usage): keep row hover lighter than the pinned highlight
Hovering an unpinned window row shows the pinned surface2 at half opacity on
a separate layer, so it never reads stronger than a pinned row. Pinned rows
do not react to hover.
* fix(app): defer sidebar styles and preserve layout exports in timeline test
* fix(usage): open the Usage screen on desktop, drop the Usage footer icon, match git panel refresh
- Desktop presses on the usage summary open the Usage screen; only compact opens the sheet.
- The Usage footer icon is gone; with nothing pinned the summary renders a plain "Usage" row
in the footer row style. A stored `usage` footer preference is ignored.
- Refresh controls use the Changes panel's icon-only ToolbarButton with RotateCw.
* fix(sidebar): keep the footer icon row fixed; footer items are rows only
The footer's icon row (Hosts, Import session, Help and support, Settings) is back to main's
fixed implementation: not in Settings, not reorderable, and plugins can't add to it.
- Footer items are full-width rows between Add project and the icon row: the usage summary
and plugin `addSidebarFooterItem` rows. The Footer card in Settings lists only those rows.
- Stored `sidebarFooterItems` keys for hosts, import, help and usage are ignored.
- `SidebarButton` is removed from the plugin UI kit; a footer item renders `SidebarRow`.
* refactor(usage): call the sidebar footer item Usage
One concept, one word: the footer item is the Usage item, with key `usage`.
- Settings > Sidebar > Footer lists it as "Usage"; its preference key is `usage`.
- `usage/summary-item.tsx` becomes `usage/sidebar-item.tsx` (`UsageSidebarItem`); both states
use testID `sidebar-usage`.
- `usage/summary.ts` becomes `usage/pinned.ts` (`resolvePinnedUsage`, `PinnedUsageWindow`):
it resolves the pinned windows the item shows.
* feat(plugins): screen params, several rows per sidebar item, SidebarSeparator
openScreen takes { screenId, params }; params live in the screen route's
query so reload, history and links keep them. currentScreen carries the
params. A sidebar item may render a fragment or array of rows; a row press
anchors the popover to that row. SidebarSeparator joins the plugin UI kit.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(plugins): any screen param key; trailing presses anchor the row's popover
Screen params go in the query under a param. prefix, so keys like serverId
no longer collide with the route segments Expo Router merges into search
params. A press anywhere inside a SidebarRow, trailing content included,
makes that row the popover anchor.
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(plugins): plugins title their screens
addScreen takes { id, title, Component }. title is a string or a function
of the screen's params; the screen header shows it and follows param
changes. A title function that throws or returns empty falls back to the
screen id. Legacy addSidebarItem screens keep their item's title and icon,
and the addSurface alias titles its screen with the id.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(usage): require discovery and remove unreleased agent resolver
* fix(plugins): restore legacy sidebar rows, share the item runtime, header hint presses its row
- Legacy addSidebarItem rows are their own group kind again: main's row, registered icon in
Settings, /sidebar/<id> route, host remembered per row.
- New-API items follow the host last used on any of the plugin's screens.
- /sidebar/<id> falls back to a same-id screen so pre-migration links resolve.
- params moves to PluginScreenProps; settings screens no longer receive it.
- Sidebar items, buttons and popovers share one runtime per installation, so no empty first frame.
- A header row's hint slot presses the row; labels wrap as on main.
- Skill and docs corrected.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(usage): one host resolver, sheet reuses the screen's controls, name the host
- The Usage row and screen default to the same host.
- The compact sheet carries the screen's controls, host selector included.
- The host selector shows with one host, and unavailable messages name the host.
- The row, sheet title and pinned label use the sidebar.footer.usage translation.
- Window rows read their percent and reset after the pin label.
- Drop the unread per-report cache writes and headline fixture fields.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(plugins): popovers, header buttons and composer pills own their runtime again
Only sidebar item rows use the installation's shared runtime. Popover content
disposes its runtime on unmount, so observations close with the popover.
* fix(plugins): a sidebar item releases its subscriptions when it unmounts
Each mounted sidebar item gets its own API scope over the host's client, created
during render so its first frame has content. The scope closes a microtask after
unmount (StrictMode's remount keeps it), when the item moves to another host, or
when the installation stops. Replaces the installation-wide shared runtime.
* refactor(plugins): one Paseo client per plugin; authors own their subscriptions
usePaseo() in every plugin surface, and client.paseo in setup, is the
installation's client, created with the installation in the registry. Authors
release their subscriptions in their own cleanup; plugin teardown disposes the
client and ends the rest. Nothing is created or disposed per mounted surface:
the per-surface runtimes, their boundaries, and the per-run Command Center and
slash command APIs are gone.
* refactor(plugins): one Paseo client per plugin; authors own their subscriptions
usePaseo() in every plugin surface, and client.paseo in setup, is the
installation's client, created with the installation in the registry. Authors
release their subscriptions in their own cleanup; plugin teardown disposes the
client and ends the rest. Nothing is created or disposed per mounted surface:
the per-surface runtimes, their boundaries, and the per-run Command Center and
slash command APIs are gone.
* fix(usage): show usage from released hosts
Normalize released-host usage responses at the client boundary so existing usage and pins remain available across app and daemon versions. Include account labels in legacy responses for older apps.
* fix(usage): keep the usage capability check out of the public SDK
* test(server): retry transient locks during runtime test cleanup
* test(usage): model hosts without either usage capability
---------
Co-authored-by: Claude <noreply@anthropic.com>
346 lines
9.8 KiB
TypeScript
346 lines
9.8 KiB
TypeScript
import type { UsageInput } from "../shared/input.js";
|
|
import { existsSync, promises as fs } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { z } from "zod";
|
|
import {
|
|
toneFromUsedPct,
|
|
unavailableUsage,
|
|
windowFromUsedPct,
|
|
type UsageReport,
|
|
type UsageWindow,
|
|
} from "@getpaseo/plugin/server/usage";
|
|
|
|
const ApiNumberSchema = z.coerce.number().finite();
|
|
const ApiOptionalStringSchema = z.preprocess(
|
|
(value) => (value == null ? undefined : value),
|
|
z.coerce.string().optional(),
|
|
);
|
|
|
|
const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
|
|
|
|
const KimiUsageFieldsSchema = z.object({
|
|
limit: ApiOptionalStringSchema,
|
|
used: ApiOptionalStringSchema,
|
|
remaining: ApiOptionalStringSchema,
|
|
resetTime: ApiOptionalStringSchema,
|
|
resetAt: ApiOptionalStringSchema,
|
|
reset_time: ApiOptionalStringSchema,
|
|
reset_at: ApiOptionalStringSchema,
|
|
name: ApiOptionalStringSchema,
|
|
title: ApiOptionalStringSchema,
|
|
scope: ApiOptionalStringSchema,
|
|
duration: z.unknown().optional(),
|
|
timeUnit: ApiOptionalStringSchema,
|
|
});
|
|
|
|
const KimiUsageLimitSchema = z
|
|
.object({
|
|
window: z.unknown().optional(),
|
|
detail: z.unknown().optional(),
|
|
})
|
|
.passthrough();
|
|
|
|
const KimiUsageResponseSchema = z.object({
|
|
usage: z.unknown().nullish(),
|
|
limits: z.unknown().nullish(),
|
|
});
|
|
|
|
type KimiUsageFields = z.infer<typeof KimiUsageFieldsSchema>;
|
|
type KimiUsageLimit = z.infer<typeof KimiUsageLimitSchema>;
|
|
|
|
function parseUsageFields(value: unknown): KimiUsageFields | null {
|
|
const parsed = KimiUsageFieldsSchema.safeParse(value);
|
|
return parsed.success ? parsed.data : null;
|
|
}
|
|
|
|
function usedPctFromFields(fields: KimiUsageFields): number | null {
|
|
const limit = fields.limit === undefined ? null : Number(fields.limit);
|
|
const used = fields.used === undefined ? null : Number(fields.used);
|
|
const remaining = fields.remaining === undefined ? null : Number(fields.remaining);
|
|
|
|
if (limit === null || !Number.isFinite(limit) || limit <= 0) return null;
|
|
|
|
let usedValue: number | null = null;
|
|
if (used !== null && Number.isFinite(used)) {
|
|
usedValue = used;
|
|
} else if (remaining !== null && Number.isFinite(remaining)) {
|
|
usedValue = limit - remaining;
|
|
}
|
|
|
|
return usedValue === null ? null : Math.max(0, Math.min(100, (usedValue / limit) * 100));
|
|
}
|
|
|
|
function resetTimeFromFields(fields: KimiUsageFields): string | null {
|
|
return fields.resetTime ?? fields.resetAt ?? fields.reset_time ?? fields.reset_at ?? null;
|
|
}
|
|
|
|
function explicitUsageLabel(...fields: Array<KimiUsageFields | null>): string | null {
|
|
for (const field of fields) {
|
|
if (!field) continue;
|
|
const label = field.name ?? field.title ?? field.scope;
|
|
if (label?.trim()) return label.trim();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function durationFrom(value: unknown): number | null {
|
|
const duration = Number(value);
|
|
return Number.isFinite(duration) && duration > 0 ? duration : null;
|
|
}
|
|
|
|
function durationLabel(duration: number, timeUnit: string | undefined): string | null {
|
|
if (!timeUnit) return null;
|
|
|
|
const normalizedUnit = timeUnit.replace(/^TIME_UNIT_/i, "").toUpperCase();
|
|
if (normalizedUnit.includes("MINUTE")) {
|
|
if (duration % 60 === 0) return `${duration / 60}-hour limit`;
|
|
return `${duration}-minute limit`;
|
|
}
|
|
if (normalizedUnit.includes("HOUR")) return `${duration}-hour limit`;
|
|
if (normalizedUnit.includes("DAY")) return `${duration}-day limit`;
|
|
if (normalizedUnit.includes("WEEK")) return `${duration}-week limit`;
|
|
if (normalizedUnit.includes("SECOND")) return `${duration}-second limit`;
|
|
return null;
|
|
}
|
|
|
|
function idPart(value: string | number): string {
|
|
return String(value)
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, "_")
|
|
.replace(/^_+|_+$/g, "");
|
|
}
|
|
|
|
function hasUsageData(fields: KimiUsageFields | null): fields is KimiUsageFields {
|
|
return (
|
|
fields !== null &&
|
|
(fields.limit !== undefined || fields.used !== undefined || fields.remaining !== undefined)
|
|
);
|
|
}
|
|
|
|
function limitFields(limit: KimiUsageLimit): {
|
|
fields: KimiUsageFields | null;
|
|
metadata: KimiUsageFields | null;
|
|
} {
|
|
const metadata = parseUsageFields(limit);
|
|
const detail = parseUsageFields(limit.detail);
|
|
return {
|
|
fields: hasUsageData(detail) ? detail : metadata,
|
|
metadata,
|
|
};
|
|
}
|
|
|
|
function windowMetadata(limit: KimiUsageLimit): KimiUsageFields | null {
|
|
return parseUsageFields(limit.window);
|
|
}
|
|
|
|
function limitIdentity(input: {
|
|
metadata: KimiUsageFields | null;
|
|
fields: KimiUsageFields;
|
|
window: KimiUsageFields | null;
|
|
index: number;
|
|
}): { id: string; label: string } {
|
|
const label = explicitUsageLabel(input.metadata, input.fields);
|
|
const duration = durationFrom(
|
|
input.window?.duration ?? input.metadata?.duration ?? input.fields.duration,
|
|
);
|
|
const timeUnit = input.window?.timeUnit ?? input.metadata?.timeUnit ?? input.fields.timeUnit;
|
|
const generatedLabel = duration === null ? null : durationLabel(duration, timeUnit);
|
|
|
|
if (duration !== null && timeUnit) {
|
|
return {
|
|
id: `coding_limit_${idPart(duration)}_${idPart(timeUnit)}`,
|
|
label: label ?? generatedLabel ?? `Limit ${input.index + 1}`,
|
|
};
|
|
}
|
|
|
|
if (label) {
|
|
return { id: `coding_limit_${idPart(label)}`, label };
|
|
}
|
|
|
|
return {
|
|
id: `coding_limit_${input.index + 1}`,
|
|
label: generatedLabel ?? `Limit ${input.index + 1}`,
|
|
};
|
|
}
|
|
|
|
function windowFromFields(input: {
|
|
id: string;
|
|
label: string;
|
|
fields: KimiUsageFields;
|
|
}): UsageWindow {
|
|
const usedPct = usedPctFromFields(input.fields);
|
|
return windowFromUsedPct({
|
|
id: input.id,
|
|
label: input.label,
|
|
utilizationPct: usedPct,
|
|
resetsAt: resetTimeFromFields(input.fields),
|
|
tone: toneFromUsedPct(usedPct),
|
|
});
|
|
}
|
|
|
|
function uniqueWindowId(baseId: string, seenIds: Set<string>): string {
|
|
let id = baseId;
|
|
let suffix = 2;
|
|
while (seenIds.has(id)) {
|
|
id = `${baseId}_${suffix}`;
|
|
suffix += 1;
|
|
}
|
|
seenIds.add(id);
|
|
return id;
|
|
}
|
|
|
|
function kimiUsageWindowsFromPayload(payload: unknown): UsageWindow[] {
|
|
const response = KimiUsageResponseSchema.parse(payload);
|
|
const windows: UsageWindow[] = [];
|
|
const seenWindowIds = new Set<string>();
|
|
const usage = parseUsageFields(response.usage);
|
|
|
|
if (hasUsageData(usage)) {
|
|
windows.push(
|
|
windowFromFields({
|
|
id: uniqueWindowId("coding_usage", seenWindowIds),
|
|
label: explicitUsageLabel(usage) ?? "Weekly limit",
|
|
fields: usage,
|
|
}),
|
|
);
|
|
}
|
|
|
|
const limits = Array.isArray(response.limits) ? response.limits : [];
|
|
for (const [index, rawLimit] of limits.entries()) {
|
|
const parsedLimit = KimiUsageLimitSchema.safeParse(rawLimit);
|
|
if (!parsedLimit.success) {
|
|
continue;
|
|
}
|
|
|
|
const limit = parsedLimit.data;
|
|
const { fields, metadata } = limitFields(limit);
|
|
if (!hasUsageData(fields)) {
|
|
continue;
|
|
}
|
|
|
|
const window = windowMetadata(limit);
|
|
const identity = limitIdentity({ metadata, fields, window, index });
|
|
windows.push(
|
|
windowFromFields({
|
|
id: uniqueWindowId(identity.id, seenWindowIds),
|
|
label: identity.label,
|
|
fields,
|
|
}),
|
|
);
|
|
}
|
|
|
|
return windows;
|
|
}
|
|
|
|
const KimiAuthSchema = z
|
|
.object({
|
|
access_token: z.string().nullish(),
|
|
refresh_token: z.string().nullish(),
|
|
expires_at: ApiNumberSchema.nullish(),
|
|
expires_in: ApiNumberSchema.nullish(),
|
|
scope: z.string().nullish(),
|
|
token_type: z.string().nullish(),
|
|
})
|
|
.passthrough();
|
|
|
|
type KimiAuth = z.infer<typeof KimiAuthSchema>;
|
|
type KimiCredentials = KimiAuth & { access_token: string };
|
|
|
|
export async function fetchUsage(
|
|
input: UsageInput,
|
|
fetchApi: typeof fetch = fetch,
|
|
): Promise<UsageReport> {
|
|
void input;
|
|
const homeDir = homedir();
|
|
|
|
async function callUsageApi(token: string): Promise<Response> {
|
|
return fetchApi(KIMI_USAGE_URL, {
|
|
signal: AbortSignal.timeout(15_000),
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
Accept: "application/json",
|
|
},
|
|
});
|
|
}
|
|
|
|
async function readCredentials(): Promise<KimiCredentials | null> {
|
|
const environmentToken = process.env["KIMI_TOKEN"] || process.env["KIMI_API_KEY"];
|
|
if (environmentToken) {
|
|
return { access_token: environmentToken };
|
|
}
|
|
|
|
for (const path of credentialPaths()) {
|
|
const credentials = await readCredentialFile(path);
|
|
if (credentials?.access_token) {
|
|
return { ...credentials, access_token: credentials.access_token };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function credentialPaths(): string[] {
|
|
const home = homeDir;
|
|
return [
|
|
join(
|
|
process.env["KIMI_CODE_HOME"] || join(home, ".kimi-code"),
|
|
"credentials",
|
|
"kimi-code.json",
|
|
),
|
|
join(home, ".kimi", "credentials", "kimi-code.json"),
|
|
];
|
|
}
|
|
|
|
async function readCredentialFile(path: string): Promise<KimiAuth | null> {
|
|
if (!existsSync(path)) return null;
|
|
try {
|
|
return KimiAuthSchema.parse(JSON.parse(await fs.readFile(path, "utf8")));
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
const credentials = await readCredentials();
|
|
if (!credentials) return unavailableUsage();
|
|
|
|
const res = await callUsageApi(credentials.access_token);
|
|
|
|
if (!res.ok) {
|
|
// Read-only on credentials; the Kimi CLI owns refresh. See docs/providers.md.
|
|
|
|
return unavailableUsage();
|
|
}
|
|
|
|
const windows = kimiUsageWindowsFromPayload(await res.json());
|
|
|
|
return {
|
|
status: "available",
|
|
planLabel: undefined,
|
|
windows,
|
|
balances: [],
|
|
details: [],
|
|
};
|
|
}
|
|
|
|
export async function identify() {
|
|
if (process.env["KIMI_TOKEN"] || process.env["KIMI_API_KEY"]) return { key: "default" };
|
|
const home = homedir();
|
|
const paths = [
|
|
join(
|
|
process.env["KIMI_CODE_HOME"] || join(home, ".kimi-code"),
|
|
"credentials",
|
|
"kimi-code.json",
|
|
),
|
|
join(home, ".kimi", "credentials", "kimi-code.json"),
|
|
];
|
|
for (const path of paths) {
|
|
try {
|
|
const auth = KimiAuthSchema.parse(JSON.parse(await fs.readFile(path, "utf8")));
|
|
if (auth.access_token) return { key: "default" };
|
|
} catch {
|
|
continue;
|
|
}
|
|
}
|
|
return null;
|
|
}
|