Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Preserve Editor focus during empty Agents reveal (#6743)
Nick Gomez2cb37a2d230d
diff --git a/.changeset/preserve-editor-focus-on-agent-reveal.md b/.changeset/preserve-editor-focus-on-agent-reveal.mdnew file mode 100644index 000000000..0424d4667--- /dev/null+++ b/.changeset/preserve-editor-focus-on-agent-reveal.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge-app": patch+---++Selecting the Editor while an empty Agents panel is opening no longer moves focus back to Agents.diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex 1a3f127eb..1057dce40 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -714,6 +714,7 @@ export function EditorPane() {} | null>(null);const [threadLaunch, setThreadLaunch] = useState<ThreadLaunchIntent | null>(null);const threadLaunchNonceRef = useRef(0);+ const [agentsFocusRevealNonce, setAgentsFocusRevealNonce] = useState(0);const [placements, setPlacements] = useState<SessionPlacements>({terminal: { container: null, isShowing: false },agents: { container: null, isShowing: false },@@ -797,8 +798,10 @@ export function EditorPane() {useLayoutEffect(publishPaneVisibility);useLayoutEffect(() => {- return paneVisibilityStore.subscribeRequests(({ pane, open }) => {+ return paneVisibilityStore.subscribeRequests(({ pane, open, reason }) => {if (noteWindow) return;+ if (pane === 'agents' && open && reason === 'user')+ setAgentsFocusRevealNonce((nonce) => nonce + 1);if (exclusive) {if (pane === 'terminal' && !terminalAvailable) return;applyPaneRequest(pane, open);@@ -885,9 +888,11 @@ export function EditorPane() {else selectPane('editor');setEditorShown(!editorShown);});- const toggleAgentsEvent = useEffectEvent(() =>- handleAgentsVisibleChange(!effectiveAgentsVisible),- );+ const toggleAgentsEvent = useEffectEvent(() => {+ const next = !effectiveAgentsVisible;+ if (next) setAgentsFocusRevealNonce((nonce) => nonce + 1);+ handleAgentsVisibleChange(next);+ });const toggleTerminalEvent = useEffectEvent(() =>handleTerminalVisibleChange(!effectiveTerminalVisible),);@@ -1273,6 +1278,7 @@ export function EditorPane() {onPreferredSessionHostReady={onPreferredSessionHostReady}agentsVisibilityRestoreSettled={desktopBridge == null || dockRestoreSettled}threadLaunch={threadLaunch}+ focusRevealRequestNonce={agentsFocusRevealNonce}installedClis={installedClis}container={placements.agents.container}isShowing={placements.agents.isShowing}diff --git a/packages/app/src/components/HeaderPaneButtons.dom.test.tsx b/packages/app/src/components/HeaderPaneButtons.dom.test.tsxindex 1e461a281..73a3f637d 100644--- a/packages/app/src/components/HeaderPaneButtons.dom.test.tsx+++ b/packages/app/src/components/HeaderPaneButtons.dom.test.tsx@@ -170,8 +170,8 @@ describe('HeaderPaneButtons', () => {await user.click(terminal);expect(requests).toEqual([- { pane: 'agents', open: true },- { pane: 'terminal', open: true },+ { pane: 'agents', open: true, reason: 'user' },+ { pane: 'terminal', open: true, reason: 'user' },]);});@@ -212,8 +212,8 @@ describe('HeaderPaneButtons', () => {expect(document.activeElement).toBe(terminal);expect(requests).toEqual([- { pane: 'agents', open: true },- { pane: 'terminal', open: false },+ { pane: 'agents', open: true, reason: 'user' },+ { pane: 'terminal', open: false, reason: 'user' },]);});@@ -267,8 +267,8 @@ describe('HeaderPaneButtons', () => {await user.keyboard(' ');expect(requests).toEqual([- { pane: 'agents', open: false },- { pane: 'terminal', open: true },+ { pane: 'agents', open: false, reason: 'user' },+ { pane: 'terminal', open: true, reason: 'user' },]);expect(document.activeElement).toBe(terminal);});@@ -499,8 +499,8 @@ describe('the Editor header button', () => {await user.keyboard('{Enter}');expect(requests).toEqual([- { pane: 'editor', open: false },- { pane: 'editor', open: true },+ { pane: 'editor', open: false, reason: 'user' },+ { pane: 'editor', open: true, reason: 'user' },]);expect(document.activeElement).toBe(editor);});diff --git a/packages/app/src/components/HeaderPaneButtons.tsx b/packages/app/src/components/HeaderPaneButtons.tsxindex 9bc5da611..fef9d67aa 100644--- a/packages/app/src/components/HeaderPaneButtons.tsx+++ b/packages/app/src/components/HeaderPaneButtons.tsx@@ -88,7 +88,7 @@ function HeaderPaneButton({ pane, pressed }: HeaderPaneButtonState) {onClick={(event) => {const button = event.currentTarget;if (pressed && paneVisibilityStore.isExclusive()) return;- paneVisibilityStore.request(pane, !pressed);+ paneVisibilityStore.request(pane, !pressed, 'user');if (pressed) queueMicrotask(() => button.focus());}}className={cn('text-muted-foreground', pressed && PRESSED_CLASSES)}diff --git a/packages/app/src/components/SessionsHost.agents.dom.test.tsx b/packages/app/src/components/SessionsHost.agents.dom.test.tsxindex 87e5c2708..9e90afaf6 100644--- a/packages/app/src/components/SessionsHost.agents.dom.test.tsx+++ b/packages/app/src/components/SessionsHost.agents.dom.test.tsx@@ -278,6 +278,17 @@ function agentsDockWrites(setDockState: ReturnType<typeof vi.fn>) {);}+function makeUsableEditorHeader(): HTMLButtonElement {+ const button = document.body.appendChild(document.createElement('button'));+ button.type = 'button';+ button.setAttribute('data-header-pane-button', 'editor');+ Object.defineProperty(button, 'getClientRects', {+ configurable: true,+ value: () => [{ width: 1, height: 1 }],+ });+ return button;+}+function makeTerminalBridge(): OkDesktopBridge {return {terminal: {@@ -317,6 +328,7 @@ function Harness({onRequestEditorFocus,onPreferredSessionHostReady,installedClis = {},+ focusRevealRequestNonce = 0,}: {bridge?: OkDesktopBridge | null;initialVisible?: boolean;@@ -331,6 +343,7 @@ function Harness({onRequestEditorFocus?: () => void;onPreferredSessionHostReady?: () => void;installedClis?: { claude?: boolean };+ focusRevealRequestNonce?: number;}) {const [container, setContainer] = useState<HTMLDivElement | null>(null);const [visible, setVisible] = useState(initialVisible);@@ -367,6 +380,7 @@ function Harness({visible={visible}agentsVisibilityRestoreSettled={restoreSettled}threadLaunch={threadLaunch}+ focusRevealRequestNonce={focusRevealRequestNonce}onVisibleChange={(v) => {onVisibleChange?.(v);setVisible(v);@@ -1885,6 +1899,71 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {}});+ test('an empty reveal does not steal focus from the Editor pane header', async () => {+ const control = makeControl();+ render(<Harness initialVisible initialShowing={false} control={control} />);+ await screen.findByTestId('sessions-dock-empty');++ const outside = makeUsableEditorHeader();+ try {+ outside.focus();+ expect(document.activeElement).toBe(outside);++ act(() => control.current?.setShowing(true));+ await act(async () => {});++ expect(document.activeElement).toBe(outside);+ } finally {+ outside.remove();+ }+ });++ test('a user reveal requested before the host mounts still focuses the empty Agents surface', async () => {+ const control = makeControl();+ setInitialRosterIds(new Set());+ render(+ <Harness+ initialVisible+ initialShowing={false}+ focusRevealRequestNonce={1}+ control={control}+ />,+ );+ const action = await screen.findByRole('button', { name: 'Configure agents' });+ const outside = makeUsableEditorHeader();+ try {+ outside.focus();+ act(() => control.current?.setShowing(true));+ await waitFor(() => expect(document.activeElement).toBe(action));+ } finally {+ outside.remove();+ }+ });++ test('an empty reveal keeps the Editor pane header focused when a session arrives later', async () => {+ vi.useFakeTimers();+ const control = makeControl();+ render(<Harness initialVisible={false} control={control} />);+ const outside = makeUsableEditorHeader();+ try {+ outside.focus();+ act(() => control.current?.setVisible(true));+ expect(screen.getByTestId('sessions-dock-empty')).toBeDefined();+ expect(document.activeElement).toBe(outside);++ act(() => setOpenThreads([makeThread({ threadId: 'arrived', title: 'Arrived' })]));++ expect(screen.getByRole('tab', { name: /Arrived/ })).toBeDefined();+ await act(async () => {});+ act(() => vi.advanceTimersByTime(5_000));+ await act(async () => {});+ expect(document.activeElement).toBe(outside);+ } finally {+ outside.remove();+ vi.useRealTimers();+ }+ });+test('a content-less empty reveal focuses the named new-chat fallback despite earlier controls', async () => {const control = makeControl();mockRegisteredAgent = FIRST_AGENT;diff --git a/packages/app/src/components/SessionsHost.tsx b/packages/app/src/components/SessionsHost.tsxindex f55858cd9..5b8ea22ab 100644--- a/packages/app/src/components/SessionsHost.tsx+++ b/packages/app/src/components/SessionsHost.tsx@@ -426,6 +426,7 @@ interface SessionsHostSharedProps {readonly launch?: TerminalLaunchIntent | null;readonly commandLaunch?: { readonly id: TerminalCommandId; readonly nonce: number } | null;readonly threadLaunch?: ThreadLaunchIntent | null;+ readonly focusRevealRequestNonce?: number;readonly installedClis?: Partial<Record<TerminalCli, boolean>>;readonly container: HTMLElement | null;readonly isShowing: boolean;@@ -478,6 +479,7 @@ export function SessionsHost({launch = null,commandLaunch = null,threadLaunch = null,+ focusRevealRequestNonce = 0,installedClis,container,isShowing,@@ -605,6 +607,13 @@ export function SessionsHost({const persistSuppressedRef = useRef<() => boolean>(() => false);const lastHandledCommandNonceRef = useRef<number | null>(null);const prevVisibleRef = useRef(isWindow ? false : visible);+ const revealFocusRequestedRef = useRef(false);+ const revealFocusRequestNonceRef = useRef<number | null>(null);+ useLayoutEffect(() => {+ if (revealFocusRequestNonceRef.current === focusRevealRequestNonce) return;+ revealFocusRequestNonceRef.current = focusRevealRequestNonce;+ if (focusRevealRequestNonce > 0) revealFocusRequestedRef.current = true;+ }, [focusRevealRequestNonce]);const consumedRestoreRevealNonceRef = useRef(terminalRestoreRevealNonce);const ptyIdBySessionRef = useRef(new Map<string, string>());const stripLaunchNonceRef = useRef(0);@@ -1867,6 +1876,18 @@ export function SessionsHost({useEffect(() => {if (!isShowing || attachedHostEl == null) return;const focusOrigin = document.activeElement;+ const focusRevealRequested = revealFocusRequestedRef.current;+ revealFocusRequestedRef.current = false;+ const focusOriginPane =+ focusOrigin instanceof HTMLElement+ ? focusOrigin.getAttribute('data-header-pane-button')+ : null;+ const focusOriginIsOtherPaneButton =+ !focusRevealRequested &&+ hostThreads &&+ focusRemainsUsable(focusOrigin) &&+ focusOriginPane !== null &&+ focusOriginPane !== 'agents';if (revealFocusHoldRef.current && focusRemainsUsable(focusOrigin)) {revealFocusRef.current = null;return;@@ -1884,12 +1905,12 @@ export function SessionsHost({initialFallbackLanding = fallback != null && document.activeElement === fallback;}const emptySurfaceLanding =- hostThreads && initialActive == null+ hostThreads && initialActive == null && !focusOriginIsOtherPaneButton? (focusAvailableButton(emptyAgentActionButtonRef.current) ??focusAvailableButton(emptyAgentStateFallbackButton(attachedHostEl))): null;revealFocusRef.current = { pendingThreadId: revealFocusRef.current?.pendingThreadId ?? null };- let landed = initialFallbackLanding;+ let landed = focusOriginIsOtherPaneButton || initialFallbackLanding;let attemptedFallback: HTMLElement | null = null;let retryFrame: number | null = null;let retired = false;@@ -1902,6 +1923,16 @@ export function SessionsHost({const targetId = revealFocusRef.current?.pendingThreadId ?? activeSessionIdRef.current;const active = sessionsRef.current.find((s) => s.id === targetId);if (active == null) return;+ if (+ focusOriginIsOtherPaneButton &&+ document.activeElement === focusOrigin &&+ focusRemainsUsable(focusOrigin)+ ) {+ const revealFocus = revealFocusRef.current;+ if (revealFocus != null) revealFocus.pendingThreadId = active.id;+ landed = true;+ return;+ }const focused = document.activeElement;const fallback = fallbackSessionFocusElement(active);if (diff --git a/packages/app/src/lib/pane-visibility-store.ts b/packages/app/src/lib/pane-visibility-store.tsindex e70b1a0e4..7e028ea94 100644--- a/packages/app/src/lib/pane-visibility-store.ts+++ b/packages/app/src/lib/pane-visibility-store.ts@@ -16,6 +16,7 @@ export type PaneVisibilitySnapshot = {export type PaneVisibilityRequest = {readonly pane: PaneId;readonly open: boolean;+ readonly reason?: 'user';};export interface PaneVisibilityStore {@@ -23,7 +24,7 @@ export interface PaneVisibilityStore {isExclusive(): boolean;subscribe(listener: () => void): () => void;publish(next: PaneVisibilitySnapshot, exclusive?: boolean): void;- request(pane: PaneId, open: boolean): void;+ request(pane: PaneId, open: boolean, reason?: 'user'): void;subscribeRequests(handler: (request: PaneVisibilityRequest) => void): () => void;}@@ -74,8 +75,12 @@ function createPaneVisibilityStore(): PaneVisibilityStore & { reset(): void } {exclusive = nextExclusive;for (const l of listeners) l();},- request(pane, open): void {- const request: PaneVisibilityRequest = { pane, open };+ request(pane, open, reason): void {+ const request: PaneVisibilityRequest = {+ pane,+ open,+ ...(reason === 'user' ? { reason } : {}),+ };if (requestHandlers.size === 0) {waitingRequests.set(pane, request);return;