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(web): route inbox previews by block target (#6898)
dev-rb8fa8f2e07d59
diff --git a/apps/web/src/components/app/PreviewPanel.test.tsx b/apps/web/src/components/app/PreviewPanel.test.tsxindex ef91c1d01c..bd1b4a637a 100644--- a/apps/web/src/components/app/PreviewPanel.test.tsx+++ b/apps/web/src/components/app/PreviewPanel.test.tsx@@ -1,45 +1,23 @@import { cleanup, fireEvent, render } from '@solidjs/testing-library';import { createSignal, onCleanup, onMount } from 'solid-js';-import { createStore, reconcile } from 'solid-js/store';import { afterEach, describe, expect, it, vi } from 'vitest';import {PreviewPanel,type PreviewPanelProps,- type PreviewPanelSelection,useMaybePreviewPanel,} from './PreviewPanel';+import type {+ PreviewBlockTarget,+ PreviewPanelSelection,+} from './previewTarget';const mocks = vi.hoisted(() => ({- navigateChannel: vi.fn(),- navigateCalendar: vi.fn(),- navigateDocument: vi.fn(),+ goToLocationFromParams: vi.fn(),+ goToLatest: vi.fn(),mounts: vi.fn(),unmounts: vi.fn(),}));-// Exercise the real preview without loading unrelated blocks or service clients.-vi.mock('@app/features/next-soup/utils', () => ({- getChannelEntityTarget: () => ({ kind: 'latest' }),- navigateChannelEntityToTarget: mocks.navigateChannel,- navigateCalendarPreviewToTarget: mocks.navigateCalendar,- navigateDocumentEntityToComment: mocks.navigateDocument,- getDocumentCommentTarget: (entity: {- commentTarget?: { commentId: string };- }) =>- entity.commentTarget- ? { commentId: entity.commentTarget.commentId, params: {} }- : undefined,- calendarViewTargetForEntity: vi.fn(),- reminderSplitTarget: vi.fn(),-}));-vi.mock('@block-calendar/types', () => ({ CALENDAR_BLOCK_ID: 'calendar' }));-vi.mock('@block-channel/utils/link', () => ({ getChannelParams: vi.fn() }));-vi.mock('@core/constant/allBlocks', () => ({- fileTypeToResolvedBlockName: (type: string) => type,-}));-vi.mock('@core/constant/featureFlags', () => ({- USE_MACRO_PR_SUMMARY_BLOCK: false,-}));vi.mock('@core/hotkey/hotkeys', () => ({useHotkeyDOMScope: () => [() => {}, {}],}));@@ -56,34 +34,43 @@ afterEach(() => {vi.clearAllMocks();});-function setup(initial: PreviewPanelSelection) {- const [entity, setEntity] = createSignal(initial);+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++function setup(initial: PreviewBlockTarget, entity?: PreviewPanelSelection) {+ const [target, setTarget] = createSignal(initial);+ const [selectedEntity, setSelectedEntity] = createSignal(entity);const [navigationRequest, setNavigationRequest] = createSignal(0);let preview: ReturnType<typeof useMaybePreviewPanel>;- const element = () => {- preview = useMaybePreviewPanel();- onMount(mocks.mounts);- onCleanup(mocks.unmounts);- return (- <div>- <span data-testid="selection">{preview?.previewEntity().id}</span>- <input aria-label="Message draft" />- </div>- );- };const createBlockInstance = vi.fn((type: string, id: string) => ({type,id,- element,+ element: () => {+ onMount(mocks.mounts);+ onCleanup(mocks.unmounts);+ preview = useMaybePreviewPanel();+ return (+ <div>+ <span data-testid="block">{id}</span>+ <span data-testid="selection">{preview?.previewEntity()?.id}</span>+ <input aria-label="Message draft" />+ </div>+ );+ },+ }));+ const getBlockHandle = vi.fn(async () => ({+ goToLocationFromParams: mocks.goToLocationFromParams,+ goToLatest: mocks.goToLatest,}));const orchestrator = {isBlockMounted: () => false,createBlockInstance,+ getBlockHandle,} as unknown as PreviewPanelProps['orchestrator'];const onFocusOut = vi.fn();const view = render(() => (<PreviewPanel- selectedEntity={entity()}+ target={target()}+ selectedEntity={selectedEntity()}navigationRequest={navigationRequest()}orchestrator={orchestrator}splitPanelContext={{} as PreviewPanelProps['splitPanelContext']}@@ -92,151 +79,116 @@ function setup(initial: PreviewPanelSelection) {));return {...view,- setEntity,+ setTarget,+ setSelectedEntity,requestNavigation: () => setNavigationRequest((count) => count + 1),+ previewEntity: () => preview?.previewEntity(),createBlockInstance,+ getBlockHandle,onFocusOut,- previewEntity: () => preview?.previewEntity(),};}-const channelSelections = [- { type: 'channel', id: 'channel-1' },- {- type: 'channel_message',- id: 'message-1',- channelId: 'channel-1',- messageId: 'message-1',- },- {- type: 'channel_thread',- id: 'thread-1',- channelId: 'channel-1',- messageId: 'thread-1',- threadId: 'thread-1',- },-] satisfies PreviewPanelSelection[];--describe('channel preview navigation', () => {- it.each(channelSelections)(- 'does not navigate or remount a $type on cache object replacement',- (selection) => {- const view = setup(selection);- const draft = view.getByLabelText('Message draft');- fireEvent.input(draft, { target: { value: 'Unsent draft' } });- expect(mocks.navigateChannel).toHaveBeenCalledTimes(1);-- // GraphQL local projections publish fresh objects on cache revisions,- // including revisions unrelated to this conversation.- view.setEntity({ ...selection, notifications: () => [] });- const refreshed = { ...selection, notifications: () => [] };- view.setEntity(refreshed);-- expect(view.previewEntity()).toBe(refreshed);- expect(mocks.navigateChannel).toHaveBeenCalledTimes(1);- expect(view.createBlockInstance).toHaveBeenCalledTimes(1);- expect(mocks.mounts).toHaveBeenCalledTimes(1);- expect(mocks.unmounts).not.toHaveBeenCalled();- expect(view.getByLabelText('Message draft')).toBe(draft);- expect((draft as HTMLInputElement).value).toBe('Unsent draft');- }- );+const channel = (+ id: string,+ params?: Record<string, string>+): PreviewBlockTarget => ({+ blockType: 'channel',+ blockId: id,+ aliasContext: undefined,+ params,+});++describe('preview block navigation', () => {+ it('does not relocate or remount when the same target arrives as a fresh object', async () => {+ const view = setup(channel('channel-1', { channel_message_id: 'm-1' }));+ await flush();+ const draft = view.getByLabelText('Message draft');+ fireEvent.input(draft, { target: { value: 'Unsent draft' } });+ expect(view.getBlockHandle).toHaveBeenCalledTimes(1);+ expect(mocks.goToLocationFromParams).toHaveBeenCalledTimes(1);++ // Hosts recompute targets from cache revisions unrelated to this block.+ view.setTarget(channel('channel-1', { channel_message_id: 'm-1' }));+ view.setTarget(channel('channel-1', { channel_message_id: 'm-1' }));+ await flush();++ expect(view.getBlockHandle).toHaveBeenCalledTimes(1);+ expect(view.createBlockInstance).toHaveBeenCalledTimes(1);+ expect(mocks.mounts).toHaveBeenCalledTimes(1);+ expect(mocks.unmounts).not.toHaveBeenCalled();+ expect(view.getByLabelText('Message draft')).toBe(draft);+ expect((draft as HTMLInputElement).value).toBe('Unsent draft');+ });it('preserves focus ownership after interacting with a refreshed preview', () => {- const view = setup(channelSelections[0]);+ const view = setup(channel('channel-1'));const draft = view.getByLabelText('Message draft');fireEvent.pointerDown(draft);- view.setEntity({ ...channelSelections[0] });+ view.setTarget(channel('channel-1'));fireEvent.focusIn(draft);expect(view.onFocusOut).not.toHaveBeenCalled();});- it('navigates when selecting another channel', () => {- const view = setup(channelSelections[0]);- view.setEntity({ type: 'channel', id: 'channel-2' });- expect(mocks.navigateChannel).toHaveBeenCalledTimes(2);- expect(view.createBlockInstance).toHaveBeenCalledTimes(2);- expect(view.getByTestId('selection').textContent).toBe('channel-2');+ it('lands untargeted channels on their latest message', async () => {+ setup(channel('channel-1'));+ await flush();+ expect(mocks.goToLatest).toHaveBeenCalledTimes(1);+ expect(mocks.goToLocationFromParams).not.toHaveBeenCalled();});- it('retargets different threads without remounting their shared channel', () => {- const view = setup(channelSelections[2]);- view.setEntity({- ...channelSelections[2],- id: 'thread-2',- messageId: 'thread-2',- threadId: 'thread-2',- });- expect(mocks.navigateChannel).toHaveBeenCalledTimes(2);- expect(view.createBlockInstance).toHaveBeenCalledTimes(1);- expect(mocks.mounts).toHaveBeenCalledTimes(1);- expect(view.getByTestId('selection').textContent).toBe('thread-2');+ it('creates a new block when selecting another channel', async () => {+ const view = setup(channel('channel-1'));+ view.setTarget(channel('channel-2'));+ await flush();+ expect(view.createBlockInstance).toHaveBeenCalledTimes(2);+ expect(mocks.goToLatest).toHaveBeenCalledTimes(2);+ expect(view.getByTestId('block').textContent).toBe('channel-2');});- it('honors explicit target changes for the same channel, including store updates', () => {- const [entity, setEntity] = createStore({- ...channelSelections[0],- target: { messageId: 'reply-1', threadId: 'thread-1' },- });- setup(entity);- setEntity(- reconcile({- ...channelSelections[0],- target: { messageId: 'reply-1', threadId: 'thread-1' },+ it('relocates within the same block without remounting it', async () => {+ const view = setup(+ channel('channel-1', {+ channel_message_id: 't-1',+ channel_thread_id: 't-1',}));- expect(mocks.navigateChannel).toHaveBeenCalledTimes(1);- setEntity('target', 'messageId', 'reply-2');- expect(mocks.navigateChannel).toHaveBeenCalledTimes(2);- setEntity('target', 'threadId', 'thread-2');- expect(mocks.navigateChannel).toHaveBeenCalledTimes(3);- expect(mocks.mounts).toHaveBeenCalledTimes(1);- });-- it('preserves calendar occurrence navigation within the singleton block', () => {- const event = {- type: 'calendar_event',- id: 'event-1',- occurrenceKey: 'occurrence-1',- time: {- kind: 'allDay',- startDate: '2026-09-17',- endDate: '2026-09-18',- },- } satisfies PreviewPanelSelection;- const view = setup(event);- view.setEntity({ ...event, occurrenceKey: 'occurrence-2' });- expect(mocks.navigateCalendar).toHaveBeenCalledTimes(2);+ view.setTarget(+ channel('channel-1', {+ channel_message_id: 't-2',+ channel_thread_id: 't-2',+ })+ );+ await flush();+ expect(mocks.goToLocationFromParams).toHaveBeenCalledTimes(2);+ expect(mocks.goToLocationFromParams).toHaveBeenLastCalledWith({+ channel_message_id: 't-2',+ channel_thread_id: 't-2',+ });expect(view.createBlockInstance).toHaveBeenCalledTimes(1);expect(mocks.mounts).toHaveBeenCalledTimes(1);});-});--describe('re-opening the previewed selection', () => {- const document = {- type: 'document',- id: 'doc-1',- fileType: 'md',- commentTarget: { commentId: 'comment-1' },- } satisfies PreviewPanelSelection;- it('navigates the document to its comment again on each request', () => {- const view = setup(document);- expect(mocks.navigateDocument).toHaveBeenCalledTimes(1);+ it('re-aims the same block on an explicit request without remounting', async () => {+ const view = setup(channel('channel-1', { channel_message_id: 'm-1' }));+ await flush();+ expect(mocks.goToLocationFromParams).toHaveBeenCalledTimes(1);- view.setEntity({ ...document });- expect(mocks.navigateDocument).toHaveBeenCalledTimes(1);-- view.requestNavigation();view.requestNavigation();- expect(mocks.navigateDocument).toHaveBeenCalledTimes(3);+ await flush();+ expect(mocks.goToLocationFromParams).toHaveBeenCalledTimes(2);expect(view.createBlockInstance).toHaveBeenCalledTimes(1);- expect(mocks.unmounts).not.toHaveBeenCalled();+ expect(mocks.mounts).toHaveBeenCalledTimes(1);});- it('re-targets a channel on request', () => {- const view = setup(channelSelections[1]);- view.requestNavigation();- expect(mocks.navigateChannel).toHaveBeenCalledTimes(2);+ it('keeps live selection metadata in its preview context', () => {+ const view = setup(channel('channel-1'), {+ type: 'channel',+ id: 'channel-1',+ });+ const refreshed = { type: 'channel' as const, id: 'channel-1' };+ view.setSelectedEntity(refreshed);+ expect(view.previewEntity()).toBe(refreshed);+ expect(view.getByTestId('selection').textContent).toBe('channel-1');});});diff --git a/apps/web/src/components/app/PreviewPanel.tsx b/apps/web/src/components/app/PreviewPanel.tsxindex 9b549bfa61..41e8af30f7 100644--- a/apps/web/src/components/app/PreviewPanel.tsx+++ b/apps/web/src/components/app/PreviewPanel.tsx@@ -1,13 +1,9 @@-import {- getDocumentCommentTarget,- navigateCalendarPreviewToTarget,- navigateChannelEntityToTarget,- navigateDocumentEntityToComment,-} from '@app/features/next-soup/utils';import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import type { BlockOrchestrator } from '@core/orchestrator';import { createContextProvider } from '@solid-primitives/context';+import deepEqual from 'fast-deep-equal';import {+ type Accessor,createMemo,createRenderEffect,createSignal,@@ -17,14 +13,11 @@ import {Suspense,} from 'solid-js';import { Dynamic } from 'solid-js/web';-import {- type PreviewPanelSelection,- previewBlockTarget,-} from './previewTarget';--export type { PreviewPanelSelection } from './previewTarget';-import { ViewShell } from '../view-shell/ViewShell';+import type {+ PreviewBlockTarget,+ PreviewPanelSelection,+} from './previewTarget';import {createPriorityCollapseController,PriorityCollapseOverflowSensor,@@ -37,31 +30,31 @@ import {export const [PreviewPanelContext, useMaybePreviewPanel] =createContextProvider((props: {- previewEntity: PreviewPanelSelection;+ previewTarget: PreviewBlockTarget;+ previewEntity?: PreviewPanelSelection;onFocusOut?: VoidFunction;}) => ({+ previewTarget: () => props.previewTarget,previewEntity: () => props.previewEntity,onFocusOut: () => props.onFocusOut?.(),}));-export type PreviewPanelProps = {- selectedEntity: PreviewPanelSelection | undefined;- /**- * Bumped by the host when the user re-opens the selection already shown, so- * the block navigates to its target again.- */- navigationRequest?: number;- orchestrator: BlockOrchestrator;+export type PreviewFrameProps = {splitPanelContext: SplitPanelContextType;onFocusOut?: VoidFunction;ref?: (el: HTMLElement) => void;headerLeading?: JSX.Element;+ /** A new value marks a new location, which hands focus back to the host. */+ locationKey?: Accessor<unknown>;+ children: JSX.Element;};-function PreviewPanelContent(- props: PreviewPanelProps & { selectedEntity: PreviewPanelSelection }-) {+/**+ * Inline preview chrome: header and toolbar slots, focus containment, and a+ * split-panel context scoped to the preview. Content mounts as children.+ */+export function PreviewFrame(props: PreviewFrameProps) {const scopedLayoutRefs: SplitPanelContextType['layoutRefs'] = {};const headerCollapseController = createPriorityCollapseController();const toolbarCollapseController = createPriorityCollapseController();@@ -69,85 +62,11 @@ function PreviewPanelContent(const [attachHotkeys, previewHotkeyScope] =useHotkeyDOMScope('preview-panel');- const blockInstance = createMemo<- ReturnType<BlockOrchestrator['createBlockInstance']> | undefined- >((previous) => {- const entity = props.selectedEntity;-- const target = previewBlockTarget(entity);-- if (previous?.type === target.blockType && previous.id === target.blockId) {- return previous;- }-- return props.orchestrator.createBlockInstance(- target.blockType,- target.blockId,- {- aliasContext: target.aliasContext,- params: target.params,- }- );- });-- // Cache reconciliation can replace an unchanged channel object. Only a new- // selection or explicit target should navigate/reset focus, not fresh metadata- // or notifications. Keep the live entity available to the preview context.- const navigationSelection = createMemo(() => {- const entity = props.selectedEntity;- if (- entity.type === 'channel' ||- entity.type === 'channel_message' ||- entity.type === 'channel_thread'- ) {- return JSON.stringify([- entity.type,- entity.id,- entity.type === 'channel' ? undefined : entity.channelId,- entity.type === 'channel' ? undefined : entity.messageId,- entity.type === 'channel' ? undefined : entity.threadId,- entity.target?.messageId,- entity.target?.threadId,- ]);- }- if (entity.type === 'document') {- return JSON.stringify([- entity.type,- entity.id,- getDocumentCommentTarget(entity)?.commentId,- ]);- }- return entity;- });-- const navigation = createMemo(- () => ({- selection: navigationSelection(),- request: props.navigationRequest ?? 0,- }),- undefined,- {- equals: (a, b) => a.selection === b.selection && a.request === b.request,- }- );-createRenderEffect(- on(navigation, () => {- const entity = props.selectedEntity;- setInteractedWith(false);- if (!blockInstance()) return;- if (- entity.type === 'channel' ||- entity.type === 'channel_message' ||- entity.type === 'channel_thread'- ) {- void navigateChannelEntityToTarget(entity, props.orchestrator);- } else if (entity.type === 'calendar_event') {- void navigateCalendarPreviewToTarget(entity, props.orchestrator);- } else if (entity.type === 'document') {- void navigateDocumentEntityToComment(entity, props.orchestrator);- }- })+ on(+ () => props.locationKey?.(),+ () => setInteractedWith(false)+ ));return (@@ -235,33 +154,111 @@ function PreviewPanelContent(toolbarCollapser: toolbarCollapseController.collapser,}}>- <PreviewPanelContext- previewEntity={props.selectedEntity}- onFocusOut={props.onFocusOut}- >- <Suspense>- <Show when={blockInstance()}>- {(instance) => <Dynamic component={instance().element} />}- </Show>- </Suspense>- </PreviewPanelContext>+ <Suspense>{props.children}</Suspense></SplitPanelContext.Provider></div></div>);}+export type PreviewPanelProps = {+ target: PreviewBlockTarget | undefined;+ /** Re-open the same target without replacing its mounted block. */+ navigationRequest?: number;+ /** Live selection metadata when a row opened this route. */+ selectedEntity?: PreviewPanelSelection;+ orchestrator: BlockOrchestrator;+ splitPanelContext: SplitPanelContextType;+ onFocusOut?: VoidFunction;+ ref?: (el: HTMLElement) => void;+ headerLeading?: JSX.Element;+};++function sameLocation(left: PreviewBlockTarget, right: PreviewBlockTarget) {+ return (+ left.blockType === right.blockType &&+ left.blockId === right.blockId &&+ deepEqual(left.params, right.params)+ );+}++function PreviewBlock(+ props: PreviewPanelProps & { target: PreviewBlockTarget }+) {+ const blockInstance = createMemo<+ ReturnType<BlockOrchestrator['createBlockInstance']> | undefined+ >((previous) => {+ const { blockType, blockId, aliasContext, params } = props.target;++ if (previous?.type === blockType && previous.id === blockId) {+ return previous;+ }++ return props.orchestrator.createBlockInstance(blockType, blockId, {+ aliasContext,+ params,+ });+ });++ // Fresh objects for the same block and params are not a navigation. Only a+ // new block or a new location should drive the block or reset focus.+ const location = createMemo(() => props.target, undefined, {+ equals: sameLocation,+ });+ const navigation = createMemo(+ () => ({ target: location(), request: props.navigationRequest ?? 0 }),+ undefined,+ {+ equals: (a, b) =>+ a.request === b.request && sameLocation(a.target, b.target),+ }+ );+ const locate = async (target: PreviewBlockTarget) => {+ const handle = await props.orchestrator.getBlockHandle(+ target.blockId,+ target.blockType+ );+ if (target.params) await handle?.goToLocationFromParams(target.params);+ else if (target.blockType === 'channel') await handle?.goToLatest();+ };++ createRenderEffect(+ on(navigation, ({ target }) => {+ if (!blockInstance()) return;+ void locate(target);+ })+ );++ return (+ <PreviewFrame+ splitPanelContext={props.splitPanelContext}+ onFocusOut={props.onFocusOut}+ ref={props.ref}+ headerLeading={props.headerLeading}+ locationKey={navigation}+ >+ <PreviewPanelContext+ previewTarget={props.target}+ previewEntity={props.selectedEntity}+ onFocusOut={props.onFocusOut}+ >+ <Show when={blockInstance()}>+ {(instance) => <Dynamic component={instance().element} />}+ </Show>+ </PreviewPanelContext>+ </PreviewFrame>+ );+}+/**- * Renders an admitted selection. Hosts use createPreviewSelectionGuard before- * changing selection so conflicts never replace their current detail view.+ * Renders an admitted block target inline. Hosts use createPreviewSelectionGuard+ * before changing the target so conflicts never replace their current detail view.*/export function PreviewPanel(props: PreviewPanelProps) {return (<div class="flex size-full min-h-0">- <Show when={props.selectedEntity}>- {(selectedEntity) => (- <PreviewPanelContent {...props} selectedEntity={selectedEntity()} />- )}+ <Show when={props.target}>+ {(target) => <PreviewBlock {...props} target={target()} />}</Show></div>);diff --git a/apps/web/src/components/app/createPreviewSelectionGuard.ts b/apps/web/src/components/app/createPreviewSelectionGuard.tsindex 54a455ce07..ff754f6634 100644--- a/apps/web/src/components/app/createPreviewSelectionGuard.ts+++ b/apps/web/src/components/app/createPreviewSelectionGuard.ts@@ -2,6 +2,7 @@ import type { NavigationStackChangeReason } from '@app/components/navigation-staimport { toast } from '@core/component/Toast/Toast';import { createSignal, onCleanup, untrack, useContext } from 'solid-js';import {+ type PreviewBlockTarget,type PreviewPanelSelection,previewBlockTarget,} from './previewTarget';@@ -9,8 +10,11 @@ import type { ContentIdentity } from './split-layout/contentInstanceRegistry';import { SplitLayoutContext } from './split-layout/context';import { useSplitPanelOrThrow } from './split-layout/layoutUtils';+/** A live row, or the block target a route already resolved it to. */+export type PreviewSelectionInput = PreviewPanelSelection | PreviewBlockTarget;+type SelectPreview = (- selection: PreviewPanelSelection | undefined,+ selection: PreviewSelectionInput | undefined,reason?: NavigationStackChangeReason) => boolean;@@ -35,9 +39,11 @@ export function createPreviewSelectionGuard(): PreviewSelectionGuard {});onCleanup(unregister);- const identity = (selection: PreviewPanelSelection | undefined) => {- const target = selection && previewBlockTarget(selection);- return target && { type: target.blockType, id: target.blockId };+ const identity = (selection: PreviewSelectionInput | undefined) => {+ if (!selection) return;+ const target =+ 'blockType' in selection ? selection : previewBlockTarget(selection);+ return { type: target.blockType, id: target.blockId };};const canSelect: SelectPreview = (selection, reason = 'navigate') =>untrack(() => {diff --git a/apps/web/src/components/app/previewTarget.ts b/apps/web/src/components/app/previewTarget.tsindex 6978314eff..c640469dff 100644--- a/apps/web/src/components/app/previewTarget.ts+++ b/apps/web/src/components/app/previewTarget.ts@@ -1,3 +1,4 @@+import type { CalendarViewTarget } from '@app/features/calendar-view/types';import {type CalendarPreviewSelection,type ChannelPreviewSelection,@@ -7,14 +8,17 @@ import {type ReminderPreviewSelection,reminderSplitTarget,} from '@app/features/next-soup/utils';-import { CALENDAR_BLOCK_ID } from '@block-calendar/types';import { getChannelParams } from '@block-channel/utils/link';import type {BlockAliasContext,BlockComponentProps,BlockName,} from '@core/block';-import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';+import {+ fileTypeToResolvedBlockName,+ isBlockAlias,+ resolveBlockAlias,+} from '@core/constant/allBlocks';import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';import type {DocumentCommentTarget,@@ -47,15 +51,19 @@ type ForeignPreviewSelection = Pick<'id' | 'type' | 'foreignSource'>;+/** Selections that render inline through a block. */export type PreviewPanelSelection =| IdOnlyPreviewSelection| DocumentPreviewSelection| ForeignPreviewSelection| ChannelPreviewSelection- | CalendarPreviewSelection| ReminderPreviewSelection;-type PreviewBlockTarget = {+/** What a list row may ask to preview: a block inline, or the Calendar view. */+export type PreviewSelection = PreviewPanelSelection | CalendarPreviewSelection;++/** The block a selection opens, plus the params that load or locate its content. */+export type PreviewBlockTarget = {blockType: BlockName;blockId: string;aliasContext: BlockAliasContext | undefined;@@ -65,53 +73,39 @@ type PreviewBlockTarget = {const documentCommentParams = (document: DocumentPreviewSelection) =>untrack(() => getDocumentCommentTarget(document)?.params);+function aliasContextFor(+ kind: string | undefined+): BlockAliasContext | undefined {+ if (kind === undefined || !isBlockAlias(kind)) return;+ return { alias: kind, baseType: resolveBlockAlias(kind) };+}+export function previewBlockTarget(entity: PreviewPanelSelection): PreviewBlockTarget {return match(entity).returnType<PreviewBlockTarget>()- .with(- { type: 'document', fileType: 'md', subType: { type: 'task' } },- (task) => ({- blockType: fileTypeToResolvedBlockName(task.fileType),- blockId: task.id,- aliasContext: {- alias: 'task',- baseType: 'md',- } satisfies BlockAliasContext,- params: documentCommentParams(task),- })- )- .with(- { type: 'document', fileType: 'md', subType: { type: 'snippet' } },- (snippet) => ({- blockType: fileTypeToResolvedBlockName(snippet.fileType),- blockId: snippet.id,- aliasContext: {- alias: 'snippet',- baseType: 'md',- } satisfies BlockAliasContext,- params: documentCommentParams(snippet),- })- ).with({ type: 'document' }, (document) => ({blockType: fileTypeToResolvedBlockName(document.fileType),blockId: document.id,- aliasContext: undefined,+ aliasContext: aliasContextFor(document.subType?.type),params: documentCommentParams(document),}))- .with({ type: P.union('channel_message', 'channel_thread') }, (message) => {- const channelTarget = untrack(() => getChannelEntityTarget(message));- return {- blockType: 'channel',- blockId: message.channelId,- aliasContext: undefined,- params:- channelTarget?.kind === 'message'- ? getChannelParams(channelTarget.messageId, channelTarget.threadId)- : undefined,- };- })+ .with(+ { type: P.union('channel', 'channel_message', 'channel_thread') },+ (channel) => {+ const target = untrack(() => getChannelEntityTarget(channel));+ return {+ blockType: 'channel',+ blockId: channel.type === 'channel' ? channel.id : channel.channelId,+ aliasContext: undefined,+ params:+ target?.kind === 'message'+ ? getChannelParams(target.messageId, target.threadId)+ : undefined,+ };+ }+ ).with({ type: 'foreign' }, (foreignEntity) => ({blockType:USE_MACRO_PR_SUMMARY_BLOCK &&@@ -131,18 +125,12 @@ export function previewBlockTarget(blockId: contact.id,aliasContext: undefined,}))- .with({ type: 'calendar_event' }, (calendarEvent) => ({- blockType: 'calendar',- blockId: CALENDAR_BLOCK_ID,- aliasContext: undefined,- params: untrack(() => calendarViewTargetForEntity(calendarEvent)),- })).with({ type: 'reminder' }, (reminder) => {const reminderTarget = reminderSplitTarget(reminder);return {blockType: fileTypeToResolvedBlockName(reminderTarget?.type),blockId: reminderTarget?.id ?? reminder.id,- aliasContext: undefined,+ aliasContext: aliasContextFor(reminderTarget?.type),};}).otherwise((fallbackEntity) => ({@@ -151,3 +139,10 @@ export function previewBlockTarget(aliasContext: undefined,}));}++/** Calendar events aim the Calendar view instead of mounting a block. */+export function previewCalendarTarget(+ entity: CalendarPreviewSelection+): CalendarViewTarget {+ return untrack(() => calendarViewTargetForEntity(entity));+}diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.tsindex 0112ae56b8..7e9b0b6ca8 100644--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts@@ -5,12 +5,13 @@ import {calendarPath,} from '@app/features/calendar-view/calendar-url';import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';-import { CHANNEL_DETAIL_SEARCH_NAMESPACE } from '@app/features/channels-view/channels-route';+import { channelsSearch } from '@app/features/channels-view/channels-route';import {driveDocumentFromContent,drivePath,} from '@app/features/drive-view/primitives/drive-route';import { driveDocumentBlockType } from '@app/features/drive-view/primitives/drive-route-schema';+import { driveSearch } from '@app/features/drive-view/primitives/drive-search';import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';import { EMAIL_DETAIL_SEARCH_NAMESPACE } from '@app/features/email-view/email-route';import {@@ -22,6 +23,8 @@ import {} from '@app/lib/split-router';import { replaceSplitSearchParams } from '@app/lib/split-router/search';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';+import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';+import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';import { match } from 'ts-pattern';import { appSplitRoutes } from './app-routes';import { decodeLegacyPair } from './legacy-route';@@ -115,19 +118,54 @@ function migrateLegacySearch({if (!externalSearch) return;const leafId = to.location.route.matches.at(-1)?.id;+ const inboxChannel =+ leafId === 'inbox-channel' ||+ (leafId === 'inbox-preview' &&+ routeParams(to.location.route).blockType === 'channel');+ const inboxDocumentType =+ leafId === 'inbox-document'+ ? routeParams(to.location.route).documentType+ : leafId === 'inbox-preview'+ ? routeParams(to.location.route).blockType+ : undefined;+ const commentKey = (() => {+ switch (inboxDocumentType) {+ case 'md':+ case 'task':+ case 'skill':+ case 'snippet':+ case 'spreadsheet':+ return MD_URL_PARAMS.commentId;+ case 'pdf':+ return PDF_URL_PARAMS.annotationId;+ }+ })();+ const inboxDocumentMapping = commentKey+ ? {+ namespace: driveSearch.namespace,+ fields: [[commentKey, 'commentId']] as const,+ }+ : undefined;const mapping = match(leafId).with('mail-thread', () => ({namespace: EMAIL_DETAIL_SEARCH_NAMESPACE,fields: [[EMAIL_URL_PARAMS.messageId, 'messageId']] as const,}))- .with('channels-channel', () => ({- namespace: CHANNEL_DETAIL_SEARCH_NAMESPACE,- fields: [- [CHANNEL_URL_PARAMS.message, 'messageId'],- [CHANNEL_URL_PARAMS.thread, 'threadId'],- ] as const,- }))+ .when(+ (id) => id === 'channels-channel' || inboxChannel,+ () => ({+ namespace: channelsSearch.namespace,+ fields: [+ [CHANNEL_URL_PARAMS.message, 'messageId'],+ [CHANNEL_URL_PARAMS.thread, 'threadId'],+ ] as const,+ })+ )+ .when(+ (id) => id === 'inbox-document' || id === 'inbox-preview',+ () => inboxDocumentMapping+ ).with(CALENDAR_ROUTE_ID, () => ({namespace: CALENDAR_SEARCH_NAMESPACE,fields: [['eventId', 'eventId']] as const,diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.tsindex 4dfbe42db9..ea7cf50ab4 100644--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts@@ -3,10 +3,12 @@ import {agentsRouteSegments,} from '@app/features/agents-view/core/route';import { getPreferredCalendarPeriodView } from '@app/features/calendar/calendar-preferences';+import { isCalendarRange } from '@app/features/calendar-view/calendar-range';import {CALENDAR_ROUTE_ID,CALENDAR_SEARCH_NAMESPACE,calendarSearchCodec,+ calendarTargetSearch,} from '@app/features/calendar-view/calendar-url';import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';import type { DriveLocation } from '@app/features/drive-view/core/types';@@ -212,12 +214,22 @@ export function splitLocationFromContent((content.type === 'component' && content.id === CALENDAR_VIEW_ID) ||(content.type === 'calendar' && content.id === CALENDAR_BLOCK_ID)) {- const rawEventId = isRecord(content.params)- ? (content.params as Record<string, unknown>).eventId- : undefined;- const eventId =- typeof rawEventId === 'string' && rawEventId.length > 0 ? rawEventId : '';- const search = calendarSearchCodec.serialize({ eventId });+ const params: Record<string, unknown> = isRecord(content.params)+ ? content.params+ : {};+ const search = calendarSearchCodec.serialize(+ calendarTargetSearch({+ eventId:+ typeof params.eventId === 'string' && params.eventId.length > 0+ ? params.eventId+ : undefined,+ occurrenceKey:+ typeof params.occurrenceKey === 'string'+ ? params.occurrenceKey+ : undefined,+ range: isCalendarRange(params.range) ? params.range : undefined,+ })+ );return {route: {matches: [diff --git a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts b/apps/web/src/components/app/split-layout/tests/layoutManager.test.tsindex 58cc99e572..38a2296949 100644--- a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts+++ b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts@@ -1000,7 +1000,7 @@ describe('layoutManager', () => {messageId: ['explicit'],extra: ['keep'],});- expect(router.search(channel.id, 'channel-detail')).toEqual({+ expect(router.search(channel.id, 'channels')).toEqual({messageId: ['first', 'last'],threadId: ['thread'],});@@ -1017,6 +1017,74 @@ describe('layoutManager', () => {dispose();});+ it('migrates legacy channel targets on Inbox preview routes', async () => {+ const { manager, location, router, dispose } = ingressRouter(+ '/inbox/channel/c1?channel_message_id=first&channel_message_id=last&channel_thread_id=thread'+ );+ await router.settled();+ const split = manager.splits()[0];+ expect(router.search(split.id, 'channels')).toEqual({+ messageId: ['first', 'last'],+ threadId: ['thread'],+ });+ expect(+ new URLSearchParams(location.read().search).getAll(+ 's0.channels.messageId'+ )+ ).toEqual(['first', 'last']);+ router.dispose();+ dispose();+ });++ it.each([+ ['md', 'comment_id'],+ ['task', 'comment_id'],+ ['pdf', 'pdf_ann_id'],+ ['spreadsheet', 'comment_id'],+ ])(+ 'migrates unprefixed %s comments on Inbox document routes',+ async (type, key) => {+ const { manager, location, router, dispose } = ingressRouter(+ `/inbox/${type}/document-1?${key}=comment-1`+ );+ await router.settled();+ const split = manager.splits()[0];+ expect(router.search(split.id, 'drive')).toEqual({+ commentId: ['comment-1'],+ });+ expect(+ new URLSearchParams(location.read().search).get('s0.drive.commentId')+ ).toBe('comment-1');+ router.dispose();+ dispose();+ }+ );++ it('prefers an explicit Inbox document comment over an unprefixed key', async () => {+ const { manager, router, dispose } = ingressRouter(+ '/inbox/md/document-1?comment_id=legacy&s0.drive.commentId=explicit'+ );+ await router.settled();+ expect(router.search(manager.splits()[0].id, 'drive')).toEqual({+ commentId: ['explicit'],+ });+ router.dispose();+ dispose();+ });++ it('preserves Drive facets during comment link migration', async () => {+ const { manager, router, dispose } = ingressRouter(+ '/inbox/md/document-1?comment_id=comment-1&s0.drive.tags=first&s0.drive.tags=second'+ );+ await router.settled();+ expect(router.search(manager.splits()[0].id, 'drive')).toEqual({+ commentId: ['comment-1'],+ tags: ['first', 'second'],+ });+ router.dispose();+ dispose();+ });+it('applies a new-split location when an entity pane is reused', async () => {const { manager, router, dispose } = ingressRouter('/channel/one', {enabled: false,@@ -1028,7 +1096,7 @@ describe('layoutManager', () => {target: 'new-split',allowDuplicate: true,search: {- 'channel-detail': { messageId: ['second'] },+ channels: { messageId: ['second'] },},});await router.settled();@@ -1036,7 +1104,7 @@ describe('layoutManager', () => {expect(manager.splits()).toHaveLength(1);expect(manager.splits()[0].content.entryMetadata).toMatchObject({search: {- 'channel-detail': { messageId: ['second'] },+ channels: { messageId: ['second'] },},});router.dispose();diff --git a/apps/web/src/components/entity-detail/EntityDetail.tsx b/apps/web/src/components/entity-detail/EntityDetail.tsxindex 786baed04f..353ffae860 100644--- a/apps/web/src/components/entity-detail/EntityDetail.tsx+++ b/apps/web/src/components/entity-detail/EntityDetail.tsx@@ -28,17 +28,29 @@ import {} from '@app/features/drive-view/views/VideoDetail';import { getChannelEntityTarget } from '@app/features/next-soup/utils';import type { MarkdownDocumentKind } from '@block-md/types';-import { ChannelDetail } from '@channel/Channel/ChannelDetail';+import {+ ChannelDetail,+ type ChannelDetailContext,+ ChannelDetailTopBar,+} from '@channel/Channel/ChannelDetail';import type { ChannelTargetRequest } from '@channel/Channel/ChannelSurface';import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';import { PreviewPanel } from '@components/app/PreviewPanel';+import { previewBlockTarget } from '@components/app/previewTarget';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import type { BlockAlias, BlockName } from '@core/block';import { fileTypeToBlockName } from '@core/constant/allBlocks';-import { createMemo, type JSX, Match, Switch, untrack } from 'solid-js';+import {+ children,+ createMemo,+ type JSX,+ Match,+ Switch,+ untrack,+} from 'solid-js';import type { EntityDetailTarget } from './EntityDetailNavigationStack';-export type EntityDetailContext =+type DocumentDetailContext =| MarkdownDetailContext| CodeDetailContext| CanvasDetailContext@@ -47,21 +59,38 @@ export type EntityDetailContext =| PdfDetailContext| UnknownDetailContext;+export type EntityDetailContext =+ | ({ type: 'document' } & DocumentDetailContext)+ | ({ type: 'channel' } & ChannelDetailContext);+export type EntityDetailProps = {target: EntityDetailTarget;shareOpen?: boolean;onShareOpenChange?: (open: boolean) => void;previewHeaderLeading?: JSX.Element;+ navigationRequest?: number;children?: (context: EntityDetailContext) => JSX.Element;};+function ResolvedEntityDetailChildren(props: {+ render?: EntityDetailProps['children'];+ context: EntityDetailContext;+ fallback?: JSX.Element;+}) {+ const resolved = children(() => {+ if (props.render) return props.render(props.context);+ return props.fallback;+ });+ return <>{resolved()}</>;+}+function PreviewPanelEntityDetail(props: EntityDetailProps) {const orchestrator = useGlobalBlockOrchestrator();const panel = useSplitPanelOrThrow();return (<PreviewPanel- selectedEntity={props.target}+ target={previewBlockTarget(props.target)}orchestrator={orchestrator}splitPanelContext={panel}headerLeading={props.previewHeaderLeading}@@ -145,8 +174,12 @@ export function EntityDetail(props: EntityDetailProps) {const target = props.target;return untrack(() => channelDetailTarget(target));});- const renderChildren = (context: EntityDetailContext) =>- props.children?.(context);+ const renderChildren = (context: DocumentDetailContext) => (+ <ResolvedEntityDetailChildren+ render={props.children}+ context={{ type: 'document', ...context }}+ />+ );return (<Switch>@@ -231,8 +264,22 @@ export function EntityDetail(props: EntityDetailProps) {<ChannelDetailchannelId={channel().channelId}target={channel().target}+ navigationRequest={props.navigationRequest}fallbackName={channel().fallbackName}- />+ >+ {(context) => (+ <ResolvedEntityDetailChildren+ render={props.children}+ context={{ type: 'channel', ...context }}+ fallback={+ <ChannelDetailTopBar+ channelId={context.channelId}+ fallbackName={channel().fallbackName}+ />+ }+ />+ )}+ </ChannelDetail>)}</Match><Match when={true}>diff --git a/apps/web/src/components/entity-detail/EntityDetailNavigationStack.tsx b/apps/web/src/components/entity-detail/EntityDetailNavigationStack.tsxindex a79c64b3e0..c80cf90089 100644--- a/apps/web/src/components/entity-detail/EntityDetailNavigationStack.tsx+++ b/apps/web/src/components/entity-detail/EntityDetailNavigationStack.tsx@@ -7,7 +7,7 @@ import {useNavigationStack,} from '@app/components/navigation-stack/NavigationStack';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';-import type { PreviewPanelSelection } from '@components/app/PreviewPanel';+import type { PreviewPanelSelection } from '@components/app/previewTarget';import { isTouchDevice } from '@core/mobile/isTouchDevice';export type EntityDetailTarget = PreviewPanelSelection & {diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsxindex 4d4cb7ca98..bb49c1f032 100644--- a/apps/web/src/features/agents-view/views/AgentsView.tsx+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx@@ -9,6 +9,7 @@ import {useGlobalNotificationSource,} from '@components/app/GlobalAppState';import { PreviewPanel } from '@components/app/PreviewPanel';+import { previewBlockTarget } from '@components/app/previewTarget';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';@@ -347,7 +348,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {)}><PreviewPanel- selectedEntity={conversation}+ target={previewBlockTarget(conversation)}orchestrator={orchestrator}splitPanelContext={panel}headerLeading={diff --git a/apps/web/src/features/calendar-view/calendar-navigation.test.ts b/apps/web/src/features/calendar-view/calendar-navigation.test.tsindex 3786edb6ee..ed3cfb5126 100644--- a/apps/web/src/features/calendar-view/calendar-navigation.test.ts+++ b/apps/web/src/features/calendar-view/calendar-navigation.test.ts@@ -30,7 +30,9 @@ describe('Calendar view navigation', () => {},],},- search: { calendar: { eventId: ['event-1'] } },+ search: {+ calendar: { eventId: ['event-1'], occurrenceKey: ['instance-1'] },+ },},});});diff --git a/apps/web/src/features/calendar-view/calendar-navigation.ts b/apps/web/src/features/calendar-view/calendar-navigation.tsindex 73805db789..e994c29fdf 100644--- a/apps/web/src/features/calendar-view/calendar-navigation.ts+++ b/apps/web/src/features/calendar-view/calendar-navigation.ts@@ -11,6 +11,7 @@ import {CALENDAR_ROUTE_ID,CALENDAR_SEARCH_NAMESPACE,calendarSearchCodec,+ calendarTargetSearch,} from './calendar-url';import { CALENDAR_VIEW_ID, type CalendarViewTarget } from './types';@@ -29,7 +30,13 @@ export function calendarViewContent(typeof target.eventId === 'string' && target.eventId.length > 0? target.eventId: undefined;- const search = calendarSearchCodec.serialize({ eventId: eventId ?? '' });+ const search = calendarSearchCodec.serialize(+ calendarTargetSearch({+ eventId,+ occurrenceKey: target.occurrenceKey,+ range: target.range,+ })+ );const params: CalendarViewTarget | undefined = eventId? {eventId,diff --git a/apps/web/src/features/calendar-view/calendar-url.ts b/apps/web/src/features/calendar-view/calendar-url.tsindex e889c77e2a..8d1d17a792 100644--- a/apps/web/src/features/calendar-view/calendar-url.ts+++ b/apps/web/src/features/calendar-view/calendar-url.ts@@ -1,6 +1,8 @@import type { CalendarPeriodView } from '@app/features/calendar/types';import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';+import { createCalendarRange } from './calendar-range';+import type { CalendarViewTarget } from './types';export const CALENDAR_ROUTE_ID = 'view-calendar';export const CALENDAR_SEARCH_NAMESPACE = 'calendar';@@ -33,10 +35,51 @@ export function calendarFocusedEventSearchKey(splitIndex = 0): string {return `s${splitIndex}.${CALENDAR_SEARCH_NAMESPACE}.eventId`;}+/**+ * The focused event and the locator that pages the view to it. The locator+ * travels as local dates; the view rebuilds the day-bounded occurrence window+ * from them, so it can aim directly instead of resolving the event first.+ */export const calendarSearch = {namespace: CALENDAR_SEARCH_NAMESPACE,- schema: z.object({ eventId: z.string() }),- defaults: { eventId: '' },+ schema: z.object({+ eventId: z.string(),+ occurrenceKey: z.string(),+ startDate: z.string(),+ endDate: z.string(),+ }),+ defaults: { eventId: '', occurrenceKey: '', startDate: '', endDate: '' },};+export type CalendarSearchParams = z.infer<typeof calendarSearch.schema>;+export const calendarSearchCodec = createSearchParamsCodec(calendarSearch);++/** Search fields for a view target. */+export function calendarTargetSearch(+ target: CalendarViewTarget+): CalendarSearchParams {+ return {+ eventId: target.eventId ?? '',+ occurrenceKey: target.occurrenceKey ?? '',+ startDate: target.range?.startDate ?? '',+ endDate: target.range?.endDate ?? '',+ };+}++/** The view target a search carries. Dates that do not parse yield no range. */+export function calendarSearchTarget(+ search: CalendarSearchParams+): CalendarViewTarget {+ return {+ eventId: search.eventId || undefined,+ occurrenceKey: search.occurrenceKey || undefined,+ range: search.startDate+ ? createCalendarRange({+ kind: 'allDay',+ startDate: search.startDate,+ endDate: search.endDate || undefined,+ })+ : undefined,+ };+}diff --git a/apps/web/src/features/calendar-view/calendar-view.tsx b/apps/web/src/features/calendar-view/calendar-view.tsxindex 7ae042776e..a35610a117 100644--- a/apps/web/src/features/calendar-view/calendar-view.tsx+++ b/apps/web/src/features/calendar-view/calendar-view.tsx@@ -13,11 +13,20 @@ import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { LoadingBlock } from '@core/component/LoadingBlock';import { useUserId } from '@core/context/user';import { useCalendarOccurrencesQuery } from '@queries/calendar/occurrences';-import { createEffect, createMemo, on, onMount, Show } from 'solid-js';+import deepEqual from 'fast-deep-equal';+import {+ type Accessor,+ createEffect,+ createMemo,+ on,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';import { CalendarFocusContextProvider } from './calendar-focus-target';import { resolveCalendarTarget } from './calendar-target';import { createCalendarTargetAim } from './calendar-target-request';-import { calendarPath, calendarSearch } from './calendar-url';+import { calendarSearch, calendarSearchTarget } from './calendar-url';import { Workspace } from './components/Workspace';import { CALENDAR_VIEW_ID, type CalendarViewTarget } from './types';@@ -33,8 +42,15 @@ function nonEmpty(value: unknown): string | undefined {return typeof value === 'string' && value.length > 0 ? value : undefined;}-/** Route-backed Calendar application view. */-export function CalendarView() {+export type CalendarViewProps = {+ /** The route this view is mounted under; period changes navigate within it. */+ route: { id: string };+ /** A new value re-aims at the URL's event without a navigation. */+ refocus?: Accessor<unknown>;+};++/** Route-backed Calendar view, hosted by its own route or inline under another. */+export function CalendarView(props: CalendarViewProps) {const calendarUiEnabled = useCalendarUiFlag();const posthog = usePosthog();const userId = useUserId();@@ -43,7 +59,13 @@ export function CalendarView() {const navigate = useNavigate();const routeParams = useParams<{ period: CalendarPeriodView }>();const [search, setSearch] = createSearchParams(calendarSearch);- const routeEventId = () => nonEmpty(search.eventId);+ const routeTarget = createMemo(+ () => calendarSearchTarget(search),+ undefined,+ {+ equals: deepEqual,+ }+ );const contentTarget = createMemo<CalendarViewTarget>(() => {const content = panel.handle.content();if (content.type !== 'component' || content.id !== CALENDAR_VIEW_ID) {@@ -54,16 +76,71 @@ export function CalendarView() {const initialContentTarget = contentTarget();const initialAim: CalendarViewTarget = nonEmpty(initialContentTarget.eventId)? initialContentTarget- : { eventId: routeEventId() };+ : routeTarget();const aim = createCalendarTargetAim({ initial: initialAim });const targetRequest = aim.target;let initializedTargetSync = false;let locallyWrittenEventId: string | null = null;+ // The event an aim is paging toward. Paging closes open details, and that+ // transient close, like the landing itself, must not rewrite the URL the aim+ // came from: its locator is what makes a repeat request the same destination.+ let aimingEventId = nonEmpty(initialAim.eventId);+ const aimAt = (target: CalendarViewTarget) => {+ aimingEventId = nonEmpty(target.eventId);+ aim.aimAt(target);+ };+ // A period change closes the selected event in the pager. Home keeps the+ // event in search, so re-aim after the new period is committed to reopen it.+ createEffect(+ on(+ () => routeParams.period,+ (period, previousPeriod) => {+ if (+ !panel.isInlinePreview ||+ previousPeriod === undefined ||+ period === previousPeriod+ ) {+ return;+ }+ let cancelled = false;+ // The pager closes its selection after it changes the route. Re-aim+ // after that synchronous close, not at the old chip before it closes.+ queueMicrotask(() => {+ if (cancelled || routeParams.period !== period) return;+ const target = routeTarget();+ if (target.eventId) aimAt(target);+ });+ onCleanup(() => {+ cancelled = true;+ });+ }+ )+ );+ createEffect(+ on(+ () => props.refocus?.(),+ () => {+ const target = routeTarget();+ if (target.eventId) aimAt(target);+ },+ { defer: true }+ )+ );+ createEffect(+ on(+ targetRequest,+ (request) => {+ // An aim that resolves to nothing will never land.+ if (!request) aimingEventId = undefined;+ },+ { defer: true }+ )+ );createEffect(on(- [routeEventId, () => contentTarget().focusRequestId],- ([eventId, focusRequestId], previous) => {+ [routeTarget, () => contentTarget().focusRequestId],+ ([target, focusRequestId], previous) => {if (!initializedTargetSync) {initializedTargetSync = true;return;@@ -73,15 +150,15 @@ export function CalendarView() {focusRequestId !== undefined &&focusRequestId !== previousFocusRequestId) {- aim.aimAt(contentTarget());+ aimAt(contentTarget());return;}- if (eventId === previous?.[0]) return;- if (locallyWrittenEventId === (eventId ?? '')) {+ if (target === previous?.[0]) return;+ if (locallyWrittenEventId === (target.eventId ?? '')) {locallyWrittenEventId = null;return;}- aim.aimAt(eventId ? { eventId } : {});+ aimAt(target.eventId ? target : {});}));@@ -111,13 +188,24 @@ export function CalendarView() {const setFocusedEventId = (eventId: string | undefined) => {const next = eventId ?? '';+ if (aimingEventId !== undefined) {+ if (!next) return;+ const landed = next === aimingEventId;+ aimingEventId = undefined;+ if (landed) return;+ }+ // Inline, a dismissed popover is not a destination change: the host's+ // selection still names this event, and clearing it would make the next+ // request for the same event a navigation.+ if (!next && panel.isInlinePreview) return;if (search.eventId === next) return;locallyWrittenEventId = next;- setSearch({ eventId: next }, { history: 'replace' });+ // A locally focused event is already on screen; drop the locator with it.+ setSearch({ eventId: next }, { mode: 'replace', history: 'replace' });};const setPeriodView = (period: CalendarPeriodView) => {if (routeParams.period === period) return;- navigate(calendarPath(period));+ navigate({ route: props.route, params: { period } });};onMount(() => {@@ -137,7 +225,7 @@ export function CalendarView() {<CalendarFocusContextProvider target={focusTarget}><CalendarViewContextProviderperiodView={routeParams.period}- focusedEventId={routeEventId()}+ focusedEventId={routeTarget().eventId}onPeriodViewChange={setPeriodView}onFocusedEventIdChange={setFocusedEventId}>diff --git a/apps/web/src/features/calendar-view/components/Workspace.tsx b/apps/web/src/features/calendar-view/components/Workspace.tsxindex a2d2d79cc8..30f883fa97 100644--- a/apps/web/src/features/calendar-view/components/Workspace.tsx+++ b/apps/web/src/features/calendar-view/components/Workspace.tsx@@ -99,7 +99,10 @@ function WorkspaceContent() {const panel = useSplitPanelOrThrow();const calendarView = useCalendarView();- onMount(() => panel.handle.setDisplayName('Calendar'));+ // An inline preview keeps its host's name.+ onMount(() => {+ if (!panel.isInlinePreview) panel.handle.setDisplayName('Calendar');+ });return (<>diff --git a/apps/web/src/features/calendar-view/route.test.ts b/apps/web/src/features/calendar-view/route.test.tsdeleted file mode 100644index f1440dda50..0000000000--- a/apps/web/src/features/calendar-view/route.test.ts+++ /dev/null@@ -1,49 +0,0 @@-import {- createRoutesManifest,- decodeRoute,- encodeRoute,- getRouteClaim,- getRouteSearchNamespaces,- routeParams,-} from '@app/lib/split-router';-import { describe, expect, it } from 'vitest';-import { CALENDAR_SEARCH_NAMESPACE, calendarSearchCodec } from './calendar-url';-import { calendarSplitRoute } from './route';--const routes = createRoutesManifest({ definitions: [calendarSplitRoute] });--describe('Calendar split route', () => {- it.each([- ['month', 'dayGridMonth'],- ['week', 'timeGridWeek'],- ['day', 'timeGridDay'],- ] as const)('round-trips the %s period', (pathPeriod, period) => {- const entry = decodeRoute(routes, ['calendar', pathPeriod]);- expect(entry).toBeDefined();- expect(routeParams(entry?.location.route)).toEqual({ period });- expect(encodeRoute(routes, entry!)).toEqual(['calendar', pathPeriod]);- expect(getRouteSearchNamespaces(routes, entry!.location.route)).toEqual(- new Set([CALENDAR_SEARCH_NAMESPACE])- );- expect(getRouteClaim(routes, entry!.location.route)).toEqual({- namespace: 'component',- id: 'calendar',- });- });-- it('rejects missing and unknown periods', () => {- expect(decodeRoute(routes, ['calendar'])).toBeUndefined();- expect(decodeRoute(routes, ['calendar', 'agenda'])).toBeUndefined();- });-- it('serializes only a non-empty focused event id', () => {- expect(calendarSearchCodec.serialize({ eventId: '' })).toBeUndefined();- expect(calendarSearchCodec.serialize({ eventId: 'event-1' })).toEqual({- eventId: ['event-1'],- });- expect(calendarSearchCodec.parse({ eventId: ['event-1'] })).toEqual({- value: { eventId: 'event-1' },- valid: true,- });- });-});diff --git a/apps/web/src/features/calendar-view/route.tsx b/apps/web/src/features/calendar-view/route.tsxindex 67831dce67..4a49fa4f23 100644--- a/apps/web/src/features/calendar-view/route.tsx+++ b/apps/web/src/features/calendar-view/route.tsx@@ -13,7 +13,9 @@ const CalendarView = lazy(async () => ({default: (await import('./calendar-view')).CalendarView,}));-export const CalendarRouteView = withAuth(() => <CalendarView />);+export const CalendarRouteView = withAuth(() => (+ <CalendarView route={calendarSplitRoute} />+));export const calendarSplitRoute = defineRoute({id: CALENDAR_ROUTE_ID,diff --git a/apps/web/src/features/channel/Channel/ChannelDetail.tsx b/apps/web/src/features/channel/Channel/ChannelDetail.tsxindex 1f5fd673fe..d47aa47b06 100644--- a/apps/web/src/features/channel/Channel/ChannelDetail.tsx+++ b/apps/web/src/features/channel/Channel/ChannelDetail.tsx@@ -16,9 +16,12 @@ import { ENABLE_CALLS } from '@core/constant/featureFlags';import { useChannelName, useChannelType } from '@core/context/channels';import { useChannelParticipantsQuery } from '@queries/channel/channel-participants';import {+ type Accessor,+ children,createComputed,createMemo,createSignal,+ type JSX,Match,on,onCleanup,@@ -39,6 +42,11 @@ import {useChannelTabItems,} from './use-channel-tab-items';+export type ChannelDetailContext = {+ channelId: string;+ name: Accessor<string>;+};+export type ChannelDetailProps = {channelId: string;/**@@ -48,27 +56,61 @@ export type ChannelDetailProps = {* ChannelSurface directly.*/target?: ChannelTargetRequest;+ /** Re-aim the current target without remounting the channel. */+ navigationRequest?: number;/** Name shown until the channel loads. */fallbackName?: string;/** Whether the composer grabs focus on mount. Defaults to false. */autofocus?: boolean;+ /** Render the host's header and register any host-specific breadcrumbs. */+ children: (context: ChannelDetailContext) => JSX.Element;};-function ChannelDetailTopBar(props: {+type ChannelDetailHeaderProps = {channelId: string;fallbackName?: string;-}) {- const { activeTab, setActiveTab } = useChannelTab();- const tabs = useChannelTabItems(props.channelId);+};++export function ChannelDetailTitle(props: ChannelDetailHeaderProps) {const channelName = useChannelName(props.channelId, props.fallbackName);const channelType = useChannelType(props.channelId);const participantsQuery = useChannelParticipantsQuery(() => props.channelId);const participants = () =>participantsQuery.isSuccess ? (participantsQuery.data ?? []) : [];++ return (+ <div class="ph-no-capture flex min-w-0 shrink items-center gap-2">+ <ChannelTopIcon+ channelId={props.channelId}+ channelType={channelType()}+ participants={participants()}+ />+ <span class="truncate text-sm font-semibold">+ {channelName() ?? 'New Channel'}+ </span>+ </div>+ );+}++export function ChannelDetailTabs(props: { channelId: string }) {+ const { activeTab, setActiveTab } = useChannelTab();+ const tabs = useChannelTabItems(props.channelId);++ return (+ <TabsInset+ list={tabs()}+ value={activeTab()}+ onChange={(value) => setActiveTab(value as ChannelTabId)}+ />+ );+}++export function ChannelDetailActions(props: ChannelDetailHeaderProps) {+ const channelName = useChannelName(props.channelId, props.fallbackName);+ const channelType = useChannelType(props.channelId);const call = useCall(() => props.channelId);- // Seed for "Ask Macro": a new chat with this channel @mentioned, so the- // user does not have to create an agent and mention the channel by hand.+ // Seed for "Ask Macro": a new chat with this channel @mentioned.const askMacroEntity = () => {const type = channelType();if (!type) return undefined;@@ -80,56 +122,59 @@ function ChannelDetailTopBar(props: {};};+ return (+ <div class="ml-auto flex shrink-0 items-center gap-2">+ <ChannelLiveIndicators channelId={props.channelId} />+ <Show when={ENABLE_CALLS && !call.isInThisChannel()}>+ <ChannelCallButton channelId={props.channelId} />+ </Show>+ <Show when={askMacroEntity()}>+ {(entity) => (+ <ChatWithAgentButton entity={entity()} label="Ask Macro" />+ )}+ </Show>+ </div>+ );+}++export function ChannelDetailTopBar(props: ChannelDetailHeaderProps) {return (<ViewShell.TopBar class="gap-3">- <div class="ph-no-capture flex min-w-0 shrink items-center gap-2">- <ChannelTopIcon- channelId={props.channelId}- channelType={channelType()}- participants={participants()}- />- <span class="truncate text-sm font-semibold">- {channelName() ?? 'New Channel'}- </span>- </div>- <TabsInset- list={tabs()}- value={activeTab()}- onChange={(value) => setActiveTab(value as ChannelTabId)}- />- <div class="ml-auto flex shrink-0 items-center gap-2">- <ChannelLiveIndicators channelId={props.channelId} />- <Show when={ENABLE_CALLS && !call.isInThisChannel()}>- <ChannelCallButton channelId={props.channelId} />- </Show>- <Show when={askMacroEntity()}>- {(entity) => (- <ChatWithAgentButton entity={entity()} label="Ask Macro" />- )}- </Show>- </div>+ <ChannelDetailTitle {...props} />+ <ChannelDetailTabs channelId={props.channelId} />+ <ChannelDetailActions {...props} /></ViewShell.TopBar>);}+function ChannelDetailHeader(props: {+ render: ChannelDetailProps['children'];+ context: ChannelDetailContext;+}) {+ const resolved = children(() => props.render(props.context));+ return <>{resolved()}</>;+}+function ChannelDetailContent(props: ChannelDetailProps) {const panel = useSplitPanelOrThrow();const channelId = props.channelId;+ const channelName = useChannelName(channelId, props.fallbackName);// Convert the value-semantic target prop into identity-stable surface- // requests: only a changed value produces a new request object.+ // requests: only a changed target or explicit re-open produces a new request.let lastTargetKey: string | undefined;const targetRequest = createMemo<ChannelTargetRequest | undefined>((previous) => {const target = props.target;- const key = !target+ const location = !target? '': target.kind === 'latest'? 'latest': `${target.messageId}:${target.threadId ?? ''}`;+ const key = `${location}:${props.navigationRequest ?? 0}`;if (lastTargetKey !== undefined && key === lastTargetKey) return previous;lastTargetKey = key;- return target;+ return target ? { ...target } : undefined;});@@ -175,9 +220,12 @@ function ChannelDetailContent(props: ChannelDetailProps) {<CallEventSync /><ChannelTabProvider activeTab={activeTab} setActiveTab={setActiveTab}><div class="flex size-full min-h-0 flex-col">- <ChannelDetailTopBar- channelId={channelId}- fallbackName={props.fallbackName}+ <ChannelDetailHeader+ render={props.children}+ context={{+ channelId,+ name: () => channelName() ?? 'New Channel',+ }}/><div class="flex min-h-0 flex-1 flex-col px-2"><Switch>@@ -214,12 +262,10 @@ function ChannelDetailContent(props: ChannelDetailProps) {}/**- * Default channel detail composed from channel parts (surface, tabs, top-bar- * pieces) — the channel analogue of MarkdownDetail. Hosts needing a custom- * arrangement compose ChannelSurface and the parts directly instead.+ * Channel body and per-channel tab state. Hosts compose the top bar from the+ * exported header parts through the children callback.*- * Keys its content by channel id internally: the timeline, controllers, and- * tab state are per-channel by construction, so a channel switch remounts.+ * Keys its content by channel id so switching channels remounts the timeline.* Hosts pass a reactive `channelId` and never key their own render.*/export function ChannelDetail(props: ChannelDetailProps) {diff --git a/apps/web/src/features/channels-view/channels-route.ts b/apps/web/src/features/channels-view/channels-route.tsindex 5956c4da23..a3023c20a6 100644--- a/apps/web/src/features/channels-view/channels-route.ts+++ b/apps/web/src/features/channels-view/channels-route.ts@@ -2,31 +2,20 @@ import { createSearchParamsCodec } from '@app/lib/split-router';import { z } from 'zod';import type { ChannelsQueryScope, ChannelsTab } from './types';-export const channelsTabSearch = {+export const channelsSearch = {namespace: 'channels',schema: z.object({tab: z.enum(['browse', 'recents']),mobileTab: z.enum(['channels', 'direct_messages', 'recents']),+ messageId: z.string(),+ threadId: z.string(),}),defaults: {tab: 'browse' as ChannelsTab,mobileTab: 'channels' as ChannelsQueryScope,+ messageId: '',+ threadId: '',},};-export const channelsTabSearchCodec =- createSearchParamsCodec(channelsTabSearch);--export const CHANNEL_DETAIL_SEARCH_NAMESPACE = 'channel-detail';--export const channelDetailSearch = {- namespace: CHANNEL_DETAIL_SEARCH_NAMESPACE,- schema: z.object({- messageId: z.string(),- threadId: z.string(),- }),- defaults: { messageId: '', threadId: '' },-};--export const channelDetailSearchCodec =- createSearchParamsCodec(channelDetailSearch);+export const channelsSearchCodec = createSearchParamsCodec(channelsSearch);diff --git a/apps/web/src/features/channels-view/channels-view-context.test.tsx b/apps/web/src/features/channels-view/channels-view-context.test.tsxdeleted file mode 100644index e92ec4371b..0000000000--- a/apps/web/src/features/channels-view/channels-view-context.test.tsx+++ /dev/null@@ -1,296 +0,0 @@-import {- SplitRouter,- type SplitRouterLayout,- type SplitRouterLayoutEntry,- type SplitRouterSettledChange,- useSplitRouter,-} from '@app/lib/split-router';-import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';-import { appSplitRoutes } from '@components/app/split-layout/split-router/app-routes';-import { cleanup, render } from '@solidjs/testing-library';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import {- type ChannelsViewContext,- ChannelsViewProvider,- useChannelsView,-} from './channels-view-context';-import type { ChannelsViewStateOptions } from './types';--const entry = vi.hoisted(() => ({- state: {} as Record<string, unknown>,- captors: new Map<string, () => unknown>(),-}));-const touch = vi.hoisted(() => ({ value: false }));-const guard = vi.hoisted(() => ({- selections: [] as unknown[],- preflights: [] as unknown[],- allow: true,-}));--vi.mock('@core/context/user', () => ({ useUserId: () => () => 'alice' }));-vi.mock('@app/features/next-soup/utils', () => ({- getChannelEntityTarget: (channel: {- target?: { messageId: string; threadId?: string };- }) =>- channel.target- ? { kind: 'message', ...channel.target }- : { kind: 'latest' },-}));-vi.mock('@core/constant/allBlocks', () => ({- fileTypeToResolvedBlockName: (type: string) => type,- isBlockAlias: () => false,- resolveBlockAlias: (type: string) => type,-}));-vi.mock('@core/mobile/isTouchDevice', () => ({- isTouchDevice: () => touch.value,-}));-vi.mock('@components/app/createPreviewSelectionGuard', () => ({- createPreviewSelectionGuard: () => {- const select = (selection: unknown) => {- guard.selections.push(selection);- return selection === undefined || guard.allow;- };- return Object.assign(select, {- canSelect: (selection: unknown) => {- guard.preflights.push(selection);- return selection === undefined || guard.allow;- },- });- },-}));-vi.mock('@components/app/split-layout/layoutUtils', () => ({- useSplitPanelOrThrow: () => ({- handle: {- currentEntryState: () => entry.state,- registerEntryStateCaptor: (key: string, capture: () => unknown) => {- entry.captors.set(key, capture);- return () => entry.captors.delete(key);- },- },- }),-}));--function createLayout(): SplitRouterLayout<string> {- let current: SplitRouterLayoutEntry<string> | undefined;- const listeners = new Set<(change: SplitRouterSettledChange) => void>();- const notify = () => {- for (const listener of listeners) listener({ history: 'push' });- };- return {- snapshot: () => ({ entries: current ? [current] : [] }),- updateCurrentLocation(_splitId, update) {- if (!current) return;- current = { splitId: current.splitId, location: update(current) };- notify();- },- open: () => ({ status: 'unavailable' }),- reconcile(locations) {- const location = locations[0];- current = location ? { splitId: 'split', location } : undefined;- notify();- },- activate: () => {},- subscribe(listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },- };-}--function mountProvider(- path = '/channels',- initialState?: ChannelsViewStateOptions-) {- let context!: ChannelsViewContext;- let router!: ReturnType<typeof useSplitRouter<string>>;- const location = createMemorySplitRouterLocation(path);- function ReadContext() {- context = useChannelsView();- router = useSplitRouter<string>();- return null;- }- const view = render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={appSplitRoutes}- location={location}- >- <SplitRouter.Scope splitId="split">- <ChannelsViewProvider initialState={initialState}>- <ReadContext />- </ChannelsViewProvider>- </SplitRouter.Scope>- </SplitRouter.Root>- ));- return { ...view, context, location, router };-}--beforeEach(() => {- localStorage.clear();- entry.state = {};- entry.captors.clear();- touch.value = false;- guard.selections = [];- guard.preflights = [];- guard.allow = true;-});-afterEach(cleanup);--describe('ChannelsViewProvider route selection', () => {- it('takes desktop and mobile tabs from pane search, ahead of saved state', () => {- entry.state = { 'channels.view': { tab: 'browse', mobileTab: 'channels' } };- const { context } = mountProvider(- '/channels?s0.channels.tab=recents&s0.channels.mobileTab=direct_messages'- );- expect(context.state.tab).toBe('recents');- expect(context.state.mobileTab).toBe('direct_messages');- });-- it('normalizes invalid URL tabs to defaults without restoring stale tabs', async () => {- const { context, location, router } = mountProvider(- '/channels?s0.channels.tab=unknown'- );- await router.settled();- expect(context.state.tab).toBe('browse');- expect(location.read().search).toBe('');- });-- it('writes each tab to pane search and follows browser Back/Forward', async () => {- const { context, location, router } = mountProvider();- context.setTab('recents');- await router.settled();- expect(location.read().search).toContain('s0.channels.tab=recents');-- context.setMobileTab('direct_messages');- await router.settled();- expect(location.read().search).toContain(- 's0.channels.mobileTab=direct_messages'- );- expect(location.back()).toBe(true);- await router.settled();- expect(context.state.tab).toBe('recents');- expect(context.state.mobileTab).toBe('channels');- expect(location.forward()).toBe(true);- await router.settled();- expect(context.state.mobileTab).toBe('direct_messages');- });-- it('keeps tab search when entering and leaving inline detail', async () => {- const { context, location, router } = mountProvider(- '/channels?s0.channels.tab=recents'- );- context.setSelectedChannel({ type: 'channel', id: 'c1' });- await router.settled();- expect(location.read().pathname).toBe('/channels/c1');- expect(location.read().search).toContain('s0.channels.tab=recents');- context.setSelectedChannel(undefined);- await router.settled();- expect(location.read().pathname).toBe('/channels');- expect(location.read().search).toContain('s0.channels.tab=recents');- });-- it('persists collapsed labels per user and restores them', () => {- const storageKey = 'macro:channels:view-state:v1:alice';- const first = mountProvider();- first.context.setLabelOpen('enterprise', false);- first.context.setLabelOpen('smb', false);- first.context.setLabelOpen('enterprise', false);- expect(first.context.state.collapsedLabels).toEqual(['enterprise', 'smb']);- first.context.setLabelOpen('smb', true);- expect(first.context.state.collapsedLabels).toEqual(['enterprise']);- expect(JSON.parse(localStorage.getItem(storageKey)!)).toMatchObject({- collapsedLabels: ['enterprise'],- });- first.unmount();- const second = mountProvider();- expect(second.context.state.collapsedLabels).toEqual(['enterprise']);- });- it('derives accepted selection from a direct detail route', () => {- const { context } = mountProvider(- '/channels/c1?s0.channel-detail.messageId=m1&s0.channel-detail.threadId=t1'- );-- expect(context.selectedChannel()).toEqual({- type: 'channel',- id: 'c1',- target: { messageId: 'm1', threadId: 't1' },- });- expect(guard.selections.at(-1)).toEqual(context.selectedChannel());- });-- it('navigates with typed target search and closes explicitly to the list', async () => {- const { context, location, router } = mountProvider();-- expect(- context.setSelectedChannel({- type: 'channel',- id: 'c1',- target: { messageId: 'm1', threadId: 't1' },- })- ).toBe(true);- await router.settled();- expect(location.read()).toMatchObject({- pathname: '/channels/c1',- search: '?s0.channel-detail.messageId=m1&s0.channel-detail.threadId=t1',- });- expect(context.selectedChannel()?.id).toBe('c1');-- expect(context.setSelectedChannel(undefined)).toBe(true);- await router.settled();- expect(location.read().pathname).toBe('/channels');- expect(context.selectedChannel()).toBeUndefined();- });-- it('keeps the accepted route when compatibility preflight refuses a request', async () => {- const { context, location, router } = mountProvider('/channels/current');- guard.allow = false;-- expect(context.setSelectedChannel({ type: 'channel', id: 'blocked' })).toBe(- false- );- await router.settled();- expect(location.read().pathname).toBe('/channels/current');- expect(context.selectedChannel()?.id).toBe('current');- });-- it('replaces a directly loaded incompatible preview with the list route', async () => {- guard.allow = false;- const { context, location, router } = mountProvider('/channels/blocked');-- await router.settled();- expect(location.read().pathname).toBe('/channels');- expect(context.selectedChannel()).toBeUndefined();- });-- it('does not route touch selections through the inline preview', async () => {- touch.value = true;- const { context, location, router } = mountProvider();-- expect(context.setSelectedChannel({ type: 'channel', id: 'c1' })).toBe(- false- );- await router.settled();- expect(context.mobileLayout()).toBe(true);- expect(location.read().pathname).toBe('/channels');- expect(guard.preflights).toEqual([]);- });-- it('does not restore the removed selected-id preference', () => {- const saved = {- selectedChannelId: 'stale',- expandedGroups: { channels: false },- };- entry.state = { 'channels.view': saved };- localStorage.setItem(- 'macro:channels:view-state:v1:alice',- JSON.stringify(saved)- );- const { context } = mountProvider();-- expect(context.selectedChannel()).toBeUndefined();- expect(context.state.expandedGroups.channels).toBe(false);- expect(entry.captors.get('channels.view')?.()).not.toHaveProperty(- 'selectedChannelId'- );- });-});diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsxindex b8bdeef8f6..d93c2ee8e7 100644--- a/apps/web/src/features/channels-view/channels-view-context.tsx+++ b/apps/web/src/features/channels-view/channels-view-context.tsx@@ -16,13 +16,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { ContextProviderProps } from '@solid-primitives/context';import { type Accessor, createEffect, createMemo, on } from 'solid-js';import { createStore, type Store } from 'solid-js/store';-import {- CHANNEL_DETAIL_SEARCH_NAMESPACE,- channelDetailSearch,- channelDetailSearchCodec,- channelsTabSearch,- channelsTabSearchCodec,-} from './channels-route';+import { channelsSearch, channelsSearchCodec } from './channels-route';import {CHANNELS_DEFAULT_RAIL_WIDTH,CHANNELS_DEFAULT_SORT_BY,@@ -96,8 +90,7 @@ export const [ChannelsViewProvider, useChannelsView] =const userId = useUserId();const navigate = useNavigate();const params = useRouteParams(channelDetailRoute);- const [detailSearch] = createSearchParams(channelDetailSearch);- const [tabSearch, setTabSearch] = createSearchParams(channelsTabSearch);+ const [search, setSearch] = createSearchParams(channelsSearch);const selectPreview = createPreviewSelectionGuard();const initial = props.initialState ?? {};const [state, setState] = makePersistedState(@@ -113,7 +106,7 @@ export const [ChannelsViewProvider, useChannelsView] =createEffect(on(- () => [tabSearch.tab, tabSearch.mobileTab] as const,+ () => [search.tab, search.mobileTab] as const,([tab, mobileTab]) => {if (state.tab !== tab) setState('tab', tab);if (state.mobileTab !== mobileTab) setState('mobileTab', mobileTab);@@ -126,12 +119,10 @@ export const [ChannelsViewProvider, useChannelsView] =() => {const channelId = params.channelId;if (typeof channelId !== 'string') return undefined;- const target = detailSearch.messageId+ const target = search.messageId? {- messageId: detailSearch.messageId,- ...(detailSearch.threadId- ? { threadId: detailSearch.threadId }- : {}),+ messageId: search.messageId,+ ...(search.threadId ? { threadId: search.threadId } : {}),}: undefined;return {@@ -141,13 +132,15 @@ export const [ChannelsViewProvider, useChannelsView] =};});- const routeSearch = (channel: ChannelPreviewSelection) => {- const target = getChannelEntityTarget(channel);- const value = {+ const routeSearch = (channel?: ChannelPreviewSelection) => {+ const target = channel && getChannelEntityTarget(channel);+ return channelsSearchCodec.serialize({+ ...channelsSearch.defaults,+ tab: state.tab,+ mobileTab: state.mobileTab,messageId: target?.kind === 'message' ? target.messageId : '',threadId: target?.kind === 'message' ? (target.threadId ?? '') : '',- };- return channelDetailSearchCodec.serialize(value);+ });};const navigateToChannel = (channel: ChannelPreviewSelection,@@ -159,13 +152,7 @@ export const [ChannelsViewProvider, useChannelsView] ={ route: channelDetailRoute, params: { channelId } },{replace,- search: {- [CHANNEL_DETAIL_SEARCH_NAMESPACE]: routeSearch(channel),- [channelsTabSearch.namespace]: channelsTabSearchCodec.serialize({- tab: state.tab,- mobileTab: state.mobileTab,- }),- },+ search: { [channelsSearch.namespace]: routeSearch(channel) },});};@@ -175,16 +162,7 @@ export const [ChannelsViewProvider, useChannelsView] =if (!channel) {navigate({ route: channelsSplitRoute, params: {} },- {- search: {- [channelsTabSearch.namespace]: channelsTabSearchCodec.serialize(- {- tab: state.tab,- mobileTab: state.mobileTab,- }- ),- },- }+ { search: { [channelsSearch.namespace]: routeSearch() } });return true;}@@ -202,13 +180,7 @@ export const [ChannelsViewProvider, useChannelsView] ={ route: channelsSplitRoute, params: {} },{replace: true,- search: {- [channelsTabSearch.namespace]:- channelsTabSearchCodec.serialize({- tab: state.tab,- mobileTab: state.mobileTab,- }),- },+ search: { [channelsSearch.namespace]: routeSearch() },});}@@ -222,12 +194,12 @@ export const [ChannelsViewProvider, useChannelsView] =setTab: (tab) => {if (state.tab === tab) return;setState('tab', tab);- setTabSearch({ tab });+ setSearch({ tab });},setMobileTab: (mobileTab) => {if (state.mobileTab === mobileTab) return;setState('mobileTab', mobileTab);- setTabSearch({ mobileTab });+ setSearch({ mobileTab });},setSelectedChannel,setGroupOpen: (group, open) => setState('expandedGroups', group, open),diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsxindex edd90b7895..82fd482aa9 100644--- a/apps/web/src/features/channels-view/channels-view.test.tsx+++ b/apps/web/src/features/channels-view/channels-view.test.tsx@@ -39,6 +39,7 @@ vi.mock('@app/components/view-shell', () => ({},}));vi.mock('@app/features/next-soup/utils', () => ({+ getChannelEntityTarget: () => undefined,markChannelNotificationsSeenOnOpen: mocks.markRead,}));vi.mock('@app/features/soup', () => ({@@ -55,9 +56,9 @@ vi.mock('@components/app/GlobalAppState', () => ({useGlobalNotificationSource: () => ({}),}));vi.mock('@components/app/PreviewPanel', () => ({- PreviewPanel: (props: { selectedEntity: ChannelEntity }) => (- <div data-testid="preview">- {props.selectedEntity.id}+ PreviewPanel: (props: { target: { blockId: string } }) => (+ <div data-testid="legacy-preview">+ {props.target.blockId}<textarea aria-label="Composer" /></div>),@@ -75,7 +76,7 @@ vi.mock(vi.mock('@entity', () => ({ ListEntityMetadataQueryProvider: mocks.pass }));vi.mock('./components/ChannelDetailView', () => ({ChannelDetailView: (props: { channel: ChannelEntity }) => (- <div data-testid="preview">+ <div data-testid="channel-detail">{props.channel.id}<textarea aria-label="Composer" /></div>@@ -212,7 +213,7 @@ describe('channel selection loading and recovery', () => {setQuery('data', { entities: [full('one', ['new'])] });setQuery('isFetching', false);});- expect(screen.getByTestId('preview').textContent).toBe('one');+ expect(screen.getByTestId('channel-detail').textContent).toBe('one');expect(mocks.markRead).toHaveBeenCalledOnce();});diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.tsxindex 0fa76ca403..775d1393ca 100644--- a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx@@ -1,5 +1,8 @@import { getChannelEntityTarget } from '@app/features/next-soup/utils';-import { ChannelDetail } from '@channel/Channel/ChannelDetail';+import {+ ChannelDetail,+ ChannelDetailTopBar,+} from '@channel/Channel/ChannelDetail';import type { ChannelTargetRequest } from '@channel/Channel/ChannelSurface';import type { ChannelEntity } from '@entity';import { createMemo } from 'solid-js';@@ -36,6 +39,13 @@ export function ChannelDetailView(props: { channel: ChannelEntity }) {target={target()}fallbackName={props.channel.name}autofocus={false}- />+ >+ {(channel) => (+ <ChannelDetailTopBar+ channelId={channel.channelId}+ fallbackName={props.channel.name}+ />+ )}+ </ChannelDetail>);}diff --git a/apps/web/src/features/channels-view/route.tsx b/apps/web/src/features/channels-view/route.tsxindex 4fe2ba6bba..9c8a471996 100644--- a/apps/web/src/features/channels-view/route.tsx+++ b/apps/web/src/features/channels-view/route.tsx@@ -13,7 +13,7 @@ import {import { lazy, Show } from 'solid-js';import { z } from 'zod';import { getViewPreset } from '../next-soup/sidebar/soup-filter-presets';-import { channelDetailSearch } from './channels-route';+import { channelsSearch } from './channels-route';const SoupView = lazy(async () => ({default: (await import('../next-soup/soup-view/soup-view')).SoupView,@@ -39,7 +39,7 @@ function LegacyChannelsView() {function ChannelsLegacyRouteView() {const params = useParams<{ channelId?: string }>();- const [search] = createSearchParams(channelDetailSearch);+ const [search] = createSearchParams(channelsSearch);const legacyChannel = (id: string): SplitContent => {const params: Record<string, string> = {};if (search.messageId) params[CHANNEL_URL_PARAMS.message] = search.messageId;diff --git a/apps/web/src/features/drive-view/components/DriveDetailView.tsx b/apps/web/src/features/drive-view/components/DriveDetailView.tsxindex 299fe43d51..21eee54fbf 100644--- a/apps/web/src/features/drive-view/components/DriveDetailView.tsx+++ b/apps/web/src/features/drive-view/components/DriveDetailView.tsx@@ -176,6 +176,7 @@ function StackEntityDetail(props: {}>{(context) => {+ if (context.type !== 'document') return null;return (<FileDetailBreadcrumbItemvalue={props.entry.value}diff --git a/apps/web/src/features/drive-view/primitives/drive-route-state.ts b/apps/web/src/features/drive-view/primitives/drive-route-state.tsindex e86d885db1..081fa70976 100644--- a/apps/web/src/features/drive-view/primitives/drive-route-state.ts+++ b/apps/web/src/features/drive-view/primitives/drive-route-state.ts@@ -22,12 +22,8 @@ import {} from 'solid-js';import type { DriveLocation, DriveState } from '../core/types';import { driveDestination } from '../drive-route-navigation';-import {- type DriveRouteParams,- type DriveSearchParams,- driveLocationFromParams,- driveSearch,-} from './drive-route';+import { type DriveRouteParams, driveLocationFromParams } from './drive-route';+import { type DriveSearchParams, driveSearch } from './drive-search';type NavigationOptions = Pick<SplitNavigateOptions<unknown>,@@ -90,6 +86,7 @@ const routeSearch = ({scope,sort,facets: normalizeFacetSelection(facets),+ commentId: '',});/** Restored entry state supplies UI state; the current URL always wins selection. */diff --git a/apps/web/src/features/drive-view/primitives/drive-route.ts b/apps/web/src/features/drive-view/primitives/drive-route.tsindex 9124158a56..3aa4e17d04 100644--- a/apps/web/src/features/drive-view/primitives/drive-route.ts+++ b/apps/web/src/features/drive-view/primitives/drive-route.ts@@ -1,14 +1,4 @@-import {- deserializeFacetSelection,- normalizeFacetSelection,-} from '@app/features/soup/filters/facets/selection';-import {- type CreateSearchParamsOptions,- isSafeName,- type SerializedSearchParams,- type SplitRouteParams,- takeLast,-} from '@app/split-router';+import type { SplitRouteParams } from '@app/split-router';import { fileTypeToBlockName } from '@core/constant/allBlocks';import { z } from 'zod';import type { DriveLocation, DriveTab } from '../core/types';@@ -76,52 +66,3 @@ export function driveDocumentFromContent(content: {const type = documentType.safeParse(fileTypeToBlockName(content.type)).data;return type ? { id: content.id, type } : undefined;}--const searchSchema = z.object({- scope: z.enum(['default', 'all', 'attachments']),- sort: z.enum(['updated_at', 'created_at', 'viewed_at']),- facets: z.record(z.string(), z.array(z.string())),-});-export type DriveSearchParams = z.infer<typeof searchSchema>;-const reservedSearchFields = new Set(['scope', 'sort', 'facets']);--export const driveSearch = {- namespace: 'drive',- schema: searchSchema,- defaults: {- scope: 'default',- sort: 'updated_at',- facets: {},- } as DriveSearchParams,- serialize(value, { defaults }): SerializedSearchParams | undefined {- const params: SerializedSearchParams = {};- if (value.scope !== defaults.scope) params.scope = [value.scope];- if (value.sort !== defaults.sort) params.sort = [value.sort];- for (const [field, values] of Object.entries(- normalizeFacetSelection(value.facets)- )) {- if (isSafeName(field) && !reservedSearchFields.has(field))- params[field] = values;- }- return Object.keys(params).length ? params : undefined;- },- deserialize(params) {- const scope = takeLast(params.scope);- const sort = takeLast(params.sort);- const legacy = takeLast(params.facets);- const facets =- legacy === undefined ? {} : deserializeFacetSelection(legacy);- for (const [field, values] of Object.entries(params)) {- if (!reservedSearchFields.has(field)) facets[field] = values;- }- return {- ...(scope === undefined- ? {}- : { scope: scope as DriveSearchParams['scope'] }),- ...(sort === undefined- ? {}- : { sort: sort as DriveSearchParams['sort'] }),- facets: normalizeFacetSelection(facets),- };- },-} satisfies CreateSearchParamsOptions<DriveSearchParams>;diff --git a/apps/web/src/features/drive-view/primitives/drive-search.ts b/apps/web/src/features/drive-view/primitives/drive-search.tsnew file mode 100644index 0000000000..e25204c6c6--- /dev/null+++ b/apps/web/src/features/drive-view/primitives/drive-search.ts@@ -0,0 +1,70 @@+import {+ deserializeFacetSelection,+ normalizeFacetSelection,+} from '@app/features/soup/filters/facets/selection';+import {+ type CreateSearchParamsOptions,+ createSearchParamsCodec,+ isSafeName,+ type SerializedSearchParams,+ takeLast,+} from '@app/split-router';+import { z } from 'zod';++const searchSchema = z.object({+ scope: z.enum(['default', 'all', 'attachments']),+ sort: z.enum(['updated_at', 'created_at', 'viewed_at']),+ facets: z.record(z.string(), z.array(z.string())),+ commentId: z.string(),+});+export type DriveSearchParams = z.infer<typeof searchSchema>;+const reservedSearchFields = new Set(['scope', 'sort', 'facets', 'commentId']);++export const driveSearch = {+ namespace: 'drive',+ schema: searchSchema,+ defaults: {+ scope: 'default',+ sort: 'updated_at',+ facets: {},+ commentId: '',+ } as DriveSearchParams,+ serialize(value, { defaults }): SerializedSearchParams | undefined {+ const params: SerializedSearchParams = {};+ if (value.scope !== defaults.scope) params.scope = [value.scope];+ if (value.sort !== defaults.sort) params.sort = [value.sort];+ if (value.commentId !== defaults.commentId)+ params.commentId = [value.commentId];+ for (const [field, values] of Object.entries(+ normalizeFacetSelection(value.facets)+ )) {+ if (isSafeName(field) && !reservedSearchFields.has(field))+ params[field] = values;+ }+ return Object.keys(params).length ? params : undefined;+ },+ deserialize(params) {+ const scope = takeLast(params.scope);+ const sort = takeLast(params.sort);+ const commentId = takeLast(params.commentId);+ const legacy = takeLast(params.facets);+ const facets: Record<string, string[]> =+ legacy === undefined ? {} : deserializeFacetSelection(legacy);+ delete facets.commentId;+ for (const [field, values] of Object.entries(params)) {+ if (!reservedSearchFields.has(field)) facets[field] = values;+ }+ return {+ ...(scope === undefined+ ? {}+ : { scope: scope as DriveSearchParams['scope'] }),+ ...(sort === undefined+ ? {}+ : { sort: sort as DriveSearchParams['sort'] }),+ ...(commentId === undefined ? {} : { commentId }),+ facets: normalizeFacetSelection(facets),+ };+ },+} satisfies CreateSearchParamsOptions<DriveSearchParams>;++export const driveSearchCodec = createSearchParamsCodec(driveSearch);diff --git a/apps/web/src/features/inbox-view/components/HomeReturnBreadcrumb.tsx b/apps/web/src/features/inbox-view/components/HomeReturnBreadcrumb.tsxnew file mode 100644index 0000000000..5837fda944--- /dev/null+++ b/apps/web/src/features/inbox-view/components/HomeReturnBreadcrumb.tsx@@ -0,0 +1,15 @@+import { ViewBreadcrumbs } from '@app/components/view-shell';++export function HomeReturnBreadcrumb(props: { onReturn: () => void }) {+ return (+ <nav aria-label="Home location" class="flex items-center gap-0.5">+ <ViewBreadcrumbs.ReturnButton+ data-allow-focus-in-preview+ onClick={props.onReturn}+ >+ Home+ </ViewBreadcrumbs.ReturnButton>+ <ViewBreadcrumbs.Separator />+ </nav>+ );+}diff --git a/apps/web/src/features/inbox-view/components/InboxEntityDetailRouteView.tsx b/apps/web/src/features/inbox-view/components/InboxEntityDetailRouteView.tsxnew file mode 100644index 0000000000..1fc77a062b--- /dev/null+++ b/apps/web/src/features/inbox-view/components/InboxEntityDetailRouteView.tsx@@ -0,0 +1,206 @@+import { EntityDetail } from '@app/components/entity-detail/EntityDetail';+import type { EntityDetailTarget } from '@app/components/entity-detail/EntityDetailNavigationStack';+import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';+import { useParams } from '@app/lib/split-router';+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';+import {+ ChannelDetailActions,+ ChannelDetailTabs,+} from '@channel/Channel/ChannelDetail';+import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';+import { PreviewPanel } from '@components/app/PreviewPanel';+import type { PreviewBlockTarget } from '@components/app/previewTarget';+import { SidePanel } from '@components/app/side-panel';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { type Accessor, createMemo, Match, Show, Switch } from 'solid-js';+import { isInboxDocumentType } from '../inbox-route-schema';+import { useInboxView } from '../inbox-view-context';+import { HomeReturnBreadcrumb } from './HomeReturnBreadcrumb';++type DetailParams = {+ channelId?: string;+ documentType?: string;+ documentId?: string;+};++/** The shared details that can render without a legacy block instance. */+function entityDetailTarget(+ params: DetailParams,+ preview: PreviewBlockTarget | undefined+): EntityDetailTarget | undefined {+ if (!preview) return;+ if (params.channelId && preview.blockType === 'channel') {+ const location = preview.params as Record<string, unknown> | undefined;+ const messageId = location?.[CHANNEL_URL_PARAMS.message];+ const threadId = location?.[CHANNEL_URL_PARAMS.thread];+ return {+ type: 'channel',+ id: params.channelId,+ ...(typeof messageId === 'string'+ ? {+ target: {+ messageId,+ ...(typeof threadId === 'string' ? { threadId } : {}),+ },+ }+ : {}),+ };+ }++ const { documentType, documentId } = params;+ if (+ !documentType ||+ !documentId ||+ !isInboxDocumentType(documentType) ||+ documentType === 'spreadsheet' ||+ documentType === 'unknown' ||+ preview.params+ ) {+ // The shared file details do not yet navigate to document comments.+ return;+ }+ const subType =+ documentType === 'task' ||+ documentType === 'snippet' ||+ documentType === 'skill'+ ? { type: documentType }+ : undefined;+ return {+ type: 'document',+ id: documentId,+ fileType: subType ? 'md' : documentType === 'csv' ? 'code' : documentType,+ ...(subType ? { subType } : {}),+ };+}++function InboxEntityDetailBody(props: {+ target: EntityDetailTarget;+ value: Accessor<string>;+ navigationRequest: number;+}) {+ return (+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">+ <Show when={props.target.type !== 'channel'}>+ <ViewShell.TopBar>+ <ViewBreadcrumbs.Outlet aria-label="Home location" />+ <div class="ml-auto">+ <SidePanel.Toggle />+ </div>+ </ViewShell.TopBar>+ </Show>+ <div class="relative min-h-0 min-w-0 flex-1">+ <EntityDetail+ target={props.target}+ navigationRequest={props.navigationRequest}+ >+ {(context) => {+ const name = () => {+ switch (context.type) {+ case 'channel':+ return context.name();+ case 'document':+ return context.documentMetadata.documentName;+ }+ };+ const channel = () =>+ context.type === 'channel' ? context : undefined;++ return (+ <>+ <ViewBreadcrumbs.Item+ value={props.value()}+ metadata={props.target}+ order={1}+ >+ {(item) => (+ <ViewBreadcrumbs.Button+ isActive={item.isActive()}+ onClick={item.onSelect}+ tooltip={name()}+ >+ <span class="truncate">{name()}</span>+ </ViewBreadcrumbs.Button>+ )}+ </ViewBreadcrumbs.Item>+ <Show when={channel()}>+ {(current) => (+ <ViewShell.TopBar class="gap-3">+ <ViewBreadcrumbs.Outlet aria-label="Channel location" />+ <ChannelDetailTabs channelId={current().channelId} />+ <ChannelDetailActions channelId={current().channelId} />+ </ViewShell.TopBar>+ )}+ </Show>+ </>+ );+ }}+ </EntityDetail>+ </div>+ </div>+ );+}++function InboxDirectDetail(props: {+ target: EntityDetailTarget;+ closePreview: () => void;+ navigationRequest: number;+}) {+ const value = () => `${props.target.type}:${props.target.id}`;++ return (+ <ViewBreadcrumbs.Root+ value={value()}+ onChange={(next) => {+ if (next === 'home') props.closePreview();+ }}+ >+ <ViewBreadcrumbs.Item value="home" metadata={null} order={0}>+ {(item) => (+ <ViewBreadcrumbs.ReturnButton onClick={item.onSelect}>+ Home+ </ViewBreadcrumbs.ReturnButton>+ )}+ </ViewBreadcrumbs.Item>+ <SidePanel.Root>+ <InboxEntityDetailBody+ target={props.target}+ value={value}+ navigationRequest={props.navigationRequest}+ />+ </SidePanel.Root>+ </ViewBreadcrumbs.Root>+ );+}++/** Home's typed channel and document routes; unsupported locations keep the block preview. */+export function InboxEntityDetailRouteView() {+ const params = useParams<DetailParams>();+ const panel = useSplitPanelOrThrow();+ const orchestrator = useGlobalBlockOrchestrator();+ const { previewTarget, previewNavigationRequest, closePreview } =+ useInboxView();+ const detail = createMemo(() => entityDetailTarget(params, previewTarget()));++ return (+ <Switch>+ <Match when={detail()}>+ {(target) => (+ <InboxDirectDetail+ target={target()}+ closePreview={closePreview}+ navigationRequest={previewNavigationRequest()}+ />+ )}+ </Match>+ <Match when={true}>+ <PreviewPanel+ target={previewTarget()}+ navigationRequest={previewNavigationRequest()}+ orchestrator={orchestrator}+ splitPanelContext={panel}+ headerLeading={<HomeReturnBreadcrumb onReturn={closePreview} />}+ />+ </Match>+ </Switch>+ );+}diff --git a/apps/web/src/features/inbox-view/components/InboxList.tsx b/apps/web/src/features/inbox-view/components/InboxList.tsxindex 70963bd074..e062379e01 100644--- a/apps/web/src/features/inbox-view/components/InboxList.tsx+++ b/apps/web/src/features/inbox-view/components/InboxList.tsx@@ -23,7 +23,7 @@ import { makePersistedState } from '@app/lib/persistence';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { PullToRefresh } from '@components/app/mobile/PullToRefresh';import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';-import type { PreviewPanelSelection } from '@components/app/previewTarget';+import type { PreviewSelection } from '@components/app/previewTarget';import {useSplitPanelOrThrow,withSplitPanelOwner,@@ -89,8 +89,8 @@ type InboxListActivationMetadata = {};type InboxListProps = {- previewEntity: PreviewPanelSelection | undefined;- onPreviewEntityChange: (entity: PreviewPanelSelection | undefined) => void;+ hasPreview: boolean;+ onPreviewEntityChange: (entity: PreviewSelection | undefined) => void;onPreviewActivate?: () => void;};@@ -277,7 +277,7 @@ export function InboxList(props: InboxListProps) {const createActionNavigationHandler = ():| EntityActionNavigationHandler| undefined => {- if (props.previewEntity === undefined) return;+ if (!props.hasPreview) return;return ({ entity }) => {previewAfterNavigation.clear();diff --git a/apps/web/src/features/inbox-view/inbox-calendar-preview.ts b/apps/web/src/features/inbox-view/inbox-calendar-preview.tsnew file mode 100644index 0000000000..ba5555edad--- /dev/null+++ b/apps/web/src/features/inbox-view/inbox-calendar-preview.ts@@ -0,0 +1,58 @@+import {+ calendarSearch,+ calendarSearchTarget,+ calendarTargetSearch,+} from '@app/features/calendar-view/calendar-url';+import type { CalendarPreviewSelection } from '@app/features/next-soup/utils';+import {+ createSearchParams,+ type SerializedSearchParams,+ useNavigate,+ useRouteParams,+} from '@app/lib/split-router';+import { previewCalendarTarget } from '@components/app/previewTarget';+import {+ enableCalendarUi,+ isFeatureEnabled,+} from '@core/constant/featureFlags';+import deepEqual from 'fast-deep-equal';+import { createSignal } from 'solid-js';+import { inboxCalendarNavigation } from './inbox-preview-navigation';+import { inboxCalendarRoute } from './route';++type WithTab = (+ search: Record<string, SerializedSearchParams | undefined>+) => Record<string, SerializedSearchParams | undefined>;++/** Owns Home's inline Calendar location and repeat-click event refocus. */+export function useInboxCalendarPreview(withTab: WithTab) {+ const navigate = useNavigate();+ const calendarParams = useRouteParams(inboxCalendarRoute);+ const [openCalendarSearch] = createSearchParams(calendarSearch);+ const [calendarRefocus, setCalendarRefocus] = createSignal(0);+ const calendarOpen = () => typeof calendarParams.period === 'string';++ const openCalendarEvent = (entity: CalendarPreviewSelection) => {+ if (!isFeatureEnabled(enableCalendarUi)) return false;+ const calendarTarget = previewCalendarTarget(entity);+ const navigation = inboxCalendarNavigation(calendarTarget);+ if (!navigation) return false;+ const alreadyOpen =+ calendarOpen() &&+ calendarParams.period === navigation.params.period &&+ deepEqual(+ calendarTargetSearch(calendarTarget),+ calendarTargetSearch(calendarSearchTarget(openCalendarSearch))+ );+ // The same URL still needs to refocus the event in the inline calendar.+ if (alreadyOpen) setCalendarRefocus((count) => count + 1);+ else+ navigate(+ { route: inboxCalendarRoute, params: navigation.params },+ { search: withTab(navigation.search) }+ );+ return true;+ };++ return { calendarOpen, calendarRefocus, openCalendarEvent };+}diff --git a/apps/web/src/features/inbox-view/inbox-preview-navigation.ts b/apps/web/src/features/inbox-view/inbox-preview-navigation.tsindex 9aa952f019..4e5b63eadf 100644--- a/apps/web/src/features/inbox-view/inbox-preview-navigation.ts+++ b/apps/web/src/features/inbox-view/inbox-preview-navigation.ts@@ -1,131 +1,126 @@+import { getPreferredCalendarPeriodView } from '@app/features/calendar/calendar-preferences';+import type { CalendarPeriodView } from '@app/features/calendar/types';import {- calendarEventTimeForEntity,- getChannelEntityTarget,- getDocumentCommentTarget,-} from '@app/features/next-soup/utils';-import type { CalendarBlockProps } from '@block-calendar/types';+ CALENDAR_SEARCH_NAMESPACE,+ calendarSearchCodec,+ calendarTargetSearch,+} from '@app/features/calendar-view/calendar-url';+import type { CalendarViewTarget } from '@app/features/calendar-view/types';import {+ channelsSearch,+ channelsSearchCodec,+} from '@app/features/channels-view/channels-route';+import {+ driveSearch,+ driveSearchCodec,+} from '@app/features/drive-view/primitives/drive-search';+import type { SerializedSearchParams } from '@app/lib/split-router';+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';+import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';+import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';+import {+ type PreviewBlockTarget,type PreviewPanelSelection,previewBlockTarget,} from '@components/app/previewTarget';-import {- type InboxPreviewSearchParams,- inboxPreviewSearch,-} from './inbox-route';import type { InboxPreviewRouteParams } from './inbox-route-schema';-function calendarSearch(- params: CalendarBlockProps | undefined,- selection: Extract<PreviewPanelSelection, { type: 'calendar_event' }>-): Partial<InboxPreviewSearchParams> {- const range = params?.range;- const time = calendarEventTimeForEntity(selection);+type DetailSearch = Record<string, SerializedSearchParams | undefined>;++export type InboxPreviewNavigation = {+ params: InboxPreviewRouteParams;+ search: DetailSearch;+};++export type InboxCalendarNavigation = {+ params: { period: CalendarPeriodView };+ search: DetailSearch;+};++/** Every detail namespace is written so a previous item's location cannot linger. */+export function inboxDetailSearch(+ detail: {+ channel?: SerializedSearchParams;+ document?: SerializedSearchParams;+ calendar?: SerializedSearchParams;+ } = {}+): DetailSearch {return {- eventId: params?.eventId ?? '',- occurrenceKey: params?.occurrenceKey ?? '',- ...(time?.kind === 'allDay'- ? {- calendarTimeKind: 'allDay',- startDate: time.startDate,- endDate: time.endDate ?? range?.endDate ?? '',- }- : time?.kind === 'timed'- ? {- calendarTimeKind: 'timed',- startsAt: time.startsAt,- endsAt: time.endsAt ?? range?.end ?? '',- }- : range- ? {- calendarTimeKind: 'timed',- startsAt: range.start,- endsAt: range.end,- startDate: range.startDate,- endDate: range.endDate,- }- : {}),+ [channelsSearch.namespace]: detail.channel,+ [driveSearch.namespace]: detail.document,+ [CALENDAR_SEARCH_NAMESPACE]: detail.calendar,};}-function selectionSearch(- selection: PreviewPanelSelection,- blockParams: Record<string, unknown> | undefined-): InboxPreviewSearchParams {- const channelTarget =- selection.type === 'channel' ||- selection.type === 'channel_message' ||- selection.type === 'channel_thread'- ? getChannelEntityTarget(selection)- : undefined;- const channelSearch = {- targetMessageId:- channelTarget?.kind === 'message' ? channelTarget.messageId : '',- targetThreadId:- channelTarget?.kind === 'message' ? (channelTarget.threadId ?? '') : '',- };- const base: InboxPreviewSearchParams = {- ...inboxPreviewSearch.defaults,- selectionType: selection.type,- selectionId: selection.id,- };+function targetParam(target: PreviewBlockTarget, key: string): string {+ const value = (target.params as Record<string, unknown> | undefined)?.[key];+ return typeof value === 'string' ? value : '';+}- switch (selection.type) {- case 'document':- return {- ...base,- fileType: selection.fileType ?? '',- subType: selection.subType?.type ?? '',- targetCommentId: getDocumentCommentTarget(selection)?.commentId ?? '',- };- case 'foreign':- return { ...base, foreignSource: selection.foreignSource };- case 'channel':- return {- ...base,- ...channelSearch,- };- case 'channel_message':- case 'channel_thread':- return {- ...base,- sourceMessageId: selection.messageId,- sourceThreadId: selection.threadId ?? '',- ...channelSearch,- };- case 'calendar_event':- return {- ...base,- ...calendarSearch(- blockParams as CalendarBlockProps | undefined,- selection- ),- };- case 'reminder':- return {- ...base,- reminderId: selection.id,- referencedType: selection.referencedEntity?.type ?? '',- referencedFileType: selection.referencedEntity?.fileType ?? '',- referencedSubType: selection.referencedEntity?.subType ?? '',- };- default:- return base;- }+function documentDetailSearch(+ target: PreviewBlockTarget+): SerializedSearchParams | undefined {+ if (target.blockType === 'channel') return;+ return driveSearchCodec.serialize({+ ...driveSearch.defaults,+ commentId:+ targetParam(target, MD_URL_PARAMS.commentId) ||+ targetParam(target, PDF_URL_PARAMS.annotationId),+ });}-/** Converts a live row into a minimal, reloadable Inbox route destination. */-export function inboxPreviewNavigation(selection: PreviewPanelSelection) {- const target = previewBlockTarget(selection);- const search = selectionSearch(- selection,- target.params as Record<string, unknown> | undefined- );+function channelTargetSearch(+ target: PreviewBlockTarget+): SerializedSearchParams | undefined {+ if (target.blockType !== 'channel') return;+ const params = (target.params ?? {}) as Record<string, unknown>;+ const value = (key: string) => {+ const raw = params[key];+ return typeof raw === 'string' ? raw : '';+ };+ return channelsSearchCodec.serialize({+ ...channelsSearch.defaults,+ messageId: value(CHANNEL_URL_PARAMS.message),+ threadId: value(CHANNEL_URL_PARAMS.thread),+ });+}+/** Route destination for a resolved block target. */+export function inboxPreviewTargetNavigation(+ target: PreviewBlockTarget+): InboxPreviewNavigation {return {params: {- blockType: target.blockType,+ blockType: target.aliasContext?.alias ?? target.blockType,previewId: target.blockId,- } satisfies InboxPreviewRouteParams,- search,+ },+ search: inboxDetailSearch({+ channel: channelTargetSearch(target),+ document: documentDetailSearch(target),+ }),+ };+}++/**+ * Route destination for a calendar event: the Calendar view's own period path+ * with the event and its locator range in the Calendar search namespace.+ */+export function inboxCalendarNavigation(+ target: CalendarViewTarget,+ period: CalendarPeriodView = getPreferredCalendarPeriodView()+): InboxCalendarNavigation | undefined {+ if (!target.eventId) return;+ return {+ params: { period },+ search: inboxDetailSearch({+ calendar: calendarSearchCodec.serialize(calendarTargetSearch(target)),+ }),};}++/** Reduces a live row to the block it opens and the params that locate content in it. */+export function inboxPreviewNavigation(+ selection: PreviewPanelSelection+): InboxPreviewNavigation {+ return inboxPreviewTargetNavigation(previewBlockTarget(selection));+}diff --git a/apps/web/src/features/inbox-view/inbox-route-schema.ts b/apps/web/src/features/inbox-view/inbox-route-schema.tsindex fb3f90f5bd..c5bc228d06 100644--- a/apps/web/src/features/inbox-view/inbox-route-schema.ts+++ b/apps/web/src/features/inbox-view/inbox-route-schema.ts@@ -1,16 +1,56 @@-import { CALENDAR_BLOCK_ID } from '@block-calendar/types';-import { BlockRegistry } from '@core/block';+import { channelsSearch } from '@app/features/channels-view/channels-route';+import {+ DRIVE_DOCUMENT_TYPES,+ type DriveDocumentType,+} from '@app/features/drive-view/primitives/drive-route-schema';+import { driveSearch } from '@app/features/drive-view/primitives/drive-search';+import {+ type BlockAlias,+ BlockAliasRegistry,+ type BlockName,+ BlockRegistry,+} from '@core/block';import { z } from 'zod';+/**+ * The block an inline Home item opens. Aliases such as `task` name markdown+ * subtypes, as Drive's document routes do. `calendar` is not a block here:+ * the `inbox-calendar` route renders the Calendar view at `calendar/:period`.+ */export const inboxPreviewRouteParams = z.object({- blockType: z.enum(BlockRegistry),+ blockType: z.enum([...BlockRegistry, ...BlockAliasRegistry] as const),previewId: z.string().min(1),})- .refine(- ({ blockType, previewId }) =>- blockType !== 'write' &&- (blockType !== 'calendar' || previewId === CALENDAR_BLOCK_ID)- );+ .refine(({ blockType }) => blockType !== 'write' && blockType !== 'calendar');export type InboxPreviewRouteParams = z.infer<typeof inboxPreviewRouteParams>;+export function isInboxDocumentType(value: string): value is DriveDocumentType {+ return (DRIVE_DOCUMENT_TYPES as readonly string[]).includes(value);+}++const aliasBaseTypes: Record<BlockAlias, BlockName> = {+ csv: 'code',+ task: 'md',+ snippet: 'md',+ skill: 'md',+};++/**+ * The block an item's path names once aliases resolve, so `/inbox/task/<id>`+ * shares identity with `md:<id>`. Static so route declarations stay light+ * rather than loading every block definition.+ */+export function inboxBaseBlockType(+ blockType: InboxPreviewRouteParams['blockType']+): BlockName {+ return blockType in aliasBaseTypes+ ? aliasBaseTypes[blockType as BlockAlias]+ : (blockType as BlockName);+}++/** Search the inline Home item owns; the channel namespace is shared with the channels view. */+export const INBOX_PREVIEW_SEARCH_NAMESPACES = [+ channelsSearch.namespace,+ driveSearch.namespace,+] as const;diff --git a/apps/web/src/features/inbox-view/inbox-route.ts b/apps/web/src/features/inbox-view/inbox-route.tsindex 94a3749e6a..3666261365 100644--- a/apps/web/src/features/inbox-view/inbox-route.ts+++ b/apps/web/src/features/inbox-view/inbox-route.ts@@ -1,401 +1,116 @@+import type { CalendarPeriodView } from '@app/features/calendar/types';import { calendarViewContent } from '@app/features/calendar-view/calendar-navigation';-import { createSearchParamsCodec } from '@app/lib/split-router';-import { CALENDAR_BLOCK_ID } from '@block-calendar/types';+import {+ type CalendarSearchParams,+ calendarSearchTarget,+} from '@app/features/calendar-view/calendar-url';+import type { channelsSearch } from '@app/features/channels-view/channels-route';+import type { DriveSearchParams } from '@app/features/drive-view/primitives/drive-search';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';-import type { PreviewPanelSelection } from '@components/app/previewTarget';+import type { PreviewBlockTarget } from '@components/app/previewTarget';import type { SplitContent } from '@components/app/split-layout/layoutManager';-import type { BlockName } from '@core/block';-import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';-import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';+import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';import { documentCommentLocation } from '@notifications/document-comment-location';-import { match } from 'ts-pattern';-import { z } from 'zod';-import type { InboxPreviewRouteParams } from './inbox-route-schema';+import type { z } from 'zod';+import {+ type InboxPreviewRouteParams,+ isInboxDocumentType,+} from './inbox-route-schema';-export const INBOX_PREVIEW_SEARCH_NAMESPACE = 'inbox-preview';--const previewSelectionTypes = [- '',- 'agent_session',- 'automation',- 'call',- 'calendar_event',- 'channel',- 'channel_message',- 'channel_thread',- 'chat',- 'crm_company',- 'crm_contact',- 'document',- 'email',- 'foreign',- 'project',- 'reminder',-] as const;--const reminderReferenceTypes = [- '',- 'agent_session',- 'automation',- 'call',- 'channel',- 'channel_message',- 'channel_thread',- 'chat',- 'crm_company',- 'crm_contact',- 'document',- 'email',- 'foreign',- 'project',-] as const;--const documentSubTypes = ['', 'task', 'snippet', 'skill'] as const;-const calendarTimeKinds = ['', 'timed', 'allDay'] as const;--export const inboxPreviewSearch = {- namespace: INBOX_PREVIEW_SEARCH_NAMESPACE,- schema: z.object({- selectionType: z.enum(previewSelectionTypes),- selectionId: z.string(),- fileType: z.string(),- subType: z.enum(documentSubTypes),- foreignSource: z.enum(['', 'unknown', 'github_pull_request']),- sourceMessageId: z.string(),- sourceThreadId: z.string(),- targetMessageId: z.string(),- targetThreadId: z.string(),- targetCommentId: z.string(),- eventId: z.string(),- occurrenceKey: z.string(),- calendarTimeKind: z.enum(calendarTimeKinds),- startsAt: z.string(),- endsAt: z.string(),- startDate: z.string(),- endDate: z.string(),- reminderId: z.string(),- referencedType: z.enum(reminderReferenceTypes),- referencedFileType: z.string(),- referencedSubType: z.string(),- }),- defaults: {- selectionType: '' as const,- selectionId: '',- fileType: '',- subType: '' as const,- foreignSource: '' as const,- sourceMessageId: '',- sourceThreadId: '',- targetMessageId: '',- targetThreadId: '',- targetCommentId: '',- eventId: '',- occurrenceKey: '',- calendarTimeKind: '' as const,- startsAt: '',- endsAt: '',- startDate: '',- endDate: '',- reminderId: '',- referencedType: '' as const,- referencedFileType: '',- referencedSubType: '',- },+export type InboxPreviewSearch = {+ channel: Pick<+ z.infer<typeof channelsSearch.schema>,+ 'messageId' | 'threadId'+ >;+ document: Pick<DriveSearchParams, 'commentId'>;};-export type InboxPreviewSearchParams = z.infer<- typeof inboxPreviewSearch.schema->;--export const inboxPreviewSearchCodec =- createSearchParamsCodec(inboxPreviewSearch);--function calendarTime(search: InboxPreviewSearchParams) {- if (search.calendarTimeKind === 'timed' && search.startsAt && search.endsAt) {- return {- kind: 'timed' as const,- startsAt: search.startsAt,- endsAt: search.endsAt,- };+/** Normalize typed and fallback child routes to the same block identity. */+export function inboxDetailParamsFromRoute(params: {+ blockType?: InboxPreviewRouteParams['blockType'];+ previewId?: string;+ channelId?: string;+ documentType?: string;+ documentId?: string;+}): InboxPreviewRouteParams | undefined {+ if (params.channelId) {+ return { blockType: 'channel', previewId: params.channelId };}if (- search.calendarTimeKind === 'allDay' &&- search.startDate &&- search.endDate+ params.documentType &&+ params.documentId &&+ isInboxDocumentType(params.documentType)) {return {- kind: 'allDay' as const,- startDate: search.startDate,- endDate: search.endDate,+ blockType: params.documentType,+ previewId: params.documentId,};}+ if (params.blockType && params.previewId) {+ return { blockType: params.blockType, previewId: params.previewId };+ }}-function fallbackSelection(- params: InboxPreviewRouteParams-): PreviewPanelSelection | undefined {- const id = params.previewId;- return match(params.blockType)- .returnType<PreviewPanelSelection | undefined>()- .with('agent', () => ({ type: 'agent_session', id }))- .with('automation', () => ({ type: 'automation', id }))- .with('call', () => ({ type: 'call', id }))- .with('calendar', () => ({ type: 'calendar_event', id }))- .with('channel', () => ({ type: 'channel', id }))- .with('chat', () => ({ type: 'chat', id }))- .with('company', () => ({ type: 'crm_company', id }))- .with('contact', () => ({ type: 'crm_contact', id }))- .with('email', () => ({ type: 'email', id }))- .with('project', () => ({ type: 'project', id }))- .with('pr', () =>- USE_MACRO_PR_SUMMARY_BLOCK- ? ({- type: 'foreign',- id,- foreignSource: 'github_pull_request',- } as const)- : undefined- )- .with(- 'canvas',- 'code',- 'image',- 'md',- 'pdf',- 'spreadsheet',- 'unknown',- 'video',- (fileType) => ({ type: 'document', id, fileType })- )- .with('write', () => undefined)- .exhaustive();+function channelParams(+ search: InboxPreviewSearch['channel']+): Record<string, string> | undefined {+ if (!search.messageId) return;+ return {+ [CHANNEL_URL_PARAMS.message]: search.messageId,+ ...(search.threadId+ ? { [CHANNEL_URL_PARAMS.thread]: search.threadId }+ : {}),+ };}-function selectionIdentity(selection: PreviewPanelSelection): {- blockType: BlockName;- id: string;-} {- return match(selection)- .returnType<{ blockType: BlockName; id: string }>()- .with({ type: 'document' }, (document) => ({- blockType: fileTypeToResolvedBlockName(document.fileType),- id: document.id,- }))- .with(- { type: 'channel_message' },- { type: 'channel_thread' },- (channel) => ({ blockType: 'channel', id: channel.channelId })- )- .with({ type: 'calendar_event' }, () => ({- blockType: 'calendar',- id: CALENDAR_BLOCK_ID,- }))- .with({ type: 'foreign' }, (foreign) => ({- blockType:- USE_MACRO_PR_SUMMARY_BLOCK &&- foreign.foreignSource === 'github_pull_request'- ? 'pr'- : 'unknown',- id: foreign.id,- }))- .with({ type: 'crm_company' }, (company) => ({- blockType: 'company',- id: company.id,- }))- .with({ type: 'crm_contact' }, (contact) => ({- blockType: 'contact',- id: contact.id,- }))- .with({ type: 'reminder' }, (reminder) => ({- blockType: fileTypeToResolvedBlockName(- reminder.referencedEntity?.subType ??- reminder.referencedEntity?.fileType ??- reminder.referencedEntity?.type- ),- id: reminder.referencedEntity?.id ?? reminder.id,- }))- .otherwise((selection) => ({- blockType: fileTypeToResolvedBlockName(selection.type),- id: selection.id,- }));+function commentParams(+ blockType: InboxPreviewRouteParams['blockType'],+ search: InboxPreviewSearch['document']+): Record<string, string> | undefined {+ if (!search.commentId) return;+ const alias = isBlockAlias(blockType) ? blockType : undefined;+ return documentCommentLocation(search.commentId, {+ fileType: resolveBlockAlias(blockType),+ subType: alias ? { type: alias } : undefined,+ }).params;}-function decodedSelection(+/** The block the path names, with the location params the URL carries for it. */+export function inboxPreviewTarget(params: InboxPreviewRouteParams,- search: InboxPreviewSearchParams-): PreviewPanelSelection | undefined {- const id = search.selectionId || params.previewId;- const target = search.targetMessageId- ? {- messageId: search.targetMessageId,- ...(search.targetThreadId ? { threadId: search.targetThreadId } : {}),- }- : undefined;-- return match(search.selectionType)- .returnType<PreviewPanelSelection | undefined>()- .with('', () => undefined)- .with('document', () => ({- type: 'document',- id,- ...(search.fileType ? { fileType: search.fileType } : {}),- ...(search.subType- ? {- subType: {- type: search.subType,- ...(search.subType === 'task' ? { is_completed: false } : {}),- },- }- : {}),- ...(search.targetCommentId- ? { commentTarget: { commentId: search.targetCommentId } }- : {}),- }))- .with('foreign', () => ({- type: 'foreign',- id,- foreignSource: search.foreignSource || 'unknown',- }))- .with('channel', () => ({- type: 'channel',- id: params.previewId,- ...(target ? { target } : {}),- }))- .with('channel_message', () => ({- type: 'channel_message',- id,- channelId: params.previewId,- messageId: search.sourceMessageId || search.targetMessageId || id,- ...(search.sourceThreadId ? { threadId: search.sourceThreadId } : {}),- ...(target ? { target } : {}),- }))- .with('channel_thread', () => ({- type: 'channel_thread',- id,- channelId: params.previewId,- messageId: search.sourceMessageId || search.targetMessageId || id,- threadId:- search.sourceThreadId ||- search.targetThreadId ||- search.sourceMessageId ||- id,- ...(target ? { target } : {}),- }))- .with('calendar_event', () => ({- type: 'calendar_event',- id: search.eventId || id,- ...(search.occurrenceKey ? { occurrenceKey: search.occurrenceKey } : {}),- ...(calendarTime(search) ? { time: calendarTime(search) } : {}),- }))- .with('reminder', () => ({- type: 'reminder',- id: search.reminderId || id,- ...(search.referencedType- ? {- referencedEntity: {- id: params.previewId,- type: search.referencedType,- ...(search.referencedFileType- ? { fileType: search.referencedFileType }- : {}),- ...(search.referencedSubType- ? { subType: search.referencedSubType }- : {}),- },- }- : {}),- }))- .with('agent_session', (type) => ({ type, id }))- .with('automation', (type) => ({ type, id }))- .with('call', (type) => ({ type, id }))- .with('chat', (type) => ({ type, id }))- .with('crm_company', (type) => ({ type, id }))- .with('crm_contact', (type) => ({ type, id }))- .with('email', (type) => ({ type, id }))- .with('project', (type) => ({ type, id }))- .exhaustive();+ search: InboxPreviewSearch+): PreviewBlockTarget {+ const blockType = resolveBlockAlias(params.blockType);+ return {+ blockType,+ blockId: params.previewId,+ aliasContext: isBlockAlias(params.blockType)+ ? { alias: params.blockType, baseType: blockType }+ : undefined,+ params:+ blockType === 'channel'+ ? channelParams(search.channel)+ : commentParams(params.blockType, search.document),+ };}-/** Rebuilds the minimal preview target from path identity plus typed search. */-export function inboxPreviewSelection(+/** Full-block compatibility content for touch surfaces. */+export function inboxPreviewLegacyTarget(params: InboxPreviewRouteParams,- search: InboxPreviewSearchParams-): PreviewPanelSelection | undefined {- const decoded = decodedSelection(params, search);- if (!decoded) return fallbackSelection(params);- const identity = selectionIdentity(decoded);- return identity.blockType === params.blockType &&- identity.id === params.previewId- ? decoded- : fallbackSelection(params);-}--function legacyCommentParams(search: InboxPreviewSearchParams) {- return search.targetCommentId- ? documentCommentLocation(search.targetCommentId, {- fileType: search.fileType,- subType: search.subType ? { type: search.subType } : undefined,- }).params- : undefined;+ search: InboxPreviewSearch+): SplitContent {+ const target = inboxPreviewTarget(params, search);+ return {+ type: params.blockType,+ id: params.previewId,+ ...(target.params ? { params: target.params } : {}),+ };}-/** Full-block compatibility target for disabled or touch-only view surfaces. */-export function inboxPreviewLegacyTarget(- params: InboxPreviewRouteParams,- search: InboxPreviewSearchParams+/** Calendar view content for touch surfaces, from the inline calendar route's period and search. */+export function inboxCalendarLegacyTarget(+ period: CalendarPeriodView,+ search: CalendarSearchParams): SplitContent {- const documentSubType =- search.selectionType === 'document'- ? search.subType- : search.selectionType === 'reminder'- ? search.referencedSubType- : '';- if (- params.blockType === 'md' &&- (documentSubType === 'task' ||- documentSubType === 'snippet' ||- documentSubType === 'skill')- ) {- return {- type: documentSubType,- id: params.previewId,- params: legacyCommentParams(search),- };- }- if (search.selectionType === 'document' && search.targetCommentId) {- return {- type: params.blockType,- id: params.previewId,- params: legacyCommentParams(search),- };- }- if (params.blockType === 'channel' && search.targetMessageId) {- return {- type: 'channel',- id: params.previewId,- params: {- [CHANNEL_URL_PARAMS.message]: search.targetMessageId,- ...(search.targetThreadId- ? { [CHANNEL_URL_PARAMS.thread]: search.targetThreadId }- : {}),- },- };- }- if (params.blockType === 'calendar') {- const range =- search.startsAt && search.endsAt && search.startDate && search.endDate- ? {- start: search.startsAt,- end: search.endsAt,- startDate: search.startDate,- endDate: search.endDate,- }- : undefined;- return calendarViewContent({- eventId: search.eventId || undefined,- occurrenceKey: search.occurrenceKey || undefined,- range,- });- }- return { type: params.blockType, id: params.previewId };+ return calendarViewContent({ ...calendarSearchTarget(search), period });}diff --git a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx b/apps/web/src/features/inbox-view/inbox-view-context.test.tsxdeleted file mode 100644index bc9fbe83aa..0000000000--- a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx+++ /dev/null@@ -1,586 +0,0 @@-import {- SplitRouter,- type SplitRouterLayout,- type SplitRouterLayoutEntry,- type SplitRouterSettledChange,- useSplitRouter,-} from '@app/lib/split-router';-import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';-import type { PreviewPanelSelection } from '@components/app/previewTarget';-import { appSplitRoutes } from '@components/app/split-layout/split-router/app-routes';-import { cleanup, render } from '@solidjs/testing-library';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import {- type InboxViewContext,- InboxViewProvider,- useInboxView,-} from './inbox-view-context';-import { INBOX_ENTRY_STATE_KEY } from './persistence';-import type { InboxViewStateOptions } from './types';--vi.mock('@service-storage/websocket', () => ({- storageWS: { reconnectIfDisconnected: vi.fn() },- createWebSocketJob: vi.fn(),-}));-vi.mock('@service-connection/websocket', () => ({- ws: { addEventListener: vi.fn(), send: vi.fn() },- state: () => 'closed',- createConnectionBlockWebsocketEffect: vi.fn(),- createConnectionWebsocketEffect: vi.fn(),-}));--const entry = vi.hoisted(() => ({- state: {} as Record<string, unknown>,- captors: new Map<string, () => unknown>(),-}));-const user = vi.hoisted(() => ({ id: 'alice' }));-const guard = vi.hoisted(() => ({- selections: [] as unknown[],- preflights: [] as unknown[],- allow: true,-}));-vi.mock('@core/context/user', () => ({ useUserId: () => () => user.id }));-vi.mock('@components/app/previewTarget', () => ({- previewBlockTarget: (selection: {- type: string;- id: string;- channelId?: string;- fileType?: string;- foreignSource?: string;- occurrenceKey?: string;- referencedEntity?: {- id: string;- type: string;- fileType?: string;- subType?: string;- };- }) => {- if (selection.type === 'calendar_event') {- return {- blockType: 'calendar',- blockId: 'view',- params: {- eventId: selection.id,- occurrenceKey: selection.occurrenceKey,- range: {- start: '2025-01-01T00:00:00.000Z',- end: '2025-01-02T00:00:00.000Z',- startDate: '2025-01-01',- endDate: '2025-01-02',- },- },- };- }- if (selection.type === 'reminder') {- const reference = selection.referencedEntity;- const referenceType =- reference?.subType ??- reference?.fileType ??- reference?.type ??- 'unknown';- return {- blockType: ['task', 'snippet', 'skill'].includes(referenceType)- ? 'md'- : referenceType,- blockId: reference?.id ?? selection.id,- };- }- return {- blockType:- selection.type === 'document'- ? selection.fileType- : selection.type === 'channel_message' ||- selection.type === 'channel_thread'- ? 'channel'- : selection.type === 'foreign'- ? 'unknown'- : selection.type,- blockId: selection.channelId ?? selection.id,- };- },-}));-vi.mock('@core/constant/allBlocks', () => ({- fileTypeToResolvedBlockName: (type: string) =>- ['task', 'snippet', 'skill'].includes(type) ? 'md' : type,- isBlockAlias: () => false,- itemToBlockName: (item: { fileType?: string }) => item.fileType ?? 'md',- resolveBlockAlias: (type: string) => type,-}));-vi.mock('@components/app/createPreviewSelectionGuard', () => ({- createPreviewSelectionGuard: () => {- const select = (selection: unknown) => {- guard.selections.push(selection);- return selection === undefined || guard.allow;- };- return Object.assign(select, {- canSelect: (selection: unknown) => {- guard.preflights.push(selection);- return selection === undefined || guard.allow;- },- });- },-}));--vi.mock('@components/app/split-layout/layoutUtils', () => ({- useSplitPanelOrThrow: () => ({- handle: {- currentEntryState: () => entry.state,- registerEntryStateCaptor: (key: string, capture: () => unknown) => {- entry.captors.set(key, capture);- return () => entry.captors.delete(key);- },- },- }),-}));--function createLayout(): SplitRouterLayout<string> {- let current: SplitRouterLayoutEntry<string> | undefined;- const listeners = new Set<(change: SplitRouterSettledChange) => void>();- const notify = () => {- for (const listener of listeners) listener({ history: 'push' });- };- return {- snapshot: () => ({ entries: current ? [current] : [] }),- updateCurrentLocation(_splitId, update) {- if (!current) return;- current = { splitId: current.splitId, location: update(current) };- notify();- },- open: () => ({ status: 'unavailable' }),- reconcile(locations) {- const location = locations[0];- current = location ? { splitId: 'split', location } : undefined;- notify();- },- activate: () => {},- subscribe(listener) {- listeners.add(listener);- return () => listeners.delete(listener);- },- };-}--function mountProvider(initialState?: InboxViewStateOptions, path = '/inbox') {- let context!: InboxViewContext;- let router!: ReturnType<typeof useSplitRouter<string>>;- const location = createMemorySplitRouterLocation(path);- function ReadContext() {- context = useInboxView();- router = useSplitRouter<string>();- return null;- }- const view = render(() => (- <SplitRouter.Root- layout={createLayout()}- routes={appSplitRoutes}- location={location}- >- <SplitRouter.Scope splitId="split">- <InboxViewProvider initialState={initialState}>- <ReadContext />- </InboxViewProvider>- </SplitRouter.Scope>- </SplitRouter.Root>- ));- return { ...view, context, location, router };-}--beforeEach(() => {- localStorage.clear();- user.id = 'alice';- entry.state = {};- entry.captors.clear();- guard.selections = [];- guard.preflights = [];- guard.allow = true;-});-afterEach(cleanup);--describe('InboxViewProvider initialization', () => {- it('honors explicit fields except the URL-owned tab', () => {- entry.state = { [INBOX_ENTRY_STATE_KEY]: { version: 1, tab: 'signal' } };- const initial: InboxViewStateOptions = {- tab: 'noise',- search: 'release notes',- groupBy: 'type',- facets: { type: ['email'], read: ['unread'] },- };-- expect(mountProvider(initial).context.state).toEqual({- ...initial,- tab: 'signal',- groupBy: 'date',- });- });-- it.each([- { tab: 'signal', groupBy: 'date' },- { tab: 'noise', groupBy: 'date' },- { tab: 'reminders', groupBy: 'none' },- ] as const)('defaults omitted fields for $tab', ({ tab, groupBy }) => {- expect(- mountProvider({ tab }, `/inbox?s0.inbox.tab=${tab}`).context.state- ).toEqual({- tab,- groupBy,- search: '',- facets: {},- });- });-- it('normalizes facet selections without mutating the caller', () => {- const facets = { type: ['email', 'channel', 'email'], read: [] };- const { context } = mountProvider({ facets });-- expect(context.state.facets).toEqual({ type: ['channel', 'email'] });- expect(facets).toEqual({- type: ['email', 'channel', 'email'],- read: [],- });- });-- it('preserves explicit empty values and grouping', () => {- entry.state = {- [INBOX_ENTRY_STATE_KEY]: {- version: 1,- tab: 'noise',- search: 'old search',- groupBy: 'type',- facets: { type: ['email'] },- },- };- expect(- mountProvider({ search: '', groupBy: 'none', facets: {} }).context.state- ).toEqual({ tab: 'signal', search: '', groupBy: 'none', facets: {} });- });-- it('restores filters while resetting entry navigation to Signal', () => {- entry.state = {- [INBOX_ENTRY_STATE_KEY]: {- version: 1,- tab: 'noise',- search: 'old search',- groupBy: 'type',- facets: { read: ['unread'] },- },- };-- expect(mountProvider().context.state).toEqual({- tab: 'signal',- search: '',- groupBy: 'date',- facets: { read: ['unread'] },- });- });-- it('restores filter changes when returning through split history', () => {- const view = mountProvider({ tab: 'noise', search: 'explicit search' });- view.context.setState('groupBy', 'type');- view.context.setFacets({ type: ['email'] });- const stored = entry.captors.get(INBOX_ENTRY_STATE_KEY)?.();- expect(stored).toEqual({- version: 1,- tab: 'signal',- facets: { type: ['email'] },- });-- view.unmount();- entry.state = { [INBOX_ENTRY_STATE_KEY]: stored };- expect(mountProvider().context.state).toEqual({- tab: 'signal',- search: '',- groupBy: 'date',- facets: { type: ['email'] },- });- });-- it('persists type and status filters across a full reload with no entry state', () => {- const view = mountProvider();- view.context.setFacets({ type: ['none'], read: ['unread'] });- view.unmount();- entry.state = {};- expect(mountProvider().context.state.facets).toEqual({- type: ['none'],- read: ['unread'],- });- });-- it('uses saved preferences for a fresh Home navigation, but honors explicit facets', () => {- const view = mountProvider();- view.context.setFacets({ type: ['channels'] });- view.unmount();- const next = mountProvider({ tab: 'signal' });- expect(next.context.state.facets).toEqual({ type: ['channels'] });- next.unmount();- expect(mountProvider({ facets: {} }).context.state.facets).toEqual({});- });-- it('keeps filters scoped to the signed-in user', () => {- const view = mountProvider();- view.context.setFacets({ type: ['none'] });- view.unmount();- user.id = 'bob';- expect(mountProvider().context.state.facets).toEqual({});- });-- it('restores read-only filters with their entity types', () => {- localStorage.setItem(- 'macro:home:filters:v1:alice',- JSON.stringify({- version: 1,- facets: { type: ['channels'], read: ['read'] },- })- );- entry.state = {- [INBOX_ENTRY_STATE_KEY]: {- version: 1,- facets: { type: ['channels'], read: ['read'] },- },- };- expect(mountProvider().context.state.facets).toEqual({- type: ['channels'],- read: ['read'],- });- });-- it('keeps Read and Unread mutually exclusive and normalizes both to All', () => {- const { context } = mountProvider();- context.setFacets({ read: ['read'] });- expect(context.state.facets).toEqual({ read: ['read'] });- context.setFacets({ read: ['unread'] });- expect(context.state.facets).toEqual({ read: ['unread'] });- context.setFacets({ read: ['unread', 'read'] });- expect(context.state.facets).toEqual({});- });-- it('persists resetting all filters and tolerates corrupt stored preferences', () => {- const view = mountProvider();- view.context.setFacets({ type: ['none'], read: ['unread'] });- view.context.setFacets({});- view.unmount();- const restored = mountProvider();- expect(restored.context.state.facets).toEqual({});- restored.unmount();- localStorage.setItem('macro:home:filters:v1:alice', '{broken');- expect(mountProvider().context.state.facets).toEqual({});- });-});--describe('InboxViewProvider route selection', () => {- it('takes the tab from pane search ahead of explicit and restored state', () => {- entry.state = { [INBOX_ENTRY_STATE_KEY]: { version: 1, tab: 'signal' } };- const { context } = mountProvider(- { tab: 'signal' },- '/inbox?s0.inbox.tab=noise'- );- expect(context.state.tab).toBe('noise');- });-- it('normalizes invalid URL tabs without restoring an old selection', async () => {- const { context, location, router } = mountProvider(- undefined,- '/inbox?s0.inbox.tab=unknown'- );- await router.settled();- expect(context.state.tab).toBe('signal');- expect(location.read().search).toBe('');- });-- it('writes the tab to the URL and follows browser Back/Forward', async () => {- const { context, location, router } = mountProvider();- context.setTab('noise');- await router.settled();- expect(location.read().search).toBe('?s0.inbox.tab=noise');- expect(location.back()).toBe(true);- await router.settled();- expect(context.state.tab).toBe('signal');- expect(location.forward()).toBe(true);- await router.settled();- expect(context.state.tab).toBe('noise');- });-- it('keeps the URL tab when opening and closing a preview', async () => {- const { context, location, router } = mountProvider(- undefined,- '/inbox?s0.inbox.tab=noise'- );- context.openPreview({ type: 'email', id: 'thread-1' });- await router.settled();- expect(location.read().pathname).toBe('/inbox/email/thread-1');- expect(location.read().search).toContain('s0.inbox.tab=noise');- context.closePreview();- await router.settled();- expect(location.read().pathname).toBe('/inbox');- expect(location.read().search).toContain('s0.inbox.tab=noise');- });-- it('rebuilds a heterogeneous channel-message preview from a direct URL', () => {- const { context } = mountProvider(- undefined,- '/inbox/channel/channel-1?s0.inbox-preview.selectionType=channel_message&s0.inbox-preview.selectionId=row-1&s0.inbox-preview.sourceMessageId=message-1&s0.inbox-preview.sourceThreadId=thread-1&s0.inbox-preview.targetMessageId=message-1&s0.inbox-preview.targetThreadId=thread-1'- );-- expect(context.previewEntity()).toEqual({- type: 'channel_message',- id: 'row-1',- channelId: 'channel-1',- messageId: 'message-1',- threadId: 'thread-1',- target: { messageId: 'message-1', threadId: 'thread-1' },- });- expect(guard.selections.at(-1)).toEqual(context.previewEntity());- });-- it('serializes a live preview selection and closes it through the root route', async () => {- const { context, location, router } = mountProvider();-- expect(- context.openPreview({- type: 'document',- id: 'task-1',- fileType: 'md',- subType: { type: 'task', is_completed: false },- })- ).toBe(true);- await router.settled();- expect(location.read().pathname).toBe('/inbox/md/task-1');- expect(location.read().search).toContain(- 's0.inbox-preview.selectionType=document'- );- expect(context.previewEntity()).toMatchObject({- type: 'document',- id: 'task-1',- fileType: 'md',- subType: { type: 'task' },- });-- context.closePreview();- await router.settled();- expect(location.read().pathname).toBe('/inbox');- expect(context.previewEntity()).toBeUndefined();- });-- it('asks the preview to navigate again when the previewed row is re-opened', async () => {- const { context, location, router } = mountProvider();- const row = {- type: 'document',- id: 'doc-1',- fileType: 'md',- commentTarget: { commentId: 'comment-1' },- } satisfies PreviewPanelSelection;-- context.openPreview(row);- await router.settled();- const url = location.read().pathname + location.read().search;- expect(context.previewNavigationRequest()).toBe(0);-- expect(context.openPreview({ ...row })).toBe(true);- expect(context.openPreview({ ...row })).toBe(true);- await router.settled();- expect(context.previewNavigationRequest()).toBe(2);- expect(location.read().pathname + location.read().search).toBe(url);-- context.openPreview({ ...row, commentTarget: { commentId: 'comment-2' } });- await router.settled();- expect(context.previewNavigationRequest()).toBe(2);- expect(location.read().search).toContain(- 's0.inbox-preview.targetCommentId=comment-2'- );- });-- it('round-trips calendar, reminder, foreign, and document subtype targets', async () => {- const { context, location, router } = mountProvider();-- context.openPreview({- type: 'calendar_event',- id: 'event-1',- occurrenceKey: 'occurrence-1',- time: {- kind: 'timed',- startsAt: '2025-01-01T12:00:00.000Z',- endsAt: '2025-01-01T13:00:00.000Z',- },- });- await router.settled();- expect(location.read().pathname).toBe('/inbox/calendar/view');- expect(context.previewEntity()).toMatchObject({- type: 'calendar_event',- id: 'event-1',- occurrenceKey: 'occurrence-1',- });-- context.openPreview({- type: 'reminder',- id: 'reminder-1',- referencedEntity: {- id: 'task-2',- type: 'document',- fileType: 'md',- subType: 'task',- },- });- await router.settled();- expect(location.read().pathname).toBe('/inbox/md/task-2');- expect(context.previewEntity()).toMatchObject({- type: 'reminder',- id: 'reminder-1',- referencedEntity: { id: 'task-2', subType: 'task' },- });-- context.openPreview({- type: 'foreign',- id: 'foreign-1',- foreignSource: 'unknown',- });- await router.settled();- expect(location.read().pathname).toBe('/inbox/unknown/foreign-1');- expect(context.previewEntity()).toEqual({- type: 'foreign',- id: 'foreign-1',- foreignSource: 'unknown',- });-- context.openPreview({- type: 'document',- id: 'snippet-1',- fileType: 'md',- subType: { type: 'snippet' },- });- await router.settled();- expect(location.read().pathname).toBe('/inbox/md/snippet-1');- expect(context.previewEntity()).toMatchObject({- type: 'document',- id: 'snippet-1',- fileType: 'md',- subType: { type: 'snippet' },- });- });-- it('keeps the accepted preview when compatibility preflight blocks selection', async () => {- const { context, location, router } = mountProvider(- undefined,- '/inbox/email/current'- );- guard.allow = false;-- expect(context.openPreview({ type: 'email', id: 'blocked' })).toBe(false);- await router.settled();- expect(location.read().pathname).toBe('/inbox/email/current');- expect(context.previewEntity()).toEqual({ type: 'email', id: 'current' });- });-- it('replaces an incompatible direct preview and closes previews on tab change', async () => {- guard.allow = false;- const blocked = mountProvider(undefined, '/inbox/email/blocked');- await blocked.router.settled();- expect(blocked.location.read().pathname).toBe('/inbox');- blocked.unmount();-- guard.allow = true;- const accepted = mountProvider(undefined, '/inbox/email/open');- accepted.context.setTab('noise');- await accepted.router.settled();- expect(accepted.location.read().pathname).toBe('/inbox');- expect(accepted.context.state.tab).toBe('noise');- });-});diff --git a/apps/web/src/features/inbox-view/inbox-view-context.tsx b/apps/web/src/features/inbox-view/inbox-view-context.tsxindex d9906029fe..d4e9694cb5 100644--- a/apps/web/src/features/inbox-view/inbox-view-context.tsx+++ b/apps/web/src/features/inbox-view/inbox-view-context.tsx@@ -1,16 +1,24 @@+import { channelsSearch } from '@app/features/channels-view/channels-route';+import { driveSearch } from '@app/features/drive-view/primitives/drive-search';import type { FacetSelection } from '@app/features/soup/filters/facets/types';import { makePersistedState } from '@app/lib/persistence';import {createSearchParams,+ type SerializedSearchParams,useNavigate,- useRouteParams,+ useParams,} from '@app/lib/split-router';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';-import type { PreviewPanelSelection } from '@components/app/previewTarget';+import {+ type PreviewBlockTarget,+ type PreviewSelection,+ previewBlockTarget,+} from '@components/app/previewTarget';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { createAssertedContextProvider } from '@core/context/createContext';import { useUserId } from '@core/context/user';import type { ContextProviderProps } from '@solid-primitives/context';+import deepEqual from 'fast-deep-equal';import {type Accessor,createEffect,@@ -25,19 +33,25 @@ import {type SetStoreFunction,type Store,} from 'solid-js/store';-import { inboxPreviewNavigation } from './inbox-preview-navigation';+import { useInboxCalendarPreview } from './inbox-calendar-preview';import {- INBOX_PREVIEW_SEARCH_NAMESPACE,- inboxPreviewSearch,- inboxPreviewSearchCodec,- inboxPreviewSelection,-} from './inbox-route';+ type InboxPreviewNavigation,+ inboxDetailSearch,+ inboxPreviewTargetNavigation,+} from './inbox-preview-navigation';+import { inboxDetailParamsFromRoute, inboxPreviewTarget } from './inbox-route';+import { isInboxDocumentType } from './inbox-route-schema';import { inboxTabSearch, inboxTabSearchCodec } from './inbox-tab-search';import {createInboxViewPersistence,normalizeInboxFacets,} from './persistence';-import { inboxPreviewRoute, inboxSplitRoute } from './route';+import {+ inboxChannelRoute,+ inboxDocumentRoute,+ inboxPreviewRoute,+ inboxSplitRoute,+} from './route';import type {InboxGroupBy,InboxTab,@@ -52,10 +66,15 @@ type InboxViewProviderProps = ContextProviderProps & {export type InboxViewContext = {state: Store<InboxViewState>;setState: SetStoreFunction<InboxViewState>;- previewEntity: Accessor<PreviewPanelSelection | undefined>;- /** Counts re-opens of the selection already previewed, such as a re-click. */+ /** The block the route currently opens inline, if any. */+ previewTarget: Accessor<PreviewBlockTarget | undefined>;+ /** Re-aim a target when the selected row is opened again at the same URL. */previewNavigationRequest: Accessor<number>;- openPreview: (entity: PreviewPanelSelection) => boolean;+ /** Whether the route opens the Calendar view inline. */+ calendarOpen: Accessor<boolean>;+ /** Bumped when the open calendar event is requested again, to re-aim in place. */+ calendarRefocus: Accessor<number>;+ openPreview: (entity: PreviewSelection) => boolean;closePreview: () => void;setTab: (tab: InboxTab) => void;setFacets: (facets: FacetSelection) => void;@@ -72,8 +91,10 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<const panel = useSplitPanelOrThrow();const userId = useUserId();const navigate = useNavigate();- const routeParams = useRouteParams(inboxPreviewRoute);- const [previewSearch] = createSearchParams(inboxPreviewSearch);+ const routeParams =+ useParams<Parameters<typeof inboxDetailParamsFromRoute>[0]>();+ const [channelSearch] = createSearchParams(channelsSearch);+ const [documentSearch] = createSearchParams(driveSearch);const [tabSearch] = createSearchParams(inboxTabSearch);const selectPreview = createPreviewSelectionGuard();const initial = props.initialState ?? {};@@ -108,77 +129,78 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<));- const previewEntity = createMemo<PreviewPanelSelection | undefined>(() => {- const blockType = routeParams.blockType;- const previewId = routeParams.previewId;- if (typeof blockType !== 'string' || typeof previewId !== 'string') return;- return inboxPreviewSelection({ blockType, previewId }, previewSearch);+ const previewTarget = createMemo<PreviewBlockTarget | undefined>(() => {+ const params = inboxDetailParamsFromRoute(routeParams);+ if (!params) return;+ return inboxPreviewTarget(params, {+ channel: channelSearch,+ document: documentSearch,+ });});- const navigatePreview = (entity: PreviewPanelSelection, replace = false) => {- const preview = inboxPreviewNavigation(entity);- navigate(- { route: inboxPreviewRoute, params: preview.params },- {- replace,- search: {- [INBOX_PREVIEW_SEARCH_NAMESPACE]: inboxPreviewSearchCodec.serialize(- preview.search- ),- [inboxTabSearch.namespace]: inboxTabSearchCodec.serialize({- tab: state.tab,- }),- },- }- );+ const withTab = (+ search: Record<string, SerializedSearchParams | undefined>+ ) => ({+ ...search,+ [inboxTabSearch.namespace]: inboxTabSearchCodec.serialize({+ tab: state.tab,+ }),+ });+ const { calendarOpen, calendarRefocus, openCalendarEvent } =+ useInboxCalendarPreview(withTab);+ const navigateDetail = (+ { params, search }: InboxPreviewNavigation,+ replace = false+ ) => {+ const { blockType, previewId } = params;+ const target =+ blockType === 'channel'+ ? { route: inboxChannelRoute, params: { channelId: previewId } }+ : isInboxDocumentType(blockType)+ ? {+ route: inboxDocumentRoute,+ params: { documentType: blockType, documentId: previewId },+ }+ : { route: inboxPreviewRoute, params };+ navigate(target, { replace, search: withTab(search) });};+ const navigateTarget = (target: PreviewBlockTarget, replace = false) =>+ navigateDetail(inboxPreviewTargetNavigation(target), replace);const closePreview = () =>navigate({ route: inboxSplitRoute, params: {} },- {- search: {- [inboxTabSearch.namespace]: inboxTabSearchCodec.serialize({- tab: state.tab,- }),- },- }+ { search: withTab(inboxDetailSearch()) });const [previewNavigationRequest, setPreviewNavigationRequest] =createSignal(0);- // Re-opening the previewed selection leaves the route unchanged, so the- // preview sees no new selection; the request asks it to navigate again.- const isPreviewed = (entity: PreviewPanelSelection) => {- const current = previewEntity();- return (- current !== undefined &&- JSON.stringify(inboxPreviewNavigation(current)) ===- JSON.stringify(inboxPreviewNavigation(entity))- );- };- const openPreview = (entity: PreviewPanelSelection) => {- if (!selectPreview.canSelect(entity)) return false;- if (isPreviewed(entity)) {+ const openPreview = (entity: PreviewSelection) => {+ if (entity.type === 'calendar_event') {+ return openCalendarEvent(entity);+ }+ const target = previewBlockTarget(entity);+ if (!selectPreview.canSelect(target)) return false;+ const current = previewTarget();+ if (+ current &&+ deepEqual(+ inboxPreviewTargetNavigation(current),+ inboxPreviewTargetNavigation(target)+ )+ ) {setPreviewNavigationRequest((count) => count + 1);return true;}- navigatePreview(entity);+ navigateTarget(target);return true;};createEffect(- on(previewEntity, (entity, previous) => {- if (selectPreview(entity)) return;- if (previous) navigatePreview(previous, true);+ on(previewTarget, (target, previous) => {+ if (selectPreview(target)) return;+ if (previous) navigateTarget(previous, true);elsenavigate({ route: inboxSplitRoute, params: {} },- {- replace: true,- search: {- [inboxTabSearch.namespace]: inboxTabSearchCodec.serialize({- tab: state.tab,- }),- },- }+ { replace: true, search: withTab(inboxDetailSearch()) });}));@@ -201,8 +223,10 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<return {state,setState,- previewEntity,+ previewTarget,previewNavigationRequest,+ calendarOpen,+ calendarRefocus,openPreview,closePreview,setTab,diff --git a/apps/web/src/features/inbox-view/inbox-view.tsx b/apps/web/src/features/inbox-view/inbox-view.tsxindex 0b87fc9cf5..70e0292279 100644--- a/apps/web/src/features/inbox-view/inbox-view.tsx+++ b/apps/web/src/features/inbox-view/inbox-view.tsx@@ -1,14 +1,10 @@-import {- useViewShell,- ViewBreadcrumbs,- ViewShell,-} from '@app/components/view-shell';-import { SplitRouter } from '@app/lib/split-router';+import { useViewShell, ViewShell } from '@app/components/view-shell';+import { calendarSearch } from '@app/features/calendar-view/calendar-url';+import { CalendarView } from '@app/features/calendar-view/calendar-view';+import { createSearchParams, SplitRouter } from '@app/lib/split-router';import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';-import {- PreviewPanel,- type PreviewPanelSelection,-} from '@components/app/PreviewPanel';+import { PreviewFrame, PreviewPanel } from '@components/app/PreviewPanel';+import type { PreviewSelection } from '@components/app/previewTarget';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';@@ -17,10 +13,12 @@ import { ListEntityMetadataQueryProvider } from '@entity';import SpinnerIcon from '@phosphor/spinner.svg';import { createEffect, onMount, Show, Suspense } from 'solid-js';import { HomeChatStart } from './components/HomeChatStart';+import { HomeReturnBreadcrumb } from './components/HomeReturnBreadcrumb';import { InboxListLayout } from './components/InboxHeader';import { InboxList } from './components/InboxList';import { InboxTabs } from './components/InboxTabs';import { InboxViewProvider, useInboxView } from './inbox-view-context';+import { inboxCalendarRoute } from './route';import type { InboxViewStateOptions } from './types';export type InboxViewProps = {@@ -37,8 +35,8 @@ function InboxFallback() {}function HomeListPane(props: {- previewEntity: PreviewPanelSelection | undefined;- onPreviewEntityChange: (entity: PreviewPanelSelection | undefined) => void;+ hasPreview: boolean;+ onPreviewEntityChange: (entity: PreviewSelection | undefined) => void;onNewChat: () => void;}) {const shell = useViewShell();@@ -56,7 +54,7 @@ function HomeListPane(props: {><Suspense fallback={<InboxFallback />}><InboxList- previewEntity={props.previewEntity}+ hasPreview={props.hasPreview}onPreviewEntityChange={props.onPreviewEntityChange}onPreviewActivate={showContent}/>@@ -65,30 +63,26 @@ function HomeListPane(props: {);}-function HomeReturnBreadcrumb(props: { onReturn: () => void }) {- return (- <nav aria-label="Home location" class="flex items-center gap-0.5">- <ViewBreadcrumbs.ReturnButton- data-allow-focus-in-preview- onClick={props.onReturn}- >- Home- </ViewBreadcrumbs.ReturnButton>- <ViewBreadcrumbs.Separator />- </nav>- );-}-function InboxViewRoot() {const panel = useSplitPanelOrThrow();- const { state, setTab, previewEntity, openPreview, closePreview } =- useInboxView();+ const {+ state,+ setTab,+ previewTarget,+ calendarOpen,+ openPreview,+ closePreview,+ } = useInboxView();createEffect(() => {if (state.tab !== 'reminders') return;setTab('signal');});const newChat = closePreview;+ const onPreviewEntityChange = (entity: PreviewSelection | undefined) => {+ if (entity) openPreview(entity);+ else closePreview();+ };// The touch nav item and legacy touch view both call this "Notifications".onMount(() =>@@ -112,21 +106,22 @@ function InboxViewRoot() {><ViewShell.Aside class="flex flex-col bg-panel"><HomeListPane- previewEntity={previewEntity()}- onPreviewEntityChange={(entity) =>- entity ? openPreview(entity) : closePreview()+ hasPreview={+ previewTarget() !== undefined || calendarOpen()}+ onPreviewEntityChange={onPreviewEntityChange}onNewChat={newChat}/></ViewShell.Aside><ViewShell.Main class="overflow-hidden">- <SplitRouter.Outlet- fallback={() => (- <Suspense fallback={<InboxFallback />}>- <HomeChatStart />- </Suspense>- )}- />+ {/* Detail routes load lazily. Suspend only this area, so+ the list stays mounted and a pending detail's effects+ wait until it resolves. */}+ <Suspense fallback={<InboxFallback />}>+ <SplitRouter.Outlet+ fallback={() => <HomeChatStart />}+ />+ </Suspense></ViewShell.Main></ViewShell.Root></div>@@ -135,10 +130,8 @@ function InboxViewRoot() {<ViewShell.Root aside={false} main={{ min: 224 }}><ViewShell.Main><HomeListPane- previewEntity={previewEntity()}- onPreviewEntityChange={(entity) =>- entity ? openPreview(entity) : closePreview()- }+ hasPreview={previewTarget() !== undefined || calendarOpen()}+ onPreviewEntityChange={onPreviewEntityChange}onNewChat={newChat}/></ViewShell.Main>@@ -151,16 +144,35 @@ function InboxViewRoot() {);}+/** The Calendar view aimed at an event, inside Home's inline preview chrome. */+export function InboxCalendarRouteView() {+ const panel = useSplitPanelOrThrow();+ const { closePreview, calendarRefocus } = useInboxView();+ const [search] = createSearchParams(calendarSearch);++ return (+ <div class="flex size-full min-h-0">+ <PreviewFrame+ splitPanelContext={panel}+ headerLeading={<HomeReturnBreadcrumb onReturn={closePreview} />}+ locationKey={() => `${search.eventId}:${search.occurrenceKey}`}+ >+ <CalendarView route={inboxCalendarRoute} refocus={calendarRefocus} />+ </PreviewFrame>+ </div>+ );+}+export function InboxDetailRouteView() {const panel = useSplitPanelOrThrow();const orchestrator = useGlobalBlockOrchestrator();- const { previewEntity, previewNavigationRequest, closePreview } =+ const { previewTarget, previewNavigationRequest, closePreview } =useInboxView();return (<Suspense><PreviewPanel- selectedEntity={previewEntity()}+ target={previewTarget()}navigationRequest={previewNavigationRequest()}orchestrator={orchestrator}splitPanelContext={panel}diff --git a/apps/web/src/features/inbox-view/route.tsx b/apps/web/src/features/inbox-view/route.tsxindex 1064345241..15580b5240 100644--- a/apps/web/src/features/inbox-view/route.tsx+++ b/apps/web/src/features/inbox-view/route.tsx@@ -1,9 +1,24 @@+import type { CalendarPeriodView } from '@app/features/calendar/types';+import {+ CALENDAR_SEARCH_NAMESPACE,+ calendarPeriodParams,+ calendarPeriodPath,+ calendarSearch,+} from '@app/features/calendar-view/calendar-url';+import { channelsSearch } from '@app/features/channels-view/channels-route';+import { channelDetailRoute } from '@app/features/channels-view/route';+import { driveSearch } from '@app/features/drive-view/primitives/drive-search';+import { driveRootDocumentRoute } from '@app/features/drive-view/route';import {createSearchParams,defineRoute,+ routeParams,+ type SplitRouterEntry,useParams,} from '@app/lib/split-router';-import type { SplitContent } from '@components/app/split-layout/layoutManager';+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';+import { URL_PARAMS as MARKDOWN_URL_PARAMS } from '@block-md/constants';+import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';import {NewAppView,RedirectSplit,@@ -11,10 +26,17 @@ import {} from '@components/app/split-layout/split-router/app-route-shell';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { lazy, Show } from 'solid-js';+import { URL_PARAMS as EMAIL_URL_PARAMS } from '../email-thread/core/location';import { getViewPreset } from '../next-soup/sidebar/soup-filter-presets';-import { inboxPreviewLegacyTarget, inboxPreviewSearch } from './inbox-route';import {+ inboxCalendarLegacyTarget,+ inboxDetailParamsFromRoute,+ inboxPreviewLegacyTarget,+} from './inbox-route';+import {+ INBOX_PREVIEW_SEARCH_NAMESPACES,type InboxPreviewRouteParams,+ inboxBaseBlockType,inboxPreviewRouteParams,} from './inbox-route-schema';@@ -27,6 +49,20 @@ const InboxView = lazy(async () => ({const InboxDetailRouteView = lazy(async () => ({default: (await import('./inbox-view')).InboxDetailRouteView,}));+const InboxEntityDetailRouteView = lazy(async () => ({+ default: (await import('./components/InboxEntityDetailRouteView'))+ .InboxEntityDetailRouteView,+}));+const InboxCalendarRouteView = lazy(async () => ({+ default: (await import('./inbox-view')).InboxCalendarRouteView,+}));++type InboxDetailParams = Partial<InboxPreviewRouteParams> & {+ channelId?: string;+ documentType?: string;+ documentId?: string;+ period?: CalendarPeriodView;+};function LegacyInboxView() {const preset = getViewPreset('inbox');@@ -42,26 +78,33 @@ function LegacyInboxView() {}function InboxLegacyRouteView() {- const params = useParams<Partial<InboxPreviewRouteParams>>();- const [search] = createSearchParams(inboxPreviewSearch);+ const params = useParams<InboxDetailParams>();+ const [channelSearch] = createSearchParams(channelsSearch);+ const [documentSearch] = createSearchParams(driveSearch);+ const [eventSearch] = createSearchParams(calendarSearch);const legacyTarget = () => {- const { blockType, previewId } = params;- if (!blockType || !previewId) return;- return inboxPreviewLegacyTarget({ blockType, previewId }, search);+ const { period } = params;+ if (period) return inboxCalendarLegacyTarget(period, eventSearch);+ const detail = inboxDetailParamsFromRoute(params);+ if (!detail) return;+ return inboxPreviewLegacyTarget(detail, {+ channel: channelSearch,+ document: documentSearch,+ });};return (<Show when={legacyTarget()} fallback={<LegacyInboxView />}>- {(target) => <RedirectSplit to={target() as SplitContent} />}+ {(target) => <RedirectSplit to={target()} />}</Show>);}export const InboxRouteView = withAuth(() => {- const params = useParams<Partial<InboxPreviewRouteParams>>();+ const params = useParams<InboxDetailParams>();const detailRequested = () =>- typeof params.blockType === 'string' &&- typeof params.previewId === 'string';+ inboxDetailParamsFromRoute(params) !== undefined ||+ typeof params.period === 'string';return (<NewAppView@@ -77,15 +120,74 @@ export const InboxRouteView = withAuth(() => {);});+/** The Calendar view inline in Home, at the Calendar route's own period path and search. */+export const inboxCalendarRoute = defineRoute({+ id: 'inbox-calendar',+ path: 'calendar/:period',+ params: calendarPeriodParams,+ serializeParams: ({ period }) => ({ period: calendarPeriodPath(period) }),+ component: InboxCalendarRouteView,+ search: [CALENDAR_SEARCH_NAMESPACE],+});++export const inboxChannelRoute = defineRoute({+ ...channelDetailRoute,+ id: 'inbox-channel',+ path: 'channel/:channelId',+ component: InboxEntityDetailRouteView,+});++export const inboxDocumentRoute = defineRoute({+ ...driveRootDocumentRoute,+ id: 'inbox-document',+ component: InboxEntityDetailRouteView,+ externalSearch: (entry: Readonly<SplitRouterEntry>) => {+ const type = routeParams<{ documentType?: string }>(+ entry.location.route+ ).documentType;+ if (+ type === 'md' ||+ type === 'task' ||+ type === 'snippet' ||+ type === 'skill'+ ) {+ return Object.values(MARKDOWN_URL_PARAMS);+ }+ if (type === 'pdf') return Object.values(PDF_URL_PARAMS);+ return type === 'spreadsheet' ? [MARKDOWN_URL_PARAMS.commentId] : [];+ },+ remountKey: ({ documentType, documentId }) =>+ `${inboxBaseBlockType(documentType)}:${documentId}`,+});export const inboxPreviewRoute = defineRoute({id: 'inbox-preview',path: ':blockType/:previewId',params: inboxPreviewRouteParams,component: InboxDetailRouteView,- remountKey: ({ blockType, previewId }) => `${blockType}:${previewId}`,+ search: INBOX_PREVIEW_SEARCH_NAMESPACES,+ // Blocks read their own location keys from the URL, as they do in Drive.+ externalSearch: (entry: Readonly<SplitRouterEntry>) => {+ const type = routeParams<{ blockType?: string }>(+ entry.location.route+ ).blockType;+ if (type === 'channel') return Object.values(CHANNEL_URL_PARAMS);+ if (type === 'email') return Object.values(EMAIL_URL_PARAMS);+ if (+ type === 'md' ||+ type === 'task' ||+ type === 'snippet' ||+ type === 'skill'+ ) {+ return Object.values(MARKDOWN_URL_PARAMS);+ }+ if (type === 'pdf') return Object.values(PDF_URL_PARAMS);+ return type === 'spreadsheet' ? [MARKDOWN_URL_PARAMS.commentId] : [];+ },+ remountKey: ({ blockType, previewId }) =>+ `${inboxBaseBlockType(blockType)}:${previewId}`,claim: ({ blockType, previewId }) => ({namespace: 'block',- id: `${blockType}:${previewId}`,+ id: `${inboxBaseBlockType(blockType)}:${previewId}`,}),});@@ -94,5 +196,11 @@ export const inboxSplitRoute = defineRoute({path: 'inbox',component: InboxRouteView,search: '*' as const,- children: [inboxPreviewRoute],+ // The period path is matched before the block pattern can claim `calendar`.+ children: [+ inboxCalendarRoute,+ inboxChannelRoute,+ inboxDocumentRoute,+ inboxPreviewRoute,+ ],});diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.tsindex def94125ca..393bad743f 100644--- a/apps/web/src/features/next-soup/utils.test.ts+++ b/apps/web/src/features/next-soup/utils.test.ts@@ -1,9 +1,15 @@import { createCalendarRange } from '@app/features/calendar-view/calendar-range';-import { previewBlockTarget } from '@components/app/previewTarget';+import {+ previewBlockTarget,+ previewCalendarTarget,+} from '@components/app/previewTarget';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { afterEach, describe, expect, it, vi } from 'vitest';-import { inboxPreviewNavigation } from '../inbox-view/inbox-preview-navigation';-import { inboxPreviewSelection } from '../inbox-view/inbox-route';+import {+ inboxCalendarNavigation,+ inboxPreviewNavigation,+} from '../inbox-view/inbox-preview-navigation';+import { inboxPreviewTarget } from '../inbox-view/inbox-route';vi.mock('@core/mobile/isTouchDevice', () => ({isTouchDevice: vi.fn(() => false),@@ -118,6 +124,7 @@ import type { SplitManager } from '@components/app/split-layout/layoutManager';import { type ChannelEntityTarget, type EntityData, queryKeys } from '@entity';import type { NotificationSource, UnifiedNotification } from '@notifications';import {+ type CalendarPreviewSelection,executeMarkEntitiesDone,executeMarkEntitiesUndone,getChannelEntityTarget,@@ -443,15 +450,22 @@ describe('calendar view navigation', () => {}),],},- search: { calendar: { eventId: ['event-1'] } },+ search: {+ calendar: expect.objectContaining({+ eventId: ['event-1'],+ occurrenceKey: ['instance-1'],+ startDate: ['2026-01-27'],+ endDate: ['2026-01-28'],+ }),+ },}),}),expect.any(Object));});- it('keeps a recurring reminder on its instance through the Inbox preview route', () => {- const result = inboxPreviewNavigation({+ it('keeps a recurring reminder on its instance through the Calendar route', () => {+ const selection = {type: 'calendar_event',id: 'event-1',time: {@@ -472,15 +486,9 @@ describe('calendar view navigation', () => {},} as UnifiedNotification,],- } as never);- expect(result.search).toMatchObject({- occurrenceKey: '2026-09-23T22:00:00+00:00',- startsAt: '2026-09-23T22:00:00Z',- endsAt: '2026-09-23T22:30:00Z',- });-- const selection = inboxPreviewSelection(result.params, result.search);- expect(previewBlockTarget(selection!).params).toMatchObject({+ } satisfies CalendarPreviewSelection;+ const target = previewCalendarTarget(selection);+ expect(target).toEqual({eventId: 'event-1',occurrenceKey: '2026-09-23T22:00:00+00:00',range: createCalendarRange({@@ -489,6 +497,14 @@ describe('calendar view navigation', () => {endsAt: '2026-09-23T22:30:00Z',}),});+ expect(+ inboxCalendarNavigation(target, 'timeGridWeek')?.search.calendar+ ).toEqual({+ eventId: ['event-1'],+ occurrenceKey: ['2026-09-23T22:00:00+00:00'],+ startDate: [target.range!.startDate],+ endDate: [target.range!.endDate],+ });});});@@ -593,25 +609,31 @@ describe('Drive document routing', () => {});describe('Inbox calendar preview navigation', () => {- it.each([- { kind: 'allDay' as const, startDate: '2025-01-01', endDate: '2025-01-03' },- {- kind: 'timed' as const,- startsAt: '2025-01-01T12:00:00.000Z',- endsAt: '2025-01-01T13:00:00.000Z',- },- ])('round-trips $kind event times', (time) => {- const result = inboxPreviewNavigation({- type: 'calendar_event',- id: 'event-1',- time,- });- expect(result.search.calendarTimeKind).toBe(time.kind);- expect(inboxPreviewSelection(result.params, result.search)).toMatchObject({- type: 'calendar_event',- id: 'event-1',- time,+ it('targets the Calendar period path with the event and locator in search', () => {+ const range = {+ start: '2025-01-01T00:00:00.000Z',+ end: '2025-01-02T00:00:00.000Z',+ startDate: '2025-01-01',+ endDate: '2025-01-02',+ };+ expect(+ inboxCalendarNavigation(+ { eventId: 'event-1', occurrenceKey: 'occurrence-1', range },+ 'timeGridWeek'+ )+ ).toEqual({+ params: { period: 'timeGridWeek' },+ search: {+ channels: undefined,+ calendar: {+ eventId: ['event-1'],+ occurrenceKey: ['occurrence-1'],+ startDate: [range.startDate],+ endDate: [range.endDate],+ },+ },});+ expect(inboxCalendarNavigation({}, 'timeGridWeek')).toBeUndefined();});});@@ -626,18 +648,24 @@ describe('Inbox channel preview navigation', () => {blockType: 'channel',previewId: 'channel-1',});- expect(result.search).toMatchObject({- targetMessageId: 'message-1',- targetThreadId: 'thread-1',+ expect(result.search).toEqual({+ channels: { messageId: ['message-1'], threadId: ['thread-1'] },});});it('keeps untargeted channels at latest', () => {expect(inboxPreviewNavigation({ type: 'channel', id: 'channel-1' }).search- ).toMatchObject({- targetMessageId: '',- targetThreadId: '',- });+ ).toEqual({ channels: undefined });+ });+ it('names markdown subtypes in the path', () => {+ expect(+ inboxPreviewNavigation({+ type: 'document',+ id: 'task-1',+ fileType: 'md',+ subType: { type: 'task', is_completed: false },+ }).params+ ).toEqual({ blockType: 'task', previewId: 'task-1' });});});@@ -1055,16 +1083,16 @@ describe('getDocumentCommentTarget', () => {const result = inboxPreviewNavigation(documentRow([commentNotification('n1', 'comment-1')]) as never);- expect(result.search.targetCommentId).toBe('comment-1');- const selection = inboxPreviewSelection(result.params, result.search);- expect(selection).toMatchObject({- type: 'document',- id: 'doc-1',- commentTarget: { commentId: 'comment-1' },+ expect(result.params).toEqual({ blockType: 'md', previewId: 'doc-1' });+ expect(result.search.drive).toEqual({+ commentId: ['comment-1'],});- expect(previewBlockTarget(selection!).params).toEqual({- comment_id: 'comment-1',+ const target = inboxPreviewTarget(result.params, {+ channel: { messageId: '', threadId: '' },+ document: { commentId: 'comment-1' },});+ expect(target).toMatchObject({ blockType: 'md', blockId: 'doc-1' });+ expect(target.params).toEqual({ comment_id: 'comment-1' });});it('passes the comment to a document preview', () => {diff --git a/apps/web/src/lib/split-router/router.ts b/apps/web/src/lib/split-router/router.tsindex 558a557631..9018544ab4 100644--- a/apps/web/src/lib/split-router/router.ts+++ b/apps/web/src/lib/split-router/router.ts@@ -255,6 +255,18 @@ export function createSplitRouter<TSplitId>(if (index < 0) return;return accepted[index];};+ // A settled destination with the same URL and route state needs no new key,+ // transition, history entry, or middleware run.+ const isCurrentDestination = (splitId: TSplitId, entry: SplitRouterEntry) => {+ if (transitions.has(GLOBAL_TRANSITION) || transitions.pending(splitId))+ return false;+ const current = findEntry(splitId);+ return (+ current !== undefined &&+ deepEqual(current.location, entry.location) &&+ Object.is(current.state, entry.state)+ );+ };const findClaimedSplit = (claim: SplitRouteClaim,@@ -788,8 +800,11 @@ export function createSplitRouter<TSplitId>(};if (state !== undefined) next.state = state;- let targetId: TSplitId | undefined;- if (target !== 'new-split') targetId = target;+ const targetId =+ target === 'new-split' ? undefined : (target as TSplitId);+ if (targetId !== undefined && isCurrentDestination(targetId, next)) {+ return;+ }transitionEntry({key: targetId ?? Symbol('new-split-transition'),splitId: targetId,@@ -826,6 +841,7 @@ export function createSplitRouter<TSplitId>([namespace]: update,}),};+ if (isCurrentDestination(splitId, next)) return;transitionEntry({key: splitId,diff --git a/apps/web/src/lib/split-router/tests/router.test.ts b/apps/web/src/lib/split-router/tests/router.test.tsindex 345c63948e..af358ad08c 100644--- a/apps/web/src/lib/split-router/tests/router.test.ts+++ b/apps/web/src/lib/split-router/tests/router.test.ts@@ -889,6 +889,46 @@ describe('split router', () => {expect(routeParams(router.route(first!.splitId)).folderId).toBe('three');});+ it('ignores navigation and search writes that resolve to the current destination', async () => {+ const middleware = vi.fn<SplitRouterMiddleware>(() => undefined);+ const location = createMemorySplitRouterLocation(+ '/drive/folder/one?s0.drive.sort=name'+ );+ const layout = createLayout();+ const router = createSplitRouter({+ layout,+ routes,+ location,+ middleware: [middleware],+ });+ await router.settled();+ const splitId = layout.snapshot().entries[0]!.splitId;+ const listener = vi.fn();+ router.subscribe(listener);+ middleware.mockClear();+ const committed = location.history().length;++ router.navigate(splitId, '/drive/folder/one');+ router.navigate(splitId, {+ route: driveFolderRoute,+ params: { folderId: 'one' },+ });+ router.navigate(splitId, '/drive/folder/one', { replace: true });+ router.updateSearch(splitId, 'drive', { sort: ['name'] });+ await router.settled();++ expect(middleware).not.toHaveBeenCalled();+ expect(listener).not.toHaveBeenCalled();+ expect(location.history()).toHaveLength(committed);+ expect(router.canGo(splitId, -1)).toBe(false);++ // A real change still transitions.+ router.updateSearch(splitId, 'drive', { sort: ['size'] });+ await router.settled();+ expect(middleware).toHaveBeenCalledOnce();+ expect(location.read().search).toBe('?s0.drive.sort=size');+ });+it('pushes a repeated route as a new history entry', async () => {const location = createMemorySplitRouterLocation('/drive/folder/one');const layout = createLayout();diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex d32c5d443e..9a08af02ab 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -326,9 +326,12 @@ records `path` (`catch_up` or `full`) and `reason`## Chat navigation railFollowing a channel mention or browser notification for the conversation already-shown in Chat activates that workspace and jumps to the targeted message or reply. It keeps-the existing preview and does not show a **Content already open** toast. The-same applies to a channel preview in Home; a closed channel opens normally.+shown in Chat activates that workspace and jumps to the targeted message or reply.+It keeps the shared channel detail mounted and does not show a **Content already open**+toast. The same applies to a channel preview in Home; a closed channel opens normally.+In Chat, the detail uses the shared channel top bar with Messages, Attachments,+Participants, and Calls tabs (when calls are enabled). A message target switches+back to Messages; changing unread notifications does not restart navigation.The title bar's **Hide navigation** control hides the whole rail. Reopen it with**Show navigation** (the hamburger) immediately before the conversation title,@@ -342,7 +345,7 @@ On desktop, the Chat rail has `All` and `Recent` tabs. All contains anoptional `Favorites` section and theindependently paginated `Channels` and `DMs` sections. Favorites appears whenthe user has channel favorites and only lists channels. Channel favorites open-in the channel preview. Shift-clicking a favorite, channel, or DM opens that+in the shared channel detail. Shift-clicking a favorite, channel, or DM opens thatconversation in a new split instead.### Channel labelsdiff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex dc5f59b678..346eef5218 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -20,11 +20,11 @@ Switching tabs or navigating an in-app route is not a back/forward-cache restore| `/app/invite?token=<token>` | GTM invite welcome page ("Welcome, <first name>", Continue → signup). Links come from the staff portal, last 48h, and grant the first month of Premium free once the account is created || `/app/internal/invite-links` | Macro staff only (`@macro.com`): create GTM invite links and track opens, signups, and subscriptions || `/app/inbox` | Desktop: Home (notifications + recent activity); mobile: Notifications soup |-| `/app/inbox/<block-type>/<uuid>` | Home with a heterogeneous item opened inline; target metadata is stored in `sN.inbox-preview.*` query values |+| `/app/inbox/<block-type>/<uuid>` | Home with an item opened inline; `<block-type>` may be an alias such as `task`; a targeted channel message uses `sN.channels.messageId` (and optionally `sN.channels.threadId`) and a document comment `sN.drive.commentId`; a calendar row renders the Calendar view inline at `/app/inbox/calendar/<month-or-week-or-day>` with the event, occurrence, and locator range in `sN.calendar.*` || `/app/mail` | Email client || `/app/mail/<uuid>` | Email with a thread opened inline; a targeted message uses `sN.email-detail.messageId` || `/app/channels` | Channels list |-| `/app/channels/<uuid>` | Channels with a conversation opened inline; message/thread targets use `sN.channel-detail.*` |+| `/app/channels/<uuid>` | Channels with a conversation opened inline; message/thread targets use `sN.channels.messageId` and `sN.channels.threadId`, in the same namespace as the Channels tab || `/app/drive` | Files (Drive defaults to My Files) || `/app/drive/<recent-or-shared>` | A Drive tab (`/app/drive/tab/<...>` remains a compatibility alias) || `/app/drive/folder/<uuid>` | A Drive folder; breadcrumbs resolve from current accessible folder data |@@ -40,7 +40,7 @@ Switching tabs or navigating an in-app route is not a back/forward-cache restore| `/app/companies` | Customers (CRM; needs a team) || `/app/activity` | Activity heatmap + feed || `/app/home` | Assistant (AI-first landing) |-| `/app/calendar/<month-or-week-or-day>` | Calendar; the focused event uses `sN.calendar.eventId` |+| `/app/calendar/<month-or-week-or-day>` | Calendar; the focused event, its occurrence, and the locator range use `sN.calendar.*` || `/app/<document-type>/<uuid>` | Legacy document URL (including `md`, `pdf`, `canvas`, `spreadsheet`, and the other Drive document types); redirects to `/app/drive/<document-type>/<uuid>` || `/app/documents`, `/app/files` | Legacy Files views; redirect to `/app/drive` || `/app/chat/<uuid>` | A standalone AI chat |@@ -50,6 +50,17 @@ Switching tabs or navigating an in-app route is not a back/forward-cache restore| `/app/md/<doc>/channel/<channel>` | Doc + channel in a split || `/app/settings/account` | Settings (also `/app/settings/api-keys`, `/mcp-server`, `/shortcuts`, etc.) |+When an event opens inline from Home, changing the Calendar period stays under+`/app/inbox/calendar/`, updates the period segment, and re-focuses that event.+Back/Forward restores the period and its event locator from `sN.calendar.*`.++Home uses the shared channel and file details for channel conversations and+supported documents, with a **Home** breadcrumb that returns to the list. A+channel message or thread target stays in its conversation. Document comment+targets, spreadsheets, unknown items, and other unsupported block types retain+the legacy inline preview so their navigation still works. The URL shape stays+`/app/inbox/<block-type>/<uuid>` in either rendering mode.+On touch devices, documents (including tasks) open in legacy blocks rather thaninline Drive details. Canonical `/app/drive/.../<document-type>/<uuid>` links alsofall back to legacy document routes. This uses touch detection, not the native-app