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

Talk workspace W2: live edit loop — Talk's writes and the Code tab edit the working tree #17177

opened this

Merged 36h 15m ago, live in production

torque/forge:torque/17120-talk-workspace-w2-live-edit-loop-talk-s → main 0 commits fork 3 threads · 3 unresolved

  • Merged. torque/17120-talk-workspace-w2-live-edit-loop-talk-s was merged into main as e0c876b.

Review

Sign in to review this change.
16 files changed +684 −11
docs/features/talk-workspace.md +12
@@ -22,3 +22,15 @@ The frame is served by the forge at `/talk/dev/<token>/…` (`src/web/pages/talk
2222 What the frame cannot do, said on the page too: it is a sandboxed frame, so an app that signs people in or posts forms does not work in it, and absolute links like `/x` that the app writes itself point at the forge, not the app; use relative links.
2323
2424 Where the page shows only **Error**, the file and line sit in its title; the terminal's `p` view prints them: "Error in src/app.ts:12; ask the crew to fix it". Both read `paneStatus`.
25
26 ## Live edits: the working tree (#17120, W2)
27
28 A workspace's changes are a **working tree**, not a commit per write (`src/actions/working_tree.ts`, rows in `working_edit`, one person's per repository and branch). Nothing becomes a commit until it is asked for.
29
30 - **Talk:** `write_file` with `live: true` saves the file to the working tree of an existing branch other than the default and answers `{ live: true, files }` with no commit. Without `live` it commits as before, and the conversation's first write still commits, since that makes the branch.
31 - **Code tab:** under the file tree, **Edit live** opens a path (its uncommitted text, else the branch's) and **Save live** writes it to the working tree.
32 - **Diff tab:** over the commits, the uncommitted files as a diff against the branch's tip, with **Commit** (one commit, your message) and **Discard**.
33 - **Terminal:** the `p` view says `Not committed yet: N files on <branch>` and has the same three actions: `e` saves a file live (path, then its text on one line, `\n` for a line break), `C` commits with your message, `X` discards.
34
35 Not yet: the dev server reading the working tree, so the dev frame does not reload from uncommitted files; Test what I touched and Open pull (W3).
36
src/actions/working_tree.ts added +140
@@ -0,0 +1,140 @@
1 /**

High: saveWorking caps per file and file count but not total bytes; workingDiff seals every edit into git on each Diff render with no byte check. Cap total working-tree bytes at save (MAX_COMMIT_BYTES) and refuse in workingDiff.

2 * Live edits (#17120, W2 of #16940): Talk's `write_file` (with `live: true`) and the Code tab write
3 * a workspace's working tree, not a commit. The files accumulate against the branch's tip as a
4 * diff; nothing becomes a commit until `commitWorking` is asked for. Plain data in, plain data out,
5 * so both doors say the same.
6 */
7
8 import type { App } from "../app.ts";
9 import { commitIdentity } from "../core/commit_identity.ts";
10 import type { Repo } from "../core/repos.ts";
11 import type { User } from "../core/users.ts";
12 import { clearEdits, editBytes, editCount, editOf, editsOf, saveEdit } from "../core/working_tree.ts";
13 import { diffRange, type Diff } from "../git/diff.ts";
14 import { commitFiles } from "../git/write.ts";
15 import { isSafeRef, isSafeTreePath } from "../git/guard.ts";
16 import { blobForRender, refTip } from "../git/read.ts";
17 import { repoDir } from "../git/repos.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19 import { requireWriter } from "./access.ts";
20 import { MAX_COMMIT_BYTES, MAX_FILE_BYTES } from "./contents.ts";
21 import { mirrorCopyWords } from "./mirror_copy.ts";
22 import { commitToBranch } from "./repos.ts";
23
24 /** At most this many files uncommitted on one branch. */
25 export const WORKING_FILES_MAX = 200;
26
27 export const WORKING_WORDS = {
28 not_found: "No such repository or branch.",
29 forbidden: "This is not yours to write.",
30 unauthorized: "Sign in to edit.",
31 default_branch: "Live edits go to a branch of their own, never the default branch.",
32 bad_path: "That path is not one a repository can hold.",
33 too_large: "That is too large to hold uncommitted: commit or discard some files first.",
34 too_many: `A working tree holds at most ${WORKING_FILES_MAX} changed files: commit or discard some first.`,
35 nothing: "Nothing has changed here yet.",
36 moved: "The branch moved since: look at the diff again.",
37 failed: "The change could not be saved just now.",
38 } as const;
39
40 export type WorkingError = keyof typeof WORKING_WORDS | { readonly kind: "mirror_read_only"; readonly says: string };
41
42 /** The words for a refusal, from the table or the mirror's own. */
43 export const workingWords = (e: WorkingError): string => (typeof e === "string" ? WORKING_WORDS[e] : e.says);
44
45 /** Save one file of the working tree of `branch` (which must exist): live, no commit. */
46 export async function saveWorking(app: App, actor: User | undefined, repo: Repo, branch: string, path: string, content: string): Promise<Result<{ readonly files: number }, WorkingError>> {
47 const writer = requireWriter(app, actor, repo);
48 if (!writer.ok) return err(writer.error === "not_found" || writer.error === "unauthorized" ? writer.error : "forbidden");
49 const readOnly = mirrorCopyWords(app, writer.value, repo);
50 if (readOnly !== undefined) return err({ kind: "mirror_read_only", says: readOnly });
51 if (!isSafeRef(branch)) return err("not_found");
52 if (branch === repo.defaultBranch) return err("default_branch");
53 if (!isSafeTreePath(path) || path.split("/").some((p) => p.toLowerCase() === ".git")) return err("bad_path");
54 const size = Buffer.byteLength(content, "utf8");
55 if (size > MAX_FILE_BYTES) return err("too_large");
56 // The whole working tree stays a commit that can be built: the diff seals it and a commit lands
57 // it.
58 if (editBytes(app.db, writer.value.id, repo.id, branch, path) + size > MAX_COMMIT_BYTES) return err("too_large");
59 if ((await refTip(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${branch}`)) === undefined) return err("not_found");
60 const known = editsOf(app.db, writer.value.id, repo.id, branch);
61 if (known.length >= WORKING_FILES_MAX && !known.some((e) => e.path === path)) return err("too_many");
62 saveEdit(app.db, writer.value.id, repo.id, branch, path, content);
63 return ok({ files: editCount(app.db, writer.value.id, repo.id, branch) });
64 }
65
66 /**
67 * The working tree against the branch's tip: what a commit now would add. Empty when nothing
68 * changed.
69 */
70 export async function workingDiff(app: App, user: User, repo: Repo, branch: string): Promise<Diff | undefined> {
71 const edits = editsOf(app.db, user.id, repo.id, branch);
72 if (edits.length === 0) return { files: [], additions: 0, deletions: 0 };
73 if (editBytes(app.db, user.id, repo.id, branch) > MAX_COMMIT_BYTES) return undefined;
74 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
75 const tip = await refTip(dir, `refs/heads/${branch}`);
76 if (tip === undefined) return undefined;
77 // The commit is sealed as a commit would be, then refused at landing: the objects exist for the
78 // diff and no ref ever names them (git prunes them).
79 let sealed: string | undefined;
80 await commitFiles(dir, {
81 branch,
82 message: "working tree",
83 files: edits.map((e) => ({ path: e.path, content: e.content })),
84 expectTip: tip,
85 author: commitIdentity(app.config, user),
86 land: async (oid) => {
87 sealed = oid;
88 return err("not landed");
89 },
90 });
91 if (sealed === undefined) return undefined;
92 const d = await diffRange(dir, tip, sealed);
93 return d.ok ? d.value : undefined;
94 }
95
96 /**
97 * Commit the working tree to its branch, as one commit, when asked; the working tree is then empty.
98 */
99 export async function commitWorking(app: App, user: User, repo: Repo, branch: string, message: string): Promise<Result<{ readonly commit: string; readonly files: number }, WorkingError>> {
100 const edits = editsOf(app.db, user.id, repo.id, branch);
101 if (edits.length === 0) return err("nothing");
102 const tip = await refTip(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${branch}`);
103 if (tip === undefined) return err("not_found");
104 if (editBytes(app.db, user.id, repo.id, branch) > MAX_COMMIT_BYTES) return err("too_large");
105 const done = await commitToBranch(app, user, repo, { branch, message: message.trim() === "" ? "Update files" : message.trim(), files: edits.map((e) => ({ path: e.path, content: e.content })), expectTip: tip });
106 if (!done.ok) {
107 const e = done.error;
108 if (typeof e === "string") return err(e === "not_found" || e === "unauthorized" ? e : "forbidden");
109 if (e.kind === "mirror_read_only") return err(e);
110 if (e.kind === "branch_moved") return err("moved");
111 if (e.kind === "protected_branch") return err("default_branch");
112 return err("failed");
113 }
114 clearEdits(app.db, user.id, repo.id, branch);
115 return ok({ commit: done.value.commitOid, files: edits.length });
116 }
117
118 /** Throw the working tree away; how many files it held. */
119 export const discardWorking = (app: App, user: User, repo: Repo, branch: string): number => clearEdits(app.db, user.id, repo.id, branch);
120
121 /**
122 * The text the editor opens for `path`: its uncommitted text, else the branch's, else nothing (a
123 * new file).
124 */
125 export async function openForEdit(app: App, user: User, repo: Repo, branch: string, path: string): Promise<string> {
126 const live = editOf(app.db, user.id, repo.id, branch, path);
127 if (live !== undefined) return live;
128 if (!isSafeRef(branch) || !isSafeTreePath(path)) return "";
129 const blob = await blobForRender(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${branch}`, path, MAX_FILE_BYTES);
130 return blob.kind === "text" ? new TextDecoder().decode(blob.body) : "";
131 }
132
133 /** The one line both doors say of a working tree: how many files, and where; none is a commit. */
134 export const uncommittedWords = (files: number, branch: string): string => `Not committed yet: ${files} file${files === 1 ? "" : "s"} on ${branch}.`;
135
136 /** The uncommitted line for a branch, or none when it holds nothing: the terminal's `p` view. */
137 export function uncommittedLine(app: App, user: User, repo: Repo, branch: string): string[] {
138 const n = editCount(app.db, user.id, repo.id, branch);
139 return n === 0 ? [] : [uncommittedWords(n, branch)];
140 }
src/core/migration-pins/20261201190000-working-edit.pin added +1
@@ -0,0 +1,1 @@
1 6fc9d36af1691f4728dcf6030c95f5a4e18533da938bffd45b80bf22c712c5cb
src/core/migrations/20261201190000-working-edit.ts added +13
@@ -0,0 +1,13 @@
1 // A workspace's working tree (#17120, W2 of #16940): the files a person or Talk changed on a branch
2 // that are not a commit yet. One row per file; the branch's tip is the base they are read against.
3 export default `
4 CREATE TABLE working_edit (
5 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
6 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
7 branch TEXT NOT NULL,
8 path TEXT NOT NULL,
9 content TEXT NOT NULL,
10 updated_at TEXT NOT NULL,
11 PRIMARY KEY (user_id, repo_id, branch, path)
12 );
13 `;
src/core/working_tree.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * The working tree of a workspace (#17120, W2 of #16940): files changed on a branch and not yet
3 * committed, kept per person, repository and branch. Plain rows in, plain rows out; the git side
4 * (diff, commit) is `actions/working_tree.ts`.
5 */
6 import type { Database } from "bun:sqlite";
7
8 export interface WorkingEdit {
9 readonly path: string;
10 readonly content: string;
11 readonly updatedAt: string;
12 }
13
14 /** Set (or replace) one file of the working tree. */
15 export function saveEdit(db: Database, userId: string, repoId: string, branch: string, path: string, content: string): void {
16 db.query(
17 `INSERT INTO working_edit (user_id, repo_id, branch, path, content, updated_at) VALUES (?1,?2,?3,?4,?5,?6)
18 ON CONFLICT (user_id, repo_id, branch, path) DO UPDATE SET content = excluded.content, updated_at = excluded.updated_at`,
19 ).run(userId, repoId, branch, path, content, new Date().toISOString());
20 }
21
22 /** The files changed on this branch, by path. */
23 export function editsOf(db: Database, userId: string, repoId: string, branch: string): WorkingEdit[] {
24 return db
25 .query<{ path: string; content: string; updated_at: string }, [string, string, string]>(
26 "SELECT path, content, updated_at FROM working_edit WHERE user_id = ?1 AND repo_id = ?2 AND branch = ?3 ORDER BY path",
27 )
28 .all(userId, repoId, branch)
29 .map((r) => ({ path: r.path, content: r.content, updatedAt: r.updated_at }));
30 }
31
32 /** One file's uncommitted content, if it has any. */
33 export function editOf(db: Database, userId: string, repoId: string, branch: string, path: string): string | undefined {
34 return db
35 .query<{ content: string }, [string, string, string, string]>("SELECT content FROM working_edit WHERE user_id = ?1 AND repo_id = ?2 AND branch = ?3 AND path = ?4")
36 .get(userId, repoId, branch, path)?.content;
37 }
38
39 /** Forget every uncommitted file of the branch (after a commit, or a discard). */
40 export function clearEdits(db: Database, userId: string, repoId: string, branch: string): number {
41 return db.query("DELETE FROM working_edit WHERE user_id = ?1 AND repo_id = ?2 AND branch = ?3").run(userId, repoId, branch).changes;
42 }
43
44 /** How many files the branch has uncommitted. */
45 export function editCount(db: Database, userId: string, repoId: string, branch: string): number {
46 return db.query<{ n: number }, [string, string, string]>("SELECT COUNT(*) AS n FROM working_edit WHERE user_id = ?1 AND repo_id = ?2 AND branch = ?3").get(userId, repoId, branch)!.n;
47 }
48
49 /** The bytes of text the branch holds uncommitted (UTF-8, as a commit would carry it). */
50 export function editBytes(db: Database, userId: string, repoId: string, branch: string, exceptPath = ""): number {
51 return db
52 .query<{ n: number }, [string, string, string, string]>(
53 "SELECT COALESCE(SUM(LENGTH(CAST(content AS BLOB))), 0) AS n FROM working_edit WHERE user_id = ?1 AND repo_id = ?2 AND branch = ?3 AND path != ?4",
54 )
55 .get(userId, repoId, branch, exceptPath)!.n;
56 }
src/generated/migrations.ts +4 −2
@@ -455,7 +455,8 @@ import m450 from "../core/migrations/20261201150000-dns-record.ts";
455455 import m451 from "../core/migrations/20261201150000-pinned-firewall.ts";
456456 import m452 from "../core/migrations/20261201170000-managed-database.ts";
457457 import m453 from "../core/migrations/20261201180000-game-box-diag.ts";
458 import m454 from "../core/migrations/20261201190500-runner-machine.ts";
458 import m454 from "../core/migrations/20261201190000-working-edit.ts";
459 import m455 from "../core/migrations/20261201190500-runner-machine.ts";
459460
460461 /** Each migration file's name and its default export, in name order. */
461462 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -913,5 +914,6 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
913914 ["20261201150000-pinned-firewall.ts", m451],
914915 ["20261201170000-managed-database.ts", m452],
915916 ["20261201180000-game-box-diag.ts", m453],
916 ["20261201190500-runner-machine.ts", m454],
917 ["20261201190000-working-edit.ts", m454],
918 ["20261201190500-runner-machine.ts", m455],
917919 ];
src/http/mcp/tools/branches.ts +1 −1
@@ -11,7 +11,7 @@ export const tool: Tool = {
1111 name: "branches",
1212 doc: "`{ repo, name?, action?, from?, kind? }`: without `name`, lists the branches; `kind: \"tags\"` lists the tags instead (as GET `/api/v1/repos/:owner/:name/tags` does, newest first; no `name` or `action`); with `name` and `action` (`create` from `from`, or `delete`) it does what the branches page does: the default branch is never deleted, only a writer may act",
1313 description:
14 "A repo's branches; `action` create (`from`) or delete `name`, not the default.",
14 "A repo's branches; `action` create (`from`) or delete `name`.",
1515 inputSchema: {
1616 type: "object",
1717 properties: {
src/http/mcp/tools/new_app.ts +1 −1
@@ -22,7 +22,7 @@ export const tool: Tool = {
2222 name: "new_app",
2323 doc: "`{ name?, sentence?, description?, brief?, owner?, visibility?, agent?, pick?, template? }`: make an app from a sentence: with `sentence` and no `name` the name is derived from it (`-2`, `-3` when taken), `name` and `sentence` together keep the name; the card line is `description` (≤160 with `brief`), the first issue `brief`, else `description`, else `sentence`; answers `{ repo, url, issue, agent, run, visibility, says? }` (`run`: state or `none`) and draws the `ui://forge/app` card; refused as `POST /api/v1/apps` is (unverified, app_limit, no_such_agent, name_taken)",
2424 description:
25 "An app from a sentence: repo, production; `description` files a first issue.",
25 "An app from a sentence: repo, production; `description` files an issue.",
2626 inputSchema: {
2727 type: "object",
2828 properties: {
src/http/mcp/tools/write_file.ts +16 −4
@@ -7,6 +7,7 @@ import { editMesh, isStlPath, type MeshForm } from "../../../actions/mesh_edit.t
77 import { sizeText } from "../../../web/render/mesh.ts";
88 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
99 import { mirrorCopyWords } from "../../../actions/mirror_copy.ts";
10 import { saveWorking, workingWords } from "../../../actions/working_tree.ts";
1011 import { ensureBuildPull } from "../../../actions/build_pull.ts";
1112 import { branchFor, chatBuildOf, startChatBuild } from "../../../core/chat_build.ts";
1213 import type { Repo } from "../../../core/repos.ts";
@@ -92,7 +93,7 @@ function inTurn<T>(app: object, key: string, work: () => Promise<T>): Promise<T>
9293 }
9394
9495 /** One file committed to `branch`, as the lane or as an ordinary write. */
95 async function writeOne(ctx: Parameters<Tool["run"]>[0], user: Parameters<Tool["run"]>[1], repo: Repo, branch: string, path: string, content: string, message: string) {
96 async function writeOne(ctx: Parameters<Tool["run"]>[0], user: Parameters<Tool["run"]>[1], repo: Repo, branch: string, path: string, content: string, message: string, live = false) {
9697 // The direct lane (`core/talk_lane.ts`): this conversation's preview branch of the person's own app.
9798 const lane = laneOf(ctx.app.db, user, ctx.auth.through, repo, branch);
9899 if (lane?.kind === "refused") return bad("forbidden", lane.says);
@@ -101,6 +102,13 @@ async function writeOne(ctx: Parameters<Tool["run"]>[0], user: Parameters<Tool["
101102 // The first lane write makes the branch: one that is there already was made some other way.
102103 if (lane?.kind === "first" && there.ok) return bad("forbidden", LANE_WORDS.notMadeHere);
103104 if (lane?.kind !== "first" && !there.ok) return bad("not_found", "no such branch");
105 // A live write (#17120) changes the workspace's working tree and commits nothing; the branch is
106 // made by the first lane write, which is a commit, so a live one needs the branch to be there.
107 if (live && there.ok) {
108 const saved = await saveWorking(ctx.app, user, repo, branch, path, content);
109 if (!saved.ok) return bad(typeof saved.error === "string" ? saved.error : saved.error.kind, workingWords(saved.error));
110 return good({ says: `Changed ${path} in the working tree of ${branch}: ${saved.value.files} file${saved.value.files === 1 ? "" : "s"} not committed yet.`, live: true, files: saved.value.files });
111 }
104112 // The head read here is the one the commit must follow: a branch
105113 // deleted or moved since is refused as branch_moved, not recreated.
106114 const committed = await commitToBranch(ctx.app, user, repo, {
@@ -126,7 +134,7 @@ async function writeOne(ctx: Parameters<Tool["run"]>[0], user: Parameters<Tool["
126134
127135 export const tool: Tool = {
128136 name: "write_file",
129 doc: "`{ repo, branch, path, content, message, mesh?, dryRun? }` (`content` and `message` unless `mesh`): commit one file to an existing branch (or, from Talk, to the conversation's preview branch `talk-<id>` of an app the person owns, made by the first write, whose draft pull previews it) as `POST …/contents` does, with the same refusals (protected default, too large, a path with `..`) in `edit_words`' sentences; answers `{ commit, says }`. On an .stl, `mesh: { scale?: factor | { axis, size }, move?: [x, y, z], turn?: \"x\"|\"y\"|\"z\" }` (not `content`) scales, moves, turns it as the file page does: previews the new Box unless `dryRun` is false, which commits it",
137 doc: "`{ repo, branch, path, content, message, live?, mesh?, dryRun? }` (`live: true`: no `message`, no commit; the file joins the branch's working tree, shown in Diff): commit one file to an existing branch (or, from Talk, to the conversation's preview branch `talk-<id>` of an app the person owns, made by the first write, whose draft pull previews it) as `POST …/contents` does, with the same refusals (protected default, too large, a path with `..`) in `edit_words`' sentences; answers `{ commit, says }`. On an .stl, `mesh: { scale?: factor | { axis, size }, move?: [x, y, z], turn?: \"x\"|\"y\"|\"z\" }` (not `content`) scales, moves, turns it as the file page does: previews the new Box unless `dryRun` is false, which commits it",
130138 description: "No shell? Commit one file to a branch. With a shell, clone and push.",
131139 inputSchema: {
132140 type: "object",
@@ -138,6 +146,7 @@ export const tool: Tool = {
138146 message: { type: "string" },
139147 mesh: { type: "object" },
140148 dryRun: { type: "boolean" },
149 live: { type: "boolean" },
141150 },
142151 required: ["repo", "branch", "path"],
143152 },
@@ -151,7 +160,10 @@ export const tool: Tool = {
151160 const repo = repoArg(ctx, user, args);
152161 if (isAnswer(repo)) return repo;
153162 if (args["mesh"] !== undefined) return meshRun(ctx, user, repo, args);
154 const { branch, path, content, message } = args;
163 const { branch, path, content } = args;
164 const live = args["live"] === true;
165 // A live write has no commit, so no message is asked of it.
166 const message = live && args["message"] === undefined ? "" : args["message"];
155167 if (
156168 typeof branch !== "string" ||
157169 typeof path !== "string" ||
@@ -161,7 +173,7 @@ export const tool: Tool = {
161173 return bad("invalid", "branch, path, content and message are strings");
162174 if (!isSafeRef(branch)) return bad("not_found", "no such branch");
163175 const conversationId = conversationIdOf(ctx.auth.through);
164 const write = () => writeOne(ctx, user, repo, branch, path, content, message);
176 const write = () => writeOne(ctx, user, repo, branch, path, content, message, live);
165177 return conversationId !== undefined && branch === branchFor(conversationId) ? inTurn(ctx.app, conversationId, write) : write();
166178 },
167179 };
src/http/routes/talk.ts +4
@@ -5,6 +5,7 @@
55 import { talkView, talkSend, talkWall, talkStream, talkAgainSend, talkQueueCancel, talkConfirm, talkUndo, talkAct, talkNew, talkDisplaySave, talkDownload, talkRename, talkArchive, talkPin } from "../../web/pages/talk.ts";
66 import { peekRoute } from "../../web/peek.ts";
77 import { talkBuild, talkRestore, talkPublish } from "../../web/talk_build.ts";
8 import { talkWorkCommit, talkWorkDiscard, talkWorkSave } from "../../web/talk_tree.ts";
89 import { talkModel } from "../../web/talk_model.ts";
910 import { talkDev, talkDevFrame } from "../../web/pages/talk_dev.ts";
1011 import type { Handler } from "../context.ts";
@@ -34,6 +35,9 @@ export function talkRoutes(router: Router<Handler>): void {
3435 router.add("POST", "/talk/:id/model", talkModel);
3536 router.add("POST", "/talk/:id/archive", talkArchive);
3637 router.add("POST", "/talk/:id/pin", talkPin);
38 router.add("POST", "/talk/:id/work/save", talkWorkSave);
39 router.add("POST", "/talk/:id/work/commit", talkWorkCommit);
40 router.add("POST", "/talk/:id/work/discard", talkWorkDiscard);
3741 router.add("POST", "/talk/:id/build/restore", talkRestore);
3842 router.add("POST", "/talk/:id/build/publish", talkPublish);
3943 router.add("POST", "/talk/:id/again/:how", talkAgainSend);
src/tui/screens/talk_chats.ts +75
@@ -35,6 +35,7 @@ import { filesOf, receiptIssues, repoOf, steerOf, stepOf } from "../../core/talk
3535 import { cardsPlaced, holdsCard, plainVoice } from "../../core/talk_voice.ts";
3636 import { setTalkDisplay, talkDisplay } from "../../core/settings.ts";
3737 import { talkDisplayScreen } from "./talk_display.ts";
38 import { commitWorking, discardWorking, openForEdit, saveWorking, uncommittedLine, workingWords } from "../../actions/working_tree.ts";
3839 import { devBranch, devReading, paneStatus, startDev, stopDev } from "../../actions/dev_workspace.ts";
3940 import { conversationPulls, liveReceipts, paneCrew, paneFell, paneInfo, type LiveReceipt } from "../../core/talk_work.ts";
4041 import { tapRunLogs } from "../../runs/log.ts";
@@ -256,6 +257,72 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
256257 }),
257258 );
258259 };
260 // The page's Save live, Commit and Discard (`actions/working_tree.ts`), on the branch this
261 // conversation builds.
262 const workingKey = (key: "e" | "C" | "X"): void => {
263 const user = f.user;
264 const build = chatBuildOf(f.app.db, chat.id);
265 const home = build === undefined ? undefined : getRepoById(f.app.db, build.repoId);
266 if (user === undefined || build === undefined || home === undefined) {
267 note = "No branch of this conversation to change yet.";
268 ctx.invalidate();
269 return;
270 }
271 const say = (words: string): void => {
272 note = words;
273 ctx.invalidate();
274 };
275 if (key === "X") {
276 const n = discardWorking(f.app, user, home, build.branch);
277 say(n === 0 ? "Nothing was changed here." : `Discarded ${n} uncommitted file${n === 1 ? "" : "s"}.`);
278 return;
279 }
280 if (key === "C") {
281 void later(ctx, () =>
282 promptScreen(ctx, screen, {
283 title: "Commit",
284 label: "message for the one commit",
285 placeholder: "Update files",
286 onSubmit: (words) => {
287 runAsync(ctx, async () => {
288 const done = await commitWorking(f.app, user, home, build.branch, words.slice(0, 200));
289 say(done.ok ? `Committed ${done.value.files} file${done.value.files === 1 ? "" : "s"} to ${build.branch}.` : workingWords(done.error));
290 });
291 return undefined;
292 },
293 }),
294 );
295 return;
296 }
297 void later(ctx, () =>
298 promptScreen(ctx, screen, {
299 title: "Save live",
300 label: "path of the file to change",
301 placeholder: "src/app.ts",
302 onSubmit: (path) => {
303 const at = path.trim();
304 runAsync(ctx, async () => {
305 const was = (await openForEdit(f.app, user, home, build.branch, at)).trimEnd().replaceAll("\n", "\\n");
306 ctx.push(
307 promptScreen(ctx, screen, {
308 title: at,
309 label: "its new text, one line (\\n for a line break)",
310 value: was,
311 onSubmit: (text) => {
312 runAsync(ctx, async () => {
313 const saved = await saveWorking(f.app, user, home, build.branch, at, `${text.replaceAll("\\n", "\n")}\n`);
314 say(saved.ok ? `Saved ${at} live: ${saved.value.files} file${saved.value.files === 1 ? "" : "s"}.` : workingWords(saved.error));
315 });
316 return undefined;
317 },
318 }),
319 );
320 });
321 return undefined;
322 },
323 }),
324 );
325 };
259326 const paneLines = (): string[] => {
260327 if (repo === undefined || f.user === undefined) return ["No repository yet."];
261328 // Where the person picked, else where the agent pointed the pane (`pane`), as the page frames it.
@@ -269,12 +336,15 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
269336 const dev = devReading(f.app, f.user, ws.repo, branch);
270337 const url = ws.url;
271338 const fell = paneFell(f.app.db, ws.repo.id, ws.fell);
339 const buildHere = name === repo ? chatBuildOf(f.app.db, chat.id) : undefined;
272340 return [
273341 `${name} · ${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}${pointedAt(picked, steer).path === undefined ? "" : ` · ${pointedAt(picked, steer).path ?? ""}`}`,
274342 paneInfo(f.app.db, ws.repo, ws.shows),
275343 `Status: ${((st) => (st.state === "error" ? `${st.word}; ask the crew to fix it` : st.word))(paneStatus({ url, dev, crew: paneCrew(f.app.db, f.app.config.dataDir, ws.repo.id, f.user, { runs: mayReadRuns(f.app, f.user, ws.repo), logs: false }) }))}`,
276344 `Dev server: ${dev === undefined ? `not running; d starts ${branch} with hot reload` : `${dev.state} on ${branch}; d stops it`}${dev?.state === "live" ? " (the page frames it, sandboxed: sign-in and forms that post do not work in it; it sleeps after 10 minutes unused)" : ""}`,
277345 ...(fell === undefined ? [] : [fell]),
346 // The working tree, as the Diff tab says it: changed here, not a commit until asked (#17120).
347 ...(buildHere === undefined || f.user === undefined ? [] : uncommittedLine(f.app, f.user, ws.repo, buildHere.branch)),
278348 // Who else is here and what was done lately, in the page's words (`togetherOf`).
279349 ...((t) => [...(t.here === undefined ? [] : [`Here: ${t.here.words}`]), ...(t.lately.length === 0 ? [] : [`Lately: ${t.lately.map((l) => `${l.words} · ${agoWords(l.at, Date.now())}`).join(" · ")}`]), ...(t.elsewhere === undefined ? [] : [`Elsewhere: ${t.elsewhere}`]), ...t.held, ...(t.landed === undefined ? [] : [`${t.landed.words} (L shows Live)`])])(togetherOf(f.app.db, ws.repo, f.user)),
280350 "o picks the repository, w the version, l a path, L Live.",
@@ -371,6 +441,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
371441 binding([keyOf("reread")], "reload"),
372442 binding(["p"], "pane"),
373443 binding(["o", "w", "l", "L"], "in the pane: repository, version, path, Live"),
444 binding(["e", "C", "X"], "in the pane: save a file live, commit, or discard what is not committed"),
374445 binding(["d"], "in the pane: start or stop the dev server"),
375446 binding(["b"], "a result's buttons"),
376447 binding(["v"], "steps open or folded"),
@@ -481,6 +552,10 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
481552 );
482553 return true;
483554 }
555 if (pane && (e.key === "e" || e.key === "C" || e.key === "X")) {
556 workingKey(e.key);
557 return true;
558 }
484559 if (pane && e.key === "d") {
485560 // The dev server of the branch shown: started or stopped as the page's button does, by a
486561 // writer.
src/web/pages/talk_preview.ts +2 −2
@@ -105,9 +105,9 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
105105 const offer = heldRun !== undefined && offersOwnToken(ctx.app, user, heldRun) ? ownTokenBox(`/${ws.repo.ownerName}/${ws.repo.name}`, heldRun.id) : null;
106106 const panel =
107107 view === "code"
108 ? await codeView(ctx.app, work)
108 ? await codeView(ctx.app, work, { user, edit: ctx.url?.searchParams.get("edit") ?? "" })
109109 : view === "diff"
110 ? await diffView(ctx.app, work, ask.version, ask.mine === undefined ? undefined : { ...ask.mine, picked: at.pull })
110 ? await diffView(ctx.app, work, ask.version, ask.mine === undefined ? undefined : { ...ask.mine, picked: at.pull }, user)
111111 : url === undefined || ask.wait !== undefined
112112 ? html`<div class="talk-stage talk-stage-wait" data-stage${ask.busy === true ? raw(" data-busy") : null}><p class="talk-stage-note" data-stage-note>${ask.wait ?? ask.idle ?? "Nothing is running yet: the app appears here once it is built."}</p>${crew === undefined ? null : crewBlock(crew, `/${ws.repo.ownerName}/${ws.repo.name}`, ws.repo, liveSrc, () => ctx.url.pathname, undefined, offer)}</div>${ask.build === undefined ? null : html`<h2 class="talk-stage-files small muted">The files it starts from</h2>${await codeView(ctx.app, work)}`}`
113113 : html`${steer === undefined || steer.try === "" ? null : html`<p class="talk-try small" data-pane-try>Try: ${steer.try}</p>`}<div class="talk-stage" data-stage data-env="${ws.shows === undefined ? "production" : previewEnv(ws.shows)}"><iframe class="talk-frame" data-frame src="${url}" title="Live preview of ${name}" referrerpolicy="no-referrer" sandbox="${devFrame === undefined ? "allow-scripts allow-same-origin allow-forms allow-popups" : "allow-scripts allow-forms allow-popups"}"></iframe><p class="talk-stage-note small" data-stage-note hidden>Updating the preview…</p></div>${crewRegion(crew !== undefined && (going || crew.state === "failed") ? crew : undefined, ws.repo, liveSrc, () => ctx.url.pathname, ws.shows, offer)}`;
src/web/talk_code.ts +12 −1
@@ -27,6 +27,10 @@ import { renderDiff } from "./diff-view.ts";
2727 import { html, raw, type Html } from "./html.ts";
2828 import { explorerFragment, urlPath } from "./pages/explorer.ts";
2929 import { icon } from "./ui.ts";
30 import { liveEditor, workingActions } from "./talk_tree.ts";
31 import { openForEdit, workingDiff } from "../actions/working_tree.ts";
32 import { editCount } from "../core/working_tree.ts";
33 import type { User } from "../core/users.ts";
3034
3135 const counts = (f: { additions: number; deletions: number }): Html =>
3236 html`<span class="talk-code-n diff-stat"
@@ -35,7 +39,7 @@ const counts = (f: { additions: number; deletions: number }): Html =>
3539 >`;
3640
3741 /** The Code tab: the files changed here first, then the whole tree, each opening in the pane. */
38 export async function codeView(app: App, w: PaneWork): Promise<Html> {
42 export async function codeView(app: App, w: PaneWork, live?: { readonly user: User; readonly edit: string }): Promise<Html> {
3943 const dir = repoDir(app.reposRoot, w.repo.ownerName, w.repo.name);
4044 const base = `/${w.repo.ownerName}/${w.repo.name}`;
4145 const changed = await branchDiff(app.db, app.reposRoot, w);
@@ -90,6 +94,7 @@ export async function codeView(app: App, w: PaneWork): Promise<Html> {
9094 The files could not be read just now.
9195 </p>`}
9296 </nav>
97 ${live === undefined || w.build === undefined ? null : liveEditor(w.build, live.edit, live.edit === "" ? "" : await openForEdit(app, live.user, w.repo, w.build.branch, live.edit))}
9398 <div class="talk-code-file" data-code-file hidden>
9499 <button
95100 type="button"
@@ -111,6 +116,7 @@ export async function diffView(
111116 w: PaneWork,
112117 version: number | undefined,
113118 mine?: PaneMine,
119 user?: User,
114120 ): Promise<Html> {
115121 // Beside no build, Diff is what this conversation's work changed, or the one pull picked above.
116122 if (w.build === undefined && mine !== undefined && mine.picked === undefined) return await mineView(app, w.repo, mine);
@@ -149,7 +155,12 @@ export async function diffView(
149155 : null}
150156 >${label}</a
151157 >`;
158 // What is changed and not committed yet, over the commits: Commit and Discard are here.
159 const uncommitted = user === undefined || w.build === undefined || editCount(app.db, user.id, w.repo.id, w.build.branch) === 0 ? undefined : await workingDiff(app, user, w.repo, w.build.branch);
152160 return html`<div class="talk-diff">
161 ${uncommitted === undefined || w.build === undefined
162 ? null
163 : html`${workingActions(w.build, uncommitted.files.length)}${renderDiff(uncommitted, { fileLinkBase: `/${name}/blob/${encodeURIComponent(w.build.branch)}` })}`}
153164 <div class="talk-diff-head small">
154165 ${versions.length < 2
155166 ? null
src/web/talk_tree.ts added +109
@@ -0,0 +1,109 @@
1 /**

Design: talk-work/talk-live are new component classes: document them in docs/design/areas/<area>.md; use a named textarea component, not a hand-rolled rule (see talk_code.ts). Principle 1: say 'not committed' once, not in the words, the label and the flash.

2 * The working tree in Talk's pane (#17120, W2 of #16940): the Code tab saves a file live, the Diff
3 * tab shows what has changed and not been committed, and a commit is made only when asked. Plain
4 * forms, no script. The git side is `actions/working_tree.ts`.
5 */
6
7 import { uncommittedWords, commitWorking, discardWorking, saveWorking, workingWords } from "../actions/working_tree.ts";
8 import { chatBuildOf, type ChatBuild } from "../core/chat_build.ts";
9 import { getConversation } from "../core/conversations.ts";
10 import type { User } from "../core/users.ts";
11 import { getRepoById, type Repo } from "../core/repos.ts";
12 import type { Ctx } from "../http/context.ts";
13 import { notFoundPage, signInFirst } from "./chrome.ts";
14 import { readForm, type Form } from "./form.ts";
15 import { html, type Html } from "./html.ts";
16 import { flashTo } from "./layout.ts";
17 import { btn } from "./ui.ts";
18
19 const ID = /^[0-9a-z]{1,40}$/;
20 const MESSAGE_MAX = 200;
21
22 /** The conversation's build and repository, when the conversation is the person's. */
23 function workOf(ctx: Ctx): { readonly build: ChatBuild; readonly repo: Repo } | undefined {
24 const id = ctx.params["id"];
25 const user = ctx.auth.user;
26 if (user === undefined || id === undefined || !ID.test(id) || getConversation(ctx.app.db, user.id, id) === undefined) return undefined;
27 const build = chatBuildOf(ctx.app.db, id);
28 const repo = build === undefined ? undefined : getRepoById(ctx.app.db, build.repoId);
29 return build === undefined || repo === undefined ? undefined : { build, repo };
30 }
31
32 const back = (id: string, pane: "code" | "diff"): string => `/talk/${id}?pane=${pane}`;
33
34 /**
35 * One work action's frame: the person signed in, the form from this origin, the conversation
36 * theirs; `act` answers with the flash and the tab to go back to.
37 */
38 async function workAction(ctx: Ctx, act: (user: User, w: { readonly build: ChatBuild; readonly repo: Repo }, form: Form) => Promise<{ readonly tone: "success" | "danger"; readonly message: string; readonly pane: "code" | "diff" }>): Promise<Response> {
39 const user = ctx.auth.user;
40 if (user === undefined) return signInFirst(ctx);
41 const form = await readForm(ctx, "rw");
42 if (form instanceof Response) return form;
43 const w = workOf(ctx);
44 if (w === undefined) return notFoundPage(ctx);
45 const said = await act(user, w, form);
46 return flashTo(ctx, back(w.build.conversationId, said.pane), { tone: said.tone, message: said.message });
47 }
48
49 const files = (n: number): string => `${n} file${n === 1 ? "" : "s"}`;
50
51 // POST /talk/:id/work/save: one file, live.
52 export const talkWorkSave = (ctx: Ctx): Promise<Response> =>
53 workAction(ctx, async (user, w, form) => {
54 const path = form.get("path");
55 const content = form.get("content");
56 if (typeof path !== "string" || typeof content !== "string") return { tone: "danger", message: "Say which file, and its text.", pane: "code" };
57 const saved = await saveWorking(ctx.app, user, w.repo, w.build.branch, path.trim(), content.replaceAll("\r\n", "\n"));
58 return saved.ok
59 ? { tone: "success", message: `Saved ${path.trim()} live: ${files(saved.value.files)}.`, pane: "diff" }
60 : { tone: "danger", message: workingWords(saved.error), pane: "code" };
61 });
62
63 // POST /talk/:id/work/commit: the working tree as one commit, when asked.
64 export const talkWorkCommit = (ctx: Ctx): Promise<Response> =>
65 workAction(ctx, async (user, w, form) => {
66 const message = form.get("message");
67 const done = await commitWorking(ctx.app, user, w.repo, w.build.branch, typeof message === "string" ? message.slice(0, MESSAGE_MAX) : "");
68 return done.ok
69 ? { tone: "success", message: `Committed ${files(done.value.files)} to ${w.build.branch}.`, pane: "diff" }
70 : { tone: "danger", message: workingWords(done.error), pane: "diff" };
71 });
72
73 // POST /talk/:id/work/discard
74 export const talkWorkDiscard = (ctx: Ctx): Promise<Response> =>
75 workAction(ctx, async (user, w) => {
76 const n = discardWorking(ctx.app, user, w.repo, w.build.branch);
77 return { tone: "success", message: n === 0 ? "Nothing was changed here." : `Discarded ${files(n)} uncommitted.`, pane: "diff" };
78 });
79
80 /** Commit and Discard, over the uncommitted diff: nothing commits until the first is pressed. */
81 export function workingActions(build: ChatBuild, files: number): Html {
82 const base = `/talk/${build.conversationId}/work`;
83 return html`<section class="stack small" aria-label="Not committed yet">
84 <p>${uncommittedWords(files, build.branch)}</p>
85 <form method="post" action="${base}/commit" class="bar">
86 <input class="input" name="message" maxlength="${MESSAGE_MAX}" placeholder="Commit message" aria-label="Commit message" />
87 ${btn("Commit", { variant: "primary", icon: "check", label: "Commit the uncommitted files to the branch" })}
88 </form>
89 <form method="post" action="${base}/discard">${btn("Discard", { icon: "trash", label: "Throw the uncommitted files away" })}</form>
90 </section>`;
91 }
92
93 /** The live editor of the Code tab: open a file, change its text, save it to the working tree. */
94 export function liveEditor(build: ChatBuild, path: string, text: string): Html {
95 return html`<section class="stack" aria-label="Edit live">
96 <form method="get" class="bar">
97 <input type="hidden" name="pane" value="code" />
98 <input class="input" name="edit" value="${path}" placeholder="src/app.ts" aria-label="File path" />
99 ${btn("Open", { icon: "file", label: "Open this file in the editor" })}
100 </form>
101 ${path === ""
102 ? null
103 : html`<form method="post" action="/talk/${build.conversationId}/work/save">
104 <input type="hidden" name="path" value="${path}" />
105 <textarea class="input mono" name="content" rows="10" spellcheck="false" aria-label="Text of ${path}">${text}</textarea>
106 ${btn("Save live", { variant: "primary", icon: "check", label: "Save to the working tree" })}
107 </form>`}
108 </section>`;
109 }
test/tui-talk-chats.test.ts +40
@@ -15,6 +15,10 @@ import { createIssue } from "../src/core/issues.ts";
1515 import { createRun } from "../src/core/runs.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
1717 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { saveWorking } from "../src/actions/working_tree.ts";
19 import { editCount, editsOf } from "../src/core/working_tree.ts";
20 import { refTip } from "../src/git/read.ts";
21 import { repoDir } from "../src/git/repos.ts";
1822 import { startChatBuild } from "../src/core/chat_build.ts";
1923 import { hold } from "../src/core/fence.ts";
2024 import { STARTER_PROMPTS } from "../src/actions/talk.ts";
@@ -299,6 +303,42 @@ describe("the terminal's conversations screen", () => {
299303 expect(text).toContain("Status: Error in src/app.ts:12; ask the crew to fix it");
300304 });
301305
306 test("p says what is changed and not committed yet, as the Diff tab does (#17120)", async () => {
307 const made = createConversation(app.db, alice.id);
308 if (!made.ok) throw new Error(made.error);
309 const repo = await createRepo(app, alice, { name: "livework", visibility: "public" });
310 if (!repo.ok) throw new Error(repo.error);
311 const build = startChatBuild(app.db, made.value.id, repo.value.id, true);
312 const seeded = await commitToBranch(app, alice, repo.value, { branch: build.branch, message: "v1", files: [{ path: "a.txt", content: "a\n" }] });
313 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
314 appendTurn(app.db, alice.id, made.value.id, { role: "tool", text: 'mcp__forge__write_file {"repo":"alice/livework","path":"a.txt","content":"b"}' });
315 expect(await drive(alice, [...open, "\r", "p"])).not.toContain("Not committed yet");
316 const saved = await saveWorking(app, alice, repo.value, build.branch, "a.txt", "b\n");
317 if (!saved.ok) throw new Error(JSON.stringify(saved.error));
318 expect(await drive(alice, [...open, "\r", "p"])).toContain(`Not committed yet: 1 file on ${build.branch}`);
319 });
320
321 test("p offers save live, commit and discard, as the Diff tab does (#17120)", async () => {
322 const made = createConversation(app.db, alice.id);
323 if (!made.ok) throw new Error(made.error);
324 const repo = await createRepo(app, alice, { name: "livekeys", visibility: "public" });
325 if (!repo.ok) throw new Error(repo.error);
326 const build = startChatBuild(app.db, made.value.id, repo.value.id, true);
327 const seeded = await commitToBranch(app, alice, repo.value, { branch: build.branch, message: "v1", files: [{ path: "a.txt", content: "a\n" }] });
328 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
329 appendTurn(app.db, alice.id, made.value.id, { role: "tool", text: 'mcp__forge__write_file {"repo":"alice/livekeys","path":"a.txt","content":"b"}' });
330 const saved = await drive(alice, [...open, "\r", "p", "e", "a.txt", "\r", "hello", "\r"]);
331 expect(saved).toContain("Saved a.txt live: 1 file.");
332 expect(editsOf(app.db, alice.id, repo.value.id, build.branch).map((e) => [e.path, e.content])).toEqual([["a.txt", "ahello\n"]]);
333 const before = await refTip(repoDir(app.reposRoot, "alice", "livekeys"), `refs/heads/${build.branch}`);
334 expect(await drive(alice, [...open, "\r", "p", "C", "Say hello", "\r"])).toContain(`Committed 1 file to ${build.branch}.`);
335 expect(await refTip(repoDir(app.reposRoot, "alice", "livekeys"), `refs/heads/${build.branch}`)).not.toBe(before);
336 expect(editCount(app.db, alice.id, repo.value.id, build.branch)).toBe(0);
337 if (!(await saveWorking(app, alice, repo.value, build.branch, "a.txt", "again\n")).ok) throw new Error("save");
338 expect(await drive(alice, [...open, "\r", "p", "X"])).toContain("Discarded 1 uncommitted file.");
339 expect(editCount(app.db, alice.id, repo.value.id, build.branch)).toBe(0);
340 });
341
302342 test("an ask waits at the foot of the conversation, never in the thread, and a opens Confirms to answer it", async () => {
303343 const made = createConversation(app.db, alice.id);
304344 if (!made.ok) throw new Error(made.error);
test/working-tree.test.ts added +198
@@ -0,0 +1,198 @@
1 /**
2 * Live edits (#17120, W2 of #16940): write_file with `live` and the Code tab change the working
3 * tree, not the branch; the diff accumulates; a commit is made only when asked. Hand calculation:
4 * a.txt "one\ntwo\n" -> "one\n2\nthree\n" is +2 −1; b.txt is new with one line, +1.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { commitWorking, discardWorking, openForEdit, saveWorking, uncommittedWords, workingDiff, WORKING_FILES_MAX } from "../src/actions/working_tree.ts";
11 import { commitToBranch } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { createRepo, type Repo } from "../src/core/repos.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createConversation } from "../src/core/conversations.ts";
16 import { startChatBuild } from "../src/core/chat_build.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { editCount, editsOf, saveEdit } from "../src/core/working_tree.ts";
20 import { refTip } from "../src/git/read.ts";
21 import { repoDir } from "../src/git/repos.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 let dataDir: string;
28 let app: App;
29 let servers: Servers;
30 let ada: User;
31 let bob: User;
32 let repo: Repo;
33 let token: string;
34
35 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
36 if (!r.ok) throw new Error(JSON.stringify(r.error));
37 return r.value;
38 };
39 const tip = (branch: string) => refTip(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${branch}`);
40
41 async function mcpCall(name: string, args: unknown): Promise<{ error?: string; value?: any }> {
42 const res = await fetch(`${servers.url}/mcp`, {
43 method: "POST",
44 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
45 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
46 });
47 const body = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
48 const text: string = body.result.content[0]?.text ?? "";
49 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
50 }
51
52 beforeAll(async () => {
53 dataDir = await mkdtemp(join(tmpdir(), "forge-working-tree-"));
54 app = createApp({ dataDir, port: 0 });
55 servers = await serve(app);
56 ada = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase" }));
57 bob = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }));
58 repo = ok(await createRepo(app.db, app.reposRoot, { ownerId: ada.id, name: "live", visibility: "public" }));
59 ok(await commitToBranch(app, ada, repo, { message: "seed", files: [{ path: "a.txt", content: "one\ntwo\n" }] }));
60 ok(await commitToBranch(app, ada, repo, { branch: "work", message: "branch", files: [{ path: "a.txt", content: "one\ntwo\n" }] }));
61 token = createToken(app.db, ada.id, "rw", "rw").token;
62 }, 30_000);
63
64 afterAll(async () => {
65 servers?.stop();
66 app?.close();
67 await rm(dataDir, { recursive: true, force: true });
68 });
69
70 test("a live save commits nothing, the diff accumulates, a commit lands once when asked", async () => {
71 const before = await tip("work");
72 ok(await saveWorking(app, ada, repo, "work", "a.txt", "one\n2\nthree\n"));
73 ok(await saveWorking(app, ada, repo, "work", "b.txt", "new\n"));
74 expect(await tip("work")).toBe(before);
75 expect(editCount(app.db, ada.id, repo.id, "work")).toBe(2);
76 const d = (await workingDiff(app, ada, repo, "work"))!;
77 expect(d.files.map((f) => f.path)).toEqual(["a.txt", "b.txt"]);
78 expect([d.additions, d.deletions]).toEqual([3, 1]);
79 // Saving a file again replaces it: the count stays, the text is the newest.
80 ok(await saveWorking(app, ada, repo, "work", "b.txt", "newer\n"));
81 expect(editsOf(app.db, ada.id, repo.id, "work").find((e) => e.path === "b.txt")!.content).toBe("newer\n");
82 expect(await openForEdit(app, ada, repo, "work", "b.txt")).toBe("newer\n");
83 expect(await openForEdit(app, ada, repo, "work", "nothing.txt")).toBe("");
84 expect(uncommittedWords(2, "work")).toContain("2 files on work");
85 const done = ok(await commitWorking(app, ada, repo, "work", "Two files"));
86 expect(done.files).toBe(2);
87 expect(await tip("work")).toBe(done.commit);
88 expect(await tip("work")).not.toBe(before);
89 expect(editCount(app.db, ada.id, repo.id, "work")).toBe(0);
90 expect(await commitWorking(app, ada, repo, "work", "again")).toEqual({ ok: false, error: "nothing" });
91 });
92
93 test("a working tree is one person's: another writer sees none of it, and may not save to a repository they cannot write", async () => {
94 ok(await saveWorking(app, ada, repo, "work", "c.txt", "c\n"));
95 expect(editCount(app.db, bob.id, repo.id, "work")).toBe(0);
96 expect(await saveWorking(app, bob, repo, "work", "c.txt", "x")).toEqual({ ok: false, error: "forbidden" });
97 expect(await saveWorking(app, undefined, repo, "work", "c.txt", "x")).toEqual({ ok: false, error: "unauthorized" });
98 expect(discardWorking(app, ada, repo, "work")).toBe(1);
99 expect(await workingDiff(app, ada, repo, "work")).toEqual({ files: [], additions: 0, deletions: 0 });
100 });
101
102 test("refusals: the default branch, a path out of the tree, a missing branch, too many files, too large", async () => {
103 expect(await saveWorking(app, ada, repo, repo.defaultBranch, "a.txt", "x")).toEqual({ ok: false, error: "default_branch" });
104 expect(await saveWorking(app, ada, repo, "work", "../x", "x")).toEqual({ ok: false, error: "bad_path" });
105 expect(await saveWorking(app, ada, repo, "work", ".git/config", "x")).toEqual({ ok: false, error: "bad_path" });
106 expect(await saveWorking(app, ada, repo, "nope", "a.txt", "x")).toEqual({ ok: false, error: "not_found" });
107 expect(await saveWorking(app, ada, repo, "work", "big.txt", "x".repeat(2 * 1024 * 1024 + 1))).toEqual({ ok: false, error: "too_large" });
108 for (let i = 0; i < WORKING_FILES_MAX; i++) ok(await saveWorking(app, ada, repo, "work", `f${i}.txt`, "x"));
109 expect(await saveWorking(app, ada, repo, "work", "one-more.txt", "x")).toEqual({ ok: false, error: "too_many" });
110 // An existing file of the tree may still be saved at the cap.
111 ok(await saveWorking(app, ada, repo, "work", "f0.txt", "y"));
112 discardWorking(app, ada, repo, "work");
113 });
114
115 test("write_file with live: true saves to the working tree and answers without a commit", async () => {
116 const before = await tip("work");
117 const r = await mcpCall("write_file", { repo: "ada/live", branch: "work", path: "m.txt", content: "m\n", live: true });
118 expect(r.error).toBeUndefined();
119 expect(r.value.live).toBe(true);
120 expect(r.value.commit).toBeUndefined();
121 expect(r.value.says).toContain("not committed yet");
122 expect(await tip("work")).toBe(before);
123 expect(editsOf(app.db, ada.id, repo.id, "work").map((e) => e.path)).toEqual(["m.txt"]);
124 // Without live it still commits, as before.
125 const c = await mcpCall("write_file", { repo: "ada/live", branch: "work", path: "n.txt", content: "n\n", message: "n" });
126 expect(c.value.commit).toBeDefined();
127 expect(await tip("work")).not.toBe(before);
128 const refused = await mcpCall("write_file", { repo: "ada/live", branch: "main", path: "m.txt", content: "m\n", live: true });
129 expect(refused.error).toContain("branch of their own");
130 discardWorking(app, ada, repo, "work");
131 });
132
133 test("the pane: save, see the uncommitted diff with Commit, refuse another origin, commit when asked", async () => {
134 const conv = ok(createConversation(app.db, ada.id)).id;
135 const build = startChatBuild(app.db, conv, repo.id, true);
136 ok(await commitToBranch(app, ada, repo, { branch: build.branch, message: "v1", files: [{ path: "a.txt", content: "one\ntwo\n" }] }));
137 const cookie = `forge_session=${createSession(app.db, ada.id).token}`;
138 const post = (path: string, form: Record<string, string>, origin = servers.url) =>
139 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { origin, cookie }, body: new URLSearchParams(form) });
140 const before = await tip(build.branch);
141 // Another origin changes nothing.
142 expect((await post(`/talk/${conv}/work/save`, { path: "a.txt", content: "evil\n" }, "https://evil.example")).status).toBe(403);
143 expect(editCount(app.db, ada.id, repo.id, build.branch)).toBe(0);
144 // Someone else's conversation is not found.
145 const other = `forge_session=${createSession(app.db, bob.id).token}`;
146 const theirs = await fetch(`${servers.url}/talk/${conv}/work/save`, { method: "POST", redirect: "manual", headers: { origin: servers.url, cookie: other }, body: new URLSearchParams({ path: "a.txt", content: "x" }) });
147 expect(theirs.status).toBe(404);
148 expect((await post(`/talk/${conv}/work/save`, { path: "a.txt", content: "<b>changed</b>\n" })).status).toBe(303);
149 expect(await tip(build.branch)).toBe(before);
150 const diff = await (await fetch(`${servers.url}/talk/${conv}?pane=diff&fragment=pane`, { headers: { cookie } })).text();
151 expect(diff).toContain("1 file on " + build.branch);
152 expect(diff).toContain(`/talk/${conv}/work/commit`);
153 expect(diff).toContain("&lt;b&gt;changed&lt;/b&gt;");
154 expect(diff).not.toContain("<b>changed</b>");
155 const code = await (await fetch(`${servers.url}/talk/${conv}?pane=code&edit=a.txt&fragment=pane`, { headers: { cookie } })).text();
156 expect(code).toContain("&lt;b&gt;changed&lt;/b&gt;");
157 expect(code).toContain(`/talk/${conv}/work/save`);
158 expect((await post(`/talk/${conv}/work/commit`, { message: "Make it bold" })).status).toBe(303);
159 expect(await tip(build.branch)).not.toBe(before);
160 expect(editCount(app.db, ada.id, repo.id, build.branch)).toBe(0);
161 });
162
163 test("the whole working tree is capped at one commit's bytes, and the diff refuses above it", async () => {
164 const two = "x".repeat(2 * 1024 * 1024);
165 for (let i = 0; i < 5; i++) ok(await saveWorking(app, ada, repo, "work", `big${i}.txt`, two));
166 // Five files of 2 MiB are exactly the cap (10 MiB); one more byte is refused, a smaller
167 // replacement is not.
168 expect(await saveWorking(app, ada, repo, "work", "tip.txt", "x")).toEqual({ ok: false, error: "too_large" });
169 ok(await saveWorking(app, ada, repo, "work", "big0.txt", "small"));
170 ok(await saveWorking(app, ada, repo, "work", "tip.txt", "x"));
171 discardWorking(app, ada, repo, "work");
172 // Rows written past the cap by some other way: the diff builds nothing.
173 saveEdit(app.db, ada.id, repo.id, "work", "a.txt", two);
174 for (let i = 0; i < 5; i++) saveEdit(app.db, ada.id, repo.id, "work", `z${i}.txt`, two);
175 expect(await workingDiff(app, ada, repo, "work")).toBeUndefined();
176 expect(await commitWorking(app, ada, repo, "work", "m")).toEqual({ ok: false, error: "too_large" });
177 discardWorking(app, ada, repo, "work");
178 });
179
180 test("deleting a repository deletes its uncommitted text", async () => {
181 const gone = ok(await createRepo(app.db, app.reposRoot, { ownerId: ada.id, name: "gone", visibility: "public" }));
182 saveEdit(app.db, ada.id, gone.id, "work", "a.txt", "x");
183 app.db.query("DELETE FROM repo WHERE id = ?1").run(gone.id);
184 expect(editCount(app.db, ada.id, gone.id, "work")).toBe(0);
185 });
186
187 test("the Discard route throws the working tree away, for its owner only", async () => {
188 const conv = ok(createConversation(app.db, ada.id)).id;
189 const build = startChatBuild(app.db, conv, repo.id, true);
190 ok(await commitToBranch(app, ada, repo, { branch: build.branch, message: "v1", files: [{ path: "a.txt", content: "one\n" }] }));
191 ok(await saveWorking(app, ada, repo, build.branch, "a.txt", "two\n"));
192 const post = (cookie: string, origin = servers.url) => fetch(`${servers.url}/talk/${conv}/work/discard`, { method: "POST", redirect: "manual", headers: { origin, cookie }, body: new URLSearchParams({}) });
193 expect((await post(`forge_session=${createSession(app.db, ada.id).token}`, "https://evil.example")).status).toBe(403);
194 expect((await post(`forge_session=${createSession(app.db, bob.id).token}`)).status).toBe(404);
195 expect(editCount(app.db, ada.id, repo.id, build.branch)).toBe(1);
196 expect((await post(`forge_session=${createSession(app.db, ada.id).token}`)).status).toBe(303);
197 expect(editCount(app.db, ada.id, repo.id, build.branch)).toBe(0);
198 });

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

Keyboard shortcuts

Docs