tuxevil-rotator 4.1.0 → 4.2.1

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.
@@ -31,7 +31,7 @@ import { providerLabel, type Tone } from "../lib/status.js";
31
31
  import { run } from "../state/actions.js";
32
32
  import { api } from "../state/api.js";
33
33
  import { createModelCatalogState } from "../state/model-catalog.js";
34
- import { accountPath, BASE, navigate, providerPath, query, route, setQuery } from "../state/router.js";
34
+ import { accountPath, BASE, effortPath, navigate, providerPath, query, route, setQuery } from "../state/router.js";
35
35
  import { masker, now, overview } from "../state/store.js";
36
36
  import { Icon } from "../components/icons.js";
37
37
  import { Drawer, Menu } from "../components/overlays.js";
@@ -50,6 +50,7 @@ import {
50
50
  StatusPill,
51
51
  Switch,
52
52
  } from "../components/ui.js";
53
+ import { EffortRouteDrawer, EffortRoutingPanel } from "./EffortRouting.js";
53
54
  import { openAddAccount } from "./shared.js";
54
55
 
55
56
  const catalogState = createModelCatalogState(() => api.catalog());
@@ -142,7 +143,9 @@ export function ModelsPage(): JSX.Element {
142
143
  }
143
144
 
144
145
  const closeDrawer = () => {
145
- const back = query.value.toString();
146
+ const params = new URLSearchParams(query.value);
147
+ params.delete("from");
148
+ const back = params.toString();
146
149
  navigate(`${BASE}/models${back ? `?${back}` : ""}`);
147
150
  };
148
151
  const drawerSummary = providers.find((summary) => summary.provider.id === drawerId) ?? null;
@@ -152,6 +155,7 @@ export function ModelsPage(): JSX.Element {
152
155
  {header}
153
156
  <ModelStats state={state} providers={providers} />
154
157
  <ProvidersPanel state={state} providers={providers} />
158
+ <EffortRoutingPanel state={state} change={change} />
155
159
  <ModelsPanel state={state} />
156
160
  <Drawer open={Boolean(drawerId)} onClose={closeDrawer} label="Provider details">
157
161
  {drawerId &&
@@ -169,6 +173,13 @@ export function ModelsPage(): JSX.Element {
169
173
  </div>
170
174
  ))}
171
175
  </Drawer>
176
+ <EffortRouteDrawer
177
+ state={state}
178
+ match={route.value.effort}
179
+ change={change}
180
+ commit={(fn) => catalogState.change(fn)}
181
+ onClose={closeDrawer}
182
+ />
172
183
  </>
173
184
  );
174
185
  }
