Public: anyone can read this; the crew can change it.
Start now with your own Claude account: one paste on a waiting build (#16490) #16571
Check · Review · Land · Live done — Landed and live in production.
fix/own-token → main 0 commits 4 threads · 4 unresolved
13 files
changed +540
−11
- docs/features/start-now-own-account.md
- src/actions/own_token.ts
- src/crew/meter_watch.ts
- src/crew/token_check.ts
- src/http/server.ts
- src/tui/screens/runlog.ts
- src/web/own_token.ts
- src/web/pages/talk.ts
- src/web/pages/talk_preview.ts
- src/web/studio/run.ts
- test/own-token.test.ts
- test/talk-live-pane-fenced.test.ts
- test/tui-own-token.test.ts
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 { tokenWorks } 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 = "Paste what claude setup-token prints, or an Anthropic API key: it is tested first, kept sealed, and never shown again."; | |
| 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 tokenWorks(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/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/token_check.ts added +20
| @@ -0,0 +1,20 @@ | ||
| 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 | * fetcher is the global one unless a caller passes its own, as the meter watch's callers do. | |
| 5 | */ | |
| 6 | import { kindOfToken } from "../core/subscriptions.ts"; | |
| 7 | import { readMeter, type Fetch } from "./meter_watch.ts"; | |
| 8 | ||
| 9 | export async function tokenWorks(token: string, fetcher: Fetch = fetch): Promise<boolean> { | |
| 10 | if (kindOfToken(token) === "oauth") return (await readMeter(token, fetcher)) !== undefined; | |
| 11 | try { | |
| 12 | const res = await fetcher("https://api.anthropic.com/v1/models", { | |
| 13 | headers: { "x-api-key": token, "anthropic-version": "2023-06-01", accept: "application/json" }, | |
| 14 | signal: AbortSignal.timeout(10_000), | |
| 15 | }); | |
| 16 | return res.ok; | |
| 17 | } catch { | |
| 18 | return false; | |
| 19 | } | |
| 20 | } |
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, togetherLine, togethernessOf } from "../web/together.ts"; |
| 9 | 10 | import { outsiderStatusPage } from "./offer_routes.ts"; |
| 10 | 11 | import { standingFragment } from "../web/pages/fork-standing.ts"; |
| @@ -1696,6 +1697,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1696 | 1697 | router.add("GET", "/:owner/:name/runs/:id", runPage); |
| 1697 | 1698 | router.add("POST", "/:owner/:name/runs/:id/cancel", runCancel); |
| 1698 | 1699 | router.add("POST", "/:owner/:name/runs/:id/requeue", runRequeue); |
| 1700 | router.add("POST", "/:owner/:name/runs/:id/own-token", runOwnToken); | |
| 1699 | 1701 | router.add("POST", "/:owner/:name/runs/:id/steer", runSteer); |
| 1700 | 1702 | // The public social cards: a repo as owner~name, an app as its slug. |
| 1701 | 1703 | 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) { |
| @@ -125,8 +130,10 @@ export function runLogScreen( | ||
| 125 | 130 | ...(run.placement === "job" && run.sandboxEnforced === true ? jobSandboxWords(run.sandboxNote).split(/(?<=\.) /) : []), |
| 126 | 131 | ...(began === "" ? [] : [`${began[0]!.toUpperCase()}${began.slice(1)}.`]), |
| 127 | 132 | ]; |
| 133 | const offering = offer(); | |
| 128 | 134 | const rows = split(area, "v", [ |
| 129 | 135 | len(1), |
| 136 | ...(offering ? [len(1)] : []), | |
| 130 | 137 | ...(price === "" ? [] : [len(1)]), |
| 131 | 138 | ...wall.map(() => len(1)), |
| 132 | 139 | fill(1), |
| @@ -152,9 +159,13 @@ export function runLogScreen( | ||
| 152 | 159 | style(tone === undefined ? c.mutedFg : c.fg, c.bg), |
| 153 | 160 | head!.x + head!.w, |
| 154 | 161 | ); |
| 155 | const lead = price === "" ? 1 : 2; | |
| 156 | if (price !== "") { | |
| 162 | if (offering) { | |
| 157 | 163 | const row = rows[1]!; |
| 164 | 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); | |
| 165 | } | |
| 166 | const lead = (price === "" ? 1 : 2) + (offering ? 1 : 0); | |
| 167 | if (price !== "") { | |
| 168 | const row = rows[offering ? 2 : 1]!; | |
| 158 | 169 | s.text(row.x, row.y, truncate(price, row.w), style(c.mutedFg, c.bg), row.x + row.w); |
| 159 | 170 | } |
| 160 | 171 | wall.forEach((words, i) => { |
| @@ -187,6 +198,25 @@ export function runLogScreen( | ||
| 187 | 198 | } |
| 188 | 199 | }, |
| 189 | 200 | key(e) { |
| 201 | if (e.key === "a" && !e.ctrl && !e.alt && offer()) { | |
| 202 | const run = view!.run; | |
| 203 | ctx.push( | |
| 204 | promptScreen(ctx, self, { | |
| 205 | title: START_NOW_HEAD, | |
| 206 | label: "token (what claude setup-token printed, or an API key)", | |
| 207 | mask: true, | |
| 208 | onSubmit: (token) => { | |
| 209 | runAsync(ctx, async () => { | |
| 210 | const started = await startNowWithOwnToken(f.app, f.user, run, token); | |
| 211 | ctx.toast(started.ok ? "Saved as your own account; the build is starting on it." : START_NOW_WORDS[started.error], started.ok ? "success" : "danger"); | |
| 212 | read(); | |
| 213 | }); | |
| 214 | return undefined; | |
| 215 | }, | |
| 216 | }), | |
| 217 | ); | |
| 218 | return true; | |
| 219 | } | |
| 190 | 220 | if (e.key === "o" && !e.ctrl && !e.alt) { |
| 191 | 221 | web(); |
| 192 | 222 | 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 } from "./ui.ts"; | |
| 16 | ||
| 17 | /** | |
| 18 | * The box, for the run at `base`/runs/`runId`: under the wait it sits beside, a heading, one | |
| 19 | * sentence, the field and the button. No card: it is one step of the wait, not a panel of its own. | |
| 20 | */ | |
| 21 | export function ownTokenBox(base: string, runId: string): Html { | |
| 22 | const id = `own-token-${runId}`; | |
| 23 | return html`<form class="stack mt" method="post" action="${base}/runs/${runId}/own-token" data-own-token data-own-token-box aria-labelledby="${id}-h"> | |
| 24 | <h2 class="h3" id="${id}-h">${START_NOW_HEAD}</h2> | |
| 25 | <p class="muted small">${START_NOW_LINE}</p> | |
| 26 | <label class="sr-only" for="${id}">Your Claude token or API key</label> | |
| 27 | <span class="bar"> | |
| 28 | <input class="input mono" id="${id}" name="token" type="password" autocomplete="off" autocapitalize="off" spellcheck="false" required placeholder="sk-ant-…" /> | |
| 29 | ${btn("Start now", { variant: "primary" })} | |
| 30 | </span> | |
| 31 | <p class="small" role="status" data-own-token-said></p> | |
| 32 | </form>`; | |
| 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; | |
| 53 | var done = document.createElement('p'); | |
| 54 | done.setAttribute('role', 'status'); | |
| 55 | done.textContent = out.said; | |
| 56 | box.replaceWith(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"; |
| @@ -687,7 +688,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 687 | 688 | </div> |
| 688 | 689 | ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null} |
| 689 | 690 | </div>`; |
| 690 | 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 }) }); | |
| 691 | 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 }) }); | |
| 691 | 692 | } |
| 692 | 693 | |
| 693 | 694 | /** |
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, () => ctx.url.pathname)}</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, () => ctx.url.pathname, 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, () => ctx.url.pathname, 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, () => ctx.url.pathname, 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, back: () => string, shows?: number): Html { | |
| 158 | function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: string; readonly name: string }, src: string, back: () => 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, back, shows); | |
| 161 | : crewBlock(crew, `/${repo.ownerName}/${repo.name}`, repo, src, back, 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, back: () => string, shows?: number): Html { | |
| 172 | function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: string; readonly name: string }, src: string, back: () => 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>`; |
| @@ -176,7 +182,7 @@ function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: str | ||
| 176 | 182 | // Its own live region: the crew's next run is read as it is queued, starts or ends, and the frame |
| 177 | 183 | // above it is never redrawn for it. |
| 178 | 184 | 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}"> |
| 179 | ${crew.held === true || crew.state === "failed" ? html`${line}${again}${steps}${run}` : html`<details class="talk-crew-fold" open><summary><span class="small${working}">${workLineHtml(crew.line)}</span></summary>${steps}${run}${reply}</details>`} | |
| 185 | ${crew.held === true || crew.state === "failed" ? html`${line}${again}${steps}${run}` : html`<details class="talk-crew-fold" open><summary><span class="small${working}">${workLineHtml(crew.line)}</span></summary>${steps}${run}${reply}</details>`}${offer} | |
| 180 | 186 | </div>`; |
| 181 | 187 | } |
| 182 | 188 |
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"; |
| @@ -229,6 +231,7 @@ export async function runView( | ||
| 229 | 231 | >`} |
| 230 | 232 | </div> |
| 231 | 233 | <p class="mt" id="run-summary">${stoppedLine(run) ?? run.summary}${when(run.state === "cancelled", () => endedTail(run, word === "stopping"))}</p> |
| 234 | ${when(offersOwnToken(ctx.app, ctx.auth.user, run), () => ownTokenBox(repoBase(repo), run.id))} | |
| 232 | 235 | ${when(wayIn(ctx.app, ctx.auth.user, run.summary, repo), (way) => html`<div class="small" id="run-way">${blockedWay(way)}</div>`)} |
| 233 | 236 | ${when( |
| 234 | 237 | carried.length > 0, |
| @@ -479,6 +482,6 @@ export async function runView( | ||
| 479 | 482 | palette: repoPalette(ctx, repo), |
| 480 | 483 | body, |
| 481 | 484 | styleCss: RUN_PAGE_CSS, |
| 482 | scriptJs: `${liveRegionsJs}\n${studioRunJs}\n${openFoldJs}`, | |
| 485 | scriptJs: `${liveRegionsJs}\n${studioRunJs}\n${openFoldJs}\n${ownTokenJs}`, | |
| 483 | 486 | }); |
| 484 | 487 | } |
test/own-token.test.ts added +157
| @@ -0,0 +1,157 @@ | ||
| 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 } 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 | const realFetch = globalThis.fetch; | |
| 32 | ||
| 33 | beforeAll(async () => { | |
| 34 | dir = await mkdtemp(join(tmpdir(), "forge-own-token-")); | |
| 35 | app = createApp({ dataDir: dir, port: 0 }); | |
| 36 | servers = await serve(app); | |
| 37 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 38 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 39 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 40 | alice = a.value; | |
| 41 | bob = b.value; | |
| 42 | const made = await createRepo(app, alice, { name: "shop", visibility: "public" }); | |
| 43 | if (!made.ok) throw new Error(String(made.error)); | |
| 44 | repo = made.value; | |
| 45 | // Anthropic, canned: the one Claude token it accepts reads a usage meter; nothing else does. | |
| 46 | // Every other address goes to the real fetch (the forge under test). | |
| 47 | globalThis.fetch = Object.assign(async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => { | |
| 48 | const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; | |
| 49 | if (!url.startsWith("https://api.anthropic.com/")) return realFetch(input, init); | |
| 50 | const auth = new Headers(init?.headers).get("authorization") ?? ""; | |
| 51 | tested.push(auth.replace(/^Bearer /, "")); | |
| 52 | return auth === `Bearer ${TOKEN}` ? Response.json({ five_hour: { utilization: 10 } }) : new Response("{}", { status: 401 }); | |
| 53 | }, { preconnect: realFetch.preconnect }); | |
| 54 | }); | |
| 55 | ||
| 56 | afterAll(async () => { | |
| 57 | globalThis.fetch = realFetch; | |
| 58 | servers.stop(); | |
| 59 | app.close(); | |
| 60 | await rm(dir, { recursive: true, force: true }); | |
| 61 | }); | |
| 62 | ||
| 63 | /** A build alice sent, paused by the provider until later and queued again: the wait the box is for. */ | |
| 64 | function held(): string { | |
| 65 | return createRun(app.db, { | |
| 66 | repoId: repo.id, | |
| 67 | kind: "agent", | |
| 68 | actorId: alice.id, | |
| 69 | reason: "assigned", | |
| 70 | sent: true, | |
| 71 | attempt: 1, | |
| 72 | notBefore: new Date(Date.now() + 15 * 60_000).toISOString(), | |
| 73 | summary: "paused: The crew is catching its breath (too many requests this minute); your build starts again by 21:49 UTC.", | |
| 74 | }).id; | |
| 75 | } | |
| 76 | ||
| 77 | const as = (user: User) => `forge_session=${createSession(app.db, user.id).token}`; | |
| 78 | const post = (user: User, runId: string, token: string) => | |
| 79 | fetch(`${servers.url}/alice/shop/runs/${runId}/own-token`, { | |
| 80 | method: "POST", | |
| 81 | headers: { cookie: as(user), origin: servers.url, accept: "application/json", "content-type": "application/x-www-form-urlencoded" }, | |
| 82 | body: new URLSearchParams({ token }), | |
| 83 | }); | |
| 84 | ||
| 85 | test("the owner of a held build is offered the box on its page; anyone else reads the wait as it is", async () => { | |
| 86 | const id = held(); | |
| 87 | expect(offersOwnToken(app, alice, getRun(app.db, id)!)).toBe(true); | |
| 88 | expect(offersOwnToken(app, bob, getRun(app.db, id)!)).toBe(false); | |
| 89 | const mine = await (await fetch(`${servers.url}/alice/shop/runs/${id}`, { headers: { cookie: as(alice) } })).text(); | |
| 90 | expect(mine).toContain("Start now with your own Claude account"); | |
| 91 | expect(mine).toContain(`action="/alice/shop/runs/${id}/own-token"`); | |
| 92 | expect(mine).toMatch(/<input[^>]*name="token"[^>]*type="password"/); | |
| 93 | const theirs = await (await fetch(`${servers.url}/alice/shop/runs/${id}`, { headers: { cookie: as(bob) } })).text(); | |
| 94 | expect(theirs).not.toContain("Start now with your own Claude account"); | |
| 95 | const refused = await post(bob, id, TOKEN); | |
| 96 | expect(refused.status).toBe(422); | |
| 97 | expect(tested).toEqual([]); | |
| 98 | }); | |
| 99 | ||
| 100 | test("a token that is not one, or one Anthropic refuses, keeps nothing and says so plainly", async () => { | |
| 101 | const id = held(); | |
| 102 | const notOne = await post(alice, id, "two words"); | |
| 103 | expect(notOne.status).toBe(422); | |
| 104 | expect(((await notOne.json()) as { said: string }).said).toContain("That is not a token"); | |
| 105 | const refused = await post(alice, id, "sk-ant-oat01-not-the-right-one"); | |
| 106 | expect(((await refused.json()) as { said: string }).said).toContain("did not accept that token"); | |
| 107 | expect(ownSubscription(app.db, alice.id)).toBeUndefined(); | |
| 108 | expect(getRun(app.db, id)!.notBefore).not.toBeNull(); | |
| 109 | }); | |
| 110 | ||
| 111 | test("without script the form posts, and comes back to the run with what happened", async () => { | |
| 112 | const id = held(); | |
| 113 | const res = await fetch(`${servers.url}/alice/shop/runs/${id}/own-token`, { | |
| 114 | method: "POST", | |
| 115 | redirect: "manual", | |
| 116 | headers: { cookie: as(alice), origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 117 | body: new URLSearchParams({ token: "sk-ant-oat01-not-the-right-one" }), | |
| 118 | }); | |
| 119 | expect(res.status).toBe(303); | |
| 120 | expect(res.headers.get("location")).toBe(`/alice/shop/runs/${id}`); | |
| 121 | const back = await (await fetch(`${servers.url}${res.headers.get("location")}`, { headers: { cookie: `${as(alice)}; ${res.headers.get("set-cookie")?.split(";")[0] ?? ""}` } })).text(); | |
| 122 | expect(back).toContain("did not accept that token"); | |
| 123 | }); | |
| 124 | ||
| 125 | test("a working token is saved sealed as her own, the build is let go at once, and the token never comes back", async () => { | |
| 126 | const id = held(); | |
| 127 | const res = await post(alice, id, ` ${TOKEN}\n`); | |
| 128 | expect(res.status).toBe(200); | |
| 129 | const body = await res.text(); | |
| 130 | expect(body).toContain("Your build is starting on it now"); | |
| 131 | expect(body).not.toContain(TOKEN); | |
| 132 | const own = ownSubscription(app.db, alice.id); | |
| 133 | expect(own).toBeDefined(); | |
| 134 | const row = app.db.query<{ token_enc: string }, [string]>("SELECT token_enc FROM subscription WHERE id = ?1").get(own!.id)!; | |
| 135 | expect(row.token_enc).not.toContain(TOKEN); | |
| 136 | expect(getRun(app.db, id)!.notBefore).toBeNull(); | |
| 137 | expect(getRun(app.db, id)!.summary).toBe("starting on your own Claude account"); | |
| 138 | expect(readRunLog(dir, id).lines.join("\n")).toContain("alice added their own Claude account; the run starts on it now"); | |
| 139 | // Once she has her own, the box is not offered again. | |
| 140 | expect(offersOwnToken(app, alice, getRun(app.db, held())!)).toBe(false); | |
| 141 | }); | |
| 142 | ||
| 143 | test("the test of a token asks Anthropic the way its kind needs, and a refusal or a dead line is false", async () => { | |
| 144 | const asked: { url: string; headers: Record<string, string> }[] = []; | |
| 145 | const canned = (status: number, body: unknown) => async (url: string, init: RequestInit) => { | |
| 146 | asked.push({ url, headers: init.headers as Record<string, string> }); | |
| 147 | return new Response(JSON.stringify(body), { status }); | |
| 148 | }; | |
| 149 | expect(await tokenWorks(TOKEN, canned(200, { five_hour: { utilization: 10 } }))).toBe(true); | |
| 150 | expect(asked[0]!.url).toBe("https://api.anthropic.com/api/oauth/usage"); | |
| 151 | expect(asked[0]!.headers["authorization"]).toBe(`Bearer ${TOKEN}`); | |
| 152 | expect(await tokenWorks("sk-ant-api03-key", canned(200, { data: [] }))).toBe(true); | |
| 153 | expect(asked[1]!.url).toBe("https://api.anthropic.com/v1/models"); | |
| 154 | expect(asked[1]!.headers["x-api-key"]).toBe("sk-ant-api03-key"); | |
| 155 | expect(await tokenWorks("sk-ant-api03-key", canned(401, {}))).toBe(false); | |
| 156 | expect(await tokenWorks("sk-ant-api03-key", async () => { throw new Error("offline"); })).toBe(false); | |
| 157 | }); |
test/talk-live-pane-fenced.test.ts +12
| @@ -205,6 +205,18 @@ test("new_app through /mcp, the owner's turns stored: the pane opens on the queu | ||
| 205 | 205 | // The pane is open on the new app: the page splits and draws the crew's run in its stage. |
| 206 | 206 | expect(queued).toContain(" data-split"); |
| 207 | 207 | expect(queued).toContain('class="talk-crew-now"'); |
| 208 | // Queued, nothing holds it: no box. Held for want of an account, the owner's pane offers the | |
| 209 | // one step to start it on her own (#16490), inside the crew's live region; its field is an | |
| 210 | // `input.input`, which the region's swap never empties while it holds words. | |
| 211 | expect(queued).not.toContain("Start now with your own Claude account"); | |
| 212 | app.db.run("UPDATE run SET not_before = ?2, summary = ?3 WHERE id = ?1", [run.id, new Date(Date.now() + 15 * 60_000).toISOString(), "paused: The crew is catching its breath (too many requests this minute); your build starts again by 21:49 UTC."]); | |
| 213 | const held = await page(chat.value.id); | |
| 214 | const region = held.slice(held.indexOf('<div class="talk-crew-now"'), held.indexOf("</form>", held.indexOf("data-own-token")) + 7); | |
| 215 | expect(region).toContain("Start now with your own Claude account"); | |
| 216 | expect(region).toContain(`action="/trevato/unit-converter/runs/${run.id}/own-token"`); | |
| 217 | expect(region).toMatch(/<input class="input mono"[^>]*name="token"[^>]*type="password"/); | |
| 218 | app.db.run("UPDATE run SET not_before = NULL, summary = '' WHERE id = ?1", [run.id]); | |
| 219 | expect(await page(chat.value.id)).not.toContain("Start now with your own Claude account"); | |
| 208 | 220 | |
| 209 | 221 | claimRun(app.db, run.id); |
| 210 | 222 | expect(line(await page(chat.value.id))).toMatch( |
test/tui-own-token.test.ts added +115
| @@ -0,0 +1,115 @@ | ||
| 1 | /** | |
| 2 | * The terminal's door to "Start now with your own Claude account" (#16490): on a person's own held | |
| 3 | * build the run screen says so, `a` asks for the token masked, and a working one starts the build | |
| 4 | * with a toast; a token Anthropic refuses keeps nothing. Anyone else's screen offers nothing. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App as Forge } from "../src/app.ts"; | |
| 12 | import { ownSubscription } from "../src/core/model_grant.ts"; | |
| 13 | import type { Repo } from "../src/core/repos.ts"; | |
| 14 | import { createRun, getRun } from "../src/core/runs.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 17 | import { runLogScreen } from "../src/tui/screens/runlog.ts"; | |
| 18 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 19 | import { quietLogs } from "./helpers/globals.ts"; | |
| 20 | import { settleApp, settleUntil } from "./helpers/tui.ts"; | |
| 21 | ||
| 22 | quietLogs(); | |
| 23 | ||
| 24 | const TOKEN = "sk-ant-oat01-the-terminal-test-token"; | |
| 25 | const realFetch = globalThis.fetch; | |
| 26 | let dir: string; | |
| 27 | let forge: Forge; | |
| 28 | let repo: Repo; | |
| 29 | let alice: User; | |
| 30 | let bob: User; | |
| 31 | ||
| 32 | beforeAll(async () => { | |
| 33 | dir = await mkdtemp(join(tmpdir(), "forge-tui-own-token-")); | |
| 34 | forge = createApp({ dataDir: dir, port: 0 }); | |
| 35 | const a = await createUser(forge.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-passphrase", adminIfFirst: true }); | |
| 36 | const b = await createUser(forge.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-passphrase" }); | |
| 37 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 38 | alice = a.value; | |
| 39 | bob = b.value; | |
| 40 | const r = await createRepo(forge, alice, { name: "lamp", visibility: "public" }); | |
| 41 | if (!r.ok) throw new Error("repo"); | |
| 42 | repo = r.value; | |
| 43 | // Anthropic, canned: it accepts the one Claude token, through its usage meter. | |
| 44 | globalThis.fetch = Object.assign(async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => { | |
| 45 | const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; | |
| 46 | if (!url.startsWith("https://api.anthropic.com/")) return realFetch(input, init); | |
| 47 | const ok = new Headers(init?.headers).get("authorization") === `Bearer ${TOKEN}`; | |
| 48 | return ok ? Response.json({ five_hour: { utilization: 10 } }) : new Response("{}", { status: 401 }); | |
| 49 | }, { preconnect: realFetch.preconnect }); | |
| 50 | }); | |
| 51 | afterAll(async () => { | |
| 52 | globalThis.fetch = realFetch; | |
| 53 | forge.close?.(); | |
| 54 | await rm(dir, { recursive: true, force: true }); | |
| 55 | }); | |
| 56 | ||
| 57 | const held = () => | |
| 58 | createRun(forge.db, { | |
| 59 | repoId: repo.id, | |
| 60 | kind: "agent", | |
| 61 | actorId: alice.id, | |
| 62 | reason: "assigned", | |
| 63 | sent: true, | |
| 64 | attempt: 1, | |
| 65 | notBefore: new Date(Date.now() + 15 * 60_000).toISOString(), | |
| 66 | summary: "paused: The crew is catching its breath (too many requests this minute); your build starts again by 21:49 UTC.", | |
| 67 | }).id; | |
| 68 | ||
| 69 | const open = async (user: User, runId: string) => { | |
| 70 | const { app, session } = createForgeApp(forge, { sshUsername: user.username, remoteAddress: "127.0.0.1", user }, { terminal: headlessTerminal(110, 22), exitHooks: false }); | |
| 71 | app.start(); | |
| 72 | await settleApp(app); | |
| 73 | app.push(runLogScreen(session, app.ctx, repo, runId)); | |
| 74 | await settleApp(app); | |
| 75 | return app; | |
| 76 | }; | |
| 77 | const press = (app: Awaited<ReturnType<typeof open>>, key: string) => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 78 | ||
| 79 | test("someone else's screen of the held build offers nothing, and `a` does nothing there", async () => { | |
| 80 | const app = await open(bob, held()); | |
| 81 | expect(app.screen.toText()).not.toContain("Start now with your own Claude account"); | |
| 82 | press(app, "a"); | |
| 83 | await settleApp(app); | |
| 84 | expect(app.screen.toText()).not.toContain("claude setup-token"); | |
| 85 | }); | |
| 86 | ||
| 87 | test("the owner's screen says it; `a` asks masked; a refused token keeps nothing, a working one starts the build", async () => { | |
| 88 | const runId = held(); | |
| 89 | const app = await open(alice, runId); | |
| 90 | expect(app.screen.toText()).toContain("Start now with your own Claude account: press a"); | |
| 91 | press(app, "a"); | |
| 92 | await settleApp(app); | |
| 93 | expect(app.screen.toText()).toContain("claude setup-token"); | |
| 94 | ||
| 95 | app.dispatch({ type: "paste", text: "sk-ant-oat01-not-it" }); | |
| 96 | await settleApp(app); | |
| 97 | expect(app.screen.toText()).not.toContain("sk-ant-oat01-not-it"); | |
| 98 | press(app, "enter"); | |
| 99 | await settleUntil(app, "did not accept that token"); | |
| 100 | expect(ownSubscription(forge.db, alice.id)).toBeUndefined(); | |
| 101 | expect(getRun(forge.db, runId)!.notBefore).not.toBeNull(); | |
| 102 | ||
| 103 | press(app, "a"); | |
| 104 | await settleApp(app); | |
| 105 | app.dispatch({ type: "paste", text: TOKEN }); | |
| 106 | await settleApp(app); | |
| 107 | expect(app.screen.toText()).not.toContain(TOKEN); | |
| 108 | press(app, "enter"); | |
| 109 | await settleUntil(app, "the build is starting on it"); | |
| 110 | expect(ownSubscription(forge.db, alice.id)).toBeDefined(); | |
| 111 | expect(getRun(forge.db, runId)!.notBefore).toBeNull(); | |
| 112 | // Once started on her own account, the screen no longer offers it. | |
| 113 | await settleApp(app); | |
| 114 | expect(app.screen.toText()).not.toContain("press a and paste"); | |
| 115 | }); |
new above
offline
The
akey, its prompt and its toasts have no test. Add one that fails without this branch.