Public: anyone can read this; the crew can change it.
A per-minute rate limit: a person's build goes first, waits a minute, and says so plainly (#16490) #16495
Check · Review · Land · Live — It conflicts with its base.
fix/ratelimit → main 1 commit
17 files
changed +574
−13
docs/features/start-now-own-account.md added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | --- | |
| 2 | topic: Bring your own AI | |
| 3 | row: A waiting build starts now on your own Claude account | |
| 4 | --- | |
| 5 | # Start a waiting build on your own Claude account | |
| 6 | ||
| 7 | When your own build waits because the forge has no model account with room (too many requests | |
| 8 | this minute, a full window, spent credit), the wait offers one step: **Start now with your own | |
| 9 | Claude account**. | |
| 10 | ||
| 11 | - **Page:** on the build's run page, or in Talk's crew pane, paste the value `claude setup-token` | |
| 12 | prints (or an Anthropic API key) and press **Start now**. The build starts on it straight away; | |
| 13 | the page does not reload. | |
| 14 | - **Terminal:** on the run's log screen, press `a` and paste the token (it is masked). | |
| 15 | ||
| 16 | The token is tested with Anthropic before anything is kept. A token that does not answer is not | |
| 17 | saved, and you are told so. A working one is saved as your own subscription: sealed, never shown | |
| 18 | again, and spent only on your own repositories. Change or remove it later under Settings, Model. | |
| 19 | ||
| 20 | Only the person whose build it is, in their own repository, and who has not added an account yet, | |
| 21 | is offered the box. `src/actions/own_token.ts` is the one path all three surfaces call. |
src/actions/own_token.ts added +67
| @@ -0,0 +1,67 @@ | ||
| 1 | /** | |
| 2 | * "Start now with your own Claude account" (#16490): a person whose own build waits because the | |
| 3 | * forge has no account with room pastes a token where the wait is shown, and the build starts on | |
| 4 | * it. The token is tested first (nothing is kept of one that does not answer), saved as their own | |
| 5 | * subscription for their own repositories (`addOwnModel`: sealed, never shown again), and the held | |
| 6 | * run is let go at once (`releaseHeld`). The page, Talk and the terminal all call this. | |
| 7 | */ | |
| 8 | import type { App } from "../app.ts"; | |
| 9 | import { ownSubscription } from "../core/model_grant.ts"; | |
| 10 | import { getRepoById } from "../core/repos.ts"; | |
| 11 | import { getRun, type Run } from "../core/runs.ts"; | |
| 12 | import { kindOfToken } from "../core/subscriptions.ts"; | |
| 13 | import type { User } from "../core/users.ts"; | |
| 14 | import { releaseHeld } from "../crew/meter_watch.ts"; | |
| 15 | import { checkToken } from "../crew/token_check.ts"; | |
| 16 | import { appendRunLog } from "../runs/log.ts"; | |
| 17 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 18 | import { addOwnModel } from "./model_grant.ts"; | |
| 19 | import { announceRun } from "./runs.ts"; | |
| 20 | ||
| 21 | export type StartNowError = "not_held" | "has_own" | "invalid_token" | "not_working"; | |
| 22 | ||
| 23 | /** What a refused start says, on every surface. */ | |
| 24 | export const START_NOW_WORDS: Readonly<Record<StartNowError, string>> = { | |
| 25 | not_held: "This build is not waiting for an account any more.", | |
| 26 | has_own: "Your own account is already added; this build waits on it.", | |
| 27 | invalid_token: "That is not a token. Paste the whole value claude setup-token printed, or an API key.", | |
| 28 | not_working: "Anthropic did not accept that token. Nothing was kept; check it and paste it again.", | |
| 29 | }; | |
| 30 | ||
| 31 | /** The heading and line every surface shows with the box. */ | |
| 32 | export const START_NOW_HEAD = "Start now with your own Claude account"; | |
| 33 | export const START_NOW_LINE = "It is tested first, kept sealed, never shown again, and spent only on your own repositories."; | |
| 34 | ||
| 35 | /** | |
| 36 | * Whether `user` is offered the box on `run`: a person's own build, in their own repository, held | |
| 37 | * for want of an account with room (a pause that waits on a time), and they have no account of | |
| 38 | * their own yet. Anyone else reads the wait as it is. | |
| 39 | */ | |
| 40 | export function offersOwnToken(app: App, user: User | undefined, run: Run, now = new Date()): boolean { | |
| 41 | if (user === undefined || user.kind !== "user") return false; | |
| 42 | if (run.kind !== "agent" || run.state !== "queued" || run.notBefore === null || Date.parse(run.notBefore) <= now.getTime()) return false; | |
| 43 | if (!run.summary.startsWith("paused")) return false; | |
| 44 | if (getRepoById(app.db, run.repoId)?.ownerId !== user.id) return false; | |
| 45 | return ownSubscription(app.db, user.id) === undefined; | |
| 46 | } | |
| 47 | ||
| 48 | /** Test, save, and let the held run go: the run as it is now, or why not. */ | |
| 49 | export async function startNowWithOwnToken( | |
| 50 | app: App, | |
| 51 | user: User | undefined, | |
| 52 | run: Run, | |
| 53 | rawToken: string, | |
| 54 | ): Promise<Result<Run, StartNowError>> { | |
| 55 | if (!offersOwnToken(app, user, run)) return err(user !== undefined && ownSubscription(app.db, user.id) !== undefined ? "has_own" : "not_held"); | |
| 56 | const token = rawToken.trim(); | |
| 57 | if (kindOfToken(token) === undefined) return err("invalid_token"); | |
| 58 | if (!(await checkToken(token))) return err("not_working"); | |
| 59 | const added = addOwnModel(app, user, { token }); | |
| 60 | if (!added.ok) return err(added.error === "name_taken" ? "has_own" : "invalid_token"); | |
| 61 | // The wait's words go with the wait: the card says what happens now. | |
| 62 | releaseHeld(app.db, run.id, new Date(), "starting on your own Claude account"); | |
| 63 | appendRunLog(app.config.dataDir, run.id, `${user!.username} added their own Claude account; the run starts on it now`); | |
| 64 | const now = getRun(app.db, run.id) ?? run; | |
| 65 | announceRun(app, now); | |
| 66 | return ok(now); | |
| 67 | } |
src/crew/limits.ts +49
| @@ -78,6 +78,55 @@ export function takeLimit( | ||
| 78 | 78 | return { until, limit: named, said }; |
| 79 | 79 | } |
| 80 | 80 | |
| 81 | /** | |
| 82 | * A refusal for this minute's requests (a 429 "rate limit" / "too many requests" that names no | |
| 83 | * window and no time), not a used-up 5-hour or weekly window. Claude Code has already retried it | |
| 84 | * with its own backoff before giving up, and it passes on no retry-after, so the forge waits | |
| 85 | * short and doubles (`breathWait`), never the 15 minutes an unnamed limit gets. | |
| 86 | */ | |
| 87 | export function perMinute(limit: RunnerLimit | undefined): boolean { | |
| 88 | if (limit === undefined || limit.limitedUntil !== undefined) return false; | |
| 89 | const said = limit.said ?? ""; | |
| 90 | return /\b429\b|rate[ _-]?limit|too many requests/i.test(said) && !/usage limit|session limit|weekly|week\b|5-hour/i.test(said); | |
| 91 | } | |
| 92 | ||
| 93 | /** The first wait after a per-minute refusal; doubled each time the same run is refused again. */ | |
| 94 | const BREATH_MS = 60_000; | |
| 95 | ||
| 96 | /** | |
| 97 | * How long a run waits after a per-minute refusal (#16490). A run a person sent waits the least | |
| 98 | * (1, 2, 4, 8 minutes), and the crew's own work backs off first and further (4, 8, 16, 30), so | |
| 99 | * when one account is shared the person's build is the one that gets the next minute. | |
| 100 | */ | |
| 101 | export function breathWait(attempt: number, sent: boolean): number { | |
| 102 | const n = Math.max(0, Math.min(attempt, 5)); | |
| 103 | return sent ? Math.min(BREATH_MS * 2 ** n, 8 * 60_000) : Math.min(4 * BREATH_MS * 2 ** n, 30 * 60_000); | |
| 104 | } | |
| 105 | ||
| 106 | /** Per account (a subscription id, or the forge's own token): until when the crew's own runs hold. */ | |
| 107 | const breathing = new Map<string, number>(); | |
| 108 | ||
| 109 | /** After a per-minute refusal on `account`: the crew's own runs on it wait until `until`. */ | |
| 110 | export function noteBreath(account: string, until: Date): void { | |
| 111 | if ((breathing.get(account) ?? 0) < until.getTime()) breathing.set(account, until.getTime()); | |
| 112 | } | |
| 113 | ||
| 114 | /** Until when the crew's own runs on `account` hold, or undefined when they need not. */ | |
| 115 | export function breathingUntil(account: string, now: Date): Date | undefined { | |
| 116 | const until = breathing.get(account); | |
| 117 | if (until === undefined) return undefined; | |
| 118 | if (until <= now.getTime()) { | |
| 119 | breathing.delete(account); | |
| 120 | return undefined; | |
| 121 | } | |
| 122 | return new Date(until); | |
| 123 | } | |
| 124 | ||
| 125 | /** What a run paused by a per-minute refusal says: plain words and the time, never the provider's. */ | |
| 126 | export function breathWords(at: Date, sent: boolean): string { | |
| 127 | return `The crew is catching its breath (too many requests this minute); ${sent ? "your build" : "it"} starts again by ${whenText(at)}.`; | |
| 128 | } | |
| 129 | ||
| 81 | 130 | /** `12:04 UTC` — how a resume time reads on a card. */ |
| 82 | 131 | export function whenText(at: Date): string { |
| 83 | 132 | return `${at.toISOString().slice(11, 16)} UTC`; |
src/crew/meter_watch.ts +13
| @@ -117,6 +117,19 @@ export function releasePaused(db: Database, account: string, now: Date): number | ||
| 117 | 117 | .run(now.toISOString(), account).changes; |
| 118 | 118 | } |
| 119 | 119 | |
| 120 | /** | |
| 121 | * One held run let go now: its `not_before` cleared if it still waits (a person just gave it an | |
| 122 | * account of their own). One run, where `releasePaused` lets go every run on an account; the crew | |
| 123 | * accounts pull's `recheckHeld` (builder-voice) is to absorb both into one. | |
| 124 | */ | |
| 125 | export function releaseHeld(db: Database, runId: string, now: Date, summary: string): boolean { | |
| 126 | return ( | |
| 127 | db | |
| 128 | .query("UPDATE run SET not_before = NULL, summary = ?3 WHERE id = ?1 AND kind = 'agent' AND state = 'queued' AND not_before > ?2") | |
| 129 | .run(runId, now.toISOString(), summary).changes > 0 | |
| 130 | ); | |
| 131 | } | |
| 132 | ||
| 120 | 133 | function tokenOf(db: Database, dataDir: string, id: string, env: Record<string, string | undefined>): string | undefined { |
| 121 | 134 | if (id === PLATFORM) return platformToken(env); |
| 122 | 135 | const row = db.query<{ token_enc: string }, [string]>("SELECT token_enc FROM subscription WHERE id = ?1").get(id); |
src/crew/pacing.ts +1 −1
| @@ -118,7 +118,7 @@ export function pauseCause(summary: string): string { | ||
| 118 | 118 | const said = summary.replace(/^paused: /, "").toLowerCase(); |
| 119 | 119 | if (/\b(credit|balance|billing|budget|quota)\b/.test(said)) return "credit"; |
| 120 | 120 | if (/\bnetwork\b/.test(said)) return "network"; |
| 121 | if (/\b(window|limit|rate|overloaded|resting)\b/.test(said)) return "rate limit"; | |
| 121 | if (/\b(window|limit|rate|overloaded|resting)\b|too many requests/.test(said)) return "rate limit"; | |
| 122 | 122 | if (/\b(api[ _-]?error|server error|internal|unavailable|bad gateway|5\d\d)\b/.test(said)) return "provider error"; |
| 123 | 123 | if (/\b(host|memory|restart)\b/.test(said)) return "host"; |
| 124 | 124 | return "other"; |
src/crew/runner.ts +40 −1
| @@ -159,9 +159,14 @@ import { | ||
| 159 | 159 | } from "./network.ts"; |
| 160 | 160 | import { BUDGET_REACHED, briefTools, currentRunner, runAgent, type AgentOutcome } from "./agent_runner.ts"; |
| 161 | 161 | import { |
| 162 | breathingUntil, | |
| 163 | breathWait, | |
| 164 | breathWords, | |
| 162 | 165 | isRateLimited, |
| 163 | 166 | limitOf, |
| 164 | 167 | MAX_PAUSES, |
| 168 | noteBreath, | |
| 169 | perMinute, | |
| 165 | 170 | resumeAt, |
| 166 | 171 | takeLimit, |
| 167 | 172 | whenText, |
| @@ -637,7 +642,7 @@ async function runClaimed( | ||
| 637 | 642 | if (paused) announceRun(app, paused); |
| 638 | 643 | return { |
| 639 | 644 | resumeAt: outcome.resumeAt, |
| 640 | attempt: run.attempt + 1, | |
| 645 | attempt: outcome.keepAttempt === true ? run.attempt : run.attempt + 1, | |
| 641 | 646 | summary: outcome.summary, |
| 642 | 647 | }; |
| 643 | 648 | } |
| @@ -885,6 +890,8 @@ type Outcome = | ||
| 885 | 890 | readonly resumeAt: string; |
| 886 | 891 | readonly sessionId: string; |
| 887 | 892 | readonly costUsd: number; |
| 893 | /** Held before it began (a person's run goes first): the wait does not count as a pause. */ | |
| 894 | readonly keepAttempt?: boolean; | |
| 888 | 895 | }; |
| 889 | 896 | |
| 890 | 897 | /** |
| @@ -1562,6 +1569,21 @@ async function work( | ||
| 1562 | 1569 | resumesAt: new Date(picked.until), |
| 1563 | 1570 | }; |
| 1564 | 1571 | } |
| 1572 | // The account turned requests away this minute: the crew's own work holds, a person's run | |
| 1573 | // goes ahead (#16490). The hold is not a pause the run is counted for. | |
| 1574 | const breathing = run.sent ? undefined : breathingUntil(picked.kind === "ready" ? picked.subscription.id : PLATFORM, new Date()); | |
| 1575 | if (breathing !== undefined) { | |
| 1576 | const words = breathWords(breathing, false); | |
| 1577 | write(words); | |
| 1578 | return { | |
| 1579 | state: "paused", | |
| 1580 | summary: `paused: ${words}`, | |
| 1581 | resumeAt: breathing.toISOString(), | |
| 1582 | sessionId: previous?.sessionId ?? "", | |
| 1583 | costUsd: 0, | |
| 1584 | keepAttempt: true, | |
| 1585 | }; | |
| 1586 | } | |
| 1565 | 1587 | // The forge's own token is for admin-owned repositories only; anyone |
| 1566 | 1588 | // else's run waits for a grant rather than spend what is not theirs. |
| 1567 | 1589 | // The owner's capped monthly grant (`core/model_grant.ts`) is the one |
| @@ -1931,6 +1953,23 @@ async function work( | ||
| 1931 | 1953 | // its clone and session as they are, and goes on when the limit lifts. |
| 1932 | 1954 | // A limit that never lifts is not waited on forever. |
| 1933 | 1955 | let limitLifts: Date | undefined; |
| 1956 | // A per-minute refusal (a 429 naming no window): no account rests for it, the run waits a | |
| 1957 | // minute or a few by who sent it, and the crew's own runs on that account hold a while so a | |
| 1958 | // person's build gets the next minute. Plain words; the provider's are in the log. | |
| 1959 | if (isRateLimited(result) && !signal.aborted && perMinute(result.limit) && run.attempt < MAX_PAUSES) { | |
| 1960 | const now = new Date(); | |
| 1961 | const at = new Date(now.getTime() + breathWait(run.attempt, run.sent)); | |
| 1962 | noteBreath(picked.kind === "ready" ? picked.subscription.id : PLATFORM, new Date(now.getTime() + breathWait(0, false))); | |
| 1963 | write(`the provider: ${result.limit.said ?? result.reason}`); | |
| 1964 | pausing = true; | |
| 1965 | return { | |
| 1966 | state: "paused", | |
| 1967 | summary: `paused: ${breathWords(at, run.sent)}`, | |
| 1968 | resumeAt: at.toISOString(), | |
| 1969 | sessionId: result.sessionId, | |
| 1970 | costUsd: result.costUsd, | |
| 1971 | }; | |
| 1972 | } | |
| 1934 | 1973 | if (isRateLimited(result) && !signal.aborted) { |
| 1935 | 1974 | const now = new Date(); |
| 1936 | 1975 | // The account rests until the provider's time; another on the same |
src/crew/token_check.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** | |
| 2 | * Whether Anthropic accepts a token a person pastes (#16490), asked before anything is kept: a | |
| 3 | * Claude account's own token reads its usage meter (`readMeter`); an API key lists models. The | |
| 4 | * test is swapped by tests and by a local forge that talks to a canned provider. | |
| 5 | */ | |
| 6 | import { kindOfToken } from "../core/subscriptions.ts"; | |
| 7 | import { readMeter, type Fetch } from "./meter_watch.ts"; | |
| 8 | ||
| 9 | /** Whether Anthropic accepts `token`: a Claude account's own token reads its usage meter; an API key lists models. */ | |
| 10 | export async function tokenWorks(token: string, fetcher: Fetch = fetch): Promise<boolean> { | |
| 11 | if (kindOfToken(token) === "oauth") return (await readMeter(token, fetcher)) !== undefined; | |
| 12 | try { | |
| 13 | const res = await fetcher("https://api.anthropic.com/v1/models", { | |
| 14 | headers: { "x-api-key": token, "anthropic-version": "2023-06-01", accept: "application/json" }, | |
| 15 | signal: AbortSignal.timeout(10_000), | |
| 16 | }); | |
| 17 | return res.ok; | |
| 18 | } catch { | |
| 19 | return false; | |
| 20 | } | |
| 21 | } | |
| 22 | ||
| 23 | /** What asks Anthropic, swapped by tests and by a local forge with a canned provider. */ | |
| 24 | let tester: (token: string) => Promise<boolean> = (token) => tokenWorks(token); | |
| 25 | export function useTokenTester(fn: ((token: string) => Promise<boolean>) | undefined): void { | |
| 26 | tester = fn ?? ((token) => tokenWorks(token)); | |
| 27 | } | |
| 28 | ||
| 29 | /** Whether Anthropic accepts `token`, by the tester in use. */ | |
| 30 | export const checkToken = (token: string): Promise<boolean> => tester(token); | |
| 31 |
src/http/server.ts +2
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { runOwnToken } from "../web/own_token.ts"; | |
| 8 | 9 | import { togetherFragment } from "../web/together.ts"; |
| 9 | 10 | import { outsiderStatusPage } from "./offer_routes.ts"; |
| 10 | 11 | import { standingFragment } from "../web/pages/fork-standing.ts"; |
| @@ -1690,6 +1691,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1690 | 1691 | router.add("GET", "/:owner/:name/runs/:id", runPage); |
| 1691 | 1692 | router.add("POST", "/:owner/:name/runs/:id/cancel", runCancel); |
| 1692 | 1693 | router.add("POST", "/:owner/:name/runs/:id/requeue", runRequeue); |
| 1694 | router.add("POST", "/:owner/:name/runs/:id/own-token", runOwnToken); | |
| 1693 | 1695 | router.add("POST", "/:owner/:name/runs/:id/steer", runSteer); |
| 1694 | 1696 | // The public social cards: a repo as owner~name, an app as its slug. |
| 1695 | 1697 | router.add("GET", "/og/repo/:ref.svg", ogCard("repo")); |
src/tui/screens/runlog.ts +33 −3
| @@ -20,7 +20,8 @@ import { subscribeRunLog } from "../../runs/log.ts"; | ||
| 20 | 20 | import { stoppedWords } from "../../runs/cancelled.ts"; |
| 21 | 21 | import { withEnded } from "../../runs/ended_words.ts"; |
| 22 | 22 | import { stillEnding } from "../../runs/ending.ts"; |
| 23 | import { Scroll, live, openOnWeb } from "./common.ts"; | |
| 23 | import { Scroll, live, openOnWeb, promptScreen, runAsync } from "./common.ts"; | |
| 24 | import { offersOwnToken, startNowWithOwnToken, START_NOW_HEAD, START_NOW_WORDS } from "../../actions/own_token.ts"; | |
| 24 | 25 | import { costText, envLabel, runTone } from "./runwords.ts"; |
| 25 | 26 | import { priceWords } from "../../core/run_price.ts"; |
| 26 | 27 | import { getUsage } from "../../core/usage.ts"; |
| @@ -61,6 +62,9 @@ export function runLogScreen( | ||
| 61 | 62 | ctx.invalidate(); |
| 62 | 63 | }; |
| 63 | 64 | |
| 65 | // A person's own build held for want of an account: one step to start it on theirs (#16490). | |
| 66 | const offer = (): boolean => view !== undefined && offersOwnToken(f.app, f.user, view.run); | |
| 67 | ||
| 64 | 68 | const web = (): void => |
| 65 | 69 | openOnWeb(f, ctx, `/${repo.ownerName}/${repo.name}/runs/${runId}`, "the run's log"); |
| 66 | 70 | |
| @@ -74,6 +78,7 @@ export function runLogScreen( | ||
| 74 | 78 | binding(["g", "G"], "top, end"), |
| 75 | 79 | binding(["o"], "open on the web"), |
| 76 | 80 | binding(["r"], "refresh"), |
| 81 | ...(offer() ? [binding(["a"], "start now on your own account")] : []), | |
| 77 | 82 | ]; |
| 78 | 83 | }, |
| 79 | 84 | load(signal) { |
| @@ -122,8 +127,10 @@ export function runLogScreen( | ||
| 122 | 127 | // does. One sentence a row, so a narrow terminal cuts neither. |
| 123 | 128 | const wall = |
| 124 | 129 | run.placement === "job" && run.sandboxEnforced === true ? jobSandboxWords(run.sandboxNote).split(/(?<=\.) /) : []; |
| 130 | const offering = offer(); | |
| 125 | 131 | const rows = split(area, "v", [ |
| 126 | 132 | len(1), |
| 133 | ...(offering ? [len(1)] : []), | |
| 127 | 134 | ...(price === "" ? [] : [len(1)]), |
| 128 | 135 | ...wall.map(() => len(1)), |
| 129 | 136 | fill(1), |
| @@ -149,9 +156,13 @@ export function runLogScreen( | ||
| 149 | 156 | style(tone === undefined ? c.mutedFg : c.fg, c.bg), |
| 150 | 157 | head!.x + head!.w, |
| 151 | 158 | ); |
| 152 | const lead = price === "" ? 1 : 2; | |
| 153 | if (price !== "") { | |
| 159 | if (offering) { | |
| 154 | 160 | const row = rows[1]!; |
| 161 | s.text(row.x, row.y, truncate(`${START_NOW_HEAD}: press a and paste your token.`, row.w), style(c.fg, c.bg), row.x + row.w); | |
| 162 | } | |
| 163 | const lead = (price === "" ? 1 : 2) + (offering ? 1 : 0); | |
| 164 | if (price !== "") { | |
| 165 | const row = rows[offering ? 2 : 1]!; | |
| 155 | 166 | s.text(row.x, row.y, truncate(price, row.w), style(c.mutedFg, c.bg), row.x + row.w); |
| 156 | 167 | } |
| 157 | 168 | wall.forEach((words, i) => { |
| @@ -184,6 +195,25 @@ export function runLogScreen( | ||
| 184 | 195 | } |
| 185 | 196 | }, |
| 186 | 197 | key(e) { |
| 198 | if (e.key === "a" && !e.ctrl && !e.alt && offer()) { | |
| 199 | const run = view!.run; | |
| 200 | ctx.push( | |
| 201 | promptScreen(ctx, self, { | |
| 202 | title: START_NOW_HEAD, | |
| 203 | label: "token (what claude setup-token printed, or an API key)", | |
| 204 | mask: true, | |
| 205 | onSubmit: (token) => { | |
| 206 | runAsync(ctx, async () => { | |
| 207 | const started = await startNowWithOwnToken(f.app, f.user, run, token); | |
| 208 | ctx.toast(started.ok ? "Saved as your own account; the build is starting on it." : START_NOW_WORDS[started.error], started.ok ? "success" : "danger"); | |
| 209 | read(); | |
| 210 | }); | |
| 211 | return undefined; | |
| 212 | }, | |
| 213 | }), | |
| 214 | ); | |
| 215 | return true; | |
| 216 | } | |
| 187 | 217 | if (e.key === "o" && !e.ctrl && !e.alt) { |
| 188 | 218 | web(); |
| 189 | 219 | return true; |
src/web/own_token.ts added +82
| @@ -0,0 +1,82 @@ | ||
| 1 | /** | |
| 2 | * The box a person's held build offers where its wait is shown (#16490): "Start now with your own | |
| 3 | * Claude account", one masked field and one button, posting to the run's own address. Without | |
| 4 | * script the form posts and comes back to the run with a flash; with it the box says what | |
| 5 | * happened in place, and the run page's (or Talk's) live stream shows the build starting. | |
| 6 | */ | |
| 7 | import { startNowWithOwnToken, START_NOW_HEAD, START_NOW_LINE, START_NOW_WORDS } from "../actions/own_token.ts"; | |
| 8 | import type { Ctx } from "../http/context.ts"; | |
| 9 | import { json, prefersJson } from "../http/respond.ts"; | |
| 10 | import { getRun } from "../core/runs.ts"; | |
| 11 | import { loadRepo, notFoundPage, repoBase, 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, card } from "./ui.ts"; | |
| 16 | ||
| 17 | /** The box, for the run at `base`/runs/`runId`. */ | |
| 18 | export function ownTokenBox(base: string, runId: string): Html { | |
| 19 | const id = `own-token-${runId}`; | |
| 20 | return card( | |
| 21 | html`<div class="stack"> | |
| 22 | <h2 class="h3" id="${id}-h">${START_NOW_HEAD}</h2> | |
| 23 | <p class="muted small">Paste the token <code>claude setup-token</code> prints, or an Anthropic API key. ${START_NOW_LINE}</p> | |
| 24 | <form class="stack" method="post" action="${base}/runs/${runId}/own-token" data-own-token> | |
| 25 | <label class="sr-only" for="${id}">Your Claude token or API key</label> | |
| 26 | <input class="input mono" id="${id}" name="token" type="password" autocomplete="off" autocapitalize="off" spellcheck="false" required placeholder="sk-ant-…" /> | |
| 27 | <p class="small" role="status" data-own-token-said></p> | |
| 28 | <span>${btn("Start now", { variant: "primary" })}</span> | |
| 29 | </form> | |
| 30 | </div>`, | |
| 31 | { extra: "mt", attrs: html`data-own-token-box aria-labelledby="${id}-h"` }, | |
| 32 | ); | |
| 33 | } | |
| 34 | ||
| 35 | /** The box's script: it posts in place, says what happened, and keeps the token out of the page. */ | |
| 36 | export const ownTokenJs = /* js */ ` | |
| 37 | (function () { | |
| 38 | document.addEventListener('submit', function (e) { | |
| 39 | var form = e.target; | |
| 40 | if (!form || !form.matches || !form.matches('form[data-own-token]') || !window.fetch) return; | |
| 41 | e.preventDefault(); | |
| 42 | var said = form.querySelector('[data-own-token-said]'); | |
| 43 | var button = form.querySelector('button'); | |
| 44 | var field = form.querySelector('input[name=token]'); | |
| 45 | if (button) button.disabled = true; | |
| 46 | if (said) said.textContent = 'Testing it with Anthropic…'; | |
| 47 | fetch(form.action, { method: 'POST', credentials: 'same-origin', headers: { accept: 'application/json' }, body: new FormData(form) }) | |
| 48 | .then(function (r) { return r.json().catch(function () { return { ok: false, said: 'Nothing was saved; try again.' }; }); }) | |
| 49 | .then(function (out) { | |
| 50 | if (field) field.value = ''; | |
| 51 | if (out.ok) { | |
| 52 | var box = form.closest('[data-own-token-box]'); | |
| 53 | var done = document.createElement('p'); | |
| 54 | done.setAttribute('role', 'status'); | |
| 55 | done.textContent = out.said; | |
| 56 | if (box) box.replaceChildren(done); | |
| 57 | return; | |
| 58 | } | |
| 59 | if (said) said.textContent = out.said; | |
| 60 | if (button) button.disabled = false; | |
| 61 | }) | |
| 62 | .catch(function () { if (said) said.textContent = 'That was not sent: no connection.'; if (button) button.disabled = false; }); | |
| 63 | }); | |
| 64 | })(); | |
| 65 | `; | |
| 66 | ||
| 67 | const STARTED = "Saved as your own account. Your build is starting on it now."; | |
| 68 | ||
| 69 | /** POST /:owner/:name/runs/:id/own-token */ | |
| 70 | export async function runOwnToken(ctx: Ctx): Promise<Response> { | |
| 71 | const repo = loadRepo(ctx); | |
| 72 | if (!repo) return notFoundPage(ctx); | |
| 73 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 74 | const form = await readForm(ctx, "rw"); | |
| 75 | if (form instanceof Response) return form; | |
| 76 | const run = getRun(ctx.app.db, ctx.params.id ?? ""); | |
| 77 | if (run === undefined || run.repoId !== repo.id) return notFoundPage(ctx); | |
| 78 | const started = await startNowWithOwnToken(ctx.app, ctx.auth.user, run, field(form, "token")); | |
| 79 | const said = started.ok ? STARTED : START_NOW_WORDS[started.error]; | |
| 80 | if (prefersJson(ctx.request)) return json({ ok: started.ok, said }, started.ok ? 200 : 422); | |
| 81 | return flashTo(ctx, `${repoBase(repo)}/runs/${run.id}`, started.ok ? { message: said } : { tone: "danger", message: said }); | |
| 82 | } |
src/web/pages/talk.ts +2 −1
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | * their id, the agent acts with their permissions (`crew/conversation.ts`). |
| 15 | 15 | */ |
| 16 | 16 | |
| 17 | import { ownTokenJs } from "../own_token.ts"; | |
| 17 | 18 | import { blockedFlash } from "../blocked.ts"; |
| 18 | 19 | import { noTalkAccountBlocked } from "../../actions/blocked_words.ts"; |
| 19 | 20 | import type { Database } from "bun:sqlite"; |
| @@ -682,7 +683,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 682 | 683 | </div> |
| 683 | 684 | ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null} |
| 684 | 685 | </div>`; |
| 685 | return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + peekCss + paneCss + codePaneCss + (panel === null ? "" : buildCss) + voiceCss, scriptJs: `${talkJs}\n${liveRegionsJs}`, description: "Talk to the forge.", wide: true, ...(!split ? {} : { frameSrc: frames }) }); | |
| 686 | return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + peekCss + paneCss + codePaneCss + (panel === null ? "" : buildCss) + voiceCss, scriptJs: `${talkJs}\n${liveRegionsJs}\n${ownTokenJs}`, description: "Talk to the forge.", wide: true, ...(!split ? {} : { frameSrc: frames }) }); | |
| 686 | 687 | } |
| 687 | 688 | |
| 688 | 689 | /** |
src/web/pages/talk_preview.ts +12 −6
| @@ -11,6 +11,9 @@ | ||
| 11 | 11 | * streaming beside it carries on. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { offersOwnToken } from "../../actions/own_token.ts"; | |
| 15 | import { getRun } from "../../core/runs.ts"; | |
| 16 | import { ownTokenBox } from "../own_token.ts"; | |
| 14 | 17 | import { paneQuery, pointedAt, workspaceOf, type Apps, type PaneAt, type PaneSteer, type paneOffer } from "../../actions/talk_workspace.ts"; |
| 15 | 18 | import { previewEnv } from "../../apps/data.ts"; |
| 16 | 19 | import type { User } from "../../core/users.ts"; |
| @@ -89,14 +92,17 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w | ||
| 89 | 92 | // While nothing is framed, what the crew is doing on the repository, read from its newest run. |
| 90 | 93 | const crew = view === "preview" ? paneCrew(ctx.app.db, ctx.app.config.dataDir, ws.repo.id, user, { runs: mayReadRuns(ctx.app, user, ws.repo), logs: mayReadRunLog(ctx.app, user, ws.repo) }) : undefined; |
| 91 | 94 | const going = crew !== undefined && (crew.state === "queued" || crew.state === "running"); |
| 95 | // A person's own build held for want of an account: the box to start it on theirs, right here. | |
| 96 | const heldRun = crew?.state === "queued" ? getRun(ctx.app.db, crew.runId) : undefined; | |
| 97 | const offer = heldRun !== undefined && offersOwnToken(ctx.app, user, heldRun) ? ownTokenBox(`/${ws.repo.ownerName}/${ws.repo.name}`, heldRun.id) : null; | |
| 92 | 98 | const panel = |
| 93 | 99 | view === "code" |
| 94 | 100 | ? await codeView(ctx.app, work) |
| 95 | 101 | : view === "diff" |
| 96 | 102 | ? await diffView(ctx.app, work, ask.version, ask.mine === undefined ? undefined : { ...ask.mine, picked: at.pull }) |
| 97 | 103 | : url === undefined || ask.wait !== undefined |
| 98 | ? html`<div class="talk-stage talk-stage-wait" data-stage${ask.busy === true ? raw(" data-busy") : null}><p class="talk-stage-note" data-stage-note>${ask.wait ?? ask.idle ?? "Nothing is running yet: the app appears here once it is built."}</p>${crew === undefined ? null : crewBlock(crew, `/${ws.repo.ownerName}/${ws.repo.name}`, ws.repo, liveSrc)}</div>${ask.build === undefined ? null : html`<h2 class="talk-stage-files small muted">The files it starts from</h2>${await codeView(ctx.app, work)}`}` | |
| 99 | : html`${steer === undefined || steer.try === "" ? null : html`<p class="talk-try small" data-pane-try>Try: ${steer.try}</p>`}<div class="talk-stage" data-stage data-env="${ws.shows === undefined ? "production" : previewEnv(ws.shows)}"><iframe class="talk-frame" data-frame src="${url}" title="Live preview of ${name}" referrerpolicy="no-referrer" sandbox="allow-scripts allow-same-origin allow-forms allow-popups"></iframe><p class="talk-stage-note small" data-stage-note hidden>Updating the preview…</p></div>${crewRegion(crew !== undefined && (going || crew.state === "failed") ? crew : undefined, ws.repo, liveSrc, ws.shows)}`; | |
| 104 | ? html`<div class="talk-stage talk-stage-wait" data-stage${ask.busy === true ? raw(" data-busy") : null}><p class="talk-stage-note" data-stage-note>${ask.wait ?? ask.idle ?? "Nothing is running yet: the app appears here once it is built."}</p>${crew === undefined ? null : crewBlock(crew, `/${ws.repo.ownerName}/${ws.repo.name}`, ws.repo, liveSrc, undefined, offer)}</div>${ask.build === undefined ? null : html`<h2 class="talk-stage-files small muted">The files it starts from</h2>${await codeView(ctx.app, work)}`}` | |
| 105 | : html`${steer === undefined || steer.try === "" ? null : html`<p class="talk-try small" data-pane-try>Try: ${steer.try}</p>`}<div class="talk-stage" data-stage data-env="${ws.shows === undefined ? "production" : previewEnv(ws.shows)}"><iframe class="talk-frame" data-frame src="${url}" title="Live preview of ${name}" referrerpolicy="no-referrer" sandbox="allow-scripts allow-same-origin allow-forms allow-popups"></iframe><p class="talk-stage-note small" data-stage-note hidden>Updating the preview…</p></div>${crewRegion(crew !== undefined && (going || crew.state === "failed") ? crew : undefined, ws.repo, liveSrc, ws.shows, offer)}`; | |
| 100 | 106 | // The address bar of what runs: which environment, where it lives, reload and open on its own. |
| 101 | 107 | const where = url === undefined ? null : html`<span class="talk-addr small" title="${url}"><span class="muted">${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}</span> ${new URL(url).host}</span>`; |
| 102 | 108 | // Waiting, the pane is a live region on the repository's runs: a deploy that turns running swaps |
| @@ -149,10 +155,10 @@ function productionOrigin(ctx: Ctx, repoId: string): string | undefined { | ||
| 149 | 155 | * whenever the pane is open, so the crew's next run (the person's next change) is picked up on |
| 150 | 156 | * run.* and drawn under the same frame, which the swap never touches. |
| 151 | 157 | */ |
| 152 | function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: string; readonly name: string }, src: string, shows?: number): Html { | |
| 158 | function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: string; readonly name: string }, src: string, shows?: number, offer: Html | null = null): Html { | |
| 153 | 159 | return crew === undefined |
| 154 | 160 | ? html`<div class="talk-crew-now" id="talk-crew-now" data-live="run.*" data-live-repo="${repo.ownerName}/${repo.name}" data-live-src="${src}"></div>` |
| 155 | : crewBlock(crew, `/${repo.ownerName}/${repo.name}`, repo, src, shows); | |
| 161 | : crewBlock(crew, `/${repo.ownerName}/${repo.name}`, repo, src, shows, offer); | |
| 156 | 162 | } |
| 157 | 163 | |
| 158 | 164 | /** |
| @@ -163,7 +169,7 @@ function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: stri | ||
| 163 | 169 | * works it folds to its one line (a `<details>`, the fold kept per conversation by the script); a |
| 164 | 170 | * hold or a failure is drawn open and unfoldable, so neither is ever hidden. |
| 165 | 171 | */ |
| 166 | function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: string; readonly name: string }, src: string, shows?: number): Html { | |
| 172 | function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: string; readonly name: string }, src: string, shows?: number, offer: Html | null = null): Html { | |
| 167 | 173 | const working = crew.state === "running" ? " talk-crew-working" : ""; |
| 168 | 174 | const line = html`<p class="small${working}">${workLineHtml(crew.line)}</p>`; |
| 169 | 175 | const steps = !crew.tail || (crew.steps.length === 0 && crew.state !== "running") ? null : html`<div class="talk-crew-steps small muted" data-crew-steps="${crew.runId}" aria-live="polite">${crew.steps.map((item) => (item.thought ? html`<p class="talk-crew-thought">${item.text}</p>` : html`<p>${item.text}</p>`))}</div>`; |
| @@ -173,7 +179,7 @@ function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: str | ||
| 173 | 179 | // Its own live region: the crew's next run is read as it is queued, starts or ends, and the frame |
| 174 | 180 | // above it is never redrawn for it. |
| 175 | 181 | return html`<div class="talk-crew-now" id="talk-crew-now" data-live="run.*" data-live-repo="${repo.ownerName}/${repo.name}" data-live-src="${src}"> |
| 176 | ${crew.held === true || crew.state === "failed" ? html`${line}${steps}${run}` : html`<details class="talk-crew-fold" open><summary><span class="small${working}">${workLineHtml(crew.line)}</span></summary>${steps}${run}${reply}</details>`} | |
| 182 | ${crew.held === true || crew.state === "failed" ? html`${line}${steps}${run}` : html`<details class="talk-crew-fold" open><summary><span class="small${working}">${workLineHtml(crew.line)}</span></summary>${steps}${run}${reply}</details>`}${offer} | |
| 177 | 183 | </div>`; |
| 178 | 184 | } |
| 179 | 185 |
src/web/studio/run.ts +4 −1
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | * at `?all=1`. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { offersOwnToken } from "../../actions/own_token.ts"; | |
| 12 | import { ownTokenBox, ownTokenJs } from "../own_token.ts"; | |
| 11 | 13 | import { time } from "../time_element.ts"; |
| 12 | 14 | import { wayIn } from "../../actions/blocked_words.ts"; |
| 13 | 15 | import { blockedWay } from "../blocked.ts"; |
| @@ -233,6 +235,7 @@ export async function runView( | ||
| 233 | 235 | )} |
| 234 | 236 | </div> |
| 235 | 237 | <p class="mt" id="run-summary">${stoppedLine(run) ?? run.summary}${when(run.state === "cancelled", () => endedTail(run, word === "stopping"))}</p> |
| 238 | ${when(offersOwnToken(ctx.app, ctx.auth.user, run), () => ownTokenBox(repoBase(repo), run.id))} | |
| 236 | 239 | ${when(wayIn(ctx.app, ctx.auth.user, run.summary, repo), (way) => html`<div class="small" id="run-way">${blockedWay(way)}</div>`)} |
| 237 | 240 | ${when( |
| 238 | 241 | carried.length > 0, |
| @@ -482,6 +485,6 @@ export async function runView( | ||
| 482 | 485 | palette: repoPalette(ctx, repo), |
| 483 | 486 | body, |
| 484 | 487 | styleCss: RUN_PAGE_CSS, |
| 485 | scriptJs: `${liveRegionsJs}\n${studioRunJs}\n${openFoldJs}`, | |
| 488 | scriptJs: `${liveRegionsJs}\n${studioRunJs}\n${openFoldJs}\n${ownTokenJs}`, | |
| 486 | 489 | }); |
| 487 | 490 | } |
test/crew-breath.test.ts added +36
| @@ -0,0 +1,36 @@ | ||
| 1 | /** | |
| 2 | * A per-minute refusal (#16490): told apart from a full window, waited a minute or a few by who | |
| 3 | * sent the run, said in plain words, and held for the crew's own work so a person's goes first. | |
| 4 | */ | |
| 5 | import { expect, test } from "bun:test"; | |
| 6 | import { breathingUntil, breathWait, breathWords, noteBreath, perMinute } from "../src/crew/limits.ts"; | |
| 7 | import { pauseCause } from "../src/crew/pacing.ts"; | |
| 8 | ||
| 9 | test("a 429 with no window is per-minute; a used-up window or a time named is not", () => { | |
| 10 | expect(perMinute({ said: "API Error: Request rejected (429) · This request would exceed your account's rate limit. Please try again later." })).toBe(true); | |
| 11 | expect(perMinute({ said: "Too many requests" })).toBe(true); | |
| 12 | expect(perMinute({ said: "You've hit your usage limit" })).toBe(false); | |
| 13 | expect(perMinute({ said: "rate limit", limitedUntil: "2026-11-25T22:00:00.000Z", window: "5h" })).toBe(false); | |
| 14 | expect(perMinute(undefined)).toBe(false); | |
| 15 | }); | |
| 16 | ||
| 17 | test("a person's run waits least; the crew's own backs off first and further, both capped", () => { | |
| 18 | expect([0, 1, 2, 3, 9].map((n) => breathWait(n, true) / 60_000)).toEqual([1, 2, 4, 8, 8]); | |
| 19 | expect([0, 1, 2, 3, 9].map((n) => breathWait(n, false) / 60_000)).toEqual([4, 8, 16, 30, 30]); | |
| 20 | }); | |
| 21 | ||
| 22 | test("the words are plain and carry the time; the cause reads as a rate limit", () => { | |
| 23 | const at = new Date("2026-11-25T21:49:36.000Z"); | |
| 24 | expect(breathWords(at, true)).toBe("The crew is catching its breath (too many requests this minute); your build starts again by 21:49 UTC."); | |
| 25 | expect(breathWords(at, false)).toContain("; it starts again by 21:49 UTC."); | |
| 26 | expect(pauseCause(`paused: ${breathWords(at, true)}`)).toBe("rate limit"); | |
| 27 | }); | |
| 28 | ||
| 29 | test("the crew's own runs hold on an account until its breath is back, and only that account", () => { | |
| 30 | const now = new Date("2026-11-25T21:30:00.000Z"); | |
| 31 | noteBreath("acct-a", new Date(now.getTime() + 4 * 60_000)); | |
| 32 | noteBreath("acct-a", new Date(now.getTime() + 60_000)); // an earlier time never shortens it | |
| 33 | expect(breathingUntil("acct-a", now)?.toISOString()).toBe("2026-11-25T21:34:00.000Z"); | |
| 34 | expect(breathingUntil("acct-b", now)).toBeUndefined(); | |
| 35 | expect(breathingUntil("acct-a", new Date(now.getTime() + 5 * 60_000))).toBeUndefined(); | |
| 36 | }); |
test/crew-pause.test.ts +39
| @@ -4,6 +4,9 @@ | ||
| 4 | 4 | * `crew.test.ts` so each part runs apart (#1798). |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { breathingUntil } from "../src/crew/limits.ts"; | |
| 8 | import { actingVia } from "../src/core/acting_via.ts"; | |
| 9 | import { PLATFORM } from "../src/core/subscriptions.ts"; | |
| 7 | 10 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 8 | 11 | import { existsSync, readFileSync } from "node:fs"; |
| 9 | 12 | import { join } from "node:path"; |
| @@ -98,4 +101,40 @@ describe("the crew, with a stand-in Claude Code: paused by the provider", () => | ||
| 98 | 101 | expect(log).toContain("clone kept as it was left"); |
| 99 | 102 | expect(log).toContain("PAUSED.md present: yes"); |
| 100 | 103 | }, 90_000); |
| 104 | ||
| 105 | test("a per-minute refusal pauses a person's build a minute in plain words, and holds the crew's own work on that account", async () => { | |
| 106 | const issue = openIssue(app, alice, repo, { title: "Trim the hedge", body: "OUT-OF-BREATH: square, not round." }); | |
| 107 | if (!issue.ok) throw new Error(String(issue.error)); | |
| 108 | // Assigned in alice's own request, as a page does: her run, sent by a person. | |
| 109 | expect(actingVia({ userId: alice.id, door: "web" }, () => assignIssue(app, alice, repo, issue.value, bot)).ok).toBe(true); | |
| 110 | const before = Date.now(); | |
| 111 | const paused = await settled((r) => r.issueId === issue.value.id && r.attempt === 0); | |
| 112 | expect(paused.state).toBe("cancelled"); | |
| 113 | // The provider's words stay in the log; the card says what happens, in plain words. | |
| 114 | expect(paused.summary).toMatch( | |
| 115 | /^paused: The crew is catching its breath \(too many requests this minute\); your build starts again by \d\d:\d\d UTC\.$/, | |
| 116 | ); | |
| 117 | expect(paused.summary).not.toContain("429"); | |
| 118 | expect(readRunLog(dataDir, paused.id).lines.join("\n")).toContain("Request rejected (429)"); | |
| 119 | const waiting = listRuns(app.db, repo.id, { kind: "agent" }).find((r) => r.issueId === issue.value.id && r.state === "queued")!; | |
| 120 | // A person's run waits a minute, not the 15 an unnamed limit gets. | |
| 121 | const wait = new Date(waiting.notBefore!).getTime() - before; | |
| 122 | expect(wait).toBeGreaterThan(30_000); | |
| 123 | expect(wait).toBeLessThan(2 * 60_000); | |
| 124 | // The crew's own runs on the forge's account hold a few minutes, so the person's goes first. | |
| 125 | const held = breathingUntil(PLATFORM, new Date()); | |
| 126 | expect(held).toBeDefined(); | |
| 127 | expect(held!.getTime()).toBeGreaterThan(new Date(waiting.notBefore!).getTime()); | |
| 128 | ||
| 129 | // The crew's own work (an assignment no person sent now) on the same account holds until | |
| 130 | // then, and the hold is not counted as one of its pauses. | |
| 131 | const own = openIssue(app, alice, repo, { title: "Rake the leaves", body: "the whole lawn" }); | |
| 132 | if (!own.ok) throw new Error(String(own.error)); | |
| 133 | expect(assignIssue(app, alice, repo, own.value, bot).ok).toBe(true); | |
| 134 | const holding = await settled((r) => r.issueId === own.value.id && r.state === "cancelled"); | |
| 135 | expect(holding.summary).toMatch(/; it starts again by \d\d:\d\d UTC\.$/); | |
| 136 | const queued = listRuns(app.db, repo.id, { kind: "agent" }).find((r) => r.issueId === own.value.id && r.state === "queued")!; | |
| 137 | expect(queued.attempt).toBe(0); | |
| 138 | expect(new Date(queued.notBefore!).getTime()).toBe(held!.getTime()); | |
| 139 | }, 90_000); | |
| 101 | 140 | }); |
test/helpers/crew-standin.ts +5
| @@ -205,6 +205,11 @@ echo "half-done" > PAUSED.md | ||
| 205 | 205 | echo '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"You\u2019ve hit your session limit \u00b7 resets 7:20am (UTC)","total_cost_usd":0.02,"num_turns":2,"session_id":"fake-1","terminal_reason":"api_error"}' |
| 206 | 206 | exit 0 |
| 207 | 207 | fi |
| 208 | if grep -q OUT-OF-BREATH "${promptFile}" && [ ! -f MINUTE.md ]; then | |
| 209 | echo "once" > MINUTE.md | |
| 210 | echo '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"API Error: Request rejected (429) \u00b7 This request would exceed your account\u2019s rate limit. Please try again later.","total_cost_usd":0,"num_turns":1,"session_id":"fake-1","terminal_reason":"api_error"}' | |
| 211 | exit 0 | |
| 212 | fi | |
| 208 | 213 | if grep -q PUSH-THEN-DOWN "${promptFile}" && [ ! -f "${dataDir}/down" ]; then |
| 209 | 214 | echo "work by the crew $(date +%s%N)" >> CREW.md |
| 210 | 215 | git add -A && git commit -qm "crew work" && git push -q -u origin HEAD |
test/own-token.test.ts added +137
| @@ -0,0 +1,137 @@ | ||
| 1 | /** | |
| 2 | * "Start now with your own Claude account" (#16490): a person's own build held for want of an | |
| 3 | * account offers one step where the wait is shown; a token is tested before anything is kept, | |
| 4 | * saved sealed as their own, and the run is let go at once. Nobody else is offered it, and the | |
| 5 | * token never comes back in any answer. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { offersOwnToken } from "../src/actions/own_token.ts"; | |
| 13 | import { tokenWorks, useTokenTester } from "../src/crew/token_check.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { ownSubscription } from "../src/core/model_grant.ts"; | |
| 16 | import type { Repo } from "../src/core/repos.ts"; | |
| 17 | import { createRun, getRun } from "../src/core/runs.ts"; | |
| 18 | import { createSession } from "../src/core/sessions.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { readRunLog } from "../src/runs/log.ts"; | |
| 22 | ||
| 23 | const TOKEN = "sk-ant-oat01-a-canned-token-for-the-test-only"; | |
| 24 | let dir: string; | |
| 25 | let app: App; | |
| 26 | let servers: Servers; | |
| 27 | let alice: User; | |
| 28 | let bob: User; | |
| 29 | let repo: Repo; | |
| 30 | let tested: string[] = []; | |
| 31 | ||
| 32 | beforeAll(async () => { | |
| 33 | dir = await mkdtemp(join(tmpdir(), "forge-own-token-")); | |
| 34 | app = createApp({ dataDir: dir, port: 0 }); | |
| 35 | servers = await serve(app); | |
| 36 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 37 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 38 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 39 | alice = a.value; | |
| 40 | bob = b.value; | |
| 41 | const made = await createRepo(app, alice, { name: "shop", visibility: "public" }); | |
| 42 | if (!made.ok) throw new Error(String(made.error)); | |
| 43 | repo = made.value; | |
| 44 | useTokenTester(async (token) => { | |
| 45 | tested.push(token); | |
| 46 | return token === TOKEN; | |
| 47 | }); | |
| 48 | }); | |
| 49 | ||
| 50 | afterAll(async () => { | |
| 51 | useTokenTester(undefined); | |
| 52 | servers.stop(); | |
| 53 | app.close(); | |
| 54 | await rm(dir, { recursive: true, force: true }); | |
| 55 | }); | |
| 56 | ||
| 57 | /** A build alice sent, paused by the provider until later and queued again: the wait the box is for. */ | |
| 58 | function held(): string { | |
| 59 | return createRun(app.db, { | |
| 60 | repoId: repo.id, | |
| 61 | kind: "agent", | |
| 62 | actorId: alice.id, | |
| 63 | reason: "assigned", | |
| 64 | sent: true, | |
| 65 | attempt: 1, | |
| 66 | notBefore: new Date(Date.now() + 15 * 60_000).toISOString(), | |
| 67 | summary: "paused: The crew is catching its breath (too many requests this minute); your build starts again by 21:49 UTC.", | |
| 68 | }).id; | |
| 69 | } | |
| 70 | ||
| 71 | const as = (user: User) => `forge_session=${createSession(app.db, user.id).token}`; | |
| 72 | const post = (user: User, runId: string, token: string) => | |
| 73 | fetch(`${servers.url}/alice/shop/runs/${runId}/own-token`, { | |
| 74 | method: "POST", | |
| 75 | headers: { cookie: as(user), origin: servers.url, accept: "application/json", "content-type": "application/x-www-form-urlencoded" }, | |
| 76 | body: new URLSearchParams({ token }), | |
| 77 | }); | |
| 78 | ||
| 79 | test("the owner of a held build is offered the box on its page; anyone else reads the wait as it is", async () => { | |
| 80 | const id = held(); | |
| 81 | expect(offersOwnToken(app, alice, getRun(app.db, id)!)).toBe(true); | |
| 82 | expect(offersOwnToken(app, bob, getRun(app.db, id)!)).toBe(false); | |
| 83 | const mine = await (await fetch(`${servers.url}/alice/shop/runs/${id}`, { headers: { cookie: as(alice) } })).text(); | |
| 84 | expect(mine).toContain("Start now with your own Claude account"); | |
| 85 | expect(mine).toContain(`action="/alice/shop/runs/${id}/own-token"`); | |
| 86 | expect(mine).toMatch(/<input[^>]*name="token"[^>]*type="password"/); | |
| 87 | const theirs = await (await fetch(`${servers.url}/alice/shop/runs/${id}`, { headers: { cookie: as(bob) } })).text(); | |
| 88 | expect(theirs).not.toContain("Start now with your own Claude account"); | |
| 89 | const refused = await post(bob, id, TOKEN); | |
| 90 | expect(refused.status).toBe(422); | |
| 91 | expect(tested).toEqual([]); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a token that is not one, or one Anthropic refuses, keeps nothing and says so plainly", async () => { | |
| 95 | const id = held(); | |
| 96 | const notOne = await post(alice, id, "two words"); | |
| 97 | expect(notOne.status).toBe(422); | |
| 98 | expect(((await notOne.json()) as { said: string }).said).toContain("That is not a token"); | |
| 99 | const refused = await post(alice, id, "sk-ant-oat01-not-the-right-one"); | |
| 100 | expect(((await refused.json()) as { said: string }).said).toContain("did not accept that token"); | |
| 101 | expect(ownSubscription(app.db, alice.id)).toBeUndefined(); | |
| 102 | expect(getRun(app.db, id)!.notBefore).not.toBeNull(); | |
| 103 | }); | |
| 104 | ||
| 105 | test("a working token is saved sealed as her own, the build is let go at once, and the token never comes back", async () => { | |
| 106 | const id = held(); | |
| 107 | const res = await post(alice, id, ` ${TOKEN}\n`); | |
| 108 | expect(res.status).toBe(200); | |
| 109 | const body = await res.text(); | |
| 110 | expect(body).toContain("Your build is starting on it now"); | |
| 111 | expect(body).not.toContain(TOKEN); | |
| 112 | const own = ownSubscription(app.db, alice.id); | |
| 113 | expect(own).toBeDefined(); | |
| 114 | const row = app.db.query<{ token_enc: string }, [string]>("SELECT token_enc FROM subscription WHERE id = ?1").get(own!.id)!; | |
| 115 | expect(row.token_enc).not.toContain(TOKEN); | |
| 116 | expect(getRun(app.db, id)!.notBefore).toBeNull(); | |
| 117 | expect(getRun(app.db, id)!.summary).toBe("starting on your own Claude account"); | |
| 118 | expect(readRunLog(dir, id).lines.join("\n")).toContain("alice added their own Claude account; the run starts on it now"); | |
| 119 | // Once she has her own, the box is not offered again. | |
| 120 | expect(offersOwnToken(app, alice, getRun(app.db, held())!)).toBe(false); | |
| 121 | }); | |
| 122 | ||
| 123 | test("the test of a token asks Anthropic the way its kind needs, and a refusal or a dead line is false", async () => { | |
| 124 | const asked: { url: string; headers: Record<string, string> }[] = []; | |
| 125 | const canned = (status: number, body: unknown) => async (url: string, init: RequestInit) => { | |
| 126 | asked.push({ url, headers: init.headers as Record<string, string> }); | |
| 127 | return new Response(JSON.stringify(body), { status }); | |
| 128 | }; | |
| 129 | expect(await tokenWorks(TOKEN, canned(200, { five_hour: { utilization: 10 } }))).toBe(true); | |
| 130 | expect(asked[0]!.url).toBe("https://api.anthropic.com/api/oauth/usage"); | |
| 131 | expect(asked[0]!.headers["authorization"]).toBe(`Bearer ${TOKEN}`); | |
| 132 | expect(await tokenWorks("sk-ant-api03-key", canned(200, { data: [] }))).toBe(true); | |
| 133 | expect(asked[1]!.url).toBe("https://api.anthropic.com/v1/models"); | |
| 134 | expect(asked[1]!.headers["x-api-key"]).toBe("sk-ant-api03-key"); | |
| 135 | expect(await tokenWorks("sk-ant-api03-key", canned(401, {}))).toBe(false); | |
| 136 | expect(await tokenWorks("sk-ant-api03-key", async () => { throw new Error("offline"); })).toBe(false); | |
| 137 | }); |
new above
offline