Public: anyone can read this; the crew can change it.

Revert "Start now with your own Claude account: one paste on a waiting build (#16490)" #16611

opened this

Check · Review · Land · Live — It conflicts with its base. Next: builder, it conflicts with its base.

Conflicts with main

revert-16571 → main 1 commit

Review

Sign in to review this change.
13 files changed +11 −540
docs/features/start-now-own-account.md deleted −21
@@ -1,21 +0,0 @@
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 deleted −67
@@ -1,67 +0,0 @@
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,19 +117,6 @@ export function releasePaused(db: Database, account: string, now: Date): number
117117 .run(now.toISOString(), account).changes;
118118 }
119119
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
133120 function tokenOf(db: Database, dataDir: string, id: string, env: Record<string, string | undefined>): string | undefined {
134121 if (id === PLATFORM) return platformToken(env);
135122 const row = db.query<{ token_enc: string }, [string]>("SELECT token_enc FROM subscription WHERE id = ?1").get(id);
src/crew/token_check.ts deleted −20
@@ -1,20 +0,0 @@
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,7 +5,6 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { runOwnToken } from "../web/own_token.ts";
98 import { togetherFragment, togetherLine, togethernessOf } from "../web/together.ts";
109 import { outsiderStatusPage } from "./offer_routes.ts";
1110 import { standingFragment } from "../web/pages/fork-standing.ts";
@@ -1697,7 +1696,6 @@ export function buildRouter(): Router<Handler> {
16971696 router.add("GET", "/:owner/:name/runs/:id", runPage);
16981697 router.add("POST", "/:owner/:name/runs/:id/cancel", runCancel);
16991698 router.add("POST", "/:owner/:name/runs/:id/requeue", runRequeue);
1700 router.add("POST", "/:owner/:name/runs/:id/own-token", runOwnToken);
17011699 router.add("POST", "/:owner/:name/runs/:id/steer", runSteer);
17021700 // The public social cards: a repo as owner~name, an app as its slug.
17031701 router.add("GET", "/og/repo/:ref.svg", ogCard("repo"));
src/tui/screens/runlog.ts +3 −33
@@ -20,8 +20,7 @@ import { subscribeRunLog } from "../../runs/log.ts";
2020 import { stoppedWords } from "../../runs/cancelled.ts";
2121 import { withEnded } from "../../runs/ended_words.ts";
2222 import { stillEnding } from "../../runs/ending.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";
23 import { Scroll, live, openOnWeb } from "./common.ts";
2524 import { costText, envLabel, runTone } from "./runwords.ts";
2625 import { priceWords } from "../../core/run_price.ts";
2726 import { getUsage } from "../../core/usage.ts";
@@ -62,9 +61,6 @@ export function runLogScreen(
6261 ctx.invalidate();
6362 };
6463
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
6864 const web = (): void =>
6965 openOnWeb(f, ctx, `/${repo.ownerName}/${repo.name}/runs/${runId}`, "the run's log");
7066
@@ -78,7 +74,6 @@ export function runLogScreen(
7874 binding(["g", "G"], "top, end"),
7975 binding(["o"], "open on the web"),
8076 binding(["r"], "refresh"),
81 ...(offer() ? [binding(["a"], "start now on your own account")] : []),
8277 ];
8378 },
8479 load(signal) {
@@ -130,10 +125,8 @@ export function runLogScreen(
130125 ...(run.placement === "job" && run.sandboxEnforced === true ? jobSandboxWords(run.sandboxNote).split(/(?<=\.) /) : []),
131126 ...(began === "" ? [] : [`${began[0]!.toUpperCase()}${began.slice(1)}.`]),
132127 ];
133 const offering = offer();
134128 const rows = split(area, "v", [
135129 len(1),
136 ...(offering ? [len(1)] : []),
137130 ...(price === "" ? [] : [len(1)]),
138131 ...wall.map(() => len(1)),
139132 fill(1),
@@ -159,13 +152,9 @@ export function runLogScreen(
159152 style(tone === undefined ? c.mutedFg : c.fg, c.bg),
160153 head!.x + head!.w,
161154 );
162 if (offering) {
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);
155 const lead = price === "" ? 1 : 2;
167156 if (price !== "") {
168 const row = rows[offering ? 2 : 1]!;
157 const row = rows[1]!;
169158 s.text(row.x, row.y, truncate(price, row.w), style(c.mutedFg, c.bg), row.x + row.w);
170159 }
171160 wall.forEach((words, i) => {
@@ -198,25 +187,6 @@ export function runLogScreen(
198187 }
199188 },
200189 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 }
220190 if (e.key === "o" && !e.ctrl && !e.alt) {
221191 web();
222192 return true;
src/web/own_token.ts deleted −82
@@ -1,82 +0,0 @@
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 +1 −2
@@ -14,7 +14,6 @@
1414 * their id, the agent acts with their permissions (`crew/conversation.ts`).
1515 */
1616
17 import { ownTokenJs } from "../own_token.ts";
1817 import { blockedFlash } from "../blocked.ts";
1918 import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
2019 import type { Database } from "bun:sqlite";
@@ -688,7 +687,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
688687 </div>
689688 ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null}
690689 </div>`;
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 }) });
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 }) });
692691 }
693692
694693 /**
src/web/pages/talk_preview.ts +6 −12
@@ -11,9 +11,6 @@
1111 * streaming beside it carries on.
1212 */
1313
14 import { offersOwnToken } from "../../actions/own_token.ts";
15 import { getRun } from "../../core/runs.ts";
16 import { ownTokenBox } from "../own_token.ts";
1714 import { paneQuery, pointedAt, workspaceOf, type Apps, type PaneAt, type PaneSteer, type paneOffer } from "../../actions/talk_workspace.ts";
1815 import { previewEnv } from "../../apps/data.ts";
1916 import type { User } from "../../core/users.ts";
@@ -92,17 +89,14 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
9289 // While nothing is framed, what the crew is doing on the repository, read from its newest run.
9390 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;
9491 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;
9892 const panel =
9993 view === "code"
10094 ? await codeView(ctx.app, work)
10195 : view === "diff"
10296 ? await diffView(ctx.app, work, ask.version, ask.mine === undefined ? undefined : { ...ask.mine, picked: at.pull })
10397 : url === undefined || ask.wait !== undefined
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)}`;
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)}`;
106100 // The address bar of what runs: which environment, where it lives, reload and open on its own.
107101 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>`;
108102 // Waiting, the pane is a live region on the repository's runs: a deploy that turns running swaps
@@ -155,10 +149,10 @@ function productionOrigin(ctx: Ctx, repoId: string): string | undefined {
155149 * whenever the pane is open, so the crew's next run (the person's next change) is picked up on
156150 * run.* and drawn under the same frame, which the swap never touches.
157151 */
158 function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: string; readonly name: string }, src: string, back: () => string, shows?: number, offer: Html | null = null): Html {
152 function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: string; readonly name: string }, src: string, back: () => string, shows?: number): Html {
159153 return crew === undefined
160154 ? 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>`
161 : crewBlock(crew, `/${repo.ownerName}/${repo.name}`, repo, src, back, shows, offer);
155 : crewBlock(crew, `/${repo.ownerName}/${repo.name}`, repo, src, back, shows);
162156 }
163157
164158 /**
@@ -169,7 +163,7 @@ function crewRegion(crew: PaneCrew | undefined, repo: { readonly ownerName: stri
169163 * works it folds to its one line (a `<details>`, the fold kept per conversation by the script); a
170164 * hold or a failure is drawn open and unfoldable, so neither is ever hidden.
171165 */
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 {
166 function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: string; readonly name: string }, src: string, back: () => string, shows?: number): Html {
173167 const working = crew.state === "running" ? " talk-crew-working" : "";
174168 const line = html`<p class="small${working}">${workLineHtml(crew.line)}</p>`;
175169 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>`;
@@ -182,7 +176,7 @@ function crewBlock(crew: PaneCrew, base: string, repo: { readonly ownerName: str
182176 // Its own live region: the crew's next run is read as it is queued, starts or ends, and the frame
183177 // above it is never redrawn for it.
184178 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}">
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}
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>`}
186180 </div>`;
187181 }
188182
src/web/studio/run.ts +1 −4
@@ -8,8 +8,6 @@
88 * at `?all=1`.
99 */
1010
11 import { offersOwnToken } from "../../actions/own_token.ts";
12 import { ownTokenBox, ownTokenJs } from "../own_token.ts";
1311 import { time } from "../time_element.ts";
1412 import { wayIn } from "../../actions/blocked_words.ts";
1513 import { blockedWay } from "../blocked.ts";
@@ -231,7 +229,6 @@ export async function runView(
231229 >`}
232230 </div>
233231 <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))}
235232 ${when(wayIn(ctx.app, ctx.auth.user, run.summary, repo), (way) => html`<div class="small" id="run-way">${blockedWay(way)}</div>`)}
236233 ${when(
237234 carried.length > 0,
@@ -482,6 +479,6 @@ export async function runView(
482479 palette: repoPalette(ctx, repo),
483480 body,
484481 styleCss: RUN_PAGE_CSS,
485 scriptJs: `${liveRegionsJs}\n${studioRunJs}\n${openFoldJs}\n${ownTokenJs}`,
482 scriptJs: `${liveRegionsJs}\n${studioRunJs}\n${openFoldJs}`,
486483 });
487484 }
test/own-token.test.ts deleted −157
@@ -1,157 +0,0 @@
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,18 +205,6 @@ test("new_app through /mcp, the owner's turns stored: the pane opens on the queu
205205 // The pane is open on the new app: the page splits and draws the crew's run in its stage.
206206 expect(queued).toContain(" data-split");
207207 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");
220208
221209 claimRun(app.db, run.id);
222210 expect(line(await page(chat.value.id))).toMatch(
test/tui-own-token.test.ts deleted −115
@@ -1,115 +0,0 @@
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 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs