Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(web): reuse claimed split content with search targets (#7094)

dev-rbadb83c27e0e1
diff --git a/apps/web/src/lib/split-router/README.md b/apps/web/src/lib/split-router/README.md
index 2878474099..c9a45fa0f8 100644
--- a/apps/web/src/lib/split-router/README.md
+++ b/apps/web/src/lib/split-router/README.md
@@ -12,6 +12,7 @@ stay outside this library.
- `defineRoute()` infers node-local callback and synchronous Standard Schema
output types, including `remountKey`, and types descendant references relative
to that root. `defineRoutes()` assembles the static tree and rebinds ancestry.
+ Both attach a non-enumerable `to(params)` builder to route definitions in place.
- `useRouteParams(route)` reads only that node's params. `useParams(route)` reads
the merged branch through that node; `useParams()` still reads the entire
active branch.
@@ -30,6 +31,7 @@ export const folder = defineRoute({
id: 'folder',
path: 'drive/folder/:folderId',
params: z.object({ folderId: z.string() }),
+ search: ['drive'],
children: [defineRoute({
id: 'document',
path: 'document/:documentId',
@@ -40,16 +42,21 @@ export const folder = defineRoute({
export const document = folder.children[0];
export const routes = defineRoutes({ definitions: [folder] });
-navigate({
- route: document,
- params: { folderId: 'folder-1', documentId: 'document-1' },
+navigate(document.to({ folderId: 'folder-1', documentId: 'document-1' }));
+// Search remains a navigation option, not part of the route target:
+navigate(document.to({ folderId: 'folder-1', documentId: 'document-1' }), {
+ search: { drive: { commentId: ['comment-1'] } },
});
const branch = useParams(document); // folderId + documentId
const local = useRouteParams(document); // documentId only
```
-Both helpers return the same objects: they do not clone, mutate, compile, or
-cache the tree. Ancestry metadata exists only in TypeScript. Export root definitions
+These helpers preserve the same route objects; they do not clone or compile the tree.
+`to(params)` returns `{ route, params }` without serializing, validating, or
+navigating. It is available on nested declarations and plain nodes assembled by
+`defineRoutes()`. TypeScript enforces the complete destination params; navigation
+validates them at runtime. Route identity is preserved while the builder is attached
+in place. Ancestry metadata exists only in TypeScript. Export root definitions
directly and take descendant references through their named parent; positional
aliases from `routes.definitions` are unnecessary. A separately declared child
variable cannot acquire knowledge of a parent that later adopts it. Use `defineRoute`
diff --git a/apps/web/src/lib/split-router/router.ts b/apps/web/src/lib/split-router/router.ts
index 9018544ab4..06c20bc720 100644
--- a/apps/web/src/lib/split-router/router.ts
+++ b/apps/web/src/lib/split-router/router.ts
@@ -10,12 +10,18 @@ import {
assertRouteEntry,
assertSearchNamespacesAllowed,
createRoutesManifest,
+ filterRouteSearch,
getRouteClaim,
+ getRouteSearchNamespaces,
parseRouteEntryState,
type SplitRouteNode,
type SplitRoutesManifest,
} from './routes';
-import { assertSafeSearchName, updateSearchState } from './search';
+import {
+ assertSafeSearchName,
+ parseSplitSearch,
+ updateSearchState,
+} from './search';
import { createTransitionManager, type Transition } from './transitions';
import type {
BrowserHistoryIntent,
@@ -29,8 +35,13 @@ import type {
SplitRouterLayoutSnapshot,
SplitRouterOptions,
SplitRouterStateUpdate,
+ SplitSearchUpdate,
} from './types';
-import { decodeSplitRouterLocation, serializeSplitRouterLocation } from './url';
+import {
+ decodeSplitRouterLocation,
+ parseExternalLocation,
+ serializeSplitRouterLocation,
+} from './url';
import { isPromise, throwIfAborted } from './utils';
type CommitOptions = {
@@ -64,6 +75,7 @@ type EntryTransition<TSplitId> = {
cause: 'navigate' | 'history' | 'search';
allowDuplicate?: boolean;
apply: (entry: SplitRouterEntry) => boolean;
+ onReuse?: (splitId: TSplitId, entry: SplitRouterEntry) => boolean;
};
const GLOBAL_TRANSITION = Symbol('split-router-global-transition');
@@ -583,8 +595,9 @@ export function createSplitRouter<TSplitId>(
// an in-flight departure to replace it immediately after activation.
const hadPending = transitions.pending(owner.splitId) !== undefined;
cancelTargetTransition(owner.splitId);
+ const updated = config.onReuse?.(owner.splitId, entry) ?? false;
layout.activate(owner.splitId);
- if (hadPending) notify(owner.splitId);
+ if (hadPending || updated) notify(owner.splitId);
};
const waitForClaim = async (
turn: Promise<void>,
@@ -781,6 +794,14 @@ export function createSplitRouter<TSplitId>(
Object.keys(navigateOptions.search ?? {})
);
+ const explicitSearch =
+ typeof to === 'string'
+ ? filterRouteSearch(
+ routes,
+ decoded.location.route,
+ parseSplitSearch(parseExternalLocation(to).search).get(0)
+ )
+ : undefined;
let history: BrowserHistoryIntent = 'push';
if (navigateOptions.replace) history = 'replace';
@@ -812,6 +833,43 @@ export function createSplitRouter<TSplitId>(
from: targetEntry,
cause: 'navigate',
allowDuplicate: navigateOptions.allowDuplicate,
+ onReuse(ownerId, entry) {
+ const owner = acceptedById().get(ownerId);
+ if (!owner) return false;
+ const redirected = !deepEqual(
+ entry.location.search,
+ next.location.search
+ );
+ const search = redirected
+ ? filterRouteSearch(
+ routes,
+ entry.location.route,
+ entry.location.search
+ )
+ : explicitSearch;
+ const patches = redirected ? undefined : navigateOptions.search;
+ if (!search && !patches) return false;
+ const owned = getRouteSearchNamespaces(routes, owner.location.route);
+ const compatible = (values?: Record<string, SplitSearchUpdate>) =>
+ Object.fromEntries(
+ Object.entries(values ?? {}).filter(
+ ([name]) => owned.has('*') || owned.has(name)
+ )
+ ) as Record<string, SplitSearchUpdate>;
+ const location = updateSearchState(
+ updateSearchState(owner.location, compatible(search)),
+ compatible(patches)
+ );
+ if (deepEqual(owner.location, location)) return false;
+ return applyEntry({
+ entry: { ...owner, key: createEntryKey(), location },
+ target: ownerId,
+ replace: navigateOptions.replace ?? false,
+ history,
+ preserveHash: false,
+ requireTarget: true,
+ });
+ },
apply: (entry) =>
applyEntry({
entry,
diff --git a/apps/web/src/lib/split-router/routes.ts b/apps/web/src/lib/split-router/routes.ts
index 55d1d46bac..aa22c51686 100644
--- a/apps/web/src/lib/split-router/routes.ts
+++ b/apps/web/src/lib/split-router/routes.ts
@@ -160,6 +160,22 @@ type RouteDefinitionsParamsSchemaConstraint<
readonly 'ERROR: route params schema keys and optionality must match paths and aliases': RouteDefinitionsParamsSchemaIssues<TDefinitions>;
};
+/** Attach the builder in place so declarations retain their route identity. */
+function attachRouteBuilders(
+ definitions: readonly SplitRouteDefinitionConstraint[]
+): void {
+ for (const definition of definitions) {
+ if (!Object.hasOwn(definition, 'to')) {
+ Object.defineProperty(definition, 'to', {
+ value: (params: SplitRouteParams = {}) => ({
+ route: definition,
+ params,
+ }),
+ });
+ }
+ attachRouteBuilders(definition.children ?? []);
+ }
+}
export function defineRoute<
const TPath extends string,
const TAliases extends readonly string[] | undefined,
@@ -219,7 +235,7 @@ export function defineRoute<
export function defineRoute(
definition: SplitRouteDefinitionConstraint
): unknown {
- // The overloads add phantom ancestry; runtime declarations remain untouched.
+ attachRouteBuilders([definition]);
return definition;
}
@@ -233,6 +249,7 @@ export function defineRoutes<
(NoInfer<TRoutes> extends SplitRoutes ? unknown : SplitRoutes) &
RouteDefinitionsParamsSchemaConstraint<NoInfer<TRoutes>['definitions']>
): DefinedSplitRoutes<TRoutes> {
+ attachRouteBuilders(routes.definitions);
return routes as DefinedSplitRoutes<TRoutes>;
}
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 af358ad08c..a6ecf59447 100644
--- a/apps/web/src/lib/split-router/tests/router.test.ts
+++ b/apps/web/src/lib/split-router/tests/router.test.ts
@@ -329,10 +329,7 @@ describe('split router', () => {
const router = createSplitRouter({ layout, routes, location });
const splitId = layout.snapshot().entries[0]!.splitId;
- router.navigate(splitId, {
- route: driveFolderRoute,
- params: { folderId: 'two' },
- });
+ router.navigate(splitId, driveFolderRoute.to({ folderId: 'two' }));
await router.settled();
expect(location.read().pathname).toBe('/drive/folder/two');
@@ -709,6 +706,26 @@ describe('split router', () => {
router.dispose();
});
+ it('keeps same-claim navigation search in its restored duplicate pane', async () => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/one'
+ );
+ const router = createSplitRouter({ layout, routes, location });
+ const [first, second] = layout.snapshot().entries;
+
+ router.navigate(second!.splitId, '/drive/folder/one', {
+ search: { drive: { sort: ['name'] } },
+ });
+ await router.settled();
+
+ expect(router.search(first!.splitId, 'drive')).toBeUndefined();
+ expect(router.search(second!.splitId, 'drive')).toEqual({ sort: ['name'] });
+ expect(layout.activatedSplitId()).toBeUndefined();
+ expect(router.history(second!.splitId)?.entries).toHaveLength(2);
+ router.dispose();
+ });
+
it('checks search redirects but preserves same-claim updates in restored duplicate panes', async () => {
const layout = createLayout();
const location = createMemorySplitRouterLocation(
@@ -803,6 +820,155 @@ describe('split router', () => {
router.dispose();
});
+ it('updates compatible search on an existing claim owner without replacing its route', async () => {
+ const contextualRoutes: SplitRoutes = {
+ ...routes,
+ definitions: [
+ ...routes.definitions,
+ defineRoute({
+ id: 'inbox-folder',
+ path: 'inbox/:folderId',
+ params: z.object({ folderId: z.string() }),
+ search: ['drive', 'inbox'],
+ claim: ({ folderId }) => ({ namespace: 'folder', id: folderId }),
+ }),
+ ],
+ };
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two?s0.drive.sort=name'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes: contextualRoutes,
+ location,
+ });
+ const [owner, caller] = layout.snapshot().entries;
+
+ router.navigate(caller!.splitId, '/inbox/one', {
+ search: {
+ drive: (current) => ({ ...current, message_id: ['target'] }),
+ inbox: { tab: ['unread'] },
+ },
+ });
+ await router.settled();
+
+ expect(layout.activatedSplitId()).toBe(owner!.splitId);
+ expect(router.route(owner!.splitId)?.matches.at(-1)?.id).toBe(
+ 'drive-folder'
+ );
+ expect(router.search(owner!.splitId, 'drive')).toEqual({
+ sort: ['name'],
+ message_id: ['target'],
+ });
+ expect(router.search(owner!.splitId, 'inbox')).toBeUndefined();
+ expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');
+ expect(router.history(caller!.splitId)?.entries).toHaveLength(1);
+ expect(location.read().pathname).toBe(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ router.dispose();
+ });
+
+ it('ignores URL search that the claimed destination route does not own', async () => {
+ const contextualRoutes: SplitRoutes = {
+ ...routes,
+ definitions: [
+ ...routes.definitions,
+ defineRoute({
+ id: 'inbox-folder',
+ path: 'inbox/:folderId',
+ params: z.object({ folderId: z.string() }),
+ search: ['inbox'],
+ claim: ({ folderId }) => ({ namespace: 'folder', id: folderId }),
+ }),
+ ],
+ };
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two?s0.drive.sort=name'
+ );
+ const layout = createLayout();
+ const router = createSplitRouter({
+ layout,
+ routes: contextualRoutes,
+ location,
+ });
+ const [owner, caller] = layout.snapshot().entries;
+
+ router.navigate(
+ caller!.splitId,
+ '/inbox/one?s0.drive.sort=bad&s0.inbox.tab=unread'
+ );
+ await router.settled();
+
+ expect(layout.activatedSplitId()).toBe(owner!.splitId);
+ expect(router.search(owner!.splitId, 'drive')).toEqual({ sort: ['name'] });
+ expect(router.search(owner!.splitId, 'inbox')).toBeUndefined();
+ expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');
+ expect(router.history(caller!.splitId)?.entries).toHaveLength(1);
+ router.dispose();
+ });
+
+ it('applies explicit URL search to an existing claim owner', async () => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two?s0.drive.sort=name'
+ );
+ const router = createSplitRouter({ layout, routes, location });
+ const [owner, caller] = layout.snapshot().entries;
+
+ router.navigate(
+ caller!.splitId,
+ '/drive/folder/one?s0.drive.message_id=target'
+ );
+ await router.settled();
+
+ expect(layout.activatedSplitId()).toBe(owner!.splitId);
+ expect(router.search(owner!.splitId, 'drive')).toEqual({
+ message_id: ['target'],
+ });
+ expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');
+
+ const historyLength = location.history().length;
+ router.navigate(caller!.splitId, '/drive/folder/one');
+ await router.settled();
+ expect(router.search(owner!.splitId, 'drive')).toEqual({
+ message_id: ['target'],
+ });
+ expect(location.history()).toHaveLength(historyLength);
+ router.dispose();
+ });
+
+ it('forwards middleware search targets to an existing owner', async () => {
+ const layout = createLayout();
+ const location = createMemorySplitRouterLocation(
+ '/drive/folder/one/~/drive/folder/two'
+ );
+ const router = createSplitRouter({
+ layout,
+ routes,
+ location,
+ middleware: [
+ ({ cause, path, redirect }) => {
+ if (cause === 'navigate' && path === '/legacy/one') {
+ return redirect('/drive/folder/one?s0.drive.message_id=target');
+ }
+ },
+ ],
+ });
+ const [owner, caller] = layout.snapshot().entries;
+
+ router.navigate(caller!.splitId, '/legacy/one');
+ await router.settled();
+
+ expect(layout.activatedSplitId()).toBe(owner!.splitId);
+ expect(router.search(owner!.splitId, 'drive')).toEqual({
+ message_id: ['target'],
+ });
+ expect(routeParams(router.route(caller!.splitId)).folderId).toBe('two');
+ router.dispose();
+ });
+
it('publishes pending-state removal when a replacement navigation reuses another owner', async () => {
const gate = Promise.withResolvers<void>();
const layout = createLayout();
diff --git a/apps/web/src/lib/split-router/tests/routes.test.ts b/apps/web/src/lib/split-router/tests/routes.test.ts
index 2cc6f970e8..4f017123cb 100644
--- a/apps/web/src/lib/split-router/tests/routes.test.ts
+++ b/apps/web/src/lib/split-router/tests/routes.test.ts
@@ -21,6 +21,7 @@ import type {
InferSplitRouteParams,
InferSplitRouteState,
InferSplitRouteStateInput,
+ SplitNavigate,
SplitRoutes,
} from '../types';
@@ -160,8 +161,26 @@ function assertInvalidRouteDeclarations() {
},
],
});
+ // @ts-expect-error Route builders require every ancestor's destination params.
+ driveRoute.children[0].children[0].to({ documentId: 'document-1' });
+ defineRoute({
+ id: 'number',
+ path: ':id',
+ params: z.object({ id: z.coerce.number() }),
+ }).to({
+ // @ts-expect-error Route builders use the schema's output type.
+ id: '1',
+ });
}
+function assertNestedRouteBuilderNavigation(navigate: SplitNavigate<string>) {
+ navigate(
+ driveRoute.children[0].children[0].to({
+ folderId: 'folder-1',
+ documentId: 'document-1',
+ })
+ );
+}
describe('route entry state schemas', () => {
it('parses inherited state and exposes it through the owning branch', () => {
const entry = decodeRoute(routes, [
@@ -227,6 +246,7 @@ describe('route entry state schemas', () => {
describe('typed route trees', () => {
it('checks declaration contracts without widening node inference', () => {
expectTypeOf(assertInvalidRouteDeclarations).toBeFunction();
+ expectTypeOf(assertNestedRouteBuilderNavigation).toBeFunction();
});
it('preserves declaration and schema identity while typing descendant ancestry', () => {
const declarations = {
@@ -262,6 +282,24 @@ describe('typed route trees', () => {
}>();
});
+ it('builds typed targets while preserving nested route references', () => {
+ const detail = driveRoute.children[0].children[0];
+ const params = { folderId: 'folder-1', documentId: 'document-1' };
+ expect(detail.to(params)).toEqual({ route: detail, params });
+ expect(detail.to(params).route).toBe(detail);
+ expect(Object.keys(detail)).not.toContain('to');
+ expect(driveRoute.to()).toEqual({ route: driveRoute, params: {} });
+
+ const tree = defineRoutes({
+ definitions: [{ id: 'plain', path: 'plain/:id' }],
+ });
+ const plain = tree.definitions[0];
+ expect(plain.to({ id: '1' })).toEqual({
+ route: plain,
+ params: { id: '1' },
+ });
+ });
+
it('types descendants directly from a named definition before assembly', () => {
const detail = driveRoute.children[0].children[0];
expectTypeOf<InferSplitRouteParams<typeof detail>>().toEqualTypeOf<{
@@ -304,6 +342,10 @@ describe('typed route trees', () => {
expectTypeOf<InferSplitRouteNavigationParams<typeof root>>().toEqualTypeOf<{
documentId: string;
}>();
+ expect(root.to({ documentId: 'document-1' })).toEqual({
+ route: root,
+ params: { documentId: 'document-1' },
+ });
const widened: SplitRoutes = tree;
const redefined = defineRoutes(widened);
expectTypeOf(redefined.definitions[0]?.children).toEqualTypeOf<
diff --git a/apps/web/src/lib/split-router/types.ts b/apps/web/src/lib/split-router/types.ts
index 21f9e2af37..9de22fab0e 100644
--- a/apps/web/src/lib/split-router/types.ts
+++ b/apps/web/src/lib/split-router/types.ts
@@ -341,9 +341,14 @@ type BranchParams<TParams> =
}
: TParams;
+/** Builds a typed route target without resolving the route against a router. */
+type RouteTo<TRoute, TParams> = {} extends TParams
+ ? (params?: TParams) => { route: TRoute; params: TParams }
+ : (params: TParams) => { route: TRoute; params: TParams };
+
type DefinedRoute<TRoute, TParent, TParentNavigation, TParentStateSchema> =
TRoute extends unknown
- ? Omit<TRoute, 'children' | typeof branchParams> & {
+ ? Omit<TRoute, 'children' | 'to' | typeof branchParams> & {
readonly [branchParams]: {
read: MergeRouteParams<
TParent,
@@ -355,6 +360,13 @@ type DefinedRoute<TRoute, TParent, TParentNavigation, TParentStateSchema> =
>;
state: EffectiveRouteStateSchema<TRoute, TParentStateSchema>;
};
+ to: RouteTo<
+ DefinedRoute<TRoute, TParent, TParentNavigation, TParentStateSchema>,
+ MergeRouteParams<
+ {},
+ TParentNavigation & BranchParams<LocalNavigationParams<TRoute>>
+ >
+ >;
} & (TRoute extends {
children: infer TChildren extends readonly unknown[];
}
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index e35e8ea082..313775d85d 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -102,8 +102,9 @@ selection participates in browser Back/Forward independently per pane. Explicit
return controls navigate to the workspace's list root. Multiple panes navigate
their child routes and history independently; returning to a list does not
activate another pane. Opening a resource already displayed in another pane
-still activates its owner through router claim arbitration; the compatibility
-preview guard can instead reject a conflicting embedded preview. On touch, or
+activates its owner through router claim arbitration, preserves the owner's route,
+and applies compatible search targets to that pane. The compatibility preview
+guard can instead reject a conflicting embedded preview. On touch, or
when the new-app-view flag cannot render the detail, Home, Email, Tasks, and
Channels detail URLs fall back to the existing full-block surface. Legacy email
and channel message targets are normalized into per-pane search by ingress