Skip to content

Commit 1c06da1

Browse files
refactor(chat): one navigation decision for every link surface CU-17tkuw61kfy (#2883)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1b81a19 commit 1c06da1

67 files changed

Lines changed: 1451 additions & 641 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎openframe-frontend-core/eslint-config/base.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { boxedPrimitivesPlugin } from './boxed-primitives.js';
99
import { ignores } from './ignores.js';
1010
import { imageSizesPlugin } from './image-sizes.js';
1111
import { layoutVariantsPlugin } from './layout-variants.js';
12+
import { navigationPlugin } from './navigation.js';
1213
import { popupPortalPlugin } from './popup-portal.js';
1314
import { reExportsPlugin } from './re-exports.js';
1415
import { webviewPerformancePlugin } from './webview-performance.js';
@@ -19,6 +20,7 @@ export const flamingoPlugin = {
1920
rules: {
2021
...webviewPerformancePlugin.rules,
2122
...layoutVariantsPlugin.rules,
23+
...navigationPlugin.rules,
2224
...imageSizesPlugin.rules,
2325
...boxedPrimitivesPlugin.rules,
2426
...popupPortalPlugin.rules,
@@ -333,6 +335,15 @@ export const base = [
333335
rules: { 'flamingo/no-mixed-layout-variants': 'error' },
334336
},
335337

338+
// A link is followed through the lib's navigation executor only — see ./navigation.js.
339+
{
340+
name: 'flamingo/base/navigation',
341+
files: ['**/*.{js,mjs,jsx,ts,mts,tsx}'],
342+
ignores: ['**/*.{test,spec}.{js,mjs,jsx,ts,mts,tsx}', '**/__tests__/**'],
343+
plugins: { flamingo: flamingoPlugin },
344+
rules: { 'flamingo/no-navigation-fallback': 'error' },
345+
},
346+
336347
// A picture's `sizes` and quality come from the lib's image-size table — see ./image-sizes.js. Tests and stories
337348
// draw no picture a reader waits on.
338349
{
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
/**
2+
* A link is followed in ONE way: the lib's navigation executor (`executeNavigation`, `executeNavigationImperative`,
3+
* `executeNewTabNavigation`, the hooks built on it), which hands a same-tab link to the host's `runtime.navigation.navigate` and lets the browser
4+
* open what the host does not take. Nothing beside it navigates: no fallback option handed to it, and no router push or
5+
* `location` write in the same function as a call to it. A second path is how a host's routing gets skipped quietly
6+
* (CU-17tkuw61kfy: every caller passed `fallbackNavigate: router.push`). If a host does not navigate, wire its
7+
* `navigate`; never route around it.
8+
*/
9+
10+
/** The executor and the hooks that call it. */
11+
const EXECUTORS = new Set([
12+
'executeNavigation',
13+
'executeNavigationImperative',
14+
'executeNewTabNavigation',
15+
'useNavLinkViaRuntime',
16+
'useNavigateViaRuntime',
17+
]);
18+
19+
/** `router.push(...)`, `router.replace(...)`: a router call on anything named like a router. */
20+
const ROUTER_METHOD = new Set(['push', 'replace']);
21+
const LOCATION_METHOD = new Set(['assign', 'replace']);
22+
23+
function calleeName(callee) {
24+
if (callee.type === 'Identifier') return callee.name;
25+
if (callee.type === 'MemberExpression' && !callee.computed && callee.property.type === 'Identifier') {
26+
return callee.property.name;
27+
}
28+
return null;
29+
}
30+
31+
function objectName(node) {
32+
if (node.type === 'Identifier') return node.name;
33+
if (node.type === 'MemberExpression' && !node.computed && node.property.type === 'Identifier') {
34+
return node.property.name;
35+
}
36+
if (node.type === 'CallExpression') return calleeName(node.callee);
37+
return null;
38+
}
39+
40+
/** A direct navigation: `router.push(x)`, `location.assign(x)`, `window.open(x)`, or a `location.href =` write. */
41+
function directNavigation(node) {
42+
if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression' && !node.callee.computed) {
43+
const method = node.callee.property.name;
44+
const owner = objectName(node.callee.object);
45+
if (!owner) return null;
46+
if (ROUTER_METHOD.has(method) && /router$/i.test(owner)) return `${owner}.${method}()`;
47+
if (LOCATION_METHOD.has(method) && owner === 'location') return `location.${method}()`;
48+
if (method === 'open' && owner === 'window') return 'window.open()';
49+
}
50+
if (
51+
node.type === 'AssignmentExpression' &&
52+
node.left.type === 'MemberExpression' &&
53+
!node.left.computed &&
54+
node.left.property.name === 'href' &&
55+
objectName(node.left.object) === 'location'
56+
) {
57+
return 'location.href =';
58+
}
59+
return null;
60+
}
61+
62+
const FUNCTION_TYPES = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
63+
64+
/** @type {import('eslint').Rule.RuleModule} */
65+
const noNavigationFallback = {
66+
meta: {
67+
type: 'problem',
68+
docs: { description: 'Disallow a second way to navigate beside the lib navigation executor' },
69+
schema: [],
70+
messages: {
71+
option:
72+
"`{{key}}` hands {{executor}} a second way to navigate. Links go through the host's " +
73+
'`runtime.navigation.navigate`; a host that does not navigate wires `navigate`, never a fallback.',
74+
beside:
75+
'{{call}} navigates beside {{executor}} in the same function. Follow a link through the executor only; a ' +
76+
'host that does not navigate wires `runtime.navigation.navigate`.',
77+
},
78+
},
79+
create(context) {
80+
// The module that DEFINES the executor is where navigating is implemented; the rule guards its callers.
81+
const definesExecutor = context.sourceCode.ast.body.some(statement => {
82+
const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
83+
return declaration?.type === 'FunctionDeclaration' && EXECUTORS.has(declaration.id?.name);
84+
});
85+
if (definesExecutor) return {};
86+
/** Per enclosing function: the executor calls and the direct navigations anywhere inside it (nested handlers
87+
* included). The file itself is a frame too, but only for its top-level code: two components in one file are
88+
* two functions. */
89+
const frames = [];
90+
const reported = new Set();
91+
const enter = () => frames.push({ executors: [], direct: [] });
92+
const exit = () => {
93+
const frame = frames.pop();
94+
if (!frame || frame.executors.length === 0) return;
95+
for (const { node, call } of frame.direct) {
96+
if (reported.has(node)) continue;
97+
reported.add(node);
98+
context.report({ node, messageId: 'beside', data: { call, executor: frame.executors[0] } });
99+
}
100+
};
101+
/** The frames a fact belongs to: every enclosing function, or the file when at the top level. */
102+
const owners = () => (frames.length > 1 ? frames.slice(1) : frames);
103+
const noteDirect = node => {
104+
const call = directNavigation(node);
105+
if (call) for (const frame of owners()) frame.direct.push({ node, call });
106+
};
107+
108+
return {
109+
Program: enter,
110+
'Program:exit': exit,
111+
...Object.fromEntries(
112+
[...FUNCTION_TYPES].flatMap(t => [
113+
[t, enter],
114+
[`${t}:exit`, exit],
115+
]),
116+
),
117+
CallExpression(node) {
118+
const name = calleeName(node.callee);
119+
if (name && EXECUTORS.has(name)) {
120+
for (const frame of owners()) frame.executors.push(name);
121+
for (const arg of node.arguments) {
122+
if (arg.type !== 'ObjectExpression') continue;
123+
for (const prop of arg.properties) {
124+
const key = prop.type === 'Property' && !prop.computed ? (prop.key.name ?? prop.key.value) : null;
125+
if (typeof key === 'string' && /^fallback/i.test(key)) {
126+
context.report({ node: prop, messageId: 'option', data: { key, executor: name } });
127+
}
128+
}
129+
}
130+
return;
131+
}
132+
noteDirect(node);
133+
},
134+
AssignmentExpression: noteDirect,
135+
};
136+
},
137+
};
138+
139+
export const navigationPlugin = {
140+
meta: { name: 'flamingo-navigation' },
141+
rules: { 'no-navigation-fallback': noNavigationFallback },
142+
};

‎openframe-frontend-core/eslint.config.mjs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,8 @@ export default defineConfig([
217217
'src/__tests__/data-table-loading-items.test.tsx',
218218
// The same marker on the chat's conversation rows (loaded and loading), counted per list.
219219
'src/components/chat/__tests__/chat-history-loading.test.tsx',
220+
// The same marker on the source strip's skeleton chips under an answer being written, counted per host setting.
221+
'src/components/chat/__tests__/embeddable-chat-source-skeleton.test.tsx',
220222
// Static controls drawn real and inert while loading: the `inert` ancestor and the skeleton surfaces are
221223
// role-less and aria-hidden, so `screen` cannot see what is under test.
222224
'src/components/ui/__tests__/static-controls-loading.test.tsx',
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { RuleTester } from 'eslint';
2+
import { navigationPlugin } from '../../eslint-config/navigation.js';
3+
4+
new RuleTester().run('no-navigation-fallback', navigationPlugin.rules['no-navigation-fallback'], {
5+
valid: [
6+
// The executor alone.
7+
'function onClick(e) { executeNavigation({ event: e, runtime, href, path, targetPlatform, hostRoute }); }',
8+
'function open() { executeNewTabNavigation({ runtime, href, targetPlatform: null }); }',
9+
// A router call with no executor in the function: a query-string write, not a link.
10+
'function setPage(p) { router.replace(`${pathname}?page=${p}`); }',
11+
// Two components in one file: one follows links, the other writes the URL.
12+
'function Row() { const go = e => executeNavigation({ event: e, runtime, href }); }\n' +
13+
'function List() { router.replace(`${pathname}?q=1`); }',
14+
// The module that defines the executor implements navigating.
15+
'export function executeNavigation(args) { window.location.assign(args.href); }',
16+
],
17+
invalid: [
18+
{
19+
// CU-17tkuw61kfy: every caller handed the executor `router.push`.
20+
code: 'function onClick(e) { executeNavigation({ event: e, runtime, href, fallbackNavigate: router.push }); }',
21+
errors: [{ messageId: 'option' }],
22+
},
23+
{
24+
code: 'function go() { executeNavigationImperative({ runtime, href, fallback: href => location.assign(href) }); }',
25+
errors: [{ messageId: 'option' }, { messageId: 'beside' }],
26+
},
27+
{
28+
// A second path after the executor.
29+
code: 'function onClick(e) { if (!executeNavigation({ event: e, runtime, href })) router.push(href); }',
30+
errors: [{ messageId: 'beside' }],
31+
},
32+
{
33+
// A new tab opened by hand beside the executor.
34+
code:
35+
'function onSelect(row, wantsNewTab) {\n' +
36+
" if (wantsNewTab) { window.open(row.href, '_blank'); return; }\n" +
37+
' executeNavigationImperative({ runtime, href: row.href });\n' +
38+
'}',
39+
errors: [{ messageId: 'beside' }],
40+
},
41+
{
42+
code: 'function onClick(e) { executeNavigation({ event: e, runtime, href }) || (window.location.href = href); }',
43+
errors: [{ messageId: 'beside' }],
44+
},
45+
{
46+
// A handler nested in a component: the component follows links, so it navigates only through the executor.
47+
code:
48+
'function Card() {\n' +
49+
' const onClick = e => executeNavigation({ event: e, runtime, href });\n' +
50+
' const onKey = () => router.push(href);\n' +
51+
'}',
52+
errors: [{ messageId: 'beside' }],
53+
},
54+
],
55+
});

‎openframe-frontend-core/src/components/announcement-bar.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { X } from 'lucide-react';
44
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
5+
import { useChatRuntime } from '../contexts/chat-runtime-context';
56
import { useEndpointsRuntime } from '../contexts/endpoints-runtime-context';
67
import { usePathname } from '../embed-shims/next-navigation';
78
import { useSelfFetch } from '../hooks/use-self-fetch';
@@ -16,6 +17,7 @@ import { isAnnouncementOnSurface } from '../utils/announcement-surface';
1617
import { getAppType } from '../utils/app-config';
1718
import { pickReadableTextColor } from '../utils/color-analysis';
1819
import { pathMatchesAny } from '../utils/path-pattern';
20+
import { executeNavigationImperative, executeNewTabNavigation } from './chat/utils/execute-navigation';
1921
import { EntityIcon } from './icon-display';
2022
import { AnnouncementBarView } from './ui/announcement-bar-view';
2123
import { Button } from './ui/button';
@@ -89,6 +91,8 @@ export function AnnouncementBar({
8991
// `usePathname` on a Next host, the embedder's registered router elsewhere).
9092
// Read HERE so every host gets `excluded_paths` with no wiring of its own.
9193
const pathname = usePathname();
94+
// The CTA is followed through the lib's navigation executor, with the host's runtime when there is one.
95+
const runtime = useChatRuntime();
9296

9397
// Optional endpoint runtime: no provider → no URL → fetching disabled.
9498
const endpoints = useEndpointsRuntime();
@@ -200,7 +204,7 @@ export function AnnouncementBar({
200204
if (previewMode || !announcement?.cta_url) return;
201205
// Scheme guard: cta_url is admin-entered data — only http(s) (absolute or
202206
// relative) may navigate. A `javascript:` value would otherwise execute
203-
// via location.href / window.open (stored XSS).
207+
// via a navigation (stored XSS).
204208
let safeUrl: string;
205209
try {
206210
// Resolve against the CURRENT page (not the origin) so path-relative and
@@ -211,11 +215,9 @@ export function AnnouncementBar({
211215
} catch {
212216
return;
213217
}
214-
if (announcement.cta_target === '_blank') {
215-
window.open(safeUrl, '_blank', 'noopener,noreferrer');
216-
} else {
217-
window.location.href = safeUrl;
218-
}
218+
// The admin chose the tab (`cta_target`).
219+
if (announcement.cta_target === '_blank') executeNewTabNavigation({ runtime, href: safeUrl });
220+
else executeNavigationImperative({ runtime, href: safeUrl, openIn: 'same-tab' });
219221
};
220222

221223
// Never had anything to show: render nothing. Dismissal AND deactivation

‎openframe-frontend-core/src/components/chat/.embeddable-chat.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ interface EmbeddableChatProps {
3232
```
3333

3434
### Key Runtime Dependencies
35-
- **`useRequiredChatRuntime()`** — provides `user`, `source`, and navigation context (replaces hub's `useAuth`, `currentPlatform`, `useNavLink`)
35+
- **`useRequiredChatRuntime()`** — provides `user`, `source`, and navigation context (replaces hub's `useAuth`, `currentPlatform`, `useNavLinkViaRuntime`)
3636
- **`useUnifiedChat()`** — orchestrates Guide/Mingo mode switching and transport adapters
3737
- **`useSseChatAdapter()`** — SSE transport for Guide mode (replaces `useDocChat`)
3838
- **`NavLinkAnchorViaRuntime`** — runtime-aware link rendering (replaces hub's `NavLinkAnchor`)

‎openframe-frontend-core/src/components/chat/.nav-link-anchor-via-runtime.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Primary export. Resolves the final href and new-tab decision at runtime, then de
2020
- **`resolveHrefForRuntime`** — adapts the raw `href` for the active runtime context
2121
- **`computeIsNewTab`** — applies embed-mode short-circuit → `runtime.navigation.decideNewTab` → lib fallback chain
2222
- **`newTabAnchorAttrs`** — produces correct `target` / `rel` attributes
23-
- **`handleChatNavClick`** — unified click handler shared with source chips and inline cards
23+
- **`executeNavigation`** — unified click handler shared with source chips and inline cards
2424
- **`useChatPanel`** — closes the chat panel on same-tab navigation; leaves it open for new-tab clicks
2525

2626
> **Chat-only contract:** Uses `useRequiredChatRuntime`, which **throws** if mounted outside a `<ChatRuntimeContext.Provider>`. This is intentional — silent fallback when the runtime is absent is never acceptable.
@@ -44,7 +44,7 @@ function ChatMarkdownLink({ href, children }) {
4444
}
4545
```
4646

47-
> For links **outside** the chat tree (header chrome, marketing pages), use the hub's own `useNavLink`-based anchor instead — this component will throw in those contexts by design.
47+
> A host mounts the runtime app-wide, so its header, footer and pages use this component (or `useNavLinkViaRuntime` / `useNavigateViaRuntime`) for their own links too.
4848
4949
## Source
5050

‎openframe-frontend-core/src/components/chat/__tests__/chat-message-in-app-links.test.tsx‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
* is the lib rule with no target platform).
1818
*/
1919

20-
import { fireEvent, render, screen } from '@testing-library/react';
20+
import { fireEvent, render, screen, within } from '@testing-library/react';
21+
import type React from 'react';
2122
import { beforeEach, describe, expect, it, vi } from 'vitest';
2223
import { type ChatRuntime, ChatRuntimeContext } from '../../../contexts/chat-runtime-context';
2324
import { ChatMessageEnhanced } from '../chat-message-enhanced';
@@ -101,13 +102,14 @@ describe('ChatMessageEnhanced — in-app screen links', () => {
101102

102103
it("draws a link that stays in the app as the inline box, by the runtime's own new-tab rule", () => {
103104
renderAnswer(ANSWER);
104-
// The box is the anchor around the lib's InlineChip (`InlineAppLinkChip`), routed by the same host anchor.
105-
for (const anchor of screen.getAllByRole('link')) expect(anchor).toHaveClass('no-underline');
105+
// The same routed anchor as every link (see the routing case above); only its content is the lib's InlineChip.
106+
for (const anchor of screen.getAllByRole('link')) expect(within(anchor).getByTestId('inline-chip')).toBeTruthy();
106107
});
107108

108109
it('keeps a link the runtime sends to a new tab a plain link, not a box', () => {
109110
renderAnswer(ANSWER.replace(/\]\(\//g, `](${ORIGIN}/`));
110-
expect(screen.getByRole('link', { name: 'Devices → Add Device' })).not.toHaveClass('no-underline');
111+
const anchor = screen.getByRole('link', { name: 'Devices → Add Device' });
112+
expect(within(anchor).queryByTestId('inline-chip')).toBeNull();
111113
});
112114

113115
it('opens the same link written absolute in a new tab, even on the page origin', () => {
@@ -122,4 +124,34 @@ describe('ChatMessageEnhanced — in-app screen links', () => {
122124
expect(openExternal).toHaveBeenCalledWith(`${ORIGIN}/devices/new`);
123125
expect(routerPush).not.toHaveBeenCalled();
124126
});
127+
128+
it('draws a plain link, without the inline box, when no chat runtime is mounted', () => {
129+
// A host anchor that needs no runtime: the markdown link must not require one either.
130+
function HostAnchor({
131+
href,
132+
className,
133+
children,
134+
}: {
135+
href: string;
136+
className?: string;
137+
children?: React.ReactNode;
138+
}) {
139+
return (
140+
<a href={href} className={className}>
141+
{children}
142+
</a>
143+
);
144+
}
145+
render(
146+
<ChatMessageEnhanced
147+
NavLinkAnchor={HostAnchor}
148+
content={[{ text: ANSWER, type: 'text' }]}
149+
renderEntityCard={() => null}
150+
role="assistant"
151+
/>,
152+
);
153+
const anchor = screen.getByRole('link', { name: 'Devices → Add Device' });
154+
expect(anchor.getAttribute('href')).toBe('/devices/new');
155+
expect(within(anchor).queryByTestId('inline-chip')).toBeNull();
156+
});
125157
});

0 commit comments

Comments
 (0)