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

Talk brings a repository kept elsewhere in to work on, and a tell on a mirror goes to the person's copy #16374

Merged opened this

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

Merged

talk/origins-bring → main 0 commits

  • Merged. talk/origins-bring was merged into main as b0b02c3.

Review

Sign in to review this change.
21 files changed +617 −29
docs/features/bring.md +14
@@ -18,6 +18,20 @@ the `+` menu and the palette.
1818 - Code: `src/origins/bring.ts` (link, host, needs), `src/actions/bring.ts`,
1919 `src/web/pages/bring.ts`. Test: `test/bring.test.ts`.
2020
21 ## Work on a repository kept elsewhere (Talk's `bring`)
22
23 Say "bring octo/widgets in" in Talk (or open **Work on a repository** in the
24 terminal's palette) with the account that holds it connected on
25 `/settings/origins`. Talk asks first, then mirrors it and makes **your copy**
26 beside it: both private here, whatever the repository is at its origin, which is
27 not changed. A mirror already here in public is made private, and Talk says so;
28 one you do not administer is not brought in. The crew works on your copy; a change you tell on the mirror goes to
29 your copy too, so nothing is filed at the origin. Asking again reuses both.
30
31 - Code: `bringToWork` and `workCopyOf` in `src/actions/bring.ts`, the MCP tool
32 `src/http/mcp/tools/bring.ts`, the screen `src/tui/screens/bringwork.ts`.
33 Test: `test/talk-bring.test.ts` (two forges, a crew stand-in).
34
2135 ## What is left to bring over (`/migrate/inventory`)
2236
2337 Connect the account your apps live on (`/migrate`), then open
scripts/dupes-pairs.json +1 −1
@@ -18,7 +18,7 @@
1818 {"a":"test/cluster-jobs.test.ts#test: a Job fails: the container's exit code is reported, the Job is deleted","b":"test/cluster-jobs.test.ts#test: an aborted call deletes the Job and throws","same":false,"why":"similar in style, but one function would not serve both"},
1919 {"a":"test/via-token.test.ts#mcp","b":"test/explore-unknown-words.test.ts#call","same":true,"why":"two helpers post one MCP tools/call"},
2020 {"a":"test/view-source.test.ts#test: a failed fetch lands in the job and in fetch_error, scrubbed","b":"test/origins.test.ts#test: mirroring the same repo twice is refused","same":false,"why":"similar in style, but one function would not serve both"},
21 {"a":"src/tui/screens/bring.ts#bringWords","b":"src/actions/revert_words.ts#takeBackWords","same":false,"why":"similar in style, but one function would not serve both"},
21 {"a":"src/actions/bring.ts#bringWords","b":"src/actions/revert_words.ts#takeBackWords","same":false,"why":"similar in style, but one function would not serve both"},
2222 {"a":"test/report-receipt.test.ts#test: the MCP report tool answers the same receipt, with no token","b":"test/report-words.test.ts#test: the MCP `report` tool answers the module's sentence","same":false,"why":"similar in style, but one function would not serve both"},
2323 {"a":"test/mcp-economics.test.ts#test: dryRun false sets it, and the read agrees","b":"test/mcp-economics.test.ts#test: an admin agent token is told not found, to read or to set","same":false,"why":"similar in style, but one function would not serve both"},
2424 {"a":"src/actions/board-pins.ts#pinPanel","b":"src/actions/board-pins.ts#movePinned","same":false,"why":"similar in style, but one function would not serve both"},
scripts/feature-doors-allow.json −1
@@ -1,6 +1,5 @@
11 [
22 "docs/features/absorb.md",
3 "docs/features/bring.md",
43 "docs/features/claim-own-name.md",
54 "docs/features/crawl-budget.md",
65 "docs/features/dependency-standing.md",
src/actions/bring.ts +172 −3
@@ -15,18 +15,22 @@
1515 import type { App } from "../app.ts";
1616 import { getAppByRepo, slugFor, getAppBySlug, SLUG_MAX, type AppRecord } from "../core/apps.ts";
1717 import { listAppEnvNames } from "../core/app_env.ts";
18 import { listOrigins } from "../core/origins.ts";
19 import { getRepoById, type Repo } from "../core/repos.ts";
18 import { getOriginFor, listOrigins, mirrorOf } from "../core/origins.ts";
19 import { canRead, getRepoById, listForks, type Repo } from "../core/repos.ts";
2020 import { isActive, type User } from "../core/users.ts";
2121 import { readerFor } from "../git/read.ts";
2222 import { repoDir } from "../git/repos.ts";
2323 import { err, ok, type Result } from "../kernel/result.ts";
2424 import { startMirror } from "../origins/mirror.ts";
25 import type { MirrorJob } from "../origins/jobs.ts";
25 import { settled, type MirrorJob } from "../origins/jobs.ts";
26 import type { Origin } from "../origins/types.ts";
2627 import { needsOf, originOnHost, parseBringLink } from "../origins/bring.ts";
2728 import { requireVerified } from "./verify.ts";
2829 import { appLimitWords } from "./app_limit.ts";
2930 import { enableApp, setAppEnvVar } from "./apps.ts";
31 import { forkRepo, updateRepoSettings } from "./repos.ts";
32 import { seatEmptyCrew } from "./seat_crew.ts";
33 import { during } from "../perf/jobs.ts";
3034
3135 export type BringError =
3236 | { readonly kind: "unauthorized" }
@@ -35,6 +39,20 @@ export type BringError =
3539 /** No connected account on that forge: sign in there first. */
3640 | { readonly kind: "connect"; readonly host: string };
3741
42 /** The words for a refusal, as every door says them. */
43 export function bringWords(e: BringError): string {
44 switch (e.kind) {
45 case "connect":
46 return `Sign in to ${e.host} first (connect your account there, on /settings/origins), then try again.`;
47 case "invalid":
48 return e.message;
49 case "unverified":
50 return "Verify your email first: an app runs code.";
51 case "unauthorized":
52 return "Only a person's own account brings an app.";
53 }
54 }
55
3856 const LINK_WORDS = {
3957 empty: "Paste the link to an app.",
4058 not_a_link: "That is not a link to a repository (https://host/owner/name).",
@@ -149,3 +167,154 @@ export async function setBroughtEnv(
149167 }
150168 return count;
151169 }
170
171 // ---- a repository to work on (#10262) ----
172 //
173 // A repository kept elsewhere becomes one thing to work on here: a mirror that follows the origin,
174 // and the person's own native fork of it, `<name>-work`, where the crew works (a mirror's
175 // branches are the origin's, so no crew run writes there). Both private, whatever the origin's
176 // visibility. The person is shown one thing: the origin's name, "your copy".
177
178 /** The name a work copy takes beside its mirror. */
179 export const workName = (mirror: Repo): string => `${mirror.name}-work`;
180
181 /** How long a bring waits for its mirror before answering that it is still copying; a test seam. */
182 export const bringWait: { ms: number } = { ms: 60_000 };
183
184 /** The longest `repo` (a link or owner/name) and `origin` a bring takes. */
185 const BRING_INPUT_MAX = 300;
186
187 /**
188 * A bring promises both repositories are private here. A mirror made earlier from a public
189 * repository, or by a mirror job another call started without `private`, is made private now,
190 * by its admin; one the person may not administer is refused rather than said to be private.
191 */
192 async function madePrivate(app: App, actor: User, repo: Repo): Promise<Result<{ repo: Repo; made: boolean }, "public">> {
193 if (repo.visibility === "private") return ok({ repo, made: false });
194 const made = await updateRepoSettings(app, actor, repo, { visibility: "private" });
195 return made.ok ? ok({ repo: made.value, made: true }) : err("public");
196 }
197
198 /**
199 * The person's copy of a mirror: their native fork of it, made private with a crew seated when
200 * missing. One per person and mirror, so asking again (a second bring, every tell) finds it.
201 */
202 export async function workCopyOf(
203 app: App,
204 actor: User,
205 mirror: Repo,
206 ): Promise<Result<{ repo: Repo; made: boolean }, string>> {
207 const found = (): Repo | undefined => listForks(app.db, mirror.id).find((r) => r.ownerId === actor.id && r.origin === null);
208 const have = found();
209 if (have !== undefined) return ok({ repo: have, made: false });
210 const forked = await forkRepo(app, actor, mirror, workName(mirror), { visibility: "private" });
211 if (!forked.ok) {
212 // Two asks at once: the other made it.
213 const other = found();
214 return other === undefined ? err(String(forked.error)) : ok({ repo: other, made: false });
215 }
216 await seatEmptyCrew(app, actor, forked.value);
217 return ok({ repo: forked.value, made: true });
218 }
219
220 export interface BroughtIn {
221 /** `owner/name` at the origin: what the person calls it. */
222 readonly name: string;
223 /** Where it is kept, as a person says it: `GitHub`, `codeberg.org`. */
224 readonly from: string;
225 readonly mirror: Repo;
226 /** Undefined while the mirror is still copying: the first tell makes it. */
227 readonly copy: Repo | undefined;
228 /** Whether the mirror and the copy were already here. */
229 readonly reused: { readonly mirror: boolean; readonly copy: boolean };
230 /** Whether a mirror already here in public was made private by this bring. */
231 readonly madePrivate: boolean;
232 }
233
234 const OWNER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
235
236 /** The origin and the `owner/name` a bring names: a link, or `owner/name` on `originId` or the one origin. */
237 function bringTarget(app: App, actor: User, repo: string, originId: string | undefined): Result<{ origin: Origin; fullName: string }, BringError> {
238 const text = repo.trim().replace(/\.git$/, "");
239 if (OWNER_NAME.test(text)) {
240 const origins = listOrigins(app.db, actor.id).filter((o) => !o.needsReauth);
241 const origin = originId === undefined ? (origins.length === 1 ? origins[0] : undefined) : getOriginFor(app.db, actor.id, originId);
242 if (origin === undefined)
243 return err({ kind: "invalid", message: origins.length === 0 ? "Connect the account that holds it on /settings/origins first." : "Say which account holds it: send `origin`, an id from `origins`." });
244 return ok({ origin, fullName: text });
245 }
246 const parsed = parseBringLink(text);
247 if (!parsed.ok) return err({ kind: "invalid", message: LINK_WORDS[parsed.error] });
248 const origin = originOnHost(listOrigins(app.db, actor.id), parsed.value.host);
249 if (origin === undefined) return err({ kind: "connect", host: parsed.value.host });
250 return ok({ origin, fullName: parsed.value.fullName });
251 }
252
253 /**
254 * Bring a repository in to work on: its mirror (reused when it is here), then the person's copy
255 * (reused too). Bringing it twice makes nothing new.
256 */
257 export async function bringToWork(
258 app: App,
259 actor: User | undefined,
260 input: { readonly repo: string; readonly origin?: string },
261 ): Promise<Result<BroughtIn, BringError>> {
262 if (actor === undefined || !isActive(actor) || actor.kind === "agent") return err({ kind: "unauthorized" });
263 if (!requireVerified(app, actor).ok) return err({ kind: "unverified" });
264 // Bounded here, for every door: a link and an origin's id are short.
265 if (input.repo.length > BRING_INPUT_MAX || (input.origin?.length ?? 0) > BRING_INPUT_MAX)
266 return err({ kind: "invalid", message: `A link, owner/name or account id is at most ${String(BRING_INPUT_MAX)} characters.` });
267 const target = bringTarget(app, actor, input.repo, input.origin);
268 if (!target.ok) return target;
269 const { origin, fullName } = target.value;
270 const host = URL.parse(origin.webUrl)?.host ?? origin.webUrl;
271 const from = host === "github.com" ? "GitHub" : host;
272 const here = mirrorOf(app.db, origin.id, fullName);
273 let mirror = here === undefined ? undefined : getRepoById(app.db, here);
274 if (mirror !== undefined && !canRead(app.db, mirror, actor)) mirror = undefined;
275 const reusedMirror = mirror !== undefined;
276 const keptPublic = err({ kind: "invalid", message: `${fullName} is already mirrored here in public by an account you do not administer, so it cannot be brought in private.` } as const);
277 if (mirror === undefined) {
278 const job = startMirror(app, actor, origin, fullName, undefined, { private: true });
279 let timer: ReturnType<typeof setTimeout> | undefined;
280 let done;
281 try {
282 done = await Promise.race([
283 settled(job.id),
284 new Promise<undefined>((resolve) => {
285 timer = setTimeout(() => during("bring-wait", () => resolve(undefined)), bringWait.ms);
286 }),
287 ]);
288 } finally {
289 clearTimeout(timer);
290 }
291 if (done === undefined) {
292 const now = mirrorOf(app.db, origin.id, fullName);
293 const row = now === undefined ? undefined : getRepoById(app.db, now);
294 if (row === undefined) return err({ kind: "invalid", message: `${fullName} is still being copied from ${from}; ask again in a minute.` });
295 const kept = await madePrivate(app, actor, row);
296 if (!kept.ok) return keptPublic;
297 return ok({ name: fullName, from, mirror: kept.value.repo, copy: undefined, reused: { mirror: false, copy: false }, madePrivate: kept.value.made });
298 }
299 if (done.stage !== "done" || done.repo === undefined)
300 return err({ kind: "invalid", message: done.error ?? `${fullName} could not be copied from ${from}.` });
301 mirror = getRepoById(app.db, done.repo.id) ?? done.repo;
302 }
303 const kept = await madePrivate(app, actor, mirror);
304 if (!kept.ok) return keptPublic;
305 const copy = await workCopyOf(app, actor, kept.value.repo);
306 if (!copy.ok) return err({ kind: "invalid", message: `${fullName} is here, but your copy could not be made (${copy.error}).` });
307 return ok({ name: fullName, from, mirror: kept.value.repo, copy: copy.value.repo, reused: { mirror: reusedMirror, copy: !copy.value.made }, madePrivate: kept.value.made });
308 }
309
310 /**
311 * What a bring says, the same at every door: the repository by its origin's name, and "your copy",
312 * never the two repositories it is made of.
313 */
314 export function broughtWords(b: BroughtIn): string {
315 const madePrivate = b.madePrivate ? ` Its mirror here was public; it is private now.` : "";
316 const copyPublic = b.copy !== undefined && b.copy.visibility !== "private" ? ` Your copy is public, as you set it.` : "";
317 if (b.copy === undefined) return `${b.name} is still being copied from ${b.from}; your copy is made when you first ask for a change.${madePrivate}`;
318 if (b.reused.mirror && b.reused.copy) return `${b.name} was already here, with your copy; nothing new was made. Ask for a change and the crew works on your copy.${madePrivate}${copyPublic}`;
319 return `${b.name} from ${b.from} is here as your copy, private, with the crew on it${b.reused.mirror ? " (it was already mirrored)" : ""}. Ask for a change and the crew works there; ${b.from} is unchanged until you propose it upstream.${madePrivate}`;
320 }
src/crew/conversation_ask.ts +1
@@ -151,6 +151,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
151151 stop: (a) => (val(a, "run") === "" ? "Stop the forge's agent in the middle of its answer" : `Stop crew run ${val(a, "run")}${clause(" in ", val(a, "repo"))}`),
152152 write_file: (a) => `Commit ${val(a, "path") || "a file"} to ${val(a, "branch") || "a branch"} in ${repo(a)}`,
153153 open_pull: (a) => `Open a pull in ${repo(a)}${clause(": ", quote(a, "title"))}`,
154 bring: (a) => `Bring ${val(a, "repo") || "the repository"} in to work on: a mirror and your copy, both private here`,
154155 new_app: (a) => `Make a new app${clause(" called ", val(a, "name"))}${clause(": ", quote(a, "sentence"))}`,
155156 asks_act: (a) => `${capital(verb(a, "action", { dismiss: "dismiss", decline: "decline", mute: "mute", listen: "unmute", undo: "undo", ship: "ship", close: "close", replan: "replan" }, "decide"))} ${a["action"] === "listen" ? repo(a) : a["action"] === "undo" ? "the last decision on your asks" : count(a["items"], "ask", "asks")}`,
156157 asks: () => "Change the filter on what waits on you",
src/crew/conversation_confirm.ts +2
@@ -126,6 +126,8 @@ export const ASKING: Readonly<Record<string, Asking>> = {
126126 outsiders: {},
127127 seal: {},
128128 migrate: {},
129 // A repository kept elsewhere, mirrored and copied here: the person's credential spent on it.
130 bring: {},
129131 account_suspend: {},
130132 account_access: {
131133 once: "The link was shown once, to you, and is not kept here.",
src/http/mcp/catalog.ts +4 −2
@@ -27,7 +27,8 @@ export const DEFAULT_TOOLS: readonly string[] = [
2727 * `show`, which draws the forge's own data in a reply as a chart, and `fetch_url`, which reads a
2828 * page the person linked), and the everyday writes on that work (comment, close or reopen, assign,
2929 * labels, edit, review, merge, the plan on an issue, a word to or a stop of a crew run, a
30 * branch, a file and a pull for an app built in Talk, a new app). Each write is held as any write
30 * branch, a file and a pull for an app built in Talk, a new app, a repository kept elsewhere
31 * brought in to work on). Each write is held as any write
3132 * of this token is: after the agent has read text someone else wrote, a write the person's own
3233 * words do not ask for comes back `needs_confirm`, and the asked-first list
3334 * (`crew/conversation_confirm.ts`) holds its tools always; `test/mcp-talk-tools.test.ts` calls
@@ -48,7 +49,7 @@ export const TALK_TOOLS: readonly string[] = [
4849 "issue", "issues", "pull", "pulls", "commits", "threads", "search", "read_file", "repo", "run_log",
4950 "preview", "assigned", "health", "releases", "person", "whoami_can", "show", "pane", "origins", "invite", "wall",
5051 "close", "assign", "labels", "edit", "review", "merge", "keep_plan", "steer", "stop",
51 "write_file", "branches", "open_pull", "new_app", "fetch_url",
52 "write_file", "branches", "open_pull", "new_app", "fetch_url", "bring",
5253 ];
5354
5455 /**
@@ -105,6 +106,7 @@ export const KEYWORDS: Readonly<Record<string, string>> = {
105106 usage: "spent spend cost money budget",
106107 run_log: "failed failure why log output",
107108 origins: "github gitlab codeberg gitea forgejo connected account accounts elsewhere outside external",
109 bring: "github import mirror copy work fork elsewhere",
108110 };
109111
110112 /** Entries matching every word of `query`, best first; a name weighs more than a description. */
src/http/mcp/tools/bring.ts added +30
@@ -0,0 +1,30 @@
1 import { bringToWork, broughtWords, bringWords } from "../../../actions/bring.ts";
2 import { good, bad, str, type Tool } from "../shared.ts";
3
4 export const tool: Tool = {
5 name: "bring",
6 description: "Bring in `repo` (link, or owner/name on `origin`) to work on.",
7 inputSchema: {
8 type: "object",
9 properties: {
10 repo: { type: "string", maxLength: 300 },
11 origin: { type: "string", maxLength: 300 },
12 },
13 required: ["repo"],
14 },
15 writes: true,
16 async run(ctx, user, args) {
17 const origin = str(args["origin"]);
18 const brought = await bringToWork(ctx.app, user, { repo: str(args["repo"]), ...(origin === "" ? {} : { origin }) });
19 if (!brought.ok) return bad(brought.error.kind === "unauthorized" ? "forbidden" : brought.error.kind, bringWords(brought.error));
20 const b = brought.value;
21 const at = (r: { ownerName: string; name: string }) => `/${r.ownerName}/${r.name}`;
22 return good({
23 says: broughtWords(b),
24 name: b.name,
25 ...(b.copy === undefined ? {} : { copy: at(b.copy) }),
26 mirror: at(b.mirror),
27 reused: b.reused,
28 });
29 },
30 };
src/http/mcp/tools/index.ts +1
@@ -38,6 +38,7 @@ export { tool as board_pins } from "./board_pins.ts";
3838 export { tool as board_write } from "./board_write.ts";
3939 export { tool as boards } from "./boards.ts";
4040 export { tool as branches } from "./branches.ts";
41 export { tool as bring } from "./bring.ts";
4142 export { tool as builds } from "./builds.ts";
4243 export { tool as capacity } from "./capacity.ts";
4344 export { tool as claim_link } from "./claim_link.ts";
src/http/mcp/tools/tell.ts +13 −2
@@ -10,6 +10,7 @@ import { mayReadRuns } from "../../../actions/runs.ts";
1010 import { getIssue } from "../../../core/issues.ts";
1111 import { tellStatusFields } from "../../../runs/tell_status.ts";
1212 import { issueHold } from "../../../core/talk_work.ts";
13 import { workCopyOf } from "../../../actions/bring.ts";
1314 import { good, bad, type Tool, str, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1415
1516 export const tool: Tool = {
@@ -89,15 +90,25 @@ export const tool: Tool = {
8990 }
9091 const said = str(args["text"]).trim();
9192 if (overTellLimit(said)) return bad("invalid", `${tellTooLongWords(said)} ${TELL_LIMIT_HINT}`);
92 const repo = repoArg(ctx, user, args);
93 if (isAnswer(repo)) return repo;
93 const named = repoArg(ctx, user, args);
94 if (isAnswer(named)) return named;
9495 if (args["issue"] !== undefined) {
96 const repo = named;
9597 const n = args["issue"];
9698 const found = typeof n === "number" && Number.isInteger(n) && n > 0 ? getIssue(ctx.app.db, repo.id, n) : undefined;
9799 if (found === undefined || !mayReadRuns(ctx.app, user, repo)) return bad("not_found", "no such tell");
98100 // A run that waits says on what, from its own log, and links the control that changes it.
99101 return good({ issue: found.number, ...tellStatusFields(ctx.app.db, repo.id, found), ...issueHold(ctx.app.db, ctx.app.config.dataDir, found, user, ctx.url.origin) });
100102 }
103 // A mirror's branches are its origin's, so the crew never works there: a change told on one
104 // goes to the person's own copy of it, made when missing (`workCopyOf`). Resolved here, at the
105 // door, not in `tell`, which the forge's own boot calls too.
106 let repo = named;
107 if (repo.origin !== null && said !== "") {
108 const copy = await workCopyOf(ctx.app, user, repo);
109 if (!copy.ok) return bad("no_copy", "Your copy of it could not be made here, so nothing was told; bring it in again with `bring`.");
110 repo = copy.value.repo;
111 }
101112 const where = parseContext(args["context"]);
102113 if (where === null)
103114 return bad(
src/origins/mirror.ts +9 −1
@@ -86,6 +86,11 @@ export const firstFetchRetry: {
8686 wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
8787 };
8888
89 /** `private`: the mirror is private here whatever the origin's visibility (a copy to work on). */
90 export interface MirrorOptions {
91 readonly private?: true;
92 }
93
8994 export async function mirrorRepo(
9095 app: App,
9196 actor: User,
@@ -93,6 +98,7 @@ export async function mirrorRepo(
9398 fullName: string,
9499 name?: string,
95100 job?: string,
101 options: MirrorOptions = {},
96102 ): Promise<Result<MirrorResult, MirrorError>> {
97103 const stage = (patch: Parameters<typeof advance>[1]): void => {
98104 if (job !== undefined) advance(job, patch);
@@ -150,7 +156,7 @@ export async function mirrorRepo(
150156 ownerId: actor.id,
151157 name: chosen,
152158 // A read-only origin's mirror is private to its owner (#10520).
153 visibility: remote.private || origin.readOnly ? "private" : "public",
159 visibility: remote.private || origin.readOnly || options.private === true ? "private" : "public",
154160 description: remote.description,
155161 defaultBranch,
156162 });
@@ -237,6 +243,7 @@ export function startMirror(
237243 origin: Origin,
238244 fullName: string,
239245 name?: string,
246 options: MirrorOptions = {},
240247 ): MirrorJob {
241248 const running = runningJob(origin.id, fullName);
242249 if (running !== undefined) return running;
@@ -251,6 +258,7 @@ export function startMirror(
251258 fullName,
252259 name,
253260 job.id,
261 options,
254262 );
255263 if (!result.ok) {
256264 advance(job.id, {
src/tui/forge.ts +9
@@ -132,6 +132,7 @@ import { newForgeScreen } from "./screens/newforge.ts";
132132 import { newOrgScreen } from "./screens/neworg.ts";
133133 import { migrateScreen } from "./screens/migrate.ts";
134134 import { bringScreen } from "./screens/bring.ts";
135 import { bringWorkScreen } from "./screens/bringwork.ts";
135136 import { openNewApp, templateAppScreen } from "./screens/newapp.ts";
136137 import { newRepoScreen } from "./screens/newrepo.ts";
137138 import { repoScreen } from "./screens/repo.ts";
@@ -391,6 +392,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
391392 hint: "paste a link from another forge; it runs here",
392393 run: () => ctx.push(bringScreen(session, ctx, blank("Bring an app"))),
393394 });
395 // A repository kept elsewhere, to work on here, as Talk's `bring` does: a person's.
396 if (session.user !== undefined && session.user.kind !== "agent")
397 commands.push({
398 id: "bring-work",
399 title: "Work on a repository",
400 hint: "from GitHub or another forge: your private copy here, the crew on it",
401 run: () => ctx.push(bringWorkScreen(session, ctx, blank("Work on a repository"))),
402 });
394403 // An organization you own, as /organizations/new and MCP `org_create` make it: a person's,
395404 // never an agent's (#7260).
396405 if (session.user !== undefined && session.user.kind !== "agent")
src/tui/screens/bring.ts +1 −15
@@ -5,7 +5,7 @@
55 * `.env.example` asks for is prompted for, masked. Empty leaves it unset.
66 */
77
8 import { bringLanded, setBroughtEnv, startBring, type BringError, type Brought } from "../../actions/bring.ts";
8 import { bringLanded, bringWords, setBroughtEnv, startBring, type Brought } from "../../actions/bring.ts";
99 import { connectOrigin, connectRefusal } from "../../actions/origins.ts";
1010 import { connectWords } from "../../actions/origin_words.ts";
1111 import { connectSite, PLAIN_HTTP_WORDS } from "../../origins/bring.ts";
@@ -15,20 +15,6 @@ import type { Session } from "../session.ts";
1515 import { later, promptScreen, runAsync } from "./common.ts";
1616 import { showMirrorJob } from "./mirror.ts";
1717
18 /** The words for a refusal, as the page says them. */
19 export function bringWords(e: BringError): string {
20 switch (e.kind) {
21 case "connect":
22 return `Sign in to ${e.host} first (connect your account there), then try again.`;
23 case "invalid":
24 return e.message;
25 case "unverified":
26 return "Verify your email first: an app runs code.";
27 case "unauthorized":
28 return "Only a person's own account brings an app.";
29 }
30 }
31
3218 function askNext(f: Session, ctx: Ctx, parent: Screen, brought: Brought, asking: readonly string[]): void {
3319 const [name, ...rest] = asking;
3420 if (name === undefined) return;
src/tui/screens/bringwork.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * "Work on a repository" in the terminal: the door beside Talk's `bring`. A link or `owner/name`
3 * kept on GitHub or another forge is mirrored here and the person's copy made beside it, both
4 * private, the crew on the copy (`bringToWork`); asked again, both are reused. Said by the
5 * origin's name and "your copy", as Talk says it.
6 */
7
8 import { bringToWork, bringWords, broughtWords } from "../../actions/bring.ts";
9 import type { Ctx, Screen } from "../app/app.ts";
10 import type { Session } from "../session.ts";
11 import { promptScreen } from "./common.ts";
12
13 export function bringWorkScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
14 return promptScreen(ctx, parent, {
15 title: "Work on a repository",
16 label: "Link, or owner/name",
17 placeholder: "https://github.com/octo/widgets",
18 hint: "Kept on GitHub or another forge you connected. It stays private here; the origin is unchanged.",
19 onSubmit: (repo) => {
20 if (repo.trim() === "") return "Paste the link, or owner/name.";
21 ctx.toast(`Bringing ${repo.trim()} in…`);
22 return bringToWork(f.app, f.user, { repo }).then((brought) => {
23 ctx.toast(brought.ok ? broughtWords(brought.value) : bringWords(brought.error), brought.ok ? "success" : "danger");
24 if (brought.ok) ctx.pop();
25 });
26 },
27 });
28 }
test/conversation-ask.test.ts +5
@@ -158,6 +158,11 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
158158 { repo: "marin/cakes", title: "Frosting", head: "frosting" },
159159 'Open a pull in marin/cakes: "Frosting".',
160160 ],
161 [
162 "bring",
163 { repo: "https://github.com/marin/cakes" },
164 "Bring https://github.com/marin/cakes in to work on: a mirror and your copy, both private here.",
165 ],
161166 [
162167 "new_app",
163168 { name: "cakes", sentence: "A shop for cakes" },
test/job-slices.test.ts +1
@@ -263,6 +263,7 @@ function jobs(): Record<string, () => unknown> {
263263 const UNTIMED: Record<string, string> = {
264264 "deploy-permit-ceiling": "a one-shot timer armed per deploy that only aborts it and resolves the race when a deploy outlives 30 minutes; permit-ceiling.test.ts and deploy-permit-ceiling.test.ts drive it with a short ceiling",
265265 "upstream-wait": "a one-shot timer that only aborts one proxied request when its app sends no headers in 30 s; no work of its own, cleared when the headers arrive; the upstream-wait tests drive it with a short wait",
266 "bring-wait": "a one-shot timer that only resolves a promise when a bring's mirror is still copying after 60 s, so the answer says it is copying (actions/bring.ts, bringToWork); no work of its own; talk-bring.test.ts brings a repository that settles first",
266267 "runner-wait": "one-shot timers that only resolve a promise: a runner's claim held open, a check's look at its job each second (checks/runner_jobs.ts, runner_step.ts) and the runner program's own pauses; off unless FORGE_CHECKS_PLACEMENT=runner, and checks-runner-placement.test.ts drives all three",
267268 "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock",
268269 "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly",
test/mcp-forge-protocol.test.ts +1
@@ -190,6 +190,7 @@ describe("the forge over MCP: protocol", () => {
190190 "events",
191191 "reports",
192192 "branches",
193 "bring",
193194 "builds",
194195 "commits",
195196 "wall",
test/mcp-talk-tools.test.ts +1
@@ -281,6 +281,7 @@ describe("every write Talk's agent is newly listed is held after it reads someon
281281 const WRITES: Readonly<Record<string, Record<string, unknown>>> = {
282282 assign: { repo: "alice/hostile", number: 1, kind: "issue", assignee: "mallory" },
283283 branches: { repo: "alice/hostile", name: "evil", action: "create" },
284 bring: { repo: "https://github.com/mallory/evil" },
284285 close: { repo: "alice/hostile", number: 1 },
285286 edit: { repo: "alice/hostile", number: 1, title: "pwned" },
286287 invite: { repo: "alice/hostile", who: "mallory" },
test/palette-roster.test.ts +2
@@ -96,6 +96,7 @@ test("a site-admin person is offered the whole roster", () => {
9696 ["new-app", "New app", "say what it does in a sentence; the crew starts on it"],
9797 ["new-app-template", "New app from a template", "copy a repository you can read, as the starting files"],
9898 ["bring-app", "Bring an app", "paste a link from another forge; it runs here"],
99 ["bring-work", "Work on a repository", "from GitHub or another forge: your private copy here, the crew on it"],
99100 ["new-org", "New organization", "an organization you own, for a client's apps"],
100101 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
101102 ["inventory", "What is left to bring over", "every repository on your connected accounts, what it holds, where its move stands"],
@@ -402,6 +403,7 @@ test("a member person is offered the signed-in roster without the admin entries"
402403 ["new-app", "New app", "say what it does in a sentence; the crew starts on it"],
403404 ["new-app-template", "New app from a template", "copy a repository you can read, as the starting files"],
404405 ["bring-app", "Bring an app", "paste a link from another forge; it runs here"],
406 ["bring-work", "Work on a repository", "from GitHub or another forge: your private copy here, the crew on it"],
405407 ["new-org", "New organization", "an organization you own, for a client's apps"],
406408 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
407409 ["inventory", "What is left to bring over", "every repository on your connected accounts, what it holds, where its move stands"],
test/talk-bring.test.ts added +293
@@ -0,0 +1,293 @@
1 /**
2 * Talk brings a repository kept elsewhere in to work on (#10262), proven with two forges: bob's
3 * forge holds bob/widgets; alice's forge, with a crew, has bob's forge connected as an origin.
4 * "Bring bob/widgets in" is held behind a confirm that says it stays private; the yes makes a
5 * private mirror and alice's private copy beside it, the crew seated on the copy; bringing it
6 * again makes nothing new; and "change the README", told on the mirror, ends in a crew pull on
7 * the copy, never an issue on bob's forge.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { sayYes } from "../src/actions/conversation_confirms.ts";
14 import { bringWait } from "../src/actions/bring.ts";
15 import { createRepo } from "../src/actions/repos.ts";
16 import { connectOrigin, startMirrorJob } from "../src/actions/origins.ts";
17 import { createApp, type App } from "../src/app.ts";
18 import { listCrewRoles } from "../src/core/agents.ts";
19 import { appendTurn, createConversation, listTurns } from "../src/core/conversations.ts";
20 import { waitingFor } from "../src/core/fence.ts";
21 import { listIssues } from "../src/core/issues.ts";
22 import { listPulls } from "../src/core/pulls.ts";
23 import { getRepo, listForks } from "../src/core/repos.ts";
24 import { createToken } from "../src/core/tokens.ts";
25 import { createUser, getUserByName, type User } from "../src/core/users.ts";
26 import { mintViaToken } from "../src/core/via_token.ts";
27 import type { Ctx } from "../src/http/context.ts";
28 import { serve, type Servers } from "../src/http/server.ts";
29 import { settled } from "../src/origins/jobs.ts";
30 import { syncsSettled } from "../src/origins/sync.ts";
31 import { createForgeApp, forgeCommands } from "../src/tui/forge.ts";
32 import { headlessTerminal } from "../src/tui/term/terminal.ts";
33 import { promote } from "./helpers/members.ts";
34 import { settleApp } from "./helpers/tui.ts";
35 import { seedAdmin } from "./helpers/admin.ts";
36 import { startStandInCrew, stopStandInCrew, type StandInCrew } from "./helpers/crew-standin.ts";
37 import { pollUntil } from "./helpers/poll.ts";
38 import { proveAll } from "./helpers/verified.ts";
39
40 let friendDir: string;
41 let friend: App;
42 let friendServers: Servers;
43 let w: StandInCrew;
44 let link = "";
45 let bobToken = "";
46 let rpc = 1;
47 /** A forge whose crew can run seats one on a new copy (`crewCanRun`): a model key says it can. */
48 const KEY = process.env["ANTHROPIC_API_KEY"];
49
50 const post = async (token: string, name: string, args: Record<string, unknown>) => {
51 const res = await fetch(`${w.servers.url}/mcp`, {
52 method: "POST",
53 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
54 body: JSON.stringify({ jsonrpc: "2.0", id: rpc++, method: "tools/call", params: { name, arguments: args } }),
55 });
56 const r = ((await res.json()) as { result: { content: { text: string }[]; isError?: boolean } }).result;
57 return { text: r.content[0]!.text, error: r.isError === true };
58 };
59
60 beforeAll(async () => {
61 process.env["ANTHROPIC_API_KEY"] = "test-key";
62 friendDir = await mkdtemp(join(tmpdir(), "forge-talk-bring-friend-"));
63 friend = createApp({ dataDir: friendDir, port: 0 });
64 friendServers = await serve(friend);
65 await seedAdmin(friend, { username: "bob", email: "[email protected]", password: "bob-passphrase-long" });
66 proveAll(friend);
67 const bob = getUserByName(friend.db, "bob")!;
68 bobToken = createToken(friend.db, bob.id, "t", "rw").token;
69 const auth = { "content-type": "application/json", authorization: `Bearer ${bobToken}` };
70 // Public there, so the copy's privacy here is the bring's doing.
71 expect((await fetch(`${friendServers.url}/api/v1/repos`, { method: "POST", headers: auth, body: JSON.stringify({ name: "widgets", visibility: "public" }) })).status).toBeLessThan(300);
72 expect((await fetch(`${friendServers.url}/api/v1/repos/bob/widgets/contents`, { method: "POST", headers: auth, body: JSON.stringify({ branch: "main", message: "first", files: [{ path: "README.md", content: "# widgets\n" }] }) })).status).toBeLessThan(300);
73 link = `${friendServers.url}/bob/widgets`;
74 for (const name of ["gadgets", "sprockets"]) {
75 expect((await fetch(`${friendServers.url}/api/v1/repos`, { method: "POST", headers: auth, body: JSON.stringify({ name, visibility: "public" }) })).status).toBeLessThan(300);
76 expect((await fetch(`${friendServers.url}/api/v1/repos/bob/${name}/contents`, { method: "POST", headers: auth, body: JSON.stringify({ branch: "main", message: "first", files: [{ path: "README.md", content: `# ${name}\n` }] }) })).status).toBeLessThan(300);
77 }
78
79 w = await startStandInCrew();
80 proveAll(w.app);
81 const connected = await connectOrigin(w.app, w.alice, { host: friendServers.url, token: bobToken });
82 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
83 });
84
85 afterAll(async () => {
86 if (KEY === undefined) delete process.env["ANTHROPIC_API_KEY"];
87 else process.env["ANTHROPIC_API_KEY"] = KEY;
88 await syncsSettled();
89 // Awaited, so no run of this crew is still writing when the next file starts.
90 await stopStandInCrew(w);
91 friendServers.stop();
92 friend.close();
93 await rm(friendDir, { recursive: true, force: true, maxRetries: 5 });
94 });
95
96 describe("bring, then tell: the crew works on the person's copy", () => {
97 test("Talk's bring is held; its sentence names the repository and says it stays private", async () => {
98 const c = createConversation(w.app.db, w.alice.id);
99 if (!c.ok) throw new Error(c.error);
100 const words = "bring bob/widgets in so the crew can work on it";
101 appendTurn(w.app.db, w.alice.id, c.value.id, { role: "person", text: words });
102 const via = `conversation:${c.value.id}`;
103 const minted = mintViaToken(w.app.db, w.alice.id, via, words, new Date(Date.now() + 600_000).toISOString());
104 if (!minted.ok) throw new Error(minted.error);
105 const held = await post(minted.value.token, "bring", { repo: link });
106 expect(held.text).toContain("needs_confirm");
107 expect(getRepo(w.app.db, "alice", "widgets")).toBeUndefined();
108 const turns = listTurns(w.app.db, w.alice.id, c.value.id, { limit: 50 });
109 const confirm = turns.ok ? turns.value.find((t) => t.role === "confirm") : undefined;
110 expect(confirm?.text).toContain("bob/widgets");
111 expect(confirm?.text).toContain("both private here");
112
113 // The person's yes brings it.
114 const waiting = waitingFor(w.app.db, w.alice.id).find((h) => h.via === via)!;
115 const url = new URL(w.servers.url);
116 const ctx: Ctx = { app: w.app, request: new Request(url.href), url, params: {}, auth: { user: w.alice, scope: undefined, via: "session" }, theme: undefined };
117 const yes = await sayYes(ctx, w.alice, waiting.id);
118 expect(yes.ok && yes.done).toBe(true);
119 const said = JSON.stringify(yes.ok ? yes.result : null);
120 expect(said).toContain("bob/widgets");
121 expect(said).toContain("your copy");
122 expect(said).not.toContain("widgets-work is");
123
124 const mirror = getRepo(w.app.db, "alice", "widgets")!;
125 const copy = getRepo(w.app.db, "alice", "widgets-work")!;
126 expect(mirror.origin).not.toBeNull();
127 expect(mirror.visibility).toBe("private");
128 expect(copy.origin).toBeNull();
129 expect(copy.forkParentId).toBe(mirror.id);
130 expect(copy.visibility).toBe("private");
131 expect(listCrewRoles(w.app.db, copy.id).some((r) => r.role === "builder")).toBe(true);
132 });
133
134 test("bringing it again reuses both and says so: no second copy", async () => {
135 const token = createToken(w.app.db, w.alice.id, "t", "rw").token;
136 for (const repo of [link, "bob/widgets"]) {
137 const again = await post(token, "bring", { repo });
138 expect(again.error).toBe(false);
139 const answer = JSON.parse(again.text) as { says: string; reused: { mirror: boolean; copy: boolean }; copy: string };
140 expect(answer.reused).toEqual({ mirror: true, copy: true });
141 expect(answer.says).toContain("already here");
142 expect(answer.copy).toBe("/alice/widgets-work");
143 }
144 const mirror = getRepo(w.app.db, "alice", "widgets")!;
145 expect(listForks(w.app.db, mirror.id).filter((r) => r.ownerId === w.alice.id).map((r) => r.name)).toEqual(["widgets-work"]);
146 expect(getRepo(w.app.db, "alice", "widgets-2")).toBeUndefined();
147 });
148
149 test("a change told on the mirror ends in a crew pull on the copy, and nothing on the origin", async () => {
150 const token = createToken(w.app.db, w.alice.id, "t", "rw").token;
151 const told = await post(token, "tell", { repo: "alice/widgets", text: "Make the README say hello" });
152 expect(told.error).toBe(false);
153 expect(JSON.parse(told.text).page).toContain("/alice/widgets-work/issues/");
154 const copy = getRepo(w.app.db, "alice", "widgets-work")!;
155 await pollUntil(() => listPulls(w.app.db, copy.id, { state: "all" }).length > 0, "a crew pull on the copy");
156 const pull = listPulls(w.app.db, copy.id, { state: "all" })[0]!;
157 expect(pull.title).toContain("README");
158 const mirror = getRepo(w.app.db, "alice", "widgets")!;
159 expect(listIssues(w.app.db, mirror.id, { state: "all" })).toEqual([]);
160 const theirs = getRepo(friend.db, "bob", "widgets")!;
161 expect(listIssues(friend.db, theirs.id, { state: "all" })).toEqual([]);
162 expect(listPulls(friend.db, theirs.id, { state: "all" })).toEqual([]);
163 });
164 });
165
166 /** A person on this forge with bob's account connected as their origin, and an rw token. */
167 let people = 0;
168 const person = async (proven = true): Promise<{ user: User; token: string; originId: string }> => {
169 const name = `p${String(++people)}`;
170 const made = await createUser(w.app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase" });
171 if (!made.ok) throw new Error(made.error);
172 promote(w.app.db, made.value);
173 if (proven) proveAll(w.app);
174 const connected = await connectOrigin(w.app, made.value, { host: friendServers.url, token: bobToken });
175 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
176 return { user: made.value, token: createToken(w.app.db, made.value.id, "t", "rw").token, originId: connected.value.id };
177 };
178
179 describe("bring keeps its promises", () => {
180 test("a mirror already here in public is made private by the bring, and the answer says so", async () => {
181 const p = await person();
182 const job = startMirrorJob(w.app, p.user, p.originId, "bob/gadgets");
183 if (!job.ok) throw new Error(String(job.error));
184 expect((await settled(job.value.id))?.stage).toBe("done");
185 expect(getRepo(w.app.db, p.user.username, "gadgets")!.visibility).toBe("public");
186 const brought = await post(p.token, "bring", { repo: `${friendServers.url}/bob/gadgets` });
187 expect(brought.error).toBe(false);
188 const answer = JSON.parse(brought.text) as { says: string; reused: { mirror: boolean } };
189 expect(answer.reused.mirror).toBe(true);
190 expect(answer.says).toContain("it is private now");
191 expect(getRepo(w.app.db, p.user.username, "gadgets")!.visibility).toBe("private");
192 expect(getRepo(w.app.db, p.user.username, "gadgets-work")!.visibility).toBe("private");
193 });
194
195 test("still copying when the wait ends: it says to ask again, and a later bring makes the copy", async () => {
196 const p = await person();
197 bringWait.ms = 0;
198 try {
199 const early = await post(p.token, "bring", { repo: `${friendServers.url}/bob/sprockets` });
200 expect(early.error).toBe(true);
201 expect(early.text).toContain("still being copied");
202 } finally {
203 bringWait.ms = 60_000;
204 }
205 // The next bring joins the copy still running (or finds it landed) and makes the person's copy.
206 const later = JSON.parse((await post(p.token, "bring", { repo: `${friendServers.url}/bob/sprockets` })).text) as { copy: string };
207 expect(later.copy).toBe(`/${p.user.username}/sprockets-work`);
208 expect(getRepo(w.app.db, p.user.username, "sprockets")!.visibility).toBe("private");
209 });
210
211 test("a repository the origin does not have fails in words, and nothing is made", async () => {
212 const p = await person();
213 const failed = await post(p.token, "bring", { repo: `${friendServers.url}/bob/nothing-here` });
214 expect(failed.error).toBe(true);
215 expect(getRepo(w.app.db, p.user.username, "nothing-here")).toBeUndefined();
216 expect(getRepo(w.app.db, p.user.username, "nothing-here-work")).toBeUndefined();
217 });
218
219 test("a mirror the person can no longer read is never reused or named", async () => {
220 const p = await person();
221 expect((await post(p.token, "bring", { repo: link })).error).toBe(false);
222 const theirs = getRepo(w.app.db, p.user.username, "widgets")!;
223 // Moved to another owner, private: this person can no longer read it.
224 w.app.db.query("UPDATE repo SET owner_id = ?1, visibility = 'private' WHERE id = ?2").run(w.bot.id, theirs.id);
225 const again = await post(p.token, "bring", { repo: link });
226 expect(again.text).not.toContain(theirs.id);
227 if (!again.error) expect((JSON.parse(again.text) as { mirror: string }).mirror).not.toBe(`/${w.bot.username}/widgets`);
228 });
229
230 test("a link or account id past 300 characters is refused in words", async () => {
231 const p = await person();
232 const long = await post(p.token, "bring", { repo: `${link}/${"x".repeat(300)}` });
233 expect(long.error).toBe(true);
234 expect(long.text).toContain("at most 300 characters");
235 expect((await post(p.token, "bring", { repo: link, origin: "o".repeat(301) })).text).toContain("at most 300 characters");
236 });
237
238 test("the crew, a person not yet verified and a stranger are refused through the MCP tool", async () => {
239 const bot = createToken(w.app.db, w.bot.id, "t", "rw").token;
240 const byBot = await post(bot, "bring", { repo: link });
241 expect(byBot.error).toBe(true);
242 expect(byBot.text).toContain("forbidden");
243 const fresh = await createUser(w.app.db, { origin: "seed", username: "unproven", email: "[email protected]", password: "a-good-passphrase" });
244 if (!fresh.ok) throw new Error(fresh.error);
245 promote(w.app.db, fresh.value);
246 const unproven = await post(createToken(w.app.db, fresh.value.id, "t", "rw").token, "bring", { repo: link });
247 expect(unproven.error).toBe(true);
248 expect(unproven.text.toLowerCase()).toContain("verif");
249 const res = await fetch(`${w.servers.url}/mcp`, {
250 method: "POST",
251 headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
252 body: JSON.stringify({ jsonrpc: "2.0", id: rpc++, method: "tools/call", params: { name: "bring", arguments: { repo: link } } }),
253 });
254 expect(JSON.stringify(await res.json())).not.toContain("your copy");
255 expect(getRepo(w.app.db, "unproven", "widgets")).toBeUndefined();
256 });
257
258 test("the terminal's Work on a repository brings it and toasts the same words", async () => {
259 const p = await person();
260 const terminal = headlessTerminal(160, 40);
261 const { app: tui, session } = createForgeApp(w.app, { sshUsername: p.user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: p.user }, { terminal, exitHooks: false, toastMs: 10 * 60_000 });
262 tui.start();
263 try {
264 await settleApp(tui);
265 forgeCommands(session)(tui.ctx).find((c) => c.id === "bring-work")!.run();
266 await settleApp(tui);
267 terminal.feed(`${link}\r`);
268 await pollUntil(() => getRepo(w.app.db, p.user.username, "widgets-work") !== undefined, "the copy");
269 await settleApp(tui);
270 expect(tui.screen.toText()).toContain("as your copy, private");
271 } finally {
272 tui.stop();
273 }
274 });
275
276 test("a tell on a mirror with no words makes no copy; a copy that cannot be made tells nothing", async () => {
277 const p = await person();
278 const job = startMirrorJob(w.app, p.user, p.originId, "bob/widgets");
279 if (!job.ok) throw new Error(String(job.error));
280 expect((await settled(job.value.id))?.stage).toBe("done");
281 const mirror = `${p.user.username}/widgets`;
282 const empty = await post(p.token, "tell", { repo: mirror, text: "" });
283 expect(empty.error).toBe(true);
284 expect(getRepo(w.app.db, p.user.username, "widgets-work")).toBeUndefined();
285 // A repository of their own already holds the copy's name: the fork cannot be made.
286 const made = await createRepo(w.app, p.user, { name: "widgets-work", visibility: "private" });
287 if (!made.ok) throw new Error(String(made.error));
288 const refused = await post(p.token, "tell", { repo: mirror, text: "Make the README say hello" });
289 expect(refused.error).toBe(true);
290 expect(refused.text).toContain("no_copy");
291 expect(listIssues(w.app.db, getRepo(w.app.db, p.user.username, "widgets")!.id, { state: "all" })).toEqual([]);
292 });
293 });
test/tui-bring.test.ts +29 −4
@@ -6,7 +6,9 @@ import { join } from "node:path";
66 import { createApp, type App } from "../src/app.ts";
77 import { createUser, type User } from "../src/core/users.ts";
88 import { createForgeApp, forgeCommands, Session } from "../src/tui/forge.ts";
9 import { bringScreen, bringWords } from "../src/tui/screens/bring.ts";
9 import { bringWords } from "../src/actions/bring.ts";
10 import { bringScreen } from "../src/tui/screens/bring.ts";
11 import { bringWorkScreen } from "../src/tui/screens/bringwork.ts";
1012 import { blank } from "../src/tui/screens/common.ts";
1113 import { headlessTerminal } from "../src/tui/term/terminal.ts";
1214 import { quietLogs } from "./helpers/globals.ts";
@@ -44,12 +46,35 @@ afterAll(async () => {
4446 await rm(dir, { recursive: true, force: true });
4547 });
4648
49 describe("work on a repository", () => {
50 test("owner/name with no account connected says where to connect one, as Talk does", async () => {
51 const terminal = headlessTerminal(140, 30);
52 const { app: tui, session } = createForgeApp(app, identity(alice), { terminal, exitHooks: false });
53 tui.start();
54 tui.ctx.push(bringWorkScreen(session, tui.ctx, blank("Work on a repository")));
55 try {
56 await settleApp(tui);
57 expect(tui.screen.toText()).toContain("Link, or owner/name");
58 terminal.feed("\r");
59 await settleApp(tui);
60 expect(tui.screen.toText()).toContain("Paste the link, or owner/name.");
61 terminal.feed("octo/widgets\r");
62 await settleApp(tui);
63 expect(tui.screen.toText()).toContain("/settings/origins");
64 } finally {
65 tui.stop();
66 }
67 });
68 });
69
4770 describe("the bring screen", () => {
4871 test("the palette offers it to a person, never to an agent or a guest", () => {
4972 const ids = (u?: User) => forgeCommands(new Session(app, identity(u)))({} as never).map((c) => c.id);
50 expect(ids(alice)).toContain("bring-app");
51 expect(ids({ ...alice, kind: "agent" })).not.toContain("bring-app");
52 expect(ids()).not.toContain("bring-app");
73 for (const id of ["bring-app", "bring-work"]) {
74 expect(ids(alice)).toContain(id);
75 expect(ids({ ...alice, kind: "agent" })).not.toContain(id);
76 expect(ids()).not.toContain(id);
77 }
5378 });
5479
5580 test("a link that is no repository, or a forge not connected, is answered in words", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs