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
feat: new preview mode (#4998)
Peter Chinman36d5559173ec
diff --git a/apps/web/src/components/app/PreviewPanel.tsx b/apps/web/src/components/app/PreviewPanel.tsxdeleted file mode 100644index 6a007ce5d3..0000000000--- a/apps/web/src/components/app/PreviewPanel.tsx+++ /dev/null@@ -1,270 +0,0 @@-import {- getChannelEntityTarget,- navigateChannelEntityToTarget,-} from '@app/features/next-soup/utils';-import { getChannelParams } from '@block-channel/utils/link';-import type { BlockAliasContext, BlockName } from '@core/block';-import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';-import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';-import type { BlockOrchestrator } from '@core/orchestrator';-import { throttledDependent } from '@core/util/debounce';-import type { NonNullableFields } from '@core/util/withRequired';-import {- type EntityData,- isGithubPrEntity,- isSnippetEntity,- isTaskEntity,-} from '@entity';-import { createContextProvider } from '@solid-primitives/context';-import {- type Component,- createMemo,- createRenderEffect,- createSignal,- on,- Show,- Suspense,- untrack,-} from 'solid-js';-import { Dynamic } from 'solid-js/web';-import {- SplitPanelContext,- type SplitPanelContextType,-} from './split-layout/context';--export const [PreviewPanelContext, useMaybePreviewPanel] =- createContextProvider(- (props: { previewEntity: EntityData; onFocusOut?: VoidFunction }) => {- return {- previewEntity: () => props.previewEntity,- onFocusOut: () => props.onFocusOut?.(),- };- }- );--type PreviewPanel = {- selectedEntity: EntityData | undefined;- orchestrator: BlockOrchestrator;- splitPanelContext: SplitPanelContextType;- onFocusOut?: VoidFunction;- ref?: (el: HTMLElement) => void;-};--const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (- props-) => {- let scopedSplitPanelContextType: SplitPanelContextType = {} as any;- const scopedLayoutRefs: SplitPanelContextType['layoutRefs'] = {- ...props.splitPanelContext.layoutRefs,- };-- if (props.selectedEntity.type === 'project') {- // Isolate the previewed project's preview state from the outer panel so- // the nested SoupView's sync effect doesn't clobber the parent. Preview- // can only work one level deep, so we never enable preview inside.- const [previewState, setPreviewState] = createSignal(false);- scopedSplitPanelContextType.previewState = [previewState, setPreviewState];- }-- const throttledSelectedEntity = throttledDependent(- () => props.selectedEntity,- 150- );-- const blockInstance = () => {- const aliasContext = isTaskEntity(props.selectedEntity)- ? ({- alias: 'task',- baseType: 'md',- } as BlockAliasContext)- : isSnippetEntity(props.selectedEntity)- ? ({- alias: 'snippet',- baseType: 'md',- } as BlockAliasContext)- : undefined;-- let blockType: BlockName;- let blockId: string;- if (props.selectedEntity.type === 'document') {- blockType = fileTypeToResolvedBlockName(props.selectedEntity.fileType);- blockId = props.selectedEntity.id;- } else if (- props.selectedEntity.type === 'channel_message' ||- props.selectedEntity.type === 'channel_thread'- ) {- blockType = 'channel';- blockId = props.selectedEntity.channelId;- } else if (props.selectedEntity.type === 'foreign') {- // GitHub PRs preview in the dedicated /pr block (keyed by foreign entity- // id); other foreign sources fall back to the generic unknown block.- // Mirrors the open path in openEntityInSplitFromUnifiedList, which is- // also gated on USE_MACRO_PR_SUMMARY_BLOCK.- blockType =- USE_MACRO_PR_SUMMARY_BLOCK && isGithubPrEntity(props.selectedEntity)- ? 'pr'- : 'unknown';- blockId = props.selectedEntity.id;- } else if (props.selectedEntity.type === 'crm_company') {- blockType = 'company';- blockId = props.selectedEntity.id;- } else if (props.selectedEntity.type === 'crm_contact') {- blockType = 'contact';- blockId = props.selectedEntity.id;- } else {- blockType = props.selectedEntity.type;- blockId = props.selectedEntity.id;- }-- // Sample the target untracked so notification churn can't remount the- // block. Mounting a channel with its target params makes the first- // messages fetch the load_around one, instead of latest-page (visible- // flash) followed by the id-keyed re-target below.- const channelTarget =- blockType === 'channel'- ? untrack(() => getChannelEntityTarget(props.selectedEntity))- : undefined;-- return props.orchestrator.createBlockInstance(blockType, blockId, {- aliasContext,- params:- channelTarget?.kind === 'message'- ? getChannelParams(channelTarget.messageId, channelTarget.threadId)- : undefined,- });- };- const [interactedWith, setInteractedWith] = createSignal(false);-- // Key on the id: the entity object is live, and unrelated notification- // churn must not re-target the previewed channel.- const selectedEntityId = createMemo(() => props.selectedEntity.id);-- createRenderEffect(- on(selectedEntityId, () => {- setInteractedWith(false);- navigateChannelEntityToTarget(props.selectedEntity, props.orchestrator);- })- );-- createRenderEffect(() => {- // noop: previously we constrained toolbarLeft width based on the main split's- // halfSplitState. This caused preview topbars (e.g. the hamburger menu) to- // appear "hung" from the middle in preview mode.- // Keeping this effect slot in case we need future layout hacks.- });-- return (- <div- ref={props.ref}- class="flex flex-col size-full"- onFocusIn={(event) => {- if (interactedWith()) return;-- // TODO: use state instead to determine when preview block can recieve focus- if (event.target.hasAttribute('data-allow-focus-in-preview')) {- setInteractedWith(true);- return;- }-- // Prevent blocks from stealing focus in preview mode.- // Redirect to the previous element if it was outside the preview,- // otherwise blur the target to keep focus on the search list.- const relatedTarget = event.relatedTarget;- const currentTarget = event.currentTarget;-- if (- relatedTarget instanceof HTMLElement &&- !currentTarget.contains(relatedTarget)- ) {- relatedTarget.focus();- } else {- (event.target as HTMLElement).blur?.();- }- }}- onPointerDown={() => {- setInteractedWith(true);- }}- tabIndex={-1}- >- {/* Display the split header content here */}- <div- class="relative w-full flex items-center justify-between shrink-0 bg-surface px-2 py-2"- data-preview-split-header- >- <div- class="flex h-full items-center gap-1"- ref={(ref) => {- scopedLayoutRefs.headerLeft = ref;- }}- />- <div- class="flex h-full items-center gap-1"- ref={(ref) => {- scopedLayoutRefs.headerRight = ref;- }}- />- </div>-- {/* Legacy: We've moved to a single top bar in most places but some blocks/places still try to display a toolbar as well.- This is for those blocks so we can see their toolbars int eh preview panel */}- <div- class="relative w-full flex items-center justify-between shrink-0 bg-surface px-2 py-2"- data-preview-split-toolbar- >- <div- class="flex h-full items-center gap-1"- ref={(ref) => {- scopedLayoutRefs.toolbarLeft = ref;- }}- />- <div- class="flex h-full items-center gap-1"- ref={(ref) => {- scopedLayoutRefs.toolbarRight = ref;- }}- />- </div>-- <div class="flex-1 min-h-0">- <SplitPanelContext.Provider- value={{- ...props.splitPanelContext,- ...scopedSplitPanelContextType,- layoutRefs: scopedLayoutRefs,- // Disable halfSplit positioning logic for preview topbars.- // The preview panel is already laid out by the outer split; applying halfSplitState- // here incorrectly shifts toolbar content towards the middle.- halfSplitState: undefined,- }}- >- <PreviewPanelContext- previewEntity={throttledSelectedEntity()}- onFocusOut={props.onFocusOut}- >- <Suspense>- <Dynamic component={blockInstance().element} />- </Suspense>- </PreviewPanelContext>- </SplitPanelContext.Provider>- </div>- </div>- );-};--export const PreviewPanel: Component<PreviewPanel> = (props) => {- return (- <div class="flex flex-row size-full">- <Show when={props.selectedEntity}>- {(selectedEntity) => (- <PreviewPanelContent- ref={props.ref}- selectedEntity={selectedEntity()}- orchestrator={props.orchestrator}- splitPanelContext={props.splitPanelContext}- onFocusOut={props.onFocusOut}- />- )}- </Show>- </div>- );-};diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsxindex 61c841714d..cf242641ef 100644--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx@@ -1328,7 +1328,7 @@ export const AppSidebar = (props: AppSidebarProps) => {<divclass={cn('group/sidebar flex flex-col gap-0 overflow-hidden bg-surface px-3 pb-3 pt-4 text-[13px]',- isExpanded() && 'relative h-full shrink-0 max-w-60 w-60 opacity-100',+ isExpanded() && 'relative h-full shrink-0 max-w-55 w-55 opacity-100',props.sidebarState === 'hidden' &&'fixed left-0 top-0 bottom-0 h-full -translate-x-full max-w-0 w-0 opacity-0 pointer-events-none',isCollapsed() && 'fixed z-modal-content',@@ -1336,7 +1336,7 @@ export const AppSidebar = (props: AppSidebarProps) => {!overlayOpen() &&'left-0 inset-y-0 h-full max-w-0 w-0 opacity-0 pointer-events-none -translate-x-2',isOverlayExpanded() &&- 'left-0 inset-y-0 h-full max-w-60 w-60 opacity-100 translate-x-0 rounded-r-xl shadow-menu ring-1 ring-edge-muted'+ 'left-0 inset-y-0 h-full max-w-55 w-55 opacity-100 translate-x-0 rounded-r-xl shadow-menu ring-1 ring-edge-muted')}data-expanded={isExpandedView()}data-slim={isSlim()}diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsxindex ea1273685f..3ee2c6a91b 100644--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx@@ -6,9 +6,11 @@ import {} from '@components/app/sidebarVisibility';import { Resize } from '@core/component/Resize';import { splitContainerSelector } from '@core/dom-selectors';+import { isMobile } from '@core/mobile/isMobile';import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { tabTitleSignal } from '@core/signal/tabTitle';-import { useNavigate } from '@solidjs/router';+import { useWindowSize } from '@solid-primitives/resize-observer';+import { useLocation, useNavigate } from '@solidjs/router';import { cn } from '@ui';import {type Accessor,@@ -27,19 +29,22 @@ import { SplitPanel } from './components/SplitPanel';import { SplitLayoutContext } from './context';import {createSplitLayout,- type SplitContent,SplitEvent,type SplitEventWithType,type SplitId,type SplitManager,type SplitState,} from './layoutManager';-import { decodePairs } from './layoutUtils';+import { createLayoutUrlSync, restorePreviewPairs } from './layoutUrlSync';import {createMobileSwipeLayout,type MobileSwipeLayout,} from './mobile/createMobileSwipeLayout';import { MobileSplitContainer } from './mobile/MobileSplitContainer';+import {+ loadRestorablePreviewLayout,+ PREVIEW_QUERY_PARAM,+} from './previewPersistence';type SplitLayoutContainerProps = {pairs: string[];@@ -55,75 +60,6 @@ function getParentSplitId(element: Element | null) {return splitId as SplitId;}-function sameSplitContentIdentity(a: SplitContent, b: SplitContent) {- return a.type === b.type && a.id === b.id;-}--function getUrlSyncAffectedSplit(- splitManager: SplitManager,- currentPairs: SplitContent[],- nextPairs: SplitContent[]-) {- const changedIndex = nextPairs.findIndex(- (nextPair, index) =>- !currentPairs[index] ||- !sameSplitContentIdentity(currentPairs[index], nextPair)- );-- if (changedIndex < 0) return undefined;-- const affectedPair = nextPairs[changedIndex];- return splitManager- .splits()- .find((split) => sameSplitContentIdentity(split.content, affectedPair));-}--/**- * Creates an effect that syncs the layout manager with the URL.- *- * @param splitManager The layout manager to sync with- * @param pairs The accessor to the current pairs- * @param decodedPairs The accessor to the decoded pairs- */-function createLayoutUrlSync(- splitManager: SplitManager,- pairs: Accessor<string[]>,- decodedPairs: Accessor<SplitContent[]>-) {- const navigate = useNavigate();- const urlLayoutDrift = createMemo(- () => splitManager.getUrlSegments().join('/') !== pairs().join('/')- );-- /** Syncs changes from the layout manager to the URL*/- createEffect(- on([() => splitManager.getUrlSegments().join('/')], () => {- if (urlLayoutDrift()) {- const nextUrlSegments = splitManager.getUrlSegments();- const nextPairs = decodePairs(nextUrlSegments);- const affectedSplit = getUrlSyncAffectedSplit(- splitManager,- decodedPairs(),- nextPairs- );- const replace = affectedSplit?.lastNavigationCause === 'replace';-- // Flush the state to the url- navigate(`/${nextUrlSegments.join('/')}`, { replace });- }- })- );-- /** Syncs changes from the URL to the layout manager */- createEffect(- on([pairs], () => {- if (urlLayoutDrift()) {- splitManager.reconcile(decodedPairs());- }- })- );-}-/*** Manages focus / active between splits*@@ -308,9 +244,22 @@ function createSplitFocusTracker(props: {}export function SplitLayoutContainer(props: SplitLayoutContainerProps) {- const decodedPairs = () => decodePairs(props.pairs);+ const location = useLocation();+ const navigate = useNavigate();+ const viewportSize = useWindowSize();+ const previewQuery = () => location.query[PREVIEW_QUERY_PARAM];+ const decodedLayout = createMemo(() =>+ loadRestorablePreviewLayout(props.pairs, previewQuery(), {+ allowPreviewPairs: !isMobile(),+ })+ );+ const initialLayout = decodedLayout();const blockOrchestrator = useGlobalBlockOrchestrator();- const splitManager = createSplitLayout(blockOrchestrator, decodedPairs());+ const splitManager = createSplitLayout(+ blockOrchestrator,+ initialLayout.contents+ );+ restorePreviewPairs(splitManager, initialLayout.previewPairs);const [, setTabTitle] = tabTitleSignal;const sidebar = useSidebarCollapse();@@ -345,7 +294,17 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {// <For> on plain ids for stable referential equalityconst ids = createMemo(() => splits().map(({ id }) => id));- createLayoutUrlSync(splitManager, () => props.pairs, decodedPairs);+ createLayoutUrlSync(+ splitManager,+ () => props.pairs,+ previewQuery,+ decodedLayout,+ {+ navigate,+ search: () => location.search,+ hash: () => location.hash,+ }+ );createSplitFocusTracker({ splitManager, panelRefs, splits });return (@@ -369,7 +328,19 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {<Show when={splitManager.getSplit(id)}>{(handle) => (<Suspense>- <Resize.Panel id={id} minSize={400} index={index()}>+ <Resize.Panel+ id={id}+ minSize={400}+ // Automatic redistribution targets an engaged+ // Controller at its configured preferred width.+ // This is not a hard max: the gutter can still be+ // dragged past it.+ redistributionPreferredSize={splitManager.previewControllerWidth(+ id,+ viewportSize.width+ )}+ index={index()}+ ><SplitPanelsplit={splits()[index()]!}handle={handle()}diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 1109215b9b..3b79bdb115 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -4,6 +4,7 @@ import type { SetPredicatesInput } from '@app/features/next-soup/filters/filter-import { mergeQuery } from '@app/features/next-soup/filters/filter-store/query-store';import type { Query } from '@app/features/next-soup/filters/filter-store/types';import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';+import { NonMemberChannelPreview } from '@app/features/next-soup/soup-view/non-member-channel-preview';import { SoupView } from '@app/features/next-soup/soup-view/soup-view';import { SettingsPanelComponentWrapper } from '@app/features/settings/Settings';import { useAnalytics } from '@app/lib/analytics/analytics-context';@@ -25,7 +26,9 @@ import {} from '@core/constant/featureFlags';import { useUserContext } from '@core/context/user';import type { ViewId } from '@core/types/view';+import EmptyStatePreviewIcon from '@design/empty-state-doc.svg';import { useAutomationEntities } from '@queries/agent-schedule/entities';+import { EmptyStatePanel } from '@ui';import { type Component, type JSXElement, lazy, onMount, Show } from 'solid-js';import type { SplitContent } from './layoutManager';import { useSplitPanelOrThrow } from './layoutUtils';@@ -380,6 +383,49 @@ registerComponent(/** END - APP ROUTES */registerComponent('loading', () => <LoadingBlock />);+// Placeholder a Preview Pair's Viewer opens before its Controller has+// navigated anywhere (see layoutManager engagePreviewMode).+registerComponent('preview-empty', () => {+ const panel = useSplitPanelOrThrow();+ onMount(() => panel.handle.setDisplayName('Preview'));+ return (+ <EmptyStatePanel+ graphic={EmptyStatePreviewIcon}+ title="No content selected"+ description="Select an item from the connected list to preview it here"+ centered+ />+ );+});+// Join prompt for a channel the viewer can see but hasn't joined, shown in a+// Preview Pair's Viewer when the controlling list focuses such a row (see+// openEntityInSplitFromUnifiedList). Params don't round-trip through the URL,+// so a restored split has none — fall back to the placeholder and let the+// controller's focus→preview effect re-open the real prompt.+registerComponent('non-member-channel', (params) => {+ const panel = useSplitPanelOrThrow();+ const channelId =+ typeof params?.channelId === 'string' ? params.channelId : undefined;+ if (!channelId) {+ return <RedirectSplit to={{ type: 'component', id: 'preview-empty' }} />;+ }+ const channelName =+ typeof params?.channelName === 'string' ? params.channelName : 'Channel';+ const memberCount =+ typeof params?.memberCount === 'number' ? params.memberCount : 0;+ onMount(() => panel.handle.setDisplayName(channelName));+ return (+ <NonMemberChannelPreview+ channelId={channelId}+ channelName={channelName}+ memberCount={memberCount}+ // Join landed — hand the Viewer off to the real channel block in place.+ onJoined={() =>+ panel.handle.replace({ next: { type: 'channel', id: channelId } })+ }+ />+ );+});registerComponent('channel-compose', () => {usePageViewTracking('channel-compose');return <ChannelCompose />;diff --git a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsxindex 3e6a06c605..da60b4444e 100644--- a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx+++ b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx@@ -52,7 +52,6 @@ function PopoverSplitModal(props: {}) {const [panelRef, setPanelRef] = createSignal<HTMLElement | null>(null);const [contentOffsetTop, setContentOffsetTop] = createSignal(0);- const [previewState, setPreviewState] = createSignal(false);const [titleFileMenuRef, setTitleFileMenuRef] =createSignal<HTMLDivElement>();const [titleFileMenuTrigger, setTitleFileMenuTrigger] =@@ -78,6 +77,8 @@ function PopoverSplitModal(props: {toggleSpotlight: () => {},isSpotLight: () => false,isPopover: () => true,+ isViewerSplit: () => false,+ isControllerSplit: () => false,replace: () => {},removeFromHistory: () => {},registerContentChangeListener: () => {},@@ -99,6 +100,10 @@ function PopoverSplitModal(props: {registerEntryStateCaptor: () => () => {},captureEntryState: () => {},currentEntryState: () => undefined,+ canEngagePreview: () => false,+ engagePreview: () => {},+ disengagePreview: () => {},+ viewerId: () => undefined,};const stubPanelContext: SplitPanelContextType = {@@ -111,10 +116,6 @@ function PopoverSplitModal(props: {setContentOffsetTop,bottomPanel: () => undefined,registerBottomPanel: () => () => {},- previewState: [previewState, setPreviewState] as [- typeof previewState,- typeof setPreviewState,- ],layoutRefs: {},titleFileMenuRef,setTitleFileMenuRef,diff --git a/apps/web/src/components/app/split-layout/components/PreviewButton.tsx b/apps/web/src/components/app/split-layout/components/PreviewButton.tsxnew file mode 100644index 0000000000..036abde4f8--- /dev/null+++ b/apps/web/src/components/app/split-layout/components/PreviewButton.tsx@@ -0,0 +1,73 @@+import { useAnalytics } from '@app/lib/analytics/analytics-context';+import { registerHotkey } from '@core/hotkey/hotkeys';+import { TOKENS } from '@core/hotkey/tokens';+import EyeIcon from '@phosphor-icons/core/regular/eye.svg?component-solid';+import EyeSlashIcon from '@phosphor-icons/core/regular/eye-slash.svg?component-solid';+import { Button, Tooltip } from '@ui';+import { Show } from 'solid-js';+import { useSplitPanelOrThrow } from '../layoutUtils';++/** Toggle Preview mode for eligible Controller content outside a Viewer. */+export function PreviewButton(+ props: {+ disabled?: boolean;+ disabledLabel?: string;+ onEngage?: () => void;+ } = {}+) {+ const panel = useSplitPanelOrThrow();+ const analytics = useAnalytics();++ const isViewer = () => panel.handle.isViewerSplit();+ const isController = () => panel.handle.isControllerSplit();+ const canEngage = () => !props.disabled && panel.handle.canEngagePreview();+ const unavailableLabel = () =>+ props.disabled+ ? (props.disabledLabel ?? 'Preview unavailable')+ : 'No space for preview';++ const togglePreview = () => {+ if (isController()) {+ panel.handle.disengagePreview();+ return;+ }+ if (!canEngage()) return;++ analytics.track('preview_panel_use');+ panel.handle.engagePreview();+ if (panel.handle.isControllerSplit()) props.onEngage?.();+ };++ registerHotkey({+ hotkeyToken: TOKENS.unifiedList.togglePreview,+ scopeId: panel.splitHotkeyScope,+ description: 'Toggle preview',+ condition: () => !isViewer() && canEngage(),+ keyDownHandler: () => {+ togglePreview();+ return true;+ },+ hotkey: 'space',+ });++ return (+ <Show when={!isViewer()}>+ <Tooltip+ hotkey={canEngage() ? TOKENS.unifiedList.togglePreview : undefined}+ label={canEngage() ? 'Preview' : unavailableLabel()}+ >+ <Button+ onClick={togglePreview}+ variant="base"+ size="sm"+ depth={2}+ class="bg-surface"+ disabled={!canEngage()}+ >+ {isController() ? <EyeSlashIcon /> : <EyeIcon />}+ <span>Preview</span>+ </Button>+ </Tooltip>+ </Show>+ );+}diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsxindex df61e298e3..eb477ae98d 100644--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx@@ -179,8 +179,13 @@ function SplitCloseButton() {return isOnlySplit && isNotUnifiedList ? 'Return to list' : 'Close';});+ // A Viewer has no close affordance or close hotkey: it closes with its+ // Controller, when its Preview Pair dissolves (external navigation or the+ // Controller leaving its list view), or via the preview toggle.+ const isPreviewViewer = () => context.handle.isViewerSplit();+return (- <Show when={layout.manager.splits().length > 1}>+ <Show when={layout.manager.splits().length > 1 && !isPreviewViewer()}><Buttonclass="p-1 rounded-lg"label={label()}@@ -374,10 +379,18 @@ function SplitHeaderContextMenu(props: ParentProps) {disabled={!hasOtherSplits()}onClick={() => {const currentSplitId = panel.handle.id;+ // A Preview Pair is one unit: keep the current split's partner so+ // closing "other" splits from a Viewer doesn't strand it by+ // removing its Controller (or vice versa).+ const partnerId =+ layout.manager.controllerOf(currentSplitId) ??+ layout.manager.viewerOf(currentSplitId);+ const kept = new Set([currentSplitId, partnerId]);+const otherSplitIds = layout.manager.splits().map((split) => split.id)- .filter((id) => id !== currentSplitId);+ .filter((id) => !kept.has(id));for (const splitId of otherSplitIds) {layout.manager.removeSplit(splitId);diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsxindex 076acbd1f2..c707bfe3d8 100644--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx@@ -5,6 +5,7 @@ import { SoupViewContextProvider } from '@app/features/next-soup/soup-view/soup-import { globalSplitManager } from '@app/signal/splitLayout';import { MobileTopEdgeFade } from '@components/app/mobile/MobileEdgeFade';import { isSoloSettings } from '@core/constant/SettingsState';+import { BlockOpenTrackingDelayContext } from '@core/context/blockOpenTracking';import { splitContainerAttribute } from '@core/dom-selectors';import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { isMobile } from '@core/mobile/isMobile';@@ -46,13 +47,18 @@ type SplitPanelProps = {index: number;};+/**+ * A Preview Pair Viewer displays content passively. Only record it as opened+ * after the user lingers, so keyboard scanning does not mark every row viewed.+ */+const PREVIEW_VIEWER_OPEN_TRACK_DELAY_MS = 1_500;+export function SplitPanel(props: SplitPanelProps) {const [attachHotKeys, splitHotkeyScope] = useHotkeyDOMScope(`split=${props.split.id}`);const [panelRef, setPanelRef] = createSignal<HTMLDivElement | null>(null);const [contentOffsetTop, setContentOffsetTop] = createSignal(0);- const [previewState, setPreviewState] = createSignal(false);const [titleFileMenuRef, setTitleFileMenuRef] =createSignal<HTMLDivElement>();const [titleFileMenuTrigger, setTitleFileMenuTrigger] =@@ -81,6 +87,7 @@ export function SplitPanel(props: SplitPanelProps) {const content = props.handle.content();return !isListViewID(content.id);},+ isViewerSplit: () => props.handle.isViewerSplit(),getSplitCount: () => splitLayoutHelpers.getSplitCount(),toggleSpotlight: () => props.handle.toggleSpotlight(),canGoForward: () => props.handle.canGoForward(),@@ -100,6 +107,10 @@ export function SplitPanel(props: SplitPanelProps) {createEffect(on([panelRef], () => {if (isMobile()) return;+ // Only the active split may claim focus on mount. A Preview Pair's Viewer+ // is created with activate:false while its controller stays active, and+ // must not steal the keyboard from it.+ if (!props.active) return;panelRef()?.focus();}));@@ -157,11 +168,58 @@ export function SplitPanel(props: SplitPanelProps) {const splitUnfocusedStyling = () =>!isMobile() && !props.active && multipleSplits();+ const gutterSize = () =>+ globalSplitManager()?.resizeContext()?.gutterSize() ?? 0;++ /**+ * This split is a Viewer sitting immediately right of its Controller: the+ * pane slides left across the gutter so it sits flush against the+ * Controller, reading as tucked behind it.+ */+ const tuckedBehindController = createMemo(() => {+ return (+ !isMobile() && !props.handle.isSpotLight() && props.handle.isViewerSplit()+ );+ });++ /**+ * This split is a preview controller with its viewer tucked flush against+ * its right edge: paint above the viewer so the controller's card and+ * shadow read as being in front.+ */+ const hasTuckedViewer = createMemo(() => {+ return (+ !isMobile() &&+ !props.handle.isSpotLight() &&+ props.handle.isControllerSplit()+ );+ });++ /**+ * Both members of a tucked Preview Pair share the active edge color when+ * either member is active. The active member stays solid; its partner is+ * dashed so focus ownership remains visible without breaking the Preview+ * Pair's shared visual treatment.+ */+ const previewPairFocusStyling = createMemo(() => {+ const manager = globalSplitManager();+ if (!manager || isMobile() || props.handle.isSpotLight()) return false;++ const peerId = props.handle.isControllerSplit()+ ? manager.viewerOf(props.split.id)+ : props.handle.isViewerSplit()+ ? manager.controllerOf(props.split.id)+ : undefined;+ if (!peerId || manager.getSplit(peerId)?.isSpotLight()) return false;++ const activeId = manager.activeSplitId();+ return activeId === props.split.id || activeId === peerId;+ });+return (<SoupContextProvider soup={nextSoup}><SplitPanelContext.Providervalue={{- previewState: [previewState, setPreviewState],isPanelActive: () => props.active,handle: props.handle,setContentOffsetTop,@@ -214,6 +272,14 @@ export function SplitPanel(props: SplitPanelProps) {// mobile: status bar + floating header strip.'--mobile-content-inset-top':'calc(var(--safe-top, 0px) + var(--split-header-height, 0px))',+ // Slide the preview pane left across the gutter so it sits+ // flush against the controller, keeping its right edge in+ // place. The gutter's drag hit-area still paints (and+ // hit-tests) above this extension, so resizing works.+ ...(tuckedBehindController() && {+ 'margin-left': `-${gutterSize()}px`,+ width: `calc(100% + ${gutterSize()}px)`,+ }),}}ref={(ref) => {setPanelRef(ref);@@ -227,7 +293,7 @@ export function SplitPanel(props: SplitPanelProps) {><PaneledgeColor={- splitFocusStyling()+ splitFocusStyling() || previewPairFocusStyling()? 'color-mix(in oklch, var(--color-edge) 80%, var(--color-ink))': undefined}@@ -237,6 +303,15 @@ export function SplitPanel(props: SplitPanelProps) {'shadow-sm shadow-drop-shadow/50 bg-panel/80 dark-mode:bg-panel/30':splitUnfocusedStyling(),'shadow-2xl shadow-drop-shadow': splitFocusStyling(),+ 'border-solid!': previewPairFocusStyling() && props.active,+ 'border-dashed!': previewPairFocusStyling() && !props.active,+ // Drawer look: the Viewer meets its Controller with+ // a square, borderless left edge (the ! beats Surface's+ // inline border shorthand)...+ 'rounded-l-none border-l-0!': tuckedBehindController(),+ // ...and the controller squares and removes its right edge,+ // leaving no border between the Preview Pair's panels.+ 'rounded-r-none border-r-0!': hasTuckedViewer(),})}depth={isMobile() ? 0 : 1}@@ -259,9 +334,7 @@ export function SplitPanel(props: SplitPanelProps) {'items-start overflow-visible',!hasToolbarContent() && 'hidden',isMobile() && 'hidden',- (!previewState() ||- isListViewID(props.handle.content().id)) &&- 'border-b-0' /* List views draw the preview border below their filter bar instead (see SoupView). */+ 'border-b-0')}><SplitToolbar ref={setToolbarRef} />@@ -277,7 +350,15 @@ export function SplitPanel(props: SplitPanelProps) {><Suspense><SoupViewContextProvider soup={nextSoup}>- <Dynamic component={props.split.mount.element} />+ <BlockOpenTrackingDelayContext.Provider+ value={+ props.handle.isViewerSplit()+ ? PREVIEW_VIEWER_OPEN_TRACK_DELAY_MS+ : 0+ }+ >+ <Dynamic component={props.split.mount.element} />+ </BlockOpenTrackingDelayContext.Provider></SoupViewContextProvider></Suspense></div>diff --git a/apps/web/src/components/app/split-layout/components/SplitToolbar.tsx b/apps/web/src/components/app/split-layout/components/SplitToolbar.tsxindex 4b2afd9da7..67c639445b 100644--- a/apps/web/src/components/app/split-layout/components/SplitToolbar.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitToolbar.tsx@@ -45,19 +45,10 @@ export function SplitToolbarLeft(const panel = useSplitPanelOrThrow();const [portalRef, setPortalRef] = createSignal<HTMLDivElement | null>(null);- const halfWidthClasses = () =>- 'absolute h-full left-[30%] top-0 flex items-center'.split(' ');-createRenderEffect(() => {const ref = portalRef();if (!ref) return;ref.style.width = '100%';- const halfSplitState = panel.halfSplitState?.();- if (halfSplitState?.side === 'right') {- ref.classList.add(...halfWidthClasses());- } else {- ref.classList.remove(...halfWidthClasses());- }if (props.class) {ref.classList.add(props.class);}@@ -82,19 +73,10 @@ export function SplitToolbarRight(props: ParentProps<{ order?: number }>) {const panel = useSplitPanelOrThrow();const [portalRef, setPortalRef] = createSignal<HTMLDivElement | null>(null);- const halfWidthClasses = () =>- 'absolute h-full right-[70%] top-0 flex items-center'.split(' ');-createRenderEffect(() => {const ref = portalRef();if (!ref) return;ref.style.order = props.order?.toString() ?? '0';- const halfSplitState = panel.halfSplitState?.();- if (halfSplitState?.side === 'left') {- ref.classList.add(...halfWidthClasses());- } else {- ref.classList.remove(...halfWidthClasses());- }});return (<Show when={panel.layoutRefs.toolbarRight}>diff --git a/apps/web/src/components/app/split-layout/context.ts b/apps/web/src/components/app/split-layout/context.tsindex 3fd8de0e41..e30ba208de 100644--- a/apps/web/src/components/app/split-layout/context.ts+++ b/apps/web/src/components/app/split-layout/context.ts@@ -5,7 +5,6 @@ import {createContext,type JSX,type Setter,- type Signal,} from 'solid-js';import type { SplitHandle, SplitManager } from './layoutManager';@@ -34,11 +33,6 @@ export const SplitLayoutContext = createContext<{manager: SplitManager;}>();-export type HalfSplitState = {- percentage: number;- side: 'left' | 'right';-};-export type SplitBottomPanelRegistration = {id: string;title?: JSX.Element;@@ -85,10 +79,8 @@ export type SplitPanelContextType = {panelSize: NullableSize;contentOffsetTop: Accessor<number>;setContentOffsetTop: Setter<number>;- halfSplitState?: Accessor<HalfSplitState | undefined>;bottomPanel: Accessor<SplitBottomPanelRegistration | undefined>;registerBottomPanel: (panel: SplitBottomPanelRegistration) => () => void;- previewState: Signal<boolean>;layoutRefs: {headerLeft?: HTMLDivElement;headerRight?: HTMLDivElement;diff --git a/apps/web/src/components/app/split-layout/layout.ts b/apps/web/src/components/app/split-layout/layout.tsindex 2a5f24fb3b..cfedda2d2e 100644--- a/apps/web/src/components/app/split-layout/layout.ts+++ b/apps/web/src/components/app/split-layout/layout.ts@@ -26,6 +26,11 @@ export function useSplitLayout() {return splitManager.openWithSplit(content, {...options,preferNewSplit,+ // Navigation issued from inside a split panel (links, mentions,+ // references) carries that panel as its source; callers outside any+ // panel (sidebar, command menu) stay handle-less, which is what marks+ // "external navigation" for Preview Pair routing.+ handle: options?.handle ?? splitPanelContext?.handle,});}diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.tsindex 182e599d1e..349d04227a 100644--- a/apps/web/src/components/app/split-layout/layoutManager.ts+++ b/apps/web/src/components/app/split-layout/layoutManager.ts@@ -8,6 +8,7 @@ import type {import type { ResizeZoneCtx } from '@core/component/Resize/types';import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';import { settingsTabToSlug } from '@core/constant/settingsTabsConfig';+import { isMobile } from '@core/mobile/isMobile';import type {BlockInstanceHandle,BlockOrchestrator,@@ -28,9 +29,19 @@ import {resolveComponent,} from './componentRegistry';import { createHistory, type History } from './history';+import {+ isPreviewControllerContent,+ previewControllerWidthForContent,+} from './previewController';const ENABLE_DEFAULT_ALWAYS_IN_HISTORY = false;+/** Placeholder content a Preview Pair's Viewer opens before any navigation. */+const PREVIEW_VIEWER_EMPTY_CONTENT = {+ type: 'component',+ id: 'preview-empty',+} as const;+export type SplitId = string & { readonly SplitId: unique symbol };type SplitKey = `${BlockName | BlockAlias | 'component'}:${string}`;@@ -203,6 +214,12 @@ export type OpenWithSplitOptions = {reopen?: 'latest';};+/**+ * A live Preview Pair: navigation in the Controller is redirected into its+ * immediately-adjacent Viewer.+ */+export type PreviewPair = { controllerId: SplitId; viewerId: SplitId };+/*** A navigation interceptor registered by, e.g. mobile swipe layout.* Called at the start of `openWithSplit`. Return `{ handled: true }` to consume@@ -382,6 +399,44 @@ export type SplitManager = {*/setNavigationInterceptor: (fn: NavigationInterceptor | undefined) => void;+ /**+ * Engage preview mode on a split: it becomes the Controller in a Preview+ * Pair with an eagerly-created Viewer, and navigation routes between them by+ * configured controller capability. No-op on mobile and when there is no+ * room for the Viewer.+ */+ engagePreviewMode: (controllerId: SplitId) => void;++ /** Restore a Preview Pair using an existing adjacent Viewer. */+ restorePreviewPair: (controllerId: SplitId, viewerId: SplitId) => boolean;++ /**+ * Whether preview mode can engage on this split — requires room for the+ * Viewer (or an adoptable placeholder already on screen). Reactive.+ */+ canEngagePreview: (controllerId: SplitId) => boolean;++ /** Exit preview mode and close the Preview Pair's Viewer. */+ disengagePreviewMode: (controllerId: SplitId) => void;++ /** Preserve both splits while unlinking their Preview Pair. */+ unlinkPreviewPair: (controllerId: SplitId) => void;++ /** The automatic-redistribution preference for a Controller. Reactive. */+ previewControllerWidth: (+ controllerId: SplitId,+ viewportWidth?: number+ ) => number | undefined;++ /** The Controller's live Viewer id, if one exists. Reactive. */+ viewerOf: (controllerId: SplitId) => SplitId | undefined;++ /** The controller whose viewer is the given split, if any. Reactive. */+ controllerOf: (viewerId: SplitId) => SplitId | undefined;++ /** All live, immediately-adjacent Preview Pairs. */+ previewPairs: Accessor<PreviewPair[]>;+/** Get reactive accessor to popovers map */popovers: () => Map<string,@@ -415,6 +470,10 @@ export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {content: () => SplitContent;isSpotLight: () => boolean;isPopover: () => boolean;+ /** Whether this split is the Viewer side of a Preview Pair. */+ isViewerSplit: () => boolean;+ /** Whether this split is the Controller side of a Preview Pair. */+ isControllerSplit: () => boolean;displayName: () => string;canGoBack: () => boolean;isActive: () => boolean;@@ -460,6 +519,14 @@ export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {* Returns `undefined` if no state has been captured.*/currentEntryState: () => EntryState | undefined;+ /** Whether preview mode can engage on this split (room for a viewer). */+ canEngagePreview: () => boolean;+ /** Engage preview mode on this split (see SplitManager.engagePreviewMode). */+ engagePreview: () => void;+ /** Exit preview mode and close this Controller's Viewer. */+ disengagePreview: () => void;+ /** This Controller's live Viewer id, if one exists. Reactive. */+ viewerId: () => SplitId | undefined;} & UrlCapabilities;function newSplitId(): SplitId {@@ -538,6 +605,13 @@ export function createSplitLayout(lastActiveSplitId: SplitId | undefined;spotlightId: SplitId | undefined;events: SplitEventWithType[];+ /**+ * Preview Pairs keyed by Controller id. Key present = preview mode+ * engaged on that split, and the Viewer always exists (engage+ * refuses to run without room for one). IDs remain in-memory only;+ * SplitLayout persists stable URL-order indices for reload restoration.+ */+ previewPairs: Record<SplitId, { viewerId: SplitId }>;popovers: Map<string,{@@ -555,6 +629,7 @@ export function createSplitLayout(lastActiveSplitId: undefined,spotlightId: undefined,events: [],+ previewPairs: {},popovers: new Map(),});@@ -761,6 +836,11 @@ export function createSplitLayout(};return s.with(i, target);});++ // Content changes that bypass Preview Pair routing (direct handle.replace,+ // history back/forward) can violate its content invariant; unlink the+ // Preview Pair when they do.+ enforcePreviewPairContentInvariant(split.id);}function back(id: SplitId) {@@ -983,6 +1063,11 @@ export function createSplitLayout(return;}+ // Closing a Preview Pair's Controller closes its Viewer too. Remove+ // the Viewer first so the Controller's final remove event determines+ // which remaining split receives focus.+ const viewerId = viewerOf(currentSplit.id);+ if (viewerId) removeSplit(viewerId, false);removeSplit(currentSplit.id);},getUrlSegments: () => contentUrlSegments(content()),@@ -992,6 +1077,8 @@ export function createSplitLayout(isActive: () => currentSplit.id === state.activeSplitId,isSpotLight: () => state.spotlightId === currentSplit.id,isPopover: () => state.popovers.has(currentSplit.id),+ isViewerSplit: () => controllerOf(currentSplit.id) !== undefined,+ isControllerSplit: () => viewerOf(currentSplit.id) !== undefined,toggleSpotlight: (force?: boolean) => {toggleSpotlightSplit(currentSplit.id, force);},@@ -1054,6 +1141,10 @@ export function createSplitLayout(const c = live.content as { state?: EntryState };return c.state;},+ canEngagePreview: () => canEngagePreview(currentSplit.id),+ engagePreview: () => engagePreviewMode(currentSplit.id),+ disengagePreview: () => disengagePreviewMode(currentSplit.id),+ viewerId: () => viewerOf(currentSplit.id),};};@@ -1089,16 +1180,19 @@ export function createSplitLayout(initialHistory,});- setState('splits', (previousSplits) => {- if (insertIndex === undefined) return [...previousSplits, split];-- const nextSplits = [...previousSplits];- nextSplits.splice(- Math.max(0, Math.min(insertIndex, nextSplits.length)),- 0,- split- );- return nextSplits;+ batch(() => {+ setState('splits', (previousSplits) => {+ if (insertIndex === undefined) return [...previousSplits, split];++ const nextSplits = [...previousSplits];+ nextSplits.splice(+ Math.max(0, Math.min(insertIndex, nextSplits.length)),+ 0,+ split+ );+ return nextSplits;+ });+ pruneNonAdjacentPreviewPairs();});const handle = getSplit(split.id)!;@@ -1122,6 +1216,7 @@ export function createSplitLayout(contentChangeListeners.delete(id);entryStateCaptors.delete(id);+ clearPreviewPairsFor(id);setSplitNamesById(produce((map) => {delete map[id];@@ -1139,6 +1234,252 @@ export function createSplitLayout(}}+ /**+ * An unclaimed placeholder split sitting immediately right of the+ * controller that engage adopts as the viewer instead of creating a+ * duplicate.+ */+ function adoptableViewerFor(controllerId: SplitId): SplitId | undefined {+ const controllerIndex = splitIndexById(controllerId);+ const adjacent =+ controllerIndex >= 0 ? state.splits[controllerIndex + 1] : undefined;+ if (+ adjacent &&+ sameContent(adjacent.content, PREVIEW_VIEWER_EMPTY_CONTENT) &&+ !controllerOf(adjacent.id)+ ) {+ return adjacent.id;+ }+ return undefined;+ }++ /**+ * Whether preview mode can engage on this split: there must be room for+ * the Viewer (or an adoptable placeholder already on screen).+ * Reactive.+ */+ function canEngagePreview(controllerId: SplitId): boolean {+ if (isMobile()) return false;+ const controller = findSplitById(controllerId);+ if (+ !controller ||+ isExcluded(controller) ||+ !isPreviewControllerContent(controller.content) ||+ controllerOf(controllerId) !== undefined+ ) {+ return false;+ }+ if (viewerOf(controllerId) !== undefined) return true;+ return adoptableViewerFor(controllerId) !== undefined || canAppendSplit();+ }++ /** Whether two live splits can form a non-overlapping adjacent Preview Pair. */+ function canLinkPreviewPair(+ controllerId: SplitId,+ viewerId: SplitId+ ): boolean {+ if (isMobile()) return false;+ const controllerIndex = splitIndexById(controllerId);+ const controller = state.splits[controllerIndex];+ const viewer = state.splits[controllerIndex + 1];+ if (+ !controller ||+ controller.id !== controllerId ||+ !viewer ||+ viewer.id !== viewerId ||+ isExcluded(controller) ||+ isExcluded(viewer)+ ) {+ return false;+ }+ if (!isPreviewControllerContent(controller.content)) {+ return false;+ }++ // Neither side can already participate in another Preview Pair.+ return (+ state.previewPairs[controllerId] === undefined &&+ state.previewPairs[viewerId] === undefined &&+ controllerOf(controllerId) === undefined &&+ controllerOf(viewerId) === undefined+ );+ }++ /** The sole creator of Controller/Viewer Preview Pairs. */+ function linkPreviewPair(controllerId: SplitId, viewerId: SplitId): boolean {+ if (!canLinkPreviewPair(controllerId, viewerId)) return false;+ setState('previewPairs', controllerId, { viewerId });++ // A restored layout comes up with its last split — often the viewer — as+ // active. The controller owns the keyboard when its viewer is active only+ // because it was the last URL entry, so return activation to it.+ if (state.activeSplitId === viewerId) {+ activateSplit(controllerId);+ }+ return true;+ }++ /**+ * Structural split mutations may not leave a Preview Pair whose Viewer is+ * anywhere except immediately right of its Controller.+ */+ function pruneNonAdjacentPreviewPairs() {+ setState(+ 'previewPairs',+ produce((map) => {+ for (const controllerId of Object.keys(map) as SplitId[]) {+ const controllerIndex = splitIndexById(controllerId);+ if (+ controllerIndex < 0 ||+ state.splits[controllerIndex + 1]?.id !==+ map[controllerId]?.viewerId+ ) {+ delete map[controllerId];+ }+ }+ })+ );+ }++ function restorePreviewPair(+ controllerId: SplitId,+ viewerId: SplitId+ ): boolean {+ return linkPreviewPair(controllerId, viewerId);+ }++ function engagePreviewMode(controllerId: SplitId) {+ // Mobile shows one panel at a time; a side-by-side viewer cannot exist.+ if (isMobile()) return;+ const controller = findSplitById(controllerId);+ if (!controller || !isPreviewControllerContent(controller.content)) return;+ if (state.previewPairs[controllerId] !== undefined) return;+ if (controllerOf(controllerId) !== undefined) return;++ // The viewer opens with its placeholder immediately; navigation then+ // replaces its content. Adopt an unclaimed placeholder already sitting+ // right of the controller instead of duplicating it. Without room for a+ // viewer, preview mode does not engage at all.+ let viewerId = adoptableViewerFor(controllerId);+ if (viewerId === undefined) {+ if (!canAppendSplit()) return;+ const controllerIndex = splitIndexById(controllerId);+ const viewerHandle = createNewSplit({+ content: PREVIEW_VIEWER_EMPTY_CONTENT,+ activate: false,+ referredFrom: null,+ allowDuplicate: true,+ insertIndex: controllerIndex >= 0 ? controllerIndex + 1 : undefined,+ });+ if (!viewerHandle) return;+ viewerId = viewerHandle.id;+ }+ linkPreviewPair(controllerId, viewerId);++ // The Controller's configured width is enforced declaratively as an+ // automatic-redistribution preference and maximum (see+ // SplitLayoutContainer). Direct gutter drags remain unconstrained by it.+ }++ function unlinkPreviewPair(controllerId: SplitId) {+ setState(+ 'previewPairs',+ produce((map) => {+ delete map[controllerId];+ })+ );+ }++ function disengagePreviewMode(controllerId: SplitId) {+ const viewerId = viewerOf(controllerId);+ unlinkPreviewPair(controllerId);+ if (viewerId) removeSplit(viewerId);+ }++ const previewControllerWidth = (+ controllerId: SplitId,+ viewportWidth?: number+ ) => {+ if (viewerOf(controllerId) === undefined) return undefined;+ const content = findSplitById(controllerId)?.content;+ return content+ ? previewControllerWidthForContent(content, viewportWidth)+ : undefined;+ };++ const viewerOf = (controllerId: SplitId): SplitId | undefined => {+ return state.previewPairs[controllerId]?.viewerId;+ };++ const controllerOf = (viewerId: SplitId): SplitId | undefined => {+ for (const [controllerId, previewPair] of Object.entries(+ state.previewPairs+ )) {+ if (previewPair.viewerId === viewerId) {+ return controllerId as SplitId;+ }+ }+ return undefined;+ };++ const previewPairs = createMemo<PreviewPair[]>(() => {+ return Object.entries(state.previewPairs).map(+ ([controllerId, { viewerId }]) => ({+ controllerId: controllerId as SplitId,+ viewerId,+ })+ );+ });++ /** Called whenever split `id` leaves the layout. */+ function clearPreviewPairsFor(id: SplitId) {+ setState(+ 'previewPairs',+ produce((map) => {+ // Controller removed outside its close action: Preview Pair gone, its+ // Viewer stays. SplitHandle.close removes the Viewer first.+ delete map[id];+ for (const key of Object.keys(map) as SplitId[]) {+ // Viewer closed (✕ button, hotkey, reconcile): preview mode+ // disengages on its controller.+ if (map[key]?.viewerId === id) delete map[key];+ }+ })+ );+ }++ /** The Preview Pair a split belongs to, seen from either side. */+ function previewPairOf(id: SplitId): PreviewPair | undefined {+ const viewerId = state.previewPairs[id]?.viewerId;+ if (viewerId !== undefined) return { controllerId: id, viewerId };+ const controllerId = controllerOf(id);+ if (controllerId) return { controllerId, viewerId: id };+ return undefined;+ }++ /**+ * A Preview Pair consists of an eligible Controller and its Viewer. A block+ * such as a project may be eligible to act as a Controller while also being+ * valid Viewer content; the live pair assignment, rather than content type,+ * determines its role.+ *+ * Content changes that reach the Controller outside `openWithSplit` (direct+ * `handle.replace`, history back/forward, URL reconcile) can make it+ * ineligible; when they do, the Preview Pair closes.+ */+ function enforcePreviewPairContentInvariant(id: SplitId) {+ const split = findSplitById(id);+ if (!split) return;++ // Controller side: ineligible content breaks the Preview Pair.+ if (+ viewerOf(id) !== undefined &&+ !isPreviewControllerContent(split.content)+ ) {+ disengagePreviewMode(id);+ }+ }+function hasSplit(type: SplitContentType, id: string): boolean {return !!state.splits.find((s) => s.content.type === type && s.content.id === id@@ -1242,6 +1583,7 @@ export function createSplitLayout(if (!usedIds.has(split.id)) {contentChangeListeners.delete(split.id);entryStateCaptors.delete(split.id);+ clearPreviewPairsFor(split.id);setSplitNamesById(produce((map) => {delete map[split.id];@@ -1251,8 +1593,21 @@ export function createSplitLayout(}}- // Update state in a single batch- setState('splits', resultSplits);+ // Update order and unlink any Preview Pair that the rebuild separated+ // before reactive consumers can observe the new split layout.+ batch(() => {+ setState('splits', resultSplits);+ pruneNonAdjacentPreviewPairs();+ });++ // URL-driven rebuilds can swap a Preview Pair member's content in place+ // (same id, new content) — enforce its content invariant here too.+ for (const [controllerId, previewPair] of Object.entries(+ state.previewPairs+ )) {+ enforcePreviewPairContentInvariant(controllerId as SplitId);+ enforcePreviewPairContentInvariant(previewPair.viewerId);+ }}const lastEvent = createMemo(() => state.events[state.events.length - 1]);@@ -1359,9 +1714,82 @@ export function createSplitLayout(if (result.handled) return undefined;}+ // Preview Pair routing:+ // - External (handle-less) replacement navigation while a Preview Pair+ // member is active dissolves the Preview Pair: the Viewer closes and+ // the content replaces the Controller. Explicit new-split intent is honored+ // without dissolving the Preview Pair when the layout has room.+ // - A replace originating from the Controller (`options.handle` names+ // it) lands in the Viewer without stealing the keyboard. That+ // includes new-split intent when the layout is full — the fallback+ // replaces the Viewer, never the Controller.+ // - The Viewer itself navigates like any split: it replaces+ // itself, honors new-split intent, and a full layout falls back to+ // replacing it (its own handle), never the Controller.+ // Options are rewritten once, never recursively. Runs before the+ // duplicate short-circuit so an existing-content hit can never activate+ // (and focus) another split while the Controller holds the keyboard.+ {+ const explicitSourceId = options.handle?.id;+ const sourceId = explicitSourceId ?? state.activeSplitId;+ const previewPair = sourceId ? previewPairOf(sourceId) : undefined;+ if (previewPair && findSplitById(previewPair.viewerId)) {+ if (explicitSourceId === undefined) {+ // Global create-new actions are handle-less too, but they are not+ // replacement navigation. Honor their explicit new-split intent+ // when there is room and leave the Preview Pair intact.+ if (!options.preferNewSplit || !canAppendSplit()) {+ disengagePreviewMode(previewPair.controllerId);+ options = {+ ...options,+ handle: getSplit(previewPair.controllerId),+ preferNewSplit: false,+ insertIndex: undefined,+ };+ }+ } else if (+ explicitSourceId === previewPair.controllerId &&+ (!options.preferNewSplit || !canAppendSplit())+ ) {+ options = {+ ...options,+ handle: getSplit(previewPair.viewerId),+ preferNewSplit: false,+ activate: false,+ insertIndex: undefined,+ // Controller-originated navigation is transient selection state,+ // not preview history: it replaces the Viewer's current+ // entry, so only the preview's own navigation stacks up.+ mergeHistory: true,+ };+ }+ }+ }+const existingSplit = getSplitByContent(content.type, content.id);if (!options.allowDuplicate && existingSplit) {+ // A controller selection can resolve to content already mounted in its+ // own viewer (notably two rows from one channel). Refresh the viewer's+ // merged history entry so per-entry source metadata follows the latest+ // selection instead of being stranded on the first row.+ if (options.mergeHistory && options.handle?.id === existingSplit.id) {+ existingSplit.captureEntryState();+ const currentState = existingSplit.currentEntryState();+ const nextContent =+ currentState || content.state+ ? {+ ...content,+ state: { ...currentState, ...content.state },+ }+ : content;+ existingSplit.replace({+ next: nextContent,+ referredFrom: options.referredFrom ?? null,+ mergeHistory: true,+ });+ }+if (options.activate !== false) {existingSplit.activate();}@@ -1494,5 +1922,14 @@ export function createSplitLayout(setNavigationInterceptor: (fn) => {navigationInterceptor = fn;},+ engagePreviewMode,+ restorePreviewPair,+ canEngagePreview,+ disengagePreviewMode,+ unlinkPreviewPair,+ previewControllerWidth,+ viewerOf,+ controllerOf,+ previewPairs,};}diff --git a/apps/web/src/components/app/split-layout/layoutUrlSync.ts b/apps/web/src/components/app/split-layout/layoutUrlSync.tsnew file mode 100644index 0000000000..01d4239dfd--- /dev/null+++ b/apps/web/src/components/app/split-layout/layoutUrlSync.ts@@ -0,0 +1,200 @@+import type { Navigator } from '@solidjs/router';+import {+ type Accessor,+ batch,+ createEffect,+ createMemo,+ on,+ onCleanup,+} from 'solid-js';+import type { SplitContent, SplitManager } from './layoutManager';+import { decodePairs } from './layoutUtils';+import {+ PREVIEW_QUERY_PARAM,+ type PreviewPairUrlEntry,+ type PreviewQueryValue,+ type RestorablePreviewLayout,+ serializePreviewPairs,+} from './previewPersistence';++type LayoutUrlSyncEnvironment = {+ navigate: Navigator;+ search: Accessor<string>;+ hash: Accessor<string>;+};++function sameSplitContentIdentity(a: SplitContent, b: SplitContent) {+ return a.type === b.type && a.id === b.id;+}++function getUrlSyncAffectedSplit(+ splitManager: SplitManager,+ currentPairs: SplitContent[],+ nextPairs: SplitContent[]+) {+ const changedIndex = nextPairs.findIndex(+ (nextPair, index) =>+ !currentPairs[index] ||+ !sameSplitContentIdentity(currentPairs[index], nextPair)+ );++ if (changedIndex < 0) return undefined;++ const affectedPair = nextPairs[changedIndex];+ return splitManager+ .splits()+ .find((split) => sameSplitContentIdentity(split.content, affectedPair));+}++/** Restore URL-declared Preview Pairs through the manager's invariant gate. */+export function restorePreviewPairs(+ splitManager: SplitManager,+ previewPairs: readonly PreviewPairUrlEntry[]+) {+ const splits = splitManager.splits();+ for (const previewPair of previewPairs) {+ const controller = splits[previewPair.controllerIndex];+ const viewer = splits[previewPair.controllerIndex + 1];+ if (!controller || !viewer) continue;+ splitManager.restorePreviewPair(controller.id, viewer.id);+ }+}++function previewPairsForUrl(splitManager: SplitManager): PreviewPairUrlEntry[] {+ const splits = splitManager.getVisibleSplits();+ const indices = new Map(splits.map((split, index) => [split.id, index]));+ return splitManager+ .previewPairs()+ .flatMap((previewPair): PreviewPairUrlEntry[] => {+ const controllerIndex = indices.get(previewPair.controllerId);+ return controllerIndex === undefined ? [] : [{ controllerIndex }];+ });+}++function previewQueryMatches(+ current: PreviewQueryValue,+ canonical: string | undefined+): boolean {+ return current === canonical;+}++/**+ * Keep the split manager and the path/query representation of its layout in+ * sync. Router access is injected so the reactive behavior can be tested+ * without mounting the complete split UI.+ */+export function createLayoutUrlSync(+ splitManager: SplitManager,+ pairs: Accessor<string[]>,+ previewQuery: Accessor<PreviewQueryValue>,+ decodedLayout: Accessor<RestorablePreviewLayout>,+ environment: LayoutUrlSyncEnvironment+) {+ let reconcilingFromUrl = false;+ let managerSyncQueued = false;+ let disposed = false;+ onCleanup(() => {+ disposed = true;+ });++ const managerUrlState = () => {+ const segments = splitManager.getUrlSegments();+ const preview = serializePreviewPairs(previewPairsForUrl(splitManager));+ return { segments, preview };+ };++ const managerUrlSignature = () => {+ const state = managerUrlState();+ return JSON.stringify([state.segments, state.preview]);+ };++ const urlLayoutDrift = createMemo(() => {+ const state = managerUrlState();+ return (+ state.segments.join('/') !== pairs().join('/') ||+ !previewQueryMatches(previewQuery(), state.preview)+ );+ });++ const syncManagerToUrl = (options: { replace?: boolean } = {}) => {+ if (!urlLayoutDrift()) return;++ const nextState = managerUrlState();+ const pathChanged = nextState.segments.join('/') !== pairs().join('/');+ const nextPairs = decodePairs(nextState.segments);+ const affectedSplit = getUrlSyncAffectedSplit(+ splitManager,+ decodedLayout().contents,+ nextPairs+ );+ const replace =+ options.replace ?? affectedSplit?.lastNavigationCause === 'replace';++ // Preserve unrelated query/hash state for query-only updates. Path+ // changes retain the existing split-navigation behavior of clearing+ // content-specific location state.+ const query = pathChanged+ ? new URLSearchParams()+ : new URLSearchParams(environment.search());+ if (nextState.preview) {+ query.set(PREVIEW_QUERY_PARAM, nextState.preview);+ } else {+ query.delete(PREVIEW_QUERY_PARAM);+ }+ const search = query.toString();+ const hash = pathChanged ? '' : environment.hash();+ const nextUrl = `/${nextState.segments.join('/')}${+ search ? `?${search}` : ''+ }${hash}`;++ environment.navigate(nextUrl, { replace });+ };++ // Preview operations can update splits and their Preview Pair in separate+ // reactive writes. Coalesce those writes so the URL never observes an+ // intermediate bare placeholder or severed Preview Pair.+ const scheduleManagerToUrlSync = () => {+ if (managerSyncQueued) return;+ managerSyncQueued = true;+ queueMicrotask(() => {+ managerSyncQueued = false;+ if (!disposed && !reconcilingFromUrl) syncManagerToUrl();+ });+ };++ /** Sync changes from the layout manager to path and query together. */+ createEffect(+ on(+ managerUrlSignature,+ () => {+ if (!reconcilingFromUrl) scheduleManagerToUrlSync();+ },+ { defer: true }+ )+ );++ /** Sync changes from either URL path or preview query to the manager. */+ createEffect(+ on([pairs, previewQuery], () => {+ if (urlLayoutDrift()) {+ const nextLayout = decodedLayout();+ reconcilingFromUrl = true;+ try {+ batch(() => {+ for (const previewPair of splitManager.previewPairs()) {+ splitManager.unlinkPreviewPair(previewPair.controllerId);+ }+ splitManager.reconcile(nextLayout.contents);+ restorePreviewPairs(splitManager, nextLayout.previewPairs);+ });+ } finally {+ reconcilingFromUrl = false;+ }++ // Invalid query tuples and unlinked placeholders are rewritten to the+ // manager's canonical representation without adding browser history.+ if (urlLayoutDrift()) syncManagerToUrl({ replace: true });+ }+ })+ );+}diff --git a/apps/web/src/components/app/split-layout/layoutUtils.ts b/apps/web/src/components/app/split-layout/layoutUtils.tsindex 3368e30263..745ca9a811 100644--- a/apps/web/src/components/app/split-layout/layoutUtils.ts+++ b/apps/web/src/components/app/split-layout/layoutUtils.ts@@ -107,6 +107,17 @@ export function useSplitPanel() {return useContext(SplitPanelContext);}+/**+ * Whether content may claim focus automatically when it mounts in the current+ * split. Preview Pair Viewers stay passive until the user focuses them.+ *+ * This is intentionally a snapshot: dissolving a Preview Pair later must not+ * trigger delayed autofocus in content that is already mounted.+ */+export function useCanAutofocusSplitContent() {+ return !useSplitPanel()?.handle.isViewerSplit();+}+/*** Remove all the items from all split histories that meet a certain criteria.* @param managerdiff --git a/apps/web/src/components/app/split-layout/previewController.ts b/apps/web/src/components/app/split-layout/previewController.tsnew file mode 100644index 0000000000..89a325d22c--- /dev/null+++ b/apps/web/src/components/app/split-layout/previewController.ts@@ -0,0 +1,72 @@+import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';+import type { SplitContent, SplitContentType } from './layoutManager';++type PreviewControllerWidth = {+ preferredPx: number;+ /** Optional viewport-relative ceiling, where 0.75 corresponds to 75vw. */+ maxViewportFraction?: number;+};++/** Default automatic-redistribution width for preview controllers. */+const DEFAULT_PREVIEW_CONTROLLER_WIDTH: PreviewControllerWidth = {+ preferredPx: 440,+};++type PreviewControllerContentConfig = {+ type: SplitContentType;+ /** Omit to match every block with this content type. */+ id?: string;+ redistributionWidth?: PreviewControllerWidth;+};++/** Non-list additions and exact-content overrides for preview controllers. */+const PREVIEW_CONTROLLER_CONTENT_CONFIG: readonly PreviewControllerContentConfig[] =+ [+ {+ type: 'project',+ },+ {+ type: 'component',+ id: LIST_VIEW_ID.mail,+ redistributionWidth: { preferredPx: 1050, maxViewportFraction: 0.6 },+ },+ {+ type: 'component',+ id: LIST_VIEW_ID.companies,+ redistributionWidth: {+ preferredPx: 880,+ maxViewportFraction: 0.7,+ },+ },+ ];++function previewControllerConfig(content: SplitContent) {+ return PREVIEW_CONTROLLER_CONTENT_CONFIG.find(+ (candidate) =>+ candidate.type === content.type &&+ (candidate.id === undefined || candidate.id === content.id)+ );+}++export function isPreviewControllerContent(content: SplitContent): boolean {+ return (+ (content.type === 'component' && isListViewID(content.id)) ||+ previewControllerConfig(content) !== undefined+ );+}++export function previewControllerWidthForContent(+ content: SplitContent,+ viewportWidth?: number+): number | undefined {+ if (!isPreviewControllerContent(content)) return undefined;+ const config = previewControllerConfig(content);+ const width = config?.redistributionWidth ?? DEFAULT_PREVIEW_CONTROLLER_WIDTH;+ const viewportMax =+ width.maxViewportFraction !== undefined &&+ viewportWidth !== undefined &&+ viewportWidth > 0+ ? viewportWidth * width.maxViewportFraction+ : Infinity;+ return Math.min(width.preferredPx, viewportMax);+}diff --git a/apps/web/src/components/app/split-layout/previewPersistence.ts b/apps/web/src/components/app/split-layout/previewPersistence.tsnew file mode 100644index 0000000000..dd617663df--- /dev/null+++ b/apps/web/src/components/app/split-layout/previewPersistence.ts@@ -0,0 +1,143 @@+import { LIST_VIEW_ID } from '@app/constants/list-views';+import type { SplitContent } from './layoutManager';+import { decodePairs } from './layoutUtils';+import { isPreviewControllerContent } from './previewController';++/** Query parameter carrying Controller/Viewer Preview Pairs. */+export const PREVIEW_QUERY_PARAM = 'preview';++/** A Preview Pair keyed by its Controller's stable URL-order index. */+export type PreviewPairUrlEntry = {+ controllerIndex: number;+};++/** URL content plus Preview Pairs restored from its query string. */+export type RestorablePreviewLayout = {+ contents: SplitContent[];+ previewPairs: PreviewPairUrlEntry[];+};++export type PreviewQueryValue = string | string[] | undefined;++function isPreviewPairUrlEntry(+ value: PreviewPairUrlEntry+): value is PreviewPairUrlEntry {+ return Number.isInteger(value.controllerIndex) && value.controllerIndex >= 0;+}++function parsePreviewPairs(value: PreviewQueryValue): PreviewPairUrlEntry[] {+ if (typeof value !== 'string' || value.length === 0) return [];++ return value.split('_').flatMap((tuple): PreviewPairUrlEntry[] => {+ if (!/^\d+$/.test(tuple)) return [];++ const entry: PreviewPairUrlEntry = {+ controllerIndex: Number(tuple),+ };+ return isPreviewPairUrlEntry(entry) ? [entry] : [];+ });+}++/** Serialize Preview Pairs into their canonical compact query value. */+export function serializePreviewPairs(+ previewPairs: readonly PreviewPairUrlEntry[]+): string | undefined {+ const value = previewPairs+ .filter(isPreviewPairUrlEntry)+ .toSorted((a, b) => a.controllerIndex - b.controllerIndex)+ .map(({ controllerIndex }) => String(controllerIndex))+ .join('_');+ return value || undefined;+}++function isPreviewEmpty(content: SplitContent): boolean {+ return content.type === 'component' && content.id === 'preview-empty';+}++function validPreviewPairsForContents(+ contents: readonly SplitContent[],+ previewPairs: readonly PreviewPairUrlEntry[]+): PreviewPairUrlEntry[] {+ const claimedIndices = new Set<number>();+ const valid: PreviewPairUrlEntry[] = [];++ for (const previewPair of previewPairs) {+ const viewerIndex = previewPair.controllerIndex + 1;+ const controller = contents[previewPair.controllerIndex];+ const viewer = contents[viewerIndex];+ if (!controller || !viewer) continue;+ // Only the Controller's content type is constrained — a Viewer may itself+ // be controller-eligible (e.g. a Project controlling another Project),+ // matching the runtime's canLinkPreviewPair. Double-role assignment is+ // prevented by claimedIndices below.+ if (!isPreviewControllerContent(controller)) {+ continue;+ }+ if (+ claimedIndices.has(previewPair.controllerIndex) ||+ claimedIndices.has(viewerIndex)+ ) {+ continue;+ }+ claimedIndices.add(previewPair.controllerIndex);+ claimedIndices.add(viewerIndex);+ valid.push(previewPair);+ }++ return valid.sort((a, b) => a.controllerIndex - b.controllerIndex);+}++/**+ * Decode a URL layout and restore Preview Pairs declared by its query string.+ * Unlinked `preview-empty` entries are removed so the internal placeholder can+ * never load as an independent split.+ */+export function loadRestorablePreviewLayout(+ segments: readonly string[],+ previewQuery: PreviewQueryValue,+ options: { allowPreviewPairs?: boolean } = {}+): RestorablePreviewLayout {+ const decoded = decodePairs([...segments]);+ const queryPreviewPairs =+ options.allowPreviewPairs === false ? [] : parsePreviewPairs(previewQuery);+ const validPreviewPairs = validPreviewPairsForContents(+ decoded,+ queryPreviewPairs+ );+ const linkedViewerIndices = new Set(+ validPreviewPairs.map((previewPair) => previewPair.controllerIndex + 1)+ );++ const keptContents: SplitContent[] = [];+ const remappedIndices = new Map<number, number>();+ decoded.forEach((content, index) => {+ if (isPreviewEmpty(content) && !linkedViewerIndices.has(index)) return;+ remappedIndices.set(index, keptContents.length);+ keptContents.push(content);+ });++ if (keptContents.length === 0) {+ return {+ contents: [{ type: 'component', id: LIST_VIEW_ID.inbox }],+ previewPairs: [],+ };+ }++ return {+ contents: keptContents,+ previewPairs: validPreviewPairs.flatMap(+ (previewPair): PreviewPairUrlEntry[] => {+ const controllerIndex = remappedIndices.get(+ previewPair.controllerIndex+ );+ const viewerIndex = remappedIndices.get(+ previewPair.controllerIndex + 1+ );+ return controllerIndex === undefined ||+ viewerIndex !== controllerIndex + 1+ ? []+ : [{ ...previewPair, controllerIndex }];+ }+ ),+ };+}diff --git a/apps/web/src/components/app/split-layout/registerSplitHotkeys.ts b/apps/web/src/components/app/split-layout/registerSplitHotkeys.tsindex 258d265593..99fad528b0 100644--- a/apps/web/src/components/app/split-layout/registerSplitHotkeys.ts+++ b/apps/web/src/components/app/split-layout/registerSplitHotkeys.ts@@ -18,6 +18,7 @@ export function registerSplitHotkeys(args: {splitName: () => string;getSplitCount: () => number;isNotUnifiedList: () => boolean;+ isViewerSplit: () => boolean;}) {const {splitHotkeyScope,@@ -30,12 +31,14 @@ export function registerSplitHotkeys(args: {splitName,getSplitCount,isNotUnifiedList,+ isViewerSplit: isPreviewSplit,goHome,} = args;registerHotkey({scopeId: splitHotkeyScope,hotkey: ['cmd+escape', 'opt+escape'],- condition: () => isNotUnifiedList() || getSplitCount() > 1,+ condition: () =>+ !isPreviewSplit() && (isNotUnifiedList() || getSplitCount() > 1),description: () => (isNotUnifiedList() ? 'Go home' : 'Close split'),keyDownHandler: () => {if (isNotUnifiedList()) {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 bad298fc51..ae35062ef7 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@@ -1,3 +1,4 @@+import type { ResizeZoneCtx } from '@core/component/Resize/types';import type { BlockOrchestrator } from '@core/orchestrator';import { createRoot } from 'solid-js';import { beforeAll, describe, expect, it, vi } from 'vitest';@@ -184,6 +185,39 @@ describe('layoutManager', () => {dispose();});});++ it('refreshes entry state when merging content already open in the target split', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ {+ type: 'md',+ id: 'doc-1',+ state: { retained: true, source: 'first' },+ },+ ]);+ const split = manager.getSplit(manager.splits()[0].id)!;++ manager.openWithSplit(+ { type: 'md', id: 'doc-1', state: { source: 'second' } },+ { handle: split, mergeHistory: true, referredFrom: null }+ );++ expect(split.history()).toHaveLength(1);+ expect(split.content().state).toEqual({+ retained: true,+ source: 'second',+ });++ split.replace({ next: { type: 'md', id: 'doc-2' } });+ split.goBack();+ expect(split.content().state).toEqual({+ retained: true,+ source: 'second',+ });++ dispose();+ });+ });});describe('navigation params', () => {@@ -459,4 +493,734 @@ describe('layoutManager', () => {});});});++ describe('preview mode', () => {+ const setup = () => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'component', id: 'inbox' },+ ]);+ const controllerId = manager.splits()[0].id;+ manager.activateSplit(controllerId);+ return { manager, controllerId };+ };++ it('eagerly opens an empty viewer right of the controller without activating it', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);++ expect(manager.previewControllerWidth(controllerId)).toBe(440);+ expect(manager.splits()).toHaveLength(2);+ const viewerId = manager.splits()[1].id;+ expect(manager.viewerOf(controllerId)).toBe(viewerId);+ expect(manager.controllerOf(viewerId)).toBe(controllerId);+ expect(manager.getSplit(controllerId)?.isControllerSplit()).toBe(true);+ expect(manager.getSplit(controllerId)?.isViewerSplit()).toBe(false);+ expect(manager.getSplit(viewerId)?.isControllerSplit()).toBe(false);+ expect(manager.getSplit(viewerId)?.isViewerSplit()).toBe(true);+ expect(manager.previewPairs()).toEqual([{ controllerId, viewerId }]);+ expect(manager.splits()[1].content).toMatchObject({+ type: 'component',+ id: 'preview-empty',+ });+ expect(manager.events()).toMatchObject({+ type: SplitEvent.Insert,+ splitId: viewerId,+ activate: false,+ });+ expect(manager.activeSplitId()).toBe(controllerId);++ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ expect(manager.splits()).toHaveLength(2);+ expect(manager.splits()[1].content).toMatchObject({+ type: 'md',+ id: 'doc-1',+ });++ dispose();+ });+ });++ it('uses the configured controller width for Email Soup', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'component', id: 'mail' },+ ]);+ const controllerId = manager.splits()[0].id;++ manager.engagePreviewMode(controllerId);++ expect(manager.previewControllerWidth(controllerId)).toBe(1050);++ dispose();+ });+ });++ it('allows a Project block to control unless it is already a Viewer', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'project', id: 'project-controller' },+ ]);+ const controller = manager.getSplit(manager.splits()[0].id)!;++ expect(controller.canEngagePreview()).toBe(true);+ controller.engagePreview();++ const viewerId = controller.viewerId()!;+ const viewer = manager.getSplit(viewerId)!;+ manager.openWithSplit(+ { type: 'project', id: 'project-viewer' },+ { referredFrom: null, handle: controller }+ );++ expect(controller.content()).toMatchObject({+ type: 'project',+ id: 'project-controller',+ });+ expect(viewer.content()).toMatchObject({+ type: 'project',+ id: 'project-viewer',+ });+ expect(manager.viewerOf(controller.id)).toBe(viewer.id);+ expect(viewer.isViewerSplit()).toBe(true);+ expect(viewer.canEngagePreview()).toBe(false);++ viewer.engagePreview();+ expect(manager.previewPairs()).toEqual([+ { controllerId: controller.id, viewerId: viewer.id },+ ]);++ dispose();+ });+ });++ it('caps the Companies controller width at 70vw', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'component', id: 'companies' },+ ]);+ const controllerId = manager.splits()[0].id;++ manager.engagePreviewMode(controllerId);++ expect(manager.previewControllerWidth(controllerId, 1000)).toBe(700);+ expect(manager.previewControllerWidth(controllerId, 1600)).toBe(880);++ dispose();+ });+ });++ it('creates a distinct empty viewer for each preview controller', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'component', id: 'inbox' },+ { type: 'component', id: 'channels' },+ ]);+ const [firstController, secondController] = manager.splits();++ manager.engagePreviewMode(firstController.id);+ const firstViewerId = manager.viewerOf(firstController.id)!;+ manager.engagePreviewMode(secondController.id);+ const secondViewerId = manager.viewerOf(secondController.id)!;++ expect(secondViewerId).toBeDefined();+ expect(secondViewerId).not.toBe(firstViewerId);+ expect(manager.splits().map((split) => split.id)).toEqual([+ firstController.id,+ firstViewerId,+ secondController.id,+ secondViewerId,+ ]);++ dispose();+ });+ });++ it('adopts an unclaimed adjacent placeholder split instead of duplicating it', () => {+ createRoot((dispose) => {+ // An existing unclaimed placeholder is adopted rather than duplicated,+ // leaving the placeholder (last initial split) active beforehand.+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'component', id: 'inbox' },+ { type: 'component', id: 'preview-empty' },+ ]);+ const controllerId = manager.splits()[0].id;+ const placeholderId = manager.splits()[1].id;+ expect(manager.activeSplitId()).toBe(placeholderId);++ manager.engagePreviewMode(controllerId);++ expect(manager.splits()).toHaveLength(2);+ expect(manager.viewerOf(controllerId)).toBe(placeholderId);+ // The controller takes over activation from its adopted viewer so+ // active-split-targeted navigations redirect through it.+ expect(manager.activeSplitId()).toBe(controllerId);++ dispose();+ });+ });++ it('restores a persisted Preview Pair onto existing adjacent splits', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'component', id: 'inbox' },+ { type: 'md', id: 'doc-1' },+ ]);+ const controllerId = manager.splits()[0].id;+ const viewerId = manager.splits()[1].id;++ expect(manager.restorePreviewPair(controllerId, viewerId)).toBe(true);+ expect(manager.splits()).toHaveLength(2);+ expect(manager.viewerOf(controllerId)).toBe(viewerId);+ expect(manager.controllerOf(viewerId)).toBe(controllerId);+ expect(manager.previewControllerWidth(controllerId)).toBe(440);+ expect(manager.activeSplitId()).toBe(controllerId);++ dispose();+ });+ });++ it('rejects a persisted Preview Pair that is no longer adjacent', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'component', id: 'inbox' },+ { type: 'md', id: 'between' },+ { type: 'md', id: 'viewer' },+ ]);+ const controllerId = manager.splits()[0].id;+ const viewerId = manager.splits()[2].id;++ expect(manager.restorePreviewPair(controllerId, viewerId)).toBe(false);+ expect(manager.previewPairs()).toEqual([]);++ dispose();+ });+ });++ it('unlinks a Preview Pair when a split is inserted between it', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ const viewerId = manager.viewerOf(controllerId)!;++ const inserted = manager.createNewSplit({+ content: { type: 'md', id: 'between' },+ referredFrom: null,+ insertIndex: 1,+ });++ expect(manager.splits().map((split) => split.id)).toEqual([+ controllerId,+ inserted.id,+ viewerId,+ ]);+ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.controllerOf(viewerId)).toBeUndefined();+ expect(manager.previewPairs()).toEqual([]);++ dispose();+ });+ });++ it('unlinks a Preview Pair when reconciliation separates it', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ manager.openWithSplit(+ { type: 'md', id: 'viewer' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ const viewerId = manager.viewerOf(controllerId)!;+ const between = manager.createNewSplit({+ content: { type: 'md', id: 'between' },+ referredFrom: null,+ });++ manager.reconcile([+ { type: 'component', id: 'inbox' },+ { type: 'md', id: 'between' },+ { type: 'md', id: 'viewer' },+ ]);++ expect(manager.splits().map((split) => split.id)).toEqual([+ controllerId,+ between.id,+ viewerId,+ ]);+ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.controllerOf(viewerId)).toBeUndefined();+ expect(manager.previewPairs()).toEqual([]);++ dispose();+ });+ });++ it('controller-originated navigation never grows the preview history', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ const viewerId = manager.viewerOf(controllerId)!;+ const viewer = manager.getSplit(viewerId)!;++ // Selections from the controller replace the preview's current entry.+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ manager.openWithSplit(+ { type: 'md', id: 'doc-2' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ expect(manager.splits()).toHaveLength(2);+ expect(viewer.content()).toMatchObject({ type: 'md', id: 'doc-2' });+ expect(viewer.history()).toHaveLength(1);+ expect(viewer.canGoBack()).toBe(false);+ expect(manager.activeSplitId()).toBe(controllerId);++ // The preview's own navigation stacks up as usual...+ manager.openWithSplit(+ { type: 'md', id: 'doc-3' },+ { referredFrom: null, handle: manager.getSplit(viewerId) }+ );+ expect(viewer.history()).toHaveLength(2);++ // ...and back returns to the last controller selection.+ viewer.goBack();+ expect(viewer.content()).toMatchObject({ type: 'md', id: 'doc-2' });++ dispose();+ });+ });++ it('routes Controller replacements to the Viewer, honoring new-split intent', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ const viewerId = manager.viewerOf(controllerId)!;++ // A replacement from the Controller lands in the Viewer.+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ expect(manager.splits()).toHaveLength(2);+ expect(manager.getSplit(viewerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-1',+ });+ expect(manager.activeSplitId()).toBe(controllerId);++ // Explicit new-split intent opens a real new split; the Preview Pair+ // stays.+ manager.openWithSplit(+ { type: 'md', id: 'doc-2' },+ {+ referredFrom: null,+ preferNewSplit: true,+ handle: manager.getSplit(controllerId),+ }+ );+ expect(manager.splits()).toHaveLength(3);+ expect(manager.getSplit(viewerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-1',+ });+ expect(manager.viewerOf(controllerId)).toBe(viewerId);++ dispose();+ });+ });++ it('honors handle-less new-split intent without dissolving the Preview Pair', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ const viewerId = manager.viewerOf(controllerId)!;++ const newSplit = manager.openWithSplit(+ { type: 'component', id: 'inbox' },+ {+ referredFrom: 'hotkey',+ allowDuplicate: true,+ preferNewSplit: true,+ }+ );++ expect(manager.splits()).toHaveLength(3);+ expect(manager.viewerOf(controllerId)).toBe(viewerId);+ expect(manager.controllerOf(viewerId)).toBe(controllerId);+ expect(newSplit?.content()).toMatchObject({+ type: 'component',+ id: 'inbox',+ });+ expect(manager.activeSplitId()).toBe(newSplit?.id);++ dispose();+ });+ });++ it('new-split intent falls back to the Viewer when the layout is full', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ const viewerId = manager.viewerOf(controllerId)!;+ manager.setResizeContext({+ canFit: () => false,+ } as unknown as ResizeZoneCtx);++ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ {+ referredFrom: null,+ preferNewSplit: true,+ handle: manager.getSplit(controllerId),+ }+ );+ // The fallback replaces the Viewer — never the Controller.+ expect(manager.splits()).toHaveLength(2);+ expect(manager.getSplit(viewerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-1',+ });+ expect(manager.getSplit(controllerId)!.content()).toMatchObject({+ type: 'component',+ id: 'inbox',+ });++ dispose();+ });+ });++ it('external (handle-less) navigation dissolves the Preview Pair', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ expect(manager.splits()).toHaveLength(2);++ // Sidebar-style soup view: content replaces the controller, the+ // Viewer closes.+ manager.openWithSplit(+ { type: 'component', id: 'channels' },+ { referredFrom: null }+ );+ expect(manager.splits()).toHaveLength(1);+ expect(manager.getSplit(controllerId)!.content()).toMatchObject({+ type: 'component',+ id: 'channels',+ });+ expect(manager.viewerOf(controllerId)).toBeUndefined();++ // Command-menu-style entity selection dissolves the Preview Pair the+ // same way.+ manager.engagePreviewMode(controllerId);+ expect(manager.splits()).toHaveLength(2);+ manager.openWithSplit(+ { type: 'md', id: 'doc-k' },+ { referredFrom: null }+ );+ expect(manager.splits()).toHaveLength(1);+ expect(manager.getSplit(controllerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-k',+ });+ expect(manager.viewerOf(controllerId)).toBeUndefined();++ dispose();+ });+ });++ it('returns a duplicate split without activating it', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.createNewSplit({+ content: { type: 'md', id: 'doc-open-elsewhere' },+ referredFrom: null,+ });+ manager.activateSplit(controllerId);+ manager.engagePreviewMode(controllerId);+ const viewerId = manager.viewerOf(controllerId)!;++ const result = manager.openWithSplit(+ { type: 'md', id: 'doc-open-elsewhere' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );++ expect(manager.splits()).toHaveLength(3);+ expect(result?.content()).toMatchObject({+ type: 'md',+ id: 'doc-open-elsewhere',+ });+ expect(manager.activeSplitId()).toBe(controllerId);+ // The eager viewer keeps its placeholder; nothing was opened into it.+ expect(manager.getSplit(viewerId)!.content()).toMatchObject({+ type: 'component',+ id: 'preview-empty',+ });++ dispose();+ });+ });++ it('disengages the Controller when the Viewer is closed', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ const viewerId = manager.viewerOf(controllerId)!;++ manager.removeSplit(viewerId);+ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.previewPairs()).toEqual([]);++ // Subsequent navigation replaces the controller normally.+ manager.openWithSplit(+ { type: 'md', id: 'doc-2' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ expect(manager.splits()).toHaveLength(1);+ expect(manager.getSplit(controllerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-2',+ });++ dispose();+ });+ });++ it('disengages when the Controller navigates away from a list view', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ expect(manager.splits()).toHaveLength(2);++ // The Viewer still shows the placeholder: it closes along with the+ // Preview Pair.+ manager.getSplit(controllerId)!.replace({+ next: { type: 'md', id: 'doc-x' },+ });+ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.splits()).toHaveLength(1);++ dispose();+ });+ });++ it('closes a content-bearing viewer when the controller leaves its list view', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ const viewerId = manager.viewerOf(controllerId)!;++ manager.getSplit(controllerId)!.replace({+ next: { type: 'md', id: 'doc-x' },+ });+ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.splits()).toHaveLength(1);+ expect(manager.getSplit(viewerId)).toBeUndefined();++ dispose();+ });+ });++ it('closes the viewer when the controller closes', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ const viewerId = manager.viewerOf(controllerId)!;++ manager.getSplit(controllerId)!.close();+ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.previewPairs()).toEqual([]);+ expect(manager.getSplit(controllerId)).toBeUndefined();+ expect(manager.getSplit(viewerId)).toBeUndefined();+ expect(manager.splits()).toHaveLength(1);+ expect(manager.splits()[0].content).toMatchObject({+ type: 'component',+ id: 'inbox',+ });++ dispose();+ });+ });++ it('disengages when reconcile drops the viewer', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ expect(manager.viewerOf(controllerId)).toBeDefined();++ manager.reconcile([{ type: 'component', id: 'inbox' }]);++ expect(manager.splits()).toHaveLength(1);+ expect(manager.splits()[0].id).toBe(controllerId);+ expect(manager.viewerOf(controllerId)).toBeUndefined();++ dispose();+ });+ });++ it('disengage closes the viewer and restores normal replace behavior', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ const viewerId = manager.viewerOf(controllerId)!;++ manager.disengagePreviewMode(controllerId);+ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.previewControllerWidth(controllerId)).toBeUndefined();+ expect(manager.getSplit(viewerId)).toBeUndefined();++ manager.openWithSplit(+ { type: 'md', id: 'doc-2' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ expect(manager.splits()).toHaveLength(1);+ expect(manager.getSplit(controllerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-2',+ });++ dispose();+ });+ });++ it('can unlink the Preview Pair without closing splits for URL reconstruction', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ const viewerId = manager.viewerOf(controllerId)!;++ manager.unlinkPreviewPair(controllerId);++ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.previewControllerWidth(controllerId)).toBeUndefined();+ expect(manager.getSplit(controllerId)).toBeDefined();+ expect(manager.getSplit(viewerId)).toBeDefined();++ dispose();+ });+ });++ it('leaves openWithSplit untouched when no split is engaged', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();++ manager.openWithSplit(+ { type: 'md', id: 'doc-1' },+ { referredFrom: null, handle: manager.getSplit(controllerId) }+ );+ expect(manager.splits()).toHaveLength(1);+ expect(manager.getSplit(controllerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-1',+ });+ expect(manager.activeSplitId()).toBe(controllerId);++ dispose();+ });+ });++ it('the Viewer navigates like a normal split', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.engagePreviewMode(controllerId);+ const viewerId = manager.viewerOf(controllerId)!;++ // A replacement from the Viewer replaces the Viewer.+ manager.openWithSplit(+ { type: 'md', id: 'doc-2' },+ { referredFrom: null, handle: manager.getSplit(viewerId) }+ );+ expect(manager.splits()).toHaveLength(2);+ expect(manager.getSplit(viewerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-2',+ });+ expect(manager.viewerOf(controllerId)).toBe(viewerId);++ // New-split intent from the Viewer opens a real new split;+ // the Preview Pair stays intact and the Controller is untouched.+ manager.openWithSplit(+ { type: 'md', id: 'doc-3' },+ {+ referredFrom: null,+ preferNewSplit: true,+ handle: manager.getSplit(viewerId),+ }+ );+ expect(manager.splits()).toHaveLength(3);+ expect(manager.getSplit(viewerId)!.content()).toMatchObject({+ type: 'md',+ id: 'doc-2',+ });+ expect(manager.getSplit(controllerId)!.content()).toMatchObject({+ type: 'component',+ id: 'inbox',+ });+ expect(manager.viewerOf(controllerId)).toBe(viewerId);++ dispose();+ });+ });++ it('cannot engage without room for a Viewer', () => {+ createRoot((dispose) => {+ const { manager, controllerId } = setup();+ manager.setResizeContext({+ canFit: () => false,+ } as unknown as ResizeZoneCtx);++ expect(manager.canEngagePreview(controllerId)).toBe(false);+ manager.engagePreviewMode(controllerId);++ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.splits()).toHaveLength(1);++ dispose();+ });+ });++ it('cannot engage ineligible content as a preview controller', () => {+ createRoot((dispose) => {+ const manager = createSplitLayout(createMockOrchestrator(), [+ { type: 'md', id: 'doc-1' },+ ]);+ const controllerId = manager.splits()[0].id;++ expect(manager.canEngagePreview(controllerId)).toBe(false);+ manager.engagePreviewMode(controllerId);++ expect(manager.viewerOf(controllerId)).toBeUndefined();+ expect(manager.splits()).toHaveLength(1);++ dispose();+ });+ });+ });});diff --git a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.tsnew file mode 100644index 0000000000..8b98cb177c--- /dev/null+++ b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts@@ -0,0 +1,216 @@+import type { BlockOrchestrator } from '@core/orchestrator';+import type { Navigator } from '@solidjs/router';+import { batch, createMemo, createRoot, createSignal } from 'solid-js';+import { beforeAll, describe, expect, it, vi } from 'vitest';+import { createSplitLayout, type SplitContent } from '../layoutManager';+import { createLayoutUrlSync } from '../layoutUrlSync';+import {+ loadRestorablePreviewLayout,+ type PreviewQueryValue,+} from '../previewPersistence';++vi.mock('../componentRegistry', () => ({+ resolveComponent: vi.fn((id: string, params: Record<string, string>) => ({+ type: 'mock-component',+ id,+ params,+ })),+}));++vi.mock('@core/constant/allBlocks', () => ({+ isBlockAlias: vi.fn(() => false),+ resolveBlockAlias: vi.fn((type: string) => type),+}));++beforeAll(() => {+ Object.defineProperty(window, 'matchMedia', {+ writable: true,+ value: (query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => true,+ }),+ });+});++function createMockOrchestrator(): BlockOrchestrator {+ return {+ createBlockInstance: vi.fn((_type, id, _splitId) => ({+ node: { type: 'mock-node', id },+ detach: vi.fn(),+ dispose: vi.fn(),+ })),+ } as unknown as BlockOrchestrator;+}++type HarnessOptions = {+ managerContent: SplitContent[];+ urlSegments: string[];+ previewQuery?: PreviewQueryValue;+ search?: string;+ hash?: string;+};++function createHarness(options: HarnessOptions) {+ const navigate = vi.fn();++ return createRoot((dispose) => {+ const manager = createSplitLayout(+ createMockOrchestrator(),+ options.managerContent+ );+ const [pairs, setPairs] = createSignal(options.urlSegments);+ const [previewQuery, setPreviewQuery] = createSignal<PreviewQueryValue>(+ options.previewQuery+ );+ const [search, setSearch] = createSignal(options.search ?? '');+ const [hash, setHash] = createSignal(options.hash ?? '');+ const decodedLayout = createMemo(() =>+ loadRestorablePreviewLayout(pairs(), previewQuery())+ );++ createLayoutUrlSync(manager, pairs, previewQuery, decodedLayout, {+ navigate: navigate as Navigator,+ search,+ hash,+ });++ return {+ manager,+ navigate,+ dispose,+ setUrl(+ segments: string[],+ preview: PreviewQueryValue,+ nextSearch = '',+ nextHash = ''+ ) {+ batch(() => {+ setPairs(segments);+ setPreviewQuery(preview);+ setSearch(nextSearch);+ setHash(nextHash);+ });+ },+ };+ });+}++async function flushUrlSync() {+ await new Promise<void>((resolve) => queueMicrotask(resolve));+ await new Promise<void>((resolve) => queueMicrotask(resolve));+}++describe('layout URL synchronization', () => {+ it('coalesces preview engagement into one canonical manager-to-URL update', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'inbox' }],+ urlSegments: ['component', 'inbox'],+ });++ await flushUrlSync();+ harness.navigate.mockClear();+ harness.manager.engagePreviewMode(harness.manager.splits()[0].id);+ await flushUrlSync();++ expect(harness.navigate).toHaveBeenCalledTimes(1);+ expect(harness.navigate).toHaveBeenCalledWith(+ `/${harness.manager.getUrlSegments().join('/')}?preview=0`,+ { replace: false }+ );++ harness.dispose();+ });++ it('preserves unrelated query and hash state for a query-only update', async () => {+ const harness = createHarness({+ managerContent: [+ { type: 'component', id: 'inbox' },+ { type: 'component', id: 'preview-empty' },+ ],+ urlSegments: ['component', 'inbox', 'component', 'preview-empty'],+ search: '?keep=value',+ hash: '#selection',+ });++ await flushUrlSync();+ harness.navigate.mockClear();+ harness.manager.engagePreviewMode(harness.manager.splits()[0].id);+ await flushUrlSync();++ expect(harness.navigate).toHaveBeenCalledWith(+ `/${harness.manager.getUrlSegments().join('/')}?keep=value&preview=0#selection`,+ { replace: false }+ );++ harness.dispose();+ });++ it('reconciles URL path and preview state without navigating back', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'inbox' }],+ urlSegments: ['component', 'inbox'],+ });+ await flushUrlSync();+ harness.navigate.mockClear();++ harness.setUrl(['component', 'inbox', 'md', 'doc-1'], '0', '?preview=0');+ await flushUrlSync();++ const [controller, viewer] = harness.manager.splits();+ expect(controller.content).toMatchObject({+ type: 'component',+ id: 'inbox',+ });+ expect(viewer.content).toMatchObject({ type: 'md', id: 'doc-1' });+ expect(harness.manager.viewerOf(controller.id)).toBe(viewer.id);+ expect(harness.navigate).not.toHaveBeenCalled();++ harness.dispose();+ });++ it('canonicalizes invalid bare preview placeholders with replace', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'inbox' }],+ urlSegments: ['component', 'inbox', 'component', 'preview-empty'],+ });++ await flushUrlSync();++ expect(harness.navigate).toHaveBeenCalledTimes(1);+ expect(harness.navigate).toHaveBeenCalledWith('/component/inbox', {+ replace: true,+ });++ harness.dispose();+ });++ it('uses replace navigation and clears location state for replace-caused path changes', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'inbox' }],+ urlSegments: ['component', 'inbox'],+ search: '?keep=value',+ hash: '#selection',+ });+ await flushUrlSync();+ harness.navigate.mockClear();++ const split = harness.manager.getSplit(harness.manager.splits()[0].id)!;+ split.replace({+ next: { type: 'md', id: 'doc-1' },+ mergeHistory: true,+ });+ await flushUrlSync();++ expect(harness.navigate).toHaveBeenCalledWith('/md/doc-1', {+ replace: true,+ });++ harness.dispose();+ });+});diff --git a/apps/web/src/components/app/split-layout/tests/previewController.test.ts b/apps/web/src/components/app/split-layout/tests/previewController.test.tsnew file mode 100644index 0000000000..04267cdfb7--- /dev/null+++ b/apps/web/src/components/app/split-layout/tests/previewController.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';+import {+ isPreviewControllerContent,+ previewControllerWidthForContent,+} from '../previewController';++describe('preview controller content', () => {+ it('explicitly recognizes configured content', () => {+ expect(isPreviewControllerContent({ type: 'component', id: 'inbox' })).toBe(+ true+ );+ expect(+ isPreviewControllerContent({ type: 'component', id: 'settings' })+ ).toBe(false);+ expect(isPreviewControllerContent({ type: 'md', id: 'doc-1' })).toBe(false);+ expect(+ isPreviewControllerContent({ type: 'project', id: 'project-1' })+ ).toBe(true);+ });++ it('resolves default and content-specific widths from the same config', () => {+ expect(+ previewControllerWidthForContent({ type: 'component', id: 'inbox' })+ ).toBe(440);+ expect(+ previewControllerWidthForContent({ type: 'component', id: 'mail' })+ ).toBe(1050);+ expect(+ previewControllerWidthForContent({ type: 'component', id: 'companies' })+ ).toBe(880);+ expect(+ previewControllerWidthForContent(+ { type: 'component', id: 'companies' },+ 1000+ )+ ).toBe(700);+ expect(+ previewControllerWidthForContent(+ { type: 'component', id: 'companies' },+ 1600+ )+ ).toBe(880);+ expect(+ previewControllerWidthForContent({ type: 'component', id: 'settings' })+ ).toBeUndefined();+ expect(+ previewControllerWidthForContent({+ type: 'project',+ id: 'project-1',+ })+ ).toBe(440);+ });+});diff --git a/apps/web/src/components/app/split-layout/tests/previewPersistence.test.ts b/apps/web/src/components/app/split-layout/tests/previewPersistence.test.tsnew file mode 100644index 0000000000..e9425706fd--- /dev/null+++ b/apps/web/src/components/app/split-layout/tests/previewPersistence.test.ts@@ -0,0 +1,164 @@+import { describe, expect, it, vi } from 'vitest';+import {+ loadRestorablePreviewLayout,+ serializePreviewPairs,+} from '../previewPersistence';++vi.mock('../layoutUtils', () => ({+ decodePairs: (segments: string[]) => {+ const pairs: Array<{ type: string; id: string }> = [];+ for (let index = 0; index < segments.length; index += 2) {+ const type = segments[index];+ const id = segments[index + 1];+ if (!type || !id) break;+ pairs.push({ type, id });+ }+ return pairs.length > 0 ? pairs : [{ type: 'component', id: 'inbox' }];+ },+}));++const controllerAndPlaceholder = [+ 'component',+ 'mail',+ 'component',+ 'preview-empty',+];++describe('Preview Pair URL state', () => {+ it('serializes one or more Preview Pairs in Controller order', () => {+ expect(+ serializePreviewPairs([{ controllerIndex: 2 }, { controllerIndex: 0 }])+ ).toBe('0_2');+ expect(serializePreviewPairs([])).toBeUndefined();+ });++ it('restores a copied placeholder Preview Pair', () => {+ expect(loadRestorablePreviewLayout(controllerAndPlaceholder, '0')).toEqual({+ contents: [+ { type: 'component', id: 'mail' },+ { type: 'component', id: 'preview-empty' },+ ],+ previewPairs: [{ controllerIndex: 0 }],+ });+ });++ it('restores a Preview Pair after the Viewer has real content', () => {+ const segments = ['component', 'mail', 'md', 'doc-1'];++ expect(loadRestorablePreviewLayout(segments, '0')).toEqual({+ contents: [+ { type: 'component', id: 'mail' },+ { type: 'md', id: 'doc-1' },+ ],+ previewPairs: [{ controllerIndex: 0 }],+ });+ });++ it('restores a Preview Pair whose Viewer is itself controller-eligible', () => {+ // A Project controlling another Project is a valid runtime pair+ // (canLinkPreviewPair only constrains the Controller), so it must survive+ // a URL round trip.+ const segments = ['project', 'proj-controller', 'project', 'proj-viewer'];++ expect(loadRestorablePreviewLayout(segments, '0')).toEqual({+ contents: [+ { type: 'project', id: 'proj-controller' },+ { type: 'project', id: 'proj-viewer' },+ ],+ previewPairs: [{ controllerIndex: 0 }],+ });+ });++ it('restores multiple non-overlapping Preview Pairs', () => {+ const segments = [+ 'component',+ 'mail',+ 'component',+ 'preview-empty',+ 'component',+ 'channels',+ 'md',+ 'doc-1',+ ];++ expect(loadRestorablePreviewLayout(segments, '0_2')).toEqual({+ contents: [+ { type: 'component', id: 'mail' },+ { type: 'component', id: 'preview-empty' },+ { type: 'component', id: 'channels' },+ { type: 'md', id: 'doc-1' },+ ],+ previewPairs: [{ controllerIndex: 0 }, { controllerIndex: 2 }],+ });+ });++ it('removes a bare preview placeholder without a query Preview Pair', () => {+ expect(+ loadRestorablePreviewLayout(controllerAndPlaceholder, undefined)+ ).toEqual({+ contents: [{ type: 'component', id: 'mail' }],+ previewPairs: [],+ });+ });++ it('keeps valid tuples while dropping malformed and overlapping tuples', () => {+ const segments = [+ 'component',+ 'mail',+ 'md',+ 'doc-1',+ 'component',+ 'channels',+ 'md',+ 'doc-2',+ ];++ expect(+ loadRestorablePreviewLayout(segments, 'bad_0_0_nope_2').previewPairs+ ).toEqual([{ controllerIndex: 0 }, { controllerIndex: 2 }]);+ });++ it('rejects out-of-bounds and content-invalid tuples', () => {+ expect(+ loadRestorablePreviewLayout(+ ['component', 'settings', 'md', 'doc-1'],+ '0_4'+ )+ ).toEqual({+ contents: [+ { type: 'component', id: 'settings' },+ { type: 'md', id: 'doc-1' },+ ],+ previewPairs: [],+ });+ });++ it('rejects repeated query parameters as non-canonical', () => {+ expect(+ loadRestorablePreviewLayout(controllerAndPlaceholder, ['0', '2'])+ ).toEqual({+ contents: [{ type: 'component', id: 'mail' }],+ previewPairs: [],+ });+ });++ it('falls back to inbox when a placeholder is the only URL entry', () => {+ expect(+ loadRestorablePreviewLayout(['component', 'preview-empty'], undefined)+ ).toEqual({+ contents: [{ type: 'component', id: 'inbox' }],+ previewPairs: [],+ });+ });++ it('filters preview state when Preview Pairs are disabled', () => {+ expect(+ loadRestorablePreviewLayout(controllerAndPlaceholder, '0', {+ allowPreviewPairs: false,+ })+ ).toEqual({+ contents: [{ type: 'component', id: 'mail' }],+ previewPairs: [],+ });+ });+});diff --git a/apps/web/src/components/app/split-layout/tests/registerSplitHotkeys.test.ts b/apps/web/src/components/app/split-layout/tests/registerSplitHotkeys.test.tsnew file mode 100644index 0000000000..d32be66bf2--- /dev/null+++ b/apps/web/src/components/app/split-layout/tests/registerSplitHotkeys.test.ts@@ -0,0 +1,65 @@+import { registerHotkey } from '@core/hotkey/hotkeys';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { registerSplitHotkeys } from '../registerSplitHotkeys';++vi.mock('@app/signal/splitLayout', () => ({+ globalSplitManager: () => undefined,+}));++vi.mock('@core/hotkey/hotkeys', () => ({+ registerHotkey: vi.fn(),+}));++vi.mock('@core/hotkey/tokens', () => ({+ TOKENS: {+ split: {+ close: 'split.close',+ go: { back: 'split.go.back', forward: 'split.go.forward' },+ },+ window: {+ spotlight: { toggle: 'window.spotlight.toggle' },+ focusSplitRight: 'window.focusSplitRight',+ focusSplitLeft: 'window.focusSplitLeft',+ },+ },+}));++vi.mock('../layoutUtils', () => ({+ focusAdjacentSplit: vi.fn(),+}));++vi.mock('../utils/canSpotlight', () => ({+ canSpotlight: () => false,+}));++describe('registerSplitHotkeys', () => {+ beforeEach(() => {+ vi.mocked(registerHotkey).mockClear();+ });++ it('disables cmd+escape and opt+escape inside a Preview Pair Viewer', () => {+ let isPreviewSplit = true;+ registerSplitHotkeys({+ splitHotkeyScope: 'split=test',+ insertSplit: vi.fn(),+ closeSplit: vi.fn(),+ toggleSpotlight: vi.fn(),+ canGoBack: () => false,+ goBack: vi.fn(),+ canGoForward: () => false,+ goForward: vi.fn(),+ goHome: vi.fn(),+ splitName: () => 'Test',+ getSplitCount: () => 2,+ isNotUnifiedList: () => true,+ isViewerSplit: () => isPreviewSplit,+ });++ const closeRegistration = vi.mocked(registerHotkey).mock.calls[0]?.[0];+ expect(closeRegistration?.hotkey).toEqual(['cmd+escape', 'opt+escape']);+ expect(closeRegistration?.condition?.()).toBe(false);++ isPreviewSplit = false;+ expect(closeRegistration?.condition?.()).toBe(true);+ });+});diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsxindex a8730bec3d..4454609fa1 100644--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx@@ -33,10 +33,12 @@ import {isOpenCallTabRequested,} from '@channel/Channel/link';import { ChannelParticipantsTab } from '@channel/Participants/ChannelParticipantsTab';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import {+ useCanAutofocusSplitContent,+ useSplitPanelOrThrow,+} from '@components/app/split-layout/layoutUtils';import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';import { useBlockId } from '@core/block';import { EntityPermissionsGate } from '@core/component/EntityPermissionsGate';@@ -185,8 +187,8 @@ function NewTop(props: { channelId: string }) {export function NewChannelBlockAdapter(props: BlockChannelProps) {useBlockEntityCommands();- const isPreview = !!useMaybePreviewPanel();const splitPanel = useSplitPanelOrThrow();+ const canAutofocusSplitContent = useCanAutofocusSplitContent();const { navigatedFromJK } = useNavigatedFromJK();const channelId = useBlockId();const blockHandle = blockHandleSignal.get;@@ -195,21 +197,17 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {// Decide whether the user asked to auto-join the call (via ?join_call=true// deep link or programmatic open props) before creating signals so we// can land directly on the Call tab without flashing Messages first.- // Skipped inside a preview panel so hover-previews don't auto-join.const wantsJoinCall =- !isPreview &&- (isJoinCallRequested(props[CHANNEL_URL_PARAMS.joinCall]) ||- isJoinCallRequested(searchParams[CHANNEL_URL_PARAMS.joinCall]));+ isJoinCallRequested(props[CHANNEL_URL_PARAMS.joinCall]) ||+ isJoinCallRequested(searchParams[CHANNEL_URL_PARAMS.joinCall]);const callCtx = useCallContextOptional();const hasActiveCallHere = !!(callCtx?.isInCall() && callCtx.activeChannelId() === channelId);- const persistedChannelState = (- isPreview- ? undefined- : splitPanel.handle.currentEntryState()?.[CHANNEL_STATE_ENTRY_KEY]- ) as ChannelEntryStateSnapshot | undefined;+ const persistedChannelState = splitPanel.handle.currentEntryState()?.[+ CHANNEL_STATE_ENTRY_KEY+ ] as ChannelEntryStateSnapshot | undefined;const hasInitialTargetRequest = () => {const hasPropsTarget =@@ -227,7 +225,6 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {};const shouldHydratePersistedChannelState =- !isPreview &&!wantsJoinCall &&!hasActiveCallHere &&!isOpenCallTabRequested(props[CHANNEL_URL_PARAMS.openCallTab]) &&@@ -262,7 +259,6 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {const botManagement = useChannelBotManagement({channelId,hotkeyScopeId: splitPanel.splitHotkeyScope,- isPreview,openParticipants: () => setActiveTab('participants'),});@@ -270,14 +266,14 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {// `createComputed` (not `createEffect`) so this runs before paint and matches// `activeTab` on the first frame (e.g. deep-link opens on Call tab).createComputed(() => {- if (isPreview || !callCtx) return;+ if (!callCtx) return;const tab = activeTab();callCtx.syncCallPageTab(channelId, tab === 'call');});// Nav away unmounts this block without switching tabs first — clear stale ownership.onCleanup(() => {- if (isPreview || !callCtx) return;+ if (!callCtx) return;callCtx.syncCallPageTab(channelId, false);});@@ -401,24 +397,21 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {setMessagesHandle(() => handle);};- if (!isPreview) {- const disposeChannelStateCaptor =- splitPanel.handle.registerEntryStateCaptor(- CHANNEL_STATE_ENTRY_KEY,- (): ChannelEntryStateSnapshot => {- const handle = messagesHandle();- const messages = handle- ? handle.getMessagesStateSnapshot()- : lastMessagesStateSnapshot;- lastMessagesStateSnapshot = messages;- return {- activeTab: activeTab(),- messages,- };- }- );- onCleanup(disposeChannelStateCaptor);- }+ const disposeChannelStateCaptor = splitPanel.handle.registerEntryStateCaptor(+ CHANNEL_STATE_ENTRY_KEY,+ (): ChannelEntryStateSnapshot => {+ const handle = messagesHandle();+ const messages = handle+ ? handle.getMessagesStateSnapshot()+ : lastMessagesStateSnapshot;+ lastMessagesStateSnapshot = messages;+ return {+ activeTab: activeTab(),+ messages,+ };+ }+ );+ onCleanup(disposeChannelStateCaptor);const initialMessagesStateSnapshot = () =>shouldHydratePersistedChannelState@@ -449,7 +442,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {<NewChannelchannelId={channelId}onHandleReady={onChannelReady}- autofocus={!isPreview && !navigatedFromJK()}+ autofocus={canAutofocusSplitContent && !navigatedFromJK()}initialMessagesStateSnapshot={initialMessagesStateSnapshot()}{...convertTargetMessage(initialTargetMessageParams())}/>diff --git a/apps/web/src/features/block-channel/component/useChannelBotManagement.ts b/apps/web/src/features/block-channel/component/useChannelBotManagement.tsindex 11aaaf8688..d6605b1228 100644--- a/apps/web/src/features/block-channel/component/useChannelBotManagement.ts+++ b/apps/web/src/features/block-channel/component/useChannelBotManagement.ts@@ -21,7 +21,6 @@ import { createSignal, onCleanup } from 'solid-js';type UseChannelBotManagementOptions = {channelId: string;hotkeyScopeId: string;- isPreview: boolean;openParticipants: () => void;};@@ -37,9 +36,7 @@ export function useChannelBotManagement(const enabled = () => featureFlag().enabled;const canManageBots = () =>- !options.isPreview &&- enabled() &&- channelType() === ChannelTypeEnum.Private;+ enabled() && channelType() === ChannelTypeEnum.Private;const openCreateBot = () => {requestBotCreation(options.channelId);@@ -101,7 +98,7 @@ export function useChannelBotManagement(icon: CopyIcon,keywords: ['bot', 'webhook', 'endpoint'],displayPriority: 8,- condition: () => enabled() && !options.isPreview,+ condition: enabled,keyDownHandler: () => {void copyWebhookUrl();return true;diff --git a/apps/web/src/features/block-channel/utils/link.ts b/apps/web/src/features/block-channel/utils/link.tsindex ac17df7123..d43121f3d1 100644--- a/apps/web/src/features/block-channel/utils/link.ts+++ b/apps/web/src/features/block-channel/utils/link.ts@@ -1,6 +1,9 @@import { globalSplitManager } from '@app/signal/splitLayout';import { URL_PARAMS } from '@block-channel/constants';-import type { SplitManager } from '@components/app/split-layout/layoutManager';+import type {+ SplitHandle,+ SplitManager,+} from '@components/app/split-layout/layoutManager';import type { BlockOrchestrator } from '@core/orchestrator';export function getChannelParams(@@ -56,6 +59,12 @@ export async function navigateToChannelMessage(options?: {splitManager?: SplitManager;preferNewSplit?: boolean;+ /**+ * The split this navigation originates from. When it is an engaged+ * preview controller, the open is redirected into its viewer split and+ * never steals the keyboard from the controller.+ */+ sourceHandle?: SplitHandle;}) {const splitManager = options?.splitManager ?? globalSplitManager();@@ -63,7 +72,12 @@ export async function navigateToChannelMessage(const existing = splitManager.getSplitByContent('channel', channelId);if (existing) {- existing.activate();+ // The channel already showing in the source's own viewer is a plain+ // retarget; activating it would pull focus out of the controller.+ const isSourcesViewer =+ options?.sourceHandle?.isControllerSplit() &&+ options.sourceHandle.viewerId() === existing.id;+ if (!isSourcesViewer) existing.activate();} else {splitManager.openWithSplit({@@ -75,6 +89,7 @@ export async function navigateToChannelMessage(activate: true,referredFrom: null,preferNewSplit: options?.preferNewSplit,+ handle: options?.sourceHandle,});}diff --git a/apps/web/src/features/block-chat/component/Chat.tsx b/apps/web/src/features/block-chat/component/Chat.tsxindex 8af9d353c6..6d200a7636 100644--- a/apps/web/src/features/block-chat/component/Chat.tsx+++ b/apps/web/src/features/block-chat/component/Chat.tsx@@ -4,7 +4,7 @@ import { TopBar } from '@block-chat/component/TopBar';import type { ChatData } from '@block-chat/definition';import { pendingLocationParamsSignal } from '@block-chat/signal/pendingLocationParams';import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';+import { useCanAutofocusSplitContent } from '@components/app/split-layout/layoutUtils';import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';import { useHasPaidAccess } from '@core/auth/license';import { useBlockId, useIsNestedBlock } from '@core/block';@@ -148,7 +148,7 @@ function ChatInner(props: {const scopeId = blockHotkeyScopeSignal.get;const blockElement = blockElementSignal.get;const { navigatedFromJK } = useNavigatedFromJK();- const isPreview = !!useMaybePreviewPanel();+ const canAutofocusSplitContent = useCanAutofocusSplitContent();const [scrollRef, setScrollRef] = createSignal<HTMLElement>();const [showStreamDebug, setShowStreamDebug] = createSignal(false);const [markdownText, setMarkdownText] = createSignal(@@ -304,10 +304,12 @@ function ChatInner(props: {hotkeyToken: TOKENS.chat.stop,});- // In preview mode, switching between Soup tabs was causing this createEffect to overflow the stack. We should figure out that root cause, this flag fixes it for now.+ // J/K navigation focuses the block once it mounts, except when that block is+ // passive content in a Preview Pair Viewer.let hasRun = false;createEffect(() => {if (hasRun) return;+ if (!canAutofocusSplitContent) return;if (!blockElement()) return;if (!navigatedFromJK()) return;blockElement()?.focus();@@ -368,7 +370,9 @@ function ChatInner(props: {chatId={chat.chatId()}onSend={onSend}onStop={onStop}- autoFocusOnMount={!isPreview && !navigatedFromJK()}+ autoFocusOnMount={+ canAutofocusSplitContent && !navigatedFromJK()+ }/></div></div>diff --git a/apps/web/src/features/block-chat/signal/chatBlockData.test.ts b/apps/web/src/features/block-chat/signal/chatBlockData.test.tsnew file mode 100644index 0000000000..460b46e335--- /dev/null+++ b/apps/web/src/features/block-chat/signal/chatBlockData.test.ts@@ -0,0 +1,8 @@+import { describe, expect, it } from 'vitest';+import { chatBlockData } from './chatBlockData';++describe('chatBlockData', () => {+ it('initializes without a circular block-registry dependency', () => {+ expect(chatBlockData).toBeTypeOf('function');+ });+});diff --git a/apps/web/src/features/block-email/component/Block.tsx b/apps/web/src/features/block-email/component/Block.tsxindex 7586be4520..d5427e12d5 100644--- a/apps/web/src/features/block-email/component/Block.tsx+++ b/apps/web/src/features/block-email/component/Block.tsx@@ -1,6 +1,6 @@import { useBlockEntityCommands } from '@app/features/next-soup/actions';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';import { EmailDebouncedReadMarker } from '@notifications';import { useThreadQuery } from '@queries/email/thread';@@ -12,7 +12,9 @@ export default function BlockEmail() {useBlockEntityCommands();const blockData = blockDataSignal.get;const notificationSource = useGlobalNotificationSource();- const isPreview = !!useMaybePreviewPanel();+ // A Preview Pair Viewer shows the thread passively — wait longer before+ // marking it seen so scanning/previewing doesn't clear unread state.+ const isPreview = !!useSplitPanel()?.handle.isViewerSplit();const threadId = createMemo(() => blockData()?.thread?.db_id ?? '');diff --git a/apps/web/src/features/block-email/component/Email.tsx b/apps/web/src/features/block-email/component/Email.tsxindex def927b918..e203399c14 100644--- a/apps/web/src/features/block-email/component/Email.tsx+++ b/apps/web/src/features/block-email/component/Email.tsx@@ -6,7 +6,10 @@ import {} from '@block-email/component/EmailContext';import { SidePanel } from '@components/app/side-panel';import { useSplitLayout } from '@components/app/split-layout/layout';-import { useSplitPanel } from '@components/app/split-layout/layoutUtils';+import {+ useCanAutofocusSplitContent,+ useSplitPanel,+} from '@components/app/split-layout/layoutUtils';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { useEmail, useUserContext } from '@core/context/user';import { TOKENS } from '@core/hotkey/tokens';@@ -82,6 +85,7 @@ function EmailContent(props: EmailViewProps) {const context = useEmailContext();const splitPanel = useSplitPanel();+ const canAutofocusSplitContent = useCanAutofocusSplitContent();const { isLoading: isUserLoading } = useUserContext();const userEmail = useEmail();@@ -445,10 +449,11 @@ function EmailContent(props: EmailViewProps) {const navigateToPreviousMessage = () => navigateMessage('prev');const navigateToNextMessage = () => navigateMessage('next');- // In preview mode, switching between Soup tabs was causing this createEffect to overflow the stack. We should figure out that root cause, this flag fixes it for now.+ // Wait for the block element before claiming focus on initial mount.let hasRun = false;createEffect(() => {if (hasRun) return;+ if (!canAutofocusSplitContent) return;// Focus the email block on mountif (isTouchDevice()) return;if (!blockElement()) return;diff --git a/apps/web/src/features/block-email/component/EmailContext.tsx b/apps/web/src/features/block-email/component/EmailContext.tsxindex 399edba49f..f1944b9908 100644--- a/apps/web/src/features/block-email/component/EmailContext.tsx+++ b/apps/web/src/features/block-email/component/EmailContext.tsx@@ -7,7 +7,6 @@ import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils'import { URL_PARAMS } from '@block-email/constants';import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientConversion';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import {getPermissions,@@ -384,7 +383,6 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {};const soup = useMaybeSoup();- const previewPanel = useMaybePreviewPanel();const splitPanel = useSplitPanel();const userId = useUserId();@@ -601,7 +599,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {soup,(nextEntity) => {const splitHandle = splitPanel?.handle;- if (!splitHandle || previewPanel !== undefined) return;+ if (!splitHandle) return;void openEntityInSplitFromUnifiedList(nextEntity, {splitHandle,mergeHistory: true,diff --git a/apps/web/src/features/block-md/component/Notebook.tsx b/apps/web/src/features/block-md/component/Notebook.tsxindex 35b814da0e..e88d82f20a 100644--- a/apps/web/src/features/block-md/component/Notebook.tsx+++ b/apps/web/src/features/block-md/component/Notebook.tsx@@ -8,6 +8,7 @@ import {import { useGoToTempRedirect } from '@block-md/signal/location';import { mdStore } from '@block-md/signal/markdownBlockData';import { SidePanel } from '@components/app/side-panel';+import { useCanAutofocusSplitContent } from '@components/app/split-layout/layoutUtils';import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';import { useBlockAliasedName, useBlockId } from '@core/block';import {@@ -128,6 +129,7 @@ export function Notebook(props: {const md = mdStore.get;const history = useHistory();const { navigatedFromJK } = useNavigatedFromJK();+ const canAutofocusSplitContent = useCanAutofocusSplitContent();const documentId = props.documentId;const canEdit = useCanEdit();const inlineAiEditing = useFeatureFlag(INLINE_AI_EDITING_FLAG, {@@ -267,10 +269,11 @@ export function Notebook(props: {}});- // In preview mode, switching between Soup tabs was causing this createEffect to overflow the stack. We should figure out that root cause, this flag fixes it for now.+ // Wait for the block element before claiming focus on initial mount.let hasRun = false;createEffect(() => {if (hasRun) return;+ if (!canAutofocusSplitContent) return;if (!blockElement()) return;blockElement()?.focus();hasRun = true;@@ -376,7 +379,9 @@ export function Notebook(props: {</Show></div></SidePanel.Section>- <TitleEditor autoFocusOnMount={!navigatedFromJK()} />+ <TitleEditor+ autoFocusOnMount={canAutofocusSplitContent && !navigatedFromJK()}+ /><div class="spacer h-3" /><div class="mb-6 flex flex-row flex-wrap items-center gap-2 text-sm empty:hidden"><InlineTaskProperties />diff --git a/apps/web/src/features/block-project/component/Block.tsx b/apps/web/src/features/block-project/component/Block.tsxindex 998b54beaa..c91efa8a31 100644--- a/apps/web/src/features/block-project/component/Block.tsx+++ b/apps/web/src/features/block-project/component/Block.tsx@@ -7,21 +7,14 @@ import { defineQueryFilters } from '@app/features/next-soup/filters/filter-storeimport { SoupContextProvider } from '@app/features/next-soup/soup-context';import { SoupViewList } from '@app/features/next-soup/soup-view/soup-view';import { SoupViewContextProvider } from '@app/features/next-soup/soup-view/soup-view-context';-import { useAnalytics } from '@app/lib/analytics/analytics-context';import { getIsSpecialProject } from '@block-project/isSpecial';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { SidePanel } from '@components/app/side-panel';-import { SplitPanelContext } from '@components/app/split-layout/context';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { useBlockId } from '@core/block';import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';import { FileDropOverlay } from '@core/component/FileDropOverlay';import { toast } from '@core/component/Toast/Toast';-import { ENABLE_PROJECT_VIEW_PREVIEW } from '@core/constant/featureFlags';import { fileFolderDrop } from '@core/directive/fileFolderDrop';import { fileSelector } from '@core/directive/fileSelector';-import { registerHotkey } from '@core/hotkey/hotkeys';-import { TOKENS } from '@core/hotkey/tokens';import { blockHotkeyScopeSignal } from '@core/signal/blockElement';import {handleFileFolderDrop,@@ -94,11 +87,6 @@ const Block: Component = () => {}};- const previewPanel = useMaybePreviewPanel();-- const splitPanelContext = useSplitPanelOrThrow();- const analytics = useAnalytics();-const projectSoup = createSoupState({initialPredicates: { and: ['project-content'] },predicateConfigs: [@@ -110,29 +98,6 @@ const Block: Component = () => {],});- // Preview can only work one level deep — don't register the toggle when- // this project is already being rendered inside a preview panel.- if (!previewPanel) {- registerHotkey({- hotkey: ['space'],- scopeId: splitPanelContext.splitHotkeyScope,- description: 'Toggle Preview',- hotkeyToken: TOKENS.unifiedList.togglePreview,- keyDownHandler: () => {- if (projectSoup.previewEntity()) {- projectSoup.setPreviewEntity(undefined);- return true;- }- const focused = projectSoup.focus.id();- if (!focused) return true;- analytics.track('preview_panel_use');- projectSoup.setPreviewEntity(focused);- return true;- },- hide: true,- });- }-return (<DocumentBlockContainer><div@@ -156,38 +121,13 @@ const Block: Component = () => {</Show><div class="flex size-full min-w-0 flex-col overflow-hidden"><TopBar />- <Show- when={ENABLE_PROJECT_VIEW_PREVIEW}- fallback={- <ProjectEntityList- projectId={projectId}- soup={projectSoup}- // Scope is already attached by the block container so we can use that- // Change this when we remove blocks- scopeId={blockHotkeyScopeSignal.get()}- />- }- >- <div class="flex size-full">- <SplitPanelContext.Provider- value={{- ...splitPanelContext,- halfSplitState: () =>- projectSoup.previewEntity() && projectSoup.focus.item()- ? { side: 'left', percentage: 30 }- : undefined,- }}- >- <ProjectEntityList- projectId={projectId}- soup={projectSoup}- // Scope is already attached by the block container so we can use that- // Change this when we remove blocks- scopeId={blockHotkeyScopeSignal.get()}- />- </SplitPanelContext.Provider>- </div>- </Show>+ <ProjectEntityList+ projectId={projectId}+ soup={projectSoup}+ // Scope is already attached by the block container so we can use that+ // Change this when we remove blocks+ scopeId={blockHotkeyScopeSignal.get()}+ /></div></SidePanel.Layout></ModalsProvider>diff --git a/apps/web/src/features/block-project/component/TopBar.tsx b/apps/web/src/features/block-project/component/TopBar.tsxindex 4f6161d829..ab72a05a17 100644--- a/apps/web/src/features/block-project/component/TopBar.tsx+++ b/apps/web/src/features/block-project/component/TopBar.tsx@@ -10,6 +10,7 @@ import {ResponsivePermissionsBadge,ToolButton,} from '@components/app/ResponsiveBlockToolbar';+import { PreviewButton } from '@components/app/split-layout/components/PreviewButton';import { useDrawerControl } from '@components/app/split-layout/components/SplitDrawerContext';import {type FileOperation,@@ -27,7 +28,6 @@ import {SplitToolbarLeft,SplitToolbarRight,} from '@components/app/split-layout/components/SplitToolbar';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { useBlockId } from '@core/block';import { DETAILS_DRAWER_ID } from '@core/component/DetailsDrawer';import { toast } from '@core/component/Toast/Toast';@@ -36,10 +36,7 @@ import {ShareTrigger,useShareDialogContext,} from '@core/component/TopBar/ShareButton';-import {- ENABLE_PROJECT_SHARING,- ENABLE_PROJECT_VIEW_PREVIEW,-} from '@core/constant/featureFlags';+import { ENABLE_PROJECT_SHARING } from '@core/constant/featureFlags';import { isMobile } from '@core/mobile/isMobile';import { useCanEdit, useIsDocumentOwner } from '@core/signal/permissions';import { buildSimpleEntityUrl } from '@core/util/url';@@ -52,8 +49,6 @@ import { ProjectCreateMenu, useProjectCreateTools } from './ProjectCreateMenu';// with folder block.export function TopBar() {- const splitPanelContext = useSplitPanelOrThrow();- const [preview] = splitPanelContext.previewState;const id = useBlockId();const isSpecialProject = getIsSpecialProject(id);const isOwner = useIsDocumentOwner();@@ -94,11 +89,6 @@ export function TopBar() {: []),]);- const showToolbarRight = () => {- if (!ENABLE_PROJECT_VIEW_PREVIEW) return true;- return !preview();- };-const { tools: createTools, CreateDialog } = useProjectCreateTools(id,name,@@ -161,21 +151,20 @@ export function TopBar() {</Show></div></SplitToolbarLeft>- <Show when={showToolbarRight()}>- <SplitToolbarRight>- <For each={toolbarTools()}>- {(tool) => (- <Show when={!tool.condition || tool.condition()}>- {tool.buttonComponent ? (- <tool.buttonComponent />- ) : (- <ToolButton tool={tool} />- )}- </Show>- )}- </For>- </SplitToolbarRight>- </Show>+ <SplitToolbarRight>+ <For each={toolbarTools()}>+ {(tool) => (+ <Show when={!tool.condition || tool.condition()}>+ {tool.buttonComponent ? (+ <tool.buttonComponent />+ ) : (+ <ToolButton tool={tool} />+ )}+ </Show>+ )}+ </For>+ <PreviewButton />+ </SplitToolbarRight></Show><CreateDialog /></>diff --git a/apps/web/src/features/chat/SoupChatInput.tsx b/apps/web/src/features/chat/SoupChatInput.tsxindex 37e30f08e5..95cdd52035 100644--- a/apps/web/src/features/chat/SoupChatInput.tsx+++ b/apps/web/src/features/chat/SoupChatInput.tsx@@ -123,7 +123,6 @@ function SoupChatInputInner() {<divref={containerRef}class="absolute bottom-0 inset-x-px pb-2 px-2 flex justify-center pointer-events-none"- classList={{ hidden: splitPanelContext.previewState[0]() }}style={{'background-image': `linear-gradient(transparent, var(--color-surface) 85%)`,}}diff --git a/apps/web/src/features/entity/extractors-notification/notification-content.tsx b/apps/web/src/features/entity/extractors-notification/notification-content.tsxindex bb21e8048d..9c4a8c5e64 100644--- a/apps/web/src/features/entity/extractors-notification/notification-content.tsx+++ b/apps/web/src/features/entity/extractors-notification/notification-content.tsx@@ -1,5 +1,6 @@import { globalSplitManager } from '@app/signal/splitLayout';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { EntityIcon } from '@core/component/EntityIcon';import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';@@ -26,6 +27,9 @@ export function DocumentMentionPill(props: {notification: UnifiedNotification;}) {const notificationSource = useGlobalNotificationSource();+ // The containing split (when any) is the navigation source, so opens from+ // an engaged preview controller route into its viewer split.+ const panel = useSplitPanel();const { markAsDone } = useNotificationActions({notification: props.notification,});@@ -46,7 +50,13 @@ export function DocumentMentionPill(props: {e.stopPropagation();const splitManager = globalSplitManager();if (!splitManager) return;- await openNotification(props.notification, splitManager, e.shiftKey);+ await openNotification(+ props.notification,+ splitManager,+ e.shiftKey,+ undefined,+ panel?.handle+ );await notificationSource.markAsRead(props.notification);};diff --git a/apps/web/src/features/entity/extractors-notification/notification-row.tsx b/apps/web/src/features/entity/extractors-notification/notification-row.tsxindex 53daf27cd7..e282336a00 100644--- a/apps/web/src/features/entity/extractors-notification/notification-row.tsx+++ b/apps/web/src/features/entity/extractors-notification/notification-row.tsx@@ -1,5 +1,6 @@import { globalSplitManager } from '@app/signal/splitLayout';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';import { toast } from '@core/component/Toast/Toast';import type { NotificationType } from '@core/types';@@ -301,6 +302,9 @@ function ExpandedBody(props: BodyProps) {*/export function NotificationRow(props: NotificationRowProps) {const notificationSource = useGlobalNotificationSource();+ // The containing split (when any) is the navigation source, so opens from+ // an engaged preview controller route into its viewer split.+ const panel = useSplitPanel();const unread = () => isNotificationUnread(props.notification);const canMarkDone = () =>props.showMarkDone !== false &&@@ -325,7 +329,8 @@ export function NotificationRow(props: NotificationRowProps) {props.notification,splitManager,e.shiftKey,- entityOverride+ entityOverride,+ panel?.handle);await notificationSource.markAsRead(props.notification);props.onClick?.(e);diff --git a/apps/web/src/features/entity/extractors-notification/notification-stacks.tsx b/apps/web/src/features/entity/extractors-notification/notification-stacks.tsxindex c31393ce08..080d5d0de0 100644--- a/apps/web/src/features/entity/extractors-notification/notification-stacks.tsx+++ b/apps/web/src/features/entity/extractors-notification/notification-stacks.tsx@@ -1,5 +1,6 @@import { globalSplitManager } from '@app/signal/splitLayout';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';import { toast } from '@core/component/Toast/Toast';import { buildSimpleEntityUrl } from '@core/util/url';@@ -64,6 +65,10 @@ export function NotificationStackRow(props: {entityId: props.entity.id,});+ // The containing split (when any) is the navigation source, so opens from+ // an engaged preview controller route into its viewer split.+ const panel = useSplitPanel();+const handleClick = async (e: PointerEvent | MouseEvent | KeyboardEvent) => {const mostRecent = getMostRecentNotification(props.stack);const splitManager = globalSplitManager();@@ -79,7 +84,8 @@ export function NotificationStackRow(props: {mostRecent,splitManager,e.shiftKey,- entityOverride+ entityOverride,+ panel?.handle);await notificationSource.markAsRead(mostRecent);props.onClick?.(e);diff --git a/apps/web/src/features/next-soup/actions/make-delete-action.ts b/apps/web/src/features/next-soup/actions/make-delete-action.tsindex 50384979fa..0602a552c5 100644--- a/apps/web/src/features/next-soup/actions/make-delete-action.ts+++ b/apps/web/src/features/next-soup/actions/make-delete-action.ts@@ -1,6 +1,5 @@import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';import { globalSplitManager } from '@app/signal/splitLayout';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { globalRemoveFromSplitHistory } from '@components/app/split-layout/layoutUtils';import { toast } from '@core/component/Toast/Toast';import type { EntityData } from '@entity';@@ -47,15 +46,11 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {});};- const previewPanel = useMaybePreviewPanel();-const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {const currentIndex = soup.focus.index();const nextRow =soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);- const inPreview = previewPanel !== undefined;-// Separate email entities from non-email entitiesconst emailEntities = entities.filter((e) => e.type === 'email');const nonEmailEntities = entities.filter((e) => e.type !== 'email');@@ -103,7 +98,7 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {toast.failure('Failed to move to Trash');});- restoreSoupFocus(nextRow?.id, inPreview);+ restoreSoupFocus(nextRow?.id);};if (nonEmailEntities.length > 0) {@@ -134,7 +129,7 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {if (nextRow) {soup.focus.set(nextRow.id);}- restoreSoupFocus(nextRow?.id, inPreview);+ restoreSoupFocus(nextRow?.id);}},onCancel: () => {@@ -142,7 +137,7 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {if (firstEntity) {soup.focus.set(firstEntity.id);}- restoreSoupFocus(firstEntity?.id, inPreview);+ restoreSoupFocus(firstEntity?.id);},});} else if (emailEntities.length > 0) {diff --git a/apps/web/src/features/next-soup/actions/make-hide-company-action.ts b/apps/web/src/features/next-soup/actions/make-hide-company-action.tsindex d62f936866..7536c4d4ef 100644--- a/apps/web/src/features/next-soup/actions/make-hide-company-action.ts+++ b/apps/web/src/features/next-soup/actions/make-hide-company-action.ts@@ -1,4 +1,3 @@-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { toast } from '@core/component/Toast/Toast';import type { EntityData } from '@entity';import type { SoupState } from '../create-soup-state';@@ -16,8 +15,6 @@ export const makeHideCompanyAction = (options: MakeHideCompanyOptions) => {const canExecute = (entity: EntityData): boolean =>entity.type === 'crm_company';- const previewPanel = useMaybePreviewPanel();-const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {const entity = entities[0];if (entity?.type !== 'crm_company') return;@@ -27,8 +24,6 @@ export const makeHideCompanyAction = (options: MakeHideCompanyOptions) => {const currentIndex = soup.focus.index();const nextRow =soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);- const inPreview = previewPanel !== undefined;-const hidden = entity.hidden;soup.selection.clear();@@ -41,7 +36,7 @@ export const makeHideCompanyAction = (options: MakeHideCompanyOptions) => {toast.failure(hidden ? 'Failed to unhide' : 'Failed to hide');}- await restoreSoupFocus(nextRow?.id, inPreview);+ await restoreSoupFocus(nextRow?.id);};return { canExecute, executeWithSoup };diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.test.tsnew file mode 100644index 0000000000..e53d3ff432--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts@@ -0,0 +1,135 @@+import type { SplitHandle } from '@components/app/split-layout/layoutManager';+import type { EntityData } from '@entity';+import type { NotificationSource } from '@notifications';+import { createRoot } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { SoupState } from '../create-soup-state';++const mocks = vi.hoisted(() => ({+ controller: {+ isControllerSplit: vi.fn(() => true),+ },+ mutateAsync: vi.fn(async () => {}),+ openEntityInSplitFromUnifiedList: vi.fn(async () => {}),+}));++vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanel: () => ({ handle: mocks.controller }),+}));++vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: false }),+}));++vi.mock('@core/constant/featureFlags', () => ({+ ENABLE_NEW_INBOX_FLAG: 'new-inbox',+ ENABLE_NEW_INBOX_OVERRIDE: undefined,+}));++vi.mock('@core/component/Toast/Toast', () => ({+ toast: {+ dismiss: vi.fn(),+ failure: vi.fn(),+ success: vi.fn(),+ },+}));++vi.mock('@queries/undo', () => ({+ useUndoableMutation: () => ({+ mutateAsync: mocks.mutateAsync,+ }),+}));++vi.mock('@app/features/next-soup/utils', () => ({+ applyEntitiesDoneOptimistic: vi.fn(),+ executeMarkEntitiesDone: vi.fn(),+ executeMarkEntitiesUndone: vi.fn(),+ openEntityInSplitFromUnifiedList: mocks.openEntityInSplitFromUnifiedList,+ resolveMarkEntitiesDoneVariables: () => ({+ emailIds: [],+ notificationIds: [],+ }),+ restoreSoupFocus: vi.fn(),+}));++import { makeMarkDoneAction } from './make-mark-done-action';++const currentEntity = {+ type: 'email',+ id: 'current',+} as EntityData;+const nextEntity = {+ type: 'email',+ id: 'next',+} as EntityData;++function createSoup() {+ const focusSet = vi.fn();+ const nextRow = { id: 'next-row', original: nextEntity };+ const soup = {+ focus: {+ id: () => 'current-row',+ set: focusSet,+ },+ selection: {+ clear: vi.fn(),+ },+ items: {+ count: () => 2,+ get: vi.fn(),+ },+ navigate: {+ peekOffset: vi.fn(() => ({ index: 1, row: nextRow })),+ },+ collapseEntity: {+ shouldCollapse: () => false,+ callback: vi.fn(),+ },+ } as unknown as SoupState;+ return { soup, focusSet };+}++function createAction() {+ return createRoot((dispose) => ({+ action: makeMarkDoneAction({+ notificationSource: () => ({}) as NotificationSource,+ }),+ dispose,+ }));+}++describe('makeMarkDoneAction', () => {+ beforeEach(() => {+ mocks.controller.isControllerSplit.mockReturnValue(true);+ mocks.mutateAsync.mockClear();+ mocks.openEntityInSplitFromUnifiedList.mockClear();+ });++ it('opens the next focused entity in an engaged Preview Controller', async () => {+ const { soup, focusSet } = createSoup();+ const { action, dispose } = createAction();++ await action.executeWithSoup([currentEntity], soup);++ expect(focusSet).toHaveBeenCalledWith('next-row');+ expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledWith(+ nextEntity,+ {+ splitHandle: mocks.controller as unknown as SplitHandle,+ mergeHistory: true,+ }+ );+ dispose();+ });++ it('does not open the next entity when the split is not a Controller', async () => {+ mocks.controller.isControllerSplit.mockReturnValue(false);+ const { soup } = createSoup();+ const { action, dispose } = createAction();++ await action.executeWithSoup([currentEntity], soup);++ expect(mocks.openEntityInSplitFromUnifiedList).not.toHaveBeenCalled();+ dispose();+ });+});diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.tsindex 48925473a5..6208846699 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.ts@@ -4,11 +4,11 @@ import {executeMarkEntitiesDone,executeMarkEntitiesUndone,type MarkEntitiesDoneContext,+ openEntityInSplitFromUnifiedList,resolveMarkEntitiesDoneVariables,restoreSoupFocus,} from '@app/features/next-soup/utils';import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { toast } from '@core/component/Toast/Toast';import {@@ -96,9 +96,6 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {splitPanel?.handle.referredFrom() === 'inbox');const { notificationSource, hotkeyGroup } = options;- const previewPanel = useMaybePreviewPanel();- const inPreview = previewPanel !== undefined;-const mutation = useUndoableMutation<void,Error,@@ -180,7 +177,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {onUndone: () => {if (toastId !== undefined) toast.dismiss(toastId);variables.restoreFocus?.();- restoreSoupFocus(firstEntityId, inPreview);+ restoreSoupFocus(firstEntityId);variables.navigateBack?.();},onRedone: showToast,@@ -294,6 +291,13 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {if (nextRow) {soup.focus.set(nextRow.id);+ const controller = splitPanel?.handle;+ if (controller?.isControllerSplit()) {+ void openEntityInSplitFromUnifiedList(nextRow.original, {+ splitHandle: controller,+ mergeHistory: true,+ });+ }onNavigate?.(nextRow.original);}diff --git a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts b/apps/web/src/features/next-soup/actions/make-move-to-project-action.tsindex 9ac592ba21..55354b4b18 100644--- a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts+++ b/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts@@ -1,5 +1,4 @@import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { toast } from '@core/component/Toast/Toast';import type { EntityData } from '@entity';import type { SoupState } from '../create-soup-state';@@ -29,15 +28,11 @@ export const makeMoveToProjectAction = () => {});};- const previewPanel = useMaybePreviewPanel();-const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {const currentIndex = soup.focus.index();const nextRow =soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);- const inPreview = previewPanel !== undefined;-openBulkEditModal({view: 'moveToProject',entities,@@ -51,14 +46,14 @@ export const makeMoveToProjectAction = () => {? `Moved ${entities.length} items`: 'Moved to folder');- restoreSoupFocus(nextRow?.id, inPreview);+ restoreSoupFocus(nextRow?.id);},onCancel: () => {const firstEntity = entities[0];if (firstEntity) {soup.focus.set(firstEntity.id);}- restoreSoupFocus(firstEntity?.id, inPreview);+ restoreSoupFocus(firstEntity?.id);},});};diff --git a/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts b/apps/web/src/features/next-soup/actions/make-remove-from-project-action.tsindex 44900098a3..078549975c 100644--- a/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts+++ b/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts@@ -1,4 +1,3 @@-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { toast } from '@core/component/Toast/Toast';import type { EntityData } from '@entity';import { createBulkRemoveFromProjectDssEntityMutation } from '@entity';@@ -29,15 +28,11 @@ export const makeRemoveFromProjectAction = () => {return true;};- const previewPanel = useMaybePreviewPanel();-const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {// Entities leave the viewed folder's list; move focus to a neighborconst currentIndex = soup.focus.index();const nextRow =soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);- const inPreview = previewPanel !== undefined;-const success = await execute(entities);// Rolled back on failure; keep selection and focus for a retryif (!success) return;@@ -46,7 +41,7 @@ export const makeRemoveFromProjectAction = () => {if (nextRow) {soup.focus.set(nextRow.id);}- restoreSoupFocus(nextRow?.id, inPreview);+ restoreSoupFocus(nextRow?.id);};return { canExecute, execute, executeWithSoup };diff --git a/apps/web/src/features/next-soup/actions/make-rename-action.ts b/apps/web/src/features/next-soup/actions/make-rename-action.tsindex 9c57a05bbd..f248842317 100644--- a/apps/web/src/features/next-soup/actions/make-rename-action.ts+++ b/apps/web/src/features/next-soup/actions/make-rename-action.ts@@ -1,5 +1,4 @@import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { toast } from '@core/component/Toast/Toast';import type { EntityData } from '@entity';import type { SoupState } from '../create-soup-state';@@ -39,13 +38,9 @@ export const makeRenameAction = (options: MakeRenameOptions) => {});};- const previewPanel = useMaybePreviewPanel();-const executeWithSoup = async (entities: EntityData[], soup: SoupState) => {const firstEntity = entities[0];- const inPreview = previewPanel !== undefined;-openBulkEditModal({view: 'rename',entities,@@ -56,13 +51,13 @@ export const makeRenameAction = (options: MakeRenameOptions) => {if (firstEntity) {soup.focus.set(firstEntity.id);}- restoreSoupFocus(firstEntity?.id, inPreview);+ restoreSoupFocus(firstEntity?.id);},onCancel: () => {if (firstEntity) {soup.focus.set(firstEntity.id);}- restoreSoupFocus(firstEntity?.id, inPreview);+ restoreSoupFocus(firstEntity?.id);},});};diff --git a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts b/apps/web/src/features/next-soup/actions/use-block-entity-commands.tsindex cc3b8206e2..02bd4387bc 100644--- a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts+++ b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts@@ -3,7 +3,6 @@ import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils'import { useAllProperties } from '@app/features/property/editor/hooks/useAllProperties';import { openPropertyEditor } from '@app/features/property/editor/state/propertyEditor';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';-import { useMaybePreviewPanel } from '@components/app/PreviewPanel';import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { useBlockId } from '@core/block';import { useQuickAccess } from '@core/context/quickAccess';@@ -42,7 +41,6 @@ export const useBlockEntityCommands = () => {const notificationSource = useGlobalNotificationSource();const soup = useMaybeSoup();const splitPanel = useSplitPanel();- const previewPanel = useMaybePreviewPanel();const markDone = makeMarkDoneAction({userId: () => userId(),@@ -91,12 +89,10 @@ export const useBlockEntityCommands = () => {}};- // The 'e' hotkey from inside a block is reserved for entities opened full- // screen from the inbox/mail lists, mirroring the j/k gating in- // use-soup-navigation-hotkeys. Blocks rendered in the preview panel fall- // through to the originating list's own 'e' registration.+ // The 'e' hotkey from inside a block is reserved for entities opened from+ // the inbox/mail lists, mirroring the j/k gating in+ // use-soup-navigation-hotkeys.const canUseMarkDoneHotkey = () => {- if (previewPanel) return false;const referredFrom = splitPanel?.handle.referredFrom();return referredFrom === 'inbox' || referredFrom === 'mail';};diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.tsindex 3543ddd825..3b7c7268f9 100644--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts@@ -113,6 +113,9 @@ export const useEntityActionHotkeys = (const openNextEntity = (entity: EntityData) => {if (!splitHandle) return;+ // Preview Controllers are synchronized centrally by executeWithSoup so+ // every mark-done entry point, including menus and swipe, behaves alike.+ if (splitHandle.isControllerSplit()) return;const handleContent = splitHandle.content().type;if (handleContent === 'component' || handleContent === 'project') return;openEntityInSplitFromUnifiedList(entity, {diff --git a/apps/web/src/features/next-soup/create-soup-state.test.ts b/apps/web/src/features/next-soup/create-soup-state.test.tsindex de45794f74..3fc91b1c23 100644--- a/apps/web/src/features/next-soup/create-soup-state.test.ts+++ b/apps/web/src/features/next-soup/create-soup-state.test.ts@@ -227,6 +227,27 @@ describe('createSoupState', () => {});});+ it('should skip rows rejected by the navigation predicate', () => {+ createRoot((dispose) => {+ const entities = [+ createTestEntity('1'),+ createTestEntity('2'),+ createTestEntity('3'),+ ];+ const state = createSoupState({ initialData: entities });+ state.focus.set('1');++ const result = state.navigate.down({+ skip: (row) => row.id === '2',+ });++ expect(result?.row.original).toBe(entities[2]);+ expect(state.focus.id()).toBe('3');++ dispose();+ });+ });+it('should navigate to first', () => {createRoot((dispose) => {const entities = [createTestEntity('1'), createTestEntity('2')];@@ -382,24 +403,6 @@ describe('createSoupState', () => {});});- describe('previewEntity', () => {- it('should manage preview entity state', () => {- createRoot((dispose) => {- const state = createSoupState();-- expect(state.previewEntity()).toBeUndefined();-- state.setPreviewEntity('entity-1');- expect(state.previewEntity()).toBe('entity-1');-- state.setPreviewEntity(undefined);- expect(state.previewEntity()).toBeUndefined();-- dispose();- });- });- });-describe('selection', () => {it('should expose selection state', () => {createRoot((dispose) => {diff --git a/apps/web/src/features/next-soup/create-soup-state.ts b/apps/web/src/features/next-soup/create-soup-state.tsindex bec7e6d9b6..b11319bdad 100644--- a/apps/web/src/features/next-soup/create-soup-state.ts+++ b/apps/web/src/features/next-soup/create-soup-state.ts@@ -59,6 +59,7 @@ type NavigationOptions = {wrapNavigation?: boolean;skipGroupHeaders?: boolean;skipLoadMore?: boolean;+ skip?: (row: SoupRow) => boolean;};export type SortConfig<T> = {@@ -166,8 +167,6 @@ export const createSoupState = <TId extends string = FilterID>(if (nextIndex < 0) lastFocusedRowId = undefined;};- const [previewEntity, setPreviewEntity] = createSignal<string | undefined>();-const [collapseEntityCallback, setCollapseEntityCallback] = createSignal<((entityId: string) => Promise<void>) | undefined>(undefined);@@ -223,6 +222,7 @@ export const createSoupState = <TId extends string = FilterID>(row: SoupRow,options?: NavigationOptions): boolean => {+ if (options?.skip?.(row)) return true;if (row.getIsLoadMore() && options?.skipLoadMore) return true;if (!row.group) return false;if (row.getIsGrouped()) {@@ -299,8 +299,11 @@ export const createSoupState = <TId extends string = FilterID>(return calculateFocusRow(nextIndex);};- const navigateBy = (offset: number): NavigationResult => {- const peeked = peek(offset);+ const navigateBy = (+ offset: number,+ options?: NavigationOptions+ ): NavigationResult => {+ const peeked = peek(offset, options);if (!peeked) return;return setFocus(peeked.index);@@ -353,8 +356,8 @@ export const createSoupState = <TId extends string = FilterID>(},navigate: {- down: () => navigateBy(1),- up: () => navigateBy(-1),+ down: (options?: NavigationOptions) => navigateBy(1, options),+ up: (options?: NavigationOptions) => navigateBy(-1, options),by: navigateBy,toIndex: setFocus,toId: (id: string) => {@@ -375,9 +378,6 @@ export const createSoupState = <TId extends string = FilterID>(indexOf,},- previewEntity,- setPreviewEntity,-collapseEntity: {callback: collapseEntityCallback,set: setCollapseEntityCallback,diff --git a/apps/web/src/features/next-soup/preview-history.ts b/apps/web/src/features/next-soup/preview-history.tsnew file mode 100644index 0000000000..a7b10dc1e6--- /dev/null+++ b/apps/web/src/features/next-soup/preview-history.ts@@ -0,0 +1,25 @@+import type { SplitContent } from '@components/app/split-layout/layoutManager';++const PREVIEW_SOURCE_ENTITY_ID_STATE_KEY = 'soup.previewSourceEntityId';++/** Stamp the controller row identity onto a preview viewer history entry. */+export function withPreviewSourceEntityId(+ content: SplitContent,+ entityId: string+): SplitContent {+ return {+ ...content,+ state: {+ ...content.state,+ [PREVIEW_SOURCE_ENTITY_ID_STATE_KEY]: entityId,+ },+ };+}++/** The controller row that created this preview viewer history entry. */+export function previewSourceEntityId(+ content: SplitContent+): string | undefined {+ const value = content.state?.[PREVIEW_SOURCE_ENTITY_ID_STATE_KEY];+ return typeof value === 'string' ? value : undefined;+}diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsxindex 9bebcdb09b..cc98488ae8 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx@@ -4,10 +4,8 @@ import { SoupViewContextGroup } from '@app/features/next-soup/soup-view/filters-import { SoupViewContextSort } from '@app/features/next-soup/soup-view/filters-bar/soup-view-context-sort';import { UnifiedFilterDropdown } from '@app/features/next-soup/soup-view/filters-bar/unified-filter-dropdown';import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import { usePreviewPaneVisiblity } from '@app/features/next-soup/soup-view/use-preview-pane-visibility';-import { useAnalytics } from '@app/lib/analytics/analytics-context';import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { PreviewButton } from '@components/app/split-layout/components/PreviewButton';import {SplitToolbarLeft,SplitToolbarRight,@@ -17,51 +15,20 @@ import {ENABLE_NEW_INBOX_FLAG,ENABLE_NEW_INBOX_OVERRIDE,} from '@core/constant/featureFlags';-import { registerHotkey } from '@core/hotkey/hotkeys';-import { TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';-import EyeIcon from '@phosphor-icons/core/regular/eye.svg?component-solid';-import EyeSlashIcon from '@phosphor-icons/core/regular/eye-slash.svg?component-solid';-import { Button, Tooltip } from '@ui';import { createMemo, createSignal, Show } from 'solid-js';-import { useSoup } from '../../soup-context';-export function SoupFiltersBar(props: { variant?: 'default' | 'tag' } = {}) {+export function SoupFiltersBar(props: {+ variant?: 'default' | 'tag';+ hasPreviewItems: boolean;+ onPreviewEngage: () => void;+}) {const { resetToTabDefaults, consolidatedFiltersList } =useFilterRefinements();const [filterDropdownOpen, setFilterDropdownOpen] = createSignal(false);const panel = useSplitPanelOrThrow();- const analytics = useAnalytics();- const soup = useSoup();- const { setPreviewOpen } = useSoupView();-- const { isWideSplitPanel, previewOpen, selectedEntity } =- usePreviewPaneVisiblity();-- const togglePreview = () => {- if (previewOpen()) {- setPreviewOpen(false);- soup.setPreviewEntity(undefined);- return;- }-- analytics.track('preview_panel_use');- soup.setPreviewEntity(selectedEntity()?.id);- setPreviewOpen(true);- };-- registerHotkey({- hotkeyToken: TOKENS.unifiedList.togglePreview,- scopeId: panel.splitHotkeyScope,- description: 'Toggle preview',- keyDownHandler: () => {- togglePreview();- return true;- },- hotkey: 'space',- });const isSearchView = createMemo(() => {const content = panel.handle.content();@@ -109,24 +76,11 @@ export function SoupFiltersBar(props: { variant?: 'default' | 'tag' } = {}) {</div></SplitToolbarLeft><SplitToolbarRight>- <Tooltip- hotkey={- isWideSplitPanel() ? TOKENS.unifiedList.togglePreview : undefined- }- label={isWideSplitPanel() ? 'Preview' : 'No space for preview'}- >- <Button- onClick={togglePreview}- variant="base"- size="sm"- depth={2}- class="bg-surface"- disabled={!isWideSplitPanel()}- >- {previewOpen() ? <EyeSlashIcon /> : <EyeIcon />}- <span>Preview</span>- </Button>- </Tooltip>+ <PreviewButton+ disabled={!props.hasPreviewItems}+ disabledLabel="No items to preview"+ onEngage={props.onPreviewEngage}+ /></SplitToolbarRight>{/* Active filters bar - shown below the toolbar when there are filters */}<Show when={!isSearchView() && !isTagView()}>diff --git a/apps/web/src/features/next-soup/soup-view/non-member-channel-preview.tsx b/apps/web/src/features/next-soup/soup-view/non-member-channel-preview.tsxindex a2cee04056..300da8999b 100644--- a/apps/web/src/features/next-soup/soup-view/non-member-channel-preview.tsx+++ b/apps/web/src/features/next-soup/soup-view/non-member-channel-preview.tsx@@ -1,5 +1,4 @@import EmptyStateChannelsGraphic from '@design/empty-state-channels.svg';-import type { ChannelEntity } from '@entity';import { useJoinChannelMutation } from '@queries/channel/join-links';import { EmptyStatePanel } from '@ui';@@ -7,14 +6,24 @@ import { EmptyStatePanel } from '@ui';* Preview-pane state for a focused channel the viewer is not a participant of* (a team channel of their team they haven't joined). The channel can't be* read yet, so instead of mounting the channel block the pane offers the join- * action; once the join lands the soup refetch flips `isParticipant` and the- * real preview takes over.+ * action; once the join lands `onJoined` hands the Viewer off to the real+ * channel block (and the soup refetch flips the row's `isParticipant`).+ *+ * Takes plain display fields rather than the entity so it can render as a+ * Preview Pair Viewer component (opened from the controlling list).*/-export function NonMemberChannelPreview(props: { entity: ChannelEntity }) {- const joinMutation = useJoinChannelMutation();+export function NonMemberChannelPreview(props: {+ channelId: string;+ channelName: string;+ memberCount: number;+ onJoined?: () => void;+}) {+ const joinMutation = useJoinChannelMutation({+ onSuccess: () => props.onJoined?.(),+ });const description = () => {- const count = props.entity.participantIds?.length ?? 0;+ const count = props.memberCount;const members =count > 0 ? ` (${count} ${count === 1 ? 'member' : 'members'})` : '';return `You're not in this channel yet${members}. Join it to read and send messages.`;@@ -23,13 +32,13 @@ export function NonMemberChannelPreview(props: { entity: ChannelEntity }) {return (<EmptyStatePanelgraphic={EmptyStateChannelsGraphic}- title={props.entity.name}+ title={props.channelName}description={description()}primaryAction={{label: joinMutation.isPending ? 'Joining…' : 'Join channel',onClick: () => {if (joinMutation.isPending) return;- joinMutation.mutate({ channelId: props.entity.id });+ joinMutation.mutate({ channelId: props.channelId });},}}centereddiff --git a/apps/web/src/features/next-soup/soup-view/preview-content-row.test.ts b/apps/web/src/features/next-soup/soup-view/preview-content-row.test.tsnew file mode 100644index 0000000000..013cfc4023--- /dev/null+++ b/apps/web/src/features/next-soup/soup-view/preview-content-row.test.ts@@ -0,0 +1,82 @@+import type { SplitContent } from '@components/app/split-layout/layoutManager';+import type { EntityData } from '@entity';+import { describe, expect, it } from 'vitest';+import { withPreviewSourceEntityId } from '../preview-history';+import { previewContentMatchesEntity } from './preview-content-row';++const channelMessage = (messageId: string): EntityData =>+ ({+ type: 'channel_message',+ id: `channel-1:${messageId}`,+ channelId: 'channel-1',+ messageId,+ }) as EntityData;++const channelThread = (threadId: string): EntityData =>+ ({+ type: 'channel_thread',+ id: threadId,+ channelId: 'channel-1',+ messageId: threadId,+ threadId,+ }) as EntityData;++describe('previewContentMatchesEntity', () => {+ it('prefers the stamped source row after history removes channel params', () => {+ const channel = { type: 'channel', id: 'channel-1' } as EntityData;+ const origin = channelThread('thread-2');+ const content = withPreviewSourceEntityId(+ { type: 'channel', id: 'channel-1' },+ origin.id+ );++ expect(+ [channel, origin].find((entity) =>+ previewContentMatchesEntity(content, entity)+ )+ ).toBe(origin);+ });++ it('retains direct entity id matching', () => {+ const entity = { id: 'document-1' } as EntityData;++ expect(+ previewContentMatchesEntity({ type: 'md', id: 'document-1' }, entity)+ ).toBe(true);+ });++ it('uses the message param to disambiguate rows from the same channel', () => {+ const other = channelMessage('message-1');+ const origin = channelMessage('message-2');+ const content: SplitContent = {+ type: 'channel',+ id: 'channel-1',+ params: { channel_message_id: 'message-2' },+ };++ expect(+ [other, origin].find((entity) =>+ previewContentMatchesEntity(content, entity)+ )+ ).toBe(origin);+ });++ it('uses the thread param to resolve the originating notification row', () => {+ const other = channelThread('thread-1');+ const origin = channelThread('thread-2');+ const content: SplitContent = {+ type: 'channel',+ id: 'channel-1',+ params: {+ channel_message_id: 'reply-2',+ channel_thread_id: 'thread-2',+ },+ };++ expect(+ [other, origin].find((entity) =>+ previewContentMatchesEntity(content, entity)+ )+ ).toBe(origin);+ });+});diff --git a/apps/web/src/features/next-soup/soup-view/preview-content-row.ts b/apps/web/src/features/next-soup/soup-view/preview-content-row.tsnew file mode 100644index 0000000000..1241a40110--- /dev/null+++ b/apps/web/src/features/next-soup/soup-view/preview-content-row.ts@@ -0,0 +1,34 @@+import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';+import type { SplitContent } from '@components/app/split-layout/layoutManager';+import type { EntityData } from '@entity';+import { previewSourceEntityId } from '../preview-history';++export function previewContentMatchesEntity(+ content: SplitContent,+ entity: EntityData+) {+ const sourceEntityId = previewSourceEntityId(content);+ if (sourceEntityId !== undefined) return entity.id === sourceEntityId;++ if (entity.id === content.id) return true;+ if (content.type !== 'channel') return false;+ const params = content.params as+ | Record<string, string | undefined>+ | undefined;++ if (entity.type === 'channel_message') {+ return (+ entity.channelId === content.id &&+ entity.messageId === params?.[CHANNEL_PARAMS.message]+ );+ }++ if (entity.type === 'channel_thread') {+ return (+ entity.channelId === content.id &&+ entity.threadId === params?.[CHANNEL_PARAMS.thread]+ );+ }++ return false;+}diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex b009e2748f..4dc6197b0d 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -139,8 +139,6 @@ interface SoupViewContextValues {featuredIds: Accessor<string[]>;items: Accessor<SoupEntity[]>;rows: Accessor<SoupRow[]>;- previewOpen: Accessor<boolean>;- setPreviewOpen: Setter<boolean>;isSearchServiceLoading: Accessor<boolean>;isLocalSearchSettling: Accessor<boolean>;queryFilters: QueryStore;@@ -213,7 +211,6 @@ export const SoupViewContextProvider: FlowComponent<SoupViewContextProviderProps> = (props) => {const soup = props.soup ?? createSoupState();- const [previewOpen, setPreviewOpen] = createSignal(false);const [enabled, setEnabled] = createSignal(props.initialEnabled ?? false);const [config, setConfig] = createSignal<SoupViewInitializeOptions>({initialQuery: props.initialQuery,@@ -1169,8 +1166,6 @@ export const SoupViewContextProvider: FlowComponent<},items,rows,- previewOpen,- setPreviewOpen,searchText: search.searchText,setSearchText: search.setSearchText,searchPaused: sourceSearchPaused,diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsxindex 58818c468d..21f0297b54 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx@@ -21,7 +21,6 @@ import { InboxSelector } from '@app/features/next-soup/soup-view/filters-bar/inbimport { SoupFiltersBar } from '@app/features/next-soup/soup-view/filters-bar/soup-filters-bar';import { SoupSearchbar } from '@app/features/next-soup/soup-view/filters-bar/soup-view-search-bar';import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';-import { NonMemberChannelPreview } from '@app/features/next-soup/soup-view/non-member-channel-preview';import { MaybeSoupEntityActionDrawerManager } from '@app/features/next-soup/soup-view/SoupEntityActionDrawerManager';import { SoupSectionHeader } from '@app/features/next-soup/soup-view/section-header';import { SoupEntityContextMenu } from '@app/features/next-soup/soup-view/soup-entity-context-menu';@@ -39,10 +38,7 @@ import {SoupViewTabs,useApplyPreset,} from '@app/features/next-soup/soup-view/soup-view-tabs';-import {- useIsNewInboxEnabled,- usePreviewPaneVisiblity,-} from '@app/features/next-soup/soup-view/use-preview-pane-visibility';+import { useIsNewInboxEnabled } from '@app/features/next-soup/soup-view/use-is-new-inbox-enabled';import { CompanyKanban } from '@app/features/next-soup/soup-view/views/companies/CompanyKanban';import { CompanyListEntity } from '@app/features/next-soup/soup-view/views/companies/CompanyListEntity';import { ResponsiveCompanyListHeader } from '@app/features/next-soup/soup-view/views/companies/CompanyListHeader';@@ -57,9 +53,9 @@ import { TaskListEntity } from '@app/features/next-soup/soup-view/views/tasks/Taimport { ResponsiveTaskListHeader } from '@app/features/next-soup/soup-view/views/tasks/TaskListHeader';import { TaskGroupHeader } from '@app/features/next-soup/soup-view/views/tasks/task-group-header';import {- navigateChannelEntityToTarget,openEntityInNewTab,openEntityInSplitFromUnifiedList,+ preventDuplicatePreviewEntityOpen,} from '@app/features/next-soup/utils';import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';import { usePreference } from '@app/preferences/use-preference';@@ -67,28 +63,19 @@ import { useDealStages } from '@companies/crm/deal-stages';import { CrmStageIcon } from '@companies/crm/StageIcon';import type { CrmViewConfig } from '@companies/crm/saved-views';import { useCrmUnavailable } from '@companies/crm/team-crm-config';-import {- useGlobalBlockOrchestrator,- useGlobalNotificationSource,-} from '@components/app/GlobalAppState';+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { FloatRegion } from '@components/app/mobile/float-regions/FloatRegion';import { PullToRefresh } from '@components/app/mobile/PullToRefresh';import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';-import {- PreviewPanel,- useMaybePreviewPanel,-} from '@components/app/PreviewPanel';import { CollapsibleHeaderItem } from '@components/app/split-layout/components/CollapsibleHeaderItem';import {SplitHeaderLeft,SplitHeaderRight,} from '@components/app/split-layout/components/SplitHeader';-import { SplitPanelContext } from '@components/app/split-layout/context';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { LoadingBlock } from '@core/component/LoadingBlock';-import { Resize } from '@core/component/Resize';import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import {@@ -100,7 +87,6 @@ import { TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';import { openExternalUrl } from '@core/util/url';import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';-import EmptyStatePreviewIcon from '@design/empty-state-doc.svg';import {type EntityData,isNonMemberChannelEntity,@@ -125,7 +111,7 @@ import {} from '@queries/soup/normalized-cache';import { createElementSize } from '@solid-primitives/resize-observer';import { debounce } from '@solid-primitives/scheduled';-import { Button, cn, EmptyStatePanel, Layer, Tooltip } from '@ui';+import { Button, cn, Layer, Tooltip } from '@ui';import {type Accessor,batch,@@ -147,6 +133,7 @@ import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';import type { CacheSnapshot } from 'virtua/unstable_core';import { SoupEntitySelectionToolbar } from './soup-entity-selection-toolbar';import { useSoupNavigationHotkeys } from './use-soup-navigation-hotkeys';+import { useSoupPreviewAvailability } from './use-soup-preview-availability';import { useSoupViewHotkeys } from './use-soup-view-hotkeys';export const DefaultGroupHeader = (@@ -306,9 +293,6 @@ const useSoupNotificationInvalidators = () => {};const SOUP_LIST_STATE_ENTRY_KEY = 'soup.listState';-const SOUP_PREVIEW_ENTITY_ENTRY_KEY = 'soup.preview';-const SOUP_PREVIEW_OPEN_ENTRY_KEY = 'soup.previewOpen';-type SoupListEntryState = {focus: string | undefined;virtualCache?: CacheSnapshot;@@ -349,17 +333,28 @@ export const SoupView = (props: SoupViewProps) => {const panel = useSplitPanelOrThrow();const soupView = useSoupView();const isNewInboxEnabled = useIsNewInboxEnabled();+ const hasPreviewItems = useSoupPreviewAvailability({+ rows: soupView.rows,+ isLoading: soupView.source.isLoading,+ splitHandle: panel.handle,+ });+ const openFocusedEntityInPreview = () => {+ const focusedRow = soup.focus.row();+ if (+ !focusedRow ||+ focusedRow.getIsGrouped() ||+ focusedRow.getIsLoadMore()+ ) {+ return;+ }+ void openEntityInSplitFromUnifiedList(focusedRow.original, {+ splitHandle: panel.handle,+ });+ };const entryState = panel.handle.currentEntryState();const contentId = panel.handle.content().id;- const persistedPreviewEntity = entryState?.[SOUP_PREVIEW_ENTITY_ENTRY_KEY] as- | string- | undefined;- const persistedPreviewOpen = entryState?.[SOUP_PREVIEW_OPEN_ENTRY_KEY] as- | boolean- | undefined;-const persistedFilters = entryState?.['search.filters'] as Query | undefined;const persistedPredicates = entryState?.['search.predicates'] as@@ -412,14 +407,6 @@ export const SoupView = (props: SoupViewProps) => {if (init) return;init = true;batch(() => {- soup.setPreviewEntity(persistedPreviewEntity);- // Existing entries only stored the symbolic entity id. Treat one as an- // open pane. The new-inbox default is applied reactively below because- // its PostHog flag can resolve after this one-time initialization.- soupView.setPreviewOpen(- persistedPreviewOpen ?? persistedPreviewEntity !== undefined- );-soupView.initialize({initialQuery: initialCrmView? (initialCrmView.filters as Query | undefined)@@ -480,30 +467,20 @@ export const SoupView = (props: SoupViewProps) => {});});- // Production resolves the new-inbox flag asynchronously, so wait for it- // before applying the default instead of locking in the initial false value.- if (- persistedPreviewOpen === undefined &&- persistedPreviewEntity === undefined- ) {- let previewDefaulted = false;- createRenderEffect(() => {- if (previewDefaulted || !isNewInboxEnabled()) return;- previewDefaulted = true;- soupView.setPreviewOpen(true);- });- }-- const previewEntityCaptorTeardown = panel.handle.registerEntryStateCaptor(- SOUP_PREVIEW_ENTITY_ENTRY_KEY,- () => soup.previewEntity()- );- const previewOpenCaptorTeardown = panel.handle.registerEntryStateCaptor(- SOUP_PREVIEW_OPEN_ENTRY_KEY,- () => soupView.previewOpen()- );- onCleanup(previewEntityCaptorTeardown);- onCleanup(previewOpenCaptorTeardown);+ // A fresh Inbox starts in preview mode once its initial result settles, but+ // only when it has an entity to show. Resolve this once so manually exiting+ // preview mode is not undone by later Soup updates.+ let initialInboxPreviewResolved = false;+ createEffect(() => {+ if (initialInboxPreviewResolved || soupView.source.isLoading()) return;+ initialInboxPreviewResolved = true;+ if (contentId !== 'inbox') return;+ if (panel.handle.lastNavigationCause() !== 'fresh') return;+ if (panel.handle.isViewerSplit()) return;+ if (!hasPreviewItems()) return;+ panel.handle.engagePreview();+ if (panel.handle.isControllerSplit()) openFocusedEntityInPreview();+ });onMount(() => {if (contentId !== 'documents') return;@@ -603,179 +580,157 @@ export const SoupView = (props: SoupViewProps) => {},});- const { paneVisible, previewVisible } = usePreviewPaneVisiblity();-- createEffect(() => {- const visible = paneVisible();- const [getPreview, setPreview] = panel.previewState;- if (visible !== getPreview()) setPreview(visible);- });- onCleanup(() => panel.previewState[1](false));-return (- <SplitPanelContext.Provider- value={{- ...panel,- halfSplitState: () =>- previewVisible() ? { side: 'left', percentage: 30 } : undefined,- }}- >- <div class="size-full flex flex-col" data-list-view={activeListView()}>- <div- class={cn('flex flex-col w-full', {- // In preview the separating border sits below this region, so it- // ends up under the active-filters bar when shown, otherwise right- // under the toolbar (the wrapper collapses to zero height).- 'border-b border-edge-muted': !isMobile() && paneVisible(),- })}- >- <SplitHeaderLeft>- <div- class={cn('h-full flex gap-3 items-center', {- 'shrink-0': !narrowSearchExpanded(),- 'flex-1 min-w-0': narrowSearchExpanded(),- })}+ <div class="size-full flex flex-col" data-list-view={activeListView()}>+ <div class="flex flex-col w-full">+ <SplitHeaderLeft>+ <div+ class={cn('h-full flex gap-3 items-center', {+ 'shrink-0': !narrowSearchExpanded(),+ 'flex-1 min-w-0': narrowSearchExpanded(),+ })}+ >+ <Show when={!isMobile() && !narrowSearchExpanded()}>+ <div class="flex items-center gap-1">+ <span class="text-sm font-semibold">{props.viewName}</span>+ <Show when={docsUrl()}>+ {(url) => (+ <Button+ variant="ghost"+ class="p-0.5 rounded-sm text-ink-extra-muted hover:text-ink-muted"+ label="View documentation"+ onClick={() => openExternalUrl(url())}+ >+ <InfoIcon class="size-3.5" />+ </Button>+ )}+ </Show>+ </div>+ </Show>+ <Show+ when={!narrowSearchExpanded() && !isComponentListView('search')}>- <Show when={!isMobile() && !narrowSearchExpanded()}>- <div class="flex items-center gap-1">- <span class="text-sm font-semibold">{props.viewName}</span>- <Show when={docsUrl()}>- {(url) => (- <Button- variant="ghost"- class="p-0.5 rounded-sm text-ink-extra-muted hover:text-ink-muted"- label="View documentation"- onClick={() => openExternalUrl(url())}- >- <InfoIcon class="size-3.5" />- </Button>- )}- </Show>- </div>+ <Show when={!isMobile()}>+ <CollapsibleHeaderItem+ id="tabs"+ priority={1}+ expanded={() => props.customTabs ?? <SoupViewTabs />}+ collapsed={() =>+ props.customTabs ?? <CollapsedSoupViewTabs />+ }+ containerClass="h-full"+ /></Show>- <Show- when={!narrowSearchExpanded() && !isComponentListView('search')}- >- <Show when={!isMobile()}>- <CollapsibleHeaderItem- id="tabs"- priority={1}- expanded={() => props.customTabs ?? <SoupViewTabs />}- collapsed={() =>- props.customTabs ?? <CollapsedSoupViewTabs />- }- containerClass="h-full"+ </Show>+ <Show+ when={+ !isMobile() &&+ !narrowSearchExpanded() &&+ isComponentListView('mail')+ }+ >+ <InboxSelector />+ </Show>+ </div>+ </SplitHeaderLeft>+ <Show when={!isMobile()}>+ <SplitHeaderRight>+ <Show+ when={!narrowSearchExpanded() && isComponentListView('companies')}+ >+ <CompanyViewsMenu />+ <CompanyDisplayMenu />+ </Show>+ <Show+ when={+ !narrowSearchExpanded() &&+ !isComponentListView('search') &&+ props.showCreateButton !== false+ }+ >+ <SoupViewCreateButton />+ </Show>+ <Show when={narrowSearchExpanded()}>+ <Layer depth={2}>+ <div class="flex-1 min-w-0">+ <SoupSearchbar+ variant="secondary"+ autoFocus+ initialValue={props.initialSearchText}+ onDismiss={() => setNarrowSearchExpanded(false)}/>- </Show>- </Show>- <Show- when={- !isMobile() &&- !narrowSearchExpanded() &&- isComponentListView('mail')- }- >- <InboxSelector />- </Show>- </div>- </SplitHeaderLeft>- <Show when={!isMobile()}>- <SplitHeaderRight>- <Show- when={- !narrowSearchExpanded() &&- !isComponentListView('search') &&- props.showCreateButton !== false- }- >- <SoupViewCreateButton />- </Show>- <Show- when={- !narrowSearchExpanded() && isComponentListView('companies')- }- >- <CompanyViewsMenu />- <CompanyDisplayMenu />- </Show>- <Show when={narrowSearchExpanded()}>+ </div>+ </Layer>+ </Show>+ <Show+ when={!isComponentListView('search')}+ fallback={<Layer depth={2}>- <div class="flex-1 min-w-0">+ <div class="grow ml-2 min-w-0 [contain:inline-size]"><SoupSearchbarvariant="secondary"- autoFocus+ placeholder="Search, @mention contacts"initialValue={props.initialSearchText}- onDismiss={() => setNarrowSearchExpanded(false)}/></div></Layer>+ }+ >+ <Show when={!narrowSearchExpanded()}>+ <CollapsibleHeaderItem+ id="search"+ priority={0}+ onCollapsedChange={(isCollapsed) => {+ setSearchIsCollapsed(isCollapsed);+ if (!isCollapsed) setNarrowSearchExpanded(false);+ }}+ expanded={() => (+ <Layer depth={2}>+ <div class="w-60 ml-2">+ <SoupSearchbar+ variant="secondary"+ initialValue={props.initialSearchText}+ />+ </div>+ </Layer>+ )}+ collapsed={() => (+ <Tooltip label="Search" hotkey={TOKENS.soup.openSearch}>+ <Button+ variant="base"+ class="p-1 size-7 rounded-lg ml-2 bg-surface"+ onClick={() => setNarrowSearchExpanded(true)}+ depth={2}+ >+ <SearchIcon class="size-4 touch:size-6" />+ </Button>+ </Tooltip>+ )}+ /></Show>- <Show- when={!isComponentListView('search')}- fallback={- <Layer depth={2}>- <div class="grow ml-2 min-w-0 [contain:inline-size]">- <SoupSearchbar- variant="secondary"- placeholder="Search, @mention contacts"- initialValue={props.initialSearchText}- />- </div>- </Layer>- }- >- <Show when={!narrowSearchExpanded()}>- <CollapsibleHeaderItem- id="search"- priority={0}- onCollapsedChange={(isCollapsed) => {- setSearchIsCollapsed(isCollapsed);- if (!isCollapsed) setNarrowSearchExpanded(false);- }}- expanded={() => (- <Layer depth={2}>- <div class="w-60 ml-2">- <SoupSearchbar- variant="secondary"- initialValue={props.initialSearchText}- />- </div>- </Layer>- )}- collapsed={() => (- <Tooltip label="Search" hotkey={TOKENS.soup.openSearch}>- <Button- variant="base"- class="p-1 size-7 rounded-lg ml-2 bg-surface"- onClick={() => setNarrowSearchExpanded(true)}- depth={2}- >- <SearchIcon class="size-4 touch:size-6" />- </Button>- </Tooltip>- )}- />- </Show>- </Show>- </SplitHeaderRight>- </Show>- </div>- <SoupFiltersBar variant={props.filterBarVariant} />- <Show when={applyDefaultCrmView}>- <CrmDefaultViewLoader />- </Show>- <div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full">- <Suspense>- <Show when={!isBoardMode()} fallback={<CompanyKanban />}>- <SoupViewList /></Show>- </Suspense>- <Show when={isMobile()}>- <FloatRegion region="accessory">- <MobileSoupViewTabs />- </FloatRegion>+ </SplitHeaderRight>+ </Show>+ </div>+ <SoupFiltersBar+ variant={props.filterBarVariant}+ hasPreviewItems={hasPreviewItems()}+ onPreviewEngage={openFocusedEntityInPreview}+ />+ <Show when={applyDefaultCrmView}>+ <CrmDefaultViewLoader />+ </Show>+ <div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full">+ <Suspense>+ <Show when={!isBoardMode()} fallback={<CompanyKanban />}>+ <SoupViewList /></Show>- </div>+ </Suspense>+ <Show when={isMobile()}>+ <FloatRegion region="accessory">+ <MobileSoupViewTabs />+ </FloatRegion>+ </Show></div><Suspense>{/* The board hides the AI bar: it floats over the bottom edge, where@@ -791,7 +746,7 @@ export const SoupView = (props: SoupViewProps) => {<SoupChatInput /></Show></Suspense>- </SplitPanelContext.Provider>+ </div>);};@@ -848,14 +803,6 @@ const SoupViewListContent = (props: SoupViewListProps) => {return isListViewID(id) ? id : undefined;});- const {- paneVisible,- previewVisible,- previewOpen,- selectedEntity,- nonMemberChannelEntity,- } = usePreviewPaneVisiblity();-const focusFirstEntity = () => {const allRows = rows();const firstEntityIndex = allRows.findIndex(@@ -866,10 +813,6 @@ const SoupViewListContent = (props: SoupViewListProps) => {const result = soup.navigate.toIndex(firstEntityIndex);- if (paneVisible()) {- soup.setPreviewEntity(result?.row.id);- }-if (result) {virtualizerHandle()?.scrollToIndex(result.index, { align: 'nearest' });}@@ -917,12 +860,8 @@ const SoupViewListContent = (props: SoupViewListProps) => {setFocusEffectsEnabled(true);};- const previewPanel = useMaybePreviewPanel();-// Defer .focus() so the hotkey focusin handler's setActiveScope write doesn't re-invalidate this effect from inside its own tracking scope.createEffect(() => {- if (previewPanel) return;-const ref = soupViewRef();if (!ref) return;queueMicrotask(() => ref.focus());@@ -930,11 +869,7 @@ const SoupViewListContent = (props: SoupViewListProps) => {const [attachHotkeys, soupViewScope] = useHotkeyDOMScope('soup-view');- const scopeId = createMemo(() => {- return previewPanel- ? soupViewScope- : (props.scopeId ?? panel.splitHotkeyScope);- });+ const scopeId = createMemo(() => props.scopeId ?? panel.splitHotkeyScope);// Register navigation hotkeys on the active list scope (usually the split// scope). Most handlers are disposed with SoupViewList, but j/k intentionally@@ -979,12 +914,10 @@ const SoupViewListContent = (props: SoupViewListProps) => {};useSoupViewHotkeys({- splitId: panel.handle.id,scopeId: scopeId(),soup,splitHandle: panel.handle,virtualizerHandle,- previewState: previewVisible,currentView,activeTab,applyTabPreset,@@ -1011,8 +944,6 @@ const SoupViewListContent = (props: SoupViewListProps) => {source.fetchNextPage();}, 15);- const orchestrator = useGlobalBlockOrchestrator();-type EntityClickArgs = {type: 'entity' | 'project';entity: EntityData;@@ -1029,27 +960,39 @@ const SoupViewListContent = (props: SoupViewListProps) => {type === 'entity' ? args.entity : args.projectEntity) as EntityData;- // Channels the viewer hasn't joined can't be read: no preview, no- // navigation — the row's Join button is the only affordance.- if (isNonMemberChannelEntity(entity)) return;-// FIXME: this never gets called because we have overridesif (event.metaKey || event.ctrlKey) {- openEntityInNewTab({ entity, location });+ // Channels the viewer hasn't joined can't be opened; the row's inline+ // Join button (or, in preview, the Viewer's Join prompt) is the only+ // affordance.+ if (!isNonMemberChannelEntity(entity)) {+ openEntityInNewTab({ entity, location });+ }return;}- if (paneVisible() && type === 'entity') {- const alreadyFocused = soup.focus.id() === entity.id;+ // Plain click while engaged as a Controller previews into the Viewer;+ // shift+click falls through to open a fresh split instead. Non-member+ // channels flow through to openEntityInSplitFromUnifiedList, which shows the+ // Viewer's Join prompt when previewing and otherwise no-ops.+ if (+ panel.handle.isControllerSplit() &&+ type === 'entity' &&+ !event.shiftKey+ ) {+ if (preventDuplicatePreviewEntityOpen(entity, panel.handle)) return;+ // Single click: focus the row AND open it in the Preview Pair's Viewer.+ // The openWithSplit redirect keeps the Viewer unfocused so keyboard+ // navigation stays in this list.if (args.rowIndex !== undefined) soup.focus.setIndex(args.rowIndex);else soup.focus.set(entity.id);- soup.setPreviewEntity(entity.id);-- if (alreadyFocused) {- navigateChannelEntityToTarget(entity, orchestrator);- }+ await openEntityInSplitFromUnifiedList(entity, {+ location,+ splitHandle: panel.handle,+ referredFrom: currentView(),+ });return;}@@ -1247,8 +1190,8 @@ const SoupViewListContent = (props: SoupViewListProps) => {if (force) return;restored = true;- // The new inbox opens with the preview pane showing a placeholder, so don't- // auto-focus (and thus auto-select/open) the first row on initial load.+ // The new inbox opens with a Preview Pair Viewer, so don't auto-focus (and+ // thus open) the first row on initial load.registerFocusEffects(!isNewInboxEnabled());};@@ -1276,428 +1219,340 @@ const SoupViewListContent = (props: SoupViewListProps) => {}}data-hotkey-scope={soupViewScope}data-soup-view- data-soup-view-id={panel.handle.id + (previewPanel ? '-preview' : '')}+ data-soup-view-id={panel.handle.id}>- <Resize.Zone direction="horizontal" gutter={0}>- <Resize.Panel- id="soup-list"- minSize={300}- maxSize={paneVisible() ? 440 : undefined}- >- <SoupViewFileDropzone>- <div- class={cn(- '@container/u-list size-full unified-list-root flex flex-col relative no-select-children',- paneVisible() && 'border-r border-edge-muted'- )}- >- <Show when={isMobile() && source.isPlaceholderData()}>- <MobileTabLoadingBar />- </Show>- <Show when={isMobile()}>- <PullToRefresh- scrollContainer={() =>- showEmptyState() ? emptyStateRef() : listScrollerRef()- }- onRefresh={pullRefresh}- />- </Show>- <StaticMarkdownContext>- <Switch>- <Match- when={- source.isFetching() &&- !rows().length &&- !isPullRefreshing()- }- >- {/* Non-list states pad the chrome top themselves — the+ <SoupViewFileDropzone>+ <div class="@container/u-list size-full unified-list-root flex flex-col relative no-select-children">+ <Show when={isMobile() && source.isPlaceholderData()}>+ <MobileTabLoadingBar />+ </Show>+ <Show when={isMobile()}>+ <PullToRefresh+ scrollContainer={() =>+ showEmptyState() ? emptyStateRef() : listScrollerRef()+ }+ onRefresh={pullRefresh}+ />+ </Show>+ <StaticMarkdownContext>+ <Switch>+ <Match+ when={+ source.isFetching() && !rows().length && !isPullRefreshing()+ }+ >+ {/* Non-list states pad the chrome top themselves — thepanel leaves list views unpadded so rows canunder-scroll the status bar. */}- <div class="flex-1 min-h-0 flex flex-col mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">- <LoadingBlock />- </div>- </Match>- <Match- when={- (isSearchServiceLoading() || isLocalSearchSettling()) &&- !rows().length &&- !isPullRefreshing()- }+ <div class="flex-1 min-h-0 flex flex-col mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">+ <LoadingBlock />+ </div>+ </Match>+ <Match+ when={+ (isSearchServiceLoading() || isLocalSearchSettling()) &&+ !rows().length &&+ !isPullRefreshing()+ }+ >+ <div class="flex items-center gap-2 p-3 text-xs text-text-muted mobile:mt-(--mobile-content-inset-top) mobile:mb-(--mobile-content-inset-bottom)">+ <Spinner class="size-3 animate-spin" />+ Searching...+ </div>+ </Match>+ <Match when={showEmptyState()}>+ <div+ ref={setEmptyStateRef}+ class="flex-1 min-h-0 flex flex-col mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)"+ >+ <EmptyState+ listView={currentView()}+ search={!!searchText()}+ hasRefinementsFromBase={hasActiveRefinements()}+ hasHiddenItems={hasHiddenItems()}+ onClearFilters={resetToTabDefaults}+ />+ </div>+ </Match>+ <Match when={rows().length}>+ <ListLayoutProvider ref={localEntityListRef}>+ <Show when={currentView() === 'tasks' && !isMobile()}>+ <ResponsiveTaskListHeader class="shrink-0" />+ </Show>+ <Show when={currentView() === 'companies' && !isMobile()}>+ <ResponsiveCompanyListHeader class="shrink-0" />+ </Show>+ <SwipableRowProvider+ container={localEntityListRef}+ canSwipeLeft={(entityId) => {+ const entity = entityById().get(entityId);+ if (!entity) return false;++ const tab = activeTab();++ if (+ !isListViewID(contentId) ||+ (tab && !canExecuteMarkDoneOnView(contentId, tab))+ )+ return false;++ return markDoneAction.canExecute(entity.original);+ }}+ onSwipeLeft={(entityId) => {+ const entity = entityById().get(entityId);+ if (!entity) return;+ markDoneAction.executeWithSoup([entity.original], soup);+ }}+ setCollapseEntity={soup.collapseEntity.set}>- <div class="flex items-center gap-2 p-3 text-xs text-text-muted mobile:mt-(--mobile-content-inset-top) mobile:mb-(--mobile-content-inset-bottom)">- <Spinner class="size-3 animate-spin" />- Searching...- </div>- </Match>- <Match when={showEmptyState()}>- <div- ref={setEmptyStateRef}- class="flex-1 min-h-0 flex flex-col mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)"+ <SoupList+ cache={readListEntryState()?.virtualCache}+ ref={(el) => {+ setLocalEntityListRef(el);+ soupNavigationTouchHighlight(el);+ }}+ scrollerRef={setListScrollerRef}+ virtualizerClass={'scrollbar-hidden space-y-2'}+ class="overflow-hidden flex min-w-0"+ virtualizerRef={registerVirtualizerHandler}+ onScrollBottom={debouncedFetchMore}+ scrollBottomOffset={300}+ rows={rows()}>- <EmptyState- listView={currentView()}- search={!!searchText()}- hasRefinementsFromBase={hasActiveRefinements()}- hasHiddenItems={hasHiddenItems()}- onClearFilters={resetToTabDefaults}- />- </div>- </Match>- <Match when={rows().length}>- <ListLayoutProvider ref={localEntityListRef}>- <Show when={currentView() === 'tasks' && !isMobile()}>- <ResponsiveTaskListHeader class="shrink-0" />- </Show>- <Show- when={currentView() === 'companies' && !isMobile()}- >- <ResponsiveCompanyListHeader class="shrink-0" />- </Show>- <SwipableRowProvider- container={localEntityListRef}- canSwipeLeft={(entityId) => {- const entity = entityById().get(entityId);- if (!entity) return false;-- const tab = activeTab();-- if (- !isListViewID(contentId) ||- (tab && !canExecuteMarkDoneOnView(contentId, tab))- )- return false;-- return markDoneAction.canExecute(entity.original);- }}- onSwipeLeft={(entityId) => {- const entity = entityById().get(entityId);- if (!entity) return;- markDoneAction.executeWithSoup(- [entity.original],- soup- );- }}- setCollapseEntity={soup.collapseEntity.set}- >- <SoupList- cache={readListEntryState()?.virtualCache}- ref={(el) => {- setLocalEntityListRef(el);- soupNavigationTouchHighlight(el);- }}- scrollerRef={setListScrollerRef}- virtualizerClass={'scrollbar-hidden space-y-2'}- class="overflow-hidden flex min-w-0"- virtualizerRef={registerVirtualizerHandler}- onScrollBottom={debouncedFetchMore}- scrollBottomOffset={300}- rows={rows()}- >- {(row, i) => {- const timestamp = () => {- if (row.original.sortTs)- return row.original.sortTs;-- const sort_ = soup.sort.active();- if (!sort_.length) return;-- switch (sort_[0].id) {- case 'viewed_at':- return row.original.viewedAt;- case 'created_at':- return row.original.createdAt;- case 'updated_at':- return row.original.updatedAt;- default:- return row.original.createdAt;+ {(row, i) => {+ const timestamp = () => {+ if (row.original.sortTs) return row.original.sortTs;++ const sort_ = soup.sort.active();+ if (!sort_.length) return;++ switch (sort_[0].id) {+ case 'viewed_at':+ return row.original.viewedAt;+ case 'created_at':+ return row.original.createdAt;+ case 'updated_at':+ return row.original.updatedAt;+ default:+ return row.original.createdAt;+ }+ };++ return (+ <>+ <Show when={i() === 0 && featuredCount() > 0}>+ <SoupSectionHeader>+ <span class="truncate">Featured Results</span>+ </SoupSectionHeader>+ </Show>+ <Show+ when={+ i() === featuredCount() && featuredCount() > 0}- };-- return (- <>- <Show when={i() === 0 && featuredCount() > 0}>- <SoupSectionHeader>- <span class="truncate">- Featured Results- </span>- </SoupSectionHeader>- </Show>- <Show- when={- i() === featuredCount() &&- featuredCount() > 0- }- >- <SoupSectionHeader>- <span class="truncate">More Results</span>- </SoupSectionHeader>- </Show>-- <Switch>- {/* Group header row */}- <Match- when={row.getIsGrouped() && row.group}- >- {(group) => (- <Dynamic- component={- group().renderHeader ??- groupHeaderComponent()- }- group={group()}- highlighted={row.isFocused()}- />- )}- </Match>-- {/* Load more row */}- <Match- when={- row.group?.isExpanded() &&- row.getIsLoadMore() &&- row.group- }- >- {(group) => {- const highlighted = () =>- row.isFocused();- return (- <div- class={cn(- 'my-1 rounded min-h-9 flex items-center justify-center',- highlighted()- ? 'w-[calc(100%-0.5rem)] mx-1 bg-active/60'- : 'mx-auto'- )}- >- <Show- when={- !isFetchingGroupPage(- group().key- )- }- fallback={- <Button- variant="base"- size="sm"- depth={2}- class={cn({- 'bg-surface':- !highlighted(),- 'border-transparent':- highlighted(),- })}- disabled- >- <Spinner class="size-3 animate-spin" />- Loading...- </Button>- }- >- <Button- variant="base"- size="sm"- depth={2}- class={cn({- 'bg-surface': !highlighted(),- 'border-transparent':- highlighted(),- })}- onClick={() => {- fetchNextGroupPage(- group().key- );- }}- >- <CaretDownIcon class="size-2.5" />- Load More- </Button>- </Show>- </div>- );- }}- </Match>-- {/* Entity row */}- <Match- when={- !row.group || row.group?.isExpanded()+ >+ <SoupSectionHeader>+ <span class="truncate">More Results</span>+ </SoupSectionHeader>+ </Show>++ <Switch>+ {/* Group header row */}+ <Match when={row.getIsGrouped() && row.group}>+ {(group) => (+ <Dynamic+ component={+ group().renderHeader ??+ groupHeaderComponent()}- >- <SoupEntityContextMenu- entity={row.original}+ group={group()}+ highlighted={row.isFocused()}+ />+ )}+ </Match>++ {/* Load more row */}+ <Match+ when={+ row.group?.isExpanded() &&+ row.getIsLoadMore() &&+ row.group+ }+ >+ {(group) => {+ const highlighted = () => row.isFocused();+ return (+ <div+ class={cn(+ 'my-1 rounded min-h-9 flex items-center justify-center',+ highlighted()+ ? 'w-[calc(100%-0.5rem)] mx-1 bg-active/60'+ : 'mx-auto'+ )}>- <Dynamic- component={listEntityComponent()}- entity={row.original}- timestamp={timestamp()}- highlighted={row.isFocused()}- onMouseMove={() => {- if (isKeypressActive()) return;- if (- previewOpen() ||- isNewInboxEnabled()- )- return;- soup.focus.setIndex(row.index);- }}- showUnrollNotifications={- row.original.type !== 'email' &&- soup.predicates.isActive('inbox') &&- !soup.predicates.isActive('noise')+ <Show+ when={+ !isFetchingGroupPage(group().key)}- checked={row.isSelected()}- onChecked={(- next: boolean,- shiftKey: boolean- ) =>- handleMultiSelectChecked({- entity: row.original,- entityIndex: i(),- next,- shiftKey: shiftKey ?? false,- })+ fallback={+ <Button+ variant="base"+ size="sm"+ depth={2}+ class={cn({+ 'bg-surface': !highlighted(),+ 'border-transparent':+ highlighted(),+ })}+ disabled+ >+ <Spinner class="size-3 animate-spin" />+ Loading...+ </Button>}- onClick={(event: MouseEvent) => {- onEntityClick({- type: 'entity',- entity: row.original,- event,- location: undefined,- rowIndex: row.index,- });- }}- onProjectClick={(- projectEntity,- event- ) => {- onEntityClick({- type: 'project',- projectEntity,- entity: row.original,- event,- location: undefined,- rowIndex: row.index,- });- }}- onContentHitClick={(- e: PointerEvent | MouseEvent,- location?: SearchLocation- ) => {- onEntityClick({- type: 'entity',- entity: row.original,- event: e,- location,- rowIndex: row.index,- });- }}- entityRowConfig={{- swipeLeftColor: 'bg-success',- swipeLeftRevealedComponent: (- <CheckIcon class="size-8 text-panel" />- ),- }}- />- </SoupEntityContextMenu>- </Match>- </Switch>- <Show- when={- i() === rows().length - 1 &&- (isSearchServiceLoading() ||- source.isFetchingNextPage())- }- >- <div class="flex items-center gap-2 p-3 text-xs text-text-muted">- <Spinner class="size-3 animate-spin" />- {source.isFetchingNextPage()- ? 'Loading more...'- : 'Searching...'}- </div>- </Show>- <Show when={i() === rows().length - 1}>- {/* Desktop-only: mobile clearance comes+ >+ <Button+ variant="base"+ size="sm"+ depth={2}+ class={cn({+ 'bg-surface': !highlighted(),+ 'border-transparent':+ highlighted(),+ })}+ onClick={() => {+ fetchNextGroupPage(group().key);+ }}+ >+ <CaretDownIcon class="size-2.5" />+ Load More+ </Button>+ </Show>+ </div>+ );+ }}+ </Match>++ {/* Entity row */}+ <Match+ when={!row.group || row.group?.isExpanded()}+ >+ <SoupEntityContextMenu entity={row.original}>+ <Dynamic+ component={listEntityComponent()}+ entity={row.original}+ timestamp={timestamp()}+ highlighted={row.isFocused()}+ onMouseMove={() => {+ if (isKeypressActive()) return;+ if (panel.handle.isControllerSplit())+ return;+ soup.focus.setIndex(row.index);+ }}+ showUnrollNotifications={+ row.original.type !== 'email' &&+ soup.predicates.isActive('inbox') &&+ !soup.predicates.isActive('noise')+ }+ checked={row.isSelected()}+ onChecked={(+ next: boolean,+ shiftKey: boolean+ ) =>+ handleMultiSelectChecked({+ entity: row.original,+ entityIndex: i(),+ next,+ shiftKey: shiftKey ?? false,+ })+ }+ onClick={(event: MouseEvent) => {+ onEntityClick({+ type: 'entity',+ entity: row.original,+ event,+ location: undefined,+ rowIndex: row.index,+ });+ }}+ onProjectClick={(+ projectEntity,+ event+ ) => {+ onEntityClick({+ type: 'project',+ projectEntity,+ entity: row.original,+ event,+ location: undefined,+ rowIndex: row.index,+ });+ }}+ onContentHitClick={(+ e: PointerEvent | MouseEvent,+ location?: SearchLocation+ ) => {+ onEntityClick({+ type: 'entity',+ entity: row.original,+ event: e,+ location,+ rowIndex: row.index,+ });+ }}+ entityRowConfig={{+ swipeLeftColor: 'bg-success',+ swipeLeftRevealedComponent: (+ <CheckIcon class="size-8 text-panel" />+ ),+ }}+ />+ </SoupEntityContextMenu>+ </Match>+ </Switch>+ <Show+ when={+ i() === rows().length - 1 &&+ (isSearchServiceLoading() ||+ source.isFetchingNextPage())+ }+ >+ <div class="flex items-center gap-2 p-3 text-xs text-text-muted">+ <Spinner class="size-3 animate-spin" />+ {source.isFetchingNextPage()+ ? 'Loading more...'+ : 'Searching...'}+ </div>+ </Show>+ <Show when={i() === rows().length - 1}>+ {/* Desktop-only: mobile clearance comesfrom the in-scroll trailing spacer. */}- <div class="h-15 mobile:hidden" />- </Show>- </>- );- }}- </SoupList>- </SwipableRowProvider>- </ListLayoutProvider>-- <Show when={!props.customScrollbarHidden}>- <CustomScrollbar- scrollContainer={() => {- // Find the actual scroll container (VList creates its own scroll container)- const listEl = localEntityListRef();- if (!listEl) return undefined;- const scrollContainer = listEl.querySelector(- soupListContainerSelector- ) as HTMLElement;- return scrollContainer || undefined;- }}- />- </Show>- </Match>- </Switch>- </StaticMarkdownContext>- </div>- </SoupViewFileDropzone>- </Resize.Panel>-- <Show when={paneVisible()}>- <Resize.Panel- id="soup-preview"- minSize={0}- target={{- kind: 'percent',- percent: isNewInboxEnabled() ? 55 : 70,- }}- >- <div class="size-full">- <Show- when={selectedEntity()}- fallback={- <Show- when={nonMemberChannelEntity()}- fallback={- <EmptyStatePanel- graphic={EmptyStatePreviewIcon}- title="Nothing selected"- description={- isNewInboxEnabled()- ? 'Select an item from your inbox to preview it here.'- : 'Select an item from the list to preview it here'- }- centered- />- }- >- {(channel) => (- <NonMemberChannelPreview entity={channel()} />- )}- </Show>- }- >- {(entity) => (- <PreviewPanel- selectedEntity={entity()}- orchestrator={orchestrator}- splitPanelContext={panel}- onFocusOut={() => {- soupViewRef()?.focus();+ <div class="h-15 mobile:hidden" />+ </Show>+ </>+ );+ }}+ </SoupList>+ </SwipableRowProvider>+ </ListLayoutProvider>++ <Show when={!props.customScrollbarHidden}>+ <CustomScrollbar+ scrollContainer={() => {+ // Find the actual scroll container (VList creates its own scroll container)+ const listEl = localEntityListRef();+ if (!listEl) return undefined;+ const scrollContainer = listEl.querySelector(+ soupListContainerSelector+ ) as HTMLElement;+ return scrollContainer || undefined;}}/>- )}- </Show>- </div>- </Resize.Panel>- </Show>- </Resize.Zone>+ </Show>+ </Match>+ </Switch>+ </StaticMarkdownContext>+ </div>+ </SoupViewFileDropzone><Show when={soup.selection.count() > 0}><SoupEntitySelectionToolbarselected={soup.selection.selected()}diff --git a/apps/web/src/features/next-soup/soup-view/use-is-new-inbox-enabled.ts b/apps/web/src/features/next-soup/soup-view/use-is-new-inbox-enabled.tsnew file mode 100644index 0000000000..7d01d4c888--- /dev/null+++ b/apps/web/src/features/next-soup/soup-view/use-is-new-inbox-enabled.ts@@ -0,0 +1,23 @@+import { isListViewID } from '@app/constants/list-views';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import {+ ENABLE_NEW_INBOX_FLAG,+ ENABLE_NEW_INBOX_OVERRIDE,+} from '@core/constant/featureFlags';++export function useIsNewInboxEnabled() {+ const panel = useSplitPanelOrThrow();++ const currentView = () => {+ const { type, id } = panel.handle.content();+ if (type !== 'component') return;+ return isListViewID(id) ? id : undefined;+ };++ const newInboxFlag = useFeatureFlag(ENABLE_NEW_INBOX_FLAG, {+ enabledOverride: ENABLE_NEW_INBOX_OVERRIDE,+ });++ return () => currentView() === 'inbox' && newInboxFlag().enabled;+}diff --git a/apps/web/src/features/next-soup/soup-view/use-preview-pane-visibility.ts b/apps/web/src/features/next-soup/soup-view/use-preview-pane-visibility.tsdeleted file mode 100644index 4e41ec3969..0000000000--- a/apps/web/src/features/next-soup/soup-view/use-preview-pane-visibility.ts+++ /dev/null@@ -1,79 +0,0 @@-import { isListViewID } from '@app/constants/list-views';-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';-import {- ENABLE_NEW_INBOX_FLAG,- ENABLE_NEW_INBOX_OVERRIDE,-} from '@core/constant/featureFlags';-import { isMobile } from '@core/mobile/isMobile';-import { type ChannelEntity, isNonMemberChannelEntity } from '@entity';-import { createMemo } from 'solid-js';--export const WIDE_SPLIT_PANEL_BREAKPOINT = 640;--export function useIsNewInboxEnabled() {- const panel = useSplitPanelOrThrow();-- const currentView = () => {- const { type, id } = panel.handle.content();- if (type !== 'component') return;- return isListViewID(id) ? id : undefined;- };-- const newInboxFlag = useFeatureFlag(ENABLE_NEW_INBOX_FLAG, {- enabledOverride: ENABLE_NEW_INBOX_OVERRIDE,- });-- const isNewInboxEnabled = () =>- currentView() === 'inbox' && newInboxFlag().enabled;-- return isNewInboxEnabled;-}--export function usePreviewPaneVisiblity() {- const panel = useSplitPanelOrThrow();- const { soup, rows, previewOpen } = useSoupView();-- const isWideSplitPanel = createMemo(- () => (panel.panelSize.width ?? 0) > WIDE_SPLIT_PANEL_BREAKPOINT- );-- // Group headers and load-more rows carry a representative entity, but they- // are navigation controls rather than user-selectable preview items.- const focusedRowEntity = createMemo(() => {- const row = soup.focus.row();- if (!row || row.getIsGrouped() || row.getIsLoadMore()) return;- return row.original;- });-- // Channels the viewer hasn't joined can't be read — instead of the entity- // block, the pane renders a join prompt for these.- const nonMemberChannelEntity = createMemo(() => {- const entity = focusedRowEntity();- return entity && isNonMemberChannelEntity(entity)- ? (entity as ChannelEntity)- : undefined;- });-- const selectedEntity = createMemo(() => {- const entity = focusedRowEntity();- if (!entity || isNonMemberChannelEntity(entity)) return;- return entity;- });-- const paneVisible = createMemo(- () =>- rows().length > 0 && !isMobile() && isWideSplitPanel() && previewOpen()- );- const previewVisible = createMemo(() => paneVisible() && !!selectedEntity());-- return {- paneVisible,- previewVisible,- previewOpen,- selectedEntity,- nonMemberChannelEntity,- isWideSplitPanel,- };-}diff --git a/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.ts b/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.tsindex 7352fd3c6c..38a65f1967 100644--- a/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.ts+++ b/apps/web/src/features/next-soup/soup-view/use-soup-navigation-hotkeys.ts@@ -1,13 +1,25 @@import { isListViewID } from '@app/constants/list-views';-import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';-import type { SplitHandle } from '@components/app/split-layout/layoutManager';+import {+ isDuplicatePreviewEntityOpen,+ notifyDuplicateContentOpen,+ openEntityInSplitFromUnifiedList,+} from '@app/features/next-soup/utils';+import { globalSplitManager } from '@app/signal/splitLayout';+import type {+ SplitContent,+ SplitEvent,+ SplitEventPayload,+ SplitHandle,+} from '@components/app/split-layout/layoutManager';import { entityIdSelector } from '@core/dom-selectors';import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';import { TOKENS } from '@core/hotkey/tokens';import type { EntityData } from '@entity';-import { type Accessor, createMemo, onCleanup } from 'solid-js';+import { debounce } from '@solid-primitives/scheduled';+import { type Accessor, createEffect, createMemo, onCleanup } from 'solid-js';import type { VirtualizerHandle } from 'virtua/solid';import type { SoupState } from '../create-soup-state';+import { previewContentMatchesEntity } from './preview-content-row';type UseSoupNavigationHotkeysOptions = {scopeId: string;@@ -46,7 +58,24 @@ export const useSoupNavigationHotkeys = (return isListViewID(referredFrom) ? referredFrom : undefined;});+ // Row focus moves instantly on every keypress; the (expensive) block swap in+ // the Viewer trails the last press. mergeHistory keeps the Viewer's+ // history at a single scanning entry while holding j/k.+ const openInViewerDebounced = debounce((entity: EntityData) => {+ openEntityInSplitFromUnifiedList(entity, {+ splitHandle,+ mergeHistory: true,+ referredFrom: navigationReferredFrom(),+ });+ }, 150);+ onCleanup(() => openInViewerDebounced.clear());+const openEntity = (entity: EntityData) => {+ if (splitHandle.isControllerSplit()) {+ openInViewerDebounced(entity);+ return;+ }+const handleContent = splitHandle.content().type;if (handleContent === 'component' || handleContent === 'project') return;@@ -58,6 +87,67 @@ export const useSoupNavigationHotkeys = (});};+ const navigateToOpenableEntity = (offset: -1 | 1) => {+ let skippedDuplicate = false;+ const next = soup.navigate.by(offset, {+ skip: (row) => {+ if (+ !splitHandle.isControllerSplit() ||+ row.getIsGrouped() ||+ row.getIsLoadMore()+ ) {+ return false;+ }+ const blocked = isDuplicatePreviewEntityOpen(row.original, splitHandle);+ skippedDuplicate ||= blocked;+ return blocked;+ },+ });+ if (skippedDuplicate) notifyDuplicateContentOpen();+ return next;+ };++ /**+ * The row this preview-split content corresponds to, if it lives in this+ * list. Channel messages/threads open as their channel, so those rows are+ * matched through their channelId.+ */+ const rowForPreviewContent = (content: SplitContent) =>+ soup.rows().find((row) => {+ if (row.getIsGrouped() || row.getIsLoadMore()) return false;+ const entity = row.original as EntityData;+ if (!entity) return false;+ return previewContentMatchesEntity(content, entity);+ });++ // Preview history → list selection: stepping the Viewer's history+ // back or forward to content that was opened from this list re-selects the+ // corresponding row.+ createEffect(() => {+ const viewerId = splitHandle.viewerId();+ if (!viewerId) return;+ const viewer = globalSplitManager()?.getSplit(viewerId);+ if (!viewer) return;++ const syncSelection = (+ payload: SplitEventPayload[SplitEvent.ContentChange]+ ) => {+ if (+ payload.cause !== 'history-back' &&+ payload.cause !== 'history-forward'+ ) {+ return;+ }+ const row = rowForPreviewContent(payload.newContent);+ if (!row) return;+ const result = soup.navigate.toId(row.id);+ if (result) scrollTo(result.index);+ };++ viewer.registerContentChangeListener(syncSelection);+ onCleanup(() => viewer.unregisterContentChangeListener(syncSelection));+ });+const navigateAndSelectEntity = (offset: number) => {const nextRow = soup.navigate.by(offset);if (!nextRow) return true;@@ -124,7 +214,7 @@ export const useSoupNavigationHotkeys = (const navigateDown = () => {const rowCount = soup.rows().length;- const next = soup.navigate.down();+ const next = navigateToOpenableEntity(1);if (!next) {fetchNextPageIfNeeded();@@ -142,7 +232,7 @@ export const useSoupNavigationHotkeys = (};const navigateUp = () => {- const next = soup.navigate.up();+ const next = navigateToOpenableEntity(-1);if (!next) return true;diff --git a/apps/web/src/features/next-soup/soup-view/use-soup-preview-availability.test.ts b/apps/web/src/features/next-soup/soup-view/use-soup-preview-availability.test.tsnew file mode 100644index 0000000000..c333bea5b6--- /dev/null+++ b/apps/web/src/features/next-soup/soup-view/use-soup-preview-availability.test.ts@@ -0,0 +1,83 @@+import type { SplitHandle } from '@components/app/split-layout/layoutManager';+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import type { SoupRow } from '../create-soup-state';+import {+ hasPreviewableSoupRows,+ useSoupPreviewAvailability,+} from './use-soup-preview-availability';++const row = (+ options: { grouped?: boolean; loadMore?: boolean } = {}+): SoupRow =>+ ({+ getIsGrouped: () => options.grouped ?? false,+ getIsLoadMore: () => options.loadMore ?? false,+ }) as SoupRow;++const flushEffects = () => Promise.resolve();++describe('Soup preview availability', () => {+ it('requires an entity row rather than a group or load-more row', () => {+ expect(+ hasPreviewableSoupRows([row({ grouped: true }), row({ loadMore: true })])+ ).toBe(false);+ expect(hasPreviewableSoupRows([row({ grouped: true }), row()])).toBe(true);+ });++ it('disengages preview when the last entity row disappears', async () => {+ const disengagePreview = vi.fn();+ let setRows!: (rows: SoupRow[]) => void;+ let dispose!: () => void;++ createRoot((rootDispose) => {+ dispose = rootDispose;+ const [rows, updateRows] = createSignal([row()]);+ setRows = updateRows;+ useSoupPreviewAvailability({+ rows,+ isLoading: () => false,+ splitHandle: {+ isControllerSplit: () => true,+ disengagePreview,+ } as unknown as SplitHandle,+ });+ });++ await flushEffects();+ expect(disengagePreview).not.toHaveBeenCalled();++ setRows([]);+ await flushEffects();+ expect(disengagePreview).toHaveBeenCalledOnce();+ dispose();+ });++ it('keeps preview open while an empty result is still loading', async () => {+ const disengagePreview = vi.fn();+ let setLoading!: (loading: boolean) => void;+ let dispose!: () => void;++ createRoot((rootDispose) => {+ dispose = rootDispose;+ const [isLoading, updateLoading] = createSignal(true);+ setLoading = updateLoading;+ useSoupPreviewAvailability({+ rows: () => [],+ isLoading,+ splitHandle: {+ isControllerSplit: () => true,+ disengagePreview,+ } as unknown as SplitHandle,+ });+ });++ await flushEffects();+ expect(disengagePreview).not.toHaveBeenCalled();++ setLoading(false);+ await flushEffects();+ expect(disengagePreview).toHaveBeenCalledOnce();+ dispose();+ });+});diff --git a/apps/web/src/features/next-soup/soup-view/use-soup-preview-availability.ts b/apps/web/src/features/next-soup/soup-view/use-soup-preview-availability.tsnew file mode 100644index 0000000000..1d2802af7a--- /dev/null+++ b/apps/web/src/features/next-soup/soup-view/use-soup-preview-availability.ts@@ -0,0 +1,30 @@+import type { SoupRow } from '@app/features/next-soup/create-soup-state';+import type { SplitHandle } from '@components/app/split-layout/layoutManager';+import { type Accessor, createEffect, createMemo } from 'solid-js';++export function hasPreviewableSoupRows(rows: readonly SoupRow[]): boolean {+ return rows.some((row) => !row.getIsGrouped() && !row.getIsLoadMore());+}++/**+ * Tracks whether a Soup view has an entity that can be previewed and closes+ * its Preview Pair once a settled result contains no such entities.+ */+export function useSoupPreviewAvailability(options: {+ rows: Accessor<readonly SoupRow[]>;+ isLoading: Accessor<boolean>;+ splitHandle: SplitHandle;+}): Accessor<boolean> {+ const hasPreviewItems = createMemo(() =>+ hasPreviewableSoupRows(options.rows())+ );++ createEffect(() => {+ if (options.isLoading() || hasPreviewItems()) return;+ if (options.splitHandle.isControllerSplit()) {+ options.splitHandle.disengagePreview();+ }+ });++ return hasPreviewItems;+}diff --git a/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts b/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.tsindex 7660c8c31f..af945c4975 100644--- a/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts+++ b/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts@@ -7,14 +7,8 @@ import { useAnalytics } from '@app/lib/analytics/analytics-context';import { globalSplitManager } from '@app/signal/splitLayout';import type { SplitHandle } from '@components/app/split-layout/layoutManager';import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';-import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';import { TOKENS } from '@core/hotkey/tokens';-import {- getHotkeyCommand,- getScopeElement,- isScopeInActiveBranch,- runCommand,-} from '@core/hotkey/utils';+import { isScopeInActiveBranch } from '@core/hotkey/utils';import {filterNotDoneNotifications,filterValidNotifications,@@ -28,12 +22,10 @@ import type { SoupState } from '../create-soup-state';import { type TabbedListView, VIEW_TAB_LISTS } from './soup-view-tabs';type UseSoupViewHotkeysOptions = {- splitId: string;scopeId: string;soup: SoupState;splitHandle: SplitHandle;virtualizerHandle: Accessor<VirtualizerHandle | undefined>;- previewState: Accessor<boolean>;currentView: Accessor<ListView | undefined>;activeTab: Accessor<string | undefined>;applyTabPreset: (view: ListView, tabId: string) => void;@@ -46,7 +38,6 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {soup,splitHandle,virtualizerHandle,- previewState,currentView,activeTab,applyTabPreset,@@ -133,7 +124,12 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {const splitManager = globalSplitManager();return (!!splitManager &&- openSingleStackNotification(validNotifs, splitManager, newSplit)+ openSingleStackNotification(+ validNotifs,+ splitManager,+ newSplit,+ splitHandle+ ));};@@ -193,51 +189,16 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {hotkey: ['cmd+enter'],scopeId,description: 'Focus Preview',+ condition: () => splitHandle.isControllerSplit(),keyDownHandler: () => {- const preview = previewState();- const entity = soup.focus.item();- if (!entity) return false;-- if (preview) {- // focus inside preview block- const blockEl = document.getElementById(`block-${entity.id}`);- if (blockEl) {- // TODO: use state instead to determine when preview block can receive focus- blockEl.setAttribute('data-allow-focus-in-preview', '');-- blockEl.focus();- const getEnterCommand = () => {- const currentActiveScope = activeScope();- if (!currentActiveScope) return undefined;- const activeScopeNode = hotkeyScopeTree.get(currentActiveScope);- if (!activeScopeNode) return undefined;- if (activeScopeNode?.type !== 'dom') return;- const dom = getScopeElement(currentActiveScope);- if (!dom) return undefined;- const closestBlockScope = dom.closest(`[id="block-${entity.id}"]`);- if (- !closestBlockScope ||- !(closestBlockScope instanceof HTMLElement)- )- return;- const scopeId = closestBlockScope.dataset.hotkeyScope;- if (!scopeId) return undefined;-- return getHotkeyCommand(scopeId, 'enter');- };- const command = getEnterCommand();- if (command) {- runCommand(command);- }- }+ const manager = globalSplitManager();+ const viewerId = splitHandle.viewerId();+ if (splitHandle.isControllerSplit() && viewerId && manager) {+ manager.activateSplit(viewerId);+ manager.returnFocus();return true;}-- openEntityInSplitFromUnifiedList(entity, {- splitHandle,- referredFrom: currentView(),- });- return true;+ return false;},displayPriority: 4,}).withGroup(group);diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsxindex e86bf2d394..ec2b1a8be3 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx+++ b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx@@ -3,8 +3,10 @@ import { EmptyState } from '@app/features/next-soup/soup-view/empty-states';import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';import { SoupEntityContextMenu } from '@app/features/next-soup/soup-view/soup-entity-context-menu';import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import { usePreviewPaneVisiblity } from '@app/features/next-soup/soup-view/use-preview-pane-visibility';-import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';+import {+ openEntityInSplitFromUnifiedList,+ preventDuplicatePreviewEntityOpen,+} from '@app/features/next-soup/utils';import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';import { useDealStages } from '@companies/crm/deal-stages';import { CrmStageIcon } from '@companies/crm/StageIcon';@@ -13,13 +15,9 @@ import {useCrmPermissions,useCrmUnavailable,} from '@companies/crm/team-crm-config';-import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';-import { PreviewPanel } from '@components/app/PreviewPanel';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { CustomScrollbar } from '@core/component/CustomScrollbar';-import { Resize } from '@core/component/Resize';import { UserIcon } from '@core/component/UserIcon';-import EmptyStatePreviewIcon from '@design/empty-state-doc.svg';import {Entity,type EntityData,@@ -31,7 +29,7 @@ import CircleDashed from '@phosphor/circle-dashed.svg';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { EntityType } from '@service-properties/generated/schemas/entityType';import { createElementSize } from '@solid-primitives/resize-observer';-import { cn, EmptyStatePanel, Layer } from '@ui';+import { cn, Layer } from '@ui';import { createMemo, createSignal, For, Show } from 'solid-js';/** Column key for companies without a Stage value. */@@ -57,15 +55,11 @@ type StageColumn = {* admins/owners only, matching CRM edit access; moving deals out of a* closed stage additionally requires the move-closed-deals permission).*- * Like the list, the board supports the toggleable preview pane (Preview- * button / space in the filters bar): while it's open, clicking a card- * previews the company to the side instead of replacing the split.*/export function CompanyKanban() {const { source, soup, stageFilter, searchText } = useSoupView();const panel = useSplitPanelOrThrow();const saveMutation = useBulkSaveEntityPropertiesMutation();- const orchestrator = useGlobalBlockOrchestrator();const { stages, filterStages, stageProperty, resolveStage } = useDealStages();const { canEditCrm, canMoveClosedDeals } = useCrmPermissions();@@ -104,8 +98,6 @@ export function CompanyKanban() {);});- const { paneVisible, selectedEntity } = usePreviewPaneVisiblity();-const companies = createMemo(() => source.data().filter(isCrmCompanyEntity));// Mirror the list view's empty states: beyond CRM-unavailable, an empty@@ -186,14 +178,17 @@ export function CompanyKanban() {};const openCompany = (entity: EntityData, event: MouseEvent) => {- soup.focus.set(entity.id);-- // While the preview pane is open, card clicks retarget it instead of- // replacing the split (mirrors the list view's behavior).- if (paneVisible()) {- soup.setPreviewEntity(entity.id);+ // Shift+click always opens a fresh split; a plain click while engaged as a+ // Controller previews into the Viewer and shouldn't re-open an entity+ // already shown elsewhere. Matches the list view's onEntityClick.+ if (+ !event.shiftKey &&+ panel.handle.isControllerSplit() &&+ preventDuplicatePreviewEntityOpen(entity, panel.handle)+ ) {return;}+ soup.focus.set(entity.id);void openEntityInSplitFromUnifiedList(entity, {openInNewSplit: event.shiftKey,@@ -215,153 +210,116 @@ export function CompanyKanban() {/>}>- <Resize.Zone direction="horizontal" gutter={0}>- <Resize.Panel id="company-kanban" minSize={200}>- {/* Relative wrapper anchors the horizontal scrollbar to the board's- bottom edge when the split is too narrow for all columns. */}- <div- class={cn(- 'relative size-full min-w-0',- paneVisible() && 'border-r border-edge-muted'- )}- >- <div- ref={setScrollRef}- class="size-full overflow-x-auto overflow-y-hidden scrollbar-hidden"- >- <div class="flex h-full gap-3 p-3">- <For each={columns()}>- {(column, columnIndex) => (- <div- class={cn(- // Fallback sizing until the board is measured; after- // that the snapping columnWidth() takes over.- 'flex h-full min-w-56 flex-1 flex-col rounded-lg border border-edge-muted bg-surface',- dropTarget() === column.key &&- draggedId() &&- 'border-accent/50 bg-accent/5'- )}- style={- columnWidth() !== undefined- ? { width: `${columnWidth()}px`, flex: 'none' }- : undefined+ {/* Relative wrapper anchors the horizontal scrollbar to the board's+ bottom edge when the split is too narrow for all columns. */}+ <div class="relative size-full min-w-0">+ <div+ ref={setScrollRef}+ class="size-full overflow-x-auto overflow-y-hidden scrollbar-hidden"+ >+ <div class="flex h-full gap-3 p-3">+ <For each={columns()}>+ {(column, columnIndex) => (+ <div+ class={cn(+ // Fallback sizing until the board is measured; after+ // that the snapping columnWidth() takes over.+ 'flex h-full min-w-56 flex-1 flex-col rounded-lg border border-edge-muted bg-surface',+ dropTarget() === column.key &&+ draggedId() &&+ 'border-accent/50 bg-accent/5'+ )}+ style={+ columnWidth() !== undefined+ ? { width: `${columnWidth()}px`, flex: 'none' }+ : undefined+ }+ onDragOver={(e) => {+ if (!draggedId()) return;+ e.preventDefault();+ setDropTarget(column.key);+ }}+ onDragLeave={(e) => {+ if (+ e.relatedTarget instanceof Node &&+ e.currentTarget.contains(e.relatedTarget)+ ) {+ return;+ }+ if (dropTarget() === column.key) setDropTarget(undefined);+ }}+ onDrop={(e) => {+ e.preventDefault();+ const id =+ draggedId() ?? e.dataTransfer?.getData('text/plain');+ setDropTarget(undefined);+ setDraggedId(undefined);+ if (id) moveToStage(id, column.key);+ }}+ >+ <div class="flex items-center gap-2 px-3 py-2.5 text-xs font-semibold text-ink-muted">+ <Show+ when={column.key !== NO_STAGE_KEY}+ fallback={+ <CircleDashed class="size-3.5 text-ink-extra-muted" />}- onDragOver={(e) => {- if (!draggedId()) return;- e.preventDefault();- setDropTarget(column.key);- }}- onDragLeave={(e) => {- if (- e.relatedTarget instanceof Node &&- e.currentTarget.contains(e.relatedTarget)- ) {- return;- }- if (dropTarget() === column.key)- setDropTarget(undefined);- }}- onDrop={(e) => {- e.preventDefault();- const id =- draggedId() ?? e.dataTransfer?.getData('text/plain');- setDropTarget(undefined);- setDraggedId(undefined);- if (id) moveToStage(id, column.key);- }}>- <div class="flex items-center gap-2 px-3 py-2.5 text-xs font-semibold text-ink-muted">- <Show- when={column.key !== NO_STAGE_KEY}- fallback={- <CircleDashed class="size-3.5 text-ink-extra-muted" />- }- >- <CrmStageIcon- optionId={column.key}- index={columnIndex()}- class="size-3.5"- />- </Show>- <span class="truncate">{column.label}</span>- </div>- <div class="min-h-0 flex-1 overflow-y-auto scrollbar-hidden flex flex-col gap-2 px-2 pb-2">- <For each={column.entities}>- {(entity) => (- // The context-menu trigger is h-full (sized for list- // rows); an auto-height wrapper resolves that to the- // card's content height instead of the column's.- <div class="shrink-0">- <SoupEntityContextMenu entity={entity}>- <CompanyKanbanCard- entity={entity}- draggable={canDragFrom(column.key)}- dragging={draggedId() === entity.id}- onDragStart={(e) => {- e.dataTransfer?.setData(- 'text/plain',- entity.id- );- if (e.dataTransfer) {- e.dataTransfer.effectAllowed = 'move';- }- setDraggedId(entity.id);- }}- onDragEnd={() => {- setDraggedId(undefined);- setDropTarget(undefined);- }}- onClick={(e) => openCompany(entity, e)}- />- </SoupEntityContextMenu>- </div>- )}- </For>- </div>- </div>- )}- </For>- </div>- </div>- {/* watchContent: columns mount after the initial measurement, so- overflow must be re-detected as they load in. */}- <CustomScrollbar- scrollContainer={scrollRef}- horizontal- revealZone={48}- gutterSize={20}- watchContent- />- </div>- </Resize.Panel>- <Show when={paneVisible()}>- <Resize.Panel- id="soup-preview"- minSize={500}- target={{ kind: 'percent', percent: 70 }}- >- <Show- when={selectedEntity()}- fallback={- <EmptyStatePanel- graphic={EmptyStatePreviewIcon}- title="Nothing selected"- description="Select a card from the board to preview it here"- centered- />- }- >- {(entity) => (- <PreviewPanel- selectedEntity={entity()}- orchestrator={orchestrator}- splitPanelContext={panel}- />+ <CrmStageIcon+ optionId={column.key}+ index={columnIndex()}+ class="size-3.5"+ />+ </Show>+ <span class="truncate">{column.label}</span>+ </div>+ <div class="min-h-0 flex-1 overflow-y-auto scrollbar-hidden flex flex-col gap-2 px-2 pb-2">+ <For each={column.entities}>+ {(entity) => (+ // The context-menu trigger is h-full (sized for list+ // rows); an auto-height wrapper resolves that to the+ // card's content height instead of the column's.+ <div class="shrink-0">+ <SoupEntityContextMenu entity={entity}>+ <CompanyKanbanCard+ entity={entity}+ draggable={canDragFrom(column.key)}+ dragging={draggedId() === entity.id}+ onDragStart={(e) => {+ e.dataTransfer?.setData(+ 'text/plain',+ entity.id+ );+ if (e.dataTransfer) {+ e.dataTransfer.effectAllowed = 'move';+ }+ setDraggedId(entity.id);+ }}+ onDragEnd={() => {+ setDraggedId(undefined);+ setDropTarget(undefined);+ }}+ onClick={(e) => openCompany(entity, e)}+ />+ </SoupEntityContextMenu>+ </div>+ )}+ </For>+ </div>+ </div>)}- </Show>- </Resize.Panel>- </Show>- </Resize.Zone>+ </For>+ </div>+ </div>+ {/* watchContent: columns mount after the initial measurement, so+ overflow must be re-detected as they load in. */}+ <CustomScrollbar+ scrollContainer={scrollRef}+ horizontal+ revealZone={48}+ gutterSize={20}+ watchContent+ />+ </div></Show>);}diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.tsindex e948a7e2f6..1c80cb4a88 100644--- a/apps/web/src/features/next-soup/utils.test.ts+++ b/apps/web/src/features/next-soup/utils.test.ts@@ -1,4 +1,6 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';++const { toastAlert } = vi.hoisted(() => ({ toastAlert: vi.fn() }));// utils.ts transitively imports the websocket client modules, which open real// sockets at module scope and reject under jsdom.@@ -12,10 +14,29 @@ vi.mock('@service-connection/websocket', () => ({createConnectionBlockWebsocketEffect: vi.fn(),createConnectionWebsocketEffect: vi.fn(),}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { alert: toastAlert },+}));+import { setGlobalSplitManager } from '@app/signal/splitLayout';+import type {+ SplitHandle,+ SplitManager,+} from '@components/app/split-layout/layoutManager';import type { ChannelEntityTarget, EntityData } from '@entity';import type { UnifiedNotification } from '@notifications';-import { getChannelEntityTarget, getRowClickFallbackLocation } from './utils';+import { previewSourceEntityId } from './preview-history';+import {+ getChannelEntityTarget,+ getRowClickFallbackLocation,+ openEntityInSplitFromUnifiedList,+ preventDuplicatePreviewEntityOpen,+} from './utils';++afterEach(() => {+ setGlobalSplitManager(undefined);+ toastAlert.mockClear();+});const sendNotification = (id: string, messageId: string): UnifiedNotification =>({@@ -90,6 +111,64 @@ const channelThreadRow = (opts?: {...(opts?.notifications ? { notifications: () => opts.notifications } : {}),}) as unknown as EntityData;+describe('preview duplicate navigation', () => {+ it('rejects content owned by a different preview viewer and notifies', () => {+ const controller = {+ viewerId: () => 'viewer-1',+ } as unknown as SplitHandle;+ setGlobalSplitManager({+ getSplitByContent: vi.fn(() => ({ id: 'viewer-2' })),+ } as unknown as SplitManager);++ expect(preventDuplicatePreviewEntityOpen(channelRow(), controller)).toBe(+ true+ );+ expect(toastAlert).toHaveBeenCalledWith('Content already open.');+ });++ it('allows content already displayed by the controller own viewer', () => {+ const controller = {+ viewerId: () => 'viewer-1',+ } as unknown as SplitHandle;+ setGlobalSplitManager({+ getSplitByContent: vi.fn(() => ({ id: 'viewer-1' })),+ } as unknown as SplitManager);++ expect(preventDuplicatePreviewEntityOpen(channelRow(), controller)).toBe(+ false+ );+ expect(toastAlert).not.toHaveBeenCalled();+ });+});++describe('preview history source', () => {+ it('stamps the originating controller entity on viewer content', async () => {+ const openWithSplit = vi.fn();+ const controller = {+ content: () => ({ type: 'component', id: 'inbox' }),+ isControllerSplit: () => true,+ viewerId: () => 'viewer-1',+ } as unknown as SplitHandle;+ setGlobalSplitManager({+ activeSplit: vi.fn(),+ getOrchestrator: vi.fn(() => ({})),+ getSplitByContent: vi.fn(),+ openWithSplit,+ } as unknown as SplitManager);++ await openEntityInSplitFromUnifiedList(+ {+ type: 'document',+ id: 'doc-1',+ fileType: 'md',+ } as EntityData,+ { splitHandle: controller }+ );++ expect(previewSourceEntityId(openWithSplit.mock.calls[0][0])).toBe('doc-1');+ });+});+describe('getChannelEntityTarget', () => {it('activates a stamped target over attached channel notifications (search message hit)', () => {const entity = channelMessageRow({diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.tsindex c20a1d02ce..1dd84325f8 100644--- a/apps/web/src/features/next-soup/utils.ts+++ b/apps/web/src/features/next-soup/utils.ts@@ -12,8 +12,10 @@ import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/constants';import type {ReferredFrom,+ SplitContent,SplitHandle,} from '@components/app/split-layout/layoutManager';+import { toast } from '@core/component/Toast/Toast';import { fileTypeToBlockName } from '@core/constant/allBlocks';import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';import {@@ -30,6 +32,7 @@ import {type EntityData,emailQueryKeyExcludesDone,getSnippetHit,+ isChannelEntity,isEmailEntity,isGithubPrEntity,isHitSnippetEntity,@@ -70,6 +73,7 @@ import {import { emailClient } from '@service-email/client';import { isAfter } from 'date-fns';import { match } from 'ts-pattern';+import { withPreviewSourceEntityId } from './preview-history';const mergeSearchEntities = <T extends EntityData>(first: WithSearch<T>,@@ -289,23 +293,15 @@ export const openEntityInNewTab = ({* like 'escape' won't work.** @param entityId - Optional entity ID to focus on. If not provided, focuses the first entity in the list.- * @param inPreview - Whether to check for the soup view in a preview panel*/-export const restoreSoupFocus = async (- entityId?: string,- inPreview = false-): Promise<void> => {+export const restoreSoupFocus = async (entityId?: string): Promise<void> => {// Get the active split's soup view DOM referenceconst activeSplitId = globalSplitManager()?.activeSplitId();if (!activeSplitId) return;- let domRef = document.querySelector(`[data-soup-view-id="${activeSplitId}"]`);-- if (inPreview) {- domRef = document.querySelector(- `[data-soup-view-id="${activeSplitId}-preview"]`- );- }+ const domRef = document.querySelector(+ `[data-soup-view-id="${activeSplitId}"]`+ );if (!(domRef instanceof HTMLElement)) return;@@ -341,6 +337,37 @@ interface OpenEntityOptions {referredFrom?: ReferredFrom;}+const DUPLICATE_CONTENT_MESSAGE = 'Content already open.';++/** Whether this entity is open outside the controller's own preview viewer. */+export function isDuplicatePreviewEntityOpen(+ entity: EntityData,+ controller: SplitHandle+): boolean {+ const splitManager = globalSplitManager();+ const viewerId = controller.viewerId();+ if (!splitManager || !viewerId) return false;++ const content = getEntitySplitContent(entity);+ const existing = splitManager.getSplitByContent(content.type, content.id);+ return existing !== undefined && existing.id !== viewerId;+}++/** Show the standard duplicate-content notification. */+export function notifyDuplicateContentOpen() {+ toast.alert(DUPLICATE_CONTENT_MESSAGE);+}++/** Reject and notify for an entity already owned by another split. */+export function preventDuplicatePreviewEntityOpen(+ entity: EntityData,+ controller: SplitHandle+): boolean {+ if (!isDuplicatePreviewEntityOpen(entity, controller)) return false;+ notifyDuplicateContentOpen();+ return true;+}+/*** Resolve which channel message to activate when a channel row is opened.*@@ -500,9 +527,31 @@ export const openEntityInSplitFromUnifiedList = async (return;}- // Channels the viewer hasn't joined can't be read; the row's Join button is+ // Channels the viewer hasn't joined can't be read. In a Preview Pair, offer+ // the Join prompt in the Viewer; otherwise the row's inline Join button is// the only affordance.- if (isNonMemberChannelEntity(entity)) return;+ if (isNonMemberChannelEntity(entity)) {+ if (isChannelEntity(entity) && splitHandle?.isControllerSplit()) {+ const joinPromptContent = withPreviewSourceEntityId(+ {+ type: 'component',+ id: 'non-member-channel',+ params: {+ channelId: entity.id,+ channelName: entity.name,+ memberCount: entity.participantIds?.length ?? 0,+ },+ },+ entity.id+ );+ splitManager.openWithSplit(joinPromptContent, {+ referredFrom: options.referredFrom,+ activate: true,+ handle: splitHandle,+ });+ }+ return;+ }if (isGithubPrEntity(entity)) {if (USE_MACRO_PR_SUMMARY_BLOCK) {@@ -527,6 +576,15 @@ export const openEntityInSplitFromUnifiedList = async (const content = getEntitySplitContent(entity);+ if (+ !allowDuplicate &&+ !openInNewSplit &&+ splitHandle &&+ preventDuplicatePreviewEntityOpen(entity, splitHandle)+ ) {+ return;+ }+const channelTarget = getChannelEntityTarget(entity);const channelMessageTarget =channelTarget?.kind === 'message' ? channelTarget : undefined;@@ -553,21 +611,23 @@ export const openEntityInSplitFromUnifiedList = async (: undefined;const referredFrom = options.referredFrom ?? sourceListView;- splitManager.openWithSplit(- { ...content, params },- {- referredFrom,- activate: true,- preferNewSplit: openInNewSplit,- handle: splitHandle,- mergeHistory,- allowDuplicate,- reopen:- entity.type === 'channel' && !location && openChannelAtLatest- ? 'latest'- : undefined,- }- );+ let splitContent: SplitContent = { ...content, params };+ if (splitHandle?.isControllerSplit()) {+ splitContent = withPreviewSourceEntityId(splitContent, entity.id);+ }++ splitManager.openWithSplit(splitContent, {+ referredFrom,+ activate: true,+ preferNewSplit: openInNewSplit,+ handle: splitHandle,+ mergeHistory,+ allowDuplicate,+ reopen:+ entity.type === 'channel' && !location && openChannelAtLatest+ ? 'latest'+ : undefined,+ });// Navigate to specific location if providedif (location) {diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.tsindex 7444940e9b..f197993018 100644--- a/apps/web/src/features/notifications/notification-navigation.ts+++ b/apps/web/src/features/notifications/notification-navigation.ts@@ -4,7 +4,10 @@ import {} from '@block-channel/utils/link';import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';-import type { SplitManager } from '@components/app/split-layout/layoutManager';+import type {+ SplitHandle,+ SplitManager,+} from '@components/app/split-layout/layoutManager';import type { BlockAlias, BlockName } from '@core/block';import {type ItemLike,@@ -43,17 +46,27 @@ async function goToLocationInSplit(}/**- * Opens a split if it is not already open.+ * Opens a split if it is not already open. When `sourceHandle` names the+ * split the navigation originates from and that split is an engaged preview+ * controller, the open is redirected into its viewer split (via the+ * openWithSplit redirect) and never steals the keyboard from the controller.*/function openSplitIfNotOpen(layoutManager: SplitManager,type: BlockName | BlockAlias | 'component',id: string,- options: { newSplit?: boolean; params?: Record<string, string> } = {}+ options: {+ newSplit?: boolean;+ params?: Record<string, string>;+ sourceHandle?: SplitHandle;+ } = {}) {const existing = layoutManager.getSplitByContent(type, id);if (existing) {- existing.activate();+ const isSourcesViewer =+ options.sourceHandle?.isControllerSplit() &&+ options.sourceHandle.viewerId() === existing.id;+ if (!isSourcesViewer) existing.activate();} else {layoutManager.openWithSplit({ type, id },@@ -61,6 +74,7 @@ function openSplitIfNotOpen(activate: true,referredFrom: null,preferNewSplit: options.newSplit,+ handle: options.sourceHandle,});}@@ -100,13 +114,17 @@ export function getChannelNotificationParams(async function openChannelNotification(notification: UnifiedNotification,layoutManager: SplitManager,- newSplit: boolean = false+ newSplit: boolean = false,+ sourceHandle?: SplitHandle) {const channelId = notification.entity_id;const { messageId, threadId } = getChannelNotificationParams(notification);if (!messageId) {- openSplitIfNotOpen(layoutManager, 'channel', channelId, { newSplit });+ openSplitIfNotOpen(layoutManager, 'channel', channelId, {+ newSplit,+ sourceHandle,+ });return;}@@ -114,6 +132,7 @@ async function openChannelNotification(await navigateToChannelMessage(orchestrator, channelId, messageId, threadId, {splitManager: layoutManager,preferNewSplit: newSplit,+ sourceHandle,});}@@ -160,7 +179,8 @@ type OpenNotificationFromIdError = NotSupportedError | NotFoundError;function getSupportedHandler(notification: UnifiedNotification,- entity?: NotificationEntityOverride+ entity?: NotificationEntityOverride,+ sourceHandle?: SplitHandle): ((layoutManager: SplitManager, newSplit?: boolean) => Promise<void>) | null {const tag = notification.notification_metadata.tag as NotificationType;@@ -169,19 +189,25 @@ function getSupportedHandler(P.union(...CHANNEL_EVENT_TYPES),() =>(lm: SplitManager, newSplit: boolean = false) =>- openChannelNotification(notification, lm, newSplit)+ openChannelNotification(notification, lm, newSplit, sourceHandle)).with('ai_response',() =>async (lm: SplitManager, newSplit: boolean = false) =>- openSplitIfNotOpen(lm, 'chat', notification.entity_id, { newSplit })+ openSplitIfNotOpen(lm, 'chat', notification.entity_id, {+ newSplit,+ sourceHandle,+ })).with('new_email', () => {const meta = notification.notification_metadata;if (meta.tag !== 'new_email') return null;return async (lm: SplitManager, newSplit: boolean = false) => {- openSplitIfNotOpen(lm, 'email', meta.content.threadId, { newSplit });+ openSplitIfNotOpen(lm, 'email', meta.content.threadId, {+ newSplit,+ sourceHandle,+ });};}).with(@@ -190,6 +216,7 @@ function getSupportedHandler(async (lm: SplitManager, newSplit: boolean = false) =>openSplitIfNotOpen(lm, 'channel', notification.entity_id, {newSplit,+ sourceHandle,})).with('document_mention', () => {@@ -214,6 +241,7 @@ function getSupportedHandler({splitManager: lm,preferNewSplit: newSplit,+ sourceHandle,});return;@@ -221,6 +249,7 @@ function getSupportedHandler(openSplitIfNotOpen(lm, 'channel', notification.entity_id, {newSplit,+ sourceHandle,});};})@@ -231,13 +260,17 @@ function getSupportedHandler(async (lm: SplitManager, newSplit: boolean = false) =>openSplitIfNotOpen(lm, 'channel', notification.entity_id, {newSplit,+ sourceHandle,})).with('task_assigned', () => {const meta = notification.notification_metadata;if (meta.tag !== 'task_assigned') return null;return async (lm: SplitManager, newSplit: boolean = false) => {- openSplitIfNotOpen(lm, 'task', meta.content.taskId, { newSplit });+ openSplitIfNotOpen(lm, 'task', meta.content.taskId, {+ newSplit,+ sourceHandle,+ });};}).with(P.union(...GITHUB_EVENT_TYPES), () => {@@ -254,7 +287,10 @@ function getSupportedHandler(}return async (lm: SplitManager, newSplit: boolean = false) => {if (USE_MACRO_PR_SUMMARY_BLOCK) {- openSplitIfNotOpen(lm, 'pr', notification.entity_id, { newSplit });+ openSplitIfNotOpen(lm, 'pr', notification.entity_id, {+ newSplit,+ sourceHandle,+ });return;}@@ -282,6 +318,7 @@ function getSupportedHandler(openSplitIfNotOpen(lm, blockName, notification.entity_id, {newSplit,params,+ sourceHandle,});}).with('replied_to_document_comment_thread', () => {@@ -300,6 +337,7 @@ function getSupportedHandler(openSplitIfNotOpen(lm, blockName, notification.entity_id, {newSplit,params,+ sourceHandle,});}).with('commented_on_document', () => {@@ -318,6 +356,7 @@ function getSupportedHandler(openSplitIfNotOpen(lm, blockName, notification.entity_id, {newSplit,params,+ sourceHandle,});}).with('inbox_reauth_required', () => null)@@ -332,9 +371,15 @@ export function openNotification(notification: UnifiedNotification,layoutManager: SplitManager,newSplit: boolean = false,- entity?: NotificationEntityOverride+ entity?: NotificationEntityOverride,+ /**+ * The split this navigation originates from (e.g. the list whose row was+ * clicked). Routes the open through that split's preview viewer when its+ * preview mode is engaged.+ */+ sourceHandle?: SplitHandle): ResultAsync<void, NotSupportedError> {- const handler = getSupportedHandler(notification, entity);+ const handler = getSupportedHandler(notification, entity, sourceHandle);if (!handler) {return errAsync({tag: 'NotSupportedError',@@ -347,12 +392,19 @@ export function openNotification(export function openSingleStackNotification(notifications: UnifiedNotification[],layoutManager: SplitManager,- newSplit: boolean = false+ newSplit: boolean = false,+ sourceHandle?: SplitHandle): boolean {const stacks = stackNotifications(notifications);if (stacks.length !== 1) return false;const mostRecent = getMostRecentNotification(stacks[0]!);- openNotification(mostRecent, layoutManager, newSplit);+ openNotification(+ mostRecent,+ layoutManager,+ newSplit,+ undefined,+ sourceHandle+ );return true;}diff --git a/apps/web/src/lib/core/component/Resize/Resize.tsx b/apps/web/src/lib/core/component/Resize/Resize.tsxindex de44a04fb3..cd31dd0e81 100644--- a/apps/web/src/lib/core/component/Resize/Resize.tsx+++ b/apps/web/src/lib/core/component/Resize/Resize.tsx@@ -103,7 +103,14 @@ function Zone(props: ParentProps<ZoneProps>) {solver.dropPanel(id);}- function update(id: PanelId, config: { minSize?: number; maxSize?: number }) {+ function update(+ id: PanelId,+ config: {+ minSize?: number;+ maxSize?: number;+ redistributionPreferredSize?: number;+ }+ ) {solver.updatePanel(id, config);}@@ -189,6 +196,9 @@ function Zone(props: ParentProps<ZoneProps>) {* @property id - Unique identifier for the panel* @property minSize - Minimum size constraint for the panel in pixels* @property maxSize - Maximum size constraint for the panel in pixels (defaults to Infinity)+ * @property redistributionPreferredSize - Preferred size used only during+ * automatic layout redistribution. It is reduced when neighboring panel+ * minimums leave insufficient room.* @property collapsed - Accessor that returns whether the panel should be collapsed. This* is currently kind of COPE and should be avoided. Is used for the side-bar which should* be toggled without being unmounted. It is WAY preferred to let the system derive its@@ -202,6 +212,7 @@ type PanelProps = {id: PanelId;minSize: number;maxSize?: number;+ redistributionPreferredSize?: number;/*** Initial target size for the panel at registration time.* - number: interpreted as a percentage (e.g., 25 = 25%)@@ -268,6 +279,7 @@ function Panel(props: ParentProps<PanelProps>) {id: props.id,minSize: props.minSize,maxSize: props.maxSize ?? Infinity,+ redistributionPreferredSize: props.redistributionPreferredSize,target: getTarget(),},props.index@@ -279,6 +291,7 @@ function Panel(props: ParentProps<PanelProps>) {ctx.update(props.id, {minSize: props.minSize,maxSize: props.maxSize ?? Infinity,+ redistributionPreferredSize: props.redistributionPreferredSize,});});@@ -293,6 +306,7 @@ function Panel(props: ParentProps<PanelProps>) {id: props.id,minSize: props.minSize,maxSize: props.maxSize ?? Infinity,+ redistributionPreferredSize: props.redistributionPreferredSize,target: getTarget(),},props.index@@ -319,6 +333,7 @@ function Panel(props: ParentProps<PanelProps>) {id: props.id,minSize: props.minSize,maxSize: props.maxSize ?? Infinity,+ redistributionPreferredSize: props.redistributionPreferredSize,target: getTarget(),},props.indexdiff --git a/apps/web/src/lib/core/component/Resize/solver.test.ts b/apps/web/src/lib/core/component/Resize/solver.test.tsindex a591ae2b63..75046bc0c4 100644--- a/apps/web/src/lib/core/component/Resize/solver.test.ts+++ b/apps/web/src/lib/core/component/Resize/solver.test.ts@@ -1,4 +1,4 @@-import { createRoot } from 'solid-js';+import { createRoot, createSignal } from 'solid-js';import { describe, expect, it } from 'vitest';import { createResizeSolver } from './solver';@@ -81,4 +81,137 @@ describe('createResizeSolver', () => {});});});++ describe('redistributionPreferredSize', () => {+ it('waits until another panel can absorb the redistributed space', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 8,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'controller', minSize: 100 });+ solver.updatePanel('controller', {+ redistributionPreferredSize: 440,+ });+ expect(solver.solve().sizes.get('controller')).toBe(1600);++ solver.addPanel({ id: 'viewer', minSize: 100 });+ expect(solver.solve().sizes.get('controller')).toBe(440);++ dispose();+ });++ it('restores the preference after automatic redistribution without constraining manual resizing', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 8,+ size: () => 1600,+ panels: [],+ }),+ }));++ // createEffect performs its initial solve after the root body.+ await Promise.resolve();++ solver.addPanel({ id: 'controller', minSize: 100 });+ solver.addPanel({ id: 'viewer', minSize: 100 });+ solver.addPanel({ id: 'adjacent', minSize: 100 });+ solver.updatePanel('controller', { redistributionPreferredSize: 440 });++ expect(solver.solve().sizes.get('controller')).toBe(440);++ solver.moveHandle(0, 160);+ expect(solver.solve().sizes.get('controller')).toBe(600);++ solver.dropPanel('adjacent');+ expect(solver.solve().sizes.get('controller')).toBe(440);++ dispose();+ });++ it('grows beyond an equal share when the preferred size fits', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 8,+ size: () => 2000,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'controller', minSize: 400 });+ solver.updatePanel('controller', {+ redistributionPreferredSize: 1200,+ });+ solver.addPanel({ id: 'viewer', minSize: 400 });++ expect(solver.solve().sizes.get('controller')).toBe(1200);++ solver.moveHandle(0, 100);+ expect(solver.solve().sizes.get('controller')).toBe(1300);++ dispose();+ });++ it('yields to the neighboring panel minimum', async () => {+ const { solver, dispose } = createRoot((dispose) => ({+ dispose,+ solver: createResizeSolver({+ direction: 'horizontal',+ gutter: () => 8,+ size: () => 1600,+ panels: [],+ }),+ }));++ await Promise.resolve();++ solver.addPanel({ id: 'controller', minSize: 400 });+ solver.updatePanel('controller', {+ redistributionPreferredSize: 1200,+ });+ solver.addPanel({ id: 'viewer', minSize: 400 });++ expect(solver.solve().sizes.get('controller')).toBe(1192);+ expect(solver.solve().sizes.get('viewer')).toBe(400);++ dispose();+ });+ });++ describe('canFitPanel', () => {+ it('accounts for the gutter added by the candidate panel', () => {+ createRoot((dispose) => {+ const [size, setSize] = createSignal(1215);+ const solver = createResizeSolver({+ direction: 'horizontal',+ gutter: () => 8,+ size,+ panels: [+ { id: 'A', minSize: 400 },+ { id: 'B', minSize: 400 },+ ],+ });++ expect(solver.canFitPanel({ id: 'C', minSize: 400 })).toBe(false);++ setSize(1216);+ expect(solver.canFitPanel({ id: 'C', minSize: 400 })).toBe(true);++ dispose();+ });+ });+ });});diff --git a/apps/web/src/lib/core/component/Resize/solver.ts b/apps/web/src/lib/core/component/Resize/solver.tsindex 2f6d069a26..ece53eee7c 100644--- a/apps/web/src/lib/core/component/Resize/solver.ts+++ b/apps/web/src/lib/core/component/Resize/solver.ts@@ -14,7 +14,11 @@ type ResizeSolver = {dropPanel: (id: PanelId) => void;updatePanel: (id: PanelId,- config: { minSize?: number; maxSize?: number }+ config: {+ minSize?: number;+ maxSize?: number;+ redistributionPreferredSize?: number;+ }) => void;solve: () => LayoutResult;reset: () => void;@@ -154,6 +158,71 @@ function initPanel(panel: PanelConfig): Panel {};}+/**+ * Pin automatic-layout preferences when the remaining panels can absorb the+ * leftover space. Preferences yield to every panel's minimum size, while+ * manual resize solves ignore them entirely.+ */+function applyRedistributionPreferences(+ panels: Panel[],+ usable: number+): Panel[] {+ if (usable <= 0) return panels;++ const preferredPanels = panels.flatMap((panel) => {+ const preferred = panel.redistributionPreferredSize;+ if (preferred === undefined || !Number.isFinite(preferred)) return [];+ const size = Math.min(Math.max(preferred, panel.minSize), panel.maxSize);+ return [{ panel, size }];+ });+ if (preferredPanels.length === 0) return panels;++ const preferredIds = new Set(preferredPanels.map(({ panel }) => panel.id));+ const remainingPanels = panels.filter((panel) => !preferredIds.has(panel.id));+ const remainingMin = sumArray(remainingPanels.map((panel) => panel.minSize));+ const availableForPreferred = usable - remainingMin;+ const preferredMin = sumArray(+ preferredPanels.map(({ panel }) => panel.minSize)+ );+ if (availableForPreferred + EPSILON < preferredMin) return panels;++ const preferredTotal = sumArray(preferredPanels.map(({ size }) => size));+ const overflow = Math.max(0, preferredTotal - availableForPreferred);+ if (overflow > 0) {+ const shrinkable = sumArray(+ preferredPanels.map(({ panel, size }) => size - panel.minSize)+ );+ if (shrinkable > 0) {+ for (const target of preferredPanels) {+ const room = target.size - target.panel.minSize;+ target.size -= overflow * (room / shrinkable);+ }+ }+ }++ const resolvedPreferredTotal = sumArray(+ preferredPanels.map(({ size }) => size)+ );+ const remainingMax = sumArray(remainingPanels.map((panel) => panel.maxSize));+ // Avoid leaving a gap when no other panel can absorb the remaining space.+ if (resolvedPreferredTotal + remainingMax + EPSILON < usable) return panels;++ const preferredSizeById = new Map(+ preferredPanels.map(({ panel, size }) => [panel.id, size])+ );+ return panels.map((panel) => {+ const preferred = preferredSizeById.get(panel.id);+ return preferred === undefined+ ? panel+ : {+ ...panel,+ minSize: preferred,+ maxSize: preferred,+ share: preferred / usable,+ };+ });+}+/*** Create the internal-hiding business logic for a resize Zone.* @param params@@ -178,7 +247,11 @@ export function createResizeSolver(params: {// counter manually manages reactivity, rather than a store on panel data -// whose side effects become a pain.const [counter, setCounter] = createSignal(0);- const setDirty = () => setCounter((p) => p + 1);+ let nextSolveKind: 'automatic' | 'manual' = 'automatic';+ const setDirty = (kind: 'automatic' | 'manual' = 'automatic') => {+ nextSolveKind = kind;+ setCounter((p) => p + 1);+ };const panelsInOrder = () => {counter(); // deps@@ -206,18 +279,29 @@ export function createResizeSolver(params: {// the solve on dependencies effectcreateEffect(() => {const ps = panelsInOrder();+ const solveKind = nextSolveKind;+ nextSolveKind = 'automatic';++ const usable = getUsable(ps.length, params.size(), params.gutter());+ const solvePanels =+ solveKind === 'automatic'+ ? applyRedistributionPreferences(ps, usable)+ : ps;// run the solve to get pixel values- const solve = computeFractionalShares(ps, params.size(), params.gutter());+ const solve = computeFractionalShares(+ solvePanels,+ params.size(),+ params.gutter()+ );// basically update the float share values to match the actual pixel sizes returned by the solve.const ids = order();const n = ids.length;- const usable = getUsable(n, params.size(), params.gutter());if (usable > 0 && n > 0) {const clampedPx = ids.map((id) => solve.sizes.get(id) ?? 0);- const mins = ps.map((p) => p.minSize ?? 0);- const maxs = ps.map((p) => p.maxSize ?? Infinity);+ const mins = solvePanels.map((p) => p.minSize ?? 0);+ const maxs = solvePanels.map((p) => p.maxSize ?? Infinity);const free: number[] = [];const clamped: number[] = [];@@ -321,7 +405,11 @@ export function createResizeSolver(params: {function updatePanel(id: PanelId,- config: { minSize?: number; maxSize?: number }+ config: {+ minSize?: number;+ maxSize?: number;+ redistributionPreferredSize?: number;+ }) {const panel = panelData[id];if (!panel) return;@@ -340,6 +428,13 @@ export function createResizeSolver(params: {changed = true;}}+ if ('redistributionPreferredSize' in config) {+ const next = config.redistributionPreferredSize;+ if (panel.redistributionPreferredSize !== next) {+ panel.redistributionPreferredSize = next;+ changed = true;+ }+ }if (changed) setDirty();}@@ -485,7 +580,7 @@ export function createResizeSolver(params: {}}- setDirty();+ setDirty('manual');}return {@@ -510,7 +605,7 @@ export function createResizeSolver(params: {canFitPanel: (panel: PanelConfig) => {const currentPanels = panelsInOrder();const n = currentPanels.length;- const usable = getUsable(n, params.size(), params.gutter());+ const usable = getUsable(n + 1, params.size(), params.gutter());if (usable <= 0) return false;const minSum = sumArray(currentPanels.map((p) => p.minSize ?? 0));const totalMinRequired = minSum + (panel.minSize ?? 0);diff --git a/apps/web/src/lib/core/component/Resize/types.ts b/apps/web/src/lib/core/component/Resize/types.tsindex 8869edd9ba..f2d3303ce2 100644--- a/apps/web/src/lib/core/component/Resize/types.ts+++ b/apps/web/src/lib/core/component/Resize/types.ts@@ -17,6 +17,7 @@ export type Panel = {id: PanelId;minSize: number;maxSize: number;+ redistributionPreferredSize?: number;share: number;target: PanelSizeSpec;};@@ -25,6 +26,7 @@ export type PanelConfig = {id: PanelId;minSize?: number;maxSize?: number;+ redistributionPreferredSize?: number;target?: PanelSizeSpec;};@@ -38,7 +40,14 @@ export type ResizeZoneCtx = {direction: Accessor<'horizontal' | 'vertical'>;register: (panel: PanelConfig, index?: number) => void;unregister: (id: PanelId) => void;- update: (id: PanelId, config: { minSize?: number; maxSize?: number }) => void;+ update: (+ id: PanelId,+ config: {+ minSize?: number;+ maxSize?: number;+ redistributionPreferredSize?: number;+ }+ ) => void;gutterSize: () => number;size: () => number;sizeOf: (id: PanelId) => () => number;diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 2b9d7ca500..f5e269285d 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -288,12 +288,6 @@ const _ENABLE_SOUP_FROM_FILTER = resolveFeatureFlag(false);-export const ENABLE_PREVIEW = resolveFeatureFlag('ENABLE_PREVIEW', true);-export const ENABLE_PROJECT_VIEW_PREVIEW = resolveFeatureFlag(- 'ENABLE_PROJECT_VIEW_PREVIEW',- true-);-const _ENABLE_DOCK_NOTITIFCATIONS = resolveFeatureFlag('ENABLE_DOCK_NOTITIFCATIONS',DEV_MODE_ENVdiff --git a/apps/web/src/lib/core/context/blockOpenTracking.ts b/apps/web/src/lib/core/context/blockOpenTracking.tsnew file mode 100644index 0000000000..061169fc69--- /dev/null+++ b/apps/web/src/lib/core/context/blockOpenTracking.ts@@ -0,0 +1,8 @@+import { createContext } from 'solid-js';++/**+ * Delay before a mounted block is recorded as opened. Presentation layers may+ * provide a delay for passively displayed content; ordinary blocks default to+ * immediate tracking.+ */+export const BlockOpenTrackingDelayContext = createContext(0);diff --git a/apps/web/src/lib/core/internal/BlockLoader.tsx b/apps/web/src/lib/core/internal/BlockLoader.tsxindex e7d7b9596e..8626f9d81a 100644--- a/apps/web/src/lib/core/internal/BlockLoader.tsx+++ b/apps/web/src/lib/core/internal/BlockLoader.tsx@@ -1,5 +1,4 @@import { useAnalytics } from '@app/lib/analytics/analytics-context';-import { SplitPanelContext } from '@components/app/split-layout/context';import type { OwnedBlockHandle } from '@core/orchestrator';import { useQueryClient } from '@queries/client';import type { AccessLevel as UserAccessLevel } from '@service-storage/generated/schemas/accessLevel';@@ -14,6 +13,7 @@ import {type LoadFunction,useIsNestedBlock,} from '../block';+import { BlockOpenTrackingDelayContext } from '../context/blockOpenTracking';import {blockEditPermissionEnabledSignal,blockErrorSignal,@@ -64,9 +64,9 @@ export function BlockLoader<const setEditPermissionEnabled = blockEditPermissionEnabledSignal.set;const setHandle = blockHandleSignal.set;const isNested = useIsNestedBlock();- const splitPanelContext = useContext(SplitPanelContext);- // NOTE: not reactive but PreviewPanel component manually creates a true signal for the context provider- const isPreview = splitPanelContext?.previewState?.[0]() ?? false;+ // Snapshot at mount so later presentation changes do not alter how an+ // already-mounted block is tracked.+ const openTrackingDelayMs = useContext(BlockOpenTrackingDelayContext);const analytics = useAnalytics();setLiveTrackingEnabled(props.definition.liveTrackingEnabled ?? false);@@ -105,8 +105,14 @@ Check that the load function does not return a preload source when the intent is}});+ let openTrackTimer: ReturnType<typeof setTimeout> | undefined;+ onCleanup(() => clearTimeout(openTrackTimer));+createEffect(() => {const result = getResult();+ // Any content change supersedes a still-pending "opened" track.+ clearTimeout(openTrackTimer);+if (!result) {setData(undefined);setFile(undefined);@@ -138,21 +144,29 @@ Check that the load function does not return a preload source when the intent isconst data = result.value;setError(null);- if (!isNested && !isPreview && data) {- // we need to pass in a client accessor since the mutation is dynamically imported outside a query context provider- import('./trackBlockOpened').then(({ track }) => {- track({- itemId: props.id,- blockName: data.__block,- client: useQueryClient,+ if (!isNested && data) {+ const trackOpened = () => {+ // we need to pass in a client accessor since the mutation is dynamically imported outside a query context provider+ import('./trackBlockOpened').then(({ track }) => {+ track({+ itemId: props.id,+ blockName: data.__block,+ client: useQueryClient,+ });});- });- analytics.pageView(data.__block);- analytics.track('open_entity', {- entityType: data.__block,- entityId: props.id,- });+ analytics.pageView(data.__block);+ analytics.track('open_entity', {+ entityType: data.__block,+ entityId: props.id,+ });+ };++ if (openTrackingDelayMs > 0) {+ openTrackTimer = setTimeout(trackOpened, openTrackingDelayMs);+ } else {+ trackOpened();+ }}setData(() => data);