graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Fix inline branch navigation and restore browser destination settings
justrachff01e8d7b631
diff --git a/apps/native/app/api/inline-reference/route.ts b/apps/native/app/api/inline-reference/route.tsnew file mode 100644index 00000000..4f85af01--- /dev/null+++ b/apps/native/app/api/inline-reference/route.ts@@ -0,0 +1,11 @@+import { NextRequest } from "next/server";+import { resolveRoot } from "@/lib/server-root";+import { resolveInlineReference } from "@/lib/inline-reference";+export const runtime = "nodejs";+export const dynamic = "force-dynamic";+export async function GET(req: NextRequest) {+ const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });+ try { return Response.json(await resolveInlineReference(resolved.root, req.nextUrl.searchParams.get("path") ?? "")); }+ catch { return Response.json({ error: "Could not resolve this reference." }, { status: 400 }); }+}diff --git a/apps/native/components/primitives/Markdown.tsx b/apps/native/components/primitives/Markdown.tsxindex a589685a..2fccc14d 100644--- a/apps/native/components/primitives/Markdown.tsx+++ b/apps/native/components/primitives/Markdown.tsx@@ -110,7 +110,7 @@ function inlineCode(onOpen?: (path: string) => void) {<code{...rest}onClick={pathish ? () => onOpen(target) : undefined}- title={pathish ? `Open ${stripCiteMarkup(text)} in the files pane` : undefined}+ title={pathish ? `Open ${stripCiteMarkup(text)}` : undefined}className={`rounded-[4px] bg-inset px-1 py-px font-mono text-[0.92em] text-ink shadow-hairline ${pathish ? "cursor-pointer underline decoration-line underline-offset-2 transition-colors hover:bg-hover hover:decoration-ink" : ""}`}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 773d407f..2766eb8c 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -24,6 +24,7 @@ import { newPageToken, newSessionName, type Chat, type Msg } from "./harness-typimport ChangesPane from "./ChangesPane";import ReviewsPane from "./ReviewsPane";import { useBrowserVisibility } from "./useBrowserVisibility";+import { useReferenceNavigation } from "./useReferenceNavigation";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { type PromptModel } from "@/components/primitives/PromptBar";import SidebarNav from "@/components/primitives/SidebarNav";@@ -182,12 +183,12 @@ export default function GraffHarness() {sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal});- const openPath = useCallback((path: string) => {- setProjectsOpen(false); setAgentsOpen(false); setBrowserOpen(false);- setConversationsOpen(false);- setFilesOpen(true);- setFileRequest({ path, n: (fileReqRef.current += 1) });- }, []);+ const { openPath, openReference } = useReferenceNavigation({+ context: (id = activeIdRef.current) => ({ root: chatsRef.current.find(c => c.id === id)?.cwd ?? activePathRef.current ?? health?.cwd, chat: handleOf(id), focus: () => focusChat(id) }),+ hideOtherPanes: () => { setProjectsOpen(false); setAgentsOpen(false); setConversationsOpen(false); setReviewsOpen(false); },+ files: setFilesOpen, browser: setBrowserOpen, error: setSplitNotice,+ request: path => setFileRequest({ path, n: (fileReqRef.current += 1) }),+ });const openChanges = useCallback(() => {setProjectsOpen(false);@@ -442,7 +443,7 @@ export default function GraffHarness() {const columnBody = (thread: Chat) => <ChatColumn key={thread.id} thread={thread}compact={columnIds.length > 1 || navigation.focusedMode || filesOpen || browserOpen || agentsOpen || reviewsOpen || !!(fileRequest?.changes)} following={tailing[thread.id] ?? true} register={paneRef(thread.id)}- onOpenPath={openPath} onReview={openChanges}+ onOpenPath={path => openReference(path, thread.id)} onReview={openChanges}onAnswer={(text, cancelled) => { const live = sessionsRef.current.get(thread.id); const ask = thread.messages.findLast(m => m.role === "assistant")?.turn.ask; if (live && ask) void answer(handleOf(thread.id), live, { callId: ask.callId, text, cancelled }); }}onEditPrompt={(n, text) => {const live = sessionsRef.current.get(thread.id);diff --git a/apps/native/components/site/ThemeToggle.tsx b/apps/native/components/site/ThemeToggle.tsxindex 55577887..52c9c069 100644--- a/apps/native/components/site/ThemeToggle.tsx+++ b/apps/native/components/site/ThemeToggle.tsx@@ -4,6 +4,7 @@ import { createPortal } from "react-dom";import { restoreActionFocus } from "../primitives/ActionMenu";import CustomThemes from "./CustomThemes";import McpServers from "./McpServers";+import DesktopSettings from "./DesktopSettings";import { appearanceEvent, appearanceKey, applyAppearance, readAppearance, type Appearance } from "@/lib/appearance";import { appearancePanelPosition, type PanelBox } from "./appearance-panel";@@ -66,6 +67,7 @@ export function ThemeToggle({ labeled = false }: { labeled?: boolean }) {<span className="block text-[11px] font-medium text-ink">{option.name}</span><span className="block text-[9px] leading-4 text-ink-3">{option.detail}</span></button>)}</div><CustomThemes selected={theme} />+ <DesktopSettings embedded /><McpServers /></div></div>, document.body)}diff --git a/apps/native/components/site/useReferenceNavigation.ts b/apps/native/components/site/useReferenceNavigation.tsnew file mode 100644index 00000000..ccfc8c84--- /dev/null+++ b/apps/native/components/site/useReferenceNavigation.ts@@ -0,0 +1,47 @@+"use client";+import { useRef } from "react";+import { browserNavigate } from "@/lib/browser-client";+import type { InlineReference } from "@/lib/inline-reference";++export async function dispatchInlineReference(target: string, root: string | undefined, actions: {+ file(path: string): void;+ browser(url: string): Promise<void>;+}, request: typeof fetch = fetch) {+ const params = new URLSearchParams({ path: target });+ if (root) params.set("root", root);+ const response = await request(`/api/inline-reference?${params}`, { cache: "no-store" });+ if (!response.ok) throw new Error("Could not resolve this reference. Try again.");+ const result = await response.json() as InlineReference;+ if (result.kind === "browser") await actions.browser(result.url);+ else actions.file(result.path);+}++export function useReferenceNavigation(options: {+ context(id?: number): { root?: string; chat: string; focus(): void };+ hideOtherPanes(): void;+ files(open: boolean): void;+ browser(open: boolean): void;+ request(path: string): void;+ error(message: string): void;+}) {+ const current = useRef(options); current.current = options;+ const sequence = useRef(0);+ const openPath = (path: string) => {+ sequence.current++;+ const o = current.current;+ o.hideOtherPanes(); o.browser(false); o.files(true); o.request(path);+ };+ const openReference = (path: string, id?: number) => {+ const ticket = ++sequence.current, o = current.current, context = o.context(id);+ o.error("");+ void dispatchInlineReference(path, context.root, {+ file: target => { if (ticket === sequence.current) { context.focus(); openPath(target); } },+ browser: async url => {+ if (ticket !== sequence.current) return;+ context.focus(); o.hideOtherPanes(); o.files(false); o.browser(true);+ await browserNavigate(context.chat, url);+ },+ }).catch(error => { if (ticket === sequence.current) o.error(error instanceof Error ? error.message : "Could not open reference."); });+ };+ return { openPath, openReference };+}diff --git a/apps/native/electron/inline-reference-visual.cjs b/apps/native/electron/inline-reference-visual.cjsnew file mode 100644index 00000000..60152e52--- /dev/null+++ b/apps/native/electron/inline-reference-visual.cjs@@ -0,0 +1,44 @@+const assert = require('node:assert/strict');+const desktop = require('./test-desktop.cjs');++/** Real Markdown click → reference dispatch → visible native BrowserTabs page.+ * The API reply uses a loopback destination; server Git resolution is tested separately. */+async function inlineReferenceVisual({ wc, js, wait, browser, destination, closeBrowser, screenshot }) {+ await closeBrowser();+ await js(`(() => {+ const previous = window.fetch;+ window.referenceRequests = [];+ window.fetch = async (input, options) => {+ const url = new URL(typeof input === 'string' ? input : input.url, location.origin);+ if (url.pathname === '/api/inline-reference') {+ window.referenceRequests.push(Object.fromEntries(url.searchParams));+ return new Response(JSON.stringify({kind:'browser',url:${JSON.stringify(destination + '/branch')}}), {headers:{'content-type':'application/json'}});+ }+ if (url.pathname === '/api/acp' && options?.body && JSON.parse(options.body).method === 'session/prompt') {+ const rows = [+ {jsonrpc:'2.0',method:'session/update',params:{sessionId:'demo',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'The branch is ' + String.fromCharCode(96) + 'release/v1.2.3' + String.fromCharCode(96) + '.'}}}},+ {jsonrpc:'2.0',id:1,result:{stopReason:'end_turn'}}+ ];+ return new Response(rows.map(row=>JSON.stringify(row)).join('\\n')+'\\n', {headers:{'content-type':'application/x-ndjson'}});+ }+ return previous(input, options);+ };+ window.restoreReferenceFetch = () => { window.fetch = previous; };+ const input = document.querySelector('[data-chat][data-focused="true"] textarea[aria-label="Prompt"]') || document.querySelector('textarea[aria-label="Prompt"]');+ input.focus();+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set.call(input, 'Show the release branch.');+ input.dispatchEvent(new Event('input', {bubbles:true}));+ })()`);+ try {+ await desktop.testInput(wc, { type: 'keyDown', keyCode: 'Enter' });+ await desktop.testInput(wc, { type: 'keyUp', keyCode: 'Enter' });+ await wait(`Array.from(document.querySelectorAll('code')).some(e=>e.textContent==='release/v1.2.3')`, 'branch rendered as inline code');+ await js(`Array.from(document.querySelectorAll('code')).find(e=>e.textContent==='release/v1.2.3').click()`);+ await wait(() => { const tab = browser.tabs.get(browser.visible); return tab?.view?.getVisible() && tab.view.webContents.getURL() === destination + '/branch' && !tab.view.webContents.isLoading(); }, 'inline branch opens visible embedded browser');+ assert.equal(await js(`window.referenceRequests.at(-1).path`), 'release/v1.2.3');+ assert.equal(await js(`document.body.textContent.includes('ENOENT')`), false);+ assert.ok(await js(`!!document.querySelector('input[aria-label="Address"]')`));+ await screenshot('inline-reference-browser.png');+ } finally { await js('window.restoreReferenceFetch()'); }+}+module.exports = { inlineReferenceVisual };diff --git a/apps/native/electron/link-destination-visual.cjs b/apps/native/electron/link-destination-visual.cjsindex e30fce6a..9c3bb21e 100644--- a/apps/native/electron/link-destination-visual.cjs+++ b/apps/native/electron/link-destination-visual.cjs@@ -197,6 +197,7 @@ async function runLinkDestinationVisuals({ origin, output }) {assert.ok(await js(`!!document.querySelector('textarea[aria-label="Prompt"]')`));assert.deepEqual(errors, [], 'browser IPC completes without errors');await require('./browser-address-visual.cjs').runBrowserAddress({ wc, browser, destination, guard, wait, delayOpenReply: () => { delayNextOpen = true; }, openReplySent: () => delayedReplySent });+ await require('./inline-reference-visual.cjs').inlineReferenceVisual({ wc, js, wait, browser, destination, closeBrowser, screenshot });assert.deepEqual(blocked, [], 'no external network or engine/model requests attempted');console.log('Link destination visuals passed: default/save/switch, reload and fresh-store persistence, normal/blank links, closed-browser reveal, overlays, unsafe/same-origin links, split focus and preserved app.');} finally {diff --git a/apps/native/lib/inline-reference.test.ts b/apps/native/lib/inline-reference.test.tsnew file mode 100644index 00000000..7484a7c2--- /dev/null+++ b/apps/native/lib/inline-reference.test.ts@@ -0,0 +1,59 @@+import { test, expect } from "bun:test";+import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { execFileSync } from "node:child_process";+import { NextRequest } from "next/server";+import { GET } from "../app/api/inline-reference/route";+import { dispatchInlineReference } from "../components/site/useReferenceNavigation";++async function fixture(run: (root: string, git: (args: string[]) => string) => Promise<void>) {+ const root = await mkdtemp(path.join(os.tmpdir(), "inline-reference-"));+ const git = (args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();+ try {+ git(["init", "-q"]);+ git(["-c", "user.name=Test", "-c", "[email protected]", "commit", "--allow-empty", "-qm", "Fixture"]);+ git(["branch", "release/v1.2.3"]);+ git(["remote", "add", "origin", "[email protected]:example/project.git"]);+ await run(root, git);+ } finally { await rm(root, { recursive: true, force: true }); }+}+const request: typeof fetch = async input => GET(new NextRequest(new URL(String(input), "http://localhost")));++test("inline branch click dispatches through the API to Browser, never Files", async () => {+ await fixture(async root => {+ const files: string[] = [], pages: string[] = [];+ await dispatchInlineReference("release/v1.2.3", root, {+ file: value => { files.push(value); }, browser: async value => { pages.push(value); },+ }, request);+ expect(files).toEqual([]);+ expect(pages).toEqual(["https://github.com/example/project/tree/release/v1.2.3"]);+ await mkdir(path.join(root, "release")); await writeFile(path.join(root, "release/v1.2.3"), "real file");+ await dispatchInlineReference("release/v1.2.3", root, {+ file: value => { files.push(value); }, browser: async value => { pages.push(value); },+ }, request);+ expect(files).toEqual(["release/v1.2.3"]);+ expect(pages).toHaveLength(1);+ });+});++test("remote-only branches resolve; unknown refs and unsupported remotes do not invent URLs", async () => {+ await fixture(async (root, git) => {+ git(["update-ref", "refs/remotes/origin/fix/navigation", "HEAD"]);+ const route = async (target: string) => (await request(`/api/inline-reference?${new URLSearchParams({ root, path: target })}`)).json();+ expect(await route("fix/navigation")).toEqual({ kind: "browser", url: "https://github.com/example/project/tree/fix/navigation" });+ for (const target of ["unknown/path", "release/v1.2.3~1", "--help", "../outside"]) expect((await route(target)).kind).toBe("file");+ git(["remote", "set-url", "origin", "https://example.invalid/project.git"]);+ expect((await route("release/v1.2.3")).kind).toBe("file");+ });+});++test("browser navigation failure surfaces instead of falling back to the files pane", async () => {+ await fixture(async root => {+ const files: string[] = [];+ await expect(dispatchInlineReference("release/v1.2.3", root, {+ file: value => { files.push(value); }, browser: async () => { throw new Error("Browser unavailable"); },+ }, request)).rejects.toThrow("Browser unavailable");+ expect(files).toEqual([]);+ });+});diff --git a/apps/native/lib/inline-reference.ts b/apps/native/lib/inline-reference.tsnew file mode 100644index 00000000..0f6c4d5f--- /dev/null+++ b/apps/native/lib/inline-reference.ts@@ -0,0 +1,35 @@+import { stat } from "node:fs/promises";+import { execFile } from "node:child_process";+import { promisify } from "node:util";+import path from "node:path";+import { githubIssueUrlsFromRemote } from "./git-review";++const run = promisify(execFile);+export type InlineReference = { kind: "file"; path: string } | { kind: "browser"; url: string };++/** Files win over identically named branches. Never infer a remote from prose. */+export async function resolveInlineReference(root: string, target: string): Promise<InlineReference> {+ const file: InlineReference = { kind: "file", path: target };+ if (!target || target.includes("\0")) throw new Error("Invalid reference");+ const absolute = path.resolve(root, target);+ if (absolute !== root && !absolute.startsWith(root + path.sep)) return file;+ try { await stat(absolute); return file; }+ catch (error) { if (!["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }+ const git = async (args: string[]) => (await run("git", args, { cwd: root, timeout: 5000, maxBuffer: 65536 })).stdout.trim();+ // Exact refs only: no revision expressions, shell interpolation or network calls.+ try { await git(["check-ref-format", `refs/heads/${target}`]); }+ catch { return file; }+ let branch = false;+ for (const ref of [`refs/heads/${target}`, `refs/remotes/origin/${target}`]) {+ try { await git(["show-ref", "--verify", "--quiet", ref]); branch = true; break; }+ catch { /* Not this ref. */ }+ }+ if (!branch) return file;+ const remote = await git(["remote", "get-url", "origin"]).catch(() => "");+ const github = githubIssueUrlsFromRemote(remote);+ if (!github) return file;+ const base = github.list.slice(0, -"/issues".length);+ const url = new URL(`${base}/tree/${target.split("/").map(encodeURIComponent).join("/")}`);+ if (url.protocol !== "https:" || url.hostname !== "github.com" || url.username || url.password) return file;+ return { kind: "browser", url: url.href };+}