diff --git a/README.md b/README.md
index 9353541..0b4e2d0 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,9 @@
# margin
**Yet another code review tool.** Yes. The one that makes sure you actually read the change, shows
-which tests run each line, and lets you break a line in place, with vim keys, to see whether any of
-them notice. See [the project page](https://antas.cz/margin/).
+which tests run each line, and lets you edit a line in place to see whether any of them notice.
+The GUI defaults to standard editing and offers Vim keybindings in Settings.
+See [the project page](https://antas.cz/margin/).
margin reviews git changes with a coding agent beside you. The agent reads the change first, lays
out a route through it in reading order and writes a note on every change: what it does, why it is
diff --git a/cmd/margin-gui/agent.go b/cmd/margin-gui/agent.go
index b8d2e97..50bef4e 100644
--- a/cmd/margin-gui/agent.go
+++ b/cmd/margin-gui/agent.go
@@ -21,6 +21,7 @@ import (
"github.com/redrick/margin/internal/cli"
"github.com/redrick/margin/internal/config"
"github.com/redrick/margin/internal/control"
+ "github.com/redrick/margin/internal/review"
)
// scrollback is how much agent output is kept to replay when the review is shown again.
@@ -46,6 +47,7 @@ func (a *Agents) SetSubmit(submit bool) {
type session struct {
cmd *exec.Cmd
+ command string
pty *os.File
lease *os.File
exited chan struct{}
@@ -73,10 +75,11 @@ func (a *Agents) Start(reviewPath, repo string, created bool, cols, rows int) (s
return s.replay(), nil
}
return "", startLeasedAgent(reviewPath, func(lease *os.File) error {
- if _, err := loadAgentReview(reviewPath, repo); err != nil {
+ rv, err := loadAgentReview(reviewPath, repo)
+ if err != nil {
return err
}
- return a.launchNew(lease, reviewPath, repo, config.Load().Agent, created, false, cols, rows)
+ return a.launchNew(lease, rv, repo, config.Load().Agent, created, false, cols, rows)
})
}
@@ -86,8 +89,13 @@ func (s *session) replay() string {
return base64.StdEncoding.EncodeToString(s.buf)
}
-func (a *Agents) launchNew(lease *os.File, path, repo, command string, created, continued bool, cols, rows int) error {
- saved := savedAgent{Command: command, Repo: resumeIdentity(repo), Run: rand.Text(), Auto: true}
+func (a *Agents) launchNew(lease *os.File, rv *review.Review, repo, command string, created, continued bool, cols, rows int) error {
+ path := rv.Path
+ preparation, err := beginWalkPreparation(rv)
+ if err != nil {
+ return err
+ }
+ saved := savedAgent{Command: command, Repo: resumeIdentity(repo), Run: rand.Text(), Auto: true, PreparingWalk: !continued && preparation != ""}
var registration *control.Server
var endpoint string
provider := agentPreset(command)
@@ -98,7 +106,7 @@ func (a *Agents) launchNew(lease *os.File, path, repo, command string, created,
log.Printf("registering the Codex conversation: %v", err)
}
}
- argv := (config.Config{Agent: command}).AgentArgv(kickoff(path, created, continued, endpoint))
+ argv := (config.Config{Agent: command}).AgentArgv(kickoff(path, created, continued, endpoint, preparation))
if provider == "claude" {
saved.ID = newClaudeID()
argv = append([]string{argv[0], "--session-id", saved.ID}, argv[1:]...)
@@ -128,7 +136,7 @@ func (a *Agents) launch(lease *os.File, path, repo string, argv []string, saved
return err
}
s := &session{
- cmd: cmd, pty: f, lease: lease, run: saved.Run, resuming: resuming,
+ cmd: cmd, command: saved.Command, pty: f, lease: lease, run: saved.Run, resuming: resuming,
exited: make(chan struct{}), registration: registration,
}
if err := updateReviewResume(path, func(record *reviewResume) bool {
@@ -352,7 +360,7 @@ func (a *Agents) pump(reviewPath string, s *session) {
}
}
-func kickoff(reviewPath string, created, continued bool, endpoint string) string {
+func kickoff(reviewPath string, created, continued bool, endpoint, preparation string) string {
command := "margin"
if endpoint != "" {
// A reused Codex app server can supply its own PATH to shell commands.
@@ -364,16 +372,24 @@ func kickoff(reviewPath string, created, continued bool, endpoint string) string
if endpoint != "" {
brief += " --gui-agent " + quoteAgentArg(endpoint)
}
+ var prompt string
if continued {
- return "Continue the saved Margin review at " + reviewPath + ". Run `" + brief + " --continue` for the saved context. " +
+ prompt = "Continue the saved Margin review at " + reviewPath + ". Run `" + brief + " --continue` for the saved context. " +
"Wait for the reader's next instruction before reviewing again, running tests or editing files."
+ } else {
+ if created || preparation != "" {
+ brief += " --new"
+ }
+ prompt = "Code review with margin. The person reads the review in the margin desktop app beside you. Review file: " + reviewPath + "\n" +
+ "Start the review: run `" + brief + "` and follow its instructions."
}
- if created {
- brief += " --new"
+ if preparation != "" {
+ prompt += "\nThe reader can review by file while you prepare the functional walkthrough. " +
+ "After step 0, save the complete grouping and run `" + command + " walkthrough-ready --review " + quoteAgentArg(reviewPath) +
+ " --preparation " + quoteAgentArg(preparation) + "` before writing notes or measuring coverage. " +
+ "If it reports a problem with the grouping, fix it and run the command again. Keep any existing reader feedback."
}
- return "Code review with margin. The person reads the review in the margin desktop app beside you, " +
- "which reloads whenever the review file changes. Review file: " + reviewPath + "\n" +
- "Start the review: run `" + brief + "` and follow its instructions."
+ return prompt
}
func quoteAgentArg(arg string) string {
diff --git a/cmd/margin-gui/agent_resume.go b/cmd/margin-gui/agent_resume.go
index 84db1a0..ba54e0d 100644
--- a/cmd/margin-gui/agent_resume.go
+++ b/cmd/margin-gui/agent_resume.go
@@ -15,12 +15,14 @@ import (
)
type AgentResumeStatus struct {
- Name string `json:"name,omitempty"`
- Saved bool `json:"saved"`
- Exact bool `json:"exact"`
- Auto bool `json:"auto"`
- CanLink bool `json:"canLink"`
- Failed bool `json:"failed"`
+ WalkAttempted bool `json:"walkAttempted,omitempty"`
+ WalkPreparing bool `json:"walkPreparing,omitempty"`
+ Name string `json:"name,omitempty"`
+ Saved bool `json:"saved"`
+ Exact bool `json:"exact"`
+ Auto bool `json:"auto"`
+ CanLink bool `json:"canLink"`
+ Failed bool `json:"failed"`
}
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
@@ -92,16 +94,17 @@ func newClaudeID() string {
}
func (a *Agents) ResumeStatus(path, repo string) AgentResumeStatus {
- saved := readReviewResume(path).Agent
+ record := readReviewResume(path)
+ saved := record.Agent
if saved == nil || saved.Repo != resumeIdentity(repo) || strings.TrimSpace(saved.Command) == "" {
- return AgentResumeStatus{CanLink: agentPreset(config.Load().Agent) != ""}
+ return AgentResumeStatus{CanLink: agentPreset(config.Load().Agent) != "", WalkAttempted: record.WalkPreparation != ""}
}
name := filepath.Base(strings.Fields(saved.Command)[0])
provider := agentPreset(saved.Command)
exact := validSessionID(provider, saved.ID)
return AgentResumeStatus{
Name: name, Saved: true, Exact: exact, Auto: saved.Auto && exact && !saved.Failed,
- CanLink: provider != "", Failed: saved.Failed,
+ CanLink: provider != "", Failed: saved.Failed, WalkAttempted: record.WalkPreparation != "", WalkPreparing: saved.PreparingWalk,
}
}
@@ -178,7 +181,7 @@ func (a *Agents) restore(path, repo string, automatic, continued bool, cols, row
return errors.New("no saved agent for this review")
}
if continued {
- return a.launchNew(lease, path, repo, saved.Command, false, true, cols, rows)
+ return a.launchNew(lease, rv, repo, saved.Command, false, true, cols, rows)
}
args, err := nativeResumeArgs(*saved)
if err != nil {
diff --git a/cmd/margin-gui/assets/answers.js b/cmd/margin-gui/assets/answers.js
index d72690b..a9dbe71 100644
--- a/cmd/margin-gui/assets/answers.js
+++ b/cmd/margin-gui/assets/answers.js
@@ -6,18 +6,29 @@ import { api, state, esc, el, toast, errText, md, openModal, closeModal } from "
let panel = null;
-export async function openAnswers(focus = "") {
+export async function openAnswers(focus, navigation, onRead) {
+ const review = state.opened;
let v;
try {
v = await api("Reviews.Answers");
} catch (e) {
- return toast(errText(e), true);
+ toast(errText(e), true);
+ return false;
}
- panel = { v, focus, editing: false, replying: "" };
+ if (review !== state.opened || (focus && !v.sections[focus])) return false;
+ panel = { v, focus, onRead, editing: false, replying: "" };
const body = el(`
`);
const m = openModal("Answers to your comments", body, "wide");
+ if (navigation) m.querySelector(".modal-head").insertBefore(navigation, m.querySelector(".modal-head > button"));
m.onkey = answersKey;
render();
+ if (focus) onRead(focus, v.sections[focus]);
+ return true;
+}
+
+export function hasAnswerDraft() {
+ const textarea = document.querySelector(".answers textarea");
+ return textarea && (panel.editing ? textarea.value !== panel.v.text : !!textarea.value.trim());
}
function render() {
@@ -67,7 +78,10 @@ function render() {
let at = 0;
for (const [id, start] of order) {
if (start > at) doc.append(el(`${md(v.text.slice(at, start))}
`));
- const sec = el(``);
+ const sec = el(``);
+ const read = () => panel.onRead(id, v.sections[id]);
+ sec.addEventListener("click", read);
+ sec.addEventListener("focus", read);
const comment = state.view?.reader?.comments.find((c) => c.id === id);
const bar = el(`${comment ? `${comment.resolved ? "resolved" : "open"}` : ""}
`);
const reply = el(``);
@@ -87,7 +101,10 @@ function render() {
const target = panel.focus && box.querySelector(`.ans-sec[data-id="${CSS.escape(panel.focus)}"]`);
if (target) {
target.classList.add("focus");
- requestAnimationFrame(() => target.scrollIntoView({ block: "start" }));
+ requestAnimationFrame(() => {
+ target.focus({ preventScroll: true });
+ target.scrollIntoView({ block: "start" });
+ });
panel.focus = "";
}
}
@@ -157,8 +174,11 @@ function answersKey(e) {
// is editing or replying.
Events.On("review:changed", async () => {
if (!panel || !document.querySelector(".modal .answers") || panel.editing || panel.replying) return;
+ const opened = state.opened, current = panel;
try {
- panel.v = await api("Reviews.Answers");
+ const v = await api("Reviews.Answers");
+ if (state.opened !== opened || panel !== current || panel.editing || panel.replying) return;
+ panel.v = v;
render();
} catch {}
});
diff --git a/cmd/margin-gui/assets/app.js b/cmd/margin-gui/assets/app.js
index 2de3925..4088c6f 100644
--- a/cmd/margin-gui/assets/app.js
+++ b/cmd/margin-gui/assets/app.js
@@ -1,7 +1,7 @@
import { Events } from "/wails/runtime.js";
import { api, $, state, hooks, toast, errText, tail, openModal, closeModal, applyTheme, setThemeMode, followsSystem } from "./core.js";
-import { openReview, openReviewFile, reviewKey, renderReview, sendComments, sendFixes } from "./review.js";
-import { loadWorkspace, loadRecent, renderSide, addFolder, selectWorktree, homeKey, backToReview, syncSideButtons, openSwitcher, switcherOpen, openSettings, navState } from "./nav.js";
+import { openReview, openReviewFile, reviewKey, renderReview, renderWalkthrough, sendComments, sendFixes } from "./review.js";
+import { loadWorkspace, loadRecent, renderSide, addFolder, selectWorktree, refreshWorktree, homeKey, backToReview, syncSideButtons, openSwitcher, switcherOpen, openSettings, navState } from "./nav.js";
// Agent terminal
@@ -75,7 +75,9 @@ async function refreshAgent(opened) {
]);
if (state.opened !== opened || request !== agentStatusRequest) return null;
opened.agent = saved ?? {};
+ opened.walkAgentLive = live;
setAgentLive(live);
+ renderWalkthrough();
$("#agent-btn").disabled = !!(opened.launching || opened.linking);
return live;
}
@@ -122,6 +124,9 @@ async function startAgent(opened, action, automatic = false) {
if (opened.launching) return;
const button = $("#agent-btn");
opened.launching = true;
+ opened.launchingWalkthrough = action === "Start" || action === "Resume" && opened.agent?.walkPreparing;
+ opened.walkFailure = false;
+ renderWalkthrough();
button.disabled = true;
// A launch changes the process status while the terminal may still receive earlier events.
++agentStatusRequest;
@@ -138,12 +143,17 @@ async function startAgent(opened, action, automatic = false) {
if (await refreshAgent(opened) && !automatic) term.focus();
} catch (e) {
if (state.opened === opened) {
+ opened.walkFailure = true;
await refreshAgent(opened).catch(() => {});
toast(errText(e), true);
}
} finally {
opened.launching = false;
- if (state.opened === opened) button.disabled = false;
+ opened.launchingWalkthrough = false;
+ if (state.opened === opened) {
+ button.disabled = false;
+ renderWalkthrough();
+ }
}
}
@@ -227,6 +237,7 @@ function togglePicker() {
function showReviewer(loading = false) {
if (loading) {
+ $("#walkthrough").classList.add("hidden");
$("#agent-btn").disabled = true;
$("#agent-link").classList.add("hidden");
}
@@ -254,7 +265,6 @@ async function crumbBack() {
if (!o) return;
const w = state.worktree;
if (w && (w.path === o.repo || w.repo?.worktrees?.some((x) => x.path === o.repo))) {
- $("#workspace").classList.remove("focus");
return selectWorktree(w, w.repo);
}
const nav = navState();
@@ -295,7 +305,7 @@ async function pickReviewFile() {
document.addEventListener("keydown", (e) => {
if (switcherOpen()) return;
- if (document.activeElement?.closest?.(".cm-editor")) return;
+ const inEditor = document.activeElement?.closest?.(".cm-editor");
const inTerm = document.activeElement?.closest?.("#terminal");
const inInput = ["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement?.tagName) && !inTerm;
if (inTerm) {
@@ -305,7 +315,7 @@ document.addEventListener("keydown", (e) => {
}
return;
}
- if ((e.ctrlKey || e.metaKey) && (e.key === "k" || e.key === "p")) {
+ if (!inEditor && (e.ctrlKey || e.metaKey) && (e.key === "k" || e.key === "p")) {
e.preventDefault();
return openSwitcher();
}
@@ -313,7 +323,8 @@ document.addEventListener("keydown", (e) => {
e.preventDefault();
return openSettings();
}
- if (inInput) return;
+ if (inEditor || inInput) return;
+ if ((e.key === "Enter" || e.key === " ") && e.target.closest?.("button, summary")) return;
if (!e.ctrlKey && !e.metaKey && !e.altKey) {
if (e.key === "\\") {
e.preventDefault();
@@ -344,7 +355,7 @@ $("#show-side").onclick = togglePicker;
$("#toggle-picker").onclick = togglePicker;
$("#crumb").onclick = crumbBack;
$("#back-review").onclick = backToReview;
-$("#wt-refresh").onclick = () => state.worktree && selectWorktree(state.worktree, state.worktree.repo);
+$("#wt-refresh").onclick = refreshWorktree;
$("#agent-btn").onclick = toggleAgent;
$("#agent-link").onclick = linkAgent;
$("#send-btn").onclick = sendComments;
diff --git a/cmd/margin-gui/assets/core.js b/cmd/margin-gui/assets/core.js
index 5b20379..43537dc 100644
--- a/cmd/margin-gui/assets/core.js
+++ b/cmd/margin-gui/assets/core.js
@@ -23,10 +23,8 @@ export const state = {
step: 0,
nudged: false,
more: false,
- filter: 0,
- showGhosts: true,
+ filter: "All notes",
split: false,
- showNotes: true,
unfold: false,
expand: {},
whole: {},
diff --git a/cmd/margin-gui/assets/discussions.js b/cmd/margin-gui/assets/discussions.js
new file mode 100644
index 0000000..89b462c
--- /dev/null
+++ b/cmd/margin-gui/assets/discussions.js
@@ -0,0 +1,127 @@
+// The comments note includes a reader's quoted follow-ups. They are not agent replies.
+export function agentReply(section = "") {
+ const lines = section.trim().split("\n").slice(1);
+ let reader = false;
+ const text = [];
+ for (const line of lines) {
+ if (line.startsWith("**Reply from the reader:**")) {
+ reader = true;
+ continue;
+ }
+ if (reader && line.startsWith(">")) continue;
+ reader = false;
+ if (!text.length && (!line.trim() || line.startsWith(">"))) continue;
+ text.push(line);
+ }
+ return text.join("\n").replace(/\n{3,}/g, "\n\n").trim();
+}
+
+export function discussionThreads(view, questions, sections) {
+ const notes = new Map();
+ for (const station of view.stations) for (const note of station.notes) {
+ if (note.qid && note.text) notes.set(note.qid, note.text);
+ }
+ const threads = new Map();
+ for (const [kind, items] of [["comment", view.reader.comments], ["question", view.reader.questions], ["diff", questions]]) {
+ for (const q of items) {
+ if (kind === "diff") {
+ const replies = questionTurns(q).filter((t) => t.answer).map((t) => ({ ...t, reply: { kind: "inline", text: t.answer } }));
+ threads.set(q.id, { ...q, kind, replies, reply: replies.at(-1)?.reply });
+ continue;
+ }
+ const section = agentReply(sections[q.id]);
+ const note = notes.get(q.id);
+ const reply = section ? { kind: "section", text: section } : note ? { kind: "note", text: note } : null;
+ threads.set(q.id, { ...q, kind, reply });
+ }
+ }
+ return threads;
+}
+
+export const questionTurns = (q) => [q, ...(q.followUps ?? [])];
+
+export function questionReply(path, thread, id) {
+ const replies = thread?.replies ?? [];
+ if (id) return replies.find((turn) => turn.id === id);
+ for (let i = replies.length - 1; i >= 0; i--) {
+ if (unreadReply(path, replies[i])) return replies[i];
+ }
+ return replies.at(-1);
+}
+
+export function questionSelection(part, from, end) {
+ if (!part?.rows) return null;
+ const rows = part.rows.filter((r) => r.n > 0 && r.n - 1 >= from && r.n - 1 <= end);
+ if (rows.length !== end - from + 1) return null;
+ return JSON.stringify([part.file, !!part.base, rows.map((r) => (r.s ?? []).map((span) => span.t).join(""))]);
+}
+
+export function nextThread(threads, station, replies, activeID, from, stepAt, include = () => true) {
+ const order = (x) => [stepAt(x.part, x.at), x.part < 0 ? Infinity : x.part, x.at];
+ const compare = (a, b) => {
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
+ return 0;
+ };
+ const items = [...threads.values()].filter((q) => q.station === station && (!replies || q.reply) && include(q));
+ items.sort((a, b) => compare(order(a), order(b)) || (a.asked ?? "").localeCompare(b.asked ?? "") || a.id.localeCompare(b.id, undefined, { numeric: true }));
+ const i = items.findIndex((q) => q.id === activeID);
+ if (i >= 0) return items.length > 1 ? items[(i + 1) % items.length] : null;
+ return items.find((q) => compare(order(q), from) >= 0) ?? items[0];
+}
+
+const seen = new Map();
+const localResolutions = new Map();
+
+function resolutionKey(path, q) {
+ return "margin.gui.resolved." + JSON.stringify([path, q.id, q.asked ?? ""]);
+}
+
+export function localResolution(path, q) {
+ const key = resolutionKey(path, q);
+ if (!localResolutions.has(key)) {
+ let stored;
+ try { stored = localStorage.getItem(key); } catch {}
+ localResolutions.set(key, stored === "true" ? true : stored === "false" ? false : undefined);
+ }
+ return localResolutions.get(key);
+}
+
+export function setLocalResolution(path, q, value) {
+ const key = resolutionKey(path, q);
+ localResolutions.set(key, value);
+ try {
+ if (value === undefined) localStorage.removeItem(key);
+ else localStorage.setItem(key, String(value));
+ } catch {}
+}
+
+function seenKey(path, q) {
+ return "margin.gui.reply." + JSON.stringify([path, q.id, q.asked ?? ""]);
+}
+
+function replyVersion(text) {
+ // Store a fingerprint so the browser's preferences do not duplicate reply text.
+ let hash = 2166136261;
+ for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 16777619);
+ return `${text.length}:${hash >>> 0}`;
+}
+
+export function unreadReply(path, q) {
+ if (q?.replies) return q.replies.some((turn) => unreadReply(path, turn));
+ if (!q?.reply) return false;
+ const key = seenKey(path, q);
+ if (!seen.has(key)) {
+ let before;
+ try { before = localStorage.getItem(key); } catch {}
+ seen.set(key, before);
+ }
+ return seen.get(key) !== replyVersion(q.reply.text);
+}
+
+export function readReply(path, q) {
+ if (!q?.reply) return;
+ const key = seenKey(path, q);
+ const version = replyVersion(q.reply.text);
+ seen.set(key, version);
+ try { localStorage.setItem(key, version); } catch {}
+}
diff --git a/cmd/margin-gui/assets/editor-mode.js b/cmd/margin-gui/assets/editor-mode.js
new file mode 100644
index 0000000..0c23cb7
--- /dev/null
+++ b/cmd/margin-gui/assets/editor-mode.js
@@ -0,0 +1,19 @@
+const key = "margin.vim";
+let mode = "standard";
+try {
+ if (localStorage.getItem(key) === "on") mode = "vim";
+} catch {}
+
+export function editorMode() {
+ return mode;
+}
+
+export function setEditorMode(next) {
+ mode = next;
+ try {
+ localStorage.setItem(key, mode === "vim" ? "on" : "off");
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/cmd/margin-gui/assets/index.html b/cmd/margin-gui/assets/index.html
index 6bcf56d..4bec67c 100644
--- a/cmd/margin-gui/assets/index.html
+++ b/cmd/margin-gui/assets/index.html
@@ -51,8 +51,9 @@ margin
+
@@ -75,7 +76,48 @@ margin
-
+
@@ -106,6 +148,8 @@
margin
+
+