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

A DXF drawing can be moved, scaled or have a layer removed, previewed, then saved as one commit, from the page and from MCP #17077

opened this

Merged 2d 2h ago, live in production

scout/forge:scout/17058-a-dxf-drawing-can-be-moved-scaled-or-hav → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/17058-a-dxf-drawing-can-be-moved-scaled-or-hav was merged into main as 63ed874.

Review

Sign in to review this change.
17 files changed +765 −12
docs/features/dxf-edit.md added +7
@@ -0,0 +1,7 @@
1 ---
2 topic: Files in the browser
3 row: Move, scale or trim a .dxf drawing
4 ---
5 # Change a DXF drawing
6
7 A writer sees a form under an ASCII `.dxf` (not over 2 MB): scale by a factor, move x and y, remove a layer. Preview draws the new drawing with its entity count before and after and writes nothing; Commit writes one commit, `p.dxf: remove layer DOORS, scale ×2`. `src/web/render/dxf_edit.ts` is the pure rewrite (only the values of codes 10/20, 11/21 on a LINE and the radius 40 of a CIRCLE or ARC change; every other line and line end is kept byte for byte; z is untouched, TEXT, blocks and dimensions are left as they were and counted); `src/actions/dxf_edit.ts` is the preview-or-commit action (`commitEdit`, shared with `mesh_edit.ts`); the page is the file edit route's `dxf` form. In the terminal the palette's "Move, scale or remove a layer of a DXF drawing" (`src/tui/screens/dxf_edit.ts`); an agent calls the MCP `dxf_edit` tool (`move: [dx, dy]`, `scale`, `removeLayer`; `dryRun: false` commits). Pinned by `test/dxf-edit.test.ts`. Not done: non-uniform scale, a turn, bulges and blocks.
docs/features/file-dxf.md +2
@@ -35,3 +35,5 @@ over. The readout is text in a live region, so a screen reader hears it.
3535 words (`measureDxfTyped`).
3636 - The script is `dxf-client.ts`, bundled once as `/assets/dxf-<hash>.js` and
3737 loaded only on a page with a drawing. The render caps are unchanged.
38
39 A writer can also change a drawing: see [dxf-edit.md](dxf-edit.md).
src/actions/contents.ts +2 −2
@@ -28,6 +28,7 @@ import {
2828 type CommitFilesError,
2929 type CommitResult,
3030 } from "../git/write.ts";
31 import { MAX_FILE_BYTES } from "../kernel/file_limit.ts";
3132 import { err, ok, type Result } from "../kernel/result.ts";
3233 import type { WriteThroughError } from "../origins/write-through.ts";
3334 import { requireWriter, type AccessError } from "./access.ts";
@@ -35,8 +36,7 @@ import { mirrorCopyWords } from "./mirror_copy.ts";
3536 import { createBranch, deleteBranch, originPush } from "./branches.ts";
3637 import { openPull as openPullAction } from "./pulls.ts";
3738
38 /** Per-file ceiling. Anything larger belongs in a push, not a JSON body. */
39 export const MAX_FILE_BYTES = 2 * 1024 * 1024;
39 export { MAX_FILE_BYTES };
4040 /** Per-commit ceiling, across every file in the edit. */
4141 export const MAX_COMMIT_BYTES = 10 * 1024 * 1024;
4242 /** A bound on fan-out, so one request cannot mean ten thousand blobs. */
src/actions/dxf_edit.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * Move, scale or remove a layer from a DXF drawing and (when asked) save it as one commit. The
3 * page's Preview and Commit buttons, the MCP `dxf_edit` tool and the terminal all call this, so
4 * what was previewed is what is committed: the gate (a writer only), the bounds on every number,
5 * the message and the protected-branch rule are one thing. The commit is `mesh_edit`'s
6 * (`commitEdit`).
7 */
8
9 import type { App } from "../app.ts";
10 import type { Repo } from "../core/repos.ts";
11 import type { User } from "../core/users.ts";
12 import { isSafeRef, isSafeTreePath } from "../git/guard.ts";
13 import { blobForRender } from "../git/read.ts";
14 import { repoDir } from "../git/repos.ts";
15 import { err, ok, type Result } from "../kernel/result.ts";
16 import { draw, parseDxf } from "../web/render/dxf.ts";
17 import { checkLayer, editDxf, type DxfEdit } from "../web/render/dxf_edit.ts";
18 import { requireWriter } from "./access.ts";
19 import { MAX_FILE_BYTES, type EditFilesError, type EditResult } from "./contents.ts";
20 import { commitEdit, parseNumber } from "./mesh_edit.ts";
21
22 /** The form's raw text, unchecked. */
23 export interface DxfForm {
24 readonly ref: string;
25 readonly path: string;
26 readonly dx: string;
27 readonly dy: string;
28 readonly factor: string;
29 readonly layer: string;
30 }
31
32 export interface DxfEdited {
33 readonly bytes: Uint8Array;
34 /** The drawing as the viewer draws it: an inline SVG. */
35 readonly svg: string;
36 readonly before: number;
37 readonly after: number;
38 readonly left: number;
39 }
40
41 export type DxfEditError = { readonly kind: "refused"; readonly why: string } | { readonly kind: "missing" } | EditFilesError;
42
43 export const isDxfPath = (path: string): boolean => /\.dxf$/i.test(path) && isSafeTreePath(path);
44
45 /** The form's text as one bounded edit, or the sentence that refuses it. */
46 export function parseDxfForm(form: DxfForm): { ok: true; edit: DxfEdit } | { ok: false; why: string } {
47 let scale: number | undefined;
48 if (form.factor.trim() !== "") {
49 const f = parseNumber("The scale factor", form.factor, { min: 0.001, max: 1000 });
50 if (!f.ok) return f;
51 if (f.value !== 1) scale = f.value;
52 }
53 const d = [form.dx, form.dy].map((t, i) => (t.trim() === "" ? { ok: true as const, value: 0 } : parseNumber(`Move ${"xy"[i]}`, t)));
54 for (const r of d) if (!r.ok) return r;
55 const [dx, dy] = d.map((r) => (r.ok ? r.value : 0)) as [number, number];
56 let removeLayer: string | undefined;
57 if (form.layer.trim() !== "") {
58 const l = checkLayer(form.layer);
59 if (!l.ok) return l;
60 removeLayer = l.value;
61 }
62 const edit: DxfEdit = {
63 ...(scale !== undefined ? { scale } : {}),
64 ...(dx !== 0 || dy !== 0 ? { move: [dx, dy] as const } : {}),
65 ...(removeLayer !== undefined ? { removeLayer } : {}),
66 };
67 if (Object.keys(edit).length === 0) return { ok: false, why: "Nothing to change: give a scale, a move or a layer to remove." };
68 return { ok: true, edit };
69 }
70
71 /** The commit subject: what was done, in the order it was done. */
72 export function dxfMessage(edit: DxfEdit, path: string): string {
73 const parts: string[] = [];
74 if (edit.removeLayer !== undefined) parts.push(`remove layer ${edit.removeLayer}`);
75 if (edit.scale !== undefined) parts.push(`scale ×${edit.scale}`);
76 if (edit.move !== undefined) parts.push(`move ${edit.move.join(", ")}`);
77 const leaf = path.slice(path.lastIndexOf("/") + 1);
78 return `${leaf}: ${parts.join(", ")}`.slice(0, 120);
79 }
80
81 /** Read, change and (with `commit`) save. A preview returns the drawing and writes nothing. */
82 export async function editDrawing(
83 app: App,
84 actor: User | undefined,
85 repo: Repo,
86 form: DxfForm,
87 commit: boolean,
88 ): Promise<Result<{ readonly edited: DxfEdited; readonly message: string; readonly landed?: EditResult }, DxfEditError>> {
89 const writer = requireWriter(app, actor, repo);
90 if (!writer.ok) return writer;
91 const { ref, path } = form;
92 if (!isSafeRef(ref)) return err({ kind: "missing" });
93 if (!isDxfPath(path)) return err({ kind: "refused", why: "Only a .dxf file can be changed here." });
94 const parsed = parseDxfForm(form);
95 if (!parsed.ok) return err({ kind: "refused", why: parsed.why });
96
97 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
98 const blob = await blobForRender(dir, ref, path, MAX_FILE_BYTES);
99 if (blob.kind === "too_large")
100 return err({ kind: "refused", why: `This DXF is over ${MAX_FILE_BYTES / 1048576} MB, more than one commit here can hold; change it in a CAD tool and commit it with git.` });
101 if (blob.kind === "missing") return err({ kind: "missing" });
102 const made = editDxf(blob.body, parsed.edit);
103 if (!made.ok) return err({ kind: "refused", why: made.why });
104 const drawing = parseDxf(made.value.text);
105 if ("error" in drawing) return err({ kind: "refused", why: `The changed drawing cannot be drawn: ${drawing.error}.` });
106 const d = draw(drawing.shapes);
107 const svg = `<svg viewBox="0 0 ${d.width} ${d.height}" role="img" aria-label="The changed drawing" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none">${d.body}</svg>`;
108 const edited: DxfEdited = { bytes: new TextEncoder().encode(made.value.text), svg, before: made.value.before, after: made.value.after, left: made.value.left };
109 const message = dxfMessage(parsed.edit, path);
110 if (!commit) return ok({ edited, message });
111 const landed = await commitEdit(app, writer.value, repo, { ref, path, message, bytes: edited.bytes, branchPrefix: "dxf" });
112 if (!landed.ok) return landed;
113 return ok({ edited, message, landed: landed.value });
114 }
src/actions/mesh_edit.ts +21 −6
@@ -203,19 +203,34 @@ export async function editMesh(
203203 const message = editMessage(parsed.edit, path);
204204 if (!commit) return ok({ edited: edited.value, message });
205205
206 const landed = await commitEdit(app, writer.value, repo, { ref, path, message, bytes: edited.value.bytes, branchPrefix: "mesh" });
207 if (!landed.ok) return landed;
208 return ok({ edited: edited.value, message, landed: landed.value });
209 }
210
211 /**
212 * Save one file's new bytes as one commit: on the branch `ref` when it is one a writer may commit
213 * to, else on a new branch with a pull. The mesh and the drawing edits share it.
214 */
215 export async function commitEdit(
216 app: App,
217 writer: User,
218 repo: Repo,
219 at: { readonly ref: string; readonly path: string; readonly message: string; readonly bytes: Uint8Array; readonly branchPrefix: string },
220 ) {
221 const { ref, path, message } = at;
222 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
206223 const isBranch = (await refTip(dir, `refs/heads/${ref}`)) !== undefined;
207 const mustBranch = !isBranch || (ref === repo.defaultBranch && repo.protectDefault && !canAdmin(app.db, repo, writer.value));
224 const mustBranch = !isBranch || (ref === repo.defaultBranch && repo.protectDefault && !canAdmin(app.db, repo, writer));
208225 const leaf = (path.split("/").pop() ?? path).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
209 const landed = await editFiles(app, writer.value, repo, {
226 return editFiles(app, writer, repo, {
210227 // A tag or commit cannot be a pull's base: its edit forks from the default branch.
211228 branch: isBranch ? ref : repo.defaultBranch,
212229 base: isBranch ? ref : repo.defaultBranch,
213230 message,
214 files: [{ path, content: edited.value.bytes }],
231 files: [{ path, content: at.bytes }],
215232 ...(mustBranch
216 ? { newBranch: `${writer.value.username}/mesh-${leaf === "" ? "file" : leaf}-${Date.now().toString(36)}`, openPull: { title: message, body: "" } }
233 ? { newBranch: `${writer.username}/${at.branchPrefix}-${leaf === "" ? "file" : leaf}-${Date.now().toString(36)}`, openPull: { title: message, body: "" } }
217234 : {}),
218235 });
219 if (!landed.ok) return landed;
220 return ok({ edited: edited.value, message, landed: landed.value });
221236 }
src/http/mcp/tools/dxf_edit.ts added +61
@@ -0,0 +1,61 @@
1 import { editMessage } from "../../../actions/edit_words.ts";
2 import { editDrawing, type DxfForm } from "../../../actions/dxf_edit.ts";
3 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer, str } from "../shared.ts";
4
5 const num = (v: unknown): string => (typeof v === "number" && Number.isFinite(v) ? String(v) : "");
6
7 export const tool: Tool = {
8 name: "dxf_edit",
9 doc: "`{ repo, branch, path, move?: [dx, dy], scale?, removeLayer?, dryRun? }`: move, scale about the origin or drop a layer of an ASCII .dxf; previews the drawing's entity count, `dryRun: false` commits it as one commit",
10 description: "Move, scale or remove a layer of a .dxf drawing; dryRun:false commits.",
11 inputSchema: {
12 type: "object",
13 properties: {
14 repo: REPO_ARG,
15 branch: { type: "string" },
16 path: { type: "string" },
17 move: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2 },
18 scale: { type: "number" },
19 removeLayer: { type: "string", maxLength: 80 },
20 dryRun: { type: "boolean" },
21 },
22 required: ["repo", "branch", "path"],
23 },
24 writes: true,
25 dryByDefault: true,
26 async run(ctx, user, args) {
27 const repo = repoArg(ctx, user, args);
28 if (isAnswer(repo)) return repo;
29 const { branch, path, move, scale, removeLayer } = args;
30 if (typeof branch !== "string" || typeof path !== "string") return bad("invalid", "branch and path are strings");
31 const form: DxfForm = { ref: branch, path, dx: "", dy: "", factor: "", layer: "" };
32 let f = form;
33 if (move !== undefined) {
34 if (!Array.isArray(move) || move.length !== 2 || move.some((v) => num(v) === "")) return bad("invalid", "move is [x, y], two numbers");
35 f = { ...f, dx: num(move[0]), dy: num(move[1]) };
36 }
37 if (scale !== undefined) {
38 if (num(scale) === "") return bad("invalid", "scale is a finite number");
39 f = { ...f, factor: num(scale) };
40 }
41 if (removeLayer !== undefined) {
42 if (typeof removeLayer !== "string") return bad("invalid", "removeLayer is a layer name");
43 f = { ...f, layer: str(removeLayer) };
44 }
45 const done = await editDrawing(ctx.app, user, repo, f, args["dryRun"] === false);
46 if (!done.ok) {
47 const e = done.error;
48 if (typeof e === "string") return bad(e, e === "not_found" ? "no such repository" : "this is not yours to write");
49 if (e.kind === "refused") return bad("refused", e.why);
50 if (e.kind === "missing") return bad("not_found", "no such branch or file");
51 return bad(e.kind, editMessage(e.kind));
52 }
53 const { edited, message, landed } = done.value;
54 const base = { entitiesBefore: edited.before, entitiesAfter: edited.after, untouched: edited.left, svg: edited.svg, message };
55 // The page's words: "The new drawing" to preview, "Committed to <branch>" after.
56 if (landed === undefined)
57 return good({ says: `The new drawing: ${edited.before} entities before, ${edited.after} after. ${message}. Send dryRun: false to commit it.`, ...base });
58 const says = landed.pull !== undefined ? `Committed to ${landed.branch} and opened this pull request.` : `Committed to ${landed.branch}.`;
59 return good({ says, ...base, commit: landed.commit.commitOid, branch: landed.branch, ...(landed.pull !== undefined ? { pull: landed.pull.number } : {}) });
60 },
61 };
src/http/mcp/tools/index.ts +1
@@ -62,6 +62,7 @@ export { tool as desk } from "./desk.ts";
6262 export { tool as detach } from "./detach.ts";
6363 export { tool as drills } from "./drills.ts";
6464 export { tool as drop } from "./drop.ts";
65 export { tool as dxf_edit } from "./dxf_edit.ts";
6566 export { tool as economics } from "./economics.ts";
6667 export { tool as edit } from "./edit.ts";
6768 export { tool as egress_grants } from "./egress_grants.ts";
src/kernel/file_limit.ts added +2
@@ -0,0 +1,2 @@
1 /** Per-file ceiling for one commit. Anything larger belongs in a push, not a JSON body. */
2 export const MAX_FILE_BYTES = 2 * 1024 * 1024;
src/tui/screens/dxf_edit.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * Move, scale or drop a layer of a DXF drawing, in the terminal: the same action as the file page's
3 * form (`actions/dxf_edit.ts`), so the same gate (a writer only), bounds, commit message and
4 * protected-branch rule.
5 */
6
7 import { requireWriter } from "../../actions/access.ts";
8 import { editDrawing, isDxfPath, type DxfForm } from "../../actions/dxf_edit.ts";
9 import type { Repo } from "../../core/repos.ts";
10 import type { Ctx, Screen } from "../app/app.ts";
11 import type { Command } from "../app/palette.ts";
12 import type { Session } from "../session.ts";
13 import { later, promptScreen } from "./common.ts";
14
15 /** The palette's command while a repository is open and this viewer may write to it. */
16 export function dxfEditCommands(f: Session, ctx: Ctx, repo: Repo | undefined, parent: () => Screen): Command[] {
17 if (repo === undefined || !requireWriter(f.app, f.user, repo).ok) return [];
18 const ask = (label: string, next: (v: string) => string | undefined | Promise<void>): Screen =>
19 promptScreen(ctx, parent(), { title: "Edit a DXF drawing", label, value: "", hint: "", onSubmit: next });
20 return [
21 {
22 id: "dxf-edit",
23 title: `${repo.ownerName}/${repo.name} — Move, scale or remove a layer of a DXF drawing`,
24 hint: "change a .dxf file and save it as a commit",
25 run: () =>
26 ctx.push(
27 promptScreen(ctx, parent(), {
28 title: "Edit a DXF drawing",
29 label: "Path of the .dxf file",
30 placeholder: "plans/part.dxf",
31 onSubmit: (path) => {
32 if (!isDxfPath(path)) return "Give the path of a .dxf file.";
33 return later(ctx, () =>
34 ask("Scale factor, like 2 or 0.5 (blank: none)", (factor) =>
35 later(ctx, () =>
36 ask("Move dx dy, like 10 0 (blank: none)", (move) =>
37 later(ctx, () =>
38 ask("Layer to remove (blank: none)", async (layer) => {
39 const [dx = "", dy = ""] = move.trim().split(/\s+/);
40 const form: DxfForm = { ref: repo.defaultBranch, path, factor, dx, dy, layer };
41 const done = await editDrawing(f.app, f.user, repo, form, true);
42 if (done.ok) {
43 const landed = done.value.landed;
44 ctx.toast(landed?.pull === undefined ? `Committed to ${landed?.branch ?? repo.defaultBranch}.` : `Opened a pull from ${landed.branch}.`);
45 return;
46 }
47 const e = done.error;
48 ctx.toast(
49 typeof e === "object" && e.kind === "refused" ? e.why : typeof e === "object" && e.kind === "missing" ? "No such file." : "That edit could not be saved.",
50 "danger",
51 );
52 }),
53 ),
54 ),
55 ),
56 ),
57 );
58 },
59 }),
60 ),
61 },
62 ];
63 }
src/tui/screens/workspace.ts +2
@@ -240,6 +240,7 @@ import { deskCommands } from "./desk.ts";
240240 import { landCommands } from "./landasis.ts";
241241 import { shiftCommands } from "./subtitle_shift.ts";
242242 import { meshEditCommands } from "./mesh_edit.ts";
243 import { dxfEditCommands } from "./dxf_edit.ts";
243244 import { dataImportCommands } from "./dataimport.ts";
244245 import { dataMoveCommands } from "./datamove.ts";
245246 import { jobsCommands } from "./jobs.ts";
@@ -2478,6 +2479,7 @@ export function workspaceScreen(
24782479 ...landCommands(f, ctx, repo),
24792480 ...shiftCommands(f, ctx, repo, () => screen),
24802481 ...meshEditCommands(f, ctx, repo, () => screen),
2482 ...dxfEditCommands(f, ctx, repo, () => screen),
24812483 ...dataImportCommands(f, ctx, repo),
24822484 ...dataMoveCommands(f, ctx, repo),
24832485 ...jobsCommands(f, ctx, repo),
src/web/pages/edit.ts +41 −1
@@ -22,6 +22,7 @@ import { fileKind, NO_BYTES } from "../render/kinds.ts";
2222 import { editFiles, fileAt, MAX_FILE_BYTES } from "../../actions/contents.ts";
2323 import { editMesh, type MeshForm } from "../../actions/mesh_edit.ts";
2424 import { sizeText } from "../render/mesh.ts";
25 import { editDrawing, type DxfForm } from "../../actions/dxf_edit.ts";
2526 import { shiftSubtitles } from "../../actions/subtitle_shift.ts";
2627 import { contribute } from "../../actions/contribute.ts";
2728 import { NO_WRITE_ACCESS } from "../../actions/pull_words.ts";
@@ -951,7 +952,7 @@ function shiftRefused(ctx: Ctx, scope: RepoScope, ref: string, path: string, why
951952 palette: scope.palette,
952953 body: html`${pageHead("Nothing was shifted")}
953954 <p role="alert">${why}</p>
954 <p>${btn("Back to the file", { href: `${scope.base}/blob/${encodeURIComponent(ref)}/${path}`, variant: "primary" })}</p>`,
955 <p>${btn("See the drawing as it is", { href: `${scope.base}/blob/${encodeURIComponent(ref)}/${path}`, variant: "primary" })}</p>`,
955956 },
956957 400,
957958 );
@@ -1027,6 +1028,44 @@ async function meshSubmit(ctx: Ctx, scope: RepoScope, repo: Repo, form: Form): P
10271028 return flashTo(ctx, `${scope.base}/blob/${encodeURIComponent(landed.branch)}/${path}`, { message: `Committed to ${landed.branch}.` });
10281029 }
10291030
1031 /** The DXF form: Preview draws the new drawing and asks again; Commit writes it as one commit. */
1032 async function dxfSubmit(ctx: Ctx, scope: RepoScope, repo: Repo, form: Form): Promise<Response> {
1033 const ref = formValue(form, "ref");
1034 const path = formValue(form, "path").trim().replace(/^\/+/, "");
1035 const fields: DxfForm = { ref, path, factor: formValue(form, "factor"), dx: formValue(form, "dx"), dy: formValue(form, "dy"), layer: formValue(form, "layer") };
1036 const done = await editDrawing(ctx.app, ctx.auth.user, repo, fields, formValue(form, "do") === "save");
1037 if (!done.ok) {
1038 const e = done.error;
1039 if (typeof e === "object" && e.kind === "refused") return shiftRefused(ctx, scope, ref, path, e.why);
1040 if (typeof e === "object" && e.kind === "missing") return notFoundPage(ctx);
1041 if (e === "not_found" || e === "unauthorized") return notFoundPage(ctx);
1042 return shiftRefused(ctx, scope, ref, path, editErrorText(e));
1043 }
1044 const { edited, landed } = done.value;
1045 if (landed === undefined) {
1046 const hidden = Object.entries(fields).map(([k, v]) => html`<input type="hidden" name="${k}" value="${v}">`);
1047 return page({
1048 ctx,
1049 title: "The new drawing",
1050 crumbs: scope.crumbs,
1051 palette: scope.palette,
1052 body: html`${pageHead("The new drawing")}
1053 <p>${done.value.message}</p>
1054 <figure class="dxf-view">${raw(edited.svg)}</figure>
1055 <dl class="status-rows"><div class="status-row"><dt>Entities before</dt><dd>${edited.before.toLocaleString("en")}</dd></div>
1056 <div class="status-row"><dt>Entities after</dt><dd>${edited.after.toLocaleString("en")}</dd></div></dl>
1057 <form method="post" action="${scope.base}/edit">
1058 <input type="hidden" name="dxf" value="1"><input type="hidden" name="do" value="save">${hidden}

The preview page sets the facts as row-facts, but the drawing page uses status-rows for the same kind of fact. Use the one the DXF page already uses. The page also never shows the drawing as it was, so the preview cannot be compared with the original. Show the before beside the after, or link back to it.

1059 <p>${btn("Commit", { type: "submit", variant: "primary" })}
1060 ${btn("Back to the file", { href: `${scope.base}/blob/${encodeURIComponent(ref)}/${path}`, variant: "outline" })}</p>
1061 </form>`,
1062 });
1063 }
1064 if (landed.pull !== undefined)
1065 return flashTo(ctx, `${scope.base}/pulls/${landed.pull.number}`, { message: `Committed to ${landed.branch} and opened this pull request.` });
1066 return flashTo(ctx, `${scope.base}/blob/${encodeURIComponent(landed.branch)}/${path}`, { message: `Committed to ${landed.branch}.` });
1067 }
1068
10301069 /**
10311070 * POST /:owner/:name/edit — the one write.
10321071 *
@@ -1043,6 +1082,7 @@ export async function editSubmit(ctx: Ctx): Promise<Response> {
10431082 if (!scope.caps.write) return notFoundPage(ctx);
10441083 if (form.has("shift")) return shiftSubmit(ctx, scope, repo, form);
10451084 if (form.has("mesh")) return meshSubmit(ctx, scope, repo, form);
1085 if (form.has("dxf")) return dxfSubmit(ctx, scope, repo, form);
10461086
10471087 const ref = formValue(form, "ref");
10481088 const path = formValue(form, "path").trim().replace(/^\/+/, "");
src/web/render/dxf.ts +23 −2
@@ -15,7 +15,8 @@
1515 import { html, raw } from "../html.ts";
1616 import type { Rendered, RenderInput } from "./renderers.ts";
1717 import { RENDER_CAP } from "./kinds.ts";
18 import { fileSize } from "../ui.ts";
18 import { btn, field, fileSize } from "../ui.ts";
19 import { MAX_FILE_BYTES } from "../../kernel/file_limit.ts";
1920 import { within } from "./bounds.ts";
2021 import { dxfUnitName, type ViewFrame, measureXY, parseTwoPoints2d, unitNote } from "./measure.ts";
2122 import { dxfAssetPath } from "./dxf-asset.ts";
@@ -246,12 +247,32 @@ export function dxf(input: RenderInput): Rendered {
246247 const label = `Drawing of ${plural(total, "entity").replace("entitys", "entities")}`;
247248 const unit = dxfUnitName(parsed.units);
248249 const f = drawn.frame;
250 // A writer sees the edit form under a drawing a commit can hold.
251 const shift = input.shift;
252 const edit =
253 shift === undefined
outdated

The 2 MB limit is written as 2 * 1024 * 1024 here and again in src/web/render/dxf_edit.ts and src/actions/dxf_edit.ts (the error text). Import MAX_FILE_BYTES from actions/contents.ts so there is one limit.

254 ? html``
255 : input.size > MAX_FILE_BYTES
256 ? html`<p class="muted small">This DXF is over 2 MB, more than one commit here can hold: change it in a CAD tool and commit it with git.</p>`
257 : html`<form method="post" action="${shift.action}" class="mt">
outdated

The dxf-edit class has no rule in the stylesheet. Use only the named components (mt and stack are enough) and drop it. The form sits inside the <figure class="dxf-view">, so the drawing's figure now holds a mutation form. Put the form after the figure.

258 <input type="hidden" name="ref" value="${shift.ref}">
259 <input type="hidden" name="path" value="${shift.path}">
260 <input type="hidden" name="dxf" value="1">
261 <div class="stack">
262 ${field({ name: "factor", label: "Scale by a factor", placeholder: "2 or 0.5", autocomplete: "off" })}
263 ${field({ name: "dx", label: "Move x", placeholder: "0", autocomplete: "off" })}
264 ${field({ name: "dy", label: "Move y", placeholder: "0", autocomplete: "off" })}
265 ${field({ name: "layer", label: "Remove layer", placeholder: parsed.layers[0] ?? "0", autocomplete: "off" })}
266 </div>
267 <p>${btn("Preview the new drawing", { type: "submit", name: "do", value: "preview", variant: "outline" })}
268 ${btn("Commit", { type: "submit", name: "do", value: "save", variant: "primary" })}</p>
269 </form>`;
249270 const content = html`<figure class="dxf-view" data-measure data-module="${dxfAssetPath()}" data-min-x="${f.minX}" data-max-y="${f.maxY}" data-scale="${f.scale}" data-pad="${f.pad}" data-unit="${unit ?? ""}">
250271 <svg viewBox="0 0 ${drawn.width} ${drawn.height}" role="img" aria-label="${label}" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none">${raw(drawn.body)}</svg>
251272 <p class="small" id="dxf-readout" data-readout aria-live="polite">${unitNote(unit)}</p>
252273 <p class="muted small">Lines, circles, arcs and polylines are drawn; other entities are only counted.${parsed.dropped > 0 ? ` ${parsed.dropped.toLocaleString("en")} more past the first ${ENTITY_CAP.toLocaleString("en")} are not drawn.` : ""}</p>
253274 <dl class="status-rows">${facts.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}</dl>
254 </figure>`;
275 </figure>${edit}`;
255276 return { content, lines: 0, summary: `${plural(total, "entity").replace("entitys", "entities")} · ${fileSize(input.size)}` };
256277 }
257278
src/web/render/dxf_edit.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * Change an ASCII DXF's ENTITIES: move, scale about the origin, or remove a layer. Pure: text in,
3 * text out. The file is a list of (group code, value) line pairs and only the values this changes
4 * are rewritten; every other line, its line ends and its order are kept byte for byte.
5 *
6 * What moves and scales: LINE, CIRCLE, ARC, LWPOLYLINE, POINT (codes 10/20, and 11/21 on a LINE),
7 * and under scale the radius (40) of a CIRCLE or ARC. Arcs keep their angles: the scale is uniform.
8 * Every other entity (text, blocks, dimensions, hatches) is left as it was and counted in `left`,
9 * so the caller can say so. The z coordinate is not touched.
10 */
11
12 import { MAX_FILE_BYTES } from "../../kernel/file_limit.ts";
13 import { within } from "./bounds.ts";
14
15 export interface DxfEdit {
16 /** Scale about the origin by this factor (applied before the move). */
17 readonly scale?: number;
18 readonly move?: readonly [number, number];
19 /** Drop every entity on this layer. */
20 readonly removeLayer?: string;
21 }
22
outdated

DxfEdited is declared here and again in src/actions/dxf_edit.ts with different fields. Rename one, for example DxfRewrite, so a search finds one thing.

23 export interface DxfRewrite {
24 readonly text: string;
25 /** Entities before and after (a removed layer's are gone). */
26 readonly before: number;
27 readonly after: number;
28 /** Entities of a type this does not move or scale, kept as they were. */
29 readonly left: number;
30 }
31
32 /** A coordinate past this is corrupt (the viewer's own limit). */
33 export const COORD_LIMIT = 1e9;
34 export const LAYER_CHARS = 80;
35
36 const MOVES = new Set(["LINE", "CIRCLE", "ARC", "LWPOLYLINE", "POINT"]);
37
38 /** The layer name as written, or the sentence that says why not. */
39 export function checkLayer(name: string): { ok: true; value: string } | { ok: false; why: string } {
40 const v = name.trim();
41 if (v === "") return { ok: false, why: "Name the layer to remove." };
42 if (v.length > LAYER_CHARS) return { ok: false, why: `A layer name is at most ${LAYER_CHARS} characters.` };
43 // eslint-disable-next-line no-control-regex
44 if (/[\u0000-\u001f\u007f]/.test(v)) return { ok: false, why: "A layer name has no control characters." };
45 return { ok: true, value: v };
46 }
47
48 /** A number written the way a DXF reader reads it: no exponent, no float dust. */
49 function written(n: number): string {
50 const r = Number(n.toPrecision(15));
51 if (r === 0) return "0";
52 const s = String(r);
53 if (!/e/i.test(s)) return s;
54 return r.toFixed(12).replace(/\.?0+$/, "") || "0";
55 }
56
57 /** Apply `edit`; `ok: false` says why it cannot. */
58 export function editDxf(source: Uint8Array, edit: DxfEdit): { ok: true; value: DxfRewrite } | { ok: false; why: string } {
59 if (source.subarray(0, 8192).includes(0)) return { ok: false, why: "This is a binary DXF; only ASCII DXF can be changed here." };
60 let text: string;
61 try {
62 text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(source);
63 } catch {
64 return { ok: false, why: "This DXF is not UTF-8 text." };
65 }
66 const factor = edit.scale ?? 1;
67 const [dx, dy] = edit.move ?? [0, 0];
68 if (![factor, dx, dy].every(Number.isFinite) || factor <= 0) return { ok: false, why: "The scale must be greater than zero, and every number finite." };
69 let layer: string | undefined;
70 if (edit.removeLayer !== undefined) {
71 const c = checkLayer(edit.removeLayer);
72 if (!c.ok) return c;
73 layer = c.value;
74 }
75
76 // Alternating content and line end, so joining them again is the file.
77 const parts = text.split(/(\r\n|\n|\r)/);
78 const val = (pair: number): string | undefined => parts[pair * 4 + 2];
79 const code = (pair: number): number => Number((parts[pair * 4] ?? "").trim());
80 const pairs = Math.floor((parts.length + 1) / 4);
81
82 // Entities: [first pair, end pair) inside the ENTITIES section.
83 const ents: { type: string; from: number; to: number; layer: string }[] = [];
84 let sawEntities = false;
85 let inEntities = false;
86 let expectName = false;
87 let cur: (typeof ents)[number] | undefined;
88 for (let i = 0; i < pairs; i++) {
89 const c = code(i);
90 if (!Number.isInteger(c)) return { ok: false, why: "This is not group-code, value pairs." };
91 const v = (val(i) ?? "").trim();
92 if (c === 0) {
93 if (cur !== undefined) {
94 cur.to = i;
95 ents.push(cur);
96 cur = undefined;
97 }
98 if (v === "EOF") break;
99 if (v === "SECTION") {
100 expectName = true;
101 inEntities = false;
102 } else if (v === "ENDSEC") inEntities = false;
103 else if (inEntities) cur = { type: v, from: i, to: i + 1, layer: "0" };
104 continue;
105 }
106 if (expectName && c === 2) {
107 expectName = false;
108 inEntities = v === "ENTITIES";
109 if (inEntities) sawEntities = true;
110 continue;
111 }
112 if (cur !== undefined && c === 8) cur.layer = v;
113 }
114 if (!sawEntities) return { ok: false, why: "This DXF has no ENTITIES section." };
115
116 const drop = new Set<number>();
117 let removed = 0;
118 if (layer !== undefined) {
119 for (const e of ents) if (e.layer === layer) {
120 for (let i = e.from; i < e.to; i++) drop.add(i);
121 removed++;
122 }
123 if (removed === 0) return { ok: false, why: `No entity is on layer ${layer}.` };
124 if (removed === ents.length) return { ok: false, why: `Layer ${layer} holds every entity: removing it would leave an empty drawing.` };
125 }
126
127 let left = 0;
128 for (const e of ents) {
129 if (drop.has(e.from)) continue;
130 if (!MOVES.has(e.type)) {
131 left++;
132 continue;
133 }
134 if (factor === 1 && dx === 0 && dy === 0) continue;
135 for (let i = e.from + 1; i < e.to; i++) {
136 const c = code(i);
137 const isX = c === 10 || (c === 11 && e.type === "LINE");
138 const isY = c === 20 || (c === 21 && e.type === "LINE");
139 const isR = c === 40 && (e.type === "CIRCLE" || e.type === "ARC");
140 if (!isX && !isY && !isR) continue;
141 const n = within(val(i), COORD_LIMIT);
142 if (n === undefined) {
143 // Text where a number belongs is not ours to change; a number past the limit is corrupt.
144 const t = (val(i) ?? "").trim();
145 if (t !== "" && Number.isFinite(Number(t))) return { ok: false, why: "A coordinate in this drawing is out of range." };
146 continue;
147 }
148 const next = isR ? n * factor : n * factor + (isX ? dx : dy);
149 if (!Number.isFinite(next) || Math.abs(next) > COORD_LIMIT) return { ok: false, why: "That change takes a coordinate out of range." };
150 parts[i * 4 + 2] = written(next);
151 }
152 }
153
154 const out: string[] = [];
155 for (let i = 0; i < parts.length; i++) if (!drop.has(Math.floor(i / 4)) || i >= pairs * 4) out.push(parts[i]!);
156 const result = out.join("");
157 if (new TextEncoder().encode(result).length > MAX_FILE_BYTES) return { ok: false, why: "The changed file is over 2 MB, more than one commit here can hold." };
158 return { ok: true, value: { text: result, before: ents.length, after: ents.length - removed, left } };
159 }
test/conversation-confirm.test.ts +1 −1
@@ -125,7 +125,7 @@ describe("the one list of what asks first", () => {
125125 const NOT_ASKED = new Set([
126126 "access", "account_requests", "app_flags", "apps", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide", "atlas",
127127 "asks", "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "changes", "valves", "cloud_accounts", "close", "confirm_wait",
128 "crew", "decisions_by", "desk", "detach", "economics", "edit", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner",
128 "crew", "decisions_by", "desk", "detach", "dxf_edit", "economics", "edit", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner",
129129 "follow_mode", "forge", "fork", "front_page", "hold", "issue_teams", "keep_plan", "knobs", "labels", "lift", "limb", "maintenance", "make_it_yours", "map", "merge", "new_app",
130130 "next_up", "week", "notify", "open_pull", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports",
131131 "repo", "request_review", "restore_drill", "review", "say", "scorecard", "signup", "snapshot_now", "spend", "steer", "sync", "system", "take_back", "take_updates",
test/delete-tier.test.ts +1
@@ -127,6 +127,7 @@ const SPARED: Readonly<Record<string, string>> = {
127127 account_access: "a reset mints a one-use link; the person's password and passkeys stand until they use it",
128128 claim_link: "a revoked claim link is restored by `undo`, and a new one can always be revealed",
129129 crew: "an agent taken off a repository's crew is seated again with `add`; nothing it did is lost",
130 dxf_edit: "it removes a layer from a drawing as a reviewable commit that git history keeps; nothing is lost and a preview writes nothing",
130131 egress_grants: "a revoked grant is granted again by the same tool; no data goes with it",
131132 invites: "a revoked invite is an unused link; a new one is minted in its place",
132133 invite: "a contributor taken off is let in again with the same tool; their work, pulls and account are untouched",
test/dxf-edit.test.ts added +264
@@ -0,0 +1,264 @@
1 /**
2 * Move, scale and remove a layer of a DXF: the pure module, the action (preview equals commit, a
3 * reader is refused), the file page's form and the MCP tool.
4 */
5 import { afterAll, beforeAll, describe, 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 { createApp, type App } from "../src/app.ts";
10 import { editDrawing, type DxfForm } from "../src/actions/dxf_edit.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { signUp } from "../src/actions/users.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { getUserByName } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { localSource } from "../src/view/local.ts";
18 import { editDxf } from "../src/web/render/dxf_edit.ts";
19 import { tool as dxfTool } from "../src/http/mcp/tools/dxf_edit.ts";
20 import { fixtureSlot } from "./helpers/slot.ts";
21 import { seedAdmin } from "./helpers/admin.ts";
22 import { createForgeApp } from "../src/tui/forge.ts";
23 import { dxfEditCommands } from "../src/tui/screens/dxf_edit.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import type { Screen } from "../src/tui/app/app.ts";
26 import { commitLog } from "../src/git/read.ts";
27 import { repoDir } from "../src/git/repos.ts";
28 import { settleApp } from "./helpers/tui.ts";
29 import { quietLogs } from "./helpers/globals.ts";
30
31 quietLogs();
32
33 const pairs = (...p: (string | number)[]): string => p.join("\n") + "\n";
34 /** One of each drawn kind on two layers, a TEXT it does not understand and an odd group code. */
35 const DXF = pairs(
36 0, "SECTION", 2, "HEADER", 9, "$INSUNITS", 70, 4, 0, "ENDSEC",
37 0, "SECTION", 2, "ENTITIES",
38 0, "LINE", 8, "WALLS", 10, "1.5", 20, "2", 30, "0", 11, "4", 21, "6", 999, "keep me",
39 0, "CIRCLE", 8, "WALLS", 10, "0", 20, "0", 40, "5",
40 0, "ARC", 8, "DOORS", 10, "10", 20, "10", 40, "2", 50, "0", 51, "90",
41 0, "LWPOLYLINE", 8, "DOORS", 90, 3, 70, 1, 10, "0", 20, "0", 10, "3", 20, "0", 10, "3", 20, "3",
42 0, "TEXT", 8, "WALLS", 10, "7", 20, "7", 40, "2.5", 1, "hello",
43 0, "ENDSEC", 0, "EOF",
44 );
45 const bytes = (s: string): Uint8Array => new TextEncoder().encode(s);
46 const run = (edit: Parameters<typeof editDxf>[1], src = DXF) => {
47 const r = editDxf(bytes(src), edit);
48 if (!r.ok) throw new Error(r.why);
49 return r.value;
50 };
51 /** Lines that differ, as [before, after]. */
52 const changed = (a: string, b: string): [string, string][] => {
53 const x = a.split("\n"), y = b.split("\n");
54 expect(y.length).toBe(x.length);
55 return x.flatMap((l, i): [string, string][] => (l === y[i] ? [] : [[l, y[i]!]]));
56 };
57
58 describe("editDxf", () => {
59 test("move changes only the x and y of the drawn entities, every polyline vertex included", () => {
60 const out = run({ move: [10, -1] });
61 expect(changed(DXF, out.text)).toEqual([
62 ["1.5", "11.5"], ["2", "1"], ["4", "14"], ["6", "5"], // the line, its z (30) and 999 untouched
63 ["0", "10"], ["0", "-1"], // circle centre
64 ["10", "20"], ["10", "9"], // arc centre
65 ["0", "10"], ["0", "-1"], ["3", "13"], ["0", "-1"], ["3", "13"], ["3", "2"],
66 ]);
67 expect(out.left).toBe(1);
68 });
69
70 test("scale multiplies coordinates and a radius, not an arc's angles", () => {
71 const out = run({ scale: 2 });
72 expect(out.text).toContain("0\nARC\n8\nDOORS\n10\n20\n20\n20\n40\n4\n50\n0\n51\n90\n");
73 expect(out.text).toContain("0\nCIRCLE\n8\nWALLS\n10\n0\n20\n0\n40\n10\n");
74 // The text entity, its height and the polyline's count (90) are as they were.
75 expect(out.text).toContain("0\nTEXT\n8\nWALLS\n10\n7\n20\n7\n40\n2.5\n1\nhello\n");
76 expect(out.text).toContain("90\n3\n70\n1\n10\n0\n20\n0\n10\n6\n20\n0\n10\n6\n20\n6\n");
77 });
78
79 test("scale, then move", () => {
80 expect(run({ scale: 2, move: [1, 1] }).text).toContain("0\nLINE\n8\nWALLS\n10\n4\n20\n5\n30\n0\n11\n9\n21\n13\n");
81 });
82
83 test("removing a layer drops only its entities, and unknown pairs survive byte for byte", () => {
84 const out = run({ removeLayer: "DOORS" });
85 expect([out.before, out.after]).toEqual([5, 3]);
86 expect(out.text).not.toContain("ARC");
87 expect(out.text).not.toContain("LWPOLYLINE");
88 expect(out.text).toContain("999\nkeep me\n");
89 expect(out.text).toBe(DXF.replace(/0\nARC\n[\s\S]*?(?=0\nTEXT)/, ""));
90 });
91
92 test("line ends, a BOM and a missing final newline come back unchanged", () => {
93 const src = "" + DXF.replace(/\n/g, "\r\n").trimEnd();
94 const out = run({ move: [1, 0] }, src);
95 expect(out.text.startsWith("")).toBe(true);
96 expect(out.text.endsWith("EOF")).toBe(true);
97 expect(out.text.split("\r\n").length).toBe(src.split("\r\n").length);
98 expect(out.text).not.toMatch(/[^\r]\n/);
99 });
100
101 test("refusals: binary, no ENTITIES, numbers out of bounds, a bad or absent layer, an empty result", () => {
102 const refuse = (src: Uint8Array | string, edit: Parameters<typeof editDxf>[1]) => {
103 const r = editDxf(typeof src === "string" ? bytes(src) : src, edit);
104 expect(r.ok).toBe(false);
105 return r.ok ? "" : r.why;
106 };
107 expect(refuse(new Uint8Array([65, 0, 66]), { move: [1, 1] })).toMatch(/binary/);
108 expect(refuse(pairs(0, "SECTION", 2, "HEADER", 0, "ENDSEC", 0, "EOF"), { move: [1, 1] })).toMatch(/ENTITIES/);
109 expect(refuse(DXF, { scale: 0 })).toMatch(/greater than zero/);
110 expect(refuse(DXF, { move: [Number.NaN, 0] })).toMatch(/finite/);
111 expect(refuse(DXF, { move: [2e9, 0] })).toMatch(/out of range/);
112 expect(refuse(DXF, { removeLayer: "NOPE" })).toMatch(/No entity/);
113 expect(refuse(DXF, { removeLayer: "A\nB" })).toMatch(/control/);
114 expect(refuse(DXF, { removeLayer: "x".repeat(81) })).toMatch(/80/);
115 expect(refuse(DXF.replace(/DOORS/g, "WALLS"), { removeLayer: "WALLS" })).toMatch(/empty/);
116 });
117 });
118
119 describe("the action, the page and the tool", () => {
120 let dataDir: string;
121 let app: App;
122 let servers: Servers;
123 let alice = "";
124 const form = (over: Partial<DxfForm> = {}): DxfForm => ({ ref: "main", path: "p.dxf", dx: "", dy: "", factor: "2", layer: "", ...over });
125 const repo = () => getRepo(app.db, "alice", "plans")!;
126 const stored = async (): Promise<string> => {
127 const blob = await localSource(app, repo(), undefined).blob("main", "p.dxf");
128 if (!blob.ok || blob.value.kind === "too_large") throw new Error("no file");
129 return new TextDecoder().decode(blob.value.body as Uint8Array);
130 };
131
132 beforeAll(async () => {
133 dataDir = await mkdtemp(join(tmpdir(), "forge-dxf-"));
134 app = createApp({ dataDir, port: 0 });
135 servers = await serve(app);
136 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-long-dxf-passphrase" });
137 const k = await signUp(app, { username: "kim", email: "[email protected]", password: "a-long-dxf-passphrase" }, { slot: fixtureSlot(app) });
138 if (!a.ok || !k.ok) throw new Error("signup failed");
139 alice = `forge_session=${createSession(app.db, a.value.id).token}`;
140 const made = await createRepo(app, a.value, { name: "plans", visibility: "public" });
141 if (!made.ok) throw new Error("repo failed");
142 await commitToBranch(app, a.value, made.value, { message: "first", files: [{ path: "p.dxf", content: bytes(DXF) }, { path: "n.txt", content: bytes("x") }] });
143 });
144 afterAll(async () => {
145 servers.stop();
146 app.close();
147 await rm(dataDir, { recursive: true, force: true });
148 });
149
150 test("a preview writes nothing, and the commit writes exactly what it showed", async () => {
151 const head = (await stored());
152 const preview = await editDrawing(app, getUserByName(app.db, "alice"), repo(), form({ layer: "DOORS" }), false);
153 expect(preview.ok).toBe(true);
154 if (!preview.ok) return;
155 expect(await stored()).toBe(head);
156 expect([preview.value.edited.before, preview.value.edited.after]).toEqual([5, 3]);
157 expect(preview.value.edited.svg).toContain("<svg");
158 const saved = await editDrawing(app, getUserByName(app.db, "alice"), repo(), form({ layer: "DOORS" }), true);
159 expect(saved.ok).toBe(true);
160 if (!saved.ok) return;
161 expect(saved.value.edited.svg).toBe(preview.value.edited.svg);
162 expect(await stored()).toBe(new TextDecoder().decode(preview.value.edited.bytes));
163 expect(saved.value.message).toBe("p.dxf: remove layer DOORS, scale ×2");
164 expect(saved.value.landed?.branch).toBe("main");
165 });
166
167 test("a reader is refused and nothing is written; so are bad paths and numbers", async () => {
168 const before = await stored();
169 const kim = getUserByName(app.db, "kim");
170 const r = await editDrawing(app, kim, repo(), form(), true);
171 expect(r.ok).toBe(false);
172 const anon = await editDrawing(app, undefined, repo(), form(), true);
173 expect(anon.ok).toBe(false);
174 const alice_ = getUserByName(app.db, "alice");
175 for (const bad of [form({ path: "n.txt" }), form({ factor: "abc" }), form({ factor: "0" }), form({ factor: "", dx: "2000000" }), form({ factor: "" })]) {
176 const e = await editDrawing(app, alice_, repo(), bad, true);
177 expect(e.ok).toBe(false);
178 if (!e.ok) expect(typeof e.error === "object" && e.error.kind === "refused").toBe(true);
179 }
180 expect(await stored()).toBe(before);
181 });
182
183 test("the page offers the form to a writer only, previews, then commits", async () => {
184 const base = servers.url;
185 const get = async (cookie?: string) => (await fetch(`${base}/alice/plans/blob/main/p.dxf`, { headers: cookie === undefined ? {} : { cookie } })).text();
186 expect(await get()).not.toContain('name="dxf"');
187 expect(await get(alice)).toContain('name="dxf"');
188 const post = (fields: Record<string, string>, cookie = alice) =>
189 fetch(`${base}/alice/plans/edit`, {
190 method: "POST",
191 redirect: "manual",
192 headers: { origin: new URL(base).origin, cookie },
193 body: new URLSearchParams({ ref: "main", path: "p.dxf", dxf: "1", ...fields }),
194 });
195 const before = await stored();
196 const shown = await post({ do: "preview", dx: "5", dy: "5" });
197 expect(shown.status).toBe(200);
198 const body = await shown.text();
199 expect(body).toContain("The new drawing");
200 expect(body).toContain("Entities after");
201 expect(await stored()).toBe(before);
202 expect((await post({ do: "save", dx: "5", dy: "5" })).status).toBe(303);
203 expect(await stored()).not.toBe(before);
204 const cross = await fetch(`${base}/alice/plans/edit`, { method: "POST", redirect: "manual", headers: { origin: "https://evil.test", cookie: alice }, body: new URLSearchParams({ ref: "main", path: "p.dxf", dxf: "1", do: "save", dx: "1" }) });
205 expect(cross.status).toBeGreaterThanOrEqual(400);
206 });
207
208 test("the MCP tool previews by default and commits on dryRun: false", async () => {
209 const user = getUserByName(app.db, "alice")!;
210 const ctx = { app, scope: "rw" } as unknown as Parameters<typeof dxfTool.run>[0];
211 const args = { repo: "alice/plans", branch: "main", path: "p.dxf", move: [1, 0] };
212 const before = await stored();
213 const dry = await dxfTool.run(ctx, user, args);
214 expect(dry.ok).toBe(true);
215 if (dry.ok) expect((dry.value as { says: string }).says).toContain("Send dryRun: false");
216 expect(await stored()).toBe(before);
217 const bad = await dxfTool.run(ctx, user, { ...args, move: [1] });
218 expect(bad.ok).toBe(false);
219 const done = await dxfTool.run(ctx, user, { ...args, dryRun: false });
220 expect(done.ok).toBe(true);
221 if (done.ok) expect((done.value as { says: string }).says).toBe("Committed to main.");
222 expect(await stored()).not.toBe(before);
223 });
224
225 test("the terminal's command is for a writer and makes the same commit", async () => {
226 const open = (username: string) => {
227 const { app: tui, session } = createForgeApp(
228 app,
229 { sshUsername: username, remoteAddress: "127.0.0.1", fingerprint: `SHA256:${username}`, user: getUserByName(app.db, username)! },
230 { terminal: headlessTerminal(100, 30), exitHooks: false },
231 );
232 tui.start();
233 const parent: Screen = { title: "parent", keys: [], render() {}, key: () => false };
234 return { tui, command: dxfEditCommands(session, tui.ctx, repo(), () => parent) };
235 };
236 const type = async (tui: ReturnType<typeof open>["tui"], text: string) => {
237 for (const key of text) tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
238 tui.dispatch({ type: "key", key: "enter", ctrl: false, alt: false, shift: false });
239 await settleApp(tui);
240 };
241 const reader = open("kim");
242 expect(reader.command).toEqual([]);
243 reader.tui.stop();
244 const { tui, command } = open("alice");
245 expect(command.map((c) => c.id)).toEqual(["dxf-edit"]);
246 let announce = () => {};
247 const announced = new Promise<void>((resolve) => (announce = resolve));
248 const off = app.bus.subscribe((e) => e.kind === "push" && announce());
249 try {
250 void command[0]!.run();
251 await settleApp(tui);
252 await type(tui, "p.dxf");
253 await type(tui, "3");
254 await type(tui, "");
255 await type(tui, "");
256 await announced;
257 const log = await commitLog(repoDir(app.reposRoot, "alice", "plans"), "main", { limit: 1 });
258 expect(log.ok && log.value[0]?.subject).toBe("p.dxf: scale ×3");
259 } finally {
260 off();
261 tui.stop();
262 }
263 });
264 });
test/mcp-forge-protocol.test.ts +1
@@ -120,6 +120,7 @@ describe("the forge over MCP: protocol", () => {
120120 "desk",
121121 "drills",
122122 "drop",
123 "dxf_edit",
123124 "sizes",
124125 "releases",
125126 "apps",

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

Keyboard shortcuts

Docs