diff --git a/AGENTS.md b/AGENTS.md index fe89e94fa..7ee8a6b28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,7 +98,6 @@ server/ app/ index.html the SPA shell, the bundler entry; #root holds static copies of RouteLoadingFallback and (swapped in on /login by an inline script) LoginForm's first render, painted before the bundle runs client.tsx browser entry: renders `LoginForm` on `/login`, else `AppShell` (a path check, no router) - boot.ts runs first in client.tsx: installs the sidebar history bridge before AppShell registers popstate listeners app/api/ sessions/route.ts GET list all sessions sessions/search/route.ts GET ?q= — NDJSON { scores } batches (titles + transcripts); closing the request stops the scan @@ -151,6 +150,8 @@ app/api/ lib/ dynamic.tsx `dynamic()` over `React.lazy` + `Suspense` navigation.ts `useRouter`/`useSearchParams` over the History API + browser-history.ts single native History API owner: view positions, traversal, reload bounds and root exit guard + session-links.ts session URL builder and same-origin session-link classification omp/ shared omp foundations (paths, CLI probe, RpcProcess) plugins-cli.ts `runOmpCli`, `listPlugins` (`omp plugin list --json` as `PluginEntry[]`), `parseJsonLoose`, `ANSI_RE`; loaded by the daemon too (relative imports only); used by `app/api/plugins/route.ts`, `cluster-config-server.ts` and `daemon-cluster-config.ts` hosts/ hosts and the local daemon (see "Remote hosts"); none of the daemon-loaded files may import `@/` (the daemon runs on Node through `jiti`) @@ -224,7 +225,7 @@ lib/ tool-presets.ts PRESET_NONE/DEFAULT/FULL + getToolNamesForPreset() types.ts shared TypeScript types normalize.ts normalizeToolCalls() — field name mismatch between file format and our types - navigation-history.ts pure back/forward view-history stack + shortcut matcher (⌘[/⌘], Alt+←/→) + navigation-history.ts platform and shortcut matching (⌘[/⌘], Alt+←/→) word-prediction.ts pure ghost-text arithmetic (advance/accept) for composer word prediction worktree.ts project/worktree resolution and git worktree operations @@ -271,7 +272,8 @@ hooks/ useIsMobile.ts responsive breakpoint hook usePrefersReducedMotion.ts OS reduce-motion preference (SMIL-safe) useTheme.ts theme state (localStorage key "omp-theme"; top bar color → theme-color meta, "omp-theme-color" cookie and the manifest link's ?theme=, see lib/manifest-theme.ts) - useNavigationHistory.ts in-app back/forward stack (record/peek/commit/drop) for visited chat views + useNavigationHistory.ts native browser Back/Forward and owned-view bounds + useSidebarHistory.ts document-exit draft protection; does not own sidebar state useWordPrediction.ts debounced omp predict_word ghost text + feedback useBtw.ts /btw records/active panel/history dialog fed by btw_* SSE frames useChatSearchHighlights.ts find-in-page for the sidebar search: CSS Custom Highlight API paint + jump to a picked hit @@ -1738,36 +1740,32 @@ during the wait. - The Models panel reads and writes `models.yml` in the omp agent directory (`~/.omp/agent/models.yml`, `.yaml` fallback). - API-key status endpoints must never return the raw key. -### Navigate back / forward (`lib/navigation-history.ts`, `hooks/useNavigationHistory.ts`) -- Browser-style back/forward over visited chat views (sessions + the new-chat - composer), in-memory per page load. It is **omp-web's own stack**, never the - browser History API — the app only ever `router.replace`s `?session=`, and - the real history stack belongs to the mobile back-gesture / exit-guard - machinery (`useSidebarHistory` + the popstate bridge). -- AppShell records views from one effect keyed on - `(selectedSession?.id, newSessionCwd)`: recording the entry the cursor - already sits on is a no-op, which is what makes back/forward - self-suppressing — `navigateInHistory` commits the step, the view lands, the - effect re-records the target, nothing is pushed. Any other view change - (sidebar/palette select, new chat, session created, fork, project-switch - close) pushes normally and truncates the forward branch, browser-style. -- Applying a step: peek → resolve the session id via `/api/sessions` → - commit + `handleSelectSession`, or `handleNewSession` for new-chat entries. - A dead id (deleted session) drops that entry and tries the next one in the - same direction; a failed list fetch aborts without dropping. A view change - during the await (versioned ref) aborts the navigation so a slow fetch - never yanks the chat away. -- Shortcuts live in `useGlobalKeyboardShortcuts`: ⌘[/⌘] (macOS standard), - Alt+←/Alt+→ (Windows/Linux standard; on macOS Alt+Arrow stays free — it is - word-wise caret movement), plus the mouse back/forward buttons - (`BrowserBack`/`BrowserForward`). The keystroke is always swallowed while a - handler is registered — an exhausted stack stops dead rather than falling - through to the browser's own back/forward, so the app is never backed out - of by accident — and shortcuts are skipped entirely while a - `[role="dialog"]` modal is open. The sidebar header buttons (before Archived - Sessions, wrapped in `.sidebar-nav-buttons`) disable on stack bounds, show - the platform shortcut in their tooltip, and hide below a 240px sidebar via - the `.sidebar-shell` container query (the keyboard shortcuts still work). +### Session URLs and browser history (`lib/browser-history.ts`, `lib/navigation.ts`) +- The browser owns session, new-chat and sidebar view history. `?session=ID` + selects a session; `?cwd=...&hostId=...` selects a new-chat workspace. + `sidebar=open|closed` restores explicit visibility, including on mobile. + AppShell pushes user view changes and replaces new-session promotion or + same-conversation identity moves. Sidebar-only traversal keeps the chat mounted. +- Pooled new chats use `poolId`, `projectId` and `creationId` instead of a worker + path. Restore the logical project and the same creation ID; a worker cwd is + never a fallback. `rememberCreationInitialization` freezes the first native + initialization in tab-local sessionStorage so older sidebar entries and reloads + cannot replay that creation with changed model defaults. It is not URL data. +- `lib/browser-history.ts` is the sole history owner. It preserves unrelated + `history.state`, stores positions (not view copies) in sessionStorage for + reloadable bounds, and keeps a non-view root sentinel for document-exit + confirmation. Canceled exits restore the accepted URL without truncating + forward history. `useSidebarHistory` supplies the draft guard and beforeunload + warning; it never intercepts sidebar/session navigation. +- The sidebar resolves each requested URL session against its list, resetting + restore attempts on target changes. Async workspace validation cancels on + navigation. Identity moves replace the URL without remounting the composer. +- Sidebar session titles are real anchors. `sessionLinkHref` recognizes internal + session URLs before Markdown file-link classification; ordinary clicks push + SPA history, while modified/middle clicks retain native browser behavior. +- Header navigation buttons and keyboard shortcuts use the same native owner, + stop at owned-view bounds, and preserve the existing modal shortcut exclusion. + Native browser Back can leave the app at the root, subject to draft protection. ### Composer word prediction (`hooks/useWordPrediction.ts`, `components/GhostMirror.tsx`) - Ghost text comes from omp's `predict_word` command (engine = omp's diff --git a/CHANGELOG.md b/CHANGELOG.md index c2fc2456a..70e43aa47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f **Before upgrading:** after this update, every linked host already in the first pool uses this machine's provider logins (it can read their access tokens and stored API keys) without a confirmation having been shown. This includes a first pool disabled through the API, and a host added to the first pool later through `PUT /api/hosts` or by editing `pools.json`. Each linked member needs an updated ompweb host daemon (link protocol 9 at that release; cluster members now need link protocol 10, see the first entry) and omp 15.13.1 or newer; until its daemon is updated, cluster placement skips that member, and a start fails when no other member is eligible. Before updating, remove a host that should not receive the logins from the first pool using `PUT /api/hosts` or editing `~/.omp/agent/omp-web/pools.json`; the old version has no membership switch. - **Hosts can use the server's provider logins.** **Settings → Hosts** has a per-host toggle, **Use this server's provider logins**, off by default; turning it on asks for confirmation. Sessions started on that host then use the logins stored on the ompweb server instead of the host's own, through `omp auth-broker serve` on the server and a loopback forwarder in the host daemon. The host token never enters an omp process's environment, and OAuth refresh tokens never leave the server machine; the host can read current access tokens and stored API keys. Starting a session on a sharing host needs a daemon on link protocol v9 and omp 15.13.1 or newer, and is refused otherwise rather than falling back to the host's own logins. Custom providers in `models.yml`, environment-variable API keys and omp settings are not shared. A reverse proxy must let `/api/hosts/broker/` through without its own authentication, response buffering or redirects. - **Windows hosts can be pool workers and accept local maintenance controls.** `ompweb host status`, `drain` and `resume` now work on Windows through a named pipe with a random name and a per-start token, kept in `/omp-web/host-control.json`; requests without the current token are refused. Windows hosts also report CPU busy time and available memory, so pools can place sessions on them. Windows reports no load average, so CPU pressure there comes from busy time alone. +- **Share session links and navigate with browser Back/Forward.** Session titles in the sidebar are real links, supporting Copy link and opening in another tab. Session links in chat open the conversation rather than the file viewer. The URL records the selected session or new-chat workspace and sidebar visibility, and Back/Forward restores those views on desktop and mobile. Sidebar-only navigation keeps the composer mounted, per-session drafts survive switches, and leaving the app still warns about unsent drafts. - **Archive and restore sessions on linked hosts.** Archiving now works for sessions on any linked machine, not only this one. The Archived Sessions browser lists every host's archive, shows which host each session is on, and restores it on that host. A host that is offline or runs an older ompweb host is named in the browser instead of hiding its archive silently. Restore rejects a session ID already active on any registered host, so every registered host must be online to restore, even an archive on this machine; the browser names the offline host that blocks it. A per-session claim stops web-server processes that share one agent directory from restoring the same session together; it does not coordinate separate web servers that share a daemon. A restore on another host keeps running when the web server stops waiting for it (after 30 s, or when the link drops), so the session stays claimed until that host's daemon process confirms it stopped: restoring the same ID again, on any host, is refused until then instead of creating a second active copy. Only the daemon process that took the restore can confirm that, so if the daemon was replaced, restarted or shut down meanwhile, or its host was unregistered, the session stays blocked: there is no timeout and no automatic clearing, and recovery is manual (see AGENTS.md). A restored session's attachments and other files are put back before the session becomes visible, so a file attached from another tab at that moment can no longer fail the restore or block retrying it. Restore streams archives with fixed 256 MiB compressed and expanded limits and rejects unsupported session IDs before consuming the archive. - **Traditional Chinese (`zh-TW`) interface language.** Select Traditional Chinese (繁體中文) in the top-bar language menu. On compact layouts, open **More controls** first. Alternatively, let omp-web pick it automatically when the browser language is `zh-TW`, `zh-HK`, `zh-MO`, or `zh-Hant`. Localized Web Push notifications and a Traditional Chinese README (`README.zh-TW.md`) are included. - **Several web apps can share one host daemon and the same live sessions.** Link additional servers with `ompweb host login --add --url ` (token from stdin). Prompts, tool progress, results and dialogs stay synchronized, and restarting one web app leaves the other connected to the same omp process. Link protocol v7 moves session startup, idle cleanup and interrupted-run recovery into the host; older links remain supported without sharing their processes. Schedule the first daemon upgrade while its host is quiescent. diff --git a/README.md b/README.md index 7d5ed32ed..9c34fabe8 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,20 @@ The **Steer**, **Delete** and **Edit** actions on a queued message are commands The queue panel shows omp's own queue (`queuedMessages` in `get_state` and `queue_update` events), so every device viewing a session sees the same queued messages. **Stop** moves the text of messages still waiting in the queue back into the composer instead of letting the agent run them; a steer the model already picked up through live steering still runs. +## Shareable navigation + +Each session has a URL such as `/?session=`. Session titles in the sidebar +are links: use your browser's Copy link or open-in-new-tab controls. Session +links in chat navigate within the app. + +Browser Back/Forward and the sidebar navigation buttons restore session changes +and sidebar visibility (`&sidebar=open` or `&sidebar=closed`). New-chat URLs keep +their workspace in `?cwd=...`, with `hostId` for another machine, or +`?poolId=...&projectId=...&creationId=...` for a pooled creation. Reloading restores +the URL's view; sidebar-only changes do not reset the composer. Frozen pooled +initialization stays in this tab's session storage, not in shared URLs. +Drafts remain separate from URLs, and leaving the app warns about unsent drafts. + ## App installation behind authentication To install the web app, sign in first and use your browser's installation menu. diff --git a/app/boot.ts b/app/boot.ts deleted file mode 100644 index bf3410ba6..000000000 --- a/app/boot.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Imported first by client.tsx so it runs before AppShell's module evaluates and registers its own popstate listeners. -import { SIDEBAR_HISTORY_BRIDGE_SCRIPT } from "@/lib/sidebar-history-bridge"; - -const script = document.createElement("script"); -script.textContent = SIDEBAR_HISTORY_BRIDGE_SCRIPT; -document.head.append(script); diff --git a/app/client.tsx b/app/client.tsx index a988daa36..dc6e0101b 100644 --- a/app/client.tsx +++ b/app/client.tsx @@ -1,4 +1,3 @@ -import "./boot"; import { StrictMode, Suspense } from "react"; import { createRoot } from "react-dom/client"; import { AppErrorBoundary } from "@/components/AppErrorBoundary"; diff --git a/components/AppShell.tsx b/components/AppShell.tsx index d85afcddc..233590173 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -7,7 +7,7 @@ import { useGlobalKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts"; import { useSidebarHistory } from "@/hooks/useSidebarHistory"; import { useModalDialog } from "@/hooks/useModalDialog"; import { useNavigationHistory } from "@/hooks/useNavigationHistory"; -import { isMacPlatform, navigateShortcutHint, NAVIGATION_HISTORY_MAX_ENTRIES } from "@/lib/navigation-history"; +import { isMacPlatform, navigateShortcutHint } from "@/lib/navigation-history"; import { useMobileSidebarGestures } from "@/hooks/useMobileSidebarGestures"; import { SessionSidebar } from "./SessionSidebar"; import type { SearchMatchTarget } from "./SessionSearchMatches"; @@ -37,7 +37,7 @@ import { getFileApiUrl, getFileName, getRelativeFilePath, joinFilePath } from "@ import { normalizeLocalPath } from "@/lib/file-links"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { buildAtMentionText, buildFileAtMentionsText, buildFileLineMentionText } from "@/lib/file-fuzzy"; -import { getInitialNavigation } from "@/lib/initial-navigation"; +import { getInitialNavigation, readCreationInitialization, rememberCreationInitialization } from "@/lib/initial-navigation"; import { comparableProjectPath } from "@/lib/comparable-path"; import { foldedHostProjectKey, hostProjectKey, LOCAL_HOST_ID, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; import { isClusterTarget } from "@/lib/hosts/cluster"; @@ -121,10 +121,30 @@ type AutoNameStatus = | { kind: "error"; message: string }; type TimerHandle = NodeJS.Timeout; +function viewUrl({ sessionId, cwd, hostId, poolId, projectId, creationId, sidebarOpen }: { sessionId?: string; cwd?: string | null; hostId?: string; poolId?: string; projectId?: string; creationId?: string; sidebarOpen: boolean }): string { + const params = new URLSearchParams(); + if (sessionId) params.set("session", sessionId); + else if (poolId || projectId) { + if (poolId) params.set("poolId", poolId); + if (projectId) params.set("projectId", projectId); + if (creationId) params.set("creationId", creationId); + } + else if (cwd) { + params.set("cwd", cwd); + if (hostId && hostId !== LOCAL_HOST_ID) params.set("hostId", hostId); + } + params.set("sidebar", sidebarOpen ? "open" : "closed"); + return `/?${params}`; +} + export function AppShell({ appName }: { appName: string }) { const router = useRouter(); const searchParams = useSearchParams(); - const [initialNavigation] = useState(() => getInitialNavigation(searchParams)); + const initialNavigation = useMemo(() => getInitialNavigation(searchParams), [searchParams]); + const navViewVersionRef = useRef(0); + useEffect(() => { + navViewVersionRef.current += 1; + }, [searchParams]); const { t, locale } = useI18n(); const isMobile = useIsMobile(); const isCompactOverlay = useIsCompactOverlay(); @@ -137,10 +157,11 @@ export function AppShell({ appName }: { appName: string }) { const [newSessionCreation, setNewSessionCreation] = useState<{ id?: string; initialization?: string }>({}); const newSessionCreationId = newSessionCreation.id; const handleNewSessionInitialization = useCallback((initialization: string) => { + if (newSessionCreationId) initialization = rememberCreationInitialization(newSessionCreationId, initialization); setNewSessionCreation((current) => current.id === newSessionCreationId && current.initialization === undefined ? { ...current, initialization } : current); }, [newSessionCreationId]); const [newSessionPoolProject, setNewSessionPoolProject] = useState(null); - const [workspaceOptions, setWorkspaceOptions] = useState<{ projects: ManagedProject[]; selectedProject: string | null; cwd: string | null; hostId: string }>({ projects: [], selectedProject: null, cwd: null, hostId: LOCAL_HOST_ID }); + const [workspaceOptions, setWorkspaceOptions] = useState<{ projects: ManagedProject[]; selectedProject: string | null; cwd: string | null; hostId: string; loaded: boolean }>({ projects: [], selectedProject: null, cwd: null, hostId: LOCAL_HOST_ID, loaded: false }); const [addProjectOpen, setAddProjectOpen] = useState(false); const [addProjectHostId, setAddProjectHostId] = useState(LOCAL_HOST_ID); const openAddProject = useCallback((open: boolean, hostId: string = LOCAL_HOST_ID) => { @@ -148,8 +169,8 @@ export function AppShell({ appName }: { appName: string }) { setAddProjectOpen(open); }, []); const { hosts, pools, poolsLoaded } = useHostRows(); - const handleWorkspaceOptionsChange = useCallback((projects: ManagedProject[], selectedProject: string | null, cwd: string | null, hostId: string) => { - setWorkspaceOptions({ projects, selectedProject, cwd, hostId }); + const handleWorkspaceOptionsChange = useCallback((projects: ManagedProject[], selectedProject: string | null, cwd: string | null, hostId: string, loaded: boolean) => { + setWorkspaceOptions({ projects, selectedProject, cwd, hostId, loaded }); }, []); const [initialCwdStatus, setInitialCwdStatus] = useState<"idle" | "validating" | "ready" | "error">( () => initialNavigation.requestedCwd ? "validating" : "idle", @@ -162,7 +183,15 @@ export function AppShell({ appName }: { appName: string }) { const [settingsTab, setSettingsTab] = useState(null); const [archiveBrowserOpen, setArchiveBrowserOpen] = useState(false); const [modelsRefreshKey, setModelsRefreshKey] = useState(0); - const [sidebarOpen, setSidebarOpen] = useState(true); + const sidebarOpen = searchParams.get("sidebar") === "open" || (searchParams.get("sidebar") !== "closed" && !isMobile); + const setSidebarOpen = useCallback((next: boolean | ((open: boolean) => boolean)) => { + const params = new URLSearchParams(window.location.search); + const previous = params.get("sidebar") === "open" || (params.get("sidebar") !== "closed" && !isMobile); + const open = typeof next === "function" ? next(previous) : next; + if (open === previous) return; + params.set("sidebar", open ? "open" : "closed"); + router.push(`/?${params}`); + }, [isMobile, router]); const [mobileSidebarReady, setMobileSidebarReady] = useState(false); const [sidebarWidth, setSidebarWidth] = useState(SIDEBAR_DEFAULT_WIDTH); const [toolCallsDefaultCollapsed, setToolCallsDefaultCollapsed] = useState(true); @@ -347,11 +376,6 @@ export function AppShell({ appName }: { appName: string }) { advanceAppUpdateVisibleStage(next); } }, [advanceAppUpdateVisibleStage]); - // On mobile the sidebar is an overlay drawer; hide it by default so the chat - // is visible on load. Runs once the breakpoint resolves after hydration. - useEffect(() => { - if (isMobile) setSidebarOpen(false); - }, [isMobile]); useEffect(() => { setMobileSidebarReady(true); }, []); @@ -735,7 +759,7 @@ export function AppShell({ appName }: { appName: string }) { const toggleTopPanel = useCallback((panel: "branches" | "system") => { if (isMobile) setSidebarOpen(false); setActiveTopPanel((cur) => cur === panel ? null : panel); - }, [isMobile]); + }, [isMobile, setSidebarOpen]); // Generation speed — current live t/s and the session average. const [generationSpeed, setGenerationSpeed] = useState(null); @@ -769,7 +793,7 @@ export function AppShell({ appName }: { appName: string }) { if (mobileToolsRef.current) mobileToolsRef.current.open = false; } setSidebarOpen((open) => !open); - }, [isMobile]); + }, [isMobile, setSidebarOpen]); const resetSidebarWidth = useCallback(() => { setSidebarWidth(SIDEBAR_DEFAULT_WIDTH); @@ -1110,6 +1134,11 @@ export function AppShell({ appName }: { appName: string }) { useEffect(() => { const requestedCwd = initialNavigation.requestedCwd; if (!requestedCwd) return; + // A sidebar switch leaves newSessionCwd null and follows activeCwd; its own pushed URL needs no validation. + if (!selectedSession && (newSessionCwd ?? activeCwd) === requestedCwd && (newSessionCwd !== null ? newSessionHostId : activeHostId) === remoteHostId(initialNavigation.hostId)) { + setInitialCwdStatus("ready"); + return; + } const controller = new AbortController(); setInitialCwdStatus("validating"); @@ -1131,6 +1160,12 @@ export function AppShell({ appName }: { appName: string }) { // The sidebar will notify us when it adopts this cwd. Avoid remounting // the just-created empty chat during that initial synchronization. suppressCwdRef.current = data.cwd; + setSettingsTab(null); + setSelectedSession(null); + setNewSessionPoolProject(null); + setActivePoolProject(null); + setSessionKey((key) => key + 1); + setInitialSessionRestored(true); setNewSessionCwd(data.cwd); setNewSessionHostId(remoteHostId(initialNavigation.hostId)); setActiveCwd(data.cwd); @@ -1144,9 +1179,67 @@ export function AppShell({ appName }: { appName: string }) { }); return () => controller.abort(); - }, [initialNavigation]); + }, [initialNavigation.requestedCwd, initialNavigation.hostId, selectedSession, newSessionCwd, newSessionHostId, activeCwd, activeHostId]); + + useEffect(() => { + const { poolId, projectId, creationId } = initialNavigation; + if (!poolId && !projectId) return; + // The sidebar reports an empty list before its first fetch; only a settled list can reject a target. + if (!poolsLoaded || !workspaceOptions.loaded) return; + const project = workspaceOptions.projects.find((candidate) => candidate.poolId === poolId && candidate.projectId === projectId); + if (!poolId || !projectId || !project) { + setInitialCwdError(translate("agentSession.invalidPoolTarget")); + setInitialCwdStatus("error"); + return; + } + if (!creationId) { + router.replace(viewUrl({ poolId, projectId, creationId: crypto.randomUUID(), sidebarOpen })); + return; + } + if (!selectedSession && newSessionPoolProject?.poolId === poolId && newSessionPoolProject.projectId === projectId && newSessionCreation.id === creationId) { + // The app already adopted this target (sidebar pick, New Session); a previous URL's error must not hide it. + setInitialCwdStatus("idle"); + return; + } + setSelectedSession(null); + setSettingsTab(null); + setNewSessionCwd(null); + setNewSessionHostId(undefined); + setNewSessionPoolProject(project); + setActivePoolProject(project); + setActiveCwd(null); + setActiveHostId(undefined); + setNewSessionCreation({ id: creationId, initialization: readCreationInitialization(creationId) }); + setSessionKey((key) => key + 1); + setInitialCwdStatus("idle"); + setInitialSessionRestored(true); + }, [initialNavigation, poolsLoaded, workspaceOptions.projects, workspaceOptions.loaded, newSessionPoolProject, newSessionCreation.id, selectedSession, router, sidebarOpen]); + + useEffect(() => { + if (initialNavigation.sessionId || initialNavigation.requestedCwd || initialNavigation.poolId || initialNavigation.projectId) return; + if (selectedSession || newSessionCwd || newSessionHostId || newSessionPoolProject || activePoolProject) { + setSelectedSession(null); + setNewSessionCwd(null); + setNewSessionHostId(undefined); + setNewSessionPoolProject(null); + setActivePoolProject(null); + setSessionKey((key) => key + 1); + setSettingsTab(null); + } + setInitialCwdStatus("idle"); + setInitialSessionRestored(true); + }, [initialNavigation.sessionId, initialNavigation.requestedCwd, initialNavigation.poolId, initialNavigation.projectId, selectedSession, newSessionCwd, newSessionHostId, newSessionPoolProject, activePoolProject]); + + // Back/Forward to a session the list has not loaded yet must not leave the + // previous chat composable under the new URL; the restore reselects it. + const handleRestorePending = useCallback(() => { + setSelectedSession(null); + setInitialSessionRestored(false); + }, []); - const handleCwdChange = useCallback((cwd: string | null, projectRoot: string | null, hostId: string, project?: ManagedProject) => { + const handleCwdChange = useCallback((cwd: string | null, projectRoot: string | null, hostId: string, project?: ManagedProject, automatic = false) => { + // The sidebar's own top-project pick replaces the URL: Back must not land on an emptied bare view. + const navigate = automatic ? router.replace : router.push; setActivePoolProject(project?.poolId ? project : null); setActiveCwd(project?.poolId ? null : cwd); setActiveHostId(project?.poolId ? undefined : remoteHostId(hostId)); @@ -1154,7 +1247,8 @@ export function AppShell({ appName }: { appName: string }) { if (selectedSession?.poolId === project.poolId && selectedSession.projectId === project.projectId) return; if (newSessionPoolProject?.poolId === project.poolId && newSessionPoolProject.projectId === project.projectId) return; setNewSessionPoolProject(project); - setNewSessionCreation({ id: crypto.randomUUID() }); + const creationId = crypto.randomUUID(); + setNewSessionCreation({ id: creationId }); setNewSessionCwd(null); setNewSessionHostId(undefined); setSelectedSession(null); @@ -1164,7 +1258,7 @@ export function AppShell({ appName }: { appName: string }) { setSystemPrompt(null); setSystemPromptLoading(false); setActiveTopPanel(null); - router.replace("/"); + navigate(viewUrl({ poolId: project.poolId, projectId: project.projectId, creationId, sidebarOpen })); return; } // A standalone path is never a fallback for a pending pool placement. @@ -1201,8 +1295,8 @@ export function AppShell({ appName }: { appName: string }) { setSystemPrompt(null); setSystemPromptLoading(false); setActiveTopPanel(null); - router.replace("/"); - }, [router, selectedSession, newSessionPoolProject]); + navigate(viewUrl({ cwd, hostId, sidebarOpen })); + }, [router, selectedSession, newSessionPoolProject, sidebarOpen]); const handleSelectSession = useCallback((session: SessionInfo, isRestore = false) => { // Re-picking the already-open session (sidebar double-click, palette @@ -1211,11 +1305,17 @@ export function AppShell({ appName }: { appName: string }) { setSettingsTab(null); // Re-picking the current conversation still closes/rearms the drawer, // without remounting the chat or disturbing its draft. - if (isMobile && !isRestore) { - setSidebarOpen(false); - requestAnimationFrame(() => chatInputRef.current?.focus()); + if (isMobile && !isRestore) requestAnimationFrame(() => chatInputRef.current?.focus()); + if (session.id === selectedSession?.id) { + if (isMobile && !isRestore) setSidebarOpen(false); + // Back/Forward may have left a workspace URL over this still-selected chat; + // returning to its own URL also cancels that workspace's validation. + if (!isRestore && initialNavigation.sessionId !== session.id) { + router.push(viewUrl({ sessionId: session.id, sidebarOpen: isMobile ? false : sidebarOpen })); + setInitialCwdStatus("idle"); + } + return; } - if (!isRestore && session.id === selectedSession?.id) return; setNewSessionCwd(null); setNewSessionPoolProject(null); setSelectedSession(session); @@ -1231,17 +1331,16 @@ export function AppShell({ appName }: { appName: string }) { // genuine project switch. suppressCwdRef.current = session.cwd; } - // Skip router.replace when restoring from the URL: the param is already correct. - if (!isRestore) { - router.replace(`?session=${encodeURIComponent(session.id)}`); - } - }, [router, isMobile, selectedSession?.id]); + if (!isRestore) router.push(viewUrl({ sessionId: session.id, sidebarOpen: isMobile ? false : sidebarOpen })); + setInitialCwdStatus("idle"); + }, [router, isMobile, selectedSession?.id, sidebarOpen, setSidebarOpen, initialNavigation.sessionId]); const handleNewSession = useCallback((creationId: string, cwd: string | null, hostId?: string, project?: ManagedProject, initialization?: string) => { setSettingsTab(null); setSelectedSession(null); const target = project ?? (cwd === activeCwd ? activePoolProject : null); - setNewSessionCreation({ id: creationId || crypto.randomUUID(), initialization }); + const nextCreationId = creationId || crypto.randomUUID(); + setNewSessionCreation({ id: nextCreationId, initialization: initialization ?? readCreationInitialization(nextCreationId) }); setNewSessionPoolProject(target?.poolId ? target : null); setNewSessionCwd(target?.poolId ? null : cwd); setNewSessionHostId(target?.poolId ? undefined : remoteHostId(hostId)); @@ -1251,99 +1350,13 @@ export function AppShell({ appName }: { appName: string }) { setSystemPrompt(null); setSystemPromptLoading(false); setActiveTopPanel(null); - if (isMobile) { - setSidebarOpen(false); - requestAnimationFrame(() => chatInputRef.current?.focus()); - } - router.replace("/"); - }, [router, isMobile, activeCwd, activePoolProject]); + if (isMobile) requestAnimationFrame(() => chatInputRef.current?.focus()); + router.push(viewUrl({ cwd: target?.poolId ? null : cwd, hostId: target?.poolId ? undefined : hostId, poolId: target?.poolId, projectId: target?.projectId, creationId: nextCreationId, sidebarOpen: isMobile ? false : sidebarOpen })); + }, [router, isMobile, activeCwd, activePoolProject, sidebarOpen]); - // ---- In-app Navigate back / forward over visited chat views ---- - // Own stack, not the browser History API (that one belongs to the mobile - // back-gesture/exit-guard machinery — see lib/navigation-history.ts). const navigationHistory = useNavigationHistory(); - const { - record: recordNavigationView, - peekBack: peekNavigationBack, - peekForward: peekNavigationForward, - } = navigationHistory; - // Bumped by the recording effect on every view change. navigateInHistory - // captures it across its await and bails if the user moved on meanwhile, - // so a slow session-list fetch can never yank the chat out from under a - // view the user just switched to. - const navViewVersionRef = useRef(0); - const navSessionId = selectedSession?.id ?? null; - const navSessionCwd = selectedSession?.cwd ?? null; - useEffect(() => { - navViewVersionRef.current += 1; - recordNavigationView({ - sessionId: navSessionId, - cwd: navSessionId ? navSessionCwd : newSessionCwd, - ...(!navSessionId && newSessionHostId ? { hostId: newSessionHostId } : {}), - ...(!navSessionId && newSessionPoolProject ? { poolId: newSessionPoolProject.poolId, projectId: newSessionPoolProject.projectId } : {}), - ...(!navSessionId ? { creationId: newSessionCreationId } : {}), - ...(!navSessionId && newSessionPoolProject && newSessionCreation.initialization ? { initialization: newSessionCreation.initialization } : {}), - }); - }, [navSessionId, navSessionCwd, newSessionCwd, newSessionHostId, newSessionPoolProject, newSessionCreation, newSessionCreationId, recordNavigationView]); - - // Resolves a history entry's session id against the live list. `null` - // means the id is gone (entry should be dropped); "unavailable" means the - // list itself could not be fetched (keep the entry, abort this navigation). - const fetchSessionForNavigation = useCallback(async (sessionId: string): Promise => { - try { - const res = await fetch(`/api/sessions?id=${encodeURIComponent(sessionId)}`); - if (!res.ok) return "unavailable"; - const data = (await res.json()) as { sessions?: SessionInfo[] }; - return data.sessions?.find((s) => s.id === sessionId) ?? null; - } catch { - return "unavailable"; - } - }, []); - - const navigateInHistory = useCallback(async (direction: -1 | 1): Promise => { - // Dead entries (deleted sessions) are skipped, like browser history - // skipping a dead slot; bound the loop by the stack's own cap. - for (let attempt = 0; attempt <= NAVIGATION_HISTORY_MAX_ENTRIES; attempt++) { - const entry = direction === -1 ? peekNavigationBack() : peekNavigationForward(); - // Nothing that way: stay put. An exhausted stack never falls through to - // the browser's own back/forward — the keystroke is swallowed by the - // keyboard layer, so the app can never be backed out of by accident. - if (!entry) return; - if (entry.sessionId === null) { - if (direction === -1) navigationHistory.commitBack(); - else navigationHistory.commitForward(); - const project = entry.poolId ? workspaceOptions.projects.find((candidate) => candidate.poolId === entry.poolId && candidate.projectId === entry.projectId) : undefined; - if (entry.poolId && !project) { toast.error(translate("errors.generic")); return; } - handleNewSession(entry.creationId ?? crypto.randomUUID(), entry.cwd, entry.hostId, project, entry.initialization); - return; - } - const versionAtPress = navViewVersionRef.current; - const session = await fetchSessionForNavigation(entry.sessionId); - if (navViewVersionRef.current !== versionAtPress) return; // user moved on: do nothing - if (session === "unavailable") return; // list fetch failed: keep the entry, try again next press - if (session) { - if (direction === -1) navigationHistory.commitBack(); - else navigationHistory.commitForward(); - handleSelectSession(session, false); - return; - } - if (direction === -1) navigationHistory.dropPeekedBack(); - else navigationHistory.dropPeekedForward(); - } - }, [navigationHistory, peekNavigationBack, peekNavigationForward, fetchSessionForNavigation, handleNewSession, handleSelectSession, workspaceOptions.projects]); - - // Shared by the sidebar buttons and the global shortcuts. The keyboard - // layer always swallows the keystroke, so both directions stop dead at the - // ends of the stack instead of continuing into browser history. - const handleNavigateBack = useCallback(() => { - void navigateInHistory(-1); - }, [navigateInHistory]); - const handleNavigateForward = useCallback(() => { - void navigateInHistory(1); - }, [navigateInHistory]); - - // Tooltip shortcut labels follow the platform (⌘[ vs Alt+←). Computed from - // navigator after mount state to keep SSR markup stable. + const handleNavigateBack = navigationHistory.back; + const handleNavigateForward = navigationHistory.forward; const [navIsMac] = useState(() => isMacPlatform()); const sidebarNavigation = useMemo(() => ({ canBack: navigationHistory.canBack, @@ -1386,8 +1399,8 @@ export function AppShell({ appName }: { appName: string }) { setSelectedSession(session); setRefreshKey((k) => k + 1); hydrateSelectedSession(session.id); - router.replace(`?session=${encodeURIComponent(session.id)}`); - }, [router, hydrateSelectedSession]); + router.replace(viewUrl({ sessionId: session.id, sidebarOpen })); + }, [router, hydrateSelectedSession, sidebarOpen]); const handleSessionMoved = useCallback((oldId: string, newId: string) => { if (activeSessionIdRef.current !== oldId) return; @@ -1397,8 +1410,8 @@ export function AppShell({ appName }: { appName: string }) { hydrateSelectedSession(newId); // This is the same conversation. Preserve ChatWindow's run/edit fences // and its mounted composer, including unfinished attachments and audio. - router.replace(`?session=${encodeURIComponent(newId)}`); - }, [router, hydrateSelectedSession]); + router.replace(viewUrl({ sessionId: newId, sidebarOpen })); + }, [router, hydrateSelectedSession, sidebarOpen]); const handleAgentEnd = useCallback(() => { setRefreshKey((k) => k + 1); @@ -1490,8 +1503,8 @@ export function AppShell({ appName }: { appName: string }) { path: "", })); hydrateSelectedSession(newSessionId); - router.replace(`?session=${encodeURIComponent(newSessionId)}`); - }, [router, hydrateSelectedSession]); + router.push(viewUrl({ sessionId: newSessionId, sidebarOpen })); + }, [router, hydrateSelectedSession, sidebarOpen]); const handleSessionDeleted = useCallback((sessionId: string) => { // The composer for this session can never be reopened, so its draft would @@ -1502,7 +1515,8 @@ export function AppShell({ appName }: { appName: string }) { const cwd = selectedSession.cwd; setSelectedSession(null); setNewSessionCwd(selectedSession.poolId ? null : cwd ?? null); - setNewSessionCreation({ id: crypto.randomUUID() }); + const creationId = crypto.randomUUID(); + setNewSessionCreation({ id: creationId }); setNewSessionPoolProject(selectedSession.poolId ? workspaceOptions.projects.find((project) => project.poolId === selectedSession.poolId && project.projectId === selectedSession.projectId) ?? null : null); setNewSessionHostId(remoteHostId(selectedSession.hostId)); setSessionKey((k) => k + 1); @@ -1510,10 +1524,13 @@ export function AppShell({ appName }: { appName: string }) { setBranchActiveLeafId(null); setSystemPrompt(null); setActiveTopPanel(null); - router.replace("/"); + router.replace(viewUrl({ cwd: selectedSession.poolId ? null : cwd, hostId: selectedSession.hostId, poolId: selectedSession.poolId, projectId: selectedSession.projectId, creationId, sidebarOpen })); } - }, [selectedSession, router, workspaceOptions.projects]); + }, [selectedSession, router, workspaceOptions.projects, sidebarOpen]); const handleInitialRestoreDone = useCallback(() => { + setSelectedSession(null); + setNewSessionCwd(null); + setInitialCwdStatus("idle"); setInitialSessionRestored(true); }, []); @@ -1547,12 +1564,12 @@ export function AppShell({ appName }: { appName: string }) { if (attemptsLeft > 0) { archiveRetryTimerRef.current = setTimeout(() => void selectRestoredSession(attemptsLeft - 1), 300); } else if (activeSessionIdRef.current === sessionAtRestoreStart) { - router.replace(`?session=${encodeURIComponent(sessionId)}`); + router.push(viewUrl({ sessionId, sidebarOpen: isMobile ? false : sidebarOpen })); } }; void selectRestoredSession(); - }, [handleSelectSession, router]); + }, [handleSelectSession, router, isMobile, sidebarOpen]); const handleCloseFileTab = useCallback((tabId: string) => { // Compute everything from the current list outside the updaters: no side @@ -1583,7 +1600,7 @@ export function AppShell({ appName }: { appName: string }) { setRightPanelOpen(true); // On mobile the file panel is full-screen; close the drawer so it shows. if (isMobile) setSidebarOpen(false); - }, [isMobile]); + }, [isMobile, setSidebarOpen]); // Agent open requests that wait for the user. URLs always ask unless the // user opted into opening links from the viewed session automatically; URLs @@ -1789,7 +1806,14 @@ export function AppShell({ appName }: { appName: string }) { // What Settings act for, as settingsHostId picks it: the sidebar's project, else the open session, the new chat, the pool project. const settingsTarget = activeCwd ? { hostId: activeHostId } : selectedSession ?? (newSessionCwd !== null ? { hostId: newSessionHostId } : effectivePoolProject); const clusterSettings = isClusterTarget(settingsTarget, settingsHostId, pools); - const showChat = selectedSession !== null || effectiveNewSessionCwd !== null || effectivePoolProject !== null; + // Only a URL that still names an unresolved session is a pending restore; any + // other view (New Session, a project, a pooled composer) ends it. + const restorePending = Boolean(initialSessionId) && !initialSessionRestored; + // A workspace URL that is still validating or was rejected must not leave the previous chat usable under it. + const workspaceUnresolved = Boolean(initialNavigation.requestedCwd || initialNavigation.poolId || initialNavigation.projectId) + && (initialCwdStatus === "validating" || initialCwdStatus === "error"); + // While a URL session restore is pending, the sidebar's project must not offer a new chat in its place. + const showChat = !workspaceUnresolved && (selectedSession !== null || (!restorePending && (effectiveNewSessionCwd !== null || effectivePoolProject !== null))); const currentRate = generationSpeed?.current; const rate = currentRate ?? generationSpeed?.average; const speed = showChat ? formatGenerationSpeed(rate) : null; @@ -1857,15 +1881,9 @@ export function AppShell({ appName }: { appName: string }) { }; }, [isMobile, locale, settingsTab, showChat]); // While restoring initial session from URL, don't show the placeholder - const showPlaceholder = initialSessionRestored && !showChat; - - const sidebarHistory = useSidebarHistory({ - active: isMobile && (showChat || Boolean(initialSessionId)), - ready: mobileSidebarReady, - sidebarOpen, - setSidebarOpen, - url: searchParams.toString(), - }); + const showPlaceholder = !restorePending && !showChat; + + const sidebarHistory = useSidebarHistory(); useEffect(() => { if (sidebarHistory.exitNeedsNativeBack) { toast.info(t("appShell.exitNativeBackTitle"), t("appShell.exitNativeBackDescription")); @@ -1908,8 +1926,9 @@ export function AppShell({ appName }: { appName: string }) { onSelectSession={handleSelectSession} onNewSession={handleNewSession} initialSessionId={initialSessionId} - skipInitialProjectSelection={initialNavigation.requestedCwd !== null} + skipInitialProjectSelection={initialNavigation.requestedCwd !== null || Boolean(initialNavigation.poolId || initialNavigation.projectId)} onInitialRestoreDone={handleInitialRestoreDone} + onRestorePending={handleRestorePending} refreshKey={refreshKey} onSessionDeleted={handleSessionDeleted} selectedCwd={selectedSession?.cwd ?? newSessionCwd ?? null} diff --git a/components/ChatInput.navigation.test.mjs b/components/ChatInput.navigation.test.mjs index 32cd91f54..577627cad 100644 --- a/components/ChatInput.navigation.test.mjs +++ b/components/ChatInput.navigation.test.mjs @@ -30,7 +30,7 @@ function warnsOnExit() { function Guard() { // The actual history protocol is exercised in useSidebarHistory.test.mjs. // This mounts the same document guard with the real composer/draft store. - useSidebarHistory({ active: false, ready: false, sidebarOpen: true, setSidebarOpen() {}, url: "" }); + useSidebarHistory(); return null; } diff --git a/components/MarkdownBody.file-links.test.mjs b/components/MarkdownBody.file-links.test.mjs index a3f99de4c..15bd607e2 100644 --- a/components/MarkdownBody.file-links.test.mjs +++ b/components/MarkdownBody.file-links.test.mjs @@ -6,7 +6,10 @@ const { cleanup, fireEvent, render } = await import("@testing-library/react/pure const { MarkdownBody } = await import("./MarkdownBody.tsx"); -afterEach(cleanup); +afterEach(() => { + cleanup(); + window.history.replaceState(null, "", "/"); +}); function renderChat(markdown, opened = []) { return render(React.createElement(MarkdownBody, { cwd: "/home/me/project", onOpenFile: (file) => opened.push(file) }, markdown)); @@ -79,3 +82,47 @@ test("without a file panel (a remote host's session) a path link renders as its assert.deepEqual(links.map((a) => a.getAttribute("href")), ["https://x.test"]); assert.match(container.textContent, /local:\/\/uploads\/a\.txt/); }); + +test("session references navigate in the app rather than opening a filesystem root", () => { + const opened = []; + const { container } = renderChat( + "[root](/?session=one&left=0#message) [query](?session=two&right=0) [absolute](https://omp.test/?session=three#latest)", + opened, + ); + const links = [...container.querySelectorAll("a")]; + const hrefs = ["/?session=one&left=0#message", "/?session=two&right=0", "/?session=three#latest"]; + assert.deepEqual(links.map((link) => link.getAttribute("href")), hrefs); + assert.ok(links.every((link) => !link.hasAttribute("target"))); + for (const [index, link] of links.entries()) { + assert.equal(fireEvent.click(link, { button: 0 }), false); + assert.equal(window.location.pathname + window.location.search + window.location.hash, hrefs[index]); + } + assert.deepEqual(opened, []); +}); + +test("session references leave modified, middle and new-target clicks to the browser", () => { + const opened = []; + const { container } = renderChat("[session](/?session=other)", opened); + const link = container.querySelector("a"); + assert.ok(link); + const initialUrl = window.location.href; + for (const modifier of ["ctrlKey", "metaKey", "shiftKey", "altKey"]) { + assert.equal(fireEvent.click(link, { button: 0, [modifier]: true }), true, modifier); + } + assert.equal(fireEvent(link, new MouseEvent("auxclick", { button: 1, bubbles: true, cancelable: true })), true); + link.target = "_blank"; + assert.equal(fireEvent.click(link, { button: 0 }), true); + assert.equal(window.location.href, initialUrl); + assert.deepEqual(opened, []); +}); + +test("foreign-origin session URLs keep their external link behavior", () => { + const opened = []; + const { container } = renderChat("[other server](https://else.test/?session=one)", opened); + const link = container.querySelector("a"); + assert.equal(link.getAttribute("href"), "https://else.test/?session=one"); + assert.equal(link.target, "_blank"); + assert.equal(link.rel, "noopener noreferrer"); + assert.equal(fireEvent.click(link, { button: 0 }), true); + assert.deepEqual(opened, []); +}); diff --git a/components/MarkdownBody.tsx b/components/MarkdownBody.tsx index d9c304534..52daa8b1e 100644 --- a/components/MarkdownBody.tsx +++ b/components/MarkdownBody.tsx @@ -5,6 +5,8 @@ import ReactMarkdown, { type Components, type UrlTransform } from "react-markdow import { remarkInlineCodeFileLinks, resolveLocalFileHref } from "@/lib/file-links"; import { getFileApiUrl } from "@/lib/file-paths"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; +import { useRouter } from "@/lib/navigation"; +import { sessionLinkHref } from "@/lib/session-links"; import { AgentLinkContext, agentAwareUrlTransform, agentLinkIds, remarkAgentLinks } from "../lib/agent-links"; import { GithubRepoContext, remarkGithubRefs } from "../lib/github-refs"; import { normalizeDisplayMath, useMarkdownPlugins, type MarkdownPlugins } from "../lib/markdown"; @@ -52,6 +54,7 @@ export function useMarkdownBodyRendering({ children, isStreaming, cwd, sourceSes [baseRemarkPlugins, githubRepo, onOpenFile, cwd], ); const openAgentLink = useContext(AgentLinkContext); + const router = useRouter(); // Rebuilt only when its captured props change, not on every render. const components = useMemo(() => { @@ -138,6 +141,18 @@ export function useMarkdownBodyRendering({ children, isStreaming, cwd, sourceSes const anchor = event.preventDefault()}>{textParts}; return imageParts.length > 0 ? <>{anchor}{imageParts} : anchor; } + const sessionHref = sessionLinkHref(href); + if (sessionHref) { + const handleClick = (event: MouseEvent) => { + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + const target = event.currentTarget.getAttribute("target"); + if (target && target !== "_self") return; + event.preventDefault(); + router.push(sessionHref); + }; + const anchor = {textParts}; + return imageParts.length > 0 ? <>{anchor}{imageParts} : anchor; + } const filePath = resolveLocalFileHref(href, cwd); if (filePath) { // Without a file panel (a remote host's session, a dialog) a path link has nowhere to go: show its text. @@ -173,7 +188,7 @@ export function useMarkdownBodyRendering({ children, isStreaming, cwd, sourceSes ); }, }; - }, [isStreaming, cwd, sourceSessionId, onOpenFile, suppressImages, openAgentLink, autoCharts, fileSource]); + }, [isStreaming, cwd, sourceSessionId, onOpenFile, suppressImages, openAgentLink, autoCharts, fileSource, router]); return { markdown: normalizedMarkdown, remarkPlugins, rehypePlugins, components, urlTransform }; } diff --git a/components/SessionSidebar-rows.draft.test.mjs b/components/SessionSidebar-rows.draft.test.mjs index 42c2da46d..145b81c5a 100644 --- a/components/SessionSidebar-rows.draft.test.mjs +++ b/components/SessionSidebar-rows.draft.test.mjs @@ -2,7 +2,7 @@ import "../tests/setup-dom.mjs"; import assert from "node:assert/strict"; import test from "node:test"; import React from "react"; -const { act, cleanup, render, screen, waitFor } = await import("@testing-library/react/pure.js"); +const { act, cleanup, fireEvent, render, screen, waitFor } = await import("@testing-library/react/pure.js"); const { default: userEvent } = await import("@testing-library/user-event"); const { ChatInput } = await import("./ChatInput.tsx"); // Same specifiers as the component's own imports, so both see one draft store. @@ -68,3 +68,49 @@ test("a mounted session row follows composer typing, attachment-only drafts and window.matchMedia = previousMatchMedia; } }); + +test("session rows expose shareable links without selecting on modified or middle clicks", () => { + let selections = 0; + try { + const { container } = render(React.createElement(SessionItem, { + session: session("host:session/a?b#c"), isSelected: true, + onClick() { selections += 1; }, relativeTimeNow: Date.now(), + })); + const link = screen.getByRole("link", { name: "host:session/a?b#c" }); + assert.equal(link.getAttribute("href"), "/?session=host%3Asession%2Fa%3Fb%23c"); + assert.equal(link.getAttribute("aria-current"), "true"); + const title = link.querySelector("span"); + for (const modifier of ["ctrlKey", "metaKey", "shiftKey", "altKey"]) { + assert.equal(fireEvent.click(title, { button: 0, [modifier]: true }), true, modifier); + assert.equal(selections, 0, "modified clicks must not bubble into row selection"); + } + assert.equal(fireEvent(title, new MouseEvent("auxclick", { button: 1, bubbles: true, cancelable: true })), true); + assert.equal(fireEvent.contextMenu(title), true, "native Copy link stays available"); + assert.equal(selections, 0); + assert.equal(fireEvent.click(title, { button: 0 }), false); + assert.equal(selections, 1, "the anchor and row must not both select"); + fireEvent.click(container.querySelector(".session-item-row"), { button: 0 }); + assert.equal(selections, 2, "row padding still selects"); + } finally { + cleanup(); + } +}); + +test("Delete on a session link opens confirmation and cancellation returns focus to the link", async () => { + let selections = 0; + try { + render(React.createElement(SessionItem, { + session: session("delete-link"), isSelected: false, + onClick() { selections += 1; }, relativeTimeNow: Date.now(), + })); + const link = screen.getByRole("link", { name: "delete-link" }); + link.focus(); + assert.equal(fireEvent.keyDown(link, { key: "Delete" }), false); + assert.ok(screen.getByRole("dialog")); + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + await waitFor(() => assert.equal(document.activeElement, link)); + assert.equal(selections, 0); + } finally { + cleanup(); + } +}); diff --git a/components/SessionSidebar-rows.tsx b/components/SessionSidebar-rows.tsx index 6b14c3ebd..55a27b9e3 100644 --- a/components/SessionSidebar-rows.tsx +++ b/components/SessionSidebar-rows.tsx @@ -11,6 +11,7 @@ import { transcriptToMarkdown } from "@/lib/transcript"; import { toast } from "./ui/toast"; import { SessionSearchMatches, type SearchMatchTarget } from "./SessionSearchMatches"; import { hasDraft, subscribeDrafts } from "@/lib/draft-store"; +import { sessionHref } from "@/lib/session-links"; import { MAX_PROJECT_SESSIONS, formatRelativeTime, @@ -741,7 +742,7 @@ const SessionItem = memo(function SessionItem({ const [actionMenuOpen, setActionMenuOpen] = useState(false); const [deleting, setDeleting] = useState(false); const inputRef = useRef(null); - const contentButtonRef = useRef(null); + const contentLinkRef = useRef(null); const menuButtonRef = useRef(null); const title = session.name || session.firstMessage.slice(0, 50) || session.id.slice(0, 12); // A session's composer draft is keyed by its id (ChatWindow's `draftKey`). @@ -827,7 +828,7 @@ const SessionItem = memo(function SessionItem({ const closeConfirmation = useCallback(() => { setConfirmDelete(false); setActionMenuOpen(false); - requestAnimationFrame(() => contentButtonRef.current?.focus()); + requestAnimationFrame(() => contentLinkRef.current?.focus()); }, []); return ( @@ -892,7 +893,22 @@ const SessionItem = memo(function SessionItem({ ) : ( <> {depth > 0 &&