Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(web): adopt standalone split router across the application (#6728)

dev-rb726a3dc03369
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index beb8390741..5c275707e5 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -1724,7 +1724,7 @@ type SidebarOpenAction = 'current-split' | 'new-split' | 'fullscreen';
interface SidebarOpenInSplitMenuProps {
/** The content the menu's actions open. */
- content: () => SplitContent;
+ content?: () => SplitContent;
/**
* Runs once an action has placed the content in a split — e.g. the Email
* account rows scope the freshly opened mail list to their inbox.
@@ -1732,6 +1732,7 @@ interface SidebarOpenInSplitMenuProps {
onOpened?: (split: SplitHandle, action: SidebarOpenAction) => void;
/** View-owned navigation for rows that select a location inside this split. */
onOpenCurrentSplit?: () => void;
+ onOpenNewSplit?: () => void;
onOpenFullscreen?: () => void;
onOpenChange?: (open: boolean) => void;
/**
@@ -1762,6 +1763,8 @@ export const SidebarOpenInSplitMenu = (props: SidebarOpenInSplitMenuProps) => {
props.onOpenCurrentSplit();
return;
}
+ if (!props.content) return;
+
const result = layout.openWithSplit(props.content(), {
allowDuplicate: true,
mergeHistory: false,
@@ -1780,6 +1783,13 @@ export const SidebarOpenInSplitMenu = (props: SidebarOpenInSplitMenuProps) => {
analytics.track('split_created', { from: 'sidebar' });
+ if (props.onOpenNewSplit) {
+ props.onOpenNewSplit();
+ return;
+ }
+
+ if (!props.content) return;
+
const result = manager.openWithSplit(props.content(), {
activate: true,
allowDuplicate: true,
@@ -1800,6 +1810,9 @@ export const SidebarOpenInSplitMenu = (props: SidebarOpenInSplitMenuProps) => {
globalSplitManager()?.returnFocus();
return;
}
+
+ if (!props.content) return;
+
const split = layout.replaceAllSplits(props.content(), {
referredFrom: 'sidebar',
});
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index 4e6421c511..a3c3a56d98 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -1,3 +1,11 @@
+import {
+ createRoutesManifest,
+ createSolidRouterLocation,
+ decodeRouteLayout,
+ SplitRouter,
+ type SplitRouterMiddleware,
+ type SplitRoutes,
+} from '@app/lib/split-router';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import { Resize } from '@core/component/Resize';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
@@ -22,27 +30,40 @@ import {
type SplitId,
type SplitManager,
} from './layoutManager';
-import { createLayoutUrlSync } from './layoutUrlSync';
-import { decodePairs } from './layoutUtils';
import {
createMobileSwipeLayout,
type MobileSwipeLayout,
} from './mobile/createMobileSwipeLayout';
import { MobileSplitContainer } from './mobile/MobileSplitContainer';
+import { splitContentFromLocation } from './split-router/legacy-route';
import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
import { createSplitFocusTracker } from './splitFocusTracker';
+import { createAppSplitRouterLayout } from './splitRouterLayout';
type SplitLayoutContainerProps = {
pairs: string[];
+ routes: SplitRoutes;
+ middleware?: readonly SplitRouterMiddleware[];
setManager: Setter<SplitManager | undefined>;
};
export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
const location = useLocation();
const navigate = useNavigate();
- const initialContents = decodePairs(props.pairs);
+ // Bootstrap the legacy layout with the same local state adopted by the router.
+ const routes = createRoutesManifest(props.routes);
+ const initialContents = decodeRouteLayout(routes, props.pairs).map((entry) =>
+ splitContentFromLocation(entry.location)
+ );
const blockOrchestrator = useGlobalBlockOrchestrator();
const splitManager = createSplitLayout(blockOrchestrator, initialContents);
+ const routerLayout = createAppSplitRouterLayout(splitManager, routes);
+ const externalLocation = createSolidRouterLocation({
+ pathname: () => `/${props.pairs.join('/')}`,
+ search: () => location.search,
+ hash: () => location.hash,
+ navigate,
+ });
const [, setTabTitle] = tabTitleSignal;
// Create the mobile swipe layout once on mobile devices.
@@ -59,7 +80,7 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
// Drop refs for departed splits by reconciling against the live list:
// batched mutations can remove several splits in one flush (e.g. closing
- // multiple splits), and the events signal only surfaces the last event.
+ // a Preview Pair), and the events signal only surfaces the last event.
createEffect(() => {
const alive = new Set(splits().map(({ id }) => id));
for (const id of panelRefs.keys()) {
@@ -69,10 +90,6 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
const activeSplitSelector = createSelector(splitManager.activeSplitId);
- createEffect(() => props.setManager(splitManager));
-
- onCleanup(() => props.setManager(undefined));
-
createEffect(() => {
setTabTitle(splitManager.tabTitle());
});
@@ -80,70 +97,78 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
// <For> on plain ids for stable referential equality
const ids = createMemo(() => splits().map(({ id }) => id));
- createLayoutUrlSync(splitManager, () => props.pairs, {
- navigate,
- search: () => location.search,
- });
createSplitFocusTracker({ splitManager, panelRefs, splits });
+ createEffect(() => props.setManager(splitManager));
+ onCleanup(() => props.setManager(undefined));
return (
- <SplitLayoutContext.Provider value={{ manager: splitManager }}>
- <div class="size-full" classList={{ 'py-1.5 pr-1.5': useBentoLayout() }}>
- <Show
- when={isNativeMobilePlatform() && mobileSwipeLayout}
- fallback={
- // Desktop: side-by-side resizable splits.
- <Resize.Zone
- direction="horizontal"
- gutter={useBentoLayout() ? 6 : 1}
- showDividers={!useBentoLayout()}
- captureResizeCtx={splitManager.setResizeContext}
- >
- <For each={ids()}>
- {(id, index) => (
- <Show when={splitManager.getSplit(id)}>
- {(handle) => (
- <Suspense>
- <Resize.Panel
- id={id}
- minSize={DEFAULT_SPLIT_MIN_WIDTH}
- index={index()}
- >
- <SplitPanel
- split={splits()[index()]!}
- handle={handle()}
- active={activeSplitSelector(id)}
- setPanelRef={(panelRef) =>
- panelRefs.set(id, panelRef)
- }
- index={index()}
- />
- </Resize.Panel>
- </Suspense>
- )}
- </Show>
- )}
- </For>
- </Resize.Zone>
- }
+ <SplitRouter.Root
+ layout={routerLayout}
+ routes={routes}
+ location={externalLocation}
+ middleware={props.middleware}
+ >
+ <SplitLayoutContext.Provider value={{ manager: splitManager }}>
+ <div
+ class="size-full"
+ classList={{ 'py-1.5 pr-1.5': useBentoLayout() }}
>
- {/* Mobile: stacked FG/BG layout with swipe-back gesture. */}
- <MobileSplitContainer
- splitManager={splitManager}
- mobileSwipeLayout={mobileSwipeLayout!}
- splits={splits}
- panelRefs={panelRefs}
- />
- </Show>
- </div>
- <PopoverSplitRenderer
- popovers={splitManager.popovers}
- onClosePopover={(id) => {
- const activePopovers = splitManager.getActivePopovers();
- const popover = activePopovers.find((p) => p.id === id);
- popover?.close();
- }}
- />
- </SplitLayoutContext.Provider>
+ <Show
+ when={isNativeMobilePlatform() && mobileSwipeLayout}
+ fallback={
+ // Desktop: side-by-side resizable splits.
+ <Resize.Zone
+ direction="horizontal"
+ gutter={useBentoLayout() ? 6 : 1}
+ showDividers={!useBentoLayout()}
+ captureResizeCtx={splitManager.setResizeContext}
+ >
+ <For each={ids()}>
+ {(id, index) => (
+ <Show when={splitManager.getSplit(id)}>
+ {(handle) => (
+ <Suspense>
+ <Resize.Panel
+ id={id}
+ minSize={DEFAULT_SPLIT_MIN_WIDTH}
+ index={index()}
+ >
+ <SplitPanel
+ split={splits()[index()]!}
+ handle={handle()}
+ active={activeSplitSelector(id)}
+ setPanelRef={(panelRef) =>
+ panelRefs.set(id, panelRef)
+ }
+ index={index()}
+ />
+ </Resize.Panel>
+ </Suspense>
+ )}
+ </Show>
+ )}
+ </For>
+ </Resize.Zone>
+ }
+ >
+ {/* Mobile: stacked FG/BG layout with swipe-back gesture. */}
+ <MobileSplitContainer
+ splitManager={splitManager}
+ mobileSwipeLayout={mobileSwipeLayout!}
+ splits={splits}
+ panelRefs={panelRefs}
+ />
+ </Show>
+ </div>
+ <PopoverSplitRenderer
+ popovers={splitManager.popovers}
+ onClosePopover={(id) => {
+ const activePopovers = splitManager.getActivePopovers();
+ const popover = activePopovers.find((p) => p.id === id);
+ popover?.close();
+ }}
+ />
+ </SplitLayoutContext.Provider>
+ </SplitRouter.Root>
);
}
diff --git a/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx b/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
index 63448b6e3c..e53282267f 100644
--- a/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
@@ -2,11 +2,15 @@ import { setGlobalSplitManager } from '@app/signal/splitLayout';
import type { WithRequired } from '@core/util/withRequired';
import type { RouteDefinition, RouteSectionProps } from '@solidjs/router';
import { SplitLayoutContainer } from './SplitLayout';
+import { appSplitRouterMiddleware } from './split-router/app-middleware';
+import { appSplitRoutes } from './split-router/app-routes';
function LayoutRoute(props: RouteSectionProps) {
return (
<SplitLayoutContainer
pairs={props.params.splits?.split('/') ?? []}
+ routes={appSplitRoutes}
+ middleware={appSplitRouterMiddleware}
setManager={setGlobalSplitManager}
/>
);
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 613d671fc7..eef36b1148 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -1,144 +1,28 @@
-import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
-import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
import { parseAgentsRoute } from '@app/features/agents-view/core/route';
-import { AgentsView } from '@app/features/agents-view/views/AgentsView';
import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives/use-spreadsheet-access';
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
-import { ChannelsView } from '@app/features/channels-view/channels-view';
-import {
- DriveView,
- type DriveViewProps,
-} from '@app/features/drive-view/drive-view';
import { EmailCompose } from '@app/features/email-compose/email-compose';
-import { EmailView } from '@app/features/email-view/email-view';
-import { GettingStarted } from '@app/features/getting-started';
-import { Home } from '@app/features/home';
-import { InboxView } from '@app/features/inbox-view/inbox-view';
-import { queryStateFrom } from '@app/features/next-soup/filters/filter-store';
-import type { SetPredicatesInput } from '@app/features/next-soup/filters/filter-store/predicates-store';
-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 { SoupView } from '@app/features/next-soup/soup-view/soup-view';
-import { useRecentViewFlag } from '@app/features/next-soup/use-recent-view-flag';
import { ReminderEditorSplit } from '@app/features/reminders/ReminderEditorSplit';
-import { McpConnections } from '@app/features/settings/McpConnections';
-import { SettingsPanelComponentWrapper } from '@app/features/settings/Settings';
-import { TasksView } from '@app/features/tasks-view/tasks-view';
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { useFeatureFlag, usePosthog } from '@app/lib/analytics/posthog';
import { EventComposerSplit } from '@block-calendar/components/EventComposerSplit';
import { ChannelCompose } from '@block-channel/component/Compose';
import { ComposeSkill } from '@block-md/component/ComposeSkill';
import { ComposeTask } from '@block-md/component/ComposeTask';
-import {
- CRM_VIEW_URL_PARAM,
- type CrmViewConfig,
- decodeCrmViewParam,
-} from '@companies/crm/saved-views';
-import { useIsAuthenticated } from '@core/auth';
import { LoadingBlock } from '@core/component/LoadingBlock';
-import {
- DEV_MODE_ENV,
- enableChatV3Agents,
- enableCrm,
- enableNewAppViews,
- enableReminders,
- isFeatureEnabled,
- LOCAL_ONLY,
-} from '@core/constant/featureFlags';
-import { useUserContext } from '@core/context/user';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { DEV_MODE_ENV, LOCAL_ONLY } from '@core/constant/featureFlags';
import type { ViewId } from '@core/types/view';
-import { useAutomationEntities } from '@queries/agent-schedule/entities';
+import { type JSXElement, lazy, Show } from 'solid-js';
+import * as views from './split-router/app-views';
import {
- type Component,
- createRenderEffect,
- createSignal,
- type JSXElement,
- lazy,
- onCleanup,
- onMount,
- Show,
-} from 'solid-js';
-import type { SplitContent } from './layoutManager';
-import { useSplitPanelOrThrow } from './layoutUtils';
-
-function usePageViewTracking(pageTitle: string) {
- const analytics = useAnalytics();
- onMount(() => {
- analytics.pageView(pageTitle);
- analytics.track('open_view', { viewId: pageTitle });
- });
-}
-
-const NEW_APP_VIEWS_FLAG_WAIT_MS = 5_000;
-
-function useNewAppViews(options?: {
- enabledLayout?: () => 'legacy' | 'composable';
-}) {
- const panel = useSplitPanelOrThrow();
- const flag = useFeatureFlag(enableNewAppViews);
- const [timedOut, setTimedOut] = createSignal(false);
- const timer = setTimeout(() => setTimedOut(true), NEW_APP_VIEWS_FLAG_WAIT_MS);
- onCleanup(() => clearTimeout(timer));
-
- // PostHog can be blocked or fail before invoking its flag callback. Bound
- // the loading state so these views fall back to their legacy equivalents
- // instead of displaying a loading block forever.
- const ready = () => !flag().loading || timedOut();
- const enabled = () => ready() && flag().enabled;
-
- createRenderEffect(() => {
- if (!ready()) return;
- panel.handle.updateMeta?.({
- splitPanelLayout: enabled()
- ? (options?.enabledLayout?.() ?? 'composable')
- : 'legacy',
- });
- });
-
- return { ready, enabled };
-}
-
-/**
- * Guard that delays rendering until user is authenticated.
- * Use for components that require user context (userId, email).
- */
-const withAuth = <P extends object>(Comp: Component<P>): Component<P> => {
- return (props: P) => {
- const isAuthenticated = useIsAuthenticated();
- return (
- <Show when={isAuthenticated()} fallback={<LoadingBlock />}>
- <Comp {...props} />
- </Show>
- );
- };
-};
+ RedirectSplit,
+ usePageViewTracking,
+ withAuth,
+} from './split-router/app-views';
type ComponentParams = Record<string, unknown>;
type ComponentFactory = (params: ComponentParams) => JSXElement;
-type DocumentsComponentParams = DriveViewProps & {
- initialFilters?: Query;
- initialClientFilters?: SetPredicatesInput<string>;
-};
-
-function mergeClientFilters(
- base?: SetPredicatesInput<string>,
- refinement?: SetPredicatesInput<string>
-): SetPredicatesInput<string> | undefined {
- if (!base) return refinement;
- if (!refinement) return base;
-
- return {
- and: [...new Set([...(base.and ?? []), ...(refinement.and ?? [])])],
- or: [...new Set([...(base.or ?? []), ...(refinement.or ?? [])])],
- };
-}
-
export type ComponentMeta = {
kind?: string;
splitPanelLayout?: 'legacy' | 'composable';
@@ -177,17 +61,6 @@ type ResolvedComponent = {
initialMeta?: ComponentMeta;
};
-// Similar to SolidRouter's `<Navigate />` but for splits
-function RedirectSplit(props: { to: SplitContent }) {
- const panel = useSplitPanelOrThrow();
-
- onMount(() => {
- panel.handle.replace({ next: props.to });
- });
-
- return null;
-}
-
/**
* A reminder view carries its reminder id in the id slot — `reminder-view~<id>`
* — because component params are dropped on URL restore (see `contentUrlSegments`)
@@ -232,148 +105,29 @@ registerComponent('unified-list', () => (
<RedirectSplit to={{ type: 'component', id: 'inbox' }} />
));
-/** BEGIN - APP ROUTES */
-registerComponent(
- 'home',
- withAuth(() => {
- usePageViewTracking('home');
- return <Home />;
- })
-);
-
-registerComponent(
- 'getting-started',
- withAuth(() => {
- usePageViewTracking('getting-started');
- return <GettingStarted />;
- })
-);
-
-function LegacyInboxView() {
- const preset = getViewPreset('inbox');
- return (
- <SoupView
- viewName={isTouchDevice() ? 'Notifications' : 'Home'}
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- disableLocalSearch
- />
- );
-}
-
-function RegisteredInboxView() {
- usePageViewTracking('inbox');
- const newAppViews = useNewAppViews();
- return (
- <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>
- <Show when={newAppViews.enabled()} fallback={<LegacyInboxView />}>
- <InboxView />
- </Show>
- </Show>
- );
-}
-
-registerComponent('inbox', withAuth(RegisteredInboxView));
-
-registerComponent('recent', withAuth(RecentViewWrapper));
-
-function TrackedRecentView() {
- usePageViewTracking('recent');
- const preset = getViewPreset('recent');
- return (
- <SoupView
- viewName="Recent"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- // Rows carry the server's touched_at, so sorting on it preserves
- // the touched-by-me order and lets optimistic bumps reorder locally.
- initialClientSort={['touched_at']}
- disableLocalSearch
- />
- );
-}
-
-function RecentViewWrapper() {
- const recentViewEnabled = useRecentViewFlag();
- const posthog = usePosthog();
-
- // Registered even when the flag is off so a bookmarked /recent or a
- // restored split recovers to the inbox instead of an empty split, and the
- // touched query is never issued. The redirect replaces the split
- // irreversibly, so it must wait for PostHog to actually answer — on a
- // fresh reload the flag reads false until flags load.
- return (
- <Show
- when={recentViewEnabled()}
- fallback={
- <Show when={posthog.flagsLoaded()}>
- <RedirectSplit to={{ type: 'component', id: 'inbox' }} />
- </Show>
- }
- >
- <TrackedRecentView />
- </Show>
- );
-}
-
-const MyActivityView = lazy(() =>
- import('@app/features/activity/views/my-activity-view').then((module) => ({
- default: module.MyActivityView,
- }))
-);
-
-function TrackedMyActivityView() {
- usePageViewTracking('activity');
- return <MyActivityView onOpen={openEntityInSplit} />;
-}
-
-function MyActivityViewWrapper() {
- const activityFeedEnabled = useActivityFeedFlag();
- const posthog = usePosthog();
-
- // Wait for flags before replacing a bookmarked or restored activity split.
- // While disabled, never mount the feed or issue its queries.
- return (
- <Show
- when={activityFeedEnabled()}
- fallback={
- <Show when={posthog.flagsLoaded()}>
- <RedirectSplit to={{ type: 'component', id: 'inbox' }} />
- </Show>
- }
- >
- <TrackedMyActivityView />
- </Show>
- );
-}
-
-registerComponent('activity', withAuth(MyActivityViewWrapper));
-
-registerComponent(
- 'reminders',
- withAuth(() => {
- // Registered even when the flag is closed so a bookmarked /reminders or a
- // restored split recovers to the inbox instead of an empty split.
- if (!isFeatureEnabled(enableReminders)) {
- return <RedirectSplit to={{ type: 'component', id: 'inbox' }} />;
- }
- usePageViewTracking('reminders');
- const preset = getViewPreset('reminders');
- return (
- <SoupView
- viewName="Reminders"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- disableLocalSearch
- />
- );
- })
-);
-
-// The Activity tab briefly shipped as two separate views; restored splits
-// may still reference their ids.
+// Compatibility factories for restored content and hosts outside a route outlet.
+// App views themselves are composed by the application route layer.
+registerComponent('home', (params) => <views.HomeView {...params} />);
+registerComponent('getting-started', (params) => (
+ <views.GettingStartedView {...params} />
+));
+registerComponent('inbox', (params) => <views.InboxRouteView {...params} />);
+registerComponent('recent', (params) => <views.RecentView {...params} />);
+registerComponent('activity', (params) => <views.ActivityView {...params} />);
+registerComponent('reminders', (params) => <views.RemindersView {...params} />);
+registerComponent('agents', (params) => <views.AgentsRouteView {...params} />);
+registerComponent('mail', (params) => <views.MailView {...params} />);
+registerComponent('documents', (params) => (
+ <views.DriveRouteView {...params} />
+));
+registerComponent('tasks', (params) => <views.TasksRouteView {...params} />);
+registerComponent('channels', (params) => (
+ <views.ChannelsRouteView {...params} />
+));
+registerComponent('calls', (params) => <views.CallsView {...params} />);
+registerComponent('companies', (params) => <views.CompaniesView {...params} />);
+registerComponent('folders', (params) => <views.FoldersView {...params} />);
+registerComponent('search', (params) => <views.SearchView {...params} />);
registerComponent('firehose', () => (
<RedirectSplit to={{ type: 'component', id: 'activity' }} />
));
@@ -381,316 +135,6 @@ registerComponent('my-activity', () => (
<RedirectSplit to={{ type: 'component', id: 'activity' }} />
));
-function LegacyAgentsView() {
- const user = useUserContext();
- const preset = getViewPreset('agents', undefined, {
- userId: user.userId(),
- isTeamAdmin: false,
- });
- const automationEntities = useAutomationEntities();
-
- return (
- <SoupView
- viewName="Agents"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- additionalEntities={automationEntities}
- />
- );
-}
-
-function RegisteredAgentsView(params: ComponentParams) {
- const route =
- typeof params.agentsRoute === 'string'
- ? parseAgentsRoute(params.agentsRoute)
- : undefined;
- usePageViewTracking('agents');
- const panel = useSplitPanelOrThrow();
- const agentsFlag = useFeatureFlag(enableChatV3Agents);
- const useAgentsWorkspace = () => agentsFlag().enabled && !isTouchDevice();
- const connectionsRequested = () => {
- const content = panel.handle.content();
- return (
- content.type === 'component' &&
- content.params?.agentPage === 'connections'
- );
- };
-
- createRenderEffect(() => {
- if (agentsFlag().loading) return;
- panel.handle.updateMeta?.({
- splitPanelLayout: useAgentsWorkspace() ? 'composable' : 'legacy',
- });
- });
-
- return (
- <Show when={!agentsFlag().loading} fallback={<LoadingBlock />}>
- <Show
- when={useAgentsWorkspace()}
- fallback={
- <Show
- when={connectionsRequested()}
- fallback={
- route ? (
- <RedirectSplit
- to={{
- type:
- route.conversation.type === 'agent_session'
- ? 'agent'
- : 'chat',
- id: route.conversation.id,
- }}
- />
- ) : (
- <LegacyAgentsView />
- )
- }
- >
- <McpConnections />
- </Show>
- }
- >
- <AgentsView initialRoute={route} />
- </Show>
- </Show>
- );
-}
-
-registerComponent('agents', withAuth(RegisteredAgentsView));
-
-function LegacyMailView() {
- const preset = getViewPreset('mail');
- return (
- <SoupView
- viewName="Email"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- />
- );
-}
-
-function RegisteredMailView() {
- usePageViewTracking('mail');
- const newAppViews = useNewAppViews({
- enabledLayout: () => (isTouchDevice() ? 'legacy' : 'composable'),
- });
-
- return (
- <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>
- <Show when={newAppViews.enabled()} fallback={<LegacyMailView />}>
- <EmailView />
- </Show>
- </Show>
- );
-}
-
-registerComponent('mail', withAuth(RegisteredMailView));
-
-registerComponent(
- 'documents',
- withAuth((params: DocumentsComponentParams = {}) => {
- usePageViewTracking('documents');
- const newAppViews = useNewAppViews();
- const user = useUserContext();
- const preset = getViewPreset('documents', undefined, {
- userId: user.userId(),
- isTeamAdmin: false,
- });
- const initialFilters =
- preset?.filters && params.initialFilters
- ? mergeQuery(queryStateFrom(preset.filters), params.initialFilters)
- : (params.initialFilters ?? preset?.filters);
- const initialClientFilters = mergeClientFilters(
- preset?.clientFilters,
- params.initialClientFilters
- );
- return (
- <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>
- <Show
- when={newAppViews.enabled()}
- fallback={
- <SoupView
- viewName="Files"
- initialFilters={initialFilters}
- initialClientFilters={initialClientFilters}
- initialGroupBy={preset?.groupBy}
- />
- }
- >
- <DriveView initialFacets={params.initialFacets} />
- </Show>
- </Show>
- );
- })
-);
-
-function LegacyTasksView() {
- const user = useUserContext();
- const preset = getViewPreset('tasks', undefined, {
- userId: user.userId(),
- isTeamAdmin: false,
- });
-
- return (
- <SoupView
- viewName="Tasks"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- />
- );
-}
-
-function RegisteredTasksView() {
- usePageViewTracking('tasks');
- const newAppViews = useNewAppViews();
-
- return (
- <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>
- <Show when={newAppViews.enabled()} fallback={<LegacyTasksView />}>
- <TasksView />
- </Show>
- </Show>
- );
-}
-
-registerComponent('tasks', withAuth(RegisteredTasksView));
-
-function LegacyChannelsView() {
- const preset = getViewPreset('channels');
-
- return (
- <SoupView
- viewName="Channels"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- />
- );
-}
-
-function FeatureGatedChannelsView() {
- const newAppViews = useNewAppViews({
- enabledLayout: () => (isTouchDevice() ? 'legacy' : 'composable'),
- });
-
- return (
- <Show when={newAppViews.ready()} fallback={<LoadingBlock />}>
- <Show when={newAppViews.enabled()} fallback={<LegacyChannelsView />}>
- <ChannelsView />
- </Show>
- </Show>
- );
-}
-
-function RegisteredChannelsView() {
- usePageViewTracking('channels');
-
- return <FeatureGatedChannelsView />;
-}
-
-registerComponent('channels', withAuth(RegisteredChannelsView));
-
-registerComponent(
- 'calls',
- withAuth(() => {
- usePageViewTracking('calls');
- const preset = getViewPreset('calls');
- return (
- <SoupView
- viewName="Calls"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- />
- );
- })
-);
-
-registerComponent(
- 'companies',
- withAuth(() => {
- // Registered even when the CRM feature is off so direct navigation /
- // restored splits redirect instead of throwing in resolveComponent.
- if (!isFeatureEnabled(enableCrm)) {
- return <RedirectSplit to={{ type: 'component', id: 'inbox' }} />;
- }
- usePageViewTracking('companies');
- const panel = useSplitPanelOrThrow();
- createRenderEffect(() => {
- panel.handle.updateMeta?.({
- splitPanelLayout: isTouchDevice() ? 'legacy' : 'composable',
- });
- });
- const preset = getViewPreset('companies');
- // Share links land here as `/companies?crmView=<encoded config>` — the
- // param carries the full view state (never data), decoded client-side.
- const crmViewParam = new URLSearchParams(window.location.search).get(
- CRM_VIEW_URL_PARAM
- );
- const initialCrmView: CrmViewConfig | undefined = crmViewParam
- ? decodeCrmViewParam(crmViewParam)
- : undefined;
- return (
- <SoupView
- viewName="Customers"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- initialCrmView={initialCrmView}
- />
- );
- })
-);
-
-registerComponent(
- 'folders',
- withAuth(() => {
- usePageViewTracking('folders');
- const user = useUserContext();
- const preset = getViewPreset('folders', undefined, {
- userId: user.userId(),
- isTeamAdmin: false,
- });
- return (
- <SoupView
- viewName="Folders"
- initialFilters={preset?.filters}
- initialClientFilters={preset?.clientFilters}
- initialGroupBy={preset?.groupBy}
- />
- );
- })
-);
-
-type SearchComponentParams = {
- initialQuery?: string;
- initialFilters?: Query;
- initialClientFilters?: SetPredicatesInput<string>;
-};
-
-registerComponent(
- 'search',
- withAuth((params: SearchComponentParams = {}) => {
- usePageViewTracking('search');
- const preset = getViewPreset('search');
- return (
- <SoupView
- viewName="Search"
- initialFilters={params.initialFilters ?? preset?.filters}
- initialClientFilters={
- params.initialClientFilters ?? preset?.clientFilters
- }
- initialSearchText={params.initialQuery}
- />
- );
- })
-);
-
-/** END - APP ROUTES */
-
registerComponent('loading', () => <LoadingBlock />);
registerComponent('channel-compose', () => {
usePageViewTracking('channel-compose');
@@ -755,7 +199,7 @@ registerComponent(
'import-linear',
lazy(() => import('@app/features/integrations/import-linear/ImportLinear'))
);
-registerComponent('settings', () => <SettingsPanelComponentWrapper />);
+registerComponent('settings', () => <views.SettingsView />);
if (LOCAL_ONLY) {
registerComponent(
diff --git a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx
index 47b389268b..093bbe6d95 100644
--- a/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx
+++ b/apps/web/src/components/app/split-layout/components/PopoverSplitRenderer.tsx
@@ -86,15 +86,14 @@ function PopoverSplitModal(props: {
isSpotLight: () => false,
isPopover: () => true,
replace: () => {},
- // A popover has no URL and no history to rewrite.
+ // A popover has no history to rewrite.
adoptContentId: () => {},
+ updateCurrentEntry: () => {},
removeFromHistory: () => {},
registerContentChangeListener: () => {},
unregisterContentChangeListener: () => {},
previousContent: () => null,
history: () => [],
- getUrlSegments: () => [],
- getUrl: () => '',
meta: () =>
props.popover.mount.kind === 'component'
? props.popover.mount.meta
diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
index 550f5e8690..a1a6a44539 100644
--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
@@ -4,6 +4,7 @@ import { driveLocationLabel } from '@app/features/drive-view/core/location-label
import type { DriveState } from '@app/features/drive-view/core/types';
import { useSoup } from '@app/features/next-soup/soup-context';
import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
+import { useSplitRouter } from '@app/lib/split-router';
import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { useSidebarCollapse } from '@components/app/sidebarVisibility';
@@ -47,7 +48,7 @@ import { Portal } from 'solid-js/web';
import { match, P } from 'ts-pattern';
import { splitBackInterceptor } from '../back-interceptor';
import { SplitLayoutContext, SplitPanelContext } from '../context';
-import type { SplitContent } from '../layoutManager';
+import type { SplitContent, SplitId } from '../layoutManager';
import {
closeSplitOrReturnToList,
shouldShowSplitCloseButton,
@@ -256,7 +257,9 @@ function SplitDriveReturnButton() {
const sourceLabel = () => {
const state = sourceList()?.state;
const label = state?.['drive.returnLabel'];
+
if (typeof label === 'string') return label;
+
const driveState = state?.['drive.view.v2'] as DriveState | undefined;
return driveState ? driveLocationLabel(driveState.location) : 'My Files';
};
@@ -362,6 +365,7 @@ function SoupNavigationButtons() {
function SplitHeaderContextMenu(props: ParentProps) {
const panel = useContext(SplitPanelContext);
const layout = useContext(SplitLayoutContext);
+ const router = useSplitRouter<SplitId>();
if (!panel || !layout) return props.children;
const splitIndex = createMemo(() =>
@@ -406,7 +410,7 @@ function SplitHeaderContextMenu(props: ParentProps) {
activeSplitId: layout.manager.activeSplitId(),
currentSplitId: panel.handle.id,
currentSplitIndex: splitIndex(),
- currentSplitUrl: panel.handle.getUrl(),
+ currentSplitUrl: router.href(panel.handle.id),
splits: splits.map((split, index) => ({
index,
id: split.id,
diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
index cf5d073a2a..d095a315ad 100644
--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
@@ -2,6 +2,7 @@ import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';
import { createSoupState } from '@app/features/next-soup/create-soup-state';
import { SoupContextProvider } from '@app/features/next-soup/soup-context';
import { SoupViewContextProvider } from '@app/features/next-soup/soup-view/soup-view-context';
+import { SplitRouter } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
import { ContentLoading } from '@components/app/ContentLoading';
import { MobileTopEdgeFade } from '@components/app/mobile/MobileEdgeFade';
@@ -188,7 +189,10 @@ export function SplitPanel(props: SplitPanelProps) {
>
<Suspense fallback={<ContentLoading />}>
<SoupViewContextProvider soup={nextSoup}>
- <Dynamic component={props.split.mount.element} />
+ <SplitRouter.Outlet
+ splitId={props.handle.id}
+ fallback={() => <Dynamic component={props.split.mount.element} />}
+ />
</SoupViewContextProvider>
</Suspense>
</SplitPanelControllerProvider>
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index f18570fbbd..51678f4ad7 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -1,8 +1,5 @@
import { LIST_VIEW_ID, type ListView } from '@app/constants/list-views';
-import {
- agentsRouteSegments,
- parseAgentsRoute,
-} from '@app/features/agents-view/core/route';
+import { parseAgentsRoute } from '@app/features/agents-view/core/route';
import type {
BlockAlias,
BlockAliasContext,
@@ -11,13 +8,12 @@ import type {
} from '@core/block';
import type { ResizeZoneCtx } from '@core/component/Resize/types';
import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';
-import { settingsTabToSlug } from '@core/constant/settingsTabsConfig';
import type {
BlockInstanceHandle,
BlockOrchestrator,
} from '@core/orchestrator';
-import { activeTabId } from '@core/signal/settingsTab';
import { useFocusLock } from '@core/util/createControlledOpenSignal';
+import deepEqual from 'fast-deep-equal';
import {
type Accessor,
batch,
@@ -52,27 +48,31 @@ type SplitKey = `${BlockName | BlockAlias | 'component'}:${string}`;
*/
export type EntryState = Record<string, unknown>;
-export type SplitContent = {
+type SplitContentState = {
/**
* Whether to preserve the params originally passed when navigating to this content.
* If false, then it only does so the first time.
*/
preserveParams?: boolean;
-} & (
- | {
- type: BlockName | BlockAlias;
- id: string;
- params?: BlockComponentProps[BlockName];
- aliasContext?: BlockAliasContext;
- state?: EntryState;
- }
- | {
- type: 'component';
- id: string;
- params?: Record<string, unknown>;
- state?: EntryState;
- }
-);
+ state?: EntryState;
+ /** Per-entry integration metadata, opaque to the layout manager. */
+ entryMetadata?: unknown;
+};
+
+export type SplitContent = SplitContentState &
+ (
+ | {
+ type: BlockName | BlockAlias;
+ id: string;
+ params?: BlockComponentProps[BlockName];
+ aliasContext?: BlockAliasContext;
+ }
+ | {
+ type: 'component';
+ id: string;
+ params?: Record<string, unknown>;
+ }
+ );
export type SplitContentType = SplitContent['type'];
@@ -87,40 +87,6 @@ export type NavigationCause =
| 'history-forward'
| 'replace';
-function sameContent(a: SplitContent, b: SplitContent): boolean {
- return a.type === b.type && a.id === b.id;
-}
-
-function getAliasOrType(content: SplitContent): string {
- return content.type === 'component'
- ? content.type
- : content.aliasContext?.alias || content.type;
-}
-
-/**
- * The `type/id` URL pair for a split's content. The settings panel is stored
- * internally as `component/settings` content, but serializes as
- * `settings/<active-tab-slug>` so the URL reflects (and can restore) which
- * settings page is open. Reads the active-tab signal, so the URL updates
- * reactively as the tab changes. `decodePairs` maps `settings/<tab>` back to
- * the internal `component/settings` content on the way in.
- *
- * This applies on mobile too: settings docks as a split there, and now that
- * settings is no longer a standalone `/settings/:tab` route, `settings/<tab>`
- * is claimed by the split layout like any other split — so there's no reason
- * to keep the tab out of the URL.
- */
-function contentUrlSegments(content: SplitContent): string[] {
- if (content.type === 'component') {
- const agentsRoute = agentsRouteSegments(content.id);
- if (agentsRoute) return agentsRoute;
- }
- if (content.type === 'component' && content.id === 'settings') {
- return ['settings', settingsTabToSlug(activeTabId())];
- }
- return [getAliasOrType(content), content.id].map(String);
-}
-
function keyOfSplitContent(s: SplitContent): SplitKey {
return `${s.type}:${s.id}`;
}
@@ -240,11 +206,6 @@ function keyOfSplitState(s: SplitState): SplitKey {
return `${s.content.type}:${s.content.id}`;
}
-export type UrlCapabilities = {
- getUrlSegments: () => string[];
- getUrl: () => string;
-};
-
export enum SplitEvent {
Insert,
Remove,
@@ -354,7 +315,7 @@ export type SplitManager = {
/**
* Reconcile the splits with the provided list of splits.
- * Useful for when the url changes.
+ * Useful when applying externally restored layout state.
*
* All [SplitContent] of type `component` will be fully re-created.
* All [SplitContent] of type `block` will be preserved, and not re-mounted.
@@ -409,7 +370,7 @@ export type SplitManager = {
/**
* Register a predicate that marks certain splits as excluded — excluded splits
- * are hidden from URL encoding, duplicate detection, and content lookup.
+ * are hidden from external serialization, duplicate detection, and content lookup.
* Used for mobile swipe back behavior, where we want to ignore the bg split.
*/
setExclusionFilter: (
@@ -436,7 +397,7 @@ export type SplitManager = {
handle: PopoverSplitHandle;
}
>;
-} & UrlCapabilities;
+};
export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {
unregisterContentChangeListener: (
@@ -529,7 +490,14 @@ export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {
* Returns `undefined` if no state has been captured.
*/
currentEntryState: () => EntryState | undefined;
-} & UrlCapabilities;
+ /**
+ * Replace the current history entry without remounting its content or
+ * notifying content-identity listeners. Identity-changing updates are ignored.
+ */
+ updateCurrentEntry: (
+ updater: (current: SplitContent) => SplitContent
+ ) => void;
+};
function newSplitId(): SplitId {
return brandSplitId(
@@ -574,11 +542,6 @@ function createPinnedMount(
};
}
-function sameIdentity(a: SplitContent, b: SplitContent): boolean {
- if (a.type !== b.type) return false;
- return a.id === b.id;
-}
-
function contentIdentity(content: SplitContent) {
const route =
content.type === 'component' ? parseAgentsRoute(content.id) : undefined;
@@ -736,6 +699,22 @@ export function createSplitLayout(
});
}
+ function applyEntryMetadata(
+ split: SplitState,
+ desired: SplitContent
+ ): SplitState {
+ if (deepEqual(split.content.entryMetadata, desired.entryMetadata)) {
+ return split;
+ }
+
+ const content = {
+ ...split.content,
+ entryMetadata: desired.entryMetadata,
+ } as SplitContent;
+ split.history.replaceCurrent(content);
+ return { ...split, content };
+ }
+
const DEFAULT_SPLIT_CONTENT = defaultSplitContent ?? {
type: 'component',
id: LIST_VIEW_ID.inbox,
@@ -819,7 +798,10 @@ export function createSplitLayout(
if (isDuplicateSplit(otherSplits, next)) return;
const splitIndex = splitIndexById(split.id);
- if (splitIndex >= 0 && !sameIdentity(split.content, content)) {
+ if (
+ splitIndex >= 0 &&
+ keyOfSplitContent(split.content) !== keyOfSplitContent(content)
+ ) {
setSplitNamesById(
produce((map) => {
delete map[split.id];
@@ -845,7 +827,7 @@ export function createSplitLayout(
}
}
- if (sameIdentity(split.content, content)) {
+ if (keyOfSplitContent(split.content) === keyOfSplitContent(content)) {
// Update referredFrom if provided, even if content is the same
if (referredFrom !== undefined) {
return setState('splits', (s) => {
@@ -1018,8 +1000,8 @@ export function createSplitLayout(
* the mount. See `SplitHandle.adoptContentId` for why this exists.
*
* The history entry is rewritten rather than pushed, and the navigation
- * cause is `replace`, so the URL sync swaps the path in place instead of
- * adding a back step to a placeholder the user can never return to.
+ * cause is `replace`, so external state can replace the id instead of adding
+ * a back step to a placeholder the user can never return to.
*/
function adoptContentId(
id: SplitId,
@@ -1065,6 +1047,37 @@ export function createSplitLayout(
});
}
+ function updateCurrentEntry(
+ id: SplitId,
+ updater: (current: SplitContent) => SplitContent
+ ): void {
+ const split = findSplitById(id);
+ if (!split) return;
+ if (
+ split.history.index < 0 ||
+ split.history.index >= split.history.items.length
+ ) {
+ return;
+ }
+
+ const current = split.content;
+ const next = updater(current);
+ if (
+ next === current ||
+ keyOfSplitContent(current) !== keyOfSplitContent(next)
+ )
+ return;
+
+ batch(() => {
+ split.history.replaceCurrent(next);
+ setState('splits', (splits) => {
+ const index = splits.findIndex((candidate) => candidate.id === id);
+ if (index < 0) return splits;
+ return splits.with(index, { ...splits[index], content: next });
+ });
+ });
+ }
+
function reset(id: SplitId) {
const i = splitIndexById(id);
if (i < 0) return console.error(`Split with id ${id} not found`);
@@ -1080,21 +1093,6 @@ export function createSplitLayout(
});
}
- const getUrlSegments = () => {
- return state.splits
- .filter((s) => !isExcluded(s))
- .flatMap((s) => contentUrlSegments(s.content));
- };
-
- const getUrl = () => {
- const visibleSplits = state.splits.filter((s) => !isExcluded(s));
- return (
- visibleSplits.map((s) => getAliasOrType(s.content)).join('/') +
- '/' +
- visibleSplits.map((s) => s.content.id).join('/')
- );
- };
-
function activateSplit(id: SplitId) {
// Invariant: an excluded split (the mobile background split) can never
// become the active split. Promote it out of exclusion first.
@@ -1202,7 +1200,10 @@ export function createSplitLayout(
// If there's only one split and it's the default split, then no-op
if (state.splits.length <= 1) {
// If it's not the default split, replace it with the default
- if (!sameContent(content(), DEFAULT_SPLIT_CONTENT))
+ if (
+ keyOfSplitContent(content()) !==
+ keyOfSplitContent(DEFAULT_SPLIT_CONTENT)
+ )
replace(currentSplit.id, {
next: DEFAULT_SPLIT_CONTENT,
referredFrom: null,
@@ -1213,8 +1214,6 @@ export function createSplitLayout(
removeSplit(currentSplit.id);
},
- getUrlSegments: () => contentUrlSegments(content()),
- getUrl: () => contentUrlSegments(content()).join('/'),
isFirst: () => state.splits.at(0)?.id === id,
isLast: () => state.splits.at(-1)?.id === id,
isActive: () => currentSplit.id === state.activeSplitId,
@@ -1282,6 +1281,8 @@ export function createSplitLayout(
const c = live.content as { state?: EntryState };
return c.state;
},
+ updateCurrentEntry: (updater) =>
+ updateCurrentEntry(currentSplit.id, updater),
};
};
@@ -1291,7 +1292,9 @@ export function createSplitLayout(
const { content, activate, referredFrom, initialHistory, insertIndex } =
options;
const initialContent = content ?? DEFAULT_SPLIT_CONTENT;
- const isDefault = sameContent(initialContent, DEFAULT_SPLIT_CONTENT);
+ const isDefault =
+ keyOfSplitContent(initialContent) ===
+ keyOfSplitContent(DEFAULT_SPLIT_CONTENT);
// Direct split creation permits duplicate shells, but never duplicate entities.
const existing = findOpenView(initialContent);
@@ -1401,14 +1404,37 @@ export function createSplitLayout(
return getSplit(match.id);
}
+ function reconcileEntryMetadata(
+ visibleSplits: SplitState[],
+ newSplits: SplitContent[]
+ ) {
+ const metadataChanged = visibleSplits.some(
+ (split, index) =>
+ !deepEqual(split.content.entryMetadata, newSplits[index]?.entryMetadata)
+ );
+ if (!metadataChanged) return;
+
+ setState('splits', (splits) => {
+ const nextById = new Map(
+ visibleSplits.map((split, index) => [
+ split.id,
+ applyEntryMetadata(split, newSplits[index]),
+ ])
+ );
+ return splits.map((split) => nextById.get(split.id) ?? split);
+ });
+ }
+
function reconcileSplits(newSplits: SplitContent[]) {
- // URL segments are produced by getUrlSegments(), which excludes excluded splits.
const visibleSplits = state.splits.filter((s) => !isExcluded(s));
const currentKeys = visibleSplits.map(keyOfSplitState);
const newKeys = newSplits.map(keyOfSplitContent);
const changed = newKeys.join(',') !== currentKeys.join(',');
- if (!changed) return;
+ if (!changed) {
+ reconcileEntryMetadata(visibleSplits, newSplits);
+ return;
+ }
// Build the result array by position, preserving excluded splits unchanged.
const resultSplits: SplitState[] = [];
@@ -1423,7 +1449,7 @@ export function createSplitLayout(
// Assign existing splits before creating replacements. Matching by content
// after the same-position fast path lets a split keep its identity (and its
- // history/mount) when browser navigation merely moves it to another index.
+ // history/mount) when inbound state merely moves it to another index.
const assignments = new Array<SplitState | undefined>(newSplits.length);
for (let i = 0; i < newSplits.length; i++) {
@@ -1433,7 +1459,8 @@ export function createSplitLayout(
if (
splitAtSameIndex &&
!usedIds.has(splitAtSameIndex.id) &&
- sameContent(splitAtSameIndex.content, newContent)
+ keyOfSplitContent(splitAtSameIndex.content) ===
+ keyOfSplitContent(newContent)
) {
assignments[i] = splitAtSameIndex;
usedIds.add(splitAtSameIndex.id);
@@ -1445,7 +1472,8 @@ export function createSplitLayout(
const existing = visibleSplits.find(
(split) =>
- !usedIds.has(split.id) && sameContent(split.content, newSplits[i])
+ !usedIds.has(split.id) &&
+ keyOfSplitContent(split.content) === keyOfSplitContent(newSplits[i])
);
if (existing) {
assignments[i] = existing;
@@ -1456,7 +1484,7 @@ export function createSplitLayout(
for (let i = 0; i < newSplits.length; i++) {
const existing = assignments[i];
if (existing) {
- resultSplits.push(existing);
+ resultSplits.push(applyEntryMetadata(existing, newSplits[i]));
continue;
}
@@ -1730,8 +1758,10 @@ export function createSplitLayout(
}
const visibleSplits = state.splits.filter((split) => !isExcluded(split));
const splitToKeep =
- visibleSplits.find((split) => sameContent(split.content, content)) ??
- visibleSplits[0];
+ visibleSplits.find(
+ (split) =>
+ keyOfSplitContent(split.content) === keyOfSplitContent(content)
+ ) ?? visibleSplits[0];
if (!splitToKeep) {
return createNewSplit({
@@ -1753,7 +1783,9 @@ export function createSplitLayout(
const handle = getSplit(splitToKeep.id);
if (handle) {
- if (!sameContent(splitToKeep.content, content)) {
+ if (
+ keyOfSplitContent(splitToKeep.content) !== keyOfSplitContent(content)
+ ) {
handle.replace({
next: content,
mergeHistory: false,
@@ -1795,8 +1827,6 @@ export function createSplitLayout(
swapSplit,
canSwapSplit,
createNewSplit,
- getUrlSegments,
- getUrl,
activateSplit,
hasSplit,
getSplitByContent,
diff --git a/apps/web/src/components/app/split-layout/layoutUrlSync.ts b/apps/web/src/components/app/split-layout/layoutUrlSync.ts
deleted file mode 100644
index 491db55a4e..0000000000
--- a/apps/web/src/components/app/split-layout/layoutUrlSync.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import type { Navigator } from '@solidjs/router';
-import {
- type Accessor,
- createEffect,
- createMemo,
- on,
- onCleanup,
-} from 'solid-js';
-import type { SplitContent, SplitManager } from './layoutManager';
-import { decodePairs } from './layoutUtils';
-
-type LayoutUrlSyncEnvironment = {
- navigate: Navigator;
- search: 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));
-}
-
-/**
- * Keep the split manager and the path 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[]>,
- environment: LayoutUrlSyncEnvironment
-) {
- let reconcilingFromUrl = false;
- let managerSyncQueued = false;
- let disposed = false;
- onCleanup(() => {
- disposed = true;
- });
-
- const managerUrlSignature = () => splitManager.getUrlSegments().join('/');
- const urlLayoutDrift = createMemo(
- () => managerUrlSignature() !== pairs().join('/')
- );
-
- const syncManagerToUrl = (options: { replace?: boolean } = {}) => {
- if (!urlLayoutDrift()) return;
-
- const segments = splitManager.getUrlSegments();
- const currentQuery = new URLSearchParams(environment.search());
- // Action links can mount before settings has selected its requested tab.
- // Preserve their query until the wrapper has canonicalized that tab.
- if (
- pairs()[0] === 'settings' &&
- ((pairs()[1] === 'harness' && currentQuery.get('pair')) ||
- (pairs()[1] === 'agents' && currentQuery.get('createAgent') === 'true'))
- ) {
- return;
- }
- const nextPairs = decodePairs(segments);
- const affectedSplit = getUrlSyncAffectedSplit(
- splitManager,
- decodePairs(pairs()),
- nextPairs
- );
- const replace =
- options.replace ?? affectedSplit?.lastNavigationCause === 'replace';
-
- // Path changes clear content-specific query and hash locations.
- const nextUrl = `/${segments.join('/')}`;
-
- environment.navigate(nextUrl, { replace });
- };
-
- // Coalesce batched layout mutations into one URL update.
- const scheduleManagerToUrlSync = () => {
- if (managerSyncQueued) return;
- managerSyncQueued = true;
- queueMicrotask(() => {
- managerSyncQueued = false;
- if (!disposed && !reconcilingFromUrl) syncManagerToUrl();
- });
- };
-
- /** Sync changes from the layout manager to the URL path. */
- createEffect(
- on(
- managerUrlSignature,
- () => {
- if (!reconcilingFromUrl) scheduleManagerToUrlSync();
- },
- { defer: true }
- )
- );
-
- /** Sync changes from the URL path to the manager. */
- createEffect(
- on(pairs, () => {
- if (urlLayoutDrift()) {
- const nextContents = decodePairs(pairs());
- reconcilingFromUrl = true;
- try {
- splitManager.reconcile(nextContents);
- } finally {
- reconcilingFromUrl = false;
- }
-
- // Rewrite invalid URL content 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.ts
index 5d9865f8ad..751201650b 100644
--- a/apps/web/src/components/app/split-layout/layoutUtils.ts
+++ b/apps/web/src/components/app/split-layout/layoutUtils.ts
@@ -1,8 +1,5 @@
import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';
-import { agentsRouteFromSegments } from '@app/features/agents-view/core/route';
import { globalSplitManager } from '@app/signal/splitLayout';
-import type { BlockAlias, BlockName } from '@core/block';
-import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';
import { createCallback } from '@solid-primitives/rootless';
import {
type Accessor,
@@ -20,56 +17,6 @@ import type {
} from './layoutManager';
import type { CollapsibleItemInput } from './utils/createPriorityCollapser';
-export function decodePairs(segments: string[]): SplitContent[] {
- const pairs: SplitContent[] = [];
- for (let i = 0; i < segments.length; i += 2) {
- const type = segments[i];
- const id = segments[i + 1];
- if (!type || !id) break;
- const agentsRoute = agentsRouteFromSegments(type, id);
-
- if (agentsRoute) {
- pairs.push({ type: 'component', id: agentsRoute });
- } else if (type === 'settings') {
- // `settings/<tab>` is the URL form of the docked settings panel; it maps
- // to the internal `component/settings` content. The active tab is read
- // reactively from the URL by SettingsPanelComponentWrapper, so it isn't
- // threaded through content params. See `contentUrlSegments` in
- // layoutManager for the matching encode.
- pairs.push({ type: 'component', id: 'settings' });
- } else if (type === 'component') {
- // Ignore placeholders left in URLs saved before Preview Pair removal.
- if (id === 'preview-empty' || id === 'non-member-channel') continue;
- pairs.push({ type: 'component', id });
- } else {
- const resolvedType = resolveBlockAlias(type as BlockName | BlockAlias);
- if (isBlockAlias(type)) {
- const content: SplitContent = {
- type,
- id,
- aliasContext: {
- alias: type,
- baseType: resolvedType,
- },
- };
- pairs.push(content);
- } else {
- const content: SplitContent = { type: resolvedType, id };
- pairs.push(content);
- }
- }
- }
- return pairs.length ? pairs : [{ type: 'component', id: LIST_VIEW_ID.inbox }];
-}
-
-function _encodePairs(splits: ReadonlyArray<SplitContent>): string[] {
- return splits.flatMap((s) => [
- // Use the alias type if available, otherwise use the base type
- s.type === 'component' ? s.type : s.aliasContext?.alias || s.type,
- s.id,
- ]);
-}
-
const _isInSplit = createCallback(() => {
return !!useContext(SplitPanelContext);
});
diff --git a/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts b/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts
index 533ad91609..856c6b722a 100644
--- a/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts
+++ b/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts
@@ -64,8 +64,7 @@ export function createMobileSwipeLayout(
const fgSplitId = () => (fgIsSlotA() ? slotASplitId() : slotBSplitId());
const bgSplitId = () => (fgIsSlotA() ? slotBSplitId() : slotASplitId());
- const sameContent = (a: SplitContent, b: SplitContent) =>
- a.type === b.type && a.id === b.id;
+ const contentKey = (content: SplitContent) => `${content.type}:${content.id}`;
// The BG split is always exactly bgSplitId() — derive exclusion directly from
// the slot signals rather than maintaining a separate set.
@@ -111,14 +110,15 @@ export function createMobileSwipeLayout(
// If the target is already mounted in BG, promote it instead of recreating it.
if (
bgHandle &&
- (sameContent(bgHandle.content(), content) ||
+ (contentKey(bgHandle.content()) === contentKey(content) ||
splitManager.findOpenView(content)?.owner === bgHandle.id)
) {
// Reopening from a list supplies a new source even for the same entity.
bgHandle.replace({
- next: sameContent(bgHandle.content(), content)
- ? content
- : bgHandle.content(),
+ next:
+ contentKey(bgHandle.content()) === contentKey(content)
+ ? content
+ : bgHandle.content(),
referredFrom,
mergeHistory: true,
});
diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
new file mode 100644
index 0000000000..ae5b89c024
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
@@ -0,0 +1,32 @@
+import {
+ driveDocumentFromContent,
+ drivePath,
+} from '@app/features/drive-view/primitives/drive-route';
+import { routeParams, type SplitRouterMiddleware } from '@app/lib/split-router';
+import { appSplitRoutes } from './app-routes';
+import { decodeLegacyPair } from './legacy-route';
+
+export const appSplitRouterMiddleware = [
+ ({ to, redirect }) => {
+ if (to.location.route.matches[0].id !== 'legacy-content') return;
+ const params = routeParams(to.location.route);
+ const type = typeof params.type === 'string' ? params.type : undefined;
+ const id = typeof params.id === 'string' ? params.id : undefined;
+ if (type === 'component' && id) {
+ if (id === 'preview-empty' || id === 'non-member-channel')
+ return redirect('/inbox');
+ if (id === 'documents') return redirect('/drive');
+ if (id === 'settings') return redirect('/settings');
+ if (
+ appSplitRoutes.definitions.some((route) => route.id === `view-${id}`)
+ ) {
+ return redirect(`/${id}`);
+ }
+ }
+ const content = type && id ? decodeLegacyPair(type, id) : undefined;
+ const document = content && driveDocumentFromContent(content);
+ if (!document) return;
+
+ return redirect(drivePath({ kind: 'tab', tab: 'owned' }, document));
+ },
+] satisfies readonly SplitRouterMiddleware[];
diff --git a/apps/web/src/components/app/split-layout/split-router/app-routes.ts b/apps/web/src/components/app/split-layout/split-router/app-routes.ts
new file mode 100644
index 0000000000..98c4adc3c5
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-router/app-routes.ts
@@ -0,0 +1,121 @@
+import { driveSplitRoute } from '@app/features/drive-view/primitives/drive-route';
+import {
+ defineRoute,
+ type SplitRouteDefinition,
+ type SplitRoutes,
+} from '@app/lib/split-router';
+import {
+ settingsSlugToTab,
+ settingsTabToSlug,
+} from '@core/constant/settingsTabsConfig';
+import { type Component, lazy } from 'solid-js';
+import { z } from 'zod';
+import type * as AppViews from './app-views';
+import { handleLegacySplitPath, legacySplitRoute } from './legacy-route';
+
+type AppViewSelector = (
+ views: typeof AppViews
+) => Component<Record<string, unknown>>;
+
+// URL parsing must not initialize the application views and their dependencies.
+function lazyView(select: AppViewSelector) {
+ return lazy(async () => {
+ const views = await import('./app-views');
+ return { default: views.withLaunchParams(() => select(views)) };
+ });
+}
+
+function viewRoute(
+ id: string,
+ view: AppViewSelector,
+ externalSearch: string[] = []
+) {
+ return defineRoute({
+ id: `view-${id}`,
+ path: id,
+ component: lazyView(view),
+ search: '*',
+ externalSearch,
+ claim: () => ({ namespace: 'component', id }),
+ });
+}
+
+const agentsSplitRoutes = ['agents', 'coders', 'agent-chats'].map((section) =>
+ defineRoute({
+ id: section,
+ path: section === 'agent-chats' ? 'agents/chat/:id' : `${section}/:id`,
+ aliases: section === 'agent-chats' ? ['agent-chats/:id'] : undefined,
+ params: z.object({ id: z.string() }),
+ component: lazyView((views) => views.AgentsRouteView),
+ remountKey: ({ id }: Record<string, unknown>) => String(id),
+ claim: ({ id }) => ({
+ namespace: section === 'agent-chats' ? 'chat' : 'agent',
+ id,
+ }),
+ })
+);
+
+const settingsSplitRoute = defineRoute({
+ id: 'settings',
+ path: 'settings/:tab?',
+ params: z.object({
+ tab: z
+ .string()
+ .refine((tab) => settingsSlugToTab(tab) !== undefined)
+ .default(settingsTabToSlug('Account')),
+ }),
+ component: lazyView((views) => views.SettingsView),
+ claim: () => ({ namespace: 'component', id: 'settings' }),
+ externalSearch: ['pair', 'createAgent'],
+});
+
+const DriveView = lazyView((views) => views.DriveRouteView);
+const DriveDetailView = lazy(async () => ({
+ default: (await import('@app/features/drive-view/components/DriveDetailView'))
+ .DriveDetailView,
+}));
+
+function withDriveComponents(
+ route: SplitRouteDefinition
+): SplitRouteDefinition {
+ return {
+ ...route,
+ component:
+ route.id === 'drive'
+ ? DriveView
+ : route.id.endsWith('-document')
+ ? DriveDetailView
+ : route.component,
+ children: route.children?.flatMap((child) =>
+ child ? [withDriveComponents(child)] : []
+ ),
+ };
+}
+
+export const appSplitRoutes: SplitRoutes = {
+ definitions: [
+ withDriveComponents(driveSplitRoute),
+ settingsSplitRoute,
+ ...agentsSplitRoutes,
+ viewRoute('home', (views) => views.HomeView),
+ viewRoute('getting-started', (views) => views.GettingStartedView),
+ viewRoute('inbox', (views) => views.InboxRouteView),
+ viewRoute('recent', (views) => views.RecentView),
+ viewRoute('activity', (views) => views.ActivityView),
+ viewRoute('reminders', (views) => views.RemindersView),
+ viewRoute('agents', (views) => views.AgentsRouteView, ['createAgent']),
+ viewRoute('mail', (views) => views.MailView),
+ viewRoute('tasks', (views) => views.TasksRouteView),
+ viewRoute('channels', (views) => views.ChannelsRouteView),
+ viewRoute('calls', (views) => views.CallsView),
+ viewRoute('companies', (views) => views.CompaniesView, ['crmView']),
+ viewRoute('folders', (views) => views.FoldersView),
+ viewRoute('search', (views) => views.SearchView),
+ legacySplitRoute,
+ ],
+ globalSearch: ['referral_code'],
+ unmatchedPathHandlers: [handleLegacySplitPath],
+ defaultEntry: () => ({
+ location: { route: { matches: [{ id: 'view-inbox', params: {} }] } },
+ }),
+};
diff --git a/apps/web/src/components/app/split-layout/split-router/app-views.tsx b/apps/web/src/components/app/split-layout/split-router/app-views.tsx
new file mode 100644
index 0000000000..e6c962d09c
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-router/app-views.tsx
@@ -0,0 +1,487 @@
+import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
+import { useActivityFeedFlag } from '@app/features/activity/use-activity-feed-flag';
+import { parseAgentsRoute } from '@app/features/agents-view/core/route';
+import { AgentsView } from '@app/features/agents-view/views/AgentsView';
+import { ChannelsView } from '@app/features/channels-view/channels-view';
+import {
+ DriveView,
+ type DriveViewProps,
+} from '@app/features/drive-view/drive-view';
+import { EmailView } from '@app/features/email-view/email-view';
+import { GettingStarted } from '@app/features/getting-started';
+import { Home } from '@app/features/home';
+import { InboxView } from '@app/features/inbox-view/inbox-view';
+import { queryStateFrom } from '@app/features/next-soup/filters/filter-store';
+import type { SetPredicatesInput } from '@app/features/next-soup/filters/filter-store/predicates-store';
+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 { useRecentViewFlag } from '@app/features/next-soup/use-recent-view-flag';
+import { McpConnections } from '@app/features/settings/McpConnections';
+import { SettingsPanelComponentWrapper } from '@app/features/settings/Settings';
+import { TasksView } from '@app/features/tasks-view/tasks-view';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { useFeatureFlag, usePosthog } from '@app/lib/analytics/posthog';
+import {
+ CRM_VIEW_URL_PARAM,
+ decodeCrmViewParam,
+} from '@companies/crm/saved-views';
+import { useIsAuthenticated } from '@core/auth';
+import { LoadingBlock } from '@core/component/LoadingBlock';
+import {
+ enableChatV3Agents,
+ enableCrm,
+ enableNewAppViews,
+ enableReminders,
+ isFeatureEnabled,
+} from '@core/constant/featureFlags';
+import { useUserContext } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { useAutomationEntities } from '@queries/agent-schedule/entities';
+import {
+ type Component,
+ createRenderEffect,
+ createSignal,
+ type JSX,
+ lazy,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import type { SplitContent } from '../layoutManager';
+import { useSplitPanelOrThrow } from '../layoutUtils';
+
+// Legacy fallbacks are loaded only when a view actually needs them.
+const SoupView = lazy(async () => ({
+ default: (await import('@app/features/next-soup/soup-view/soup-view'))
+ .SoupView,
+}));
+
+export function usePageViewTracking(pageTitle: string) {
+ const analytics = useAnalytics();
+ onMount(() => {
+ analytics.pageView(pageTitle);
+ analytics.track('open_view', { viewId: pageTitle });
+ });
+}
+
+export function withAuth<P extends object>(View: Component<P>): Component<P> {
+ return (props) => {
+ const authenticated = useIsAuthenticated();
+ return (
+ <Show when={authenticated()} fallback={<LoadingBlock />}>
+ <View {...props} />
+ </Show>
+ );
+ };
+}
+
+// Settings URL helpers also read app routes. Resolve the component only when
+// rendering, so route declarations never capture a partially initialized module.
+export function withLaunchParams(
+ view: () => Component<Record<string, unknown>>
+) {
+ return () => {
+ const View = view();
+ const content = useSplitPanelOrThrow().handle.content();
+ return <View {...(content.type === 'component' ? content.params : {})} />;
+ };
+}
+
+export function RedirectSplit(props: { to: SplitContent }) {
+ const panel = useSplitPanelOrThrow();
+ onMount(() => panel.handle.replace({ next: props.to }));
+ return null;
+}
+
+/** App-only feature gating and shell metadata; feature views stay route-agnostic. */
+function NewAppView(props: {
+ id: string;
+ children: JSX.Element;
+ fallback: JSX.Element;
+ desktopOnly?: boolean;
+ composableOnTouch?: boolean;
+}) {
+ usePageViewTracking(props.id);
+ const panel = useSplitPanelOrThrow();
+ const flag = useFeatureFlag(enableNewAppViews);
+ const [timedOut, setTimedOut] = createSignal(false);
+ const timer = setTimeout(() => setTimedOut(true), 5_000);
+ onCleanup(() => clearTimeout(timer));
+ const ready = () => !flag().loading || timedOut();
+ const enabled = () => ready() && flag().enabled;
+ createRenderEffect(() => {
+ if (!ready()) return;
+ panel.handle.updateMeta?.({
+ splitPanelLayout:
+ enabled() && (!isTouchDevice() || props.composableOnTouch)
+ ? 'composable'
+ : 'legacy',
+ });
+ });
+ return (
+ <Show
+ when={ready() || (props.desktopOnly && isTouchDevice())}
+ fallback={<LoadingBlock />}
+ >
+ <Show
+ when={enabled() && (!props.desktopOnly || !isTouchDevice())}
+ fallback={props.fallback}
+ >
+ {props.children}
+ </Show>
+ </Show>
+ );
+}
+
+export const HomeView = withAuth(() => {
+ usePageViewTracking('home');
+ return <Home />;
+});
+export const GettingStartedView = withAuth(() => {
+ usePageViewTracking('getting-started');
+ return <GettingStarted />;
+});
+
+function LegacyInboxView() {
+ const preset = getViewPreset('inbox');
+ return (
+ <SoupView
+ viewName={isTouchDevice() ? 'Notifications' : 'Home'}
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ disableLocalSearch
+ />
+ );
+}
+export const InboxRouteView = withAuth(() => (
+ <NewAppView id="inbox" composableOnTouch fallback={<LegacyInboxView />}>
+ <InboxView />
+ </NewAppView>
+));
+
+function TrackedRecentView() {
+ usePageViewTracking('recent');
+ const preset = getViewPreset('recent');
+ return (
+ <SoupView
+ viewName="Recent"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialClientSort={['touched_at']}
+ disableLocalSearch
+ />
+ );
+}
+export const RecentView = withAuth(() => {
+ const enabled = useRecentViewFlag();
+ const posthog = usePosthog();
+ return (
+ <Show
+ when={enabled()}
+ fallback={
+ <Show when={posthog.flagsLoaded()}>
+ <RedirectSplit to={{ type: 'component', id: 'inbox' }} />
+ </Show>
+ }
+ >
+ <TrackedRecentView />
+ </Show>
+ );
+});
+
+const MyActivityView = lazy(async () => ({
+ default: (await import('@app/features/activity/views/my-activity-view'))
+ .MyActivityView,
+}));
+function TrackedActivityView() {
+ usePageViewTracking('activity');
+ return <MyActivityView onOpen={openEntityInSplit} />;
+}
+export const ActivityView = withAuth(() => {
+ const enabled = useActivityFeedFlag();
+ const posthog = usePosthog();
+ return (
+ <Show
+ when={enabled()}
+ fallback={
+ <Show when={posthog.flagsLoaded()}>
+ <RedirectSplit to={{ type: 'component', id: 'inbox' }} />
+ </Show>
+ }
+ >
+ <TrackedActivityView />
+ </Show>
+ );
+});
+
+export const RemindersView = withAuth(() => {
+ if (!isFeatureEnabled(enableReminders))
+ return <RedirectSplit to={{ type: 'component', id: 'inbox' }} />;
+ usePageViewTracking('reminders');
+ const preset = getViewPreset('reminders');
+ return (
+ <SoupView
+ viewName="Reminders"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ disableLocalSearch
+ />
+ );
+});
+
+function LegacyAgentsView() {
+ const user = useUserContext();
+ const preset = getViewPreset('agents', undefined, {
+ userId: user.userId(),
+ isTeamAdmin: false,
+ });
+ const entities = useAutomationEntities();
+ return (
+ <SoupView
+ viewName="Agents"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ additionalEntities={entities}
+ />
+ );
+}
+export const AgentsRouteView = withAuth((params: Record<string, unknown>) => {
+ const panel = useSplitPanelOrThrow();
+ const route = parseAgentsRoute(
+ typeof params.agentsRoute === 'string'
+ ? params.agentsRoute
+ : panel.handle.content().id
+ );
+ usePageViewTracking('agents');
+ const flag = useFeatureFlag(enableChatV3Agents);
+ const enabled = () => flag().enabled && !isTouchDevice();
+ const connectionsRequested = () => {
+ const content = panel.handle.content();
+ return (
+ content.type === 'component' &&
+ content.params?.agentPage === 'connections'
+ );
+ };
+ createRenderEffect(() => {
+ if (!flag().loading)
+ panel.handle.updateMeta?.({
+ splitPanelLayout: enabled() ? 'composable' : 'legacy',
+ });
+ });
+ return (
+ <Show when={!flag().loading} fallback={<LoadingBlock />}>
+ <Show
+ when={enabled()}
+ fallback={
+ <Show
+ when={connectionsRequested()}
+ fallback={
+ route ? (
+ <RedirectSplit
+ to={{
+ type:
+ route.conversation.type === 'agent_session'
+ ? 'agent'
+ : 'chat',
+ id: route.conversation.id,
+ }}
+ />
+ ) : (
+ <LegacyAgentsView />
+ )
+ }
+ >
+ <McpConnections />
+ </Show>
+ }
+ >
+ <AgentsView initialRoute={route} />
+ </Show>
+ </Show>
+ );
+});
+
+function LegacyMailView() {
+ const preset = getViewPreset('mail');
+ return (
+ <SoupView
+ viewName="Email"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ />
+ );
+}
+export const MailView = withAuth(() => (
+ <NewAppView id="mail" fallback={<LegacyMailView />}>
+ <EmailView />
+ </NewAppView>
+));
+
+export const DriveRouteView = withAuth(
+ (
+ props: DriveViewProps & {
+ initialFilters?: Query;
+ initialClientFilters?: SetPredicatesInput<string>;
+ }
+ ) => {
+ const user = useUserContext();
+ const preset = getViewPreset('documents', undefined, {
+ userId: user.userId(),
+ isTeamAdmin: false,
+ });
+ const initialFilters =
+ preset?.filters && props.initialFilters
+ ? mergeQuery(queryStateFrom(preset.filters), props.initialFilters)
+ : (props.initialFilters ?? preset?.filters);
+ const initialClientFilters =
+ preset?.clientFilters && props.initialClientFilters
+ ? {
+ and: [
+ ...new Set([
+ ...(preset.clientFilters.and ?? []),
+ ...(props.initialClientFilters.and ?? []),
+ ]),
+ ],
+ or: [
+ ...new Set([
+ ...(preset.clientFilters.or ?? []),
+ ...(props.initialClientFilters.or ?? []),
+ ]),
+ ],
+ }
+ : (props.initialClientFilters ?? preset?.clientFilters);
+ return (
+ <NewAppView
+ id="documents"
+ composableOnTouch
+ fallback={
+ <SoupView
+ viewName="Files"
+ initialFilters={initialFilters}
+ initialClientFilters={initialClientFilters}
+ initialGroupBy={preset?.groupBy}
+ />
+ }
+ >
+ <DriveView initialFacets={props.initialFacets} />
+ </NewAppView>
+ );
+ }
+);
+
+function LegacyTasksView() {
+ const user = useUserContext();
+ const preset = getViewPreset('tasks', undefined, {
+ userId: user.userId(),
+ isTeamAdmin: false,
+ });
+ return (
+ <SoupView
+ viewName="Tasks"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ />
+ );
+}
+export const TasksRouteView = withAuth(() => (
+ <NewAppView id="tasks" composableOnTouch fallback={<LegacyTasksView />}>
+ <TasksView />
+ </NewAppView>
+));
+
+function LegacyChannelsView() {
+ const preset = getViewPreset('channels');
+ return (
+ <SoupView
+ viewName="Channels"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ />
+ );
+}
+export const ChannelsRouteView = withAuth(() => (
+ <NewAppView id="channels" fallback={<LegacyChannelsView />}>
+ <ChannelsView />
+ </NewAppView>
+));
+
+export const CallsView = withAuth(() => {
+ usePageViewTracking('calls');
+ const preset = getViewPreset('calls');
+ return (
+ <SoupView
+ viewName="Calls"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ />
+ );
+});
+export const CompaniesView = withAuth(() => {
+ if (!isFeatureEnabled(enableCrm))
+ return <RedirectSplit to={{ type: 'component', id: 'inbox' }} />;
+ usePageViewTracking('companies');
+ const panel = useSplitPanelOrThrow();
+ createRenderEffect(() =>
+ panel.handle.updateMeta?.({
+ splitPanelLayout: isTouchDevice() ? 'legacy' : 'composable',
+ })
+ );
+ const preset = getViewPreset('companies');
+ const crmView = new URLSearchParams(window.location.search).get(
+ CRM_VIEW_URL_PARAM
+ );
+ return (
+ <SoupView
+ viewName="Customers"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ initialCrmView={crmView ? decodeCrmViewParam(crmView) : undefined}
+ />
+ );
+});
+export const FoldersView = withAuth(() => {
+ usePageViewTracking('folders');
+ const user = useUserContext();
+ const preset = getViewPreset('folders', undefined, {
+ userId: user.userId(),
+ isTeamAdmin: false,
+ });
+ return (
+ <SoupView
+ viewName="Folders"
+ initialFilters={preset?.filters}
+ initialClientFilters={preset?.clientFilters}
+ initialGroupBy={preset?.groupBy}
+ />
+ );
+});
+export const SearchView = withAuth(
+ (props: {
+ initialQuery?: string;
+ initialFilters?: Query;
+ initialClientFilters?: SetPredicatesInput<string>;
+ }) => {
+ usePageViewTracking('search');
+ const preset = getViewPreset('search');
+ return (
+ <SoupView
+ viewName="Search"
+ initialFilters={props.initialFilters ?? preset?.filters}
+ initialClientFilters={
+ props.initialClientFilters ?? preset?.clientFilters
+ }
+ initialSearchText={props.initialQuery}
+ />
+ );
+ }
+);
+export const SettingsView = SettingsPanelComponentWrapper;
diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
new file mode 100644
index 0000000000..0f8acf377f
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
@@ -0,0 +1,327 @@
+import {
+ agentsRouteFromSegments,
+ agentsRouteSegments,
+} from '@app/features/agents-view/core/route';
+import type { DriveLocation } from '@app/features/drive-view/core/types';
+import {
+ type DriveDocumentRoute,
+ driveDestination,
+} from '@app/features/drive-view/primitives/drive-route';
+import {
+ defineRoute,
+ routeParams,
+ type SplitLocation,
+ type SplitRouteMatch,
+ type SplitRouterEntry,
+ type UnmatchedSplitPathHandler,
+} from '@app/lib/split-router';
+import {
+ assertRouteState,
+ decodeRoute,
+ encodeRoute,
+ filterRouteSearch,
+ type SplitRoutesManifest,
+} from '@app/lib/split-router/routes';
+import { parseSearchState } from '@app/lib/split-router/search';
+import { isRecord } from '@app/lib/split-router/utils';
+import type { BlockAlias, BlockName } from '@core/block';
+import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';
+import { z } from 'zod';
+import type { SplitContent } from '../layoutManager';
+
+export function decodeLegacyPair(
+ type: string,
+ id: string
+): SplitContent | undefined {
+ if (!type || !id) return;
+
+ const agentsRoute = agentsRouteFromSegments(type, id);
+ if (agentsRoute) return { type: 'component', id: agentsRoute };
+
+ if (type === 'settings') {
+ return { type: 'component', id: 'settings' };
+ }
+
+ if (type === 'component') {
+ // Retired Preview Pair placeholders must never reach the view registry.
+ return {
+ type: 'component',
+ id: id === 'preview-empty' || id === 'non-member-channel' ? 'inbox' : id,
+ };
+ }
+
+ const resolvedType = resolveBlockAlias(type as BlockName | BlockAlias);
+
+ if (isBlockAlias(type)) {
+ return {
+ type,
+ id,
+ aliasContext: {
+ alias: type,
+ baseType: resolvedType,
+ },
+ };
+ }
+
+ return { type: resolvedType, id };
+}
+
+function legacyEntry(type: string, id: string): SplitRouterEntry | undefined {
+ const agentsRoute = agentsRouteFromSegments(type, id);
+ if (agentsRoute) {
+ return {
+ location: {
+ route: { matches: [{ id: type, params: { id } }] },
+ },
+ };
+ }
+
+ if (type === 'settings') {
+ return {
+ location: {
+ route: { matches: [{ id: 'settings', params: { tab: id } }] },
+ },
+ };
+ }
+
+ if (type === 'component' && id === 'settings') {
+ return {
+ location: {
+ route: { matches: [{ id: 'settings', params: { tab: 'account' } }] },
+ },
+ };
+ }
+
+ if (type === 'component' && id === 'documents') {
+ return {
+ location: { route: { matches: [{ id: 'drive', params: {} }] } },
+ };
+ }
+
+ if (!decodeLegacyPair(type, id)) return;
+
+ return {
+ location: {
+ route: {
+ matches: [{ id: 'legacy-content', params: { type, id } }],
+ },
+ },
+ };
+}
+
+export const handleLegacySplitPath: UnmatchedSplitPathHandler = (context) => {
+ const { segments } = context;
+
+ if (segments.length === 1 && ['documents', 'files'].includes(segments[0]!)) {
+ return [
+ {
+ location: {
+ route: { matches: [{ id: 'drive', params: {} }] },
+ },
+ },
+ ];
+ }
+
+ if (
+ context.matchedRouteId &&
+ context.matchedRouteId !== 'settings' &&
+ !context.matchedRouteId.startsWith('view-') &&
+ context.matchedRouteId !== 'legacy-content'
+ ) {
+ return;
+ }
+ if (segments.length < 2 || segments.length % 2 !== 0) return;
+
+ const entries = [];
+
+ for (let index = 0; index < segments.length; index += 2) {
+ if (
+ segments[index] === 'component' &&
+ (segments[index + 1] === 'preview-empty' ||
+ segments[index + 1] === 'non-member-channel')
+ )
+ continue;
+ const entry = legacyEntry(segments[index]!, segments[index + 1]!);
+
+ if (!entry) return;
+
+ entries.push(entry);
+ }
+
+ return entries;
+};
+
+export function encodeLegacyContent(content: SplitContent): string[] {
+ return [
+ content.type === 'component'
+ ? content.type
+ : content.aliasContext?.alias || content.type,
+ content.id,
+ ];
+}
+
+export function driveSplitContent(
+ location: DriveLocation,
+ document?: DriveDocumentRoute
+): SplitContent {
+ const matches: [SplitRouteMatch, ...SplitRouteMatch[]] = [
+ { id: 'drive', params: {} },
+ ];
+ if (location.kind === 'folder') {
+ matches.push({
+ id: 'drive-folder',
+ params: { view: 'folder', folderId: location.id ?? undefined },
+ });
+ } else if (location.tab !== 'owned') {
+ matches.push({ id: 'drive-tab', params: { tab: location.tab } });
+ }
+ if (document) {
+ matches.push({
+ id: driveDestination(location, document).route.id,
+ params: { documentId: document.id, documentType: document.type },
+ });
+ }
+ return {
+ type: 'component',
+ id: 'documents',
+ entryMetadata: { route: { matches } },
+ };
+}
+
+export function splitLocationFromContent(
+ routes: SplitRoutesManifest,
+ content: SplitContent
+): SplitLocation {
+ if (content.type === 'component' && content.id === 'documents') {
+ return { route: { matches: [{ id: 'drive', params: {} }] } };
+ }
+
+ if (content.type === 'component' && content.id === 'settings') {
+ return {
+ route: {
+ matches: [{ id: 'settings', params: { tab: 'account' } }],
+ },
+ };
+ }
+
+ if (content.type === 'component') {
+ const viewId = `view-${content.id}`;
+ if (routes.byId.has(viewId)) {
+ return { route: { matches: [{ id: viewId, params: {} }] } };
+ }
+ const segments = agentsRouteSegments(content.id);
+ const [section, id] = segments ?? [];
+ if (section && id) {
+ return { route: { matches: [{ id: section, params: { id } }] } };
+ }
+ }
+
+ const [type, id] = encodeLegacyContent(content);
+ return {
+ route: {
+ matches: [{ id: 'legacy-content', params: { type, id } }],
+ },
+ };
+}
+
+/** Resolve legacy/persisted metadata before it reaches router state. */
+export function resolveContentLocation(
+ routes: SplitRoutesManifest,
+ content: SplitContent
+): SplitLocation {
+ const metadata = isRecord(content.entryMetadata)
+ ? content.entryMetadata
+ : undefined;
+ const resolve = (route: unknown) => {
+ assertRouteState(routes, route);
+ // Go through the URL representation, not schema validation of schema outputs.
+ const decoded = decodeRoute(
+ routes,
+ encodeRoute(routes, { location: { route } })
+ );
+ if (
+ !decoded ||
+ decoded.location.route.matches.length !== route.matches.length ||
+ decoded.location.route.matches.some(
+ (match, index) => match.id !== route.matches[index]!.id
+ )
+ ) {
+ throw new Error('Split content did not resolve to its route');
+ }
+ return decoded.location.route;
+ };
+ let route: SplitLocation['route'] | undefined;
+ if (metadata?.route !== undefined) {
+ try {
+ route = resolve(metadata.route);
+ } catch {
+ // Old or malformed metadata falls back to the content's compatibility route.
+ }
+ }
+ route ??= resolve(splitLocationFromContent(routes, content).route);
+ const search = filterRouteSearch(
+ routes,
+ route,
+ parseSearchState(metadata?.search)
+ );
+ return search ? { route, search } : { route };
+}
+
+export function splitContentFromLocation(
+ location: SplitLocation
+): SplitContent {
+ const root = location.route.matches[0];
+
+ if (root.id.startsWith('view-'))
+ return { type: 'component', id: root.id.slice('view-'.length) };
+ if (root.id === 'drive') return { type: 'component', id: 'documents' };
+ if (root.id === 'settings') return { type: 'component', id: 'settings' };
+
+ const params = routeParams(location.route);
+ if (
+ root.id === 'agents' ||
+ root.id === 'coders' ||
+ root.id === 'agent-chats'
+ ) {
+ const id = typeof params.id === 'string' ? params.id : undefined;
+ const componentId = id ? agentsRouteFromSegments(root.id, id) : undefined;
+ if (componentId) return { type: 'component', id: componentId };
+ throw new Error(`Invalid ${root.id} split route`);
+ }
+
+ if (root.id === 'legacy-content') {
+ const type = typeof params.type === 'string' ? params.type : undefined;
+ const id = typeof params.id === 'string' ? params.id : undefined;
+ const content = type && id ? decodeLegacyPair(type, id) : undefined;
+ if (content) return content;
+ }
+
+ throw new Error(`No split content matched route "${root.id}"`);
+}
+
+export const legacySplitRoute = defineRoute({
+ id: 'legacy-content',
+ path: ':type/:id',
+ search: '*',
+ params: z.object({ type: z.string().min(1), id: z.string().min(1) }),
+ claim: ({ type, id }) => {
+ const content = decodeLegacyPair(type, id);
+ if (!content) return;
+
+ if (content.type === 'component') {
+ const [section, conversationId] = agentsRouteSegments(content.id) ?? [];
+ if (section && conversationId) {
+ return {
+ namespace: section === 'agent-chats' ? 'chat' : 'agent',
+ id: conversationId,
+ };
+ }
+ return { namespace: 'component', id: content.id };
+ }
+
+ return {
+ namespace: 'block',
+ id: `${content.aliasContext?.baseType ?? content.type}:${id}`,
+ };
+ },
+});
diff --git a/apps/web/src/components/app/split-layout/splitRouterLayout.ts b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
new file mode 100644
index 0000000000..8fc9208797
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
@@ -0,0 +1,160 @@
+import type {
+ BrowserHistoryIntent,
+ SplitLocation,
+ SplitRouterEntry,
+ SplitRouterLayout,
+ SplitRouterLayoutSnapshot,
+ SplitRoutesManifest,
+} from '@app/lib/split-router';
+import deepEqual from 'fast-deep-equal';
+import { createEffect, createRoot, on } from 'solid-js';
+import type { SplitContent, SplitId, SplitManager } from './layoutManager';
+import {
+ resolveContentLocation,
+ splitContentFromLocation,
+} from './split-router/legacy-route';
+
+export type AppSplitRouterLayout = SplitRouterLayout<SplitId>;
+type AppSplitRouterSnapshot = SplitRouterLayoutSnapshot<SplitId>;
+
+const withoutLocation = (content: SplitContent): SplitContent => {
+ const result = { ...content };
+
+ delete result.entryMetadata;
+
+ return result;
+};
+
+const withLocation = (
+ content: SplitContent,
+ location: SplitLocation
+): SplitContent => ({
+ ...content,
+ entryMetadata: location,
+});
+
+const sameContent = (left: SplitContent, right: SplitContent) =>
+ left.type === right.type && left.id === right.id;
+
+function contentForLocation(
+ location: SplitLocation,
+ current?: SplitContent
+): SplitContent {
+ const routed = splitContentFromLocation(location);
+ const content = current && sameContent(current, routed) ? current : routed;
+ return withLocation(withoutLocation(content), location);
+}
+
+const sameRouterEntries = (
+ previous: AppSplitRouterSnapshot['entries'],
+ current: AppSplitRouterSnapshot['entries']
+) =>
+ previous.length === current.length &&
+ previous.every((entry, index) => {
+ const next = current[index];
+
+ return (
+ next !== undefined &&
+ Object.is(entry.splitId, next.splitId) &&
+ deepEqual(entry.location, next.location)
+ );
+ });
+
+function changeHistory(
+ manager: SplitManager,
+ previous: SplitRouterEntry[],
+ next: SplitRouterEntry[]
+): BrowserHistoryIntent {
+ const index = next.findIndex((entry, entryIndex) => {
+ const before = previous[entryIndex];
+ return !before || !deepEqual(before.location.route, entry.location.route);
+ });
+
+ if (index < 0) return 'push';
+
+ const changed = manager.getVisibleSplits()[index];
+
+ return changed?.lastNavigationCause === 'replace' ? 'replace' : 'push';
+}
+
+export function createAppSplitRouterLayout(
+ manager: SplitManager,
+ routes: SplitRoutesManifest
+): AppSplitRouterLayout {
+ const locationOf = (content: SplitContent) =>
+ resolveContentLocation(routes, content);
+ const snapshot = (): AppSplitRouterSnapshot => ({
+ entries: manager.getVisibleSplits().map((split) => ({
+ splitId: split.id,
+ location: locationOf(split.content),
+ })),
+ });
+
+ return {
+ snapshot,
+
+ updateCurrentEntry(splitId, update) {
+ const handle = manager.getSplit(splitId);
+
+ if (!handle) return;
+
+ handle.updateCurrentEntry((content) => {
+ const next = update({
+ splitId,
+ location: locationOf(content),
+ });
+
+ return contentForLocation(next.location, content);
+ });
+ },
+
+ open({ location, target, replace }) {
+ const handle =
+ target && target !== 'new-split' ? manager.getSplit(target) : undefined;
+
+ manager.openWithSplit(contentForLocation(location), {
+ handle,
+ preferNewSplit: target === 'new-split',
+ allowDuplicate: target === 'new-split',
+ mergeHistory: replace,
+ referredFrom: null,
+ });
+ },
+
+ reconcile(entries) {
+ const visible = manager.getVisibleSplits();
+ manager.reconcile(
+ entries.map((entry, index) =>
+ contentForLocation(entry.location, visible[index]?.content)
+ )
+ );
+ },
+
+ activate(splitId) {
+ manager.getSplit(splitId)?.activate();
+ },
+
+ subscribe(listener) {
+ return createRoot((dispose) => {
+ let previous = snapshot().entries;
+ createEffect(
+ on(
+ () => manager.getVisibleSplits(),
+ () => {
+ const current = snapshot().entries;
+ if (sameRouterEntries(previous, current)) return;
+
+ listener({
+ history: changeHistory(manager, previous, current),
+ });
+ previous = current;
+ },
+ { defer: true }
+ )
+ );
+
+ return dispose;
+ });
+ },
+ };
+}
diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
index 647578f400..106b9d909e 100644
--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
@@ -54,7 +54,9 @@ vi.mock('@app/features/next-soup/sidebar/soup-filter-presets', () => ({}));
vi.mock('@app/features/next-soup/soup-view/soup-view', () => ({}));
vi.mock('@app/features/next-soup/use-recent-view-flag', () => ({}));
vi.mock('@app/features/reminders/ReminderEditorSplit', () => ({}));
-vi.mock('@app/features/settings/Settings', () => ({}));
+vi.mock('@app/features/settings/Settings', () => ({
+ SettingsPanelComponentWrapper: () => null,
+}));
vi.mock('@app/features/tasks-view/tasks-view', () => ({}));
vi.mock('@app/signal/splitLayout', () => ({}));
vi.mock('@block-calendar/components/EventComposerSplit', () => ({}));
diff --git a/apps/web/src/components/app/split-layout/tests/app-route-isolation.test.ts b/apps/web/src/components/app/split-layout/tests/app-route-isolation.test.ts
new file mode 100644
index 0000000000..e387a5708e
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/tests/app-route-isolation.test.ts
@@ -0,0 +1,38 @@
+import {
+ createRoutesManifest,
+ decodeRoute,
+} from '@app/lib/split-router/routes';
+import { describe, expect, it, vi } from 'vitest';
+import { appSplitRoutes } from '../split-router/app-routes';
+
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
+vi.mock('../split-router/app-views', () => {
+ throw new Error('Route declarations must not eagerly load application views');
+});
+vi.mock('@app/features/drive-view/components/DriveDetailView', () => {
+ throw new Error('Route declarations must not eagerly load document views');
+});
+
+describe('application route import isolation', () => {
+ it('builds and decodes routes without initializing view modules', () => {
+ const routes = createRoutesManifest(appSplitRoutes);
+ for (const path of [
+ ['mail'],
+ ['tasks'],
+ ['settings', 'account'],
+ ['drive', 'md', 'doc'],
+ ]) {
+ expect(decodeRoute(routes, path)).toBeDefined();
+ }
+ });
+});
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.ts
index 2d2bf236d7..2011eb5ea1 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,10 +1,14 @@
import { agentsRouteId } from '@app/features/agents-view/core/route';
+import { driveSplitRoute } from '@app/features/drive-view/primitives/drive-route';
import {
getListNavigationSource,
listNavigationSourceId,
registerListNavigationSource,
withListNavigationSource,
} from '@app/features/soup/collection/list-navigation-source';
+import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';
+import { createSplitRouter } from '@app/lib/split-router/router';
+import { createRoutesManifest } from '@app/lib/split-router/routes';
import type { ResizeZoneCtx } from '@core/component/Resize/types';
import { toast } from '@core/component/Toast/Toast';
import type { BlockOrchestrator } from '@core/orchestrator';
@@ -20,6 +24,7 @@ import {
shouldShowSplitCloseButton,
} from '../layoutUtils';
import { createMobileSwipeLayout } from '../mobile/createMobileSwipeLayout';
+import { createAppSplitRouterLayout } from '../splitRouterLayout';
vi.mock('@core/component/Toast/Toast', () => ({
toast: { alert: vi.fn() },
@@ -803,6 +808,156 @@ describe('layoutManager', () => {
});
});
+ describe('router layout synchronization', () => {
+ it.each(['drive', 'drive/md/second-document'])(
+ 'navigates a second Drive pane independently from %s, including history',
+ (initialPath) => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'documents' },
+ { type: 'component', id: 'documents' },
+ ]);
+ const routes = createRoutesManifest({
+ definitions: [driveSplitRoute],
+ });
+ const router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location: createMemorySplitRouterLocation(
+ `/drive/~/${initialPath}`
+ ),
+ });
+ const [first, second] = manager.splits();
+ const firstRoute = router.route(first.id);
+ manager.activateSplit(second.id);
+
+ router.navigate(second.id, '/drive/folder/second-folder');
+ const folderRoute = router.route(second.id);
+ expect(folderRoute?.matches.at(-1)).toEqual({
+ id: 'drive-folder',
+ params: { view: 'folder', folderId: 'second-folder' },
+ });
+ expect(router.route(first.id)).toEqual(firstRoute);
+ expect(manager.activeSplitId()).toBe(second.id);
+
+ router.navigate(second.id, '/drive/md/another-document');
+ expect(router.route(second.id)?.matches.at(-1)?.params).toEqual({
+ documentType: 'md',
+ documentId: 'another-document',
+ });
+ router.navigate(second.id, -1);
+ expect(router.route(second.id)).toEqual(folderRoute);
+ expect(router.route(first.id)).toEqual(firstRoute);
+ expect(manager.activeSplitId()).toBe(second.id);
+
+ router.navigate(second.id, '/drive/shared');
+ expect(router.route(second.id)?.matches.at(-1)).toEqual({
+ id: 'drive-tab',
+ params: { tab: 'shared' },
+ });
+ expect(router.route(first.id)).toEqual(firstRoute);
+ expect(manager.splits()).toHaveLength(2);
+ router.dispose();
+ dispose();
+ });
+ }
+ );
+
+ it('still activates the owner when another Drive pane opens the same document', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'documents' },
+ { type: 'component', id: 'documents' },
+ ]);
+ const routes = createRoutesManifest({
+ definitions: [driveSplitRoute],
+ });
+ const router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location: createMemorySplitRouterLocation(
+ '/drive/md/first-document/~/drive/md/second-document'
+ ),
+ });
+ const [first, second] = manager.splits();
+ const secondRoute = router.route(second.id);
+ manager.activateSplit(second.id);
+
+ router.navigate(second.id, '/drive/md/first-document');
+
+ expect(manager.activeSplitId()).toBe(first.id);
+ expect(router.route(second.id)).toEqual(secondRoute);
+ expect(manager.splits()).toHaveLength(2);
+ router.dispose();
+ dispose();
+ });
+ });
+
+ it('does not publish manager updates that leave router state unchanged', async () => {
+ let dispose!: () => void;
+ let updateEntry!: (state: Record<string, unknown>) => void;
+ let updateLocation!: (folderId?: string) => void;
+ const listener = vi.fn();
+
+ createRoot((rootDispose) => {
+ dispose = rootDispose;
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'documents' },
+ ]);
+ const split = manager.getSplit(manager.splits()[0]!.id)!;
+ const layout = createAppSplitRouterLayout(
+ manager,
+ createRoutesManifest({
+ definitions: [
+ {
+ id: 'drive',
+ path: 'drive',
+ children: [{ id: 'drive-folder', path: 'folder/:folderId' }],
+ },
+ ],
+ })
+ );
+ layout.subscribe(listener);
+
+ updateEntry = (state) => {
+ split.updateCurrentEntry((current) => ({ ...current, state }));
+ };
+ updateLocation = (folderId) => {
+ split.updateCurrentEntry((current) => ({
+ ...current,
+ entryMetadata: {
+ route: {
+ matches: folderId
+ ? [
+ { id: 'drive', params: {} },
+ { id: 'drive-folder', params: { folderId } },
+ ]
+ : [{ id: 'drive', params: {} }],
+ },
+ },
+ }));
+ };
+ });
+ await Promise.resolve();
+
+ updateEntry({ scrollOffset: 120 });
+ await Promise.resolve();
+
+ expect(listener).not.toHaveBeenCalled();
+
+ updateLocation();
+ await Promise.resolve();
+
+ expect(listener).not.toHaveBeenCalled();
+
+ updateLocation('folder-1');
+ await Promise.resolve();
+
+ expect(listener).toHaveBeenCalledOnce();
+ dispose();
+ });
+ });
+
describe('entry state', () => {
it('captures registered entry state and merges with existing state', () => {
createRoot((dispose) => {
@@ -836,6 +991,143 @@ describe('layoutManager', () => {
});
});
+ describe('entry metadata', () => {
+ it('skips structurally equal metadata during reconciliation', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ {
+ type: 'component',
+ id: 'documents',
+ entryMetadata: {
+ route: { matches: [{ id: 'drive', params: {} }] },
+ search: { drive: { tags: ['one'] } },
+ },
+ },
+ ]);
+ const before = manager.splits()[0]!;
+ const metadataBefore = before.content.entryMetadata;
+
+ manager.reconcile([
+ {
+ type: 'component',
+ id: 'documents',
+ entryMetadata: {
+ route: { matches: [{ id: 'drive', params: {} }] },
+ search: { drive: { tags: ['one'] } },
+ },
+ },
+ ]);
+
+ expect(manager.splits()[0]).toBe(before);
+ expect(manager.splits()[0]?.content.entryMetadata).toBe(metadataBefore);
+
+ dispose();
+ });
+ });
+
+ it('updates the current entry without remounting or emitting content changes', () => {
+ createRoot((dispose) => {
+ const orchestrator = createMockOrchestrator();
+ const manager = createSplitLayout(orchestrator, [
+ {
+ type: 'md',
+ id: 'doc-1',
+ entryMetadata: { source: 'initial' },
+ },
+ ]);
+ const split = manager.getSplit(manager.splits()[0].id)!;
+ const initialHistoryLength = split.history().length;
+ const listener = vi.fn();
+ split.registerContentChangeListener(listener);
+
+ split.updateCurrentEntry((current) => ({
+ ...current,
+ entryMetadata: { source: 'updated' },
+ }));
+
+ expect(split.history()).toHaveLength(initialHistoryLength);
+ expect(split.content().entryMetadata).toEqual({
+ source: 'updated',
+ });
+ expect(split.history().at(-1)?.entryMetadata).toEqual(
+ split.content().entryMetadata
+ );
+ expect(orchestrator.createBlockInstance).toHaveBeenCalledOnce();
+ expect(listener).not.toHaveBeenCalled();
+
+ dispose();
+ });
+ });
+
+ it('applies inbound metadata to same-identity content only', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ {
+ type: 'component',
+ id: 'documents',
+ params: { privateParam: 'retained' },
+ state: { privateState: 'retained' },
+ entryMetadata: { source: 'initial' },
+ },
+ ]);
+ const split = manager.getSplit(manager.splits()[0].id)!;
+ const mountBefore = manager.splits()[0].mount;
+ const listener = vi.fn();
+ split.registerContentChangeListener(listener);
+
+ manager.reconcile([
+ {
+ type: 'component',
+ id: 'documents',
+ params: { privateParam: 'ignored' },
+ state: { privateState: 'ignored' },
+ entryMetadata: { source: 'inbound' },
+ },
+ ]);
+
+ expect(split.content()).toEqual({
+ type: 'component',
+ id: 'documents',
+ params: { privateParam: 'retained' },
+ state: { privateState: 'retained' },
+ entryMetadata: { source: 'inbound' },
+ });
+ expect(split.history().at(-1)).toEqual(split.content());
+ expect(manager.splits()[0].mount).toBe(mountBefore);
+ expect(listener).not.toHaveBeenCalled();
+
+ dispose();
+ });
+ });
+
+ it('restores metadata with the containing split-history entry', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'md', id: 'doc-1' },
+ ]);
+ const split = manager.getSplit(manager.splits()[0].id)!;
+ split.updateCurrentEntry((current) => ({
+ ...current,
+ entryMetadata: { source: 'first-entry' },
+ }));
+
+ split.replace({
+ next: {
+ type: 'md',
+ id: 'doc-2',
+ entryMetadata: { source: 'second-entry' },
+ },
+ });
+ split.goBack();
+
+ expect(split.content().entryMetadata).toEqual({
+ source: 'first-entry',
+ });
+ dispose();
+ });
+ });
+ });
+
describe('split history', () => {
it('marks mergeHistory content changes as replace navigation', () => {
createRoot((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.ts
deleted file mode 100644
index b3396be4fa..0000000000
--- a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts
+++ /dev/null
@@ -1,288 +0,0 @@
-import { agentsRouteId } from '@app/features/agents-view/core/route';
-import type { BlockOrchestrator } from '@core/orchestrator';
-import type { Navigator } from '@solidjs/router';
-import { batch, createRoot, createSignal } from 'solid-js';
-import { beforeAll, describe, expect, it, vi } from 'vitest';
-import { createSplitLayout, type SplitContent } from '../layoutManager';
-import { createLayoutUrlSync } from '../layoutUrlSync';
-
-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 {
- isBlockMounted: vi.fn(() => false),
- 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[];
- 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 [search, setSearch] = createSignal(options.search ?? '');
-
- createLayoutUrlSync(manager, pairs, {
- navigate: navigate as Navigator,
- search,
- });
-
- return {
- manager,
- navigate,
- dispose,
- setUrl(segments: string[], nextSearch = '') {
- batch(() => {
- setPairs(segments);
- setSearch(nextSearch);
- });
- },
- };
- });
-}
-
-async function flushUrlSync() {
- await new Promise<void>((resolve) => queueMicrotask(resolve));
- await new Promise<void>((resolve) => queueMicrotask(resolve));
-}
-
-describe('layout URL synchronization', () => {
- it('navigates between Agents conversations and restores browser back/forward paths', async () => {
- const chat = {
- type: 'component' as const,
- id: agentsRouteId({
- mode: 'chat',
- conversation: { type: 'agent_session', id: 'session-1' },
- }),
- };
- const code = {
- type: 'component' as const,
- id: agentsRouteId({
- mode: 'code',
- conversation: { type: 'agent_session', id: 'session-2' },
- }),
- };
- const harness = createHarness({
- managerContent: [{ type: 'component', id: 'agents' }],
- urlSegments: ['component', 'agents'],
- });
- await flushUrlSync();
- const handle = harness.manager.getSplit(harness.manager.splits()[0].id)!;
- handle.replace({ next: chat });
- await flushUrlSync();
- expect(harness.navigate).toHaveBeenLastCalledWith('/agents/session-1', {
- replace: false,
- });
- harness.setUrl(['agents', 'session-1']);
- await flushUrlSync();
- handle.replace({ next: code });
- await flushUrlSync();
- expect(harness.navigate).toHaveBeenLastCalledWith('/coders/session-2', {
- replace: false,
- });
- harness.setUrl(['coders', 'session-2']);
- await flushUrlSync();
- harness.setUrl(['agents', 'session-1']);
- await flushUrlSync();
- expect(harness.manager.splits()[0].content).toEqual(chat);
- harness.setUrl(['coders', 'session-2']);
- await flushUrlSync();
- expect(harness.manager.splits()[0].content).toEqual(code);
- harness.dispose();
- });
-
- it('replaces a pending workspace URL with the real session without remounting', async () => {
- const pendingId = agentsRouteId({
- mode: 'chat',
- conversation: { type: 'agent_session', id: 'pending-1' },
- });
- const resolvedId = agentsRouteId({
- mode: 'chat',
- conversation: { type: 'agent_session', id: 'session-1' },
- });
- const harness = createHarness({
- managerContent: [{ type: 'component', id: pendingId }],
- urlSegments: ['agents', 'pending-1'],
- });
- await flushUrlSync();
- const split = harness.manager.splits()[0];
- const mount = split.mount;
- const handle = harness.manager.getSplit(split.id)!;
- const historyLength = handle.history().length;
- handle.adoptContentId({ type: 'component', nextId: resolvedId });
- await flushUrlSync();
- expect(harness.navigate).toHaveBeenLastCalledWith('/agents/session-1', {
- replace: true,
- });
- expect(harness.manager.splits()[0].mount).toBe(mount);
- expect(handle.history()).toHaveLength(historyLength);
- expect(handle.history().at(-1)?.id).toBe(resolvedId);
- harness.dispose();
- });
-
- it('restores Agents deep links next to another split', async () => {
- const harness = createHarness({
- managerContent: [{ type: 'component', id: 'agents' }],
- urlSegments: ['md', 'document-1', 'coders', 'session-2'],
- });
- await flushUrlSync();
- expect(harness.manager.getUrlSegments()).toEqual([
- 'md',
- 'document-1',
- 'coders',
- 'session-2',
- ]);
- expect(harness.manager.splits()[1].content.id).toBe(
- agentsRouteId({
- mode: 'code',
- conversation: { type: 'agent_session', id: 'session-2' },
- })
- );
- harness.dispose();
- });
-
- it('reconciles URL paths 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']);
- await flushUrlSync();
-
- const [list, detail] = harness.manager.splits();
- expect(list.content).toMatchObject({
- type: 'component',
- id: 'inbox',
- });
- expect(detail.content).toMatchObject({ type: 'md', id: 'doc-1' });
- 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();
- });
-
- it('preserves a macrod pairing code while settings canonicalizes its tab', async () => {
- const harness = createHarness({
- managerContent: [{ type: 'component', id: 'settings' }],
- urlSegments: ['settings', 'harness'],
- search: '?pair=3GTM-FNJ9&discard=value',
- });
-
- await flushUrlSync();
-
- expect(harness.navigate).not.toHaveBeenCalled();
-
- harness.dispose();
- });
-
- it('does not stall settings URL synchronization for an empty pairing code', async () => {
- const harness = createHarness({
- managerContent: [{ type: 'component', id: 'settings' }],
- urlSegments: ['settings', 'harness'],
- search: '?pair=',
- });
-
- await flushUrlSync();
-
- expect(harness.navigate).toHaveBeenCalledWith('/settings/account', {
- replace: true,
- });
-
- harness.dispose();
- });
-
- it('preserves agent creation links while settings canonicalizes its tab', async () => {
- const harness = createHarness({
- managerContent: [{ type: 'component', id: 'settings' }],
- urlSegments: ['settings', 'agents'],
- search: '?createAgent=true',
- });
- await flushUrlSync();
- expect(harness.navigate).not.toHaveBeenCalled();
- harness.dispose();
- });
-});
diff --git a/apps/web/src/components/navigation-stack/NavigationStack.test.tsx b/apps/web/src/components/navigation-stack/NavigationStack.test.tsx
index 0d5eb4e622..4247e00e17 100644
--- a/apps/web/src/components/navigation-stack/NavigationStack.test.tsx
+++ b/apps/web/src/components/navigation-stack/NavigationStack.test.tsx
@@ -97,6 +97,33 @@ describe('NavigationStack', () => {
expect(snapshots[1]?.map(({ data }) => data)).toEqual(['Task', 'Document']);
});
+ it('reconciles external state without notifying', () => {
+ let state: NavigationStackState<string> | undefined;
+ const onChange = vi.fn();
+
+ function CaptureState() {
+ state = useNavigationStack<string>();
+
+ return null;
+ }
+
+ render(() => (
+ <NavigationStack.Root<string> onChange={onChange}>
+ <CaptureState />
+ </NavigationStack.Root>
+ ));
+
+ state?.reconcile('Document');
+
+ expect(state?.entries.map(({ data }) => data)).toEqual(['Document']);
+ expect(onChange).not.toHaveBeenCalled();
+
+ state?.reconcile();
+
+ expect(state?.entries).toHaveLength(0);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
it('only handles navigation accepted by the root', () => {
let state: NavigationStackState<string, { blocked?: boolean }> | undefined;
diff --git a/apps/web/src/components/navigation-stack/NavigationStack.tsx b/apps/web/src/components/navigation-stack/NavigationStack.tsx
index 67afa6eaeb..7890e99a74 100644
--- a/apps/web/src/components/navigation-stack/NavigationStack.tsx
+++ b/apps/web/src/components/navigation-stack/NavigationStack.tsx
@@ -24,6 +24,7 @@ export type NavigationStackState<TData, TNavigateOptions = unknown> = {
push: (data: TData) => NavigationStackEntry<TData> | undefined;
replace: (data: TData) => NavigationStackEntry<TData> | undefined;
reset: (data: TData) => NavigationStackEntry<TData> | undefined;
+ reconcile: (data?: TData) => void;
pop: () => void;
popTo: (value: string) => void;
clear: () => void;
@@ -127,6 +128,16 @@ function Root<TData = unknown, TNavigateOptions = unknown>(
return entry;
};
+ const reconcile = (data?: TData) => {
+ const entry = data === undefined ? undefined : createEntry(data);
+
+ setEntries(
+ produce((draft) => {
+ draft.splice(0, draft.length, ...(entry ? [entry] : []));
+ })
+ );
+ };
+
const pop = () => {
if (entries.length === 0) return;
if (props.beforeChange?.(entries.at(-2)?.data, 'navigate') === false)
@@ -181,6 +192,7 @@ function Root<TData = unknown, TNavigateOptions = unknown>(
reset: reset as (
data: unknown
) => NavigationStackEntry<unknown> | undefined,
+ reconcile: reconcile as (data?: unknown) => void,
pop,
popTo,
clear,
diff --git a/apps/web/src/features/block-md/component/ModalsProvider.tsx b/apps/web/src/features/block-md/component/ModalsProvider.tsx
index ab548a2c6e..a9aed3b68c 100644
--- a/apps/web/src/features/block-md/component/ModalsProvider.tsx
+++ b/apps/web/src/features/block-md/component/ModalsProvider.tsx
@@ -11,6 +11,7 @@ import {
type ParentProps,
type Setter,
Suspense,
+ useContext,
} from 'solid-js';
import { useMarkdownDocument } from '../context/markdown-document-context';
import { useMarkdownName } from './MarkdownNameProvider';
@@ -29,6 +30,7 @@ export function ModalsProvider(
const { displayName } = useMarkdownName();
const notificationSource = useGlobalNotificationSource();
const metadataQuery = useDocumentMetadataQuery(documentId);
+ const parentShareContext = useContext(ShareDialogContext);
const [localShareOpen, setLocalShareOpen] = createSignal(false);
const shareOpen = () => props.shareOpen ?? localShareOpen();
const setShareOpen: Setter<boolean> = (next) => {
@@ -57,6 +59,7 @@ export function ModalsProvider(
isOpen: shareOpen,
open: () => setShareOpen(true),
close: () => setShareOpen(false),
+ copyLink: parentShareContext?.copyLink,
}}
>
{props.children}
diff --git a/apps/web/src/features/channel/Calls/ChannelCallsTab.tsx b/apps/web/src/features/channel/Calls/ChannelCallsTab.tsx
index 0fd18509c8..4e5f36701c 100644
--- a/apps/web/src/features/channel/Calls/ChannelCallsTab.tsx
+++ b/apps/web/src/features/channel/Calls/ChannelCallsTab.tsx
@@ -105,7 +105,6 @@ function ChannelCallsList(props: { channelId: string }) {
entity: EntityData,
options: {
openInNewSplit?: boolean;
- replacePreview?: boolean;
mergeHistory?: boolean;
} = {}
) {
@@ -132,7 +131,6 @@ function ChannelCallsList(props: { channelId: string }) {
openEntity(item.entity, {
openInNewSplit: newSplit,
- replacePreview: metadata?.event?.altKey === true && !newSplit,
});
}
diff --git a/apps/web/src/features/drive-view/components/DriveDetailView.tsx b/apps/web/src/features/drive-view/components/DriveDetailView.tsx
index e81b7added..299fe43d51 100644
--- a/apps/web/src/features/drive-view/components/DriveDetailView.tsx
+++ b/apps/web/src/features/drive-view/components/DriveDetailView.tsx
@@ -5,21 +5,21 @@ import {
import { EntityDetailBreadcrumbItem } from '@app/components/entity-detail/EntityDetailBreadcrumbItem';
import { EntityDetailBreadcrumbSkeleton } from '@app/components/entity-detail/EntityDetailBreadcrumbSkeleton';
import {
- EntityDetailNavigationStack,
type EntityDetailNavigationStackEntry,
type EntityDetailTarget,
entityDetailTarget,
- useEntityDetailNavigationStack,
} from '@app/components/entity-detail/EntityDetailNavigationStack';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { MarkdownDetailBreadcrumbItem } from '@block-md/component/MarkdownDetailBreadcrumbItem';
import type { MarkdownDocumentKind } from '@block-md/types';
import { SidePanel } from '@components/app/side-panel';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { toast } from '@core/component/Toast/Toast';
import {
ShareDialogContext,
ShareTrigger,
} from '@core/component/TopBar/ShareButton';
+import { useReferralCode } from '@core/context/user';
import {
createSignal,
ErrorBoundary,
@@ -28,6 +28,9 @@ import {
Show,
Switch,
} from 'solid-js';
+import { useDriveView } from '../context/drive-context';
+import { driveLocationBreadcrumbs } from '../core/breadcrumbs';
+import { useDriveDetailNavigation } from '../drive-detail-navigation';
import {
MarkdownDetail,
MarkdownDetailBodyState,
@@ -36,8 +39,8 @@ import { DriveBreadcrumbsOutlet } from './DriveBreadcrumbs';
import { FileDetailBreadcrumbItem } from './FileDetailBreadcrumbItem';
function DriveDetailAncestorBreadcrumbs(props: { orderOffset: number }) {
- const navigationStack = useEntityDetailNavigationStack();
- const ancestors = () => navigationStack.entries.slice(0, -1);
+ const navigationStack = useDriveDetailNavigation();
+ const ancestors = () => navigationStack.entries().slice(0, -1);
return (
<For each={ancestors()}>
@@ -60,7 +63,7 @@ function markdownKind(target: DocumentDetailTarget): MarkdownDocumentKind {
}
function DriveDetailTopBar() {
- const navigationStack = useEntityDetailNavigationStack();
+ const navigationStack = useDriveDetailNavigation();
const panel = useSplitPanelOrThrow();
const activeDetail = () => {
const target = navigationStack.active()?.data;
@@ -98,7 +101,7 @@ function StackEntityDetail(props: {
shareOpen: boolean;
onShareOpenChange: (open: boolean) => void;
}) {
- const navigationStack = useEntityDetailNavigationStack();
+ const navigationStack = useDriveDetailNavigation();
const markdownTarget = () => {
const target = props.entry.data;
const blockType = entityDetailBlockType(target);
@@ -205,9 +208,20 @@ function StackEntityDetail(props: {
);
}
-export function DriveDetailView(props: { breadcrumbOrderOffset: number }) {
+export function DriveDetailView() {
+ const { state, sidebar } = useDriveView();
+ const breadcrumbOrderOffset = () =>
+ driveLocationBreadcrumbs(state.value().location, sidebar.folders()).length;
const [shareOpen, setShareOpen] = createSignal(false);
- const navigationStack = useEntityDetailNavigationStack();
+ const navigationStack = useDriveDetailNavigation();
+ const referralCode = useReferralCode();
+ const copyLink = () => {
+ const url = new URL(window.location.href);
+ const code = referralCode();
+ if (code) url.searchParams.set('referral_code', code);
+ void navigator.clipboard.writeText(url.toString());
+ toast.success('Link copied to clipboard.');
+ };
// Spreadsheets use their live block in PreviewPanel, which supplies its own
// header, sharing controls and the enclosing ViewShell's sidebar toggle.
const hasBlockHeader = () => {
@@ -221,19 +235,18 @@ export function DriveDetailView(props: { breadcrumbOrderOffset: number }) {
isOpen: shareOpen,
open: () => setShareOpen(true),
close: () => setShareOpen(false),
+ copyLink,
}}
>
- <DriveDetailAncestorBreadcrumbs
- orderOffset={props.breadcrumbOrderOffset}
- />
+ <DriveDetailAncestorBreadcrumbs orderOffset={breadcrumbOrderOffset()} />
<SidePanel.Root>
<div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
<Show when={!hasBlockHeader()}>
<DriveDetailTopBar />
</Show>
<div class="relative min-h-0 min-w-0 flex-1">
- <EntityDetailNavigationStack.Outlet>
- {(entry, state) => (
+ <Show when={navigationStack.active()}>
+ {(entry) => (
<ErrorBoundary
fallback={(error, reset) => (
<MarkdownDetailBodyState
@@ -244,16 +257,18 @@ export function DriveDetailView(props: { breadcrumbOrderOffset: number }) {
)}
>
<StackEntityDetail
- entry={entry}
+ entry={entry()}
order={
- props.breadcrumbOrderOffset + state.entries.length - 1
+ breadcrumbOrderOffset() +
+ navigationStack.entries().length -
+ 1
}
shareOpen={shareOpen()}
onShareOpenChange={setShareOpen}
/>
</ErrorBoundary>
)}
- </EntityDetailNavigationStack.Outlet>
+ </Show>
</div>
</div>
</SidePanel.Root>
diff --git a/apps/web/src/features/drive-view/components/FileDetail.tsx b/apps/web/src/features/drive-view/components/FileDetail.tsx
index 176286ee3c..cb689ee424 100644
--- a/apps/web/src/features/drive-view/components/FileDetail.tsx
+++ b/apps/web/src/features/drive-view/components/FileDetail.tsx
@@ -26,6 +26,7 @@ import {
type Setter,
Suspense,
Switch,
+ useContext,
} from 'solid-js';
export type FileDetailShareProps = {
@@ -44,6 +45,7 @@ export type FileDetailLayoutProps = ParentProps<
>;
export function FileDetailLayout(props: FileDetailLayoutProps) {
+ const parentShareContext = useContext(ShareDialogContext);
const [localShareOpen, setLocalShareOpen] = createSignal(false);
const shareOpen = () => props.shareOpen ?? localShareOpen();
const setShareOpen: Setter<boolean> = (next) => {
@@ -62,6 +64,7 @@ export function FileDetailLayout(props: FileDetailLayoutProps) {
isOpen: shareOpen,
open: () => setShareOpen(true),
close: () => setShareOpen(false),
+ copyLink: parentShareContext?.copyLink,
}}
>
<SidePanel.Layout
diff --git a/apps/web/src/features/drive-view/drive-detail-navigation.tsx b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
new file mode 100644
index 0000000000..c993297652
--- /dev/null
+++ b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
@@ -0,0 +1,205 @@
+import { entityDetailBlockType } from '@app/components/entity-detail/EntityDetail';
+import type {
+ EntityDetailNavigationOptions,
+ EntityDetailNavigationStackEntry,
+ EntityDetailTarget,
+} from '@app/components/entity-detail/EntityDetailNavigationStack';
+import {
+ routeParams,
+ useCanGo,
+ useNavigate,
+ useParams,
+ useSplitHistory,
+} from '@app/split-router';
+import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import {
+ type Accessor,
+ createContext,
+ createEffect,
+ createMemo,
+ type ParentProps,
+ useContext,
+} from 'solid-js';
+import type { DriveLocation } from './core/types';
+import {
+ type DriveDocumentRoute,
+ type DriveRouteParams,
+ driveDestination,
+ driveDocumentFromParams,
+ driveDocumentRoute,
+} from './primitives/drive-route';
+
+type DriveDetailHistoryEntry = EntityDetailNavigationStackEntry & {
+ historyIndex: number;
+};
+
+type DriveDetailNavigation = {
+ entries: Accessor<readonly DriveDetailHistoryEntry[]>;
+ active: Accessor<DriveDetailHistoryEntry | undefined>;
+ navigate: (
+ target: EntityDetailTarget,
+ options?: EntityDetailNavigationOptions
+ ) => boolean;
+ pop: () => void;
+ popTo: (value: string) => void;
+ clear: (options?: { replace?: boolean }) => void;
+};
+
+const Context = createContext<DriveDetailNavigation>();
+
+function targetFromDocument(
+ document: DriveDocumentRoute | undefined
+): Extract<EntityDetailTarget, { type: 'document' }> | undefined {
+ if (!document) return;
+
+ const target = {
+ type: 'document' as const,
+ id: document.id,
+ };
+
+ switch (document.type) {
+ case 'task':
+ return {
+ ...target,
+ fileType: 'md',
+ subType: { type: 'task', is_completed: false },
+ };
+ case 'snippet':
+ case 'skill':
+ return {
+ ...target,
+ fileType: 'md',
+ subType: { type: document.type },
+ };
+ default:
+ return { ...target, fileType: document.type };
+ }
+}
+
+function targetFromParams(params: DriveRouteParams) {
+ return targetFromDocument(driveDocumentFromParams(params));
+}
+
+function sameTarget(
+ left: EntityDetailTarget | undefined,
+ right: EntityDetailTarget | undefined
+) {
+ if (left?.type !== 'document' || right?.type !== 'document') {
+ return left === right;
+ }
+
+ return (
+ left.id === right.id &&
+ left.fileType === right.fileType &&
+ left.subType?.type === right.subType?.type
+ );
+}
+
+function opensInline(options?: EntityDetailNavigationOptions) {
+ const event = options?.event;
+ return (
+ !isTouchDevice() &&
+ !(event?.shiftKey || event?.metaKey || event?.ctrlKey || event?.altKey)
+ );
+}
+
+export function DriveDetailNavigationProvider(
+ props: ParentProps<{ location: Accessor<DriveLocation> }>
+) {
+ const params = useParams<DriveRouteParams>();
+ const navigate = useNavigate();
+ const canGoBack = useCanGo(-1);
+ const history = useSplitHistory();
+ const selectPreview = createPreviewSelectionGuard();
+ const activeTarget = createMemo(() => targetFromParams(params));
+
+ createEffect(() => {
+ selectPreview(activeTarget());
+ });
+
+ const entries = createMemo<DriveDetailHistoryEntry[]>(() => {
+ const snapshot = history();
+ if (!snapshot) return [];
+
+ const result: DriveDetailHistoryEntry[] = [];
+ for (let index = 0; index <= snapshot.index; index += 1) {
+ const target = targetFromParams(
+ routeParams(snapshot.entries[index]?.route) as DriveRouteParams
+ );
+
+ if (!target) {
+ result.splice(0);
+ continue;
+ }
+
+ const entry = {
+ value: `drive-history:${index}`,
+ data: target,
+ historyIndex: index,
+ };
+ const previous = result.at(-1);
+ if (sameTarget(previous?.data, target)) result[result.length - 1] = entry;
+ else result.push(entry);
+ }
+
+ return result;
+ });
+ const active = () => entries().at(-1);
+
+ const value: DriveDetailNavigation = {
+ entries,
+ active,
+
+ navigate(target, options) {
+ if (target.type !== 'document' || !opensInline(options)) return false;
+
+ const blockType = entityDetailBlockType(target);
+ if (!blockType || !selectPreview(target)) return false;
+
+ navigate(
+ driveDestination(
+ props.location(),
+ driveDocumentRoute({
+ id: target.id,
+ fileType: target.fileType ?? blockType,
+ subType: target.subType?.type,
+ })
+ )
+ );
+ return true;
+ },
+
+ pop() {
+ if (canGoBack()) navigate(-1);
+ else value.clear({ replace: true });
+ },
+
+ popTo(value) {
+ const entry = entries().find((candidate) => candidate.value === value);
+ const snapshot = history();
+ if (!entry || !snapshot) return;
+
+ navigate(entry.historyIndex - snapshot.index);
+ },
+
+ clear(options) {
+ // Location navigation already lands on a list route. Clearing again must
+ // not climb out of the folder/tab the user just selected.
+ if (!driveDocumentFromParams(params)) return;
+ selectPreview(undefined);
+ navigate(driveDestination(props.location()), {
+ replace: options?.replace,
+ });
+ },
+ };
+
+ return <Context.Provider value={value}>{props.children}</Context.Provider>;
+}
+
+export function useDriveDetailNavigation(): DriveDetailNavigation {
+ const context = useContext(Context);
+ if (!context) throw new Error('DriveDetailNavigationProvider is required');
+
+ return context;
+}
diff --git a/apps/web/src/features/drive-view/drive-host-actions.ts b/apps/web/src/features/drive-view/drive-host-actions.ts
index 41ce945704..6223dc055c 100644
--- a/apps/web/src/features/drive-view/drive-host-actions.ts
+++ b/apps/web/src/features/drive-view/drive-host-actions.ts
@@ -1,8 +1,4 @@
-import { entityDetailBlockType } from '@app/components/entity-detail/EntityDetail';
-import {
- entityDetailTarget,
- useEntityDetailNavigationStack,
-} from '@app/components/entity-detail/EntityDetailNavigationStack';
+import { entityDetailTarget } from '@app/components/entity-detail/EntityDetailNavigationStack';
import { makeShareAction } from '@app/features/next-soup/actions';
import {
markReminderSeenOnOpen,
@@ -26,6 +22,7 @@ import {
} from '@core/util/upload';
import type { Accessor } from 'solid-js';
import type { DriveHostActions } from './context/drive-context';
+import { useDriveDetailNavigation } from './drive-detail-navigation';
/** App-specific navigation, upload and sharing adapters for the Drive workspace. */
export function createDriveHostActions(options: {
@@ -36,7 +33,7 @@ export function createDriveHostActions(options: {
const layout = useSplitLayout();
- const navigation = useEntityDetailNavigationStack();
+ const navigation = useDriveDetailNavigation();
const notificationSource = useGlobalNotificationSource();
@@ -82,14 +79,7 @@ export function createDriveHostActions(options: {
fallbackName: entity.name,
});
- if (
- entityDetailBlockType(target) &&
- navigation.shouldNavigate(target, { event })
- ) {
- navigation.reset(target);
-
- return;
- }
+ if (navigation.navigate(target, { event })) return;
}
void openEntityInSplitFromUnifiedList(entity, {
@@ -121,14 +111,7 @@ export function createDriveHostActions(options: {
fallbackName: name,
});
- if (
- entityDetailBlockType(target) &&
- navigation.shouldNavigate(target, { event })
- ) {
- navigation.reset(target);
-
- return;
- }
+ if (navigation.navigate(target, { event })) return;
}
const result = layout.openWithSplit(favoriteSplitContent(favorite), {
diff --git a/apps/web/src/features/drive-view/drive-location-menu.tsx b/apps/web/src/features/drive-view/drive-location-menu.tsx
index 01cc615498..7cd80f1fdf 100644
--- a/apps/web/src/features/drive-view/drive-location-menu.tsx
+++ b/apps/web/src/features/drive-view/drive-location-menu.tsx
@@ -1,11 +1,12 @@
import { globalSplitManager } from '@app/signal/splitLayout';
+import { useNavigate } from '@app/split-router';
import { SidebarOpenInSplitMenu } from '@components/app/app-sidebar/sidebar';
-import type { SplitContent } from '@components/app/split-layout/layoutManager';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { batch, type ParentProps, Show } from 'solid-js';
import { useDriveView } from './context/drive-context';
-import type { DriveLocation, DriveState } from './core/types';
+import type { DriveLocation } from './core/types';
import { DriveFolderActions } from './drive-folder-actions';
+import { driveDestination } from './primitives/drive-route';
/** App-specific split/menu wiring shared by Drive's sidebar locations. */
export function DriveLocationMenu(
@@ -15,6 +16,8 @@ export function DriveLocationMenu(
const panel = useSplitPanelOrThrow();
+ const navigate = useNavigate();
+
const folder = () => {
const location = props.location;
@@ -23,20 +26,6 @@ export function DriveLocationMenu(
: undefined;
};
- const content = (): SplitContent => ({
- type: 'component',
- id: 'documents',
- state: {
- 'drive.view.v2': {
- ...state.value(),
- location: props.location,
- scope: 'default',
- search: '',
- facets: {},
- } satisfies DriveState,
- },
- });
-
const openFullscreen = () => {
const manager = globalSplitManager();
@@ -56,9 +45,11 @@ export function DriveLocationMenu(
return (
<SidebarOpenInSplitMenu
- content={content}
triggerClass="block h-auto"
onOpenCurrentSplit={() => state.navigate(props.location)}
+ onOpenNewSplit={() =>
+ navigate(driveDestination(props.location), { target: 'new-split' })
+ }
onOpenFullscreen={openFullscreen}
additionalActions={
<Show when={folder()}>
diff --git a/apps/web/src/features/drive-view/drive-view.tsx b/apps/web/src/features/drive-view/drive-view.tsx
index 6264efe940..ed76b894c3 100644
--- a/apps/web/src/features/drive-view/drive-view.tsx
+++ b/apps/web/src/features/drive-view/drive-view.tsx
@@ -1,7 +1,3 @@
-import {
- EntityDetailNavigationStack,
- useEntityDetailNavigationStack,
-} from '@app/components/entity-detail/EntityDetailNavigationStack';
import { listOwnedSlotName } from '@app/components/list';
import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
import {
@@ -9,29 +5,31 @@ import {
useSoupListNavigationHotkeys,
} from '@app/features/soup';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
-import { useEntryState } from '@components/app/split-layout/entry-state';
import {
useSplitPanelOrThrow,
withSplitPanelOwner,
} from '@components/app/split-layout/layoutUtils';
+import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { ListEntityMetadataQueryProvider } from '@entity';
import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';
-import { onCleanup, onMount, Suspense } from 'solid-js';
+import { createEffect, on, onCleanup, onMount, Suspense } from 'solid-js';
import { DriveProvider } from './context/drive-context';
import { driveLocationLabel } from './core/location-label';
import {
- DRIVE_MOBILE_TABS,
- DRIVE_TABS,
- type DriveState,
- driveMobileTabLocation,
-} from './core/types';
+ DriveDetailNavigationProvider,
+ useDriveDetailNavigation,
+} from './drive-detail-navigation';
import { createDriveHostActions } from './drive-host-actions';
import {
createDriveList,
parseDriveListSnapshot,
} from './primitives/drive-list';
+import {
+ createDriveRouteState,
+ createDriveViewState,
+ type DriveRouteState,
+} from './primitives/drive-route-state';
import { createDriveState } from './primitives/drive-state';
import { createDriveDataSource } from './queries/drive-data-source';
import { createDriveSidebarSource } from './queries/drive-sidebar-source';
@@ -39,62 +37,35 @@ import { DriveLoading, DriveWorkspace } from './views/drive-workspace';
export type DriveViewProps = { initialFacets?: FacetSelection };
-/** The only place that constructs production sources and app capabilities. */
-function DriveComposition(props: DriveViewProps) {
+/** Constructs production sources and injects app capabilities into the workspace. */
+function DriveComposition(props: { route: DriveRouteState }) {
const panel = useSplitPanelOrThrow();
-
- const navigation = useEntityDetailNavigationStack();
-
+ const navigation = useDriveDetailNavigation();
const userId = useUserId();
-
const notificationSource = useGlobalNotificationSource();
-
const tagSets = useTagSets();
-
const tagSetsReady = useTagSetsReady();
-
- const [value, setValue] = useEntryState<DriveState>('drive.view.v2', {
- default: {
- // Each form factor opens on the first entry of its own tab list.
- location: isTouchDevice()
- ? driveMobileTabLocation(DRIVE_MOBILE_TABS[0].id)
- : { kind: 'tab', tab: DRIVE_TABS[0].id },
- scope: 'default',
- sort: 'updated_at',
- search: '',
- facets: props.initialFacets ?? {},
- expandedFolderIds: [],
- favoritesOpen: true,
- rootOpen: true,
- tagsOpen: true,
- },
- });
-
+ const view = createDriveViewState(props.route, () => list.reset());
const sidebar = createDriveSidebarSource();
-
const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>
createDriveDataSource({
- selection: value,
+ selection: view.value,
userId,
tagSets,
tagSetsReady,
notificationSource,
})
);
-
const actions = createDriveHostActions({
projectId: () => state.projectId(),
-
selectFolder: (id) => state.selectFolder(id),
});
-
const list = withSplitPanelOwner(listOwnedSlotName('controller'), () =>
createDriveList({
source,
initial: parseDriveListSnapshot(
panel.handle.content().state?.['drive.listState']
),
-
onActivate: (row, metadata) =>
actions.openEntity(
row.entity,
@@ -104,24 +75,55 @@ function DriveComposition(props: DriveViewProps) {
),
})
);
-
const state = createDriveState({
- state: value,
- setState: setValue,
+ state: view.value,
+ setState: view.setValue,
folders: sidebar.folders,
list,
-
showList: () => {
navigation.clear();
},
});
+ createEffect(
+ on(
+ () => {
+ const location = view.value().location;
+ if (
+ sidebar.foldersLoading() ||
+ sidebar.foldersError() ||
+ location.kind !== 'folder' ||
+ !location.id
+ )
+ return;
+ return sidebar.folders().some((folder) => folder.id === location.id)
+ ? undefined
+ : location.id;
+ },
+ (unavailableFolderId) => {
+ if (!unavailableFolderId) return;
+ view.update(
+ {
+ ...view.value(),
+ location: { kind: 'folder', id: null },
+ scope: 'default',
+ search: '',
+ facets: {},
+ },
+ { replace: true }
+ );
+ toast.alert('Folder unavailable', {
+ subtext: 'It may have moved, been deleted, or no longer be shared.',
+ });
+ }
+ )
+ );
+
onCleanup(
panel.handle.registerEntryStateCaptor('drive.returnLabel', () =>
- driveLocationLabel(value().location, sidebar.folders())
+ driveLocationLabel(view.value().location, sidebar.folders())
)
);
-
onCleanup(
panel.handle.registerEntryStateCaptor('drive.listState', list.snapshot)
);
@@ -133,7 +135,6 @@ function DriveComposition(props: DriveViewProps) {
dataSource: source,
controller: list.controller,
handle: panel.handle,
-
openEntityInSplit: (entity, options) => {
void openEntityInSplitFromUnifiedList(entity, {
splitHandle: panel.handle,
@@ -142,7 +143,6 @@ function DriveComposition(props: DriveViewProps) {
},
});
});
-
onMount(() => panel.handle.setDisplayName('Drive'));
return (
@@ -153,13 +153,14 @@ function DriveComposition(props: DriveViewProps) {
}
export function DriveView(props: DriveViewProps) {
+ const route = createDriveRouteState(() => props.initialFacets);
return (
- <EntityDetailNavigationStack.Root>
+ <DriveDetailNavigationProvider location={route.location}>
<ListEntityMetadataQueryProvider>
<Suspense fallback={<DriveLoading />}>
- <DriveComposition {...props} />
+ <DriveComposition route={route} />
</Suspense>
</ListEntityMetadataQueryProvider>
- </EntityDetailNavigationStack.Root>
+ </DriveDetailNavigationProvider>
);
}
diff --git a/apps/web/src/features/drive-view/primitives/drive-route-state.ts b/apps/web/src/features/drive-view/primitives/drive-route-state.ts
new file mode 100644
index 0000000000..683549ebd3
--- /dev/null
+++ b/apps/web/src/features/drive-view/primitives/drive-route-state.ts
@@ -0,0 +1,156 @@
+import {
+ type FacetSelection,
+ normalizeFacetSelection,
+} from '@app/features/soup';
+import {
+ createSearchParams,
+ type SplitNavigateOptions,
+ useNavigate,
+ useParams,
+} from '@app/split-router';
+import { useEntryState } from '@components/app/split-layout/entry-state';
+import deepEqual from 'fast-deep-equal';
+import {
+ type Accessor,
+ batch,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onMount,
+ type Setter,
+} from 'solid-js';
+import type { DriveLocation, DriveState } from '../core/types';
+import {
+ type DriveRouteParams,
+ type DriveSearchParams,
+ driveDestination,
+ driveLocationFromParams,
+ driveSearch,
+} from './drive-route';
+
+type NavigationOptions = Pick<
+ SplitNavigateOptions<unknown>,
+ 'replace' | 'target'
+>;
+
+/** URL-owned Drive selection and the one-time legacy launch-facet handoff. */
+export function createDriveRouteState(
+ initialFacets: Accessor<FacetSelection | undefined>
+) {
+ const params = useParams<DriveRouteParams>();
+ const navigate = useNavigate();
+ const [search, setSearch] = createSearchParams(driveSearch);
+ const location = createMemo(() => driveLocationFromParams(params));
+ const seed = normalizeFacetSelection(initialFacets());
+ const [seeding, setSeeding] = createSignal(
+ Object.keys(search.facets).length === 0 && Object.keys(seed).length > 0
+ );
+ const facets = () => (seeding() ? seed : search.facets);
+ onMount(() => {
+ if (!seeding()) return;
+ batch(() => {
+ setSearch({ facets: seed }, { history: 'replace' });
+ setSeeding(false);
+ });
+ });
+
+ return {
+ location,
+ selection: () => ({
+ location: location(),
+ scope: search.scope,
+ sort: search.sort,
+ facets: facets(),
+ }),
+ setSearch,
+ navigate(
+ location: DriveLocation,
+ search: DriveSearchParams,
+ options: NavigationOptions = {}
+ ) {
+ navigate(driveDestination(location), {
+ ...options,
+ search: {
+ drive: driveSearch.serialize(search, {
+ defaults: driveSearch.defaults,
+ }),
+ },
+ });
+ },
+ };
+}
+export type DriveRouteState = ReturnType<typeof createDriveRouteState>;
+
+const routeSearch = ({
+ scope,
+ sort,
+ facets,
+}: DriveState): DriveSearchParams => ({
+ scope,
+ sort,
+ facets: normalizeFacetSelection(facets),
+});
+
+/** Restored entry state supplies UI state; the current URL always wins selection. */
+export function createDriveViewState(
+ route: DriveRouteState,
+ onRouteChange: () => void
+) {
+ const [saved, setSaved] = useEntryState<DriveState>('drive.view.v2', {
+ default: {
+ ...route.selection(),
+ search: '',
+ expandedFolderIds: [],
+ favoritesOpen: true,
+ rootOpen: true,
+ tagsOpen: true,
+ },
+ });
+ const value = (): DriveState => ({ ...saved(), ...route.selection() });
+ const update = (next: DriveState, options: NavigationOptions = {}) => {
+ const previous = value();
+ setSaved(() => next);
+ if (!deepEqual(next.location, previous.location)) {
+ route.navigate(next.location, routeSearch(next), options);
+ } else if (!deepEqual(routeSearch(next), routeSearch(previous))) {
+ route.setSearch(routeSearch(next), {
+ mode: 'replace',
+ history: options.replace ? 'replace' : 'push',
+ });
+ }
+ return next;
+ };
+ const setValue: Setter<DriveState> = (next) =>
+ update(typeof next === 'function' ? next(value()) : next);
+
+ createEffect(
+ on(
+ route.selection,
+ (selection) => {
+ const current = saved();
+ const locationChanged = !deepEqual(
+ current.location,
+ selection.location
+ );
+ if (
+ !locationChanged &&
+ deepEqual(
+ routeSearch(current),
+ routeSearch({ ...current, ...selection })
+ )
+ )
+ return;
+ setSaved({
+ ...current,
+ ...selection,
+ search: locationChanged ? '' : current.search,
+ });
+ onRouteChange();
+ },
+ { defer: true }
+ )
+ );
+
+ return { value, setValue, update };
+}
diff --git a/apps/web/src/features/drive-view/primitives/drive-route.ts b/apps/web/src/features/drive-view/primitives/drive-route.ts
new file mode 100644
index 0000000000..2ff74d79a8
--- /dev/null
+++ b/apps/web/src/features/drive-view/primitives/drive-route.ts
@@ -0,0 +1,247 @@
+import {
+ deserializeFacetSelection,
+ normalizeFacetSelection,
+} from '@app/features/soup/filters/facets/selection';
+import { defineRoute, routeParams } from '@app/lib/split-router/routes';
+import {
+ type CreateSearchParamsOptions,
+ isSafeName,
+ type SerializedSearchParams,
+ type SplitRouteNavigationTarget,
+ type SplitRouteParams,
+ type SplitRouterEntry,
+ takeLast,
+} from '@app/split-router';
+import { URL_PARAMS as MARKDOWN_URL_PARAMS } from '@block-md/constants';
+import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
+import { z } from 'zod';
+import type { DriveLocation, DriveTab } from '../core/types';
+
+export const DRIVE_DOCUMENT_TYPES = [
+ 'md',
+ 'task',
+ 'skill',
+ 'snippet',
+ 'canvas',
+ 'pdf',
+ 'code',
+ 'csv',
+ 'image',
+ 'video',
+ 'spreadsheet',
+ 'unknown',
+] as const;
+export type DriveDocumentType = (typeof DRIVE_DOCUMENT_TYPES)[number];
+export type DriveDocumentRoute = { id: string; type: DriveDocumentType };
+export type DriveRouteParams = SplitRouteParams & {
+ tab?: DriveTab;
+ view?: 'folder';
+ folderId?: string;
+ documentId?: string;
+ documentType?: DriveDocumentType;
+};
+
+function documentBlockType(type: string) {
+ if (type === 'task' || type === 'snippet' || type === 'skill') return 'md';
+ return type === 'csv' ? 'code' : type;
+}
+
+const documentType = z.enum(DRIVE_DOCUMENT_TYPES);
+const documentParams = z.object({
+ documentType,
+ documentId: z.string().min(1),
+});
+
+function documentRoute<const TId extends string>(id: TId) {
+ return defineRoute({
+ id,
+ path: ':documentType/:documentId',
+ params: documentParams,
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${documentBlockType(documentType)}:${documentId}`,
+ }),
+ });
+}
+
+const rootDocument = documentRoute('drive-document');
+const folderDocument = documentRoute('drive-folder-document');
+const tabDocument = documentRoute('drive-tab-document');
+const folderRoute = defineRoute({
+ id: 'drive-folder',
+ path: 'folder/:folderId?',
+ params: z
+ .object({ folderId: z.string().min(1).optional() })
+ .transform(({ folderId }) => ({ view: 'folder' as const, folderId })),
+ children: [folderDocument],
+});
+const tabRoute = defineRoute({
+ id: 'drive-tab',
+ path: ':tab',
+ aliases: ['tab/:tab'],
+ params: z.object({ tab: z.enum(['recent', 'shared']) }),
+ children: [tabDocument],
+});
+
+export const driveSplitRoute = defineRoute({
+ id: 'drive',
+ path: 'drive',
+ aliases: ['drive/owned', 'drive/tab/owned'],
+ params: z.object({}),
+ // Drive lists are independent workspaces, not singleton content. Only the
+ // document children claim content; returning to a list must stay in its pane.
+ search: ['drive'],
+ externalSearch: (entry: Readonly<SplitRouterEntry>) => {
+ const type = routeParams<DriveRouteParams>(
+ entry.location.route
+ ).documentType;
+ if (
+ type === 'md' ||
+ type === 'task' ||
+ type === 'snippet' ||
+ type === 'skill'
+ ) {
+ return Object.values(MARKDOWN_URL_PARAMS);
+ }
+ return type === 'pdf' ? Object.values(PDF_URL_PARAMS) : [];
+ },
+ children: [folderRoute, tabRoute, rootDocument],
+});
+
+export function driveLocationFromParams(
+ params: DriveRouteParams
+): DriveLocation {
+ return params.view === 'folder'
+ ? { kind: 'folder', id: params.folderId ?? null }
+ : { kind: 'tab', tab: params.tab ?? 'owned' };
+}
+
+export function driveDocumentFromParams(
+ params: DriveRouteParams
+): DriveDocumentRoute | undefined {
+ if (!params.documentId || !params.documentType) return;
+ return { id: params.documentId, type: params.documentType };
+}
+
+type DriveDestination = SplitRouteNavigationTarget<
+ | typeof driveSplitRoute
+ | typeof folderRoute
+ | typeof tabRoute
+ | typeof rootDocument
+ | typeof folderDocument
+ | typeof tabDocument
+>;
+
+/** One typed destination builder for list and detail navigation. */
+export function driveDestination(
+ location: DriveLocation,
+ document?: DriveDocumentRoute
+): DriveDestination {
+ const detail = document && {
+ documentId: document.id,
+ documentType: document.type,
+ };
+ if (location.kind === 'folder') {
+ const params = {
+ view: 'folder' as const,
+ folderId: location.id ?? undefined,
+ };
+ return detail
+ ? { route: folderDocument, params: { ...params, ...detail } }
+ : { route: folderRoute, params };
+ }
+ if (location.tab !== 'owned') {
+ const params = { tab: location.tab };
+ return detail
+ ? { route: tabDocument, params: { ...params, ...detail } }
+ : { route: tabRoute, params };
+ }
+ return detail
+ ? { route: rootDocument, params: detail }
+ : { route: driveSplitRoute, params: {} };
+}
+
+/** String URLs are only needed at legacy redirect boundaries. */
+export function drivePath(
+ location: DriveLocation,
+ document?: DriveDocumentRoute
+): string {
+ const segments = ['drive'];
+ if (location.kind === 'folder') {
+ segments.push('folder');
+ if (location.id) segments.push(location.id);
+ } else if (location.tab !== 'owned') segments.push(location.tab);
+ if (document) segments.push(document.type, document.id);
+ return `/${segments.map(encodeURIComponent).join('/')}`;
+}
+
+export function driveDocumentRoute(document: {
+ id: string;
+ fileType: string;
+ subType?: string;
+}): DriveDocumentRoute {
+ return {
+ id: document.id,
+ type:
+ documentType.safeParse(
+ documentBlockType(document.subType ?? document.fileType)
+ ).data ?? 'unknown',
+ };
+}
+
+export function driveDocumentFromContent(content: {
+ type: string;
+ id: string;
+}): DriveDocumentRoute | undefined {
+ const type = documentType.safeParse(documentBlockType(content.type)).data;
+ return type ? { id: content.id, type } : undefined;
+}
+
+const searchSchema = z.object({
+ scope: z.enum(['default', 'all', 'attachments']),
+ sort: z.enum(['updated_at', 'created_at', 'viewed_at']),
+ facets: z.record(z.string(), z.array(z.string())),
+});
+export type DriveSearchParams = z.infer<typeof searchSchema>;
+const reservedSearchFields = new Set(['scope', 'sort', 'facets']);
+
+export const driveSearch = {
+ namespace: 'drive',
+ schema: searchSchema,
+ defaults: {
+ scope: 'default',
+ sort: 'updated_at',
+ facets: {},
+ } as DriveSearchParams,
+ serialize(value, { defaults }): SerializedSearchParams | undefined {
+ const params: SerializedSearchParams = {};
+ if (value.scope !== defaults.scope) params.scope = [value.scope];
+ if (value.sort !== defaults.sort) params.sort = [value.sort];
+ for (const [field, values] of Object.entries(
+ normalizeFacetSelection(value.facets)
+ )) {
+ if (isSafeName(field) && !reservedSearchFields.has(field))
+ params[field] = values;
+ }
+ return Object.keys(params).length ? params : undefined;
+ },
+ deserialize(params) {
+ const scope = takeLast(params.scope);
+ const sort = takeLast(params.sort);
+ const legacy = takeLast(params.facets);
+ const facets =
+ legacy === undefined ? {} : deserializeFacetSelection(legacy);
+ for (const [field, values] of Object.entries(params)) {
+ if (!reservedSearchFields.has(field)) facets[field] = values;
+ }
+ return {
+ ...(scope === undefined
+ ? {}
+ : { scope: scope as DriveSearchParams['scope'] }),
+ ...(sort === undefined
+ ? {}
+ : { sort: sort as DriveSearchParams['sort'] }),
+ facets: normalizeFacetSelection(facets),
+ };
+ },
+} satisfies CreateSearchParamsOptions<DriveSearchParams>;
diff --git a/apps/web/src/features/drive-view/primitives/drive-state.ts b/apps/web/src/features/drive-view/primitives/drive-state.ts
index 77e85f8616..69f1412523 100644
--- a/apps/web/src/features/drive-view/primitives/drive-state.ts
+++ b/apps/web/src/features/drive-view/primitives/drive-state.ts
@@ -16,7 +16,7 @@ export function createDriveState(options: {
state: Accessor<DriveState>;
setState: Setter<DriveState>;
folders: Accessor<DriveFolderMetadata[]>;
- list: DriveListState;
+ list: Pick<DriveListState, 'reset'>;
showList: () => void;
}) {
const { state, setState, list } = options;
diff --git a/apps/web/src/features/drive-view/views/drive-breadcrumbs.tsx b/apps/web/src/features/drive-view/views/drive-breadcrumbs.tsx
index 00be1f11d9..4cbe830aee 100644
--- a/apps/web/src/features/drive-view/views/drive-breadcrumbs.tsx
+++ b/apps/web/src/features/drive-view/views/drive-breadcrumbs.tsx
@@ -1,16 +1,16 @@
-import { useEntityDetailNavigationStack } from '@app/components/entity-detail/EntityDetailNavigationStack';
import { ViewBreadcrumbs } from '@app/components/view-shell';
import type { ParentProps } from 'solid-js';
import { DriveLocationBreadcrumbItems } from '../components/DriveBreadcrumbs';
import { useDriveView } from '../context/drive-context';
import type { DriveLocationBreadcrumb } from '../core/breadcrumbs';
+import { useDriveDetailNavigation } from '../drive-detail-navigation';
export function DriveBreadcrumbs(
props: ParentProps<{ entries: DriveLocationBreadcrumb[] }>
) {
const { state, sidebar, actions } = useDriveView();
- const navigation = useEntityDetailNavigationStack();
+ const navigation = useDriveDetailNavigation();
return (
<ViewBreadcrumbs.Root
diff --git a/apps/web/src/features/drive-view/views/drive-workspace.tsx b/apps/web/src/features/drive-view/views/drive-workspace.tsx
index 283a46289f..c91be28077 100644
--- a/apps/web/src/features/drive-view/views/drive-workspace.tsx
+++ b/apps/web/src/features/drive-view/views/drive-workspace.tsx
@@ -1,14 +1,14 @@
-import { useEntityDetailNavigationStack } from '@app/components/entity-detail/EntityDetailNavigationStack';
import { useViewTabHotkeys, ViewShell } from '@app/components/view-shell';
+import { SplitRouter } from '@app/split-router';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
import SpinnerIcon from '@phosphor/spinner.svg';
import { createMemo, Show, Suspense } from 'solid-js';
-import { DriveDetailView } from '../components/DriveDetailView';
import { DriveFileDropzone } from '../components/drive-file-dropzone';
import { useDriveView } from '../context/drive-context';
import { driveLocationBreadcrumbs } from '../core/breadcrumbs';
import { DRIVE_TABS } from '../core/types';
+import { useDriveDetailNavigation } from '../drive-detail-navigation';
import { DriveBreadcrumbs } from './drive-breadcrumbs';
import { DriveHeader } from './drive-header';
import { DriveList } from './drive-list';
@@ -29,7 +29,7 @@ export function DriveWorkspace() {
driveLocationBreadcrumbs(state.value().location, sidebar.folders())
);
- const navigation = useEntityDetailNavigationStack();
+ const navigation = useDriveDetailNavigation();
const panel = useSplitPanelOrThrow();
@@ -77,7 +77,7 @@ export function DriveWorkspace() {
</>
}
>
- <DriveDetailView breadcrumbOrderOffset={breadcrumbs().length} />
+ <SplitRouter.Outlet />
</Show>
</ViewShell.Main>
</ViewShell.Root>
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.tsx
index b8f091d34f..7a864a542a 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
@@ -230,19 +230,6 @@ type SoupRowEntry = {
family: SoupRowFamily;
};
-/**
- * Per-view row config. A view absent from the table gets DEFAULT_SOUP_ROW.
- * Adding a row component means adding it here — the entry can't omit its
- * geometry family, so the two can't drift apart.
- */
-const SOUP_ROW_BY_VIEW: Partial<Record<ListView, SoupRowEntry>> = {
- inbox: { component: InboxListEntity, family: 'card' },
- tasks: { component: TaskListEntity, family: 'row' },
- companies: { component: CompanyListEntity, family: 'row' },
-};
-
-const DEFAULT_SOUP_ROW: SoupRowEntry = { component: ListEntity, family: 'row' };
-
const CONDENSED_NARROW_LIST_VIEWS: ReadonlySet<ListView> = new Set([
'channels',
]);
@@ -929,11 +916,18 @@ const SoupViewListContent = (props: SoupViewListProps) => {
// Register soup view hotkeys (jump navigation, enter, escape, cmd+k, etc.)
const { applyTabPreset } = useApplyPreset();
- // The row component and its geometry family both come from one per-view
- // lookup, so the list container can't disagree with the rows it renders.
+ // Resolve imported components at mount, not during module evaluation: the
+ // legacy block registry can import Soup while the entity barrel is loading.
+ // Keeping component and geometry together prevents mismatched row layouts.
+ const rowsByView: Partial<Record<ListView, SoupRowEntry>> = {
+ inbox: { component: InboxListEntity, family: 'card' },
+ tasks: { component: TaskListEntity, family: 'row' },
+ companies: { component: CompanyListEntity, family: 'row' },
+ };
+ const defaultRow: SoupRowEntry = { component: ListEntity, family: 'row' };
const rowEntry = (): SoupRowEntry => {
const view = currentView();
- return (view && SOUP_ROW_BY_VIEW[view]) ?? DEFAULT_SOUP_ROW;
+ return (view && rowsByView[view]) ?? defaultRow;
};
const groupHeaderComponent = () => {
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index 85921e4804..23b2ee9fc9 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -1,6 +1,11 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-const { toastAlert, ...operationMocks } = vi.hoisted(() => {
+const toastAlert = vi.hoisted(() => vi.fn());
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { alert: toastAlert },
+}));
+
+const operationMocks = vi.hoisted(() => {
const store: Record<string, string> = {};
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
@@ -18,7 +23,6 @@ const { toastAlert, ...operationMocks } = vi.hoisted(() => {
},
});
return {
- toastAlert: vi.fn(),
bulkMarkNotificationsAsDone: vi.fn(async () => {}),
bulkMarkNotificationsAsUndone: vi.fn(async () => {}),
cancelQueries: vi.fn(async () => {}),
@@ -48,9 +52,6 @@ vi.mock('@service-connection/websocket', () => ({
createConnectionBlockWebsocketEffect: vi.fn(),
createConnectionWebsocketEffect: vi.fn(),
}));
-vi.mock('@core/component/Toast/Toast', () => ({
- toast: { alert: toastAlert },
-}));
vi.mock('@queries/client', () => ({
queryClient: {
cancelQueries: operationMocks.cancelQueries,
@@ -389,6 +390,55 @@ describe('calendar block navigation', () => {
});
});
+describe('Drive document routing', () => {
+ it.each(['md', 'pdf', 'canvas'] as const)(
+ 'opens %s documents as canonical Drive content',
+ async (fileType) => {
+ const openWithSplit = vi.fn(() => ({ status: 'unavailable' }));
+ setGlobalSplitManager({
+ activeSplit: vi.fn(),
+ getOrchestrator: vi.fn(() => ({})),
+ getSplitByContent: vi.fn(),
+ openWithSplit,
+ } as unknown as SplitManager);
+
+ await openEntityInSplitFromUnifiedList(
+ {
+ type: 'document',
+ id: 'doc-1',
+ fileType,
+ } as EntityData,
+ { openInNewSplit: true }
+ );
+
+ expect(openWithSplit).toHaveBeenCalledWith(
+ {
+ type: 'component',
+ id: 'documents',
+ entryMetadata: {
+ route: {
+ matches: [
+ { id: 'drive', params: {} },
+ {
+ id: 'drive-document',
+ params: {
+ documentId: 'doc-1',
+ documentType: fileType,
+ },
+ },
+ ],
+ },
+ },
+ },
+ expect.objectContaining({
+ allowDuplicate: true,
+ preferNewSplit: true,
+ })
+ );
+ }
+ );
+});
+
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.ts
index 2694d2fc0e..8e84d2be7b 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -1,4 +1,5 @@
import { isListViewID } from '@app/constants/list-views';
+import { driveDocumentFromContent } from '@app/features/drive-view/primitives/drive-route';
import { URL_PARAMS as EMAIL_PARAMS } from '@app/features/email-thread/core/location';
import { withListNavigationSource } from '@app/features/soup/collection/list-navigation-source';
import {
@@ -26,6 +27,7 @@ import type {
SplitContent,
SplitHandle,
} from '@components/app/split-layout/layoutManager';
+import { driveSplitContent } from '@components/app/split-layout/split-router/legacy-route';
import { toast } from '@core/component/Toast/Toast';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import {
@@ -685,7 +687,13 @@ export const openEntityInSplitFromUnifiedList = async (
: undefined;
const referredFrom = options.referredFrom ?? sourceListView;
- let splitContent: SplitContent = { ...content, params };
+ // Documents are hosted by Drive. Construct the canonical routed content
+ // before opening the split so the layout manager does not mount a legacy
+ // block and immediately replace it during router feedback.
+ const driveDocument = driveDocumentFromContent(content);
+ let splitContent: SplitContent = driveDocument
+ ? driveSplitContent({ kind: 'tab', tab: 'owned' }, driveDocument)
+ : { ...content, params };
if (splitHandle && referredFrom && isListViewID(referredFrom)) {
splitContent = withListNavigationSource(splitContent, splitHandle);
}
@@ -696,7 +704,11 @@ export const openEntityInSplitFromUnifiedList = async (
preferNewSplit: openInNewSplit,
handle: splitHandle,
mergeHistory,
- allowDuplicate,
+ // Each routed document has a distinct Drive location even though all
+ // Drive splits share the same component identity.
+ allowDuplicate:
+ allowDuplicate ||
+ (splitContent.type === 'component' && splitContent.id === 'documents'),
reopen:
entity.type === 'channel' && !location && openChannelAtLatest
? 'latest'
diff --git a/apps/web/src/features/settings/Settings.tsx b/apps/web/src/features/settings/Settings.tsx
index 713d13ff78..5b5f64061e 100644
--- a/apps/web/src/features/settings/Settings.tsx
+++ b/apps/web/src/features/settings/Settings.tsx
@@ -1,4 +1,5 @@
import { toBaseRelative } from '@app/constants/routerBase';
+import { useParams, useNavigate as useSplitNavigate } from '@app/split-router';
import { PillTabs } from '@components/app/mobile/PillTabs';
import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
import {
@@ -14,7 +15,11 @@ import {
useSettingsState,
} from '@core/constant/SettingsState';
import { stripSettingsSplitFromUrl } from '@core/constant/settingsSplitUrl';
-import { useSettingsTabs } from '@core/constant/settingsTabsConfig';
+import {
+ settingsSlugToTab,
+ settingsTabToSlug,
+ useSettingsTabs,
+} from '@core/constant/settingsTabsConfig';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import type { ValidHotkey } from '@core/hotkey/types';
import { isMobile } from '@core/mobile/isMobile';
@@ -49,6 +54,8 @@ const NARROW_WIDTH = 820;
export function SettingsPanelComponentWrapper() {
const location = useLocation();
+ const params = useParams<{ tab?: string }>();
+
// Sync the active page from the docked split's URL (`settings/<slug>`). Read
// the live URL reactively — not static mount props — so browser back/forward
// and direct navigation stay in sync: reconcile reuses this component on
@@ -58,9 +65,13 @@ export function SettingsPanelComponentWrapper() {
// activeTabId read is untracked so a tab click (which sets it, then updates
// the URL) isn't reverted by this effect firing before the URL catches up.
createRenderEffect(() => {
- const tab = settingsTabFromSplitPath(location.pathname);
+ const tab =
+ (params.tab && settingsSlugToTab(params.tab)) ??
+ settingsTabFromSplitPath(location.pathname);
+
if (tab && untrack(activeTabId) !== tab) setActiveTabId(tab);
});
+
return (
<Show when={!isMobile()} fallback={<MobileSettingsDeepLink />}>
<SettingsPanel variant={isSoloSettings() ? 'fullscreen' : 'split'} />
@@ -73,8 +84,10 @@ function MobileSettingsDeepLink() {
const location = useLocation();
const navigate = useNavigate();
const { openSettings } = useSettingsState();
+
onMount(() => {
const tab = settingsTabFromSplitPath(location.pathname) ?? activeTabId();
+
openSettings(tab);
navigate(
stripSettingsSplitFromUrl(
@@ -83,6 +96,7 @@ function MobileSettingsDeepLink() {
{ replace: true }
);
});
+
return null;
}
@@ -100,6 +114,7 @@ export function SettingsPanel(props: SettingsPanelProps) {
activeTabId,
selectTab,
} = useSettingsState();
+ const splitNavigate = useSplitNavigate();
const { groups, flatTabs } = useSettingsTabs();
const logout = useLogout();
@@ -145,13 +160,20 @@ export function SettingsPanel(props: SettingsPanelProps) {
hotkey: 'escape',
});
+ const selectRoutedTab = (tab: SettingsTab) => {
+ selectTab(tab);
+ if (!isMobile()) {
+ splitNavigate(`/settings/${settingsTabToSlug(tab)}`);
+ }
+ };
+
// Helper to navigate to a tab by index
function navigateToTabIndex(index: number): boolean {
const tabs = flatTabs();
if (index >= 0 && index < tabs.length) {
const tab = tabs[index];
if (tab) {
- selectTab(tab.tab);
+ selectRoutedTab(tab.tab);
return true;
}
}
@@ -213,7 +235,7 @@ export function SettingsPanel(props: SettingsPanelProps) {
const handleTabChange = (value: string) => {
if (flatTabs().some((tab) => tab.tab === value)) {
- selectTab(value as SettingsTab);
+ selectRoutedTab(value as SettingsTab);
}
};
diff --git a/apps/web/src/lib/constants/defaultRoute.ts b/apps/web/src/lib/constants/defaultRoute.ts
index af2467c525..b2eafe1c26 100644
--- a/apps/web/src/lib/constants/defaultRoute.ts
+++ b/apps/web/src/lib/constants/defaultRoute.ts
@@ -1,6 +1,6 @@
-export const DEFAULT_ROUTE = '/component/inbox';
+export const DEFAULT_ROUTE = '/inbox';
/**
* Where leaving onboarding lands when no deep link was preserved (`?next=`)
*/
-export const AFTER_SETUP_ROUTE = '/component/getting-started';
+export const AFTER_SETUP_ROUTE = '/getting-started';
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
index f7f17c744c..8292b45fd9 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
@@ -521,6 +521,56 @@ describe('agent session sharing', () => {
);
});
+ it('uses a host view contextual link when provided', () => {
+ mocks.inBlock = false;
+ const copyContextLink = vi.fn();
+ render(() => (
+ <ShareDialogContext.Provider
+ value={{
+ isOpen: () => false,
+ open: vi.fn(),
+ close: vi.fn(),
+ copyLink: copyContextLink,
+ }}
+ >
+ <ShareTrigger id="task-1" blockType="task" />
+ </ShareDialogContext.Provider>
+ ));
+
+ fireEvent.click(screen.getByRole('button', { name: 'Copy Share Link' }));
+ expect(copyContextLink).toHaveBeenCalledOnce();
+ expect(mocks.copyLink).not.toHaveBeenCalled();
+ });
+
+ it('uses the host view contextual link inside the share modal', () => {
+ const copyContextLink = vi.fn();
+ render(() => (
+ <ShareDialogContext.Provider
+ value={{
+ isOpen: () => true,
+ open: vi.fn(),
+ close: vi.fn(),
+ copyLink: copyContextLink,
+ }}
+ >
+ <ShareModal
+ id="persisted-session"
+ name="Fix the menu"
+ owner="someone-else"
+ itemType="agent_session"
+ blockAlias="agent"
+ userPermissions={Permissions.CAN_VIEW}
+ isSharePermOpen
+ setIsSharePermOpen={vi.fn()}
+ />
+ </ShareDialogContext.Provider>
+ ));
+
+ fireEvent.click(screen.getByRole('button', { name: 'Copy Link' }));
+ expect(copyContextLink).toHaveBeenCalledOnce();
+ expect(mocks.copyLink).not.toHaveBeenCalled();
+ });
+
it('copies the saved session link from the shared header trigger', () => {
const [id, setId] = createSignal('saved-session');
render(() => (
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
index f57d772a2b..6bcfb6918b 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
@@ -151,6 +151,8 @@ interface IShareDialogContext {
isOpen: Accessor<boolean>;
open: () => void;
close: () => void;
+ /** Override the entity-only URL with a host view's contextual URL. */
+ copyLink?: () => void;
}
export const ShareDialogContext = createContext<IShareDialogContext>();
@@ -703,6 +705,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
export function ShareModal(props: ShareModalProps) {
const navigate = useNavigate();
const analytics = useAnalytics();
+ const shareContext = useContext(ShareDialogContext);
const currentTeamQuery = useCurrentTeamQuery();
const callRecordQuery = useCallRecordQuery(() =>
props.itemType === 'call' ? props.id : ''
@@ -744,6 +747,9 @@ export function ShareModal(props: ShareModalProps) {
const referralCode = useReferralCode();
const copyLink = createCallback(() => {
+ const contextualCopyLink = shareContext?.copyLink;
+ if (contextualCopyLink) return contextualCopyLink();
+
const params: Record<string, string> = {};
const code = referralCode();
if (code) {
@@ -1550,6 +1556,7 @@ export function ShareTrigger(props: {
const copyLink = createCallback(() => {
if (props.copyLink) return props.copyLink();
+ if (shareCtx.copyLink) return shareCtx.copyLink();
navigator.clipboard.writeText(defaultUrl());
analytics.track('copy_share_link', { blockType: blockType() });
toast.success('Link copied to clipboard.', {
diff --git a/apps/web/src/lib/core/constant/SettingsState.test.tsx b/apps/web/src/lib/core/constant/SettingsState.test.tsx
index 7f2bd8b0f9..0fe351b5cd 100644
--- a/apps/web/src/lib/core/constant/SettingsState.test.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.test.tsx
@@ -192,10 +192,23 @@ describe('settings entry points', () => {
expect(mocks.replaceAllSplits).toHaveBeenCalledWith({
type: 'component',
id: 'settings',
+ entryMetadata: {
+ route: {
+ matches: [{ id: 'settings', params: { tab: 'billing' } }],
+ },
+ },
});
state.openSettingsInSplit('Appearance');
expect(mocks.openWithSplit).toHaveBeenCalledWith(
- { type: 'component', id: 'settings' },
+ {
+ type: 'component',
+ id: 'settings',
+ entryMetadata: {
+ route: {
+ matches: [{ id: 'settings', params: { tab: 'appearance' } }],
+ },
+ },
+ },
expect.objectContaining({ allowDuplicate: false, preferNewSplit: true })
);
});
diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsx
index 3f9fee4f2e..a5ae8533c4 100644
--- a/apps/web/src/lib/core/constant/SettingsState.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.tsx
@@ -1,6 +1,11 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
import { toBaseRelative } from '@app/constants/routerBase';
import { useMobileSettings } from '@app/features/settings/context/mobile-settings';
+import {
+ rootRouteMatch,
+ routeParams,
+ type SplitLocation,
+} from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { isMobile } from '@core/mobile/isMobile';
@@ -10,6 +15,7 @@ import { useLocation, useNavigate } from '@solidjs/router';
import { createMemo, createSignal } from 'solid-js';
import {
appendSettingsSplitToUrl,
+ settingsTabSlugFromUrl,
stripSettingsSplitFromUrl,
} from './settingsSplitUrl';
import { settingsSlugToTab, settingsTabToSlug } from './settingsTabsConfig';
@@ -69,13 +75,8 @@ export const currentSettingsReturnTo = settingsReturnTo;
*/
export const settingsTabFromSplitPath = (
pathname: string
-): SettingsTab | undefined => {
- const segments = toBaseRelative(pathname).split('/').filter(Boolean);
- for (let i = 0; i + 1 < segments.length; i += 2) {
- if (segments[i] === 'settings') return settingsSlugToTab(segments[i + 1]);
- }
- return undefined;
-};
+): SettingsTab | undefined =>
+ settingsSlugToTab(settingsTabSlugFromUrl(toBaseRelative(pathname)) ?? '');
/**
* Whether settings is the only visible split — the "clobbered" mode that
@@ -87,14 +88,20 @@ export const settingsTabFromSplitPath = (
*/
export const isSoloSettings = () => {
if (isMobile()) return false;
+
const splitManager = globalSplitManager();
+
if (!splitManager) return false;
+
// Derive the sole split from the visible set (not `splits()[0]`) so the
// count check and the identity check agree even if an exclusion filter ever
// hides a split ahead of settings.
const visible = splitManager.getVisibleSplits();
+
if (visible.length !== 1) return false;
+
const [sole] = visible;
+
return sole?.content.type === 'component' && sole.content.id === 'settings';
};
@@ -106,23 +113,67 @@ export const useSettingsState = () => {
const getSettingsSplit = () => {
const splitManager = globalSplitManager();
+
if (!splitManager) return undefined;
+
return splitManager.splits().find((split) => {
const content = split.content;
+
return content.type === 'component' && content.id === 'settings';
});
};
const splitOpen = createMemo(() => getSettingsSplit() !== undefined);
+ const settingsContent = (tab: SettingsTab) => ({
+ type: 'component' as const,
+ id: 'settings' as const,
+ entryMetadata: {
+ route: {
+ matches: [
+ {
+ id: 'settings',
+ params: { tab: settingsTabToSlug(tab) },
+ },
+ ],
+ },
+ },
+ });
+
+ const updateSettingsRoute = (tab: SettingsTab) => {
+ const split = getSettingsSplit();
+
+ if (!split) return;
+
+ const slug = settingsTabToSlug(tab);
+ const location = split.content.entryMetadata as SplitLocation | undefined;
+
+ if (
+ rootRouteMatch(location?.route)?.id === 'settings' &&
+ routeParams(location?.route).tab === slug
+ ) {
+ return;
+ }
+
+ globalSplitManager()
+ ?.getSplit(split.id)
+ ?.updateCurrentEntry((content) => ({
+ ...content,
+ entryMetadata: settingsContent(tab).entryMetadata,
+ }));
+ };
+
const focusSettingsPanel = () => {
if (isTouchDevice()) return;
setTimeout(() => {
const settingsSplit = getSettingsSplit();
+
if (!settingsSplit) return;
+
const settingsPanel = document.querySelector<HTMLElement>(
`[data-split-id="${settingsSplit.id}"] [data-settings-panel]`
);
+
settingsPanel?.focus({ preventScroll: true });
}, 10);
};
@@ -139,7 +190,7 @@ export const useSettingsState = () => {
)
);
setActiveTabId(tab);
- replaceAllSplits({ type: 'component', id: 'settings' });
+ replaceAllSplits(settingsContent(tab));
};
// Mobile opens an in-place settings sheet; a fresh open lands on its index.
@@ -152,12 +203,17 @@ export const useSettingsState = () => {
)
);
mobileSettings.openSettings(tab);
+
return;
}
+
if (splitOpen()) {
- setActiveTabId(tab ?? 'Account');
+ const nextTab = tab ?? 'Account';
+ setActiveTabId(nextTab);
+ updateSettingsRoute(nextTab);
return;
}
+
collapseToSoloSettings(tab ?? 'Account');
};
@@ -166,29 +222,34 @@ export const useSettingsState = () => {
const selectTab = (tab: SettingsTab) => {
if (isMobile()) {
mobileSettings.selectPage(tab);
+
return;
}
+
setActiveTabId(tab);
+ updateSettingsRoute(tab);
};
// Opt-in: dock settings into the split layout (the pre-route behavior).
const openSettingsInSplit = (activeTabId?: SettingsTab) => {
if (isMobile()) {
openSettings(activeTabId);
+
return;
}
+
if (activeTabId) setActiveTabId(activeTabId);
- openWithSplit(
- { type: 'component', id: 'settings' },
- {
- activate: true,
- // Single settings split only: getSettingsSplit/removeSettingsSplit
- // assume one exists, so reuse an existing one instead of duplicating.
- allowDuplicate: false,
- preferNewSplit: true,
- mergeHistory: false,
- }
- );
+
+ const tab = activeTabId ?? 'Account';
+
+ openWithSplit(settingsContent(tab), {
+ activate: true,
+ // Single settings split only: getSettingsSplit/removeSettingsSplit
+ // assume one exists, so reuse an existing one instead of duplicating.
+ allowDuplicate: false,
+ preferNewSplit: true,
+ mergeHistory: false,
+ });
focusSettingsPanel();
};
@@ -202,12 +263,16 @@ export const useSettingsState = () => {
const closeSettings = () => {
if (isMobile()) {
mobileSettings.close();
+
return;
}
+
if (isSoloSettings()) {
navigate(settingsReturnTo() ?? DEFAULT_ROUTE, { replace: true });
+
return;
}
+
removeSettingsSplit();
};
@@ -224,6 +289,7 @@ export const useSettingsState = () => {
const returnTo = stripSettingsSplitFromUrl(
settingsReturnTo() ?? DEFAULT_ROUTE
);
+
navigate(
appendSettingsSplitToUrl(returnTo, settingsTabToSlug(activeTabId()))
);
@@ -242,11 +308,13 @@ export const useSettingsState = () => {
if (isMobile()) {
if (mobileSettings.open()) mobileSettings.close();
else openSettings();
+
return;
}
// Solo takes priority: if it's the only thing showing, leave it.
if (isSoloSettings()) {
closeSettings();
+
return;
}
@@ -257,10 +325,12 @@ export const useSettingsState = () => {
if (manager && manager.activeSplitId() !== settingsSplit.id) {
manager.activateSplit(settingsSplit.id);
focusSettingsPanel();
+
return;
}
// Docked and already focused → close it.
manager?.removeSplit(settingsSplit.id);
+
return;
}
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index b4b9733598..77393c3463 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -114,7 +114,7 @@ export function isFeatureEnabled(flag: Flag): boolean {
export const enableNewAppViews = defineFlag({
key: 'enable-new-app-views',
env: 'ENABLE_NEW_APP_VIEWS',
- default: DEV_MODE_ENV || undefined,
+ default: true,
});
/**
diff --git a/apps/web/src/lib/core/constant/settingsSplitUrl.test.ts b/apps/web/src/lib/core/constant/settingsSplitUrl.test.ts
index 327beced2e..4eddac6f99 100644
--- a/apps/web/src/lib/core/constant/settingsSplitUrl.test.ts
+++ b/apps/web/src/lib/core/constant/settingsSplitUrl.test.ts
@@ -1,23 +1,43 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
appendSettingsSplitToUrl,
+ settingsTabSlugFromUrl,
stripSettingsSplitFromUrl,
} from './settingsSplitUrl';
+// Route-only helpers do not need to initialize the application views.
+vi.mock('@components/app/split-layout/split-router/app-views', () => ({
+ withLaunchParams: () => () => null,
+}));
+
+// Legacy split decoding only needs alias resolution to exist.
+vi.mock('@core/constant/allBlocks', () => ({
+ isBlockAlias: vi.fn(() => false),
+ resolveBlockAlias: vi.fn((type: string) => type),
+}));
+
+describe('settingsTabSlugFromUrl', () => {
+ it('reads schema-defaulted settings state from a framed layout', () => {
+ expect(settingsTabSlugFromUrl('/drive/folder/f-1/~/settings')).toBe(
+ 'account'
+ );
+ });
+});
+
describe('stripSettingsSplitFromUrl', () => {
- it('returns a URL without a settings split unchanged', () => {
+ it('canonicalizes an old flat URL and drops unowned search', () => {
expect(
stripSettingsSplitFromUrl('/component/mail/email/e-1?filter=all#sel')
- ).toBe('/component/mail/email/e-1?filter=all#sel');
+ ).toBe('/component/mail/~/email/e-1#sel');
});
- it('strips a trailing settings split, preserving query and hash', () => {
+ it('strips a trailing settings split, preserving the hash', () => {
expect(
stripSettingsSplitFromUrl(
'/component/mail/email/e-1/settings/account?filter=all#sel'
)
- ).toBe('/component/mail/email/e-1?filter=all#sel');
+ ).toBe('/component/mail/~/email/e-1#sel');
});
it('strips the legacy component/settings form', () => {
@@ -33,6 +53,22 @@ describe('stripSettingsSplitFromUrl', () => {
it('falls back to the default route when settings was the only split', () => {
expect(stripSettingsSplitFromUrl('/settings/account')).toBe(DEFAULT_ROUTE);
});
+
+ it('remaps owned repeated search state after removing a variable-length pane', () => {
+ expect(
+ stripSettingsSplitFromUrl(
+ '/drive/folder/f-1/~/settings/account/~/component/mail?s0.drive.sort=created_at&s1.settings.tab=account&s2.mail.filter=unread&s2.mail.filter=starred'
+ )
+ ).toBe(
+ '/drive/folder/f-1/~/component/mail?s0.drive.sort=created_at&s1.mail.filter=unread&s1.mail.filter=starred'
+ );
+ });
+
+ it('accepts an old Agents chat alias and emits its canonical route', () => {
+ expect(
+ stripSettingsSplitFromUrl('/agent-chats/chat-1/~/settings/account')
+ ).toBe('/agents/chat/chat-1');
+ });
});
describe('appendSettingsSplitToUrl', () => {
@@ -42,12 +78,21 @@ describe('appendSettingsSplitToUrl', () => {
'/component/mail/email/e-1?filter=all#sel',
'account'
)
- ).toBe('/component/mail/email/e-1/settings/account?filter=all#sel');
+ ).toBe('/component/mail/~/email/e-1/~/settings/account#sel');
});
it('handles a trailing slash on the base path', () => {
expect(appendSettingsSplitToUrl('/component/inbox/', 'account')).toBe(
- '/component/inbox/settings/account'
+ '/component/inbox/~/settings/account'
);
});
+
+ it('canonicalizes aliases and preserves repeated owned search values', () => {
+ expect(
+ appendSettingsSplitToUrl(
+ '/drive/tab/owned?s0.drive.tag=one&s0.drive.tag=two#sel',
+ 'billing'
+ )
+ ).toBe('/drive/~/settings/billing?s0.drive.tag=one&s0.drive.tag=two#sel');
+ });
});
diff --git a/apps/web/src/lib/core/constant/settingsSplitUrl.ts b/apps/web/src/lib/core/constant/settingsSplitUrl.ts
index 985376dd95..7826180e5a 100644
--- a/apps/web/src/lib/core/constant/settingsSplitUrl.ts
+++ b/apps/web/src/lib/core/constant/settingsSplitUrl.ts
@@ -1,14 +1,28 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
+import {
+ createRoutesManifest,
+ decodeSplitRouterLocation,
+ rootRouteMatch,
+ routeParams,
+ serializeSplitRouterLocation,
+} from '@app/lib/split-router';
+import { appSplitRoutes } from '@components/app/split-layout/split-router/app-routes';
-/**
- * Parse a base-relative app URL. The base only anchors parsing — inputs come
- * from the router's `location`, which is already URL-canonical — and only the
- * pathname/query/hash are ever read back out.
- */
-const parseUrl = (url: string) => new URL(url, 'http://localhost');
+export const settingsTabSlugFromUrl = (
+ urlString: string
+): string | undefined => {
+ // Standalone URL operations can run before a router exists; keep state local.
+ const routes = createRoutesManifest(appSplitRoutes);
+ const entry = decodeSplitRouterLocation({
+ routes,
+ location: urlString,
+ }).entries.find(
+ ({ location }) => rootRouteMatch(location.route)?.id === 'settings'
+ );
-/** Serialize a parsed URL back to its base-relative string form. */
-const toRelativeUrl = (url: URL) => `${url.pathname}${url.search}${url.hash}`;
+ const tab = routeParams(entry?.location.route).tab;
+ return typeof tab === 'string' ? tab : undefined;
+};
/**
* Drop a settings split from a base-relative split-layout URL, if present.
@@ -17,40 +31,62 @@ const toRelativeUrl = (url: URL) => `${url.pathname}${url.search}${url.hash}`;
* inspected so a block id that happens to be "settings" isn't mistaken for
* one.
*
- * The query string and hash are preserved. If settings was the only split,
- * return the default route.
+ * The owned query string and hash are preserved. When settings was the only
+ * split there is no layout left to return to, so the default route is returned.
*/
export const stripSettingsSplitFromUrl = (urlString: string): string => {
- const url = parseUrl(urlString);
- const segments = url.pathname.split('/').filter(Boolean);
-
- for (let i = 0; i + 1 < segments.length; i += 2) {
- const type = segments[i];
- if (
- type === 'settings' ||
- (type === 'component' && segments[i + 1] === 'settings')
- ) {
- segments.splice(i, 2);
- break;
- }
- }
+ const routes = createRoutesManifest(appSplitRoutes);
+ const parsed = decodeSplitRouterLocation({
+ routes,
+ location: urlString,
+ });
+ const entries = [...parsed.entries];
+ const removedSplitIndex = entries.findIndex(
+ ({ location }) => rootRouteMatch(location.route)?.id === 'settings'
+ );
+ if (removedSplitIndex >= 0) entries.splice(removedSplitIndex, 1);
- if (segments.length === 0) return DEFAULT_ROUTE;
+ if (entries.length === 0) return DEFAULT_ROUTE;
- url.pathname = `/${segments.join('/')}`;
- return toRelativeUrl(url);
+ return serializeSplitRouterLocation({
+ routes,
+ entries,
+ previous: parsed.externalLocation,
+ preserveHash: true,
+ });
};
/**
* Append a docked settings split (`settings/<slug>`) to a base-relative
- * split-layout URL, keeping its query string and hash.
+ * split-layout URL, keeping its owned query string and hash.
*/
export const appendSettingsSplitToUrl = (
urlString: string,
settingsTabSlug: string
): string => {
- const url = parseUrl(urlString);
- const base = url.pathname.replace(/\/$/, '');
- url.pathname = `${base}/settings/${settingsTabSlug}`;
- return toRelativeUrl(url);
+ const routes = createRoutesManifest(appSplitRoutes);
+ const parsed = decodeSplitRouterLocation({
+ routes,
+ location: urlString,
+ });
+ return serializeSplitRouterLocation({
+ routes,
+ entries: [
+ ...parsed.entries,
+ {
+ location: {
+ route: {
+ matches: [
+ {
+ id: 'settings',
+ params: { tab: settingsTabSlug },
+ },
+ ],
+ },
+ },
+ },
+ ],
+ previous: parsed.externalLocation,
+ preserveHash: true,
+ });
};
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 01125ebec7..d52b69d769 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -232,57 +232,6 @@ const ROUTES: RouteDefinition[] = [
component: TaskRoute,
},
LAYOUT_ROUTE,
- /** BEGIN - APP ROUTES */
- {
- path: '/inbox',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/recent',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/activity',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/reminders',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/agents',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/mail',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/documents',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/tasks',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/channels',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/calls',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/companies',
- component: LAYOUT_ROUTE.component,
- },
- {
- path: '/files',
- component: LAYOUT_ROUTE.component,
- },
- /** END - APP ROUTES */
-
{
path: '/',
component: BasePathComponent,
diff --git a/apps/web/src/split-router/index.ts b/apps/web/src/split-router/index.ts
new file mode 100644
index 0000000000..8de7b4cafe
--- /dev/null
+++ b/apps/web/src/split-router/index.ts
@@ -0,0 +1 @@
+export * from '@app/lib/split-router';
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 50d0269b8e..4b7ef9a775 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -8,30 +8,39 @@
| `/app/welcome` | Login page (when unauthenticated) |
| `/app/invite?token=<token>` | GTM invite welcome page ("Welcome, <first name>", Continue → signup). Links come from the staff portal, last 48h, and grant the first month of Premium free once the account is created |
| `/app/internal/invite-links` | Macro staff only (`@macro.com`): create GTM invite links and track opens, signups, and subscriptions |
-| `/app/component/inbox` | Desktop: Home (notifications + recent activity); mobile: Notifications soup |
-| `/app/component/mail` | Email client |
-| `/app/component/channels` | Channels list |
-| `/app/component/documents` | Files (documents list) |
-| `/app/component/tasks` | Tasks table |
-| `/app/component/agents` | AI chats / agents list |
+| `/app/inbox` | Desktop: Home (notifications + recent activity); mobile: Notifications soup |
+| `/app/mail` | Email client |
+| `/app/channels` | Channels list |
+| `/app/drive` | Files (Drive defaults to My Files) |
+| `/app/drive/<recent-or-shared>` | A Drive tab (`/app/drive/tab/<...>` remains a compatibility alias) |
+| `/app/drive/folder/<uuid>` | A Drive folder; breadcrumbs resolve from current accessible folder data |
+| `/app/drive/<document-type>/<uuid>` | An item opened inline in My Files |
+| `/app/drive/folder/<uuid>/<document-type>/<uuid>` | An item opened inline in its Drive folder; document types include `md`, `task`, `skill`, `snippet`, `canvas`, `pdf`, `code`, `csv`, `image`, `video`, `spreadsheet`, and `unknown` |
+| `/app/tasks` | Tasks table |
+| `/app/agents` | AI chats / agents list |
| `/app/agents/<uuid>` | Chat agent session with the Agents sidebar |
| `/app/coders/<uuid>` | Code session with the Agents sidebar |
-| `/app/agent-chats/<uuid>` | Legacy AI chat opened in the Agents workspace |
-| `/app/component/calls` | Calls list |
-| `/app/component/companies` | Customers (CRM; needs a team) |
-| `/app/component/activity` | Activity heatmap + feed |
-| `/app/component/home` | Assistant (AI-first landing) |
+| `/app/agents/chat/<uuid>` | Legacy AI chat opened in the Agents workspace (`/app/agent-chats/<uuid>` remains a compatibility alias) |
+| `/app/calls` | Calls list |
+| `/app/companies` | Customers (CRM; needs a team) |
+| `/app/activity` | Activity heatmap + feed |
+| `/app/home` | Assistant (AI-first landing) |
| `/app/calendar/view` | Calendar |
-| `/app/md/<uuid>` | A document |
-| `/app/spreadsheet/<uuid>` | A native Macro spreadsheet |
+| `/app/<document-type>/<uuid>` | Legacy document URL (including `md`, `pdf`, `canvas`, `spreadsheet`, and the other Drive document types); redirects to `/app/drive/<document-type>/<uuid>` |
+| `/app/documents`, `/app/files` | Legacy Files views; redirect to `/app/drive` |
| `/app/chat/<uuid>` | A standalone AI chat |
| `/app/agent/<uuid>` | An agent session (opened from `@macro-new` / `@coder` / `@cursor`) |
| `/app/md/<doc>/chat/<chat>` | Doc + doc-scoped chat in a split |
| `/app/md/<doc>/channel/<channel>` | Doc + channel in a split |
| `/app/settings/account` | Settings (also `/app/settings/api-keys`, `/mcp-server`, `/shortcuts`, etc.) |
-Splits: the app is a tiling window manager. A second pane appends its own segment to the URL
-(`/app/<left>/<right>`). Desktop panes expose Close when available and omit
+Splits: the app is a tiling window manager. Public variable-length routes use
+`~` as the boundary between panes
+(`/app/drive/folder/<uuid>/~/mail`). Legacy fixed `type/id`
+pane routes remain accepted. Known app-view URLs under `/app/component/` redirect
+to their canonical paths above; legacy composers keep their existing paths. Split-specific view state uses positionally
+namespaced query parameters such as `s0.drive.sort=created_at`; route identity
+and breadcrumb nesting remain in the path. Desktop panes expose Close when available and omit
split-history back/forward buttons. Mobile content panes retain their back button.
The app views are referred to as **workspaces**. Expanded workspace sidebars start
@@ -40,7 +49,13 @@ displayed width. Workspace navigation uses shared 32px rows (44px on touch), 16p
glyphs in aligned 20px icon slots, a 6px text gap, and compact sentence-case section
headings. Tags and folders have a separate disclosure button on the **right** of
the row: clicking the label selects the destination; clicking Expand/Collapse
-only opens or closes its children. Long destination names are single-line and
+only opens or closes its children. Selecting a Drive folder or tab closes an
+inline detail into that destination; it does not navigate back to Drive's root.
+Multiple Drive panes navigate their folders, tabs, and history independently;
+returning to a list does not activate another Drive pane. Opening a document
+already displayed in another pane still activates its owner.
+Unavailable documents retain their error/retry UI rather than navigating away.
+Long destination names are single-line and
expose the full name on hover. Section chevrons point right and stay visible when
collapsed. Expanded chevrons point down and appear when hovering their section;
the section heading also brightens on hover. Sections and nested branches briefly
@@ -428,6 +443,13 @@ selection, keyboard preview navigation, and detail breadcrumbs. Touch layouts
never render inline previews or detail views: a tap opens the entity in the
split, so the toast only appears when the content is genuinely open elsewhere.
+Split-router ownership checks use the final redirected destination. Concurrent
+opens of the same claimed resource wait for the first outstanding request rather
+than creating duplicate panes. If pane-history navigation reaches content owned
+by another pane, it focuses that owner without advancing the requesting pane's
+history cursor. Restoring a saved layout preserves existing duplicate panes;
+search-only updates within those panes do not collapse them.
+
## Entity action dialogs
Rename, Delete, and Move to folder use compact centered dialogs on desktop and