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

Migration mode selectable at spawn time, beside "fork of mine" and "autonomous" #13250

Merged opened this

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

Merged

torque/forge:torque/13241-migration-mode-selectable-at-spawn-time → main 7 commits fork 5 threads · 5 unresolved

  • Merged. torque/13241-migration-mode-selectable-at-spawn-time was merged into main as 8e97b21.

Review

Sign in to review this change.
11 files changed +290 −10
docs/MCP.md +1 −1
@@ -212,7 +212,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
212212 | `signup` | — | Sign-ups: open (default); invite lets in only a person with an open invite link; closed refuses every new account | 324 |
213213 | `sizes` | — | A child forge's sizes: small, medium and large, each with CPU, memory and disk | 196 |
214214 | `snapshot_now` | — | Take a snapshot now, as Backups does (admin) | 133 |
215 | `spawn` | — | Spawn a child forge | 980 |
215 | `spawn` | — | Spawn a child forge | 1066 |
216216 | `spend` | — | Report what your session spent outside forge runs: who, model, tokens or dollars, issue | 470 |
217217 | `ssh_keys` | `list`, `add`, `remove` | Your SSH keys; add: key, remove: id | 250 |
218218 | `steer` | — | Say a word to one crew run by its id | 224 |
docs/SPAWN.md +4
@@ -218,3 +218,7 @@ When the order turns paid (the `checkout.session.completed` webhook, or `/pricin
218218 `/pricing/done` waits for the spawn, then mints a fresh claim link and shows it once, as `/forges/new` does; when mail is configured it is also mailed to the order's email. `/pricing/resend` re-sends a new link (the old one stops) to the order's own email only, and answers the same whether or not an order matched.
219219
220220 A paid order whose spawn fails (no capacity, a name taken in a race) becomes `failed`: a `billing.order_failed` event, the `paid_order` flow alarm, and a plain page to the buyer. On Settings → Billing an admin sees "Paid, not made" with **Retry** and a link to the provider's dashboard to refund. With no provider connected the paid plans show their size and say "ask the operator". Agents are refused as buyers.
221
222 ## Migration mode at spawn
223
224 `migration: true` (page checkbox "Migration mode", terminal field "Mode of the forked apps", API/MCP `spawn.migration`) puts each forked app in migration mode (`apps/migration_mode.ts`): the child gets the `app_migration` row with the parent's copy as its origin (open when that repository is public) and the direction `run natively here with parity to <origin>`, followed by the spawner's own words. It needs at least one app to fork. The crew's brief is not changed: only the direction and the origin row are set.
docs/features/client-forge.md +7 −2
@@ -8,8 +8,13 @@ it from there. Each step names the route or MCP tool that does it.
88 ## Make the forge
99
1010 The sender opens `/forges/new`, names the forge, picks the apps and presses
11 Spawn. An assistant does the same with MCP tool `spawn`. The answer holds one
12 claim link, shown once. `/forges` and MCP tool `forges` list the forges sent.
11 Spawn. An assistant does the same with MCP tool `spawn`. To have the crew
12 rebuild each forked app in the new forge so it behaves like its copy here,
13 tick "Rebuild them there" under More options; the terminal's New forge screen
14 has the field "Mode of the forked apps" (`migration`), and `spawn` takes
15 `migration: true`. Each forked app then gets the direction "run natively here
outdated

This promises a parity checklist on the app page. The change does not set one up (the brief is unchanged; SPAWN.md says so). Say what happens: each forked app gets the direction "run natively here with parity to its copy" and its origin row.

16 with parity to its copy" and its origin row. The answer holds one claim link,
17 shown once. `/forges` and MCP tool `forges` list the forges sent.
1318
1419 ## Send the link
1520
src/actions/spawn.ts +14 −2
@@ -69,6 +69,7 @@ import { personRefusal, planRefusal } from "../spawn/sleep.ts";
6969 import { FREE, getPlan, PAID_PLAN_ADMIN_ONLY } from "../settings/plans.ts";
7070 import { setCap } from "../spawn/credit.ts";
7171 import { fundingOf, keepFunding, syncFunding } from "../spawn/funding.ts";
72 import { cleanOrigin, migrationDirectionFor, setMigration } from "../apps/migration_mode.ts";
7273 import { planSpawn, type SpawnInput, type SpawnPlan, type SpawnSource } from "../spawn/plan.ts";
7374 import { DEFAULT_SIZE, isSize, type Size } from "../spawn/sizes.ts";
7475 import { DEFAULT_MODE } from "../spawn/chain.ts";
@@ -562,8 +563,19 @@ async function copyInto(
562563 if (!fetched.ok) return err(inStep(step, `could not copy ${a.ref}: ${fetched.error.stderr}`));
563564 // The spawner's words are each app's direction; the child's first
564565 // boot opens the direction issue from them (`spawn/first-boot.ts`).
565 if (plan.direction !== "" && repo.autonomyDirection !== plan.direction)
566 repo = updateRepoSettings(child.db, repo, { autonomyDirection: plan.direction });
566 // Migration mode: the app answers to its parent's copy, and its direction says so
567 // (`apps/migration_mode.ts`); the spawner's own words follow.
568 let direction = plan.direction;
569 if (plan.migration) {
570 const mode = {
571 origin: cleanOrigin(`${app.config.url ?? `http://${app.config.host ?? "localhost"}`}/${o}/${n}`),
572 open: parent.visibility === "public",
573 };
574 setMigration(child.db, repo.id, mode.origin, mode.open);
575 direction = [migrationDirectionFor(mode), plan.direction].filter((s) => s !== "").join(". ");
576 }
577 if (direction !== "" && repo.autonomyDirection !== direction)
578 repo = updateRepoSettings(child.db, repo, { autonomyDirection: direction });
567579 appEntries.push(
568580 await linkAppAtBirth(app, child, dir, {
569581 org: org.username,
src/contract/openapi/routes/postApiV1Forges.ts +1
@@ -20,6 +20,7 @@ export const route: Route = {
2020 for: "string",
2121 fresh: "boolean",
2222 followMode: "string",
23 migration: "boolean (the forked apps are put in migration mode: parity with their copy here; needs apps)",
2324 budgetUsd: "number",
2425 modelKey: "string",
2526 modelEndpoint: "string",
src/http/mcp/tools/spawn.ts +2 −1
@@ -5,7 +5,7 @@ import { good, bad, type Tool, APP_ARG, REVEAL_ARG, LINK_KEPT, LINK_REVEALED } f
55
66 export const tool: Tool = {
77 name: "spawn",
8 doc: "`{ name, apps?, crew?, direction?, fresh?, purpose?, followMode?, size?, plan?, template?, keepAccess?, dryRun?, reveal? }`: a child forge to keep (`purpose: \"contribute\"` makes none: it answers the fork path), planned first (`dryRun` is true unless `false`); an admin's, and an `ro` token may plan but not make; `reveal: true` shows the claim link",
8 doc: "`{ name, apps?, crew?, direction?, fresh?, purpose?, followMode?, size?, plan?, template?, keepAccess?, migration?, dryRun?, reveal? }`: a child forge to keep (`purpose: \"contribute\"` makes none: it answers the fork path), planned first (`dryRun` is true unless `false`); an admin's, and an `ro` token may plan but not make; `reveal: true` shows the claim link",
99 description:
1010 "Spawn a child forge. Plans first.",
1111 inputSchema: {
@@ -51,6 +51,7 @@ export const tool: Tool = {
5151 type: "boolean",
5252 description: "Stay an owner.",
5353 },
54 migration: { type: "boolean", description: "Apps keep parity with their copy here." },
5455 purpose: { type: "string", description: "\"contribute\" makes no forge." },
5556 dryRun: { type: "boolean" },
5657 reveal: REVEAL_ARG,
src/spawn/door.ts +1
@@ -347,6 +347,7 @@ export async function spawnDoor(
347347 followMode: raw["followMode"],
348348 size,
349349 template: raw["template"],
350 migration: raw["migration"],
350351 ...(planKey === undefined ? {} : { plan: planKey }),
351352 ...(anon ? {} : { for: raw["for"] }),
352353 };
src/spawn/plan.ts +30 −2
@@ -77,8 +77,16 @@ export interface SpawnInput {
7777 readonly size?: unknown;
7878 /** Which template the child's apps start from (`spawn/templates.ts`); optional. */
7979 readonly template?: unknown;
80 /** The plan (`settings/plans.ts`) the child is on; optional. The door has already set `size` from it. */
80 /**
81 * The plan (`settings/plans.ts`) the child is on; optional. The door has already set `size` from
82 * it.
83 */
8184 readonly plan?: unknown;
85 /**
86 * Whether each forked app is put in migration mode, keeping parity with its parent's copy;
87 * optional.
88 */
89 readonly migration?: unknown;
8290 }
8391
8492 /** What the parent has to offer. Extra fields are ignored, never copied. */
@@ -123,8 +131,16 @@ export interface SpawnPlan {
123131 readonly size?: Size;
124132 /** The template the child starts from, present only when chosen and not `blank`. */
125133 readonly template?: string;
126 /** The key of the plan the child is on, present only when one was chosen; its credit is read when the child is made. */
134 /**
135 * The key of the plan the child is on, present only when one was chosen; its credit is read when
136 * the child is made.
137 */
127138 readonly plan?: string;
139 /**
140 * Present (true) only when the forked apps are to be in migration mode
141 * (`apps/migration_mode.ts`).
142 */
143 readonly migration?: true;
128144 }
129145
130146 export interface DryRun {
@@ -289,6 +305,16 @@ export function planSpawn(
289305 plan = input.plan;
290306 }
291307
308 // Only when asked for, so a plan without it hashes as it always did.
309 let migration: true | undefined;
310 if (input.migration !== undefined && input.migration !== null && input.migration !== "") {
311 if (typeof input.migration !== "boolean") return refuse("migration", "must be true or false");
312 if (input.migration) {
313 if (apps.length === 0) return refuse("migration", "migration mode keeps parity with an app of this forge: pick at least one app to fork");

Fine as a rule, but the dry run line (further down) promises a checklist that the crew is never briefed to write; fix the wording or add the brief.

314 migration = true;
315 }
316 }
317
292318 // `forWhom` only when said, so a plan without it hashes as it always did.
293319 return ok({
294320 name,
@@ -305,6 +331,7 @@ export function planSpawn(
305331 ...(size === undefined ? {} : { size }),
306332 ...(template === undefined ? {} : { template }),
307333 ...(plan === undefined ? {} : { plan }),
334 ...(migration === undefined ? {} : { migration }),
308335 });
309336 }
310337
@@ -319,6 +346,7 @@ export function dryRun(plan: SpawnPlan, source: SpawnSource): DryRun {
319346 : [`a fresh app ${plan.fresh.name}: ${plan.fresh.description}`]),
320347 ...plan.briefs.map((b) => `crew brief for ${b.agent}`),
321348 ...plan.subscriptions.map((s) => `subscription ${s} (name only)`),
349 ...(plan.migration ? ["migration mode: each app's direction is to run natively there with parity to its copy here"] : []),
322350 ...(plan.direction === "" ? [] : ["your words, as the child's direction"]),
323351 ...(plan.keepAccess ? ["your owner access, kept after the forge is taken over"] : []),
324352 ...(plan.budgetUsd === null
src/tui/screens/newforge.ts +9 −1
@@ -50,6 +50,7 @@ const SPECS: readonly Spec[] = [
5050 { key: "followMode", label: "Follows this forge's code", hint: FOLLOW_LINE },
5151 { key: "size", label: "Size", hint: "small (default), medium or large: left and right choose, or type it.", choices: SIZE_CHOICES },
5252 { key: "template", label: "Template", hint: TEMPLATE_HINT, choices: TEMPLATE_CHOICES },
53 { key: "migration", label: "Mode of the forked apps", hint: "own (default) or migration: the crew works to run each app natively there with parity to its copy here.", choices: ["own", "migration"] },
5354 ];
5455
5556 /** The chosen template's own sentence; a typed id that is no template keeps the general hint. */
@@ -78,7 +79,8 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
7879 let error: string | undefined;
7980 let plan: string[] | undefined;
8081 let busy = false;
81 // Said when the screen opens, before anything is typed: the host's child quota has no room even for small.
82 // Said when the screen opens, before anything is typed: the host's child quota has no room even
83 // for small.
8284 const quota = quotaFull(f.app.config.dataDir);
8385
8486 const val = (k: string): string => (values[k] ?? "").trim();
@@ -95,6 +97,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
9597 ...(val("modelKey") === "" ? {} : { modelKey: val("modelKey") }),
9698 ...(val("modelEndpoint") === "" ? {} : { modelEndpoint: val("modelEndpoint") }),
9799 ...(val("budgetUsd") === "" ? {} : { budgetUsd: Number(val("budgetUsd")) }),
100 ...(val("migration") === "migration" ? { migration: true } : {}),

Any value other than "migration" is silently ignored, so a typo spawns without the mode. Refuse anything that is not "own" or "migration".

98101 // Small is the default: it is not recorded, as on the page.
99102 ...(val("size") === "" || val("size") === DEFAULT_SIZE ? {} : { size: val("size") }),
100103 // Blank is the default: it is not recorded, as on the page.
@@ -129,6 +132,11 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
129132
130133 const run = (dryRun: boolean): void => {
131134 if (busy) return;
135 // The field can be typed over: anything but own or migration is refused, never dropped.
136 if (!["", "own", "migration"].includes(val("migration"))) {
137 refuse({ error: "invalid", message: "migration: must be own or migration" });
138 return;
139 }
132140 busy = true;
133141 error = undefined;
134142 errorKey = undefined;
src/web/pages/new-forge.ts +13 −1
@@ -49,6 +49,7 @@ interface Values {
4949 readonly fresh: string;
5050 readonly followMode: string;
5151 readonly keepAccess: boolean;
52 readonly migration: boolean;
5253 readonly budgetUsd: string;
5354 readonly modelEndpoint: string;
5455 readonly size: string;
@@ -68,6 +69,7 @@ const EMPTY: Values = {
6869 fresh: "",
6970 followMode: "take-updates",
7071 keepAccess: false,
72 migration: false,
7173 budgetUsd: "",
7274 modelEndpoint: "",
7375 size: DEFAULT_SIZE,
@@ -77,7 +79,7 @@ const EMPTY: Values = {
7779 };
7880
7981 /** The fields behind "More options": an error on one opens it. */
80 const MORE_FIELDS = ["followMode", "crew", "keepAccess", "modelKey", "modelEndpoint", "budgetUsd", "template", "size"];
82 const MORE_FIELDS = ["followMode", "crew", "keepAccess", "migration", "modelKey", "modelEndpoint", "budgetUsd", "template", "size"];
8183
8284 type Errors = Partial<Record<string, string>>;
8385
@@ -325,6 +327,14 @@ function formView(
325327 chosen: values.crew,
326328 error: errors["crew"],
327329 })}
330 ${anon ? null : html`<div class="field" ${errors["migration"] ? html`data-invalid` : null}>
331 <label class="check">
outdated

Principle 1: the legend, the label and the muted sentence all say the same thing, and the sentence promises a checklist nothing writes. Keep one short label with one sentence, in plain words (principle 8), and say only what really happens.

332 <input type="checkbox" name="migration" ${values.migration ? html`checked` : null} aria-describedby="f-migration-hint" />
333 <span>Rebuild them there</span>
334 </label>
335 <span class="muted small" id="f-migration-hint">Each app's crew is told to run it natively in the new forge, matching its copy here. Needs an app above.</span>
336 ${errors["migration"] ? html`<span class="error" id="f-migration-err">${errors["migration"]}</span>` : null}
337 </div>`}
328338 ${anon
329339 ? null
330340 : html`<fieldset class="field">
@@ -541,6 +551,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
541551 fresh: field(form, "fresh").trim(),
542552 followMode: field(form, "followMode").trim() || "take-updates",
543553 keepAccess: asBool(form, "keepAccess"),
554 migration: asBool(form, "migration"),
544555 budgetUsd: field(form, "budgetUsd").trim(),
545556 modelEndpoint: field(form, "modelEndpoint").trim(),
546557 size: field(form, "size").trim() || DEFAULT_SIZE,
@@ -555,6 +566,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
555566 apps: values.apps,
556567 crew: values.crew,
557568 keepAccess: values.keepAccess,
569 ...(values.migration ? { migration: true } : {}),
558570 ...(values.fresh === "" ? {} : { fresh: values.fresh }),
559571 followMode: values.followMode,
560572 ...(values.forWhom === "" ? {} : { for: values.forWhom }),
test/spawn-migration.test.ts added +208
@@ -0,0 +1,208 @@
1 /**
2 * Migration mode at spawn time (#13241): a spawn that asks for it makes each forked app answer to
3 * its parent's copy: the `app_migration` row, and the direction `run natively here with parity to
4 * <origin>`. The page, the API/MCP door and the terminal all send `migration`.
5 */
6
7 import { afterAll, beforeAll, describe, expect, spyOn, 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 { childDirOf, spawnForge } from "../src/actions/spawn.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import * as door from "../src/spawn/door.ts";
18 import { usePlacement, useProbe } from "../src/spawn/door.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import { newForgeScreen } from "../src/tui/screens/newforge.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { settleApp } from "./helpers/tui.ts";
23 import { commitFiles } from "../src/git/write.ts";
24 import { repoDir } from "../src/git/repos.ts";
25 import { migrationOf } from "../src/apps/migration_mode.ts";
26 import { hostedPlacement } from "../src/spawn/placement.ts";
27 import { planSpawn } from "../src/spawn/plan.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29
30 quietLogs();
31
32 const source = {
33 catalog: [{ ref: "alice/bakery", readable: true, bytes: 10, forgeJsonBytes: 0 }],
34 briefs: [],
35 subscriptions: [],
36 };
37 const base = { name: "maria", org: "marias", apps: ["alice/bakery"], carryBriefs: false, carrySubscriptions: false };
38
39 describe("migration mode at spawn", () => {
40 test("the plan names it only when asked, and needs an app", () => {
41 expect(planSpawn(base, source)).toMatchObject({ ok: true });
42 expect((planSpawn(base, source) as { value: object }).value).not.toHaveProperty("migration");
43 expect((planSpawn({ ...base, migration: false }, source) as { value: object }).value).not.toHaveProperty("migration");
44 const on = planSpawn({ ...base, migration: true }, source);
45 expect(on.ok && on.value.migration).toBe(true);
46 const none = planSpawn({ ...base, apps: [], migration: true }, source);
47 expect(none.ok).toBe(false);
48 expect(!none.ok && none.error.field).toBe("migration");
49 const bad = planSpawn({ ...base, migration: "yes" }, source);
50 expect(!bad.ok && bad.error.field).toBe("migration");
51 });
52
53 describe("the spawned app", () => {
54 let dir = "";
55 let parent: App;
56 let child: App;
57 beforeAll(async () => {
58 dir = await mkdtemp(join(tmpdir(), "forge-spawn-migration-"));
59 parent = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
60 const made = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", isAdmin: true });
61 if (!made.ok) throw new Error("user");
62 const repo = await createRepo(parent, made.value, { name: "bakery", visibility: "public" });
63 if (!repo.ok) throw new Error("repo");
64 const c = await commitFiles(repoDir(parent.reposRoot, "alice", "bakery"), {
65 branch: "main",
66 message: "bakery",
67 files: [{ path: "README.md", content: "# bakery\n" }],
68 author: { name: "a", email: "[email protected]" },
69 });
70 if (!c.ok) throw new Error("commit");
71 const spawned = await spawnForge(
72 parent,
73 made.value,
74 { ...base, migration: true, direction: "Mind the oven." },
75 source,
76 {
77 placement: hostedPlacement({ host: "forge.test" }),
78 request: new Request("https://forge.test/x", { method: "POST", headers: { origin: "https://forge.test" } }),
79 url: new URL("https://forge.test/x"),
80 },
81 );
82 if (!spawned.ok) throw new Error(JSON.stringify(spawned.error));
83 child = createApp({ dataDir: childDirOf(parent, spawned.value.bodyId), port: 0 });
84 });
85 afterAll(async () => {
86 await rm(dir, { recursive: true, force: true });
87 });
88
89 test("is in migration mode with the direction", () => {
90 const repo = getRepo(child.db, "marias", "bakery")!;
91 const mode = migrationOf(child.db, repo.id);
92 expect(mode).toEqual({ origin: "https://forge.test/alice/bakery", open: true });
outdated

Greping source text proves nothing about behaviour; replace with tests that submit the page form and drive the TUI screen, and that fail when the door is broken.

93 expect(repo.autonomyDirection).toBe("run natively here with parity to https://forge.test/alice/bakery. Mind the oven.");
94 expect(repo.autonomyDirection).not.toContain("..");
95 });
96 });
97 });
98
99 describe("the doors offer it", () => {
100 let dir = "";
101 let app: App;
102 let servers: Servers;
103 let cookie = "";
104 let admin: User;
105 const PASSWORD = "a-long-new-forge-passphrase";
106
107 beforeAll(async () => {
108 dir = await mkdtemp(join(tmpdir(), "forge-spawn-migration-doors-"));
109 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
110 const a = await createUser(app.db, {
111 origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: PASSWORD, isAdmin: true,
112 });
113 if (!a.ok) throw new Error("user");
114 admin = a.value;
115 const repo = await createRepo(app, admin, { name: "bakery", visibility: "public" });
116 if (!repo.ok) throw new Error("repo");
117 const c = await commitFiles(repoDir(app.reposRoot, "alice", "bakery"), {
118 branch: "main", message: "bakery", files: [{ path: "README.md", content: "# bakery\n" }],
119 author: { name: "a", email: "[email protected]" },
120 });
121 if (!c.ok) throw new Error("commit");
122 useProbe(app, () => async () => true);
123 usePlacement(app, hostedPlacement({ host: "forge.test" }));
124 servers = await serve(app);
125 const res = await fetch(`${servers.url}/signin`, {
126 method: "POST", body: new URLSearchParams({ username: "alice", password: PASSWORD }), redirect: "manual",
127 });
128 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
129 }, 30_000);
130 afterAll(async () => {
131 servers.stop();
132 app.close();
133 await rm(dir, { recursive: true, force: true });
134 });
135
136 const post = (form: [string, string][]) =>
137 fetch(`${servers.url}/forges/new`, {
138 method: "POST",
139 headers: { cookie, origin: "https://forge.test" },
140 body: new URLSearchParams(form),
141 redirect: "manual",
142 });
143
144 test("the page offers the checkbox once, in plain words", async () => {
145 const html = (await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text()).replace(/\s+/g, " ");
146 expect(html).toContain('name="migration"');
147 expect(html).toContain("Rebuild them there");
148 expect(html).not.toContain("checklist");
149 });
150
151 test("the page form with migration on reaches the plan; off does not", async () => {
152 const spy = spyOn(door, "spawnDoor");
153 try {
154 const on = await post([["name", "maria"], ["apps", "alice/bakery"], ["migration", "on"], ["do", "plan"]]);
155 expect(on.status).toBe(200);
156 expect(spy.mock.calls.at(-1)![2]["migration"]).toBe(true);
157 expect(await on.text()).toContain("migration mode");
158 const off = await post([["name", "maria"], ["apps", "alice/bakery"], ["do", "plan"]]);
159 expect("migration" in spy.mock.calls.at(-1)![2]).toBe(false);
160 expect(await off.text()).not.toContain("migration mode");
161 } finally {
162 spy.mockRestore();
163 }
164 });
165
166 test("the page refuses migration with no app, beside the field", async () => {
167 const res = await post([["name", "maria"], ["migration", "on"], ["do", "plan"]]);
168 expect(res.status).toBe(422);
169 expect(await res.text()).toContain('id="f-migration-err"');
170 });
171
172 async function screenWith(keys: string): Promise<string> {
173 const terminal = headlessTerminal(140, 40);
174 const { app: tui, session } = createForgeApp(
175 app,
176 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin },
177 { terminal, exitHooks: false },
178 );
179 tui.start();
180 tui.ctx.push(newForgeScreen(session, tui.ctx));
181 try {
182 await settleApp(tui);
183 terminal.feed(keys + "\x10");
184 await settleApp(tui);
185 return tui.screen.toText();
186 } finally {
187 tui.stop?.();
188 }
189 }
190 // name, for, direction, apps … the migration field is the twelfth.
191 const toApps = "\t\t\t";
192 const toMigration = "\t".repeat(8);
193
194 test("the terminal's migration choice reaches the plan", async () => {
195 const text = await screenWith("maria" + toApps + "alice/bakery" + toMigration + "\x1b[C");
196 expect(text).toContain("The plan");
197 expect(text).toContain("migration mode");
198 const own = await screenWith("maria" + toApps + "alice/bakery");
199 expect(own).toContain("The plan");
200 expect(own).not.toContain("migration mode");
201 });
202
203 test("the terminal refuses a mistyped mode instead of dropping it", async () => {
204 const text = await screenWith("maria" + toApps + "alice/bakery" + toMigration + "migrate");
205 expect(text).not.toContain("The plan");
206 expect(text).toContain("must be own or migration");
207 });
208 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs