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

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/13715-from-outside-crew-run-cost-is-reported-o → main 5 commits fork

  • Merged. torque/13715-from-outside-crew-run-cost-is-reported-o was merged into main as cffc292.

Review

Sign in to review this change.
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.
5252 own credential names.
5353 - Not done: a spawn-time cap field (the PUT is the one door), and a funded hosted (in-process) child,
5454 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 {
1313 /** What the host counted the runs cost; a reservation or declared budget is never in it. */
1414 readonly spentUsd: number;
1515 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;
1618 }
1719
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
1823 /**
1924 * The credit this forge came with and what is left of it (last heard from its host), or undefined
2025 * when it has none.
@@ -23,7 +28,7 @@ export function includedCredit(app: App): Included | undefined {
2328 const f = fundingOf(app.config.dataDir);
2429 if (f === undefined || f.capUsd === null) return undefined;
2530 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 }) };
2732 }
2833
2934 /** 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 {
207207 } from "./guard.ts";
208208 import { passportEnv } from "./passport_env.ts";
209209 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";
211211
212212 const log = createLog("crew");
213213
@@ -997,6 +997,9 @@ async function work(
997997 ran: Ran,
998998 ): Promise<Outcome> {
999999 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;
10001003 const repo = getRepoById(app.db, run.repoId);
10011004 const issue =
10021005 run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
@@ -1973,7 +1976,7 @@ async function work(
19731976 if (runTmp !== undefined) await rm(runTmp, { recursive: true, force: true });
19741977 // The host counted what the run cost: ask it now, so the credit line moves
19751978 // 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 });
19771980 }
19781981 }
19791982
src/spawn/funding.ts +73 −20
@@ -8,6 +8,7 @@
88 * is good for nothing but that door.
99 */
1010
11 import { crewHasCredential } from "../core/subscriptions.ts";
1112 import { join } from "node:path";
1213 import type { App } from "../app.ts";
1314 import { readPrivate, writePrivate } from "../kernel/file_modes.ts";
@@ -19,6 +20,12 @@ export interface Funding {
1920 readonly token: string;
2021 readonly capUsd: number | null;
2122 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;
2229 }
2330
2431 const BEARER = /^[\x21-\x7e]{8,200}$/;
@@ -26,7 +33,8 @@ const file = (dataDir: string): string => join(dataDir, "parent.json");
2633
2734 function readDoc(dataDir: string): Record<string, unknown> | undefined {
2835 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.
3038 const d = JSON.parse(readPrivate(file(dataDir)) ?? "");
3139 return typeof d === "object" && d !== null && !Array.isArray(d) ? (d as Record<string, unknown>) : undefined;
3240 } catch {
@@ -40,16 +48,17 @@ const sum = (v: unknown): number | null => (typeof v === "number" && Number.isFi
4048 export function fundingOf(dataDir: string): Funding | undefined {
4149 const c = readDoc(dataDir)?.["credit"];
4250 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>;
4452 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 } : {}) };
4655 }
4756
4857 /**
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`.
5362 */
5463 export function keepFunding(dataDir: string, funding: Funding): boolean {
5564 const doc = readDoc(dataDir);
@@ -68,10 +77,15 @@ type Lent = { readonly capUsd: number; readonly spentUsd: number };
6877 * False when the child holds none. */
6978 export function syncFunding(dataDir: string, credit: Lent): boolean {
7079 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! } : {}) });
7283 }
7384
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 */
7589 export function fundedEnv(dataDir: string): Record<string, string> | undefined {
7690 const local = process.env["FORGE_PARENT_LOCAL"] ?? "";
7791 const f = fundingOf(dataDir);
@@ -81,25 +95,38 @@ export function fundedEnv(dataDir: string): Record<string, string> | undefined {
8195
8296 type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
8397
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 */
85102 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> {
86110 const f = fundingOf(app.config.dataDir);
87111 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;
90113 try {
91114 const res = await fetcher(`${local}/api/v1/credit`, {
92115 headers: { authorization: `Bearer ${f.token}` },
93116 signal: AbortSignal.timeout(3000),
94117 redirect: "error",
95118 });
96 if (!res.ok) return f;
119 if (!res.ok) return undefined;
97120 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! } : {}) };
99126 keepFunding(app.config.dataDir, next);
100127 return next;
101128 } catch {
102 return f;
129 return undefined;
103130 }
104131 }
105132
@@ -145,10 +172,36 @@ export const cappedByLent = (wanted: number, lentLeft: number | undefined): numb
145172 lentLeft === undefined ? wanted : Math.min(wanted, lentLeft);
146173
147174 /**
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).
150177 */
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 })();
154207 }
src/tui/screens/crewkey.ts +2 −1
@@ -8,6 +8,7 @@
88 import { saveCrewKey } from "../../actions/crew_key.ts";
99 import { crewHasCredential } from "../../core/subscriptions.ts";
1010 import { usdWords } from "../../spawn/credit.ts";
11 import { uncountedWords } from "../../actions/crew_means.ts";
1112 import { includedCredit } from "../../web/studio/crew_key.ts";
1213 import type { Ctx, Screen } from "../app/app.ts";
1314 import { binding } from "../app/keys.ts";
@@ -24,7 +25,7 @@ export function crewKeyLine(f: Session): string {
2425 if (crewHasCredential(f.app.db)) return "The crew runs on your key. a adds another.";
2526 const credit = includedCredit(f.app);
2627 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.`;
2829 if (credit !== undefined) return "The included credit is spent. a adds your own key to keep building.";
2930 return "The crew needs a model key to start. a adds yours.";
3031 }
src/web/pages/subscriptions.ts +2 −1
@@ -61,6 +61,7 @@ import { accountSections } from "./origins.ts";
6161 import { liveRegionsJs } from "../client.ts";
6262 import { markOf } from "../../core/marks.ts";
6363 import { crewKeyCard, includedCredit, isHostedForge } from "../studio/crew_key.ts";
64 import { uncountedWords } from "../../actions/crew_means.ts";
6465 import { usdWords } from "../../spawn/credit.ts";
6566 import { limitValue } from "../../settings/limits.ts";
6667
@@ -279,7 +280,7 @@ export function subscriptionsPage(ctx: Ctx): Response {
279280 const lent =
280281 included === undefined
281282 ? 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>`;
283284 const add = html`<section class="settings-block"><h2>Add one</h2>
284285 <form class="stack" method="post" action="${POOL}">
285286 <div class="field">
src/web/plan_row.ts +10 −5
@@ -11,6 +11,7 @@
1111
1212 import { noticeOf, type PlanNotice } from "../billing/notice.ts";
1313 import { fundingOf } from "../spawn/funding.ts";
14 import { uncountedWords } from "../actions/crew_means.ts";
1415 import { usdWords } from "../spawn/credit.ts";
1516 import { sizeWords } from "../settings/billing.ts";
1617 import { isSize } from "../spawn/sizes.ts";
@@ -29,19 +30,22 @@ export function statusWords(n: Pick<PlanNotice, "status" | "periodEnd">): string
2930 return n.status === "none" ? "No active plan" : "Active";
3031 }
3132
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 */
3337 export function planLine(dataDir: string): string | undefined {
3438 const n = noticeOf(dataDir);
3539 if (n === undefined) return undefined;
3640 const f = fundingOf(dataDir);
3741 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)}` : "";
3943 return `${n.name}${size}. ${statusWords(n)}.${credit}`;
4044 }
4145
4246 /**
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.
4549 */
4650 export function planRow(dataDir: string, parentOrigin: string | undefined, admin: boolean, more: Html | null = null): Html | null {
4751 if (!admin) return null;
@@ -56,7 +60,8 @@ export function planRow(dataDir: string, parentOrigin: string | undefined, admin
5660 }${
5761 portal === undefined || pay !== undefined ? "" : html` <a href="${portal}" rel="noopener noreferrer" target="_blank">Manage billing</a>`
5862 }${
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.
6065 parentOrigin === undefined || pay === `${parentOrigin}/pricing` ? "" : html` <a href="${parentOrigin}/pricing">Change size</a>`
6166 }</dd></div>${more}</dl>`;
6267 }
test/credit-moves.test.ts +27 −1
@@ -9,7 +9,9 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 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";
1315 import { crewNote } from "../src/web/studio/crew_key.ts";
1416
1517 let dir = "";
@@ -34,3 +36,27 @@ test("the credit line moves after the host counts a run", async () => {
3436 expect(fundingOf(dir)?.spentUsd).toBe(0.5);
3537 expect(crewNote(child)).toBe("The crew is building on $1.50 of $2 included credit.");
3638 });
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 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs