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.

fix(search): route content targets through shared pane navigation (#7122)

gbirman1eb44b6f3edf
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index 5564101100..52d902e791 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -5,6 +5,8 @@ import {
SplitRouter,
type SplitRouterMiddleware,
type SplitRoutes,
+ type SplitRoutesManifest,
+ useSplitRouter,
} from '@app/lib/split-router';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import { Resize } from '@core/component/Resize';
@@ -35,6 +37,7 @@ import {
type MobileSwipeLayout,
} from './mobile/createMobileSwipeLayout';
import { MobileSplitContainer } from './mobile/MobileSplitContainer';
+import { createContentNavigator } from './split-router/content-navigation';
import { splitContentFromLocation } from './split-router/legacy-route';
import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
import { createSplitFocusTracker } from './splitFocusTracker';
@@ -47,6 +50,18 @@ type SplitLayoutContainerProps = {
setManager: Setter<SplitManager | undefined>;
};
+function ContentNavigationBinding(props: {
+ manager: SplitManager;
+ routes: SplitRoutesManifest;
+}) {
+ const router = useSplitRouter<SplitId>();
+ props.manager.setContentNavigator(
+ createContentNavigator(props.manager, router, props.routes)
+ );
+ onCleanup(() => props.manager.setContentNavigator(undefined));
+ return null;
+}
+
export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
const location = useLocation();
const navigate = useNavigate();
@@ -110,6 +125,7 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
middleware={props.middleware}
>
<SplitLayoutContext.Provider value={{ manager: splitManager }}>
+ <ContentNavigationBinding manager={splitManager} routes={routes} />
<div
class="size-full"
classList={{ 'py-1.5 pr-1.5': useBentoLayout() }}
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index e39a1e4da3..1dcd8fb103 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -1,5 +1,6 @@
import { LIST_VIEW_ID, type ListView } from '@app/constants/list-views';
import { parseAgentsRoute } from '@app/features/agents-view/core/route';
+import type { SplitSearchUpdate } from '@app/lib/split-router';
import type {
BlockAlias,
BlockAliasContext,
@@ -168,6 +169,10 @@ export type CreateNewSplitOptions = {
};
export type OpenWithSplitOptions = {
+ /** Route-owned targets must pass through middleware and content claims before opening. */
+ search?: Record<string, SplitSearchUpdate>;
+ /** For routed opens, runs only after the router applies or reuses a destination. */
+ onApplied?: () => void;
mergeHistory?: boolean;
activate?: boolean;
referredFrom?: ReferredFrom;
@@ -195,6 +200,7 @@ export type OpenSplitResult = {
| { status: 'opened'; split: SplitHandle }
| { status: 'reused'; owner: ContentInstance['owner']; split?: SplitHandle }
| { status: 'unavailable'; split?: undefined }
+ | { status: 'navigating'; split?: undefined }
);
/** Return an outcome to consume navigation, or undefined to use normal split navigation. */
@@ -269,6 +275,12 @@ export type OpenView = ContentInstance & {
};
export type SplitManager = {
+ /** Bound by the app router; keeps imperative callers on the same navigation path. */
+ setContentNavigator: (
+ navigate:
+ | ((content: SplitContent, options: OpenWithSplitOptions) => void)
+ | undefined
+ ) => void;
/** Find the view owning this content without activating it. */
findOpenView: (content: SplitContent) => OpenView | undefined;
/** Register live inline views; call the returned function when the host is disposed. */
@@ -648,6 +660,9 @@ export function createSplitLayout(
let exclusionFilter: ((split: SplitState) => boolean) | undefined;
let splitNavigationInterceptor: SplitNavigationInterceptor | undefined;
+ let contentNavigator:
+ | ((content: SplitContent, options: OpenWithSplitOptions) => void)
+ | undefined;
const isExcluded = (split: SplitState) => exclusionFilter?.(split) ?? false;
const canAppendSplit = createMemo(
@@ -1654,6 +1669,12 @@ export function createSplitLayout(
options: OpenWithSplitOptions = {}
): OpenSplitResult {
const sourceOwner = options.handle?.id;
+ if (options.search) {
+ if (!contentNavigator)
+ throw new Error('Split content navigation requires the app router');
+ contentNavigator(content, options);
+ return { status: 'navigating', sourceOwner };
+ }
const existing = findOpenView(content);
if (options.reopen === 'latest') {
@@ -1854,5 +1875,8 @@ export function createSplitLayout(
setSplitNavigationInterceptor: (fn) => {
splitNavigationInterceptor = fn;
},
+ setContentNavigator: (navigate) => {
+ contentNavigator = navigate;
+ },
};
}
diff --git a/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts b/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts
index 856c6b722a..d895c2135b 100644
--- a/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts
+++ b/apps/web/src/components/app/split-layout/mobile/createMobileSwipeLayout.ts
@@ -61,6 +61,9 @@ export function createMobileSwipeLayout(
let animatedTrigger: (() => void) | undefined;
let forwardNavigationTrigger: (() => void) | undefined;
+ let pendingForwardApplied:
+ | { splitId: SplitId; notify: () => void }
+ | undefined;
const fgSplitId = () => (fgIsSlotA() ? slotASplitId() : slotBSplitId());
const bgSplitId = () => (fgIsSlotA() ? slotBSplitId() : slotASplitId());
@@ -78,6 +81,7 @@ export function createMobileSwipeLayout(
return navigateForward(content, options);
});
onCleanup(() => {
+ pendingForwardApplied = undefined;
splitManager.setExclusionFilter(undefined);
splitManager.setSplitNavigationInterceptor(undefined);
});
@@ -89,8 +93,9 @@ export function createMobileSwipeLayout(
function navigateForward(
content: SplitContent,
- options?: Pick<OpenWithSplitOptions, 'referredFrom'>
+ options?: Pick<OpenWithSplitOptions, 'referredFrom' | 'onApplied'>
): OpenSplitResult {
+ pendingForwardApplied = undefined;
const isFgA = fgIsSlotA();
const currentFgId = fgSplitId();
const currentBgId = bgSplitId();
@@ -122,11 +127,7 @@ export function createMobileSwipeLayout(
referredFrom,
mergeHistory: true,
});
- if (forwardNavigationTrigger) {
- forwardNavigationTrigger();
- } else {
- completeNavigateForward();
- }
+ startForwardNavigation(bgHandle.id, options?.onApplied);
return { status: 'reused', owner: bgHandle.id, split: bgHandle };
}
@@ -150,17 +151,24 @@ export function createMobileSwipeLayout(
});
if (!prepared) return { status: 'unavailable' };
+ startForwardNavigation(prepared.id, options?.onApplied);
+ return { status: 'opened', split: prepared };
+ }
+
+ function startForwardNavigation(splitId: SplitId, onApplied?: () => void) {
if (forwardNavigationTrigger) {
+ if (onApplied) pendingForwardApplied = { splitId, notify: onApplied };
forwardNavigationTrigger();
} else {
completeNavigateForward();
}
- return { status: 'opened', split: prepared };
}
function completeNavigateForward() {
const preparedFgId = bgSplitId();
- if (!preparedFgId) return;
+ const pending = pendingForwardApplied;
+ pendingForwardApplied = undefined;
+ if (!preparedFgId || !splitManager.getSplit(preparedFgId)) return;
batch(() => {
// Flip roles before activating: activateSplit refuses excluded
@@ -169,6 +177,12 @@ export function createMobileSwipeLayout(
toggleFgSlot();
splitManager.activateSplit(preparedFgId);
});
+ if (
+ pending?.splitId === preparedFgId &&
+ splitManager.activeSplitId() === preparedFgId
+ ) {
+ pending.notify();
+ }
}
function completeSwipeBack() {
diff --git a/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx b/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx
index 6643de9b0b..9f4a740541 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx
+++ b/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx
@@ -1,5 +1,8 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { useSplitRouter } from '@app/lib/split-router';
+import { parseSearchState } from '@app/lib/split-router/search';
+import { isRecord } from '@app/lib/split-router/utils';
import { useIsAuthenticated } from '@core/auth';
import { LoadingBlock } from '@core/component/LoadingBlock';
import { enableNewAppViews } from '@core/constant/featureFlags';
@@ -12,7 +15,7 @@ import {
onMount,
Show,
} from 'solid-js';
-import type { SplitContent } from '../layoutManager';
+import type { SplitContent, SplitId } from '../layoutManager';
import { useSplitPanelOrThrow } from '../layoutUtils';
export function usePageViewTracking(pageTitle: string) {
@@ -36,7 +39,24 @@ export function withAuth<P extends object>(View: Component<P>): Component<P> {
export function RedirectSplit(props: { to: SplitContent }) {
const panel = useSplitPanelOrThrow();
- onMount(() => panel.handle.replace({ next: props.to }));
+ const router = useSplitRouter<SplitId>();
+ onMount(() => {
+ const metadata = isRecord(props.to.entryMetadata)
+ ? props.to.entryMetadata
+ : {};
+ panel.handle.replace({
+ next: {
+ ...props.to,
+ entryMetadata: {
+ ...metadata,
+ search: {
+ ...router.location(panel.handle.id)?.search,
+ ...parseSearchState(metadata.search),
+ },
+ },
+ },
+ });
+ });
return null;
}
diff --git a/apps/web/src/components/app/split-layout/split-router/content-navigation.ts b/apps/web/src/components/app/split-layout/split-router/content-navigation.ts
new file mode 100644
index 0000000000..462201d3ac
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-router/content-navigation.ts
@@ -0,0 +1,50 @@
+import type { SplitRouter, SplitRoutesManifest } from '@app/lib/split-router';
+import { encodeRoute } from '@app/lib/split-router/routes';
+import { replaceSplitSearchParams } from '@app/lib/split-router/search';
+import type {
+ OpenWithSplitOptions,
+ SplitContent,
+ SplitId,
+ SplitManager,
+} from '../layoutManager';
+import { openAppSplitLocation } from '../splitRouterLayout';
+import { resolveContentLocation } from './legacy-route';
+
+export function createContentNavigator(
+ manager: SplitManager,
+ router: SplitRouter<SplitId>,
+ routes: SplitRoutesManifest
+) {
+ return (content: SplitContent, options: OpenWithSplitOptions) => {
+ const firstVisible = manager.getVisibleSplits()[0];
+ const source =
+ options.handle ??
+ manager.activeSplit() ??
+ (firstVisible ? manager.getSplit(firstVisible.id) : undefined);
+ if (!source) return;
+ const location = resolveContentLocation(routes, content);
+ const path = `/${encodeRoute(routes, { location }).map(encodeURIComponent).join('/')}`;
+ const query = new URLSearchParams();
+ replaceSplitSearchParams(query, [{ location }]);
+ let onApplied = options.onApplied;
+ const reportApplied = () => {
+ const callback = onApplied;
+ onApplied = undefined;
+ callback?.();
+ };
+ router.navigate(source.id, query.size ? `${path}?${query}` : path, {
+ target:
+ options.preferNewSplit && manager.canAppendSplit()
+ ? 'new-split'
+ : 'current',
+ replace: options.mergeHistory,
+ search: options.search,
+ onApplied: reportApplied,
+ open: (request) =>
+ openAppSplitLocation(manager, routes, request, content, {
+ ...options,
+ onApplied: reportApplied,
+ }),
+ });
+ };
+}
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 81f43a8716..8bfe1cce0c 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
@@ -11,6 +11,7 @@ import {
calendarTargetSearch,
} from '@app/features/calendar-view/calendar-url';
import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';
+import { channelsSearch } from '@app/features/channels-view/channels-route';
import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';
import {
defineRoute,
@@ -302,11 +303,31 @@ export function resolveContentLocation(
}
}
route ??= resolve(splitLocationFromContent(routes, content).route);
- const search = filterRouteSearch(
- routes,
- route,
- parseSearchState(metadataLocation?.search)
- );
+ const savedSearch = parseSearchState(metadataLocation?.search);
+ // In-app message opens carry block params, not external URL query keys.
+ // Preserve the target before middleware upgrades the block to Chat, where
+ // the legacy block (and its imperative navigation handle) is replaced.
+ const channelParams: Record<string, unknown> | undefined =
+ content.type === 'channel' && isRecord(content.params)
+ ? content.params
+ : undefined;
+ const messageId = channelParams?.[CHANNEL_URL_PARAMS.message];
+ const threadId = channelParams?.[CHANNEL_URL_PARAMS.thread];
+ let contentSearch = savedSearch;
+ if (typeof messageId === 'string') {
+ const channelSearch = { ...savedSearch?.[channelsSearch.namespace] };
+ // Message and thread identify one target; never combine two saved opens.
+ if (!Object.hasOwn(channelSearch, 'messageId')) {
+ channelSearch.messageId = [messageId];
+ if (typeof threadId === 'string') channelSearch.threadId = [threadId];
+ else delete channelSearch.threadId;
+ }
+ contentSearch = {
+ ...savedSearch,
+ [channelsSearch.namespace]: channelSearch,
+ };
+ }
+ const search = filterRouteSearch(routes, route, contentSearch);
const location: SplitLocation = { route };
if (search) location.search = search;
return location;
@@ -376,6 +397,8 @@ export const legacySplitRoute = defineRoute({
const content = decodeLegacyPair(type, id);
if (!content) return;
+ if (content.type === 'agent') return { namespace: 'agent', id };
+
if (content.type === 'component') {
const [section, conversationId] = agentsRouteSegments(content.id) ?? [];
if (section && conversationId) {
diff --git a/apps/web/src/components/app/split-layout/splitRouterLayout.ts b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
index 1faeb11a1d..318314c3c9 100644
--- a/apps/web/src/components/app/split-layout/splitRouterLayout.ts
+++ b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
@@ -7,7 +7,12 @@ import type {
} from '@app/lib/split-router';
import deepEqual from 'fast-deep-equal';
import { createEffect, createRoot, on } from 'solid-js';
-import type { SplitContent, SplitId, SplitManager } from './layoutManager';
+import type {
+ OpenWithSplitOptions,
+ SplitContent,
+ SplitId,
+ SplitManager,
+} from './layoutManager';
import {
resolveContentLocation,
splitContentFromLocation,
@@ -60,6 +65,57 @@ function changeHistory(
return changed?.lastNavigationCause === 'replace' ? 'replace' : 'push';
}
+export function openAppSplitLocation(
+ manager: SplitManager,
+ routes: SplitRoutesManifest,
+ { location, target, replace }: Parameters<AppSplitRouterLayout['open']>[0],
+ source?: SplitContent,
+ options: OpenWithSplitOptions = {}
+): ReturnType<AppSplitRouterLayout['open']> {
+ let handle: ReturnType<SplitManager['getSplit']>;
+ if (target && target !== 'new-split') {
+ handle = manager.getSplit(target);
+ }
+
+ const result = manager.openWithSplit(
+ {
+ ...contentForLocation(location, source),
+ ...(source?.state && { state: source.state }),
+ },
+ {
+ ...options,
+ search: undefined,
+ handle,
+ preferNewSplit: target === 'new-split',
+ allowDuplicate: options.allowDuplicate || target === 'new-split',
+ mergeHistory: replace,
+ referredFrom: options.referredFrom ?? null,
+ }
+ );
+ if (!result.split) return { status: 'unavailable' };
+
+ const appliedLocation = resolveContentLocation(
+ routes,
+ result.split.content()
+ );
+ if (!deepEqual(appliedLocation, location)) {
+ if (!deepEqual(appliedLocation.route, location.route)) {
+ result.split.captureEntryState();
+ }
+ result.split.updateCurrentEntry((content) =>
+ contentForLocation(location, content)
+ );
+ }
+ // Native forward animation prepares an excluded pane first. Its eventual
+ // promotion publishes the accepted location through the layout subscription.
+ if (
+ !manager.getVisibleSplits().some((split) => split.id === result.split?.id)
+ ) {
+ return { status: 'unavailable' };
+ }
+ return { status: 'applied', splitId: result.split.id };
+}
+
export function createAppSplitRouterLayout(
manager: SplitManager,
routes: SplitRoutesManifest
@@ -98,35 +154,7 @@ export function createAppSplitRouterLayout(
);
},
- open({ location, target, replace }) {
- let handle: ReturnType<SplitManager['getSplit']>;
- if (target && target !== 'new-split') {
- handle = manager.getSplit(target);
- }
-
- const result = manager.openWithSplit(contentForLocation(location), {
- handle,
- preferNewSplit: target === 'new-split',
- allowDuplicate: target === 'new-split',
- mergeHistory: replace,
- referredFrom: null,
- });
- if (!result.split) return { status: 'unavailable' };
-
- const appliedLocation = resolveContentLocation(
- routes,
- result.split.content()
- );
- if (!deepEqual(appliedLocation, location)) {
- if (!deepEqual(appliedLocation.route, location.route)) {
- result.split.captureEntryState();
- }
- result.split.updateCurrentEntry((content) =>
- contentForLocation(location, content)
- );
- }
- return { status: 'applied', splitId: result.split.id };
- },
+ open: (request) => openAppSplitLocation(manager, routes, request),
reconcile(locations) {
for (const [index, split] of manager.getVisibleSplits().entries()) {
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 ae1e95074d..73ba24891c 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
@@ -27,6 +27,10 @@ vi.mock('@service-connection/websocket', () => ({
createConnectionBlockWebsocketEffect: vi.fn(),
createConnectionWebsocketEffect: vi.fn(),
}));
+vi.mock('@app/lib/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+ useSplitRouter: () => ({ location: () => undefined }),
+}));
vi.mock('@core/auth', () => ({
useIsAuthenticated: () => () => state.authenticated(),
}));
@@ -164,7 +168,7 @@ describe('activity registration', () => {
renderActivity();
expect(state.replace).toHaveBeenCalledExactlyOnceWith({
- next: { type: 'component', id: 'home' },
+ next: { type: 'component', id: 'home', entryMetadata: { search: {} } },
});
expect(state.mountActivity).not.toHaveBeenCalled();
expect(state.pageView).not.toHaveBeenCalled();
@@ -192,7 +196,11 @@ describe('activity registration', () => {
expect(state.pageView).toHaveBeenCalledExactlyOnceWith('activity');
} else {
expect(state.replace).toHaveBeenCalledExactlyOnceWith({
- next: { type: 'component', id: 'home' },
+ next: {
+ type: 'component',
+ id: 'home',
+ entryMetadata: { search: {} },
+ },
});
expect(state.mountActivity).not.toHaveBeenCalled();
expect(state.pageView).not.toHaveBeenCalled();
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 b9e8557ef7..9d27ce1da3 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
@@ -7,6 +7,7 @@ import {
emailSplitRoute,
emailThreadRoute,
} from '@app/features/email-view/route';
+import { searchLocationUpdates } from '@app/features/next-soup/search-navigation';
import { reviewsHostedContent } from '@app/features/reviews-view/reviews-hosted-content';
import { reviewsSplitRoute } from '@app/features/reviews-view/route';
import {
@@ -25,6 +26,7 @@ import { createRoutesManifest } from '@app/lib/split-router/routes';
import type { ResizeZoneCtx } from '@core/component/Resize/types';
import { toast } from '@core/component/Toast/Toast';
import type { BlockOrchestrator } from '@core/orchestrator';
+import type { SearchLocation } from '@entity';
import { createMemo, createRoot, createSignal } from 'solid-js';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import {
@@ -39,6 +41,7 @@ import {
import { createMobileSwipeLayout } from '../mobile/createMobileSwipeLayout';
import { createAppSplitRouterMiddleware } from '../split-router/app-middleware';
import { appSplitRoutes } from '../split-router/app-routes';
+import { createContentNavigator } from '../split-router/content-navigation';
import { createAppSplitRouterLayout } from '../splitRouterLayout';
// Settings UI imports the app route registry and is unrelated to layout behavior.
@@ -858,10 +861,404 @@ describe('layoutManager', () => {
isTouchDevice: () => options.touch ?? false,
}),
});
+ manager.setContentNavigator(
+ createContentNavigator(manager, router, routes)
+ );
return { manager, location, router, dispose };
});
}
+ const searchTargets: {
+ type: SplitContent['type'];
+ target: SearchLocation;
+ namespace: string;
+ fields: Record<string, string[]>;
+ path: string;
+ }[] = [
+ {
+ type: 'channel',
+ target: { type: 'channel', messageId: 'reply', threadId: 'parent' },
+ namespace: 'channels',
+ fields: { messageId: ['reply'], threadId: ['parent'] },
+ path: '/channels/entity',
+ },
+ {
+ type: 'email',
+ target: { type: 'email', messageId: 'message' },
+ namespace: 'email-detail',
+ fields: { messageId: ['message'] },
+ path: '/mail/entity',
+ },
+ {
+ type: 'md',
+ target: { type: 'md', nodeId: 'node' },
+ namespace: 'markdown-detail',
+ fields: { nodeId: ['node'] },
+ path: '/drive/md/entity',
+ },
+ {
+ type: 'pdf',
+ target: {
+ type: 'pdf',
+ searchPage: 3,
+ highlightTerms: ['a'],
+ searchSnippet: 'snippet',
+ searchRawQuery: 'a',
+ },
+ namespace: 'pdf-detail',
+ fields: {
+ page: ['3'],
+ highlightTerms: ['a'],
+ snippet: ['snippet'],
+ query: ['a'],
+ },
+ path: '/drive/pdf/entity',
+ },
+ {
+ type: 'agent',
+ target: { type: 'agent', messageTurn: 0, author: 'user' },
+ namespace: 'agent-detail',
+ fields: {},
+ path: '/agent/entity',
+ },
+ {
+ type: 'call',
+ target: {
+ type: 'call_record',
+ callId: 'entity',
+ transcriptId: 'segment',
+ },
+ namespace: 'call-detail',
+ fields: { transcriptId: ['segment'] },
+ path: '/drive/call/entity',
+ },
+ ];
+
+ it.each(searchTargets)(
+ 'routes a $type search target on first open and on reuse',
+ async ({ type, target, namespace, fields, path }) => {
+ const { manager, router, location, dispose } = ingressRouter('/search');
+ await router.settled();
+ const onApplied = vi.fn();
+ const source = manager.getSplit(manager.splits()[0].id)!;
+ const sourceRoute = router.route(source.id);
+ manager.openWithSplit(
+ { type, id: 'entity' },
+ {
+ handle: source,
+ preferNewSplit: true,
+ search: searchLocationUpdates('entity', target),
+ onApplied,
+ }
+ );
+ await router.settled();
+ expect(manager.splits()).toHaveLength(2);
+ const owner = manager.splits().find((split) => split.id !== source.id)!;
+ expect(router.search(owner.id, namespace)).toMatchObject({
+ ...fields,
+ seek: [expect.any(String)],
+ });
+ expect(location.read().pathname).toContain(path);
+ expect(onApplied).toHaveBeenCalledOnce();
+ const firstRequest = router.search(owner.id, namespace)?.seek;
+ manager.openWithSplit(
+ { type, id: 'entity' },
+ {
+ handle: source,
+ preferNewSplit: true,
+ search: searchLocationUpdates('entity', target),
+ onApplied,
+ }
+ );
+ await router.settled();
+ expect(manager.splits()).toHaveLength(2);
+ expect(router.route(source.id)).toEqual(sourceRoute);
+ expect(router.search(source.id, namespace)).toBeUndefined();
+ expect(router.search(owner.id, namespace)?.seek).not.toEqual(
+ firstRequest
+ );
+ expect(manager.activeSplitId()).toBe(owner.id);
+ expect(onApplied).toHaveBeenCalledTimes(2);
+ router.dispose();
+ dispose();
+ }
+ );
+
+ it.each([false, true])(
+ 'preserves native search navigation and list context (animated: %s)',
+ async (animated) => {
+ const { manager, router, dispose } = ingressRouter('/search', {
+ touch: true,
+ });
+ await router.settled();
+ const source = manager.getSplit(manager.splits()[0].id)!;
+ let swipe!: ReturnType<typeof createMobileSwipeLayout>;
+ const disposeSwipe = createRoot((cleanup) => {
+ swipe = createMobileSwipeLayout(manager);
+ return cleanup;
+ });
+ const animate = vi.fn();
+ const onApplied = vi.fn();
+ if (animated) swipe.setForwardNavigationTrigger(animate);
+ manager.openWithSplit(
+ withListNavigationSource({ type: 'channel', id: 'entity' }, source),
+ {
+ handle: source,
+ referredFrom: 'search',
+ onApplied,
+ search: searchLocationUpdates('entity', {
+ type: 'channel',
+ messageId: 'message',
+ }),
+ }
+ );
+ await router.settled();
+ if (animated) {
+ expect(animate).toHaveBeenCalledOnce();
+ expect(onApplied).not.toHaveBeenCalled();
+ expect(manager.activeSplitId()).toBe(source.id);
+ swipe.completeNavigateForward();
+ await router.settled();
+ }
+ const detail = manager.activeSplit()!;
+ expect(onApplied).toHaveBeenCalledOnce();
+ expect(detail.id).not.toBe(source.id);
+ expect(detail.referredFrom()).toBe('search');
+ expect(listNavigationSourceId(detail)).toBe(source.id);
+ expect(router.search(detail.id, 'channels')?.messageId).toEqual([
+ 'message',
+ ]);
+ expect(swipe.canGoBack()).toBe(true);
+ swipe.swipeBack();
+ await router.settled();
+ expect(manager.activeSplitId()).toBe(source.id);
+ expect(router.route(source.id)?.matches[0].id).toBe('view-search');
+ router.dispose();
+ disposeSwipe();
+ dispose();
+ }
+ );
+
+ it.each(['same', 'different', 'removed'])(
+ 'only reports the promoted native request applied (%s prepared target)',
+ async (next) => {
+ const { manager, router, dispose } = ingressRouter('/search', {
+ touch: true,
+ });
+ await router.settled();
+ const source = manager.activeSplit()!;
+ let swipe!: ReturnType<typeof createMobileSwipeLayout>;
+ const disposeSwipe = createRoot((cleanup) => {
+ swipe = createMobileSwipeLayout(manager);
+ swipe.setForwardNavigationTrigger(vi.fn());
+ return cleanup;
+ });
+ const first = vi.fn();
+ const second = vi.fn();
+ const open = (id: string, onApplied: () => void) =>
+ manager.openWithSplit(
+ { type: 'channel', id },
+ {
+ handle: source,
+ onApplied,
+ search: searchLocationUpdates(id, {
+ type: 'channel',
+ messageId: 'hit',
+ }),
+ }
+ );
+ open('entity', first);
+ await router.settled();
+ expect(first).not.toHaveBeenCalled();
+ if (next === 'removed') {
+ manager.removeSplit(swipe.slotBSplitId()!);
+ } else {
+ open(next === 'same' ? 'entity' : 'other', second);
+ }
+ await router.settled();
+ expect(second).not.toHaveBeenCalled();
+ swipe.completeNavigateForward();
+ await router.settled();
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(next === 'removed' ? 0 : 1);
+ router.dispose();
+ disposeSwipe();
+ dispose();
+ }
+ );
+
+ it('uses a remaining visible pane when the active pane was removed', async () => {
+ const { manager, router, dispose } = ingressRouter('/search');
+ await router.settled();
+ const source = manager.splits()[0];
+ const removed = manager.createNewSplit({
+ content: { type: 'md', id: 'removed' },
+ activate: true,
+ referredFrom: null,
+ })!;
+ await router.settled();
+ manager.removeSplit(removed.id);
+ await router.settled();
+ expect(manager.activeSplit()).toBeUndefined();
+ manager.openWithSplit(
+ { type: 'channel', id: 'entity' },
+ {
+ search: searchLocationUpdates('entity', {
+ type: 'channel',
+ messageId: 'hit',
+ }),
+ }
+ );
+ await router.settled();
+ expect(router.search(source.id, 'channels')?.messageId).toEqual(['hit']);
+ expect(manager.activeSplitId()).toBe(source.id);
+ router.dispose();
+ dispose();
+ });
+
+ it.each(['/home/agent/entity', '/agents/entity', '/coders/entity'])(
+ 'reuses an agent target inside %s while preserving Changes state',
+ async (path) => {
+ const { manager, router, dispose } = ingressRouter(
+ `${path}/~/search?s0.changes.pane=split&s0.changes.style=split`
+ );
+ await router.settled();
+ const [owner, source] = manager.splits();
+ const ownerRoute = router.route(owner.id);
+ manager.openWithSplit(
+ { type: 'agent', id: 'entity' },
+ {
+ handle: manager.getSplit(source.id),
+ search: searchLocationUpdates('entity', {
+ type: 'agent',
+ messageTurn: 0,
+ author: 'agent',
+ }),
+ }
+ );
+ await router.settled();
+ expect(manager.splits()).toHaveLength(2);
+ expect(router.route(owner.id)).toEqual(ownerRoute);
+ expect(router.route(source.id)?.matches[0].id).toBe('view-search');
+ expect(router.search(owner.id, 'agent-detail')).toMatchObject({
+ messageTurn: ['0'],
+ author: ['agent'],
+ });
+ expect(router.search(owner.id, 'changes')).toEqual({
+ pane: ['split'],
+ style: ['split'],
+ });
+ router.dispose();
+ dispose();
+ }
+ );
+
+ it('retargets an existing Home channel without replacing Home or its filters', async () => {
+ const { manager, router, dispose } = ingressRouter(
+ '/home/channel/entity/~/search?s0.channels.tab=recents&s0.channels.messageId=old&s0.channels.threadId=old-parent'
+ );
+ await router.settled();
+ const [owner, source] = manager.splits();
+ const ownerRoute = router.route(owner.id);
+ manager.openWithSplit(
+ { type: 'channel', id: 'entity' },
+ {
+ handle: manager.getSplit(source.id),
+ search: searchLocationUpdates('entity', {
+ type: 'channel',
+ messageId: 'new-root',
+ }),
+ }
+ );
+ await router.settled();
+ expect(router.route(owner.id)).toEqual(ownerRoute);
+ expect(router.search(owner.id, 'channels')).toEqual({
+ tab: ['recents'],
+ messageId: ['new-root'],
+ seek: [expect.any(String)],
+ });
+ expect(router.route(source.id)?.matches[0].id).toBe('view-search');
+ router.dispose();
+ dispose();
+ });
+
+ it.each([
+ { name: 'top-level message', expected: { messageId: ['message-1'] } },
+ {
+ name: 'thread reply',
+ threadId: 'thread-1',
+ expected: { messageId: ['message-1'], threadId: ['thread-1'] },
+ },
+ {
+ name: 'saved tab',
+ threadId: 'thread-1',
+ saved: { tab: ['recents'] },
+ expected: {
+ messageId: ['message-1'],
+ threadId: ['thread-1'],
+ tab: ['recents'],
+ },
+ },
+ {
+ name: 'top-level message after a saved thread',
+ saved: { threadId: ['old-thread'], tab: ['recents'] },
+ expected: { messageId: ['message-1'], tab: ['recents'] },
+ },
+ {
+ name: 'reply after a saved thread',
+ threadId: 'thread-1',
+ saved: { threadId: ['old-thread'] },
+ expected: { messageId: ['message-1'], threadId: ['thread-1'] },
+ },
+ {
+ name: 'explicit saved target',
+ threadId: 'thread-1',
+ saved: { messageId: ['saved-message'], threadId: ['saved-thread'] },
+ expected: { messageId: ['saved-message'], threadId: ['saved-thread'] },
+ },
+ {
+ name: 'explicit saved top-level target',
+ threadId: 'thread-1',
+ saved: { messageId: ['saved-message'] },
+ expected: { messageId: ['saved-message'] },
+ },
+ ])(
+ 'preserves an in-app channel target through the Chat redirect: $name',
+ async ({ threadId, saved, expected }) => {
+ const { manager, location, router, dispose } = ingressRouter('/search');
+ await router.settled();
+
+ manager.openWithSplit(
+ {
+ type: 'channel',
+ id: 'channel-1',
+ params: {
+ channel_message_id: 'message-1',
+ ...(threadId ? { channel_thread_id: threadId } : {}),
+ },
+ ...(saved
+ ? { entryMetadata: { search: { channels: saved } } }
+ : {}),
+ },
+ { activate: true }
+ );
+ await router.settled();
+
+ expect(location.read().pathname).toBe('/channels/channel-1');
+ const search = new URLSearchParams(location.read().search);
+ expect(search.get('s0.channels.messageId')).toBe(expected.messageId[0]);
+ expect(search.get('s0.channels.threadId')).toBe(
+ expected.threadId?.[0] ?? null
+ );
+ expect(router.search(manager.splits()[0].id, 'channels')).toEqual(
+ expected
+ );
+
+ router.dispose();
+ dispose();
+ }
+ );
+
it.each([
['md', 'md'],
['pdf', 'pdf'],
diff --git a/apps/web/src/components/entity-detail/EntityDetail.tsx b/apps/web/src/components/entity-detail/EntityDetail.tsx
index a10e470358..4c2e2eb023 100644
--- a/apps/web/src/components/entity-detail/EntityDetail.tsx
+++ b/apps/web/src/components/entity-detail/EntityDetail.tsx
@@ -66,7 +66,7 @@ export type EntityDetailContext =
export type EntityDetailProps = {
target: EntityDetailTarget;
previewHeaderLeading?: JSX.Element;
- navigationRequest?: number;
+ navigationRequest?: number | string;
children?: (context: EntityDetailContext) => JSX.Element;
};
diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
index f68d7b076e..08b70231f7 100644
--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
@@ -21,6 +21,7 @@ import {
forgetPendingSession,
pendingSession,
} from '@app/features/block-agent/context/pending-session';
+import { createAgentRouteTarget } from '@app/features/block-agent/primitives/create-agent-route-target';
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
import { SidePanel } from '@components/app/side-panel';
import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';
@@ -79,6 +80,7 @@ function SessionContent(props: {
sessionId,
startupError,
} = useAgentSession();
+ const searchTarget = createAgentRouteTarget();
const panel = useSplitPanelOrThrow();
const userId = useUserId();
@@ -272,14 +274,14 @@ function SessionContent(props: {
>
<AgentPreviewBanner />
<div class="transcript-host">
- <Transcript />
+ <Transcript searchTarget={searchTarget()} />
</div>
<div class="dock">
<div class="composer-anchor flex flex-col gap-2">
<ChangesHandoff />
<ReviewNotesDock />
<AgentComposer
- autofocus
+ autofocus={!searchTarget()}
input={ChatSessionInput}
modelSelector={SessionModelSelector}
/>
diff --git a/apps/web/src/features/agents-view/route.test.tsx b/apps/web/src/features/agents-view/route.test.tsx
index 30bd6de0c8..9f5b3a4e4e 100644
--- a/apps/web/src/features/agents-view/route.test.tsx
+++ b/apps/web/src/features/agents-view/route.test.tsx
@@ -15,7 +15,8 @@ const state = vi.hoisted(() => ({
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => state.flag,
}));
-vi.mock('@app/lib/split-router', () => ({
+vi.mock('@app/lib/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),
defineRoute: (route: unknown) => route,
}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
diff --git a/apps/web/src/features/agents-view/route.tsx b/apps/web/src/features/agents-view/route.tsx
index bf93a07b48..859a27d01a 100644
--- a/apps/web/src/features/agents-view/route.tsx
+++ b/apps/web/src/features/agents-view/route.tsx
@@ -1,4 +1,5 @@
import { changesSearch } from '@app/features/agent-changes/changes-search';
+import { agentDetailSearch } from '@app/features/block-agent/agent-route';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { defineRoute } from '@app/lib/split-router';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
@@ -113,7 +114,7 @@ export const agentsRoute = defineRoute({
component: AgentsRouteView,
remountKey: ({ id }) => id,
claim: ({ id }) => ({ namespace: 'agent', id }),
- search: [changesSearch.namespace],
+ search: [changesSearch.namespace, agentDetailSearch.namespace],
toReference: ({ id }) => uuidRouteReference(id, 'agent'),
});
@@ -124,7 +125,7 @@ export const codersRoute = defineRoute({
component: AgentsRouteView,
remountKey: ({ id }) => id,
claim: ({ id }) => ({ namespace: 'agent', id }),
- search: [changesSearch.namespace],
+ search: [changesSearch.namespace, agentDetailSearch.namespace],
toReference: ({ id }) => uuidRouteReference(id, 'agent'),
});
diff --git a/apps/web/src/features/block-agent/agent-route.ts b/apps/web/src/features/block-agent/agent-route.ts
new file mode 100644
index 0000000000..4ec83c07b3
--- /dev/null
+++ b/apps/web/src/features/block-agent/agent-route.ts
@@ -0,0 +1,15 @@
+import { createSearchParamsCodec } from '@app/lib/split-router';
+import { z } from 'zod';
+
+export const agentDetailSearch = {
+ namespace: 'agent-detail',
+ schema: z.object({
+ messageTurn: z.number().int().min(-1),
+ author: z.enum(['user', 'agent']),
+ seek: z.string(),
+ }),
+ defaults: { messageTurn: -1, author: 'user' as 'user' | 'agent', seek: '' },
+};
+
+export const agentDetailSearchCodec =
+ createSearchParamsCodec(agentDetailSearch);
diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsx
index 5472cf6e64..5857328c49 100644
--- a/apps/web/src/features/block-agent/component/Block.tsx
+++ b/apps/web/src/features/block-agent/component/Block.tsx
@@ -19,11 +19,12 @@ import { blockHandleSignal } from '@core/signal/load';
import type { NotificationSource } from '@notifications/notification-source';
import { useSearchParams } from '@solidjs/router';
import { EmptyStatePanel } from '@ui';
-import { createSignal, Show, useContext } from 'solid-js';
+import { createEffect, createSignal, on, Show, useContext } from 'solid-js';
import { AgentSessionProvider } from '../agent-session-provider';
import { useAgentSession } from '../context/AgentSessionContext';
import { forgetPendingSession } from '../context/pending-session';
import { parseAgentMessageTarget } from '../core/search-location';
+import { createAgentRouteTarget } from '../primitives/create-agent-route-target';
import { AgentComposer } from './AgentComposer';
import { AgentPreviewBanner } from './AgentPreviewBanner';
import { AgentSessionReadMarker } from './AgentSessionReadMarker';
@@ -36,13 +37,30 @@ function AgentBlockContent(props: {
notificationSource: NotificationSource;
}) {
const [params] = useSearchParams();
+ const routeTarget = createAgentRouteTarget();
const [searchTarget, setSearchTarget] = createSignal(
- parseAgentMessageTarget(params)
+ routeTarget() ?? parseAgentMessageTarget(params)
+ );
+ let routeOwnsTarget = Boolean(routeTarget());
+ createEffect(
+ on(
+ routeTarget,
+ (target) => {
+ if (target || routeOwnsTarget) {
+ routeOwnsTarget = Boolean(target);
+ setSearchTarget(target);
+ }
+ },
+ { defer: true }
+ )
);
createMethodRegistration(blockHandleSignal.get, {
goToLocationFromParams: (params: Record<string, unknown>) => {
const target = parseAgentMessageTarget(params);
- if (target) setSearchTarget(target);
+ if (target) {
+ routeOwnsTarget = false;
+ setSearchTarget(target);
+ }
},
});
const {
diff --git a/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx b/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx
index 3c0d05ca56..ccdcfc4adf 100644
--- a/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx
+++ b/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx
@@ -7,6 +7,7 @@ import type { NotificationSource } from '@notifications/notification-source';
import { cleanup, render } from '@solidjs/testing-library';
import { createSignal, type JSX } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AgentMessageTarget } from '../core/search-location';
import BlockAgent from './Block';
const mocks = vi.hoisted(() => ({
@@ -15,6 +16,8 @@ const mocks = vi.hoisted(() => ({
failed: (): boolean => false,
active: (): boolean => false,
source: undefined as NotificationSource | undefined,
+ target: (): AgentMessageTarget | undefined => undefined,
+ navigate: (_params: Record<string, unknown>) => {},
}));
// Keep both real session hosts and the real read marker. Replace unrelated
@@ -58,8 +61,18 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanelOrThrow: () => ({ isPanelActive: () => mocks.active() }),
}));
vi.mock('@core/block', () => ({ useBlockId: () => 'placeholder-session' }));
-vi.mock('@core/orchestrator', () => ({ createMethodRegistration: vi.fn() }));
+vi.mock('@core/orchestrator', () => ({
+ createMethodRegistration: (
+ _handle: unknown,
+ methods: { goToLocationFromParams: typeof mocks.navigate }
+ ) => {
+ mocks.navigate = methods.goToLocationFromParams;
+ },
+}));
vi.mock('@core/signal/load', () => ({ blockHandleSignal: { get: vi.fn() } }));
+vi.mock('../primitives/create-agent-route-target', () => ({
+ createAgentRouteTarget: () => () => mocks.target(),
+}));
vi.mock('@solidjs/router', () => ({ useSearchParams: () => [{}] }));
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'owner' }));
vi.mock('@core/util/url', () => ({ openExternalUrl: vi.fn() }));
@@ -130,7 +143,11 @@ vi.mock('./AgentSplitHeader', () => ({
vi.mock('./sidepanel/AgentSidePanelSections', () => ({
AgentSidePanelSections: () => null,
}));
-vi.mock('./Transcript', () => ({ Transcript: () => <div>Conversation</div> }));
+vi.mock('./Transcript', () => ({
+ Transcript: (props: { searchTarget?: AgentMessageTarget }) => (
+ <output>{JSON.stringify(props.searchTarget)}</output>
+ ),
+}));
vi.mock('@app/features/agents-view/components/ChatComposer', () => ({
ChatSessionInput: () => null,
}));
@@ -148,12 +165,30 @@ beforeEach(() => {
mocks.loaded = () => false;
mocks.failed = () => false;
mocks.active = () => false;
+ mocks.target = () => undefined;
mocks.source = {
notificationsByEntity: () => ({}),
isLoading: () => false,
} as NotificationSource;
});
+it('preserves an imperative agent target across Home route cleanup', () => {
+ const [target, setTarget] = createSignal<AgentMessageTarget | undefined>({
+ messageTurn: 0,
+ author: 'agent',
+ });
+ mocks.target = target;
+ const view = render(() => <BlockAgent />);
+ const output = () => view.container.querySelector('output')!.textContent;
+ mocks.navigate({ agent_message_turn: '2', agent_message_author: 'user' });
+ setTarget(undefined);
+ expect(JSON.parse(output()!)).toEqual({ messageTurn: 2, author: 'user' });
+ setTarget({ messageTurn: 3, author: 'agent' });
+ expect(JSON.parse(output()!)).toEqual({ messageTurn: 3, author: 'agent' });
+ setTarget(undefined);
+ expect(output()).toBe('');
+});
+
afterEach(() => {
cleanup();
vi.useRealTimers();
@@ -209,4 +244,24 @@ describe.each(['Home', 'Agents'] as const)('%s session host', (host) => {
await vi.advanceTimersByTimeAsync(2_000);
expect(mocks.markRead).not.toHaveBeenCalled();
});
+
+ it('clears a route target before the same session is reopened', () => {
+ const [target, setTarget] = createSignal<AgentMessageTarget>();
+ mocks.target = target;
+ mountHost();
+ const output = () => document.querySelector('output')!.textContent;
+ expect(output()).toBe('');
+ setTarget({ messageTurn: 0, author: 'agent' });
+ expect(JSON.parse(output()!)).toEqual({
+ messageTurn: 0,
+ author: 'agent',
+ });
+ setTarget(undefined);
+ expect(output()).toBe('');
+ setTarget({ messageTurn: 0, author: 'agent' });
+ expect(JSON.parse(output()!)).toEqual({
+ messageTurn: 0,
+ author: 'agent',
+ });
+ });
});
diff --git a/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts b/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts
new file mode 100644
index 0000000000..7f2d537e40
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts
@@ -0,0 +1,13 @@
+import { createSearchParams } from '@app/lib/split-router';
+import { createMemo } from 'solid-js';
+import { agentDetailSearch } from '../agent-route';
+import type { AgentMessageTarget } from '../core/search-location';
+
+export function createAgentRouteTarget() {
+ const [search] = createSearchParams(agentDetailSearch);
+ return createMemo<AgentMessageTarget | undefined>(() => {
+ search.seek;
+ if (search.messageTurn < 0) return;
+ return { messageTurn: search.messageTurn, author: search.author };
+ });
+}
diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx
new file mode 100644
index 0000000000..09c0d8b732
--- /dev/null
+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx
@@ -0,0 +1,92 @@
+import type { CallBlockProps } from '@block-call/constants';
+import { cleanup, render } from '@solidjs/testing-library';
+import { createStore } from 'solid-js/store';
+import { afterEach, expect, it, vi } from 'vitest';
+import { CallBlockAdapter } from './CallBlockAdapter';
+
+const state = vi.hoisted(() => ({
+ search: {} as { transcriptId: string; seek: string },
+ navigate: (_params: CallBlockProps) => {},
+}));
+vi.mock('@app/lib/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+ createSearchParams: () => [state.search],
+}));
+vi.mock('@app/signal/splitLayout', () => ({
+ globalSplitManager: () => undefined,
+}));
+vi.mock('@core/block', () => ({ useBlockId: () => 'call' }));
+vi.mock('@core/orchestrator', () => ({
+ createMethodRegistration: (
+ _handle: unknown,
+ methods: { goToLocationFromParams: typeof state.navigate }
+ ) => {
+ state.navigate = methods.goToLocationFromParams;
+ },
+}));
+vi.mock('@core/signal/load', () => ({
+ blockHandleSignal: { get: () => undefined },
+}));
+vi.mock('@solidjs/router', () => ({ useSearchParams: () => [{}] }));
+vi.mock('@queries/call/call', () => ({
+ useCallRecordQuery: () => ({ data: {} }),
+}));
+vi.mock('@core/component/DocumentBlockContainer', () => ({
+ DocumentBlockContainer: (props: { children: unknown }) => props.children,
+}));
+vi.mock('@components/app/side-panel', () => ({
+ SidePanel: { Layout: (props: { children: unknown }) => props.children },
+}));
+vi.mock('./CallRecording/CallRecordingSplitHeader', () => ({
+ CallRecordingSplitHeader: () => null,
+}));
+vi.mock('./sidepanel/CallSidePanelSections', () => ({
+ CallSidePanelSections: () => null,
+}));
+vi.mock('./CallRecording/CallRecordingBody', () => ({
+ CallRecordingBody: (props: {
+ transcriptTarget?: { transcriptId: string; gen: number };
+ }) => <output>{JSON.stringify(props.transcriptTarget)}</output>,
+}));
+afterEach(cleanup);
+
+it('delivers and clears transcript requests in the legacy call body', () => {
+ const [search, setSearch] = createStore({
+ transcriptId: 'segment',
+ seek: 'first',
+ });
+ state.search = search;
+ const view = render(() => <CallBlockAdapter />);
+ const target = () =>
+ JSON.parse(view.container.querySelector('output')!.textContent!);
+ expect(target()).toEqual({ transcriptId: 'segment', gen: 0 });
+ setSearch('seek', 'repeat');
+ expect(target()).toEqual({ transcriptId: 'segment', gen: 1 });
+ setSearch({ transcriptId: 'another', seek: 'next' });
+ expect(target().transcriptId).toBe('another');
+ expect(target().gen).toBeGreaterThan(1);
+ setSearch({ transcriptId: '', seek: '' });
+ expect(view.container.querySelector('output')!.textContent).toBe('');
+ setSearch({ transcriptId: 'segment', seek: 'reopen' });
+ expect(target().transcriptId).toBe('segment');
+});
+
+it('preserves an imperative transcript target across Home route cleanup', () => {
+ const [search, setSearch] = createStore({
+ transcriptId: 'route-segment',
+ seek: 'first',
+ });
+ state.search = search;
+ const view = render(() => <CallBlockAdapter />);
+ const target = () =>
+ JSON.parse(view.container.querySelector('output')!.textContent!);
+ state.navigate({ call_transcript_id: 'mention-segment' });
+ const mentionTarget = target();
+ setSearch({ transcriptId: '', seek: '' });
+ expect(target()).toEqual(mentionTarget);
+ expect(target().transcriptId).toBe('mention-segment');
+ setSearch({ transcriptId: 'new-route-segment', seek: 'next' });
+ expect(target().transcriptId).toBe('new-route-segment');
+ setSearch({ transcriptId: '', seek: '' });
+ expect(view.container.querySelector('output')!.textContent).toBe('');
+});
diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.tsx
index e55fac5e67..aac609d098 100644
--- a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx
+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.tsx
@@ -1,3 +1,4 @@
+import { createSearchParams } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
import {
type CallBlockProps,
@@ -11,7 +12,8 @@ import { createMethodRegistration } from '@core/orchestrator';
import { blockHandleSignal } from '@core/signal/load';
import { useCallRecordQuery } from '@queries/call/call';
import { useSearchParams } from '@solidjs/router';
-import { createSignal, Show } from 'solid-js';
+import { createEffect, createSignal, on, Show } from 'solid-js';
+import { callDetailSearch } from '../call-route';
import { CallRecordingBody } from './CallRecording/CallRecordingBody';
import { CallRecordingSplitHeader } from './CallRecording/CallRecordingSplitHeader';
import { CallSidePanelSections } from './sidepanel/CallSidePanelSections';
@@ -21,8 +23,10 @@ export function CallBlockAdapter(props: CallBlockProps) {
const callRecord = useCallRecordQuery(() => callId);
const blockHandle = blockHandleSignal.get;
const [searchParams] = useSearchParams();
+ const [routeSearch] = createSearchParams(callDetailSearch);
const initialTranscriptId = ((): string | undefined => {
+ if (routeSearch.transcriptId) return routeSearch.transcriptId;
const fromProps = props[URL_PARAMS.transcriptId];
if (fromProps) return fromProps;
const isSingleSplit = globalSplitManager()?.splits().length === 1;
@@ -38,10 +42,33 @@ export function CallBlockAdapter(props: CallBlockProps) {
: undefined
);
+ let routeOwnsTarget = Boolean(routeSearch.transcriptId);
+ createEffect(
+ on(
+ () => [routeSearch.transcriptId, routeSearch.seek],
+ () => {
+ if (!routeSearch.transcriptId) {
+ if (routeOwnsTarget) {
+ routeOwnsTarget = false;
+ setTranscriptTarget(undefined);
+ }
+ return;
+ }
+ routeOwnsTarget = true;
+ setTranscriptTarget((previous) => ({
+ transcriptId: routeSearch.transcriptId,
+ gen: (previous?.gen ?? 0) + 1,
+ }));
+ },
+ { defer: true }
+ )
+ );
+
createMethodRegistration(blockHandle, {
goToLocationFromParams: async (params: CallBlockProps) => {
const next = params[URL_PARAMS.transcriptId];
if (!next) return;
+ routeOwnsTarget = false;
setTranscriptTarget((prev) => ({
transcriptId: next,
gen: (prev?.gen ?? 0) + 1,
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
new file mode 100644
index 0000000000..b3ed8e7a6d
--- /dev/null
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
@@ -0,0 +1,152 @@
+import type { ChannelTargetRequest } from '@channel/Channel/ChannelSurface';
+import { cleanup, render } from '@solidjs/testing-library';
+import { createStore } from 'solid-js/store';
+import { afterEach, expect, it, vi } from 'vitest';
+import { NewChannelBlockAdapter } from './NewChannelBlockAdapter';
+
+const state = vi.hoisted(() => ({
+ search: {} as { messageId: string; threadId: string; seek: string },
+ navigate: (_params: Record<string, unknown>) => {},
+ latest: () => {},
+}));
+vi.mock('@app/lib/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+ createSearchParams: () => [state.search],
+}));
+vi.mock('@app/signal/splitLayout', () => ({
+ globalSplitManager: () => undefined,
+}));
+vi.mock('@core/block', () => ({ useBlockId: () => 'channel' }));
+vi.mock('@core/constant/allBlocks', () => ({
+ blocks: {},
+ resolveBlockAlias: (type: string) => type,
+}));
+vi.mock('@core/orchestrator', () => ({
+ createMethodRegistration: (
+ _handle: unknown,
+ methods: {
+ goToLocationFromParams: typeof state.navigate;
+ goToLatest: typeof state.latest;
+ }
+ ) => {
+ state.navigate = methods.goToLocationFromParams;
+ state.latest = methods.goToLatest;
+ },
+}));
+vi.mock('@core/signal/load', () => ({
+ blockHandleSignal: { get: () => undefined },
+}));
+vi.mock('@core/signal/blockElement', () => ({
+ blockHotkeyScopeSignal: { set: () => {} },
+}));
+vi.mock('@solidjs/router', () => ({
+ useSearchParams: () => [{}, () => {}],
+}));
+vi.mock('@app/features/next-soup/actions', () => ({
+ useBlockEntityCommands: () => {},
+}));
+vi.mock('@components/app/split-layout/layoutUtils', () => ({
+ useCanAutofocusSplitContent: () => false,
+ useSplitPanelOrThrow: () => ({
+ splitHotkeyScope: 'split',
+ handle: {
+ currentEntryState: () => undefined,
+ registerEntryStateCaptor: () => () => {},
+ },
+ }),
+}));
+vi.mock('@components/app/useNavigatedFromJK', () => ({
+ useNavigatedFromJK: () => ({ navigatedFromJK: () => false }),
+}));
+vi.mock('@channel/Call/CallContext', () => ({
+ useCallContextOptional: () => undefined,
+}));
+vi.mock('@channel/Bots/use-channel-bot-management', () => ({
+ useChannelBotManagement: () => ({}),
+}));
+vi.mock('@app/features/chat/ChatWithAgentButton', () => ({}));
+vi.mock('@channel/Attachments/ChannelAttachmentsTab', () => ({}));
+vi.mock('@channel/Call/CallEventSync', () => ({}));
+vi.mock('@channel/Call/ChannelCallAutoJoin', () => ({}));
+vi.mock('@channel/Call/ChannelCallButton', () => ({}));
+vi.mock('@channel/Call/ChannelCallTab', () => ({}));
+vi.mock('@channel/Call/use-call', () => ({}));
+vi.mock('@channel/Calls/ChannelCallsTab', () => ({}));
+vi.mock('@channel/Channel/ChannelTopBarLiveIndicators', () => ({}));
+vi.mock('@channel/Participants/ChannelParticipantsTab', () => ({}));
+vi.mock('@channel/channel-invite-button', () => ({}));
+vi.mock('@channel/channel-picture', () => ({}));
+vi.mock('@components/app/split-layout/components/SplitFileMenu', () => ({}));
+vi.mock('@components/app/split-layout/components/SplitLabel', () => ({}));
+vi.mock('@components/app/split-layout/components/SplitHeader', () => ({}));
+vi.mock('@core/context/channels', () => ({}));
+vi.mock('@core/context/user', () => ({}));
+vi.mock('@queries/call/call', () => ({}));
+vi.mock('@queries/channel/channel-participants', () => ({}));
+vi.mock('@entity', () => ({}));
+vi.mock('@ui', () => ({
+ cn: (...values: string[]) => values.join(' '),
+}));
+vi.mock('@channel/Channel/use-channel-tab-items', () => ({
+ normalizeChannelTab: (tab: string) => tab,
+}));
+vi.mock('./Top', () => ({}));
+// Observe the real adapter's requests without mounting the timeline/chrome.
+vi.mock('@channel/Channel/ChannelSurface', () => ({
+ ChannelSurface: (props: { targetRequest?: ChannelTargetRequest }) => (
+ <output>{JSON.stringify(props.targetRequest)}</output>
+ ),
+ ChannelMessages: () => null,
+}));
+afterEach(cleanup);
+
+function setup() {
+ const [search, setSearch] = createStore({
+ messageId: 'route-message',
+ threadId: '',
+ seek: 'first',
+ });
+ state.search = search;
+ const view = render(() => <NewChannelBlockAdapter />);
+ const target = () => {
+ const text = view.container.querySelector('output')!.textContent;
+ return text ? JSON.parse(text) : undefined;
+ };
+ return { setSearch, target };
+}
+
+it('clears a route-owned channel target and accepts the next request', () => {
+ const { setSearch, target } = setup();
+ expect(target()).toEqual({ kind: 'message', messageId: 'route-message' });
+ setSearch({ messageId: '', seek: '' });
+ expect(target()).toBeUndefined();
+ setSearch({ messageId: 'reply', threadId: 'thread', seek: 'next' });
+ expect(target()).toEqual({
+ kind: 'message',
+ messageId: 'reply',
+ threadId: 'thread',
+ });
+});
+
+it.each(['message', 'latest'] as const)(
+ 'preserves an imperative %s request across Home route cleanup',
+ (kind) => {
+ const { setSearch, target } = setup();
+ if (kind === 'message')
+ state.navigate({ channel_message_id: 'mention-message' });
+ else state.latest();
+ setSearch({ messageId: '', seek: '' });
+ expect(target()).toEqual(
+ kind === 'message'
+ ? { kind: 'message', messageId: 'mention-message' }
+ : { kind: 'latest' }
+ );
+ setSearch({ messageId: 'new-route-message', seek: 'next' });
+ expect(target()).toEqual({
+ kind: 'message',
+ messageId: 'new-route-message',
+ });
+ setSearch({ messageId: '', seek: '' });
+ expect(target()).toBeUndefined();
+ }
+);
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index 57b7fccdc3..02f263b879 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -1,3 +1,4 @@
+import { channelsSearch } from '@app/features/channels-view/channels-route';
import {
ChatWithAgentButton,
ChatWithAgentIcon,
@@ -7,6 +8,7 @@ import {
makeRenameAction,
useBlockEntityCommands,
} from '@app/features/next-soup/actions';
+import { createSearchParams } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
import { URL_PARAMS } from '@block-channel/constants';
import { ChannelAttachmentsTab } from '@channel/Attachments/ChannelAttachmentsTab';
@@ -83,8 +85,10 @@ import { useSearchParams } from '@solidjs/router';
import { cn } from '@ui';
import {
createComputed,
+ createEffect,
createSignal,
Match,
+ on,
onCleanup,
Show,
Suspense,
@@ -314,8 +318,14 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
const channelId = useBlockId();
const blockHandle = blockHandleSignal.get;
const [searchParams, setSearchParams] = useSearchParams();
+ const [routeSearch] = createSearchParams(channelsSearch);
const initialTargetMessageParams = (): ChannelTargetMessageParams => {
+ if (routeSearch.messageId)
+ return {
+ [URL_PARAMS.message]: routeSearch.messageId,
+ [URL_PARAMS.thread]: routeSearch.threadId || undefined,
+ };
const hasPropsTarget =
props[URL_PARAMS.message] !== undefined ||
props[URL_PARAMS.thread] !== undefined;
@@ -353,6 +363,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
] as ChannelEntryStateSnapshot | undefined;
const hasInitialTargetRequest = () => {
+ if (routeSearch.messageId) return true;
const hasPropsTarget =
props[URL_PARAMS.message] !== undefined ||
props[URL_PARAMS.thread] !== undefined;
@@ -390,12 +401,36 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
const [targetRequest, setTargetRequest] = createSignal<
ChannelTargetRequest | undefined
>(toChannelTargetRequest(initialTargetMessageParams()));
+ let routeOwnsTarget = Boolean(routeSearch.messageId);
let surfaceApi: ChannelSurfaceApi | undefined;
const setActiveTab = (tab: ChannelTabId) => {
setActiveTabInternal(normalizeChannelTab(tab));
};
+ createEffect(
+ on(
+ () => [routeSearch.messageId, routeSearch.threadId, routeSearch.seek],
+ () => {
+ if (!routeSearch.messageId) {
+ if (routeOwnsTarget) {
+ routeOwnsTarget = false;
+ setTargetRequest(undefined);
+ }
+ return;
+ }
+ routeOwnsTarget = true;
+ setActiveTab(DEFAULT_CHANNEL_TAB);
+ setTargetRequest({
+ kind: 'message',
+ messageId: routeSearch.messageId,
+ threadId: routeSearch.threadId || undefined,
+ });
+ },
+ { defer: true }
+ )
+ );
+
const botManagement = useChannelBotManagement({
channelId,
hotkeyScopeId: splitPanel.splitHotkeyScope,
@@ -442,6 +477,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
// leaves it waiting for whenever the user returns to Messages.
const target = toChannelTargetRequest(params);
if (target) {
+ routeOwnsTarget = false;
setActiveTab(DEFAULT_CHANNEL_TAB);
setTargetRequest(target);
}
@@ -457,6 +493,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
}
},
goToLatest: async () => {
+ routeOwnsTarget = false;
setActiveTab(DEFAULT_CHANNEL_TAB);
setTargetRequest({ kind: 'latest' });
},
diff --git a/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx b/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx
new file mode 100644
index 0000000000..304fb7cd60
--- /dev/null
+++ b/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx
@@ -0,0 +1,115 @@
+import type { EmailThreadHost } from '@app/features/email-thread/context/email-thread-context';
+import { cleanup, render } from '@solidjs/testing-library';
+import type { ComponentProps } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { afterEach, expect, it, vi } from 'vitest';
+import { EmailBlockAdapter } from './EmailBlockAdapter';
+
+const state = vi.hoisted(() => ({
+ search: {} as { messageId: string; seek: string },
+ navigate: (_params: Record<string, unknown>) => {},
+ host: undefined as EmailThreadHost | undefined,
+}));
+vi.mock('@app/lib/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+ createSearchParams: () => [state.search],
+}));
+vi.mock('@solidjs/router', () => ({ useSearchParams: () => [{}] }));
+vi.mock('@components/app/split-layout/layoutUtils', () => ({
+ useSplitPanel: () => undefined,
+ useCanAutofocusSplitContent: () => false,
+}));
+vi.mock('@core/orchestrator', () => ({
+ createMethodRegistration: (
+ _handle: unknown,
+ methods: { goToLocationFromParams: typeof state.navigate }
+ ) => {
+ state.navigate = methods.goToLocationFromParams;
+ },
+}));
+vi.mock('@core/signal/load', () => ({
+ blockHandleSignal: { get: () => undefined },
+}));
+vi.mock('@core/signal/blockElement', () => ({
+ blockElementSignal: { get: () => undefined },
+ blockHotkeyScopeSignal: { get: () => undefined },
+}));
+vi.mock('@core/hotkey/utils', () => ({ registerScopeSignalHotkey: () => {} }));
+vi.mock('./use-email-list-navigation', () => ({
+ useEmailListNavigation: () => undefined,
+}));
+vi.mock('./util/emailHotkeys', () => ({ registerEmailHotkeys: () => {} }));
+vi.mock('./component/TopBar', () => ({ TopBar: () => null }));
+vi.mock('./EmailThreadHostView', () => ({
+ EmailThreadHostView: (props: { host: EmailThreadHost }) => {
+ state.host = props.host;
+ return null;
+ },
+}));
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+it('preserves a pending imperative target when Home clears route search', () => {
+ vi.useFakeTimers();
+ const [search, setSearch] = createStore({
+ messageId: 'route-message',
+ seek: 'request',
+ });
+ state.search = search;
+ const props = {
+ title: 'Email',
+ threadId: () => 'thread',
+ source: {},
+ threadTransport: {},
+ } as ComponentProps<typeof EmailBlockAdapter>;
+ render(() => <EmailBlockAdapter {...props} />);
+ expect(state.host?.targetMessageId?.()).toBe('route-message');
+ state.navigate({ email_message_id: 'legacy-message' });
+ setSearch({ messageId: '', seek: '' });
+ vi.runAllTimers();
+ expect(state.host?.targetMessageId?.()).toBe('legacy-message');
+ setSearch({ messageId: 'new-route-message', seek: 'new-request' });
+ expect(state.host?.targetMessageId?.()).toBe('new-route-message');
+});
+
+it('clears a route-owned target without replaying its previous message', () => {
+ const [search, setSearch] = createStore({
+ messageId: 'route-message',
+ seek: 'request',
+ });
+ state.search = search;
+ const props = {
+ title: 'Email',
+ threadId: () => 'thread',
+ source: {},
+ threadTransport: {},
+ } as ComponentProps<typeof EmailBlockAdapter>;
+ render(() => <EmailBlockAdapter {...props} />);
+ setSearch({ messageId: '', seek: '' });
+ expect(state.host?.targetMessageId?.()).toBeUndefined();
+ expect(state.host?.targetRequest?.()).toBeUndefined();
+});
+
+it('leaves a delivered imperative target and its request unchanged when route search clears', () => {
+ vi.useFakeTimers();
+ const [search, setSearch] = createStore({
+ messageId: 'route-message',
+ seek: 'request',
+ });
+ state.search = search;
+ const props = {
+ title: 'Email',
+ threadId: () => 'thread',
+ source: {},
+ threadTransport: {},
+ } as ComponentProps<typeof EmailBlockAdapter>;
+ render(() => <EmailBlockAdapter {...props} />);
+ state.navigate({ email_message_id: 'legacy-message' });
+ vi.runAllTimers();
+ const request = state.host?.targetRequest?.();
+ setSearch({ messageId: '', seek: '' });
+ expect(state.host?.targetMessageId?.()).toBe('legacy-message');
+ expect(state.host?.targetRequest?.()).toBe(request);
+});
diff --git a/apps/web/src/features/block-email/EmailBlockAdapter.tsx b/apps/web/src/features/block-email/EmailBlockAdapter.tsx
index 6e908d55e7..83b37c866b 100644
--- a/apps/web/src/features/block-email/EmailBlockAdapter.tsx
+++ b/apps/web/src/features/block-email/EmailBlockAdapter.tsx
@@ -3,6 +3,8 @@ import type {
EmailThreadSource,
} from '@app/features/email-thread/context/email-thread-context';
import { URL_PARAMS } from '@app/features/email-thread/core/location';
+import { emailDetailSearch } from '@app/features/email-view/email-route';
+import { createSearchParams } from '@app/lib/split-router';
import {
useCanAutofocusSplitContent,
useSplitPanel,
@@ -17,7 +19,13 @@ import {
} from '@core/signal/blockElement';
import { blockHandleSignal } from '@core/signal/load';
import { useSearchParams } from '@solidjs/router';
-import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
import { TopBar } from './component/TopBar';
import {
EmailThreadHostView,
@@ -33,9 +41,15 @@ export function EmailBlockAdapter(props: {
threadTransport: EmailThreadHostViewProps['threadTransport'];
}) {
const [params] = useSearchParams();
+ const [routeSearch] = createSearchParams(emailDetailSearch);
const rawTarget = params[URL_PARAMS.messageId];
const [targetMessageId, setTargetMessageId] = createSignal(
- Array.isArray(rawTarget) ? rawTarget[0] : rawTarget
+ routeSearch.messageId ||
+ (Array.isArray(rawTarget) ? rawTarget[0] : rawTarget)
+ );
+ let routeOwnsTarget = Boolean(routeSearch.messageId);
+ const [targetRequest, setTargetRequest] = createSignal<string | undefined>(
+ routeOwnsTarget ? routeSearch.seek : undefined
);
const split = useSplitPanel();
const listNavigation = useEmailListNavigation(props.threadId);
@@ -44,12 +58,34 @@ export function EmailBlockAdapter(props: {
const hotkeyScope = blockHotkeyScopeSignal.get;
const focusContainer = () => blockElement()?.focus({ preventScroll: true });
let targetTimer: ReturnType<typeof setTimeout> | undefined;
+ createEffect(
+ on(
+ () => [routeSearch.messageId, routeSearch.seek],
+ () => {
+ if (!routeSearch.messageId) {
+ if (routeOwnsTarget) {
+ routeOwnsTarget = false;
+ setTargetMessageId(undefined);
+ setTargetRequest(undefined);
+ }
+ return;
+ }
+ clearTimeout(targetTimer);
+ routeOwnsTarget = true;
+ setTargetMessageId(routeSearch.messageId);
+ setTargetRequest(routeSearch.seek);
+ },
+ { defer: true }
+ )
+ );
createMethodRegistration(blockHandleSignal.get, {
goToLocationFromParams: (params: Record<string, unknown>) => {
const id = params[URL_PARAMS.messageId];
if (typeof id !== 'string' || !id) return;
clearTimeout(targetTimer);
+ routeOwnsTarget = false;
setTargetMessageId(undefined);
+ setTargetRequest(undefined);
targetTimer = setTimeout(() => setTargetMessageId(id), 0);
},
});
@@ -63,6 +99,7 @@ export function EmailBlockAdapter(props: {
const host: EmailThreadHost = {
listNavigation,
targetMessageId,
+ targetRequest,
focusContainer,
isActive: () => split?.isPanelActive() !== false,
registerKeyboard: (handlers) => {
diff --git a/apps/web/src/features/block-md/component/Block.tsx b/apps/web/src/features/block-md/component/Block.tsx
index 2c6d11f17a..c42d6c4112 100644
--- a/apps/web/src/features/block-md/component/Block.tsx
+++ b/apps/web/src/features/block-md/component/Block.tsx
@@ -9,7 +9,7 @@ import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsla
import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';
import { useCanAutofocusSplitContent } from '@components/app/split-layout/layoutUtils';
import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';
-import { useBlockAliasedName, useBlockId } from '@core/block';
+import { useBlockAliasedName, useBlockId, useIsNestedBlock } from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { ENABLE_MARKDOWN_SIDE_PANEL } from '@core/constant/featureFlags';
import { blockDataSignal as blockLoaderDataSignal } from '@core/internal/BlockLoader';
@@ -32,6 +32,7 @@ import { Show, Suspense } from 'solid-js';
import { createMarkdownDocumentState } from '../context/markdown-document-state';
import type { MarkdownData } from '../definition';
import { OldOverlay } from '../history/OldOverlay';
+import { createMarkdownRouteNavigation } from '../primitives/create-markdown-route-navigation';
import { loadMarkdownCachedSnapshot } from '../queries/markdown-document-operations';
import type { MarkdownDocumentKind, MarkdownDocumentSource } from '../types';
import { FindAndReplace } from './FindAndReplace';
@@ -78,6 +79,11 @@ export default function MarkdownBlockAdapter(props: BlockMarkdownProps) {
const isInstructions = () =>
instructionsMdId.isSuccess && documentId === instructionsMdId.data;
const markdownState = createMarkdownDocumentState();
+ if (!useIsNestedBlock())
+ createMarkdownRouteNavigation(
+ () => documentId,
+ markdownState.params.navigate
+ );
createMethodRegistration(blockHandleSignal.get, {
goToLocationFromParams: markdownState.params.navigate,
});
diff --git a/apps/web/src/features/block-md/markdown-route.ts b/apps/web/src/features/block-md/markdown-route.ts
new file mode 100644
index 0000000000..ac8bb0f733
--- /dev/null
+++ b/apps/web/src/features/block-md/markdown-route.ts
@@ -0,0 +1,15 @@
+import { createSearchParamsCodec } from '@app/lib/split-router';
+import { z } from 'zod';
+
+export const markdownDetailSearch = {
+ namespace: 'markdown-detail',
+ schema: z.object({
+ documentId: z.string(),
+ nodeId: z.string(),
+ seek: z.string(),
+ }),
+ defaults: { documentId: '', nodeId: '', seek: '' },
+};
+
+export const markdownDetailSearchCodec =
+ createSearchParamsCodec(markdownDetailSearch);
diff --git a/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts b/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts
new file mode 100644
index 0000000000..90a949923e
--- /dev/null
+++ b/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts
@@ -0,0 +1,25 @@
+import { createSearchParams } from '@app/lib/split-router';
+import { type Accessor, createEffect, on } from 'solid-js';
+import { URL_PARAMS } from '../constants';
+import { markdownDetailSearch } from '../markdown-route';
+
+/** Deliver route requests to the editor's existing queued location handler. */
+export function createMarkdownRouteNavigation(
+ documentId: Accessor<string>,
+ navigate: (params: Record<string, string>) => void
+) {
+ const [search] = createSearchParams(markdownDetailSearch);
+ createEffect(
+ on(
+ () =>
+ [search.nodeId, search.seek, search.documentId, documentId()] as const,
+ ([nodeId]) => {
+ if (
+ nodeId &&
+ (!search.documentId || search.documentId === documentId())
+ )
+ navigate({ [URL_PARAMS.nodeId]: nodeId });
+ }
+ )
+ );
+}
diff --git a/apps/web/src/features/block-pdf/component/Block.tsx b/apps/web/src/features/block-pdf/component/Block.tsx
index e70773eb76..0119b6806b 100644
--- a/apps/web/src/features/block-pdf/component/Block.tsx
+++ b/apps/web/src/features/block-pdf/component/Block.tsx
@@ -14,6 +14,7 @@ import { useSearchParams } from '@solidjs/router';
import { Show } from 'solid-js';
import { usePdfDocument } from '../context/pdf-document-context';
import type { PdfBlockData } from '../definition';
+import { createPdfRouteTarget } from '../primitives/create-pdf-route-target';
import { type LocationSearchParams, URL_PARAMS } from '../signal/location';
import {
PdfDocument,
@@ -28,6 +29,9 @@ export default function BlockPdf() {
useBlockEntityCommands();
const documentId = useBlockId();
const isNested = useIsNestedBlock();
+ const target = isNested
+ ? () => undefined
+ : createPdfRouteTarget(() => documentId);
const metadata = blockMetadataSignal.get;
const documentName = useBlockDocumentName('Unknown Filename');
const canComment = useCanComment();
@@ -57,6 +61,7 @@ export default function BlockPdf() {
isOwner: isOwner(),
}}
locationParams={getLocationParams(searchParams)}
+ navigationTarget={target()}
registerMethods={registerMethods}
>
<PdfBlockContent />
diff --git a/apps/web/src/features/block-pdf/component/PdfDocument.test.tsx b/apps/web/src/features/block-pdf/component/PdfDocument.test.tsx
new file mode 100644
index 0000000000..b1134e5084
--- /dev/null
+++ b/apps/web/src/features/block-pdf/component/PdfDocument.test.tsx
@@ -0,0 +1,121 @@
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal, type JSX } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { LocationBlockParams } from '../signal/location';
+import { PdfDocument, type PdfDocumentMethods } from './PdfDocument';
+
+const state = vi.hoisted(() => ({
+ ready: (): boolean => false,
+ visible: (): boolean => false,
+ navigate: vi.fn(),
+ initial: vi.fn(),
+ clearOverlays: vi.fn(),
+}));
+
+vi.mock('@solidjs/router', () => ({ useBeforeLeave: () => {} }));
+vi.mock('../context/pdf-document-context', () => ({
+ PdfDocumentProvider: (props: { children: JSX.Element }) => props.children,
+ usePdfDocument: () => ({
+ isNested: () => true,
+ documentVersionId: () => undefined,
+ setPersistedViewLocation: () => {},
+ locationParams: () => ({ pageNumber: '3', yPos: '0' }),
+ }),
+}));
+vi.mock('../context/pdf-viewer-context', () => ({
+ PdfViewerProvider: (props: { children: JSX.Element }) => props.children,
+ usePdfViewer: () => ({
+ root: {
+ isReady: () => state.ready(),
+ hasVisiblePages: () => state.visible(),
+ instance: () => ({ clearAllOverlays: state.clearOverlays }),
+ },
+ setRootElement: () => {},
+ }),
+}));
+vi.mock('../context/pdf-comments-context', () => ({
+ PdfCommentsProvider: (props: { children: JSX.Element }) => props.children,
+}));
+vi.mock('../signal/location', () => ({
+ useGoToLinkLocation: () => state.initial,
+ useGoToLinkLocationFromParams: () => state.navigate,
+}));
+vi.mock('../signal/save', () => ({ usePdfSave: () => vi.fn() }));
+vi.mock('../signal/setting', () => ({ useUpdateColorsEffect: () => {} }));
+vi.mock('../store/comments/commentStore', () => ({
+ usePdfCommentProjection: () => ({}),
+}));
+vi.mock('../store/placeables', () => ({
+ useSyncActivePlaceableWithCommentThread: () => {},
+}));
+vi.mock('../websocket/preprocess', () => ({ preprocess: vi.fn() }));
+vi.mock('./Document', () => ({ Document: () => null }));
+
+beforeEach(() => vi.clearAllMocks());
+afterEach(cleanup);
+
+function setup(initialTarget?: LocationBlockParams, initiallyReady = false) {
+ const [target, setTarget] = createSignal(initialTarget);
+ const [ready, setReady] = createSignal(initiallyReady);
+ const [visible, setVisible] = createSignal(false);
+ state.ready = ready;
+ state.visible = visible;
+ let methods!: Partial<PdfDocumentMethods>;
+ render(() => (
+ <PdfDocument
+ documentId="document"
+ documentName="PDF"
+ permissions={{ canComment: false, canEdit: false, isOwner: false }}
+ navigationTarget={target()}
+ registerMethods={(value) => (methods = value)}
+ >
+ {null}
+ </PdfDocument>
+ ));
+ return { setTarget, setReady, setVisible, methods };
+}
+
+it.each([false, true])(
+ 'discards a cleared route target while waiting for the viewer (ready=%s)',
+ (ready) => {
+ const test = setup({ pdf_search_page: '7' }, ready);
+ test.setTarget(undefined);
+ test.setReady(true);
+ test.setVisible(true);
+ expect(state.navigate).not.toHaveBeenCalled();
+ expect(state.clearOverlays).not.toHaveBeenCalled();
+
+ test.setTarget({ pdf_search_page: '8' });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith({
+ pdf_search_page: '8',
+ });
+ test.setTarget({ pdf_search_page: '8' });
+ expect(state.navigate).toHaveBeenCalledTimes(2);
+ }
+);
+
+it('preserves a newer imperative location when the route target clears', async () => {
+ const test = setup({ pdf_search_page: '7' });
+ const mention = { pdf_page_number: '4', pdf_page_y: '0.5' };
+ await test.methods.goToLocationFromParams?.(mention);
+ test.setTarget(undefined);
+ test.setReady(true);
+ test.setVisible(true);
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith(mention);
+
+ test.setVisible(false);
+ test.setTarget({ pdf_search_page: '8' });
+ test.setTarget(undefined);
+ test.setVisible(true);
+ expect(state.navigate).toHaveBeenCalledTimes(1);
+});
+
+it('keeps legacy initial-location navigation when there is no route target', () => {
+ const test = setup();
+ test.setReady(true);
+ expect(state.initial).toHaveBeenCalledExactlyOnceWith({
+ pageNumber: '3',
+ yPos: '0',
+ });
+ expect(state.navigate).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/block-pdf/component/PdfDocument.tsx b/apps/web/src/features/block-pdf/component/PdfDocument.tsx
index ef2311548e..2fff23d053 100644
--- a/apps/web/src/features/block-pdf/component/PdfDocument.tsx
+++ b/apps/web/src/features/block-pdf/component/PdfDocument.tsx
@@ -66,6 +66,7 @@ export type PdfDocumentProps = {
portalScope?: PortalScope;
permissions: PdfDocumentPermissions;
locationParams?: LocationSearchParams;
+ navigationTarget?: LocationBlockParams;
registerMethods?: (methods: Partial<PdfDocumentMethods>) => void;
children: JSX.Element;
};
@@ -113,9 +114,25 @@ function PdfDocumentBehavior(props: PdfDocumentProps) {
const goToInitialLocation = useGoToLinkLocation();
const goToLocationFromParams = useGoToLinkLocationFromParams();
let imperativeNavigationQueued = false;
+ let routeOwnsTarget = false;
+
+ createEffect(() => {
+ const target = props.navigationTarget;
+ if (!target) {
+ if (routeOwnsTarget) {
+ routeOwnsTarget = false;
+ setPendingLocationParams(undefined);
+ }
+ return;
+ }
+ routeOwnsTarget = true;
+ imperativeNavigationQueued = true;
+ setPendingLocationParams({ ...target });
+ });
props.registerMethods?.({
goToLocationFromParams: async (params) => {
+ routeOwnsTarget = false;
imperativeNavigationQueued = true;
setPendingLocationParams({ ...params });
},
diff --git a/apps/web/src/features/block-pdf/pdf-route.ts b/apps/web/src/features/block-pdf/pdf-route.ts
new file mode 100644
index 0000000000..317da88acc
--- /dev/null
+++ b/apps/web/src/features/block-pdf/pdf-route.ts
@@ -0,0 +1,24 @@
+import { createSearchParamsCodec } from '@app/lib/split-router';
+import { z } from 'zod';
+
+export const pdfDetailSearch = {
+ namespace: 'pdf-detail',
+ schema: z.object({
+ documentId: z.string(),
+ page: z.number().int().nonnegative(),
+ highlightTerms: z.array(z.string()),
+ snippet: z.string(),
+ query: z.string(),
+ seek: z.string(),
+ }),
+ defaults: {
+ documentId: '',
+ page: 0,
+ highlightTerms: [] as string[],
+ snippet: '',
+ query: '',
+ seek: '',
+ },
+};
+
+export const pdfDetailSearchCodec = createSearchParamsCodec(pdfDetailSearch);
diff --git a/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts b/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts
new file mode 100644
index 0000000000..3c4d25982a
--- /dev/null
+++ b/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts
@@ -0,0 +1,24 @@
+import { createSearchParams } from '@app/lib/split-router';
+import { type Accessor, createMemo } from 'solid-js';
+import { URL_PARAMS } from '../constants';
+import { pdfDetailSearch } from '../pdf-route';
+import type { LocationBlockParams } from '../signal/location';
+
+export function createPdfRouteTarget(documentId: Accessor<string>) {
+ const [search] = createSearchParams(pdfDetailSearch);
+ return createMemo<LocationBlockParams | undefined>(() => {
+ // A fresh request must replay navigation even when its location is unchanged.
+ search.seek;
+ if (
+ search.page < 1 ||
+ (search.documentId && search.documentId !== documentId())
+ )
+ return;
+ return {
+ [URL_PARAMS.searchPage]: String(search.page),
+ [URL_PARAMS.searchHighlightTerms]: JSON.stringify(search.highlightTerms),
+ [URL_PARAMS.searchSnippet]: search.snippet,
+ [URL_PARAMS.searchRawQuery]: search.query,
+ };
+ });
+}
diff --git a/apps/web/src/features/channel/Channel/ChannelDetail.tsx b/apps/web/src/features/channel/Channel/ChannelDetail.tsx
index 8efb1c44c8..063994d36e 100644
--- a/apps/web/src/features/channel/Channel/ChannelDetail.tsx
+++ b/apps/web/src/features/channel/Channel/ChannelDetail.tsx
@@ -77,7 +77,7 @@ export type ChannelDetailProps = {
*/
target?: ChannelTargetRequest;
/** Re-aim the current target without remounting the channel. */
- navigationRequest?: number;
+ navigationRequest?: number | string;
/** Name shown until the channel loads. */
fallbackName?: string;
/** Whether the composer grabs focus on mount. Defaults to false. */
diff --git a/apps/web/src/features/channels-view/channels-route.ts b/apps/web/src/features/channels-view/channels-route.ts
index a3023c20a6..bbc61ace81 100644
--- a/apps/web/src/features/channels-view/channels-route.ts
+++ b/apps/web/src/features/channels-view/channels-route.ts
@@ -9,12 +9,14 @@ export const channelsSearch = {
mobileTab: z.enum(['channels', 'direct_messages', 'recents']),
messageId: z.string(),
threadId: z.string(),
+ seek: z.string(),
}),
defaults: {
tab: 'browse' as ChannelsTab,
mobileTab: 'channels' as ChannelsQueryScope,
messageId: '',
threadId: '',
+ seek: '',
},
};
diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx
index 355e64c4a2..46582b5485 100644
--- a/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx
+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx
@@ -5,11 +5,16 @@ import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ routeSearch: vi.fn((): { seek?: string } => ({})),
getTarget:
vi.fn<
typeof import('@app/features/next-soup/utils').getChannelEntityTarget
>(),
}));
+vi.mock('@app/lib/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+ createSearchParams: () => [mocks.routeSearch()],
+}));
vi.mock('@app/features/next-soup/actions', () => ({
useBlockEntityCommands: vi.fn(),
}));
@@ -20,8 +25,13 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanelOrThrow: () => ({ splitHotkeyScope: 'test' }),
}));
vi.mock('@channel/Channel/ChannelDetail', () => ({
- ChannelDetail: (props: { target?: ChannelTargetRequest }) => (
- <output data-testid="target">{JSON.stringify(props.target)}</output>
+ ChannelDetail: (props: {
+ target?: ChannelTargetRequest;
+ navigationRequest?: string;
+ }) => (
+ <output data-testid="target" data-request={props.navigationRequest}>
+ {JSON.stringify(props.target)}
+ </output>
),
ChannelDetailTopBar: () => null,
}));
@@ -43,6 +53,7 @@ const replyTarget = {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.routeSearch.mockReturnValue({});
mocks.getTarget.mockReturnValue(replyTarget);
});
afterEach(cleanup);
@@ -89,4 +100,24 @@ describe('Chat detail navigation', () => {
JSON.stringify(target)
);
});
+
+ it('replays the same search target without re-deriving it from notifications', () => {
+ const [seek, setSeek] = createSignal('first');
+ mocks.routeSearch.mockReturnValue({
+ get seek() {
+ return seek();
+ },
+ });
+ render(() => <ChannelDetailView channel={channel} />);
+ expect(screen.getByTestId('target').dataset.request).toBe('first');
+
+ mocks.getTarget.mockReturnValue({ kind: 'latest' });
+ setSeek('repeat');
+
+ expect(screen.getByTestId('target').dataset.request).toBe('repeat');
+ expect(screen.getByTestId('target').textContent).toBe(
+ JSON.stringify(replyTarget)
+ );
+ expect(mocks.getTarget).toHaveBeenCalledOnce();
+ });
});
diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
index c9199ccab6..6d86a12aae 100644
--- a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
@@ -1,5 +1,6 @@
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
import { getChannelEntityTarget } from '@app/features/next-soup/utils';
+import { createSearchParams } from '@app/lib/split-router';
import {
ChannelDetail,
ChannelDetailTopBar,
@@ -8,6 +9,7 @@ import type { ChannelTargetRequest } from '@channel/Channel/ChannelSurface';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import type { ChannelEntity } from '@entity';
import { createMemo } from 'solid-js';
+import { channelsSearch } from '../channels-route';
/**
* Rail-selection adapter for the shared ChannelDetail. Fresh metadata and
@@ -18,6 +20,7 @@ import { createMemo } from 'solid-js';
*/
export function ChannelDetailView(props: { channel: ChannelEntity }) {
const panel = useSplitPanelOrThrow();
+ const [search] = createSearchParams(channelsSearch);
useBlockEntityCommands({
id: props.channel.id,
scopeId: panel.splitHotkeyScope,
@@ -48,6 +51,7 @@ export function ChannelDetailView(props: { channel: ChannelEntity }) {
<ChannelDetail
channelId={props.channel.id}
target={target()}
+ navigationRequest={search.seek}
fallbackName={props.channel.name}
autofocus={false}
>
diff --git a/apps/web/src/features/drive-view/route.tsx b/apps/web/src/features/drive-view/route.tsx
index 94f80799fb..b158f42ed5 100644
--- a/apps/web/src/features/drive-view/route.tsx
+++ b/apps/web/src/features/drive-view/route.tsx
@@ -9,7 +9,9 @@ import {
import { callDetailSearch } from '@block-call/call-route';
import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';
import { URL_PARAMS as MARKDOWN_URL_PARAMS } from '@block-md/constants';
+import { markdownDetailSearch } from '@block-md/markdown-route';
import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
+import { pdfDetailSearch } from '@block-pdf/pdf-route';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import {
NewAppView,
@@ -136,6 +138,7 @@ const documentRemountKey = ({
export const driveRootDocumentRoute = defineRoute({
id: 'drive-document',
+ search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
path: ':documentType/:documentId',
params: driveDocumentParams,
state: driveDetailTrailSchema,
@@ -151,6 +154,7 @@ export const driveRootDocumentRoute = defineRoute({
export const driveFolderDocumentRoute = defineRoute({
id: 'drive-folder-document',
+ search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
path: ':documentType/:documentId',
params: driveDocumentParams,
state: driveDetailTrailSchema,
@@ -166,6 +170,7 @@ export const driveFolderDocumentRoute = defineRoute({
export const driveTabDocumentRoute = defineRoute({
id: 'drive-tab-document',
+ search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
path: ':documentType/:documentId',
params: driveDocumentParams,
state: driveDetailTrailSchema,
diff --git a/apps/web/src/features/drive-view/views/MarkdownDetail.tsx b/apps/web/src/features/drive-view/views/MarkdownDetail.tsx
index dc54d3f9b2..c815e5288b 100644
--- a/apps/web/src/features/drive-view/views/MarkdownDetail.tsx
+++ b/apps/web/src/features/drive-view/views/MarkdownDetail.tsx
@@ -7,6 +7,7 @@ import { ModalsProvider } from '@block-md/component/ModalsProvider';
import { MarkdownSidePanelSections } from '@block-md/component/sidepanel/MarkdownSidePanelSections';
import { createMarkdownDocumentState } from '@block-md/context/markdown-document-state';
import { OldOverlay } from '@block-md/history/OldOverlay';
+import { createMarkdownRouteNavigation } from '@block-md/primitives/create-markdown-route-navigation';
import {
loadMarkdownDocument,
type MarkdownDocumentData,
@@ -90,6 +91,7 @@ function MarkdownDetailContent(props: {
const notificationSource = useGlobalNotificationSource();
const orchestrator = useGlobalBlockOrchestrator();
const state = createMarkdownDocumentState();
+ createMarkdownRouteNavigation(() => props.documentId, state.params.navigate);
// Mention chips and notifications aim an open document at a comment or node
// through its block handle; without one the click only activates the view.
diff --git a/apps/web/src/features/drive-view/views/PdfDetail.tsx b/apps/web/src/features/drive-view/views/PdfDetail.tsx
index e1dac8b15a..b7969a4871 100644
--- a/apps/web/src/features/drive-view/views/PdfDetail.tsx
+++ b/apps/web/src/features/drive-view/views/PdfDetail.tsx
@@ -8,6 +8,7 @@ import {
} from '@block-pdf/component/PdfSplitToolbar';
import { Tabs } from '@block-pdf/component/Tabs';
import { usePdfDocument } from '@block-pdf/context/pdf-document-context';
+import { createPdfRouteTarget } from '@block-pdf/primitives/create-pdf-route-target';
import {
type LocationSearchParams,
URL_PARAMS,
@@ -132,6 +133,7 @@ export function PdfDetailDocument(props: {
children?: (context: PdfDetailContext) => JSX.Element;
}) {
const [searchParams] = useSearchParams();
+ const target = createPdfRouteTarget(() => props.documentId);
const permissions = () => getPermissions(props.data.userAccessLevel);
return (
@@ -156,6 +158,7 @@ export function PdfDetailDocument(props: {
isOwner: props.data.userAccessLevel === 'owner',
}}
locationParams={getLocationParams(searchParams)}
+ navigationTarget={target()}
>
<PdfDetailContent data={props.data} children={props.children} />
</PdfDocument>
diff --git a/apps/web/src/features/email-thread/context/email-thread-context.ts b/apps/web/src/features/email-thread/context/email-thread-context.ts
index 2676a3e41f..4d48c0c2f5 100644
--- a/apps/web/src/features/email-thread/context/email-thread-context.ts
+++ b/apps/web/src/features/email-thread/context/email-thread-context.ts
@@ -75,5 +75,6 @@ export interface EmailThreadHost {
isActive?: Accessor<boolean>;
registerKeyboard?: (handlers: EmailThreadKeyboardHandlers) => void;
targetMessageId?: Accessor<string | undefined>;
+ targetRequest?: Accessor<string | undefined>;
focusContainer?: () => void;
}
diff --git a/apps/web/src/features/email-thread/primitives/email-thread-state.ts b/apps/web/src/features/email-thread/primitives/email-thread-state.ts
index d594e26c62..b441d3533e 100644
--- a/apps/web/src/features/email-thread/primitives/email-thread-state.ts
+++ b/apps/web/src/features/email-thread/primitives/email-thread-state.ts
@@ -17,7 +17,11 @@ import { createThreadDrafts } from './thread-drafts';
import { createThreadRecipients } from './thread-recipients';
import { createThreadSnapshot } from './thread-snapshot';
-type NavigationTarget = { threadId: string; messageId: string | undefined };
+type NavigationTarget = {
+ threadId: string;
+ messageId: string | undefined;
+ request?: string;
+};
export type EmailThreadState = {
isScrollingToMessage: Accessor<boolean>;
@@ -139,11 +143,14 @@ export function createEmailThreadState(
() => ({
threadId: threadContext.source.id(),
messageId: host.targetMessageId?.(),
+ request: host.targetRequest?.(),
}),
undefined,
{
equals: (a, b) =>
- a.threadId === b.threadId && a.messageId === b.messageId,
+ a.threadId === b.threadId &&
+ a.messageId === b.messageId &&
+ a.request === b.request,
}
);
const [clearedTarget, setClearedTarget] = createSignal<NavigationTarget>();
diff --git a/apps/web/src/features/email-thread/primitives/thread-navigation-target.test.ts b/apps/web/src/features/email-thread/primitives/thread-navigation-target.test.ts
index 0736ca8722..d32d9f9d31 100644
--- a/apps/web/src/features/email-thread/primitives/thread-navigation-target.test.ts
+++ b/apps/web/src/features/email-thread/primitives/thread-navigation-target.test.ts
@@ -57,7 +57,8 @@ function setup(
const [targetMessageId, setTarget] = createSignal<string | undefined>(
target
);
- const host = { targetMessageId, isActive };
+ const [targetRequest, setTargetRequest] = createSignal('initial');
+ const host = { targetMessageId, targetRequest, isActive };
const state = createEmailThreadState(source, host);
const navigation = createThreadNavigation(
{ threadId },
@@ -72,6 +73,7 @@ function setup(
navigation,
fetchOlder,
setTarget,
+ setTargetRequest,
setFetching,
setTouch,
setActive,
@@ -269,3 +271,18 @@ it('does not restart a cleared target on a cache update, but supports opening it
fixture.dispose();
}
});
+
+it('replays a previously handled message when a fresh route request arrives', async () => {
+ const fixture = setup('target', ['first', 'target', 'last']);
+ try {
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(fixture.container.scrollBy).toHaveBeenCalledOnce();
+ expect(fixture.state.messages.targetMessageId()).toBeUndefined();
+ fixture.setTargetRequest('second-click');
+ await vi.advanceTimersByTimeAsync(20);
+ expect(fixture.container.scrollBy).toHaveBeenCalledTimes(2);
+ expect(fixture.state.messages.focusedId()).toBe('target');
+ } finally {
+ fixture.dispose();
+ }
+});
diff --git a/apps/web/src/features/email-view/components/EmailDetailView.tsx b/apps/web/src/features/email-view/components/EmailDetailView.tsx
index 9e76bffdd5..d172cc2d34 100644
--- a/apps/web/src/features/email-view/components/EmailDetailView.tsx
+++ b/apps/web/src/features/email-view/components/EmailDetailView.tsx
@@ -102,6 +102,7 @@ function EmailDetailHeader(
export function EmailDetailView(props: {
thread: EmailThreadTarget;
targetMessageId?: string;
+ targetRequest?: string;
}) {
const { closeThread, selectedThread } = useEmailView();
const panel = useSplitPanelOrThrow();
@@ -172,6 +173,7 @@ export function EmailDetailView(props: {
listNavigation,
focusContainer,
targetMessageId: () => props.targetMessageId,
+ targetRequest: () => props.targetRequest,
isActive: panel.isPanelActive,
registerKeyboard: (handlers) => {
registerEmailHotkeys(hotkeyScope(), handlers);
@@ -287,6 +289,7 @@ export function EmailDetailRouteView() {
<EmailDetailView
thread={{ id: params.threadId }}
targetMessageId={search.messageId || undefined}
+ targetRequest={search.seek}
/>
);
}
diff --git a/apps/web/src/features/email-view/email-route.ts b/apps/web/src/features/email-view/email-route.ts
index f2fdc3c835..096eebb6b6 100644
--- a/apps/web/src/features/email-view/email-route.ts
+++ b/apps/web/src/features/email-view/email-route.ts
@@ -26,8 +26,8 @@ export const EMAIL_DETAIL_SEARCH_NAMESPACE = 'email-detail';
export const emailDetailSearch = {
namespace: EMAIL_DETAIL_SEARCH_NAMESPACE,
- schema: z.object({ messageId: z.string() }),
- defaults: { messageId: '' },
+ schema: z.object({ messageId: z.string(), seek: z.string() }),
+ defaults: { messageId: '', seek: '' },
};
export const emailDetailSearchCodec =
diff --git a/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx b/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx
index 866d4d668e..282f8f0e46 100644
--- a/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx
+++ b/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx
@@ -1,7 +1,8 @@
import { EntityDetail } from '@app/components/entity-detail/EntityDetail';
import type { EntityDetailTarget } from '@app/components/entity-detail/entity-detail-target';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
-import { useParams } from '@app/lib/split-router';
+import { channelsSearch } from '@app/features/channels-view/channels-route';
+import { createSearchParams, useParams } from '@app/lib/split-router';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { ChannelDetailTopBar } from '@channel/Channel/ChannelDetail';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
@@ -73,7 +74,7 @@ function entityDetailTarget(
function HomeEntityDetailBody(props: {
target: EntityDetailTarget;
value: Accessor<string>;
- navigationRequest: number;
+ navigationRequest: number | string;
}) {
return (
<div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
@@ -141,7 +142,7 @@ function HomeEntityDetailBody(props: {
function HomeDirectDetail(props: {
target: EntityDetailTarget;
closePreview: () => void;
- navigationRequest: number;
+ navigationRequest: number | string;
}) {
const value = () => `${props.target.type}:${props.target.id}`;
@@ -173,6 +174,7 @@ function HomeDirectDetail(props: {
/** Home's typed channel and document routes; unsupported locations keep the block preview. */
export function HomeEntityDetailRouteView() {
const params = useParams<DetailParams>();
+ const [search] = createSearchParams(channelsSearch);
const panel = useSplitPanelOrThrow();
const orchestrator = useGlobalBlockOrchestrator();
const { previewTarget, previewNavigationRequest, closePreview } =
@@ -186,7 +188,7 @@ export function HomeEntityDetailRouteView() {
<HomeDirectDetail
target={target()}
closePreview={closePreview}
- navigationRequest={previewNavigationRequest()}
+ navigationRequest={`${previewNavigationRequest()}:${search.seek}`}
/>
)}
</Match>
diff --git a/apps/web/src/features/home/home-preview-navigation.ts b/apps/web/src/features/home/home-preview-navigation.ts
index d053fae742..fc50b496db 100644
--- a/apps/web/src/features/home/home-preview-navigation.ts
+++ b/apps/web/src/features/home/home-preview-navigation.ts
@@ -1,3 +1,7 @@
+import { agentDetailSearch } from '@app/features/block-agent/agent-route';
+import { callDetailSearch } from '@app/features/block-call/call-route';
+import { markdownDetailSearch } from '@app/features/block-md/markdown-route';
+import { pdfDetailSearch } from '@app/features/block-pdf/pdf-route';
import { getPreferredCalendarPeriodView } from '@app/features/calendar/calendar-preferences';
import type { CalendarPeriodView } from '@app/features/calendar/types';
import {
@@ -14,6 +18,7 @@ import {
driveSearch,
driveSearchCodec,
} from '@app/features/drive-view/primitives/drive-search';
+import { emailDetailSearch } from '@app/features/email-view/email-route';
import type { SerializedSearchParams } from '@app/lib/split-router';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
@@ -46,6 +51,11 @@ export function homeDetailSearch(
} = {}
): DetailSearch {
return {
+ [agentDetailSearch.namespace]: undefined,
+ [callDetailSearch.namespace]: undefined,
+ [markdownDetailSearch.namespace]: undefined,
+ [pdfDetailSearch.namespace]: undefined,
+ [emailDetailSearch.namespace]: undefined,
[channelsSearch.namespace]: detail.channel,
[driveSearch.namespace]: detail.document,
[CALENDAR_SEARCH_NAMESPACE]: detail.calendar,
diff --git a/apps/web/src/features/home/route.tsx b/apps/web/src/features/home/route.tsx
index 424acbfbc4..a7549ff269 100644
--- a/apps/web/src/features/home/route.tsx
+++ b/apps/web/src/features/home/route.tsx
@@ -180,8 +180,11 @@ export const homePreviewRoute = defineRoute({
remountKey: ({ blockType, previewId }) =>
`${homeBaseBlockType(blockType)}:${previewId}`,
claim: ({ blockType, previewId }) => ({
- namespace: 'block',
- id: `${homeBaseBlockType(blockType)}:${previewId}`,
+ namespace: blockType === 'agent' ? 'agent' : 'block',
+ id:
+ blockType === 'agent'
+ ? previewId
+ : `${homeBaseBlockType(blockType)}:${previewId}`,
}),
toReference: ({ previewId, blockType }) =>
blockType === 'pr'
diff --git a/apps/web/src/features/next-soup/search-navigation-readers.test.tsx b/apps/web/src/features/next-soup/search-navigation-readers.test.tsx
new file mode 100644
index 0000000000..b84054facb
--- /dev/null
+++ b/apps/web/src/features/next-soup/search-navigation-readers.test.tsx
@@ -0,0 +1,132 @@
+import { createAgentRouteTarget } from '@app/features/block-agent/primitives/create-agent-route-target';
+import { createMarkdownRouteNavigation } from '@app/features/block-md/primitives/create-markdown-route-navigation';
+import { createPdfRouteTarget } from '@app/features/block-pdf/primitives/create-pdf-route-target';
+import type {
+ SplitRouter as Router,
+ SplitRouterLayout,
+ SplitRouterLayoutEntry,
+} from '@app/lib/split-router';
+import {
+ createMemorySplitRouterLocation,
+ defineRoute,
+ SplitRouter,
+ useSplitRouter,
+} from '@app/lib/split-router';
+import { replaceSplitSearchParams } from '@app/lib/split-router/search';
+import type { SearchLocation } from '@entity';
+import { cleanup, render } from '@solidjs/testing-library';
+import { type Accessor, createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ searchLocationTarget,
+ searchLocationUpdates,
+} from './search-navigation';
+
+afterEach(cleanup);
+
+function setup(location: SearchLocation) {
+ let entry: SplitRouterLayoutEntry<string> | undefined;
+ const layout: SplitRouterLayout<string> = {
+ snapshot: () => ({ entries: entry ? [entry] : [] }),
+ reconcile: (locations) => {
+ entry = { splitId: 'pane', location: locations[0]! };
+ },
+ updateCurrentLocation: (_, update) => {
+ entry = { ...entry!, location: update(entry!) };
+ },
+ open: () => ({ status: 'unavailable' }),
+ activate: () => {},
+ subscribe: () => () => {},
+ };
+ const target = searchLocationTarget('document', location);
+ const query = new URLSearchParams();
+ replaceSplitSearchParams(query, [
+ { location: { search: { [target.namespace]: target.params } } },
+ ]);
+ const route = defineRoute({
+ id: 'detail',
+ path: 'detail',
+ search: '*' as const,
+ });
+ const navigateMarkdown = vi.fn();
+ let router!: Router<string>;
+ let pdf!: ReturnType<typeof createPdfRouteTarget>;
+ let agent!: ReturnType<typeof createAgentRouteTarget>;
+ let setDocument!: (id: string) => void;
+ let documentId!: Accessor<string>;
+ function Reader() {
+ router = useSplitRouter<string>();
+ [documentId, setDocument] = createSignal('document');
+ createMarkdownRouteNavigation(documentId, navigateMarkdown);
+ pdf = createPdfRouteTarget(documentId);
+ agent = createAgentRouteTarget();
+ return null;
+ }
+ render(() => (
+ <SplitRouter.Root
+ layout={layout}
+ routes={{ definitions: [route] }}
+ location={createMemorySplitRouterLocation(`/detail?${query}`)}
+ >
+ <SplitRouter.Scope splitId="pane">
+ <Reader />
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
+ ));
+ return {
+ navigateMarkdown,
+ pdf,
+ agent,
+ setDocument,
+ router,
+ replay: () =>
+ router.navigate('pane', route.to(), {
+ search: searchLocationUpdates('document', location),
+ }),
+ };
+}
+
+it('delivers cold and repeated Markdown targets, but never to another document in the pane', async () => {
+ const test = setup({ type: 'md', nodeId: 'node' });
+ expect(test.navigateMarkdown).toHaveBeenCalledExactlyOnceWith({
+ node_id: 'node',
+ });
+ test.replay();
+ await test.router.settled();
+ expect(test.navigateMarkdown).toHaveBeenCalledTimes(2);
+ test.setDocument('other-document');
+ expect(test.navigateMarkdown).toHaveBeenCalledTimes(2);
+});
+
+it('delivers complete PDF highlight requests and replays the same page', async () => {
+ const test = setup({
+ type: 'pdf',
+ searchPage: 7,
+ searchRawQuery: 'one two',
+ searchSnippet: 'one & two',
+ highlightTerms: ['one', 'two'],
+ });
+ const first = test.pdf();
+ expect(first).toEqual({
+ pdf_search_page: '7',
+ pdf_search_raw_query: 'one two',
+ pdf_search_snippet: 'one & two',
+ pdf_search_highlight_terms: '["one","two"]',
+ });
+ test.replay();
+ await test.router.settled();
+ expect(test.pdf()).toEqual(first);
+ expect(test.pdf()).not.toBe(first);
+ test.setDocument('other-document');
+ expect(test.pdf()).toBeUndefined();
+});
+
+it('keeps agent turn zero and creates a fresh scroll request for a repeated hit', async () => {
+ const test = setup({ type: 'agent', messageTurn: 0, author: 'agent' });
+ const first = test.agent();
+ expect(first).toEqual({ messageTurn: 0, author: 'agent' });
+ test.replay();
+ await test.router.settled();
+ expect(test.agent()).toEqual(first);
+ expect(test.agent()).not.toBe(first);
+});
diff --git a/apps/web/src/features/next-soup/search-navigation.test.ts b/apps/web/src/features/next-soup/search-navigation.test.ts
new file mode 100644
index 0000000000..c348d5c213
--- /dev/null
+++ b/apps/web/src/features/next-soup/search-navigation.test.ts
@@ -0,0 +1,99 @@
+import { agentDetailSearchCodec } from '@app/features/block-agent/agent-route';
+import { callDetailSearchCodec } from '@app/features/block-call/call-route';
+import { markdownDetailSearchCodec } from '@app/features/block-md/markdown-route';
+import { pdfDetailSearchCodec } from '@app/features/block-pdf/pdf-route';
+import { channelsSearchCodec } from '@app/features/channels-view/channels-route';
+import { emailDetailSearchCodec } from '@app/features/email-view/email-route';
+import {
+ parseSplitSearch,
+ replaceSplitSearchParams,
+} from '@app/lib/split-router/search';
+import type { SearchLocation } from '@entity';
+import { describe, expect, it } from 'vitest';
+import {
+ searchLocationTarget,
+ searchLocationUpdates,
+} from './search-navigation';
+
+describe('search target URLs', () => {
+ const locations: SearchLocation[] = [
+ { type: 'channel', messageId: 'reply', threadId: 'parent' },
+ { type: 'email', messageId: 'old-message' },
+ { type: 'md', nodeId: 'node-1' },
+ {
+ type: 'pdf',
+ searchPage: 3,
+ highlightTerms: ['one two', '日本語'],
+ searchSnippet: 'one two & 日本語',
+ searchRawQuery: 'one two',
+ },
+ { type: 'agent', messageTurn: 0, author: 'agent' },
+ { type: 'call_record', callId: 'call', transcriptId: 'segment' },
+ ];
+
+ it.each(locations)(
+ 'round-trips every field of $type through pane-local URL search',
+ (location) => {
+ const target = searchLocationTarget('entity', location, 'request');
+ const query = new URLSearchParams();
+ replaceSplitSearchParams(query, [
+ { location: { search: { [target.namespace]: target.params } } },
+ ]);
+ const restored = parseSplitSearch(query.toString()).get(0)?.[
+ target.namespace
+ ];
+ const codecs = {
+ channel: channelsSearchCodec,
+ email: emailDetailSearchCodec,
+ md: markdownDetailSearchCodec,
+ pdf: pdfDetailSearchCodec,
+ agent: agentDetailSearchCodec,
+ call_record: callDetailSearchCodec,
+ };
+ const parsed = codecs[location.type].parse(restored);
+ expect(parsed.valid).toBe(true);
+ expect(parsed.value).toMatchObject({ seek: 'request' });
+ expect(restored).toEqual(target.params);
+ if (location.type === 'pdf')
+ expect(parsed.value).toEqual({
+ documentId: 'entity',
+ page: 3,
+ highlightTerms: ['one two', '日本語'],
+ snippet: 'one two & 日本語',
+ query: 'one two',
+ seek: 'request',
+ });
+ if (location.type === 'agent')
+ expect(parsed.value).toMatchObject({ messageTurn: 0, author: 'agent' });
+ }
+ );
+
+ it('clears the previous thread while preserving the selected Chat tab', () => {
+ const patch = searchLocationUpdates('entity', {
+ type: 'channel',
+ messageId: 'root',
+ }).channels;
+ expect(typeof patch).toBe('function');
+ if (typeof patch !== 'function')
+ throw new Error('Expected a field-preserving update');
+ expect(
+ patch({
+ tab: ['recents'],
+ messageId: ['old'],
+ threadId: ['old-parent'],
+ seek: ['old-request'],
+ })
+ ).toEqual({
+ tab: ['recents'],
+ messageId: ['root'],
+ seek: [expect.any(String)],
+ });
+ });
+
+ it('assigns independent requests to repeated clicks on the same location', () => {
+ const location: SearchLocation = { type: 'email', messageId: 'message' };
+ expect(searchLocationTarget('entity', location).params.seek).not.toEqual(
+ searchLocationTarget('entity', location).params.seek
+ );
+ });
+});
diff --git a/apps/web/src/features/next-soup/search-navigation.ts b/apps/web/src/features/next-soup/search-navigation.ts
new file mode 100644
index 0000000000..432659f1a6
--- /dev/null
+++ b/apps/web/src/features/next-soup/search-navigation.ts
@@ -0,0 +1,125 @@
+import {
+ agentDetailSearch,
+ agentDetailSearchCodec,
+} from '@app/features/block-agent/agent-route';
+import {
+ callDetailSearch,
+ callDetailSearchCodec,
+} from '@app/features/block-call/call-route';
+import {
+ markdownDetailSearch,
+ markdownDetailSearchCodec,
+} from '@app/features/block-md/markdown-route';
+import {
+ pdfDetailSearch,
+ pdfDetailSearchCodec,
+} from '@app/features/block-pdf/pdf-route';
+import {
+ channelsSearch,
+ channelsSearchCodec,
+} from '@app/features/channels-view/channels-route';
+import {
+ emailDetailSearch,
+ emailDetailSearchCodec,
+} from '@app/features/email-view/email-route';
+import type {
+ SerializedSearchParams,
+ SplitSearchUpdate,
+} from '@app/lib/split-router';
+import type { SearchLocation } from '@entity';
+import { match } from 'ts-pattern';
+
+/** One navigation request per click, including repeated clicks on the same hit. */
+export function searchLocationTarget(
+ entityId: string,
+ location: SearchLocation,
+ seek: string = crypto.randomUUID()
+): {
+ namespace: string;
+ params: SerializedSearchParams;
+ fields: readonly string[];
+} {
+ return match(location)
+ .with({ type: 'channel' }, (target) => ({
+ namespace: channelsSearch.namespace,
+ params: channelsSearchCodec.serialize({
+ ...channelsSearch.defaults,
+ messageId: target.messageId,
+ threadId: target.threadId ?? '',
+ seek,
+ })!,
+ fields: ['messageId', 'threadId', 'seek'],
+ }))
+ .with({ type: 'email' }, (target) => ({
+ namespace: emailDetailSearch.namespace,
+ params: emailDetailSearchCodec.serialize({
+ messageId: target.messageId,
+ seek,
+ })!,
+ fields: ['messageId', 'seek'],
+ }))
+ .with({ type: 'md' }, (target) => ({
+ namespace: markdownDetailSearch.namespace,
+ params: markdownDetailSearchCodec.serialize({
+ documentId: entityId,
+ nodeId: target.nodeId,
+ seek,
+ })!,
+ fields: ['documentId', 'nodeId', 'seek'],
+ }))
+ .with({ type: 'pdf' }, (target) => ({
+ namespace: pdfDetailSearch.namespace,
+ params: pdfDetailSearchCodec.serialize({
+ documentId: entityId,
+ page: target.searchPage,
+ highlightTerms: target.highlightTerms,
+ snippet: target.searchSnippet,
+ query: target.searchRawQuery,
+ seek,
+ })!,
+ fields: [
+ 'documentId',
+ 'page',
+ 'highlightTerms',
+ 'snippet',
+ 'query',
+ 'seek',
+ ],
+ }))
+ .with({ type: 'agent' }, (target) => ({
+ namespace: agentDetailSearch.namespace,
+ params: agentDetailSearchCodec.serialize({
+ messageTurn: target.messageTurn,
+ author: target.author,
+ seek,
+ })!,
+ fields: ['messageTurn', 'author', 'seek'],
+ }))
+ .with({ type: 'call_record' }, (target) => ({
+ namespace: callDetailSearch.namespace,
+ params: callDetailSearchCodec.serialize({
+ transcriptId: target.transcriptId,
+ seek,
+ })!,
+ fields: ['transcriptId', 'seek'],
+ }))
+ .exhaustive();
+}
+
+/** Replace the whole target while preserving unrelated fields, such as the Chat tab. */
+export function searchLocationUpdates(
+ entityId: string,
+ location: SearchLocation
+): Record<string, SplitSearchUpdate> {
+ const target = searchLocationTarget(entityId, location);
+ return {
+ [target.namespace]: (current) => ({
+ ...Object.fromEntries(
+ Object.entries(current ?? {}).filter(
+ ([field]) => !target.fields.includes(field)
+ )
+ ),
+ ...target.params,
+ }),
+ };
+}
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index 78ca2f05e1..c09f445b09 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -126,8 +126,12 @@ vi.mock('@core/constant/featureFlags', async (importOriginal) => {
};
});
+import type { SerializedSearchParams } from '@app/lib/split-router';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
-import type { SplitManager } from '@components/app/split-layout/layoutManager';
+import type {
+ OpenWithSplitOptions,
+ SplitManager,
+} from '@components/app/split-layout/layoutManager';
import { type ChannelEntityTarget, type EntityData, queryKeys } from '@entity';
import type { NotificationSource, UnifiedNotification } from '@notifications';
import { hydrateChannelNotificationSelection } from '@queries/channel/notification-selection';
@@ -146,6 +150,16 @@ import {
resolveMarkEntitiesDoneVariables,
} from './utils';
+function targetSearch(
+ open: ReturnType<typeof vi.fn>,
+ namespace: string,
+ current?: SerializedSearchParams
+) {
+ const options = open.mock.calls.at(-1)?.[1] as OpenWithSplitOptions;
+ const update = options.search?.[namespace];
+ return typeof update === 'function' ? update(current) : update;
+}
+
afterEach(() => {
setGlobalSplitManager(undefined);
vi.clearAllMocks();
@@ -220,7 +234,7 @@ describe('agent session search navigation', () => {
}
);
- it('opens the agent block with durable params and retargets it on each snippet click', async () => {
+ it('carries agent targets through route search without waiting for block handles', async () => {
const openWithSplit = vi.fn(() => ({ status: 'unavailable' }));
const goToLocationFromParams = vi.fn();
const getBlockHandle = vi.fn(async () => ({ goToLocationFromParams }));
@@ -236,18 +250,20 @@ describe('agent session search navigation', () => {
{
type: 'agent',
id: 'session',
- params: { agent_message_turn: '0', agent_message_author: 'user' },
+ params: undefined,
},
expect.any(Object)
);
await openEntityInSplitFromUnifiedList(entity, {
location: { type: 'agent', messageTurn: 4, author: 'agent' },
});
- expect(getBlockHandle).toHaveBeenCalledWith('session');
- expect(goToLocationFromParams).toHaveBeenLastCalledWith({
- agent_message_turn: '4',
- agent_message_author: 'agent',
+ expect(targetSearch(openWithSplit, 'agent-detail')).toMatchObject({
+ messageTurn: ['4'],
+ author: ['agent'],
+ seek: [expect.any(String)],
});
+ expect(getBlockHandle).not.toHaveBeenCalled();
+ expect(goToLocationFromParams).not.toHaveBeenCalled();
});
});
@@ -1118,17 +1134,55 @@ describe('getChannelEntityTarget', () => {
);
expect(openWithSplit).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({ channel_message_id: 'message' }),
- }),
+ expect.objectContaining({ type: 'channel', id: 'channel-1' }),
expect.any(Object)
);
+ expect(targetSearch(openWithSplit, 'channels')).toMatchObject({
+ messageId: ['message'],
+ seek: [expect.any(String)],
+ });
expect(bulkMarkAsRead).toHaveBeenCalledWith([notification]);
});
+ it('keeps an explicit channel search target without navigating to latest', async () => {
+ const getBlockHandle = vi.fn(async () => undefined);
+ const openWithSplit = vi.fn(() => ({ status: 'navigating' }));
+ setGlobalSplitManager({
+ activeSplit: vi.fn(),
+ getOrchestrator: vi.fn(() => ({ getBlockHandle })),
+ getSplitByContent: vi.fn(),
+ findOpenView: vi.fn(),
+ openWithSplit,
+ } as unknown as SplitManager);
+ await openEntityInSplitFromUnifiedList(channelRow(), {
+ location: { type: 'channel', messageId: 'hit' },
+ });
+ expect(targetSearch(openWithSplit, 'channels')).toMatchObject({
+ messageId: ['hit'],
+ });
+ expect(openWithSplit).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.objectContaining({ reopen: undefined })
+ );
+ expect(getBlockHandle).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ 'channels',
+ 'email-detail',
+ 'markdown-detail',
+ 'pdf-detail',
+ 'agent-detail',
+ 'call-detail',
+ ])('clears stale %s targets on ordinary Home navigation', (namespace) => {
+ const navigation = homePreviewNavigation({ type: 'channel', id: 'other' });
+ expect(Object.hasOwn(navigation.search, namespace)).toBe(true);
+ expect(navigation.search[namespace]).toBeUndefined();
+ });
+
it.each(
[false, true].flatMap((openInNewSplit) =>
- ['opened', 'reused', 'unavailable'].map((status) => ({
+ ['opened', 'reused', 'unavailable', 'navigating'].map((status) => ({
openInNewSplit,
status,
}))
@@ -1169,7 +1223,7 @@ describe('getChannelEntityTarget', () => {
preferNewSplit: openInNewSplit,
})
);
- if (status === 'unavailable') {
+ if (status === 'unavailable' || status === 'navigating') {
expect(bulkMarkAsRead).not.toHaveBeenCalled();
} else {
expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([unread, reply]);
@@ -1177,6 +1231,35 @@ describe('getChannelEntityTarget', () => {
}
);
+ it('marks routed channel notifications only after the destination is applied', async () => {
+ const reply = replyNotification('deferred', 'reply-message', 'root');
+ const bulkMarkAsRead = vi.fn(async () => {});
+ let onApplied: (() => void) | undefined;
+ setGlobalSplitManager({
+ activeSplit: vi.fn(),
+ getOrchestrator: vi.fn(() => ({})),
+ openWithSplit: (
+ ...[_content, options]: Parameters<SplitManager['openWithSplit']>
+ ) => {
+ onApplied = options?.onApplied;
+ return { status: 'navigating' };
+ },
+ } as unknown as SplitManager);
+
+ await openEntityInSplitFromUnifiedList(
+ channelRow({ notifications: [reply] }),
+ {
+ notificationSource:
+ notificationSourceWithBulkMarkAsRead(bulkMarkAsRead),
+ scopeChannelThreads: false,
+ }
+ );
+ expect(bulkMarkAsRead).not.toHaveBeenCalled();
+ expect(onApplied).toBeDefined();
+ onApplied!();
+ expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([reply]);
+ });
+
it('chooses the unread reply target before marking a Chat conversation read', async () => {
const reply = replyNotification('reply-target', 'reply-message', 'root');
const openWithSplit = vi.fn(() => ({ status: 'opened' }));
@@ -1199,15 +1282,10 @@ describe('getChannelEntityTarget', () => {
scopeChannelThreads: false,
}
);
- expect(openWithSplit).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- channel_message_id: 'reply-message',
- channel_thread_id: 'root',
- }),
- }),
- expect.any(Object)
- );
+ expect(targetSearch(openWithSplit, 'channels')).toMatchObject({
+ messageId: ['reply-message'],
+ threadId: ['root'],
+ });
expect(bulkMarkAsRead).toHaveBeenCalledExactlyOnceWith([reply]);
});
@@ -1634,8 +1712,11 @@ describe('call navigation', () => {
{ id: 'drive-call', params: { callId: 'call-1' } },
],
},
- search: { 'call-detail': { transcriptId: ['segment-1'] } },
},
});
+ expect(targetSearch(openWithSplit, 'call-detail')).toMatchObject({
+ transcriptId: ['segment-1'],
+ seek: [expect.any(String)],
+ });
});
});
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index d92a1bb981..c10f102832 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -14,7 +14,6 @@ import {
type CalendarViewTarget,
} from '@app/features/calendar-view/types';
import { driveHostedContent } from '@app/features/drive-view/drive-hosted-content';
-import { URL_PARAMS as EMAIL_PARAMS } from '@app/features/email-thread/core/location';
import { projectRouteId } from '@app/features/projects/core/route';
import { reviewsHostedContent } from '@app/features/reviews-view/reviews-hosted-content';
import { withListNavigationSource } from '@app/features/soup/collection/list-navigation-source';
@@ -23,18 +22,13 @@ import {
getEntityNotifications,
scopeChannelNotificationsForEntity,
} from '@app/features/soup/entity-notifications';
-import { isRecord } from '@app/lib/split-router/utils';
+import { replaceSplitSearchParams } from '@app/lib/split-router/search';
import { globalSplitManager } from '@app/signal/splitLayout';
import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
-import { URL_PARAMS as CALL_PARAMS } from '@block-call/constants';
-import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import {
- getChannelParams,
goToChannelLatest,
goToChannelMessage,
} from '@block-channel/utils/link';
-import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
-import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/constants';
import type {
ReferredFrom,
SplitContent,
@@ -131,6 +125,10 @@ import { refreshActiveGraphqlSoupQueries } from '@queries/soup/graphql/active-qu
import { emailClient } from '@service-email/client';
import { isAfter } from 'date-fns';
import { match } from 'ts-pattern';
+import {
+ searchLocationTarget,
+ searchLocationUpdates,
+} from './search-navigation';
export { scopeChannelNotificationsForEntity };
@@ -291,7 +289,7 @@ export const openEntityInNewTab = ({
) {
entityPath = `/app/channel/${entity.channelId}`;
} else {
- entityPath = `/app/${entity.type}/${entity.id}`;
+ entityPath = `/app/${entity.type === 'agent_session' ? 'agent' : entity.type}/${entity.id}`;
}
// Add location params if present
@@ -302,76 +300,25 @@ export const openEntityInNewTab = ({
calendarFocusedEventSearchKey(),
calendarViewTargetForEntity(entity).eventId ?? entity.id
);
- } else if (
- entity.type === 'channel_message' ||
- entity.type === 'channel_thread'
- ) {
- entityUrl.searchParams.set(CHANNEL_PARAMS.message, entity.messageId);
- if (entity.threadId) {
- entityUrl.searchParams.set(CHANNEL_PARAMS.thread, entity.threadId);
- }
- } else if (location) {
- switch (location.type) {
- case 'agent':
- for (const [key, value] of Object.entries(
- agentMessageParams(location)
- )) {
- entityUrl.searchParams.set(key, value);
- }
- break;
- case 'channel':
- if (location.messageId) {
- entityUrl.searchParams.set(
- CHANNEL_PARAMS.message,
- location.messageId
- );
- }
- if (location.threadId) {
- entityUrl.searchParams.set(CHANNEL_PARAMS.thread, location.threadId);
- }
- break;
- case 'email':
- if (location.messageId) {
- entityUrl.searchParams.set('email_message_id', location.messageId);
- }
-
- break;
- case 'md':
- if (location.nodeId) {
- entityUrl.searchParams.set('node_id', location.nodeId);
- }
- break;
- case 'pdf':
- if (location.searchPage !== undefined) {
- entityUrl.searchParams.set(
- 'search_page',
- location.searchPage.toString()
- );
- }
- if (location.searchRawQuery) {
- entityUrl.searchParams.set(
- 'search_raw_query',
- location.searchRawQuery
- );
- }
- if (location.highlightTerms) {
- entityUrl.searchParams.set(
- 'search_highlight_terms',
- JSON.stringify(location.highlightTerms)
- );
- }
- if (location.searchSnippet) {
- entityUrl.searchParams.set('search_snippet', location.searchSnippet);
- }
- break;
- case 'call_record':
- if (location.transcriptId) {
- entityUrl.searchParams.set(
- CALL_PARAMS.transcriptId,
- location.transcriptId
- );
- }
- break;
+ } else {
+ const channelTarget = getChannelEntityTarget(entity);
+ const target =
+ location ??
+ (channelTarget?.kind === 'message'
+ ? {
+ type: 'channel' as const,
+ messageId: channelTarget.messageId,
+ threadId: channelTarget.threadId,
+ }
+ : undefined);
+ if (target) {
+ const { namespace, params } = searchLocationTarget(
+ getEntitySplitContent(entity).id,
+ target
+ );
+ replaceSplitSearchParams(entityUrl.searchParams, [
+ { location: { search: { [namespace]: params } } },
+ ]);
}
}
@@ -775,24 +722,19 @@ export const openEntityInSplitFromUnifiedList = async (
channelTarget?.kind === 'message' ? channelTarget : undefined;
const openChannelAtLatest = channelTarget?.kind === 'latest';
- let params: Record<string, string> | undefined;
- if (entity.type === 'agent_session' && location?.type === 'agent') {
- params = agentMessageParams(location);
- } else if (entity.type === 'channel' && location?.type === 'channel') {
- params = getChannelParams(location.messageId, location.threadId);
- } else if (channelMessageTarget) {
- params = getChannelParams(
- channelMessageTarget.messageId,
- channelMessageTarget.threadId
- );
- } else if (entity.type === 'call' && location?.type === 'call_record') {
- params = { [CALL_PARAMS.transcriptId]: location.transcriptId };
- }
+ const target =
+ location ??
+ (channelMessageTarget
+ ? {
+ type: 'channel' as const,
+ messageId: channelMessageTarget.messageId,
+ threadId: channelMessageTarget.threadId,
+ }
+ : undefined);
const commentParams =
- !location && entity.type === 'document'
+ !target && entity.type === 'document'
? getDocumentCommentTarget(entity)?.params
: undefined;
- params ??= commentParams;
const sourceContent =
splitHandle?.content() ?? splitManager.activeSplit()?.content();
@@ -810,32 +752,24 @@ export const openEntityInSplitFromUnifiedList = async (
driveHostedContent(content, {
allowDocuments: !isTouchDevice() && !commentParams,
});
- let splitContent: SplitContent = hostedContent ?? { ...content, params };
- const callTranscriptId =
- entity.type === 'call' && location?.type === 'call_record'
- ? location.transcriptId
- : undefined;
- if (callTranscriptId) {
- splitContent = {
- ...splitContent,
- entryMetadata: {
- ...(isRecord(splitContent.entryMetadata)
- ? splitContent.entryMetadata
- : {}),
- search: {
- 'call-detail': {
- transcriptId: [callTranscriptId],
- seek: [`${Date.now()}-${Math.random()}`],
- },
- },
- },
- };
- }
+ let splitContent: SplitContent = hostedContent ?? {
+ ...content,
+ params: commentParams,
+ };
if (splitHandle && referredFrom && isListViewID(referredFrom)) {
splitContent = withListNavigationSource(splitContent, splitHandle);
}
+ const markNotificationsSeen = () => {
+ if (options.notificationSource) {
+ markChannelNotificationsSeenOnOpen(entity, options.notificationSource, {
+ scopeChannelThreads: options.scopeChannelThreads,
+ });
+ }
+ };
const result = splitManager.openWithSplit(splitContent, {
+ search: target ? searchLocationUpdates(content.id, target) : undefined,
+ onApplied: target ? markNotificationsSeen : undefined,
referredFrom,
activate: true,
preferNewSplit: openInNewSplit,
@@ -852,43 +786,14 @@ export const openEntityInSplitFromUnifiedList = async (
toast.alert('Content already open');
}
- if (result.status !== 'unavailable' && options.notificationSource) {
- markChannelNotificationsSeenOnOpen(entity, options.notificationSource, {
- scopeChannelThreads: options.scopeChannelThreads,
- });
+ if (result.status === 'opened' || result.status === 'reused') {
+ markNotificationsSeen();
}
- // Routed calls have no block handle. Update a reused split's route search
- // instead of waiting for a legacy block method that will never register.
- if (location?.type === 'call_record') {
- if (result.status === 'reused' && result.split && callTranscriptId) {
- result.split.replace({
- next: {
- ...result.split.content(),
- entryMetadata: splitContent.entryMetadata,
- },
- mergeHistory: true,
- });
- } else if (result.status === 'reused' && !result.split) {
- await navigateToLocation(content.id, location, blockOrchestrator);
- }
- } else if (location) {
- await navigateToLocation(content.id, location, blockOrchestrator);
- } else if (channelMessageTarget) {
- // NOTE: This will force target message navigation in case the split is already open.
- await navigateToLocation(
- content.id,
- {
- type: 'channel',
- messageId: channelMessageTarget.messageId,
- threadId: channelMessageTarget.threadId,
- },
- blockOrchestrator
- );
- } else if (commentParams && entity.type === 'document') {
+ if (commentParams && entity.type === 'document') {
// An already-open document ignores new split params.
await navigateDocumentEntityToComment(entity, blockOrchestrator);
- } else if (openChannelAtLatest) {
+ } else if (!target && openChannelAtLatest) {
// Force the scroll-to-bottom even when the channel is already open in a
// (preview) split, where reopen: 'latest' only reactivates the parked
// split without re-pinning it to the newest message.
@@ -1093,61 +998,6 @@ function getEntitySplitContent(entity: EntityData) {
);
}
-/**
- * Navigates to a specific location within a block.
- */
-async function navigateToLocation(
- entityId: string,
- location: SearchLocation,
- blockOrchestrator: BlockOrchestrator
-): Promise<void> {
- const blockHandle = await blockOrchestrator.getBlockHandle(entityId);
- if (!blockHandle) return;
-
- switch (location.type) {
- case 'agent': {
- await blockHandle.goToLocationFromParams(agentMessageParams(location));
- break;
- }
- case 'channel': {
- // NOTE: this is handled by the channel block params but this can be used to re-flash an open channel
- await blockHandle.goToLocationFromParams(
- getChannelParams(location.messageId, location.threadId)
- );
- break;
- }
- case 'email': {
- await blockHandle.goToLocationFromParams({
- [EMAIL_PARAMS.messageId]: location.messageId,
- });
- break;
- }
- case 'md': {
- await blockHandle.goToLocationFromParams({
- [MD_PARAMS.nodeId]: location.nodeId,
- });
- break;
- }
- case 'pdf': {
- await blockHandle.goToLocationFromParams({
- [PDF_PARAMS.searchPage]: location.searchPage.toString(),
- [PDF_PARAMS.searchRawQuery]: location.searchRawQuery,
- [PDF_PARAMS.searchHighlightTerms]: JSON.stringify(
- location.highlightTerms
- ),
- [PDF_PARAMS.searchSnippet]: location.searchSnippet,
- });
- break;
- }
- case 'call_record': {
- await blockHandle.goToLocationFromParams({
- [CALL_PARAMS.transcriptId]: location.transcriptId,
- });
- break;
- }
- }
-}
-
async function _archiveEmail(
id: string,
options: { archive: boolean; optimisticallyExclude?: boolean }
@@ -1902,5 +1752,3 @@ export async function executeMarkEntitiesUndone(args: {
]);
return hasQueuedEmail ? 'queued' : 'committed';
}
-
-import { agentMessageParams } from '@app/features/block-agent/core/search-location';
diff --git a/apps/web/src/lib/split-router/layout.ts b/apps/web/src/lib/split-router/layout.ts
index 103e5ae072..b9a4a9bc7a 100644
--- a/apps/web/src/lib/split-router/layout.ts
+++ b/apps/web/src/lib/split-router/layout.ts
@@ -96,6 +96,7 @@ export function createLayoutAdapter<TSplitId>(
};
const apply = (options: {
+ open?: SplitRouterLayout<TSplitId>['open'];
entry: SplitRouterEntry;
target: TSplitId | 'new-split';
replace: boolean;
@@ -113,7 +114,7 @@ export function createLayoutAdapter<TSplitId>(
return { changed: false, layoutChanged: false };
}
- if (targetId !== undefined && current) {
+ if (!options.open && targetId !== undefined && current) {
if (deepEqual(current.location, options.entry.location)) {
return { changed: true, layoutChanged: false, splitId: targetId };
}
@@ -131,7 +132,7 @@ export function createLayoutAdapter<TSplitId>(
}
const before = snapshot().entries;
- const result = layout.open({
+ const result = (options.open ?? layout.open)({
location: options.entry.location,
target: options.target,
replace: options.replace,
diff --git a/apps/web/src/lib/split-router/router.ts b/apps/web/src/lib/split-router/router.ts
index 06c20bc720..f4e1d3219a 100644
--- a/apps/web/src/lib/split-router/router.ts
+++ b/apps/web/src/lib/split-router/router.ts
@@ -58,6 +58,7 @@ type LayoutTransition = {
};
type ApplyOptions<TSplitId> = {
+ open?: SplitNavigateOptions<TSplitId>['open'];
entry: SplitRouterEntry;
target: TSplitId | 'new-split';
replace: boolean;
@@ -76,6 +77,7 @@ type EntryTransition<TSplitId> = {
allowDuplicate?: boolean;
apply: (entry: SplitRouterEntry) => boolean;
onReuse?: (splitId: TSplitId, entry: SplitRouterEntry) => boolean;
+ onApplied?: () => void;
};
const GLOBAL_TRANSITION = Symbol('split-router-global-transition');
@@ -477,6 +479,7 @@ export function createSplitRouter<TSplitId>(
const applyEntry = (config: ApplyOptions<TSplitId>): boolean => {
const previousById = acceptedById();
const result = layout.apply({
+ open: config.open,
entry: config.entry,
target: config.target,
replace: config.replace,
@@ -512,6 +515,7 @@ export function createSplitRouter<TSplitId>(
) => {
const changed = transition.apply(entry);
if (changed) notify(transition.splitId);
+ if (changed) transition.onApplied?.();
return changed;
};
@@ -559,6 +563,7 @@ export function createSplitRouter<TSplitId>(
throwIfAborted(controller.signal);
const changed = config.apply(entry);
if (changed && splitId === undefined) notify();
+ if (changed) config.onApplied?.();
} finally {
finish();
}
@@ -598,6 +603,7 @@ export function createSplitRouter<TSplitId>(
const updated = config.onReuse?.(owner.splitId, entry) ?? false;
layout.activate(owner.splitId);
if (hadPending || updated) notify(owner.splitId);
+ config.onApplied?.();
};
const waitForClaim = async (
turn: Promise<void>,
@@ -833,6 +839,7 @@ export function createSplitRouter<TSplitId>(
from: targetEntry,
cause: 'navigate',
allowDuplicate: navigateOptions.allowDuplicate,
+ onApplied: navigateOptions.onApplied,
onReuse(ownerId, entry) {
const owner = acceptedById().get(ownerId);
if (!owner) return false;
@@ -872,6 +879,7 @@ export function createSplitRouter<TSplitId>(
},
apply: (entry) =>
applyEntry({
+ open: navigateOptions.open,
entry,
target,
replace: navigateOptions.replace ?? false,
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 a6ecf59447..f002286409 100644
--- a/apps/web/src/lib/split-router/tests/router.test.ts
+++ b/apps/web/src/lib/split-router/tests/router.test.ts
@@ -135,6 +135,100 @@ const settle = () => new Promise<void>((resolve) => queueMicrotask(resolve));
afterEach(() => vi.restoreAllMocks());
describe('split router', () => {
+ it('runs the host opening policy only after acceptance and ignores superseded requests', async () => {
+ const gate = Promise.withResolvers<void>();
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location: createMemorySplitRouterLocation('/drive'),
+ middleware: [
+ ({ cause, to }) =>
+ cause === 'navigate' &&
+ routeParams(to.location.route).folderId === 'slow'
+ ? gate.promise
+ : undefined,
+ ],
+ });
+ await router.settled();
+ const source = layout.snapshot().entries[0].splitId;
+ const open = vi.fn((request: Parameters<Layout['open']>[0]) =>
+ layout.open({ ...request, target: 'new-split' })
+ );
+ const cancelled = vi.fn();
+ const applied = vi.fn();
+ router.navigate(source, '/drive/folder/slow', {
+ open,
+ onApplied: cancelled,
+ });
+ await settle();
+ expect(open).not.toHaveBeenCalled();
+ expect(cancelled).not.toHaveBeenCalled();
+ router.navigate(source, '/drive/folder/accepted', {
+ open,
+ onApplied: applied,
+ });
+ await settle();
+ expect(open).toHaveBeenCalledOnce();
+ expect(layout.snapshot().entries).toHaveLength(2);
+ expect(routeParams(router.route('split-2')!).folderId).toBe('accepted');
+ gate.resolve();
+ await router.settled();
+ expect(open).toHaveBeenCalledOnce();
+ expect(applied).toHaveBeenCalledOnce();
+ expect(cancelled).not.toHaveBeenCalled();
+ router.dispose();
+ });
+
+ it('updates an existing claim owner without invoking the host opening policy', async () => {
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location: createMemorySplitRouterLocation('/drive/~/drive/folder/owned'),
+ });
+ await router.settled();
+ const [source, owner] = layout.snapshot().entries;
+ const open = vi.fn(layout.open);
+ const onApplied = vi.fn();
+ router.navigate(source.splitId, '/drive/folder/owned', {
+ open,
+ onApplied,
+ search: { drive: { query: ['new target'] } },
+ });
+ await router.settled();
+ expect(open).not.toHaveBeenCalled();
+ expect(router.search(owner.splitId, 'drive')).toEqual({
+ query: ['new target'],
+ });
+ expect(router.route(source.splitId)?.matches).toHaveLength(1);
+ expect(onApplied).toHaveBeenCalledOnce();
+ router.dispose();
+ });
+
+ it('does not report navigation applied when the host cannot open a pane', async () => {
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location: createMemorySplitRouterLocation('/drive'),
+ });
+ await router.settled();
+ const onApplied = vi.fn();
+ router.navigate(
+ layout.snapshot().entries[0].splitId,
+ '/drive/folder/missing',
+ {
+ open: () => ({ status: 'unavailable' }),
+ onApplied,
+ }
+ );
+ await router.settled();
+ expect(onApplied).not.toHaveBeenCalled();
+ expect(layout.snapshot().entries).toHaveLength(1);
+ router.dispose();
+ });
+
it('becomes ready when a synchronous layout change supersedes async initialization', async () => {
const layout = createLayout();
let release!: () => void;
@@ -1950,15 +2044,18 @@ describe('split router', () => {
await router.settled();
const splitId = layout.snapshot().entries[0]!.splitId;
- router.navigate(splitId, 'folder/two', { target: 'new-split' });
+ const onApplied = vi.fn();
+ router.navigate(splitId, 'folder/two', { target: 'new-split', onApplied });
expect(layout.snapshot().entries).toHaveLength(1);
+ expect(onApplied).not.toHaveBeenCalled();
release();
await router.settled();
expect(layout.snapshot().entries).toHaveLength(2);
expect(location.read().pathname).toBe('/drive/~/drive/folder/two');
+ expect(onApplied).toHaveBeenCalledOnce();
});
it('retains declared global search and drops unowned keys', async () => {
diff --git a/apps/web/src/lib/split-router/types.ts b/apps/web/src/lib/split-router/types.ts
index 8a0ea85cf4..0d8e1f0cd1 100644
--- a/apps/web/src/lib/split-router/types.ts
+++ b/apps/web/src/lib/split-router/types.ts
@@ -123,6 +123,11 @@ export type SplitNavigateOptions<
TStateInput = SplitRouterEntryState,
TStateOutput = TStateInput,
> = {
+ /** Host opening policy, invoked after middleware accepts a new destination.
+ * Existing claim owners are updated in place without invoking this callback. */
+ open?: SplitRouterLayout<TSplitId>['open'];
+ /** Runs after the destination is applied or an existing owner is activated. */
+ onApplied?: () => void;
replace?: boolean;
target?: 'current' | 'new-split' | TSplitId;
search?: Record<string, SplitSearchUpdate>;
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 55302e6e94..61089a51c8 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -56,6 +56,17 @@ Switching tabs or navigating an in-app route is not a back/forward-cache restore
| `/app/debug/ui?ui=invert-util` | UI gallery, including the inverted Markdown demo on the InvertUtil page |
| `/app/debug/<component>` | Registered debug views (for example `icon-gallery`, `md`, or `agent-ui`); existing environment gates apply. `/app/component/<component>` remains a compatibility alias for these views |
+Search-result locations use pane-local namespaces: `channels` (message/thread),
+`email-detail` (message), `markdown-detail` (node), `pdf-detail` (page and highlight
+context), `agent-detail` (turn/author), and `call-detail` (transcript segment).
+A `seek` value identifies each click so selecting the same hit again scrolls again.
+Markdown and PDF targets also name their document so navigation to another file in
+the same workspace cannot apply the previous file's target.
+Channel-message @mentions and AI-generated channel mentions also preserve their
+message/thread target when opening a channel or reusing its existing pane.
+Returning to Home's list clears the prior target, so reopening an item without
+a specific location does not replay the previous search hit.
+
When an event opens inline from Home, changing the Calendar period stays under
`/app/home/calendar/`, updates the period segment, and re-focuses that event.
Back/Forward restores the period and its event locator from `sN.calendar.*`.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 3950a2c44a..80e14c9e8e 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -669,7 +669,7 @@ without resetting its selections.
## Search
-Sidebar `Search` button → `/app/.../component/search` with a focused query box. Results
+Sidebar `Search` button → `/app/search` with a focused query box. Results
(including a `Featured Results` group) filter live as you type; no Enter needed. `Ctrl+K` is
usually faster for jump-to-entity; `/` opens workspace search when no editor is focused.
@@ -684,6 +684,24 @@ not saved into the view's desktop search or restored entry state. Home and
top-level Tasks use this same overlay; embedded project task lists retain their
own search while the dock is open.
+Search snippets carry their target in the destination pane's route search. Channel
+messages open Chat at the message (replies open their parent thread); email snippets
+open the matching message, Markdown snippets the matching node, PDFs the matching
+page and highlighted text, agent snippets the matching turn/author, and call
+snippets the matching transcript segment. Plain rows keep their existing behavior:
+email rows open normally, while agent and call content results use their first hit.
+
+Verify both a cold open and a result whose entity is already open in another pane,
+including a Home or Drive detail: reuse keeps that pane's workspace and filters,
+leaves the search pane intact, and scrolls to the target. Scroll away and click the
+same snippet again to verify it re-targets. Repeat with Shift-click and Cmd/Ctrl-click
+(new split and new browser tab), and check Back/Forward restores the earlier target.
+Channel checks should include an older offscreen message, a reply, and then a root
+message to ensure the previous thread target is cleared.
+For a PDF that is still loading, clear its route target before pages become visible:
+the old search hit must not apply afterward. A newer mention or preview target must
+survive that cleanup and still open when the viewer is ready.
+
Agent-session results use the robot icon and show a highlighted transcript snippet.
`Show more [N]` expands additional matches, labeled **User / Agent · Turn N**.
Click a snippet to open `/app/agent/<uuid>` at that folded message; a plain row click