From 7ed6a52cabd3559346b7be64a98efe50c62a9954 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:44:09 +0200 Subject: [PATCH 1/2] feat(chat): session tabs above the chat (fixes #353) --- components/AppShell.tsx | 54 +++++++++++ components/SessionTabs.test.mjs | 71 ++++++++++++++ components/SessionTabs.tsx | 161 ++++++++++++++++++++++++++++++++ lib/i18n/locales/en.json | 5 + lib/i18n/locales/ja.json | 5 + lib/i18n/locales/zh-CN.json | 5 + lib/i18n/locales/zh-TW.json | 5 + 7 files changed, 306 insertions(+) create mode 100644 components/SessionTabs.test.mjs create mode 100644 components/SessionTabs.tsx diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 85795fb82..9398e09d2 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -18,6 +18,7 @@ import { notificationHistory, useUnreadNotificationCount } from "@/lib/notificat 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 EXPAND_THINKING_STORAGE_KEY = "omp-web:expand-thinking"; 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 @@ export function AppShell({ appName }: { appName: string }) { const isMobile = useIsMobile(); const isCompactOverlay = useIsCompactOverlay(); const [selectedSession, setSelectedSession] = useState(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(() => 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(null); // Host of newSessionCwd; undefined is this machine. Every host-aware state @@ -1343,6 +1379,15 @@ export function AppShell({ appName }: { appName: string }) { } }, [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 @@ export function AppShell({ appName }: { appName: string }) { // 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)); setRefreshKey((k) => k + 1); if (selectedSession?.id === sessionId) { const cwd = selectedSession.cwd; @@ -2645,6 +2691,14 @@ export function AppShell({ appName }: { appName: string }) { {/* Chat content */}
+ {openSessionTabs.length > 0 && ( + + )} {showChat ? ( { + 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, ""); +}); diff --git a/components/SessionTabs.tsx b/components/SessionTabs.tsx new file mode 100644 index 000000000..897592cf0 --- /dev/null +++ b/components/SessionTabs.tsx @@ -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([]); + const [runningIds, setRunningIds] = useState>(new Set()); + const [awaitingIds, setAwaitingIds] = useState>(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 ( +
+ {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 ( +
+ + +
+ ); + })} +
+ ); +} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index b7bda9c71..50a0d8d94 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1707,6 +1707,11 @@ "settingsConfig.contextCompaction": "Context Compaction", "settingsConfig.contextCompactionDesc": "OMP automatically compacts oversized context to prevent hitting context limits.", "settingsConfig.automaticCompaction": "Automatic Compaction", + "sessionTabs.tabsLabel": "Open sessions", + "sessionTabs.untitledSession": "Untitled session", + "sessionTabs.closeTab": "Close {title} tab", + "sessionTabs.running": "Running", + "sessionTabs.awaitingInput": "Waiting for input", "settingsConfig.automaticCompactionDesc": "Compact context before model context limit is hit.", "settingsConfig.continueAfterCompaction": "Continue After Compaction", "settingsConfig.continueAfterCompactionDesc": "Resume task execution after compaction completes.", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index f62f7bcb9..05792acca 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1667,6 +1667,11 @@ "settingsConfig.contextCompaction": "Context Compaction", "settingsConfig.contextCompactionDesc": "OMP automatically compacts oversized context to prevent hitting context limits.", "settingsConfig.automaticCompaction": "Automatic Compaction", + "sessionTabs.tabsLabel": "開いているセッション", + "sessionTabs.untitledSession": "無題のセッション", + "sessionTabs.closeTab": "{title} タブを閉じる", + "sessionTabs.running": "実行中", + "sessionTabs.awaitingInput": "入力待ち", "settingsConfig.automaticCompactionDesc": "Compact context before model context limit is hit.", "settingsConfig.continueAfterCompaction": "Continue After Compaction", "settingsConfig.continueAfterCompactionDesc": "Resume task execution after compaction completes.", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index ac9dc1fbe..4aa09e460 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1667,6 +1667,11 @@ "settingsConfig.contextCompaction": "上下文压缩", "settingsConfig.contextCompactionDesc": "OMP 会自动压缩超限的上下文以避免达到模型上下文上限。", "settingsConfig.automaticCompaction": "自动压缩", + "sessionTabs.tabsLabel": "打开的会话", + "sessionTabs.untitledSession": "未命名会话", + "sessionTabs.closeTab": "关闭 {title} 标签页", + "sessionTabs.running": "运行中", + "sessionTabs.awaitingInput": "等待输入", "settingsConfig.automaticCompactionDesc": "在达到模型上下文上限前自动压缩上下文。", "settingsConfig.continueAfterCompaction": "压缩后继续执行", "settingsConfig.continueAfterCompactionDesc": "上下文压缩完成后自动恢复任务执行。", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 530707dd6..419bdf161 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -1707,6 +1707,11 @@ "settingsConfig.contextCompaction": "情境壓縮", "settingsConfig.contextCompactionDesc": "OMP 會自動壓縮過大的情境,以避免超出情境上限。", "settingsConfig.automaticCompaction": "自動壓縮", + "sessionTabs.tabsLabel": "開啟的對話", + "sessionTabs.untitledSession": "未命名對話", + "sessionTabs.closeTab": "關閉 {title} 標籤頁", + "sessionTabs.running": "執行中", + "sessionTabs.awaitingInput": "等待輸入", "settingsConfig.automaticCompactionDesc": "在達到模型情境上限之前自動壓縮情境。", "settingsConfig.continueAfterCompaction": "壓縮後繼續執行", "settingsConfig.continueAfterCompactionDesc": "情境壓縮完成後繼續執行任務。", From 23b909256fe9fd1a6c73074cb48da692cc4c2828 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:17:18 +0200 Subject: [PATCH 2/2] Scope sidebar-row clicks to #workspace-sidebar in foreign-source AppShell tests (fixes Windows CI duplicate-title failure on #555) --- hooks/useAgentSession.rpc.test.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index efce900b5..f07c09c91 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6816,7 +6816,7 @@ test("equal-path file tabs retain their originating session when the selected ow await sleep(60); }); await until(() => view.queryByText("FIRST OWNER CONTENT"), "the first owner file opens"); - await act(async () => { fireEvent.click(view.getByText("Worker two conversation")); await sleep(60); }); + await act(async () => { fireEvent.click(within(view.container.querySelector("#workspace-sidebar")).getByText("Worker two conversation")); await sleep(60); }); await act(async () => { stream.emit({ type: "host_tool_call", id: "second-open", sessionId: "worker-two", hostId: "h2", cwd: "/shared", toolName: "open_file", arguments: { path: "/shared/report.txt" } }); await sleep(60); @@ -6847,7 +6847,7 @@ test("a retained foreign-source tab cannot mention its path into the selected wo await sleep(60); }); await until(() => view.queryByText("FIRST OWNER CONTENT"), "the first owner's file opens"); - await act(async () => { fireEvent.click(view.getByText("Worker two conversation")); await sleep(60); }); + await act(async () => { fireEvent.click(within(view.container.querySelector("#workspace-sidebar")).getByText("Worker two conversation")); await sleep(60); }); await act(async () => { fireEvent.change(view.getByRole("textbox"), { target: { value: "Worker two draft" } }); stream.emit({ type: "host_tool_call", id: "mention-second-open", sessionId: "worker-two", hostId: "h2", cwd: "/shared", toolName: "open_file", arguments: { path: "/shared/report.txt" } }); @@ -6862,7 +6862,7 @@ test("a retained foreign-source tab cannot mention its path into the selected wo if (foreignMention) await act(async () => { fireEvent.click(foreignMention); }); assert.equal(view.getByRole("textbox").value, "Worker two draft", "a source-relative path must not be inserted into another worker's composer"); assert.equal(foreignMention === null || foreignMention.disabled, true, "the foreign-source action is unavailable"); - await act(async () => { fireEvent.click(view.getByText("Worker one conversation")); await sleep(60); }); + await act(async () => { fireEvent.click(within(view.container.querySelector("#workspace-sidebar")).getByText("Worker one conversation")); await sleep(60); }); const sourceMention = view.getByRole("button", { name: translate("appShell.mentionFileInChat") }); assert.equal(sourceMention.disabled, false, "returning to the source session restores the action"); await act(async () => {