Public: anyone can read this; the crew can change it.
From outside: Crew run cost is reported on the issue but never lands in any credit counter #13731
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/13715-from-outside-crew-run-cost-is-reported-o → main 5 commits fork
9 files
changed +255
−31
docs/features/child-credit.md +10
| @@ -52,3 +52,13 @@ crew calls the model through the parent; the child never holds the credential. | ||
| 52 | 52 | own credential names. |
| 53 | 53 | - Not done: a spawn-time cap field (the PUT is the one door), and a funded hosted (in-process) child, |
| 54 | 54 | which has no door to call. |
| 55 | ||
| 56 | ## Run cost the host did not count (#13715) | |
| 57 | A run's end asks the host what it counted (`runEnded`) and compares it with the count the run started with. When the run cost something by its own account, ran on the included credit (not the owner's own key) and the host's count has not risen since it began, that run's cost alone (never a sum) is kept as `uncountedUsd` in `parent.json`. The included-credit line on `/settings/subscriptions`, the plan line and the terminal's crew-key line then say "A run cost $0.78 that this credit did not count." The note clears when the host's count next moves, on a run's end or on the heartbeat (`syncFunding`). | |
| 58 | ||
| 59 | The note is a hint, not a figure, and it can be wrong: | |
| 60 | - The host may count the run late. The note then shows until the count moves. | |
| 61 | - Two runs that end together are each judged against their own start. Another run's counted spend makes this run look counted (the note stays silent when it should speak). Both runs uncounted shows the later one's cost, not both. | |
| 62 | - An unknown count, at the start or at the end, says nothing. | |
| 63 | ||
| 64 | Why the cost never reached the counter in the first place is not found here. That cause is tracked on #13762. |
src/actions/crew_means.ts +6 −1
| @@ -13,8 +13,13 @@ export interface Included { | ||
| 13 | 13 | /** What the host counted the runs cost; a reservation or declared budget is never in it. */ |
| 14 | 14 | readonly spentUsd: number; |
| 15 | 15 | readonly leftUsd: number; |
| 16 | /** The last run's cost the host's count did not rise by (#13715), a hint; absent when none. */ | |
| 17 | readonly uncountedUsd?: number; | |
| 16 | 18 | } |
| 17 | 19 | |
| 20 | /** The sentence that says a run's cost the credit did not count, or "" when there is none. */ | |
| 21 | export const uncountedWords = (usd: number): string => (usd > 0 ? ` A run cost $${usd.toFixed(2)} that this credit did not count.` : ""); | |
| 22 | ||
| 18 | 23 | /** |
| 19 | 24 | * The credit this forge came with and what is left of it (last heard from its host), or undefined |
| 20 | 25 | * when it has none. |
| @@ -23,7 +28,7 @@ export function includedCredit(app: App): Included | undefined { | ||
| 23 | 28 | const f = fundingOf(app.config.dataDir); |
| 24 | 29 | if (f === undefined || f.capUsd === null) return undefined; |
| 25 | 30 | const spentUsd = f.spentUsd ?? 0; |
| 26 | return { capUsd: f.capUsd, spentUsd, leftUsd: leftUsd({ capUsd: f.capUsd, spentUsd }) }; | |
| 31 | return { capUsd: f.capUsd, spentUsd, leftUsd: leftUsd({ capUsd: f.capUsd, spentUsd }), ...(f.uncountedUsd === undefined ? {} : { uncountedUsd: f.uncountedUsd }) }; | |
| 27 | 32 | } |
| 28 | 33 | |
| 29 | 34 | /** Whether the crew can run: a key of the owner's, or included credit with money left. */ |
src/crew/runner.ts +5 −2
| @@ -207,7 +207,7 @@ import { | ||
| 207 | 207 | } from "./guard.ts"; |
| 208 | 208 | import { passportEnv } from "./passport_env.ts"; |
| 209 | 209 | import { hostOfApiBase, isGatewayAddress, ownEnv, sandboxTmpEnv } from "./runner_env.ts"; |
| 210 | import { cappedByLent, fundedEnv, lentCreditLeft, refreshFundingOnce, runEnded } from "../spawn/funding.ts"; | |
| 210 | import { cappedByLent, fundedEnv, fundingOf, lentCost, lentCreditLeft, refreshFundingOnce, runEnded } from "../spawn/funding.ts"; | |
| 211 | 211 | |
| 212 | 212 | const log = createLog("crew"); |
| 213 | 213 | |
| @@ -997,6 +997,9 @@ async function work( | ||
| 997 | 997 | ran: Ran, |
| 998 | 998 | ): Promise<Outcome> { |
| 999 | 999 | const began = new Date().toISOString(); |
| 1000 | // What the host had counted when this run began: its end is judged against this, not against | |
| 1001 | // what another run's end left in the copy (#13715). | |
| 1002 | const spentAtStart = fundingOf(app.config.dataDir)?.spentUsd ?? null; | |
| 1000 | 1003 | const repo = getRepoById(app.db, run.repoId); |
| 1001 | 1004 | const issue = |
| 1002 | 1005 | run.issueId === null ? undefined : getIssueById(app.db, run.issueId); |
| @@ -1973,7 +1976,7 @@ async function work( | ||
| 1973 | 1976 | if (runTmp !== undefined) await rm(runTmp, { recursive: true, force: true }); |
| 1974 | 1977 | // The host counted what the run cost: ask it now, so the credit line moves |
| 1975 | 1978 | // when a run spends (#11948). |
| 1976 | void runEnded(app); | |
| 1979 | void runEnded(app, fetch, { costUsd: lentCost(app, getRun(app.db, run.id)?.costUsd ?? 0), spentAtStart }); | |
| 1977 | 1980 | } |
| 1978 | 1981 | } |
| 1979 | 1982 |
src/spawn/funding.ts +73 −20
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * is good for nothing but that door. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { crewHasCredential } from "../core/subscriptions.ts"; | |
| 11 | 12 | import { join } from "node:path"; |
| 12 | 13 | import type { App } from "../app.ts"; |
| 13 | 14 | import { readPrivate, writePrivate } from "../kernel/file_modes.ts"; |
| @@ -19,6 +20,12 @@ export interface Funding { | ||
| 19 | 20 | readonly token: string; |
| 20 | 21 | readonly capUsd: number | null; |
| 21 | 22 | readonly spentUsd: number | null; |
| 23 | /** | |
| 24 | * What the last run cost by its own account when the host's count did not rise between its | |
| 25 | * start and its end (#13715). A hint, not a figure: the host may count it late. Cleared when | |
| 26 | * the host's count next moves. | |
| 27 | */ | |
| 28 | readonly uncountedUsd?: number; | |
| 22 | 29 | } |
| 23 | 30 | |
| 24 | 31 | const BEARER = /^[\x21-\x7e]{8,200}$/; |
| @@ -26,7 +33,8 @@ const file = (dataDir: string): string => join(dataDir, "parent.json"); | ||
| 26 | 33 | |
| 27 | 34 | function readDoc(dataDir: string): Record<string, unknown> | undefined { |
| 28 | 35 | try { |
| 29 | // Its own regular file and nothing a link there names: the parent reads this in a child's directory, and writes it back. | |
| 36 | // Its own regular file and nothing a link there names: the parent reads this in a child's | |
| 37 | // directory, and writes it back. | |
| 30 | 38 | const d = JSON.parse(readPrivate(file(dataDir)) ?? ""); |
| 31 | 39 | return typeof d === "object" && d !== null && !Array.isArray(d) ? (d as Record<string, unknown>) : undefined; |
| 32 | 40 | } catch { |
| @@ -40,16 +48,17 @@ const sum = (v: unknown): number | null => (typeof v === "number" && Number.isFi | ||
| 40 | 48 | export function fundingOf(dataDir: string): Funding | undefined { |
| 41 | 49 | const c = readDoc(dataDir)?.["credit"]; |
| 42 | 50 | if (typeof c !== "object" || c === null) return undefined; |
| 43 | const { token, capUsd, spentUsd } = c as Record<string, unknown>; | |
| 51 | const { token, capUsd, spentUsd, uncountedUsd } = c as Record<string, unknown>; | |
| 44 | 52 | if (typeof token !== "string" || !BEARER.test(token)) return undefined; |
| 45 | return { token, capUsd: sum(capUsd), spentUsd: sum(spentUsd) }; | |
| 53 | const lost = sum(uncountedUsd); | |
| 54 | return { token, capUsd: sum(capUsd), spentUsd: sum(spentUsd), ...(lost !== null && lost > 0 ? { uncountedUsd: lost } : {}) }; | |
| 46 | 55 | } |
| 47 | 56 | |
| 48 | 57 | /** |
| 49 | * Write `credit` into a forge's `parent.json`, keeping the rest; false when it has none of its own, or it | |
| 50 | * could not be written. The parent calls this on a child's directory, from outside the child's cell: what | |
| 51 | * it keeps is what `readPrivate` read (the child's own file, never one a link there names) and it is | |
| 52 | * written through `writePrivate`. | |
| 58 | * Write `credit` into a forge's `parent.json`, keeping the rest; false when it has none of its own, | |
| 59 | * or it could not be written. The parent calls this on a child's directory, from outside the | |
| 60 | * child's cell: what it keeps is what `readPrivate` read (the child's own file, never one a link | |
| 61 | * there names) and it is written through `writePrivate`. | |
| 53 | 62 | */ |
| 54 | 63 | export function keepFunding(dataDir: string, funding: Funding): boolean { |
| 55 | 64 | const doc = readDoc(dataDir); |
| @@ -68,10 +77,15 @@ type Lent = { readonly capUsd: number; readonly spentUsd: number }; | ||
| 68 | 77 | * False when the child holds none. */ |
| 69 | 78 | export function syncFunding(dataDir: string, credit: Lent): boolean { |
| 70 | 79 | const f = fundingOf(dataDir); |
| 71 | return f !== undefined && keepFunding(dataDir, { token: f.token, capUsd: credit.capUsd, spentUsd: credit.spentUsd }); | |
| 80 | if (f === undefined) return false; | |
| 81 | const still = f.uncountedUsd !== undefined && f.spentUsd !== null && credit.spentUsd <= f.spentUsd; | |
| 82 | return keepFunding(dataDir, { token: f.token, capUsd: credit.capUsd, spentUsd: credit.spentUsd, ...(still ? { uncountedUsd: f.uncountedUsd! } : {}) }); | |
| 72 | 83 | } |
| 73 | 84 | |
| 74 | /** The environment that points a crew run at the parent's door; undefined unless funded and the door is reachable. */ | |
| 85 | /** | |
| 86 | * The environment that points a crew run at the parent's door; undefined unless funded and the door | |
| 87 | * is reachable. | |
| 88 | */ | |
| 75 | 89 | export function fundedEnv(dataDir: string): Record<string, string> | undefined { |
| 76 | 90 | const local = process.env["FORGE_PARENT_LOCAL"] ?? ""; |
| 77 | 91 | const f = fundingOf(dataDir); |
| @@ -81,25 +95,38 @@ export function fundedEnv(dataDir: string): Record<string, string> | undefined { | ||
| 81 | 95 | |
| 82 | 96 | type FetchLike = (url: string, init?: RequestInit) => Promise<Response>; |
| 83 | 97 | |
| 84 | /** Ask the parent how much is left and keep the answer; the last known stands when it does not answer. Never throws. */ | |
| 98 | /** | |
| 99 | * Ask the parent how much is left and keep the answer; the last known stands when it does not | |
| 100 | * answer. Never throws. | |
| 101 | */ | |
| 85 | 102 | export async function refreshFunding(app: App, fetcher: FetchLike = fetch): Promise<Funding | undefined> { |
| 103 | return (await askHost(app, fetcher)) ?? fundingOf(app.config.dataDir); | |
| 104 | } | |
| 105 | ||
| 106 | /** | |
| 107 | * The host's answer kept, or undefined when this forge is not funded or the host did not answer. | |
| 108 | */ | |
| 109 | async function askHost(app: App, fetcher: FetchLike): Promise<Funding | undefined> { | |
| 86 | 110 | const f = fundingOf(app.config.dataDir); |
| 87 | 111 | const local = process.env["FORGE_PARENT_LOCAL"] ?? ""; |
| 88 | if (f === undefined) return undefined; | |
| 89 | if (!isParentLocal(local)) return f; | |
| 112 | if (f === undefined || !isParentLocal(local)) return undefined; | |
| 90 | 113 | try { |
| 91 | 114 | const res = await fetcher(`${local}/api/v1/credit`, { |
| 92 | 115 | headers: { authorization: `Bearer ${f.token}` }, |
| 93 | 116 | signal: AbortSignal.timeout(3000), |
| 94 | 117 | redirect: "error", |
| 95 | 118 | }); |
| 96 | if (!res.ok) return f; | |
| 119 | if (!res.ok) return undefined; | |
| 97 | 120 | const d = (await res.json()) as Record<string, unknown>; |
| 98 | const next = { token: f.token, capUsd: sum(d["capUsd"]), spentUsd: sum(d["spentUsd"]) }; | |
| 121 | const spent = sum(d["spentUsd"]); | |
| 122 | // What the host counts replaces the copy; a note of uncounted spend stands only while its count | |
| 123 | // has not moved. | |
| 124 | const still = f.uncountedUsd !== undefined && (spent === null || f.spentUsd === null || spent <= f.spentUsd); | |
| 125 | const next: Funding = { token: f.token, capUsd: sum(d["capUsd"]), spentUsd: spent, ...(still ? { uncountedUsd: f.uncountedUsd! } : {}) }; | |
| 99 | 126 | keepFunding(app.config.dataDir, next); |
| 100 | 127 | return next; |
| 101 | 128 | } catch { |
| 102 | return f; | |
| 129 | return undefined; | |
| 103 | 130 | } |
| 104 | 131 | } |
| 105 | 132 | |
| @@ -145,10 +172,36 @@ export const cappedByLent = (wanted: number, lentLeft: number | undefined): numb | ||
| 145 | 172 | lentLeft === undefined ? wanted : Math.min(wanted, lentLeft); |
| 146 | 173 | |
| 147 | 174 | /** |
| 148 | * A run ended: when this forge is funded, ask the host what it counted, so the | |
| 149 | * credit line moves. The answer's promise when asked, undefined when not funded. | |
| 175 | * What a run cost that the host could have counted: on the owner's own key the | |
| 176 | * lent credit was never involved, so nothing (#13715). | |
| 150 | 177 | */ |
| 151 | export function runEnded(app: App, fetcher?: FetchLike): Promise<Funding | undefined> | undefined { | |
| 152 | if (fundingOf(app.config.dataDir) === undefined) return undefined; | |
| 153 | return refreshFunding(app, fetcher); | |
| 178 | export const lentCost = (app: App, costUsd: number): number => (crewHasCredential(app.db) ? 0 : costUsd); | |
| 179 | ||
| 180 | /** | |
| 181 | * A run ended: when this forge is funded, ask the host what it counted, so the credit line | |
| 182 | * moves. Each run is judged against the count it started with (`spentAtStart`), not against | |
| 183 | * what another run's end left in the copy: when it cost something by its own account | |
| 184 | * (`costUsd`) and the host's count has not risen since it began, this run's cost alone, never a | |
| 185 | * sum, is kept as `uncountedUsd` (#13715). A count unknown at either end says nothing. The | |
| 186 | * answer's promise when asked, undefined when not funded. | |
| 187 | */ | |
| 188 | export function runEnded( | |
| 189 | app: App, | |
| 190 | fetcher: FetchLike = fetch, | |
| 191 | opts: { costUsd?: number; spentAtStart?: number | null } = {}, | |
| 192 | ): Promise<Funding | undefined> | undefined { | |
| 193 | const costUsd = opts.costUsd ?? 0; | |
| 194 | const dir = app.config.dataDir; | |
| 195 | const held = fundingOf(dir); | |
| 196 | if (held === undefined) return undefined; | |
| 197 | const start = opts.spentAtStart === undefined ? held.spentUsd : opts.spentAtStart; | |
| 198 | return (async () => { | |
| 199 | const next = await askHost(app, fetcher); | |
| 200 | if (next === undefined) return fundingOf(dir); | |
| 201 | const flat = start !== null && next.spentUsd !== null && next.spentUsd <= start; | |
| 202 | if (!flat || !(costUsd > 0) || !Number.isFinite(costUsd)) return next; | |
| 203 | const noted = { ...next, uncountedUsd: Math.round(costUsd * 1e6) / 1e6 }; | |
| 204 | keepFunding(dir, noted); | |
| 205 | return noted; | |
| 206 | })(); | |
| 154 | 207 | } |
src/tui/screens/crewkey.ts +2 −1
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | import { saveCrewKey } from "../../actions/crew_key.ts"; |
| 9 | 9 | import { crewHasCredential } from "../../core/subscriptions.ts"; |
| 10 | 10 | import { usdWords } from "../../spawn/credit.ts"; |
| 11 | import { uncountedWords } from "../../actions/crew_means.ts"; | |
| 11 | 12 | import { includedCredit } from "../../web/studio/crew_key.ts"; |
| 12 | 13 | import type { Ctx, Screen } from "../app/app.ts"; |
| 13 | 14 | import { binding } from "../app/keys.ts"; |
| @@ -24,7 +25,7 @@ export function crewKeyLine(f: Session): string { | ||
| 24 | 25 | if (crewHasCredential(f.app.db)) return "The crew runs on your key. a adds another."; |
| 25 | 26 | const credit = includedCredit(f.app); |
| 26 | 27 | if (credit !== undefined && credit.leftUsd > 0) |
| 27 | return `The crew is building on ${usdWords(credit.leftUsd)} of ${usdWords(credit.capUsd)} included credit (${usdWords(credit.spentUsd)} spent). a adds your own key.`; | |
| 28 | return `The crew is building on ${usdWords(credit.leftUsd)} of ${usdWords(credit.capUsd)} included credit (${usdWords(credit.spentUsd)} spent).${uncountedWords(credit.uncountedUsd ?? 0)} a adds your own key.`; | |
| 28 | 29 | if (credit !== undefined) return "The included credit is spent. a adds your own key to keep building."; |
| 29 | 30 | return "The crew needs a model key to start. a adds yours."; |
| 30 | 31 | } |
src/web/pages/subscriptions.ts +2 −1
| @@ -61,6 +61,7 @@ import { accountSections } from "./origins.ts"; | ||
| 61 | 61 | import { liveRegionsJs } from "../client.ts"; |
| 62 | 62 | import { markOf } from "../../core/marks.ts"; |
| 63 | 63 | import { crewKeyCard, includedCredit, isHostedForge } from "../studio/crew_key.ts"; |
| 64 | import { uncountedWords } from "../../actions/crew_means.ts"; | |
| 64 | 65 | import { usdWords } from "../../spawn/credit.ts"; |
| 65 | 66 | import { limitValue } from "../../settings/limits.ts"; |
| 66 | 67 | |
| @@ -279,7 +280,7 @@ export function subscriptionsPage(ctx: Ctx): Response { | ||
| 279 | 280 | const lent = |
| 280 | 281 | included === undefined |
| 281 | 282 | ? null |
| 282 | : html`<p class="small muted" id="included-credit">${icon("key")} Included crew credit: ${usdWords(included.leftUsd)} of ${usdWords(included.capUsd)} left. When it is spent the crew stops until you add your own key.</p>`; | |
| 283 | : html`<p class="small muted" id="included-credit">${icon("key")} Included crew credit: ${usdWords(included.leftUsd)} of ${usdWords(included.capUsd)} left.${uncountedWords(included.uncountedUsd ?? 0)} When it is spent the crew stops until you add your own key.</p>`; | |
| 283 | 284 | const add = html`<section class="settings-block"><h2>Add one</h2> |
| 284 | 285 | <form class="stack" method="post" action="${POOL}"> |
| 285 | 286 | <div class="field"> |
src/web/plan_row.ts +10 −5
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | |
| 12 | 12 | import { noticeOf, type PlanNotice } from "../billing/notice.ts"; |
| 13 | 13 | import { fundingOf } from "../spawn/funding.ts"; |
| 14 | import { uncountedWords } from "../actions/crew_means.ts"; | |
| 14 | 15 | import { usdWords } from "../spawn/credit.ts"; |
| 15 | 16 | import { sizeWords } from "../settings/billing.ts"; |
| 16 | 17 | import { isSize } from "../spawn/sizes.ts"; |
| @@ -29,19 +30,22 @@ export function statusWords(n: Pick<PlanNotice, "status" | "periodEnd">): string | ||
| 29 | 30 | return n.status === "none" ? "No active plan" : "Active"; |
| 30 | 31 | } |
| 31 | 32 | |
| 32 | /** The plan as one plain line of text, or undefined when this forge was told none; the page and the terminal say the same. */ | |
| 33 | /** | |
| 34 | * The plan as one plain line of text, or undefined when this forge was told none; the page and the | |
| 35 | * terminal say the same. | |
| 36 | */ | |
| 33 | 37 | export function planLine(dataDir: string): string | undefined { |
| 34 | 38 | const n = noticeOf(dataDir); |
| 35 | 39 | if (n === undefined) return undefined; |
| 36 | 40 | const f = fundingOf(dataDir); |
| 37 | 41 | const size = isSize(n.size) ? ` (${sizeWords(n.size)})` : ""; |
| 38 | const credit = n.creditUsd > 0 && f?.spentUsd != null ? ` ${usdWords(f.spentUsd)} of ${usdWords(n.creditUsd)} crew credit used this month.` : ""; | |
| 42 | const credit = n.creditUsd > 0 && f?.spentUsd != null ? ` ${usdWords(f.spentUsd)} of ${usdWords(n.creditUsd)} crew credit used this month.${uncountedWords(f.uncountedUsd ?? 0)}` : ""; | |
| 39 | 43 | return `${n.name}${size}. ${statusWords(n)}.${credit}`; |
| 40 | 44 | } |
| 41 | 45 | |
| 42 | 46 | /** |
| 43 | * One `dl` row for a forge's admins; null for anyone else or a forge told nothing. `more` is a row to share the same `dl` | |
| 44 | * (the Cores row), so the facts read as one list. | |
| 47 | * One `dl` row for a forge's admins; null for anyone else or a forge told nothing. `more` is a row | |
| 48 | * to share the same `dl` (the Cores row), so the facts read as one list. | |
| 45 | 49 | */ |
| 46 | 50 | export function planRow(dataDir: string, parentOrigin: string | undefined, admin: boolean, more: Html | null = null): Html | null { |
| 47 | 51 | if (!admin) return null; |
| @@ -56,7 +60,8 @@ export function planRow(dataDir: string, parentOrigin: string | undefined, admin | ||
| 56 | 60 | }${ |
| 57 | 61 | portal === undefined || pay !== undefined ? "" : html` <a href="${portal}" rel="noopener noreferrer" target="_blank">Manage billing</a>` |
| 58 | 62 | }${ |
| 59 | // One link per place: when Pay already goes to the host's pricing page, Change size would repeat it. | |
| 63 | // One link per place: when Pay already goes to the host's pricing page, Change size would | |
| 64 | // repeat it. | |
| 60 | 65 | parentOrigin === undefined || pay === `${parentOrigin}/pricing` ? "" : html` <a href="${parentOrigin}/pricing">Change size</a>` |
| 61 | 66 | }</dd></div>${more}</dl>`; |
| 62 | 67 | } |
test/credit-moves.test.ts +27 −1
| @@ -9,7 +9,9 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; | ||
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | import { fundingOf, keepFunding, refreshFunding } from "../src/spawn/funding.ts"; | |
| 12 | import { addSubscription } from "../src/core/subscriptions.ts"; | |
| 13 | import { fundingOf, keepFunding, lentCost, refreshFunding, runEnded } from "../src/spawn/funding.ts"; | |
| 14 | import { includedCredit, uncountedWords } from "../src/actions/crew_means.ts"; | |
| 13 | 15 | import { crewNote } from "../src/web/studio/crew_key.ts"; |
| 14 | 16 | |
| 15 | 17 | let dir = ""; |
| @@ -34,3 +36,27 @@ test("the credit line moves after the host counts a run", async () => { | ||
| 34 | 36 | expect(fundingOf(dir)?.spentUsd).toBe(0.5); |
| 35 | 37 | expect(crewNote(child)).toBe("The crew is building on $1.50 of $2 included credit."); |
| 36 | 38 | }); |
| 39 | ||
| 40 | test("a run that cost money the host did not count says so beside the credit line (#13715)", async () => { | |
| 41 | keepFunding(dir, { token: "maria.bearer-token", capUsd: 2, spentUsd: 0 }); | |
| 42 | process.env["FORGE_PARENT_LOCAL"] = "http://127.0.0.1:1"; | |
| 43 | const same = async () => new Response(JSON.stringify({ capUsd: 2, spentUsd: 0 })); | |
| 44 | await runEnded(child, same, { costUsd: 0.78 }); | |
| 45 | expect(fundingOf(dir)?.uncountedUsd).toBe(0.78); | |
| 46 | expect(uncountedWords(0.78)).toContain("$0.78"); | |
| 47 | expect(includedCredit(child)?.uncountedUsd).toBe(0.78); | |
| 48 | // The host's count rising is the counter doing its work: the note goes. | |
| 49 | await runEnded(child, async () => new Response(JSON.stringify({ capUsd: 2, spentUsd: 0.5 })), { costUsd: 0.5 }); | |
| 50 | expect(fundingOf(dir)?.uncountedUsd).toBeUndefined(); | |
| 51 | expect(fundingOf(dir)?.spentUsd).toBe(0.5); | |
| 52 | }); | |
| 53 | ||
| 54 | test("on the owner's own key no cost is passed, so no false 'not counted' note (#13715)", async () => { | |
| 55 | const added = addSubscription(child.db, dir, { name: "mine", token: "sk-ant-api03-abcdefghijklmnop" }); | |
| 56 | expect(added.ok).toBe(true); | |
| 57 | expect(lentCost(child, 0.78)).toBe(0); | |
| 58 | keepFunding(dir, { token: "maria.bearer-token", capUsd: 2, spentUsd: 0 }); | |
| 59 | const same = async () => new Response(JSON.stringify({ capUsd: 2, spentUsd: 0 })); | |
| 60 | await runEnded(child, same, { costUsd: lentCost(child, 0.78) }); | |
| 61 | expect(fundingOf(dir)?.uncountedUsd).toBeUndefined(); | |
| 62 | }); |
test/credit-uncounted.test.ts added +120
| @@ -0,0 +1,120 @@ | ||
| 1 | /** | |
| 2 | * A run's cost the host did not count is said, as a hint, beside the credit lines (#13715): each | |
| 3 | * run is judged against the count it started with, only the last run's cost is kept (never a | |
| 4 | * sum), a failed ask changes nothing, the heartbeat keeps or clears the note, and the plan line, | |
| 5 | * the terminal line and /settings/subscriptions all say the same one sentence. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm, writeFile } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 13 | import { fundingOf, keepFunding, runEnded, syncFunding } from "../src/spawn/funding.ts"; | |
| 14 | import { uncountedWords } from "../src/actions/crew_means.ts"; | |
| 15 | import { planLine } from "../src/web/plan_row.ts"; | |
| 16 | import { crewKeyLine } from "../src/tui/screens/crewkey.ts"; | |
| 17 | import { Session } from "../src/tui/session.ts"; | |
| 18 | import { adminCookie } from "./helpers/admin.ts"; | |
| 19 | ||
| 20 | const SAID = " A run cost $0.78 that this credit did not count."; | |
| 21 | const TOKEN = "maria.bearer-token"; | |
| 22 | ||
| 23 | let dir = ""; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | let cookie = ""; | |
| 27 | ||
| 28 | /** A host whose count is `spentUsd` against a $2 cap. */ | |
| 29 | const host = (spentUsd: number) => async () => new Response(JSON.stringify({ capUsd: 2, spentUsd })); | |
| 30 | /** The child's copy as the host last told it, with a note when `uncountedUsd` is given. */ | |
| 31 | const heard = (spentUsd: number, uncountedUsd?: number): void => { | |
| 32 | keepFunding(dir, { token: TOKEN, capUsd: 2, spentUsd, ...(uncountedUsd === undefined ? {} : { uncountedUsd }) }); | |
| 33 | }; | |
| 34 | ||
| 35 | beforeAll(async () => { | |
| 36 | dir = await mkdtemp(join(tmpdir(), "credit-uncounted-")); | |
| 37 | await writeFile(join(dir, "parent.json"), "{}"); | |
| 38 | app = createApp({ dataDir: dir, port: 0 }); | |
| 39 | servers = await serve(app); | |
| 40 | cookie = await adminCookie(app, { username: "maria", email: "[email protected]", password: "a-good-passphrase" }); | |
| 41 | process.env["FORGE_PARENT_LOCAL"] = "http://127.0.0.1:1"; | |
| 42 | }, 30_000); | |
| 43 | ||
| 44 | afterAll(async () => { | |
| 45 | delete process.env["FORGE_PARENT_LOCAL"]; | |
| 46 | await servers.stop(); | |
| 47 | app.close(); | |
| 48 | await rm(dir, { recursive: true, force: true }); | |
| 49 | }); | |
| 50 | ||
| 51 | beforeEach(() => heard(0)); | |
| 52 | ||
| 53 | /** A signed-out terminal session, the one the crew-key line is read in. */ | |
| 54 | const guest = (): Session => | |
| 55 | new Session(app, { sshUsername: "guest", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: undefined }); | |
| 56 | ||
| 57 | test("the note is one plain sentence, and nothing when there is no cost", () => { | |
| 58 | expect(uncountedWords(0.78)).toBe(SAID); | |
| 59 | expect(uncountedWords(0)).toBe(""); | |
| 60 | }); | |
| 61 | ||
| 62 | test("a run whose start the count has risen past is not flagged, though the copy already moved (#13715)", async () => { | |
| 63 | // Run A began at $0; run B's end moved the copy to $0.30; A ends with the host still at $0.30. | |
| 64 | heard(0.3); | |
| 65 | await runEnded(app, host(0.3), { costUsd: 0.5, spentAtStart: 0 }); | |
| 66 | expect(fundingOf(dir)?.uncountedUsd).toBeUndefined(); | |
| 67 | }); | |
| 68 | ||
| 69 | test("two uncounted runs keep the last one's cost, never the sum", async () => { | |
| 70 | await runEnded(app, host(0), { costUsd: 0.5, spentAtStart: 0 }); | |
| 71 | expect(fundingOf(dir)?.uncountedUsd).toBe(0.5); | |
| 72 | await runEnded(app, host(0), { costUsd: 0.78, spentAtStart: 0 }); | |
| 73 | expect(fundingOf(dir)?.uncountedUsd).toBe(0.78); | |
| 74 | }); | |
| 75 | ||
| 76 | test("an unknown count at the start says nothing", async () => { | |
| 77 | await runEnded(app, host(0), { costUsd: 0.78, spentAtStart: null }); | |
| 78 | expect(fundingOf(dir)?.uncountedUsd).toBeUndefined(); | |
| 79 | }); | |
| 80 | ||
| 81 | test("a failed ask, refused or thrown, keeps the copy and its note and adds nothing", async () => { | |
| 82 | heard(0, 0.25); | |
| 83 | const refused = await runEnded(app, async () => new Response("no", { status: 500 }), { costUsd: 0.78, spentAtStart: 0 }); | |
| 84 | expect(refused?.uncountedUsd).toBe(0.25); | |
| 85 | const thrown = await runEnded(app, async () => { throw new Error("down"); }, { costUsd: 0.78, spentAtStart: 0 }); | |
| 86 | expect(thrown?.uncountedUsd).toBe(0.25); | |
| 87 | expect(fundingOf(dir)).toEqual({ token: TOKEN, capUsd: 2, spentUsd: 0, uncountedUsd: 0.25 }); | |
| 88 | }); | |
| 89 | ||
| 90 | test("the heartbeat keeps the note while the count stands and clears it once the count moves", () => { | |
| 91 | heard(0.1, 0.78); | |
| 92 | expect(syncFunding(dir, { capUsd: 2, spentUsd: 0.1 })).toBe(true); | |
| 93 | expect(fundingOf(dir)?.uncountedUsd).toBe(0.78); | |
| 94 | expect(syncFunding(dir, { capUsd: 2, spentUsd: 0.2 })).toBe(true); | |
| 95 | expect(fundingOf(dir)?.uncountedUsd).toBeUndefined(); | |
| 96 | expect(fundingOf(dir)?.spentUsd).toBe(0.2); | |
| 97 | }); | |
| 98 | ||
| 99 | test("the plan line and the terminal line say the note, and only when there is one", async () => { | |
| 100 | await writeFile(join(dir, "plan.json"), JSON.stringify({ name: "Large", size: "large", priceUsd: 99, creditUsd: 50, status: "active" })); | |
| 101 | expect(planLine(dir)).not.toContain("did not count"); | |
| 102 | expect(crewKeyLine(guest())).not.toContain("did not count"); | |
| 103 | heard(0, 0.78); | |
| 104 | expect(planLine(dir)).toContain(`$0 of $50 crew credit used this month.${SAID}`); | |
| 105 | expect(crewKeyLine(guest())).toBe( | |
| 106 | `The crew is building on $2 of $2 included credit ($0 spent).${SAID} a adds your own key.`, | |
| 107 | ); | |
| 108 | }); | |
| 109 | ||
| 110 | test("/settings/subscriptions says the note on its included-credit line", async () => { | |
| 111 | const line = async (): Promise<string> => { | |
| 112 | const page = await (await fetch(`${servers.url}/settings/subscriptions`, { headers: { cookie } })).text(); | |
| 113 | const m = /<p[^>]*id="included-credit"[^>]*>([\s\S]*?)<\/p>/.exec(page); | |
| 114 | expect(m).not.toBeNull(); | |
| 115 | return m![1]!.replace(/<[^>]+>/g, ""); | |
| 116 | }; | |
| 117 | expect(await line()).not.toContain("did not count"); | |
| 118 | heard(0, 0.78); | |
| 119 | expect(await line()).toContain(`$2 of $2 left.${SAID} When it is spent`); | |
| 120 | }); |
new above
offline