diff --git a/cmd/margin-gui/assets/review.js b/cmd/margin-gui/assets/review.js index 170f9ee..f456ab7 100644 --- a/cmd/margin-gui/assets/review.js +++ b/cmd/margin-gui/assets/review.js @@ -100,6 +100,7 @@ async function loadReview(dir, arg, fresh, file, restore, browsing) { state.gh = null; state.ghErr = ""; state.ghPull = null; + document.getElementById("gh-back")?.remove(); Object.assign(state, { station: 0, note: -1, step: 0, sel: null, compose: null, editing: null, block: null, parts: {}, expand: {}, whole: {}, around: {}, known: null, query: "", spot: -1, spotLines: null, filter: "All notes" }); state.fresh = new Set(); @@ -311,6 +312,7 @@ async function selectWalkthrough(mode, event) { activeThread = ""; readingOrigin = null; state.ghPull = null; + document.getElementById("gh-back")?.remove(); Object.assign(state, { station: 0, note: -1, step: 0, sel: null, compose: null, editing: null, block: null, parts: {}, around: {}, known: null, fresh: new Set(), spot: -1, spotLines: null }); } @@ -740,7 +742,7 @@ function renderToolbar() { tb.append(discussionNav); if (state.gh) { const open = ghOpen().length; - btn(`GitHub${open ? " · " + open + " open" : ""}`, `Everything said on PR #${state.gh.number}: threads on the code and the conversation`, false, openGitHubPanel, "github"); + btn(`GitHub${open ? " · " + open + " open" : ""}`, `Everything said on PR #${state.gh.number}: threads on the code and the conversation (B)`, false, () => openGitHubPanel(true), "github"); btn("↻", "Pull comments, replies, reactions and resolved state from GitHub again", false, pullGitHub, "github").setAttribute("aria-label", "Refresh GitHub"); } btn("Export", "Your comments, flagged problems and calls, to post yourself", false, openExport, "export"); @@ -1436,7 +1438,10 @@ function commentCard(c, opts = {}) { actions.append(del); } actions.append(localResolveAction(c), ...githubActions(c), ...resolveActions(c)); + const reply = c.github ? replyParts(ghMine(c), c.id, threadKey(c), c) : null; + if (reply) actions.insertBefore(reply[0], actions.lastElementChild); card.append(actions); + if (reply) card.append(reply[1]); if (opts.jump) card.onclick = opts.jump; return threadDisclosure(card, c, "comment", opts); } @@ -3749,6 +3754,7 @@ async function loadThreads(opened = state.opened, quiet = true) { if (state.opened !== opened || state.view?.mode !== mode || request !== threadsRequest) return; state.ghPull = pull; if (state.view) { + ghPanelState(); rerenderKeepScroll(); if (document.querySelector(".modal.gh-panel")) openGitHubPanel(); } @@ -3819,34 +3825,45 @@ function githubThread(c) { const rr = reactionsRow(t.reactions); if (rr) out.push(rr); if (t.replies.length) out.push(repliesBox(t.replies)); + const check = ghCheckBox(t, true); + if (check) out.push(check); return out; } +// ghChange runs a change to a thread on GitHub and redraws with what GitHub has after it, keeping the +// thread in view in the panel even when it no longer matches its filters. +async function ghChange(t, key, call, { resolved = false, comment = null } = {}) { + const opened = state.opened; + const mode = state.view?.mode; + const request = threadsRequest; + const pull = await call(); + if (state.opened !== opened) return false; + if (comment && resolved && localResolution(state.view.path, comment) === false) { + setLocalResolution(state.view.path, comment, undefined); + } + if (resolved) expandedDisclosures.delete(key); + ghUI.keep.add(t.id); + ghUI.focus = t.id; + if (state.view?.mode !== mode || request !== threadsRequest) { + loadThreads(opened); + } else { + state.ghPull = pull; + rerenderKeepScroll(); + if (document.querySelector(".modal.gh-panel")) openGitHubPanel(); + else disclosureSummary(key)?.focus({ preventScroll: true }); + } + return true; +} + function resolveButton(t, what, key, comment) { if (!t || !(t.resolved ? t.canUnresolve : t.canResolve)) return null; const b = el(``); b.onclick = async (e) => { e.stopPropagation(); b.disabled = true; - const opened = state.opened; - const mode = state.view?.mode; - const request = threadsRequest; try { - const pull = await api("Reviews.ResolveGitHubThread", t.id, !t.resolved); - if (state.opened !== opened) return; - if (comment && !t.resolved && localResolution(state.view.path, comment) === false) { - setLocalResolution(state.view.path, comment, undefined); - } - expandedDisclosures.delete(key); - if (state.view?.mode !== mode || request !== threadsRequest) { - loadThreads(opened); - } else { - state.ghPull = pull; - rerenderKeepScroll(); - if (document.querySelector(".modal.gh-panel")) openGitHubPanel(); - else disclosureSummary(key)?.focus({ preventScroll: true }); - } - toast(`${what} ${t.resolved ? "opened again" : "resolved"} on GitHub`); + const done = await ghChange(t, key, () => api("Reviews.ResolveGitHubThread", t.id, !t.resolved), { resolved: !t.resolved, comment }); + if (done) toast(`${what} ${t.resolved ? "opened again" : "resolved"} on GitHub`); } catch (err) { b.disabled = false; toast(errText(err), true); @@ -3855,6 +3872,107 @@ function resolveButton(t, what, key, comment) { return b; } +// Replies being written to GitHub threads, by review and thread, so redraws keep what was typed. +const ghReplyDrafts = new Map(); + +// replyParts gives a thread's "Reply" button and the box the reply is written in; the box stays +// empty until the reader starts a reply. Ctrl+Enter sends, Esc closes it (the text is kept). +function replyParts(t, what, key, comment) { + if (!t || !state.gh) return null; + const dk = JSON.stringify([state.view?.path ?? "", t.id]); + const box = el(`
`); + box.onclick = (e) => e.stopPropagation(); + const button = el(``); + const draw = (focus = false) => { + box.replaceChildren(); + const draft = ghReplyDrafts.get(dk); + button.classList.toggle("on", !!draft?.open); + if (!draft?.open) return; + const check = ghCheckOf(t); + const form = el(`
+ +
${check?.text ? `` : ""} + + ${!t.resolved && t.canResolve ? `` : ""} +
`); + const ta = form.querySelector("textarea"); + const buttons = [...form.querySelectorAll("button")]; + const update = () => { + ta.readOnly = draft.pending; + for (const b of buttons) b.disabled = draft.pending || (b.type === "submit" || b.dataset.act === "resolve" ? !draft.text.trim() : false); + }; + ta.value = draft.text; + ta.oninput = () => { + draft.text = ta.value; + update(); + }; + const close = () => { + if (draft.pending) return; + draft.open = false; + if (!draft.text.trim()) ghReplyDrafts.delete(dk); + draw(); + button.focus(); + }; + const send = async (resolve) => { + if (draft.pending || !draft.text.trim()) return; + draft.pending = true; + update(); + try { + const done = await ghChange(t, key, () => api("Reviews.ReplyGitHubThread", t.id, draft.text, resolve), { resolved: resolve, comment }); + ghReplyDrafts.delete(dk); + if (done) toast(`Replied to ${what} on GitHub${resolve ? " and resolved it" : ""}`); + } catch (err) { + draft.pending = false; + if (box.isConnected) update(); + toast(errText(err), true); + } + }; + form.querySelector('[data-act="cancel"]').onclick = close; + const agent = form.querySelector('[data-act="agent"]'); + if (agent) { + agent.onclick = () => { + draft.text = (draft.text.trim() ? draft.text.trimEnd() + "\n\n" : "") + check.text.trim(); + ta.value = draft.text; + update(); + ta.focus(); + }; + } + const res = form.querySelector('[data-act="resolve"]'); + if (res) res.onclick = () => send(true); + form.onsubmit = (e) => { + e.preventDefault(); + send(false); + }; + ta.onkeydown = (e) => { + e.stopPropagation(); + if (e.isComposing) return; + if (e.key === "Escape") { + e.preventDefault(); + close(); + } else if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + send(false); + } + }; + update(); + box.append(form); + if (focus) { + ta.focus(); + ta.setSelectionRange(ta.value.length, ta.value.length); + } + }; + button.onclick = (e) => { + e.stopPropagation(); + const draft = ghReplyDrafts.get(dk) ?? { text: "", pending: false }; + draft.open = !draft.open; + if (!draft.open && !draft.text.trim()) ghReplyDrafts.delete(dk); + else ghReplyDrafts.set(dk, draft); + draw(draft.open); + }; + draw(); + return [button, box]; +} + function resolveActions(c) { if (!c.github || !state.gh) return []; const out = []; @@ -3879,6 +3997,8 @@ function threadCard(t, opts = {}) { const rr = reactionsRow(first.reactions); if (rr) card.append(rr); if (t.comments.length > 1) card.append(repliesBox(t.comments.slice(1))); + const check = ghCheckBox(t, true); + if (check) card.append(check); const actions = el(`
`); const open = el(``); open.onclick = (e) => { @@ -3889,6 +4009,8 @@ function threadCard(t, opts = {}) { const key = `github:${t.id}`; const rb = resolveButton(t, "thread", key); if (rb) actions.append(rb); + const reply = replyParts(t, "the thread", key); + if (reply) actions.append(reply[0]); if (opts.jump && t.station) { const j = el(``); j.onclick = (e) => { @@ -3899,6 +4021,7 @@ function threadCard(t, opts = {}) { actions.append(j); } card.append(actions); + if (reply) card.append(reply[1]); if (t.resolved && !opts.static) return reviewDisclosure(card, key, `resolved GitHub thread by ${first.author || "ghost"}`); card.querySelector(".ck").onclick = (e) => { e.stopPropagation(); @@ -3935,11 +4058,341 @@ function jumpToLine(station, file, line, base) { } } -// openGitHubPanel lists everything said on the pull request: threads on the code (open first, then -// those no stop shows, then resolved) and the conversation. -function openGitHubPanel() { +// The GitHub panel lists every review thread on the pull request, the reader's own included, with +// what the agent found about each beside it. Its filters, scroll and the thread last worked on +// survive leaving it for the code, so the reader can go back to exactly where they were (B). +const ghUI = { path: "", author: "", show: "open", agent: "", q: "", scroll: 0, focus: "", keep: new Set(), checks: {}, asking: false, extra: "" }; + +function ghPanelState() { + if (ghUI.path !== state.view?.path) { + Object.assign(ghUI, { path: state.view?.path ?? "", author: "", show: "open", agent: "", q: "", scroll: 0, focus: "", keep: new Set(), checks: {}, extra: "" }); + $("#gh-back")?.remove(); + loadChecks(); + } + return ghUI; +} + +async function loadChecks() { + const path = state.view?.path; + if (!path) return; + try { + const checks = await api("Reviews.GitHubChecks"); + if (state.view?.path !== path) return; + ghUI.checks = checks ?? {}; + if (document.querySelector(".modal.gh-panel")) openGitHubPanel(); + else if (state.view) rerenderKeepScroll(); + } catch {} +} + +Events.On("review:github", () => loadChecks()); + +const ghStarter = (t) => t.comments[0]?.author || "ghost"; +const ghWhere = (t) => t.path + (t.prLine ? ":" + t.prLine : t.originalLine ? ":" + t.originalLine + " (was)" : ""); +const ghCheckOf = (t) => ghUI.checks?.[t.id]; +const ghStatusLabel = { done: "done", partly: "partly done", "not done": "not done", unclear: "unclear", pending: "agent checking…" }; + +function ghThreadsAll() { + const pull = state.ghPull; + if (!pull) return []; + const all = [...Object.values(pull.mine ?? {}), ...pull.threads]; + const line = (t) => t.prLine || t.line || 0; + return all.sort((a, b) => a.path.localeCompare(b.path) || line(a) - line(b) || (a.comments[0]?.created ?? "").localeCompare(b.comments[0]?.created ?? "")); +} + +function ghMatches(t, ui) { + if (ui.author && ghStarter(t).toLowerCase() !== ui.author.toLowerCase()) return false; + if (!ui.keep.has(t.id)) { + if (ui.show === "open" && t.resolved) return false; + if (ui.show === "resolved" && !t.resolved) return false; + } + if (ui.agent) { + const st = ghCheckOf(t)?.status ?? ""; + if (ui.agent === "unchecked" && st) return false; + if (ui.agent === "work" && !["not done", "partly", "unclear"].includes(st)) return false; + if (ui.agent === "done" && st !== "done") return false; + } + if (ui.q) { + const hay = [t.path, ...t.comments.map((c) => c.author + " " + c.body), ghCheckOf(t)?.text ?? ""].join("\n").toLowerCase(); + if (!hay.includes(ui.q.toLowerCase())) return false; + } + return true; +} + +// ghStopFor finds the stop and line that show file:line (1-based, the new side), if any does. +function ghStopFor(file, line) { + for (const s of state.view?.stations ?? []) { + for (const p of s.parts ?? []) { + if (p.file === file && !p.base && line - 1 >= p.start && line - 1 <= p.end) return s.id; + } + } + return ""; +} + +// ghLeave closes the panel for the code, remembering where the reader was, and offers the way back. +function ghLeave(thread) { + const scroller = document.querySelector(".modal.gh-panel .gh-panel-body"); + if (scroller) ghUI.scroll = scroller.scrollTop; + if (thread) ghUI.focus = thread; + closeModal(); + ghBackButton(); +} + +function ghBackButton() { + if ($("#gh-back") || !state.gh) return; + const b = el(``); + b.onclick = () => openGitHubPanel(); + document.body.append(b); +} + +// ghGoTo shows file:line: on its stop when one shows it, else in a peek that returns to the panel. +function ghGoTo(file, line, thread) { + const station = ghStopFor(file, line); + if (station) { + ghLeave(thread); + return jumpToLine(station, file, line, false); + } + if (thread) ghUI.focus = thread; + const scroller = document.querySelector(".modal.gh-panel .gh-panel-body"); + if (scroller) ghUI.scroll = scroller.scrollTop; + openPeek(file, Math.max(line - 1, 0), () => openGitHubPanel()); +} + +function ghGoToThread(t) { + if (t.station) { + ghLeave(t.id); + return jumpToLine(t.station, t.path, t.line, t.side === "base"); + } + ghGoTo(t.path, t.prLine || t.originalLine || 1, t.id); +} + +const refRe = /((?:[\w@.-]+\/)*[\w@.-]+\.[A-Za-z0-9]{1,8}):(\d+)(?:[-–](\d+))?|\b([0-9a-f]{7,40})\b/g; + +// linkRefs makes file:line mentions and commit hashes in rendered text clickable. +function linkRefs(root, thread) { + const files = new Set((state.view?.stations ?? []).flatMap((s) => (s.parts ?? []).map((p) => p.file))); + for (const t of ghThreadsAll()) files.add(t.path); + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const nodes = []; + while (walker.nextNode()) if (!walker.currentNode.parentElement.closest("a, button, .gh-ref")) nodes.push(walker.currentNode); + for (const node of nodes) { + const text = node.nodeValue; + refRe.lastIndex = 0; + if (!refRe.test(text)) continue; + refRe.lastIndex = 0; + const frag = document.createDocumentFragment(); + let last = 0; + for (const m of text.matchAll(refRe)) { + const [whole, file, line, , sha] = m; + let link = null; + if (file) { + const known = files.has(file) || [...files].find((f) => f.endsWith("/" + file)); + if (known) { + const path = files.has(file) ? file : known; + link = el(``); + link.onclick = (e) => { + e.stopPropagation(); + ghGoTo(path, +line, thread); + }; + } + } else if (sha && /\d/.test(sha) && /[a-f]/.test(sha)) { + link = el(``); + link.onclick = (e) => { + e.stopPropagation(); + if (thread) ghUI.focus = thread; + const scroller = document.querySelector(".modal.gh-panel .gh-panel-body"); + if (scroller) ghUI.scroll = scroller.scrollTop; + openCommit(sha, document.querySelector(".modal.gh-panel") ? () => openGitHubPanel() : null); + }; + } + if (!link) continue; + frag.append(text.slice(last, m.index), link); + last = m.index + whole.length; + } + if (!last) continue; + frag.append(text.slice(last)); + node.replaceWith(frag); + } + return root; +} + +function ghMd(src, thread) { + return linkRefs(el(`
${ghBody(src)}
`), thread); +} + +// ghCheckBox shows what the agent said about a thread. +function ghCheckBox(t, compact = false) { + const c = ghCheckOf(t); + if (!c) return null; + const cls = c.status.replace(" ", "-"); + const box = el(`
${esc(ghStatusLabel[c.status] ?? c.status)} the agent
`); + if (c.text) box.append(ghMd(c.text, t.id)); + else if (c.status === "pending") box.append(el(`
${state.agentLive ? "The agent is looking at the code; its answer shows here." : "Start the agent; it has not answered yet."}
`)); + return box; +} + +async function askAgentAbout(ids, extra = "") { + if (!ids.length) return toast("No threads to ask about."); + if (!state.agentLive) return toast("Start the agent first, so it can check the threads.", true); + ghUI.asking = true; + try { + ghUI.checks = (await api("Reviews.AskGitHubStatus", ids, extra)) ?? ghUI.checks; + toast(`Asked the agent where ${plural(ids.length, "thread stands", "threads stand")}; answers show beside each thread.`); + } catch (e) { + toast(errText(e), true); + } finally { + ghUI.asking = false; + } + if (document.querySelector(".modal.gh-panel")) openGitHubPanel(); +} + +function ghPanelCard(t) { + const first = t.comments[0] ?? { author: "", body: "", url: "" }; + const own = t.comment ? reader().comments.find((c) => c.id === t.comment) : null; + const card = el(`
+
+
+ + ${t.resolved ? "resolved" : "open"} + ${t.outdated ? `outdated` : ""} + ${own ? `your ${esc(own.id)}` : ""} + ${esc((first.created || "").slice(0, 10))} +
+
${esc(first.author || "ghost")}
+
+
+
`); + const main = card.querySelector(".gh-card-main"); + const firstTurn = card.querySelector(".gh-turn"); + firstTurn.append(ghMd(first.body, t.id)); + const rr = reactionsRow(first.reactions); + if (rr) firstTurn.append(rr); + for (const rp of t.comments.slice(1)) { + const turn = el(`
${esc(rp.author || "ghost")} ${esc((rp.created || "").slice(0, 10))}
`); + turn.append(ghMd(rp.body, t.id)); + const r2 = reactionsRow(rp.reactions); + if (r2) turn.append(r2); + main.append(turn); + } + card.querySelector(".gh-loc").onclick = (e) => { + e.stopPropagation(); + ghGoToThread(t); + }; + const actions = el(`
`); + const go = el(``); + go.onclick = (e) => { + e.stopPropagation(); + ghGoToThread(t); + }; + actions.append(go); + const rb = resolveButton(t, "thread", `github:${t.id}`, own); + if (rb) actions.append(rb); + const reply = replyParts(t, "the thread", `github:${t.id}`, own); + if (reply) actions.append(reply[0]); + const ask = el(``); + ask.onclick = (e) => { + e.stopPropagation(); + ghUI.focus = t.id; + askAgentAbout([t.id]); + }; + actions.append(ask); + const open = el(``); + open.onclick = (e) => { + e.stopPropagation(); + openURL(first.url); + }; + actions.append(open); + main.append(actions); + if (reply) main.append(reply[1]); + const side = card.querySelector(".gh-card-side"); + const check = ghCheckBox(t); + if (check) side.append(check); + else side.append(el(`
Not checked yet. “Ask agent” has it compare the thread with the code.
`)); + card.onclick = () => { + ghUI.focus = t.id; + document.querySelectorAll(".gh-card.gh-focus").forEach((x) => x.classList.remove("gh-focus")); + card.classList.add("gh-focus"); + }; + return card; +} + +function chip(label, on, onclick, title = "") { + const b = el(``); + b.onclick = onclick; + return b; +} + +function ghFilterBar(threads, shown) { + const ui = ghUI; + const bar = el(`
`); + const redraw = () => openGitHubPanel(); + const authors = new Map(); + for (const t of threads) authors.set(ghStarter(t), (authors.get(ghStarter(t)) ?? 0) + 1); + const me = state.gh?.viewer ?? ""; + const row1 = el(`
Started by
`); + row1.append(chip(`anyone ${threads.length}`, !ui.author, () => ((ui.author = ""), redraw()))); + const names = [...authors.keys()].sort((a, b) => (b === me) - (a === me) || authors.get(b) - authors.get(a) || a.localeCompare(b)); + for (const name of names) { + row1.append(chip(`${name === me ? "me · " : ""}${esc(name)} ${authors.get(name)}`, ui.author.toLowerCase() === name.toLowerCase(), () => ((ui.author = ui.author === name ? "" : name), redraw()))); + } + const row2 = el(`
Show
`); + const byAuthor = threads.filter((t) => !ui.author || ghStarter(t).toLowerCase() === ui.author.toLowerCase()); + for (const [id, label, n] of [["open", "open", byAuthor.filter((t) => !t.resolved).length], ["resolved", "resolved", byAuthor.filter((t) => t.resolved).length], ["all", "all", byAuthor.length]]) { + row2.append(chip(`${label} ${n}`, ui.show === id, () => ((ui.show = id), ui.keep.clear(), redraw()))); + } + row2.append(el(`Agent says`)); + for (const [id, label, title] of [["", "anything", "Every thread"], ["work", "needs work", "The agent found it not done, partly done or unclear"], ["done", "done", "The agent found it done"], ["unchecked", "not checked", "Not asked yet"]]) { + row2.append(chip(label, ui.agent === id, () => ((ui.agent = id), redraw()), title)); + } + const search = el(``); + search.oninput = () => { + ui.q = search.value; + clearTimeout(search._t); + search._t = setTimeout(() => { + redraw(); + const s2 = document.querySelector(".modal.gh-panel .gh-search"); + s2?.focus(); + s2?.setSelectionRange(s2.value.length, s2.value.length); + }, 200); + }; + search.onkeydown = (e) => { + if (e.key === "Escape" && search.value) { + e.stopPropagation(); + search.value = ""; + search.oninput(); + } + }; + row2.append(el(``), search); + const askable = shown.filter((t) => !t.resolved || ui.show !== "open"); + const row3 = el(`
`); + const ask = el(``); + ask.disabled = !askable.length || ghUI.asking; + const extra = el(``); + extra.oninput = () => (ui.extra = extra.value); + extra.onkeydown = (e) => { + if (e.key === "Enter") ask.click(); + }; + ask.onclick = () => askAgentAbout(askable.map((t) => t.id), ui.extra); + row3.append(ask, extra); + if (!state.agentLive) row3.append(el(`start the agent first`)); + bar.append(row1, row2, row3); + return bar; +} + +// openGitHubPanel opens the panel, or redraws it in place, keeping the reader's place in it. +function openGitHubPanel(fresh = false) { + const ui = ghPanelState(); const pull = state.ghPull; - const body = el(`
`); + const existing = document.querySelector(".modal.gh-panel .gh-panel-body"); + let anchor = null; + if (existing) { + ui.scroll = existing.scrollTop; + const a = ui.focus && existing.querySelector(`[data-thread="${CSS.escape(ui.focus)}"]`); + if (a) anchor = { id: ui.focus, off: a.offsetTop - existing.scrollTop }; + } else if (fresh) { + ui.keep.clear(); + } + $("#gh-back")?.remove(); + const body = el(`
`); const head = prHead(state.gh); const re = el(``); re.onclick = pullGitHub; @@ -3948,24 +4401,33 @@ function openGitHubPanel() { if (!pull) { body.append(el(`

Nothing pulled yet.

`)); } else { - const all = pull.threads; - const groups = [ - ["Open, on lines in this review", all.filter((t) => !t.resolved && t.station)], - ["Open, on lines this review does not show", all.filter((t) => !t.resolved && !t.station)], - ["Resolved", all.filter((t) => t.resolved)], - ]; - for (const [h, ts] of groups) { - if (!ts.length) continue; - body.append(el(`

${h} (${ts.length})

`)); - for (const t of ts) body.append(threadCard(t, { where: true, static: true, jump: () => jumpToLine(t.station, t.path, t.line, t.side === "base") })); - } - const mine = Object.keys(pull.mine).length; - if (mine) body.append(el(`

${plural(mine, "thread", "threads")} started by your posted comments ${mine > 1 ? "are" : "is"} shown on those comments.

`)); - body.append(el(`

Conversation (${pull.conversation.length})

`)); - if (!pull.conversation.length) body.append(el(`

Nothing said outside the code.

`)); - for (const p of pull.conversation) body.append(ghPostCard(p)); + const all = ghThreadsAll(); + const shown = all.filter((t) => ghMatches(t, ui)); + body.append(ghFilterBar(all, shown)); + const list = el(`
`); + if (!shown.length) list.append(el(`

No thread matches.${all.length ? "" : " Nobody commented on the code yet."}

`)); + for (const t of shown) list.append(ghPanelCard(t)); + body.append(list); + const conv = pull.conversation.filter((p) => (!ui.author || (p.author || "").toLowerCase() === ui.author.toLowerCase()) && (!ui.q || (p.author + " " + p.body).toLowerCase().includes(ui.q.toLowerCase()))); + const det = el(`

Conversation (${conv.length})

`); + det.ontoggle = () => (ui.convOpen = det.open); + if (!conv.length) det.append(el(`

Nothing said outside the code${ui.author ? " by " + esc(ui.author) : ""}.

`)); + for (const p of conv) det.append(ghPostCard(p)); + body.append(det); + } + let m = existing?.closest(".modal"); + if (m) { + existing.replaceWith(body); + } else { + m = openModal(`GitHub · PR #${state.gh.number}`, body, "wide gh-panel").querySelector(".modal"); + } + const a = anchor && body.querySelector(`[data-thread="${CSS.escape(anchor.id)}"]`); + if (a) body.scrollTop = a.offsetTop - anchor.off; + else if (!fresh || existing) body.scrollTop = ui.scroll; + if (!existing && !fresh && ui.focus) { + const f = body.querySelector(`[data-thread="${CSS.escape(ui.focus)}"]`); + if (f) requestAnimationFrame(() => f.scrollIntoView({ block: "nearest" })); } - const m = openModal(`GitHub · PR #${state.gh.number}`, body, "narrow gh-panel"); return m; } @@ -4151,11 +4613,13 @@ async function openGitHubReview() { // Overlays: peek, commit, export, help -async function openPeek(file, line) { +async function openPeek(file, line, onclosed = null) { try { - showPeek(await api("Reviews.Peek", file, line)); + const m = showPeek(await api("Reviews.Peek", file, line)); + if (onclosed) m.onclosed = onclosed; } catch (e) { toast(errText(e), true); + onclosed?.(); } } @@ -4164,16 +4628,23 @@ function showPeek(pv) { for (const r of pv.rows) { code.append(el(`
${r.n}${renderSpans(r.s, "") || " "}
`)); } - openModal(pv.title, code); + const m = openModal(pv.title, code); requestAnimationFrame(() => code.querySelector(".row.sel")?.scrollIntoView({ block: "center" })); + return m; } -async function openCommit(sha) { +async function openCommit(sha, onclosed = null) { try { const pv = await api("Reviews.Commit", sha); - openModal(pv.title, el(`
${esc(pv.text)}
`)); + const pre = el(`
${esc(pv.text)}
`); + const m = openModal(pv.title, pre); + if (onclosed) { + linkRefs(pre); + m.onclosed = onclosed; + } } catch (e) { toast(errText(e), true); + onclosed?.(); } } @@ -4200,7 +4671,7 @@ const helpKeys = [ ["Walk", [["space", "next step; at the end of a stop, the next stop"], ["b", "previous step"], ["w", "switch between step by step and the full view"], ["e", "more of the stop card or overview; on a draft comment, edit it"], ["y n ?", "answer the orient question (overview)"]]], ["Move", [["} {", "next / previous stop"], ["] [", "next / previous note"], ["j k", "move the selected line"], ["J K shift+click", "select a block of lines"], ["ctrl+d ctrl+u", "half a page down / up"], ["g G", "top / bottom"], ["h l 0", "scroll code sideways / back"], ["N", "next new note (or previous match)"], ["L", "follow the note the selected note mentions (stop:n); again for the next one"], ["ctrl+o", "back to where you followed a mention from"]]], ["Judge", [["1 2 3", "verdict: looks good / needs changes / not sure"], ["space", "mark the selected note read in the full view"], ["?", "agree with the selected problem"], ["P", "ask the agent to fix the problems you agreed with and the stops that need changes"], ["x", "dismiss the selected note"], ["enter", "tick the selected call"], ["v", "reveal note cards on this stop"]]], - ["Talk", [["c", "comment on the selected line (draft); Edit on its card rewords it"], ["S", "send all drafts to the agent"], ["A", "the agent's answers to your comments: read, edit, reply"], ["a", "ask the agent about the selected line"], ["y Y", "copy the note / the whole stop"], ["`", "focus the agent terminal; ctrl+esc leaves it"]]], + ["Talk", [["c", "comment on the selected line (draft); Edit on its card rewords it"], ["S", "send all drafts to the agent"], ["A", "the agent's answers to your comments: read, edit, reply"], ["B", "the GitHub panel, back where you left it"], ["a", "ask the agent about the selected line"], ["y Y", "copy the note / the whole stop"], ["`", "focus the agent terminal; ctrl+esc leaves it"]]], ["See", [["/", "search; n N next / previous"], ["F", "filter notes by kind or focus"], ["n", "cycle note visibility"], ["s", "switch between inline and split"], ["z", "fold unchanged code"], ["+ -", "more / less context on the selected part"], ["f", "whole file of the selected part"], ["t", "tests that run the selected line"], ["T", "run them (the stop's tests when no line is selected)"], ["i", "try a change to the selected line or block: edit or delete it, its tests run against that, then it is put back"], ["o", "show or hide the test output"], ["u U", "next / previous untested change"], ["esc", "end search or spotlight, close an overlay"], ["r", "reload"], ["\\", "show or hide the sidebar"], ["ctrl+k", "go to a repository, worktree, branch or review"], ["ctrl+,", "settings"]]], ]; @@ -4310,6 +4781,7 @@ export function reviewKey(e) { S: sendComments, P: sendFixes, A: () => openDiscussionAnswers(), + B: () => (state.gh ? openGitHubPanel() : toast("No GitHub pull request for this review.")), r: () => reload().then(() => toast("reloaded")), H: openHelp, L: followSelectedRef, diff --git a/cmd/margin-gui/assets/style.css b/cmd/margin-gui/assets/style.css index d3d7c23..1c6555d 100644 --- a/cmd/margin-gui/assets/style.css +++ b/cmd/margin-gui/assets/style.css @@ -963,3 +963,49 @@ button.linkish:hover { text-decoration: underline; } .gh-reply .gh-md { margin-top: 0; } .m-gh { color: var(--accent); } .modal.gh-panel .gh-confirm > .comment { margin: 6px 0; } + +/* GitHub panel: every thread with what the agent found beside it */ +.modal.gh-panel { width: min(1400px, 95vw); height: 88vh; max-height: 88vh; } +.gh-panel-body { display: flex; flex-direction: column; gap: 8px; } +.gh-filters { position: sticky; top: -10px; z-index: 2; margin: 0 -14px; padding: 8px 14px; background: var(--bg-1); border-bottom: 1px solid var(--line); display: flex; flex-direction: column; gap: 6px; } +.gh-frow { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; } +.gh-frow .spacer { flex: 1; } +.gh-flabel { font-size: 11.5px; color: var(--fg-faint); margin: 0 2px 0 6px; } +.gh-flabel:first-child { margin-left: 0; min-width: 72px; } +.gh-search, .gh-extra { font: 12.5px var(--sans, inherit); background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 3px 8px; } +.gh-search { width: 240px; } +.gh-extra { flex: 1; min-width: 200px; } +.gh-search:focus, .gh-extra:focus { border-color: var(--accent); outline: none; } +.gh-cards { display: flex; flex-direction: column; gap: 10px; } +.gh-card { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 14px; padding: 10px 12px; border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: 8px; background: var(--bg); scroll-margin-top: 120px; } +.gh-card.gh-is-resolved { border-left-color: var(--ok); } +.gh-card.gh-is-resolved .gh-card-main { opacity: .8; } +.gh-card.gh-focus { box-shadow: 0 0 0 2px var(--accent); } +@media (max-width: 900px) { .gh-card { grid-template-columns: minmax(0, 1fr); } } +.gh-card-main { display: flex; flex-direction: column; gap: 6px; min-width: 0; } +.gh-card-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } +.gh-card-head .spacer { flex: 1; } +.gh-loc { font: 12.5px var(--mono); } +.badge.gh-open { background: var(--issue-tint); color: var(--bad-fg); } +.gh-turn { font-size: 13px; } +.gh-turn > b { font-size: 12.5px; } +.gh-turn-reply { border-left: 2px solid var(--line); padding-left: 10px; margin-left: 2px; } +.gh-card-side { min-width: 0; } +.gh-check { border: 1px solid var(--line); border-radius: 6px; padding: 8px 10px; background: var(--bg-1); font-size: 13px; } +.gh-check.compact { margin-top: 6px; font-size: 12.5px; padding: 6px 8px; } +.gh-check-none { border-style: dashed; background: none; } +.gh-check-done { border-color: var(--ok); background: var(--good-tint); } +.gh-check-not-done { border-color: var(--issue); background: var(--bad-tint); } +.gh-check-partly, .gh-check-unclear { border-color: var(--warn); } +.gh-check-head { display: flex; align-items: center; gap: 6px; } +.gh-reply-box:empty { display: none; } +.gh-reply-box .ans-reply textarea { min-height: 70px; } +.badge.gh-status-done { background: var(--good-tint); color: var(--good-fg); } +.badge.gh-status-not-done { background: var(--bad-tint); color: var(--bad-fg); } +.badge.gh-status-partly, .badge.gh-status-unclear { color: var(--warn-fg); border: 1px solid var(--warn); } +.badge.gh-status-pending { color: var(--fg-dim); } +.gh-ref { font: 12px var(--mono); } +.gh-conv > summary { cursor: pointer; list-style: revert; } +.gh-conv > summary h4 { display: inline; } +.gh-conv { display: flex; flex-direction: column; gap: 8px; } +.gh-back { position: fixed; left: 16px; bottom: 84px; z-index: 30; padding: 6px 12px; border-radius: 18px; background: var(--primary-bg); color: var(--on-primary); border: 1px solid var(--primary-line); box-shadow: 0 6px 20px rgba(0, 0, 0, .35); cursor: pointer; font-size: 12.5px; } diff --git a/cmd/margin-gui/ghstatus.go b/cmd/margin-gui/ghstatus.go new file mode 100644 index 0000000..99f1b4b --- /dev/null +++ b/cmd/margin-gui/ghstatus.go @@ -0,0 +1,213 @@ +package main + +import ( + "errors" + "fmt" + "os" + "regexp" + "strings" + + "github.com/redrick/margin/internal/fsx" + "github.com/redrick/margin/internal/github" + "github.com/redrick/margin/internal/review" + "github.com/redrick/margin/internal/text" +) + +// The GitHub note is the markdown file, beside the review, where the agent says where the pull +// request's review threads stand: one section per thread, headed by the thread's id. margin writes +// each section with the thread as GitHub has it and "Status: pending"; the agent replaces the status +// and says what it found below it. + +// GitHubCheck is what the agent said about one thread. +type GitHubCheck struct { + // Status is done, partly, not done, unclear, or pending while the agent has not answered. + Status string `json:"status"` + Text string `json:"text"` +} + +const ghPending = "pending" + +var ghHeading = regexp.MustCompile(`(?m)^## +(\S+)`) +var ghStatusLine = regexp.MustCompile(`(?mi)^[*_\s]*status[*_\s]*:[*_\s]*([^\n]*)$`) + +// ghSections splits the note into its thread sections, by thread id, in the order they come. +func ghSections(doc string) (ids []string, sections map[string]string) { + sections = map[string]string{} + hs := ghHeading.FindAllStringSubmatchIndex(doc, -1) + for i, h := range hs { + end := len(doc) + if i+1 < len(hs) { + end = hs[i+1][0] + } + id := doc[h[2]:h[3]] + if _, seen := sections[id]; seen { + continue + } + ids = append(ids, id) + sections[id] = doc[h[0]:end] + } + return ids, sections +} + +// ghCheck reads the agent's status and answer out of one section: the last status line, and what +// follows it. +func ghCheck(section string) GitHubCheck { + ms := ghStatusLine.FindAllStringSubmatchIndex(section, -1) + if len(ms) == 0 { + return GitHubCheck{Status: ghPending} + } + m := ms[len(ms)-1] + status := strings.ToLower(strings.Trim(section[m[2]:m[3]], "*_ .`")) + switch { + case strings.HasPrefix(status, "pending"): + status = ghPending + case strings.HasPrefix(status, "not done"), strings.HasPrefix(status, "not fixed"), strings.HasPrefix(status, "open"): + status = "not done" + case strings.HasPrefix(status, "partly"), strings.HasPrefix(status, "partial"): + status = "partly" + case strings.HasPrefix(status, "done"), strings.HasPrefix(status, "fixed"), strings.HasPrefix(status, "resolved"): + status = "done" + default: + status = "unclear" + } + return GitHubCheck{Status: status, Text: strings.TrimSpace(section[m[1]:])} +} + +// GitHubChecks reads what the agent said about the pull request's threads, by thread id. +func (r *Reviews) GitHubChecks() (map[string]GitHubCheck, error) { + path := r.current() + if path == "" { + return nil, errors.New("no review open") + } + data, err := os.ReadFile(review.GitHubPath(path)) + if errors.Is(err, os.ErrNotExist) { + return map[string]GitHubCheck{}, nil + } + if err != nil { + return nil, err + } + _, secs := ghSections(string(data)) + out := map[string]GitHubCheck{} + for id, sec := range secs { + out[id] = ghCheck(sec) + } + return out, nil +} + +// AskGitHubStatus writes the threads into the GitHub note, waiting for the agent, and asks the agent +// to check each against the code and say where it stands. Sections of other threads stay. +func (r *Reviews) AskGitHubStatus(ids []string, extra string) (map[string]GitHubCheck, error) { + path := r.current() + if path == "" { + return nil, errors.New("no review open") + } + if !r.agents.Running(path) { + return nil, errors.New("start the agent first, so it can check the threads") + } + if len(ids) == 0 { + return nil, errors.New("no threads to check") + } + d, err := r.document(0) + if err != nil { + return nil, err + } + r.gh.mu.Lock() + pr, known := r.gh.pr, r.gh.threads + if r.gh.path != d.Review.Path { + pr = nil + } + r.gh.mu.Unlock() + if pr == nil { + return nil, errors.New("pull from GitHub first") + } + var threads []*github.Thread + for _, id := range ids { + t := known[id] + if t == nil { + return nil, fmt.Errorf("margin does not know thread %s; pull from GitHub again", id) + } + threads = append(threads, t) + } + note := review.GitHubPath(path) + data, err := os.ReadFile(note) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + doc := string(data) + if strings.TrimSpace(doc) == "" { + doc = fmt.Sprintf("# Review threads on PR #%d\n\nmargin writes each thread below; the agent replaces `Status: pending` and says what it found.\n", pr.Number) + } + for _, t := range threads { + doc = putGHSection(doc, t.ID, ghSection(t)) + } + if err := fsx.WriteFileAtomic(note, []byte(doc), 0o644); err != nil { + return nil, err + } + if err := r.agents.Send(path, ghStatusMessage(pr, threads, note, extra)); err != nil { + return nil, fmt.Errorf("written to %s, but not sent: %w", note, err) + } + return r.GitHubChecks() +} + +// putGHSection replaces the section of thread id, or adds it at the end. +func putGHSection(doc, id, section string) string { + _, secs := ghSections(doc) + if old, ok := secs[id]; ok { + i := strings.Index(doc, old) + return doc[:i] + section + "\n" + doc[i+len(old):] + } + return strings.TrimRight(doc, "\n") + "\n\n" + section +} + +func ghSection(t *github.Thread) string { + var b strings.Builder + where := t.Path + switch { + case t.Line > 0: + where += fmt.Sprintf(":%d", t.Line) + case t.OriginalLine > 0: + where += fmt.Sprintf(":%d (outdated, first written on that line)", t.OriginalLine) + } + state := "open" + if t.Resolved { + state = "resolved" + } + starter := "ghost" + if len(t.Comments) > 0 && t.Comments[0].Author != "" { + starter = t.Comments[0].Author + } + fmt.Fprintf(&b, "## %s\n\n`%s` · started by %s · %s on GitHub\n\n", t.ID, where, starter, state) + for i, c := range t.Comments { + if i > 0 { + b.WriteString(">\n") + } + author := c.Author + if author == "" { + author = "ghost" + } + body := text.Sanitize(strings.TrimSpace(c.Body)) + fmt.Fprintf(&b, "> **%s:** %s\n", author, strings.ReplaceAll(body, "\n", "\n> ")) + } + b.WriteString("\nStatus: pending\n") + return b.String() +} + +func ghStatusMessage(pr *github.PR, threads []*github.Thread, note, extra string) string { + list := make([]string, len(threads)) + for i, t := range threads { + list[i] = t.ID + } + msg := fmt.Sprintf("[margin github] The reader wants to know where %d review thread(s) on PR #%d stand (head %s). "+ + "Each is written out in %s, one section per thread, headed by its id: %s. "+ + "For each section read the thread, then check the current code, and any commit a reply names (git show ), "+ + "to decide whether what the thread asks for is really done. "+ + "Replace `Status: pending` with exactly one of `Status: done`, `Status: partly`, `Status: not done` or `Status: unclear`, "+ + "then below it say in a few short sentences what you found: what was fixed, what is still missing or wrong. "+ + "Name the code as repo-relative path:line with current line numbers (e.g. `internal/x/y.go:42`), so the reader can jump there; name commits by short sha. "+ + "Do not change code, do not post or resolve anything on GitHub, and leave the quoted thread and the other sections as they are.", + len(threads), pr.Number, pr.HeadSHA[:min(9, len(pr.HeadSHA))], note, strings.Join(list, ", ")) + if extra = strings.Join(strings.Fields(text.Sanitize(extra)), " "); extra != "" { + msg += " The reader adds: " + extra + } + return msg +} diff --git a/cmd/margin-gui/ghstatus_test.go b/cmd/margin-gui/ghstatus_test.go new file mode 100644 index 0000000..528ed3a --- /dev/null +++ b/cmd/margin-gui/ghstatus_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "strings" + "testing" + + "github.com/redrick/margin/internal/github" +) + +func TestGitHubNote(t *testing.T) { + t1 := &github.Thread{ID: "PRRT_a", Path: "x.go", Line: 4, Comments: []github.TComment{ + {Author: "me", Body: "rename this\n## not a heading"}, {Author: "bob", Body: "fixed in abc123"}}} + t2 := &github.Thread{ID: "PRRT_b", Path: "y.go", OriginalLine: 9, Outdated: true, Resolved: true, + Comments: []github.TComment{{Author: "me", Body: "why?"}}} + + doc := putGHSection("# head\n", t1.ID, ghSection(t1)) + doc = putGHSection(doc, t2.ID, ghSection(t2)) + ids, secs := ghSections(doc) + if strings.Join(ids, ",") != "PRRT_a,PRRT_b" { + t.Fatalf("ids %v in\n%s", ids, doc) + } + if c := ghCheck(secs["PRRT_a"]); c.Status != ghPending || c.Text != "" { + t.Fatalf("fresh section %+v", c) + } + if !strings.Contains(secs["PRRT_a"], "> **bob:** fixed in abc123") || !strings.Contains(secs["PRRT_b"], "`y.go:9 (outdated") { + t.Fatalf("sections\n%s", doc) + } + + // The agent answers the first; asking again about the second keeps that answer. + doc = strings.Replace(doc, "Status: pending\n", "**Status:** Partly.\n\nRenamed, but `x.go:12` still uses the old name.\n", 1) + doc = putGHSection(doc, t2.ID, ghSection(t2)) + _, secs = ghSections(doc) + c := ghCheck(secs["PRRT_a"]) + if c.Status != "partly" || c.Text != "Renamed, but `x.go:12` still uses the old name." { + t.Fatalf("answer %+v", c) + } + if ghCheck(secs["PRRT_b"]).Status != ghPending || strings.Count(doc, "## PRRT_b") != 1 { + t.Fatalf("second ask\n%s", doc) + } + + for in, want := range map[string]string{"Status: done": "done", "status: Not done — x": "not done", "Status: fixed": "done", "Status: hmm": "unclear"} { + if got := ghCheck("## T\n\n" + in + "\n").Status; got != want { + t.Errorf("%q: %q, want %q", in, got, want) + } + } +} diff --git a/cmd/margin-gui/github.go b/cmd/margin-gui/github.go index 4bbdf03..57ed708 100644 --- a/cmd/margin-gui/github.go +++ b/cmd/margin-gui/github.go @@ -22,8 +22,9 @@ type ghCache struct { path string pr *github.PR posting bool - // threads holds the ids of the review threads last read from GitHub; only those can be resolved. - threads map[string]bool + // threads holds the review threads last read from GitHub, by id; only those can be resolved or + // handed to the agent. + threads map[string]*github.Thread } var ghRun github.Runner = github.GH @@ -305,10 +306,14 @@ type ThreadView struct { // Path and PRLine are where GitHub has it; PRLine is 0 when GitHub lost the line. Path string `json:"path"` PRLine int `json:"prLine"` + // OriginalLine is where the thread was first written, for a thread GitHub lost the line of. + OriginalLine int `json:"originalLine,omitempty"` // Station, Line (1-based) and Side place it in the review; Station is empty when no stop shows it. Station string `json:"station,omitempty"` Line int `json:"line,omitempty"` Side string `json:"side,omitempty"` + // Comment is the reader's own comment that started the thread, when margin posted it. + Comment string `json:"comment,omitempty"` } // GitHubPull is everything said on the pull request, as last read. @@ -352,12 +357,15 @@ func (r *Reviews) GitHubThreads() (*GitHubPull, error) { c := toGitHub(q) if t := github.FindThread(threads, q.GitHub, pr.Place(c).Path, c.Body); t != nil { mine[t] = true - out.Mine[q.ID] = threadView(t) + v := threadView(t) + v.Station, v.Line, v.Side = placeThread(d, pr, t) + v.Comment = q.ID + out.Mine[q.ID] = v } } - known := map[string]bool{} + known := map[string]*github.Thread{} for _, t := range threads { - known[t.ID] = true + known[t.ID] = t if mine[t] { continue } @@ -375,7 +383,7 @@ func (r *Reviews) GitHubThreads() (*GitHubPull, error) { func threadView(t *github.Thread) ThreadView { v := ThreadView{ID: t.ID, Resolved: t.Resolved, CanResolve: t.CanResolve, CanUnresolve: t.CanUnresolve, Outdated: t.Outdated, - Comments: t.Comments, Reactions: []github.Reaction{}, Replies: []github.TComment{}, Path: t.Path, PRLine: t.Line} + Comments: t.Comments, Reactions: []github.Reaction{}, Replies: []github.TComment{}, Path: t.Path, PRLine: t.Line, OriginalLine: t.OriginalLine} if v.Comments == nil { v.Comments = []github.TComment{} } @@ -438,21 +446,50 @@ func abs(n int) int { // ResolveGitHubThread resolves a review thread on GitHub, or opens it again, when the reader clicks // it. GitHub refuses it when they may not. func (r *Reviews) ResolveGitHubThread(thread string, resolved bool) (*GitHubPull, error) { - d, err := r.document(0) + d, pr, err := r.knownThread(thread) if err != nil { return nil, err } + if err := pr.SetResolved(ghRun, d.Review.RepoDir(), thread, resolved); err != nil { + return nil, err + } + return r.GitHubThreads() +} + +// ReplyGitHubThread posts the reader's reply at the end of a review thread on GitHub, and resolves the +// thread after it when they asked for that too. A reply that went out stays out even when resolving +// fails; the error says so. +func (r *Reviews) ReplyGitHubThread(thread, body string, resolve bool) (*GitHubPull, error) { + d, pr, err := r.knownThread(thread) + if err != nil { + return nil, err + } + repo := d.Review.RepoDir() + if _, err := pr.Reply(ghRun, repo, thread, body); err != nil { + return nil, err + } + if resolve { + if err := pr.SetResolved(ghRun, repo, thread, true); err != nil { + return nil, fmt.Errorf("replied, but resolving failed: %w", err) + } + } + return r.GitHubThreads() +} + +// knownThread checks the thread is one margin last read from GitHub for the open review. +func (r *Reviews) knownThread(thread string) (*doc.Doc, *github.PR, error) { + d, err := r.document(0) + if err != nil { + return nil, nil, err + } r.gh.mu.Lock() - pr, known := r.gh.pr, r.gh.threads[thread] + pr, known := r.gh.pr, r.gh.threads[thread] != nil if r.gh.path != d.Review.Path { pr = nil } r.gh.mu.Unlock() if pr == nil || !known { - return nil, errors.New("margin does not know that thread; pull from GitHub first") - } - if err := pr.SetResolved(ghRun, d.Review.RepoDir(), thread, resolved); err != nil { - return nil, err + return nil, nil, errors.New("margin does not know that thread; pull from GitHub first") } - return r.GitHubThreads() + return d, pr, nil } diff --git a/cmd/margin-gui/github_test.go b/cmd/margin-gui/github_test.go index 0399f1e..aea4b31 100644 --- a/cmd/margin-gui/github_test.go +++ b/cmd/margin-gui/github_test.go @@ -43,6 +43,9 @@ func fakeGH(t *testing.T, repo, file string, otherLine int, posts *[]map[string] case strings.HasPrefix(cmd, "api graphql -f owner="): return []byte(`{"data":{"repository":{"pullRequest":{"comments":{"nodes":[{"url":"u","body":"looks fine","createdAt":"2026-01-02","author":{"login":"other"}}]},` + `"reviews":{"nodes":[{"body":"","state":"COMMENTED","submittedAt":"2026-01-01"},{"body":"ok","state":"APPROVED","submittedAt":"2026-01-01"}]}}}}}`), nil + case strings.HasPrefix(cmd, "api graphql -f id=T9 -f body="): + *posts = append(*posts, map[string]any{"_to": "reply", "body": strings.TrimPrefix(args[5], "body=")}) + return []byte(`{"data":{"addPullRequestReviewThreadReply":{"comment":{"url":"https://github.com/o/r/pull/7#discussion_r50"}}}}`), nil case strings.HasPrefix(cmd, "api graphql -f id=T9"): *posts = append(*posts, map[string]any{"_to": "resolve"}) return []byte(`{}`), nil @@ -150,7 +153,7 @@ func TestGitHubPosting(t *testing.T) { if err != nil { t.Fatal(err) } - if v, ok := pull.Mine["c2"]; !ok || v.Reactions[0].Content != "HEART" || !v.CanResolve || v.ID != "T9" { + if v, ok := pull.Mine["c2"]; !ok || v.Reactions[0].Content != "HEART" || !v.CanResolve || v.ID != "T9" || v.Comment != "c2" { t.Fatalf("mine %+v", pull.Mine) } if len(pull.Threads) != 2 || pull.Threads[0].Station != "reserve" || pull.Threads[0].Line != p.Range.End+1 || @@ -166,4 +169,20 @@ func TestGitHubPosting(t *testing.T) { if _, err := r.ResolveGitHubThread("T-unknown", true); err == nil { t.Fatal("resolved a thread margin never read") } + + n := len(posts) + if _, err := r.ReplyGitHubThread("T9", " fixed in abc123 ", false); err != nil || len(posts) != n+1 || + posts[n]["_to"] != "reply" || posts[n]["body"] != "fixed in abc123" { + t.Fatalf("reply: %v %v", err, posts[n:]) + } + if _, err := r.ReplyGitHubThread("T9", "done", true); err != nil || len(posts) != n+3 || + posts[n+1]["_to"] != "reply" || posts[n+2]["_to"] != "resolve" { + t.Fatalf("reply and resolve: %v %v", err, posts[n:]) + } + if _, err := r.ReplyGitHubThread("T9", " ", false); err == nil { + t.Fatal("sent an empty reply") + } + if _, err := r.ReplyGitHubThread("T-unknown", "hi", false); err == nil { + t.Fatal("replied to a thread margin never read") + } } diff --git a/cmd/margin-gui/review.go b/cmd/margin-gui/review.go index 863f949..ad17d3a 100644 --- a/cmd/margin-gui/review.go +++ b/cmd/margin-gui/review.go @@ -391,7 +391,7 @@ func (r *Reviews) loadCurrent(expectedPath string, requested walkMode) (*View, e } } if !reused { - paths := append(d.WatchPaths(), review.StatePath(path), review.CommentsPath(path)) + paths := append(d.WatchPaths(), review.StatePath(path), review.CommentsPath(path), review.GitHubPath(path)) if snapshot != nil { paths = snapshot.inputs.AppendWatchPaths(append(paths, walk.alternate.WatchPaths()...)) } @@ -512,6 +512,8 @@ func (r *Reviews) watch(paths []string) { } if len(changed) == 1 && changed[0] == review.StatePath(path) { r.app.Event.Emit("review:reader") + } else if len(changed) == 1 && changed[0] == review.GitHubPath(path) { + r.app.Event.Emit("review:github") } else { r.app.Event.Emit("review:changed") } diff --git a/docs/gui.md b/docs/gui.md index a92e24d..a08b34e 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -314,9 +314,31 @@ shows the reactions and replies it got on GitHub. Everyone else's review threads come into the review too. Each one is drawn on its line, found by the line's text in the pull request's diff, with its replies and reactions; resolved threads are folded until you click their header. *Resolve on GitHub* (or *Unresolve*) appears on any thread -GitHub lets you change. *GitHub · N open* in the toolbar opens a panel with every thread: those on -lines the review shows (with *Go to line*), those on lines it does not show or that GitHub marks -outdated, the resolved ones, and the pull request's conversation and review texts. +GitHub lets you change. + +*Reply on GitHub* opens a box under any thread, yours or someone else's, on its line or in the +panel. The reply goes out as you wrote it (Markdown) when you click *Reply* or press `Ctrl+Enter`; +*Reply & resolve* sends it and then resolves the thread. When the agent has checked the thread, +*Use agent's answer* puts what it found into the box for you to edit first. `Esc` closes the box +and keeps what you typed. + +*GitHub · N open* in the toolbar (or `B`) opens a panel with every review thread on the pull +request, your own included, ordered by file and line, and the conversation below them. Filter it by +who started a thread (*me* first), by open, resolved or all, by what the agent said, or by text. A +thread you resolve or reopen there stays where it is until you open the panel again, so working +down the list keeps your place. + +*Go to code* (or the thread's `path:line`) jumps to its line when a stop shows it, else opens the +code around it. `path:line` mentions and commit hashes inside comments and answers are links too. A +*← GitHub comments* button then takes you back to the same thread, scroll and filters, as does `B`; +closing a peek or commit goes back by itself. + +*Ask agent where these stand* sends every thread the panel shows to the agent (*Ask agent* on a +card sends just that one), with an optional line of your own. margin writes the threads, replies +included, into `.github.md` beside the review; the agent checks each against the code and +any commit a reply names, and answers under it with *done*, *partly*, *not done* or *unclear* and +the lines it means. The answer shows beside the thread in the panel, and on the thread's card in +the review, as soon as the agent writes it. The agent is told not to change code or touch GitHub. margin pulls all of it when the review opens and when the window gets focus again (at most every 30 seconds). **↻** in the toolbar pulls again at once, reading the pull request's diff afresh too. Agent notes and @@ -361,6 +383,7 @@ Changed settings apply to reviews and agents started afterwards. | `\` | show or hide the sidebar | | `` ` `` | put the keyboard in the agent's terminal; `ctrl+esc` takes it out | | `A` | the agent's answers to your comments | +| `B` | the GitHub panel, back where you left it | | `T` `i` `o` | run the selected line's tests, try a change to it, show or hide the test output (margin-tui has them too) | | `j` `k` `enter` | on a worktree page: move through what to review and open it | | `/` | on a worktree page: filter the branches, commits or pull requests | diff --git a/internal/github/github.go b/internal/github/github.go index 2f29cdc..87ab4ca 100644 --- a/internal/github/github.go +++ b/internal/github/github.go @@ -603,6 +603,35 @@ func (p *PR) SetResolved(run Runner, repo, threadID string, resolved bool) error return err } +// Reply adds the reader's comment to the end of a review thread and gives back the page GitHub made +// for it. +func (p *PR) Reply(run Runner, repo, threadID, body string) (*Posted, error) { + body = strings.TrimSpace(body) + if body == "" { + return nil, errors.New("nothing to reply") + } + const q = `mutation($id: ID!, $body: String!) { + addPullRequestReviewThreadReply(input: {pullRequestReviewThreadId: $id, body: $body}) { comment { url } } +}` + out, err := run(repo, nil, "api", "graphql", "-f", "id="+threadID, "-f", "body="+body, "-f", "query="+q) + if err != nil { + return nil, err + } + var res struct { + Data struct { + AddPullRequestReviewThreadReply struct { + Comment struct { + URL string `json:"url"` + } `json:"comment"` + } `json:"addPullRequestReviewThreadReply"` + } `json:"data"` + } + if err := json.Unmarshal(out, &res); err != nil { + return nil, fmt.Errorf("GitHub took the reply, but its answer was unreadable: %w", err) + } + return &Posted{URL: res.Data.AddPullRequestReviewThreadReply.Comment.URL}, nil +} + // Post is something said on the pull request outside the code: a conversation comment, or the // text of a review with its decision (State: APPROVED, CHANGES_REQUESTED, COMMENTED…). type Post struct { diff --git a/internal/github/github_test.go b/internal/github/github_test.go index a97dbf2..c24605a 100644 --- a/internal/github/github_test.go +++ b/internal/github/github_test.go @@ -228,4 +228,14 @@ func TestThreads(t *testing.T) { if q := calls[len(calls)-1].args; !strings.Contains(q[len(q)-1], "resolveReviewThread") || strings.Contains(q[len(q)-1], "unresolve") { t.Fatalf("mutation %v", q) } + run = fake(&calls, map[string]string{"api graphql -f id=T1 -f body=thanks": `{"data":{"addPullRequestReviewThreadReply":{"comment":{"url":"u60"}}}}`}) + if got, err := pr.Reply(run, "/repo", "T1", " thanks\n"); err != nil || got.URL != "u60" { + t.Fatalf("reply %v %v", got, err) + } + if q := calls[len(calls)-1].args; !strings.Contains(q[len(q)-1], "addPullRequestReviewThreadReply") { + t.Fatalf("mutation %v", q) + } + if _, err := pr.Reply(run, "/repo", "T1", " "); err == nil { + t.Fatal("sent an empty reply") + } } diff --git a/internal/review/review.go b/internal/review/review.go index 037017d..7c80d06 100644 --- a/internal/review/review.go +++ b/internal/review/review.go @@ -333,6 +333,15 @@ func StatePath(reviewPath string) string { return strings.TrimSuffix(reviewPath, filepath.Ext(reviewPath)) + ".state.yaml" } +// GitHubPath is the note, beside the review file, where the agent says where the pull request's +// review threads stand. +func GitHubPath(reviewPath string) string { + if base, ok := strings.CutSuffix(reviewPath, ".review.yaml"); ok { + return base + ".github.md" + } + return strings.TrimSuffix(reviewPath, filepath.Ext(reviewPath)) + ".github.md" +} + // CommentsPath is the note, beside the review file, where the agent answers the reader's comments. func CommentsPath(reviewPath string) string { if base, ok := strings.CutSuffix(reviewPath, ".review.yaml"); ok {