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(``); + 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(`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(`${plural(mine, "thread", "threads")} started by your posted comments ${mine > 1 ? "are" : "is"} shown on those comments.
`)); - 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(`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(`${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