Public: anyone can read this; the crew can change it.
The crew falls back to the capped key when every plan's window is full, and Settings → Crew shows and steers it #17168
Merged 33h 28m ago, live in production
crew/key-fallback → main 0 commits 1 thread · 1 unresolved
26 files
changed +874
−144
- docs/features/crew-fallback.md
- src/actions/capacity.ts
- src/actions/model_review.ts
- src/core/capacity.ts
- src/core/subscriptions.ts
- src/crew/dispatch.ts
- src/crew/key_fallback.ts
- src/crew/run_limits.ts
- src/crew/run_spend.ts
- src/crew/week_read.ts
- src/generated/screens.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/settings/limits.ts
- src/tui/screens/crewbudgets.ts
- src/tui/screens/crewfallback.ts
- src/web/pages/capacity.ts
- src/web/pages/crew.ts
- src/web/studio/crew_fallback.ts
- test/capacity-first-view.test.ts
- test/crew-key-fallback.test.ts
- test/palette-roster.test.ts
- test/settings-visible.test.ts
- test/subscriptions.test.ts
- test/usage.test.ts
docs/features/crew-fallback.md added +26
| @@ -0,0 +1,26 @@ | ||
| 1 | --- | |
| 2 | topic: Bring your own AI | |
| 3 | row: The crew's metered fallback: a capped key takes over when every plan's window is full | |
| 4 | --- | |
| 5 | # The crew's metered fallback | |
| 6 | ||
| 7 | When every subscription the crew runs on is full, the crew can keep going on a pay-per-token key | |
| 8 | instead of waiting, and you watch and steer it from **Settings → Crew → Metered fallback** or the | |
| 9 | terminal's **Metered fallback** (palette). | |
| 10 | ||
| 11 | - **When it takes over.** A plan counts as full for the crew when its 5-hour or weekly window, | |
| 12 | as the provider last measured it, has no more free than the share you keep for people | |
| 13 | (Subscriptions → kept for people). A crew run's pick passes a full plan over and takes a | |
| 14 | pay-per-token key, one with a cap before one without, while the fallback is on. Reviews start | |
| 15 | first while it does: they are cheap and they land work. A person's Talk turn weighs none of | |
| 16 | this. On a forge with no plan at all, keys are simply what the crew runs on. | |
| 17 | (`crew/key_fallback.ts`, `pickSubscription` with `CrewPick` in `core/subscriptions.ts`.) | |
| 18 | - **What you see.** One plain line: what the crew runs on now, or what it waits for ("The | |
| 19 | fallback is off: reviews wait for espo-corp's window, resets 21:30 UTC."). The capped key's | |
| 20 | spend today, this week and against its cap, as a meter, at list price. Which account each | |
| 21 | running and recent crew run used. The key itself is never shown. | |
| 22 | - **What you control.** The switch (`crew.fallback`, off until the owner turns it on, so a forge never spends on a key by default; Settings → Capacity lists it | |
| 23 | with its reason and history; `space` in the terminal). The cap, edited in place with what it | |
| 24 | would last at the last seven days' pace; after a change an **Undo** beside it (`u` in the | |
| 25 | terminal) puts back the cap it had. At its cap the key takes nothing, and runs wait for the | |
| 26 | first window to reset. |
src/actions/capacity.ts +1 −1
| @@ -59,7 +59,7 @@ export const SETTABLE_CAPACITY = [ | ||
| 59 | 59 | * them as its four tables, and the terminal names each row's group the same way. |
| 60 | 60 | */ |
| 61 | 61 | export const CAPACITY_GROUPS: readonly { readonly title: string; readonly keys: readonly CapacityKey[] }[] = [ |
| 62 | { title: "Crew", keys: ["crew.concurrency", "pace.floor", "week.use", "issue.maxBoxes", "issue.maxChars"] }, | |
| 62 | { title: "Crew", keys: ["crew.concurrency", "pace.floor", "week.use", "issue.maxBoxes", "issue.maxChars", "crew.fallback"] }, | |
| 63 | 63 | { title: "Checks", keys: ["checks.concurrency", "checks.shards", "checks.verifyShards", "queue.batch", "queue.depth", "cells.servingCores"] }, |
| 64 | 64 | { |
| 65 | 65 | title: "Hosted forges", |
src/actions/model_review.ts +4 −6
| @@ -28,14 +28,12 @@ import { | ||
| 28 | 28 | } from "../core/model_review.ts"; |
| 29 | 29 | import type { User } from "../core/users.ts"; |
| 30 | 30 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 31 | import { limitValue } from "../settings/limits.ts"; | |
| 31 | import { limitValues } from "../settings/limits.ts"; | |
| 32 | 32 | |
| 33 | 33 | export function reviewLimits(app: App): Limits & { auto: boolean } { |
| 34 | return { | |
| 35 | minLanded: limitValue(app.db, "model_review.min_landed"), | |
| 36 | slackPct: limitValue(app.db, "model_review.slack_pct"), | |
| 37 | auto: limitValue(app.db, "model_review.auto") === 1, | |
| 38 | }; | |
| 34 | // One read of the three, as the crew page shows them together. | |
| 35 | const v = limitValues(app.db, ["model_review.min_landed", "model_review.slack_pct", "model_review.auto"]); | |
| 36 | return { minLanded: v["model_review.min_landed"], slackPct: v["model_review.slack_pct"], auto: v["model_review.auto"] === 1 }; | |
| 39 | 37 | } |
| 40 | 38 | |
| 41 | 39 | const empty = (model: string): ModelStats => ({ |
src/core/capacity.ts +11 −1
| @@ -39,7 +39,8 @@ export type CapacityKey = | ||
| 39 | 39 | | "signin.edge" |
| 40 | 40 | | "pace.floor" |
| 41 | 41 | | "issue.maxBoxes" |
| 42 | | "issue.maxChars"; | |
| 42 | | "issue.maxChars" | |
| 43 | | "crew.fallback"; | |
| 43 | 44 | |
| 44 | 45 | interface Definition { |
| 45 | 46 | /** What the settings page and the API call it. */ |
| @@ -235,6 +236,15 @@ export const CAPACITY: Record<CapacityKey, Definition> = { | ||
| 235 | 236 | reason: "A long issue is a big change, and big changes fail more often, so the planner splits it first.", |
| 236 | 237 | help: "An open issue whose body is longer than this is held and handed to the planner to split before a builder starts it, once. A person's ask is split, never dropped. Read on every pick.", |
| 237 | 238 | }, |
| 239 | "crew.fallback": { | |
| 240 | label: "Metered fallback for the crew", | |
| 241 | env: "", | |
| 242 | kind: { type: "choice", values: ["on", "off"] }, | |
| 243 | // Off until the owner says on: a forge never spends its owner's money by default. | |
| 244 | fallback: "off", | |
| 245 | reason: "With every plan's window full, the crew can go on with a capped pay-per-token key rather than wait.", | |
| 246 | help: "On: crew runs, reviews first, use a pay-per-token key until its cap. Off: they wait for a window to reset. Spend and cap: the Crew settings page.", | |
| 247 | }, | |
| 238 | 248 | }; |
| 239 | 249 | |
| 240 | 250 | export const CAPACITY_KEYS = Object.keys(CAPACITY) as CapacityKey[]; |
src/core/subscriptions.ts +57 −3
| @@ -32,6 +32,8 @@ import { err, ok, type Result } from "../kernel/result.ts"; | ||
| 32 | 32 | import { open, seal } from "../kernel/secret.ts"; |
| 33 | 33 | import { accountEnv, envNameOf, runnerCredentialInEnv } from "../crew/runner_env.ts"; |
| 34 | 34 | import { limitValue } from "../settings/limits.ts"; |
| 35 | import { measureFor } from "./measure.ts"; | |
| 36 | import { getHeadroom, type LimitWindow } from "./standing.ts"; | |
| 35 | 37 | |
| 36 | 38 | export type SubscriptionKind = "oauth" | "api_key"; |
| 37 | 39 | |
| @@ -722,6 +724,30 @@ function candidates(db: Database, scope: PickScope, runId: string): CandidateRow | ||
| 722 | 724 | return rows.filter((r) => !seen.has(r.id) && seen.add(r.id) !== undefined); |
| 723 | 725 | } |
| 724 | 726 | |
| 727 | /** | |
| 728 | * A plan's window the crew may not draw on now: measured and not yet reset, with no more free than | |
| 729 | * the share its admin keeps for people (`headroom_pct`). A key has no windows. | |
| 730 | */ | |
| 731 | export function crewWindowFull(db: Database, subscriptionId: string, now: Date): { window: LimitWindow; resetsAt: string } | undefined { | |
| 732 | const kept = getHeadroom(db, subscriptionId) ?? 0; | |
| 733 | for (const window of ["5h", "week"] as const) { | |
| 734 | const m = measureFor(db, subscriptionId, window, now); | |
| 735 | if (m !== null && 100 - m.usedPct <= kept) return { window, resetsAt: m.resetsAt }; | |
| 736 | } | |
| 737 | return undefined; | |
| 738 | } | |
| 739 | ||
| 740 | /** | |
| 741 | * What a crew run's pick weighs beside where it may run (`crew/key_fallback.ts`): a plan whose | |
| 742 | * window is full is passed over, and where there are plans a pay-per-token key takes crew runs | |
| 743 | * only as the metered fallback, while it is on (`crew.fallback`), a key with a cap before one | |
| 744 | * without. Where there is no plan, keys are what the crew runs on, as before. A person's turn | |
| 745 | * (Talk) weighs neither. | |
| 746 | */ | |
| 747 | export interface CrewPick { | |
| 748 | readonly fallback: boolean; | |
| 749 | } | |
| 750 | ||
| 725 | 751 | /** Less than `MIN_RUN_USD` left on its whole-life budget. */ |
| 726 | 752 | export const budgetSpent = (r: { budget_usd: number | null; spent_usd: number }): boolean => |
| 727 | 753 | r.budget_usd !== null && r.budget_usd - r.spent_usd < MIN_RUN_USD; |
| @@ -737,9 +763,37 @@ export function pickSubscription( | ||
| 737 | 763 | scope: PickScope, |
| 738 | 764 | now: Date, |
| 739 | 765 | reserve?: { readonly runId: string; readonly usd: number }, |
| 766 | crew?: CrewPick, | |
| 740 | 767 | ): Pick { |
| 741 | const rows = candidates(db, scope, reserve?.runId ?? ""); | |
| 742 | if (rows.length === 0) return ownerIsAdmin(db, scope.ownerId) ? { kind: "env" } : { kind: "none" }; | |
| 768 | const all = candidates(db, scope, reserve?.runId ?? ""); | |
| 769 | if (all.length === 0) return ownerIsAdmin(db, scope.ownerId) ? { kind: "env" } : { kind: "none" }; | |
| 770 | // A crew run passes over a full plan, and takes a key only as the capped, switched-on fallback. | |
| 771 | const full = new Map<string, { window: LimitWindow; resetsAt: string }>(); | |
| 772 | // Where there is no plan, a key is simply what the crew runs on, as it always was. | |
| 773 | const plans = all.some((r) => r.kind === "oauth"); | |
| 774 | const kept = | |
| 775 | crew === undefined || !plans | |
| 776 | ? all | |
| 777 | : all.filter((r) => { | |
| 778 | if (r.kind === "api_key") return crew.fallback; | |
| 779 | const f = crewWindowFull(db, r.id, now); | |
| 780 | if (f !== undefined) full.set(r.name, f); | |
| 781 | return f === undefined; | |
| 782 | }); | |
| 783 | // A key with a cap is the fallback before one without: its spend has an end the owner chose. | |
| 784 | const rows = crew === undefined || !plans ? kept : [...kept.filter((r) => r.kind !== "api_key"), ...kept.filter((r) => r.kind === "api_key" && r.budget_usd !== null), ...kept.filter((r) => r.kind === "api_key" && r.budget_usd === null)]; | |
| 785 | if (rows.length === 0) { | |
| 786 | // Every plan is full and no fallback may take the run: it waits for the first window to reset. | |
| 787 | const soonest = [...full].sort((a, b) => a[1].resetsAt.localeCompare(b[1].resetsAt))[0]; | |
| 788 | const wakes = all.map((r) => r.resting_until).filter((u): u is string => u !== null && u > now.toISOString()).sort()[0]; | |
| 789 | const until = soonest?.[1].resetsAt ?? wakes ?? new Date(now.getTime() + BUDGET_RECHECK_MS).toISOString(); | |
| 790 | return { | |
| 791 | kind: "resting", | |
| 792 | until, | |
| 793 | said: soonest === undefined ? "no account here may take a crew run" : `${soonest[0]}'s ${soonest[1].window === "5h" ? "5-hour" : "weekly"} window is full for the crew (the rest is kept for people)`, | |
| 794 | names: all.map((r) => r.name), | |
| 795 | }; | |
| 796 | } | |
| 743 | 797 | // An account whose whole-life budget is spent is not offered again until |
| 744 | 798 | // an admin raises it; looked at again within the hour, so a raise is felt. |
| 745 | 799 | // Spent counts what other runs on it may still spend (their reservation) |
| @@ -788,7 +842,7 @@ export function pickSubscription( | ||
| 788 | 842 | db.query( |
| 789 | 843 | "UPDATE run SET budget_reserved_usd = NULL WHERE id = ?1 AND subscription_id = ?2", |
| 790 | 844 | ).run(reserve.runId, awake.id); |
| 791 | return pickSubscription(db, dataDir, scope, now, reserve); | |
| 845 | return pickSubscription(db, dataDir, scope, now, reserve, crew); | |
| 792 | 846 | } |
| 793 | 847 | const subscription = toSubscription(awake); |
| 794 | 848 | touchSubscription(db, awake.id, now); |
src/crew/dispatch.ts +8 −5
| @@ -67,6 +67,7 @@ import { bugsFirst } from "../flow/bugs.ts"; | ||
| 67 | 67 | import { forgeFailed } from "../flow/alarm_lane.ts"; |
| 68 | 68 | import { byDials } from "./team_share.ts"; |
| 69 | 69 | import { peopleFirst } from "./people_first.ts"; |
| 70 | import { fallbackActive, reviewsFirst, weekHolds } from "./key_fallback.ts"; | |
| 70 | 71 | import { inFocus } from "./focus.ts"; |
| 71 | 72 | import { inMaintenance } from "../maintenance/state.ts"; |
| 72 | 73 | import { gateQueue } from "../flow/valve_gate.ts"; |
| @@ -1846,10 +1847,11 @@ const notedBy = new WeakMap<App, Set<string>>(); | ||
| 1846 | 1847 | */ |
| 1847 | 1848 | export function startOrder(app: App): ReturnType<typeof gateQueue> { |
| 1848 | 1849 | const queued = listQueued(app.db, "agent", 50); |
| 1849 | return gateQueue( | |
| 1850 | app.db, | |
| 1851 | peopleFirst(app.db, bugsFirst(app.db, byDials(app.db, queued)), (run) => assignedByPerson(app, run)), | |
| 1852 | ); | |
| 1850 | const ordered = peopleFirst(app.db, bugsFirst(app.db, byDials(app.db, queued)), (run) => assignedByPerson(app, run)); | |
| 1851 | // While the metered key takes the crew's runs, reviews start first (`key_fallback.ts`). | |
| 1852 | // Asked only when there is an order to change: a review and something else both waiting. | |
| 1853 | const mixed = ordered.some((r) => r.reason === "review") && ordered.some((r) => r.reason !== "review"); | |
| 1854 | return gateQueue(app.db, mixed && fallbackActive(app.db) ? reviewsFirst(ordered) : ordered); | |
| 1853 | 1855 | } |
| 1854 | 1856 | |
| 1855 | 1857 | /** Take queued runs, oldest first, up to the limit — one per issue at a time. */ |
| @@ -1953,7 +1955,8 @@ export function pump( | ||
| 1953 | 1955 | if (!weeks.has(home.id)) weeks.set(home.id, weekFor(app, home, new Date())); |
| 1954 | 1956 | const week = weeks.get(home.id)!; |
| 1955 | 1957 | const paced = fresh.sent && week !== null && week.usedPct < 100 ? null : weekHold(week); |
| 1956 | if (paced !== null) { | |
| 1958 | // The capped key, when it may, takes what the week's hold would stop (`key_fallback.ts`). | |
| 1959 | if (weekHolds(app.db, paced)) { | |
| 1957 | 1960 | held.set(fresh.id, "pace"); |
| 1958 | 1961 | if (!noted.has(fresh.id)) { |
| 1959 | 1962 | noted.add(fresh.id); |
src/crew/key_fallback.ts added +207
| @@ -0,0 +1,207 @@ | ||
| 1 | /** | |
| 2 | * The crew's metered fallback (the owner, 2026-12-01: "yes you can do that. i need good UI around | |
| 3 | * this though so that I can observe and control it"). When every plan's window is full (no more | |
| 4 | * free than its share kept for people), crew runs go to a pay-per-token key, the one with a cap | |
| 5 | * first, reviews first, until the cap (`core/subscriptions.ts`, `pickSubscription` with `CrewPick`). Off | |
| 6 | * (`crew.fallback`), they wait for the first window to reset. One read for both doors (Settings → | |
| 7 | * Crew and the terminal's Fallback screen): which account each run uses, the key's spend against | |
| 8 | * its cap, the switch, and one plain line. Spend is list price, as every crew figure is. The key | |
| 9 | * itself is never read here, only its name and figures. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import type { App } from "../app.ts"; | |
| 14 | import { capacityValue, setCapacity } from "../core/capacity.ts"; | |
| 15 | import type { Run } from "../core/runs.ts"; | |
| 16 | import { budgetRefusal, crewWindowFull, setBudget, type CrewPick } from "../core/subscriptions.ts"; | |
| 17 | import type { User } from "../core/users.ts"; | |
| 18 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 19 | import { whenText } from "./limits.ts"; | |
| 20 | ||
| 21 | /** Whether the switch lets the crew fall back to a capped key. */ | |
| 22 | /** Off unless the owner switched it on: an unset forge holds the run rather than spend on a key. */ | |
| 23 | export const fallbackOn = (db: Database): boolean => capacityValue(db, "crew.fallback") === "on"; | |
| 24 | ||
| 25 | /** What a crew run's pick weighs: the switch. */ | |
| 26 | export const crewPick = (db: Database): CrewPick => ({ fallback: fallbackOn(db) }); | |
| 27 | ||
| 28 | /** The forge's plans and capped keys, as the fallback reads them. */ | |
| 29 | interface Accounts { | |
| 30 | readonly plans: readonly { readonly id: string; readonly name: string }[]; | |
| 31 | readonly key: { readonly id: string; readonly name: string; readonly capUsd: number; readonly spentUsd: number } | undefined; | |
| 32 | } | |
| 33 | ||
| 34 | /** The forge's plans and keys, by rank: the one select the fallback's reads share. */ | |
| 35 | const ACCOUNTS_SQL = "SELECT id, name, kind, budget_usd, spent_usd FROM subscription WHERE id <> 'platform' AND protocol = 'anthropic' ORDER BY rank, name COLLATE NOCASE"; | |
| 36 | ||
| 37 | type AccountRow = { id: string; name: string; kind: string; budget_usd: number | null; spent_usd: number }; | |
| 38 | ||
| 39 | const accountsFrom = (rows: readonly AccountRow[]): Accounts => { | |
| 40 | const key = rows.find((r) => r.kind === "api_key" && r.budget_usd !== null); | |
| 41 | return { | |
| 42 | plans: rows.filter((r) => r.kind === "oauth").map((r) => ({ id: r.id, name: r.name })), | |
| 43 | key: key === undefined ? undefined : { id: key.id, name: key.name, capUsd: key.budget_usd!, spentUsd: key.spent_usd }, | |
| 44 | }; | |
| 45 | }; | |
| 46 | ||
| 47 | function accountsOf(db: Database): Accounts { | |
| 48 | return accountsFrom(db.query<AccountRow, []>(ACCOUNTS_SQL).all()); | |
| 49 | } | |
| 50 | ||
| 51 | /** The plans whose window is full for the crew now, the first to reset first. */ | |
| 52 | function fullPlans(db: Database, now: Date, plans: Accounts["plans"]): { name: string; resetsAt: string }[] { | |
| 53 | return plans | |
| 54 | .flatMap((p) => { | |
| 55 | const f = crewWindowFull(db, p.id, now); | |
| 56 | return f === undefined ? [] : [{ name: p.name, resetsAt: f.resetsAt }]; | |
| 57 | }) | |
| 58 | .sort((a, b) => a.resetsAt.localeCompare(b.resetsAt)); | |
| 59 | } | |
| 60 | ||
| 61 | /** Whether crew runs go to the key now: every plan full, the switch on, the cap not reached. */ | |
| 62 | export function fallbackActive(db: Database, now: Date = new Date()): boolean { | |
| 63 | const { plans, key } = accountsOf(db); | |
| 64 | if (key === undefined || key.capUsd - key.spentUsd < 0.01 || plans.length === 0 || !fallbackOn(db)) return false; | |
| 65 | return fullPlans(db, now, plans).length === plans.length; | |
| 66 | } | |
| 67 | ||
| 68 | /** Whether the fallback can take runs the week's hold would stop: on, with a capped key under its cap. */ | |
| 69 | export function fallbackReady(db: Database): boolean { | |
| 70 | const { key } = accountsOf(db); | |
| 71 | return key !== undefined && key.capUsd - key.spentUsd >= 0.01 && fallbackOn(db); | |
| 72 | } | |
| 73 | ||
| 74 | /** | |
| 75 | * Whether the week's hold (`week_hold.ts`, its sentence `paced`) stops a crew run: the plans are | |
| 76 | * at the share kept for people, and no fallback may take the run (off, or capped). With the | |
| 77 | * fallback ready the run goes on, and the pick passes the full plans over for the key. | |
| 78 | */ | |
| 79 | export const weekHolds = (db: Database, paced: string | null): boolean => paced !== null && !fallbackReady(db); | |
| 80 | ||
| 81 | /** While the key takes the crew's runs, reviews start first: they are cheap and they land work. */ | |
| 82 | export const reviewsFirst = (runs: readonly Run[]): Run[] => [...runs.filter((r) => r.reason === "review"), ...runs.filter((r) => r.reason !== "review")]; | |
| 83 | ||
| 84 | /** One run as both doors list it: which account it used. */ | |
| 85 | export interface RunAccount { | |
| 86 | readonly id: string; | |
| 87 | readonly repo: string; | |
| 88 | readonly reason: string; | |
| 89 | readonly state: string; | |
| 90 | readonly account: string; | |
| 91 | readonly usd: number; | |
| 92 | readonly at: string; | |
| 93 | } | |
| 94 | ||
| 95 | /** What the card and the screen show. */ | |
| 96 | export interface FallbackView { | |
| 97 | readonly on: boolean; | |
| 98 | readonly key?: { | |
| 99 | readonly name: string; | |
| 100 | readonly capUsd: number; | |
| 101 | readonly spentUsd: number; | |
| 102 | readonly todayUsd: number; | |
| 103 | readonly weekUsd: number; | |
| 104 | /** What it spent a day over the last seven, list price. */ | |
| 105 | readonly perDayUsd: number; | |
| 106 | /** Days until the cap at that pace; null when it spends nothing. */ | |
| 107 | readonly daysLeft: number | null; | |
| 108 | }; | |
| 109 | /** One plain line: what the crew runs on now, and when it waits, for what. */ | |
| 110 | readonly line: string; | |
| 111 | readonly runs: readonly RunAccount[]; | |
| 112 | } | |
| 113 | ||
| 114 | const dollars = (n: number): string => `$${n.toFixed(2)}`; | |
| 115 | ||
| 116 | /** The key's spend since UTC midnight and over the last seven days, list price, in one read. */ | |
| 117 | const spentOf = (db: Database, id: string, day: string, week: string): { todayUsd: number; weekUsd: number } => | |
| 118 | db | |
| 119 | .query<{ todayUsd: number; weekUsd: number }, [string, string, string]>( | |
| 120 | "SELECT COALESCE(SUM(CASE WHEN created_at >= ?2 THEN cost_usd END), 0) AS todayUsd, COALESCE(SUM(cost_usd), 0) AS weekUsd FROM run WHERE subscription_id = ?1 AND created_at >= ?3", | |
| 121 | ) | |
| 122 | .get(id, day, week) ?? { todayUsd: 0, weekUsd: 0 }; | |
| 123 | ||
| 124 | /** The running crew runs and the latest, with the account each used: the select the card reads. */ | |
| 125 | const RUNS_SQL = `SELECT r.id, o.username || '/' || p.name AS repo, r.reason, r.state, s.name AS account, r.subscription_id AS sub, r.cost_usd AS usd, r.created_at AS at | |
| 126 | FROM run r JOIN repo p ON p.id = r.repo_id JOIN user o ON o.id = p.owner_id LEFT JOIN subscription s ON s.id = r.subscription_id | |
| 127 | WHERE r.kind = 'agent' AND r.state <> 'queued' | |
| 128 | ORDER BY (r.state = 'running') DESC, r.created_at DESC LIMIT ?1`; | |
| 129 | ||
| 130 | type RunRow = { id: string; repo: string; reason: string; state: string; account: string | null; sub: string | null; usd: number; at: string }; | |
| 131 | ||
| 132 | const runAccount = (r: RunRow): RunAccount => ({ id: r.id, repo: r.repo, reason: r.reason, state: r.state, account: r.account ?? (r.sub === null || r.sub === "" ? "not recorded" : "the forge's own token"), usd: r.usd, at: r.at }); | |
| 133 | ||
| 134 | /** | |
| 135 | * What the card needs from the database, in one statement (the crew page counts its work): the | |
| 136 | * switch, the plans and keys, and the latest runs with their accounts. | |
| 137 | */ | |
| 138 | function readCard(db: Database, runs: number): { on: boolean; accounts: Accounts; runs: RunAccount[] } { | |
| 139 | const row = db | |
| 140 | .query<{ fallback: string | null; accounts: string; runs: string }, [number]>( | |
| 141 | `SELECT (SELECT value FROM forge_setting WHERE key = 'crew.fallback') AS fallback, | |
| 142 | (SELECT json_group_array(json_object('id', id, 'name', name, 'kind', kind, 'budget_usd', budget_usd, 'spent_usd', spent_usd)) FROM (${ACCOUNTS_SQL})) AS accounts, | |
| 143 | (SELECT json_group_array(json_object('id', id, 'repo', repo, 'reason', reason, 'state', state, 'account', account, 'sub', sub, 'usd', usd, 'at', at)) FROM (${RUNS_SQL})) AS runs`, | |
| 144 | ) | |
| 145 | .get(runs); | |
| 146 | return { | |
| 147 | // As `fallbackOn` reads it: only "on" turns it on. | |
| 148 | on: row?.fallback === "on", | |
| 149 | accounts: accountsFrom(JSON.parse(row?.accounts ?? "[]") as AccountRow[]), | |
| 150 | runs: (JSON.parse(row?.runs ?? "[]") as RunRow[]).map(runAccount), | |
| 151 | }; | |
| 152 | } | |
| 153 | ||
| 154 | export function fallbackView(app: App, now: Date = new Date(), runs = 12): FallbackView { | |
| 155 | const { db } = app; | |
| 156 | const card = readCard(db, runs); | |
| 157 | const { on } = card; | |
| 158 | const { plans, key } = card.accounts; | |
| 159 | const full = fullPlans(db, now, plans); | |
| 160 | const allFull = plans.length > 0 && full.length === plans.length; | |
| 161 | const first = full[0]; | |
| 162 | const waits = first === undefined ? "" : `reviews wait for ${first.name}'s window, resets ${whenText(new Date(first.resetsAt))}`; | |
| 163 | let view: FallbackView["key"]; | |
| 164 | if (key !== undefined) { | |
| 165 | const day = `${now.toISOString().slice(0, 10)}T00:00:00.000Z`; | |
| 166 | const week = new Date(now.getTime() - 7 * 86_400_000).toISOString(); | |
| 167 | const { todayUsd, weekUsd } = spentOf(db, key.id, day, week); | |
| 168 | const perDayUsd = weekUsd / 7; | |
| 169 | const left = Math.max(0, key.capUsd - key.spentUsd); | |
| 170 | view = { name: key.name, capUsd: key.capUsd, spentUsd: key.spentUsd, todayUsd, weekUsd, perDayUsd, daysLeft: perDayUsd > 0 ? left / perDayUsd : null }; | |
| 171 | } | |
| 172 | const names = plans.map((p) => p.name).join(" and "); | |
| 173 | const line = | |
| 174 | key === undefined | |
| 175 | ? "No pay-per-token key with a cap: when every plan's window is full, the crew waits. Add one on Subscriptions and give it a budget." | |
| 176 | : !on | |
| 177 | ? `The fallback is off${allFull ? `: ${waits}` : `: ${key.name} never takes crew runs; when every plan's window is full, they wait`}.` | |
| 178 | : key.capUsd - key.spentUsd < 0.01 | |
| 179 | ? `${key.name} has reached its ${dollars(key.capUsd)} cap${allFull ? `: ${waits}` : "; raise it to let it take over again"}.` | |
| 180 | : allFull | |
| 181 | ? `Every plan's window is full: the crew runs on ${key.name}, reviews first, until ${first === undefined ? "its cap" : `${first.name}'s window resets at ${whenText(new Date(first.resetsAt))}`}.` | |
| 182 | : `The crew runs on ${names === "" ? "its plans" : names}; ${key.name} takes over when every window is full.`; | |
| 183 | return { on, ...(view === undefined ? {} : { key: view }), line, runs: card.runs }; | |
| 184 | } | |
| 185 | ||
| 186 | /** Turn the fallback on or off; a forge admin who is a person only. */ | |
| 187 | export function setFallback(app: App, actor: User | undefined, on: boolean): Result<{ from: string; to: string }, "not_found"> { | |
| 188 | if (actor === undefined || !actor.isAdmin || actor.kind !== "user") return err("not_found"); | |
| 189 | return ok(setCapacity(app.db, "crew.fallback", on ? "on" : "off", actor.id, on ? "the crew may fall back to the capped key" : "the crew waits for the plans' windows")); | |
| 190 | } | |
| 191 | ||
| 192 | /** Set the key's cap; what it was, for Undo. A forge admin who is a person only. */ | |
| 193 | export function setFallbackCap(app: App, actor: User | undefined, usd: number): Result<{ from: number; to: number }, "not_found" | "invalid" | "locked"> { | |
| 194 | if (actor === undefined || !actor.isAdmin || actor.kind !== "user") return err("not_found"); | |
| 195 | const key = accountsOf(app.db).key; | |
| 196 | if (key === undefined) return err("not_found"); | |
| 197 | const refused = budgetRefusal(app.db, key.id, usd); | |
| 198 | if (refused !== undefined) return err(refused.code === "not_found" ? "not_found" : refused.code === "locked" ? "locked" : "invalid"); | |
| 199 | if (!setBudget(app.db, key.id, usd)) return err("invalid"); | |
| 200 | return ok({ from: key.capUsd, to: Math.round(usd * 100) / 100 }); | |
| 201 | } | |
| 202 | ||
| 203 | /** What a cap would last at the week's pace, for the form's forecast. */ | |
| 204 | export const capForecast = (v: NonNullable<FallbackView["key"]>, capUsd = v.capUsd): string => | |
| 205 | v.perDayUsd <= 0 | |
| 206 | ? `${dollars(capUsd)} cap: it has spent nothing this week, so nothing is used up at this pace.` | |
| 207 | : `${dollars(capUsd)} cap: at ${dollars(v.perDayUsd)} a day (the last 7 days) it lasts about ${Math.max(0, Math.floor((capUsd - v.spentUsd) / v.perDayUsd))} more days.`; |
src/crew/run_limits.ts +2 −1
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | import type { App } from "../app.ts"; |
| 8 | 8 | import type { Run } from "../core/runs.ts"; |
| 9 | 9 | import { PLATFORM, pickSubscription, type Pick } from "../core/subscriptions.ts"; |
| 10 | import { crewPick } from "./key_fallback.ts"; | |
| 10 | 11 | import type { AgentOutcome } from "./agent_runner.ts"; |
| 11 | 12 | import { |
| 12 | 13 | breathWait, |
| @@ -78,7 +79,7 @@ export function limitEnding(s: LimitState): LimitEnding { | ||
| 78 | 79 | if (picked.kind === "ready") { |
| 79 | 80 | // Only a look at who could take over: no reservation is made here. |
| 80 | 81 | // The run pauses, and on resume it picks again with its reserve. |
| 81 | const next = pickSubscription(app.db, app.config.dataDir, scope, new Date()); | |
| 82 | const next = pickSubscription(app.db, app.config.dataDir, scope, new Date(), undefined, crewPick(app.db)); | |
| 82 | 83 | if (next.kind === "ready" && next.subscription.id !== picked.subscription.id) { |
| 83 | 84 | write( |
| 84 | 85 | `${picked.subscription.name} rests until ${whenText(until)}; ${next.subscription.name} takes the run`, |
src/crew/run_spend.ts +3 −1
| @@ -17,6 +17,7 @@ import { | ||
| 17 | 17 | PLATFORM, |
| 18 | 18 | type Pick, |
| 19 | 19 | } from "../core/subscriptions.ts"; |
| 20 | import { crewPick } from "./key_fallback.ts"; | |
| 20 | 21 | import { capReached } from "../core/wallet.ts"; |
| 21 | 22 | import { cappedByLent, lentCreditLeft, lentSpent, refreshFundingOnce } from "../spawn/funding.ts"; |
| 22 | 23 | import { budgetLimit, budgetVerdict, isOwnForge } from "./forge_budget.ts"; |
| @@ -81,10 +82,11 @@ export async function settleSpend(s: SpendState): Promise<Spend> { | ||
| 81 | 82 | : isOwnForge(app) |
| 82 | 83 | ? budgetLimit(app.db, "run") |
| 83 | 84 | : s.defaultBudgetUsd; |
| 85 | // A crew run passes over a full plan and falls back to the capped key while the switch is on. | |
| 84 | 86 | const picked = pickSubscription(app.db, app.config.dataDir, scope, new Date(), { |
| 85 | 87 | runId: run.id, |
| 86 | 88 | usd: ownBudget, |
| 87 | }); | |
| 89 | }, crewPick(app.db)); | |
| 88 | 90 | if (picked.kind === "resting") { |
| 89 | 91 | const names = picked.names.join(", "); |
| 90 | 92 | write( |
src/crew/week_read.ts +10 −2
| @@ -44,12 +44,20 @@ function weekOf(app: Reads, repo: Repo, now: Date): Week { | ||
| 44 | 44 | return week; |
| 45 | 45 | } |
| 46 | 46 | |
| 47 | /** The accounts a repository's crew draws on. */ | |
| 47 | /** | |
| 48 | * The accounts whose week holds a repository's crew: its plans. A pay-per-token key has no week, so | |
| 49 | * it is never measured, and counting it made every week "unmeasured" and the share kept for people | |
| 50 | * hold nothing (since #16498 put the key in the pool); the key is the fallback past that hold | |
| 51 | * instead (`crew/key_fallback.ts`). A crew with keys alone has no week to hold it, as before. | |
| 52 | */ | |
| 48 | 53 | function accountsOf(app: Reads, repo: Repo): string[] { |
| 49 | 54 | // A crew no account may serve runs on the server's own token: the account `usage` prints as |
| 50 | 55 | // `platform`. It is metered too, never skipped (#8873). |
| 51 | 56 | const granted = grantedAccounts(app.db, repo.id, repo.ownerId).map((a) => a.id); |
| 52 | return granted.length > 0 ? granted : [PLATFORM]; | |
| 57 | if (granted.length === 0) return [PLATFORM]; | |
| 58 | const keys = new Set(app.db.query<{ id: string }, []>("SELECT id FROM subscription WHERE kind = 'api_key'").all().map((r) => r.id)); | |
| 59 | const plans = granted.filter((id) => !keys.has(id)); | |
| 60 | return plans.length > 0 ? plans : granted; | |
| 53 | 61 | } |
| 54 | 62 | |
| 55 | 63 | function readWeek(app: Reads, repo: Repo, now: Date): Week { |
src/generated/screens.ts +105 −103
| @@ -29,105 +29,106 @@ import * as s24 from "../tui/screens/connections.ts"; | ||
| 29 | 29 | import * as s25 from "../tui/screens/controls.ts"; |
| 30 | 30 | import * as s26 from "../tui/screens/cores.ts"; |
| 31 | 31 | import * as s27 from "../tui/screens/crewbudgets.ts"; |
| 32 | import * as s28 from "../tui/screens/crewhandover.ts"; | |
| 33 | import * as s29 from "../tui/screens/crewkey.ts"; | |
| 34 | import * as s30 from "../tui/screens/crewsplits.ts"; | |
| 35 | import * as s31 from "../tui/screens/crewtop.ts"; | |
| 36 | import * as s32 from "../tui/screens/dataset.ts"; | |
| 37 | import * as s33 from "../tui/screens/design.ts"; | |
| 38 | import * as s34 from "../tui/screens/design_gallery.ts"; | |
| 39 | import * as s35 from "../tui/screens/devices.ts"; | |
| 40 | import * as s36 from "../tui/screens/disks.ts"; | |
| 41 | import * as s37 from "../tui/screens/displays.ts"; | |
| 42 | import * as s38 from "../tui/screens/domains.ts"; | |
| 43 | import * as s39 from "../tui/screens/dotfiles.ts"; | |
| 44 | import * as s40 from "../tui/screens/drift.ts"; | |
| 45 | import * as s41 from "../tui/screens/dutybudgets.ts"; | |
| 46 | import * as s42 from "../tui/screens/dutyswitch.ts"; | |
| 47 | import * as s43 from "../tui/screens/economics.ts"; | |
| 48 | import * as s44 from "../tui/screens/edgeonly.ts"; | |
| 49 | import * as s45 from "../tui/screens/experiments.ts"; | |
| 50 | import * as s46 from "../tui/screens/featurefeed.ts"; | |
| 51 | import * as s47 from "../tui/screens/features.ts"; | |
| 52 | import * as s48 from "../tui/screens/featureswitch.ts"; | |
| 53 | import * as s49 from "../tui/screens/feed.ts"; | |
| 54 | import * as s50 from "../tui/screens/flowsall.ts"; | |
| 55 | import * as s51 from "../tui/screens/footing.ts"; | |
| 56 | import * as s52 from "../tui/screens/forgeready.ts"; | |
| 57 | import * as s53 from "../tui/screens/forges.ts"; | |
| 58 | import * as s54 from "../tui/screens/forgeview.ts"; | |
| 59 | import * as s55 from "../tui/screens/front.ts"; | |
| 60 | import * as s56 from "../tui/screens/frontms.ts"; | |
| 61 | import * as s57 from "../tui/screens/funnel.ts"; | |
| 62 | import * as s58 from "../tui/screens/games.ts"; | |
| 63 | import * as s59 from "../tui/screens/gifts.ts"; | |
| 64 | import * as s60 from "../tui/screens/health_voice.ts"; | |
| 65 | import * as s61 from "../tui/screens/home_pins.ts"; | |
| 66 | import * as s62 from "../tui/screens/hostreach.ts"; | |
| 67 | import * as s63 from "../tui/screens/infra.ts"; | |
| 68 | import * as s64 from "../tui/screens/inventory.ts"; | |
| 69 | import * as s65 from "../tui/screens/invites.ts"; | |
| 70 | import * as s66 from "../tui/screens/knobs.ts"; | |
| 71 | import * as s67 from "../tui/screens/lapsed.ts"; | |
| 72 | import * as s68 from "../tui/screens/limits.ts"; | |
| 73 | import * as s69 from "../tui/screens/loopstalls.ts"; | |
| 74 | import * as s70 from "../tui/screens/madefrom.ts"; | |
| 75 | import * as s71 from "../tui/screens/maintainruns.ts"; | |
| 76 | import * as s72 from "../tui/screens/maintenance.ts"; | |
| 77 | import * as s73 from "../tui/screens/maintenanceweek.ts"; | |
| 78 | import * as s74 from "../tui/screens/mergedbranches.ts"; | |
| 79 | import * as s75 from "../tui/screens/mirrorpacks.ts"; | |
| 80 | import * as s76 from "../tui/screens/model.ts"; | |
| 81 | import * as s77 from "../tui/screens/money.ts"; | |
| 82 | import * as s78 from "../tui/screens/newissue.ts"; | |
| 83 | import * as s79 from "../tui/screens/next.ts"; | |
| 84 | import * as s80 from "../tui/screens/nowlist.ts"; | |
| 85 | import * as s81 from "../tui/screens/offers.ts"; | |
| 86 | import * as s82 from "../tui/screens/offsite.ts"; | |
| 87 | import * as s83 from "../tui/screens/orggrants.ts"; | |
| 88 | import * as s84 from "../tui/screens/orgteams.ts"; | |
| 89 | import * as s85 from "../tui/screens/originahead.ts"; | |
| 90 | import * as s86 from "../tui/screens/owner.ts"; | |
| 91 | import * as s87 from "../tui/screens/packrepos.ts"; | |
| 92 | import * as s88 from "../tui/screens/payments.ts"; | |
| 93 | import * as s89 from "../tui/screens/people.ts"; | |
| 94 | import * as s90 from "../tui/screens/pinned.ts"; | |
| 95 | import * as s91 from "../tui/screens/planner.ts"; | |
| 96 | import * as s92 from "../tui/screens/planrow.ts"; | |
| 97 | import * as s93 from "../tui/screens/plans.ts"; | |
| 98 | import * as s94 from "../tui/screens/previewdirs.ts"; | |
| 99 | import * as s95 from "../tui/screens/profile.ts"; | |
| 100 | import * as s96 from "../tui/screens/quotas.ts"; | |
| 101 | import * as s97 from "../tui/screens/recoverykit.ts"; | |
| 102 | import * as s98 from "../tui/screens/refused.ts"; | |
| 103 | import * as s99 from "../tui/screens/registry_items.ts"; | |
| 104 | import * as s100 from "../tui/screens/repolist.ts"; | |
| 105 | import * as s101 from "../tui/screens/requests.ts"; | |
| 106 | import * as s102 from "../tui/screens/resilience.ts"; | |
| 107 | import * as s103 from "../tui/screens/returning.ts"; | |
| 108 | import * as s104 from "../tui/screens/returns.ts"; | |
| 109 | import * as s105 from "../tui/screens/scorecard.ts"; | |
| 110 | import * as s106 from "../tui/screens/scrapes.ts"; | |
| 111 | import * as s107 from "../tui/screens/secrets.ts"; | |
| 112 | import * as s108 from "../tui/screens/sentinel.ts"; | |
| 113 | import * as s109 from "../tui/screens/series.ts"; | |
| 114 | import * as s110 from "../tui/screens/ship_time.ts"; | |
| 115 | import * as s111 from "../tui/screens/slowpages.ts"; | |
| 116 | import * as s112 from "../tui/screens/sold.ts"; | |
| 117 | import * as s113 from "../tui/screens/spend.ts"; | |
| 118 | import * as s114 from "../tui/screens/stalepulls.ts"; | |
| 119 | import * as s115 from "../tui/screens/subscriptions.ts"; | |
| 120 | import * as s116 from "../tui/screens/system.ts"; | |
| 121 | import * as s117 from "../tui/screens/teams.ts"; | |
| 122 | import * as s118 from "../tui/screens/telemetry.ts"; | |
| 123 | import * as s119 from "../tui/screens/tell_undo.ts"; | |
| 124 | import * as s120 from "../tui/screens/traffic.ts"; | |
| 125 | import * as s121 from "../tui/screens/trafficview.ts"; | |
| 126 | import * as s122 from "../tui/screens/valves.ts"; | |
| 127 | import * as s123 from "../tui/screens/waiting.ts"; | |
| 128 | import * as s124 from "../tui/screens/waiting_for_me.ts"; | |
| 129 | import * as s125 from "../tui/screens/wayback.ts"; | |
| 130 | import * as s126 from "../tui/screens/weekcard.ts"; | |
| 32 | import * as s28 from "../tui/screens/crewfallback.ts"; | |
| 33 | import * as s29 from "../tui/screens/crewhandover.ts"; | |
| 34 | import * as s30 from "../tui/screens/crewkey.ts"; | |
| 35 | import * as s31 from "../tui/screens/crewsplits.ts"; | |
| 36 | import * as s32 from "../tui/screens/crewtop.ts"; | |
| 37 | import * as s33 from "../tui/screens/dataset.ts"; | |
| 38 | import * as s34 from "../tui/screens/design.ts"; | |
| 39 | import * as s35 from "../tui/screens/design_gallery.ts"; | |
| 40 | import * as s36 from "../tui/screens/devices.ts"; | |
| 41 | import * as s37 from "../tui/screens/disks.ts"; | |
| 42 | import * as s38 from "../tui/screens/displays.ts"; | |
| 43 | import * as s39 from "../tui/screens/domains.ts"; | |
| 44 | import * as s40 from "../tui/screens/dotfiles.ts"; | |
| 45 | import * as s41 from "../tui/screens/drift.ts"; | |
| 46 | import * as s42 from "../tui/screens/dutybudgets.ts"; | |
| 47 | import * as s43 from "../tui/screens/dutyswitch.ts"; | |
| 48 | import * as s44 from "../tui/screens/economics.ts"; | |
| 49 | import * as s45 from "../tui/screens/edgeonly.ts"; | |
| 50 | import * as s46 from "../tui/screens/experiments.ts"; | |
| 51 | import * as s47 from "../tui/screens/featurefeed.ts"; | |
| 52 | import * as s48 from "../tui/screens/features.ts"; | |
| 53 | import * as s49 from "../tui/screens/featureswitch.ts"; | |
| 54 | import * as s50 from "../tui/screens/feed.ts"; | |
| 55 | import * as s51 from "../tui/screens/flowsall.ts"; | |
| 56 | import * as s52 from "../tui/screens/footing.ts"; | |
| 57 | import * as s53 from "../tui/screens/forgeready.ts"; | |
| 58 | import * as s54 from "../tui/screens/forges.ts"; | |
| 59 | import * as s55 from "../tui/screens/forgeview.ts"; | |
| 60 | import * as s56 from "../tui/screens/front.ts"; | |
| 61 | import * as s57 from "../tui/screens/frontms.ts"; | |
| 62 | import * as s58 from "../tui/screens/funnel.ts"; | |
| 63 | import * as s59 from "../tui/screens/games.ts"; | |
| 64 | import * as s60 from "../tui/screens/gifts.ts"; | |
| 65 | import * as s61 from "../tui/screens/health_voice.ts"; | |
| 66 | import * as s62 from "../tui/screens/home_pins.ts"; | |
| 67 | import * as s63 from "../tui/screens/hostreach.ts"; | |
| 68 | import * as s64 from "../tui/screens/infra.ts"; | |
| 69 | import * as s65 from "../tui/screens/inventory.ts"; | |
| 70 | import * as s66 from "../tui/screens/invites.ts"; | |
| 71 | import * as s67 from "../tui/screens/knobs.ts"; | |
| 72 | import * as s68 from "../tui/screens/lapsed.ts"; | |
| 73 | import * as s69 from "../tui/screens/limits.ts"; | |
| 74 | import * as s70 from "../tui/screens/loopstalls.ts"; | |
| 75 | import * as s71 from "../tui/screens/madefrom.ts"; | |
| 76 | import * as s72 from "../tui/screens/maintainruns.ts"; | |
| 77 | import * as s73 from "../tui/screens/maintenance.ts"; | |
| 78 | import * as s74 from "../tui/screens/maintenanceweek.ts"; | |
| 79 | import * as s75 from "../tui/screens/mergedbranches.ts"; | |
| 80 | import * as s76 from "../tui/screens/mirrorpacks.ts"; | |
| 81 | import * as s77 from "../tui/screens/model.ts"; | |
| 82 | import * as s78 from "../tui/screens/money.ts"; | |
| 83 | import * as s79 from "../tui/screens/newissue.ts"; | |
| 84 | import * as s80 from "../tui/screens/next.ts"; | |
| 85 | import * as s81 from "../tui/screens/nowlist.ts"; | |
| 86 | import * as s82 from "../tui/screens/offers.ts"; | |
| 87 | import * as s83 from "../tui/screens/offsite.ts"; | |
| 88 | import * as s84 from "../tui/screens/orggrants.ts"; | |
| 89 | import * as s85 from "../tui/screens/orgteams.ts"; | |
| 90 | import * as s86 from "../tui/screens/originahead.ts"; | |
| 91 | import * as s87 from "../tui/screens/owner.ts"; | |
| 92 | import * as s88 from "../tui/screens/packrepos.ts"; | |
| 93 | import * as s89 from "../tui/screens/payments.ts"; | |
| 94 | import * as s90 from "../tui/screens/people.ts"; | |
| 95 | import * as s91 from "../tui/screens/pinned.ts"; | |
| 96 | import * as s92 from "../tui/screens/planner.ts"; | |
| 97 | import * as s93 from "../tui/screens/planrow.ts"; | |
| 98 | import * as s94 from "../tui/screens/plans.ts"; | |
| 99 | import * as s95 from "../tui/screens/previewdirs.ts"; | |
| 100 | import * as s96 from "../tui/screens/profile.ts"; | |
| 101 | import * as s97 from "../tui/screens/quotas.ts"; | |
| 102 | import * as s98 from "../tui/screens/recoverykit.ts"; | |
| 103 | import * as s99 from "../tui/screens/refused.ts"; | |
| 104 | import * as s100 from "../tui/screens/registry_items.ts"; | |
| 105 | import * as s101 from "../tui/screens/repolist.ts"; | |
| 106 | import * as s102 from "../tui/screens/requests.ts"; | |
| 107 | import * as s103 from "../tui/screens/resilience.ts"; | |
| 108 | import * as s104 from "../tui/screens/returning.ts"; | |
| 109 | import * as s105 from "../tui/screens/returns.ts"; | |
| 110 | import * as s106 from "../tui/screens/scorecard.ts"; | |
| 111 | import * as s107 from "../tui/screens/scrapes.ts"; | |
| 112 | import * as s108 from "../tui/screens/secrets.ts"; | |
| 113 | import * as s109 from "../tui/screens/sentinel.ts"; | |
| 114 | import * as s110 from "../tui/screens/series.ts"; | |
| 115 | import * as s111 from "../tui/screens/ship_time.ts"; | |
| 116 | import * as s112 from "../tui/screens/slowpages.ts"; | |
| 117 | import * as s113 from "../tui/screens/sold.ts"; | |
| 118 | import * as s114 from "../tui/screens/spend.ts"; | |
| 119 | import * as s115 from "../tui/screens/stalepulls.ts"; | |
| 120 | import * as s116 from "../tui/screens/subscriptions.ts"; | |
| 121 | import * as s117 from "../tui/screens/system.ts"; | |
| 122 | import * as s118 from "../tui/screens/teams.ts"; | |
| 123 | import * as s119 from "../tui/screens/telemetry.ts"; | |
| 124 | import * as s120 from "../tui/screens/tell_undo.ts"; | |
| 125 | import * as s121 from "../tui/screens/traffic.ts"; | |
| 126 | import * as s122 from "../tui/screens/trafficview.ts"; | |
| 127 | import * as s123 from "../tui/screens/valves.ts"; | |
| 128 | import * as s124 from "../tui/screens/waiting.ts"; | |
| 129 | import * as s125 from "../tui/screens/waiting_for_me.ts"; | |
| 130 | import * as s126 from "../tui/screens/wayback.ts"; | |
| 131 | import * as s127 from "../tui/screens/weekcard.ts"; | |
| 131 | 132 | |
| 132 | 133 | /** Each screen file that declares palette entries: its module and the export names. */ |
| 133 | 134 | export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [ |
| @@ -207,11 +208,11 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon | ||
| 207 | 208 | [s73, ["entry"]], |
| 208 | 209 | [s74, ["entry"]], |
| 209 | 210 | [s75, ["entry"]], |
| 210 | [s76, ["modelGrantEntry","modelCeilingEntry"]], | |
| 211 | [s77, ["entry"]], | |
| 211 | [s76, ["entry"]], | |
| 212 | [s77, ["modelGrantEntry","modelCeilingEntry"]], | |
| 212 | 213 | [s78, ["entry"]], |
| 213 | [s79, ["nextAllEntry"]], | |
| 214 | [s80, ["entry"]], | |
| 214 | [s79, ["entry"]], | |
| 215 | [s80, ["nextAllEntry"]], | |
| 215 | 216 | [s81, ["entry"]], |
| 216 | 217 | [s82, ["entry"]], |
| 217 | 218 | [s83, ["entry"]], |
| @@ -258,4 +259,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon | ||
| 258 | 259 | [s124, ["entry"]], |
| 259 | 260 | [s125, ["entry"]], |
| 260 | 261 | [s126, ["entry"]], |
| 262 | [s127, ["entry"]], | |
| 261 | 263 | ]; |
src/http/lazy_lists.ts +2
| @@ -63,6 +63,8 @@ export const SETTINGS_ROUTES = [ | ||
| 63 | 63 | ["POST", "/settings/subscriptions"], |
| 64 | 64 | ["POST", "/settings/crew/key"], |
| 65 | 65 | ["POST", "/settings/crew/budgets"], |
| 66 | ["POST", "/settings/crew/fallback"], | |
| 67 | ["POST", "/settings/crew/fallback/cap"], | |
| 66 | 68 | ["POST", "/settings/subscriptions/:id/delete"], |
| 67 | 69 | ["POST", "/settings/subscriptions/allow"], |
| 68 | 70 | ["POST", "/settings/subscriptions/:id/wake"], |
src/http/marks/settings.json +2
| @@ -50,6 +50,8 @@ | ||
| 50 | 50 | "/settings/subscriptions": "admin", |
| 51 | 51 | "/settings/crew/key": "admin", |
| 52 | 52 | "/settings/crew/budgets": "admin", |
| 53 | "/settings/crew/fallback": "admin", | |
| 54 | "/settings/crew/fallback/cap": "admin", | |
| 53 | 55 | "/settings/subscriptions/:id/delete": "admin", |
| 54 | 56 | "/settings/subscriptions/allow": "admin", |
| 55 | 57 | "/settings/subscriptions/:id/wake": "admin", |
src/http/settings_routes.ts +3
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { crewKeyAdd } from "../web/studio/crew_key.ts"; |
| 11 | 11 | import { crewBudgetsSave } from "../web/studio/crew_budgets.ts"; |
| 12 | import { fallbackCapSave, fallbackSave } from "../web/studio/crew_fallback.ts"; | |
| 12 | 13 | import type { Handler } from "./context.ts"; |
| 13 | 14 | import type { Router } from "./router.ts"; |
| 14 | 15 | import { parentLinkStart } from "./rp.ts"; |
| @@ -222,6 +223,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 222 | 223 | router.add("POST", "/settings/subscriptions", subscriptionAdd); |
| 223 | 224 | router.add("POST", "/settings/crew/key", crewKeyAdd); |
| 224 | 225 | router.add("POST", "/settings/crew/budgets", crewBudgetsSave); |
| 226 | router.add("POST", "/settings/crew/fallback", fallbackSave); | |
| 227 | router.add("POST", "/settings/crew/fallback/cap", fallbackCapSave); | |
| 225 | 228 | router.add("POST", "/settings/subscriptions/:id/delete", subscriptionDelete); |
| 226 | 229 | router.add("POST", "/settings/subscriptions/allow", subscriptionAllow); |
| 227 | 230 | router.add("POST", "/settings/subscriptions/:id/wake", subscriptionWake); |
src/settings/limits.ts +20
| @@ -603,6 +603,26 @@ export function limitValue(db: Database, key: LimitKey): number { | ||
| 603 | 603 | return stored(db, key) ?? LIMITS[key].default; |
| 604 | 604 | } |
| 605 | 605 | |
| 606 | /** | |
| 607 | * `limitValue` of each of `keys`, the ones kept in the settings table read in one statement: a card | |
| 608 | * that shows several limits costs one read, not one each. | |
| 609 | */ | |
| 610 | export function limitValues<K extends LimitKey>(db: Database, keys: readonly K[]): Record<K, number> { | |
| 611 | const own = keys.filter((k) => capacityKey(k) === undefined); | |
| 612 | const rows = | |
| 613 | own.length === 0 | |
| 614 | ? new Map<string, string>() | |
| 615 | : new Map( | |
| 616 | db | |
| 617 | .query<{ key: string; value: string }, string[]>(`SELECT key, value FROM forge_setting WHERE key IN (${own.map(() => "?").join(",")})`) | |
| 618 | .all(...own.map(storeKey)) | |
| 619 | .map((r) => [r.key, r.value]), | |
| 620 | ); | |
| 621 | const out = {} as Record<K, number>; | |
| 622 | for (const k of keys) out[k] = capacityKey(k) !== undefined ? limitValue(db, k) : (decodeLimit(k, rows.get(storeKey(k))) ?? LIMITS[k].default); | |
| 623 | return out; | |
| 624 | } | |
| 625 | ||
| 606 | 626 | /** Whether an admin has set `key` (rather than it being the default). */ |
| 607 | 627 | export function limitIsSet(db: Database, key: LimitKey): boolean { |
| 608 | 628 | const cap = capacityKey(key); |
src/tui/screens/crewbudgets.ts +4 −1
| @@ -16,6 +16,7 @@ import type { Session } from "../session.ts"; | ||
| 16 | 16 | import { style } from "../term/style.ts"; |
| 17 | 17 | import { drawLines, promptScreen, Scroll } from "./common.ts"; |
| 18 | 18 | import type { PaletteEntry } from "./entries.ts"; |
| 19 | import { crewFallbackScreen } from "./crewfallback.ts"; | |
| 19 | 20 | |
| 20 | 21 | const mayAct = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind === "user" && isOwnForge(f.app); |
| 21 | 22 | |
| @@ -48,7 +49,7 @@ export function crewBudgetsScreen(f: Session, ctx: Ctx): Screen { | ||
| 48 | 49 | let note = ""; |
| 49 | 50 | const screen: Screen = { |
| 50 | 51 | title: "Crew budgets", |
| 51 | keys: [binding(["j", "k"], "choose"), binding(["enter"], "set"), binding(["esc", "q"], "back")], | |
| 52 | keys: [binding(["j", "k"], "choose"), binding(["enter"], "set"), binding(["f"], "metered fallback"), binding(["esc", "q"], "back")], | |
| 52 | 53 | render(area, s) { |
| 53 | 54 | const c = ctx.theme.c; |
| 54 | 55 | const lines = [...budgetRows(f, chosen), ...(note === "" ? [] : ["", note])]; |
| @@ -59,6 +60,8 @@ export function crewBudgetsScreen(f: Session, ctx: Ctx): Screen { | ||
| 59 | 60 | if (e.key === "esc" || e.key === "q") ctx.pop(); |
| 60 | 61 | else if (e.key === "j" || e.key === "down") chosen = Math.min(chosen + 1, BUDGET_KEYS.length - 1); |
| 61 | 62 | else if (e.key === "k" || e.key === "up") chosen = Math.max(chosen - 1, 0); |
| 63 | // What the crew spends once its plans are full sits beside what it may spend. | |
| 64 | else if (e.key === "f") ctx.push(crewFallbackScreen(f, ctx)); | |
| 62 | 65 | else if (e.key === "enter" && mayAct(f)) |
| 63 | 66 | ctx.push( |
| 64 | 67 | promptScreen(ctx, screen, { |
src/tui/screens/crewfallback.ts added +95
| @@ -0,0 +1,95 @@ | ||
| 1 | /** | |
| 2 | * The crew's metered fallback in the terminal, the twin of Settings → Crew → Metered fallback | |
| 3 | * (`web/studio/crew_fallback.ts`): the plain line, the capped key's spend today, this week and | |
| 4 | * against its cap, the switch (`space`), the cap typed in place (`c`) with what it would last, and | |
| 5 | * `u` to put back the cap it had, then which account each running and recent run uses. One read | |
| 6 | * and the same two steps as the page (`crew/key_fallback.ts`). A forge admin who is a person only. | |
| 7 | */ | |
| 8 | ||
| 9 | import { capForecast, fallbackView, setFallback, setFallbackCap, type FallbackView } from "../../crew/key_fallback.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import { binding } from "../app/keys.ts"; | |
| 12 | import type { Session } from "../session.ts"; | |
| 13 | import { style } from "../term/style.ts"; | |
| 14 | import { drawLines, promptScreen, Scroll } from "./common.ts"; | |
| 15 | import type { PaletteEntry } from "./entries.ts"; | |
| 16 | ||
| 17 | const mayAct = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind === "user"; | |
| 18 | const usd = (n: number): string => `$${n.toFixed(2)}`; | |
| 19 | const AMOUNT = /^\d{1,6}(\.\d{1,2})?$/; | |
| 20 | ||
| 21 | /** The screen's lines, the page's figures in the same words; empty for anyone the gate refuses. */ | |
| 22 | export function fallbackLines(f: Session, v: FallbackView = fallbackView(f.app)): string[] { | |
| 23 | if (!mayAct(f)) return []; | |
| 24 | const k = v.key; | |
| 25 | return [ | |
| 26 | v.line, | |
| 27 | "", | |
| 28 | `The fallback is ${v.on ? "on" : "off"} (space turns it ${v.on ? "off" : "on"}).`, | |
| 29 | ...(k === undefined | |
| 30 | ? [] | |
| 31 | : [ | |
| 32 | `${k.name}: ${usd(k.todayUsd)} today · ${usd(k.weekUsd)} this week · ${usd(k.spentUsd)} of its ${usd(k.capUsd)} cap (${Math.round((k.spentUsd / k.capUsd) * 100)}%), at list price.`, | |
| 33 | `${capForecast(k)} c sets the cap.`, | |
| 34 | ]), | |
| 35 | "", | |
| 36 | "Which account each run uses:", | |
| 37 | ...v.runs.map((r) => ` ${r.repo} · ${r.reason} · ${r.state} · ${r.account} · ${usd(r.usd)}`), | |
| 38 | ]; | |
| 39 | } | |
| 40 | ||
| 41 | export function crewFallbackScreen(f: Session, ctx: Ctx): Screen { | |
| 42 | let note = ""; | |
| 43 | let was: number | undefined; | |
| 44 | const cap = (value: number): string | undefined => { | |
| 45 | const done = setFallbackCap(f.app, f.user, value); | |
| 46 | if (!done.ok) return done.error === "locked" ? "This key's cap can only come down." : "The cap is dollars and cents, more than $0, within the forge's budget limit."; | |
| 47 | was = done.value.from; | |
| 48 | note = `The cap is ${usd(done.value.to)} (it was ${usd(done.value.from)}); u puts it back.`; | |
| 49 | ctx.invalidate(); | |
| 50 | return undefined; | |
| 51 | }; | |
| 52 | const screen: Screen = { | |
| 53 | title: "Metered fallback", | |
| 54 | keys: [binding(["space"], "on/off"), binding(["c"], "set the cap"), binding(["u"], "undo the cap"), binding(["esc", "q"], "back")], | |
| 55 | render(area, s) { | |
| 56 | const c = ctx.theme.c; | |
| 57 | const lines = [...fallbackLines(f), ...(note === "" ? [] : ["", note])]; | |
| 58 | drawLines(s, area, c, new Scroll(), lines.map((text) => [{ text, style: style(c.fg, c.bg) }])); | |
| 59 | }, | |
| 60 | key(e) { | |
| 61 | if (e.ctrl || e.alt) return true; | |
| 62 | if (e.key === "esc" || e.key === "q") ctx.pop(); | |
| 63 | else if (e.key === "space" && mayAct(f)) { | |
| 64 | const on = !fallbackView(f.app).on; | |
| 65 | if (setFallback(f.app, f.user, on).ok) note = on ? "The fallback is on." : "The fallback is off: crew runs wait for the first window to reset."; | |
| 66 | } else if (e.key === "u" && mayAct(f) && was !== undefined) { | |
| 67 | const back = was; | |
| 68 | was = undefined; | |
| 69 | cap(back); | |
| 70 | } else if (e.key === "c" && mayAct(f)) | |
| 71 | ctx.push( | |
| 72 | promptScreen(ctx, screen, { | |
| 73 | title: "The key's cap (dollars)", | |
| 74 | label: "Dollars and cents", | |
| 75 | onSubmit: (value) => (AMOUNT.test(value.trim()) ? cap(Number(value.trim())) : "The cap is dollars and cents."), | |
| 76 | }), | |
| 77 | ); | |
| 78 | else return false; | |
| 79 | ctx.invalidate(); | |
| 80 | return true; | |
| 81 | }, | |
| 82 | }; | |
| 83 | return screen; | |
| 84 | } | |
| 85 | ||
| 86 | /** The crew's metered fallback: its switch, its cap, and which account each run uses. */ | |
| 87 | export const entry: PaletteEntry = { | |
| 88 | rank: 851, | |
| 89 | id: "crewfallback", | |
| 90 | title: "Metered fallback", | |
| 91 | hint: "the capped key the crew falls back to when every plan's window is full", | |
| 92 | after: ["crewbudgets"], | |
| 93 | offered: mayAct, | |
| 94 | run: (session, ctx) => ctx.push(crewFallbackScreen(session, ctx)), | |
| 95 | }; |
src/web/pages/capacity.ts +8 −17
| @@ -85,7 +85,7 @@ export function capacityPage(ctx: Ctx): Response { | ||
| 85 | 85 | const tableRow = (s: CapacityRow) => { |
| 86 | 86 | const low = belowCeiling(ctx.app.db, s.key); |
| 87 | 87 | const follows = s.source === "derived" ? html` · follows ${byKey.get("crew.concurrency")?.label}` : null; |
| 88 | const name = html`<span ${s.key === "children.originEgress" ? html`id="children-origin-egress"` : ""}>${s.label}</span> ${fold(s, follows)}${when( | |
| 88 | const name = html`<span${s.key === "children.originEgress" ? html` id="children-origin-egress"` : ""}>${s.label}</span> ${fold(s, follows)}${when( | |
| 89 | 89 | low !== null, |
| 90 | 90 | () => html` ${badge(`below ceiling ${low?.ceiling}`, { tone: "attn" })}`, |
| 91 | 91 | )}`; |
| @@ -93,30 +93,21 @@ export function capacityPage(ctx: Ctx): Response { | ||
| 93 | 93 | return html`<tr data-key="${s.key}"><td>${name}</td> |
| 94 | 94 | <td><span class="mono">${s.value === "git" ? "on" : "off"}</span></td> |
| 95 | 95 | <td><a href="${REACH_SETTINGS}">Set in Hosted forges</a></td></tr>`; |
| 96 | return html`<tr data-key="${s.key}"><td>${name}</td> | |
| 97 | <td>${s.source === "derived" | |
| 96 | // The fallback's switch, spend and cap live on its card (`studio/crew_fallback.ts`): one place. | |
| 97 | if (s.key === "crew.fallback") | |
| 98 | return html`<tr data-key="${s.key}"><td>${name}</td><td><span class="mono">${s.value}</span></td><td><a href="/settings/crew#fallback">Set in Crew</a></td></tr>`; | |
| 99 | return html`<tr data-key="${s.key}"><td>${name}</td><td>${s.source === "derived" | |
| 98 | 100 | ? html`<span class="mono" data-derived="${s.key}">${s.value}</span>` |
| 99 | 101 | : html`${input(s.key, s.value)}${when( |
| 100 | 102 | needsReason(s.key), |
| 101 | () => html`<input | |
| 102 | class="input" | |
| 103 | id="cap-${s.key}-reason" | |
| 104 | type="text" | |
| 105 | name="reason" | |
| 106 | maxlength="${String(REASON_MAX)}" | |
| 107 | autocomplete="off" | |
| 108 | placeholder="Why (needed to set report)" | |
| 109 | aria-label="Why (needed to set report)" | |
| 110 | />`, | |
| 111 | )}`}</td> | |
| 112 | <td class="small">${effects.get(s.key)}</td></tr>`; | |
| 103 | () => html`<input class="input" id="cap-${s.key}-reason" type="text" name="reason" maxlength="${String(REASON_MAX)}" autocomplete="off" placeholder="Why (needed to set report)" aria-label="Why (needed to set report)" />`, | |
| 104 | )}`}</td><td class="small">${effects.get(s.key)}</td></tr>`; | |
| 113 | 105 | }; |
| 114 | 106 | const table = html`<form method="post" action="/settings/capacity"> |
| 115 | 107 | <table class="table setting-table" data-dense aria-label="Capacity settings"> |
| 116 | 108 | <thead><tr><th>Setting</th><th>Value</th><th>Now</th></tr></thead> |
| 117 | 109 | ${CAPACITY_GROUPS.map( |
| 118 | (g) => html`<tbody><tr><th colspan="3" scope="colgroup">${g.title}</th></tr> | |
| 119 | ${g.keys.flatMap((k) => byKey.get(k) ?? []).map(tableRow)}</tbody>`, | |
| 110 | (g) => html`<tbody><tr><th colspan="3" scope="colgroup">${g.title}</th></tr>${g.keys.flatMap((k) => byKey.get(k) ?? []).map(tableRow)}</tbody>`, | |
| 120 | 111 | )} |
| 121 | 112 | </table> |
| 122 | 113 | <p class="mt">${btn("Save", { variant: "primary", label: "Save the changed settings" })}</p> |
src/web/pages/crew.ts +2
| @@ -11,6 +11,7 @@ import { crewTop, TOP_HELP } from "../crew_top.ts"; | ||
| 11 | 11 | import { sshOn } from "../../settings/ssh.ts"; |
| 12 | 12 | import { USERNAME_PATTERN } from "../username_pattern.ts"; |
| 13 | 13 | import { budgetsCard } from "../studio/crew_budgets.ts"; |
| 14 | import { fallbackCard } from "../studio/crew_fallback.ts"; | |
| 14 | 15 | import { plannerCardView } from "../studio/planner_card.ts"; |
| 15 | 16 | import { crewKeyField } from "../studio/crew_key.ts"; |
| 16 | 17 | import { fundingOf, fundingWords } from "../../spawn/funding.ts"; |
| @@ -749,6 +750,7 @@ function crewView( | ||
| 749 | 750 | ["Model review", `At most one change of model per agent a week, to the cheapest that holds its quality. A step up always asks; a step down ${review.limits.auto ? "applies on its own" : "asks too"} (Settings → Limits). Under ${review.limits.minLanded} landed changes nothing. A week after a change the result is reported, and the change undone if quality fell. An ask nobody answers lapses after two weeks. Weekly, from the last ${review.windowDays} days of the ledger.`], |
| 750 | 751 | ], helpAsked(ctx.request.url))} |
| 751 | 752 | ${budgetsCard(ctx)} |
| 753 | ${fallbackCard(ctx)} | |
| 752 | 754 | ${knobsCard(ctx)} |
| 753 | 755 | ${plannerCardView(ctx)} |
| 754 | 756 | ${when(spending.length > 0, () => |
src/web/studio/crew_fallback.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 2 | * Settings → Crew → Metered fallback (`crew/key_fallback.ts`): which account each running and | |
| 3 | * recent run uses, the capped key's spend today, this week and against its cap as a meter, the | |
| 4 | * switch, the cap edited in place with what it would last and Undo, and one plain line. A forge | |
| 5 | * admin's card; the key itself is never shown, only its name and figures. The terminal's twin is | |
| 6 | * `tui/screens/crewfallback.ts`. | |
| 7 | */ | |
| 8 | ||
| 9 | import { capForecast, fallbackView, setFallback, setFallbackCap } from "../../crew/key_fallback.ts"; | |
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { notFoundPage, signInFirst } from "../chrome.ts"; | |
| 12 | import { field, readForm } from "../form.ts"; | |
| 13 | import { html, type Html } from "../html.ts"; | |
| 14 | import { flashTo } from "../layout.ts"; | |
| 15 | import { btn, meter, row, rowList } from "../ui.ts"; | |
| 16 | ||
| 17 | export const FALLBACK_ACTION = "/settings/crew/fallback"; | |
| 18 | export const FALLBACK_CAP_ACTION = "/settings/crew/fallback/cap"; | |
| 19 | const usd = (n: number): string => `$${n.toFixed(2)}`; | |
| 20 | const AMOUNT = /^\d{1,6}(\.\d{1,2})?$/; | |
| 21 | ||
| 22 | /** The card; null for anyone who is not a forge admin. `was` is the cap before the last change, for Undo. */ | |
| 23 | export function fallbackCard(ctx: Ctx): Html | null { | |
| 24 | if (ctx.auth.user?.isAdmin !== true) return null; | |
| 25 | const v = fallbackView(ctx.app); | |
| 26 | const was = Number(ctx.url.searchParams.get("was") ?? ""); | |
| 27 | const k = v.key; | |
| 28 | return html`<section class="settings-block" id="fallback"> | |
| 29 | <h2>Metered fallback</h2> | |
| 30 | <p data-fallback-line>${v.line}</p> | |
| 31 | <form class="bar" method="post" action="${FALLBACK_ACTION}"> | |
| 32 | <input type="hidden" name="on" value="${v.on ? "off" : "on"}" /> | |
| 33 | <span class="small">The fallback is <b>${v.on ? "on" : "off"}</b>.</span> | |
| 34 | ${btn(v.on ? "Turn it off" : "Turn it on", { size: "sm" })} | |
| 35 | </form> | |
| 36 | ${k === undefined | |
| 37 | ? null | |
| 38 | : html`<div class="mt"> | |
| 39 | ${meter(Math.min(100, (k.spentUsd / k.capUsd) * 100), `${k.name}: ${usd(k.spentUsd)} of its ${usd(k.capUsd)} cap`, k.spentUsd >= k.capUsd * 0.8 ? "attn" : undefined)} | |
| 40 | <p class="small muted">${k.name}: ${usd(k.todayUsd)} today · ${usd(k.weekUsd)} this week · ${usd(k.spentUsd)} of its ${usd(k.capUsd)} cap, at list price.</p> | |
| 41 | <form class="bar mt" method="post" action="${FALLBACK_CAP_ACTION}"> | |
| 42 | <label for="fallback-cap" class="small">Cap (dollars)</label> | |
| 43 | <input class="input" id="fallback-cap" name="cap" type="number" min="1" step="0.01" required value="${k.capUsd.toFixed(2)}" inputmode="decimal" data-size="sm" /> | |
| 44 | ${btn("Set the cap", { size: "sm" })} | |
| 45 | </form> | |
| 46 | <p class="small muted" data-fallback-forecast>${capForecast(k)}</p> | |
| 47 | ${Number.isFinite(was) && was > 0 && was !== k.capUsd | |
| 48 | ? html`<form class="bar" method="post" action="${FALLBACK_CAP_ACTION}"> | |
| 49 | <input type="hidden" name="cap" value="${was.toFixed(2)}" /> | |
| 50 | <span class="small">The cap was ${usd(was)}.</span> | |
| 51 | ${btn("Undo", { size: "sm" })} | |
| 52 | </form>` | |
| 53 | : null} | |
| 54 | </div>`} | |
| 55 | <h3 class="mt">Which account each run uses</h3> | |
| 56 | ${rowList( | |
| 57 | v.runs.map((r) => row({ href: `/${r.repo}/runs/${r.id}`, title: `${r.repo} · ${r.reason}`, meta: html`${r.state} · ${r.account} · ${usd(r.usd)}` })), | |
| 58 | { bare: true, label: "Which account each run uses" }, | |
| 59 | )} | |
| 60 | </section>`; | |
| 61 | } | |
| 62 | ||
| 63 | const admin = (ctx: Ctx): Response | undefined => { | |
| 64 | const user = ctx.auth.user; | |
| 65 | if (!user) return signInFirst(ctx); | |
| 66 | if (!user.isAdmin) return notFoundPage(ctx); | |
| 67 | return undefined; | |
| 68 | }; | |
| 69 | ||
| 70 | // POST /settings/crew/fallback | |
| 71 | export async function fallbackSave(ctx: Ctx): Promise<Response> { | |
| 72 | const denied = admin(ctx); | |
| 73 | if (denied) return denied; | |
| 74 | const form = await readForm(ctx, "admin", 256); | |
| 75 | if (form instanceof Response) return form; | |
| 76 | const on = field(form, "on") === "on"; | |
| 77 | const done = setFallback(ctx.app, ctx.auth.user, on); | |
| 78 | if (!done.ok) return notFoundPage(ctx); | |
| 79 | return flashTo(ctx, "/settings/crew#fallback", { | |
| 80 | message: on ? "The fallback is on: the capped key takes crew runs once every plan's window is full." : "The fallback is off: crew runs wait for the first window to reset.", | |
| 81 | }); | |
| 82 | } | |
| 83 | ||
| 84 | // POST /settings/crew/fallback/cap | |
| 85 | export async function fallbackCapSave(ctx: Ctx): Promise<Response> { | |
| 86 | const denied = admin(ctx); | |
| 87 | if (denied) return denied; | |
| 88 | const form = await readForm(ctx, "admin", 256); | |
| 89 | if (form instanceof Response) return form; | |
| 90 | const raw = field(form, "cap").trim(); | |
| 91 | const done = AMOUNT.test(raw) ? setFallbackCap(ctx.app, ctx.auth.user, Number(raw)) : ({ ok: false, error: "invalid" } as const); | |
| 92 | if (!done.ok) | |
| 93 | return done.error === "not_found" | |
| 94 | ? notFoundPage(ctx) | |
| 95 | : flashTo(ctx, "/settings/crew#fallback", { tone: "danger", message: done.error === "locked" ? "This key's cap was set by whoever made this forge: it can only come down." : "The cap is dollars and cents, more than $0, within the forge's budget limit." }); | |
| 96 | return flashTo(ctx, `/settings/crew?was=${done.value.from.toFixed(2)}#fallback`, { message: `The cap is ${usd(done.value.to)} (it was ${usd(done.value.from)}); Undo is beside it.` }); | |
| 97 | } |
test/capacity-first-view.test.ts +4 −3
| @@ -61,14 +61,15 @@ function words(page: string): number { | ||
| 61 | 61 | test("the first view: under 800 words and 26 KB with every row folded, every setting beside its live effect", async () => { |
| 62 | 62 | const page = await get(); |
| 63 | 63 | // The page's own part (what the shell around it is not): under 26 KB raw with every fold closed. |
| 64 | // It was 25 KB for 20 rows; the 21st, checks.verifyShards (#16671), costs about 0.8 KB folded. | |
| 64 | // It was 25 KB for 20 rows; the 21st, checks.verifyShards (#16671), costs about 0.8 KB folded. The | |
| 65 | // 22nd, crew.fallback, points to its card on the Crew page and was paid for by tighter row markup. | |
| 65 | 66 | const main = page.slice(page.indexOf('class="settings-main"'), page.indexOf("</main>")); |
| 66 | 67 | expect(new TextEncoder().encode(main).length).toBeLessThan(26_000); |
| 67 | 68 | expect(words(page)).toBeLessThan(800); |
| 68 | 69 | const rows = [...page.matchAll(/<tr data-key="([^"]+)">/g)].map((m) => m[1]); |
| 69 | expect(rows.length).toBe(21); | |
| 70 | expect(rows.length).toBe(22); | |
| 70 | 71 | // The rest is behind one ⓘ per row, closed. |
| 71 | expect(page.match(/<details class="hint why"/g)).toHaveLength(21); | |
| 72 | expect(page.match(/<details class="hint why"/g)).toHaveLength(22); | |
| 72 | 73 | expect(page).not.toMatch(/<details[^>]*\sopen/); |
| 73 | 74 | expect(page).toContain("running"); |
| 74 | 75 | expect(page).toContain("queued"); |
test/crew-key-fallback.test.ts added +187
| @@ -0,0 +1,187 @@ | ||
| 1 | /** | |
| 2 | * The crew's metered fallback (`crew/key_fallback.ts`): a plan whose window is full (no more free | |
| 3 | * than its share kept for people) is passed over by a crew run's pick, which then takes a | |
| 4 | * pay-per-token key, one with a cap first, while the switch is on and the cap holds; off or capped, | |
| 5 | * the run waits for the first window to reset, and says which. A person's | |
| 6 | * Talk turn weighs none of it. Reviews start first while the key takes the crew's runs. Both | |
| 7 | * doors, Settings → Crew and the terminal's Metered fallback, show the same line and figures, the | |
| 8 | * switch and the cap with its Undo; the key itself is never shown. The week's share kept for people | |
| 9 | * holds the crew again (the unmeasured key had switched it off), unless the capped key may take over. | |
| 10 | */ | |
| 11 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 12 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 13 | import { tmpdir } from "node:os"; | |
| 14 | import { join } from "node:path"; | |
| 15 | import { createApp, type App } from "../src/app.ts"; | |
| 16 | import { addSubscription, pickSubscription, setBudget, type Pick } from "../src/core/subscriptions.ts"; | |
| 17 | import { createSession } from "../src/core/sessions.ts"; | |
| 18 | import { createUser, type User } from "../src/core/users.ts"; | |
| 19 | import type { Run } from "../src/core/runs.ts"; | |
| 20 | import { crewPick, fallbackActive, fallbackOn, fallbackView, reviewsFirst, setFallback, setFallbackCap, weekHolds } from "../src/crew/key_fallback.ts"; | |
| 21 | import { weekHold } from "../src/crew/week_hold.ts"; | |
| 22 | import { weekFor } from "../src/crew/week_read.ts"; | |
| 23 | import { createRepo } from "../src/actions/repos.ts"; | |
| 24 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 25 | import { fallbackLines } from "../src/tui/screens/crewfallback.ts"; | |
| 26 | import type { Session } from "../src/tui/session.ts"; | |
| 27 | import { quietLogs } from "./helpers/globals.ts"; | |
| 28 | ||
| 29 | quietLogs(); | |
| 30 | let dir: string, app: App, servers: Servers, alice: User; | |
| 31 | let planId = "", keyId = ""; | |
| 32 | const KEY_TOKEN = "sk-ant-api03-never-shown-0123456789"; | |
| 33 | const scope = () => ({ repoId: "", ownerId: alice.id, agentId: "" }); | |
| 34 | const nameOf = (p: Pick): string => (p.kind === "ready" ? p.subscription.name : p.kind); | |
| 35 | const crewPickNow = () => pickSubscription(app.db, dir, scope(), new Date(), undefined, crewPick(app.db)); | |
| 36 | const inAnHour = () => new Date(Date.now() + 3_600_000).toISOString(); | |
| 37 | ||
| 38 | /** The plan's 5-hour window as the provider last said: `used` percent, resetting in an hour. */ | |
| 39 | const measure = (used: number) => | |
| 40 | app.db | |
| 41 | .query("INSERT INTO subscription_measure (subscription_id, span, used_pct, resets_at, observed_at) VALUES (?1, '5h', ?2, ?3, ?4) ON CONFLICT (subscription_id, span) DO UPDATE SET used_pct = excluded.used_pct, resets_at = excluded.resets_at, observed_at = excluded.observed_at") | |
| 42 | .run(planId, used, inAnHour(), new Date().toISOString()); | |
| 43 | ||
| 44 | beforeAll(async () => { | |
| 45 | dir = await mkdtemp(join(tmpdir(), "forge-key-fallback-")); | |
| 46 | app = createApp({ dataDir: dir, port: 0 }); | |
| 47 | servers = await serve(app); | |
| 48 | const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 49 | if (!u.ok) throw new Error(u.error); | |
| 50 | alice = u.value; | |
| 51 | const plan = addSubscription(app.db, dir, { name: "plan-a", token: "sk-ant-oat01-plan-token-0123456789", createdBy: alice.id }); | |
| 52 | const key = addSubscription(app.db, dir, { name: "key-a", token: KEY_TOKEN, createdBy: alice.id }); | |
| 53 | if (!plan.ok || !key.ok) throw new Error("subscriptions"); | |
| 54 | planId = plan.value.id; | |
| 55 | keyId = key.value.id; | |
| 56 | expect(setBudget(app.db, keyId, 500)).toBe(true); | |
| 57 | }, 30_000); | |
| 58 | ||
| 59 | afterAll(async () => { | |
| 60 | servers.stop(); | |
| 61 | app.close(); | |
| 62 | await rm(dir, { recursive: true, force: true }); | |
| 63 | }); | |
| 64 | ||
| 65 | test("a fresh forge holds the crew's run when every plan is full: the fallback is off until the owner turns it on", () => { | |
| 66 | expect(fallbackOn(app.db)).toBe(false); | |
| 67 | expect(fallbackView(app).on).toBe(false); | |
| 68 | measure(100); | |
| 69 | expect(crewPickNow().kind).toBe("resting"); | |
| 70 | expect(fallbackActive(app.db)).toBe(false); | |
| 71 | expect(setFallback(app, alice, true).ok).toBe(true); | |
| 72 | }); | |
| 73 | ||
| 74 | test("a plan with room takes the crew's run; full, the capped key does; a person's turn still takes the plan", () => { | |
| 75 | expect(fallbackOn(app.db)).toBe(true); | |
| 76 | measure(40); | |
| 77 | expect(nameOf(crewPickNow())).toBe("plan-a"); | |
| 78 | measure(100); | |
| 79 | expect(nameOf(crewPickNow())).toBe("key-a"); | |
| 80 | expect(fallbackActive(app.db)).toBe(true); | |
| 81 | // Talk weighs no window: the plan is the person's to use. | |
| 82 | expect(nameOf(pickSubscription(app.db, dir, scope(), new Date()))).toBe("plan-a"); | |
| 83 | }); | |
| 84 | ||
| 85 | test("the share kept for people counts as full: 85% used with 20% kept passes the plan over", () => { | |
| 86 | app.db.query("UPDATE subscription SET headroom_pct = 20 WHERE id = ?1").run(planId); | |
| 87 | measure(85); | |
| 88 | expect(nameOf(crewPickNow())).toBe("key-a"); | |
| 89 | measure(70); | |
| 90 | expect(nameOf(crewPickNow())).toBe("plan-a"); | |
| 91 | app.db.query("UPDATE subscription SET headroom_pct = 0 WHERE id = ?1").run(planId); | |
| 92 | }); | |
| 93 | ||
| 94 | test("off, the run waits for the plan's window and says which; on again, the key takes it", () => { | |
| 95 | measure(100); | |
| 96 | expect(setFallback(app, alice, false).ok).toBe(true); | |
| 97 | const waits = crewPickNow(); | |
| 98 | expect(waits.kind).toBe("resting"); | |
| 99 | if (waits.kind === "resting") expect(waits.said).toBe("plan-a's 5-hour window is full for the crew (the rest is kept for people)"); | |
| 100 | expect(fallbackView(app).line).toMatch(/^The fallback is off: reviews wait for plan-a's window, resets \d\d:\d\d UTC\.$/); | |
| 101 | expect(setFallback(app, alice, true).ok).toBe(true); | |
| 102 | expect(nameOf(crewPickNow())).toBe("key-a"); | |
| 103 | }); | |
| 104 | ||
| 105 | test("at its cap the key takes nothing; without a cap it is the fallback after any key that has one", () => { | |
| 106 | measure(100); | |
| 107 | app.db.query("UPDATE subscription SET spent_usd = 500 WHERE id = ?1").run(keyId); | |
| 108 | expect(crewPickNow().kind).toBe("resting"); | |
| 109 | expect(fallbackView(app).line).toContain("key-a has reached its $500.00 cap: reviews wait for plan-a's window"); | |
| 110 | app.db.query("UPDATE subscription SET spent_usd = 0 WHERE id = ?1").run(keyId); | |
| 111 | const open = addSubscription(app.db, dir, { name: "aaa-uncapped", token: "sk-or-v1-uncapped-0123456789", createdBy: alice.id }); | |
| 112 | if (!open.ok) throw new Error("uncapped"); | |
| 113 | // Used longest ago and first by name, yet the capped key goes first. | |
| 114 | expect(nameOf(crewPickNow())).toBe("key-a"); | |
| 115 | app.db.query("UPDATE subscription SET budget_usd = NULL WHERE id = ?1").run(keyId); | |
| 116 | expect(nameOf(crewPickNow())).not.toBe("plan-a"); | |
| 117 | expect(setBudget(app.db, keyId, 500)).toBe(true); | |
| 118 | app.db.query("DELETE FROM subscription WHERE id = ?1").run(open.value.id); | |
| 119 | }); | |
| 120 | ||
| 121 | test("the week's share kept for people holds the crew again, unless the capped key may take its runs", async () => { | |
| 122 | // Since #16498 the always-unmeasured key made every week unmeasured, and the hold held nothing. | |
| 123 | const made = await createRepo(app, alice, { name: "weekly", visibility: "private" }); | |
| 124 | if (!made.ok) throw new Error(String(made.error)); | |
| 125 | app.db.query("UPDATE subscription SET headroom_pct = 20 WHERE id = ?1").run(planId); | |
| 126 | app.db | |
| 127 | .query("INSERT INTO subscription_measure (subscription_id, span, used_pct, resets_at, observed_at) VALUES (?1, 'week', 80, ?2, ?3) ON CONFLICT (subscription_id, span) DO UPDATE SET used_pct = 80, resets_at = excluded.resets_at, observed_at = excluded.observed_at") | |
| 128 | .run(planId, new Date(Date.now() + 3 * 86_400_000).toISOString(), new Date().toISOString()); | |
| 129 | const paced = weekHold(weekFor(app, made.value, new Date())); | |
| 130 | expect(paced).not.toBeNull(); | |
| 131 | // On, under its cap: the run goes on, and the pick passes the plan over for the key. | |
| 132 | expect(weekHolds(app.db, paced)).toBe(false); | |
| 133 | measure(10); | |
| 134 | expect(nameOf(crewPickNow())).toBe("key-a"); | |
| 135 | // Off: the hold holds. | |
| 136 | setFallback(app, alice, false); | |
| 137 | expect(weekHolds(app.db, paced)).toBe(true); | |
| 138 | setFallback(app, alice, true); | |
| 139 | // Capped: the hold holds. | |
| 140 | app.db.query("UPDATE subscription SET spent_usd = 500 WHERE id = ?1").run(keyId); | |
| 141 | expect(weekHolds(app.db, paced)).toBe(true); | |
| 142 | app.db.query("UPDATE subscription SET spent_usd = 0 WHERE id = ?1").run(keyId); | |
| 143 | app.db.query("UPDATE subscription SET headroom_pct = 0 WHERE id = ?1").run(planId); | |
| 144 | app.db.query("DELETE FROM subscription_measure WHERE subscription_id = ?1 AND span = 'week'").run(planId); | |
| 145 | }); | |
| 146 | ||
| 147 | test("while the key takes the crew's runs, reviews start first, each side in its order", () => { | |
| 148 | const run = (id: string, reason: string) => ({ id, reason }) as unknown as Run; | |
| 149 | expect(reviewsFirst([run("a", "assigned"), run("b", "review"), run("c", "feedback"), run("d", "review")]).map((r) => r.id)).toEqual(["b", "d", "a", "c"]); | |
| 150 | }); | |
| 151 | ||
| 152 | test("the cap changes in place with its forecast, and Undo puts back the cap it had", () => { | |
| 153 | const set = setFallbackCap(app, alice, 250); | |
| 154 | expect(set.ok && set.value).toEqual({ from: 500, to: 250 }); | |
| 155 | expect(fallbackView(app).key?.capUsd).toBe(250); | |
| 156 | const back = setFallbackCap(app, alice, 500); | |
| 157 | expect(back.ok && back.value.to).toBe(500); | |
| 158 | expect(setFallbackCap(app, { ...alice, isAdmin: false }, 100).ok).toBe(false); | |
| 159 | }); | |
| 160 | ||
| 161 | test("both doors: the page and the terminal show the same line, the key's figures and the runs, never the key", async () => { | |
| 162 | measure(100); | |
| 163 | const cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 164 | const page = (await (await fetch(`${servers.url}/settings/crew`, { headers: { cookie } })).text()).replace(/'/g, "'").replace(/\s+/g, " "); | |
| 165 | const v = fallbackView(app); | |
| 166 | expect(page).toContain('id="fallback"'); | |
| 167 | expect(page).toContain(v.line); | |
| 168 | expect(page).toContain("key-a: $0.00 today · $0.00 this week · $0.00 of its $500.00 cap, at list price."); | |
| 169 | expect(page).toContain('action="/settings/crew/fallback"'); | |
| 170 | expect(page).toContain('action="/settings/crew/fallback/cap"'); | |
| 171 | expect(page).not.toContain(KEY_TOKEN); | |
| 172 | const lines = fallbackLines({ app, user: alice } as unknown as Session); | |
| 173 | expect(lines[0]).toBe(v.line); | |
| 174 | expect(lines.join("\n")).toContain("key-a: $0.00 today · $0.00 this week · $0.00 of its $500.00 cap (0%), at list price."); | |
| 175 | expect(lines.join("\n")).not.toContain(KEY_TOKEN); | |
| 176 | // The switch, through the page's POST: off, then the line says so on both doors. | |
| 177 | const off = await fetch(`${servers.url}/settings/crew/fallback`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url, cookie }, body: new URLSearchParams({ on: "off" }) }); | |
| 178 | expect(off.status).toBe(303); | |
| 179 | expect(fallbackOn(app.db)).toBe(false); | |
| 180 | expect(fallbackLines({ app, user: alice } as unknown as Session)[0]).toMatch(/^The fallback is off/); | |
| 181 | // The cap, through the page's POST, then its Undo beside it. | |
| 182 | const cap = await fetch(`${servers.url}/settings/crew/fallback/cap`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url, cookie }, body: new URLSearchParams({ cap: "300" }) }); | |
| 183 | expect(cap.headers.get("location")).toContain("was=500.00"); | |
| 184 | const after = (await (await fetch(`${servers.url}/settings/crew?was=500.00`, { headers: { cookie } })).text()).replace(/\s+/g, " "); | |
| 185 | expect(after).toContain("The cap was $500.00."); | |
| 186 | expect(after).toContain('name="cap" value="500.00"'); | |
| 187 | }); |
test/palette-roster.test.ts +1
| @@ -230,6 +230,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 230 | 230 | ["registry-items", "Component registry", "the forge's parts; install one into an app"], |
| 231 | 231 | ["archived", "Archived repositories", "put away, not gone: open one or restore it"], |
| 232 | 232 | ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"], |
| 233 | ["crewfallback", "Metered fallback", "the capped key the crew falls back to when every plan's window is full"], | |
| 233 | 234 | ["planner", "Planner", "its last pass, its spend this week and what became of what it filed"], |
| 234 | 235 | ["cloud", "Cloud accounts", "provider tokens, what they are used for, today's calls"], |
| 235 | 236 | ["infra", "Infrastructure", "what runs on your own cloud, what it costs, when it ends"], |
test/settings-visible.test.ts +9
| @@ -89,6 +89,15 @@ test("every capacity row shows its value and control, hover-free", async () => { | ||
| 89 | 89 | expect(moved).not.toContain("<form"); |
| 90 | 90 | continue; |
| 91 | 91 | } |
| 92 | // the crew's metered fallback is switched on its card, Settings → Crew: its row points there | |
| 93 | if (s.key === "crew.fallback") { | |
| 94 | const row = rowsOf(page).find((r) => r.includes('id="why-cap-crew.fallback"')); | |
| 95 | expect(row, s.key).toBeDefined(); | |
| 96 | expect(row).toContain(s.label); | |
| 97 | expect(row).toContain('href="/settings/crew#fallback"'); | |
| 98 | expect(row).not.toContain("<form"); | |
| 99 | continue; | |
| 100 | } | |
| 92 | 101 | // a row derived from Speed is read-only: its value, no form |
| 93 | 102 | const mark = s.source === "derived" ? `data-derived="${s.key}"` : `name="v.${s.key}"`; |
| 94 | 103 | const row = rowsOf(page).find((r) => r.includes(mark)); |
test/subscriptions.test.ts +3
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { getHeadroom, setHeadroom } from "../src/core/standing.ts"; |
| 2 | 2 | import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; |
| 3 | import { setCapacity } from "../src/core/capacity.ts"; | |
| 3 | 4 | import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs"; |
| 4 | 5 | import { mkdtemp, rm } from "node:fs/promises"; |
| 5 | 6 | import { tmpdir } from "node:os"; |
| @@ -363,6 +364,8 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW | ||
| 363 | 364 | }); |
| 364 | 365 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); |
| 365 | 366 | expect(addToCrew(app, alice, repo, "bot").ok).toBe(true); |
| 367 | // The work key takes the run the refused token cannot only with the metered fallback on (off by default). | |
| 368 | setCapacity(app.db, "crew.fallback", "on", alice.id, "the key may take the crew's runs"); | |
| 366 | 369 | }, 30_000); |
| 367 | 370 | |
| 368 | 371 | afterAll(async () => { |
test/usage.test.ts +3
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 8 | import { setCapacity } from "../src/core/capacity.ts"; | |
| 8 | 9 | import { chmodSync, writeFileSync } from "node:fs"; |
| 9 | 10 | import { mkdtemp, rm } from "node:fs/promises"; |
| 10 | 11 | import { tmpdir } from "node:os"; |
| @@ -380,6 +381,8 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW | ||
| 380 | 381 | const work = addSubscription(app.db, dataDir, { name: "work", token: KEY }); |
| 381 | 382 | if (!personal.ok || !work.ok) throw new Error("pool"); |
| 382 | 383 | setGrants(app.db, repo.id, EVERYONE, [personal.value.id, work.value.id]); |
| 384 | // The key takes the run the plan cannot only once the owner turns the metered fallback on (off by default). | |
| 385 | setCapacity(app.db, "crew.fallback", "on", alice.id, "the key may take the crew's runs"); | |
| 383 | 386 | const issue = openIssue(app, alice, repo, { title: "Plant tulips", body: "" }); |
| 384 | 387 | if (!issue.ok) throw new Error(String(issue.error)); |
| 385 | 388 | expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true); |
new above
offline
High: default must be "off". A fresh forge should hold the run when every plan's window is full, and spend on the key only after the owner switches it on in Settings → Crew. Add a test pinning that default.