diff --git a/apps/website/content/docs/react/chat/guides/thread-routing.mdx b/apps/website/content/docs/react/chat/guides/thread-routing.mdx index abc9c16c0..dc5965d57 100644 --- a/apps/website/content/docs/react/chat/guides/thread-routing.mdx +++ b/apps/website/content/docs/react/chat/guides/thread-routing.mdx @@ -55,6 +55,50 @@ Runtime settings can select a developer LangGraph target. Creation, streams, his +## Keep the active thread in the URL + +The example above keeps its list in page state. To make a conversation linkable and survive a reload, `useThreadRouting` from `@threadplane/react/chat` keeps the active thread in the URL, like Angular `injectThreadRouting`. It restores the thread on load, pushes a history entry when the user selects one, follows the back and forward buttons, and replaces the URL with the bare URL when `exists` reports that the thread is gone. A bare URL means no thread is selected. + +~~~tsx +import { ThreadList, useThreadRouting } from '@threadplane/react/chat'; + +function Threads({ threads, client }) { + const { threadId, setThreadId } = useThreadRouting({ + exists: (id) => client.threads.get(id).then(() => true, () => false), + }); + + return ( + setThreadId(null)} + /> + ); +} +~~~ + +Pass the same `threadId` to the session that loads the conversation. By default the thread is the path segment after `basePath` (`/` gives `/`), and the query string and hash are kept. Set `param: 'thread'` to use `?thread=` instead. `exists` may return a boolean or a promise; a check that fails keeps the thread in place. + +The default binding reads `window.location` and `window.history`. The server render and hydration read no URL and report no thread, and the browser picks up the URL right after hydration. Applications that use React Router or Next.js pass an `adapter` built from their own location and navigation: + +~~~tsx +const location = useLocation(); +const navigate = useNavigate(); +const adapter = useMemo( + () => ({ + read: () => new URLSearchParams(location.search).get('thread'), + write: (id, mode) => + navigate(id ? `?thread=${encodeURIComponent(id)}` : '?', { replace: mode === 'replace' }), + subscribe: () => () => {}, + }), + [location.search, navigate], +); +const { threadId, setThreadId } = useThreadRouting({ adapter }); +~~~ + +`write` receives `push` for a selection and `replace` for a missing thread. `subscribe` reports URL changes made outside `write`; a router that re-renders on navigation can return an empty unsubscribe. + ## Build from source From a Threadplane checkout with dependencies installed: diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index 068d41860..710e55d98 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -90,6 +90,13 @@ export { type ThreadListItem, type ThreadListProps, } from './thread-list.js'; +export { + useThreadRouting, + type ThreadRouting, + type ThreadRoutingAdapter, + type ThreadRoutingOptions, + type ThreadRoutingWriteMode, +} from './thread-routing.js'; export { Timeline, type TimelineItem, type TimelineProps } from './timeline.js'; export { TextTranscript, type TextTranscriptProps } from './text-transcript.js'; export { diff --git a/libs/react/src/chat/thread-routing.spec.tsx b/libs/react/src/chat/thread-routing.spec.tsx new file mode 100644 index 000000000..088d6d891 --- /dev/null +++ b/libs/react/src/chat/thread-routing.spec.tsx @@ -0,0 +1,255 @@ +import { act, cleanup, fireEvent, render } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { renderToString } from 'react-dom/server'; +import { + ThreadList, + useThreadRouting, + type ThreadRouting, + type ThreadRoutingAdapter, + type ThreadRoutingOptions, +} from './index'; + +let latest: ThreadRouting | null = null; + +function Probe(props: { options?: ThreadRoutingOptions }) { + latest = useThreadRouting(props.options); + return {latest.threadId ?? 'none'}; +} + +function shown(container: HTMLElement): string | null | undefined { + return container.querySelector('output')?.textContent; +} + +async function flush(): Promise { + await act(async () => { + await Promise.resolve(); + await Promise.resolve(); + }); +} + +beforeEach(() => { + window.history.replaceState(null, '', '/'); + latest = null; +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + window.history.replaceState(null, '', '/'); +}); + +describe('useThreadRouting', () => { + it('restores the active thread from the URL on load', () => { + window.history.replaceState(null, '', '/abc123'); + const { container } = render(); + expect(shown(container)).toBe('abc123'); + }); + + it('treats the bare URL as no thread and does not write', () => { + const push = vi.spyOn(window.history, 'pushState'); + const replace = vi.spyOn(window.history, 'replaceState'); + const { container } = render(); + expect(shown(container)).toBe('none'); + expect(push).not.toHaveBeenCalled(); + expect(replace).not.toHaveBeenCalled(); + }); + + it('pushes a new history entry when a thread is selected and keeps the query and hash', () => { + window.history.replaceState(null, '', '/?mode=embed#top'); + const push = vi.spyOn(window.history, 'pushState'); + const { container } = render(); + act(() => latest!.setThreadId('xyz')); + expect(push).toHaveBeenCalledTimes(1); + expect(window.location.pathname).toBe('/xyz'); + expect(window.location.search).toBe('?mode=embed'); + expect(window.location.hash).toBe('#top'); + expect(shown(container)).toBe('xyz'); + + act(() => latest!.setThreadId(null)); + expect(window.location.pathname).toBe('/'); + expect(shown(container)).toBe('none'); + }); + + it('does not write when the selected thread is already active', () => { + window.history.replaceState(null, '', '/same'); + const push = vi.spyOn(window.history, 'pushState'); + render(); + act(() => latest!.setThreadId('same')); + expect(push).not.toHaveBeenCalled(); + }); + + it('wires ThreadList selection to the URL', () => { + function Sidebar() { + const { threadId, setThreadId } = useThreadRouting(); + return ( + + ); + } + const { getByText } = render(); + fireEvent.click(getByText('Lisbon')); + expect(window.location.pathname).toBe('/b'); + expect(getByText('Lisbon').closest('button')?.getAttribute('aria-current')).toBe('true'); + }); + + it('follows back and forward navigation', () => { + const { container } = render(); + act(() => latest!.setThreadId('first')); + act(() => latest!.setThreadId('second')); + act(() => { + window.history.replaceState(null, '', '/first'); + window.dispatchEvent(new PopStateEvent('popstate')); + }); + expect(shown(container)).toBe('first'); + }); + + it('reads a query parameter when one is configured', () => { + window.history.replaceState(null, '', '/chat?thread=t1&x=1'); + const { container } = render(); + expect(shown(container)).toBe('t1'); + act(() => latest!.setThreadId('t2')); + expect(window.location.pathname).toBe('/chat'); + expect(new URLSearchParams(window.location.search).get('thread')).toBe('t2'); + expect(new URLSearchParams(window.location.search).get('x')).toBe('1'); + act(() => latest!.setThreadId(null)); + expect(window.location.search).toBe('?x=1'); + }); + + it('reads the segment after a base path', () => { + window.history.replaceState(null, '', '/embed/t1'); + const { container } = render(); + expect(shown(container)).toBe('t1'); + act(() => latest!.setThreadId('t 2')); + expect(window.location.pathname).toBe('/embed/t%202'); + expect(shown(container)).toBe('t 2'); + act(() => latest!.setThreadId(null)); + expect(window.location.pathname).toBe('/embed'); + }); + + it('trims any number of trailing slashes from the base path', () => { + window.history.replaceState(null, '', '/chat/t1'); + const { container } = render( + , + ); + expect(shown(container)).toBe('t1'); + act(() => latest!.setThreadId(null)); + expect(window.location.pathname).toBe('/chat'); + }); + + it('ignores paths outside the base path', () => { + window.history.replaceState(null, '', '/settings/profile'); + const { container } = render(); + expect(shown(container)).toBe('none'); + cleanup(); + window.history.replaceState(null, '', '/embed/t1/details'); + const nested = render(); + expect(shown(nested.container)).toBe('none'); + }); + + it('replaces a missing thread with the bare URL', async () => { + window.history.replaceState(null, '', '/dead?keep=1'); + const push = vi.spyOn(window.history, 'pushState'); + const replace = vi.spyOn(window.history, 'replaceState'); + const exists = vi.fn(async () => false); + const { container } = render(); + await flush(); + expect(exists).toHaveBeenCalledWith('dead'); + expect(replace).toHaveBeenCalledTimes(1); + expect(push).not.toHaveBeenCalled(); + expect(window.location.pathname).toBe('/'); + expect(window.location.search).toBe('?keep=1'); + expect(shown(container)).toBe('none'); + }); + + it('accepts a synchronous existence check and keeps a valid thread', async () => { + window.history.replaceState(null, '', '/live'); + const exists = vi.fn((id: string) => id === 'live'); + const { container } = render(); + await flush(); + expect(shown(container)).toBe('live'); + expect(window.location.pathname).toBe('/live'); + }); + + it('checks each thread once until another is selected, and ignores late answers', async () => { + window.history.replaceState(null, '', '/a'); + let resolveA: (ok: boolean) => void = () => undefined; + const exists = vi.fn((id: string) => + id === 'a' ? new Promise((r) => (resolveA = r)) : true, + ); + const { container, rerender } = render(); + rerender(); + expect(exists).toHaveBeenCalledTimes(1); + act(() => latest!.setThreadId('b')); + await act(async () => resolveA(false)); + expect(shown(container)).toBe('b'); + expect(window.location.pathname).toBe('/b'); + }); + + it('keeps the thread when the existence check fails', async () => { + window.history.replaceState(null, '', '/flaky'); + const exists = vi.fn(async () => { + throw new Error('offline'); + }); + const { container } = render(); + await flush(); + expect(shown(container)).toBe('flaky'); + }); + + it('uses a custom adapter in place of the browser location', async () => { + let current: string | null = 'r1'; + const listeners = new Set<() => void>(); + const writes: [string | null, string][] = []; + const adapter: ThreadRoutingAdapter = { + read: () => current, + write: (id, mode) => { + writes.push([id, mode]); + current = id; + }, + subscribe: (cb) => { + listeners.add(cb); + return () => listeners.delete(cb); + }, + }; + const push = vi.spyOn(window.history, 'pushState'); + const { container, unmount } = render( + id !== 'gone' }} />, + ); + expect(shown(container)).toBe('r1'); + + act(() => latest!.setThreadId('r2')); + expect(writes).toEqual([['r2', 'push']]); + expect(shown(container)).toBe('r2'); + + act(() => { + current = 'gone'; + listeners.forEach((cb) => cb()); + }); + await flush(); + expect(writes).toEqual([ + ['r2', 'push'], + [null, 'replace'], + ]); + expect(shown(container)).toBe('none'); + expect(push).not.toHaveBeenCalled(); + + unmount(); + expect(listeners.size).toBe(0); + }); + + it('renders on the server without touching window', () => { + vi.stubGlobal('window', undefined); + const html = renderToString(); + expect(html).toContain('none'); + }); + + it('renders the server snapshot during hydration of a thread URL', () => { + window.history.replaceState(null, '', '/abc'); + const location = vi.spyOn(window, 'location', 'get'); + renderToString(); + expect(location).not.toHaveBeenCalled(); + }); +}); diff --git a/libs/react/src/chat/thread-routing.ts b/libs/react/src/chat/thread-routing.ts new file mode 100644 index 000000000..f20196fc3 --- /dev/null +++ b/libs/react/src/chat/thread-routing.ts @@ -0,0 +1,185 @@ +import { + useCallback, + useEffect, + useMemo, + useReducer, + useRef, + useSyncExternalStore, +} from 'react'; + +/** How a thread change reaches history: a new entry, or an edit of the current one. */ +export type ThreadRoutingWriteMode = 'push' | 'replace'; + +/** + * Binds the active thread to a URL. The default adapter uses `window.location` and + * `window.history`; React Router or Next.js applications can supply one built from + * their own location and navigation functions. + */ +export interface ThreadRoutingAdapter { + /** The thread id in the current URL, or null for the bare URL. */ + read(): string | null; + /** Write a thread id (null clears it) to the URL. */ + write(threadId: string | null, mode: ThreadRoutingWriteMode): void; + /** Call `onChange` when the URL changes outside `write`, such as back and forward. */ + subscribe(onChange: () => void): () => void; +} + +/** Options for {@link useThreadRouting}. */ +export interface ThreadRoutingOptions { + /** Custom URL binding. When set, `basePath` and `param` are ignored. */ + readonly adapter?: ThreadRoutingAdapter; + /** + * Default adapter: the path the thread segment follows. `'/'` (default) gives + * `/`, `'/chat'` gives `/chat/`. The query and hash are kept. + */ + readonly basePath?: string; + /** Default adapter: store the thread in this query parameter instead of the path. */ + readonly param?: string; + /** + * Checks that a thread from the URL still exists. When it answers false, the + * URL is replaced with the bare URL. A rejected check keeps the thread. + */ + readonly exists?: (threadId: string) => boolean | Promise; +} + +/** The active thread from the URL and the function that changes it. */ +export interface ThreadRouting { + readonly threadId: string | null; + readonly setThreadId: (threadId: string | null) => void; +} + +const noop = (): void => undefined; + +function browser(): Window | undefined { + return typeof window === 'undefined' ? undefined : window; +} + +function normalizeBase(basePath: string): string { + let end = basePath.length; + while (end > 0 && basePath.charCodeAt(end - 1) === 47 /* '/' */) end -= 1; + const trimmed = basePath.slice(0, end); + return trimmed.startsWith('/') || trimmed === '' ? trimmed : `/${trimmed}`; +} + +function decode(segment: string): string | null { + try { + return decodeURIComponent(segment); + } catch { + return null; + } +} + +function browserAdapter(basePath: string, param: string | undefined): ThreadRoutingAdapter { + const base = normalizeBase(basePath); + const listeners = new Set<() => void>(); + const notify = (): void => listeners.forEach((listener) => listener()); + + const read = (): string | null => { + const win = browser(); + if (!win) return null; + if (param) return new URLSearchParams(win.location.search).get(param) || null; + const path = win.location.pathname; + if (path !== base && !path.startsWith(`${base}/`)) return null; + const rest = path.slice(base.length).split('/').filter(Boolean); + return rest.length === 1 ? decode(rest[0]) : null; + }; + + const write = (threadId: string | null, mode: ThreadRoutingWriteMode): void => { + const win = browser(); + if (!win) return; + const { pathname, search, hash } = win.location; + let url: string; + if (param) { + const query = new URLSearchParams(search); + if (threadId) query.set(param, threadId); + else query.delete(param); + const next = query.toString(); + url = `${pathname}${next ? `?${next}` : ''}${hash}`; + } else { + const path = threadId ? `${base}/${encodeURIComponent(threadId)}` : base || '/'; + url = `${path}${search}${hash}`; + } + if (mode === 'push') win.history.pushState(win.history.state, '', url); + else win.history.replaceState(win.history.state, '', url); + notify(); + }; + + const subscribe = (onChange: () => void): (() => void) => { + const win = browser(); + if (!win) return noop; + listeners.add(onChange); + win.addEventListener('popstate', onChange); + return () => { + listeners.delete(onChange); + win.removeEventListener('popstate', onChange); + }; + }; + + return { read, write, subscribe }; +} + +const serverSnapshot = (): null => null; + +/** + * Keeps the active thread in the URL, the React counterpart of Angular + * `injectThreadRouting`. The URL is the source of truth: the thread is restored + * on load, selecting one pushes a history entry, back and forward are followed, + * and a thread that `exists` rejects is replaced with the bare URL. The server + * render and hydration read no URL and report no thread. + * + * @example + * ```tsx + * const { threadId, setThreadId } = useThreadRouting({ + * exists: (id) => client.threads.get(id).then(() => true, () => false), + * }); + * return ; + * ``` + */ +export function useThreadRouting(options: ThreadRoutingOptions = {}): ThreadRouting { + const { adapter: custom, basePath = '/', param, exists } = options; + const adapter = useMemo( + () => custom ?? browserAdapter(basePath, param), + [custom, basePath, param], + ); + // A custom adapter may not notify on its own writes; re-render so the + // snapshot is read again. + const [, rerender] = useReducer((n: number) => n + 1, 0); + const threadId = useSyncExternalStore(adapter.subscribe, adapter.read, serverSnapshot); + + const setThreadId = useCallback( + (next: string | null) => { + if (next === adapter.read()) return; + adapter.write(next, 'push'); + rerender(); + }, + [adapter], + ); + + const existsRef = useRef(exists); + existsRef.current = exists; + const checked = useRef(null); + const hasCheck = exists !== undefined; + + useEffect(() => { + const check = existsRef.current; + if (!check || !threadId || threadId === checked.current) return; + checked.current = threadId; + let answer: Promise; + try { + answer = Promise.resolve(check(threadId)); + } catch { + return; + } + answer.then( + (ok) => { + if (!ok && adapter.read() === threadId) { + adapter.write(null, 'replace'); + rerender(); + } + }, + noop, + ); + }, [threadId, adapter, hasCheck]); + + return useMemo(() => ({ threadId, setThreadId }), [threadId, setThreadId]); +} diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index 0987ec8a6..4a631e5c6 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -19415,6 +19415,41 @@ "treatment": "react", "status": "in-progress", "note": "Turns RenderSpec lifecycle, stateChange and handler events into first-mount, mount-count and latest-activity timings, the React counterpart of Angular RENDER_LIFECYCLE." + }, + { + "id": "export:libs/react/src/chat/index.ts#useThreadRouting", + "taskIds": ["T29"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/thread-routing.ts", + "reason": "Keeps the active thread in the URL like Angular injectThreadRouting: restores it on load, pushes a history entry on selection, follows back and forward, and replaces a thread that exists rejects with the bare URL. React has no single router, so the URL binding is an adapter; the default reads window.location and history and reads nothing on the server." + }, + { + "id": "export:libs/react/src/chat/index.ts#ThreadRouting", + "taskIds": ["T29"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/thread-routing.ts", + "reason": "The active thread id from the URL and its setter, the React counterpart of the app-owned threadId signal Angular binds." + }, + { + "id": "export:libs/react/src/chat/index.ts#ThreadRoutingAdapter", + "taskIds": ["T29"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/thread-routing.ts", + "reason": "React-only seam: read, write and subscribe for the URL so React Router or Next.js applications bind their own location, where Angular uses the Router directly." + }, + { + "id": "export:libs/react/src/chat/index.ts#ThreadRoutingOptions", + "taskIds": ["T29"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/thread-routing.ts", + "reason": "Adapter, base path or query parameter, and an optional existence check, the counterparts of Angular toCommands, threadIdFromUrl and validate." + }, + { + "id": "export:libs/react/src/chat/index.ts#ThreadRoutingWriteMode", + "taskIds": ["T29"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/thread-routing.ts", + "reason": "Push for a selection and replace for a missing thread, matching the navigate and replaceUrl calls Angular makes." + }, + { + "id": "source:libs/react/src/chat/thread-routing.ts", + "taskIds": ["T29"], "treatment": "react", "status": "in-progress", + "note": "useThreadRouting and its default browser adapter, the React counterpart of libs/chat/src/lib/routing/thread-routing.ts." } ] } diff --git a/scripts/react-parity/verify-packages.mjs b/scripts/react-parity/verify-packages.mjs index 588e0b402..69cc3317e 100644 --- a/scripts/react-parity/verify-packages.mjs +++ b/scripts/react-parity/verify-packages.mjs @@ -512,6 +512,7 @@ const SUPPORTED_EXPORTS = { 'createClientTools', 'useClientToolCalls', 'usePendingClientToolCalls', + 'useThreadRouting', 'ToolObservation', 'SubagentCard', 'subagentsFromEvidence', diff --git a/scripts/react-parity/verify-packages.spec.mjs b/scripts/react-parity/verify-packages.spec.mjs index fc10c7659..a5b1cd33a 100644 --- a/scripts/react-parity/verify-packages.spec.mjs +++ b/scripts/react-parity/verify-packages.spec.mjs @@ -1069,6 +1069,7 @@ test('React chat requires its real supported export', () => { supported.isTyping = component; supported.ApprovalRecord = component; for (const name of ['ask', 'createClientTools', 'useClientToolCalls', 'usePendingClientToolCalls']) supported[name] = component; + supported.useThreadRouting = component; assert.throws(() => packageVerifier.assertSupportedExports('react/chat', {}), /ApprovalCard/); for (const name of Object.keys(supported)) { const { [name]: _omitted, ...rest } = supported;