graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Keep background browser navigation from changing chat focus
justrachbb02ffcdf4e4
diff --git a/apps/native/electron/browser-actions.cjs b/apps/native/electron/browser-actions.cjsindex 31fa14a1..620237d7 100644--- a/apps/native/electron/browser-actions.cjs+++ b/apps/native/electron/browser-actions.cjs@@ -1,6 +1,7 @@async function browserAction(browser, chat, method, params = {}) {if (method === 'tabs') return [...browser.tabs.values()].map(tab => browser.info(tab));- if (['open', 'navigate', 'back', 'forward', 'reload', 'info', 'close'].includes(method)) return browser.command(chat, method, params);+ if (method === 'open' || method === 'navigate') return browser.navigate(chat, params.url, { background: true });+ if (['back', 'forward', 'reload', 'info', 'close'].includes(method)) return browser.command(chat, method, params);const wc = browser.tabs.get(chat)?.view?.webContents;if (!wc) throw new Error('The browser page is closed or suspended; open it first');const evaluate = expression => wc.executeJavaScript(expression);diff --git a/apps/native/electron/browser-actions.test.cjs b/apps/native/electron/browser-actions.test.cjsindex 872de356..38edb3d2 100644--- a/apps/native/electron/browser-actions.test.cjs+++ b/apps/native/electron/browser-actions.test.cjs@@ -1,13 +1,31 @@-const { test } = require('node:test');-const assert = require('node:assert/strict');+const { test, expect } = require('bun:test');const { browserAction } = require('./browser-actions.cjs');-test('empty Find clears Chromium highlights and navigation does not need a rendered page', async () => {+test('agent open and navigation always use the background route', async () => {+ const navigations = [];+ const browser = {+ navigate: async (...args) => { navigations.push(args); return { url: args[1] }; },+ command: () => { throw Error('Foreground route must not be used by agent navigation'); },+ };+ for (const action of ['open', 'navigate']) {+ expect(await browserAction(browser, 'other-chat', action, { url: 'http://localhost/preview', background: false }))+ .toEqual({ url: 'http://localhost/preview' });+ }+ expect(navigations).toEqual(Array.from({ length: 2 }, () => ['other-chat', 'http://localhost/preview', { background: true }]));+});+test('other agent browser actions retain their existing command routing', async () => {+ const calls = [];+ const browser = { command: async (...args) => { calls.push(args); return { ok: true }; } };+ for (const method of ['back', 'forward', 'reload', 'info', 'close']) await browserAction(browser, 'other-chat', method, {});+ expect(calls.map(args => args[1])).toEqual(['back', 'forward', 'reload', 'info', 'close']);+});++test('empty Find clears Chromium highlights and rejects a closed page', async () => {const calls = [];const browser = { tabs: new Map([['chat', { view: { webContents: {findInPage: text => calls.push(text), stopFindInPage: mode => calls.push(mode),} } }]]) };await browserAction(browser, 'chat', 'find', { text: 'word' });await browserAction(browser, 'chat', 'find', { text: '' });- assert.deepEqual(calls, ['word', 'clearSelection']);- await assert.rejects(browserAction(browser, 'closed', 'find', { text: 'word' }), /closed or suspended/);+ expect(calls).toEqual(['word', 'clearSelection']);+ await expect(browserAction(browser, 'closed', 'find', { text: 'word' })).rejects.toThrow(/closed or suspended/);});diff --git a/apps/native/electron/browser-focus-frontend.cjs b/apps/native/electron/browser-focus-frontend.cjsnew file mode 100644index 00000000..b513fbeb--- /dev/null+++ b/apps/native/electron/browser-focus-frontend.cjs@@ -0,0 +1,76 @@+const assert = require('node:assert/strict');+const fs = require('node:fs'), path = require('node:path'), http = require('node:http');+const { ipcMain } = require('electron');+const desktop = require('./test-desktop.cjs');+const { BrowserTabs } = require(process.env.GRAFF_BROWSER_SOURCE || './browser-tabs.cjs');+const { startAutomation } = require('./automation.cjs');+const { callTool } = require('./desktop-tools.cjs');+async function runBrowserFocus({ win, output, click, until, report }) {+ const wc = win.webContents, js = code => wc.executeJavaScript(code);+ const focused = () => js(`document.querySelector('[data-chat][data-focused="true"]').dataset.chat`);+ if (await js(`!!document.querySelector('[aria-label="Close browser"]')`)) await click('[aria-label="Close browser"]');+ const fixture = http.createServer((req, res) => {+ if (req.url === '/fail') return res.destroy();+ res.setHeader('content-type', 'text/html');+ res.end(`<title>Preview ${req.url}</title><h1>Preview ${req.url}</h1><button id="popup" onclick="window.open('/popup','_blank')">Open popup</button>`);+ });+ await new Promise(resolve => fixture.listen(0, '127.0.0.1', resolve));+ const origin = `http://127.0.0.1:${fixture.address().port}`;+ const events = [], browser = new BrowserTabs(win, event => { events.push(event); wc.send('browser-event', event); });+ const bridge = await startAutomation(browser, null, null);+ ipcMain.removeHandler('browser');+ ipcMain.handle('browser', (_event, { chat, method, params }) => method === 'handle' ? bridge.handle(chat) : browser.command(chat, method, params));+ try {+ const navigateUser = async url => {+ await click('[aria-label="Address"]');+ for (const keyCode of url) await desktop.testInput(wc, { type: 'char', keyCode });+ await desktop.testInput(wc, { type: 'keyDown', keyCode: 'Return' });+ await desktop.testInput(wc, { type: 'keyUp', keyCode: 'Return' });+ await until(() => browser.visible && browser.tabs.get(browser.visible)?.view?.webContents.getURL() === url, 'explicit address navigation');+ };+ const a = await focused();+ await click('[aria-label="Workspace tools"]'); await click('[aria-label="Browser"]');+ await navigateUser(`${origin}/first`);+ const chatA = browser.visible;+ await click('[title="New chat (⌘T)"]');+ await until(async () => (await focused()) !== a && browser.visible !== chatA, 'second chat');+ await navigateUser(`${origin}/selected`);+ const b = await focused(), chatB = browser.visible;+ await click('textarea[aria-label="Prompt"]');+ for (const keyCode of 'Keep my draft here') await desktop.testInput(wc, { type: 'char', keyCode });+ const selected = async () => {+ assert.equal(await focused(), b, 'Background browser work must not change the active GUI chat');+ assert.equal(browser.visible, chatB, 'Background navigation must not replace the selected native view');+ assert.equal(await js(`document.activeElement === document.querySelector('[data-chat="${b}"] textarea[aria-label="Prompt"]')`), true, 'Composer focus must remain in the selected chat');+ assert.equal(await js(`document.querySelector('[data-chat="${b}"] textarea').value`), 'Keep my draft here');+ assert.equal(browser.tabs.get(chatB).view.webContents.getURL(), `${origin}/selected`);+ };+ const handle = bridge.handle(chatA);+ const env = { GRAFF_DESKTOP_ENDPOINT: `http://127.0.0.1:${handle.port}`, GRAFF_DESKTOP_SECRET: handle.token, GRAFF_DESKTOP_CHAT: chatA };+ const tool = args => callTool('browser', args, env);+ events.length = 0;+ await tool({ action: 'open', url: `${origin}/background` });+ await selected();+ assert.ok(!events.some(event => event.type === 'show'), 'Agent navigation must not request a GUI reveal');+ assert.match(JSON.stringify(await tool({ action: 'snapshot' })), /Preview \/background/);+ await tool({ action: 'click', selector: '#popup' });+ await until(() => browser.tabs.get(chatA).view.webContents.getURL() === `${origin}/popup`, 'background popup navigation');+ await selected();+ assert.ok(!events.some(event => event.type === 'show'), 'Hidden popups must remain hidden');+ await assert.rejects(browser.navigate(chatA, `${origin}/fail`, { background: true }));+ await selected();+ assert.ok(browser.tabs.get(chatA).timer, 'Failed background navigation still schedules inactive-page cleanup');+ fs.writeFileSync(path.join(output, 'browser-background-keeps-draft.png'), (await wc.capturePage()).toPNG());+ await browser.command(chatA, 'navigate', { url: `${origin}/explicit` });+ await until(async () => (await focused()) === a, 'explicit user browser reveal');+ assert.equal(browser.visible, chatA);+ assert.ok(events.some(event => event.type === 'show' && event.chat === chatA));+ await click(`[data-tab-members="${b}"] button[aria-pressed]`);+ assert.equal(await js(`document.querySelector('[data-chat="${b}"] textarea').value`), 'Keep my draft here');+ report.passed.push('native background browser open, popup and failed navigation preserve selected chat, composer draft and native view; explicit user reveal still works');+ } finally {+ browser.closeAll(); bridge.server.close(); fixture.close();+ ipcMain.removeHandler('browser'); ipcMain.handle('browser', () => null);+ }+}+module.exports = { runBrowserFocus };diff --git a/apps/native/electron/browser-tabs.cjs b/apps/native/electron/browser-tabs.cjsindex b8d8abf5..4018227f 100644--- a/apps/native/electron/browser-tabs.cjs+++ b/apps/native/electron/browser-tabs.cjs@@ -40,7 +40,7 @@ class BrowserTabs {wc.on('did-start-loading', () => { navigationStarted = performance.now(); this.profiler?.record('page-navigation'); this.notify(tab); });wc.on('did-finish-load', () => { this.profiler?.record('page-loaded', performance.now() - navigationStarted); wc.send('profile-enabled', !!this.profiler?.active); wc.send('pins-sync', tab.pins || []); });wc.setWindowOpenHandler(({ url }) => {- void this.navigate(chat, url).catch(() => {}); return { action: 'deny' };+ void this.navigate(chat, url, { background: this.visible !== chat }).catch(() => {}); return { action: 'deny' };});wc.on('will-navigate', (event, url) => { try { pageURL(url); } catch { event.preventDefault(); } });wc.on('will-redirect', (event, url) => { try { pageURL(url); } catch { event.preventDefault(); } });@@ -56,10 +56,11 @@ class BrowserTabs {this.window.contentView.addChildView(view); view.setVisible(false);return tab;}- async navigate(chat, raw) {+ async navigate(chat, raw, { background = false } = {}) {const url = pageURL(raw), tab = this.create(chat); tab.url = url;- this.attach(tab); this.emit({ chat, type: 'show' });- await tab.view.webContents.loadURL(url);+ if (!background) { this.attach(tab); this.emit({ chat, type: 'show' }); }+ try { await tab.view.webContents.loadURL(url); }+ finally { if (background && this.visible !== chat) this.hide(chat); }this.notify(tab); return this.info(tab);}attach(tab) {diff --git a/apps/native/electron/dev-preview-visual.cjs b/apps/native/electron/dev-preview-visual.cjsindex 68793617..a18da12f 100644--- a/apps/native/electron/dev-preview-visual.cjs+++ b/apps/native/electron/dev-preview-visual.cjs@@ -31,7 +31,7 @@ async function runDevPreview({ output }) {const tool = args => callTool('browser', args, env);await tool({ action: 'open', url });browser.setBounds('preview-test', { x: 0, y: 0, width: 900, height: 550 });- assert.ok(events.some(e => e.type === 'show'), 'Opening a preview requests the shared browser pane');+ assert.ok(!events.some(e => e.type === 'show'), 'Agent preview navigation does not request foreground UI');assert.match(JSON.stringify(await tool({ action: 'snapshot' })), /Initial preview/);await tool({ action: 'fill', selector: '#name', text: 'Codegraff' });await tool({ action: 'click', selector: '#go' });diff --git a/apps/native/electron/frontend-runtime.cjs b/apps/native/electron/frontend-runtime.cjsindex a8ef12fa..d5160dbd 100644--- a/apps/native/electron/frontend-runtime.cjs+++ b/apps/native/electron/frontend-runtime.cjs@@ -195,6 +195,7 @@ app.whenReady().then(async () => {report.passed.push('bounded split churn, resize, cancellation and memory checks');return;}+ await require('./browser-focus-frontend.cjs').runBrowserFocus({ win, output, click, until, report });await require('./tab-drag-visual.cjs').runTabDrag({ win, origin, output });report.passed.push('trusted pointer and keyboard: tab reorder, horizontal/vertical splits, draft retention, Escape and four-pane limit');}).then(() => finish()).catch(finish);diff --git a/docs/adr/0070-electron-browser-and-native-panels.md b/docs/adr/0070-electron-browser-and-native-panels.mdindex 7313ec02..2211a8c8 100644--- a/docs/adr/0070-electron-browser-and-native-panels.md+++ b/docs/adr/0070-electron-browser-and-native-panels.md@@ -22,6 +22,13 @@ Closed views are destroyed. Hidden views release their renderers after oneminute and retain their URL; rapid switching retains at most three live views.Reopening a suspended page reloads it, so unsaved page forms are not preserved.+Agent browser navigation updates its own chat's page without attaching its+native view or requesting a GUI reveal. Popups from hidden pages stay hidden;+explicit user navigation may reveal the page. Background navigation schedules+inactive-page cleanup even when loading fails. The native front-end regression+checks preserve the selected chat, composer draft, and browser view across these+operations, and fail against the former unconditional reveal behavior (#916).+The renderer's IPC surface permits browser navigation, geometry, picking,and Activity only. External pages never receive that surface or the desktopAPI token. Graff can act on a pinned page through an authenticated loopback