Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
30v raf-focus-after-render: focus after render for frame focus calls that race (#900)
Oleksandr Ivanchenko5f3b4ef8a169
diff --git a/frontend/src/components/ApprovalsSetting.tsx b/frontend/src/components/ApprovalsSetting.tsxindex 8da45ff5..1a033caf 100644--- a/frontend/src/components/ApprovalsSetting.tsx+++ b/frontend/src/components/ApprovalsSetting.tsx@@ -2,6 +2,7 @@// bot runs without asking. The marker always has an icon and words, never colour alone.import React, { useCallback, useEffect, useId, useRef, useState } from 'react';+import { useFocusAfterRender } from '../focusAfterRender';import { AlertTriangle, CheckCheck, Loader2, RotateCcw, ShieldCheck, ShieldOff, Undo2 } from 'lucide-react';import { AlwaysAllowed, alwaysAllowedApi, grantTool, grantWhere } from '../alwaysAllowed';import { relativeTime } from '../away';@@ -281,6 +282,7 @@ export const AlwaysAllowedList: React.FC<{const headingId = useId();const listRef = useRef<HTMLUListElement>(null);const headingRef = useRef<HTMLParagraphElement>(null);+ const focusAfterRender = useFocusAfterRender();const load = useCallback(() => {let live = true;@@ -321,10 +323,10 @@ export const AlwaysAllowedList: React.FC<{: `All ${n} taken back. ${kwantName} asks again before using any of them.`,);// Keep the keyboard in the list: the next row's Take back, else the heading- requestAnimationFrame(() => {+ focusAfterRender(() => {const buttons = listRef.current?.querySelectorAll<HTMLButtonElement>('button[data-take-back]');const next = buttons && buttons.length ? buttons[Math.min(Math.max(index, 0), buttons.length - 1)] : null;- (next ?? headingRef.current)?.focus();+ return next ?? headingRef.current;});} catch (e) {setError(e instanceof Error ? e.message : 'Couldn’t take that back. Try again.');diff --git a/frontend/src/components/BotBudget.tsx b/frontend/src/components/BotBudget.tsxindex 776cee32..11dd9bf4 100644--- a/frontend/src/components/BotBudget.tsx+++ b/frontend/src/components/BotBudget.tsx@@ -1,4 +1,5 @@import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react';+import { useFocusAfterRender } from '../focusAfterRender';import { Check, Gauge, Loader2, PauseCircle, Play, RotateCcw, SlidersHorizontal } from 'lucide-react';import {BotBudget,@@ -319,6 +320,7 @@ export const BotBudgetSection: React.FC<{ kwantId: string; kwantName: string; seconst [undoing, setUndoing] = useState(false);const first = useRef<HTMLInputElement>(null);const section = useRef<HTMLElement>(null);+ const focusAfterRender = useFocusAfterRender();const load = React.useCallback(() => {setLoadError(null);@@ -433,7 +435,7 @@ export const BotBudgetSection: React.FC<{ kwantId: string; kwantName: string; sesend={send}onContinued={() => {// The paused row swaps for Pause again once this renders: focus moves there, not to <body> (#536 Mira F4)- requestAnimationFrame(() => section.current?.querySelector<HTMLButtonElement>('[data-budget-pause-again]')?.focus());+ focusAfterRender(() => section.current?.querySelector<HTMLButtonElement>('[data-budget-pause-again]'));}}/><span className="text-[11px] text-zinc-500">or raise a limit below.</span>diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex d17070f4..9db403d3 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -1203,6 +1203,7 @@ export const ChatView: React.FC<ChatViewProps> = ({useEffect(() => {if (!focusComposerKey) return;// After the new chat's first paint, so its composer is the one that takes focus+ // Focus on a frame, not after render (kept): an effect after the commit; the composer is already rendered and the frame is cancelled on cleanupconst raf = requestAnimationFrame(() => focusComposer());return () => cancelAnimationFrame(raf);// eslint-disable-next-line react-hooks/exhaustive-deps@@ -1442,6 +1443,7 @@ export const ChatView: React.FC<ChatViewProps> = ({const slashOpen = !ideaMode && inputVal.length > 0 && inputVal.length < 5 && '/idea'.startsWith(inputVal.toLowerCase()) && !uploads.length;const completeIdea = () => {setInputVal('/idea ');+ // Focus on a frame, not after render (kept): only Tab, Enter or a click calls this, and React renders that update before the next framerequestAnimationFrame(() => {const el = textareaRef.current;if (el) {@@ -1568,7 +1570,8 @@ export const ChatView: React.FC<ChatViewProps> = ({const text = (e as CustomEvent<{ text?: unknown }>).detail?.text;if (typeof text !== 'string' || !text) return;setInputVal((prev) => withPrefill(prev, text));- requestAnimationFrame(() => {+ // After the render that shows the new text: the caret and height need it (the event can come from any caller)+ afterRender(() => {const el = textareaRef.current;if (!el) return;el.focus();diff --git a/frontend/src/components/ClaudeSignIn.tsx b/frontend/src/components/ClaudeSignIn.tsxindex 5b0f5ec5..3bb30b95 100644--- a/frontend/src/components/ClaudeSignIn.tsx+++ b/frontend/src/components/ClaudeSignIn.tsx@@ -1,4 +1,5 @@import React, { useCallback, useEffect, useRef, useState } from 'react';+import { useFocusAfterRender } from '../focusAfterRender';import { AlertTriangle, ExternalLink, Loader2, LogIn, LogOut, RotateCcw } from 'lucide-react';import { ClaudeLoginError, ClaudeLoginSession, claudeLoginApi, isClaudeSignInUrl, isLoginActive, loginFailure } from '../claudeLogin';import type { EngineInfo } from '../engines';@@ -43,6 +44,7 @@ export const ClaudeSignIn: React.FC<{ onSignedIn: () => void; focusRequest?: num/** Mac app: the link goes to the default browser once it arrives (no blank tab to fill). */const toBrowser = useRef(false);const startRef = useRef<HTMLButtonElement>(null);+ const focusAfterRender = useFocusAfterRender();const codeRef = useRef<HTMLInputElement>(null);const retryRef = useRef<HTMLButtonElement>(null);const alive = useRef(true);@@ -151,7 +153,7 @@ export const ClaudeSignIn: React.FC<{ onSignedIn: () => void; focusRequest?: numsetCode('');setBlocked(false);// Focus goes back to where it started.- requestAnimationFrame(() => startRef.current?.focus());+ focusAfterRender(() => startRef.current);};// While it's running, look again: it can time out, or finish from another tab.@@ -317,6 +319,7 @@ export const ClaudeSignOut: React.FC<{ onSignedOut: (engines: EngineInfo[]) => vif (busy) return;setOpen(false);setError(null);+ // Focus on a frame, not after render (kept): the trigger is always on screen; only Cancel, Escape or the backdrop close itrequestAnimationFrame(() => triggerRef.current?.focus());};diff --git a/frontend/src/components/CodingAgents.tsx b/frontend/src/components/CodingAgents.tsxindex 2c075435..819b8813 100644--- a/frontend/src/components/CodingAgents.tsx+++ b/frontend/src/components/CodingAgents.tsx@@ -1,4 +1,5 @@import React, { useCallback, useEffect, useId, useRef, useState } from 'react';+import { useFocusAfterRender } from '../focusAfterRender';import { AlertTriangle, Check, ChevronDown, Copy, Loader2, Plus, RotateCcw, TerminalSquare } from 'lucide-react';import {AgentCall,@@ -386,6 +387,7 @@ export const CodingAgents: React.FC<{ send?: typeof fetch; currentSpace?: stringconst [rowError, setRowError] = useState<string | null>(null);const [activity, setActivity] = useState<Record<string, Activity>>({});const addRef = useRef<HTMLButtonElement>(null);+ const focusAfterRender = useFocusAfterRender();const load = useCallback(async () => {try {@@ -422,6 +424,7 @@ export const CodingAgents: React.FC<{ send?: typeof fetch; currentSpace?: stringconst full = list.kind === 'ready' && list.connections.length >= list.max;const done = () => {setCreated(null);+ // Focus on a frame, not after render (kept): only Done (a click) calls this, and React renders that update before the next framerequestAnimationFrame(() => addRef.current?.focus());};@@ -446,6 +449,7 @@ export const CodingAgents: React.FC<{ send?: typeof fetch; currentSpace?: stringinitialSpace={currentSpace}onCancel={() => {setAdding(false);+ // Focus on a frame, not after render (kept): only Cancel (a click) calls this, and React renders that update before the next framesetFormError(null);requestAnimationFrame(() => addRef.current?.focus());}}@@ -539,7 +543,7 @@ export const CodingAgents: React.FC<{ send?: typeof fetch; currentSpace?: stringsetConfirm(null);if (created?.connection.id === c.id) setCreated(null);setList((l) => (l.kind === 'ready' ? { ...l, connections: l.connections.filter((x) => x.id !== c.id) } : l));- requestAnimationFrame(() => addRef.current?.focus());+ focusAfterRender(() => addRef.current);}}activity={activity[c.id] ?? null}onToggleActivity={() => {diff --git a/frontend/src/components/DevStatusLine.tsx b/frontend/src/components/DevStatusLine.tsxindex 5acda5ed..7dfccab7 100644--- a/frontend/src/components/DevStatusLine.tsx+++ b/frontend/src/components/DevStatusLine.tsx@@ -8,6 +8,7 @@// floor and the command guards are on in every status.import React, { useEffect, useId, useRef, useState } from 'react';+import { useFocusAfterRender } from '../focusAfterRender';import { ChevronDown, Info } from 'lucide-react';import {DevModeError,@@ -84,6 +85,7 @@ export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, teconst [note, setNote] = useState<string | null>(null);const [removed, setRemoved] = useState<(RemovedRepo & { busy: boolean; error: string | null }) | null>(null);const wrap = useRef<HTMLDivElement>(null);+ const focusAfterRender = useFocusAfterRender();// One 200 ms ping when a check lands, not on first paint.const firstCheck = useRef(checkedAt);const ping = checkedAt != null && checkedAt !== firstCheck.current;@@ -114,6 +116,7 @@ export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, teconst loneTeam = single && line.action === 'link' ? ownTeam(state.repos[0]) ?? teams.find((t) => !state.repos.some((r) => r.team === t.name)) ?? null : null;const focusAfter = (id: string) => {+ // Focus on a frame, not after render (kept): only Cancel or Escape call this, and React renders that update before the next framerequestAnimationFrame(() => {const el = [...(wrap.current?.querySelectorAll<HTMLElement>('[data-dv-row-action], [data-dv-status-action], [data-dv-norepo-action]') ?? [])].find((b) => b.dataset.dvRowAction === id || (id === 'line' && b.dataset.dvStatusAction) || (id === 'norepo' && b.dataset.dvNorepoAction !== undefined),@@ -134,7 +137,7 @@ export const DevStatusLine: React.FC<DevStatusLineProps> = ({ spaceId, state, te// A team's repo link comes back as that team's link; a hand row as a hand row (answer 5).const team = repo.added_by === 'team' && repo.from === 'repo' ? row.teamId : null;setRemoved({ repo: repo.repo, team, teamName: team ? row.team : null, busy: false, error: null });- requestAnimationFrame(() => wrap.current?.querySelector<HTMLElement>('[data-dv-undo]')?.focus());+ focusAfterRender(() => wrap.current?.querySelector<HTMLElement>('[data-dv-undo]'));},(e: unknown) => {setBusy(null);diff --git a/frontend/src/components/EngineAccounts.tsx b/frontend/src/components/EngineAccounts.tsxindex f7ade367..ca6a9479 100644--- a/frontend/src/components/EngineAccounts.tsx+++ b/frontend/src/components/EngineAccounts.tsx@@ -299,6 +299,7 @@ export const AccountList: React.FC<{spec={spec}onCancel={() => {setAdding(false);+ // Focus on a frame, not after render (kept): only Cancel or Escape call this, and React renders that update before the next framerequestAnimationFrame(() => addRef.current?.focus());}}onCreated={async () => {diff --git a/frontend/src/components/GoalsStrip.tsx b/frontend/src/components/GoalsStrip.tsxindex df147067..6c85f6f7 100644--- a/frontend/src/components/GoalsStrip.tsx+++ b/frontend/src/components/GoalsStrip.tsx@@ -794,6 +794,7 @@ export const GoalForm: React.FC<{if (hasFormErrors(errors)) {// A problem behind "More options" opens it. Then move to the first problem.if (errors.budget) setMore(true);+ // Focus on a frame, not after render (kept): a submit event: React renders the error state before the next framerequestAnimationFrame(() => formRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus());return;}diff --git a/frontend/src/components/InboxPage.tsx b/frontend/src/components/InboxPage.tsxindex 17c832e1..aa6b5ae5 100644--- a/frontend/src/components/InboxPage.tsx+++ b/frontend/src/components/InboxPage.tsx@@ -55,6 +55,7 @@ export const InboxPage: React.FC<{e.preventDefault();const next = TABS[(TABS.findIndex((x) => x.id === tab) + 1) % TABS.length].id;onTab(next);+ // Focus on a frame, not after render (kept): an arrow key: React renders the tab change before the next frame, and the tabs are always on screenrequestAnimationFrame(() => document.getElementById(`inbox-tab-${next}`)?.focus());}}tabIndex={on ? 0 : -1}diff --git a/frontend/src/components/MissionWatch.tsx b/frontend/src/components/MissionWatch.tsxindex e88da11a..efcf988a 100644--- a/frontend/src/components/MissionWatch.tsx+++ b/frontend/src/components/MissionWatch.tsx@@ -3,6 +3,7 @@// watcher's chat message and the amber Inbox row. All copy is from the design; all numbers are the// report's own rows. Data that doesn't parse never reaches here (missionWatch.ts drops it).import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';+import { useFocusAfterRender } from '../focusAfterRender';import { AlertCircle, AlertTriangle, CheckCircle2, ChevronDown, ChevronUp, Eye, Hand, HelpCircle, Info, Loader2, MessageSquare, RotateCcw, ShieldCheck, XCircle, type LucideIcon } from 'lucide-react';import {CHIP_TONES,@@ -669,6 +670,7 @@ const Controls: React.FC<{const [chipError, setChipError] = useState<string | null>(null);const [undo, setUndo] = useState<{ kwant: string } | null>(null);const chipRef = useRef<HTMLButtonElement>(null);+ const focusAfterRender = useFocusAfterRender();const wrap = useRef<HTMLDivElement>(null);const panelId = useId();const reportId = useId();@@ -732,7 +734,8 @@ const Controls: React.FC<{const close = () => {setPanel(null);setError(null);- requestAnimationFrame(() => chipRef.current?.focus());+ // close also runs after an await (run's `after`): focus once the chip is back and enabled+ focusAfterRender(() => chipRef.current);};const openPanel = (mode: 'setup' | 'change') => {setChipError(null);@@ -856,6 +859,7 @@ const Controls: React.FC<{timeZone={timeZone}onHide={() => {setReportOpen(false);+ // Focus on a frame, not after render (kept): only Hide (a click) calls this, and the chip is already on screenrequestAnimationFrame(() => chipRef.current?.focus());}}onOpenChat={board.onOpenChat ? () => board.onOpenChat!(m) : undefined}diff --git a/frontend/src/components/NewChannelModal.tsx b/frontend/src/components/NewChannelModal.tsxindex d40960a1..7752ed1e 100644--- a/frontend/src/components/NewChannelModal.tsx+++ b/frontend/src/components/NewChannelModal.tsx@@ -38,6 +38,7 @@ export const NewChannelModal: React.FC<NewChannelModalProps> = ({ isOpen, onClossetTouched(false);setError(null);setSubmitting(false);+ // Focus on a frame, not after render (kept): an effect after the commit that renders the name fieldrequestAnimationFrame(() => nameRef.current?.focus());// eslint-disable-next-line react-hooks/exhaustive-deps}, [isOpen]);diff --git a/frontend/src/components/ReviewItemView.tsx b/frontend/src/components/ReviewItemView.tsxindex c9968b99..5863f91d 100644--- a/frontend/src/components/ReviewItemView.tsx+++ b/frontend/src/components/ReviewItemView.tsx@@ -331,6 +331,7 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({const closeSend = () => {setSendOpen(false);setSendErr(null);+ // Focus on a frame, not after render (kept): only Cancel, Escape or the sheet close call this, and the button is already on screenrequestAnimationFrame(() => sendBtnRef.current?.focus());};const sendBack = async () => {@@ -701,6 +702,7 @@ const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({denyAllOpen={denyAllOpen}onClose={() => {setRollOpen(null);+ // Focus on a frame, not after render (kept): only Keep my work or Escape call this, and the button is already on screenrequestAnimationFrame(() => rollBtnRef.current?.focus());}}onDone={(r, extra) => {diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsxindex a5dd486f..28b7b853 100644--- a/frontend/src/components/RoutinesPanel.tsx+++ b/frontend/src/components/RoutinesPanel.tsx@@ -150,6 +150,7 @@ export const RoutineForm: React.FC<{const tzRef = useRef<HTMLInputElement>(null);const openTz = () => {setTzOpen(true);+ // Focus on a frame, not after render (kept): only Change (a click) calls this, and React renders that update before the next framerequestAnimationFrame(() => tzRef.current?.focus());};const setS = (patch: Partial<ScheduleForm>) => setF((prev) => ({ ...prev, schedule: { ...prev.schedule, ...patch } }));diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex 798da3fe..cf57d0b0 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -476,6 +476,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t// Opened from a page's Settings button (the Idea jar's): bring that switch into view and focus it.useEffect(() => {if (!isOpen || !focusRow || !settings) return;+ // Focus on a frame, not after render (kept): an effect after the commit that renders the switch; the frame is cancelled on cleanupconst raf = requestAnimationFrame(() => {// The Claude switch shows only in VM mode; otherwise land on the Computer card it lives in.const el =diff --git a/frontend/src/components/ShowOnce.tsx b/frontend/src/components/ShowOnce.tsxindex 4cdcc84f..b9a24701 100644--- a/frontend/src/components/ShowOnce.tsx+++ b/frontend/src/components/ShowOnce.tsx@@ -226,6 +226,7 @@ export const ShowOnceStart: React.FC<{* Record steps when the stage is up, else Show it once in Skills, else the Skills tab panel.*/export function focusAfterDiscard() {+ // Focus on a frame, not after render (kept): a plain function, not a component, so it cannot use the hook; it looks for what is on screenrequestAnimationFrame(() => {const visible = (el: Element | null): el is HTMLElement => el instanceof HTMLElement && el.getClientRects().length > 0;const rec = Array.from(document.querySelectorAll('.so-record-steps')).find(visible);diff --git a/frontend/src/components/SkillsPanel.tsx b/frontend/src/components/SkillsPanel.tsxindex 0e4673c4..bbdf1553 100644--- a/frontend/src/components/SkillsPanel.tsx+++ b/frontend/src/components/SkillsPanel.tsx@@ -560,6 +560,7 @@ export const SkillsPanel: React.FC<{const waitBtn = useRef<HTMLButtonElement>(null);// Mira §4.1: when the row goes away with focus on its button, focus moves to Show it onceconst setWaiting = useCallback((next: Recording | null) => {+ // Focus on a frame, not after render (kept): Show it once is already on screen; only the row that had focus goes awayif (!next && waitBtn.current && document.activeElement === waitBtn.current) requestAnimationFrame(() => showOnceBtn.current?.focus());setWaitingRaw(next);}, []);diff --git a/frontend/src/components/SpaceDocsTab.tsx b/frontend/src/components/SpaceDocsTab.tsxindex f771fc65..d57b865b 100644--- a/frontend/src/components/SpaceDocsTab.tsx+++ b/frontend/src/components/SpaceDocsTab.tsx@@ -1,4 +1,5 @@import React, { useCallback, useEffect, useRef, useState } from 'react';+import { useFocusAfterRender } from '../focusAfterRender';import { AlertTriangle, Copy, FileText, Loader2, RotateCw, Trash2, Upload, X } from 'lucide-react';import {DOC_ACCEPT,@@ -68,6 +69,7 @@ export const SpaceDocsTab: React.FC<{ spaceId: string; spaceName: string; isPhonconst inputRef = useRef<HTMLInputElement>(null);const chooseRef = useRef<HTMLButtonElement>(null);const panelRef = useRef<HTMLDivElement>(null);+ const focusAfterRender = useFocusAfterRender();const nextId = useRef(1);const queue = useRef<Promise<void>>(Promise.resolve());@@ -143,10 +145,10 @@ export const SpaceDocsTab: React.FC<{ spaceId: string; spaceName: string; isPhonconst next = docs.filter((d) => d.name !== name);await load();// Focus moves to the next row's remove, or to Choose files when the list is empty.- requestAnimationFrame(() => {+ focusAfterRender(() => {const target = next[Math.min(at, next.length - 1)];const el = target ? panelRef.current?.querySelector<HTMLElement>(`[data-doc-remove="${CSS.escape(target.name)}"]`) : chooseRef.current;- (el ?? chooseRef.current)?.focus();+ return el ?? chooseRef.current;});};diff --git a/frontend/src/components/TeamNeedBox.tsx b/frontend/src/components/TeamNeedBox.tsxindex b104a225..bd521c50 100644--- a/frontend/src/components/TeamNeedBox.tsx+++ b/frontend/src/components/TeamNeedBox.tsx@@ -58,6 +58,7 @@ export const TeamNeedBox: React.FC<TeamNeedBoxProps> = ({ label, register, autoF// eslint-disable-next-line react-hooks/exhaustive-deps}, [register, rt?.registerNeedBox]);useEffect(() => {+ // Focus on a frame, not after render (kept): a mount effect: the box is already renderedif (autoFocus) requestAnimationFrame(() => ta.current?.focus({ preventScroll: true }));}, [autoFocus]);useEffect(() => {@@ -110,6 +111,7 @@ export const TeamNeedBox: React.FC<TeamNeedBoxProps> = ({ label, register, autoF{onCancel: () => {onShow?.();+ // Focus on a frame, not after render (kept): only the sheet’s Cancel calls this; the box is on screen, or remounts and its autoFocus effect focuses itrequestAnimationFrame(focusBox);},onDone: () => {diff --git a/frontend/src/components/TeamPreviewSheet.tsx b/frontend/src/components/TeamPreviewSheet.tsxindex bdaf4430..65d5e88c 100644--- a/frontend/src/components/TeamPreviewSheet.tsx+++ b/frontend/src/components/TeamPreviewSheet.tsx@@ -463,6 +463,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({useEffect(() => {if (!ready || focused.current) return;focused.current = true;+ // Focus on a frame, not after render (kept): an effect after the commit that renders Rename or CreaterequestAnimationFrame(() => {const clash = !isD && Object.keys(notes).length > 0;(clash && firstRenameRef.current ? firstRenameRef.current : createRef.current)?.focus({ preventScroll: true });diff --git a/frontend/src/focusAfterRender.ts b/frontend/src/focusAfterRender.tsindex d37dbc22..157367af 100644--- a/frontend/src/focusAfterRender.ts+++ b/frontend/src/focusAfterRender.ts@@ -10,16 +10,20 @@ import { useCallback, useLayoutEffect, useReducer, useRef } from 'react';* on screen: a component that unmounts in the same update never runs its effects.*/export function useAfterRender(): (work: () => void) => void {- const queue = useRef<Array<() => void>>([]);- const [, render] = useReducer((n: number) => n + 1, 0);+ // Each piece of work waits for the render it asked for (its ticket), not just the next commit: a store update+ // (useSyncExternalStore) renders first in a sync commit of its own, before the state set next to it after an+ // await, and work run there would miss the target that state shows (raf-focus-after-render, DevStatusLine Undo).+ const queue = useRef<Array<{ at: number; work: () => void }>>([]);+ const asked = useRef(0);+ const [rendered, render] = useReducer((n: number) => n + 1, 0);useLayoutEffect(() => {- if (!queue.current.length) return;- const run = queue.current;- queue.current = [];- for (const work of run) work();+ if (!queue.current.some((q) => q.at <= rendered)) return;+ const run = queue.current.filter((q) => q.at <= rendered);+ queue.current = queue.current.filter((q) => q.at > rendered);+ for (const q of run) q.work();});return useCallback((work: () => void) => {- queue.current.push(work);+ queue.current.push({ at: ++asked.current, work });render();}, []);}diff --git a/frontend/tests/alwaysAllowedList.test.mjs b/frontend/tests/alwaysAllowedList.test.mjsindex fb73b77e..32da9831 100644--- a/frontend/tests/alwaysAllowedList.test.mjs+++ b/frontend/tests/alwaysAllowedList.test.mjs@@ -131,6 +131,31 @@ test('Take back sends that one grant and shows what is left; focus stays in theassert.equal(document.activeElement, host.querySelectorAll('[data-take-back]')[1], 'focus moves to the next row');});+test('Take back on the last row: focus moves to the new last row even when a frame comes before React renders the list', async () => {+ // A frame that is due before React's scheduler task (raf-focus-after-render): an update made after an await or a+ // .then renders in that task, so a focus on requestAnimationFrame ran first, found the old DOM and focus dropped+ // to <body>. Running each frame callback in a microtask forces that order every time.+ const realRaf = [g.requestAnimationFrame, window.requestAnimationFrame];+ const frameFirst = (on) => {+ const raf = on ? (cb) => (queueMicrotask(() => cb(performance.now())), 0) : null;+ g.requestAnimationFrame = raf ?? realRaf[0];+ window.requestAnimationFrame = raf ?? realRaf[1];+ };+ const list = three();+ server = (_url, init) => (init?.method === 'DELETE' ? json(200, { revoked: 1, always_allowed: [list[0], list[1]] }) : json(200, list));+ const host = await mount();+ try {+ frameFirst(true);+ await click(host.querySelectorAll('[data-take-back]')[2]);+ frameFirst(false);+ assert.equal(rows(host).length, 2);+ const a = document.activeElement;+ assert.ok(a === host.querySelectorAll('[data-take-back]')[1], `focus is on the new last Take back, not ${a?.tagName.toLowerCase()} "${a?.textContent.trim().slice(0, 30)}"`);+ } finally {+ frameFirst(false);+ }+});+test('Take back all sends {} and leaves only the confirmation, no heading', async () => {server = (_url, init) => (init?.method === 'DELETE' ? json(200, { revoked: 3, always_allowed: [] }) : json(200, three()));const host = await mount();diff --git a/frontend/tests/devTeamRepos.test.mjs b/frontend/tests/devTeamRepos.test.mjsindex b4e3bd75..57d96252 100644--- a/frontend/tests/devTeamRepos.test.mjs+++ b/frontend/tests/devTeamRepos.test.mjs@@ -380,6 +380,35 @@ test('DOM: Remove on a hand row sends DELETE …/dev_mode/repos/:key; team rowsroot.unmount();});+test('DOM: after Remove, focus lands on Undo even when a frame comes before React renders it', async () => {+ // A frame that is due before React's scheduler task (raf-focus-after-render): an update made after an await or a+ // .then renders in that task, so a focus on requestAnimationFrame ran first, found the old DOM and focus dropped+ // to <body>. Running each frame callback in a microtask forces that order every time.+ const realRaf = [g.requestAnimationFrame, window.requestAnimationFrame];+ const frameFirst = (on) => {+ const raf = on ? (cb) => (queueMicrotask(() => cb(performance.now())), 0) : null;+ g.requestAnimationFrame = raf ?? realRaf[0];+ window.requestAnimationFrame = raf ?? realRaf[1];+ };+ // Name the focused element instead of handing jsdom nodes to assert (printing them can run out of memory).+ const focused = () => {+ const a = document.activeElement;+ return a ? `${a.tagName.toLowerCase()} "${a.textContent.trim().slice(0, 30)}"` : 'nothing';+ };+ const { root } = await line({ repos: [APP, SITE, DOCS] });+ try {+ frameFirst(true);+ await click(document.querySelector(`[data-dv-row-action="${DOCS.key}"]`));+ await frame();+ frameFirst(false);+ assert.ok(has('[data-dv-undo]'), 'Undo is there');+ assert.ok(document.activeElement === document.querySelector('[data-dv-undo]'), `focus is on Undo, not ${focused()}`);+ } finally {+ frameFirst(false);+ root.unmount();+ }+});+test('DOM: a 409 team_repo on Remove shows the team note as the error', async () => {const { root } = await line({ repos: [APP, SITE, DOCS] });server.state = { ...server.state, repos: server.state.repos.map((r) => (r.key === DOCS.key ? { ...r, added_by: 'team', team: 'Docs' } : r)) };diff --git a/frontend/tests/focusAfterRender.test.mjs b/frontend/tests/focusAfterRender.test.mjsindex 2f367887..3e1558dd 100644--- a/frontend/tests/focusAfterRender.test.mjs+++ b/frontend/tests/focusAfterRender.test.mjs@@ -2,6 +2,7 @@// shows its target, and a guard keeps new `setTimeout(() => ….focus())` calls out of frontend/src. A focus on a// timer can run before React renders its target (the scheduler yields on a slow machine), and focus drops to// <body> for good. Use useFocusAfterRender / useAfterRender from src/focusAfterRender.ts instead.+// raf-focus-after-render: the same guard covers `requestAnimationFrame(() => ….focus())` (KEPT_FRAME).import assert from 'node:assert/strict';import test, { afterEach } from 'node:test';import { readFileSync, readdirSync } from 'node:fs';@@ -21,7 +22,7 @@ g.IS_REACT_ACT_ENVIRONMENT = false;const m = await loadBundled(`export { useFocusAfterRender, useAfterRender } from './src/focusAfterRender';export { createRoot } from 'react-dom/client';- export { createElement, useRef, useState } from 'react';+ export { createElement, useRef, useState, useSyncExternalStore } from 'react';`);const h = m.createElement;@@ -45,17 +46,43 @@ const KEPT = [{ file: 'components/dev/ProdFloorCard.tsx', has: 'cardRef.current?.contains(a)', why: 'takeBackup: the main button is always rendered (#897 keeps it)' },];+/**+ * The frame focus calls that stay (raf-focus-after-render), each with why; same rules as KEPT. A frame is safe when+ * only a click or key starts the update (React renders it before the next frame), when it runs in an effect after+ * the commit that renders its target, or when the target is already on screen.+ */+const KEPT_FRAME = [+ { file: 'components/ChatView.tsx', has: 'focusComposer()', why: 'an effect after the commit; the composer is rendered; cancelled on cleanup' },+ { file: 'components/ChatView.tsx', has: 'el.setSelectionRange(6, 6)', why: 'completeIdea: Tab, Enter or a click' },+ { file: 'components/ClaudeSignIn.tsx', has: 'triggerRef.current?.focus()', why: 'Sign out trigger is always on screen; Cancel, Escape or the backdrop' },+ { file: 'components/CodingAgents.tsx', has: 'addRef.current?.focus()', why: 'Done and Cancel: a click or key: React renders that update before the next frame', count: 2 },+ { file: 'components/DevStatusLine.tsx', has: '[data-dv-row-action], [data-dv-status-action]', why: 'focusAfter: the link form’s Cancel or Escape' },+ { file: 'components/EngineAccounts.tsx', has: 'addRef.current?.focus()', why: 'the add form’s Cancel or Escape' },+ { file: 'components/GoalsStrip.tsx', has: '[aria-invalid="true"]', why: 'a submit event: React renders the errors before the next frame' },+ { file: 'components/InboxPage.tsx', has: 'inbox-tab-', why: 'an arrow key; the tabs are always on screen' },+ { file: 'components/MissionWatch.tsx', has: 'chipRef.current?.focus()', why: 'onHide: a click; the chip is on screen' },+ { file: 'components/NewChannelModal.tsx', has: 'nameRef.current?.focus()', why: 'an effect after the commit that renders the field' },+ { file: 'components/ReviewItemView.tsx', has: 'sendBtnRef.current?.focus()', why: 'closeSend: Cancel, Escape or the sheet close; the button is on screen' },+ { file: 'components/ReviewItemView.tsx', has: 'rollBtnRef.current?.focus()', why: 'the roll-back dialog’s Keep my work or Escape; the button is on screen' },+ { file: 'components/RoutinesPanel.tsx', has: 'tzRef.current?.focus()', why: 'openTz: Change, a click' },+ { file: 'components/SettingsModal.tsx', has: 'data-switch=', why: 'an effect after the commit that renders the switch; cancelled on cleanup' },+ { file: 'components/ShowOnce.tsx', has: '.so-record-steps', why: 'focusAfterDiscard is a plain function, not a component: it can’t use the hook' },+ { file: 'components/SkillsPanel.tsx', has: 'showOnceBtn.current?.focus()', why: 'Show it once is already on screen; only the row that had focus goes' },+ { file: 'components/TeamNeedBox.tsx', has: 'ta.current?.focus({ preventScroll: true })', why: 'a mount effect: the box is rendered' },+ { file: 'components/TeamNeedBox.tsx', has: 'focusBox', why: 'the sheet’s Cancel; the box is on screen, or remounts and autofocuses' },+ { file: 'components/TeamPreviewSheet.tsx', has: 'firstRenameRef.current', why: 'an effect after the commit that renders Rename or Create' },+];+const sources = (dir) =>readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? sources(join(dir, e.name)) : /\.(tsx?|jsx?|mjs)$/.test(e.name) ? [join(dir, e.name)] : []));/** Comments out, line breaks kept (so line numbers still match). Good enough for this code base's comments. */const uncomment = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' ')).replace(/^(\s*)\/\/.*$/gm, '$1');-/** Every `setTimeout(` / `window.setTimeout(` whose callback (its first argument) calls `.focus(`. */-export function timerFocusCalls(file, text) {+/** Every call matching `re` whose callback (its first argument) passes `hit`. */+function callbackFocusCalls(file, text, re, hit) {const s = uncomment(text);const out = [];- const re = /\b(?:window\.)?setTimeout\s*\(/g;for (let mm; (mm = re.exec(s)); ) {let i = mm.index + mm[0].length;const start = i;@@ -68,11 +95,36 @@ export function timerFocusCalls(file, text) {} else if (c === ',' && depth === 0) break;}const cb = s.slice(start, i);- if (/\.focus\s*\(/.test(cb)) out.push({ file, line: s.slice(0, mm.index).split('\n').length, cb: cb.replace(/\s+/g, ' ').trim() });+ if (hit.test(cb)) out.push({ file, line: s.slice(0, mm.index).split('\n').length, cb: cb.replace(/\s+/g, ' ').trim() });}return out;}+/** Every `setTimeout(` / `window.setTimeout(` whose callback (its first argument) calls `.focus(`. */+export const timerFocusCalls = (file, text) => callbackFocusCalls(file, text, /\b(?:window\.)?setTimeout\s*\(/g, /\.focus\s*\(/);++/**+ * Every `requestAnimationFrame(` / `window.requestAnimationFrame(` whose callback calls `.focus(`, or is (or calls)+ * a `focusX` helper such as `focusBox`. A frame can come before React renders an update made after an `await`, a+ * `.then` or in an effect (raf-focus-after-render), the same race as a timer.+ */+export const frameFocusCalls = (file, text) =>+ callbackFocusCalls(file, text, /\b(?:window\.)?requestAnimationFrame\s*\(/g, /\.focus\s*\(|\bfocus[A-Z]\w*\b/);++/** Every call `find` finds in frontend/src must match a `kept` entry, and every entry must match its count. */+const checkKept = (find, kept) => {+ const calls = sources(SRC).flatMap((p) => find(relative(SRC, p).split('\\').join('/'), readFileSync(p, 'utf8')));+ const used = new Map();+ const unexpected = [];+ for (const c of calls) {+ const k = kept.find((e) => e.file === c.file && c.cb.includes(e.has));+ if (!k) unexpected.push(`${c.file}:${c.line} ${c.cb.slice(0, 90)}`);+ else used.set(k, (used.get(k) ?? 0) + 1);+ }+ const stale = kept.filter((k) => (used.get(k) ?? 0) !== (k.count ?? 1)).map((k) => `${k.file}: ${k.has} (found ${used.get(k) ?? 0}, expected ${k.count ?? 1})`);+ return { unexpected, stale };+};+test('guard: the scanner finds a timer focus on one line or many, and skips comments and other timers', () => {const found = timerFocusCalls('x.tsx',@@ -95,19 +147,37 @@ test('guard: the scanner finds a timer focus on one line or many, and skips comm});test('guard: no new setTimeout(… .focus()) in frontend/src; focus after render instead (src/focusAfterRender.ts)', () => {- const calls = sources(SRC).flatMap((p) => timerFocusCalls(relative(SRC, p).split('\\').join('/'), readFileSync(p, 'utf8')));- const used = new Map();- const unexpected = [];- for (const c of calls) {- const k = KEPT.find((e) => e.file === c.file && c.cb.includes(e.has));- if (!k) unexpected.push(`${c.file}:${c.line} ${c.cb.slice(0, 90)}`);- else used.set(k, (used.get(k) ?? 0) + 1);- }+ const { unexpected, stale } = checkKept(timerFocusCalls, KEPT);assert.deepEqual(unexpected, [], 'focus on a timer can run before React renders the target; use useFocusAfterRender() (or add it to KEPT with why)');- const stale = KEPT.filter((k) => (used.get(k) ?? 0) !== (k.count ?? 1)).map((k) => `${k.file}: ${k.has} (found ${used.get(k) ?? 0}, expected ${k.count ?? 1})`);assert.deepEqual(stale, [], 'KEPT lists a call that changed or is gone: update the list');});+test('guard: the frame scanner finds a frame focus on one line or many, a focusX helper, and skips comments and other frames', () => {+ const found = frameFocusCalls(+ 'x.tsx',+ [+ 'requestAnimationFrame(() => a.current?.focus());',+ 'const raf = window.requestAnimationFrame(() => {',+ ' b?.focus({ preventScroll: true });',+ '});',+ 'requestAnimationFrame(focusBox);',+ 'requestAnimationFrame(() => setFlash(id)); el.focus();',+ '// requestAnimationFrame(() => c.focus());',+ 'requestAnimationFrame(tick);',+ ].join('\n'),+ );+ assert.deepEqual(+ found.map((f) => f.line),+ [1, 2, 5],+ );+});++test('guard: no new requestAnimationFrame(… .focus()) in frontend/src; focus after render instead (src/focusAfterRender.ts)', () => {+ const { unexpected, stale } = checkKept(frameFocusCalls, KEPT_FRAME);+ assert.deepEqual(unexpected, [], 'focus on a frame can run before React renders an update made after an await or in an effect; use useFocusAfterRender() (or add it to KEPT_FRAME with why)');+ assert.deepEqual(stale, [], 'KEPT_FRAME lists a call that changed or is gone: update the list');+});+// ---------------------------------------------------------------------------------------------------// The hook@@ -180,3 +250,26 @@ test('hook: a target that is missing after the render is skipped and cleared, neawait click(bump);assert.ok(document.activeElement === bump, 'focus stays where the person put it');});++/** After an await, a store update (rendered first, in a sync commit) and a state update that shows the field. */+const store = { v: 0, subs: new Set(), set(v) { this.v = v; for (const f of this.subs) f(); } };+const StoreSwap = () => {+ const v = m.useSyncExternalStore((f) => (store.subs.add(f), () => store.subs.delete(f)), () => store.v);+ const [open, setOpen] = m.useState(false);+ const field = m.useRef(null);+ const focusAfterRender = m.useFocusAfterRender();+ const go = () =>+ Promise.resolve().then(() => {+ store.set(v + 1);+ setOpen(true);+ focusAfterRender(() => field.current);+ });+ return h('div', null, open ? h('input', { ref: field, 'data-field': '' }) : h('button', { type: 'button', onClick: go, 'data-go': '' }, 'Go'), h('span', null, `Saved ${v}`));+};++test('hook: work waits for the render it asked for, not an earlier store commit that does not show the target yet', async () => {+ const host = await mount(h(StoreSwap));+ await click(host.querySelector('[data-go]'));+ assert.equal(host.textContent.includes('Saved 1'), true, 'the store update rendered');+ assert.ok(document.activeElement === host.querySelector('[data-field]'), `focus is in the new field, not ${document.activeElement?.tagName.toLowerCase()}`);+});