tuxevil-rotator 4.0.0 → 4.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/CHANGELOG.md +62 -0
- package/README.md +8 -1
- package/package.json +1 -1
- package/src/audio-transcription.ts +44 -4
- package/src/compat.ts +196 -222
- package/src/config-defaults.ts +5 -0
- package/src/config-overrides.ts +16 -0
- package/src/dashboard-live.ts +10 -8
- package/src/dashboard-types.ts +94 -1
- package/src/dashboard.ts +194 -1
- package/src/effort-levels.ts +43 -0
- package/src/effort-routing.ts +304 -0
- package/src/index.ts +2 -5
- package/src/model-catalog-revision.ts +20 -0
- package/src/model-catalog.ts +304 -0
- package/src/providers/adapter.ts +18 -0
- package/src/providers/google-antigravity/catalog.ts +190 -1
- package/src/providers/google-antigravity/forward.ts +2 -0
- package/src/providers/google-antigravity/index.ts +11 -0
- package/src/providers/google-antigravity/translators.ts +67 -14
- package/src/providers/ollama/index.ts +11 -1
- package/src/providers/ollama/quota-poll-store.ts +22 -1
- package/src/providers/ollama/quota.ts +95 -23
- package/src/providers/openai-codex/catalog.ts +9 -4
- package/src/providers/openai-codex/index.ts +18 -2
- package/src/providers/opencode-zen/index.ts +11 -2
- package/src/proxy.ts +143 -28
- package/src/rotator.ts +296 -21
- package/src/settings-repository.ts +36 -5
- package/src/types.ts +72 -26
- package/src/validators.ts +37 -1
- package/src/web/app.tsx +6 -1
- package/src/web/components/icons.tsx +29 -0
- package/src/web/components/overlays.tsx +13 -1
- package/src/web/components/ui.tsx +6 -1
- package/src/web/lib/accounts.ts +1 -0
- package/src/web/lib/attention.ts +12 -0
- package/src/web/lib/effort.ts +407 -0
- package/src/web/lib/models.ts +284 -0
- package/src/web/lib/pools.ts +53 -9
- package/src/web/lib/status.ts +13 -3
- package/src/web/nav.ts +1 -0
- package/src/web/pages/AccountDetail.tsx +16 -2
- package/src/web/pages/EffortRouting.tsx +1130 -0
- package/src/web/pages/Models.tsx +888 -0
- package/src/web/pages/Overview.tsx +31 -15
- package/src/web/pages/Usage.tsx +3 -3
- package/src/web/state/api.ts +31 -0
- package/src/web/state/model-catalog.ts +103 -0
- package/src/web/state/router.ts +150 -19
- package/src/web/state/store.ts +6 -6
- package/src/web/styles/app.css +854 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// Overview: is routing working, how long will each model last, and what
|
|
2
2
|
// needs the operator. Model pools come first; accounts are one click away.
|
|
3
3
|
|
|
4
|
-
import type
|
|
4
|
+
import { type JSX } from "preact";
|
|
5
5
|
import { useMemo, useState } from "preact/hooks";
|
|
6
6
|
import type { DashboardOverview } from "../../dashboard-types.js";
|
|
7
7
|
import { buildAttention, SEVERITY_ICON, SEVERITY_TONE, type AttentionAction, type AttentionItem } from "../lib/attention.js";
|
|
8
|
-
import {
|
|
9
|
-
import { formatClock, formatCompact, formatCount, formatDuration, formatMs, pluralize } from "../lib/format.js";
|
|
8
|
+
import { buildProviderGroups, type ProviderGroup, type ModelPool } from "../lib/pools.js";
|
|
9
|
+
import { formatClock, formatCompact, formatCount, formatDuration, formatMs, formatUsd, pluralize } from "../lib/format.js";
|
|
10
10
|
import {
|
|
11
11
|
canServe,
|
|
12
12
|
isCooling,
|
|
@@ -42,7 +42,7 @@ export function OverviewPage(): JSX.Element {
|
|
|
42
42
|
const data = overview.value!;
|
|
43
43
|
const tickNow = now.value;
|
|
44
44
|
const minuteNow = Math.floor(tickNow / 60_000);
|
|
45
|
-
const
|
|
45
|
+
const providers = useMemo(() => buildProviderGroups(data, Date.now()), [data, minuteNow]);
|
|
46
46
|
const attention = useMemo(
|
|
47
47
|
() => buildAttention(data, Date.now(), masker.value.name),
|
|
48
48
|
[data, masker.value, minuteNow],
|
|
@@ -61,7 +61,7 @@ export function OverviewPage(): JSX.Element {
|
|
|
61
61
|
/>
|
|
62
62
|
<StatusHero data={data} attention={attention} />
|
|
63
63
|
{attention.length > 0 && <AttentionPanel items={attention} />}
|
|
64
|
-
<
|
|
64
|
+
<ProvidersPanel providers={providers} />
|
|
65
65
|
<div class="grid-2">
|
|
66
66
|
<RecentProblems />
|
|
67
67
|
<ControlsPanel data={data} />
|
|
@@ -322,6 +322,8 @@ const POOL_STATE: Record<ModelPool["state"], { label: string; tone: Tone } | nul
|
|
|
322
322
|
};
|
|
323
323
|
|
|
324
324
|
function estimateText(pool: ModelPool): { text: string; tone: Tone | null; title: string } {
|
|
325
|
+
if (pool.credits)
|
|
326
|
+
return { text: "—", tone: null, title: "Credit consumption depends on the model and tokens used; request counts alone cannot predict exhaustion." };
|
|
325
327
|
if (pool.burnPerHour <= 0 || pool.hoursLeft === null)
|
|
326
328
|
return { text: "Idle", tone: null, title: "No requests for this pool in the last hour" };
|
|
327
329
|
const hours = pool.hoursLeft;
|
|
@@ -333,24 +335,24 @@ function estimateText(pool: ModelPool): { text: string; tone: Tone | null; title
|
|
|
333
335
|
};
|
|
334
336
|
}
|
|
335
337
|
|
|
336
|
-
function
|
|
338
|
+
function ProvidersPanel({ providers }: { providers: ProviderGroup[] }): JSX.Element {
|
|
337
339
|
const [open, setOpen] = useState<string | null>(null);
|
|
338
340
|
return (
|
|
339
341
|
<Panel
|
|
340
|
-
title="
|
|
341
|
-
subtitle="
|
|
342
|
+
title="Providers"
|
|
343
|
+
subtitle="Connected providers and their quota pools across accounts in service, weighted by allowance or tier."
|
|
342
344
|
flush
|
|
343
345
|
>
|
|
344
|
-
{
|
|
345
|
-
<EmptyState icon="accounts" title="No
|
|
346
|
-
|
|
346
|
+
{providers.length === 0 ? (
|
|
347
|
+
<EmptyState icon="accounts" title="No providers connected">
|
|
348
|
+
Add an account to see its providers and quota pools.
|
|
347
349
|
</EmptyState>
|
|
348
350
|
) : (
|
|
349
351
|
<div class="table-scroll">
|
|
350
352
|
<table class="table pools-table">
|
|
351
353
|
<thead>
|
|
352
354
|
<tr>
|
|
353
|
-
<th scope="col">
|
|
355
|
+
<th scope="col">Provider / quota pool</th>
|
|
354
356
|
<th scope="col">Remaining</th>
|
|
355
357
|
<th scope="col">Serving</th>
|
|
356
358
|
<th scope="col" class="hide-sm">Next up</th>
|
|
@@ -362,9 +364,17 @@ function ModelsPanel({ pools }: { pools: ModelPool[] }): JSX.Element {
|
|
|
362
364
|
</tr>
|
|
363
365
|
</thead>
|
|
364
366
|
<tbody>
|
|
365
|
-
{pools.map((pool) => (
|
|
367
|
+
{providers.flatMap((group) => group.pools.length > 0 ? group.pools.map((pool) => (
|
|
366
368
|
<PoolRow key={pool.key} pool={pool} expanded={open === pool.key} onToggle={() => setOpen(open === pool.key ? null : pool.key)} />
|
|
367
|
-
))
|
|
369
|
+
)) : [
|
|
370
|
+
<tr key={group.provider}>
|
|
371
|
+
<th scope="row">{providerLabel(group.provider)}</th>
|
|
372
|
+
<td colSpan={6} class="muted">
|
|
373
|
+
{pluralize(group.accounts.length, "connected account")}
|
|
374
|
+
{" · Quota unavailable"}
|
|
375
|
+
</td>
|
|
376
|
+
</tr>
|
|
377
|
+
])}
|
|
368
378
|
</tbody>
|
|
369
379
|
</table>
|
|
370
380
|
</div>
|
|
@@ -393,9 +403,15 @@ function PoolRow({ pool, expanded, onToggle }: { pool: ModelPool; expanded: bool
|
|
|
393
403
|
</th>
|
|
394
404
|
<td data-label="Remaining">
|
|
395
405
|
<div class="pool-capacity">
|
|
396
|
-
<Meter value={pool.capacity} label={`${pool.name} pooled quota remaining`} />
|
|
406
|
+
<Meter value={pool.capacity} label={`${pool.name} pooled ${pool.credits ? "included credits" : "quota"} remaining`} />
|
|
397
407
|
<span class="num">{pool.capacity}%</span>
|
|
398
408
|
</div>
|
|
409
|
+
{pool.credits && (
|
|
410
|
+
<div class="cell-sub num">
|
|
411
|
+
{formatUsd(pool.credits.balanceUsd)} / {formatUsd(pool.credits.allowanceUsd)} included
|
|
412
|
+
{pool.credits.purchasedUsd > 0 && <> · {formatUsd(pool.credits.purchasedUsd)} purchased</>}
|
|
413
|
+
</div>
|
|
414
|
+
)}
|
|
399
415
|
<div class="cell-sub">
|
|
400
416
|
{pool.withQuota} of {pluralize(pool.members.length, "account")} with quota
|
|
401
417
|
</div>
|
package/src/web/pages/Usage.tsx
CHANGED
|
@@ -176,7 +176,7 @@ function TokenUsagePanel({
|
|
|
176
176
|
value={view.summary.peak.bar ? formatAxisTokens(view.summary.peak.value) : "—"}
|
|
177
177
|
sub={view.summary.peak.bar ? `per ${spec.per} · ${barTitle(view.summary.peak.bar, spec, nowMs)}` : "No traffic yet"}
|
|
178
178
|
/>
|
|
179
|
-
<Stat label="Est. savings" value={formatUsd(view.savings.totalUsd)} sub="
|
|
179
|
+
<Stat label="Est. savings" value={formatUsd(view.savings.totalUsd)} sub="standard list prices; excludes cache/off-peak discounts and plan costs" tone="ok" />
|
|
180
180
|
</div>
|
|
181
181
|
<TokenChart
|
|
182
182
|
bars={view.bars}
|
|
@@ -221,7 +221,7 @@ function TokenUsagePanel({
|
|
|
221
221
|
)}
|
|
222
222
|
{usage && (
|
|
223
223
|
<span class="muted">
|
|
224
|
-
All time: {formatCompact(usage.allTime.inputTokens + usage.allTime.outputTokens)} tokens · {formatCount(usage.allTime.requests)} requests · {formatUsd(usage.allTime.savingsUsd)}
|
|
224
|
+
All time: {formatCompact(usage.allTime.inputTokens + usage.allTime.outputTokens)} tokens · {formatCount(usage.allTime.requests)} requests · {formatUsd(usage.allTime.savingsUsd)} estimated list-price value
|
|
225
225
|
</span>
|
|
226
226
|
)}
|
|
227
227
|
{loading && <Spinner />}
|
|
@@ -293,7 +293,7 @@ function SavingsPanel({ usage }: { usage: UsageResponse | null }): JSX.Element {
|
|
|
293
293
|
return [...models];
|
|
294
294
|
}, [usage, bars]);
|
|
295
295
|
return (
|
|
296
|
-
<Panel title="Savings by model" subtitle={usage ? `In the ${RANGE_SPECS[usage.range].window}, at
|
|
296
|
+
<Panel title="Savings by model" subtitle={usage ? `In the ${RANGE_SPECS[usage.range].window}, at standard list prices, excluding cache/off-peak discounts and plan costs.` : undefined} flush>
|
|
297
297
|
{!usage ? (
|
|
298
298
|
<div class="panel-loading">
|
|
299
299
|
<Spinner />
|
package/src/web/state/api.ts
CHANGED
|
@@ -5,11 +5,18 @@ import type { AccountTier, Config, SpendLog, VirtualKey } from "../../types.js";
|
|
|
5
5
|
import type {
|
|
6
6
|
ActivityResponse,
|
|
7
7
|
DashboardSnapshot,
|
|
8
|
+
ModelCatalogResponse,
|
|
8
9
|
SessionInfo,
|
|
9
10
|
UsageRange,
|
|
10
11
|
UsageResponse,
|
|
11
12
|
} from "../../dashboard-types.js";
|
|
12
13
|
|
|
14
|
+
export interface EffortRouteBody {
|
|
15
|
+
alias: string;
|
|
16
|
+
defaultEffort: string;
|
|
17
|
+
targets: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
|
|
13
20
|
export class ApiError extends Error {
|
|
14
21
|
constructor(
|
|
15
22
|
readonly status: number,
|
|
@@ -179,6 +186,30 @@ export const api = {
|
|
|
179
186
|
deleteKey: (hash: string) => request("DELETE", `/api/keys/${enc(hash)}`),
|
|
180
187
|
models: () => request<{ ok: true; data: ModelCatalogEntry[] }>("GET", "/api/models"),
|
|
181
188
|
|
|
189
|
+
catalog: () => request<ModelCatalogResponse>("GET", "/api/catalog"),
|
|
190
|
+
refreshCatalog: () => request<ModelCatalogResponse>("POST", "/api/catalog/refresh"),
|
|
191
|
+
setProviderEnabled: (id: string, on: boolean) =>
|
|
192
|
+
request<ModelCatalogResponse>("POST", `/api/catalog/providers/${enc(id)}/${on ? "on" : "off"}`),
|
|
193
|
+
setProviderOrder: (order: string[]) =>
|
|
194
|
+
request<ModelCatalogResponse>("PUT", "/api/catalog/provider-order", { order }),
|
|
195
|
+
/** Keys are "<provider>/<model>". */
|
|
196
|
+
setModelsEnabled: (models: string[], on: boolean) =>
|
|
197
|
+
request<ModelCatalogResponse>("POST", `/api/catalog/models/${on ? "on" : "off"}`, { models }),
|
|
198
|
+
setAutoEnableNewModels: (on: boolean) =>
|
|
199
|
+
request<ModelCatalogResponse>("POST", `/api/catalog/new-models/${on ? "on" : "off"}`),
|
|
200
|
+
setAccountProviderEnabled: (accountId: string, providerId: string, on: boolean) =>
|
|
201
|
+
request<ModelCatalogResponse>(
|
|
202
|
+
"POST",
|
|
203
|
+
`/api/catalog/accounts/${enc(accountId)}/${enc(providerId)}/${on ? "on" : "off"}`,
|
|
204
|
+
),
|
|
205
|
+
/** A refused change throws ApiError whose body is an EffortRouteErrorResponse. */
|
|
206
|
+
createEffortRoute: (route: EffortRouteBody) =>
|
|
207
|
+
request<ModelCatalogResponse>("POST", "/api/catalog/effort-routes", route),
|
|
208
|
+
updateEffortRoute: (alias: string, route: EffortRouteBody) =>
|
|
209
|
+
request<ModelCatalogResponse>("PUT", `/api/catalog/effort-routes/${enc(alias)}`, route),
|
|
210
|
+
deleteEffortRoute: (alias: string) =>
|
|
211
|
+
request<ModelCatalogResponse>("DELETE", `/api/catalog/effort-routes/${enc(alias)}`),
|
|
212
|
+
|
|
182
213
|
spendLogs: (q: SpendQuery) =>
|
|
183
214
|
request<{ ok: true; logs: SpendLog[]; total: number; summary: SpendSummary }>(
|
|
184
215
|
"GET",
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { effect, signal, type ReadonlySignal } from "@preact/signals";
|
|
2
|
+
import type { DashboardAccount, ModelCatalogResponse } from "../../dashboard-types.js";
|
|
3
|
+
|
|
4
|
+
/** The live fields that can change the Models catalog or its chosen provider. */
|
|
5
|
+
export interface CatalogRoutingState {
|
|
6
|
+
accounts: Array<Pick<DashboardAccount, "email" | "provider" | "status" | "disabledProviders" | "invalidProviders"> & { id?: string }>;
|
|
7
|
+
modelCatalogRevision?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function routingSignature(state: CatalogRoutingState): string {
|
|
11
|
+
const accounts = state.accounts.map((account) => [
|
|
12
|
+
account.id ?? account.email,
|
|
13
|
+
account.provider.split("+").sort(),
|
|
14
|
+
account.status === "disabled" || account.status === "flagged" || account.status === "off",
|
|
15
|
+
[...(account.disabledProviders ?? [])].sort(),
|
|
16
|
+
Object.keys(account.invalidProviders ?? {}).filter((id) => Boolean(account.invalidProviders?.[id])).sort(),
|
|
17
|
+
]);
|
|
18
|
+
// Ordering, activity, quotas and countdowns do not change catalog routing.
|
|
19
|
+
accounts.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
|
|
20
|
+
return JSON.stringify([state.modelCatalogRevision, accounts]);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Kept across visits by ModelsPage; owns catalog reads and mutations. */
|
|
24
|
+
export function createModelCatalogState(fetchCatalog: () => Promise<ModelCatalogResponse>) {
|
|
25
|
+
const catalog = signal<ModelCatalogResponse | null>(null);
|
|
26
|
+
const catalogError = signal<string | null>(null);
|
|
27
|
+
let readVersion = 0;
|
|
28
|
+
let loadRequested = false;
|
|
29
|
+
let loading: Promise<void> | null = null;
|
|
30
|
+
let mutationTail = Promise.resolve();
|
|
31
|
+
let pendingMutations = 0;
|
|
32
|
+
|
|
33
|
+
function loadCatalog(): Promise<void> {
|
|
34
|
+
readVersion++;
|
|
35
|
+
loadRequested = true;
|
|
36
|
+
if (loading) return loading;
|
|
37
|
+
|
|
38
|
+
loading = Promise.resolve().then(async () => {
|
|
39
|
+
try {
|
|
40
|
+
while (loadRequested) {
|
|
41
|
+
// A refresh requested during a mutation reads its committed result.
|
|
42
|
+
while (pendingMutations > 0) await mutationTail;
|
|
43
|
+
loadRequested = false;
|
|
44
|
+
const version = readVersion;
|
|
45
|
+
try {
|
|
46
|
+
const next = await fetchCatalog();
|
|
47
|
+
if (version === readVersion && pendingMutations === 0) {
|
|
48
|
+
catalog.value = next;
|
|
49
|
+
catalogError.value = null;
|
|
50
|
+
}
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (version === readVersion && pendingMutations === 0) {
|
|
53
|
+
catalogError.value = err instanceof Error ? err.message : String(err);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
} finally {
|
|
58
|
+
loading = null;
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
return loading;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function change(fn: () => Promise<ModelCatalogResponse | null>): Promise<void> {
|
|
65
|
+
// Invalidate older GETs as soon as the action is queued, not after it ends.
|
|
66
|
+
readVersion++;
|
|
67
|
+
pendingMutations++;
|
|
68
|
+
const operation = mutationTail.then(async () => {
|
|
69
|
+
try {
|
|
70
|
+
const next = await fn();
|
|
71
|
+
if (next) {
|
|
72
|
+
catalog.value = next;
|
|
73
|
+
catalogError.value = null;
|
|
74
|
+
}
|
|
75
|
+
} finally {
|
|
76
|
+
pendingMutations--;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
// One request finishes before the next is sent; failures cannot block it.
|
|
80
|
+
mutationTail = operation.catch(() => {});
|
|
81
|
+
return operation;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function watchRouting(source: ReadonlySignal<CatalogRoutingState | null>, focusTarget?: EventTarget): () => void {
|
|
85
|
+
let previous: string | undefined;
|
|
86
|
+
const stop = effect(() => {
|
|
87
|
+
const current = source.value;
|
|
88
|
+
if (!current) return;
|
|
89
|
+
const signature = routingSignature(current);
|
|
90
|
+
if (signature === previous) return;
|
|
91
|
+
previous = signature;
|
|
92
|
+
void loadCatalog();
|
|
93
|
+
});
|
|
94
|
+
const onFocus = () => void loadCatalog();
|
|
95
|
+
focusTarget?.addEventListener("focus", onFocus);
|
|
96
|
+
return () => {
|
|
97
|
+
stop();
|
|
98
|
+
focusTarget?.removeEventListener("focus", onFocus);
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { catalog, catalogError, loadCatalog, change, watchRouting };
|
|
103
|
+
}
|
package/src/web/state/router.ts
CHANGED
|
@@ -5,15 +5,19 @@ import { computed, signal } from "@preact/signals";
|
|
|
5
5
|
|
|
6
6
|
export const BASE = "/dashboard";
|
|
7
7
|
|
|
8
|
-
export type PageId = "overview" | "accounts" | "requests" | "usage" | "keys" | "settings";
|
|
8
|
+
export type PageId = "overview" | "accounts" | "models" | "requests" | "usage" | "keys" | "settings";
|
|
9
9
|
|
|
10
10
|
export interface RouteMatch {
|
|
11
11
|
page: PageId | "not-found";
|
|
12
12
|
/** Email of the account whose drawer is open. */
|
|
13
13
|
account: string | null;
|
|
14
|
+
/** Id of the provider whose drawer is open on the Models page. */
|
|
15
|
+
provider: string | null;
|
|
16
|
+
/** Effort route editor on the Models page; alias null while creating one. */
|
|
17
|
+
effort: { alias: string | null } | null;
|
|
14
18
|
}
|
|
15
19
|
|
|
16
|
-
interface LocationState {
|
|
20
|
+
export interface LocationState {
|
|
17
21
|
path: string;
|
|
18
22
|
search: string;
|
|
19
23
|
}
|
|
@@ -24,29 +28,115 @@ function readLocation(): LocationState {
|
|
|
24
28
|
|
|
25
29
|
export const location = signal<LocationState>(readLocation());
|
|
26
30
|
|
|
31
|
+
/**
|
|
32
|
+
* Asked before navigation would lose something, such as an editor's unsaved
|
|
33
|
+
* changes. The target is null when the page itself is leaving (reload, close).
|
|
34
|
+
*/
|
|
35
|
+
export interface NavigationGuard {
|
|
36
|
+
blocks(target: LocationState | null): boolean;
|
|
37
|
+
/** Whether to leave anyway. */
|
|
38
|
+
confirm(): Promise<boolean>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let guard: NavigationGuard | null = null;
|
|
42
|
+
let asking = false;
|
|
43
|
+
|
|
44
|
+
/** Guard navigation until the returned function is called. */
|
|
45
|
+
export function guardNavigation(next: NavigationGuard): () => void {
|
|
46
|
+
guard = next;
|
|
47
|
+
return () => {
|
|
48
|
+
if (guard === next) guard = null;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function blocked(target: LocationState | null): boolean {
|
|
53
|
+
return guard?.blocks(target) ?? false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function askToLeave(leave: () => void): Promise<void> {
|
|
57
|
+
const current = guard;
|
|
58
|
+
if (!current || asking) return;
|
|
59
|
+
asking = true;
|
|
60
|
+
try {
|
|
61
|
+
if (await current.confirm()) leave();
|
|
62
|
+
} finally {
|
|
63
|
+
asking = false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Each history entry the router adds records its position (the first one has
|
|
68
|
+
// none and counts as 0), so a Back or Forward the guard blocks can be undone
|
|
69
|
+
// with history.go() without dropping entries.
|
|
70
|
+
function readPosition(): number {
|
|
71
|
+
const state = window.history.state as { position?: unknown } | null | undefined;
|
|
72
|
+
return typeof state?.position === "number" ? state.position : 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let position = readPosition();
|
|
76
|
+
// Traversals the router makes itself: undoing a blocked one, then redoing it
|
|
77
|
+
// once the user chooses to leave. A redo chosen before the undo lands waits
|
|
78
|
+
// for it, because browsers mishandle a traversal started while another is on
|
|
79
|
+
// its way. Chromium drops it and Firefox runs it first, which leaves the
|
|
80
|
+
// editor open, and WebKit counts it from the wrong entry.
|
|
81
|
+
let undoing = false;
|
|
82
|
+
let redoing = false;
|
|
83
|
+
// A redo chosen before the undo landed, as a history.go() delta.
|
|
84
|
+
let redoAfterUndo = 0;
|
|
85
|
+
|
|
86
|
+
function redo(delta: number): void {
|
|
87
|
+
if (undoing) {
|
|
88
|
+
redoAfterUndo = delta;
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
redoing = true;
|
|
92
|
+
window.history.go(delta);
|
|
93
|
+
}
|
|
94
|
+
|
|
27
95
|
window.addEventListener("popstate", () => {
|
|
96
|
+
const from = position;
|
|
97
|
+
position = readPosition();
|
|
98
|
+
if (undoing) {
|
|
99
|
+
undoing = false;
|
|
100
|
+
if (redoAfterUndo !== 0) redo(redoAfterUndo);
|
|
101
|
+
redoAfterUndo = 0;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const delta = from - position;
|
|
105
|
+
if (!redoing && delta !== 0 && (asking || blocked(readLocation()))) {
|
|
106
|
+
undoing = true;
|
|
107
|
+
window.history.go(delta);
|
|
108
|
+
void askToLeave(() => redo(-delta));
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
redoing = false;
|
|
28
112
|
location.value = readLocation();
|
|
29
113
|
});
|
|
30
114
|
|
|
115
|
+
window.addEventListener("beforeunload", (event) => {
|
|
116
|
+
if (blocked(null)) event.preventDefault();
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
function decodeSegment(segment: string | undefined): string | null {
|
|
120
|
+
if (!segment) return null;
|
|
121
|
+
try {
|
|
122
|
+
return decodeURIComponent(segment);
|
|
123
|
+
} catch {
|
|
124
|
+
return segment;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
31
128
|
export function matchRoute(path: string): RouteMatch {
|
|
32
129
|
const rest = path.replace(/\/+$/, "").slice(BASE.length).split("/").filter(Boolean);
|
|
33
|
-
const [head, second] = rest;
|
|
34
|
-
|
|
35
|
-
if (head
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
account = decodeURIComponent(second);
|
|
40
|
-
} catch {
|
|
41
|
-
account = second;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return { page: "accounts", account };
|
|
45
|
-
}
|
|
130
|
+
const [head, second, third] = rest;
|
|
131
|
+
const none = { account: null, provider: null, effort: null };
|
|
132
|
+
if (!head) return { ...none, page: "overview" };
|
|
133
|
+
if (head === "accounts") return { ...none, page: "accounts", account: decodeSegment(second) };
|
|
134
|
+
if (head === "models" && second === "effort") return { ...none, page: "models", effort: { alias: decodeSegment(third) } };
|
|
135
|
+
if (head === "models") return { ...none, page: "models", provider: decodeSegment(second) };
|
|
46
136
|
if (head === "requests" || head === "usage" || head === "keys" || head === "settings") {
|
|
47
|
-
return { page: head
|
|
137
|
+
return { ...none, page: head };
|
|
48
138
|
}
|
|
49
|
-
return { page: "not-found"
|
|
139
|
+
return { ...none, page: "not-found" };
|
|
50
140
|
}
|
|
51
141
|
|
|
52
142
|
export const route = computed(() => matchRoute(location.value.path));
|
|
@@ -56,10 +146,24 @@ export function navigate(to: string, options: { replace?: boolean } = {}): void
|
|
|
56
146
|
const target = new URL(to, window.location.origin);
|
|
57
147
|
const next = target.pathname + target.search;
|
|
58
148
|
if (next === window.location.pathname + window.location.search) return;
|
|
149
|
+
if (blocked({ path: target.pathname, search: target.search })) {
|
|
150
|
+
void askToLeave(() => go(target, options.replace ?? false));
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
go(target, options.replace ?? false);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function go(target: URL, replace: boolean): void {
|
|
157
|
+
const next = target.pathname + target.search;
|
|
59
158
|
const pathChanged = target.pathname !== window.location.pathname;
|
|
60
|
-
window.history
|
|
159
|
+
if (replace) window.history.replaceState({ position }, "", next);
|
|
160
|
+
else {
|
|
161
|
+
position += 1;
|
|
162
|
+
window.history.pushState({ position }, "", next);
|
|
163
|
+
}
|
|
61
164
|
location.value = readLocation();
|
|
62
|
-
|
|
165
|
+
const match = matchRoute(target.pathname);
|
|
166
|
+
if (pathChanged && !match.account && !match.provider && !match.effort) {
|
|
63
167
|
// Pages scroll inside the canvas, not the window.
|
|
64
168
|
document.getElementById("main")?.scrollTo(0, 0);
|
|
65
169
|
window.scrollTo(0, 0);
|
|
@@ -81,6 +185,33 @@ export function accountPath(email: string): string {
|
|
|
81
185
|
return `${BASE}/accounts/${encodeURIComponent(email)}`;
|
|
82
186
|
}
|
|
83
187
|
|
|
188
|
+
export function providerPath(providerId: string): string {
|
|
189
|
+
const search = route.value.page === "models" ? location.value.search : "";
|
|
190
|
+
return `${BASE}/models/${encodeURIComponent(providerId)}${search}`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The effort route editor, keeping the Models filters. With no alias it
|
|
195
|
+
* creates one, prefilled from the suggested family `from` when given.
|
|
196
|
+
*/
|
|
197
|
+
export function effortPath(alias: string | null, from?: string): string {
|
|
198
|
+
const search = new URLSearchParams(route.value.page === "models" ? location.value.search : "");
|
|
199
|
+
search.delete("from");
|
|
200
|
+
if (alias === null && from) search.set("from", from);
|
|
201
|
+
const text = search.toString();
|
|
202
|
+
return `${BASE}/models/effort${alias === null ? "" : `/${encodeURIComponent(alias)}`}${text ? `?${text}` : ""}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Which effort editor a location opens, or null for none. The editor keeps
|
|
207
|
+
* its draft only while this stays the same.
|
|
208
|
+
*/
|
|
209
|
+
export function effortEditorKey(target: LocationState): string | null {
|
|
210
|
+
const effort = matchRoute(target.path).effort;
|
|
211
|
+
if (!effort) return null;
|
|
212
|
+
return effort.alias ?? `new:${new URLSearchParams(target.search).get("from") ?? ""}`;
|
|
213
|
+
}
|
|
214
|
+
|
|
84
215
|
/** Legacy routes from the old dashboard. */
|
|
85
216
|
export function redirectLegacyRoutes(): void {
|
|
86
217
|
const { pathname, search } = window.location;
|
package/src/web/state/store.ts
CHANGED
|
@@ -91,13 +91,13 @@ export function applySnapshot(snapshot: DashboardSnapshot): void {
|
|
|
91
91
|
function applyAccounts(patch: AccountsPatch): void {
|
|
92
92
|
const current = overview.value;
|
|
93
93
|
if (!current) return;
|
|
94
|
-
const
|
|
95
|
-
for (const
|
|
96
|
-
for (const account of patch.upsert)
|
|
97
|
-
const order = patch.order ?? current.accounts.map((a) => a.email).filter((
|
|
94
|
+
const byId = new Map(current.accounts.map((a) => [a.id ?? a.email, a]));
|
|
95
|
+
for (const id of patch.remove) byId.delete(id);
|
|
96
|
+
for (const account of patch.upsert) byId.set(account.id ?? account.email, account);
|
|
97
|
+
const order = patch.order ?? current.accounts.map((a) => a.id ?? a.email).filter((id) => byId.has(id));
|
|
98
98
|
const seen = new Set(order);
|
|
99
|
-
const next = order.map((
|
|
100
|
-
for (const [
|
|
99
|
+
const next = order.map((id) => byId.get(id)).filter((a): a is DashboardAccount => Boolean(a));
|
|
100
|
+
for (const [id, account] of byId) if (!seen.has(id)) next.push(account);
|
|
101
101
|
overview.value = { ...current, accounts: next };
|
|
102
102
|
}
|
|
103
103
|
|