feat(header): session tabs — a horizontal working set of open sessions

Web/desktop header replaces the single session title with a strip of
soft pill tabs, one per session the user has opened (sidebar, palette
or deep link — opening anywhere adds a tab once). The active tab is the
familiar title block — rename, meta row and the full session menu —
inside a gently selected pill; a brand-new draft shows as a transient
pill until its session exists. Inactive tabs show the title with a
hover-revealed "..." menu (close tab, close other tabs, copy id) that
nudges the text like sidebar rows, and close by middle-click too.

Tabs drag to reorder, scroll behind the right-side header buttons with
soft fade edges, respect the reserved window-controls inset, and
persist across reloads. Closing the active tab activates its neighbour
(or opens a new draft when it was the last). Tab ids whose session is
not in the loaded list stay stored but hidden, so a partial session
list never destroys the working set. VS Code keeps the plain title;
mobile is untouched.
This commit is contained in:
Bohdan Triapitsyn
2026-08-24 17:07:09 +03:00
parent 7bd27d44d6
commit a3813f57e9
15 changed files with 645 additions and 1 deletions
+151 -1
View File
@@ -49,6 +49,7 @@ import type { SessionContextUsage } from '@/stores/types/sessionTypes';
import { DesktopHostSwitcherDialog } from '@/components/desktop/DesktopHostSwitcher';
import { OpenInAppButton } from '@/components/desktop/OpenInAppButton';
import { SessionSwitcherDropdown } from '@/components/session/SessionSwitcherDropdown';
import { SessionTabsStrip } from './SessionTabsStrip';
import { canUseElectronDesktopIPC, invokeDesktop, isDesktopLocalOriginActive, isDesktopShell, isVSCodeRuntime, startDesktopWindowDrag, type UpdateInfo } from '@/lib/desktop';
import { desktopHostsGet, redactSensitiveUrl } from '@/lib/desktopHosts';
import {
@@ -1572,7 +1573,7 @@ export const Header: React.FC = () => {
</span>
) : null}
</div>
) : (
) : isVSCode ? (
<div className="app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left">
{!isSidebarOpen ? (
<SessionSwitcherDropdown align="start">
@@ -1585,6 +1586,154 @@ export const Header: React.FC = () => {
</button>
</SessionSwitcherDropdown>
) : null}
<div className="flex min-w-0 flex-col justify-center px-1">
{isRenamingHeaderSession ? (
<form
ref={headerRenameFormRef}
className="flex w-full min-w-0 items-center gap-2 leading-tight"
onPointerDown={(event) => event.stopPropagation()}
onSubmit={(event) => {
event.preventDefault();
void saveHeaderSessionRename();
}}
>
<input
value={headerSessionTitleDraft}
onChange={(event) => setHeaderSessionTitleDraft(event.target.value)}
autoFocus
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === 'Escape') {
setIsRenamingHeaderSession(false);
}
}}
placeholder={t('sessions.sidebar.session.menu.rename')}
className="min-w-0 flex-1 bg-transparent typography-ui-label text-[14px] font-normal leading-tight outline-none placeholder:text-muted-foreground"
/>
<button
type="submit"
aria-label={t('sessions.sidebar.session.rename.save')}
title={t('sessions.sidebar.session.rename.save')}
className="shrink-0 text-muted-foreground hover:text-foreground"
>
<Icon name="check" className="size-4" />
</button>
<button
type="button"
onClick={() => setIsRenamingHeaderSession(false)}
aria-label={t('sessions.sidebar.session.rename.cancel')}
title={t('sessions.sidebar.session.rename.cancel')}
className="shrink-0 text-muted-foreground hover:text-foreground"
>
<Icon name="close" className="size-4" />
</button>
</form>
) : (
<span className="truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full">
{isNewSessionDraftOpen ? t('sessions.switcher.draftTitle') : currentSessionTitle}
</span>
)}
{showHeaderMetaRow ? (
<span className="flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75">
{activeProjectLabel ? <span className="truncate">{activeProjectLabel}</span> : null}
{currentBranchLabel ? (
<span className="inline-flex min-w-0 items-center gap-0.5">
<Icon name="git-branch" className="h-3 w-3 flex-shrink-0 text-muted-foreground/70" />
<span className="truncate">{currentBranchLabel}</span>
</span>
) : null}
{!isNewSessionDraftOpen && worktreeBadgeKind ? (
<span className={cn(
"inline-flex min-w-0 items-center gap-0.5",
worktreeBadgeKind === 'attention' || worktreeBadgeKind === 'invalid' || worktreeBadgeKind === 'missing' ? 'text-status-warning' : 'text-muted-foreground/60'
)}>
<Icon name="alert" className="h-3 w-3 flex-shrink-0" />
<span className="truncate">{worktreeBadge}</span>
</span>
) : null}
</span>
) : null}
</div>
<div className={cn(
'flex h-[18px] shrink-0 items-center justify-center',
// Top-aligned only when the title has a metadata line under it;
// alone, the title is centred and the button must follow.
showHeaderMetaRow ? 'self-start' : 'self-center',
)}>
{currentSessionId && !isNewSessionDraftOpen && !isRenamingHeaderSession ? (
<DropdownMenu
open={isHeaderSessionMenuOpen}
onOpenChange={setIsHeaderSessionMenuOpen}
onOpenChangeComplete={(open) => {
if (!open && pendingHeaderRenameRef.current) {
pendingHeaderRenameRef.current = false;
beginHeaderSessionRename();
}
}}
>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="xs" className="h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground" aria-label={t('header.sessionActions.openAria')}>
<Icon name="more" className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-[190px]">
<DropdownMenuItem onClick={() => { pendingHeaderRenameRef.current = true; }}><Icon name="pencil-ai" className="mr-2 size-4" />{t('sessions.sidebar.session.menu.rename')}</DropdownMenuItem>
<DropdownMenuItem onClick={copyCurrentSessionId}><Icon name="file-copy" className="mr-2 size-4" />{t('sessions.sidebar.session.menu.copyId')}</DropdownMenuItem>
<DropdownMenuSeparator />
{currentSession?.shareUrl ? (
<>
<DropdownMenuItem onClick={copyCurrentSessionShareUrl}><Icon name="file-copy" className="mr-2 size-4" />{t('sessions.sidebar.session.menu.copyLink')}</DropdownMenuItem>
<DropdownMenuItem onClick={() => void unshareCurrentSession()}><Icon name="link-unlink-m" className="mr-2 size-4" />{t('sessions.sidebar.session.menu.unshare')}</DropdownMenuItem>
</>
) : (
<DropdownMenuItem onClick={() => void shareCurrentSession()}><Icon name="share-2" className="mr-2 size-4" />{t('sessions.sidebar.session.menu.share')}</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => void exportCurrentSession()}><Icon name="download" className="mr-2 size-4" />{t('sessions.sidebar.session.menu.exportMarkdown')}</DropdownMenuItem>
{!isVSCode && !isChatContext && currentSession && !currentSession.parentId ? (
<Tooltip>
<TooltipTrigger asChild>
<span className="block">
<DropdownMenuItem
disabled={!sessionDirectory || isCurrentSessionActive || isCurrentSessionMovingToWorktree}
onClick={moveCurrentSessionToWorktree}
className="w-full"
>
<Icon name="folder-shared" className="mr-2 size-4" />
{t('sessions.sidebar.session.menu.moveToWorktree')}
</DropdownMenuItem>
</span>
</TooltipTrigger>
<TooltipContent side="right" className="max-w-72">
{isCurrentSessionMovingToWorktree
? t('sessions.sidebar.session.moveToWorktree.tooltipMoving')
: isCurrentSessionActive
? t('sessions.sidebar.session.moveToWorktree.tooltipBusy')
: t('sessions.sidebar.session.moveToWorktree.tooltip')}
</TooltipContent>
</Tooltip>
) : null}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setPendingHeaderRetentionAction('archive')}><Icon name="inbox-archive" className="mr-2 size-4" />{t('sessions.sidebar.bulkActions.archive')}</DropdownMenuItem>
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => setPendingHeaderRetentionAction('delete')}><Icon name="delete-bin" className="mr-2 size-4" />{t('sessions.sidebar.bulkActions.delete')}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
</div>
) : (
<div className="app-region-no-drag flex h-full min-w-0 flex-1 items-center gap-0.5 text-left">
{!isSidebarOpen ? (
<SessionSwitcherDropdown align="start">
<button
type="button"
className={desktopHeaderIconButtonClass}
aria-label={t('sessions.switcher.openAria')}
>
<Icon name="history" className="h-[18px] w-[18px]" />
</button>
</SessionSwitcherDropdown>
) : null}
<SessionTabsStrip>
<div className="flex min-w-0 flex-col justify-center px-1">
{isRenamingHeaderSession ? (
<form
@@ -1717,6 +1866,7 @@ export const Header: React.FC = () => {
</DropdownMenu>
) : null}
</div>
</SessionTabsStrip>
</div>
)}
@@ -0,0 +1,326 @@
import React from 'react';
import {
DndContext,
MouseSensor,
TouchSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
type Modifier,
} from '@dnd-kit/core';
import {
SortableContext,
horizontalListSortingStrategy,
useSortable,
} from '@dnd-kit/sortable';
import { CSS as DndCSS } from '@dnd-kit/utilities';
import type { Session } from '@opencode-ai/sdk/v2';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Icon } from '@/components/icon/Icon';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import { copyTextToClipboard } from '@/lib/clipboard';
import { useSessionTabsStore } from '@/stores/useSessionTabsStore';
import { useGlobalSessionsStore, resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore';
import { useSessionUIStore } from '@/sync/session-ui-store';
const restrictToXAxis: Modifier = ({ transform }) => ({ ...transform, y: 0 });
/**
* Sortable shell for the active tab: the pill itself drags, while the
* interactive content inside (rename form, menu) stops pointer-down so a text
* selection or menu click never starts a drag.
*/
const ActiveTabShell: React.FC<{ id: string; children: React.ReactNode }> = ({ id, children }) => {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id });
return (
<div
ref={setNodeRef}
style={{ transform: DndCSS.Translate.toString(transform), transition }}
className={cn('h-9 shrink-0 touch-none', isDragging && 'z-10 opacity-60')}
data-active-session-tab
{...attributes}
{...listeners}
>
<div
role="tab"
aria-selected
className="flex h-9 min-w-0 max-w-[340px] items-center rounded-[10px] bg-interactive-selection px-3"
>
{children}
</div>
</div>
);
};
type SessionTab = { id: string; session: Session };
/**
* One inactive tab: a soft pill with the session title. The "..." menu trigger
* has no reserved footprint — it appears at the tab's end on hover (or while
* its menu is open), nudging the title, mirroring the sidebar row mechanic.
* The reveal itself is opacity-only; the layout change is instant.
*/
const InactiveSessionTab: React.FC<{
tab: SessionTab;
onSelect: (tab: SessionTab) => void;
onClose: (id: string) => void;
onCloseOthers: (id: string) => void;
}> = ({ tab, onSelect, onClose, onCloseOthers }) => {
const { t } = useI18n();
const [menuOpen, setMenuOpen] = React.useState(false);
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: tab.id });
const title = tab.session.title?.trim() || t('sessions.sidebar.session.untitled');
return (
<div
ref={setNodeRef}
style={{ transform: DndCSS.Translate.toString(transform), transition }}
className={cn('h-8 shrink-0', isDragging && 'z-10 opacity-60')}
{...attributes}
{...listeners}
>
<div
role="tab"
aria-selected={false}
tabIndex={0}
onClick={() => onSelect(tab)}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
onSelect(tab);
}
}}
onAuxClick={(event) => {
if (event.button === 1) {
event.preventDefault();
onClose(tab.id);
}
}}
className={cn(
'group/session-tab flex h-8 max-w-[200px] cursor-pointer touch-none select-none items-center rounded-[10px] px-3',
'text-muted-foreground transition-colors duration-150 hover:bg-interactive-hover/40 hover:text-foreground',
menuOpen && 'bg-interactive-hover/40 text-foreground',
)}
title={title}
>
<span className="min-w-0 truncate typography-ui-label text-[13px] font-normal leading-tight">
{title}
</span>
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label={t('header.sessionTabs.tabMenuAria')}
onClick={(event) => event.stopPropagation()}
onPointerDown={(event) => event.stopPropagation()}
className={cn(
'ml-0 hidden w-0 shrink-0 items-center justify-center overflow-hidden rounded-md text-muted-foreground',
'opacity-0 transition-opacity duration-150 hover:text-foreground',
'group-hover/session-tab:ml-1.5 group-hover/session-tab:flex group-hover/session-tab:h-5 group-hover/session-tab:w-5 group-hover/session-tab:opacity-100',
menuOpen && 'ml-1.5 flex h-5 w-5 opacity-100',
)}
>
<Icon name="more" className="size-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-[190px]">
<DropdownMenuItem onClick={() => onClose(tab.id)}>
<Icon name="close" className="mr-2 size-4" />
{t('header.sessionTabs.closeTab')}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onCloseOthers(tab.id)}>
<Icon name="close-circle" className="mr-2 size-4" />
{t('header.sessionTabs.closeOtherTabs')}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => void copyTextToClipboard(tab.id)}>
<Icon name="file-copy" className="mr-2 size-4" />
{t('sessions.sidebar.session.menu.copyId')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
);
};
/**
* The header's horizontal working set of sessions (web/desktop only).
*
* Every session the user opens joins the strip once; the tab whose session is
* current renders `children` — the header's existing title block with rename,
* meta row and the full session menu — inside a softly selected pill. Closing
* a tab only removes it from the strip; closing the active one activates its
* neighbour. Ids whose session has not loaded (or was archived/deleted) stay
* in the store but do not render, so a partial session list never destroys
* the working set.
*/
export const SessionTabsStrip: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { t } = useI18n();
const tabIds = useSessionTabsStore((state) => state.tabIds);
const ensureTab = useSessionTabsStore((state) => state.ensureTab);
const closeTab = useSessionTabsStore((state) => state.closeTab);
const closeOtherTabs = useSessionTabsStore((state) => state.closeOtherTabs);
const reorderTabs = useSessionTabsStore((state) => state.reorderTabs);
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession);
const openNewSessionDraft = useSessionUIStore((state) => state.openNewSessionDraft);
const activeSessions = useGlobalSessionsStore((state) => state.activeSessions);
// Opening a session anywhere (sidebar, palette, deep link) adds its tab.
React.useEffect(() => {
if (currentSessionId) ensureTab(currentSessionId);
}, [currentSessionId, ensureTab]);
const sessionsById = React.useMemo(() => {
const map = new Map<string, Session>();
for (const session of activeSessions) map.set(session.id, session);
return map;
}, [activeSessions]);
// Only tabs with a known live session render; unknown ids stay stored.
const tabs = React.useMemo<SessionTab[]>(() => {
const list: SessionTab[] = [];
for (const id of tabIds) {
const session = sessionsById.get(id);
if (session) list.push({ id, session });
}
return list;
}, [tabIds, sessionsById]);
const handleSelect = React.useCallback((tab: SessionTab) => {
setCurrentSession(tab.id, resolveGlobalSessionDirectory(tab.session));
}, [setCurrentSession]);
const activateNeighbour = React.useCallback((closedId: string) => {
const index = tabs.findIndex((tab) => tab.id === closedId);
const neighbour = tabs[index + 1] ?? tabs[index - 1] ?? null;
if (neighbour) {
handleSelect(neighbour);
} else {
openNewSessionDraft();
}
}, [tabs, handleSelect, openNewSessionDraft]);
const handleClose = React.useCallback((id: string) => {
if (id === currentSessionId) activateNeighbour(id);
closeTab(id);
}, [activateNeighbour, closeTab, currentSessionId]);
const handleCloseOthers = React.useCallback((id: string) => {
closeOtherTabs(id);
if (currentSessionId && currentSessionId !== id) {
const kept = tabs.find((tab) => tab.id === id);
if (kept) handleSelect(kept);
}
}, [closeOtherTabs, currentSessionId, handleSelect, tabs]);
const sensors = useSensors(
useSensor(MouseSensor, { activationConstraint: { distance: 8 } }),
useSensor(TouchSensor, { activationConstraint: { delay: 200, tolerance: 6 } }),
);
const handleDragEnd = React.useCallback((event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
reorderTabs(String(active.id), String(over.id));
}
}, [reorderTabs]);
// Soft fade at the edges while more tabs hide behind them.
const scrollRef = React.useRef<HTMLDivElement | null>(null);
const [edges, setEdges] = React.useState({ left: false, right: false });
const updateEdges = React.useCallback(() => {
const node = scrollRef.current;
if (!node) return;
const left = node.scrollLeft > 2;
const right = node.scrollLeft + node.clientWidth < node.scrollWidth - 2;
setEdges((prev) => (prev.left === left && prev.right === right ? prev : { left, right }));
}, []);
React.useEffect(() => {
updateEdges();
const node = scrollRef.current;
if (!node || !globalThis.ResizeObserver) return;
const observer = new ResizeObserver(updateEdges);
observer.observe(node);
return () => observer.disconnect();
}, [updateEdges, tabs.length]);
// Keep the active tab in view when it changes.
React.useEffect(() => {
scrollRef.current
?.querySelector('[data-active-session-tab]')
?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}, [currentSessionId]);
const maskImage = edges.left && edges.right
? 'linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent)'
: edges.left
? 'linear-gradient(to right, transparent, black 24px)'
: edges.right
? 'linear-gradient(to right, black calc(100% - 24px), transparent)'
: undefined;
const tabIdsInOrder = React.useMemo(() => tabs.map((tab) => tab.id), [tabs]);
const renderTab = (tab: SessionTab) => {
if (tab.id === currentSessionId) {
return <ActiveTabShell key={tab.id} id={tab.id}>{children}</ActiveTabShell>;
}
return (
<InactiveSessionTab
key={tab.id}
tab={tab}
onSelect={handleSelect}
onClose={handleClose}
onCloseOthers={handleCloseOthers}
/>
);
};
// A brand-new draft (no session yet) shows as a transient active pill after
// the tabs; it becomes a real tab once the first message creates the session.
const showDraftPill = !currentSessionId || !tabs.some((tab) => tab.id === currentSessionId);
return (
<div className="app-region-no-drag flex h-full min-w-0 flex-1 items-center" role="tablist" aria-label={t('header.sessionTabs.stripAria')}>
<div
ref={scrollRef}
onScroll={updateEdges}
className="flex min-w-0 items-center gap-1 overflow-x-auto py-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
style={maskImage ? { maskImage, WebkitMaskImage: maskImage } : undefined}
>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
modifiers={[restrictToXAxis]}
onDragEnd={handleDragEnd}
>
<SortableContext items={tabIdsInOrder} strategy={horizontalListSortingStrategy}>
{tabs.map(renderTab)}
</SortableContext>
</DndContext>
{showDraftPill ? (
<div
role="tab"
aria-selected
className="flex h-9 min-w-0 max-w-[340px] shrink-0 items-center rounded-[10px] bg-interactive-selection px-3"
>
{children}
</div>
) : null}
</div>
</div>
);
};
+4
View File
@@ -419,6 +419,10 @@ export const dict = {
'sessions.sidebar.activity.chatsEmpty': 'Noch keine Chats.',
'chat.chatInput.chooseProject': 'Projekt auswählen',
'sessions.switcher.openAria': 'Sitzungswechsler öffnen',
'header.sessionTabs.stripAria': 'Offene Sitzungen',
'header.sessionTabs.tabMenuAria': 'Aktionen für den Sitzungs-Tab',
'header.sessionTabs.closeTab': 'Tab schließen',
'header.sessionTabs.closeOtherTabs': 'Andere Tabs schließen',
'sessions.switcher.empty': 'Keine kürzlichen Sitzungen',
'sessions.switcher.draftTitle': 'Neue Sitzung',
'sessions.sidebar.updateCheck.errorTitle': 'Fehler beim Prüfen auf Aktualisierungen',
+4
View File
@@ -481,6 +481,10 @@ export const dict = {
'sessions.archivePage.deleteSessionAria': 'Delete {title}',
'sessions.archivePage.restoreSessionAria': 'Restore {title}',
'sessions.switcher.openAria': 'Open session switcher',
'header.sessionTabs.stripAria': 'Open sessions',
'header.sessionTabs.tabMenuAria': 'Session tab actions',
'header.sessionTabs.closeTab': 'Close tab',
'header.sessionTabs.closeOtherTabs': 'Close other tabs',
'sessions.switcher.empty': 'No recent sessions',
'sessions.switcher.draftTitle': 'New session',
'sessions.sidebar.updateCheck.errorTitle': 'Failed to check for updates',
+4
View File
@@ -482,6 +482,10 @@ export const dict: Record<I18nKey, string> = {
"sessions.archivePage.deleteSessionAria": "Eliminar {title}",
"sessions.archivePage.restoreSessionAria": "Restaurar {title}",
"sessions.switcher.openAria": "Abrir selector de sesiones",
"header.sessionTabs.stripAria": "Sesiones abiertas",
"header.sessionTabs.tabMenuAria": "Acciones de la pestaña de sesión",
"header.sessionTabs.closeTab": "Cerrar pestaña",
"header.sessionTabs.closeOtherTabs": "Cerrar las demás pestañas",
"sessions.switcher.empty": "No hay sesiones recientes",
"sessions.switcher.draftTitle": "Nueva sesión",
"sessions.sidebar.updateCheck.errorTitle": "No se pudo comprobar actualizaciones",
+4
View File
@@ -312,6 +312,10 @@ export const dict = {
'sessions.archivePage.deleteSessionAria': 'Supprimer {title}',
'sessions.archivePage.restoreSessionAria': 'Restaurer {title}',
'sessions.switcher.openAria': 'Sélecteur de session ouvert',
'header.sessionTabs.stripAria': 'Sessions ouvertes',
'header.sessionTabs.tabMenuAria': 'Actions de l\'onglet de session',
'header.sessionTabs.closeTab': 'Fermer l\'onglet',
'header.sessionTabs.closeOtherTabs': 'Fermer les autres onglets',
'sessions.switcher.empty': 'Aucune session récente',
'sessions.switcher.draftTitle': 'Nouvelle session',
'sessions.sidebar.updateCheck.errorTitle': 'Échec de la vérification des mises à jour',
+4
View File
@@ -482,6 +482,10 @@ export const dict: Record<I18nKey, string> = {
'sessions.archivePage.deleteSessionAria': '{title} を削除',
'sessions.archivePage.restoreSessionAria': '{title} を復元',
'sessions.switcher.openAria': 'セッションスイッチャーを開く',
'header.sessionTabs.stripAria': '開いているセッション',
'header.sessionTabs.tabMenuAria': 'セッションタブの操作',
'header.sessionTabs.closeTab': 'タブを閉じる',
'header.sessionTabs.closeOtherTabs': '他のタブを閉じる',
'sessions.switcher.empty': '最近のセッションはありません',
'sessions.switcher.draftTitle': '新しいセッション',
'sessions.sidebar.updateCheck.errorTitle': '更新の確認に失敗しました',
+4
View File
@@ -482,6 +482,10 @@ export const dict: Record<I18nKey, string> = {
'sessions.archivePage.deleteSessionAria': '{title} 삭제',
'sessions.archivePage.restoreSessionAria': '{title} 복원',
'sessions.switcher.openAria': '세션 전환기 열기',
'header.sessionTabs.stripAria': '열린 세션',
'header.sessionTabs.tabMenuAria': '세션 탭 작업',
'header.sessionTabs.closeTab': '탭 닫기',
'header.sessionTabs.closeOtherTabs': '다른 탭 닫기',
'sessions.switcher.empty': '최근 세션 없음',
'sessions.switcher.draftTitle': '새 세션',
'sessions.sidebar.updateCheck.errorTitle': '업데이트 확인 실패',
+4
View File
@@ -293,6 +293,10 @@ export const dict: Record<I18nKey, string> = {
'sessions.archivePage.deleteSessionAria': 'Usuń {title}',
'sessions.archivePage.restoreSessionAria': 'Przywróć {title}',
'sessions.switcher.openAria': 'Otwórz przełącznik sesji',
'header.sessionTabs.stripAria': 'Otwarte sesje',
'header.sessionTabs.tabMenuAria': 'Akcje karty sesji',
'header.sessionTabs.closeTab': 'Zamknij kartę',
'header.sessionTabs.closeOtherTabs': 'Zamknij pozostałe karty',
'sessions.switcher.empty': 'Brak ostatnich sesji',
'sessions.switcher.draftTitle': 'Nowa sesja',
'sessions.sidebar.updateCheck.errorTitle': 'Nie udało się sprawdzić aktualizacji',
@@ -482,6 +482,10 @@ export const dict: Record<I18nKey, string> = {
"sessions.archivePage.deleteSessionAria": "Excluir {title}",
"sessions.archivePage.restoreSessionAria": "Restaurar {title}",
"sessions.switcher.openAria": "Abrir seletor de sessões",
"header.sessionTabs.stripAria": "Sessões abertas",
"header.sessionTabs.tabMenuAria": "Ações da aba de sessão",
"header.sessionTabs.closeTab": "Fechar aba",
"header.sessionTabs.closeOtherTabs": "Fechar outras abas",
"sessions.switcher.empty": "Nenhuma sessão recente",
"sessions.switcher.draftTitle": "Nova sessão",
"sessions.sidebar.updateCheck.errorTitle": "Não foi possível verificar atualizações",
+4
View File
@@ -482,6 +482,10 @@ export const dict: Record<I18nKey, string> = {
"sessions.archivePage.deleteSessionAria": "Видалити {title}",
"sessions.archivePage.restoreSessionAria": "Відновити {title}",
"sessions.switcher.openAria": "Відкрити перемикач сесій",
"header.sessionTabs.stripAria": "Відкриті сесії",
"header.sessionTabs.tabMenuAria": "Дії вкладки сесії",
"header.sessionTabs.closeTab": "Закрити вкладку",
"header.sessionTabs.closeOtherTabs": "Закрити інші вкладки",
"sessions.switcher.empty": "Немає недавніх сесій",
"sessions.switcher.draftTitle": "Нова сесія",
"sessions.sidebar.updateCheck.errorTitle": "Не вдалося перейти на наявність оновлень",
@@ -482,6 +482,10 @@ export const dict: Record<I18nKey, string> = {
'sessions.archivePage.deleteSessionAria': '删除 {title}',
'sessions.archivePage.restoreSessionAria': '还原 {title}',
'sessions.switcher.openAria': '打开会话切换器',
'header.sessionTabs.stripAria': '打开的会话',
'header.sessionTabs.tabMenuAria': '会话标签页操作',
'header.sessionTabs.closeTab': '关闭标签页',
'header.sessionTabs.closeOtherTabs': '关闭其他标签页',
'sessions.switcher.empty': '没有最近会话',
'sessions.switcher.draftTitle': '新会话',
'sessions.sidebar.updateCheck.errorTitle': '检查更新失败',
@@ -495,6 +495,10 @@ export const dict: Record<I18nKey, string> = {
'sessions.archivePage.deleteSessionAria': '刪除 {title}',
'sessions.archivePage.restoreSessionAria': '還原 {title}',
'sessions.switcher.openAria': '開啟會話切換器',
'header.sessionTabs.stripAria': '開啟的會話',
'header.sessionTabs.tabMenuAria': '工作階段分頁動作',
'header.sessionTabs.closeTab': '關閉分頁',
'header.sessionTabs.closeOtherTabs': '關閉其他分頁',
'sessions.switcher.empty': '沒有最近會話',
'sessions.switcher.draftTitle': '新會話',
'sessions.sidebar.updateCheck.errorTitle': '檢查更新失敗',
@@ -0,0 +1,43 @@
import { beforeEach, describe, expect, test } from 'bun:test';
import { useSessionTabsStore } from './useSessionTabsStore';
describe('useSessionTabsStore', () => {
beforeEach(() => {
useSessionTabsStore.setState({ tabIds: [] });
});
test('ensureTab appends once and preserves order', () => {
const store = useSessionTabsStore.getState();
store.ensureTab('a');
store.ensureTab('b');
store.ensureTab('a');
expect(useSessionTabsStore.getState().tabIds).toEqual(['a', 'b']);
});
test('closeTab removes only the given id; closeOtherTabs keeps only it', () => {
useSessionTabsStore.setState({ tabIds: ['a', 'b', 'c'] });
useSessionTabsStore.getState().closeTab('b');
expect(useSessionTabsStore.getState().tabIds).toEqual(['a', 'c']);
useSessionTabsStore.getState().closeOtherTabs('c');
expect(useSessionTabsStore.getState().tabIds).toEqual(['c']);
});
test('reorderTabs moves by id and ignores unknown ids', () => {
useSessionTabsStore.setState({ tabIds: ['a', 'b', 'c'] });
useSessionTabsStore.getState().reorderTabs('c', 'a');
expect(useSessionTabsStore.getState().tabIds).toEqual(['c', 'a', 'b']);
const before = useSessionTabsStore.getState().tabIds;
useSessionTabsStore.getState().reorderTabs('x', 'a');
expect(useSessionTabsStore.getState().tabIds).toBe(before);
});
test('removeTabs drops only confirmed-gone ids and no-ops otherwise', () => {
useSessionTabsStore.setState({ tabIds: ['a', 'b'] });
const before = useSessionTabsStore.getState().tabIds;
useSessionTabsStore.getState().removeTabs(['x']);
expect(useSessionTabsStore.getState().tabIds).toBe(before);
useSessionTabsStore.getState().removeTabs(['a']);
expect(useSessionTabsStore.getState().tabIds).toEqual(['b']);
});
});
@@ -0,0 +1,81 @@
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { createDeferredSafeJSONStorage } from '@/stores/utils/safeStorage';
/**
* The header's working set of sessions, shown as tabs on web/desktop.
*
* Only session ids and their order are owned here titles, directories and
* liveness come from the session stores at render time. Tabs are a per-client
* projection: opening a session anywhere adds it once, closing a tab only
* removes it from the strip and never touches the session itself. Ids whose
* session is unknown are kept (a partially loaded global list must not
* destroy the working set) and simply do not render until the session loads.
*/
interface SessionTabsStore {
tabIds: string[];
ensureTab: (sessionId: string) => void;
closeTab: (sessionId: string) => void;
closeOtherTabs: (sessionId: string) => void;
reorderTabs: (activeId: string, overId: string) => void;
/** Drop ids the caller has authoritatively confirmed no longer exist. */
removeTabs: (sessionIds: readonly string[]) => void;
}
type PersistedSessionTabs = { tabIds: string[] };
export const useSessionTabsStore = create<SessionTabsStore>()(
devtools(
persist(
(set, get) => ({
tabIds: [],
ensureTab: (sessionId) => {
if (!sessionId) return;
const { tabIds } = get();
if (tabIds.includes(sessionId)) return;
set({ tabIds: [...tabIds, sessionId] });
},
closeTab: (sessionId) => {
const { tabIds } = get();
if (!tabIds.includes(sessionId)) return;
set({ tabIds: tabIds.filter((id) => id !== sessionId) });
},
closeOtherTabs: (sessionId) => {
const { tabIds } = get();
if (!tabIds.includes(sessionId)) return;
if (tabIds.length === 1) return;
set({ tabIds: [sessionId] });
},
reorderTabs: (activeId, overId) => {
const { tabIds } = get();
const from = tabIds.indexOf(activeId);
const to = tabIds.indexOf(overId);
if (from < 0 || to < 0 || from === to) return;
const next = [...tabIds];
next.splice(to, 0, ...next.splice(from, 1));
set({ tabIds: next });
},
removeTabs: (sessionIds) => {
if (sessionIds.length === 0) return;
const gone = new Set(sessionIds);
const { tabIds } = get();
const next = tabIds.filter((id) => !gone.has(id));
if (next.length === tabIds.length) return;
set({ tabIds: next });
},
}),
{
name: 'session-tabs-store',
storage: createDeferredSafeJSONStorage<PersistedSessionTabs>(),
partialize: (state) => ({ tabIds: state.tabIds }),
},
),
),
);