Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(focus): focus command jumps and creation destinations (#8586)
Eric Hayes0c84048eaa72
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 1015c7750b..fe323fef0b 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -450,7 +450,7 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to- Desktop tabs (`components/app/tab-layout`, macOS + `enable-desktop-tabs`) hold one split layout per tab over the router's `layoutSnapshot`/`restoreLayout`; only the active tab is live, and the strip renders in the title bar's center slot. Cmd+click becomes a background tab through `openInNewTabMiddleware`, so tab operations must disarm the intent tracker before navigating. Tabs are not draggable. See the tabs section of `docs/agent-guide/navigation.md` at the repository root.- Show only the Recent conversation feed in mobile Channels, without view tabs or a persisted mobile tab selection; render its rows with Home's touch row (`ChannelCardLayout` and `InboxDivider`) and pin at most six channel favorites above it.- Mount the mobile search input before focusing it inside the dock tap; keep navigation in that handler so focus does not trigger a second navigation or lose iOS keyboard activation.-- Preserve focused chrome editors during deferred split insertion/removal autofocus; explicit return-focus commands may still focus the pane.+- Preserve focused chrome editors during deferred split insertion/removal/content-change autofocus; explicit return-focus commands may still focus the pane. On desktop, content changes claim focus only for Cmd+K navigation or create-menu arrivals, and only if the destination has not already focused a child. Back/forward and ordinary clicks do not autofocus content.- Reconcile global focus when focused DOM subtrees are removed; iOS can omit blur events, otherwise floating creation actions stay hidden after search or editor teardown.- Mount the floating mobile AI composer only on the Agents view; other views keep their New action or their own reply/comment composer.- Keep desktop New actions on `ViewCreateButton`: full width below the innerdiff --git a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsxindex 651c413de6..87da9981e6 100644--- a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx+++ b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx@@ -116,6 +116,7 @@ function PopoverSplitModal(props: {? props.popover.mount.updateMeta: undefined,referredFrom: () => null,+ lastNavigationSource: () => null,lastNavigationCause: () => 'fresh',registerEntryStateCaptor: () => () => {},captureEntryState: () => {},diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.tsindex ff4d5bcbba..cf49308ce3 100644--- a/apps/web/src/components/app/split-layout/layoutManager.ts+++ b/apps/web/src/components/app/split-layout/layoutManager.ts@@ -193,6 +193,8 @@ export type SplitState = {content: SplitContent; // mirror of the pane's current router entrymount: SplitMount; // contains pinned elementreferredFrom: ReferredFrom;+ /** Source of this arrival, cleared when the next navigation omits one. */+ lastNavigationSource: ReferredFrom;lastNavigationCause: NavigationCause;};@@ -267,6 +269,7 @@ export type SplitEventPayload = {newContent: SplitContent;previousContent: SplitContent;cause: NavigationCause;+ referredFrom?: ReferredFrom;};[SplitEvent.ReturnFocus]: void;};@@ -500,6 +503,7 @@ export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {/** Update component metadata (only available for component splits) */updateMeta: ((data: Omit<TMeta, 'kind'>) => void) | undefined;referredFrom: () => ReferredFrom;+ lastNavigationSource: () => ReferredFrom;/*** Cause of the most recent navigation event for this split. `'fresh'` on* initial mount, then updated by back/forward/replace/push.@@ -786,6 +790,7 @@ export function createSplitLayout(content,mount: createPinnedMount(orchestrator, content),referredFrom: referredFrom ?? null,+ lastNavigationSource: referredFrom ?? null,lastNavigationCause: 'fresh',};}@@ -815,6 +820,7 @@ export function createSplitLayout(newContent: content,previousContent: split.content,cause,+ referredFrom,};dispatchEvent(SplitEvent.ContentChange, payload);@@ -837,6 +843,7 @@ export function createSplitLayout(...s[i],content: content,referredFrom,+ lastNavigationSource: referredFrom,lastNavigationCause: cause,};return s.with(i, target);@@ -848,6 +855,7 @@ export function createSplitLayout(const target = {...s[i],content: content,+ lastNavigationSource: null,lastNavigationCause: cause,};return s.with(i, target);@@ -863,6 +871,7 @@ export function createSplitLayout(...s[i],content,mount: newMount,+ lastNavigationSource: referredFrom ?? null,lastNavigationCause: cause,...(referredFrom !== undefined && { referredFrom }),};@@ -1291,6 +1300,7 @@ export function createSplitLayout(return mount?.kind === 'component' ? mount.updateMeta : undefined;},referredFrom: () => s()?.referredFrom ?? null,+ lastNavigationSource: () => s()?.lastNavigationSource ?? null,lastNavigationCause: () => s()?.lastNavigationCause ?? 'fresh',registerEntryStateCaptor: (key: string, getter: () => unknown) => {let perSplit = entryStateCaptors.get(currentSplit.id);diff --git a/apps/web/src/components/app/split-layout/layoutUtils.ts b/apps/web/src/components/app/split-layout/layoutUtils.tsindex d0177c2d27..8ecd662fee 100644--- a/apps/web/src/components/app/split-layout/layoutUtils.ts+++ b/apps/web/src/components/app/split-layout/layoutUtils.ts@@ -20,6 +20,7 @@ import type {SplitHandle,SplitManager,} from './layoutManager';+import { shouldAutofocusNavigation } from './should-autofocus-navigation';const _isInSplit = createCallback(() => {return !!useContext(SplitPanelContext);@@ -115,7 +116,14 @@ export function shouldShowSplitCloseButton(manager: SplitManager) {/** Inline previews stay passive until the user focuses them. */export function useCanAutofocusSplitContent() {- return !useSplitPanel()?.isInlinePreview;+ const panel = useSplitPanel();+ if (panel?.isInlinePreview) return false;+ return panel+ ? shouldAutofocusNavigation(+ panel.handle.lastNavigationSource(),+ panel.handle.lastNavigationCause()+ )+ : true;}/**diff --git a/apps/web/src/components/app/split-layout/should-autofocus-navigation.ts b/apps/web/src/components/app/split-layout/should-autofocus-navigation.tsnew file mode 100644index 0000000000..8f8af0c7c8--- /dev/null+++ b/apps/web/src/components/app/split-layout/should-autofocus-navigation.ts@@ -0,0 +1,12 @@+import type { NavigationCause, ReferredFrom } from './layoutManager';++/** Content claims keyboard focus only after a command jump or creation. */+export function shouldAutofocusNavigation(+ referredFrom: ReferredFrom | undefined,+ cause: NavigationCause+) {+ return (+ (cause === 'fresh' || cause === 'replace') &&+ (referredFrom === 'kommand-menu' || referredFrom === 'launcher')+ );+}diff --git a/apps/web/src/components/app/split-layout/splitFocusTracker.ts b/apps/web/src/components/app/split-layout/splitFocusTracker.tsindex d99a6a08d0..d2b5fd56ed 100644--- a/apps/web/src/components/app/split-layout/splitFocusTracker.ts+++ b/apps/web/src/components/app/split-layout/splitFocusTracker.ts@@ -1,5 +1,6 @@import { activeElement } from '@app/signal/focus';import { splitContainerSelector } from '@core/dom-selectors';+import { isTouchDevice } from '@core/mobile/isTouchDevice';import { isEditableInput } from '@core/util/isEditableInput';import { type Accessor, createEffect, on, onCleanup } from 'solid-js';import {@@ -9,6 +10,7 @@ import {type SplitManager,type SplitState,} from './layoutManager';+import { shouldAutofocusNavigation } from './should-autofocus-navigation';function getParentSplitId(element: Element | null) {if (!element || !element.isConnected) return null;@@ -73,7 +75,7 @@ export function createSplitFocusTracker(props: {// look for a child to return focus to.const child = lastFocusedChildBySplitId.get(id);- if (child && child.isConnected) {+ if (child && child.isConnected && splitPanelRef.contains(child)) {child.focus();return;}@@ -140,6 +142,18 @@ export function createSplitFocusTracker(props: {focusSplitById(event.splitId);break;}+ case SplitEvent.ContentChange: {+ // The pane stays mounted when its content changes, so its one-time+ // autofocus does not run again. Focus the new content's shell if no+ // child has claimed focus by the time navigation finishes.+ if (isTouchDevice()) break;+ if (!shouldAutofocusNavigation(event.referredFrom, event.cause)) break;+ if (event.splitId !== activeSplitId()) break;+ const panel = props.panelRefs.get(event.splitId);+ if (!panel || panel.contains(document.activeElement)) break;+ panel.focus({ preventScroll: true });+ break;+ }case SplitEvent.Remove: {const splitId = findNextSplitToActivate(event.splitIndex);if (splitId) {diff --git a/apps/web/src/components/app/split-layout/tests/SplitPanel-frame-close.test.tsx b/apps/web/src/components/app/split-layout/tests/SplitPanel-frame-close.test.tsxindex c92ba0f3c0..35088dbbf3 100644--- a/apps/web/src/components/app/split-layout/tests/SplitPanel-frame-close.test.tsx+++ b/apps/web/src/components/app/split-layout/tests/SplitPanel-frame-close.test.tsx@@ -123,6 +123,7 @@ function renderDetailSplit() {content,referredFrom: null,lastNavigationCause: 'fresh',+ lastNavigationSource: null,mount: {kind: 'component',name: 'md',@@ -162,6 +163,7 @@ function renderDetailSplit() {updateMeta: () => {},referredFrom: () => null,lastNavigationCause: () => 'fresh',+ lastNavigationSource: () => null,registerEntryStateCaptor: () => () => {},captureEntryState: () => {},currentEntryState: () => undefined,diff --git a/apps/web/src/components/app/split-layout/tests/SplitPanel-header-targets.test.tsx b/apps/web/src/components/app/split-layout/tests/SplitPanel-header-targets.test.tsxindex cc0f0e5f54..6f0be44657 100644--- a/apps/web/src/components/app/split-layout/tests/SplitPanel-header-targets.test.tsx+++ b/apps/web/src/components/app/split-layout/tests/SplitPanel-header-targets.test.tsx@@ -115,6 +115,7 @@ it('mounts header contributions when chrome appears and follows its replacementid,content,referredFrom: null,+ lastNavigationSource: null,lastNavigationCause: 'fresh',mount: {kind: 'component',@@ -178,6 +179,7 @@ it('mounts header contributions when chrome appears and follows its replacementsplit.mount.kind === 'component' ? split.mount.meta : undefined,updateMeta: () => {},referredFrom: () => null,+ lastNavigationSource: () => null,lastNavigationCause: () => 'fresh',registerEntryStateCaptor: () => () => {},captureEntryState: () => {},diff --git a/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts b/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.tsindex 1bbc927a6c..e442c13fab 100644--- a/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts+++ b/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts@@ -10,6 +10,7 @@ import {vi,} from 'vitest';import type { SplitId } from '../layoutManager';+import { shouldAutofocusNavigation } from '../should-autofocus-navigation';import { createSplitFocusTracker } from '../splitFocusTracker';import { createRoutedSplitLayout } from './fixtures';@@ -68,12 +69,9 @@ const FOCUS_DEBOUNCE_MS = 50;* up from URL contents (last split active), then the focus tracker mounts* and processes the trailing Insert event.*/-function mountFreshLoad() {+function mountFreshLoad(url = '/home/~/channels') {return createRoot((dispose) => {- const manager = createRoutedSplitLayout(- createMockOrchestrator(),- '/home/~/channels'- );+ const manager = createRoutedSplitLayout(createMockOrchestrator(), url);const panelRefs = new Map<SplitId, HTMLDivElement>(manager.splits().map((split) => [split.id, createPanel()])@@ -136,6 +134,21 @@ describe('createSplitFocusTracker', () => {dispose();});+ it('does not restore a child that moved out of its pane', () => {+ const { dispose, manager, panelRefs } = mountFreshLoad('/home');+ const last = manager.splits().at(-1)!;+ const panel = panelRefs.get(last.id)!;+ const input = document.createElement('input');+ panel.append(input);+ input.focus();+ document.body.append(input);++ manager.returnFocus();++ expect(document.activeElement).toBe(panel);+ dispose();+ });+it('still focuses a new pane when the previous pane owns an editor', () => {const { dispose, manager, panelRefs } = mountFreshLoad();const [first, last] = manager.splits();@@ -149,6 +162,110 @@ describe('createSplitFocusTracker', () => {dispose();});+ it('leaves focus alone after ordinary split navigation', async () => {+ const { dispose, manager, panelRefs } = mountFreshLoad('/home');+ const last = manager.splits().at(-1)!;+ const panel = panelRefs.get(last.id)!;+ const oldInput = document.createElement('input');+ panel.append(oldInput);+ oldInput.focus();++ manager.openWithSplit({ type: 'component', id: 'channels' });+ oldInput.remove();+ await vi.runAllTimersAsync();++ expect(document.activeElement).toBe(document.body);+ dispose();+ });++ it.each(['kommand-menu', 'launcher'] as const)(+ 'focuses a reused pane after %s navigation',+ async (referredFrom) => {+ const { dispose, manager, panelRefs } = mountFreshLoad('/home');+ const last = manager.splits().at(-1)!;+ const panel = panelRefs.get(last.id)!;+ const oldInput = document.createElement('input');+ panel.append(oldInput);+ oldInput.focus();++ manager.openWithSplit(+ { type: 'component', id: 'channels' },+ { referredFrom }+ );+ oldInput.remove();+ await vi.runAllTimersAsync();++ expect(document.activeElement).toBe(panel);+ dispose();+ }+ );++ it('keeps focus claimed by the destination before the pane focus runs', async () => {+ const { dispose, manager, panelRefs } = mountFreshLoad('/home');+ const last = manager.splits().at(-1)!;+ const panel = panelRefs.get(last.id)!;++ manager.openWithSplit(+ { type: 'component', id: 'channels' },+ { referredFrom: 'kommand-menu' }+ );+ const editor = document.createElement('input');+ panel.append(editor);+ editor.focus();+ await vi.runAllTimersAsync();++ expect(document.activeElement).toBe(editor);+ dispose();+ });++ it('does not replay command-menu focus on history back', async () => {+ const { dispose, manager, panelRefs } = mountFreshLoad('/home');+ const last = manager.splits().at(-1)!;+ const panel = panelRefs.get(last.id)!;++ manager.openWithSplit(+ { type: 'component', id: 'channels' },+ { referredFrom: 'kommand-menu' }+ );+ await vi.runAllTimersAsync();++ const oldInput = document.createElement('input');+ panel.append(oldInput);+ oldInput.focus();+ manager.getSplit(last.id)?.goBack();+ oldInput.remove();+ await vi.runAllTimersAsync();++ expect(document.activeElement).toBe(document.body);+ dispose();+ });++ it('does not reuse a command source on the next ordinary replacement', async () => {+ const { dispose, manager } = mountFreshLoad('/home');+ const last = manager.splits().at(-1)!;++ manager.openWithSplit(+ { type: 'component', id: 'channels' },+ { referredFrom: 'kommand-menu' }+ );+ await vi.runAllTimersAsync();+ manager.getSplit(last.id)?.replace({+ next: { type: 'component', id: 'search' },+ });+ await vi.runAllTimersAsync();++ const handle = manager.getSplit(last.id)!;+ expect(handle.referredFrom()).toBe('kommand-menu');+ expect(handle.lastNavigationSource()).toBe(null);+ expect(+ shouldAutofocusNavigation(+ handle.lastNavigationSource(),+ handle.lastNavigationCause()+ )+ ).toBe(false);+ dispose();+ });+it('keeps a surviving pane active after removal without taking chrome focus', async () => {const { dispose, manager } = mountFreshLoad();const [first, last] = manager.splits();diff --git a/apps/web/src/features/block-canvas/block-embed-adapter.tsx b/apps/web/src/features/block-canvas/block-embed-adapter.tsxindex 83d0cbb88f..6b6b5558ab 100644--- a/apps/web/src/features/block-canvas/block-embed-adapter.tsx+++ b/apps/web/src/features/block-canvas/block-embed-adapter.tsx@@ -90,6 +90,7 @@ function CanvasBlockEmbedContent(props: CanvasEmbedViewProps) {meta: () => undefined,updateMeta: undefined,referredFrom: () => null,+ lastNavigationSource: () => null,lastNavigationCause: () => 'fresh',registerEntryStateCaptor: () => () => {},captureEntryState: () => {},diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsxindex 2d58fe0b89..c5de83575e 100644--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx@@ -1,7 +1,9 @@+import { activeElement } from '@app/signal/focus';import { MessageCommentsProvider } from '@block-md/comments/MessageCommentsProvider';import { URL_PARAMS } from '@block-md/constants';import { keyNavigationPlugin } from '@block-md/plugins/keyboardNavigation';import { SplitBottomPanel } from '@components/app/split-layout/components/SplitBottomPanel';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/core/FocusClickTarget';import {HighlightLayer,@@ -107,7 +109,6 @@ import {onCleanup,Show,Suspense,- untrack,} from 'solid-js';import { useMarkdownDocument } from '../context/markdown-document-context';import { createSaveMarkdownDocumentMutation } from '../queries/markdown-document-operations';@@ -115,6 +116,7 @@ import { EditorSystemMessage } from './EditorSystemMessage';import { MarkdownCollabProvider } from './MarkdownCollabProvider';import { MarkdownPopup } from './MarkdownPopup';import { isMarkdownEditorLoading } from './markdownEditorLoadingState';+import { shouldAutofocusDocument } from './should-autofocus-document';false && fileFolderDrop;@@ -143,12 +145,14 @@ export function MarkdownEditor(props: {}) {const {documentId,+ element: blockElement,kind,documentSource,persistedName: mdDocumentName,permissions,state: documentState,} = useMarkdownDocument();+ const panel = useSplitPanel();const authenticated = useIsAuthenticated();const { canEdit } = permissions;const blockId = documentId();@@ -630,13 +634,24 @@ export function MarkdownEditor(props: {setEditorReady(true);});- // Auto-focus on mount if enabled and editor is ready and document name is not empty.+ // Focus a named document once both its editor and metadata are ready.+ let didAutoFocus = false;createEffect(() => {+ activeElement();if (+ !didAutoFocus &&props.autoFocusOnMount &&editorReady() &&- untrack(mdDocumentName) !== ''+ mdDocumentName()) {+ if (+ !shouldAutofocusDocument(+ blockElement() ?? null,+ panel?.panelRef() ?? null+ )+ )+ return;+ didAutoFocus = true;editor.focus(undefined, { defaultSelection: 'rootStart' });}});diff --git a/apps/web/src/features/block-md/component/Notebook.tsx b/apps/web/src/features/block-md/component/Notebook.tsxindex 2d94b7783d..1b0cb4ba24 100644--- a/apps/web/src/features/block-md/component/Notebook.tsx+++ b/apps/web/src/features/block-md/component/Notebook.tsx@@ -1,5 +1,6 @@import { createSizeBreakpoints } from '@app/util/create-size-breakpoints';import { CommentMargin } from '@block-md/comments/CommentMargin';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';import { editorFocusSignal } from '@core/component/LexicalMarkdown/utils';import { ParamsProvider } from '@core/component/ParamsProvider';@@ -12,6 +13,7 @@ import { useIsMacroTeam } from '@core/context/team';import { registerHotkey } from '@core/hotkey/hotkeys';import { TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';+import { isTouchDevice } from '@core/mobile/isTouchDevice';import {captureScrollAnchor,restoreScrollAnchor,@@ -45,6 +47,7 @@ import {outlineFitsGutter,useMarkdownOutline,} from './MarkdownOutline';+import { shouldAutofocusDocument } from './should-autofocus-document';import { TaskDuplicateMatchPill } from './TaskDuplicateMatches';import { TitleEditor } from './TitleEditor';import { registerMarkdownCommands } from './useMarkdownCommands';@@ -95,6 +98,7 @@ export function Notebook(props: {autoFocus: boolean;}) {const { element: blockElement, state } = useMarkdownDocument();+ const panel = useSplitPanel();const { comments: commentState, params } = state;const { md, setMd } = state.editor;const { displayName: documentName } = useMarkdownName();@@ -283,8 +287,10 @@ export function Notebook(props: {createEffect(() => {if (hasRun) return;if (!props.autoFocus) return;- if (!blockElement()) return;- blockElement()?.focus();+ const element = blockElement();+ if (!element) return;+ if (shouldAutofocusDocument(element, panel?.panelRef() ?? null))+ element.focus();hasRun = true;});@@ -379,6 +385,7 @@ export function Notebook(props: {</div><ParamsProvider state={params}><MarkdownEditor+ autoFocusOnMount={props.autoFocus && !isTouchDevice()}resolveAppLink={resolveAppLink}loroManager={props.loroManager}showLexicalStateDebugger={diff --git a/apps/web/src/features/block-md/component/TitleEditor.tsx b/apps/web/src/features/block-md/component/TitleEditor.tsxindex 6724b9ad30..0292c59b42 100644--- a/apps/web/src/features/block-md/component/TitleEditor.tsx+++ b/apps/web/src/features/block-md/component/TitleEditor.tsx@@ -1,3 +1,5 @@+import { activeElement } from '@app/signal/focus';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';import { TagsMenu } from '@core/component/LexicalMarkdown/component/menu/TagsMenu';import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';@@ -50,6 +52,7 @@ import {} from 'solid-js';import { useMarkdownDocument } from '../context/markdown-document-context';import { useMarkdownName } from './MarkdownNameProvider';+import { shouldAutofocusDocument } from './should-autofocus-document';/*** Use the plugin architecture to set up command handlers on both the@@ -147,11 +150,13 @@ function titleNavigationPlugin(export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {const {documentId,+ element: blockElement,kind,documentSource,permissions,state: documentState,} = useMarkdownDocument();+ const panel = useSplitPanel();const canEdit = permissions.canEdit;const { md: mdData, setMd: setMdData } = documentState.editor;const renameDocumentMutation = createRenameDssEntityMutation();@@ -359,11 +364,30 @@ export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {));- // Autofocus the title if it is empty and we didn't navigate here via J/K.+ // Autofocus a new document's empty title once its metadata has loaded.+ let didAutoFocus = false;createEffect(() => {- if (props.autoFocusOnMount && rootConnected() && dataReady()) {- if (untrack(mdDocumentName) === '') {- editor.focus();+ activeElement();+ const name = mdDocumentName();+ if (+ !didAutoFocus &&+ props.autoFocusOnMount &&+ rootConnected() &&+ dataReady() &&+ name !== undefined+ ) {+ if (name === '') {+ if (+ shouldAutofocusDocument(+ blockElement() ?? null,+ panel?.panelRef() ?? null+ )+ ) {+ didAutoFocus = true;+ editor.focus();+ }+ } else {+ didAutoFocus = true;}}});diff --git a/apps/web/src/features/block-md/component/should-autofocus-document.ts b/apps/web/src/features/block-md/component/should-autofocus-document.tsnew file mode 100644index 0000000000..5084a38495--- /dev/null+++ b/apps/web/src/features/block-md/component/should-autofocus-document.ts@@ -0,0 +1,13 @@+/** A late-loading document may claim focus only while its own shell still owns it. */+export function shouldAutofocusDocument(+ block: HTMLElement | null,+ panel: HTMLElement | null+) {+ const active = document.activeElement;+ return (+ active === document.body ||+ active === document.documentElement ||+ active === block ||+ active === panel+ );+}diff --git a/apps/web/src/features/command/CommandMenu.tsx b/apps/web/src/features/command/CommandMenu.tsxindex a60f585ed9..84c4074a76 100644--- a/apps/web/src/features/command/CommandMenu.tsx+++ b/apps/web/src/features/command/CommandMenu.tsx@@ -5,7 +5,10 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import { t } from '@app/lib/i18n';import { globalSplitManager } from '@app/signal/splitLayout';import { useSplitLayout } from '@components/app/split-layout/layout';-import { enableProjects } from '@core/constant/featureFlags';+import {+ enableProjects,+ USE_MACRO_PR_SUMMARY_BLOCK,+} from '@core/constant/featureFlags';import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';import {@@ -19,7 +22,7 @@ import { runCommand } from '@core/hotkey/utils';import { debouncedDependent } from '@core/util/debounce';import { fireAndForget } from '@core/util/fireAndForget';import { lazyNamed } from '@core/util/lazyNamed';-import type { EntityData } from '@entity';+import { type EntityData, isGithubPrEntity } from '@entity';import { EntitySelectionBadge } from '@entity/components/EntitySelectionBadge';import Macro from '@icon/macro-logo.svg';import ArrowLeft from '@icon/system/regular/arrow-left.svg';@@ -131,6 +134,7 @@ export function CommandMenu() {: () => true; // assume list modelet suppressCloseAutoFocus = false;+ let wasOpen = false;createEffect(() => {const open = CommandState.isOpen();@@ -139,16 +143,27 @@ export function CommandMenu() {}if (open) {CommandState.onMenuOpen();- suppressCloseAutoFocus = false;+ if (!wasOpen) {+ suppressCloseAutoFocus = false;+ CommandState.setFocusDestinationOnClose(false);+ }} else {CommandState.onMenuClose();}+ wasOpen = open;});const handleSelect = (item: CommandMenuItem) => {+ CommandState.setFocusDestinationOnClose(+ isEntityItem(item) &&+ (item.bucket === 'initiative' ||+ (item.data.type !== 'foreign' &&+ (!isGithubPrEntity(item.data) || USE_MACRO_PR_SUMMARY_BLOCK)))+ );if (isSearchItem(item) ||isAskAiItem(item) ||+ isUserItem(item) ||item.kind === 'new-project' ||(isCommandItem(item) &&item.data.hotkeyToken === TOKENS.global.createCommand)@@ -161,10 +176,14 @@ export function CommandMenu() {class="[&>[data-command-menu]>[data-layer]>[data-surface]]:border-0! [&>[data-command-menu]>[data-layer]>[data-surface]]:bg-transparent [&>[data-command-menu]>[data-layer]>[data-surface]]:rounded-[24px]"onOpenChange={CommandState.setIsOpen}onCloseAutoFocus={(e) => {- if (suppressCloseAutoFocus) {+ if (suppressCloseAutoFocus || CommandState.focusDestinationOnClose()) {e.preventDefault();suppressCloseAutoFocus = false;}+ if (CommandState.focusDestinationOnClose()) {+ globalSplitManager()?.returnFocus();+ CommandState.setFocusDestinationOnClose(false);+ }}}open={CommandState.isOpen()}>diff --git a/apps/web/src/features/command/FavoritesCommands.tsx b/apps/web/src/features/command/FavoritesCommands.tsxindex d1691c0b80..1aa1ad75fc 100644--- a/apps/web/src/features/command/FavoritesCommands.tsx+++ b/apps/web/src/features/command/FavoritesCommands.tsx@@ -45,6 +45,7 @@ export function FavoritesCommands() {if (result.status === 'reused' && result.owner !== result.sourceOwner) {toast.alert(t('commandMenu.contentAlreadyOpen'));}+ CommandState.setFocusDestinationOnClose(true);// Close the menu and clear the query once a favorite is opened.CommandState.close();CommandState.setQuery('');diff --git a/apps/web/src/features/command/open-command-result.ts b/apps/web/src/features/command/open-command-result.tsindex 1e5b601204..90332f5c4d 100644--- a/apps/web/src/features/command/open-command-result.ts+++ b/apps/web/src/features/command/open-command-result.ts@@ -3,6 +3,7 @@ import { createGlobalSearchOpener } from '@app/features/next-soup/open-search';import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { t } from '@app/lib/i18n';+import { globalSplitManager } from '@app/signal/splitLayout';import { useSplitLayout } from '@components/app/split-layout/layout';import type { ReferredFrom } from '@components/app/split-layout/layoutManager';import { toast } from '@core/component/Toast/Toast';@@ -50,6 +51,7 @@ export function createCommandResultOpener(reopen: 'latest',});+ globalSplitManager()?.returnFocus();} catch {toast.failure(t('commandMenu.unableToOpenConversation'));}@@ -123,7 +125,7 @@ export function createCommandResultOpener(type: 'component',id: projectRouteId({ id: item.id, section: 'overview' }),},- { preferNewSplit: openInNewSplit }+ { referredFrom, preferNewSplit: openInNewSplit });return true;}diff --git a/apps/web/src/features/command/state.ts b/apps/web/src/features/command/state.tsindex 1cbe37b5d5..4f5827380b 100644--- a/apps/web/src/features/command/state.ts+++ b/apps/web/src/features/command/state.ts@@ -27,6 +27,9 @@ interface ICommandState {toggle: () => void;open: () => void;close: () => void;+ /** Let a selected destination claim focus when the menu closes. */+ focusDestinationOnClose: Accessor<boolean>;+ setFocusDestinationOnClose: Setter<boolean>;/** query */query: Accessor<string>;@@ -80,6 +83,8 @@ function createCommandState(): ICommandState {id: 'command',});const [query, setQuery] = createSignal('');+ const [focusDestinationOnClose, setFocusDestinationOnClose] =+ createSignal(false);const [selectedIndex, setSelectedIndex] = createSignal(0);const [categoryFilter, setCategoryFilter] =createSignal<CategoryFilter>('all');@@ -201,6 +206,8 @@ function createCommandState(): ICommandState {toggle,open,close,+ focusDestinationOnClose,+ setFocusDestinationOnClose,query,setQuery,diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 30d766690f..5494de8e11 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -2445,6 +2445,12 @@ stay text instead of becoming mentions, long pastes do not collapse into a4. The document auto-saves continuously (collaborative CRDT; no save button). The tab titleand header update to the typed title.+On desktop, opening a document through Cmd/Ctrl+K focuses its body editor after+the content and title have loaded. Creating a document focuses its empty title;+if the new document already has a title, it focuses the body. Ordinary clicks+and Back/Forward do not move focus into the editor. A control the user focused+while the document loaded keeps focus.+The a11y snapshot exposes the entire body as the contenteditable's `value` and as paragraphnodes — use the snapshot itself to verify content. For formatting checks, run`evaluate_script` over `[contenteditable] strong` etc.diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex 06436f66d6..3bef9303c8 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -437,6 +437,10 @@ Split focus mode (`Shift+Esc`) floats the active split in a rounded, borderedpanel over the same glass scrim as dialogs. Click the scrim or use the shortcutagain to restore the split layout.+On desktop, when navigation replaces a pane's content, keyboard focus moves into the active+pane. If the destination editor or input focuses itself, it keeps focus. A+focused search or other input outside the panes remains focused while it is open.+Image lightboxes, channel media viewers, sharing, and onboarding dialogs usethe standard glass scrim. Scroll-edge indicators fade smoothly toward contentand disappear at the corresponding scroll boundary. Image and video error@@ -1433,6 +1437,8 @@ restart rules still apply.## Keyboard model (from the in-app guide; verified partially)- `Ctrl/Cmd+K` — jump to anything by name.+ Selecting a destination focuses its split or editor after the menu closes.+ Clicking through lists and moving Back/Forward leaves editor focus alone.- `?` — the focused view's shortcuts, read from its registered keys (hiddennavigation keys and `g` sequences included); `?` again closes it. Only thekey opens it: the command menu does not list it, since run from there it