@@ -505,7 +516,14 @@ function ModelsPanel({ state }: { state: ModelCatalogResponse }): JSX.Element {
505
516
  </thead>
506
517
  <tbody>
507
518
  {visible.map((row) => (
508
- <ModelRows key={row.key} row={row} names={names} open={open.has(row.key)} onToggleOpen={() => toggleOpen(row.key)} />
519
+ <ModelRows
520
+ key={row.key}
521
+ row={row}
522
+ names={names}
523
+ open={open.has(row.key)}
524
+ onToggleOpen={() => toggleOpen(row.key)}
525
+ effortListed={row.effortRoute ? state.effortRoutes.some((entry) => entry.alias === row.effortRoute!.alias && entry.listed) : false}
526
+ />
509
527
  ))}
510
528
  </tbody>
511
529
  </table>
@@ -539,11 +557,14 @@ function ModelRows({
539
557
  names,
540
558
  open,
541
559
  onToggleOpen,
560
+ effortListed = false,
542
561
  }: {
543
562
  row: ModelRow;
544
563
  names: Record<string, string>;
545
564
  open: boolean;
546
565
  onToggleOpen: () => void;
566
+ /** The effort-routed ID that uses this model is listed, which hides the model from /v1/models. */
567
+ effortListed?: boolean;
547
568
  }): JSX.Element {
548
569
  // Offerings whose provider is on; the row switch acts on those.
549
570
  const switchable = row.offerings.filter((entry) => entry.offReason !== "provider");
@@ -571,8 +592,23 @@ function ModelRows({
571
592
  <span class="model-id">{row.id}</span>
572
593
  {row.shared && <span class="tag tag-accent">Shared</span>}
573
594
  {row.waiting && <span class="tag tag-info">Waiting for review</span>}
595
+ {row.effortRoute && <span class="tag tag-accent">Effort · {row.effortRoute.effort}</span>}
574
596
  </div>
575
597
  {sub && <div class="cell-sub">{sub}</div>}
598
+ {row.effortRoute && (
599
+ <div class="cell-sub">
600
+ Called as{" "}
601
+ <Link href={effortPath(row.effortRoute.alias)} class="effort-inline-link">
602
+ {row.effortRoute.alias}
603
+ </Link>
604
+ {effortListed && (
605
+ <>
606
+ {" "}
607
+ · hidden from <code>/v1/models</code>
608
+ </>
609
+ )}
610
+ </div>
611
+ )}
576
612
  </th>
577
613
  <td>
578
614
  <ServedBy row={row} names={names} />
@@ -11,6 +11,12 @@ import type {
11
11
  UsageResponse,
12
12
  } from "../../dashboard-types.js";
13
13
 
14
+ export interface EffortRouteBody {
15
+ alias: string;
16
+ defaultEffort: string;
17
+ targets: Record<string, string>;
18
+ }
19
+
14
20
  export class ApiError extends Error {
15
21
  constructor(
16
22
  readonly status: number,
@@ -196,6 +202,13 @@ export const api = {
196
202
  "POST",
197
203
  `/api/catalog/accounts/${enc(accountId)}/${enc(providerId)}/${on ? "on" : "off"}`,
198
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)}`),
199
212
 
200
213
  spendLogs: (q: SpendQuery) =>
201
214
  request<{ ok: true; logs: SpendLog[]; total: number; summary: SpendSummary }>(
@@ -13,9 +13,11 @@ export interface RouteMatch {
13
13
  account: string | null;
14
14
  /** Id of the provider whose drawer is open on the Models page. */
15
15
  provider: string | null;
16
+ /** Effort route editor on the Models page; alias null while creating one. */
17
+ effort: { alias: string | null } | null;
16
18
  }
17
19
 
18
- interface LocationState {
20
+ export interface LocationState {
19
21
  path: string;
20
22
  search: string;
21
23
  }
@@ -26,10 +28,94 @@ function readLocation(): LocationState {
26
28
 
27
29
  export const location = signal<LocationState>(readLocation());
28
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
+
29
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;
30
112
  location.value = readLocation();
31
113
  });
32
114
 
115
+ window.addEventListener("beforeunload", (event) => {
116
+ if (blocked(null)) event.preventDefault();
117
+ });
118
+
33
119
  function decodeSegment(segment: string | undefined): string | null {
34
120
  if (!segment) return null;
35
121
  try {
@@ -41,14 +127,16 @@ function decodeSegment(segment: string | undefined): string | null {
41
127
 
42
128
  export function matchRoute(path: string): RouteMatch {
43
129
  const rest = path.replace(/\/+$/, "").slice(BASE.length).split("/").filter(Boolean);
44
- const [head, second] = rest;
45
- if (!head) return { page: "overview", account: null, provider: null };
46
- if (head === "accounts") return { page: "accounts", account: decodeSegment(second), provider: null };
47
- if (head === "models") return { page: "models", account: null, provider: decodeSegment(second) };
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) };
48
136
  if (head === "requests" || head === "usage" || head === "keys" || head === "settings") {
49
- return { page: head, account: null, provider: null };
137
+ return { ...none, page: head };
50
138
  }
51
- return { page: "not-found", account: null, provider: null };
139
+ return { ...none, page: "not-found" };
52
140
  }
53
141
 
54
142
  export const route = computed(() => matchRoute(location.value.path));
@@ -58,11 +146,24 @@ export function navigate(to: string, options: { replace?: boolean } = {}): void
58
146
  const target = new URL(to, window.location.origin);
59
147
  const next = target.pathname + target.search;
60
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;
61
158
  const pathChanged = target.pathname !== window.location.pathname;
62
- window.history[options.replace ? "replaceState" : "pushState"](null, "", next);
159
+ if (replace) window.history.replaceState({ position }, "", next);
160
+ else {
161
+ position += 1;
162
+ window.history.pushState({ position }, "", next);
163
+ }
63
164
  location.value = readLocation();
64
165
  const match = matchRoute(target.pathname);
65
- if (pathChanged && !match.account && !match.provider) {
166
+ if (pathChanged && !match.account && !match.provider && !match.effort) {
66
167
  // Pages scroll inside the canvas, not the window.
67
168
  document.getElementById("main")?.scrollTo(0, 0);
68
169
  window.scrollTo(0, 0);
@@ -89,6 +190,28 @@ export function providerPath(providerId: string): string {
89
190
  return `${BASE}/models/${encodeURIComponent(providerId)}${search}`;
90
191
  }
91
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
+
92
215
  /** Legacy routes from the old dashboard. */
93
216
  export function redirectLegacyRoutes(): void {
94
217
  const { pathname, search } = window.location;