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): migrate workspace details to split routes (#6761)

dev-rb11058dd1dda5
diff --git a/apps/web/src/components/app/createPreviewSelectionGuard.test.tsx b/apps/web/src/components/app/createPreviewSelectionGuard.test.tsx
index ae56933e1a..56ad7adea4 100644
--- a/apps/web/src/components/app/createPreviewSelectionGuard.test.tsx
+++ b/apps/web/src/components/app/createPreviewSelectionGuard.test.tsx
@@ -1,5 +1,7 @@
-import { EntityDetailNavigationStack } from '@app/components/entity-detail/EntityDetailNavigationStack';
-import { useNavigationStack } from '@app/components/navigation-stack/NavigationStack';
+import {
+ NavigationStack,
+ useNavigationStack,
+} from '@app/components/navigation-stack/NavigationStack';
import { toast } from '@core/component/Toast/Toast';
import { render } from '@solidjs/testing-library';
import { createMemo, createRoot, type ParentProps } from 'solid-js';
@@ -84,21 +86,28 @@ function Layout(props: ParentProps) {
function setup(defaultValue?: PreviewPanelSelection[]) {
let stack!: ReturnType<typeof useNavigationStack<PreviewPanelSelection>>;
+ let selectionGuard!: ReturnType<typeof createPreviewSelectionGuard>;
function Capture() {
stack = useNavigationStack<PreviewPanelSelection>();
return null;
}
function App() {
+ selectionGuard = createPreviewSelectionGuard();
return (
- <Layout>
- <EntityDetailNavigationStack.Root defaultValue={defaultValue}>
- <Capture />
- </EntityDetailNavigationStack.Root>
- </Layout>
+ <NavigationStack.Root<PreviewPanelSelection>
+ defaultValue={defaultValue}
+ beforeChange={selectionGuard}
+ >
+ <Capture />
+ </NavigationStack.Root>
);
}
- const view = render(App);
- return { stack, ...view };
+ const view = render(() => (
+ <Layout>
+ <App />
+ </Layout>
+ ));
+ return { stack, selectionGuard, ...view };
}
it('does not move focus or toast for a conflicting restored selection', () => {
@@ -175,6 +184,23 @@ it('blocks breadcrumbs back to content opened elsewhere without changing history
first.unmount();
});
+it('preflights without claiming the requested selection', () => {
+ const first = setup();
+ const second = setup();
+ const third = setup();
+ const one = { type: 'email', id: 'one' } as const;
+ const two = { type: 'email', id: 'two' } as const;
+
+ first.stack.reset(one);
+ expect(second.selectionGuard.canSelect(one)).toBe(false);
+ expect(second.selectionGuard.canSelect(two)).toBe(true);
+ expect(third.stack.reset(two)).toBeDefined();
+
+ first.unmount();
+ second.unmount();
+ third.unmount();
+});
+
it('treats Markdown as single-instance and allows revisiting the owning preview', () => {
const first = setup();
const second = setup();
diff --git a/apps/web/src/components/app/createPreviewSelectionGuard.ts b/apps/web/src/components/app/createPreviewSelectionGuard.ts
index 615e6b2114..84f26e5831 100644
--- a/apps/web/src/components/app/createPreviewSelectionGuard.ts
+++ b/apps/web/src/components/app/createPreviewSelectionGuard.ts
@@ -9,8 +9,18 @@ import type { ContentIdentity } from './split-layout/contentInstanceRegistry';
import { SplitLayoutContext } from './split-layout/context';
import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
-/** Call before changing selection. A rejected selection leaves the current preview intact. */
-export function createPreviewSelectionGuard() {
+type SelectPreview = (
+ selection: PreviewPanelSelection | undefined,
+ reason?: NavigationStackChangeReason
+) => boolean;
+
+export type PreviewSelectionGuard = SelectPreview & {
+ /** Checks a requested selection without claiming it before navigation commits. */
+ canSelect: SelectPreview;
+};
+
+/** Call after changing selection. Use canSelect before cancellable navigation. */
+export function createPreviewSelectionGuard(): PreviewSelectionGuard {
const layout = useContext(SplitLayoutContext);
if (!layout) throw new Error('Preview selection requires a split layout');
const manager = layout.manager;
@@ -25,12 +35,12 @@ export function createPreviewSelectionGuard() {
});
onCleanup(unregister);
- return (
- selection: PreviewPanelSelection | undefined,
- reason: NavigationStackChangeReason = 'navigate'
- ) => {
+ const identity = (selection: PreviewPanelSelection | undefined) => {
const target = selection && previewBlockTarget(selection);
- const next = target && { type: target.blockType, id: target.blockId };
+ return target && { type: target.blockType, id: target.blockId };
+ };
+ const canSelect: SelectPreview = (selection, reason = 'navigate') => {
+ const next = identity(selection);
const existing = next && manager.findOpenView(next);
if (existing && existing.owner !== owner) {
if (reason === 'navigate') {
@@ -39,7 +49,13 @@ export function createPreviewSelectionGuard() {
}
return false;
}
- setCurrent(next);
return true;
};
+ const select: SelectPreview = (selection, reason) => {
+ if (!canSelect(selection, reason)) return false;
+ setCurrent(identity(selection));
+ return true;
+ };
+
+ return Object.assign(select, { canSelect });
}
diff --git a/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx b/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
index e53282267f..fb58b286e5 100644
--- a/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
@@ -1,16 +1,25 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
+import { enableNewAppViews } from '@core/constant/featureFlags';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
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 { createAppSplitRouterMiddleware } from './split-router/app-middleware';
import { appSplitRoutes } from './split-router/app-routes';
function LayoutRoute(props: RouteSectionProps) {
+ const newAppViews = useFeatureFlag(enableNewAppViews);
+ const middleware = createAppSplitRouterMiddleware({
+ newAppViews,
+ isTouchDevice,
+ });
+
return (
<SplitLayoutContainer
pairs={props.params.splits?.split('/') ?? []}
routes={appSplitRoutes}
- middleware={appSplitRouterMiddleware}
+ middleware={middleware}
setManager={setGlobalSplitManager}
/>
);
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
index ae5b89c024..8a8931fa11 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
@@ -1,32 +1,122 @@
+import { CHANNEL_DETAIL_SEARCH_NAMESPACE } from '@app/features/channels-view/channels-route';
import {
driveDocumentFromContent,
drivePath,
} from '@app/features/drive-view/primitives/drive-route';
-import { routeParams, type SplitRouterMiddleware } from '@app/lib/split-router';
+import { driveDocumentBlockType } from '@app/features/drive-view/primitives/drive-route-schema';
+import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';
+import { EMAIL_DETAIL_SEARCH_NAMESPACE } from '@app/features/email-view/email-route';
+import {
+ routeParams,
+ type SerializedSearchParams,
+ type SplitRouterMiddleware,
+} from '@app/lib/split-router';
+import { replaceSplitSearchParams } from '@app/lib/split-router/search';
+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { 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');
+type NewAppViewsState = {
+ enabled: boolean;
+ loading: boolean;
+};
+
+export function createAppSplitRouterMiddleware(options: {
+ newAppViews: () => NewAppViewsState;
+ isTouchDevice: () => boolean;
+}): readonly SplitRouterMiddleware[] {
+ return [
+ ({ to, redirect }) => {
if (
- appSplitRoutes.definitions.some((route) => route.id === `view-${id}`)
+ to.location.route.matches[0].id === 'drive' &&
+ options.isTouchDevice()
) {
- return redirect(`/${id}`);
+ const params = routeParams(to.location.route);
+ if (
+ typeof params.documentType === 'string' &&
+ typeof params.documentId === 'string'
+ ) {
+ return redirect(
+ `/${driveDocumentBlockType(params.documentType)}/${encodeURIComponent(params.documentId)}`
+ );
+ }
+ }
+ 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;
+ if (!content) return;
+ const flag = options.newAppViews();
+ const canRenderDetail =
+ !flag.loading && flag.enabled && !options.isTouchDevice();
+ if (!canRenderDetail) return;
+
+ if (content.type === 'email') {
+ return redirect(`/mail/${encodeURIComponent(content.id)}`);
+ }
+ if (content.type === 'channel') {
+ return redirect(`/channels/channel/${encodeURIComponent(content.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[];
+ if (type === 'task') {
+ return redirect(`/tasks/${encodeURIComponent(content.id)}`);
+ }
+
+ const document = driveDocumentFromContent(content);
+ if (!document) return;
+ return redirect(drivePath({ kind: 'tab', tab: 'owned' }, document));
+ },
+ ({ to, path, cause, externalSearch, redirect }) => {
+ if (cause !== 'initial' && cause !== 'external') return;
+ if (!externalSearch) return;
+
+ const leafId = to.location.route.matches.at(-1)?.id;
+ let namespace: string;
+ let fields: [string, string][];
+ if (leafId === 'mail-thread') {
+ namespace = EMAIL_DETAIL_SEARCH_NAMESPACE;
+ fields = [[EMAIL_URL_PARAMS.messageId, 'messageId']];
+ } else if (leafId === 'channels-channel') {
+ namespace = CHANNEL_DETAIL_SEARCH_NAMESPACE;
+ fields = [
+ [CHANNEL_URL_PARAMS.message, 'messageId'],
+ [CHANNEL_URL_PARAMS.thread, 'threadId'],
+ ];
+ } else {
+ return;
+ }
+
+ const raw = new URLSearchParams(externalSearch);
+ const current = to.location.search?.[namespace] ?? {};
+ const additions: SerializedSearchParams = {};
+ for (const [legacyKey, field] of fields) {
+ // Explicit canonical values, including empty ones, take precedence.
+ if (Object.hasOwn(current, field)) continue;
+ const values = raw.getAll(legacyKey);
+ if (values.length) additions[field] = values;
+ }
+ if (!Object.keys(additions).length) return;
+
+ const search = {
+ ...to.location.search,
+ [namespace]: { ...current, ...additions },
+ };
+ const query = new URLSearchParams();
+ // Middleware redirects describe one entry; the router assigns its pane index.
+ replaceSplitSearchParams(query, [{ location: { search } }]);
+ return redirect(`${path}?${query}`);
+ },
+ ];
+}
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
index 07f40830e4..530611bd5d 100644
--- 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
@@ -1,61 +1,123 @@
-import { driveSplitRoute } from '@app/features/drive-view/primitives/drive-route';
+import {
+ DRIVE_DOCUMENT_TYPES,
+ driveDocumentBlockType,
+} from '@app/features/drive-view/primitives/drive-route-schema';
+import { inboxPreviewRouteParams } from '@app/features/inbox-view/inbox-route-schema';
import {
defineRoute,
- type SplitRouteDefinition,
- type SplitRoutes,
+ defineRoutes,
+ routeParams,
+ type SplitRouterEntry,
} from '@app/lib/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 {
settingsSlugToTab,
settingsTabToSlug,
} from '@core/constant/settingsTabsConfig';
-import { type Component, lazy } from 'solid-js';
+import { type Component, createComponent, lazy } from 'solid-js';
import { z } from 'zod';
-import type * as AppViews from './app-views';
+import type { AppRouteViewId } from './app-views';
import { handleLegacySplitPath, legacySplitRoute } from './legacy-route';
-type AppViewSelector = (
- views: typeof AppViews
-) => Component<Record<string, unknown>>;
+const AppRouteRenderer = lazy(async () => ({
+ default: (await import('./app-views')).AppRouteRenderer,
+}));
-// 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)) };
- });
+/** Stable route bindings share one lazy application-view module boundary. */
+function appView(view: AppRouteViewId): Component {
+ return () => createComponent(AppRouteRenderer, { view });
}
-function viewRoute(
- id: string,
- view: AppViewSelector,
+function viewDefinition<const TId extends string>(
+ id: TId,
+ view: AppRouteViewId,
externalSearch: string[] = []
) {
return defineRoute({
id: `view-${id}`,
path: id,
- component: lazyView(view),
- search: '*',
+ component: appView(view),
+ search: '*' as const,
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 }) => id,
- claim: ({ id }) => ({
- namespace: section === 'agent-chats' ? 'chat' : 'agent',
- id,
- }),
- })
-);
+const driveDocumentParams = z.object({
+ documentType: z.enum(DRIVE_DOCUMENT_TYPES),
+ documentId: z.string().min(1),
+});
+export const driveRootDocumentRoute = defineRoute({
+ id: 'drive-document',
+ path: ':documentType/:documentId',
+ params: driveDocumentParams,
+ component: appView('drive-detail'),
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${driveDocumentBlockType(documentType)}:${documentId}`,
+ }),
+});
+export const driveFolderDocumentRoute = defineRoute({
+ id: 'drive-folder-document',
+ path: ':documentType/:documentId',
+ params: driveDocumentParams,
+ component: appView('drive-detail'),
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${driveDocumentBlockType(documentType)}:${documentId}`,
+ }),
+});
+export const driveTabDocumentRoute = defineRoute({
+ id: 'drive-tab-document',
+ path: ':documentType/:documentId',
+ params: driveDocumentParams,
+ component: appView('drive-detail'),
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${driveDocumentBlockType(documentType)}:${documentId}`,
+ }),
+});
+export const driveFolderRoute = defineRoute({
+ id: 'drive-folder',
+ path: 'folder/:folderId?',
+ params: z
+ .object({ folderId: z.string().min(1).optional() })
+ .transform(({ folderId }) => ({ view: 'folder' as const, folderId })),
+ children: [driveFolderDocumentRoute],
+});
+export const driveTabRoute = defineRoute({
+ id: 'drive-tab',
+ path: ':tab',
+ aliases: ['tab/:tab'],
+ params: z.object({ tab: z.enum(['recent', 'shared']) }),
+ children: [driveTabDocumentRoute],
+});
+export const driveSplitRoute = defineRoute({
+ id: 'drive',
+ path: 'drive',
+ aliases: ['drive/owned', 'drive/tab/owned'],
+ params: z.object({}),
+ component: appView('drive'),
+ search: ['drive'],
+ externalSearch: (entry: Readonly<SplitRouterEntry>) => {
+ const type = routeParams<{ documentType?: string }>(
+ entry.location.route
+ ).documentType;
+ if (
+ type === 'md' ||
+ type === 'task' ||
+ type === 'snippet' ||
+ type === 'skill'
+ ) {
+ return Object.values(MARKDOWN_URL_PARAMS);
+ }
+ return type === 'pdf' ? Object.values(PDF_URL_PARAMS) : [];
+ },
+ children: [driveFolderRoute, driveTabRoute, driveRootDocumentRoute],
+});
-const settingsSplitRoute = defineRoute({
+export const settingsRoute = defineRoute({
id: 'settings',
path: 'settings/:tab?',
params: z.object({
@@ -64,53 +126,160 @@ const settingsSplitRoute = defineRoute({
.refine((tab) => settingsSlugToTab(tab) !== undefined)
.default(settingsTabToSlug('Account')),
}),
- component: lazyView((views) => views.SettingsView),
+ component: appView('settings'),
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,
-}));
+export const agentsRoute = defineRoute({
+ id: 'agents',
+ path: 'agents/:id',
+ params: z.object({ id: z.string() }),
+ component: appView('agents'),
+ remountKey: ({ id }) => id,
+ claim: ({ id }) => ({ namespace: 'agent', id }),
+});
+export const codersRoute = defineRoute({
+ id: 'coders',
+ path: 'coders/:id',
+ params: z.object({ id: z.string() }),
+ component: appView('agents'),
+ remountKey: ({ id }) => id,
+ claim: ({ id }) => ({ namespace: 'agent', id }),
+});
+export const agentChatsRoute = defineRoute({
+ id: 'agent-chats',
+ path: 'agents/chat/:id',
+ aliases: ['agent-chats/:id'],
+ params: z.object({ id: z.string() }),
+ component: appView('agents'),
+ remountKey: ({ id }) => id,
+ claim: ({ id }) => ({ namespace: 'chat', id }),
+});
-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 homeRoute = viewDefinition('home', 'home');
+export const gettingStartedRoute = viewDefinition(
+ 'getting-started',
+ 'getting-started'
+);
-export const appSplitRoutes: SplitRoutes = {
+export const inboxPreviewRoute = defineRoute({
+ id: 'inbox-preview',
+ path: ':blockType/:previewId',
+ params: inboxPreviewRouteParams,
+ component: appView('inbox-detail'),
+ remountKey: ({ blockType, previewId }) => `${blockType}:${previewId}`,
+ claim: ({ blockType, previewId }) => ({
+ namespace: 'block',
+ id: `${blockType}:${previewId}`,
+ }),
+});
+export const inboxSplitRoute = defineRoute({
+ id: 'view-inbox',
+ path: 'inbox',
+ params: z.object({}),
+ component: appView('inbox'),
+ search: '*' as const,
+ children: [inboxPreviewRoute],
+});
+
+export const recentRoute = viewDefinition('recent', 'recent');
+export const activityRoute = viewDefinition('activity', 'activity');
+export const remindersRoute = viewDefinition('reminders', 'reminders');
+export const agentsViewRoute = viewDefinition('agents', 'agents', [
+ 'createAgent',
+]);
+
+export const emailThreadRoute = defineRoute({
+ id: 'mail-thread',
+ path: ':threadId',
+ params: z.object({ threadId: z.string().min(1) }),
+ component: appView('mail-detail'),
+ externalSearch: ['email_message_id'],
+ remountKey: ({ threadId }) => threadId,
+ claim: ({ threadId }) => ({
+ namespace: 'block',
+ id: `email:${threadId}`,
+ }),
+});
+export const emailSplitRoute = defineRoute({
+ id: 'view-mail',
+ path: 'mail',
+ params: z.object({}),
+ component: appView('mail'),
+ search: '*' as const,
+ children: [emailThreadRoute],
+});
+
+export const taskDetailRoute = defineRoute({
+ id: 'tasks-task',
+ path: ':taskId',
+ params: z.object({ taskId: z.string().min(1) }),
+ component: appView('tasks-detail'),
+ remountKey: ({ taskId }) => taskId,
+ claim: ({ taskId }) => ({
+ namespace: 'block',
+ id: `md:${taskId}`,
+ }),
+});
+export const tasksSplitRoute = defineRoute({
+ id: 'view-tasks',
+ path: 'tasks',
+ params: z.object({}),
+ component: appView('tasks'),
+ search: '*' as const,
+ children: [taskDetailRoute],
+});
+
+export const channelDetailRoute = defineRoute({
+ id: 'channels-channel',
+ path: 'channel/:channelId',
+ params: z.object({ channelId: z.string().min(1) }),
+ component: appView('channels-detail'),
+ externalSearch: ['channel_message_id', 'channel_thread_id'],
+ remountKey: ({ channelId }) => channelId,
+ claim: ({ channelId }) => ({
+ namespace: 'block',
+ id: `channel:${channelId}`,
+ }),
+});
+export const channelsSplitRoute = defineRoute({
+ id: 'view-channels',
+ path: 'channels',
+ params: z.object({}),
+ component: appView('channels'),
+ search: '*' as const,
+ children: [channelDetailRoute],
+});
+
+export const callsRoute = viewDefinition('calls', 'calls');
+export const companiesRoute = viewDefinition('companies', 'companies', [
+ 'crmView',
+]);
+export const foldersRoute = viewDefinition('folders', 'folders');
+export const searchRoute = viewDefinition('search', 'search');
+
+export const appSplitRoutes = defineRoutes({
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),
+ driveSplitRoute,
+ settingsRoute,
+ agentsRoute,
+ codersRoute,
+ agentChatsRoute,
+ homeRoute,
+ gettingStartedRoute,
+ inboxSplitRoute,
+ recentRoute,
+ activityRoute,
+ remindersRoute,
+ agentsViewRoute,
+ emailSplitRoute,
+ tasksSplitRoute,
+ channelsSplitRoute,
+ callsRoute,
+ companiesRoute,
+ foldersRoute,
+ searchRoute,
legacySplitRoute,
],
globalSearch: ['referral_code'],
@@ -118,4 +287,4 @@ export const appSplitRoutes: SplitRoutes = {
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
index e6c962d09c..626c4ac1af 100644
--- 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
@@ -2,15 +2,30 @@ 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 { channelDetailSearch } from '@app/features/channels-view/channels-route';
+import {
+ ChannelDetailRouteView,
+ ChannelsView,
+} from '@app/features/channels-view/channels-view';
+import { DriveDetailView } from '@app/features/drive-view/components/DriveDetailView';
import {
DriveView,
type DriveViewProps,
} from '@app/features/drive-view/drive-view';
+import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';
+import { EmailDetailRouteView } from '@app/features/email-view/components/EmailDetailView';
+import { emailDetailSearch } from '@app/features/email-view/email-route';
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 {
+ inboxPreviewLegacyTarget,
+ inboxPreviewSearch,
+} from '@app/features/inbox-view/inbox-route';
+import {
+ InboxDetailRouteView,
+ 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';
@@ -19,9 +34,12 @@ import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-prese
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 { TasksDetailRouteView } from '@app/features/tasks-view/components/TasksDetailView';
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 { createSearchParams, useRouteParams } from '@app/lib/split-router';
+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import {
CRM_VIEW_URL_PARAM,
decodeCrmViewParam,
@@ -50,6 +68,12 @@ import {
} from 'solid-js';
import type { SplitContent } from '../layoutManager';
import { useSplitPanelOrThrow } from '../layoutUtils';
+import {
+ channelDetailRoute,
+ emailThreadRoute,
+ inboxPreviewRoute,
+ taskDetailRoute,
+} from './app-routes';
// Legacy fallbacks are loaded only when a view actually needs them.
const SoupView = lazy(async () => ({
@@ -76,18 +100,6 @@ export function withAuth<P extends object>(View: Component<P>): Component<P> {
};
}
-// 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 }));
@@ -101,6 +113,9 @@ function NewAppView(props: {
fallback: JSX.Element;
desktopOnly?: boolean;
composableOnTouch?: boolean;
+ detailRequested?: () => boolean;
+ detailFallback?: JSX.Element;
+ detailDesktopOnly?: boolean;
}) {
usePageViewTracking(props.id);
const panel = useSplitPanelOrThrow();
@@ -110,24 +125,36 @@ function NewAppView(props: {
onCleanup(() => clearTimeout(timer));
const ready = () => !flag().loading || timedOut();
const enabled = () => ready() && flag().enabled;
+ const detailUnsupported = () =>
+ Boolean(
+ props.detailRequested?.() && props.detailDesktopOnly && isTouchDevice()
+ );
+ const surfaceSupported = () => !props.desktopOnly || !isTouchDevice();
+ const renderModern = () =>
+ enabled() && surfaceSupported() && !detailUnsupported();
+ const fallback = () => {
+ if (!props.detailRequested?.()) return props.fallback;
+ // JSX props are getters: evaluate the chosen fallback only once.
+ const detail = props.detailFallback;
+ return detail === undefined ? props.fallback : detail;
+ };
createRenderEffect(() => {
if (!ready()) return;
panel.handle.updateMeta?.({
splitPanelLayout:
- enabled() && (!isTouchDevice() || props.composableOnTouch)
+ renderModern() && (!isTouchDevice() || props.composableOnTouch)
? 'composable'
: 'legacy',
});
});
return (
<Show
- when={ready() || (props.desktopOnly && isTouchDevice())}
+ when={
+ ready() || (props.desktopOnly && isTouchDevice()) || detailUnsupported()
+ }
fallback={<LoadingBlock />}
>
- <Show
- when={enabled() && (!props.desktopOnly || !isTouchDevice())}
- fallback={props.fallback}
- >
+ <Show when={renderModern()} fallback={fallback()}>
{props.children}
</Show>
</Show>
@@ -155,11 +182,41 @@ function LegacyInboxView() {
/>
);
}
-export const InboxRouteView = withAuth(() => (
- <NewAppView id="inbox" composableOnTouch fallback={<LegacyInboxView />}>
- <InboxView />
- </NewAppView>
-));
+function InboxLegacyRouteView() {
+ const params = useRouteParams(inboxPreviewRoute);
+ const [search] = createSearchParams(inboxPreviewSearch);
+ const detailRequested = () =>
+ typeof params.blockType === 'string' &&
+ typeof params.previewId === 'string';
+
+ return (
+ <Show when={detailRequested()} fallback={<LegacyInboxView />}>
+ <RedirectSplit
+ to={inboxPreviewLegacyTarget(params, search) as SplitContent}
+ />
+ </Show>
+ );
+}
+
+export const InboxRouteView = withAuth(() => {
+ const params = useRouteParams(inboxPreviewRoute);
+ const detailRequested = () =>
+ typeof params.blockType === 'string' &&
+ typeof params.previewId === 'string';
+
+ return (
+ <NewAppView
+ id="inbox"
+ composableOnTouch
+ detailDesktopOnly
+ detailRequested={detailRequested}
+ detailFallback={<InboxLegacyRouteView />}
+ fallback={<LegacyInboxView />}
+ >
+ <InboxView />
+ </NewAppView>
+ );
+});
function TrackedRecentView() {
usePageViewTracking('recent');
@@ -316,11 +373,38 @@ function LegacyMailView() {
/>
);
}
-export const MailView = withAuth(() => (
- <NewAppView id="mail" fallback={<LegacyMailView />}>
- <EmailView />
- </NewAppView>
-));
+function MailLegacyRouteView() {
+ const params = useRouteParams(emailThreadRoute);
+ const [search] = createSearchParams(emailDetailSearch);
+ const legacyThread = (id: string): SplitContent => {
+ const params: Record<string, string> = {};
+ if (search.messageId) params[EMAIL_URL_PARAMS.messageId] = search.messageId;
+ return { type: 'email', id, params };
+ };
+
+ return (
+ <Show when={params.threadId} fallback={<LegacyMailView />}>
+ {(threadId) => <RedirectSplit to={legacyThread(threadId())} />}
+ </Show>
+ );
+}
+
+export const MailView = withAuth(() => {
+ const params = useRouteParams(emailThreadRoute);
+ const detailRequested = () => typeof params.threadId === 'string';
+
+ return (
+ <NewAppView
+ id="mail"
+ detailDesktopOnly
+ detailRequested={detailRequested}
+ detailFallback={<MailLegacyRouteView />}
+ fallback={<LegacyMailView />}
+ >
+ <EmailView />
+ </NewAppView>
+ );
+});
export const DriveRouteView = withAuth(
(
@@ -389,11 +473,32 @@ function LegacyTasksView() {
/>
);
}
-export const TasksRouteView = withAuth(() => (
- <NewAppView id="tasks" composableOnTouch fallback={<LegacyTasksView />}>
- <TasksView />
- </NewAppView>
-));
+function TasksLegacyRouteView() {
+ const params = useRouteParams(taskDetailRoute);
+ return (
+ <Show when={params.taskId} fallback={<LegacyTasksView />}>
+ {(taskId) => <RedirectSplit to={{ type: 'task', id: taskId() }} />}
+ </Show>
+ );
+}
+
+export const TasksRouteView = withAuth(() => {
+ const params = useRouteParams(taskDetailRoute);
+ const detailRequested = () => typeof params.taskId === 'string';
+
+ return (
+ <NewAppView
+ id="tasks"
+ composableOnTouch
+ detailDesktopOnly
+ detailRequested={detailRequested}
+ detailFallback={<TasksLegacyRouteView />}
+ fallback={<LegacyTasksView />}
+ >
+ <TasksView />
+ </NewAppView>
+ );
+});
function LegacyChannelsView() {
const preset = getViewPreset('channels');
@@ -406,11 +511,39 @@ function LegacyChannelsView() {
/>
);
}
-export const ChannelsRouteView = withAuth(() => (
- <NewAppView id="channels" fallback={<LegacyChannelsView />}>
- <ChannelsView />
- </NewAppView>
-));
+function ChannelsLegacyRouteView() {
+ const params = useRouteParams(channelDetailRoute);
+ const [search] = createSearchParams(channelDetailSearch);
+ const legacyChannel = (id: string): SplitContent => {
+ const params: Record<string, string> = {};
+ if (search.messageId) params[CHANNEL_URL_PARAMS.message] = search.messageId;
+ if (search.threadId) params[CHANNEL_URL_PARAMS.thread] = search.threadId;
+ return { type: 'channel', id, params };
+ };
+
+ return (
+ <Show when={params.channelId} fallback={<LegacyChannelsView />}>
+ {(channelId) => <RedirectSplit to={legacyChannel(channelId())} />}
+ </Show>
+ );
+}
+
+export const ChannelsRouteView = withAuth(() => {
+ const params = useRouteParams(channelDetailRoute);
+ const detailRequested = () => typeof params.channelId === 'string';
+
+ return (
+ <NewAppView
+ id="channels"
+ detailDesktopOnly
+ detailRequested={detailRequested}
+ detailFallback={<ChannelsLegacyRouteView />}
+ fallback={<LegacyChannelsView />}
+ >
+ <ChannelsView />
+ </NewAppView>
+ );
+});
export const CallsView = withAuth(() => {
usePageViewTracking('calls');
@@ -485,3 +618,36 @@ export const SearchView = withAuth(
}
);
export const SettingsView = SettingsPanelComponentWrapper;
+
+const appRouteViews = {
+ home: HomeView,
+ 'getting-started': GettingStartedView,
+ inbox: InboxRouteView,
+ 'inbox-detail': InboxDetailRouteView,
+ recent: RecentView,
+ activity: ActivityView,
+ reminders: RemindersView,
+ agents: AgentsRouteView,
+ mail: MailView,
+ 'mail-detail': EmailDetailRouteView,
+ drive: DriveRouteView,
+ 'drive-detail': DriveDetailView,
+ tasks: TasksRouteView,
+ 'tasks-detail': TasksDetailRouteView,
+ channels: ChannelsRouteView,
+ 'channels-detail': ChannelDetailRouteView,
+ calls: CallsView,
+ companies: CompaniesView,
+ folders: FoldersView,
+ search: SearchView,
+ settings: SettingsView,
+} as const;
+
+export type AppRouteViewId = keyof typeof appRouteViews;
+
+/** Shared lazy boundary target for every application route component. */
+export function AppRouteRenderer(props: { view: AppRouteViewId }) {
+ const View = appRouteViews[props.view] as Component<Record<string, unknown>>;
+ const content = useSplitPanelOrThrow().handle.content();
+ return <View {...(content.type === 'component' ? content.params : {})} />;
+}
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
index 0f8acf377f..c519358fbb 100644
--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
@@ -3,10 +3,8 @@ import {
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 type { DriveDocumentRoute } from '@app/features/drive-view/primitives/drive-route';
+import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';
import {
defineRoute,
routeParams,
@@ -24,6 +22,7 @@ import {
} from '@app/lib/split-router/routes';
import { parseSearchState } from '@app/lib/split-router/search';
import { isRecord } from '@app/lib/split-router/utils';
+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import type { BlockAlias, BlockName } from '@core/block';
import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';
import { z } from 'zod';
@@ -177,7 +176,12 @@ export function driveSplitContent(
}
if (document) {
matches.push({
- id: driveDestination(location, document).route.id,
+ id:
+ location.kind === 'folder'
+ ? 'drive-folder-document'
+ : location.tab === 'owned'
+ ? 'drive-document'
+ : 'drive-tab-document',
params: { documentId: document.id, documentType: document.type },
});
}
@@ -304,6 +308,12 @@ export const legacySplitRoute = defineRoute({
path: ':type/:id',
search: '*',
params: z.object({ type: z.string().min(1), id: z.string().min(1) }),
+ externalSearch: (entry) => {
+ const { type } = routeParams(entry.location.route);
+ if (type === 'email') return Object.values(EMAIL_URL_PARAMS);
+ if (type === 'channel') return Object.values(CHANNEL_URL_PARAMS);
+ return [];
+ },
claim: ({ type, id }) => {
const content = decodeLegacyPair(type, id);
if (!content) return;
diff --git a/apps/web/src/components/app/split-layout/splitRouterLayout.ts b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
index 8fc9208797..b8f4ebecf4 100644
--- a/apps/web/src/components/app/split-layout/splitRouterLayout.ts
+++ b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
@@ -98,14 +98,16 @@ export function createAppSplitRouterLayout(
if (!handle) return;
- handle.updateCurrentEntry((content) => {
- const next = update({
- splitId,
- location: locationOf(content),
- });
-
- return contentForLocation(next.location, content);
- });
+ const current = locationOf(handle.content());
+ const next = update({ splitId, location: current });
+ // Child routes keep the workspace mounted but can dispose its list.
+ // Capture list focus/scroll before committing that accepted transition.
+ if (!deepEqual(current.route, next.location.route)) {
+ handle.captureEntryState();
+ }
+ handle.updateCurrentEntry((content) =>
+ contentForLocation(next.location, content)
+ );
},
open({ location, target, replace }) {
@@ -122,6 +124,16 @@ export function createAppSplitRouterLayout(
},
reconcile(entries) {
+ for (const [index, split] of manager.getVisibleSplits().entries()) {
+ if (
+ !deepEqual(
+ locationOf(split.content).route,
+ entries[index]?.location.route
+ )
+ ) {
+ manager.getSplit(split.id)?.captureEntryState();
+ }
+ }
const visible = manager.getVisibleSplits();
manager.reconcile(
entries.map((entry, index) =>
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 106b9d909e..d9a6a36138 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
@@ -40,14 +40,27 @@ vi.mock('@app/features/activity/open-entity-in-split', () => ({
}));
// Quarantine unrelated registered views and their module-load side effects.
+// Route/preview codecs otherwise pull the full block-definition graph into this test.
+vi.mock('../split-router/app-routes', () => ({}));
+vi.mock('@app/features/inbox-view/inbox-route', () => ({}));
vi.mock('@app/features/agents-view/views/AgentsView', () => ({}));
-vi.mock('@app/features/channels-view/channels-view', () => ({}));
+vi.mock('@app/features/channels-view/channels-view', () => ({
+ ChannelDetailRouteView: () => null,
+}));
vi.mock('@app/features/drive-view/drive-view', () => ({}));
+vi.mock('@app/features/drive-view/components/DriveDetailView', () => ({
+ DriveDetailView: () => null,
+}));
vi.mock('@app/features/email-compose/email-compose', () => ({}));
vi.mock('@app/features/email-view/email-view', () => ({}));
+vi.mock('@app/features/email-view/components/EmailDetailView', () => ({
+ EmailDetailRouteView: () => null,
+}));
vi.mock('@app/features/getting-started', () => ({}));
vi.mock('@app/features/home', () => ({}));
-vi.mock('@app/features/inbox-view/inbox-view', () => ({}));
+vi.mock('@app/features/inbox-view/inbox-view', () => ({
+ InboxDetailRouteView: () => null,
+}));
vi.mock('@app/features/next-soup/filters/filter-store', () => ({}));
vi.mock('@app/features/next-soup/filters/filter-store/query-store', () => ({}));
vi.mock('@app/features/next-soup/sidebar/soup-filter-presets', () => ({}));
@@ -57,7 +70,11 @@ vi.mock('@app/features/reminders/ReminderEditorSplit', () => ({}));
vi.mock('@app/features/settings/Settings', () => ({
SettingsPanelComponentWrapper: () => null,
}));
+vi.mock('@app/features/settings/McpConnections', () => ({}));
vi.mock('@app/features/tasks-view/tasks-view', () => ({}));
+vi.mock('@app/features/tasks-view/components/TasksDetailView', () => ({
+ TasksDetailRouteView: () => null,
+}));
vi.mock('@app/signal/splitLayout', () => ({}));
vi.mock('@block-calendar/components/EventComposerSplit', () => ({}));
vi.mock('@block-channel/component/Compose', () => ({}));
@@ -65,7 +82,9 @@ vi.mock('@block-md/component/ComposeSkill', () => ({}));
vi.mock('@block-md/component/ComposeTask', () => ({}));
vi.mock('@companies/crm/saved-views', () => ({}));
vi.mock('@core/context/user', () => ({}));
-vi.mock('@core/mobile/isTouchDevice', () => ({}));
+vi.mock('@core/mobile/isTouchDevice', () => ({
+ isTouchDevice: () => false,
+}));
vi.mock('@queries/agent-schedule/entities', () => ({}));
vi.mock('@ui', () => ({}));
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 694a00e1b3..42007ab02f 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,8 +1,5 @@
import { agentsRouteId } from '@app/features/agents-view/core/route';
-import {
- driveDestination,
- driveSplitRoute,
-} from '@app/features/drive-view/primitives/drive-route';
+import { driveDestination } from '@app/features/drive-view/drive-route-navigation';
import {
getListNavigationSource,
listNavigationSourceId,
@@ -27,6 +24,14 @@ import {
shouldShowSplitCloseButton,
} from '../layoutUtils';
import { createMobileSwipeLayout } from '../mobile/createMobileSwipeLayout';
+import { createAppSplitRouterMiddleware } from '../split-router/app-middleware';
+import {
+ appSplitRoutes,
+ driveSplitRoute,
+ emailSplitRoute,
+ emailThreadRoute,
+ taskDetailRoute,
+} from '../split-router/app-routes';
import { createAppSplitRouterLayout } from '../splitRouterLayout';
vi.mock('@core/component/Toast/Toast', () => ({
@@ -812,6 +817,363 @@ describe('layoutManager', () => {
});
describe('router layout synchronization', () => {
+ function ingressRouter(
+ url: string,
+ options: { enabled?: boolean; loading?: boolean; touch?: boolean } = {}
+ ) {
+ return createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'inbox' },
+ ]);
+ const routes = createRoutesManifest(appSplitRoutes);
+ const location = createMemorySplitRouterLocation(url);
+ const router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location,
+ middleware: createAppSplitRouterMiddleware({
+ newAppViews: () => ({
+ enabled: options.enabled ?? true,
+ loading: options.loading ?? false,
+ }),
+ isTouchDevice: () => options.touch ?? false,
+ }),
+ });
+ return { manager, location, router, dispose };
+ });
+ }
+
+ it.each([
+ ['md', 'md'],
+ ['pdf', 'pdf'],
+ ['canvas', 'canvas'],
+ ['task', 'md'],
+ ['snippet', 'md'],
+ ['skill', 'md'],
+ ['csv', 'code'],
+ ['code', 'code'],
+ ['image', 'image'],
+ ['video', 'video'],
+ ['spreadsheet', 'spreadsheet'],
+ ['unknown', 'unknown'],
+ ])(
+ 'preserves legacy %s blocks on touch, including canonical links',
+ async (type, blockType) => {
+ for (const path of [
+ `/${blockType}/doc`,
+ `/drive/${type}/doc`,
+ `/drive/shared/${type}/doc`,
+ `/drive/folder/folder/${type}/doc`,
+ ]) {
+ const { manager, location, router, dispose } = ingressRouter(path, {
+ touch: true,
+ });
+ await router.settled();
+ expect(location.read().pathname).toBe(`/${blockType}/doc`);
+ expect(manager.splits()[0].content).toMatchObject({
+ type: blockType,
+ id: 'doc',
+ });
+ expect(location.history()).toHaveLength(1);
+ router.dispose();
+ dispose();
+ }
+ }
+ );
+
+ it('keeps Drive list routes on touch', async () => {
+ const { location, router, dispose } = ingressRouter(
+ '/drive/~/drive/shared/~/drive/folder/folder',
+ { touch: true }
+ );
+ await router.settled();
+ expect(location.read().pathname).toBe(
+ '/drive/~/drive/shared/~/drive/folder/folder'
+ );
+ router.dispose();
+ dispose();
+ });
+
+ it('normalizes legacy search per detail pane without overriding canonical values', async () => {
+ const { manager, location, router, dispose } = ingressRouter(
+ '/mail/one/~/channels/channel/c1/~/mail/two/~/mail' +
+ '?email_message_id=legacy&channel_message_id=first&channel_message_id=last' +
+ '&channel_thread_id=thread&s0.email-detail.messageId=explicit' +
+ '&s0.email-detail.extra=keep&s2.email-detail.messageId=&referral_code=code#focus'
+ );
+ await router.settled();
+ const [firstMail, channel, secondMail, mailList] = manager.splits();
+ expect(router.search(firstMail.id, 'email-detail')).toEqual({
+ messageId: ['explicit'],
+ extra: ['keep'],
+ });
+ expect(router.search(channel.id, 'channel-detail')).toEqual({
+ messageId: ['first', 'last'],
+ threadId: ['thread'],
+ });
+ expect(router.search(secondMail.id, 'email-detail')).toEqual({
+ messageId: [''],
+ });
+ expect(router.search(mailList.id, 'email-detail')).toBeUndefined();
+ expect(
+ new URLSearchParams(location.read().search).get('referral_code')
+ ).toBe('code');
+ expect(location.read().hash).toBe('#focus');
+ expect(location.history()).toHaveLength(1);
+ router.dispose();
+ dispose();
+ });
+
+ it('normalizes every external URL and restores targets through browser history', async () => {
+ const { manager, location, router, dispose } = ingressRouter(
+ '/mail/one?email_message_id=first'
+ );
+ await router.settled();
+ const split = manager.splits()[0];
+ const mount = split.mount;
+ expect(router.search(split.id, 'email-detail')).toEqual({
+ messageId: ['first'],
+ });
+
+ location.set('/mail/one?email_message_id=second');
+ await router.settled();
+ expect(router.search(split.id, 'email-detail')).toEqual({
+ messageId: ['second'],
+ });
+ expect(location.history()).toHaveLength(2);
+ expect(manager.splits()[0].mount).toBe(mount);
+
+ expect(location.back()).toBe(true);
+ await router.settled();
+ expect(router.search(split.id, 'email-detail')).toEqual({
+ messageId: ['first'],
+ });
+ expect(location.forward()).toBe(true);
+ await router.settled();
+ expect(router.search(split.id, 'email-detail')).toEqual({
+ messageId: ['second'],
+ });
+ expect(location.history()).toHaveLength(2);
+ router.dispose();
+ dispose();
+ });
+
+ it.each([
+ { enabled: false, loading: false, touch: false },
+ { enabled: true, loading: true, touch: false },
+ { enabled: true, loading: false, touch: true },
+ ])(
+ 'preserves full-block legacy targets when inline detail is unsupported: %o',
+ async (options) => {
+ const { location, router, dispose } = ingressRouter(
+ '/email/one/~/channel/c1?email_message_id=message&channel_message_id=first' +
+ '&channel_message_id=last&channel_thread_id=thread',
+ options
+ );
+ await router.settled();
+ expect(location.read().pathname).toBe('/email/one/~/channel/c1');
+ const query = new URLSearchParams(location.read().search);
+ expect(query.getAll('email_message_id')).toEqual(['message']);
+ expect(query.getAll('channel_message_id')).toEqual(['first', 'last']);
+ expect(query.get('channel_thread_id')).toBe('thread');
+ expect(
+ [...query.keys()].some(
+ (key) => key.startsWith('s0.') || key.startsWith('s1.')
+ )
+ ).toBe(false);
+ router.dispose();
+ dispose();
+ }
+ );
+
+ it('upgrades renderable legacy details and preserves repeated raw target values', async () => {
+ let dispose!: () => void;
+ let router!: ReturnType<typeof createSplitRouter<string>>;
+ let location!: ReturnType<typeof createMemorySplitRouterLocation>;
+ createRoot((rootDispose) => {
+ dispose = rootDispose;
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'email', id: 'thread-1' },
+ ]);
+ const routes = createRoutesManifest(appSplitRoutes);
+ location = createMemorySplitRouterLocation(
+ '/email/thread-1?email_message_id=first&email_message_id=last'
+ );
+ router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location,
+ middleware: createAppSplitRouterMiddleware({
+ newAppViews: () => ({ enabled: true, loading: false }),
+ isTouchDevice: () => false,
+ }),
+ });
+ });
+
+ await router.settled();
+ expect(location.read().pathname).toBe('/mail/thread-1');
+ const query = new URLSearchParams(location.read().search);
+ expect(query.getAll('email_message_id')).toEqual(['first', 'last']);
+ expect(query.getAll('s0.email-detail.messageId')).toEqual([
+ 'first',
+ 'last',
+ ]);
+ expect(location.history()).toHaveLength(1);
+ dispose();
+ });
+
+ it.each([
+ { enabled: false, touch: false },
+ { enabled: true, touch: true },
+ { enabled: false, touch: true },
+ ])(
+ 'keeps legacy task detail when enabled=$enabled and touch=$touch',
+ async ({ enabled, touch }) => {
+ let dispose!: () => void;
+ let router!: ReturnType<typeof createSplitRouter<string>>;
+ let location!: ReturnType<typeof createMemorySplitRouterLocation>;
+ createRoot((rootDispose) => {
+ dispose = rootDispose;
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'task', id: 'task-1' },
+ ]);
+ const routes = createRoutesManifest(appSplitRoutes);
+ location = createMemorySplitRouterLocation('/task/task-1');
+ router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location,
+ middleware: createAppSplitRouterMiddleware({
+ newAppViews: () => ({ enabled, loading: false }),
+ isTouchDevice: () => touch,
+ }),
+ });
+ });
+
+ await router.settled();
+ expect(location.read().pathname).toBe('/task/task-1');
+ dispose();
+ }
+ );
+
+ it('keeps a migrated workspace mounted across typed detail history', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'mail' },
+ ]);
+ const routes = createRoutesManifest(appSplitRoutes);
+ const router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location: createMemorySplitRouterLocation('/mail'),
+ });
+ const split = manager.splits()[0]!;
+ const mount = split.mount;
+ const handle = manager.getSplit(split.id)!;
+ const stopCapture = handle.registerEntryStateCaptor(
+ 'email.listState',
+ () => ({
+ focusKey: 'one',
+ scrollOffset: 420,
+ })
+ );
+
+ router.navigate(split.id, {
+ route: emailThreadRoute,
+ params: { threadId: 'one' },
+ });
+ stopCapture(); // The list is disposed when its detail outlet takes over.
+ expect(handle.currentEntryState()).toMatchObject({
+ 'email.listState': { focusKey: 'one', scrollOffset: 420 },
+ });
+ router.navigate(split.id, {
+ route: emailThreadRoute,
+ params: { threadId: 'two' },
+ });
+
+ expect(manager.splits()[0]?.mount).toBe(mount);
+ expect(manager.splits()[0]?.content).toMatchObject({
+ type: 'component',
+ id: 'mail',
+ });
+ expect(router.route(split.id)?.matches.at(-1)?.params).toEqual({
+ threadId: 'two',
+ });
+
+ router.navigate(split.id, -1);
+ expect(router.route(split.id)?.matches.at(-1)?.params).toEqual({
+ threadId: 'one',
+ });
+ router.navigate(split.id, {
+ route: emailSplitRoute,
+ params: {},
+ });
+ expect(router.route(split.id)?.matches).toEqual([
+ { id: 'view-mail', params: {} },
+ ]);
+ expect(manager.splits()[0]?.mount).toBe(mount);
+ router.dispose();
+ dispose();
+ });
+ });
+
+ it('uses canonical detail claims across routed workspaces and legacy blocks', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'tasks' },
+ { type: 'md', id: 'task-1' },
+ ]);
+ const routes = createRoutesManifest(appSplitRoutes);
+ const router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location: createMemorySplitRouterLocation('/tasks/~/md/task-1'),
+ });
+ const [tasks, legacy] = manager.splits();
+ const accepted = router.route(tasks.id);
+
+ router.navigate(tasks.id, {
+ route: taskDetailRoute,
+ params: { taskId: 'task-1' },
+ });
+
+ expect(router.route(tasks.id)).toEqual(accepted);
+ expect(manager.activeSplitId()).toBe(legacy.id);
+ expect(manager.splits()).toHaveLength(2);
+ router.dispose();
+ dispose();
+ });
+ });
+
+ it('keeps duplicate list roots independent while reusing claimed email details', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'mail' },
+ { type: 'component', id: 'mail' },
+ ]);
+ const routes = createRoutesManifest(appSplitRoutes);
+ const router = createSplitRouter({
+ routes,
+ layout: createAppSplitRouterLayout(manager, routes),
+ location: createMemorySplitRouterLocation('/mail/one/~/mail'),
+ });
+ const [owner, other] = manager.splits();
+ const otherRoute = router.route(other.id);
+ manager.activateSplit(other.id);
+
+ router.navigate(other.id, {
+ route: emailThreadRoute,
+ params: { threadId: 'one' },
+ });
+
+ expect(router.route(other.id)).toEqual(otherRoute);
+ expect(manager.activeSplitId()).toBe(owner.id);
+ expect(manager.splits()).toHaveLength(2);
+ router.dispose();
+ dispose();
+ });
+ });
+
it.each(['drive', 'drive/md/second-document'])(
'navigates a second Drive pane independently from %s, including history',
(initialPath) => {
diff --git a/apps/web/src/features/channels-view/channels-route.ts b/apps/web/src/features/channels-view/channels-route.ts
new file mode 100644
index 0000000000..62365e83a6
--- /dev/null
+++ b/apps/web/src/features/channels-view/channels-route.ts
@@ -0,0 +1,16 @@
+import { createSearchParamsCodec } from '@app/lib/split-router';
+import { z } from 'zod';
+
+export const CHANNEL_DETAIL_SEARCH_NAMESPACE = 'channel-detail';
+
+export const channelDetailSearch = {
+ namespace: CHANNEL_DETAIL_SEARCH_NAMESPACE,
+ schema: z.object({
+ messageId: z.string(),
+ threadId: z.string(),
+ }),
+ defaults: { messageId: '', threadId: '' },
+};
+
+export const channelDetailSearchCodec =
+ createSearchParamsCodec(channelDetailSearch);
diff --git a/apps/web/src/features/channels-view/channels-view-context.test.tsx b/apps/web/src/features/channels-view/channels-view-context.test.tsx
index b6c43816af..2dc5630364 100644
--- a/apps/web/src/features/channels-view/channels-view-context.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view-context.test.tsx
@@ -1,3 +1,12 @@
+import {
+ SplitRouter,
+ type SplitRouterEntry,
+ type SplitRouterLayout,
+ type SplitRouterSettledChange,
+ useSplitRouter,
+} from '@app/lib/split-router';
+import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';
+import { appSplitRoutes } from '@components/app/split-layout/split-router/app-routes';
import { cleanup, render } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
@@ -14,19 +23,39 @@ const entry = vi.hoisted(() => ({
const touch = vi.hoisted(() => ({ value: false }));
const guard = vi.hoisted(() => ({
selections: [] as unknown[],
- reasons: [] as unknown[],
+ preflights: [] as unknown[],
allow: true,
}));
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'alice' }));
+vi.mock('@app/features/next-soup/utils', () => ({
+ getChannelEntityTarget: (channel: {
+ target?: { messageId: string; threadId?: string };
+ }) =>
+ channel.target
+ ? { kind: 'message', ...channel.target }
+ : { kind: 'latest' },
+}));
+vi.mock('@core/constant/allBlocks', () => ({
+ fileTypeToResolvedBlockName: (type: string) => type,
+ isBlockAlias: () => false,
+ resolveBlockAlias: (type: string) => type,
+}));
vi.mock('@core/mobile/isTouchDevice', () => ({
isTouchDevice: () => touch.value,
}));
vi.mock('@components/app/createPreviewSelectionGuard', () => ({
- createPreviewSelectionGuard: () => (selection: unknown, reason: unknown) => {
- guard.selections.push(selection);
- guard.reasons.push(reason);
- return selection === undefined || guard.allow;
+ createPreviewSelectionGuard: () => {
+ const select = (selection: unknown) => {
+ guard.selections.push(selection);
+ return selection === undefined || guard.allow;
+ };
+ return Object.assign(select, {
+ canSelect: (selection: unknown) => {
+ guard.preflights.push(selection);
+ return selection === undefined || guard.allow;
+ },
+ });
},
}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
@@ -41,18 +70,59 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
}),
}));
-function mountProvider(initialState?: ChannelsViewStateOptions) {
+function createLayout(): SplitRouterLayout<string> {
+ let current: (SplitRouterEntry & { splitId: string }) | undefined;
+ const listeners = new Set<(change: SplitRouterSettledChange) => void>();
+ const notify = () => {
+ for (const listener of listeners) listener({ history: 'push' });
+ };
+ return {
+ snapshot: () => ({ entries: current ? [current] : [] }),
+ updateCurrentEntry(_splitId, update) {
+ if (!current) return;
+ current = { splitId: current.splitId, ...update(current) };
+ notify();
+ },
+ open: () => {},
+ reconcile(entries) {
+ const next = entries[0];
+ current = next ? { splitId: 'split', ...next } : undefined;
+ notify();
+ },
+ activate: () => {},
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+}
+
+function mountProvider(
+ path = '/channels',
+ initialState?: ChannelsViewStateOptions
+) {
let context!: ChannelsViewContext;
+ let router!: ReturnType<typeof useSplitRouter<string>>;
+ const location = createMemorySplitRouterLocation(path);
function ReadContext() {
context = useChannelsView();
+ router = useSplitRouter<string>();
return null;
}
const view = render(() => (
- <ChannelsViewProvider initialState={initialState}>
- <ReadContext />
- </ChannelsViewProvider>
+ <SplitRouter.Root
+ layout={createLayout()}
+ routes={appSplitRoutes}
+ location={location}
+ >
+ <SplitRouter.Scope splitId="split">
+ <ChannelsViewProvider initialState={initialState}>
+ <ReadContext />
+ </ChannelsViewProvider>
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
));
- return { ...view, context };
+ return { ...view, context, location, router };
}
beforeEach(() => {
@@ -61,79 +131,15 @@ beforeEach(() => {
entry.captors.clear();
touch.value = false;
guard.selections = [];
- guard.reasons = [];
+ guard.preflights = [];
guard.allow = true;
});
afterEach(cleanup);
-describe('ChannelsViewProvider preview selection', () => {
- it.each(['entry', 'local', 'explicit'] as const)(
- 'preserves a conflicting %s selection through persistence and remount',
- (source) => {
- const saved = { selectedChannelId: 'c1' };
- const storageKey = 'macro:channels:view-state:v1:alice';
- if (source === 'entry') entry.state = { 'channels.view': saved };
- if (source === 'local') {
- localStorage.setItem(storageKey, JSON.stringify(saved));
- }
- guard.allow = false;
- const first = mountProvider(source === 'explicit' ? saved : undefined);
-
- expect(first.context.state.selectedChannelId).toBe('c1');
- expect(first.context.previewChannelId()).toBeUndefined();
- expect(guard.reasons.at(-1)).toBe('restore');
- // Unrelated preference writes must retain the blocked selection too.
- first.context.setGroupOpen('channels', false);
- expect(JSON.parse(localStorage.getItem(storageKey)!)).toMatchObject(
- saved
- );
- const captured = entry.captors.get('channels.view')?.();
- expect(captured).toMatchObject(saved);
- first.unmount();
-
- guard.allow = true;
- entry.state = source === 'local' ? {} : { 'channels.view': captured };
- const second = mountProvider();
- expect(second.context.state.selectedChannelId).toBe('c1');
- expect(second.context.previewChannelId()).toBe('c1');
- }
- );
-
- it('can retry a restored selection after the other view closes', () => {
- entry.state = { 'channels.view': { selectedChannelId: 'c1' } };
- guard.allow = false;
- const { context } = mountProvider();
-
- guard.allow = true;
- context.setSelectedChannelId('c1');
- expect(context.previewChannelId()).toBe('c1');
- expect(guard.reasons.at(-1)).toBe('navigate');
-
- guard.allow = false;
- context.setSelectedChannelId('c2');
- expect(context.state.selectedChannelId).toBe('c1');
- expect(context.previewChannelId()).toBe('c1');
-
- context.setSelectedChannelId(undefined);
- expect(context.state.selectedChannelId).toBeUndefined();
- expect(context.previewChannelId()).toBeUndefined();
- });
-
- it('claims the selected channel as an inline preview on desktop', () => {
- guard.allow = false;
- const { context } = mountProvider();
-
- context.setSelectedChannelId('c1');
-
- expect(guard.selections.at(-1)).toEqual({ type: 'channel', id: 'c1' });
- expect(context.state.selectedChannelId).toBeUndefined();
- expect(context.previewChannelId()).toBeUndefined();
- });
-
+describe('ChannelsViewProvider route selection', () => {
it('persists collapsed labels per user and restores them', () => {
const storageKey = 'macro:channels:view-state:v1:alice';
const first = mountProvider();
-
first.context.setLabelOpen('enterprise', false);
first.context.setLabelOpen('smb', false);
first.context.setLabelOpen('enterprise', false);
@@ -142,28 +148,101 @@ describe('ChannelsViewProvider preview selection', () => {
expect(first.context.state.collapsedLabels).toEqual(['enterprise']);
expect(JSON.parse(localStorage.getItem(storageKey)!)).toMatchObject({
collapsedLabels: ['enterprise'],
- expandedGroups: {
- favorites: true,
- channels: true,
- direct_messages: true,
- },
});
first.unmount();
-
const second = mountProvider();
expect(second.context.state.collapsedLabels).toEqual(['enterprise']);
});
+ it('derives accepted selection from a direct detail route', () => {
+ const { context } = mountProvider(
+ '/channels/channel/c1?s0.channel-detail.messageId=m1&s0.channel-detail.threadId=t1'
+ );
+
+ expect(context.selectedChannel()).toEqual({
+ type: 'channel',
+ id: 'c1',
+ target: { messageId: 'm1', threadId: 't1' },
+ });
+ expect(guard.selections.at(-1)).toEqual(context.selectedChannel());
+ });
- it('keeps touch selections out of the preview registry', () => {
- touch.value = true;
+ it('navigates with typed target search and closes explicitly to the list', async () => {
+ const { context, location, router } = mountProvider();
+
+ expect(
+ context.setSelectedChannel({
+ type: 'channel',
+ id: 'c1',
+ target: { messageId: 'm1', threadId: 't1' },
+ })
+ ).toBe(true);
+ await router.settled();
+ expect(location.read()).toMatchObject({
+ pathname: '/channels/channel/c1',
+ search: '?s0.channel-detail.messageId=m1&s0.channel-detail.threadId=t1',
+ });
+ expect(context.selectedChannel()?.id).toBe('c1');
+
+ expect(context.setSelectedChannel(undefined)).toBe(true);
+ await router.settled();
+ expect(location.read().pathname).toBe('/channels');
+ expect(context.selectedChannel()).toBeUndefined();
+ });
+
+ it('keeps the accepted route when compatibility preflight refuses a request', async () => {
+ const { context, location, router } = mountProvider(
+ '/channels/channel/current'
+ );
guard.allow = false;
- const { context } = mountProvider();
- context.setSelectedChannelId('c1');
+ expect(context.setSelectedChannel({ type: 'channel', id: 'blocked' })).toBe(
+ false
+ );
+ await router.settled();
+ expect(location.read().pathname).toBe('/channels/channel/current');
+ expect(context.selectedChannel()?.id).toBe('current');
+ });
+
+ it('replaces a directly loaded incompatible preview with the list route', async () => {
+ guard.allow = false;
+ const { context, location, router } = mountProvider(
+ '/channels/channel/blocked'
+ );
+ await router.settled();
+ expect(location.read().pathname).toBe('/channels');
+ expect(context.selectedChannel()).toBeUndefined();
+ });
+
+ it('does not route touch selections through the inline preview', async () => {
+ touch.value = true;
+ const { context, location, router } = mountProvider();
+
+ expect(context.setSelectedChannel({ type: 'channel', id: 'c1' })).toBe(
+ false
+ );
+ await router.settled();
expect(context.mobileLayout()).toBe(true);
- expect(guard.selections.at(-1)).toBeUndefined();
- expect(context.state.selectedChannelId).toBe('c1');
- expect(context.previewChannelId()).toBeUndefined();
+ expect(location.read().pathname).toBe('/channels');
+ expect(guard.preflights).toEqual([]);
+ });
+
+ it('does not restore the removed selected-id preference', () => {
+ const saved = {
+ selectedChannelId: 'stale',
+ expandedGroups: { channels: false },
+ };
+ entry.state = { 'channels.view': saved };
+ localStorage.setItem(
+ 'macro:channels:view-state:v1:alice',
+ JSON.stringify(saved)
+ );
+ const { context } = mountProvider();
+
+ expect(context.selectedChannel()).toBeUndefined();
+ expect(context.state.expandedGroups.channels).toBe(false);
+ expect(entry.captors.get('channels.view')?.()).not.toHaveProperty(
+ 'selectedChannelId'
+ );
});
});
diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsx
index 46fed56fc0..6b2c792703 100644
--- a/apps/web/src/features/channels-view/channels-view-context.tsx
+++ b/apps/web/src/features/channels-view/channels-view-context.tsx
@@ -1,13 +1,30 @@
-import type { NavigationStackChangeReason } from '@app/components/navigation-stack/NavigationStack';
+import {
+ type ChannelPreviewSelection,
+ getChannelEntityTarget,
+} from '@app/features/next-soup/utils';
import { makePersistedState } from '@app/lib/persistence';
+import {
+ createSearchParams,
+ useNavigate,
+ useRouteParams,
+} from '@app/lib/split-router';
import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import {
+ channelDetailRoute,
+ channelsSplitRoute,
+} from '@components/app/split-layout/split-router/app-routes';
import { createAssertedContextProvider } from '@core/context/createContext';
import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import type { ContextProviderProps } from '@solid-primitives/context';
-import { createSignal } from 'solid-js';
+import { type Accessor, createEffect, createMemo, on } from 'solid-js';
import { createStore, type Store } from 'solid-js/store';
+import {
+ CHANNEL_DETAIL_SEARCH_NAMESPACE,
+ channelDetailSearch,
+ channelDetailSearchCodec,
+} from './channels-route';
import {
CHANNELS_DEFAULT_RAIL_WIDTH,
CHANNELS_DEFAULT_SORT_BY,
@@ -30,13 +47,12 @@ type ChannelsViewProviderProps = ContextProviderProps & {
export type ChannelsViewContext = {
state: Store<ChannelsViewState>;
- /** The mobile list opens channels in the split; only desktop renders the inline preview. */
+ /** The mobile list opens channels in the split; only desktop renders detail. */
mobileLayout: () => boolean;
- /** Only admitted selections may render an inline preview. */
- previewChannelId: () => string | undefined;
+ selectedChannel: Accessor<ChannelPreviewSelection | undefined>;
setTab: (tab: ChannelsTab) => void;
setMobileTab: (tab: ChannelsQueryScope) => void;
- setSelectedChannelId: (channelId: string | undefined) => void;
+ setSelectedChannel: (channel: ChannelPreviewSelection | undefined) => boolean;
setGroupOpen: (group: ChannelsRailSection, open: boolean) => void;
/** Per-user collapse state of a team channel label. */
setLabelOpen: (labelId: string, open: boolean) => void;
@@ -51,7 +67,6 @@ function createInitialState(
tab: initial.tab ?? 'browse',
mobileTab:
initial.mobileTab ?? (initial.tab === 'recents' ? 'recents' : 'channels'),
- selectedChannelId: initial.selectedChannelId,
expandedGroups: {
favorites: initial.expandedGroups?.favorites ?? true,
channels: initial.expandedGroups?.channels ?? true,
@@ -80,6 +95,10 @@ export const [ChannelsViewProvider, useChannelsView] =
(props) => {
const panel = useSplitPanelOrThrow();
const userId = useUserId();
+ const navigate = useNavigate();
+ const params = useRouteParams(channelDetailRoute);
+ const [detailSearch] = createSearchParams(channelDetailSearch);
+ const selectPreview = createPreviewSelectionGuard();
const initial = props.initialState ?? {};
const [state, setState] = makePersistedState(
createStore(createInitialState(initial)),
@@ -93,31 +112,81 @@ export const [ChannelsViewProvider, useChannelsView] =
);
const mobileLayout = () => isTouchDevice();
- const selectPreview = createPreviewSelectionGuard();
- const [previewChannelId, setPreviewChannelId] = createSignal<string>();
- const setSelectedChannelId = (
- id: string | undefined,
- reason: NavigationStackChangeReason = 'navigate'
+ const selectedChannel = createMemo<ChannelPreviewSelection | undefined>(
+ () => {
+ const channelId = params.channelId;
+ if (typeof channelId !== 'string') return undefined;
+ const target = detailSearch.messageId
+ ? {
+ messageId: detailSearch.messageId,
+ ...(detailSearch.threadId
+ ? { threadId: detailSearch.threadId }
+ : {}),
+ }
+ : undefined;
+ return {
+ type: 'channel',
+ id: channelId,
+ ...(target ? { target } : {}),
+ };
+ }
+ );
+ const routeSearch = (channel: ChannelPreviewSelection) => {
+ const target = getChannelEntityTarget(channel);
+ const value = {
+ messageId: target?.kind === 'message' ? target.messageId : '',
+ threadId: target?.kind === 'message' ? (target.threadId ?? '') : '',
+ };
+ return channelDetailSearchCodec.serialize(value);
+ };
+ const navigateToChannel = (
+ channel: ChannelPreviewSelection,
+ replace = false
+ ) => {
+ const channelId =
+ channel.type === 'channel' ? channel.id : channel.channelId;
+ navigate(
+ { route: channelDetailRoute, params: { channelId } },
+ {
+ replace,
+ search: {
+ [CHANNEL_DETAIL_SEARCH_NAMESPACE]: routeSearch(channel),
+ },
+ }
+ );
+ };
+ const setSelectedChannel = (
+ channel: ChannelPreviewSelection | undefined
) => {
- // The mobile layout keeps the selection for row highlighting only, so
- // there is no preview to claim.
- const preview =
- id && !mobileLayout() ? { type: 'channel' as const, id } : undefined;
- if (!selectPreview(preview, reason)) return;
- setPreviewChannelId(preview?.id);
- setState('selectedChannelId', id);
+ if (!channel) {
+ navigate({ route: channelsSplitRoute, params: {} });
+ return true;
+ }
+ if (mobileLayout() || !selectPreview.canSelect(channel)) return false;
+ navigateToChannel(channel);
+ return true;
};
- // Keep restored selection in persistence even if another view currently
- // owns its preview. It can be retried on selection or the next mount.
- setSelectedChannelId(state.selectedChannelId, 'restore');
+
+ createEffect(
+ on(selectedChannel, (channel, previous) => {
+ if (!selectPreview(channel)) {
+ if (previous) navigateToChannel(previous, true);
+ else
+ navigate(
+ { route: channelsSplitRoute, params: {} },
+ { replace: true }
+ );
+ }
+ })
+ );
return {
state,
mobileLayout,
- previewChannelId,
+ selectedChannel,
setTab: (tab) => setState('tab', tab),
setMobileTab: (tab) => setState('mobileTab', tab),
- setSelectedChannelId,
+ setSelectedChannel,
setGroupOpen: (group, open) => setState('expandedGroups', group, open),
setLabelOpen: (labelId, open) =>
setState('collapsedLabels', (collapsed) =>
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsx
index ff2d2167de..b99a338230 100644
--- a/apps/web/src/features/channels-view/channels-view.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view.test.tsx
@@ -7,7 +7,7 @@ import {
screen,
waitFor,
} from '@solidjs/testing-library';
-import { batch, createSignal, type JSX } from 'solid-js';
+import { batch, createSignal, type JSX, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -21,6 +21,15 @@ const mocks = vi.hoisted(() => ({
refresh: vi.fn(async () => {}),
}));
+vi.mock('@app/lib/split-router', () => ({
+ SplitRouter: {
+ Outlet: (props: { fallback: () => JSX.Element }) => (
+ <Show when={mocks.selectedId()} fallback={props.fallback()}>
+ <ChannelDetailRouteView />
+ </Show>
+ ),
+ },
+}));
vi.mock('@app/components/view-shell', () => ({
ViewShell: {
Root: mocks.pass,
@@ -78,7 +87,10 @@ vi.mock('./channels-view-context', () => ({
sortBy: { channels: 'updated_at', direct_messages: 'updated_at' },
},
mobileLayout: () => false,
- previewChannelId: () => mocks.selectedId(),
+ selectedChannel: () =>
+ mocks.selectedId()
+ ? { type: 'channel', id: mocks.selectedId() }
+ : undefined,
setAsideWidth: vi.fn(),
setMobileTab: vi.fn(),
}),
@@ -103,7 +115,7 @@ vi.mock('./queries', () => ({
}),
}));
-import { ChannelsView } from './channels-view';
+import { ChannelDetailRouteView, ChannelsView } from './channels-view';
const row = (id: string, unreadId?: string): ChannelEntity => ({
id,
diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsx
index 348ac79036..1b03b53385 100644
--- a/apps/web/src/features/channels-view/channels-view.tsx
+++ b/apps/web/src/features/channels-view/channels-view.tsx
@@ -2,6 +2,7 @@ import { ViewShell } from '@app/components/view-shell';
import { markChannelNotificationsSeenOnOpen } from '@app/features/next-soup/utils';
import { MaybeSoupEntityActionDrawerManager } from '@app/features/soup';
import { withEntityNotifications } from '@app/features/soup/entity-notifications';
+import { SplitRouter } from '@app/lib/split-router';
import {
useGlobalBlockOrchestrator,
useGlobalNotificationSource,
@@ -13,6 +14,7 @@ import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component
import { ListEntityMetadataQueryProvider } from '@entity';
import SpinnerIcon from '@phosphor/spinner.svg';
import {
+ createContext,
createEffect,
createMemo,
createSignal,
@@ -20,6 +22,7 @@ import {
onMount,
Show,
Suspense,
+ useContext,
} from 'solid-js';
import { ChannelsViewProvider, useChannelsView } from './channels-view-context';
import { ChannelsMobileView } from './components/ChannelsMobileView';
@@ -30,6 +33,10 @@ import {
useChannelByIdQuery,
useChannelsSources,
} from './queries';
+
+const ChannelSourcesContext =
+ createContext<ReturnType<typeof useChannelsSources>>();
+
import type { ChannelsViewStateOptions } from './types';
export type ChannelsViewProps = {
@@ -39,9 +46,7 @@ export type ChannelsViewProps = {
function ChannelsViewRoot() {
const panel = useSplitPanelOrThrow();
- const orchestrator = useGlobalBlockOrchestrator();
- const notificationSource = useGlobalNotificationSource();
- const { state, mobileLayout, previewChannelId, setAsideWidth, setMobileTab } =
+ const { state, mobileLayout, setAsideWidth, setMobileTab } =
useChannelsView();
const [railSearchOpen, setRailSearchOpen] = createSignal(false);
@@ -56,91 +61,6 @@ function ChannelsViewRoot() {
},
(group) => state.sortBy[group]
);
- const loadedChannels = createMemo(() =>
- deduplicateChannels([
- sources.channels.items(),
- sources.direct_messages.items(),
- sources.recents.items(),
- sources.search.items(),
- ])
- );
- const loadedSelectedChannel = createMemo(() =>
- resolveSelectedChannel(previewChannelId(), loadedChannels())
- );
- // Only a new selection may request a full edge. Incoming unread updates must
- // not blank/remount an already-open conversation or steal composer focus.
- const selectionNeedsFullEdge = createMemo(
- on(previewChannelId, () => {
- const loaded = loadedSelectedChannel();
- return (
- loaded === undefined || (loaded.unreadNotifications?.length ?? 0) > 0
- );
- })
- );
- const selectedChannelQuery = useChannelByIdQuery(
- previewChannelId,
- () =>
- !mobileLayout() &&
- previewChannelId() !== undefined &&
- (selectionNeedsFullEdge() || loadedSelectedChannel() === undefined)
- );
- const selectedChannel = createMemo(
- (previous: ReturnType<typeof loadedSelectedChannel> | undefined) => {
- const loaded = loadedSelectedChannel();
- if (loaded && !selectionNeedsFullEdge()) {
- return loaded.unreadNotifications === undefined
- ? loaded
- : { ...loaded, notifications: () => [] };
- }
- if (
- !selectedChannelQuery.isEnabled ||
- selectedChannelQuery.isLoading ||
- selectedChannelQuery.isFetching ||
- selectedChannelQuery.error
- ) {
- return previous?.id === previewChannelId() ? previous : undefined;
- }
-
- const full = resolveSelectedChannel(
- previewChannelId(),
- [],
- selectedChannelQuery.data?.entities
- );
- return full
- ? withEntityNotifications(full, notificationSource)
- : undefined;
- }
- );
-
- const selectionUnavailable = () =>
- previewChannelId() !== undefined &&
- (Boolean(selectedChannelQuery.error) ||
- (selectedChannelQuery.isEnabled &&
- !selectedChannelQuery.isLoading &&
- !selectedChannelQuery.isFetching &&
- selectedChannel() === undefined));
-
- // Stabilize the identity: metadata updates must not repeat the selection action.
- const readySelectionId = createMemo(() => selectedChannel()?.id);
-
- // The bounded unread witness is never passed to a bulk mark-read operation.
- // Send the complete, thread-scoped selection once the chosen preview is ready.
- createEffect(
- on(readySelectionId, () => {
- const channel = selectedChannel();
- if (channel && channel.isParticipant !== false)
- markChannelNotificationsSeenOnOpen(channel, notificationSource);
- })
- );
-
- const retrySelection = async () => {
- try {
- await selectedChannelQuery.refresh();
- } catch {
- // The query's inline error remains visible so another retry is possible.
- }
- };
-
onMount(() => panel.handle.setDisplayName('Channels'));
return (
@@ -169,52 +89,28 @@ function ChannelsViewRoot() {
/>
</ViewShell.Aside>
<ViewShell.Main class="overflow-hidden">
- <Show
- when={selectedChannel()}
- fallback={
- <>
- <ViewShell.TopBar>
- <span class="text-sm font-semibold">Chat</span>
- </ViewShell.TopBar>
- <div class="flex min-h-0 flex-1 items-center justify-center px-6 text-center">
- <div class="flex max-w-sm flex-col gap-2">
- <h2 class="text-base font-semibold text-ink">
- {selectionUnavailable()
- ? 'Conversation unavailable'
- : previewChannelId()
- ? 'Loading conversation'
- : 'Select a conversation'}
- </h2>
- <p class="text-sm leading-5 text-ink-muted">
- {selectionUnavailable()
- ? 'Could not load this conversation.'
- : previewChannelId()
- ? 'Preparing the conversation…'
- : 'Choose a channel or person from the sidebar to open the conversation here.'}
- </p>
- <Show when={selectionUnavailable()}>
- <button
- type="button"
- onClick={retrySelection}
- >
- Retry
- </button>
- </Show>
+ <ChannelSourcesContext.Provider value={sources}>
+ <SplitRouter.Outlet
+ fallback={() => (
+ <>
+ <ViewShell.TopBar>
+ <span class="text-sm font-semibold">Chat</span>
+ </ViewShell.TopBar>
+ <div class="flex min-h-0 flex-1 items-center justify-center px-6 text-center">
+ <div class="flex max-w-sm flex-col gap-2">
+ <h2 class="text-base font-semibold text-ink">
+ Select a conversation
+ </h2>
+ <p class="text-sm leading-5 text-ink-muted">
+ Choose a channel or person from the sidebar
+ to open the conversation here.
+ </p>
+ </div>
</div>
- </div>
- </>
- }
- >
- {(channel) => (
- <Suspense>
- <PreviewPanel
- selectedEntity={channel()}
- orchestrator={orchestrator}
- splitPanelContext={panel}
- />
- </Suspense>
- )}
- </Show>
+ </>
+ )}
+ />
+ </ChannelSourcesContext.Provider>
</ViewShell.Main>
</ViewShell.Root>
</div>
@@ -246,6 +142,110 @@ function ChannelsViewRoot() {
);
}
+export function ChannelDetailRouteView() {
+ const panel = useSplitPanelOrThrow();
+ const orchestrator = useGlobalBlockOrchestrator();
+ const { selectedChannel } = useChannelsView();
+ const notificationSource = useGlobalNotificationSource();
+ const channelId = () => selectedChannel()?.id;
+ const sources = useContext(ChannelSourcesContext);
+ const loaded = createMemo(() =>
+ resolveSelectedChannel(
+ channelId(),
+ sources
+ ? deduplicateChannels([
+ sources.channels.items(),
+ sources.direct_messages.items(),
+ sources.recents.items(),
+ sources.search.items(),
+ ])
+ : []
+ )
+ );
+ const needsFullEdge = createMemo(
+ on(
+ channelId,
+ () =>
+ loaded() === undefined ||
+ (loaded()?.unreadNotifications?.length ?? 0) > 0
+ )
+ );
+ const query = useChannelByIdQuery(
+ channelId,
+ () =>
+ channelId() !== undefined && (needsFullEdge() || loaded() === undefined)
+ );
+ const hydrated = createMemo((previous: ReturnType<typeof loaded>) => {
+ const selection = selectedChannel();
+ if (!selection || selection.type !== 'channel') return;
+ const cached = loaded();
+ if (cached && !needsFullEdge())
+ return { ...cached, target: selection.target, notifications: () => [] };
+ if (
+ !query.isEnabled ||
+ query.isLoading ||
+ query.isFetching ||
+ query.error
+ ) {
+ return previous?.id === selection.id ? previous : undefined;
+ }
+ const full = resolveSelectedChannel(selection.id, [], query.data?.entities);
+ if (!full) return;
+ return withEntityNotifications(
+ { ...full, target: selection.target },
+ notificationSource
+ );
+ });
+ const unavailable = () =>
+ Boolean(query.error) ||
+ (query.isEnabled && !query.isLoading && !query.isFetching && !hydrated());
+ const retry = async () => {
+ try {
+ await query.refresh();
+ } catch {
+ /* Query state presents the failure. */
+ }
+ };
+ const readyId = createMemo(() => hydrated()?.id);
+ createEffect(
+ on(readyId, () => {
+ const channel = hydrated();
+ if (channel && channel.isParticipant !== false)
+ markChannelNotificationsSeenOnOpen(channel, notificationSource);
+ })
+ );
+
+ return (
+ <Suspense>
+ <Show
+ when={hydrated()}
+ fallback={
+ <div class="flex size-full flex-col items-center justify-center gap-2 text-ink-muted">
+ <h2>
+ {unavailable()
+ ? 'Conversation unavailable'
+ : 'Loading conversation'}
+ </h2>
+ <Show when={unavailable()}>
+ <button type="button" onClick={retry}>
+ Retry
+ </button>
+ </Show>
+ </div>
+ }
+ >
+ {(channel) => (
+ <PreviewPanel
+ selectedEntity={channel()}
+ orchestrator={orchestrator}
+ splitPanelContext={panel}
+ />
+ )}
+ </Show>
+ </Suspense>
+ );
+}
+
/** Chat workspace with shared workspace navigation. */
export function ChannelsView(props: ChannelsViewProps) {
return (
diff --git a/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx b/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx
index 9e323f0652..d9f4cea4e5 100644
--- a/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx
+++ b/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx
@@ -26,7 +26,6 @@ import {
Switch,
} from 'solid-js';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
-import { useChannelsView } from '../channels-view-context';
import type { ChannelsDataSource } from '../queries';
import type { ChannelsQueryScope } from '../types';
import { channelMentionsUser } from '../utils';
@@ -58,7 +57,6 @@ export function ChannelsMobileView(props: {
const panel = useSplitPanelOrThrow();
const notificationSource = useGlobalNotificationSource();
const currentUserId = useUserId();
- const { state, setSelectedChannelId } = useChannelsView();
const [viewport, setViewport] = createSignal<HTMLDivElement>();
const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();
const [topSpacer, setTopSpacer] = createSignal<HTMLDivElement>();
@@ -116,7 +114,6 @@ export function ChannelsMobileView(props: {
});
const openChannel = async (channel: ChannelEntity) => {
const request = ++opening;
- setSelectedChannelId(channel.id);
try {
const full = await hydrateChannelNotificationSelection(
channel,
@@ -247,7 +244,7 @@ export function ChannelsMobileView(props: {
incomingCallId={channelActivity
.incomingCallIds()
.get(channel.id)}
- selected={state.selectedChannelId === channel.id}
+ selected={false}
focused={false}
onActivate={() => openChannel(channel)}
/>
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
index 7b9267c991..a18b31a33d 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
@@ -9,6 +9,7 @@ import {
useViewTabHotkeys,
} from '@app/components/view-shell';
import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';
+import type { ChannelPreviewSelection } from '@app/features/next-soup/utils';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { favoriteSplitContent } from '@app/util/favorites';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
@@ -123,7 +124,8 @@ export function ChannelsRail(props: ChannelsRailProps) {
state,
setGroupOpen,
setLabelOpen,
- setSelectedChannelId,
+ selectedChannel,
+ setSelectedChannel,
setSortBy,
setTab,
} = useChannelsView();
@@ -155,7 +157,10 @@ export function ChannelsRail(props: ChannelsRailProps) {
let searchInput: HTMLInputElement | undefined;
- const previewAfterNavigation = debounce(setSelectedChannelId, 150);
+ const previewAfterNavigation = debounce(
+ (channel: ChannelPreviewSelection) => setSelectedChannel(channel),
+ 150
+ );
onCleanup(() => previewAfterNavigation.clear());
const closeSearch = () => {
@@ -360,19 +365,17 @@ export function ChannelsRail(props: ChannelsRailProps) {
);
});
+ const initialSelectedChannelId = selectedChannel()?.id;
const list = withSplitPanelOwner(listOwnedSlotName('controller'), () =>
createListController<ChannelRailRow, ChannelRailActivationMetadata>({
items: visibleRows,
getKey: (row) => row.id,
isSelectable: () => false,
- initialFocusKey:
- state.selectedChannelId === undefined
- ? undefined
- : visibleRows().find(
- (row) =>
- row.kind === 'conversation' &&
- row.channel.id === state.selectedChannelId
- )?.id,
+ initialFocusKey: visibleRows().find(
+ (row) =>
+ row.kind === 'conversation' &&
+ row.channel.id === initialSelectedChannelId
+ )?.id,
onActivate: ({ item, metadata }) => {
previewAfterNavigation.clear();
const openInNewSplit =
@@ -410,7 +413,11 @@ export function ChannelsRail(props: ChannelsRailProps) {
return;
}
- setSelectedChannelId(channelId);
+ setSelectedChannel(
+ item.kind === 'conversation'
+ ? item.channel
+ : { type: 'channel', id: channelId }
+ );
},
})
);
@@ -461,7 +468,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
)
: props.sources[scope].items().map((channel) => channel.id);
- const selectedIndex = rendered.indexOf(state.selectedChannelId ?? '');
+ const selectedIndex = rendered.indexOf(selectedChannel()?.id ?? '');
const targetIndex = selectedIndex >= 0 ? selectedIndex : 0;
const virtualizer = virtualizers()[scope];
@@ -482,7 +489,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
const items = searchResults();
const selectedIndex = items.findIndex(
- (channel) => channel.id === state.selectedChannelId
+ (channel) => channel.id === selectedChannel()?.id
);
const virtualizer = virtualizers().search;
@@ -501,8 +508,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
const favorite = favorites().find(
(item) =>
- item.entityType === 'channel' &&
- item.entityId === state.selectedChannelId
+ item.entityType === 'channel' && item.entityId === selectedChannel()?.id
);
if (!favorite) return;
@@ -627,12 +633,15 @@ export function ChannelsRail(props: ChannelsRailProps) {
const row = event.result?.item;
if (row?.kind === 'conversation') {
- previewAfterNavigation(row.channel.id);
+ previewAfterNavigation(row.channel);
} else if (
row?.kind === 'favorite' &&
row.favorite.entityType === 'channel'
) {
- previewAfterNavigation(row.favorite.entityId);
+ previewAfterNavigation({
+ type: 'channel',
+ id: row.favorite.entityId,
+ });
}
},
},
@@ -1032,7 +1041,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
selectTab,
sources: props.sources,
favorites,
- selectedChannelId: () => state.selectedChannelId,
+ selectedChannel,
isGroupOpen: (group) => state.expandedGroups[group],
toggleGroup: (group) => setGroupOpen(group, !state.expandedGroups[group]),
channelTagsEnabled,
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts
index 5caa2ec53d..644a901deb 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts
@@ -1,4 +1,5 @@
import type { ListController } from '@app/components/list';
+import type { ChannelPreviewSelection } from '@app/features/next-soup/utils';
import { createAssertedContextProvider } from '@core/context/createContext';
import type { ChannelEntity } from '@entity';
import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
@@ -115,7 +116,7 @@ export type ChannelsRailContext = {
selectTab: (tab: ChannelsTab) => void;
sources: ChannelsSources;
favorites: Accessor<readonly Favorite[]>;
- selectedChannelId: Accessor<string | undefined>;
+ selectedChannel: Accessor<ChannelPreviewSelection | undefined>;
isGroupOpen: (group: ChannelsRailSection) => boolean;
toggleGroup: (group: ChannelsRailSection) => void;
/** Whether channel labels and smart tags are enabled for this user. */
diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts
index bbefae67ff..60fe65c349 100644
--- a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts
+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts
@@ -32,7 +32,7 @@ export function useChannelRailItemState(
return {
domId: domIdForRow(rail.railId, rowId),
- selected: rail.selectedChannelId() === id,
+ selected: rail.selectedChannel()?.id === id,
focused: rail.list.focus.key() === rowId,
muted: isMutedItem(notificationSource.mutedEntities(), {
item_id: id,
@@ -56,7 +56,7 @@ export function useChannelRailFavoriteItemState(favorite: Accessor<Favorite>) {
domId: domIdForRow(rail.railId, rowId),
selected:
current.entityType === 'channel' &&
- rail.selectedChannelId() === current.entityId,
+ rail.selectedChannel()?.id === current.entityId,
focused: rail.list.focus.key() === rowId,
};
});
diff --git a/apps/web/src/features/channels-view/persistence.ts b/apps/web/src/features/channels-view/persistence.ts
index 91d933e807..6cca5c1bad 100644
--- a/apps/web/src/features/channels-view/persistence.ts
+++ b/apps/web/src/features/channels-view/persistence.ts
@@ -49,7 +49,6 @@ const channelsEntryStateSchemaWithDefaults = z.object({
mobileTab: z
.enum(['channels', 'direct_messages', 'recents'])
.default('channels'),
- selectedChannelId: z.string().optional(),
expandedGroups: channelsExpandedGroupsSchema.default({
favorites: true,
channels: true,
@@ -64,7 +63,6 @@ const DEFAULT_CHANNELS_ENTRY_STATE = {
version: 1,
tab: 'browse',
mobileTab: 'channels',
- selectedChannelId: undefined,
expandedGroups: {
favorites: true,
channels: true,
@@ -105,9 +103,6 @@ function selectEntryState(state: ChannelsViewState): ChannelsEntryState {
version: 1,
tab: state.tab,
mobileTab: state.mobileTab,
- ...(state.selectedChannelId === undefined
- ? {}
- : { selectedChannelId: state.selectedChannelId }),
expandedGroups: state.expandedGroups,
collapsedLabels: state.collapsedLabels,
};
@@ -124,7 +119,6 @@ function restoreChannelsEntryState(
...current,
tab: restored.tab,
mobileTab: restored.mobileTab,
- selectedChannelId: restored.selectedChannelId,
expandedGroups: restored.expandedGroups,
collapsedLabels: restored.collapsedLabels,
};
diff --git a/apps/web/src/features/channels-view/types.ts b/apps/web/src/features/channels-view/types.ts
index d84175bd6b..7903eb4c06 100644
--- a/apps/web/src/features/channels-view/types.ts
+++ b/apps/web/src/features/channels-view/types.ts
@@ -12,7 +12,6 @@ export type ChannelsQueryScope = ChannelsGroup | 'recents';
export type ChannelsViewState = {
tab: ChannelsTab;
mobileTab: ChannelsQueryScope;
- selectedChannelId?: string;
expandedGroups: Record<ChannelsRailSection, boolean>;
/**
* Channel labels this user has collapsed. Labels themselves are team data;
diff --git a/apps/web/src/features/drive-view/drive-detail-navigation.tsx b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
index c993297652..b115d73aa4 100644
--- a/apps/web/src/features/drive-view/drive-detail-navigation.tsx
+++ b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
@@ -22,10 +22,10 @@ import {
useContext,
} from 'solid-js';
import type { DriveLocation } from './core/types';
+import { driveDestination } from './drive-route-navigation';
import {
type DriveDocumentRoute,
type DriveRouteParams,
- driveDestination,
driveDocumentFromParams,
driveDocumentRoute,
} from './primitives/drive-route';
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 7cd80f1fdf..b4d8dc4063 100644
--- a/apps/web/src/features/drive-view/drive-location-menu.tsx
+++ b/apps/web/src/features/drive-view/drive-location-menu.tsx
@@ -6,7 +6,7 @@ import { batch, type ParentProps, Show } from 'solid-js';
import { useDriveView } from './context/drive-context';
import type { DriveLocation } from './core/types';
import { DriveFolderActions } from './drive-folder-actions';
-import { driveDestination } from './primitives/drive-route';
+import { driveDestination } from './drive-route-navigation';
/** App-specific split/menu wiring shared by Drive's sidebar locations. */
export function DriveLocationMenu(
diff --git a/apps/web/src/features/drive-view/drive-route-navigation.ts b/apps/web/src/features/drive-view/drive-route-navigation.ts
new file mode 100644
index 0000000000..660d5bdff2
--- /dev/null
+++ b/apps/web/src/features/drive-view/drive-route-navigation.ts
@@ -0,0 +1,41 @@
+import {
+ driveFolderDocumentRoute,
+ driveFolderRoute,
+ driveRootDocumentRoute,
+ driveSplitRoute,
+ driveTabDocumentRoute,
+ driveTabRoute,
+} from '@components/app/split-layout/split-router/app-routes';
+import { match } from 'ts-pattern';
+import type { DriveLocation } from './core/types';
+import type { DriveDocumentRoute } from './primitives/drive-route';
+
+/** Maps Drive domain selection to a route, including its folder/tab params. */
+export function driveDestination(
+ location: DriveLocation,
+ document?: DriveDocumentRoute
+) {
+ const list = match(location)
+ .with({ kind: 'folder' }, ({ id }) => ({
+ route: driveFolderRoute,
+ params: { view: 'folder' as const, folderId: id ?? undefined },
+ }))
+ .with({ kind: 'tab', tab: 'owned' }, () => ({
+ route: driveSplitRoute,
+ params: {},
+ }))
+ .otherwise(({ tab }) => ({ route: driveTabRoute, params: { tab } }));
+ if (!document) return list;
+
+ return {
+ route: match(location)
+ .with({ kind: 'folder' }, () => driveFolderDocumentRoute)
+ .with({ kind: 'tab', tab: 'owned' }, () => driveRootDocumentRoute)
+ .otherwise(() => driveTabDocumentRoute),
+ params: {
+ ...list.params,
+ documentId: document.id,
+ documentType: document.type,
+ },
+ };
+}
diff --git a/apps/web/src/features/drive-view/primitives/drive-route-schema.ts b/apps/web/src/features/drive-view/primitives/drive-route-schema.ts
new file mode 100644
index 0000000000..749bcfb3a0
--- /dev/null
+++ b/apps/web/src/features/drive-view/primitives/drive-route-schema.ts
@@ -0,0 +1,21 @@
+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 function driveDocumentBlockType(type: string) {
+ if (type === 'task' || type === 'snippet' || type === 'skill') return 'md';
+ return type === 'csv' ? 'code' : type;
+}
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
index 683549ebd3..e86d885db1 100644
--- a/apps/web/src/features/drive-view/primitives/drive-route-state.ts
+++ b/apps/web/src/features/drive-view/primitives/drive-route-state.ts
@@ -21,10 +21,10 @@ import {
type Setter,
} from 'solid-js';
import type { DriveLocation, DriveState } from '../core/types';
+import { driveDestination } from '../drive-route-navigation';
import {
type DriveRouteParams,
type DriveSearchParams,
- driveDestination,
driveLocationFromParams,
driveSearch,
} from './drive-route';
diff --git a/apps/web/src/features/drive-view/primitives/drive-route.ts b/apps/web/src/features/drive-view/primitives/drive-route.ts
index dc4584d81e..bee086cba7 100644
--- a/apps/web/src/features/drive-view/primitives/drive-route.ts
+++ b/apps/web/src/features/drive-view/primitives/drive-route.ts
@@ -2,41 +2,21 @@ import {
deserializeFacetSelection,
normalizeFacetSelection,
} from '@app/features/soup/filters/facets/selection';
-import {
- defineRoute,
- defineRoutes,
- routeParams,
-} from '@app/lib/split-router/routes';
import {
type CreateSearchParamsOptions,
isSafeName,
type SerializedSearchParams,
- type SplitRouteNavigationTarget,
type SplitRouteParams,
- type SplitRouterEntry,
- type SplitRouteUnion,
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';
+import {
+ DRIVE_DOCUMENT_TYPES,
+ type DriveDocumentType,
+ driveDocumentBlockType,
+} from './drive-route-schema';
-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;
@@ -46,77 +26,7 @@ export type DriveRouteParams = SplitRouteParams & {
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],
-});
-
-const driveRoutes = defineRoutes({
- definitions: [
- 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 const driveSplitRoute = driveRoutes.definitions[0];
export function driveLocationFromParams(
params: DriveRouteParams
@@ -133,40 +43,6 @@ export function driveDocumentFromParams(
return { id: params.documentId, type: params.documentType };
}
-type DriveDestination = SplitRouteNavigationTarget<
- SplitRouteUnion<typeof driveRoutes>
->;
-
-/** One typed destination builder for list and detail navigation. */
-export function driveDestination(
- location: DriveLocation,
- document?: DriveDocumentRoute
-): DriveDestination {
- const [folder, tab, rootDetail] = driveSplitRoute.children;
- 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: folder.children[0], params: { ...params, ...detail } }
- : { route: folder, params };
- }
- if (location.tab !== 'owned') {
- const params = { tab: location.tab };
- return detail
- ? { route: tab.children[0], params: { ...params, ...detail } }
- : { route: tab, params };
- }
- return detail
- ? { route: rootDetail, params: detail }
- : { route: driveSplitRoute, params: {} };
-}
-
/** String URLs are only needed at legacy redirect boundaries. */
export function drivePath(
location: DriveLocation,
@@ -190,7 +66,7 @@ export function driveDocumentRoute(document: {
id: document.id,
type:
documentType.safeParse(
- documentBlockType(document.subType ?? document.fileType)
+ driveDocumentBlockType(document.subType ?? document.fileType)
).data ?? 'unknown',
};
}
@@ -199,7 +75,9 @@ export function driveDocumentFromContent(content: {
type: string;
id: string;
}): DriveDocumentRoute | undefined {
- const type = documentType.safeParse(documentBlockType(content.type)).data;
+ const type = documentType.safeParse(
+ driveDocumentBlockType(content.type)
+ ).data;
return type ? { id: content.id, type } : undefined;
}
diff --git a/apps/web/src/features/email-view/components/EmailDetailView.tsx b/apps/web/src/features/email-view/components/EmailDetailView.tsx
index 25a35474af..cfdfef57ff 100644
--- a/apps/web/src/features/email-view/components/EmailDetailView.tsx
+++ b/apps/web/src/features/email-view/components/EmailDetailView.tsx
@@ -1,9 +1,9 @@
-import { useEntityDetailNavigationStack } from '@app/components/entity-detail/EntityDetailNavigationStack';
import { useListNavigationHotkeys } from '@app/components/entity-detail/use-list-navigation-hotkeys';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { displaySubject } from '@app/features/email-compose/core/subject-text';
import type { EmailThreadHost } from '@app/features/email-thread/context/email-thread-context';
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
+import { createSearchParams, useRouteParams } from '@app/lib/split-router';
import { EmailThreadLoadGate } from '@block-email/component/EmailThreadLoadGate';
import { EmailThreadHostView } from '@block-email/EmailThreadHostView';
import { registerEmailHotkeys } from '@block-email/util/emailHotkeys';
@@ -13,6 +13,7 @@ import {
useCanAutofocusSplitContent,
useSplitPanelOrThrow,
} from '@components/app/split-layout/layoutUtils';
+import { emailThreadRoute } from '@components/app/split-layout/split-router/app-routes';
import { EntityIcon } from '@core/component/EntityIcon';
import { toEntityLoadError } from '@core/component/EntityLoadGate';
import {
@@ -27,6 +28,7 @@ import { buildEntityData } from '@entity';
import { useThreadQuery } from '@queries/email/thread';
import { representativeThreadMessage } from '@queries/email/thread-subject';
import { createEffect, createMemo, createSignal, Show } from 'solid-js';
+import { emailDetailSearch } from '../email-route';
import { useEmailView } from '../email-view-context';
import type { EmailThreadTarget } from '../types';
import { useEmailDetailListNavigation } from '../use-email-detail-list-navigation';
@@ -60,9 +62,11 @@ function EmailThreadBreadcrumb(props: {
);
}
-export function EmailDetailView(props: { thread: EmailThreadTarget }) {
- const { closeThread } = useEmailView();
- const navigationStack = useEntityDetailNavigationStack();
+export function EmailDetailView(props: {
+ thread: EmailThreadTarget;
+ targetMessageId?: string;
+}) {
+ const { closeThread, selectedThread } = useEmailView();
const panel = useSplitPanelOrThrow();
const notificationSource = useGlobalNotificationSource();
const canAutofocus = useCanAutofocusSplitContent();
@@ -120,6 +124,7 @@ export function EmailDetailView(props: { thread: EmailThreadTarget }) {
const host: EmailThreadHost = {
listNavigation,
focusContainer,
+ targetMessageId: () => props.targetMessageId,
isActive: panel.isPanelActive,
registerKeyboard: (handlers) => {
registerEmailHotkeys(hotkeyScope(), handlers);
@@ -139,17 +144,11 @@ export function EmailDetailView(props: { thread: EmailThreadTarget }) {
});
},
};
- const threadEntry = () =>
- navigationStack.entries.find(
- (entry) =>
- entry.data.type === 'email' && entry.data.id === props.thread.id
- );
- const breadcrumbValue = () => threadEntry()?.value ?? 'email-view';
+ const breadcrumbValue = () => `email-thread:${props.thread.id}`;
useListNavigationHotkeys({
scopeId: panel.splitHotkeyScope,
enabled: () =>
- panel.isPanelActive() &&
- navigationStack.active()?.value === breadcrumbValue(),
+ panel.isPanelActive() && selectedThread()?.id === props.thread.id,
navigation: listNavigation,
});
const loadResult = {
@@ -219,3 +218,15 @@ export function EmailDetailView(props: { thread: EmailThreadTarget }) {
</ShareDialogContext.Provider>
);
}
+
+export function EmailDetailRouteView() {
+ const params = useRouteParams(emailThreadRoute);
+ const [search] = createSearchParams(emailDetailSearch);
+
+ return (
+ <EmailDetailView
+ thread={{ id: params.threadId }}
+ targetMessageId={search.messageId || undefined}
+ />
+ );
+}
diff --git a/apps/web/src/features/email-view/email-route.ts b/apps/web/src/features/email-view/email-route.ts
new file mode 100644
index 0000000000..59d016d0b6
--- /dev/null
+++ b/apps/web/src/features/email-view/email-route.ts
@@ -0,0 +1,13 @@
+import { createSearchParamsCodec } from '@app/lib/split-router';
+import { z } from 'zod';
+
+export const EMAIL_DETAIL_SEARCH_NAMESPACE = 'email-detail';
+
+export const emailDetailSearch = {
+ namespace: EMAIL_DETAIL_SEARCH_NAMESPACE,
+ schema: z.object({ messageId: z.string() }),
+ defaults: { messageId: '' },
+};
+
+export const emailDetailSearchCodec =
+ createSearchParamsCodec(emailDetailSearch);
diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsx
index c34a3907f5..3aaa037e93 100644
--- a/apps/web/src/features/email-view/email-view-context.tsx
+++ b/apps/web/src/features/email-view/email-view-context.tsx
@@ -1,8 +1,4 @@
-import {
- createEntityDetailTarget,
- type EntityDetailNavigationOptions,
- useEntityDetailNavigationStack,
-} from '@app/components/entity-detail/EntityDetailNavigationStack';
+import type { EntityDetailNavigationOptions } from '@app/components/entity-detail/EntityDetailNavigationStack';
import {
createListController,
type ListActivation,
@@ -14,15 +10,28 @@ import { registerInboxFilterSplit } from '@app/features/next-soup/soup-view/inbo
import { normalizeFacetSelection } from '@app/features/soup';
import { registerListNavigationSource } from '@app/features/soup/collection/list-navigation-source';
import { makePersistedState } from '@app/lib/persistence';
+import { useNavigate, useRouteParams } from '@app/lib/split-router';
+import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import {
useSplitPanelOrThrow,
withSplitPanelOwner,
} from '@components/app/split-layout/layoutUtils';
+import {
+ emailSplitRoute,
+ emailThreadRoute,
+} from '@components/app/split-layout/split-router/app-routes';
import { createAssertedContextProvider } from '@core/context/createContext';
import { useUserId } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';
import type { ContextProviderProps } from '@solid-primitives/context';
-import { type Accessor, onCleanup } from 'solid-js';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ on,
+ onCleanup,
+} from 'solid-js';
import {
createStore,
produce,
@@ -31,6 +40,7 @@ import {
type Store,
} from 'solid-js/store';
import { DEFAULT_EMAIL_TAB } from './constants';
+import { emailDetailSearch } from './email-route';
import { createEmailViewPersistence } from './persistence';
import {
type EmailDataSource,
@@ -95,7 +105,9 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<
EmailViewProviderProps
>('EmailView', (props) => {
const panel = useSplitPanelOrThrow();
- const navigationStack = useEntityDetailNavigationStack();
+ const navigate = useNavigate();
+ const routeParams = useRouteParams(emailThreadRoute);
+ const selectPreview = createPreviewSelectionGuard();
const userId = useUserId();
const tagSets = useTagSets();
const tagSetsReady = useTagSetsReady();
@@ -108,7 +120,6 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<
inboxIds:
initial.inboxIds === undefined ? undefined : [...initial.inboxIds],
facets: normalizeFacetSelection(initial.facets),
- openThreadId: initial.openThreadId,
collapsedSidebarSectionIds: [
...(initial.collapsedSidebarSectionIds ?? []),
],
@@ -169,46 +180,63 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<
});
};
- const selectedThread = (): EmailThreadTarget | undefined => {
- const entry = navigationStack.entries.find(
- (candidate) => candidate.data.type === 'email'
+ const selectedThread = createMemo<EmailThreadTarget | undefined>(() => {
+ const threadId = routeParams.threadId;
+ return typeof threadId === 'string' ? { id: threadId } : undefined;
+ });
+
+ const opensInline = (options?: EntityDetailNavigationOptions) => {
+ const event = options?.event;
+ return (
+ !isTouchDevice() &&
+ !(event?.shiftKey || event?.metaKey || event?.ctrlKey || event?.altKey)
);
- if (!entry || entry.data.type !== 'email') return undefined;
- return {
- id: entry.data.id,
- fallbackName: entry.data.fallbackName,
- };
};
-
+ const closeThread = () => navigate({ route: emailSplitRoute, params: {} });
const openThread = (
thread: EmailThreadTarget,
options?: EntityDetailNavigationOptions
) => {
- const target = createEntityDetailTarget(
- { type: 'email', id: thread.id },
- thread.fallbackName
+ if (!opensInline(options)) return false;
+ const selection = { type: 'email' as const, id: thread.id };
+ // The router may refuse a claimed destination. Check compatibility without
+ // claiming it until the accepted route changes.
+ if (!selectPreview.canSelect(selection)) return true;
+ navigate(
+ { route: emailThreadRoute, params: { threadId: thread.id } },
+ { search: { [emailDetailSearch.namespace]: {} } }
);
- if (!navigationStack.shouldNavigate(target, options)) return false;
- // A refused reset already alerted; there is nothing to fall back to.
- if (!navigationStack.reset(target)) return true;
- const row = source
- .items()
- .find((item) => item.kind === 'entity' && item.entity.id === thread.id);
- if (row) {
- list.focus.set(row.id, { reason: 'programmatic', force: true });
- list.selection.setAnchor(row.id);
- }
-
- setState('openThreadId', thread.id);
return true;
};
- const closeThread = () => {
- setState('openThreadId', undefined);
- navigationStack.clear();
- };
-
- if (state.openThreadId) openThread({ id: state.openThreadId });
+ createEffect(
+ on(selectedThread, (thread, previous) => {
+ const selection = thread
+ ? { type: 'email' as const, id: thread.id }
+ : undefined;
+ if (!selectPreview(selection)) {
+ if (previous) {
+ navigate(
+ {
+ route: emailThreadRoute,
+ params: { threadId: previous.id },
+ },
+ { replace: true }
+ );
+ } else {
+ navigate({ route: emailSplitRoute, params: {} }, { replace: true });
+ }
+ return;
+ }
+ if (!thread) return;
+ const row = source
+ .items()
+ .find((item) => item.kind === 'entity' && item.entity.id === thread.id);
+ if (!row) return;
+ list.focus.set(row.id, { reason: 'programmatic', force: true });
+ list.selection.setAnchor(row.id);
+ })
+ );
// A tab is a fresh slice of the mailbox: filters chosen for one tab (Done
// on Signal, say) would silently narrow the next, so they reset with it.
diff --git a/apps/web/src/features/email-view/email-view.tsx b/apps/web/src/features/email-view/email-view.tsx
index d2eea6244a..c9eadb2588 100644
--- a/apps/web/src/features/email-view/email-view.tsx
+++ b/apps/web/src/features/email-view/email-view.tsx
@@ -1,8 +1,5 @@
-import {
- EntityDetailNavigationStack,
- useEntityDetailNavigationStack,
-} from '@app/components/entity-detail/EntityDetailNavigationStack';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
+import { SplitRouter } from '@app/lib/split-router';
import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';
import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
@@ -13,14 +10,11 @@ import { ListEntityMetadataQueryProvider } from '@entity';
import SpinnerIcon from '@phosphor/spinner.svg';
import {
createSignal,
- Match,
onMount,
type ParentProps,
Show,
Suspense,
- Switch,
} from 'solid-js';
-import { EmailDetailView } from './components/EmailDetailView';
import { EmailFilterDrawer } from './components/EmailFilterDrawer';
import {
EmailHeader,
@@ -39,18 +33,17 @@ export type EmailViewProps = {
};
function EmailViewBreadcrumbs(props: ParentProps) {
- const { closeThread } = useEmailView();
- const navigationStack = useEntityDetailNavigationStack();
+ const { closeThread, selectedThread } = useEmailView();
+ const value = () => {
+ const thread = selectedThread();
+ return thread ? `email-thread:${thread.id}` : 'email-view';
+ };
return (
<ViewBreadcrumbs.Root
- value={navigationStack.active()?.value ?? 'email-view'}
- onChange={(value) => {
- if (value === 'email-view') {
- closeThread();
- return;
- }
- navigationStack.popTo(value);
+ value={value()}
+ onChange={(next) => {
+ if (next === 'email-view') closeThread();
}}
>
<EmailViewBreadcrumbItem />
@@ -70,7 +63,15 @@ function EmailListFallback() {
function EmailDesktopLayout(
props: ParentProps<{ onSearchEscape: () => void }>
) {
- const { selectedThread } = useEmailView();
+ const list = () => (
+ <>
+ <EmailTopBar />
+ <ViewShell.Header>
+ <EmailHeader onSearchEscape={props.onSearchEscape} />
+ </ViewShell.Header>
+ <ViewShell.Content>{props.children}</ViewShell.Content>
+ </>
+ );
return (
<ViewShell.Root
@@ -83,18 +84,7 @@ function EmailDesktopLayout(
<EmailSidebar />
</ViewShell.Aside>
<ViewShell.Main>
- <Switch>
- <Match when={selectedThread()}>
- {(thread) => <EmailDetailView thread={thread()} />}
- </Match>
- <Match when={true}>
- <EmailTopBar />
- <ViewShell.Header>
- <EmailHeader onSearchEscape={props.onSearchEscape} />
- </ViewShell.Header>
- <ViewShell.Content>{props.children}</ViewShell.Content>
- </Match>
- </Switch>
+ <SplitRouter.Outlet fallback={list} />
</ViewShell.Main>
</ViewShell.Root>
);
@@ -171,14 +161,12 @@ function EmailViewRoot() {
/** Email shares one list across desktop sidebar and mobile pill layouts. */
export function EmailView(props: EmailViewProps) {
return (
- <EntityDetailNavigationStack.Root>
- <ListEntityMetadataQueryProvider>
- <EmailViewProvider initialState={props.initialState}>
- <EmailViewBreadcrumbs>
- <EmailViewRoot />
- </EmailViewBreadcrumbs>
- </EmailViewProvider>
- </ListEntityMetadataQueryProvider>
- </EntityDetailNavigationStack.Root>
+ <ListEntityMetadataQueryProvider>
+ <EmailViewProvider initialState={props.initialState}>
+ <EmailViewBreadcrumbs>
+ <EmailViewRoot />
+ </EmailViewBreadcrumbs>
+ </EmailViewProvider>
+ </ListEntityMetadataQueryProvider>
);
}
diff --git a/apps/web/src/features/email-view/persistence.ts b/apps/web/src/features/email-view/persistence.ts
index 9219627649..ff027c4261 100644
--- a/apps/web/src/features/email-view/persistence.ts
+++ b/apps/web/src/features/email-view/persistence.ts
@@ -31,7 +31,6 @@ const emailEntryStateSchemaWithDefaults = z.object({
tab: emailTabSchema.default('important'),
search: z.string().default(''),
facets: emailFacetsSchema.default({}),
- openThreadId: z.string().optional(),
});
type EmailEntryState = z.infer<typeof emailEntryStateSchemaWithDefaults>;
@@ -86,7 +85,6 @@ function createEmailEntryStorage(options: {
tab: restored.tab,
search: restored.search,
facets: normalizeFacetSelection(restored.facets),
- openThreadId: restored.openThreadId,
};
},
select: (state): EmailEntryState => ({
@@ -94,23 +92,18 @@ function createEmailEntryStorage(options: {
tab: state.tab,
search: state.search,
facets: normalizeFacetSelection(state.facets),
- ...(state.openThreadId === undefined
- ? {}
- : { openThreadId: state.openThreadId }),
}),
});
}
-// Split entry state is gone after a reload, so the parts of the view worth
-// coming back to — tab, inbox scope, filters, and the open thread — are also
-// kept per user, the way the Channels view keeps its selected channel. The
-// search text is deliberately per visit.
+// Split entry state is gone after a reload, so tab, inbox scope, and filters
+// are also kept per user. Detail selection belongs to the route, while search
+// text remains deliberately scoped to one visit.
const emailLocalStateSchemaWithDefaults = z.object({
version: z.literal(1).default(1),
tab: emailTabSchema.default('important'),
inboxIds: inboxIdsEntrySchema,
facets: emailFacetsSchema.default({}),
- openThreadId: z.string().optional(),
});
type EmailLocalState = z.infer<typeof emailLocalStateSchemaWithDefaults>;
@@ -127,9 +120,6 @@ function selectLocalState(state: EmailViewState): EmailLocalState {
tab: state.tab,
...(state.inboxIds === undefined ? {} : { inboxIds: [...state.inboxIds] }),
facets: normalizeFacetSelection(state.facets),
- ...(state.openThreadId === undefined
- ? {}
- : { openThreadId: state.openThreadId }),
};
}
@@ -158,7 +148,6 @@ function createEmailLocalStateStorage(options: {
tab: restored.tab,
inboxIds: restored.inboxIds,
facets: normalizeFacetSelection(restored.facets),
- openThreadId: restored.openThreadId,
};
} catch {
return undefined;
diff --git a/apps/web/src/features/email-view/types.ts b/apps/web/src/features/email-view/types.ts
index eae5dba7aa..4c9d48a379 100644
--- a/apps/web/src/features/email-view/types.ts
+++ b/apps/web/src/features/email-view/types.ts
@@ -42,11 +42,6 @@ export type EmailViewState = {
*/
inboxIds: string[] | undefined;
facets: FacetSelection;
- /**
- * The thread last opened from this view. Restored into the in-view detail on
- * the next visit, the way the Channels view reopens its selected channel.
- */
- openThreadId?: string;
/** Sidebar sections the user folded away; kept per user, not per visit. */
collapsedSidebarSectionIds: string[];
};
diff --git a/apps/web/src/features/inbox-view/components/InboxList.tsx b/apps/web/src/features/inbox-view/components/InboxList.tsx
index 752bbb2878..70963bd074 100644
--- a/apps/web/src/features/inbox-view/components/InboxList.tsx
+++ b/apps/web/src/features/inbox-view/components/InboxList.tsx
@@ -23,6 +23,7 @@ import { makePersistedState } from '@app/lib/persistence';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { PullToRefresh } from '@components/app/mobile/PullToRefresh';
import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';
+import type { PreviewPanelSelection } from '@components/app/previewTarget';
import {
useSplitPanelOrThrow,
withSplitPanelOwner,
@@ -88,8 +89,8 @@ type InboxListActivationMetadata = {
};
type InboxListProps = {
- previewEntity: EntityData | undefined;
- onPreviewEntityChange: (entity: EntityData | undefined) => void;
+ previewEntity: PreviewPanelSelection | undefined;
+ onPreviewEntityChange: (entity: PreviewPanelSelection | undefined) => void;
onPreviewActivate?: () => void;
};
diff --git a/apps/web/src/features/inbox-view/inbox-preview-navigation.ts b/apps/web/src/features/inbox-view/inbox-preview-navigation.ts
new file mode 100644
index 0000000000..fb7d5b6bdd
--- /dev/null
+++ b/apps/web/src/features/inbox-view/inbox-preview-navigation.ts
@@ -0,0 +1,125 @@
+import { getChannelEntityTarget } from '@app/features/next-soup/utils';
+import type { CalendarBlockProps } from '@block-calendar/types';
+import {
+ type PreviewPanelSelection,
+ previewBlockTarget,
+} from '@components/app/previewTarget';
+import {
+ type InboxPreviewSearchParams,
+ inboxPreviewSearch,
+} from './inbox-route';
+import type { InboxPreviewRouteParams } from './inbox-route-schema';
+
+function calendarSearch(
+ params: CalendarBlockProps | undefined,
+ time: Extract<PreviewPanelSelection, { type: 'calendar_event' }>['time']
+): Partial<InboxPreviewSearchParams> {
+ const range = params?.range;
+ return {
+ eventId: params?.eventId ?? '',
+ occurrenceKey: params?.occurrenceKey ?? '',
+ ...(time?.kind === 'allDay'
+ ? {
+ calendarTimeKind: 'allDay',
+ startDate: time.startDate,
+ endDate: time.endDate ?? range?.endDate ?? '',
+ }
+ : time?.kind === 'timed'
+ ? {
+ calendarTimeKind: 'timed',
+ startsAt: time.startsAt,
+ endsAt: time.endsAt ?? range?.end ?? '',
+ }
+ : range
+ ? {
+ calendarTimeKind: 'timed',
+ startsAt: range.start,
+ endsAt: range.end,
+ startDate: range.startDate,
+ endDate: range.endDate,
+ }
+ : {}),
+ };
+}
+
+function selectionSearch(
+ selection: PreviewPanelSelection,
+ blockParams: Record<string, unknown> | undefined
+): InboxPreviewSearchParams {
+ const channelTarget =
+ selection.type === 'channel' ||
+ selection.type === 'channel_message' ||
+ selection.type === 'channel_thread'
+ ? getChannelEntityTarget(selection)
+ : undefined;
+ const channelSearch = {
+ targetMessageId:
+ channelTarget?.kind === 'message' ? channelTarget.messageId : '',
+ targetThreadId:
+ channelTarget?.kind === 'message' ? (channelTarget.threadId ?? '') : '',
+ };
+ const base: InboxPreviewSearchParams = {
+ ...inboxPreviewSearch.defaults,
+ selectionType: selection.type,
+ selectionId: selection.id,
+ };
+
+ switch (selection.type) {
+ case 'document':
+ return {
+ ...base,
+ fileType: selection.fileType ?? '',
+ subType: selection.subType?.type ?? '',
+ };
+ case 'foreign':
+ return { ...base, foreignSource: selection.foreignSource };
+ case 'channel':
+ return {
+ ...base,
+ ...channelSearch,
+ };
+ case 'channel_message':
+ case 'channel_thread':
+ return {
+ ...base,
+ sourceMessageId: selection.messageId,
+ sourceThreadId: selection.threadId ?? '',
+ ...channelSearch,
+ };
+ case 'calendar_event':
+ return {
+ ...base,
+ ...calendarSearch(
+ blockParams as CalendarBlockProps | undefined,
+ selection.time
+ ),
+ };
+ case 'reminder':
+ return {
+ ...base,
+ reminderId: selection.id,
+ referencedType: selection.referencedEntity?.type ?? '',
+ referencedFileType: selection.referencedEntity?.fileType ?? '',
+ referencedSubType: selection.referencedEntity?.subType ?? '',
+ };
+ default:
+ return base;
+ }
+}
+
+/** Converts a live row into a minimal, reloadable Inbox route destination. */
+export function inboxPreviewNavigation(selection: PreviewPanelSelection) {
+ const target = previewBlockTarget(selection);
+ const search = selectionSearch(
+ selection,
+ target.params as Record<string, unknown> | undefined
+ );
+
+ return {
+ params: {
+ blockType: target.blockType,
+ previewId: target.blockId,
+ } satisfies InboxPreviewRouteParams,
+ search,
+ };
+}
diff --git a/apps/web/src/features/inbox-view/inbox-route-schema.ts b/apps/web/src/features/inbox-view/inbox-route-schema.ts
new file mode 100644
index 0000000000..fb3f90f5bd
--- /dev/null
+++ b/apps/web/src/features/inbox-view/inbox-route-schema.ts
@@ -0,0 +1,16 @@
+import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
+import { BlockRegistry } from '@core/block';
+import { z } from 'zod';
+
+export const inboxPreviewRouteParams = z
+ .object({
+ blockType: z.enum(BlockRegistry),
+ previewId: z.string().min(1),
+ })
+ .refine(
+ ({ blockType, previewId }) =>
+ blockType !== 'write' &&
+ (blockType !== 'calendar' || previewId === CALENDAR_BLOCK_ID)
+ );
+
+export type InboxPreviewRouteParams = z.infer<typeof inboxPreviewRouteParams>;
diff --git a/apps/web/src/features/inbox-view/inbox-route.ts b/apps/web/src/features/inbox-view/inbox-route.ts
new file mode 100644
index 0000000000..ca61d05ce4
--- /dev/null
+++ b/apps/web/src/features/inbox-view/inbox-route.ts
@@ -0,0 +1,383 @@
+import { createSearchParamsCodec } from '@app/lib/split-router';
+import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
+import type { PreviewPanelSelection } from '@components/app/previewTarget';
+import type { BlockName } from '@core/block';
+import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';
+import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
+import { match } from 'ts-pattern';
+import { z } from 'zod';
+import type { InboxPreviewRouteParams } from './inbox-route-schema';
+
+export const INBOX_PREVIEW_SEARCH_NAMESPACE = 'inbox-preview';
+
+const previewSelectionTypes = [
+ '',
+ 'agent_session',
+ 'automation',
+ 'call',
+ 'calendar_event',
+ 'channel',
+ 'channel_message',
+ 'channel_thread',
+ 'chat',
+ 'crm_company',
+ 'crm_contact',
+ 'document',
+ 'email',
+ 'foreign',
+ 'project',
+ 'reminder',
+] as const;
+
+const reminderReferenceTypes = [
+ '',
+ 'agent_session',
+ 'automation',
+ 'call',
+ 'channel',
+ 'channel_message',
+ 'channel_thread',
+ 'chat',
+ 'crm_company',
+ 'crm_contact',
+ 'document',
+ 'email',
+ 'foreign',
+ 'project',
+] as const;
+
+const documentSubTypes = ['', 'task', 'snippet', 'skill'] as const;
+const calendarTimeKinds = ['', 'timed', 'allDay'] as const;
+
+export const inboxPreviewSearch = {
+ namespace: INBOX_PREVIEW_SEARCH_NAMESPACE,
+ schema: z.object({
+ selectionType: z.enum(previewSelectionTypes),
+ selectionId: z.string(),
+ fileType: z.string(),
+ subType: z.enum(documentSubTypes),
+ foreignSource: z.enum(['', 'unknown', 'github_pull_request']),
+ sourceMessageId: z.string(),
+ sourceThreadId: z.string(),
+ targetMessageId: z.string(),
+ targetThreadId: z.string(),
+ eventId: z.string(),
+ occurrenceKey: z.string(),
+ calendarTimeKind: z.enum(calendarTimeKinds),
+ startsAt: z.string(),
+ endsAt: z.string(),
+ startDate: z.string(),
+ endDate: z.string(),
+ reminderId: z.string(),
+ referencedType: z.enum(reminderReferenceTypes),
+ referencedFileType: z.string(),
+ referencedSubType: z.string(),
+ }),
+ defaults: {
+ selectionType: '' as const,
+ selectionId: '',
+ fileType: '',
+ subType: '' as const,
+ foreignSource: '' as const,
+ sourceMessageId: '',
+ sourceThreadId: '',
+ targetMessageId: '',
+ targetThreadId: '',
+ eventId: '',
+ occurrenceKey: '',
+ calendarTimeKind: '' as const,
+ startsAt: '',
+ endsAt: '',
+ startDate: '',
+ endDate: '',
+ reminderId: '',
+ referencedType: '' as const,
+ referencedFileType: '',
+ referencedSubType: '',
+ },
+};
+
+export type InboxPreviewSearchParams = z.infer<
+ typeof inboxPreviewSearch.schema
+>;
+
+export const inboxPreviewSearchCodec =
+ createSearchParamsCodec(inboxPreviewSearch);
+
+function calendarTime(search: InboxPreviewSearchParams) {
+ if (search.calendarTimeKind === 'timed' && search.startsAt && search.endsAt) {
+ return {
+ kind: 'timed' as const,
+ startsAt: search.startsAt,
+ endsAt: search.endsAt,
+ };
+ }
+ if (
+ search.calendarTimeKind === 'allDay' &&
+ search.startDate &&
+ search.endDate
+ ) {
+ return {
+ kind: 'allDay' as const,
+ startDate: search.startDate,
+ endDate: search.endDate,
+ };
+ }
+}
+
+function fallbackSelection(
+ params: InboxPreviewRouteParams
+): PreviewPanelSelection | undefined {
+ const id = params.previewId;
+ return match(params.blockType)
+ .returnType<PreviewPanelSelection | undefined>()
+ .with('agent', () => ({ type: 'agent_session', id }))
+ .with('automation', () => ({ type: 'automation', id }))
+ .with('call', () => ({ type: 'call', id }))
+ .with('calendar', () => ({ type: 'calendar_event', id }))
+ .with('channel', () => ({ type: 'channel', id }))
+ .with('chat', () => ({ type: 'chat', id }))
+ .with('company', () => ({ type: 'crm_company', id }))
+ .with('contact', () => ({ type: 'crm_contact', id }))
+ .with('email', () => ({ type: 'email', id }))
+ .with('project', () => ({ type: 'project', id }))
+ .with('pr', () =>
+ USE_MACRO_PR_SUMMARY_BLOCK
+ ? ({
+ type: 'foreign',
+ id,
+ foreignSource: 'github_pull_request',
+ } as const)
+ : undefined
+ )
+ .with(
+ 'canvas',
+ 'code',
+ 'image',
+ 'md',
+ 'pdf',
+ 'spreadsheet',
+ 'unknown',
+ 'video',
+ (fileType) => ({ type: 'document', id, fileType })
+ )
+ .with('write', () => undefined)
+ .exhaustive();
+}
+
+function selectionIdentity(selection: PreviewPanelSelection): {
+ blockType: BlockName;
+ id: string;
+} {
+ return match(selection)
+ .returnType<{ blockType: BlockName; id: string }>()
+ .with({ type: 'document' }, (document) => ({
+ blockType: fileTypeToResolvedBlockName(document.fileType),
+ id: document.id,
+ }))
+ .with(
+ { type: 'channel_message' },
+ { type: 'channel_thread' },
+ (channel) => ({ blockType: 'channel', id: channel.channelId })
+ )
+ .with({ type: 'calendar_event' }, () => ({
+ blockType: 'calendar',
+ id: CALENDAR_BLOCK_ID,
+ }))
+ .with({ type: 'foreign' }, (foreign) => ({
+ blockType:
+ USE_MACRO_PR_SUMMARY_BLOCK &&
+ foreign.foreignSource === 'github_pull_request'
+ ? 'pr'
+ : 'unknown',
+ id: foreign.id,
+ }))
+ .with({ type: 'crm_company' }, (company) => ({
+ blockType: 'company',
+ id: company.id,
+ }))
+ .with({ type: 'crm_contact' }, (contact) => ({
+ blockType: 'contact',
+ id: contact.id,
+ }))
+ .with({ type: 'reminder' }, (reminder) => ({
+ blockType: fileTypeToResolvedBlockName(
+ reminder.referencedEntity?.subType ??
+ reminder.referencedEntity?.fileType ??
+ reminder.referencedEntity?.type
+ ),
+ id: reminder.referencedEntity?.id ?? reminder.id,
+ }))
+ .otherwise((selection) => ({
+ blockType: fileTypeToResolvedBlockName(selection.type),
+ id: selection.id,
+ }));
+}
+
+function decodedSelection(
+ params: InboxPreviewRouteParams,
+ search: InboxPreviewSearchParams
+): PreviewPanelSelection | undefined {
+ const id = search.selectionId || params.previewId;
+ const target = search.targetMessageId
+ ? {
+ messageId: search.targetMessageId,
+ ...(search.targetThreadId ? { threadId: search.targetThreadId } : {}),
+ }
+ : undefined;
+
+ return match(search.selectionType)
+ .returnType<PreviewPanelSelection | undefined>()
+ .with('', () => undefined)
+ .with('document', () => ({
+ type: 'document',
+ id,
+ ...(search.fileType ? { fileType: search.fileType } : {}),
+ ...(search.subType
+ ? {
+ subType: {
+ type: search.subType,
+ ...(search.subType === 'task' ? { is_completed: false } : {}),
+ },
+ }
+ : {}),
+ }))
+ .with('foreign', () => ({
+ type: 'foreign',
+ id,
+ foreignSource: search.foreignSource || 'unknown',
+ }))
+ .with('channel', () => ({
+ type: 'channel',
+ id: params.previewId,
+ ...(target ? { target } : {}),
+ }))
+ .with('channel_message', () => ({
+ type: 'channel_message',
+ id,
+ channelId: params.previewId,
+ messageId: search.sourceMessageId || search.targetMessageId || id,
+ ...(search.sourceThreadId ? { threadId: search.sourceThreadId } : {}),
+ ...(target ? { target } : {}),
+ }))
+ .with('channel_thread', () => ({
+ type: 'channel_thread',
+ id,
+ channelId: params.previewId,
+ messageId: search.sourceMessageId || search.targetMessageId || id,
+ threadId:
+ search.sourceThreadId ||
+ search.targetThreadId ||
+ search.sourceMessageId ||
+ id,
+ ...(target ? { target } : {}),
+ }))
+ .with('calendar_event', () => ({
+ type: 'calendar_event',
+ id: search.eventId || id,
+ ...(search.occurrenceKey ? { occurrenceKey: search.occurrenceKey } : {}),
+ ...(calendarTime(search) ? { time: calendarTime(search) } : {}),
+ }))
+ .with('reminder', () => ({
+ type: 'reminder',
+ id: search.reminderId || id,
+ ...(search.referencedType
+ ? {
+ referencedEntity: {
+ id: params.previewId,
+ type: search.referencedType,
+ ...(search.referencedFileType
+ ? { fileType: search.referencedFileType }
+ : {}),
+ ...(search.referencedSubType
+ ? { subType: search.referencedSubType }
+ : {}),
+ },
+ }
+ : {}),
+ }))
+ .with('agent_session', (type) => ({ type, id }))
+ .with('automation', (type) => ({ type, id }))
+ .with('call', (type) => ({ type, id }))
+ .with('chat', (type) => ({ type, id }))
+ .with('crm_company', (type) => ({ type, id }))
+ .with('crm_contact', (type) => ({ type, id }))
+ .with('email', (type) => ({ type, id }))
+ .with('project', (type) => ({ type, id }))
+ .exhaustive();
+}
+
+/** Rebuilds the minimal preview target from path identity plus typed search. */
+export function inboxPreviewSelection(
+ params: InboxPreviewRouteParams,
+ search: InboxPreviewSearchParams
+): PreviewPanelSelection | undefined {
+ const decoded = decodedSelection(params, search);
+ if (!decoded) return fallbackSelection(params);
+ const identity = selectionIdentity(decoded);
+ return identity.blockType === params.blockType &&
+ identity.id === params.previewId
+ ? decoded
+ : fallbackSelection(params);
+}
+
+/** Full-block compatibility target for disabled or touch-only view surfaces. */
+export function inboxPreviewLegacyTarget(
+ params: InboxPreviewRouteParams,
+ search: InboxPreviewSearchParams
+): {
+ type: BlockName | 'task' | 'snippet' | 'skill';
+ id: string;
+ params?: Record<string, unknown>;
+} {
+ const documentSubType =
+ search.selectionType === 'document'
+ ? search.subType
+ : search.selectionType === 'reminder'
+ ? search.referencedSubType
+ : '';
+ if (
+ params.blockType === 'md' &&
+ (documentSubType === 'task' ||
+ documentSubType === 'snippet' ||
+ documentSubType === 'skill')
+ ) {
+ return { type: documentSubType, id: params.previewId };
+ }
+ if (params.blockType === 'channel' && search.targetMessageId) {
+ return {
+ type: 'channel',
+ id: params.previewId,
+ params: {
+ [CHANNEL_URL_PARAMS.message]: search.targetMessageId,
+ ...(search.targetThreadId
+ ? { [CHANNEL_URL_PARAMS.thread]: search.targetThreadId }
+ : {}),
+ },
+ };
+ }
+ if (params.blockType === 'calendar') {
+ const range =
+ search.startsAt && search.endsAt && search.startDate && search.endDate
+ ? {
+ start: search.startsAt,
+ end: search.endsAt,
+ startDate: search.startDate,
+ endDate: search.endDate,
+ }
+ : undefined;
+ return {
+ type: 'calendar',
+ id: CALENDAR_BLOCK_ID,
+ params: {
+ ...(search.eventId ? { eventId: search.eventId } : {}),
+ ...(search.occurrenceKey
+ ? { occurrenceKey: search.occurrenceKey }
+ : {}),
+ ...(range ? { range } : {}),
+ },
+ };
+ }
+ return { type: params.blockType, id: params.previewId };
+}
diff --git a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx b/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
index 5e045c0f2f..0ec343bdf1 100644
--- a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
+++ b/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
@@ -1,3 +1,12 @@
+import {
+ SplitRouter,
+ type SplitRouterEntry,
+ type SplitRouterLayout,
+ type SplitRouterSettledChange,
+ useSplitRouter,
+} from '@app/lib/split-router';
+import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';
+import { appSplitRoutes } from '@components/app/split-layout/split-router/app-routes';
import { cleanup, render } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
@@ -8,12 +17,107 @@ import {
import { INBOX_ENTRY_STATE_KEY } from './persistence';
import type { InboxViewStateOptions } from './types';
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+
const entry = vi.hoisted(() => ({
state: {} as Record<string, unknown>,
captors: new Map<string, () => unknown>(),
}));
const user = vi.hoisted(() => ({ id: 'alice' }));
+const guard = vi.hoisted(() => ({
+ selections: [] as unknown[],
+ preflights: [] as unknown[],
+ allow: true,
+}));
vi.mock('@core/context/user', () => ({ useUserId: () => () => user.id }));
+vi.mock('@components/app/previewTarget', () => ({
+ previewBlockTarget: (selection: {
+ type: string;
+ id: string;
+ channelId?: string;
+ fileType?: string;
+ foreignSource?: string;
+ occurrenceKey?: string;
+ referencedEntity?: {
+ id: string;
+ type: string;
+ fileType?: string;
+ subType?: string;
+ };
+ }) => {
+ if (selection.type === 'calendar_event') {
+ return {
+ blockType: 'calendar',
+ blockId: 'view',
+ params: {
+ eventId: selection.id,
+ occurrenceKey: selection.occurrenceKey,
+ range: {
+ start: '2025-01-01T00:00:00.000Z',
+ end: '2025-01-02T00:00:00.000Z',
+ startDate: '2025-01-01',
+ endDate: '2025-01-02',
+ },
+ },
+ };
+ }
+ if (selection.type === 'reminder') {
+ const reference = selection.referencedEntity;
+ const referenceType =
+ reference?.subType ??
+ reference?.fileType ??
+ reference?.type ??
+ 'unknown';
+ return {
+ blockType: ['task', 'snippet', 'skill'].includes(referenceType)
+ ? 'md'
+ : referenceType,
+ blockId: reference?.id ?? selection.id,
+ };
+ }
+ return {
+ blockType:
+ selection.type === 'document'
+ ? selection.fileType
+ : selection.type === 'channel_message' ||
+ selection.type === 'channel_thread'
+ ? 'channel'
+ : selection.type === 'foreign'
+ ? 'unknown'
+ : selection.type,
+ blockId: selection.channelId ?? selection.id,
+ };
+ },
+}));
+vi.mock('@core/constant/allBlocks', () => ({
+ fileTypeToResolvedBlockName: (type: string) =>
+ ['task', 'snippet', 'skill'].includes(type) ? 'md' : type,
+ isBlockAlias: () => false,
+ resolveBlockAlias: (type: string) => type,
+}));
+vi.mock('@components/app/createPreviewSelectionGuard', () => ({
+ createPreviewSelectionGuard: () => {
+ const select = (selection: unknown) => {
+ guard.selections.push(selection);
+ return selection === undefined || guard.allow;
+ };
+ return Object.assign(select, {
+ canSelect: (selection: unknown) => {
+ guard.preflights.push(selection);
+ return selection === undefined || guard.allow;
+ },
+ });
+ },
+}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanelOrThrow: () => ({
@@ -27,18 +131,56 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
}),
}));
-function mountProvider(initialState?: InboxViewStateOptions) {
+function createLayout(): SplitRouterLayout<string> {
+ let current: (SplitRouterEntry & { splitId: string }) | undefined;
+ const listeners = new Set<(change: SplitRouterSettledChange) => void>();
+ const notify = () => {
+ for (const listener of listeners) listener({ history: 'push' });
+ };
+ return {
+ snapshot: () => ({ entries: current ? [current] : [] }),
+ updateCurrentEntry(_splitId, update) {
+ if (!current) return;
+ current = { splitId: current.splitId, ...update(current) };
+ notify();
+ },
+ open: () => {},
+ reconcile(entries) {
+ const next = entries[0];
+ current = next ? { splitId: 'split', ...next } : undefined;
+ notify();
+ },
+ activate: () => {},
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+}
+
+function mountProvider(initialState?: InboxViewStateOptions, path = '/inbox') {
let context!: InboxViewContext;
+ let router!: ReturnType<typeof useSplitRouter<string>>;
+ const location = createMemorySplitRouterLocation(path);
function ReadContext() {
context = useInboxView();
+ router = useSplitRouter<string>();
return null;
}
const view = render(() => (
- <InboxViewProvider initialState={initialState}>
- <ReadContext />
- </InboxViewProvider>
+ <SplitRouter.Root
+ layout={createLayout()}
+ routes={appSplitRoutes}
+ location={location}
+ >
+ <SplitRouter.Scope splitId="split">
+ <InboxViewProvider initialState={initialState}>
+ <ReadContext />
+ </InboxViewProvider>
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
));
- return { ...view, context };
+ return { ...view, context, location, router };
}
beforeEach(() => {
@@ -46,6 +188,9 @@ beforeEach(() => {
user.id = 'alice';
entry.state = {};
entry.captors.clear();
+ guard.selections = [];
+ guard.preflights = [];
+ guard.allow = true;
});
afterEach(cleanup);
@@ -212,3 +357,147 @@ describe('InboxViewProvider initialization', () => {
expect(mountProvider().context.state.facets).toEqual({});
});
});
+
+describe('InboxViewProvider route selection', () => {
+ it('rebuilds a heterogeneous channel-message preview from a direct URL', () => {
+ const { context } = mountProvider(
+ undefined,
+ '/inbox/channel/channel-1?s0.inbox-preview.selectionType=channel_message&s0.inbox-preview.selectionId=row-1&s0.inbox-preview.sourceMessageId=message-1&s0.inbox-preview.sourceThreadId=thread-1&s0.inbox-preview.targetMessageId=message-1&s0.inbox-preview.targetThreadId=thread-1'
+ );
+
+ expect(context.previewEntity()).toEqual({
+ type: 'channel_message',
+ id: 'row-1',
+ channelId: 'channel-1',
+ messageId: 'message-1',
+ threadId: 'thread-1',
+ target: { messageId: 'message-1', threadId: 'thread-1' },
+ });
+ expect(guard.selections.at(-1)).toEqual(context.previewEntity());
+ });
+
+ it('serializes a live preview selection and closes it through the root route', async () => {
+ const { context, location, router } = mountProvider();
+
+ expect(
+ context.openPreview({
+ type: 'document',
+ id: 'task-1',
+ fileType: 'md',
+ subType: { type: 'task', is_completed: false },
+ })
+ ).toBe(true);
+ await router.settled();
+ expect(location.read().pathname).toBe('/inbox/md/task-1');
+ expect(location.read().search).toContain(
+ 's0.inbox-preview.selectionType=document'
+ );
+ expect(context.previewEntity()).toMatchObject({
+ type: 'document',
+ id: 'task-1',
+ fileType: 'md',
+ subType: { type: 'task' },
+ });
+
+ context.closePreview();
+ await router.settled();
+ expect(location.read().pathname).toBe('/inbox');
+ expect(context.previewEntity()).toBeUndefined();
+ });
+
+ it('round-trips calendar, reminder, foreign, and document subtype targets', async () => {
+ const { context, location, router } = mountProvider();
+
+ context.openPreview({
+ type: 'calendar_event',
+ id: 'event-1',
+ occurrenceKey: 'occurrence-1',
+ time: {
+ kind: 'timed',
+ startsAt: '2025-01-01T12:00:00.000Z',
+ endsAt: '2025-01-01T13:00:00.000Z',
+ },
+ });
+ await router.settled();
+ expect(location.read().pathname).toBe('/inbox/calendar/view');
+ expect(context.previewEntity()).toMatchObject({
+ type: 'calendar_event',
+ id: 'event-1',
+ occurrenceKey: 'occurrence-1',
+ });
+
+ context.openPreview({
+ type: 'reminder',
+ id: 'reminder-1',
+ referencedEntity: {
+ id: 'task-2',
+ type: 'document',
+ fileType: 'md',
+ subType: 'task',
+ },
+ });
+ await router.settled();
+ expect(location.read().pathname).toBe('/inbox/md/task-2');
+ expect(context.previewEntity()).toMatchObject({
+ type: 'reminder',
+ id: 'reminder-1',
+ referencedEntity: { id: 'task-2', subType: 'task' },
+ });
+
+ context.openPreview({
+ type: 'foreign',
+ id: 'foreign-1',
+ foreignSource: 'unknown',
+ });
+ await router.settled();
+ expect(location.read().pathname).toBe('/inbox/unknown/foreign-1');
+ expect(context.previewEntity()).toEqual({
+ type: 'foreign',
+ id: 'foreign-1',
+ foreignSource: 'unknown',
+ });
+
+ context.openPreview({
+ type: 'document',
+ id: 'snippet-1',
+ fileType: 'md',
+ subType: { type: 'snippet' },
+ });
+ await router.settled();
+ expect(location.read().pathname).toBe('/inbox/md/snippet-1');
+ expect(context.previewEntity()).toMatchObject({
+ type: 'document',
+ id: 'snippet-1',
+ fileType: 'md',
+ subType: { type: 'snippet' },
+ });
+ });
+
+ it('keeps the accepted preview when compatibility preflight blocks selection', async () => {
+ const { context, location, router } = mountProvider(
+ undefined,
+ '/inbox/email/current'
+ );
+ guard.allow = false;
+
+ expect(context.openPreview({ type: 'email', id: 'blocked' })).toBe(false);
+ await router.settled();
+ expect(location.read().pathname).toBe('/inbox/email/current');
+ expect(context.previewEntity()).toEqual({ type: 'email', id: 'current' });
+ });
+
+ it('replaces an incompatible direct preview and closes previews on tab change', async () => {
+ guard.allow = false;
+ const blocked = mountProvider(undefined, '/inbox/email/blocked');
+ await blocked.router.settled();
+ expect(blocked.location.read().pathname).toBe('/inbox');
+ blocked.unmount();
+
+ guard.allow = true;
+ const accepted = mountProvider(undefined, '/inbox/email/open');
+ accepted.context.setTab('noise');
+ await accepted.router.settled();
+ expect(accepted.location.read().pathname).toBe('/inbox');
+ expect(accepted.context.state.tab).toBe('noise');
+ });
+});
diff --git a/apps/web/src/features/inbox-view/inbox-view-context.tsx b/apps/web/src/features/inbox-view/inbox-view-context.tsx
index ac8209957d..c74f657795 100644
--- a/apps/web/src/features/inbox-view/inbox-view-context.tsx
+++ b/apps/web/src/features/inbox-view/inbox-view-context.tsx
@@ -1,9 +1,21 @@
import type { FacetSelection } from '@app/features/soup/filters/facets/types';
import { makePersistedState } from '@app/lib/persistence';
+import {
+ createSearchParams,
+ useNavigate,
+ useRouteParams,
+} from '@app/lib/split-router';
+import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
+import type { PreviewPanelSelection } from '@components/app/previewTarget';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import {
+ inboxPreviewRoute,
+ inboxSplitRoute,
+} from '@components/app/split-layout/split-router/app-routes';
import { createAssertedContextProvider } from '@core/context/createContext';
import { useUserId } from '@core/context/user';
import type { ContextProviderProps } from '@solid-primitives/context';
+import { type Accessor, createEffect, createMemo, on } from 'solid-js';
import {
createStore,
produce,
@@ -11,6 +23,13 @@ import {
type SetStoreFunction,
type Store,
} from 'solid-js/store';
+import { inboxPreviewNavigation } from './inbox-preview-navigation';
+import {
+ INBOX_PREVIEW_SEARCH_NAMESPACE,
+ inboxPreviewSearch,
+ inboxPreviewSearchCodec,
+ inboxPreviewSelection,
+} from './inbox-route';
import {
createInboxViewPersistence,
normalizeInboxFacets,
@@ -29,6 +48,9 @@ type InboxViewProviderProps = ContextProviderProps & {
export type InboxViewContext = {
state: Store<InboxViewState>;
setState: SetStoreFunction<InboxViewState>;
+ previewEntity: Accessor<PreviewPanelSelection | undefined>;
+ openPreview: (entity: PreviewPanelSelection) => boolean;
+ closePreview: () => void;
setTab: (tab: InboxTab) => void;
setFacets: (facets: FacetSelection) => void;
};
@@ -43,6 +65,10 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<
>('InboxView', (props) => {
const panel = useSplitPanelOrThrow();
const userId = useUserId();
+ const navigate = useNavigate();
+ const routeParams = useRouteParams(inboxPreviewRoute);
+ const [previewSearch] = createSearchParams(inboxPreviewSearch);
+ const selectPreview = createPreviewSelectionGuard();
const initial = props.initialState ?? {};
const initialTab = initial.tab ?? 'signal';
const [state, setState] = makePersistedState(
@@ -60,8 +86,44 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<
})
);
+ const previewEntity = createMemo<PreviewPanelSelection | undefined>(() => {
+ const blockType = routeParams.blockType;
+ const previewId = routeParams.previewId;
+ if (typeof blockType !== 'string' || typeof previewId !== 'string') return;
+ return inboxPreviewSelection({ blockType, previewId }, previewSearch);
+ });
+ const navigatePreview = (entity: PreviewPanelSelection, replace = false) => {
+ const preview = inboxPreviewNavigation(entity);
+ navigate(
+ { route: inboxPreviewRoute, params: preview.params },
+ {
+ replace,
+ search: {
+ [INBOX_PREVIEW_SEARCH_NAMESPACE]: inboxPreviewSearchCodec.serialize(
+ preview.search
+ ),
+ },
+ }
+ );
+ };
+ const closePreview = () => navigate({ route: inboxSplitRoute, params: {} });
+ const openPreview = (entity: PreviewPanelSelection) => {
+ if (!selectPreview.canSelect(entity)) return false;
+ navigatePreview(entity);
+ return true;
+ };
+
+ createEffect(
+ on(previewEntity, (entity, previous) => {
+ if (selectPreview(entity)) return;
+ if (previous) navigatePreview(previous, true);
+ else navigate({ route: inboxSplitRoute, params: {} }, { replace: true });
+ })
+ );
+
const setTab = (tab: InboxTab) => {
if (state.tab === tab) return;
+ closePreview();
setState(
produce((draft) => {
@@ -78,6 +140,9 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<
return {
state,
setState,
+ previewEntity,
+ openPreview,
+ closePreview,
setTab,
setFacets,
};
diff --git a/apps/web/src/features/inbox-view/inbox-view.tsx b/apps/web/src/features/inbox-view/inbox-view.tsx
index 6ce80ed84b..4719e86130 100644
--- a/apps/web/src/features/inbox-view/inbox-view.tsx
+++ b/apps/web/src/features/inbox-view/inbox-view.tsx
@@ -3,16 +3,19 @@ import {
ViewBreadcrumbs,
ViewShell,
} from '@app/components/view-shell';
-import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
+import { SplitRouter } from '@app/lib/split-router';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
-import { PreviewPanel } from '@components/app/PreviewPanel';
+import {
+ PreviewPanel,
+ type PreviewPanelSelection,
+} from '@components/app/PreviewPanel';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { type EntityData, ListEntityMetadataQueryProvider } from '@entity';
+import { ListEntityMetadataQueryProvider } from '@entity';
import SpinnerIcon from '@phosphor/spinner.svg';
-import { createEffect, createSignal, onMount, Show, Suspense } from 'solid-js';
+import { createEffect, onMount, Show, Suspense } from 'solid-js';
import { HomeChatStart } from './components/HomeChatStart';
import { InboxListLayout } from './components/InboxHeader';
import { InboxList } from './components/InboxList';
@@ -34,8 +37,8 @@ function InboxFallback() {
}
function HomeListPane(props: {
- previewEntity: EntityData | undefined;
- onPreviewEntityChange: (entity: EntityData | undefined) => void;
+ previewEntity: PreviewPanelSelection | undefined;
+ onPreviewEntityChange: (entity: PreviewPanelSelection | undefined) => void;
onNewChat: () => void;
}) {
const shell = useViewShell();
@@ -78,27 +81,15 @@ function HomeReturnBreadcrumb(props: { onReturn: () => void }) {
function InboxViewRoot() {
const panel = useSplitPanelOrThrow();
- const orchestrator = useGlobalBlockOrchestrator();
- const { state, setTab } = useInboxView();
- const [previewEntity, setPreviewEntityState] = createSignal<EntityData>();
- const selectPreview = createPreviewSelectionGuard();
- const setPreviewEntity = (entity: EntityData | undefined) => {
- if (!selectPreview(entity)) return;
- setPreviewEntityState(entity);
- };
+ const { state, setState, previewEntity, openPreview, closePreview } =
+ useInboxView();
- let activeTab = state.tab;
createEffect(() => {
- const nextTab = state.tab;
- if (nextTab === activeTab) return;
- activeTab = nextTab;
- setPreviewEntity(undefined);
+ if (state.tab !== 'reminders') return;
+ setState('tab', 'signal');
+ setState('groupBy', 'date');
});
-
- createEffect(() => {
- if (state.tab === 'reminders') setTab('signal');
- });
- const newChat = () => setPreviewEntity(undefined);
+ const newChat = closePreview;
// The touch nav item and legacy touch view both call this "Notifications".
onMount(() =>
@@ -123,32 +114,20 @@ function InboxViewRoot() {
<ViewShell.Aside class="flex flex-col bg-panel">
<HomeListPane
previewEntity={previewEntity()}
- onPreviewEntityChange={setPreviewEntity}
+ onPreviewEntityChange={(entity) =>
+ entity ? openPreview(entity) : closePreview()
+ }
onNewChat={newChat}
/>
</ViewShell.Aside>
<ViewShell.Main class="overflow-hidden">
- <Show
- when={previewEntity()}
- fallback={
+ <SplitRouter.Outlet
+ fallback={() => (
<Suspense fallback={<InboxFallback />}>
<HomeChatStart />
</Suspense>
- }
- >
- {(entity) => (
- <Suspense>
- <PreviewPanel
- selectedEntity={entity()}
- orchestrator={orchestrator}
- splitPanelContext={panel}
- headerLeading={
- <HomeReturnBreadcrumb onReturn={newChat} />
- }
- />
- </Suspense>
)}
- </Show>
+ />
</ViewShell.Main>
</ViewShell.Root>
</div>
@@ -158,7 +137,9 @@ function InboxViewRoot() {
<ViewShell.Main>
<HomeListPane
previewEntity={previewEntity()}
- onPreviewEntityChange={setPreviewEntity}
+ onPreviewEntityChange={(entity) =>
+ entity ? openPreview(entity) : closePreview()
+ }
onNewChat={newChat}
/>
</ViewShell.Main>
@@ -171,6 +152,23 @@ function InboxViewRoot() {
);
}
+export function InboxDetailRouteView() {
+ const panel = useSplitPanelOrThrow();
+ const orchestrator = useGlobalBlockOrchestrator();
+ const { previewEntity, closePreview } = useInboxView();
+
+ return (
+ <Suspense>
+ <PreviewPanel
+ selectedEntity={previewEntity()}
+ orchestrator={orchestrator}
+ splitPanelContext={panel}
+ headerLeading={<HomeReturnBreadcrumb onReturn={closePreview} />}
+ />
+ </Suspense>
+ );
+}
+
/** Composable heterogeneous Inbox built on the shared view and Soup primitives. */
export function InboxView(props: InboxViewProps) {
return (
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index 23b2ee9fc9..3879e040b6 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -1,4 +1,11 @@
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { inboxPreviewNavigation } from '../inbox-view/inbox-preview-navigation';
+import { inboxPreviewSelection } from '../inbox-view/inbox-route';
+
+vi.mock('@core/mobile/isTouchDevice', () => ({
+ isTouchDevice: vi.fn(() => false),
+}));
const toastAlert = vi.hoisted(() => vi.fn());
vi.mock('@core/component/Toast/Toast', () => ({
@@ -113,6 +120,7 @@ import {
afterEach(() => {
setGlobalSplitManager(undefined);
vi.clearAllMocks();
+ vi.mocked(isTouchDevice).mockReturnValue(false);
});
describe('agent session search navigation', () => {
@@ -391,6 +399,57 @@ describe('calendar block navigation', () => {
});
describe('Drive document routing', () => {
+ it('keeps task documents as legacy task blocks on touch', async () => {
+ vi.mocked(isTouchDevice).mockReturnValue(true);
+ const openWithSplit = vi.fn(() => ({ status: 'unavailable' }));
+ setGlobalSplitManager({
+ activeSplit: vi.fn(),
+ getOrchestrator: vi.fn(() => ({})),
+ openWithSplit,
+ } as unknown as SplitManager);
+ await openEntityInSplitFromUnifiedList(
+ {
+ type: 'document',
+ id: 'task-1',
+ fileType: 'md',
+ subType: { type: 'task' },
+ } as EntityData,
+ {}
+ );
+ expect(openWithSplit).toHaveBeenCalledWith(
+ { type: 'task', id: 'task-1', params: undefined },
+ expect.any(Object)
+ );
+ });
+ it.each([
+ 'md',
+ 'pdf',
+ 'canvas',
+ 'code',
+ 'image',
+ 'video',
+ 'spreadsheet',
+ 'unknown',
+ ] as const)(
+ 'opens %s documents as legacy blocks on touch',
+ async (fileType) => {
+ vi.mocked(isTouchDevice).mockReturnValue(true);
+ const openWithSplit = vi.fn(() => ({ status: 'unavailable' }));
+ setGlobalSplitManager({
+ activeSplit: vi.fn(),
+ getOrchestrator: vi.fn(() => ({})),
+ openWithSplit,
+ } as unknown as SplitManager);
+ await openEntityInSplitFromUnifiedList(
+ { type: 'document', id: 'doc-1', fileType } as EntityData,
+ { openInNewSplit: true }
+ );
+ expect(openWithSplit).toHaveBeenCalledWith(
+ { type: fileType, id: 'doc-1', params: undefined },
+ expect.objectContaining({ preferNewSplit: true })
+ );
+ }
+ );
it.each(['md', 'pdf', 'canvas'] as const)(
'opens %s documents as canonical Drive content',
async (fileType) => {
@@ -439,6 +498,55 @@ describe('Drive document routing', () => {
);
});
+describe('Inbox calendar preview navigation', () => {
+ it.each([
+ { kind: 'allDay' as const, startDate: '2025-01-01', endDate: '2025-01-03' },
+ {
+ kind: 'timed' as const,
+ startsAt: '2025-01-01T12:00:00.000Z',
+ endsAt: '2025-01-01T13:00:00.000Z',
+ },
+ ])('round-trips $kind event times', (time) => {
+ const result = inboxPreviewNavigation({
+ type: 'calendar_event',
+ id: 'event-1',
+ time,
+ });
+ expect(result.search.calendarTimeKind).toBe(time.kind);
+ expect(inboxPreviewSelection(result.params, result.search)).toMatchObject({
+ type: 'calendar_event',
+ id: 'event-1',
+ time,
+ });
+ });
+});
+
+describe('Inbox channel preview navigation', () => {
+ it('preserves explicit message targets on whole-channel selections', () => {
+ const result = inboxPreviewNavigation({
+ type: 'channel',
+ id: 'channel-1',
+ target: { messageId: 'message-1', threadId: 'thread-1' },
+ });
+ expect(result.params).toEqual({
+ blockType: 'channel',
+ previewId: 'channel-1',
+ });
+ expect(result.search).toMatchObject({
+ targetMessageId: 'message-1',
+ targetThreadId: 'thread-1',
+ });
+ });
+ it('keeps untargeted channels at latest', () => {
+ expect(
+ inboxPreviewNavigation({ type: 'channel', id: 'channel-1' }).search
+ ).toMatchObject({
+ targetMessageId: '',
+ targetThreadId: '',
+ });
+ });
+});
+
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 8e84d2be7b..a50f8f0a33 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -40,6 +40,7 @@ import {
ENTITY_ID_DATA_ATTRIBUTE,
entityIdSelector,
} from '@core/dom-selectors';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import type { BlockOrchestrator } from '@core/orchestrator';
import type { DateValue } from '@core/util/date';
import { throwOnErr } from '@core/util/result';
@@ -690,7 +691,9 @@ export const openEntityInSplitFromUnifiedList = async (
// 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);
+ const driveDocument = !isTouchDevice()
+ ? driveDocumentFromContent(content)
+ : undefined;
let splitContent: SplitContent = driveDocument
? driveSplitContent({ kind: 'tab', tab: 'owned' }, driveDocument)
: { ...content, params };
diff --git a/apps/web/src/features/settings/Settings.tsx b/apps/web/src/features/settings/Settings.tsx
index 5b5f64061e..ec58f87c08 100644
--- a/apps/web/src/features/settings/Settings.tsx
+++ b/apps/web/src/features/settings/Settings.tsx
@@ -161,10 +161,9 @@ export function SettingsPanel(props: SettingsPanelProps) {
});
const selectRoutedTab = (tab: SettingsTab) => {
- selectTab(tab);
- if (!isMobile()) {
- splitNavigate(`/settings/${settingsTabToSlug(tab)}`);
- }
+ selectTab(tab, (next) => {
+ splitNavigate(`/settings/${settingsTabToSlug(next)}`);
+ });
};
// Helper to navigate to a tab by index
diff --git a/apps/web/src/features/tasks-view/components/TasksDetailView.tsx b/apps/web/src/features/tasks-view/components/TasksDetailView.tsx
index bb591b88ce..1a4a4549ee 100644
--- a/apps/web/src/features/tasks-view/components/TasksDetailView.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksDetailView.tsx
@@ -1,53 +1,24 @@
-import { EntityDetail } from '@app/components/entity-detail/EntityDetail';
-import { EntityDetailBreadcrumbItem } from '@app/components/entity-detail/EntityDetailBreadcrumbItem';
import { EntityDetailBreadcrumbSkeleton } from '@app/components/entity-detail/EntityDetailBreadcrumbSkeleton';
-import {
- EntityDetailNavigationStack,
- type EntityDetailNavigationStackEntry,
- useEntityDetailNavigationStack,
-} from '@app/components/entity-detail/EntityDetailNavigationStack';
+import type { EntityDetailTarget } from '@app/components/entity-detail/EntityDetailNavigationStack';
import { useListNavigationHotkeys } from '@app/components/entity-detail/use-list-navigation-hotkeys';
import { useListDetailNavigation } from '@app/components/list';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
+import { useRouteParams } from '@app/lib/split-router';
import { MarkdownDetailBreadcrumbItem } from '@block-md/component/MarkdownDetailBreadcrumbItem';
import { SidePanel } from '@components/app/side-panel';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { taskDetailRoute } from '@components/app/split-layout/split-router/app-routes';
import { toast } from '@core/component/Toast/Toast';
import {
ShareDialogContext,
ShareTrigger,
} from '@core/component/TopBar/ShareButton';
-import {
- createSignal,
- ErrorBoundary,
- For,
- Match,
- Show,
- Switch,
-} from 'solid-js';
+import { createSignal } from 'solid-js';
import { useTasksView } from '../tasks-view-context';
import type { TaskDetailTarget } from '../types';
-import { TaskDetail, TaskDetailBodyState } from './TaskDetail';
-
-type EntityDetailEntry = EntityDetailNavigationStackEntry;
-
-function TaskDetailAncestorBreadcrumbs() {
- const navigationStack = useEntityDetailNavigationStack();
- const ancestors = () => navigationStack.entries.slice(0, -1);
-
- return (
- <For each={ancestors()}>
- {(entry, index) => (
- <EntityDetailBreadcrumbItem entry={entry} order={index() + 1} />
- )}
- </For>
- );
-}
+import { TaskDetail } from './TaskDetail';
-function TaskDetailTopBar(props: {
- documentId: string;
- showTaskActions: boolean;
-}) {
+function TaskDetailTopBar(props: { documentId: string }) {
const panel = useSplitPanelOrThrow();
return (
@@ -57,40 +28,21 @@ function TaskDetailTopBar(props: {
fallback={<EntityDetailBreadcrumbSkeleton />}
/>
<div class="ml-auto flex shrink-0 items-center gap-2">
- <Show when={props.showTaskActions}>
- <ShareTrigger
- id={props.documentId}
- blockType="task"
- hotkeyScope={panel.splitHotkeyScope}
- />
- </Show>
+ <ShareTrigger
+ id={props.documentId}
+ blockType="task"
+ hotkeyScope={panel.splitHotkeyScope}
+ />
<SidePanel.Toggle />
</div>
</ViewShell.TopBar>
);
}
-function StackEntityDetail(props: { entry: EntityDetailEntry; order: number }) {
- return (
- <>
- <EntityDetailBreadcrumbItem entry={props.entry} order={props.order} />
- <EntityDetail target={props.entry.data} />
- </>
- );
-}
-
export function TasksDetailView(props: { task: TaskDetailTarget }) {
- const { source, openTask, closeTask } = useTasksView();
- const navigationStack = useEntityDetailNavigationStack();
+ const { source, openTask, closeTask, selectedTask } = useTasksView();
const panel = useSplitPanelOrThrow();
const [shareOpen, setShareOpen] = createSignal(false);
- const taskEntry = () =>
- navigationStack.entries.find(
- (entry) =>
- entry.data.type === 'document' && entry.data.id === props.task.id
- );
- const isTaskActive = () =>
- navigationStack.active()?.value === taskEntry()?.value;
const listNavigation = useListDetailNavigation({
currentId: () => props.task.id,
source,
@@ -107,9 +59,18 @@ export function TasksDetailView(props: { task: TaskDetailTarget }) {
});
useListNavigationHotkeys({
scopeId: panel.splitHotkeyScope,
- enabled: () => panel.isPanelActive() && isTaskActive(),
+ enabled: () =>
+ panel.isPanelActive() && selectedTask()?.id === props.task.id,
navigation: listNavigation,
});
+ const breadcrumbValue = () => `task:${props.task.id}`;
+ const metadata = (): EntityDetailTarget => ({
+ type: 'document',
+ id: props.task.id,
+ fileType: 'md',
+ subType: { type: 'task' },
+ fallbackName: props.task.fallbackName,
+ });
return (
<ShareDialogContext.Provider
@@ -119,65 +80,40 @@ export function TasksDetailView(props: { task: TaskDetailTarget }) {
close: () => setShareOpen(false),
}}
>
- <TaskDetailAncestorBreadcrumbs />
<SidePanel.Root>
<div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
- <TaskDetailTopBar
- documentId={props.task.id}
- showTaskActions={isTaskActive()}
- />
+ <TaskDetailTopBar documentId={props.task.id} />
<div class="relative min-h-0 min-w-0 flex-1">
- <EntityDetailNavigationStack.Outlet>
- {(entry, state) => (
- <Switch>
- <Match when={entry.value === taskEntry()?.value}>
- <TaskDetail
- task={props.task}
- shareOpen={shareOpen()}
- onShareOpenChange={setShareOpen}
- >
- {(context) => (
- <MarkdownDetailBreadcrumbItem
- value={entry.value}
- metadata={entry.data}
- order={state.entries.length}
- documentId={props.task.id}
- kind="task"
- fallbackName={props.task.fallbackName}
- ownerId={context.data.metadata.owner}
- projectId={
- context.data.metadata.projectId ?? undefined
- }
- onClose={closeTask}
- onDuplicate={(id, name) =>
- openTask({ id, fallbackName: name })
- }
- />
- )}
- </TaskDetail>
- </Match>
- <Match when={true}>
- <ErrorBoundary
- fallback={(error, reset) => (
- <TaskDetailBodyState
- error={error}
- actionLabel="Reset"
- onAction={reset}
- />
- )}
- >
- <StackEntityDetail
- entry={entry}
- order={state.entries.length}
- />
- </ErrorBoundary>
- </Match>
- </Switch>
+ <TaskDetail
+ task={props.task}
+ shareOpen={shareOpen()}
+ onShareOpenChange={setShareOpen}
+ >
+ {(context) => (
+ <MarkdownDetailBreadcrumbItem
+ value={breadcrumbValue()}
+ metadata={metadata()}
+ order={1}
+ documentId={props.task.id}
+ kind="task"
+ fallbackName={props.task.fallbackName}
+ ownerId={context.data.metadata.owner}
+ projectId={context.data.metadata.projectId ?? undefined}
+ onClose={closeTask}
+ onDuplicate={(id, name) =>
+ openTask({ id, fallbackName: name })
+ }
+ />
)}
- </EntityDetailNavigationStack.Outlet>
+ </TaskDetail>
</div>
</div>
</SidePanel.Root>
</ShareDialogContext.Provider>
);
}
+
+export function TasksDetailRouteView() {
+ const params = useRouteParams(taskDetailRoute);
+ return <TasksDetailView task={{ id: params.taskId }} />;
+}
diff --git a/apps/web/src/features/tasks-view/tasks-view-context.tsx b/apps/web/src/features/tasks-view/tasks-view-context.tsx
index 90dbbc332c..d2de9ef216 100644
--- a/apps/web/src/features/tasks-view/tasks-view-context.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx
@@ -1,8 +1,4 @@
-import {
- type EntityDetailNavigationOptions,
- entityDetailTarget,
- useEntityDetailNavigationStack,
-} from '@app/components/entity-detail/EntityDetailNavigationStack';
+import type { EntityDetailNavigationOptions } from '@app/components/entity-detail/EntityDetailNavigationStack';
import {
createListController,
type ListActivation,
@@ -12,15 +8,28 @@ import {
import { setSidebarSectionCollapsed } from '@app/components/view-shell';
import { normalizeFacetSelection } from '@app/features/soup';
import { makePersistedState } from '@app/lib/persistence';
+import { useNavigate, useRouteParams } from '@app/lib/split-router';
+import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import {
useSplitPanelOrThrow,
withSplitPanelOwner,
} from '@components/app/split-layout/layoutUtils';
+import {
+ taskDetailRoute,
+ tasksSplitRoute,
+} from '@components/app/split-layout/split-router/app-routes';
import { createAssertedContextProvider } from '@core/context/createContext';
import { useUserId } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';
import type { ContextProviderProps } from '@solid-primitives/context';
-import { type Accessor, onCleanup } from 'solid-js';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ on,
+ onCleanup,
+} from 'solid-js';
import {
createStore,
produce,
@@ -90,7 +99,9 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
TasksViewProviderProps
>('TasksView', (props) => {
const panel = useSplitPanelOrThrow();
- const navigationStack = useEntityDetailNavigationStack();
+ const navigate = useNavigate();
+ const routeParams = useRouteParams(taskDetailRoute);
+ const selectPreview = createPreviewSelectionGuard();
const userId = useUserId();
const tagSets = useTagSets();
const tagSetsReady = useTagSetsReady();
@@ -161,49 +172,56 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<
});
};
- const selectedTask = (): TaskDetailTarget | undefined => {
- const taskEntry = navigationStack.entries.find(
- (entry) =>
- entry.data.type === 'document' && entry.data.subType?.type === 'task'
+ const selectedTask = createMemo<TaskDetailTarget | undefined>(() => {
+ const taskId = routeParams.taskId;
+ return typeof taskId === 'string' ? { id: taskId } : undefined;
+ });
+ const taskSelection = (taskId: string) => ({
+ type: 'document' as const,
+ id: taskId,
+ fileType: 'md' as const,
+ subType: { type: 'task' as const },
+ });
+ const opensInline = (options?: EntityDetailNavigationOptions) => {
+ const event = options?.event;
+ return (
+ !isTouchDevice() &&
+ !(event?.shiftKey || event?.metaKey || event?.ctrlKey || event?.altKey)
);
- if (!taskEntry) return undefined;
-
- if (
- taskEntry.data.type !== 'document' ||
- taskEntry.data.subType?.type !== 'task'
- ) {
- return undefined;
- }
- return {
- id: taskEntry.data.id,
- fallbackName: taskEntry.data.fallbackName,
- };
};
-
+ const closeTask = () => navigate({ route: tasksSplitRoute, params: {} });
const openTask = (
task: TaskDetailTarget,
options?: EntityDetailNavigationOptions
) => {
- const target = entityDetailTarget.document({
- id: task.id,
- fileType: 'md',
- subType: { type: 'task' },
- fallbackName: task.fallbackName,
- });
- if (!navigationStack.shouldNavigate(target, options)) return false;
- // A refused reset already alerted; there is nothing to fall back to.
- if (!navigationStack.reset(target)) return true;
- const row = source
- .items()
- .find((item) => item.kind === 'entity' && item.entity.id === task.id);
- if (row) {
- list.focus.set(row.id, { reason: 'programmatic', force: true });
- list.selection.setAnchor(row.id);
- }
-
+ if (!opensInline(options)) return false;
+ if (!selectPreview.canSelect(taskSelection(task.id))) return true;
+ navigate({ route: taskDetailRoute, params: { taskId: task.id } });
return true;
};
- const closeTask = navigationStack.clear;
+
+ createEffect(
+ on(selectedTask, (task, previous) => {
+ if (!selectPreview(task ? taskSelection(task.id) : undefined)) {
+ if (previous) {
+ navigate(
+ { route: taskDetailRoute, params: { taskId: previous.id } },
+ { replace: true }
+ );
+ } else {
+ navigate({ route: tasksSplitRoute, params: {} }, { replace: true });
+ }
+ return;
+ }
+ if (!task) return;
+ const row = source
+ .items()
+ .find((item) => item.kind === 'entity' && item.entity.id === task.id);
+ if (!row) return;
+ list.focus.set(row.id, { reason: 'programmatic', force: true });
+ list.selection.setAnchor(row.id);
+ })
+ );
const setTab = (tab: TaskTab) => {
closeTask();
diff --git a/apps/web/src/features/tasks-view/tasks-view.tsx b/apps/web/src/features/tasks-view/tasks-view.tsx
index 9a35864f71..ce89745683 100644
--- a/apps/web/src/features/tasks-view/tasks-view.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view.tsx
@@ -1,21 +1,10 @@
-import {
- EntityDetailNavigationStack,
- useEntityDetailNavigationStack,
-} from '@app/components/entity-detail/EntityDetailNavigationStack';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
+import { SplitRouter } from '@app/lib/split-router';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
import { ListEntityMetadataQueryProvider } from '@entity';
import SpinnerIcon from '@phosphor/spinner.svg';
-import {
- createSignal,
- Match,
- onMount,
- type ParentProps,
- Suspense,
- Switch,
-} from 'solid-js';
-import { TasksDetailView } from './components/TasksDetailView';
+import { createSignal, onMount, type ParentProps, Suspense } from 'solid-js';
import {
TasksHeader,
TasksTopBar,
@@ -40,18 +29,17 @@ function TasksListFallback() {
}
function TasksViewBreadcrumbs(props: ParentProps) {
- const { closeTask } = useTasksView();
- const navigationStack = useEntityDetailNavigationStack();
+ const { closeTask, selectedTask } = useTasksView();
+ const value = () => {
+ const task = selectedTask();
+ return task ? `task:${task.id}` : 'tasks-view';
+ };
return (
<ViewBreadcrumbs.Root
- value={navigationStack.active()?.value ?? 'tasks-view'}
- onChange={(value) => {
- if (value === 'tasks-view') {
- closeTask();
- return;
- }
- navigationStack.popTo(value);
+ value={value()}
+ onChange={(next) => {
+ if (next === 'tasks-view') closeTask();
}}
>
<TaskViewBreadcrumbItem />
@@ -62,11 +50,24 @@ function TasksViewBreadcrumbs(props: ParentProps) {
function TasksViewRoot() {
const panel = useSplitPanelOrThrow();
- const { selectedTask } = useTasksView();
const [listElement, setListElement] = createSignal<HTMLDivElement>();
onMount(() => panel.handle.setDisplayName('Tasks'));
+ const list = () => (
+ <>
+ <TasksTopBar />
+ <ViewShell.Header>
+ <TasksHeader onSearchEscape={() => listElement()?.focus()} />
+ </ViewShell.Header>
+ <ViewShell.Content>
+ <Suspense fallback={<TasksListFallback />}>
+ <TaskList ref={setListElement} />
+ </Suspense>
+ </ViewShell.Content>
+ </>
+ );
+
return (
<SplitPanel.Root>
<SplitPanel.Body>
@@ -80,22 +81,7 @@ function TasksViewRoot() {
<TasksSidebar />
</ViewShell.Aside>
<ViewShell.Main>
- <Switch>
- <Match when={selectedTask()}>
- {(task) => <TasksDetailView task={task()} />}
- </Match>
- <Match when={!selectedTask()}>
- <TasksTopBar />
- <ViewShell.Header>
- <TasksHeader onSearchEscape={() => listElement()?.focus()} />
- </ViewShell.Header>
- <ViewShell.Content>
- <Suspense fallback={<TasksListFallback />}>
- <TaskList ref={setListElement} />
- </Suspense>
- </ViewShell.Content>
- </Match>
- </Switch>
+ <SplitRouter.Outlet fallback={list} />
</ViewShell.Main>
</ViewShell.Root>
</SplitPanel.Body>
@@ -106,14 +92,12 @@ function TasksViewRoot() {
/** Production Tasks view. */
export function TasksView(props: TasksViewProps) {
return (
- <EntityDetailNavigationStack.Root>
- <ListEntityMetadataQueryProvider>
- <TasksViewProvider initialState={props.initialState}>
- <TasksViewBreadcrumbs>
- <TasksViewRoot />
- </TasksViewBreadcrumbs>
- </TasksViewProvider>
- </ListEntityMetadataQueryProvider>
- </EntityDetailNavigationStack.Root>
+ <ListEntityMetadataQueryProvider>
+ <TasksViewProvider initialState={props.initialState}>
+ <TasksViewBreadcrumbs>
+ <TasksViewRoot />
+ </TasksViewBreadcrumbs>
+ </TasksViewProvider>
+ </ListEntityMetadataQueryProvider>
);
}
diff --git a/apps/web/src/lib/core/constant/SettingsState.test.tsx b/apps/web/src/lib/core/constant/SettingsState.test.tsx
index 0fe351b5cd..38eab0e795 100644
--- a/apps/web/src/lib/core/constant/SettingsState.test.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.test.tsx
@@ -2,6 +2,11 @@ import {
MobileSettingsProvider,
useMobileSettings,
} from '@app/features/settings/context/mobile-settings';
+import {
+ createSplitRouter,
+ type SplitRouterLayoutSnapshot,
+} from '@app/lib/split-router';
+import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';
import {
setActiveTabId as setSplitActiveTabId,
activeTabId as splitActiveTabId,
@@ -13,6 +18,7 @@ import { useSettingsState } from './SettingsState';
const mocks = vi.hoisted(() => ({
mobile: true,
hasSettingsSplit: false,
+ updateCurrentEntry: vi.fn(),
removeSplit: vi.fn(),
openWithSplit: vi.fn(),
replaceAllSplits: vi.fn(),
@@ -34,6 +40,7 @@ vi.mock('@app/signal/splitLayout', () => ({
]
: [],
removeSplit: mocks.removeSplit,
+ getSplit: () => ({ updateCurrentEntry: mocks.updateCurrentEntry }),
}),
}));
vi.mock('@components/app/split-layout/layout', () => ({
@@ -85,6 +92,55 @@ beforeEach(() => {
afterEach(cleanup);
describe('settings entry points', () => {
+ it('routes desktop tab selections without prewriting entries and retains A-B-A history', () => {
+ mocks.mobile = false;
+ mocks.hasSettingsSplit = true;
+ const { state } = mountSettings();
+ let entries: SplitRouterLayoutSnapshot<string>['entries'] = [];
+ const router = createSplitRouter({
+ routes: { definitions: [{ id: 'settings', path: 'settings/:tab' }] },
+ location: createMemorySplitRouterLocation('/settings/account'),
+ layout: {
+ snapshot: () => ({ entries }),
+ reconcile: (next) => {
+ entries = next.map((entry) => ({
+ ...entry,
+ splitId: 'settings-split',
+ }));
+ },
+ open: ({ location }) => {
+ entries = [{ splitId: 'settings-split', location }];
+ },
+ updateCurrentEntry: (id, update) => {
+ entries = entries.map((entry) =>
+ entry.splitId === id ? { ...update(entry), splitId: id } : entry
+ );
+ },
+ activate: () => {},
+ subscribe: () => () => {},
+ },
+ });
+ const navigateTab = (tab: string) => {
+ expect(mocks.updateCurrentEntry).not.toHaveBeenCalled();
+ router.navigate('settings-split', `/settings/${tab.toLowerCase()}`);
+ };
+ state.selectTab('Appearance', navigateTab);
+ state.selectTab('Account', navigateTab);
+ expect(router.history('settings-split')?.entries).toHaveLength(3);
+ router.navigate('settings-split', -1);
+ expect(entries[0].location.route.matches[0].params.tab).toBe('appearance');
+ router.navigate('settings-split', -1);
+ expect(entries[0].location.route.matches[0].params.tab).toBe('account');
+ router.dispose();
+ });
+
+ it('ignores routed navigation when selecting a mobile sheet page', () => {
+ const { state, mobile } = mountSettings();
+ const navigateTab = vi.fn();
+ state.selectTab('Appearance', navigateTab);
+ expect(mobile.page()).toBe('Appearance');
+ expect(navigateTab).not.toHaveBeenCalled();
+ });
it.each([true, false])(
'requires the provider when mobile is %s',
(mobile) => {
diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsx
index a5ae8533c4..5618a86793 100644
--- a/apps/web/src/lib/core/constant/SettingsState.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.tsx
@@ -218,14 +218,23 @@ export const useSettingsState = () => {
};
// Mobile selection belongs to the sheet, including while it is closed.
- // Desktop selection drives the split's URL through `contentUrlSegments`.
- const selectTab = (tab: SettingsTab) => {
+ // Routed panels supply navigation so the router owns the entry/history write.
+ // Other entry points retain the legacy manager path until they are migrated.
+ const selectTab = (
+ tab: SettingsTab,
+ navigateTab?: (tab: SettingsTab) => void
+ ) => {
if (isMobile()) {
mobileSettings.selectPage(tab);
return;
}
+ if (navigateTab) {
+ navigateTab(tab);
+ return;
+ }
+
setActiveTabId(tab);
updateSettingsRoute(tab);
};
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 77393c3463..b4b9733598 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: true,
+ default: DEV_MODE_ENV || undefined,
});
/**
diff --git a/apps/web/src/lib/core/tests/featureFlags.test.ts b/apps/web/src/lib/core/tests/featureFlags.test.ts
index 64fc2d4b33..09e5b40a09 100644
--- a/apps/web/src/lib/core/tests/featureFlags.test.ts
+++ b/apps/web/src/lib/core/tests/featureFlags.test.ts
@@ -1,4 +1,39 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const remoteFlag = vi.hoisted(() => vi.fn());
+vi.mock('@app/lib/analytics', () => ({
+ analytics: { posthog: { isFeatureEnabled: remoteFlag } },
+}));
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ remoteFlag.mockReset();
+});
+
+describe('new app views rollout', () => {
+ it('allows PostHog to disable and enable the production flag', async () => {
+ vi.stubEnv('MODE', 'production');
+ vi.stubEnv('VITE_ENABLE_NEW_APP_VIEWS', '');
+ vi.resetModules();
+ const { enableNewAppViews, isFeatureEnabled } = await import(
+ '../constant/featureFlags'
+ );
+ expect(enableNewAppViews.override).toBeUndefined();
+ remoteFlag.mockReturnValue(false);
+ expect(isFeatureEnabled(enableNewAppViews)).toBe(false);
+ remoteFlag.mockReturnValue(true);
+ expect(isFeatureEnabled(enableNewAppViews)).toBe(true);
+ });
+
+ it('enables local development by default', async () => {
+ vi.stubEnv('MODE', 'development');
+ vi.stubEnv('VITE_ENABLE_NEW_APP_VIEWS', '');
+ vi.resetModules();
+ const { enableNewAppViews } = await import('../constant/featureFlags');
+ expect(enableNewAppViews.override).toBe(true);
+ });
+});
import { resolveFeatureFlag } from '../constant/featureFlags';
diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.md
index 12f4293145..de5e0a7e8a 100644
--- a/apps/web/src/lib/split-router/README.md
+++ b/apps/web/src/lib/split-router/README.md
@@ -10,8 +10,8 @@ stay outside this library.
`SplitRoutesManifest`. A router compiles its own manifest once and exposes it as
`router.routes`; there is no global runtime cache.
- `defineRoute()` infers node-local callback and synchronous Standard Schema
- output types, including `remountKey`. `defineRoutes()` preserves the static
- tree and adds ancestor types to references taken from that tree.
+ output types, including `remountKey`, and types descendant references relative
+ to that root. `defineRoutes()` assembles the static tree and rebinds ancestry.
- `useRouteParams(route)` reads only that node's params. `useParams(route)` reads
the merged branch through that node; `useParams()` still reads the entire
active branch.
@@ -26,21 +26,19 @@ stay outside this library.
## Typed nested routes
```ts
-const routes = defineRoutes({
- definitions: [defineRoute({
- id: 'folder',
- path: 'drive/folder/:folderId',
- params: z.object({ folderId: z.string() }),
- children: [defineRoute({
- id: 'document',
- path: 'document/:documentId',
- params: z.object({ documentId: z.string() }),
- remountKey: ({ documentId }) => documentId,
- })],
+export const folder = defineRoute({
+ id: 'folder',
+ path: 'drive/folder/:folderId',
+ params: z.object({ folderId: z.string() }),
+ children: [defineRoute({
+ id: 'document',
+ path: 'document/:documentId',
+ params: z.object({ documentId: z.string() }),
+ remountKey: ({ documentId }) => documentId,
})],
});
-const folder = routes.definitions[0];
-const document = folder.children[0];
+export const document = folder.children[0];
+export const routes = defineRoutes({ definitions: [folder] });
navigate({
route: document,
@@ -50,15 +48,16 @@ const branch = useParams(document); // folderId + documentId
const local = useRouteParams(document); // documentId only
```
-`defineRoutes` returns the same objects: it does not clone, mutate, compile, or
-cache the tree. Its ancestry metadata exists only in TypeScript. Take references
-from its returned tree to get inherited types; previously declared child variables
-retain their original local-only types. Use `defineRoute` at nodes with callbacks
-so their schema outputs provide contextual parameter types.
+Both helpers return the same objects: they do not clone, mutate, compile, or
+cache the tree. Ancestry metadata exists only in TypeScript. Export root definitions
+directly and take descendant references through their named parent; positional
+aliases from `routes.definitions` are unnecessary. A separately declared child
+variable cannot acquire knowledge of a parent that later adopts it. Use `defineRoute`
+at nodes with callbacks so schema outputs provide contextual parameter types.
-Tree-bound destinations require the complete branch params, including when opening
-another pane. Standalone `defineRoute` references remain local-only and may inherit
-matching ancestor values from the current pane. Explicit destination params override
+Parent-bound destinations require the complete branch params, including when opening
+another pane. A separately declared child reference knows only its own subtree and
+may inherit matching ancestor values from the current pane. Explicit destination params override
those inherited values before each node's serializer runs. Serializers can therefore
receive additional branch fields; serialize the fields owned by that node. Transformed
outputs such as `Date` still require `serializeParams` and are not revalidated as inputs.
@@ -138,7 +137,10 @@ ignored.
Middleware runs for proposed entries and may redirect synchronously or
asynchronously. Synchronous navigation stays synchronous when no reservation wait
is necessary. Signals cancel superseded work; middleware should honor them when
-possible.
+possible. For initial and external navigation, `externalSearch` contains the raw
+incoming URL query snapshot, unchanged across redirects. Use it for application
+compatibility normalization; `to.location.search` remains the proposed pane's
+namespaced search. Local navigation does not inherit stale external query data.
Ordinary middleware errors are logged and fall back to the original valid
proposal, which still passes claim arbitration. Abort errors do not fall back.
diff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.ts
index dc954a4f4e..5970b55703 100644
--- a/apps/web/src/lib/split-router/index.ts
+++ b/apps/web/src/lib/split-router/index.ts
@@ -65,6 +65,7 @@ export {
} from './solid';
export type {
BrowserHistoryIntent,
+ DefinedSplitRoute,
DefinedSplitRoutes,
InferSplitRouteBranchParams,
InferSplitRouteNavigationParams,
diff --git a/apps/web/src/lib/split-router/location-sync.ts b/apps/web/src/lib/split-router/location-sync.ts
index ff9b483bfa..f1b19bedb8 100644
--- a/apps/web/src/lib/split-router/location-sync.ts
+++ b/apps/web/src/lib/split-router/location-sync.ts
@@ -50,8 +50,9 @@ export function createLocationSync(options: {
const signature = externalLocationSignature(next);
if (
- signature === externalLocationSignature(options.location.read()) ||
- outbound.includes(signature)
+ (outbound.length === 0 &&
+ signature === externalLocationSignature(options.location.read())) ||
+ outbound.at(-1) === signature
) {
return;
}
@@ -63,11 +64,17 @@ export function createLocationSync(options: {
return {
acknowledge(external) {
const signature = externalLocationSignature(external);
- const index = outbound.indexOf(signature);
+ const index = outbound.lastIndexOf(signature);
- if (index < 0) return false;
+ if (index < 0) {
+ outbound.length = 0;
+ return false;
+ }
- outbound.splice(index, 1);
+ // Location adapters may coalesce writes (last transition wins). Once a
+ // newer write is observed, earlier signatures cannot remain echo tokens:
+ // a later Back to one of those URLs is genuine external navigation.
+ outbound.splice(0, index + 1);
const desiredSignature = externalLocationSignature(desired);
if (
diff --git a/apps/web/src/lib/split-router/middleware.ts b/apps/web/src/lib/split-router/middleware.ts
index c535ff0492..a1a2793d25 100644
--- a/apps/web/src/lib/split-router/middleware.ts
+++ b/apps/web/src/lib/split-router/middleware.ts
@@ -19,6 +19,7 @@ type BatchRequest = {
from?: readonly SplitRouterEntry[];
to: SplitRouterEntry[];
cause: SplitRouterMiddlewareRequest['cause'];
+ externalSearch?: string;
signal: AbortSignal;
};
@@ -102,6 +103,7 @@ export function runSplitRouterMiddleware(
from: request.from,
to: current,
path,
+ externalSearch: request.externalSearch,
cause: request.cause,
signal: request.signal,
redirect: (to) => ({ type: 'redirect', to }),
@@ -156,6 +158,7 @@ export function prepareEntries(
from: request.from?.[index],
to: entry,
cause: request.cause,
+ externalSearch: request.externalSearch,
signal: request.signal,
})
);
diff --git a/apps/web/src/lib/split-router/router.ts b/apps/web/src/lib/split-router/router.ts
index 0a1b3b62cc..5352eb95c0 100644
--- a/apps/web/src/lib/split-router/router.ts
+++ b/apps/web/src/lib/split-router/router.ts
@@ -35,6 +35,7 @@ type CommitOptions = {
type LayoutTransition = {
entries: SplitRouterEntry[];
cause: 'initial' | 'external' | 'layout';
+ externalSearch?: string;
apply: (entries: SplitRouterEntry[]) => void;
};
@@ -214,6 +215,7 @@ export function createSplitRouter<TSplitId>(
from: transition.cause === 'initial' ? undefined : accepted,
to: transition.entries,
cause: transition.cause,
+ externalSearch: transition.externalSearch,
signal: controller.signal,
});
@@ -246,12 +248,12 @@ export function createSplitRouter<TSplitId>(
transitionLayout({
entries: decoded.entries,
cause,
+ externalSearch: decoded.externalLocation.search,
apply: applyDecoded,
});
};
accepted = layout.entries();
- applyInbound(options.location.read(), 'initial');
const applyPrepared = (
original: SplitRouterEntry[],
@@ -268,7 +270,10 @@ export function createSplitRouter<TSplitId>(
preserveHash: false,
preserveExternalSearch: false,
});
- notifyLayoutChanges(before, accepted);
+ const becameReady = !ready;
+ ready = true;
+ if (becameReady) notify();
+ else notifyLayoutChanges(before, accepted);
};
const onLayoutChange = (history: BrowserHistoryIntent) => {
@@ -530,7 +535,10 @@ export function createSplitRouter<TSplitId>(
search(splitId, namespace) {
assertSafeSearchName(namespace, 'namespace');
- return findEntry(splitId)?.location?.search?.[namespace];
+ const search = findEntry(splitId)?.location?.search;
+ return search && Object.hasOwn(search, namespace)
+ ? search[namespace]
+ : undefined;
},
canGo(splitId, delta) {
@@ -674,5 +682,8 @@ export function createSplitRouter<TSplitId>(
},
};
+ // Observe synchronous canonicalization writes during initialization, so their
+ // echoes cannot later be mistaken for a browser Back navigation.
+ applyInbound(options.location.read(), 'initial');
return router;
}
diff --git a/apps/web/src/lib/split-router/routes.ts b/apps/web/src/lib/split-router/routes.ts
index ab5ca18e55..7e2fcb47fd 100644
--- a/apps/web/src/lib/split-router/routes.ts
+++ b/apps/web/src/lib/split-router/routes.ts
@@ -2,6 +2,7 @@ import type { StandardSchemaV1 } from '@standard-schema/spec';
import { compileRoutePattern, type RoutePattern } from './path';
import { assertSafeSearchName } from './search';
import type {
+ DefinedSplitRoute,
DefinedSplitRoutes,
InferSplitRouteParams,
SplitRouteClaim,
@@ -44,9 +45,11 @@ export function defineRoute<
definition: TDefinition & { params: TParamsSchema } & RouteParamCallbacks<
StandardSchemaV1.InferOutput<TParamsSchema>
>
-): TDefinition & { params: TParamsSchema } & RouteParamCallbacks<
- StandardSchemaV1.InferOutput<TParamsSchema>
- >;
+): DefinedSplitRoute<
+ TDefinition & { params: TParamsSchema } & RouteParamCallbacks<
+ StandardSchemaV1.InferOutput<TParamsSchema>
+ >
+>;
export function defineRoute<
const TPath extends string,
const TAliases extends readonly string[] | undefined,
@@ -59,7 +62,15 @@ export function defineRoute<
} & RouteParamCallbacks<
InferSplitRouteParams<{ path: TPath; aliases: TAliases }>
>
-): TDefinition & { path: TPath; aliases: TAliases };
+): DefinedSplitRoute<
+ TDefinition & {
+ path: TPath;
+ aliases: TAliases;
+ params?: undefined;
+ } & RouteParamCallbacks<
+ InferSplitRouteParams<{ path: TPath; aliases: TAliases }>
+ >
+>;
export function defineRoute<
const TPath extends string,
const TDefinition extends SplitRouteDefinitionConstraint,
@@ -69,10 +80,17 @@ export function defineRoute<
aliases?: undefined;
params?: undefined;
} & RouteParamCallbacks<InferSplitRouteParams<{ path: TPath }>>
-): TDefinition & { path: TPath };
+): DefinedSplitRoute<
+ TDefinition & {
+ path: TPath;
+ aliases?: undefined;
+ params?: undefined;
+ } & RouteParamCallbacks<InferSplitRouteParams<{ path: TPath }>>
+>;
export function defineRoute(
definition: SplitRouteDefinitionConstraint
-): SplitRouteDefinitionConstraint {
+): unknown {
+ // The overloads add phantom ancestry; runtime declarations remain untouched.
return definition;
}
diff --git a/apps/web/src/lib/split-router/search.ts b/apps/web/src/lib/split-router/search.ts
index d8da3a968c..da3cc43882 100644
--- a/apps/web/src/lib/split-router/search.ts
+++ b/apps/web/src/lib/split-router/search.ts
@@ -45,9 +45,12 @@ export function parseSplitSearch(value: string): Map<number, SplitSearchState> {
}
const namespaces = splits.get(splitIndex) ?? {};
- const fields = namespaces[namespace] ?? {};
+ const fields = Object.hasOwn(namespaces, namespace)
+ ? namespaces[namespace]!
+ : {};
- fields[field] = [...(fields[field] ?? []), fieldValue];
+ const values = Object.hasOwn(fields, field) ? fields[field]! : [];
+ fields[field] = [...values, fieldValue];
namespaces[namespace] = fields;
splits.set(splitIndex, namespaces);
}
@@ -153,7 +156,10 @@ export function updateSearchState(
for (const [namespace, update] of Object.entries(updates ?? {})) {
assertSafeSearchName(namespace, 'namespace');
- const current = next.search?.[namespace];
+ const current =
+ next.search && Object.hasOwn(next.search, namespace)
+ ? next.search[namespace]
+ : undefined;
const requested = typeof update === 'function' ? update(current) : update;
next = withSearchNamespace(
diff --git a/apps/web/src/lib/split-router/tests/location-sync.test.ts b/apps/web/src/lib/split-router/tests/location-sync.test.ts
index d650027935..bdb11bd06c 100644
--- a/apps/web/src/lib/split-router/tests/location-sync.test.ts
+++ b/apps/web/src/lib/split-router/tests/location-sync.test.ts
@@ -43,19 +43,41 @@ describe('external location synchronization', () => {
expect(acknowledge(parseExternalLocation('/item/external'))).toBe(false);
});
- it('repairs stale acknowledgments without pushing another history entry', () => {
+ it('expires coalesced writes so a later Back is not swallowed', () => {
const { commit, navigate, acknowledge } = setup();
navigate('first');
navigate('second');
- expect(commit).toHaveBeenCalledTimes(2);
expect(acknowledge(parseExternalLocation('/item/second'))).toBe(true);
+ expect(acknowledge(parseExternalLocation('/item/first'))).toBe(false);
+ expect(commit).toHaveBeenCalledTimes(2);
+ });
+
+ it('accepts ordered echoes without additional writes', () => {
+ const { commit, navigate, acknowledge } = setup();
+ navigate('first');
+ navigate('second');
expect(acknowledge(parseExternalLocation('/item/first'))).toBe(true);
- expect(commit).toHaveBeenCalledTimes(3);
- expect(commit).toHaveBeenLastCalledWith(
- parseExternalLocation('/item/second'),
- { history: 'replace' }
- );
expect(acknowledge(parseExternalLocation('/item/second'))).toBe(true);
+ expect(acknowledge(parseExternalLocation('/item/first'))).toBe(false);
+ expect(commit).toHaveBeenCalledTimes(2);
+ });
+
+ it('allows a newer request to supersede an outstanding write even at the current URL', () => {
+ const { commit, navigate, acknowledge } = setup();
+ navigate('first');
+ navigate('initial');
+ expect(commit).toHaveBeenCalledTimes(2);
+ expect(acknowledge(parseExternalLocation('/item/initial'))).toBe(true);
+ expect(acknowledge(parseExternalLocation('/item/first'))).toBe(false);
+ });
+
+ it('expires older duplicate signatures when the latest request repeats a URL', () => {
+ const { commit, navigate, acknowledge } = setup();
+ navigate('first');
+ navigate('second');
+ navigate('first');
expect(commit).toHaveBeenCalledTimes(3);
+ expect(acknowledge(parseExternalLocation('/item/first'))).toBe(true);
+ expect(acknowledge(parseExternalLocation('/item/second'))).toBe(false);
});
});
diff --git a/apps/web/src/lib/split-router/tests/middleware.test.ts b/apps/web/src/lib/split-router/tests/middleware.test.ts
index 9bf7c1391e..8d36c8c3c1 100644
--- a/apps/web/src/lib/split-router/tests/middleware.test.ts
+++ b/apps/web/src/lib/split-router/tests/middleware.test.ts
@@ -76,10 +76,12 @@ describe('split router middleware', () => {
it('awaits middleware and restarts the pipeline after a redirect', async () => {
const visits: string[] = [];
+ const searches: (string | undefined)[] = [];
const middleware: SplitRouterMiddleware[] = [
- async ({ path }) => {
+ async ({ path, externalSearch }) => {
await Promise.resolve();
visits.push(`preload:${path}`);
+ searches.push(externalSearch);
},
({ to, redirect }) => {
const routeId = rootRouteMatch(to.location.route)?.id;
@@ -94,7 +96,8 @@ describe('split router middleware', () => {
{ routes, handlers: middleware },
{
to: legacyEntry,
- cause: 'navigate',
+ externalSearch: '?legacy=first&legacy=last',
+ cause: 'external',
signal: new AbortController().signal,
}
);
@@ -105,6 +108,10 @@ describe('split router middleware', () => {
'preload:/drive/md/document-1',
'redirect:drive',
]);
+ expect(searches).toEqual([
+ '?legacy=first&legacy=last',
+ '?legacy=first&legacy=last',
+ ]);
expect(result).toEqual({
location: {
route: {
diff --git a/apps/web/src/lib/split-router/tests/router.test.ts b/apps/web/src/lib/split-router/tests/router.test.ts
index b4b673d2a7..052ca09667 100644
--- a/apps/web/src/lib/split-router/tests/router.test.ts
+++ b/apps/web/src/lib/split-router/tests/router.test.ts
@@ -121,6 +121,92 @@ const settle = () => new Promise<void>((resolve) => queueMicrotask(resolve));
afterEach(() => vi.restoreAllMocks());
describe('split router', () => {
+ it('becomes ready when a synchronous layout change supersedes async initialization', async () => {
+ const layout = createLayout();
+ let release!: () => void;
+ let initialSignal: AbortSignal | undefined;
+ const initial = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const router = createSplitRouter({
+ routes,
+ layout,
+ location: createMemorySplitRouterLocation('/drive'),
+ middleware: [
+ ({ cause, signal }) => {
+ if (cause === 'initial') {
+ initialSignal = signal;
+ return initial;
+ }
+ },
+ ],
+ });
+ expect(router.isReady()).toBe(false);
+ // Pending cancellation may also notify before the replacement commits.
+ const readiness: boolean[] = [];
+ router.subscribe(() => readiness.push(router.isReady()));
+ layout.open({
+ location: {
+ route: { matches: [{ id: 'legacy', params: { id: 'replacement' } }] },
+ },
+ target: 'new-split',
+ replace: false,
+ });
+ await settle();
+ expect(initialSignal?.aborted).toBe(true);
+ expect(router.isReady()).toBe(true);
+ expect(readiness.at(-1)).toBe(true);
+ release();
+ await router.settled();
+ expect(router.isReady()).toBe(true);
+ expect(layout.snapshot().entries[0].location.route.matches[0].id).toBe(
+ 'legacy'
+ );
+ router.dispose();
+ });
+ it('observes initial canonicalization echoes without swallowing browser Back', async () => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/legacy/one?referral_code=code'
+ );
+ const requests: { cause: string; externalSearch?: string }[] = [];
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ to, cause, externalSearch, redirect }) => {
+ requests.push({ cause, externalSearch });
+ if (rootRouteMatch(to.location.route)?.id === 'legacy') {
+ return redirect(
+ `/drive/folder/${routeParams(to.location.route).id}`
+ );
+ }
+ },
+ ],
+ });
+ await router.settled();
+ const splitId = layout.snapshot().entries[0].splitId;
+ expect(location.read().pathname).toBe('/drive/folder/one');
+ expect(requests).toEqual([
+ { cause: 'initial', externalSearch: '?referral_code=code' },
+ { cause: 'initial', externalSearch: '?referral_code=code' },
+ ]);
+
+ router.navigate(splitId, '/drive/folder/two');
+ await router.settled();
+ expect(requests.at(-1)).toEqual({
+ cause: 'navigate',
+ externalSearch: undefined,
+ });
+ expect(location.history()).toHaveLength(2);
+ expect(location.back()).toBe(true);
+ await router.settled();
+ expect(routeParams(router.route(splitId)!)).toEqual({ folderId: 'one' });
+ expect(location.read().pathname).toBe('/drive/folder/one');
+ router.dispose();
+ });
+
it('owns one manifest per router and only shares explicitly supplied state', async () => {
const compile = vi.spyOn(path, 'compileRoutePattern');
const layout = createLayout();
@@ -1242,7 +1328,7 @@ describe('split router', () => {
).toBe('one');
});
- it('repairs stale router commits that settle out of order', async () => {
+ it('accepts Back to a URL whose outbound write was coalesced', async () => {
let current: SplitRouterExternalLocationValue = {
pathname: '/drive',
search: '',
@@ -1271,17 +1357,19 @@ describe('split router', () => {
router.updateSearch(splitId, 'drive', { sort: ['name'] });
router.updateSearch(splitId, 'drive', { sort: ['created_at'] });
+ const earlier = pending[0]!;
flush(1);
- flush();
+ pending.length = 0; // The adapter discards the superseded write.
+ expect(router.search(splitId, 'drive')).toEqual({ sort: ['created_at'] });
- expect(pending).toHaveLength(1);
- flush();
+ // A later browser Back reaches the same URL as that superseded write.
+ current = earlier;
+ for (const listener of listeners) listener(current);
await settle();
- expect(router.search(splitId, 'drive')).toEqual({
- sort: ['created_at'],
- });
- expect(location.read().search).toBe('?s0.drive.sort=created_at');
+ expect(pending).toHaveLength(0);
+ expect(router.search(splitId, 'drive')).toEqual({ sort: ['name'] });
+ expect(location.read().search).toBe('?s0.drive.sort=name');
});
it('skips layout reconciliation for an identical external location', () => {
diff --git a/apps/web/src/lib/split-router/tests/routes.test.ts b/apps/web/src/lib/split-router/tests/routes.test.ts
index 233859416a..410bab2bc9 100644
--- a/apps/web/src/lib/split-router/tests/routes.test.ts
+++ b/apps/web/src/lib/split-router/tests/routes.test.ts
@@ -148,6 +148,36 @@ describe('typed route trees', () => {
}>();
});
+ it('types descendants directly from a named definition before assembly', () => {
+ const detail = driveRoute.children[0].children[0];
+ expectTypeOf<InferSplitRouteParams<typeof detail>>().toEqualTypeOf<{
+ documentId: string;
+ }>();
+ expectTypeOf<
+ InferSplitRouteNavigationParams<typeof detail>
+ >().toEqualTypeOf<{
+ folderId: string;
+ documentId: string;
+ }>();
+ expectTypeOf<InferSplitRouteBranchParams<typeof detail>>().toEqualTypeOf<{
+ folderId: string;
+ documentId: string;
+ }>();
+ const definition = {
+ id: 'named',
+ path: 'named/:id',
+ children: [{ id: 'child', path: ':childId' }],
+ } as const;
+ const named = defineRoute(definition);
+ expect(named).toBe(definition);
+ expect(named.children[0]).toBe(definition.children[0]);
+ expectTypeOf<
+ InferSplitRouteNavigationParams<(typeof named.children)[0]>
+ >().toEqualTypeOf<{ id: string; childId: string }>();
+ const tree = defineRoutes({ definitions: [named] });
+ expect(tree.definitions[0]).toBe(named);
+ });
+
it('rebinds ancestry when an existing reference is composed into another tree', () => {
const tree = defineRoutes({ definitions: [driveRoute] });
const detail = tree.definitions[0].children[0].children[0];
diff --git a/apps/web/src/lib/split-router/tests/search.test.ts b/apps/web/src/lib/split-router/tests/search.test.ts
index 3266695f32..d01e003abd 100644
--- a/apps/web/src/lib/split-router/tests/search.test.ts
+++ b/apps/web/src/lib/split-router/tests/search.test.ts
@@ -9,6 +9,44 @@ import {
import type { SplitLocation } from '../types';
describe('split search state', () => {
+ it.each(['toString', 'valueOf', 'hasOwnProperty'])(
+ 'treats %s as an own search key without mutating Object.prototype functions',
+ (name) => {
+ const inherited = Object.getOwnPropertyDescriptor(
+ Object.prototype,
+ name
+ )!.value;
+ const before = Object.getOwnPropertyDescriptors(inherited);
+ const query = new URLSearchParams([
+ [`s0.${name}.target`, 'one'],
+ [`s0.${name}.target`, 'two'],
+ [`s0.drive.${name}`, 'value'],
+ ]);
+ const parsed = parseSplitSearch(query.toString());
+ expect(parsed.get(0)).toEqual({
+ [name]: { target: ['one', 'two'] },
+ drive: { [name]: ['value'] },
+ });
+ expect(Object.getOwnPropertyDescriptors(inherited)).toEqual(before);
+ const roundtrip = new URLSearchParams();
+ replaceSplitSearchParams(roundtrip, [
+ { location: { search: parsed.get(0) } },
+ ]);
+ expect(parseSplitSearch(roundtrip.toString())).toEqual(parsed);
+ const route: SplitLocation['route'] = {
+ matches: [{ id: 'drive', params: {} }],
+ };
+ updateSearchState(
+ { route, search: {} },
+ {
+ [name]: (current) => {
+ expect(current).toBeUndefined();
+ return { target: ['value'] };
+ },
+ }
+ );
+ }
+ );
it('round trips repeated values and removes stale namespaced query keys', () => {
const query = new URLSearchParams('referral_code=ref&s9.old.value=stale');
const search = { drive: { tags: ['one', 'two'], sort: ['name'] } };
diff --git a/apps/web/src/lib/split-router/types.ts b/apps/web/src/lib/split-router/types.ts
index 320a9e3b2b..71df385cdf 100644
--- a/apps/web/src/lib/split-router/types.ts
+++ b/apps/web/src/lib/split-router/types.ts
@@ -37,6 +37,8 @@ export type SplitRouterMiddlewareContext = {
to: Readonly<SplitRouterEntry>;
/** Canonical single-split pathname for `to`. */
path: string;
+ /** Raw incoming URL search on initial/external navigation, retained across redirects. */
+ externalSearch?: string;
cause: SplitRouterNavigationCause;
signal: AbortSignal;
redirect: (to: string) => SplitRouterMiddlewareRedirect;
@@ -59,6 +61,7 @@ export type SplitRouterMiddlewareConfig = {
export type SplitRouterMiddlewareRequest = {
from?: SplitRouterEntry;
to: SplitRouterEntry;
+ externalSearch?: string;
cause: SplitRouterNavigationCause;
signal: AbortSignal;
};
@@ -245,7 +248,7 @@ type LocalNavigationParams<TRoute> = TRoute extends { params: StandardSchemaV1 }
? MergeRouteParams<{}, PathParams<TPath>>
: SplitRouteParams;
-// Type-only ancestry. defineRoutes never adds properties to the supplied objects.
+// Type-only ancestry. Declaration helpers never add properties to supplied objects.
declare const branchParams: unique symbol;
/** Params accumulated through this node, with child fields overriding ancestors. */
@@ -313,6 +316,9 @@ type DefinedRouteList<
>;
};
+/** One original definition with descendant ancestry inferred from this root. */
+export type DefinedSplitRoute<TRoute> = DefinedRoute<TRoute, {}, {}>;
+
/** The original static tree, with ancestry available on references from that tree. */
export type DefinedSplitRoutes<
TRoutes extends { definitions: readonly unknown[] },
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 4b7ef9a775..c18ad603a4 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -9,14 +9,18 @@
| `/app/invite?token=<token>` | GTM invite welcome page ("Welcome, <first name>", Continue → signup). Links come from the staff portal, last 48h, and grant the first month of Premium free once the account is created |
| `/app/internal/invite-links` | Macro staff only (`@macro.com`): create GTM invite links and track opens, signups, and subscriptions |
| `/app/inbox` | Desktop: Home (notifications + recent activity); mobile: Notifications soup |
+| `/app/inbox/<block-type>/<uuid>` | Home with a heterogeneous item opened inline; target metadata is stored in `sN.inbox-preview.*` query values |
| `/app/mail` | Email client |
+| `/app/mail/<uuid>` | Email with a thread opened inline; a targeted message uses `sN.email-detail.messageId` |
| `/app/channels` | Channels list |
+| `/app/channels/channel/<uuid>` | Channels with a conversation opened inline; message/thread targets use `sN.channel-detail.*` |
| `/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/tasks/<uuid>` | Tasks with a task document opened inline |
| `/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 |
@@ -34,6 +38,12 @@
| `/app/md/<doc>/channel/<channel>` | Doc + channel in a split |
| `/app/settings/account` | Settings (also `/app/settings/api-keys`, `/mcp-server`, `/shortcuts`, etc.) |
+On touch devices, documents (including tasks) open in legacy blocks rather than
+inline Drive details. Canonical `/app/drive/.../<document-type>/<uuid>` links also
+fall back to legacy document routes. This uses touch detection, not the native-app
+check: in DevTools, enable touch emulation rather than only narrowing the viewport.
+Legacy document URLs upgrade to Drive only when desktop detail rendering is enabled.
+
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`
@@ -51,9 +61,19 @@ 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. 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.
+Home, Email, Tasks, Channels, and Drive keep their workspace provider mounted
+while typed child routes own the accepted inline detail. Tasks and Email replace
+the list with detail, capturing its focus and scroll state before disposal. Their child
+selection participates in browser Back/Forward independently per pane. Explicit
+return controls navigate to the workspace's list root. Multiple panes navigate
+their child routes and history independently; returning to a list does not
+activate another pane. Opening a resource already displayed in another pane
+still activates its owner through router claim arbitration; the compatibility
+preview guard can instead reject a conflicting embedded preview. On touch, or
+when the new-app-view flag cannot render the detail, Home, Email, Tasks, and
+Channels detail URLs fall back to the existing full-block surface. Legacy email
+and channel message targets are normalized into per-pane search by ingress
+middleware, including external/history navigation; explicit namespaced values win.
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
@@ -414,7 +434,9 @@ create a session before the user sends. Repeating it focuses the existing draft.
Splits navigate independently. The retired Preview Pair mode no longer creates
an adjacent viewer, redirects list navigation, or links split sizes and history.
-Inline details in workspaces continue to use their own navigation stack.
+Inline details in Home, Email, Tasks, Channels, and Drive use typed split-router
+child routes; there is no competing view-local detail stack or persisted selected
+ID. List filters, sidebar preferences, and focused-list state remain view-owned.
Split back/forward navigation skips entries whose entities are open elsewhere,
without moving focus or showing a toast. Those entries remain in history and
become reachable again after their owning view releases them. A direction is