Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

30t focus-after-render-everywhere: focus after the render, one shared hook (#898)

Oleksandr Ivanchenkob122e03831f4
diff --git a/frontend/src/components/AppsAccounts.tsx b/frontend/src/components/AppsAccounts.tsx
index b416f669..20aaa0b6 100644
--- a/frontend/src/components/AppsAccounts.tsx
+++ b/frontend/src/components/AppsAccounts.tsx
@@ -33,6 +33,7 @@ import { FindTool, FindToolApi } from './FindTool';
import { OPEN_ADD_TOOL_EVENT, OpenAddTool } from '../mcp';
import { usePhoneLayout } from '../usePhoneLayout';
import { ModernAvatar } from './ModernAvatar';
+import { useAfterRender } from '../focusAfterRender';
/** The tile mark: plain initials on the overlay colour, never a brand logo. */
const TILE_BG = '#231d4b';
@@ -575,13 +576,15 @@ export const AppsAccounts: React.FC<AppsAccountsProps> = (p) => {
.map((u) => u.name);
const needs = data ? data.connections.filter((c) => accountNeedsYou(c)).length : 0;
/** Opens "Sign-ins and settings", at one AI's card when given: its existing sign-in or set-up. */
+ const afterRender = useAfterRender();
const openManage = (engineCard?: string) => {
setManageOpen(true);
- window.setTimeout(() => {
+ // After the render that opens the section, so its cards are there to scroll to and focus.
+ afterRender(() => {
const card = engineCard ? manageRef.current?.querySelector<HTMLElement>(`[data-engine="${CSS.escape(engineCard)}"]`) : null;
(card ?? manageRef.current)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
card?.querySelector<HTMLElement>('button:not([disabled]), a[href]')?.focus({ preventScroll: true });
- }, 50);
+ });
};
const reloadAccounts = async () => {
await Promise.all([accountsState.reload(), enginesState.reload(), reload()]);
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index c223992f..d17070f4 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -122,6 +122,7 @@ import { ReactionButtons, ReplyButton, ReplyChip, ReplyQuote } from './MessageRe
import { DictationAnnouncer, DictationLine, DictationSetupPopover, MicButton, useDictation } from './DictationMic';
import { ReactResult, Reaction, ReplyRef, botNameOf, excerptOf, questionMessageId, reactionOf, replyRefOf } from '../reactReply';
import type { FloorResolveOpts } from '../dev/types';
+import { useAfterRender } from '../focusAfterRender';
export interface ChatMessage {
id: string;
@@ -919,6 +920,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (isMentionOpen) markNewSeen('mention');
}, [isMentionOpen]);
+ const afterRender = useAfterRender();
const handleSelectMention = (item: MentionItem) => {
if (mentionStartIndex < 0) return;
const cursorPos = textareaRef.current?.selectionStart ?? inputVal.length;
@@ -932,14 +934,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
setMentionStartIndex(-1);
const nextCursor = mentionStartIndex + mentionText.length;
- setTimeout(() => {
+ // After the render that shows the new text, so the caret and the height are set on it.
+ afterRender(() => {
if (textareaRef.current) {
textareaRef.current.focus();
textareaRef.current.setSelectionRange(nextCursor, nextCursor);
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 160)}px`;
}
- }, 0);
+ });
};
// Follow new tokens only while the reader is at the bottom; scrolling up to read stays put.
diff --git a/frontend/src/components/ComposioTile.tsx b/frontend/src/components/ComposioTile.tsx
index 0bc0d9ca..2bb4e38e 100644
--- a/frontend/src/components/ComposioTile.tsx
+++ b/frontend/src/components/ComposioTile.tsx
@@ -9,6 +9,7 @@ import { CatalogEntry, ConnectionsError, connectionsApi } from '../connections';
import { listNames, removeServer, serverIdOf, setServerEnabled } from '../appsAccounts';
import { editorProps } from '../escape';
import { KeyField, KeyPhase } from './FindTool';
+import { useFocusAfterRender } from '../focusAfterRender';
export interface ComposioTileApi {
addKey: (key: string) => Promise<unknown>;
@@ -108,11 +109,12 @@ export const ComposioTile: React.FC<ComposioTileProps> = (p) => {
if (open === 'remove') keepRef.current?.focus();
}, [open]);
+ const focusAfterRender = useFocusAfterRender();
const openKey = (what: Open) => {
setOpen(what);
setPhase({ s: 'idle' });
setActionError(null);
- window.setTimeout(() => keyRef.current?.focus(), 0);
+ focusAfterRender(() => keyRef.current);
};
const close = () => {
setOpen('none');
@@ -129,7 +131,7 @@ export const ComposioTile: React.FC<ComposioTileProps> = (p) => {
const text = e instanceof Error ? e.message : 'Something went wrong.';
const isRefused = e instanceof ConnectionsError && (e.status === 409 || e.status === 400);
setPhase(isRefused ? { s: 'refused', text } : { s: 'down', text });
- window.setTimeout(() => keyRef.current?.focus(), 0);
+ focusAfterRender(() => keyRef.current);
return;
}
const was = open;
diff --git a/frontend/src/components/DevModeSettings.tsx b/frontend/src/components/DevModeSettings.tsx
index 24e2ba82..33a594f2 100644
--- a/frontend/src/components/DevModeSettings.tsx
+++ b/frontend/src/components/DevModeSettings.tsx
@@ -10,6 +10,7 @@ import { DevModeState, DevTeamRef, devApi, devStore, normaliseRepo } from '../de
import { foundRepo, hasFoundCode, readableRepos } from '../devSuggest';
import { JiraSettings } from './JiraSettings';
import { useDevMode } from './DevModeSwitch';
+import { useFocusAfterRender } from '../focusAfterRender';
const card = 'rounded-xl border border-zinc-800 bg-zinc-950/60';
/** Off with a repo found: the accent family of the primary buttons (no shadow, no glow, no holo). */
@@ -68,6 +69,7 @@ export const DevModeSettings: React.FC<{ spaceId: string; spaceName: string; app
setBackup(state?.backup_command ?? '');
}, [baseRepo, baseBranch, state?.backup_command]);
+ const focusAfterRender = useFocusAfterRender();
// 0.9.8 (first-screen A): the header switch is gone, so this card is where Dev mode is turned on, the
// first time too. It shows as soon as the space's state has loaded.
if (!state) return null;
@@ -100,7 +102,7 @@ export const DevModeSettings: React.FC<{ spaceId: string; spaceName: string; app
const turnOn = () => {
if (repoErr) {
setDetails(true);
- setTimeout(() => repoInput.current?.focus(), 0);
+ focusAfterRender(() => repoInput.current);
return;
}
if (!accent && !normal) {
diff --git a/frontend/src/components/DictationMic.tsx b/frontend/src/components/DictationMic.tsx
index dd4e038a..55ccb04b 100644
--- a/frontend/src/components/DictationMic.tsx
+++ b/frontend/src/components/DictationMic.tsx
@@ -34,6 +34,7 @@ import {
type Inserted,
type MicView,
} from '../dictation';
+import { useAfterRender } from '../focusAfterRender';
export type DictPhase = 'idle' | 'asking' | 'recording' | 'transcribing';
@@ -110,6 +111,7 @@ export function useDictation(o: DictationOptions): Dictation {
const [popOpen, setPopOpen] = useState(false);
const [announce, setAnnounceState] = useState({ text: '', n: 0 });
const micRef = useRef<HTMLButtonElement>(null);
+ const afterRender = useAfterRender();
const popRef = useRef<HTMLDivElement>(null);
const levelRef = useRef(0);
const recRef = useRef<Rec | null>(null);
@@ -130,7 +132,7 @@ export function useDictation(o: DictationOptions): Dictation {
setPhaseState(p);
};
const say = (text: string) => setAnnounceState((a) => ({ text, n: a.n + 1 }));
- const focusMic = () => setTimeout(() => micRef.current?.focus({ preventScroll: true }), 0);
+ const focusMic = () => afterRender(() => micRef.current?.focus({ preventScroll: true }));
const clearAdded = () => {
if (addedTimer.current) clearTimeout(addedTimer.current);
addedTimer.current = null;
@@ -234,7 +236,8 @@ export function useDictation(o: DictationOptions): Dictation {
clearAdded();
addedTimer.current = setTimeout(() => setLine((l) => (l?.kind === 'added' ? null : l)), ADDED_MS);
const handTouch = live.current.phone && live.current.touch;
- setTimeout(() => {
+ // After the render that shows the new text, so the height and the caret are measured on it.
+ afterRender(() => {
const ta = textareaRef.current;
if (ta) {
ta.style.height = 'auto';
@@ -245,7 +248,7 @@ export function useDictation(o: DictationOptions): Dictation {
ta.focus();
ta.setSelectionRange(ins.caret, ins.caret);
}
- }, 0);
+ });
return;
}
if (r.status === 409 && r.code === 'no_transcriber') {
@@ -403,7 +406,7 @@ export function useDictation(o: DictationOptions): Dictation {
setLine(null);
say('Dictated words removed.');
const at = line.ins.from;
- setTimeout(() => {
+ afterRender(() => {
const ta = textareaRef.current;
if (ta) {
ta.style.height = 'auto';
@@ -414,7 +417,7 @@ export function useDictation(o: DictationOptions): Dictation {
ta.focus();
ta.setSelectionRange(at, at);
}
- }, 0);
+ });
};
const noteTyping = useCallback(() => {
@@ -430,7 +433,7 @@ export function useDictation(o: DictationOptions): Dictation {
if (spaceId) setMicHidden(spaceId, true);
setPopOpen(false);
say('Mic hidden. It comes back when dictation is set up.');
- setTimeout(() => textareaRef.current?.focus({ preventScroll: true }), 0);
+ afterRender(() => textareaRef.current?.focus({ preventScroll: true }));
};
// Esc anywhere stops and transcribes, before the composer's own Esc, unless a dialog or picker is open.
@@ -484,6 +487,7 @@ export function useDictation(o: DictationOptions): Dictation {
// The popover: focus its first button; Esc or a click outside closes it.
useEffect(() => {
if (!popOpen) return;
+ // Kept on a timer: this effect runs after the commit that renders the popover, so its button is already there.
const t = setTimeout(() => popRef.current?.querySelector<HTMLButtonElement>('button')?.focus({ preventScroll: true }), 0);
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
diff --git a/frontend/src/components/FindTool.tsx b/frontend/src/components/FindTool.tsx
index 362581fc..68033800 100644
--- a/frontend/src/components/FindTool.tsx
+++ b/frontend/src/components/FindTool.tsx
@@ -59,6 +59,7 @@ import {
sourceWords,
} from '../appSearch';
import { usePhoneLayout } from '../usePhoneLayout';
+import { useFocusAfterRender } from '../focusAfterRender';
export { presetPublisher };
@@ -623,10 +624,11 @@ export const FindTool: React.FC<FindToolProps> = (p) => {
return id ? (connections.find((c) => c.id === id)?.used_by ?? []).map((u) => u.name) : [];
};
+ const focusAfterRender = useFocusAfterRender();
const openKey = (app: { slug: string; name: string } | null, replace = false) => {
setKeyOpen({ slug: app?.slug ?? null, name: app?.name ?? null, replace });
setKeyPhase({ s: 'idle' });
- window.setTimeout(() => keyRef.current?.focus(), 0);
+ focusAfterRender(() => keyRef.current);
};
/** Starts an app's sign-in: the tab opens inside the click or key event, its address follows. */
@@ -673,7 +675,7 @@ export const FindTool: React.FC<FindToolProps> = (p) => {
const text = e instanceof Error ? e.message : 'Something went wrong.';
const refused = e instanceof ConnectionsError && (e.status === 409 || e.status === 400);
setKeyPhase(refused ? { s: 'refused', text } : { s: 'down', text });
- window.setTimeout(() => keyRef.current?.focus(), 0);
+ focusAfterRender(() => keyRef.current);
return;
}
if (!alive.current) return;
diff --git a/frontend/src/components/GetStarted.tsx b/frontend/src/components/GetStarted.tsx
index c46c3ea8..cd4c5984 100644
--- a/frontend/src/components/GetStarted.tsx
+++ b/frontend/src/components/GetStarted.tsx
@@ -59,6 +59,7 @@ import {
} from '../gettingStarted';
import { type StepTeam, type TeamStepView, teamDoneValue, teamStepView } from '../firstScreen';
import { type InstallTrack, forgetInstall, installDetails, startInstall, useInstallTrack, useStartVersion } from '../gettingStartedInstall';
+import { useFocusAfterRender } from '../focusAfterRender';
const FOCUS = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
const SLOW_S = 40;
@@ -778,6 +779,7 @@ export const TeamStep: React.FC<{
const [importing, setImporting] = useState(false);
const imported = useRef(false);
const importTile = useRef<HTMLButtonElement>(null);
+ const focusAfterRender = useFocusAfterRender();
// Desktop app only: one look at the usual places, for the "N found" line and the dialog.
const localSources = useLocalSources();
const [local] = localSources;
@@ -786,7 +788,7 @@ export const TeamStep: React.FC<{
setImporting(false);
// An import that went in (even if undone in the dialog) counts; Cancel or Close leaves step 3 as it was.
if (imported.current) onImported();
- else window.setTimeout(() => importTile.current?.focus(), 0);
+ else focusAfterRender(() => importTile.current);
};
const offered = new Set(view.templateIds);
const templates = rt?.available ? (rt.templates ?? []).filter((t) => offered.has(t.id)) : [];
@@ -1013,6 +1015,7 @@ export const GetStarted: React.FC<GetStartedProps> = ({ space, bots, engines, re
// Start with @team: today's Keep, then the composer, so the next thing is the first ask.
const startTeam = () => {
keep();
+ // Kept on a timer: the composer is already on screen, outside this card, and Keep can remove the card in the same update.
window.setTimeout(() => document.querySelector<HTMLTextAreaElement>('[data-composer-form] textarea')?.focus(), 0);
};
// "Bring your bots": like Keep, the card goes once step 2 is done; before that step 3 reads done.
diff --git a/frontend/src/components/GitHubConnect.tsx b/frontend/src/components/GitHubConnect.tsx
index ee4401dc..be597196 100644
--- a/frontend/src/components/GitHubConnect.tsx
+++ b/frontend/src/components/GitHubConnect.tsx
@@ -92,6 +92,7 @@ const GitHubConnectLayer: React.FC<{ req: GitHubConnectRequest; onClose: () => v
onClose();
// Back to the button it opened from, when it's still on screen.
const a = req.anchor;
+ // Kept on a timer: the anchor is already on screen and this layer unmounts in the same update, so it can't wait for its own render.
if (a?.isConnected) window.setTimeout(() => a.focus({ preventScroll: true }), 0);
};
useEscapeLayer(ref, true, close, { modal: true, fallback: () => (req.anchor?.isConnected ? req.anchor : null) });
diff --git a/frontend/src/components/JiraSetup.tsx b/frontend/src/components/JiraSetup.tsx
index 68c44b87..5f3a041d 100644
--- a/frontend/src/components/JiraSetup.tsx
+++ b/frontend/src/components/JiraSetup.tsx
@@ -38,6 +38,7 @@ import {
step1Error,
zeroMatchHelp,
} from '../dev/jiraSetup';
+import { useFocusAfterRender } from '../focusAfterRender';
export const JIRA_SETUP_EVENT = 'kwnt:jira-setup';
const WIDTH = 448;
@@ -99,6 +100,7 @@ const JiraSetupLayer: React.FC<{
const close = () => {
onClose();
const a = req.anchor;
+ // Kept on a timer: the anchor is already on screen and this layer unmounts in the same update, so it can't wait for its own render.
if (a?.isConnected) window.setTimeout(() => a.focus({ preventScroll: true }), 0);
};
useEscapeLayer(ref, true, close, {
@@ -384,6 +386,7 @@ export const JiraSetupForm: React.FC<{
const [saveErr, setSaveErr] = useState<string | null>(null);
const addrRef = useRef<HTMLInputElement>(null);
const tokRef = useRef<HTMLInputElement>(null);
+ const focusAfterRender = useFocusAfterRender();
// The password store decides whether the "Before you save the token" card comes first (as GitHub's form).
useEffect(() => {
@@ -416,6 +419,7 @@ export const JiraSetupForm: React.FC<{
[],
);
useEffect(() => {
+ // Kept on a timer: the field is already rendered (this runs after mount); the timer lets the sheet's own open focus go first.
if (stage === 1) window.setTimeout(() => addrRef.current?.focus({ preventScroll: true }), 0);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
@@ -722,7 +726,7 @@ export const JiraSetupForm: React.FC<{
onReady={(_note, accept) => {
if (accept) setAcceptRisk(true);
setGate('open');
- window.setTimeout(() => tokRef.current?.focus(), 0);
+ focusAfterRender(() => tokRef.current);
}}
/>
</div>
diff --git a/frontend/src/components/LooseEndsView.tsx b/frontend/src/components/LooseEndsView.tsx
index af797ca7..6b98f348 100644
--- a/frontend/src/components/LooseEndsView.tsx
+++ b/frontend/src/components/LooseEndsView.tsx
@@ -396,6 +396,7 @@ export const SaveFirst: React.FC<{
// Use/Unlock Bitwarden opens its form in place: focus goes to its first field, not back to the page
useEffect(() => {
if (!step) return undefined;
+ // Kept on a timer: this effect runs after the commit that renders the form, so its field is already there.
const h = window.setTimeout(() => box.current?.querySelector<HTMLElement>('input:not([disabled]), select:not([disabled])')?.focus(), 0);
return () => window.clearTimeout(h);
}, [step, !!store.status]);
diff --git a/frontend/src/components/NeedsYouStrip.tsx b/frontend/src/components/NeedsYouStrip.tsx
index d2613bab..06e44634 100644
--- a/frontend/src/components/NeedsYouStrip.tsx
+++ b/frontend/src/components/NeedsYouStrip.tsx
@@ -19,6 +19,7 @@ import {
stripIndex,
type AskAction,
} from '../askHere';
+import { useFocusAfterRender } from '../focusAfterRender';
export interface NeedsYouStripProps {
/** The open asks in this chat, oldest first (`asksHere`). Nothing shows when empty. */
@@ -187,6 +188,7 @@ export const NeedsYouStrip: React.FC<NeedsYouStripProps> = ({ asks, onAction, on
</span>
);
+ const focusAfterRender = useFocusAfterRender();
if (!item) return live;
// A Retry with nowhere to go (a failed hand-off with no board task) isn't offered (Mira's fix 3).
const base = askAction(item);
@@ -221,7 +223,7 @@ export const NeedsYouStrip: React.FC<NeedsYouStripProps> = ({ asks, onAction, on
// Not an error: this ask is resolved on its own card, so the button goes there.
cleared.current = false;
setSwitched(use);
- window.setTimeout(() => actionRef.current?.focus(), 0);
+ focusAfterRender(() => actionRef.current);
}
} catch (e) {
cleared.current = false;
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 3615e50a..7a9141c0 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -19,6 +19,7 @@ import { BotApprovalsSetting } from './ApprovalsSetting';
import { FlightSchoolPanel } from './FlightSchoolPanel';
import { useEscapeLayer } from '../escape';
import { BrowserSites, FieldErrorKey, SITE_LIMITS, changedSites, fieldError, sitesOf, sitesSummary } from '../browserSites';
+import { useFocusAfterRender } from '../focusAfterRender';
export type EditTab = 'profile' | 'memory' | 'skills' | 'routines' | 'usage';
const EDIT_TABS: Array<{ id: EditTab; label: string; Icon: typeof Brain }> = [
@@ -143,6 +144,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
const [sitesBase, setSitesBase] = useState<BrowserSites | null>(null);
const [sites, setSites] = useState<BrowserSites | null>(null);
const [sitesOpen, setSitesOpen] = useState(false);
+ const focusAfterRender = useFocusAfterRender();
// A 400 that names one list ("browser_allowed_sites: …"), shown next to that list.
const [fieldErrors, setFieldErrors] = useState<Partial<Record<FieldErrorKey, string>>>({});
// Follows the prop until the person changes this bot's approvals here.
@@ -301,7 +303,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
setFieldErrors({ [named.field]: named.text });
setError('Nothing was saved. Fix the entry marked above, then save again.');
if (named.field.startsWith('browser_')) setSitesOpen(true);
- setTimeout(() => document.getElementById(fieldInputId(named.field))?.focus(), 0);
+ focusAfterRender(() => document.getElementById(fieldInputId(named.field)));
return;
}
onClose();
diff --git a/frontend/src/components/SpaceControls.tsx b/frontend/src/components/SpaceControls.tsx
index 05dd706f..3d5c8e17 100644
--- a/frontend/src/components/SpaceControls.tsx
+++ b/frontend/src/components/SpaceControls.tsx
@@ -11,6 +11,7 @@ import { DEV_FEATURES, DEV_GUIDE_URL, EXPLAINER, SUB_ACTION_TEXT, type DevModeSt
import { approvalsRow, type SpaceApprovals } from '../approvalMode';
import { DevModeSwitch, useDevMode } from './DevModeSwitch';
import { backGestureEntry } from './BrowserControlOverlay';
+import { useFocusAfterRender } from '../focusAfterRender';
export interface SpaceControlsProps {
space: { id: string; name: string; approvals?: SpaceApprovals };
@@ -58,10 +59,14 @@ export const SpaceControls: React.FC<SpaceControlsProps> = ({ space, phone = fal
return () => window.clearTimeout(t);
}, [space.id, space.approvals]);
- const close = useCallback((refocus: boolean) => {
- setOpen(false);
- if (refocus) setTimeout(() => help.current?.focus(), 0);
- }, []);
+ const focusAfterRender = useFocusAfterRender();
+ const close = useCallback(
+ (refocus: boolean) => {
+ setOpen(false);
+ if (refocus) focusAfterRender(() => help.current);
+ },
+ [focusAfterRender],
+ );
return (
<div role="group" aria-label="Space controls" className={`kw-sc${phone ? ' kw-sc-phone' : ''}`} data-space-controls>
diff --git a/frontend/src/components/TelegramCard.tsx b/frontend/src/components/TelegramCard.tsx
index a9441ae4..0cbadcc3 100644
--- a/frontend/src/components/TelegramCard.tsx
+++ b/frontend/src/components/TelegramCard.tsx
@@ -26,6 +26,7 @@ import {
telegramApi,
tokenErrorText,
} from '../telegram';
+import { useFocusAfterRender } from '../focusAfterRender';
export type TelegramApi = typeof telegramApi;
@@ -250,11 +251,12 @@ export const SetupSheet: React.FC<SetupSheetProps> = ({ status, api, start, onSt
}
};
+ const focusAfterRender = useFocusAfterRender();
const change = () => {
setToken('');
setLink(null);
setStep({ kind: 'token', error: null, checking: false });
- window.setTimeout(() => tokenRef.current?.focus());
+ focusAfterRender(() => tokenRef.current);
};
const copy = async () => {
@@ -707,10 +709,11 @@ export const ConnectedCard: React.FC<ConnectedCardProps> = ({ status, api, onSta
setToast(null);
if (await run('undo', () => api.undoUnpair())) setUnpaired(false);
};
+ const focusAfterRender = useFocusAfterRender();
const setAllow = async (on: boolean) => {
const ok = await run('allow', () => api.patch({ allow_approvals: on }));
setConfirm(null);
- if (ok || !on) window.setTimeout(() => allowRef.current?.focus());
+ if (ok || !on) focusAfterRender(() => allowRef.current);
};
const disconnect = async () => {
if (await run('disconnect', () => api.disconnect())) onGone();
@@ -839,7 +842,7 @@ export const ConnectedCard: React.FC<ConnectedCardProps> = ({ status, api, onSta
The token is deleted from the vault{status.paired ? ` and ${status.paired.name} is unpaired` : ''}. Your bot stays in Telegram; delete it with <code>@BotFather</code> if you don't need it.
</p>
<div className="tg-row">
- <button ref={keepRef} type="button" className={quietBtn} onClick={() => (setConfirm(null), window.setTimeout(() => footRef.current?.querySelector<HTMLButtonElement>('[data-tg-disconnect-open]')?.focus()))}>
+ <button ref={keepRef} type="button" className={quietBtn} onClick={() => (setConfirm(null), focusAfterRender(() => footRef.current?.querySelector<HTMLButtonElement>('[data-tg-disconnect-open]')))}>
Keep it
</button>
<button type="button" className={dangerBtn} onClick={() => void disconnect()} disabled={busy === 'disconnect'}>
@@ -866,7 +869,7 @@ export const ConnectedCard: React.FC<ConnectedCardProps> = ({ status, api, onSta
</div>
)}
- {confirm === 'allow' && <AllowConfirm busy={busy === 'allow'} onKeep={() => (setConfirm(null), window.setTimeout(() => allowRef.current?.focus()))} onAllow={() => void setAllow(true)} />}
+ {confirm === 'allow' && <AllowConfirm busy={busy === 'allow'} onKeep={() => (setConfirm(null), focusAfterRender(() => allowRef.current))} onAllow={() => void setAllow(true)} />}
{toast && (
<Over>
<Toast text={toast.text} action={toast.undo && busy !== 'undo' ? { label: 'Undo', run: () => void undo() } : undefined} />
diff --git a/frontend/src/components/dev/LineNotes.tsx b/frontend/src/components/dev/LineNotes.tsx
index bfc81a4d..e35ded81 100644
--- a/frontend/src/components/dev/LineNotes.tsx
+++ b/frontend/src/components/dev/LineNotes.tsx
@@ -52,6 +52,7 @@ import { LineNotesError, newSendId, type LineNotesApi } from '../../dev/lineNote
import { BarTrigger, type RecipientsLoad, type SendTo } from './RecipientPicker';
import { badRecipientNotes, noDefaultNotes, target, toFor } from '../../dev/recipients';
import type { RecipientBot } from '../../dev/types';
+import { useAfterRender, useFocusAfterRender } from '../../focusAfterRender';
/** The app re-sends the `dev_card` SSE as this window event (DevDesk.tsx DEV_CARD_EVENT). */
const DEV_CARD_EVENT = 'kwant:dev-card';
@@ -237,12 +238,14 @@ export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, sta
setWriting({ path: n.path, start: n.start, end: n.end, code: n.code, text: n.text, editing: n.id, asking: false, busy: false, error: null });
};
+ const afterRender = useAfterRender();
+ // After the render that closes the note, so the line's button is back in the grid.
const focusLine = (path: string, p: LinePoint | null) => {
- window.setTimeout(() => {
+ afterRender(() => {
const grid = document.querySelector<HTMLElement>(`[data-ln-grid="${CSS.escape(path)}"]`);
const btn = p ? grid?.querySelector<HTMLElement>(`[data-ln-point="${p.side}:${p.line}"] button`) : null;
(btn ?? grid?.querySelector<HTMLElement>('button[tabindex="0"]'))?.focus();
- }, 0);
+ });
};
const stopWriting = () => {
@@ -610,6 +613,7 @@ const FileBlock: React.FC<FileBlockProps> = (p) => {
const lines = useMemo(() => flatLines(f), [f]);
const [active, setActive] = useState(0);
const [shown, setShown] = useState(false);
+ const focusAfterRender = useFocusAfterRender();
const wrap = useRef<HTMLDivElement>(null);
const near = useNear(wrap, p.open);
const drag = useRef<number | null>(null);
@@ -649,7 +653,7 @@ const FileBlock: React.FC<FileBlockProps> = (p) => {
const focusAt = (i: number) => {
const n = Math.max(0, Math.min(lines.length - 1, i));
setActive(n);
- window.setTimeout(() => wrap.current?.querySelector<HTMLElement>(`[data-ln-i="${n}"] button`)?.focus(), 0);
+ focusAfterRender(() => wrap.current?.querySelector<HTMLElement>(`[data-ln-i="${n}"] button`));
return n;
};
@@ -1133,6 +1137,7 @@ const AskThrowAway: React.FC<{ setWriting: ComposerProps['setWriting']; onCancel
type="button"
onClick={() => {
setWriting((x) => (x ? { ...x, asking: false } : x));
+ // Kept on a timer: the note's text box is already on screen, and this confirm unmounts in the same update.
window.setTimeout(() => document.querySelector<HTMLTextAreaElement>('[data-ln-text]')?.focus(), 0);
}}
className={`kw-btn-primary ${big ? 'min-h-11' : ''}`}
diff --git a/frontend/src/components/dev/RecipientPicker.tsx b/frontend/src/components/dev/RecipientPicker.tsx
index 165350b2..c75366f2 100644
--- a/frontend/src/components/dev/RecipientPicker.tsx
+++ b/frontend/src/components/dev/RecipientPicker.tsx
@@ -28,6 +28,7 @@ import {
loadShown,
saveShown,
} from '../../dev/recipients';
+import { useFocusAfterRender } from '../../focusAfterRender';
const RING = 'outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400';
@@ -499,12 +500,16 @@ export function useSendTo(
const anchorRef = useRef<HTMLElement | null>(null);
anchorRef.current = anchor;
// Closing gives focus back to the trigger that opened the picker (design §2).
- const close = React.useCallback((refocus: boolean = true) => {
- const a = anchorRef.current;
- setAnchor(null);
- after.current = null;
- if (a && refocus) window.setTimeout(() => a.isConnected && a.focus({ preventScroll: true }), 0);
- }, []);
+ const focusAfterRender = useFocusAfterRender();
+ const close = React.useCallback(
+ (refocus: boolean = true) => {
+ const a = anchorRef.current;
+ setAnchor(null);
+ after.current = null;
+ if (a && refocus) focusAfterRender(() => (a.isConnected ? a : null), { preventScroll: true });
+ },
+ [focusAfterRender],
+ );
if (!fetcher) return { st: null, picker: null, say: '' };
diff --git a/frontend/src/focusAfterRender.ts b/frontend/src/focusAfterRender.ts
new file mode 100644
index 00000000..d37dbc22
--- /dev/null
+++ b/frontend/src/focusAfterRender.ts
@@ -0,0 +1,34 @@
+import { useCallback, useLayoutEffect, useReducer, useRef } from 'react';
+
+/**
+ * Runs work after the next render of the calling component is on screen, never on a timer.
+ *
+ * A `setTimeout(() => ref.current?.focus(), 0)` races React: when its scheduler yields (a slow machine, a busy
+ * CI runner), the timer runs before the render that mounts its target, finds nothing and focus drops to <body>
+ * for good. Here the work waits in a ref and a layout effect runs it right after the commit. Scheduling also
+ * asks for a render, so the work never waits for an unrelated later one. Call it in the component that stays
+ * 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);
+ useLayoutEffect(() => {
+ if (!queue.current.length) return;
+ const run = queue.current;
+ queue.current = [];
+ for (const work of run) work();
+ });
+ return useCallback((work: () => void) => {
+ queue.current.push(work);
+ render();
+ }, []);
+}
+
+/**
+ * Focuses `target()` after the next render, so a target that the same update mounts or swaps in is there to take
+ * focus. A target that is still missing then is skipped (and cleared), never retried later.
+ */
+export function useFocusAfterRender(): (target: () => HTMLElement | null | undefined, opts?: FocusOptions) => void {
+ const after = useAfterRender();
+ return useCallback((target: () => HTMLElement | null | undefined, opts?: FocusOptions) => after(() => target()?.focus(opts)), [after]);
+}
diff --git a/frontend/tests/composioTile.test.mjs b/frontend/tests/composioTile.test.mjs
index a95b68dd..61e375a1 100644
--- a/frontend/tests/composioTile.test.mjs
+++ b/frontend/tests/composioTile.test.mjs
@@ -90,6 +90,38 @@ test('names and lists stay short', () => {
assert.equal(m.removeQuestion([], []), 'Remove Composio? Your sign-ins stay on Composio, so you can add it back later.');
});
+test('a request to open it focuses the new key field even when React yields before rendering it', async () => {
+ // React's scheduler gives up the thread after 5 ms of work. Advancing performance.now 10 ms per call makes it
+ // yield every time, as on a starved CI runner: a focus on a setTimeout(0) then runs before the render that
+ // mounts its target, and focus drops to <body> for good (focus-after-render-everywhere, after #897).
+ const perf = window.performance === globalThis.performance ? [globalThis.performance] : [globalThis.performance, window.performance];
+ const realNows = perf.map((p) => p.now);
+ let skew = 0;
+ const slow = (on) => perf.forEach((p, i) => (p.now = on ? () => (skew += 10) + realNows[i].call(p) : realNows[i]));
+ // 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.getAttribute('role') ? `[role=${a.getAttribute('role')}]` : ''} "${a.textContent.trim().slice(0, 30)}"` : 'nothing';
+ };
+ const waitFor = async (cond, ms = 2000) => {
+ const end = Date.now() + ms;
+ while (!cond() && Date.now() < end) await new Promise((r) => setTimeout(r, 10));
+ };
+ try {
+ const { api } = stubApi();
+ // The request opens the field from an effect, outside any click, so React renders it in a scheduler task.
+ slow(true);
+ const host = await mount({ entry: entry(), api, openRequest: 1 });
+ const field = () => host.querySelector('input[type="password"]');
+ await waitFor(() => !!field() && document.activeElement === field());
+ slow(false);
+ assert.ok(field(), 'the key field opens');
+ assert.ok(document.activeElement === field(), `focus is in the key field, not ${focused()}`);
+ } finally {
+ slow(false);
+ }
+});
+
test('not added: one key field adds it, and the link form hides under advanced', async () => {
const { api, calls } = stubApi();
let changed = 0;
diff --git a/frontend/tests/focusAfterRender.test.mjs b/frontend/tests/focusAfterRender.test.mjs
new file mode 100644
index 00000000..2f367887
--- /dev/null
+++ b/frontend/tests/focusAfterRender.test.mjs
@@ -0,0 +1,182 @@
+// Focus after render (focus-after-render-everywhere, after #897): the shared hook focuses after the commit that
+// 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.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { readFileSync, readdirSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+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';
+`);
+const h = m.createElement;
+
+// ---------------------------------------------------------------------------------------------------
+// The guard
+
+const SRC = fileURLToPath(new URL('../src/', import.meta.url));
+
+/**
+ * The timer focus calls that stay, each with why. A new one fails the guard; one that is gone fails it too, so
+ * this list never goes stale. `has` is a piece of the timer's callback, unique within its file.
+ */
+const KEPT = [
+ { file: 'components/GitHubConnect.tsx', has: 'a.focus({ preventScroll: true })', why: 'the anchor is already on screen and this layer unmounts in the same update' },
+ { file: 'components/JiraSetup.tsx', has: 'a.focus({ preventScroll: true })', why: 'the anchor is already on screen and this layer unmounts in the same update' },
+ { file: 'components/JiraSetup.tsx', has: 'addrRef.current?.focus', why: 'runs after mount (field already rendered); lets the sheet’s own open focus go first' },
+ { file: 'components/GetStarted.tsx', has: "'[data-composer-form] textarea'", why: 'the composer is already on screen, outside this card, and Keep can remove the card' },
+ { file: 'components/DictationMic.tsx', has: "popRef.current?.querySelector<HTMLButtonElement>('button')", why: 'an effect after the commit that renders the popover' },
+ { file: 'components/LooseEndsView.tsx', has: "box.current?.querySelector<HTMLElement>('input:not([disabled])", why: 'an effect after the commit that renders the form' },
+ { file: 'components/dev/LineNotes.tsx', has: "'[data-ln-text]'", why: 'the text box is already on screen and the confirm that calls it unmounts' },
+ { file: 'components/dev/ProdFloorCard.tsx', has: 'cardRef.current?.contains(a)', why: 'takeBackup: the main button is always rendered (#897 keeps it)' },
+];
+
+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) {
+ 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;
+ for (let depth = 0; i < s.length; i++) {
+ const c = s[i];
+ if ('([{'.includes(c)) depth++;
+ else if (')]}'.includes(c)) {
+ if (depth === 0) break;
+ depth--;
+ } 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() });
+ }
+ return out;
+}
+
+test('guard: the scanner finds a timer focus on one line or many, and skips comments and other timers', () => {
+ const found = timerFocusCalls(
+ 'x.tsx',
+ [
+ 'window.setTimeout(() => a.current?.focus(), 0);',
+ 'setTimeout(() => {',
+ ' const b = ref.current;',
+ ' b?.focus({ preventScroll: true });',
+ '}, 50);',
+ 'setTimeout(() => setOpen(false), 0); el.focus();',
+ '// setTimeout(() => c.focus(), 0);',
+ '/* window.setTimeout(() => d.focus()) */',
+ 'const t = setTimeout(done, 10);',
+ ].join('\n'),
+ );
+ assert.deepEqual(
+ found.map((f) => f.line),
+ [1, 2],
+ );
+});
+
+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);
+ }
+ 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');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// The hook
+
+const mounted = new Set();
+afterEach(() => {
+ for (const u of mounted) u();
+ document.body.replaceChildren();
+});
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mount = async (el) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(el);
+ await settle();
+ const u = () => {
+ if (!mounted.delete(u)) return;
+ root.unmount();
+ host.remove();
+ };
+ mounted.add(u);
+ return host;
+};
+
+/** A button that swaps in a field after an await (as after a save), and focuses it with the hook. */
+const Swap = ({ api, onAfter }) => {
+ const [open, setOpen] = m.useState(false);
+ const [n, setN] = m.useState(0);
+ const field = m.useRef(null);
+ const focusAfterRender = m.useFocusAfterRender();
+ const after = m.useAfterRender();
+ const go = async () => {
+ await api.save();
+ setOpen(true);
+ focusAfterRender(() => field.current);
+ after(() => onAfter?.(field.current?.value));
+ };
+ const missing = () => focusAfterRender(() => null);
+ return h(
+ 'div',
+ null,
+ open ? h('input', { ref: field, defaultValue: 'ready', 'data-field': '' }) : h('button', { type: 'button', onClick: () => void go(), 'data-go': '' }, 'Go'),
+ h('button', { type: 'button', onClick: missing, 'data-missing': '' }, 'Missing'),
+ h('button', { type: 'button', onClick: () => setN(n + 1), 'data-bump': '' }, `Bump ${n}`),
+ );
+};
+const click = async (el) => {
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+
+test('hook: focus lands on the field that the same update swaps in, and later work sees it rendered', async () => {
+ const seen = [];
+ const host = await mount(h(Swap, { api: { save: async () => undefined }, onAfter: (v) => seen.push(v) }));
+ await click(host.querySelector('[data-go]'));
+ assert.ok(document.activeElement === host.querySelector('[data-field]'), 'focus is in the new field');
+ assert.deepEqual(seen, ['ready'], 'the work ran once, after the field was rendered');
+ await click(host.querySelector('[data-bump]'));
+ assert.deepEqual(seen, ['ready'], 'and never again on a later render');
+});
+
+test('hook: a target that is missing after the render is skipped and cleared, never focused on a later render', async () => {
+ const host = await mount(h(Swap, { api: { save: async () => undefined } }));
+ const bump = host.querySelector('[data-bump]');
+ bump.focus();
+ await click(host.querySelector('[data-missing]'));
+ bump.focus();
+ await click(bump);
+ assert.ok(document.activeElement === bump, 'focus stays where the person put it');
+});
diff --git a/frontend/tests/telegram.test.mjs b/frontend/tests/telegram.test.mjs
index f9ed82d6..6aaa1d88 100644
--- a/frontend/tests/telegram.test.mjs
+++ b/frontend/tests/telegram.test.mjs
@@ -343,6 +343,43 @@ test('Allow approvals: a confirm with "Keep it off" focused; Escape keeps it off
assert.ok(!calls.some((c) => c[0] === 'patch'), 'nothing changed');
});
+test('Allow approvals: after the save, focus goes back to the Allow switch even when React yields before rendering it', async () => {
+ // React's scheduler gives up the thread after 5 ms of work. Advancing performance.now 10 ms per call makes it
+ // yield every time, as on a starved CI runner: a focus on a setTimeout(0) then runs before the render that
+ // mounts its target, and focus drops to <body> for good (focus-after-render-everywhere, after #897).
+ const perf = window.performance === globalThis.performance ? [globalThis.performance] : [globalThis.performance, window.performance];
+ const realNows = perf.map((p) => p.now);
+ let skew = 0;
+ const slow = (on) => perf.forEach((p, i) => (p.now = on ? () => (skew += 10) + realNows[i].call(p) : realNows[i]));
+ // 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.getAttribute('role') ? `[role=${a.getAttribute('role')}]` : ''} "${a.textContent.trim().slice(0, 30)}"` : 'nothing';
+ };
+ const waitFor = async (cond, ms = 2000) => {
+ const end = Date.now() + ms;
+ while (!cond() && Date.now() < end) await new Promise((r) => setTimeout(r, 10));
+ };
+ try {
+ const { api } = mockApi();
+ await mount(h(m.TelegramConnection, { api, initial: paired() }));
+ await click($('[data-tg-allow] [role="switch"]'));
+ assert.equal(document.activeElement.textContent.trim(), 'Keep it off');
+ // The switch is disabled while the save runs; the focus comes after the await, outside the click, so React
+ // renders it in a scheduler task that can yield.
+ slow(true);
+ byText('Allow from Telegram').dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ const target = () => $('[data-tg-allow] [role="switch"]');
+ await waitFor(() => $('[role="alertdialog"]') === null && document.activeElement === target());
+ slow(false);
+ assert.equal($('[data-tg-allow]').dataset.tgAllow, 'on', 'saved');
+ assert.equal($('[role="alertdialog"]'), null, 'the confirm closed');
+ assert.ok(document.activeElement === target(), `focus is on the Allow switch, not ${focused()}`);
+ } finally {
+ slow(false);
+ }
+});
+
test('Allow approvals on: amber, "On since", and the never-from-Telegram line; off needs no confirm', async () => {
const { api, calls } = mockApi({ patch: async (b) => paired({ allow_approvals: !!b.allow_approvals, allow_since: '2026-11-07T10:12:00Z' }) });
await mount(h(m.TelegramConnection, { api, initial: paired() }));