Repository navigation
feat(chat): session tabs above the chat (fixes #353) #555
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,6 +18,7 @@ | |
| import { ConfirmDialog } from "./ui/field"; | ||
| import { ThemedSelect } from "./ui/primitives"; | ||
| import { ChatWindow } from "./ChatWindow"; | ||
| import { SessionTabs, type SessionTab } from "./SessionTabs"; | ||
| import { type Tab } from "./TabBar"; | ||
| import { type FileExplorerHandle } from "./FileExplorer"; | ||
| import type { RightPanelView } from "./RightPanel"; | ||
|
|
@@ -120,6 +121,22 @@ | |
| const PROVIDER_USAGE_VISIBLE_STORAGE_KEY = "omp-web:provider-usage-visible"; | ||
| const NATIVE_SELECT_ALL_STORAGE_KEY = "omp-web:scope-native-select-all"; | ||
| const OPEN_URL_AUTOMATICALLY_STORAGE_KEY = "omp-web:open-url-automatically"; | ||
| const SESSION_TABS_STORAGE_KEY = "omp-web:session-tabs"; | ||
|
|
||
| /** Tabs the user left open, restored across reloads; validated, never trusted blindly. */ | ||
| function loadSessionTabs(): SessionTab[] { | ||
| try { | ||
| const raw = window.localStorage.getItem(SESSION_TABS_STORAGE_KEY); | ||
| if (!raw) return []; | ||
| const parsed: unknown = JSON.parse(raw); | ||
| if (!Array.isArray(parsed)) return []; | ||
| return parsed.filter((entry): entry is SessionTab => typeof entry === "object" && entry !== null | ||
| && typeof (entry as SessionTab).id === "string" && (entry as SessionTab).id.length > 0 | ||
| && ((entry as SessionTab).hostId === undefined || typeof (entry as SessionTab).hostId === "string")); | ||
| } catch { | ||
| return []; | ||
| } | ||
| } | ||
|
|
||
|
|
||
| type AutoNameStatus = | ||
|
|
@@ -137,6 +154,25 @@ | |
| const isMobile = useIsMobile(); | ||
| const isCompactOverlay = useIsCompactOverlay(); | ||
| const [selectedSession, setSelectedSession] = useState<SessionInfo | null>(null); | ||
| // Sessions opened in tabs above the chat: every visited session joins, in | ||
| // visit order; closing a tab only forgets it here, never deletes it. | ||
| const [openSessionTabs, setOpenSessionTabs] = useState<SessionTab[]>(() => loadSessionTabs()); | ||
| useEffect(() => { | ||
| try { | ||
| window.localStorage.setItem(SESSION_TABS_STORAGE_KEY, JSON.stringify(openSessionTabs)); | ||
| } catch { | ||
| // Tabs still work for this page load without persistence. | ||
| } | ||
| }, [openSessionTabs]); | ||
| useEffect(() => { | ||
| const id = selectedSession?.id; | ||
| if (!id) return; | ||
| const hostId = selectedSession?.hostId; | ||
| setOpenSessionTabs((prev) => { | ||
| if (prev.some((tab) => tab.id === id && (tab.hostId ?? "local") === (hostId ?? "local"))) return prev; | ||
| return [...prev, { id, ...(hostId ? { hostId } : {}) }]; | ||
| }); | ||
| }, [selectedSession?.id, selectedSession?.hostId]); | ||
| // The transient identity belongs to one intentional new chat, not one request attempt. | ||
| const [newSessionCwd, setNewSessionCwd] = useState<string | null>(null); | ||
| // Host of newSessionCwd; undefined is this machine. Every host-aware state | ||
|
|
@@ -390,7 +426,7 @@ | |
| if (container && active instanceof HTMLElement && container.contains(active)) { | ||
| active.blur(); | ||
| } | ||
| }, [sidebarOpen, mobileSidebarReady]); | ||
|
Check warning on line 429 in components/AppShell.tsx
|
||
| const refreshAppUpdate = useCallback(async (force = false, autoOpen = false): Promise<AppUpdateInfo | null> => { | ||
| const data = await fetchAppUpdateJson<AppUpdateInfo>( | ||
| force ? "/api/app-update?force=1" : "/api/app-update", | ||
|
|
@@ -931,7 +967,7 @@ | |
| sidebarResizeHandlersRef.current = { onMove, onUp }; | ||
| window.addEventListener("mousemove", onMove); | ||
| window.addEventListener("mouseup", onUp); | ||
| }, [isMobile, sidebarWidth]); | ||
|
Check warning on line 970 in components/AppShell.tsx
|
||
|
|
||
| // If the app unmounts mid-drag, remove the window listeners and restore the | ||
| // body cursor; otherwise the handlers leak and body stays cursor:col-resize. | ||
|
|
@@ -948,7 +984,7 @@ | |
| const resetRightPanelWidth = useCallback(() => { | ||
| rightPanelRef.current?.style.removeProperty("--right-panel-width"); | ||
| setRightPanelWidth(null); | ||
| }, []); | ||
|
Check warning on line 987 in components/AppShell.tsx
|
||
|
|
||
| const changeRightPanelWidth = useCallback((delta: number) => { | ||
| setRightPanelWidth((prev) => { | ||
|
|
@@ -959,7 +995,7 @@ | |
| rightPanelRef.current?.style.setProperty("--right-panel-width", `${next}px`); | ||
| return next; | ||
| }); | ||
| }, []); | ||
|
Check warning on line 998 in components/AppShell.tsx
|
||
|
|
||
| const handleRightPanelResizeKey = useCallback((e: React.KeyboardEvent) => { | ||
| // The handle sits on the panel's left edge: left widens, right narrows. | ||
|
|
@@ -1028,7 +1064,7 @@ | |
| rightResizeHandlersRef.current = { onMove, onUp, cancelFrame }; | ||
| window.addEventListener("mousemove", onMove); | ||
| window.addEventListener("mouseup", onUp); | ||
| }, [isMobile]); | ||
|
Check warning on line 1067 in components/AppShell.tsx
|
||
|
|
||
| // If the app unmounts mid-drag, remove the window listeners and restore the | ||
| // body cursor; otherwise the handlers leak and body stays cursor:col-resize. | ||
|
|
@@ -1343,6 +1379,15 @@ | |
| } | ||
| }, [router, isMobile, selectedSession]); | ||
|
|
||
| // Close one session tab: forget it here only, never delete the session. | ||
| // Closing the selected tab shows its neighbour (picked by SessionTabs), or | ||
| // the empty state when it was the last tab. | ||
| const handleCloseSessionTab = useCallback((tab: SessionTab, next: SessionInfo | null) => { | ||
| setOpenSessionTabs((prev) => prev.filter((entry) => !(entry.id === tab.id && (entry.hostId ?? "local") === (tab.hostId ?? "local")))); | ||
| if (next) handleSelectSession(next); | ||
| else if (selectedSession?.id === tab.id) setSelectedSession(null); | ||
| }, [handleSelectSession, selectedSession?.id]); | ||
|
|
||
| const handleNewSession = useCallback((creationId: string, cwd: string | null, hostId?: string, project?: ManagedProject, initialization?: string) => { | ||
| setSettingsTab(null); | ||
| setSelectedSession(null); | ||
|
|
@@ -1610,6 +1655,7 @@ | |
| // The composer for this session can never be reopened, so its draft would | ||
| // otherwise keep the exit guard armed for unreachable content. | ||
| clearDraft(sessionId); | ||
| setOpenSessionTabs((prev) => prev.filter((tab) => tab.id !== sessionId)); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove only the deleted host-qualified tab. If local and remote sessions share an ID, deleting one removes both tabs here. The other session still exists, but its open tab is lost. Carry the deleted host through the deletion callback and match both host and ID, as the close-tab filter already does.
|
||
| setRefreshKey((k) => k + 1); | ||
| if (selectedSession?.id === sessionId) { | ||
| const cwd = selectedSession.cwd; | ||
|
|
@@ -2645,6 +2691,14 @@ | |
|
|
||
| {/* Chat content */} | ||
| <div style={{ flex: 1, overflow: "hidden", position: "relative" }}> | ||
| {openSessionTabs.length > 0 && ( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reserve the strip's height above The session-tab strip is an in-flow sibling rendered before Give the chat region the remaining height. Use a flex column on the wrapper, and let
|
||
| <SessionTabs | ||
| tabs={openSessionTabs} | ||
| selectedId={selectedSession?.id ?? null} | ||
| onSelect={handleSelectSession} | ||
| onClose={handleCloseSessionTab} | ||
| /> | ||
| )} | ||
| {showChat ? ( | ||
| <ChatWindow | ||
| key={sessionKey} | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import assert from "node:assert/strict"; | ||
| import "../tests/setup-dom.mjs"; | ||
| import test from "node:test"; | ||
| import React from "react"; | ||
|
|
||
| const { act, cleanup, fireEvent, render } = await import("@testing-library/react/pure.js"); | ||
| const { SessionTabs } = await import("./SessionTabs.tsx"); | ||
|
|
||
| const sessions = [ | ||
| { id: "s1", path: "/a", cwd: "/a", name: "First session", created: "2026-01-01", modified: "2026-01-01", messageCount: 3, firstMessage: "first" }, | ||
| { id: "s2", path: "/b", cwd: "/b", name: "", created: "2026-01-01", modified: "2026-01-01", messageCount: 1, firstMessage: "second prompt" }, | ||
| ]; | ||
|
|
||
| async function renderTabs(t, props = {}) { | ||
| const originalFetch = globalThis.fetch; | ||
| globalThis.fetch = async (url) => { | ||
| if (String(url) === "/api/sessions") { | ||
| return Response.json({ | ||
| sessions, | ||
| runningSessionIds: ["s2"], | ||
| runningSessions: [{ id: "s2", cwd: "/b", awaitingInput: true }], | ||
| }); | ||
| } | ||
| return Response.json({}); | ||
| }; | ||
| const selected = []; | ||
| const closed = []; | ||
| const view = render(React.createElement(SessionTabs, { | ||
| tabs: [{ id: "s1" }, { id: "s2" }], | ||
| selectedId: "s1", | ||
| onSelect: (session) => selected.push(session.id), | ||
| onClose: (tab, next) => closed.push({ tab: tab.id, next: next?.id ?? null }), | ||
| ...props, | ||
| })); | ||
| t.after(() => { | ||
| cleanup(); | ||
| globalThis.fetch = originalFetch; | ||
| }); | ||
| await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); | ||
| return { view, selected, closed }; | ||
| } | ||
|
|
||
| test("session tabs show titles, mark the running one, and switch on click", async (t) => { | ||
| const { view, selected } = await renderTabs(t); | ||
| const tabs = view.getAllByRole("tab"); | ||
| assert.deepEqual(tabs.map((tab) => tab.textContent), ["First session", "second prompt"]); | ||
| assert.equal(tabs[0].getAttribute("aria-selected"), "true"); | ||
| assert.equal(tabs[1].getAttribute("aria-selected"), "false"); | ||
| // s2 is running and waiting for input: its tab carries the indicator dot. | ||
| assert.ok(tabs[1].querySelector("span[aria-hidden]"), "the running tab must show its indicator"); | ||
| assert.match(tabs[1].getAttribute("title"), /Waiting for input|sessionTabs\.awaitingInput/); | ||
| fireEvent.click(tabs[1]); | ||
| assert.deepEqual(selected, ["s2"]); | ||
| }); | ||
|
|
||
| test("closing the selected tab offers its neighbour", async (t) => { | ||
| const { view, closed } = await renderTabs(t); | ||
| const closeButtons = [...view.container.querySelectorAll("button")].filter((button) => (button.getAttribute("aria-label") ?? "").match(/Close|sessionTabs\.closeTab/)); | ||
| assert.equal(closeButtons.length, 2, "each tab needs a close button"); | ||
| fireEvent.click(closeButtons[0]); | ||
| assert.deepEqual(closed, [{ tab: "s1", next: "s2" }]); | ||
| }); | ||
|
|
||
| test("no tabs renders nothing", async (t) => { | ||
| const originalFetch = globalThis.fetch; | ||
| globalThis.fetch = async () => Response.json({ sessions: [] }); | ||
| t.after(() => { cleanup(); globalThis.fetch = originalFetch; }); | ||
| const view = render(React.createElement(SessionTabs, { tabs: [], selectedId: null, onSelect: () => {}, onClose: () => {} })); | ||
| await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); | ||
| assert.equal(view.container.innerHTML, ""); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| "use client"; | ||
|
|
||
| import { useEffect, useState } from "react"; | ||
| import { X } from "lucide-react"; | ||
| import { useI18n } from "@/lib/i18n"; | ||
| import type { SessionInfo } from "@/lib/types"; | ||
|
|
||
| /** One open session tab: the session id plus its host (sessions on different hosts can share ids). */ | ||
| export interface SessionTab { | ||
| id: string; | ||
| hostId?: string; | ||
| } | ||
|
|
||
| const REFRESH_MS = 15_000; | ||
|
|
||
| function tabKey(tab: SessionTab): string { | ||
| return `${tab.hostId ?? "local"}:${tab.id}`; | ||
| } | ||
|
|
||
| function sessionTitle(session: SessionInfo, untitled: string): string { | ||
| const name = session.name?.trim(); | ||
| if (name) return name; | ||
| const first = session.firstMessage?.trim(); | ||
| if (first && first !== "(no messages)") return first; | ||
| return untitled; | ||
| } | ||
|
|
||
| /** | ||
| * Tab strip above the chat for sessions opened this browser: click a tab to | ||
| * switch to it, × to close the tab (the session itself is untouched — it | ||
| * stays in the sidebar). Titles, running state and input-waiting state come | ||
| * from the same `/api/sessions` list the sidebar reads. | ||
| * | ||
| * Minimal scope: switching remounts the chat (like picking a session in the | ||
| * sidebar), so per-tab scroll position is not preserved yet. | ||
| */ | ||
| export function SessionTabs({ tabs, selectedId, onSelect, onClose }: { | ||
| tabs: SessionTab[]; | ||
| selectedId: string | null; | ||
| onSelect: (session: SessionInfo) => void; | ||
| /** Close a tab; `next` is the neighbour to show when the selected tab closes, or null when none remains. */ | ||
| onClose: (tab: SessionTab, next: SessionInfo | null) => void; | ||
| }) { | ||
| const { t } = useI18n(); | ||
| const [sessions, setSessions] = useState<SessionInfo[]>([]); | ||
| const [runningIds, setRunningIds] = useState<Set<string>>(new Set()); | ||
| const [awaitingIds, setAwaitingIds] = useState<Set<string>>(new Set()); | ||
|
|
||
| useEffect(() => { | ||
| let cancelled = false; | ||
| const load = async () => { | ||
| try { | ||
| const res = await fetch("/api/sessions"); | ||
| if (!res.ok || cancelled) return; | ||
| const data = await res.json() as { sessions?: SessionInfo[]; runningSessionIds?: string[]; runningSessions?: Array<{ id: string; awaitingInput?: boolean }> }; | ||
| if (cancelled) return; | ||
| setSessions(Array.isArray(data.sessions) ? data.sessions : []); | ||
| setRunningIds(new Set(data.runningSessionIds ?? [])); | ||
| setAwaitingIds(new Set((data.runningSessions ?? []).filter((entry) => entry.awaitingInput).map((entry) => entry.id))); | ||
| } catch { | ||
| // Keep the last good list; the sidebar owns the load error state. | ||
| } | ||
| }; | ||
| void load(); | ||
| const timer = setInterval(() => void load(), REFRESH_MS); | ||
| return () => { cancelled = true; clearInterval(timer); }; | ||
| }, []); | ||
|
|
||
| if (tabs.length === 0) return null; | ||
| const byId = new Map(sessions.map((session) => [session.id, session])); | ||
| // A tab whose session the list no longer knows (deleted elsewhere) drops | ||
| // off, except the selected one, which keeps its place until navigation moves on. | ||
| const visible = tabs.filter((tab) => byId.has(tab.id) || tab.id === selectedId); | ||
| if (visible.length === 0) return null; | ||
|
|
||
| const closeTab = (tab: SessionTab) => { | ||
| let next: SessionInfo | null = null; | ||
| if (tab.id === selectedId) { | ||
| const idx = visible.findIndex((entry) => tabKey(entry) === tabKey(tab)); | ||
| const neighbour = visible[idx - 1] ?? visible[idx + 1] ?? null; | ||
| next = neighbour ? byId.get(neighbour.id) ?? null : null; | ||
| } | ||
| onClose(tab, next); | ||
| }; | ||
|
|
||
| return ( | ||
| <div | ||
| role="tablist" | ||
| aria-label={t("sessionTabs.tabsLabel")} | ||
| style={{ | ||
| display: "flex", alignItems: "stretch", gap: 4, | ||
| padding: "6px 12px 0", overflowX: "auto", flexShrink: 0, | ||
| }} | ||
| > | ||
| {visible.map((tab) => { | ||
| const session = byId.get(tab.id); | ||
| const title = session ? sessionTitle(session, t("sessionTabs.untitledSession")) : tab.id; | ||
| const selected = tab.id === selectedId; | ||
| const running = runningIds.has(tab.id); | ||
| const awaitingInput = awaitingIds.has(tab.id); | ||
| return ( | ||
| <div | ||
| key={tabKey(tab)} | ||
| style={{ | ||
| display: "flex", alignItems: "center", flexShrink: 0, | ||
| maxWidth: 220, minWidth: 0, | ||
| background: selected ? "var(--bg-panel)" : "transparent", | ||
| border: "1px solid var(--border)", | ||
| borderBottom: selected ? "1px solid var(--bg-panel)" : "1px solid var(--border)", | ||
| borderRadius: "8px 8px 0 0", | ||
| }} | ||
| > | ||
| <button | ||
| type="button" | ||
| role="tab" | ||
| aria-selected={selected} | ||
| disabled={!session} | ||
| onClick={() => { if (session) onSelect(session); }} | ||
| title={awaitingInput ? t("sessionTabs.awaitingInput") : running ? t("sessionTabs.running") : title} | ||
| style={{ | ||
| display: "flex", alignItems: "center", gap: 6, | ||
| minWidth: 0, flex: 1, | ||
| height: 30, padding: "0 4px 0 10px", | ||
| background: "none", border: "none", | ||
| color: selected ? "var(--text)" : "var(--text-muted)", | ||
| cursor: session ? "pointer" : "default", | ||
| fontSize: 12, fontWeight: selected ? 600 : 400, | ||
| textAlign: "left", | ||
| }} | ||
| > | ||
| {(running || awaitingInput) && ( | ||
| <span | ||
| aria-hidden | ||
| className={running && !awaitingInput ? "live-status-dot live-pulse inline-block h-2 w-2 shrink-0 rounded-full bg-accent" : undefined} | ||
| style={awaitingInput | ||
| ? { flexShrink: 0, width: 8, height: 8, borderRadius: "50%", background: "var(--status-warning)" } | ||
| : { flexShrink: 0 }} | ||
| /> | ||
| )} | ||
| <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{title}</span> | ||
| </button> | ||
| <button | ||
| type="button" | ||
| onClick={(e) => { e.stopPropagation(); closeTab(tab); }} | ||
| title={t("sessionTabs.closeTab", { title })} | ||
| aria-label={t("sessionTabs.closeTab", { title })} | ||
| style={{ | ||
| display: "flex", alignItems: "center", justifyContent: "center", | ||
| width: 22, height: 22, marginRight: 4, padding: 0, flexShrink: 0, | ||
| background: "none", border: "none", borderRadius: 5, | ||
| color: "var(--text-dim)", cursor: "pointer", | ||
| }} | ||
| > | ||
| <X size={12} strokeWidth={2} aria-hidden="true" /> | ||
| </button> | ||
| </div> | ||
| ); | ||
| })} | ||
| </div> | ||
| ); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clear the session URL when closing the last active tab.
Selecting a session writes its URL through
router.replace. This branch clears onlyselectedSession, so the URL still identifies the closed session. Reloading can restore that session and add its tab again.When no neighbour remains, also replace the session URL with the empty-view URL. Keep the existing neighbour-selection path unchanged.