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

A repository can have its own account order, tried there without reordering the forge #17843

opened this

Merged 30h 20m ago, live in production

scout/forge:scout/17829-a-repository-can-have-its-own-account-or → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/17829-a-repository-can-have-its-own-account-or was merged into main as 14bd626.

Review

Sign in to review this change.
15 files changed +473 −10
docs/design/attention-budget.json +6 −5
@@ -244,15 +244,16 @@
244244 },
245245 "crew": {
246246 "390": {
247 "words": 742,
248 "blocks": 89,
247 "words": 763,
248 "blocks": 93,
249249 "colours": 4
250250 },
251251 "1280": {
252 "words": 742,
253 "blocks": 89,
252 "words": 763,
253 "blocks": 93,
254254 "colours": 4
255 }
255 },
256 "note": "Raised by 21 words and 4 blocks for the Account order card on a repository's settings: the one place its crew's account order is set (#17829)."
256257 },
257258 "milestone": {
258259 "390": {
docs/features/repo-account-order.md added +14
@@ -0,0 +1,14 @@
1 ---
2 topic: Tell the crew
3 row: Give one repository its own account order
4 ---
5 # Give one repository its own account order
6
7 To try one account (SubQ, say) on a single repository without reordering the forge, name it in that repository's own order.
8
9 - **Web:** Settings → General → Account order. One account name per line, first tried first; save. Empty, the default, is the forge's order. Anyone who can write to the repository sets it; an unknown name refuses the whole order.
10 - **Terminal:** open the repository, then the palette's "Account order" (`src/tui/screens/accountorder.ts`). `e` types the names, comma separated; `c` clears the order.
11 - **What it does:** a run for this repository tries those accounts before the rest, then falls through to the forge's order. An account named there that is resting, spent, full or not allowed here is passed over as it always is, so a stale name never holds a run.
outdated

Both doors: the terminal must set this too (a screen in src/tui/, entered where AGENTS.md says). Add it and replace this line with the terminal how-to.

12 - **Whose names:** a writer sees every name in the order, whoever owns the account, so a save never drops one unseen. A name already in the order may stay; a new one must be an account you may read.
13 - **Other repositories** keep the forge's order (an admin's, set under Settings → Subscriptions).
14 - **Not here yet:** the MCP tools do not set it.
src/actions/repo_account_order.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * A repository's own account order (#17829), set and cleared by someone who can write there. Names
3 * are checked against the accounts they may read (`mayRead` as in `crew_accounts.ts`) or that the
4 * order already holds; an unknown name refuses the whole order. Each change is a
5 * `repo.settings_updated` event naming `accountOrder`.
6 */
7
8 import type { App } from "../app.ts";
9 import { canWrite, type Repo } from "../core/repos.ts";
10 import { ORDER_MAX, repoAccountOrder, setRepoAccountOrder } from "../core/repo_account_order.ts";
11 import { getSubscription, getSubscriptionByName } from "../core/subscriptions.ts";
12 import type { User } from "../core/users.ts";
13 import { err, ok, type Result } from "../kernel/result.ts";
14
15 export type OrderError = "not_found" | "unknown_account" | "too_long";
16
17 export const ORDER_WORDS: Record<OrderError, string> = {
18 not_found: "no such repository",
19 unknown_account: "no account by that name that you may order",
20 too_long: `an order names at most ${ORDER_MAX} accounts`,
21 };
22
23 /**
outdated

This hides names the viewer may not read, but setRepoOrder then overwrites the whole stored order from the textarea. Saving drops the hidden accounts without a word. Either show all names to anyone who can write here, or merge: keep the stored ids the viewer cannot see when saving.

24 * The names of the accounts this repository tries first, in order. Every name, whoever owns the
25 * account: the order is the repository's and a save replaces all of it, so a writer must see all
26 * of it or a save would drop names unseen. Only writers are shown it (the settings card).
27 */
28 export function repoOrderNames(app: App, repo: Repo): string[] {
29 return repoAccountOrder(app.db, repo.id).flatMap((id) => {
30 const a = getSubscription(app.db, id);
31 return a === undefined ? [] : [a.name];
32 });
33 }
34
35 /** Set the order to `names`, or clear it when empty. */
36 export function setRepoOrder(app: App, actor: User | undefined, repo: Repo, names: readonly string[]): Result<{ names: string[] }, OrderError> {
37 if (actor === undefined || actor.kind === "agent" || !canWrite(app.db, repo, actor)) return err("not_found");
38 if (names.length > ORDER_MAX) return err("too_long");
39 const ids: string[] = [];
40 const before = repoAccountOrder(app.db, repo.id);
41 for (const name of names) {
42 const a = getSubscriptionByName(app.db, name);
43 // A name already in the order stays editable by any writer; a new one must be readable by them.
44 const mine = a !== undefined && (actor.isAdmin || a.createdBy === actor.id || before.includes(a.id));
45 if (a === undefined || a.id === "platform" || !mine) return err("unknown_account");
46 if (!ids.includes(a.id)) ids.push(a.id);
47 }
48 setRepoAccountOrder(app.db, repo.id, ids, actor.id, new Date());
49 if (JSON.stringify(before) !== JSON.stringify(ids))
50 app.bus.append({ kind: "repo.settings_updated", repoId: repo.id, actorId: actor.id, payload: { changed: { accountOrder: { from: before.length, to: ids.length } } } });
51 return ok({ names: ids.map((id) => getSubscription(app.db, id)!.name) });
52 }
53
54 /** Names as typed: one per line or comma separated, blanks dropped. */
55 export const parseOrder = (text: string): string[] => text.split(/[\n,]/).map((s) => s.trim()).filter((s) => s !== "");
src/core/account_purge.ts +1
@@ -55,6 +55,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5555 // The !forge audit keeps what was said and what came of it; who said it becomes a former member.
5656 "game_chat.user_id": FORMER,
5757 "account_ceiling.set_by": FORMER,
58 "repo_account_order.set_by": FORMER,
5859 "allocation_entry.actor_id": FORMER,
5960 "allocation_weekly.set_by": FORMER,
6061 "cloud_watch_ack.by": FORMER,
src/core/migration-pins/20261203040000-repo-account-order.pin added +1
@@ -0,0 +1,1 @@
1 65adef6ef153c92290acdefd74a8ad21288d1c396165c0045cb434cbb42b457d
src/core/migrations/20261203040000-repo-account-order.ts added +10
@@ -0,0 +1,10 @@
1 // A repository can have its own account order (#17829): the account ids its crew runs try first,
2 // in this order, before the forge's. No row is the forge's order, the default. Additive.
3 export default `
4 CREATE TABLE IF NOT EXISTS repo_account_order (
5 repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE,
6 accounts TEXT NOT NULL,
7 set_by TEXT NOT NULL,
8 set_at TEXT NOT NULL
9 );
10 `;
src/core/repo_account_order.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * A repository's own account order (#17829): the accounts its crew runs try first, in this order,
3 * to try one (SubQ, say) on one repository without reordering the forge. Empty, the default, is
4 * the forge's order. It only reorders accounts a run may already use: a name that is disabled,
5 * resting, spent or not allowed here is passed over by the pick as ever, and the run falls
6 * through to the forge's order. Plain data in and out.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 /** The most accounts one order names. */
12 export const ORDER_MAX = 16;
13
14 /** The account ids a repository tries first, in order; empty when it has no order of its own. */
15 export function repoAccountOrder(db: Database, repoId: string): string[] {
16 if (repoId === "") return [];
17 const row = db.query<{ accounts: string }, [string]>("SELECT accounts FROM repo_account_order WHERE repo_id = ?1").get(repoId);
18 if (row === null) return [];
19 try {
20 const parsed: unknown = JSON.parse(row.accounts);
21 return Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === "string") : [];
22 } catch {
23 return [];
24 }
25 }
26
27 /** Store the order; an empty one clears it. */
28 export function setRepoAccountOrder(db: Database, repoId: string, ids: readonly string[], actorId: string, now: Date): void {
29 if (ids.length === 0) {
30 db.query("DELETE FROM repo_account_order WHERE repo_id = ?1").run(repoId);
31 return;
32 }
33 db.query(
34 `INSERT INTO repo_account_order (repo_id, accounts, set_by, set_at) VALUES (?1, ?2, ?3, ?4)
35 ON CONFLICT(repo_id) DO UPDATE SET accounts = ?2, set_by = ?3, set_at = ?4`,
36 ).run(repoId, JSON.stringify(ids), actorId, now.toISOString());
37 }
38
39 /** `rows` with those `order` names first, in its order; the rest keep their place after them. */
40 export function withRepoOrder<T extends { readonly id: string }>(rows: readonly T[], order: readonly string[]): T[] {
41 if (order.length === 0) return [...rows];
42 const at = (r: T): number => {
43 const i = order.indexOf(r.id);
44 return i === -1 ? order.length : i;
45 };
46 return rows.map((r, i) => ({ r, i })).sort((a, b) => at(a.r) - at(b.r) || a.i - b.i).map((x) => x.r);
47 }
src/core/subscriptions.ts +6 −2
@@ -34,6 +34,7 @@ import { accountEnv, envNameOf, runnerCredentialInEnv } from "../crew/runner_env
3434 import { limitValue } from "../settings/limits.ts";
3535 import { measureFor } from "./measure.ts";
3636 import { getHeadroom, type LimitWindow } from "./standing.ts";
37 import { repoAccountOrder, withRepoOrder } from "./repo_account_order.ts";
3738
3839 export type SubscriptionKind = "oauth" | "api_key";
3940
@@ -911,7 +912,7 @@ const awakeAt = (r: CandidateRow, now: Date): boolean => !budgetSpent(r) && (r.r
911912 /** The accounts a crew run at a scope would take now, the next one first; `PLATFORM` is the forge's own token. */
912913 export function crewNext(db: Database, scope: { readonly repoId: string; readonly ownerId: string }, now: Date, crew: CrewPick): string[] {
913914 const all = withOwnToken(db, scope, candidates(db, { repoId: scope.repoId, ownerId: scope.ownerId, agentId: "" }, "", true), crew);
914 return crewOrder(db, all, now, crew).rows.filter((r) => awakeAt(r, now)).map((r) => r.id);
915 return withRepoOrder(crewOrder(db, all, now, crew).rows, repoAccountOrder(db, scope.repoId)).filter((r) => awakeAt(r, now)).map((r) => r.id);
915916 }
916917
917918 /**
@@ -939,7 +940,10 @@ export function pickSubscription(
939940 if (crew?.pastWeek === true) return { kind: "resting", until: new Date(now.getTime() + BUDGET_RECHECK_MS).toISOString(), said: "the week holds the crew and no other account may be used here", names: ["the crew's accounts"] };
940941 return ownerIsAdmin(db, scope.ownerId) ? { kind: "env" } : { kind: "none" };
941942 }
942 const { rows, full } = crewOrder(db, all, now, crew);
943 const ordered = crewOrder(db, all, now, crew);
944 // This repository's own order, where it has one, goes before the forge's.
945 const rows = withRepoOrder(ordered.rows, repoAccountOrder(db, scope.repoId));
946 const full = ordered.full;
943947 if (rows.length === 0) {
944948 // Every plan is full and no fallback may take the run: it waits for the first window to reset.
945949 const soonest = [...full].sort((a, b) => a[1].resetsAt.localeCompare(b[1].resetsAt))[0];
src/http/lazy_lists.ts +1
@@ -987,6 +987,7 @@ export const REPO_SETTINGS_ROUTES = [
987987 ["GET", "/:owner/:name/settings"],
988988 ["POST", "/:owner/:name/settings"],
989989 ["POST", "/:owner/:name/settings/wave"],
990 ["POST", "/:owner/:name/settings/account-order"],
990991 ["POST", "/:owner/:name/settings/archive"],
991992 ["POST", "/:owner/:name/archive"],
992993 ["POST", "/:owner/:name/restore"],
src/http/routes/repo_settings.ts +2 −1
@@ -15,7 +15,7 @@ import { promptsSettingsPage, promptSourceAdd, promptSourceRun, promptSourceDele
1515 import { proposalTokenMint, proposalTokenRevoke, contributeOpenSet, reportsOpenSet, contributeTokenRevoke } from "../../web/pages/proposal-tokens.ts";
1616 import { readGrantAdd, readGrantRevoke } from "../../web/pages/read-grants.ts";
1717 import { repoSyncSubmit, repoTakeSubmit, pinSubmit } from "../../web/pages/repo.ts";
18 import { settingsPage, settingsUpdate, waveCut, archiveSubmit, archiveConfirmed, restoreConfirmed, renameSubmit, transferSubmit, provenanceSubmit, mirrorStop, appSettingsPage, appSettingsUpdate, appDisable, appMembersUpdate, appEnvSet, appEnvDelete, appDomainAdd, appDomainCheck, appDomainDelete, appEgressGrant, appEgressRevoke, appBlocked, autonomySettingsPage, autonomySettingsUpdate, crewCeilingRaise, checkSlotsUpdate } from "../../web/pages/settings.ts";
18 import { settingsPage, settingsUpdate, waveCut, archiveSubmit, archiveConfirmed, restoreConfirmed, renameSubmit, transferSubmit, provenanceSubmit, mirrorStop, appSettingsPage, appSettingsUpdate, appDisable, appMembersUpdate, appEnvSet, appEnvDelete, appDomainAdd, appDomainCheck, appDomainDelete, appEgressGrant, appEgressRevoke, appBlocked, autonomySettingsPage, autonomySettingsUpdate, crewCeilingRaise, checkSlotsUpdate, accountOrderSave } from "../../web/pages/settings.ts";
1919 import { appSourcesPage } from "../../web/pages/sources.ts";
2020 import { statementPage, statementCsvDownload } from "../../web/pages/statement.ts";
2121 import { walletPage, walletCsvDownload, walletSave } from "../../web/pages/wallet.ts";
@@ -51,6 +51,7 @@ export function repoSettingsRoutes(router: Router<Handler>): void {
5151 router.add("GET", "/:owner/:name/settings", settingsPage);
5252 router.add("POST", "/:owner/:name/settings", settingsUpdate);
5353 router.add("POST", "/:owner/:name/settings/wave", waveCut);
54 router.add("POST", "/:owner/:name/settings/account-order", accountOrderSave);
5455 router.add("POST", "/:owner/:name/settings/archive", archiveSubmit);
5556 router.add("POST", "/:owner/:name/archive", archiveConfirmed);
5657 router.add("POST", "/:owner/:name/restore", restoreConfirmed);
src/tui/screens/accountorder.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * A repository's own account order, in the terminal (#17829): the settings card's field
3 * (`web/pages/settings.ts`) from the same action (`actions/repo_account_order.ts`), gated the same
4 * way: anyone who can write here. `e` sets the order (names, comma separated), `c` clears it.
5 * Each change is an event on the bus, so an open settings page redraws, and this screen follows
6 * a write made there.
7 */
8
9 import { ORDER_WORDS, parseOrder, repoOrderNames, setRepoOrder } from "../../actions/repo_account_order.ts";
10 import { canWrite, type Repo } from "../../core/repos.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import type { Command } from "../app/palette.ts";
14 import type { Session } from "../session.ts";
15 import { style } from "../term/style.ts";
16 import { truncate } from "../term/width.ts";
17 import { fill, len, split } from "../ui/layout.ts";
18 import { ListState, drawList, later, live, promptScreen, type ListRow } from "./common.ts";
19
20 /** Who sets the order: a person who can write to the repository. */
21 export const mayOrder = (f: Session, repo: Repo): boolean => f.user !== undefined && f.user.kind !== "agent" && canWrite(f.db, repo, f.user);
22
23 /** Say what a save did, as a toast would. */
24 export function saveOrder(f: Session, repo: Repo, names: readonly string[]): { text: string; bad: boolean } {
25 const set = setRepoOrder(f.app, f.user, repo, names);
26 if (!set.ok) return { text: ORDER_WORDS[set.error], bad: true };
27 return { text: set.value.names.length === 0 ? "Account order cleared: the forge's order." : `Account order: ${set.value.names.join(", ")}.`, bad: false };
28 }
29
30 export function accountOrderScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
31 const state = new ListState();
32 const screen: Screen = {
33 title: `${repo.ownerName}/${repo.name} — Account order`,
34 keys: [binding(["e"], "set the order"), binding(["c"], "clear it")],
35 async load(signal) {
36 live(f, signal, { repoId: repo.id, where: (e) => e.kind === "repo.settings_updated" }, () => ctx.invalidate());
37 },
38 render(area, s) {
39 const c = ctx.theme.c;
40 const names = repoOrderNames(f.app, repo);
41 const [head, list] = split(area, "v", [len(1), fill(1)]);
42 const said = !mayOrder(f, repo)
43 ? "A writer of this repository sets its account order."
44 : names.length === 0
45 ? "The forge's order. e names accounts to try first here."
46 : "Tried first, in this order. e sets it, c clears it.";
47 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
48 const rows: ListRow[] = names.map((title, i) => ({ title, meta: String(i + 1) }));
49 drawList(s, list!, c, state, rows);
50 },
51 key(e) {
52 if (state.key(e, repoOrderNames(f.app, repo).length)) return true;
53 if (e.ctrl || e.alt || (e.key !== "e" && e.key !== "c")) return false;
54 if (!mayOrder(f, repo)) {
55 ctx.toast("A writer of this repository sets its account order.", "danger");
56 return true;
57 }
58 const done = (names: readonly string[]): void => {
59 const r = saveOrder(f, repo, names);
60 ctx.toast(r.text, r.bad ? "danger" : undefined);
61 ctx.invalidate();
62 };
63 if (e.key === "c") {
64 done([]);
65 return true;
66 }
67 void later(ctx, () =>
68 promptScreen(ctx, screen, {
69 title: "Account order",
70 label: "Account names, comma separated; empty is the forge's",
71 value: repoOrderNames(f.app, repo).join(", "),
72 onSubmit: (value) => {
73 const r = saveOrder(f, repo, parseOrder(value));
74 if (r.bad) return r.text;
75 ctx.toast(r.text);
76 ctx.invalidate();
77 return undefined;
78 },
79 }),
80 );
81 return true;
82 },
83 };
84 return screen;
85 }
86
87 /** The palette's command while a repository the viewer can write to is open. */
88 export function accountOrderCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
89 if (repo === undefined || !mayOrder(f, repo)) return [];
90 return [
91 {
92 id: "account-order",
93 title: `${repo.ownerName}/${repo.name} — Account order`,
94 hint: "name the accounts this repository's crew tries first",
95 run: () => ctx.push(accountOrderScreen(f, ctx, repo)),
96 },
97 ];
98 }
src/tui/screens/workspace.ts +2
@@ -163,6 +163,7 @@ import { autonomyCommands } from "./autonomy.ts";
163163 import { trafficCommands } from "./trafficview.ts";
164164 import { chaptersCommands } from "./chapters.ts";
165165 import { cutOverCommands } from "./cutover.ts";
166 import { accountOrderCommands } from "./accountorder.ts";
166167 import { outsideAgentsCommands } from "./outsideagents.ts";
167168 import { readGrantsCommands } from "./readgrants.ts";
168169 import { crewDevicesCommands } from "./crewdevices.ts";
@@ -1420,6 +1421,7 @@ export function workspaceScreen(
14201421 ...recheckWindowCommands(f, ctx, repo, () => screen),
14211422 ...deskCommands(f, ctx, repo),
14221423 ...outsideAgentsCommands(f, ctx, repo),
1424 ...accountOrderCommands(f, ctx, repo),
14231425 ...readGrantsCommands(f, ctx, repo),
14241426 ...crewDevicesCommands(f, ctx, repo),
14251427 ...quarantineCommands(f, ctx, repo),
src/web/pages/settings.ts +30 −2
@@ -109,7 +109,7 @@ import { servedFlags } from "../../actions/app_flags.ts";
109109 import type { AppFlagRow } from "../../core/app_flags.ts";
110110 import { appSecretNeeds } from "../../actions/secrets.ts";
111111 import type { NeedRow } from "../../core/app_secrets.ts";
112 import { field } from "../form.ts";
112 import { field, readForm } from "../form.ts";
113113 import { html, raw, when, type Html } from "../html.ts";
114114 import { settingLine, toggleLine } from "../setting_line.ts";
115115 import { lastChanges } from "../../settings/last_change.ts";
@@ -132,6 +132,7 @@ import {
132132 } from "../ui.ts";
133133 import { emptyLine } from "../empty_words.ts";
134134 import { cutWaveFor } from "../../actions/cut_wave.ts";
135 import { ORDER_WORDS, parseOrder, repoOrderNames, setRepoOrder } from "../../actions/repo_account_order.ts";
135136 import { liveClientJs } from "../live.ts";
136137 import { outsideAgentsJs } from "./outside-agents-live.ts";
137138 import { crewDevicesJs } from "./crew_devices.ts";
@@ -368,6 +369,7 @@ export async function settingsPage(
368369 <div class="form-actions">${btn("Cut a wave", { variant: "primary" })}</div>
369370 </form>
370371 </section>`;
372 const accountOrder = accountOrderCard(ctx, repo);
371373 const proposals = proposalTokensSection(ctx, repo);
372374 const trail = provenanceCard(ctx, repo);
373375 const archive = html`<section class="settings-block">
@@ -446,7 +448,7 @@ export async function settingsPage(
446448 "Settings",
447449 html`${help}${lead}${mirror ? html`<div class="mt">${mirror}</div>` : null}${grantsBlock ? html`<div class="mt">${grantsBlock}</div>` : null}<div class="mt">${body}</div>${slotsBlock === null ? null : html`<div class="mt">${slotsBlock}</div>`}${trail
448450 ? html`<div class="mt">${trail}</div>`
449 : null}${upstream ? html`<div class="mt">${upstream}</div>` : null}${sources ? html`<div class="mt">${sources}</div>` : null}<div class="mt">${wave}</div><div class="mt">${archive}</div><div class="mt">${move}</div>${proposals
451 : null}${upstream ? html`<div class="mt">${upstream}</div>` : null}${sources ? html`<div class="mt">${sources}</div>` : null}<div class="mt">${accountOrder}</div><div class="mt">${wave}</div><div class="mt">${archive}</div><div class="mt">${move}</div>${proposals
450452 ? html`<div class="mt">${proposals}</div>`
451453 : null}${secrets
452454 ? html`<div class="mt">${secrets}</div>`
@@ -710,6 +712,32 @@ export async function mirrorStop(ctx: Ctx): Promise<Response> {
710712 );
711713 }
712714
715 /** The repository's own account order: a try of one account here without reordering the forge. */
716 function accountOrderCard(ctx: Ctx, repo: Repo): Html {
717 const names = repoOrderNames(ctx.app, repo);
718 return html`<section class="settings-block" id="account-order">
719 <h2>Account order</h2>
720 <form method="post" action="${repoBase(repo)}/settings/account-order">
721 <label for="account-order-names">Tried first, one account per line; empty is the forge's order</label>
722 <textarea class="input mono" id="account-order-names" name="accounts" rows="3" maxlength="1000">${names.join("\n")}</textarea>
outdated

Principle 1: the label and the hint below both explain the field. Keep one sentence (the label), and move 'resting, spent or not allowed is passed over' to the how-to.

723 <div class="form-actions">${btn("Save order", { variant: "primary" })}</div>
724 </form>
outdated

Principle 1: delete this hint; it explains the box a second time.

725 </section>`;
726 }
727
728 /** POST /:owner/:name/settings/account-order — set or clear this repository's account order. */
729 export async function accountOrderSave(ctx: Ctx): Promise<Response> {
730 const repo = loadRepo(ctx);
731 if (!repo) return repoNotFound(ctx);
732 const form = await readForm(ctx, "rw");
733 if (form instanceof Response) return form;
734 const set = setRepoOrder(ctx.app, ctx.auth.user, repo, parseOrder(field(form, "accounts")));
735 if (!set.ok && set.error === "not_found") return repoNotFound(ctx);
736 return flashTo(ctx, `${repoBase(repo)}/settings#account-order`, set.ok
737 ? { message: set.value.names.length === 0 ? "Account order cleared: the forge's order." : `Account order: ${set.value.names.join(", ")}.` }
738 : { tone: "danger", message: ORDER_WORDS[set.error] });
739 }
740
713741 /** POST /:owner/:name/settings/wave — open the draft of the next wave. */
714742 export async function waveCut(ctx: Ctx): Promise<Response> {
715743 const gate = await adminForm(ctx);
test/repo-account-order.test.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * A repository's own account order (#17829): repo A tries the account its order names while repo B
3 * keeps the forge's order; an account the order names that is resting falls through to the forge's;
4 * setting it needs write access and a known account; empty clears it.
5 */
6 import { afterAll, beforeAll, describe, 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 { parseOrder, repoOrderNames, setRepoOrder } from "../src/actions/repo_account_order.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { addSubscription, crewNext, pickSubscription, rankAfter, restSubscription } from "../src/core/subscriptions.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { promote } from "./helpers/members.ts";
20
21 quietLogs();
22 let servers: Servers;
23 let dir: string, app: App, admin: User, bob: User, a: Repo, b: Repo;
24 const NOW = new Date("2026-12-03T10:00:00.000Z");
25 const ids: Record<string, string> = {};
26
27 const person = async (username: string, isAdmin: boolean): Promise<User> => {
28 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.test`, password: "a-good-passphrase", isAdmin });
29 if (!made.ok) throw new Error(made.error);
30 promote(app.db, made.value);
31 return made.value;
32 };
33 const pick = (repo: Repo) => {
34 const p = pickSubscription(app.db, dir, { repoId: repo.id, ownerId: repo.ownerId, agentId: "" }, NOW);
35 return p.kind === "ready" ? p.subscription.name : p.kind;
36 };
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-account-order-"));
40 app = createApp({ dataDir: dir, port: 0 });
41 servers = await serve(app);
42 admin = await person("trevato", true);
43 bob = await person("bob", false);
44 for (const name of ["first-plan", "subq-plan"]) {
45 const made = addSubscription(app.db, dir, { name, token: `sk-ant-oat01-${name}-token-for-the-test`, createdBy: admin.id });
46 if (!made.ok) throw new Error(made.error);
47 ids[name] = made.value.id;
48 }
49 rankAfter(app.db, ids["subq-plan"]!, ids["first-plan"]!);
50 const ra = await createRepo(app, admin, { name: "alpha", visibility: "public" });
51 const rb = await createRepo(app, admin, { name: "beta", visibility: "public" });
52 if (!ra.ok || !rb.ok) throw new Error("repos");
53 [a, b] = [ra.value, rb.value];
54 });
55 afterAll(async () => {
56 servers.stop();
57 app.close();
58 await rm(dir, { recursive: true, force: true });
59 });
60
61 describe("repository account order", () => {
62 test("by default every repository takes the forge's order", () => {
63 expect([pick(a), pick(b)]).toEqual(["first-plan", "first-plan"]);
64 });
65
66 test("repo A uses its order while repo B keeps the forge's", () => {
67 expect(setRepoOrder(app, admin, a, ["subq-plan"]).ok).toBe(true);
68 expect(pick(a)).toBe("subq-plan");
69 expect(pick(b)).toBe("first-plan");
70 expect(crewNext(app.db, { repoId: a.id, ownerId: a.ownerId }, NOW, { fallback: false })[0]).toBe(ids["subq-plan"]!);
71 expect(repoOrderNames(app, a)).toEqual(["subq-plan"]);
72 });
73
74 test("a named account that is resting falls through to the forge's order", () => {
75 restSubscription(app.db, ids["subq-plan"]!, "2026-12-04T00:00:00.000Z", "weekly limit");
76 expect(pick(a)).toBe("first-plan");
77 });
78
79 test("empty clears it", () => {
80 expect(setRepoOrder(app, admin, a, []).ok).toBe(true);
81 expect(repoOrderNames(app, a)).toEqual([]);
82 });
83
84 test("an unknown account refuses the whole order; someone who cannot write is told nothing", () => {
85 expect(setRepoOrder(app, admin, a, ["first-plan", "nope"])).toEqual({ ok: false, error: "unknown_account" });
86 expect(setRepoOrder(app, admin, a, ["platform"])).toEqual({ ok: false, error: "unknown_account" });
87 expect(setRepoOrder(app, bob, a, ["first-plan"])).toEqual({ ok: false, error: "not_found" });
88 expect(setRepoOrder(app, undefined, a, [])).toEqual({ ok: false, error: "not_found" });
89 expect(repoOrderNames(app, a)).toEqual([]);
90 });
91
92 test("names are read one per line or comma separated", () => {
93 expect(parseOrder("a, b\n\n c ")).toEqual(["a", "b", "c"]);
94 });
95
96 test("the route: a cross-origin post is refused and writes nothing; same-origin saves; empty clears", async () => {
97 const cookie = `forge_session=${createSession(app.db, admin.id).token}`;
98 const post = (accounts: string, origin: string) =>
99 fetch(`${servers.url}/trevato/alpha/settings/account-order`, {
100 method: "POST",
101 headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" },
102 body: new URLSearchParams({ accounts }),
103 redirect: "manual",
104 });
105 expect((await post("subq-plan", "http://evil.example")).status).toBe(403);
106 expect(repoOrderNames(app, a)).toEqual([]);
107 expect((await post("subq-plan", servers.url)).status).toBeLessThan(400);
108 expect(repoOrderNames(app, a)).toEqual(["subq-plan"]);
109 expect((await post("", servers.url)).status).toBeLessThan(400);
110 expect(repoOrderNames(app, a)).toEqual([]);
111 });
112
113 test("a writer who does not own an account sees it and a save keeps it", async () => {
114 expect(setRepoOrder(app, admin, a, ["first-plan", "subq-plan"]).ok).toBe(true);
115 const writer = await person("wendy", false);
116 app.db.query("UPDATE repo SET owner_id = ?1 WHERE id = ?2").run(writer.id, a.id);
117 const mine: Repo = { ...a, ownerId: writer.id };
118 expect(repoOrderNames(app, mine)).toEqual(["first-plan", "subq-plan"]);
119 // She may keep what is there, reorder it, but not name an account she cannot read.
120 expect(setRepoOrder(app, writer, mine, ["subq-plan", "first-plan"]).ok).toBe(true);
121 expect(repoOrderNames(app, mine)).toEqual(["subq-plan", "first-plan"]);
122 const third = addSubscription(app.db, dir, { name: "third-plan", token: "sk-ant-oat01-third-plan-token-for-the-test", createdBy: admin.id });
123 expect(third.ok).toBe(true);
124 expect(setRepoOrder(app, writer, mine, ["subq-plan", "third-plan"])).toEqual({ ok: false, error: "unknown_account" });
125 });
126 });
test/tui-account-order.test.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * A repository's account order in the terminal (#17829): `e` sets it, `c` clears it, from the
3 * same action as the settings card, and only a writer is offered it.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { repoOrderNames } from "../src/actions/repo_account_order.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo, type Repo } from "../src/core/repos.ts";
12 import { addSubscription } from "../src/core/subscriptions.ts";
13 import { createUser, getUserByName, type User } from "../src/core/users.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { accountOrderCommands, accountOrderScreen } from "../src/tui/screens/accountorder.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { adminCookie } from "./helpers/admin.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 let dir: string, app: App, admin: User, bob: User, repo: Repo;
21
22 beforeAll(async () => {
23 dir = await mkdtemp(join(tmpdir(), "forge-order-tui-"));
24 app = createApp({ dataDir: dir, port: 0 });
25 await adminCookie(app, { username: "trevato", email: "[email protected]", password: "a-good-passphrase" });
26 admin = getUserByName(app.db, "trevato")!;
27 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
28 if (!made.ok) throw new Error(made.error);
29 bob = made.value;
30 const sub = addSubscription(app.db, dir, { name: "subq-plan", token: "sk-ant-oat01-subq-plan-token-for-the-test", createdBy: admin.id });
31 if (!sub.ok) throw new Error(sub.error);
32 const r = await createRepo(app.db, app.reposRoot, { ownerId: admin.id, name: "lib", visibility: "public", description: "", defaultBranch: "main" });
33 if (!r.ok) throw new Error(r.error);
34 repo = r.value;
35 });
36 afterAll(async () => {
37 app.close();
38 await rm(dir, { recursive: true, force: true });
39 });
40
41 const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false });
42 function open(user: User) {
43 const { app: tui, session } = createForgeApp(
44 app,
45 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
46 { terminal: headlessTerminal(120, 40), exitHooks: false },
47 );
48 tui.start();
49 tui.ctx.push(accountOrderScreen(session, tui.ctx, repo));
50 return { tui, session };
51 }
52
53 test("a writer sets the order with e and clears it with c; a reader is offered nothing and writes nothing", async () => {
54 const { tui, session } = open(admin);
55 await settleApp(tui);
56 expect(tui.screen.toText()).toContain("The forge's order");
57 tui.dispatch(key("e"));
58 await settleApp(tui);
59 for (const ch of "subq-plan") tui.dispatch(key(ch));
60 tui.dispatch(key("enter"));
61 await settleApp(tui);
62 expect(repoOrderNames(app, repo)).toEqual(["subq-plan"]);
63 expect(tui.screen.toText()).toContain("subq-plan");
64 tui.dispatch(key("c"));
65 await settleApp(tui);
66 expect(repoOrderNames(app, repo)).toEqual([]);
67
68 expect(accountOrderCommands(session, tui.ctx, repo).length).toBe(1);
69 const reader = open(bob);
70 expect(accountOrderCommands(reader.session, reader.tui.ctx, repo)).toEqual([]);
71 reader.tui.dispatch(key("e"));
72 await settleApp(reader.tui);
73 expect(repoOrderNames(app, repo)).toEqual([]);
74 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs