Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(gui): focus chat navigation and synchronize wheel probes

yxlyx2255a6d0b6ee
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 54a194e6..6aab813f 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useNavigationPromptFocus } from "./useNavigationPromptFocus";
import { useHarnessSessions } from "./useHarnessSessions";
import { resumeQueuedPrompt } from "@/lib/prompt-queue-resume";
import { createPromptRunner } from "./harness-prompt-runner";
@@ -121,6 +122,7 @@ export default function GraffHarness() {
};
const [pinsByChat, setPinsByChat] = useState<Record<number, BrowserPin[]>>({});
const pinsRef = useRef<Record<number, BrowserPin[]>>({});
+ const { promptFocusRoot, requestPromptFocus } = useNavigationPromptFocus();
const chatIdRef = useRef(1);
const msgIdRef = useRef(0);
// Split view: ordered visible chats, independent of focus. Each keeps its
@@ -221,7 +223,7 @@ export default function GraffHarness() {
const next = [...chatsRef.current, { id, title: null, messages: [], model: ws?.model ?? model ?? undefined, session, cwd }];
chatsRef.current = next; setChats(next);
setZoomedPane(null);
- setActiveId(id);
+ setActiveId(id); requestPromptFocus(id);
setFilesOpen(false);
setConversationsOpen(false);
setFollowing(true);
@@ -250,13 +252,14 @@ export default function GraffHarness() {
const newChat = () => openChat((chatIdRef.current += 1));
/** Focus a pane in place, or restore the selected workspace tab’s layout. */
- const focusChat = (id: number) => {
+ const focusChat = (id: number, focusPrompt = true) => {
setProjectsOpen(false); setAgentsOpen(false);
setConversationsOpen(false);
const folder = chatsRef.current.find(chat => chat.id === id)?.cwd;
if (folder && folder !== activePathRef.current) activateWorkspace(folder);
- if (!columnIds.includes(id)) setZoomedPane(null);
+ if (!columnIds.includes(id) || (zoomedPane !== null && zoomedPane !== id)) setZoomedPane(null);
setActiveId(id);
+ if (focusPrompt) requestPromptFocus(id);
};
const tabDrag = useTabDrag((id, drop) => {
@@ -442,7 +445,7 @@ export default function GraffHarness() {
}),
}}
pins={(pinsByChat[thread.id] ?? []).length}
- onShowPins={() => { focusChat(thread.id); setFilesOpen(false); setBrowserOpen(true); }}
+ onShowPins={() => { focusChat(thread.id, false); setFilesOpen(false); setBrowserOpen(true); }}
onClearPins={() => setPins(thread.id, [])} health={health}
onOpenProject={() => setDialog({ mode: "new" })} onProjects={() => setProjectsOpen(true)} onConversations={openConversations} />;
@@ -460,7 +463,7 @@ export default function GraffHarness() {
return (
- <main data-graff-main data-workspace-ready={projectsReady} className="flex h-[100dvh] gap-0 bg-canvas p-2.5 text-ink lg:pl-0">
+ <main ref={promptFocusRoot} data-graff-main data-workspace-ready={projectsReady} className="flex h-[100dvh] gap-0 bg-canvas p-2.5 text-ink lg:pl-0">
<SidebarNav
fill
className="hidden lg:flex"
@@ -473,6 +476,7 @@ export default function GraffHarness() {
onSeeAll={openConversations}
activeNav={projectsOpen ? "projects" : filesOpen ? (fileRequest?.changes ? "changes" : "workspace") : browserOpen ? "browser" : conversationsOpen ? "conversations" : "home"}
onNavigate={(key) => {
+ if (key === "home") requestPromptFocus(activeId);
setAgentsOpen(false);
setProjectsOpen(key === "projects");
if (key === "changes") { openChanges(); return; }
@@ -527,7 +531,7 @@ export default function GraffHarness() {
) : null}
<div className="min-h-0 min-w-0 flex-1" style={{ display: projectsOpen || conversationsOpen || agentsOpen ? "none" : "flex" }}>
<ChatSplitLayout threads={columns} liveChatIds={chats.map(chat => chat.id)} activeId={activeId} direction={splitDirection} layout={groups.tree} onLayoutChange={groups.setTree}
- onFocus={focusChat} onClose={closeChat} folder={thread => ({name: workspaceNameOf(thread), path: cwdOf(thread)})}
+ onFocus={id => focusChat(id, false)} onClose={closeChat} folder={thread => ({name: workspaceNameOf(thread), path: cwdOf(thread)})}
body={columnBody} split={columnIds.length > 1} />
</div>
diff --git a/apps/native/components/site/useNavigationPromptFocus.ts b/apps/native/components/site/useNavigationPromptFocus.ts
new file mode 100644
index 00000000..41149fd0
--- /dev/null
+++ b/apps/native/components/site/useNavigationPromptFocus.ts
@@ -0,0 +1,18 @@
+import { useLayoutEffect, useRef, useState } from "react";
+
+/** Explicit navigation, not active-pane changes or draft renders, owns focus. */
+export function useNavigationPromptFocus() {
+ const root = useRef<HTMLElement>(null);
+ const [request, setRequest] = useState<{ id: number } | null>(null);
+ useLayoutEffect(() => {
+ if (!request) return;
+ const prompt = root.current?.querySelector<HTMLTextAreaElement>(
+ `[data-chat="${request.id}"] textarea[aria-label="Prompt"]`,
+ );
+ // Run once in the navigation commit, never retry later during typing.
+ if (prompt && !prompt.disabled && prompt.getClientRects().length) {
+ prompt.focus({ preventScroll: true });
+ }
+ }, [request]);
+ return { promptFocusRoot: root, requestPromptFocus: (id: number) => setRequest({ id }) };
+}
diff --git a/apps/native/electron/chat-overflow-visual.cjs b/apps/native/electron/chat-overflow-visual.cjs
index 43ec8c17..1fa78bba 100644
--- a/apps/native/electron/chat-overflow-visual.cjs
+++ b/apps/native/electron/chat-overflow-visual.cjs
@@ -79,12 +79,36 @@ async function runChatOverflow({ win, origin, output }) {
}
return result.width;
};
- const wheel = async (point, deltaX, deltaY) => {
+ const wheel = async (point, deltaX, deltaY, target = transcript) => {
await testDesktop.testInput(wc, { type: 'mouseMove', ...point });
- await testDesktop.testInput(wc, { type: 'mouseWheel', ...point, deltaX, deltaY, canScroll: true });
- await sleep(200);
+ // Arm the actual target before dispatch. A transport acknowledgement or a
+ // fixed sleep does not prove the renderer received this wheel event.
+ await js(`(() => {
+ const target = ${target};
+ if (!target?.isConnected || !target.contains(document.elementFromPoint(${point.x}, ${point.y}))) {
+ throw Error('Wheel target moved before dispatch');
+ }
+ window.overflowWheel = null;
+ const receive = event => { window.overflowWheel = {
+ trusted: event.isTrusted, deltaX: event.deltaX, deltaY: event.deltaY
+ }; };
+ target.addEventListener('wheel', receive, { once: true, passive: true });
+ window.cancelOverflowWheel = () => target.removeEventListener('wheel', receive);
+ })()`);
+ try {
+ await testDesktop.testInput(wc, { type: 'mouseWheel', ...point, deltaX, deltaY, canScroll: true });
+ await wait(`window.overflowWheel !== null`);
+ assert.deepEqual(await js(`window.overflowWheel`), { trusted: true, deltaX: -deltaX || 0, deltaY: -deltaY || 0 }, 'Trusted wheel reaches the intended scroller');
+ // The wheel listener runs before the default scroll action. Wait for its
+ // rendered result as well, without injecting a second wheel on failure.
+ await js(`new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))))`);
+ await sleep(200);
+ } finally {
+ await js(`window.cancelOverflowWheel(); delete window.cancelOverflowWheel`);
+ }
};
const viewportWheels = async label => {
+ await testDesktop.focusTestPage(wc);
// The blank left gutter targets the transcript, not an intentionally scrollable code block.
const point = await js(`(() => {
const e = ${transcript}; e.scrollTop = 0; e.dispatchEvent(new Event('scroll'));
@@ -110,6 +134,9 @@ async function runChatOverflow({ win, origin, output }) {
await bounds(label);
};
const localScroll = async (selector, label) => {
+ // Establish Chromium focus before scrolling or measuring the hit target;
+ // focusing later can move the viewport to the active composer.
+ await testDesktop.focusTestPage(wc);
const point = await js(`(() => {
const e = ${transcript}, target = e.querySelector(${JSON.stringify(selector)});
if (!target) return null;
@@ -149,10 +176,7 @@ async function runChatOverflow({ win, origin, output }) {
if (i === 119) throw Error(`${label}: no stable visible wheel target ${JSON.stringify(geometry)}`);
}
assert.ok(geometry.contained, `${label}: local scroller fits transcript`);
- await js(`window.overflowWheel = null; window.overflowLocal.addEventListener('wheel', event => {
- window.overflowWheel = { trusted: event.isTrusted, deltaX: event.deltaX, deltaY: event.deltaY };
- }, { once: true, passive: true })`);
- await wheel({ x: geometry.x, y: geometry.y }, -240, 0);
+ await wheel({ x: geometry.x, y: geometry.y }, -240, 0, 'window.overflowLocal');
assert.deepEqual(await js(`window.overflowWheel`), { trusted: true, deltaX: 240, deltaY: 0 }, `${label}: trusted horizontal wheel reaches local scroller`);
assert.ok(await js(`window.overflowLocal.scrollLeft > 10`), `${label}: horizontal wheel reveals wide content`);
assert.equal(await js(`${transcript}.scrollLeft`), 0, `${label}: local scrolling never pans transcript`);
diff --git a/apps/native/electron/navigation-prompt-focus-visual.cjs b/apps/native/electron/navigation-prompt-focus-visual.cjs
new file mode 100644
index 00000000..80cf32e3
--- /dev/null
+++ b/apps/native/electron/navigation-prompt-focus-visual.cjs
@@ -0,0 +1,84 @@
+const assert = require('node:assert/strict');
+const testDesktop = require('./test-desktop.cjs');
+const { installGalleryFixture } = require('./gallery-fixture.cjs');
+
+// Real pointer dispatch: HTMLElement.click() misses the browser's focus default.
+async function runNavigationPromptFocus({ win, origin }) {
+ const wc = win.webContents, js = source => wc.executeJavaScript(source);
+ const pause = () => new Promise(resolve => setTimeout(resolve, 50));
+ const wait = async source => {
+ for (let i = 0; i < 120; i++) { if (await js(source)) return; await pause(); }
+ throw Error(`Navigation prompt focus timeout: ${source}`);
+ };
+ const click = async selector => {
+ const point = await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)throw Error('Missing click target');const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`);
+ for (const type of ['mouseDown', 'mouseUp']) await testDesktop.testInput(wc, { type, ...point, button: 'left', clickCount: 1 });
+ await pause();
+ };
+ const focused = id => wait(`document.activeElement===document.querySelector('[data-chat="${id}"] textarea[aria-label="Prompt"]') && document.activeElement?.tagName==='TEXTAREA'`);
+ const active = () => js(`document.querySelector('[data-chat][data-focused="true"]').dataset.chat`);
+ const tab = id => `[data-tab-members="${id}"] button[aria-pressed]`;
+ const sidebar = '[aria-label="Workspace navigation"]';
+ testDesktop.attachTestDebugger(wc);
+ await wc.debugger.sendCommand('Page.enable');
+ const { identifier } = await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `
+ (${installGalleryFixture.toString()})();
+ const previous=window.fetch;
+ window.fetch=async(input,options)=>{
+ const url=new URL(String(input),location.origin);
+ if(url.pathname!=='/api/sessions')return previous(input,options);
+ const row={name:'focus-history',title:'Focus history',updatedMs:100,size:100,model:null,provider:null};
+ return new Response(JSON.stringify(url.searchParams.has('name')?{...row,messages:[]}:{sessions:[row],total:1,nextCursor:null}),{headers:{'content-type':'application/json'}});
+ };
+ ` });
+ try {
+ await wc.loadURL(origin); testDesktop.present(win);
+ await wait(`!!document.querySelector('[data-workspace-ready="true"] textarea[aria-label="Prompt"]')`);
+ const first = await active();
+ await click(`${sidebar} button[aria-label="Home"]`); await focused(first);
+ await click(`${sidebar} button[aria-label="Home"]`); await focused(first);
+ await click(`${sidebar} button[aria-label="Projects"]`);
+ await click(`${sidebar} button[aria-label="Home"]`); await focused(first);
+ await click(`${sidebar} button[aria-label="New chat"]`);
+ const second = await active(); assert.notEqual(second, first); await focused(second);
+ await click('[data-workspace-toolbar] button[aria-label="New chat"]');
+ const third = await active(); assert.notEqual(third, second); await focused(third);
+ await click(tab(first)); await focused(first);
+ await click(tab(first)); await focused(first);
+
+ // A saved row already open in the renderer follows the same-current path.
+ await click(`${sidebar} button[title^="Focus history"]`);
+ await wait(`!!document.querySelector('[data-continue-snapshot]') || document.querySelectorAll('[data-tab-id]').length===4`);
+ if (await js(`!!document.querySelector('[data-continue-snapshot]')`)) await click('[data-continue-snapshot]');
+ const saved = await active();
+ await click(tab(first));
+ await click(`${sidebar} button[title^="Focus history"]`); await focused(saved);
+ await click(`${sidebar} button[title^="Focus history"]`); await focused(saved);
+
+ wc.send('desktop-action', 'split-right');
+ await wait(`document.querySelectorAll('[data-chat]').length===2`);
+ const right = await active(); await focused(right);
+ const order = await js(`Array.from(document.querySelectorAll('[data-chat]'),e=>e.dataset.chat)`);
+ await click(`[data-chat="${saved}"] textarea[aria-label="Prompt"]`);
+ for (const keyCode of 'left draft') await testDesktop.testInput(wc, { type: 'char', keyCode });
+ await focused(saved);
+ await click(`[data-chat="${right}"] textarea[aria-label="Prompt"]`);
+ for (const keyCode of 'right draft') await testDesktop.testInput(wc, { type: 'char', keyCode });
+ await focused(right);
+ await click(`${sidebar} button[aria-label="Home"]`); await focused(right);
+ assert.deepEqual(await js(`Array.from(document.querySelectorAll('[data-chat]'),e=>e.dataset.chat)`), order, 'Focus must not reorder split panes');
+ assert.equal(await js(`document.querySelector('[data-chat="${saved}"] textarea').value`), 'left draft');
+ assert.equal(await js(`document.querySelector('[data-chat="${right}"] textarea').value`), 'right draft');
+ // Ordinary pane activation must leave a clicked non-composer control alone.
+ await click(`[data-chat="${saved}"] button[title="Focus this chat"]`);
+ assert.equal(await active(), saved);
+ assert.equal(await js(`document.activeElement.matches('button[title="Focus this chat"]')`), true);
+ await pause();
+ assert.equal(await js(`document.activeElement.matches('button[title="Focus this chat"]')`), true, 'No delayed focus retry');
+ console.log('Navigation prompt focus passed: real New chat/Home/session clicks, repeated navigation, split targeting, drafts and non-composer focus.');
+ } finally {
+ await wc.debugger.sendCommand('Page.removeScriptToEvaluateOnNewDocument', { identifier });
+ await wc.loadURL(origin);
+ }
+}
+module.exports = { runNavigationPromptFocus };
diff --git a/apps/native/electron/navigation-visual.cjs b/apps/native/electron/navigation-visual.cjs
index 3ca3538b..4e279ba7 100644
--- a/apps/native/electron/navigation-visual.cjs
+++ b/apps/native/electron/navigation-visual.cjs
@@ -30,6 +30,7 @@ async function runNavigationVisuals({win:fixtureWindow,origin,output}) {
if(process.env.GRAFF_VISUAL_SUITE==='tab-drag'){await require('./tab-drag-visual.cjs').runTabDrag({win,origin,output});return;}
if(process.env.GRAFF_VISUAL_SUITE==='splits'){await require('./split-focus-visual.cjs').runSplitFocus({win,origin,output});return;}
const interactions = async () => {
+ await require('./navigation-prompt-focus-visual.cjs').runNavigationPromptFocus({win,origin});
await require('./navigation-keyboard-visual.cjs').runNavigationKeyboard({win,origin});
await require('./composer-interaction-visual.cjs').runComposerInteractions({win,origin,output});
await require('./files-recovery-visual.cjs').runFilesRecovery({win,origin,output});