feat(web): improve terminal workspace controls

This commit is contained in:
maria-rcks committed 2026-08-15 22:10:38 -04:00
1 parent 2dd5525de4
commit 63ecfa9b64
6 files changed
+656 -366

No files matched your search

+26 -10
View File
@@ -221,7 +221,11 @@ import {
import { appendPreviewAnnotationPrompt } from "../lib/previewAnnotation";
import { appendReviewCommentsToPrompt, type ReviewCommentContext } from "../reviewCommentContext";
import { environmentCatalog } from "../connection/catalog";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import {
selectThreadTerminalCustomLabels,
selectThreadTerminalUiState,
useTerminalUiStateStore,
} from "../terminalUiStateStore";
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
@@ -658,6 +662,7 @@ interface PersistentThreadTerminalDrawerProps {
newShortcutLabel: string | undefined;
closeShortcutLabel: string | undefined;
keybindings: ResolvedKeybindingsConfig;
onHide: () => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
}
@@ -672,6 +677,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
newShortcutLabel,
closeShortcutLabel,
keybindings,
onHide,
onAddTerminalContext,
}: PersistentThreadTerminalDrawerProps) {
const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
@@ -995,6 +1001,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
onSplitTerminal={splitTerminal}
onSplitTerminalVertical={splitTerminalVertical}
onNewTerminal={createNewTerminal}
onHide={onHide}
splitShortcutLabel={visible ? splitShortcutLabel : undefined}
splitVerticalShortcutLabel={visible ? splitVerticalShortcutLabel : undefined}
newShortcutLabel={visible ? newShortcutLabel : undefined}
@@ -1557,6 +1564,16 @@ function ChatViewContent(props: ChatViewProps) {
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
const activeThreadId = activeThread?.id ?? null;
const activeThreadEnvironmentId = activeThread?.environmentId ?? null;
const activeThreadRef = useMemo(
() =>
activeThreadEnvironmentId && activeThreadId
? scopeThreadRef(activeThreadEnvironmentId, activeThreadId)
: null,
[activeThreadEnvironmentId, activeThreadId],
);
const activeTerminalCustomLabels = useTerminalUiStateStore((state) =>
selectThreadTerminalCustomLabels(state.terminalCustomLabelsByThreadKey, activeThreadRef),
);
const runningTerminalIds = useThreadRunningTerminalIds({
environmentId: activeThread?.environmentId ?? null,
threadId: activeThreadId,
@@ -1586,18 +1603,15 @@ function ChatViewContent(props: ChatViewProps) {
for (const session of activeThreadKnownSessions) {
labels.set(
session.target.terminalId,
resolveTerminalSessionLabel(session.target.terminalId, session.state.summary),
activeTerminalCustomLabels[session.target.terminalId] ??
resolveTerminalSessionLabel(session.target.terminalId, session.state.summary),
);
}
for (const [terminalId, label] of Object.entries(activeTerminalCustomLabels)) {
if (!labels.has(terminalId)) labels.set(terminalId, label);
}
return labels;
}, [activeThreadKnownSessions]);
const activeThreadRef = useMemo(
() =>
activeThreadEnvironmentId && activeThreadId
? scopeThreadRef(activeThreadEnvironmentId, activeThreadId)
: null,
[activeThreadEnvironmentId, activeThreadId],
);
}, [activeTerminalCustomLabels, activeThreadKnownSessions]);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom);
const [timelineAnchor, setTimelineAnchor] = useState<{
@@ -2826,6 +2840,7 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeThreadRef, storeSetTerminalOpen],
);
const hideTerminal = useCallback(() => setTerminalOpen(false), [setTerminalOpen]);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadRef) return;
const nextOpen = !terminalUiState.terminalOpen;
@@ -6604,6 +6619,7 @@ function ChatViewContent(props: ChatViewProps) {
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
keybindings={keybindings}
onHide={hideTerminal}
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
@@ -4,10 +4,19 @@ import {
resolveTerminalSelectionActionPosition,
shouldHandleTerminalExit,
shouldHandleTerminalSelectionMouseUp,
shouldShowTerminalSidebar,
terminalSelectionActionDelayForClickCount,
terminalSelectionLineRange,
} from "./ThreadTerminalDrawer";
describe("shouldShowTerminalSidebar", () => {
it("shows the sidebar only when there is more than one terminal", () => {
expect(shouldShowTerminalSidebar(0)).toBe(false);
expect(shouldShowTerminalSidebar(1)).toBe(false);
expect(shouldShowTerminalSidebar(2)).toBe(true);
});
});
describe("resolveTerminalSelectionActionPosition", () => {
it("prefers the selection rect over the last pointer position", () => {
expect(
+395 -310
View File
@@ -5,11 +5,11 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import { type TerminalSessionState } from "@t3tools/client-runtime/state/terminal";
import {
PanelBottomCloseIcon,
Plus,
SquareSplitHorizontal,
SquareSplitVertical,
TerminalSquare,
Trash2,
XIcon,
} from "lucide-react";
import {
@@ -21,8 +21,8 @@ import {
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as Schema from "effect/Schema";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
type PointerEvent as ReactPointerEvent,
type SetStateAction,
useCallback,
useEffect,
@@ -31,9 +31,9 @@ import {
useRef,
useState,
} from "react";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { Button } from "~/components/ui/button";
import { readTextFromClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard";
import { useResizableWidth } from "~/hooks/useResizableWidth";
import { cn } from "~/lib/utils";
import { type TerminalContextSelection } from "~/lib/terminalContext";
import {
@@ -50,6 +50,7 @@ import {
isTerminalSplitShortcut,
isTerminalSplitVerticalShortcut,
isTerminalToggleShortcut,
shortcutLabelForCommand,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
} from "../keybindings";
@@ -61,6 +62,7 @@ import {
import { readLocalApi } from "~/localApi";
import { useClientSettings } from "../hooks/useSettings";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { selectThreadTerminalCustomLabels, useTerminalUiStateStore } from "../terminalUiStateStore";
import { useAttachedTerminalSession } from "../state/terminalSessions";
import { serverEnvironment } from "../state/server";
import { previewEnvironment } from "../state/preview";
@@ -73,10 +75,48 @@ import {
resolveTerminalFontSizePreference,
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../appearanceFonts";
import { RightPanelResizeHandle } from "./preview/RightPanelResizeHandle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
const MULTI_CLICK_SELECTION_ACTION_DELAY_MS = 260;
const TERMINAL_SIDEBAR_DEFAULT_WIDTH = 144;
const TERMINAL_SIDEBAR_MIN_WIDTH = 144;
const TERMINAL_SIDEBAR_MAX_WIDTH = 320;
const TERMINAL_SIDEBAR_WIDTH_STORAGE_KEY = "t3code:terminal-sidebar-width";
function TerminalToolbarAction({
label,
disabled = false,
onClick,
children,
}: {
label: string;
disabled?: boolean;
onClick: () => void;
children: ReactNode;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost"
aria-label={label}
aria-disabled={disabled || undefined}
className={cn(disabled && "cursor-not-allowed opacity-64")}
onClick={onClick}
/>
}
>
{children}
</TooltipTrigger>
<TooltipPopup side="bottom">{label}</TooltipPopup>
</Tooltip>
);
}
function maxDrawerHeight(): number {
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
@@ -245,6 +285,10 @@ export function shouldHandleTerminalSelectionMouseUp(
return selectionGestureActive && button === 0;
}
export function shouldShowTerminalSidebar(terminalCount: number): boolean {
return terminalCount > 1;
}
export function terminalSelectionLineRange(position: {
start: { y: number };
end: { y: number };
@@ -999,6 +1043,7 @@ interface ThreadTerminalDrawerProps {
onSplitTerminal: () => void;
onSplitTerminalVertical: () => void;
onNewTerminal: () => void;
onHide?: () => void;
splitShortcutLabel?: string | undefined;
splitVerticalShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
@@ -1014,35 +1059,6 @@ interface ThreadTerminalDrawerProps {
terminalLaunchLocationsById?: ReadonlyMap<string, TerminalLaunchLocation>;
}
interface TerminalActionButtonProps {
label: string;
className: string;
onClick: () => void;
children: ReactNode;
}
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
return (
<Popover>
<PopoverTrigger
openOnHover
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
>
{children}
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{label}
</PopoverPopup>
</Popover>
);
}
export default function ThreadTerminalDrawer({
mode = "drawer",
threadRef,
@@ -1060,6 +1076,7 @@ export default function ThreadTerminalDrawer({
onSplitTerminal,
onSplitTerminalVertical,
onNewTerminal,
onHide,
splitShortcutLabel,
splitVerticalShortcutLabel,
newShortcutLabel,
@@ -1073,6 +1090,21 @@ export default function ThreadTerminalDrawer({
terminalLaunchLocationsById,
}: ThreadTerminalDrawerProps) {
const isPanel = mode === "panel";
const { width: terminalSidebarWidth, handlers: terminalSidebarResizeHandlers } =
useResizableWidth({
storageKey: TERMINAL_SIDEBAR_WIDTH_STORAGE_KEY,
defaultWidth: TERMINAL_SIDEBAR_DEFAULT_WIDTH,
minWidth: TERMINAL_SIDEBAR_MIN_WIDTH,
maxWidth: TERMINAL_SIDEBAR_MAX_WIDTH,
edge: "left",
});
const terminalCustomLabels = useTerminalUiStateStore((state) =>
selectThreadTerminalCustomLabels(state.terminalCustomLabelsByThreadKey, threadRef),
);
const setTerminalCustomLabel = useTerminalUiStateStore((state) => state.setTerminalCustomLabel);
const [renamingTerminalId, setRenamingTerminalId] = useState<string | null>(null);
const [terminalRenameDraft, setTerminalRenameDraft] = useState("");
const cancelTerminalRenameRef = useRef(false);
const [advancedTypography] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
@@ -1221,19 +1253,28 @@ export default function ThreadTerminalDrawer({
(normalizedTerminalIds.length > 0 ? [resolvedActiveTerminalId] : []);
const splitDirection =
resolvedTerminalGroups[resolvedActiveGroupIndex]?.splitDirection ?? "horizontal";
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const hasTerminalSidebar = shouldShowTerminalSidebar(normalizedTerminalIds.length);
const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders =
resolvedTerminalGroups.length > 1 ||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP;
const terminalLabelById = useMemo(() => {
const automaticTerminalLabelById = useMemo(() => {
const next = new Map<string, string>();
for (const terminalId of normalizedTerminalIds) {
next.set(terminalId, terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId));
}
return next;
}, [normalizedTerminalIds, terminalLabelsById]);
const terminalLabelById = useMemo(() => {
const next = new Map<string, string>();
for (const terminalId of normalizedTerminalIds) {
next.set(
terminalId,
terminalCustomLabels[terminalId]?.trim() ||
automaticTerminalLabelById.get(terminalId) ||
getTerminalLabel(terminalId),
);
}
return next;
}, [automaticTerminalLabelById, normalizedTerminalIds, terminalCustomLabels]);
const resolveTerminalLaunchLocation = useCallback(
(terminalId: string): TerminalLaunchLocation => {
return (
@@ -1246,6 +1287,9 @@ export default function ThreadTerminalDrawer({
},
[cwd, runtimeEnv, terminalLaunchLocationsById, worktreePath],
);
const newTerminalActionLabel = newShortcutLabel
? `New Terminal (${newShortcutLabel})`
: "New Terminal";
const splitTerminalActionLabel = hasReachedSplitLimit
? `Split Terminal Horizontally (max ${MAX_TERMINALS_PER_GROUP} per group)`
: splitShortcutLabel
@@ -1256,12 +1300,13 @@ export default function ThreadTerminalDrawer({
: splitVerticalShortcutLabel
? `Split Terminal Vertically (${splitVerticalShortcutLabel})`
: "Split Terminal Vertically";
const newTerminalActionLabel = newShortcutLabel
? `New Terminal (${newShortcutLabel})`
: "New Terminal";
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
const terminalToggleShortcutLabel = shortcutLabelForCommand(keybindings, "terminal.toggle");
const hideTerminalActionLabel = terminalToggleShortcutLabel
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
: "Toggle terminal drawer";
const onSplitTerminalAction = useCallback(() => {
if (hasReachedSplitLimit) return;
onSplitTerminal();
@@ -1270,9 +1315,53 @@ export default function ThreadTerminalDrawer({
if (hasReachedSplitLimit) return;
onSplitTerminalVertical();
}, [hasReachedSplitLimit, onSplitTerminalVertical]);
const onNewTerminalAction = useCallback(() => {
onNewTerminal();
}, [onNewTerminal]);
const startTerminalRename = useCallback(
(terminalId: string) => {
cancelTerminalRenameRef.current = false;
setRenamingTerminalId(terminalId);
setTerminalRenameDraft(
terminalCustomLabels[terminalId] ?? terminalLabelById.get(terminalId) ?? "",
);
},
[terminalCustomLabels, terminalLabelById],
);
const finishTerminalRename = useCallback(() => {
if (!renamingTerminalId) return;
const nextLabel = terminalRenameDraft.trim();
const automaticLabel = automaticTerminalLabelById.get(renamingTerminalId) ?? "";
setTerminalCustomLabel(
threadRef,
renamingTerminalId,
nextLabel.length === 0 || nextLabel === automaticLabel ? null : nextLabel,
);
setRenamingTerminalId(null);
}, [
automaticTerminalLabelById,
renamingTerminalId,
setTerminalCustomLabel,
terminalRenameDraft,
threadRef,
]);
const cancelTerminalRename = useCallback(() => {
cancelTerminalRenameRef.current = true;
setRenamingTerminalId(null);
}, []);
const closeTerminalSafely = useCallback(
(terminalId: string) => {
if (renamingTerminalId === terminalId) {
cancelTerminalRenameRef.current = true;
setRenamingTerminalId(null);
}
onCloseTerminal(terminalId);
},
[onCloseTerminal, renamingTerminalId],
);
useEffect(() => {
cancelTerminalRenameRef.current = false;
setRenamingTerminalId(null);
setTerminalRenameDraft("");
}, [threadRef.environmentId, threadRef.threadId]);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
@@ -1397,7 +1486,7 @@ export default function ThreadTerminalDrawer({
) : null}
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-4 py-6 text-center text-sm text-muted-foreground">
<p>No terminal sessions for this thread yet.</p>
<Button size="xs" variant="outline" onClick={onNewTerminalAction}>
<Button size="xs" variant="outline" onClick={onNewTerminal}>
{newTerminalActionLabel}
</Button>
</div>
@@ -1406,7 +1495,41 @@ export default function ThreadTerminalDrawer({
}
const activeTerminalLaunchLocation = resolveTerminalLaunchLocation(resolvedActiveTerminalId);
const compactTerminalToolbar = (
<>
<TerminalToolbarAction
label={splitTerminalActionLabel}
disabled={hasReachedSplitLimit}
onClick={onSplitTerminalAction}
>
<SquareSplitHorizontal className="size-3.5" />
</TerminalToolbarAction>
<TerminalToolbarAction
label={splitTerminalVerticalActionLabel}
disabled={hasReachedSplitLimit}
onClick={onSplitTerminalVerticalAction}
>
<SquareSplitVertical className="size-3.5" />
</TerminalToolbarAction>
<TerminalToolbarAction label={newTerminalActionLabel} onClick={onNewTerminal}>
<Plus className="size-3.5" />
</TerminalToolbarAction>
<TerminalToolbarAction
label={closeTerminalActionLabel}
onClick={() => closeTerminalSafely(resolvedActiveTerminalId)}
>
<XIcon className="size-3.5" />
</TerminalToolbarAction>
{!isPanel && onHide ? (
<>
<span aria-hidden className="mx-0.5 h-4 w-px bg-border/70" />
<TerminalToolbarAction label={hideTerminalActionLabel} onClick={onHide}>
<PanelBottomCloseIcon className="size-3.5" />
</TerminalToolbarAction>
</>
) : null}
</>
);
return (
<aside
data-terminal-owner={isPanel ? "right-panel" : "drawer"}
@@ -1426,277 +1549,239 @@ export default function ThreadTerminalDrawer({
/>
) : null}
{!hasTerminalSidebar && (
<div className="pointer-events-none absolute right-2 top-2 z-20">
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background shadow-xs">
<TerminalActionButton
className={`p-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent"
}`}
onClick={onSplitTerminalAction}
label={splitTerminalActionLabel}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className={`p-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent"
}`}
onClick={onSplitTerminalVerticalAction}
label={splitTerminalVerticalActionLabel}
>
<SquareSplitVertical className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminalAction}
label={newTerminalActionLabel}
>
<Plus className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
{!hasTerminalSidebar ? (
<div className="pointer-events-none absolute top-2 right-2 z-20">
<div className="pointer-events-auto flex h-8 items-center rounded-lg border border-border/70 bg-background p-0.5 shadow-xs">
{compactTerminalToolbar}
</div>
</div>
)}
) : null}
<div className="min-h-0 w-full flex-1">
<div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
<div className="min-w-0 flex-1">
{isSplitView ? (
<div
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
style={
splitDirection === "vertical"
? {
gridTemplateRows: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}
: {
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}
}
>
{visibleTerminalIds.map((terminalId) => {
const terminalLaunchLocation = resolveTerminalLaunchLocation(terminalId);
return (
<div
key={terminalId}
className={`min-h-0 min-w-0 ${
splitDirection === "vertical"
? "border-t first:border-t-0"
: "border-l first:border-l-0"
} ${
terminalId === resolvedActiveTerminalId
? "border-border"
: "border-border/70"
}`}
onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) {
onActiveTerminalChange(terminalId);
}
}}
>
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={terminalLaunchLocation.cwd}
{...(terminalLaunchLocation.worktreePath !== undefined
? { worktreePath: terminalLaunchLocation.worktreePath }
: {})}
{...(terminalLaunchLocation.runtimeEnv
? { runtimeEnv: terminalLaunchLocation.runtimeEnv }
: {})}
onSessionExited={() => onCloseTerminal(terminalId)}
onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
keybindings={keybindings}
/>
</div>
<div className="flex min-h-0 w-full flex-1">
<div className="min-w-0 flex-1">
{isSplitView ? (
<div
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
style={
splitDirection === "vertical"
? {
gridTemplateRows: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}
: {
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}
}
>
{visibleTerminalIds.map((terminalId) => {
const terminalLaunchLocation = resolveTerminalLaunchLocation(terminalId);
const isActive = terminalId === resolvedActiveTerminalId;
return (
<div
key={terminalId}
className={cn(
"min-h-0 min-w-0",
splitDirection === "vertical"
? "border-t first:border-t-0"
: "border-l first:border-l-0",
isActive ? "border-border" : "border-border/70",
)}
onMouseDown={() => {
if (!isActive) onActiveTerminalChange(terminalId);
}}
>
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={terminalLaunchLocation.cwd}
{...(terminalLaunchLocation.worktreePath !== undefined
? { worktreePath: terminalLaunchLocation.worktreePath }
: {})}
{...(terminalLaunchLocation.runtimeEnv
? { runtimeEnv: terminalLaunchLocation.runtimeEnv }
: {})}
onSessionExited={() => closeTerminalSafely(terminalId)}
onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus={isActive}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
keybindings={keybindings}
/>
</div>
);
})}
</div>
) : (
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
key={resolvedActiveTerminalId}
threadRef={threadRef}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
cwd={activeTerminalLaunchLocation.cwd}
{...(activeTerminalLaunchLocation.worktreePath !== undefined
? { worktreePath: activeTerminalLaunchLocation.worktreePath }
: {})}
{...(activeTerminalLaunchLocation.runtimeEnv
? { runtimeEnv: activeTerminalLaunchLocation.runtimeEnv }
: {})}
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
keybindings={keybindings}
/>
</div>
)}
</div>
{hasTerminalSidebar && (
<aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
<div className="inline-flex h-full items-stretch">
<TerminalActionButton
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent/70"
}`}
onClick={onSplitTerminalAction}
label={splitTerminalActionLabel}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent/70"
}`}
onClick={onSplitTerminalVerticalAction}
label={splitTerminalVerticalActionLabel}
>
<SquareSplitVertical className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminalAction}
label={newTerminalActionLabel}
>
<Plus className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isGroupActive =
terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const groupActiveTerminalId = isGroupActive
? resolvedActiveTerminalId
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
return (
<div key={terminalGroup.id} className="pb-0.5">
{showGroupHeaders && (
<button
type="button"
className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
isGroupActive
? "bg-accent/70 text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
>
Group {groupIndex + 1}
</button>
)}
<div
className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
return (
<div
key={terminalId}
className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
>
{showGroupHeaders && (
<span className="text-[10px] text-muted-foreground/80">└</span>
)}
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-1 text-left"
onClick={() => onActiveTerminalChange(terminalId)}
>
<TerminalSquare className="size-3 shrink-0" />
<span className="truncate">
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={() => onCloseTerminal(terminalId)}
aria-label={closeTerminalLabel}
/>
}
>
<XIcon className="size-2.5" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{closeTerminalLabel}
</PopoverPopup>
</Popover>
)}
</div>
);
})}
</div>
</div>
);
})}
</div>
</aside>
</div>
);
})}
</div>
) : (
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
key={resolvedActiveTerminalId}
threadRef={threadRef}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
cwd={activeTerminalLaunchLocation.cwd}
{...(activeTerminalLaunchLocation.worktreePath !== undefined
? { worktreePath: activeTerminalLaunchLocation.worktreePath }
: {})}
{...(activeTerminalLaunchLocation.runtimeEnv
? { runtimeEnv: activeTerminalLaunchLocation.runtimeEnv }
: {})}
onSessionExited={() => closeTerminalSafely(resolvedActiveTerminalId)}
onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
keybindings={keybindings}
/>
</div>
)}
</div>
<aside
className={cn(
"relative flex shrink-0 flex-col border-l border-border/70 bg-muted/10",
!hasTerminalSidebar && "hidden",
)}
style={{ width: `${terminalSidebarWidth}px` }}
>
<RightPanelResizeHandle handlers={terminalSidebarResizeHandlers} />
<div className="flex h-9 shrink-0 items-center justify-center border-b border-border/70 px-2">
{hasTerminalSidebar ? compactTerminalToolbar : null}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isSplitGroup = terminalGroup.terminalIds.length > 1;
const splitVertically = terminalGroup.splitDirection === "vertical";
const SplitIcon = splitVertically ? SquareSplitVertical : SquareSplitHorizontal;
return (
<div
key={terminalGroup.id}
className={cn(
groupIndex > 0 && "mt-1",
isSplitGroup && "rounded-lg border border-border/80 bg-muted/20 p-1",
)}
>
{isSplitGroup ? (
<div className="flex h-5 items-center gap-1 px-1 text-[10px] font-medium text-muted-foreground">
<SplitIcon className="size-3" />
<span>{splitVertically ? "Split down" : "Split right"}</span>
</div>
) : null}
<div className={cn(isSplitGroup && "space-y-0.5")}>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const automaticLabel =
automaticTerminalLabelById.get(terminalId) ?? "Terminal";
const customLabel = terminalCustomLabels[terminalId]?.trim() ?? "";
const displayLabel = terminalLabelById.get(terminalId) ?? automaticLabel;
const isRenaming = renamingTerminalId === terminalId;
const terminalTabTooltipLabel = `${displayLabel}${customLabel && customLabel !== automaticLabel ? ` · ${automaticLabel}` : ""} — ${resolveTerminalLaunchLocation(terminalId).cwd} · F2 to rename`;
return (
<div
key={terminalId}
className={cn(
"group/tab flex h-6 items-center gap-0.5 rounded-md pr-2 text-xs",
isSplitGroup ? "pl-0.5" : "pl-1.5",
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
)}
>
<button
type="button"
className="group/close relative flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-sm hover:bg-muted"
aria-label={`Close ${displayLabel}`}
onClick={() => closeTerminalSafely(terminalId)}
>
<TerminalSquare className="size-3 shrink-0 group-hover/tab:hidden group-focus-visible/close:hidden pointer-coarse:hidden" />
<XIcon className="hidden size-3 group-hover/tab:block group-focus-visible/close:block pointer-coarse:block" />
</button>
{isRenaming ? (
<input
autoFocus
value={terminalRenameDraft}
aria-label="Rename terminal"
className="h-6 min-w-0 flex-1 rounded border border-input bg-background px-1.5 text-xs text-foreground outline-none focus:ring-2 focus:ring-ring"
onFocus={(event) => event.currentTarget.select()}
onChange={(event) =>
setTerminalRenameDraft(event.currentTarget.value)
}
onBlur={() => {
if (cancelTerminalRenameRef.current) {
cancelTerminalRenameRef.current = false;
return;
}
finishTerminalRename();
}}
onKeyDown={(event) => {
event.stopPropagation();
if (event.nativeEvent.isComposing) return;
if (event.key === "Enter") {
event.preventDefault();
finishTerminalRename();
} else if (event.key === "Escape") {
event.preventDefault();
cancelTerminalRename();
}
}}
/>
) : (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="flex min-w-0 flex-1 cursor-pointer items-center text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-keyshortcuts="F2"
onClick={() => onActiveTerminalChange(terminalId)}
onContextMenu={(event) => {
event.preventDefault();
onActiveTerminalChange(terminalId);
startTerminalRename(terminalId);
}}
onDoubleClick={(event) => {
event.preventDefault();
onActiveTerminalChange(terminalId);
startTerminalRename(terminalId);
}}
onKeyDown={(event) => {
if (event.key !== "F2") return;
event.preventDefault();
event.stopPropagation();
startTerminalRename(terminalId);
}}
/>
}
>
<span className="min-w-0 flex-1 truncate">
{displayLabel}
{customLabel && customLabel !== automaticLabel ? (
<span className="font-normal text-muted-foreground/80">
{` · ${automaticLabel}`}
</span>
) : null}
</span>
</TooltipTrigger>
<TooltipPopup side="left">{terminalTabTooltipLabel}</TooltipPopup>
</Tooltip>
)}
</div>
);
})}
</div>
</div>
);
})}
</div>
</aside>
</div>
</aside>
);
+13 -30
View File
@@ -1,7 +1,7 @@
import * as Schema from "effect/Schema";
import { type PointerEvent as ReactPointerEvent, useCallback, useRef, useState } from "react";
import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
import { useLocalStorage } from "./useLocalStorage";
const WidthSchema = Schema.Finite;
@@ -28,12 +28,10 @@ export interface ResizableWidthHandlers {
/**
* Width state for a side-anchored panel resized via a drag handle on the
* specified edge. Width is read from localStorage on mount and persisted on
* drag-end (not on every rAF tick — would otherwise be ~60 writes/sec).
* specified edge. Mounted consumers sharing a storage key stay synchronized.
*
* The hook updates an internal `width` state during drag (so the panel
* follows the cursor live) and only commits to localStorage when the user
* lifts the pointer.
* The hook keeps drag width local so the panel follows the cursor without
* writing at rAF frequency, then commits once when the pointer lifts.
*/
export function useResizableWidth(options: UseResizableWidthOptions): {
readonly width: number;
@@ -49,19 +47,9 @@ export function useResizableWidth(options: UseResizableWidthOptions): {
[defaultWidth, maxWidth, minWidth],
);
// No cross-tab subscription: panel width is per-window state.
const [width, setWidth] = useState<number>(() => {
if (typeof window === "undefined") return defaultWidth;
try {
const stored = getLocalStorageItem(storageKey, WidthSchema);
return clamp(stored ?? defaultWidth);
} catch (error) {
console.error("Could not read persisted panel width.", error);
return defaultWidth;
}
});
const clampedWidth = clamp(width);
const [storedWidth, setStoredWidth] = useLocalStorage(storageKey, defaultWidth, WidthSchema);
const [dragWidth, setDragWidth] = useState<number | null>(null);
const clampedWidth = clamp(dragWidth ?? storedWidth);
const dragStateRef = useRef<{
pointerId: number;
@@ -127,7 +115,7 @@ export function useResizableWidth(options: UseResizableWidthOptions): {
const active = dragStateRef.current;
if (!active) return;
active.rafId = null;
setWidth(active.pending);
setDragWidth(active.pending);
});
},
[clamp, edge],
@@ -139,24 +127,19 @@ export function useResizableWidth(options: UseResizableWidthOptions): {
if (!state || state.pointerId !== event.pointerId) return;
const finalWidth = clamp(state.pending);
releasePointer(event.pointerId);
// Commit once at drag-end to avoid 60Hz localStorage writes.
try {
setLocalStorageItem(storageKey, finalWidth, WidthSchema);
} catch (error) {
console.error("Could not persist panel width.", error);
}
setWidth(finalWidth);
setStoredWidth(finalWidth);
setDragWidth(null);
},
[clamp, releasePointer, storageKey],
[clamp, releasePointer, setStoredWidth],
);
const onPointerCancel = useCallback(
(event: ReactPointerEvent<HTMLElement>) => {
const state = dragStateRef.current;
if (!state || state.pointerId !== event.pointerId) return;
// Don't persist a cancelled drag; revert to the start width.
// Don't persist a cancelled drag; use the latest shared stored width.
releasePointer(event.pointerId);
setWidth(state.startWidth);
setDragWidth(null);
},
[releasePointer],
);
+59
View File
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";
import {
migratePersistedTerminalUiStateStoreState,
selectThreadTerminalCustomLabels,
selectThreadTerminalUiState,
useTerminalUiStateStore,
} from "./terminalUiStateStore";
@@ -18,6 +19,7 @@ describe("terminalUiStateStore actions", () => {
useTerminalUiStateStore.persist.clearStorage();
useTerminalUiStateStore.setState({
terminalUiStateByThreadKey: {},
terminalCustomLabelsByThreadKey: {},
suppressedTerminalIdsByThreadKey: {},
});
});
@@ -212,9 +214,53 @@ describe("terminalUiStateStore actions", () => {
});
});
it("normalizes persisted terminal labels", () => {
const migrated = migratePersistedTerminalUiStateStoreState(
{
terminalCustomLabelsByThreadKey: {
[scopedThreadKey(THREAD_REF)]: {
" term-1 ": " API server ",
empty: " ",
invalid: 42,
},
"legacy-thread-id": { "term-2": "Ignored" },
},
},
4,
);
expect(migrated).toEqual({
terminalUiStateByThreadKey: {},
terminalCustomLabelsByThreadKey: {
[scopedThreadKey(THREAD_REF)]: { "term-1": "API server" },
},
});
});
it("sets and clears a terminal label", () => {
const store = useTerminalUiStateStore.getState();
store.setTerminalCustomLabel(THREAD_REF, "term-1", " API server ");
expect(
selectThreadTerminalCustomLabels(
useTerminalUiStateStore.getState().terminalCustomLabelsByThreadKey,
THREAD_REF,
),
).toEqual({ "term-1": "API server" });
store.setTerminalCustomLabel(THREAD_REF, "term-1", null);
expect(
selectThreadTerminalCustomLabels(
useTerminalUiStateStore.getState().terminalCustomLabelsByThreadKey,
THREAD_REF,
),
).toEqual({});
});
it("resets to default and clears persisted entry when closing the last terminal", () => {
const store = useTerminalUiStateStore.getState();
store.newTerminal(THREAD_REF, "terminal-only");
store.setTerminalCustomLabel(THREAD_REF, "terminal-only", "Build");
store.closeTerminal(THREAD_REF, "terminal-only");
expect(
@@ -226,6 +272,12 @@ describe("terminalUiStateStore actions", () => {
THREAD_REF,
).terminalIds,
).toEqual([]);
expect(
selectThreadTerminalCustomLabels(
useTerminalUiStateStore.getState().terminalCustomLabelsByThreadKey,
THREAD_REF,
),
).toEqual({});
});
it("keeps a valid active terminal after closing an active split terminal", () => {
@@ -248,6 +300,8 @@ describe("terminalUiStateStore actions", () => {
it("reconciles terminal ids from an external ordered list", () => {
const store = useTerminalUiStateStore.getState();
store.setTerminalOpen(THREAD_REF, true);
store.setTerminalCustomLabel(THREAD_REF, "term-a", "API server");
store.setTerminalCustomLabel(THREAD_REF, "stale-term", "Old task");
store.reconcileTerminalIds(THREAD_REF, ["term-a", "term-b"]);
const terminalUiState = selectThreadTerminalUiState(
@@ -260,6 +314,11 @@ describe("terminalUiStateStore actions", () => {
{ id: "group-term-a", terminalIds: ["term-a"] },
{ id: "group-term-b", terminalIds: ["term-b"] },
]);
expect(
useTerminalUiStateStore.getState().terminalCustomLabelsByThreadKey[
scopedThreadKey(THREAD_REF)
],
).toEqual({ "term-a": "API server" });
});
it("does not import a closed panel terminal from stale metadata", () => {
+154 -16
View File
@@ -32,8 +32,11 @@ const TERMINAL_UI_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
interface PersistedTerminalUiStateStoreState {
terminalUiStateByThreadKey?: Record<string, ThreadTerminalUiState>;
terminalStateByThreadKey?: Record<string, ThreadTerminalUiState>;
terminalCustomLabelsByThreadKey?: Record<string, Record<string, string>>;
}
const EMPTY_TERMINAL_CUSTOM_LABELS: Readonly<Record<string, string>> = Object.freeze({});
export function migratePersistedTerminalUiStateStoreState(
persistedState: unknown,
_version: number,
@@ -50,8 +53,32 @@ export function migratePersistedTerminalUiStateStoreState(
parseScopedThreadKey(threadKey),
),
);
const terminalCustomLabelsByThreadKey = Object.fromEntries(
Object.entries(candidate.terminalCustomLabelsByThreadKey ?? {}).flatMap(
([threadKey, labels]) => {
if (!parseScopedThreadKey(threadKey) || !labels || typeof labels !== "object") return [];
const normalizedLabels = Object.fromEntries(
Object.entries(labels).flatMap(([terminalId, label]) => {
const normalizedTerminalId = terminalId.trim();
const normalizedLabel = typeof label === "string" ? label.trim().slice(0, 80) : "";
return normalizedTerminalId && normalizedLabel
? [[normalizedTerminalId, normalizedLabel] as const]
: [];
}),
);
return Object.keys(normalizedLabels).length > 0
? [[threadKey, normalizedLabels] as const]
: [];
},
),
);
return { terminalUiStateByThreadKey };
return {
terminalUiStateByThreadKey,
...(Object.keys(terminalCustomLabelsByThreadKey).length > 0
? { terminalCustomLabelsByThreadKey }
: {}),
};
}
function createTerminalUiStateStorage() {
@@ -489,6 +516,18 @@ export function selectThreadTerminalUiState(
);
}
export function selectThreadTerminalCustomLabels(
terminalCustomLabelsByThreadKey: Record<string, Record<string, string>>,
threadRef: ScopedThreadRef | null | undefined,
): Readonly<Record<string, string>> {
if (!threadRef || threadRef.threadId.length === 0) {
return EMPTY_TERMINAL_CUSTOM_LABELS;
}
return (
terminalCustomLabelsByThreadKey[terminalThreadKey(threadRef)] ?? EMPTY_TERMINAL_CUSTOM_LABELS
);
}
function updateTerminalUiStateByThreadKey(
terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>,
threadRef: ScopedThreadRef,
@@ -562,6 +601,7 @@ function removeRecordEntry<T>(record: Record<string, T>, key: string): Record<st
interface TerminalUiStateStoreState {
terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>;
terminalCustomLabelsByThreadKey: Record<string, Record<string, string>>;
/** Closed ids hidden from stale server metadata until that id is explicitly opened again. */
suppressedTerminalIdsByThreadKey: Record<string, string[]>;
setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void;
@@ -575,6 +615,11 @@ interface TerminalUiStateStoreState {
options?: { open?: boolean; active?: boolean },
) => void;
setActiveTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
setTerminalCustomLabel: (
threadRef: ScopedThreadRef,
terminalId: string,
label: string | null,
) => void;
closeTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
reconcileTerminalIds: (threadRef: ScopedThreadRef, nextIds: string[]) => void;
clearTerminalUiState: (threadRef: ScopedThreadRef) => void;
@@ -591,7 +636,12 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
state: ThreadTerminalUiState,
suppressedTerminalIds: readonly string[],
) => ThreadTerminalUiState,
suppression?: { terminalId: string; suppressed: boolean },
suppression?: {
terminalId: string;
suppressed: boolean;
clearCustomLabel?: boolean;
},
pruneCustomLabels = false,
) => {
set((state) => {
const threadKey = terminalThreadKey(threadRef);
@@ -609,21 +659,57 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
suppression.suppressed,
)
: state.suppressedTerminalIdsByThreadKey;
const terminalIdToClear = suppression?.clearCustomLabel
? suppression.terminalId.trim()
: "";
const currentLabels = state.terminalCustomLabelsByThreadKey[threadKey] ?? {};
let nextTerminalCustomLabelsByThreadKey =
terminalIdToClear.length > 0 && currentLabels[terminalIdToClear] !== undefined
? Object.keys(currentLabels).length === 1
? removeRecordEntry(state.terminalCustomLabelsByThreadKey, threadKey)
: {
...state.terminalCustomLabelsByThreadKey,
[threadKey]: removeRecordEntry(currentLabels, terminalIdToClear),
}
: state.terminalCustomLabelsByThreadKey;
if (pruneCustomLabels) {
const survivingIds = new Set(
selectThreadTerminalUiState(nextTerminalUiStateByThreadKey, threadRef).terminalIds,
);
const labelsForThread = nextTerminalCustomLabelsByThreadKey[threadKey] ?? {};
const survivingLabels = Object.fromEntries(
Object.entries(labelsForThread).filter(([terminalId]) =>
survivingIds.has(terminalId),
),
);
if (Object.keys(survivingLabels).length !== Object.keys(labelsForThread).length) {
nextTerminalCustomLabelsByThreadKey =
Object.keys(survivingLabels).length > 0
? {
...nextTerminalCustomLabelsByThreadKey,
[threadKey]: survivingLabels,
}
: removeRecordEntry(nextTerminalCustomLabelsByThreadKey, threadKey);
}
}
if (
nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey &&
nextSuppressedTerminalIdsByThreadKey === state.suppressedTerminalIdsByThreadKey
nextSuppressedTerminalIdsByThreadKey === state.suppressedTerminalIdsByThreadKey &&
nextTerminalCustomLabelsByThreadKey === state.terminalCustomLabelsByThreadKey
) {
return state;
}
return {
terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey,
terminalCustomLabelsByThreadKey: nextTerminalCustomLabelsByThreadKey,
};
});
};
return {
terminalUiStateByThreadKey: {},
terminalCustomLabelsByThreadKey: {},
suppressedTerminalIdsByThreadKey: {},
setTerminalOpen: (threadRef, open) => {
const terminalState = selectThreadTerminalUiState(
@@ -682,22 +768,56 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
),
setActiveTerminal: (threadRef, terminalId) =>
updateTerminal(threadRef, (state) => setThreadActiveTerminal(state, terminalId)),
setTerminalCustomLabel: (threadRef, terminalId, label) =>
set((state) => {
const normalizedTerminalId = terminalId.trim();
if (normalizedTerminalId.length === 0) return state;
const threadKey = terminalThreadKey(threadRef);
const currentLabels = state.terminalCustomLabelsByThreadKey[threadKey] ?? {};
const normalizedLabel = label?.trim().slice(0, 80) ?? "";
if (normalizedLabel.length > 0) {
if (currentLabels[normalizedTerminalId] === normalizedLabel) return state;
return {
terminalCustomLabelsByThreadKey: {
...state.terminalCustomLabelsByThreadKey,
[threadKey]: { ...currentLabels, [normalizedTerminalId]: normalizedLabel },
},
};
}
if (currentLabels[normalizedTerminalId] === undefined) return state;
const { [normalizedTerminalId]: _removed, ...remainingLabels } = currentLabels;
return {
terminalCustomLabelsByThreadKey:
Object.keys(remainingLabels).length > 0
? {
...state.terminalCustomLabelsByThreadKey,
[threadKey]: remainingLabels,
}
: removeRecordEntry(state.terminalCustomLabelsByThreadKey, threadKey),
};
}),
closeTerminal: (threadRef, terminalId) =>
updateTerminal(threadRef, (state) => closeThreadTerminal(state, terminalId), {
terminalId,
suppressed: true,
clearCustomLabel: true,
}),
reconcileTerminalIds: (threadRef, nextIds) =>
updateTerminal(threadRef, (state, suppressedTerminalIds) => {
if (suppressedTerminalIds.length === 0) {
return reconcileThreadTerminalSessionIds(state, nextIds);
}
const suppressedIds = new Set(suppressedTerminalIds);
return reconcileThreadTerminalSessionIds(
state,
nextIds.filter((terminalId) => !suppressedIds.has(terminalId)),
);
}),
updateTerminal(
threadRef,
(state, suppressedTerminalIds) => {
if (suppressedTerminalIds.length === 0) {
return reconcileThreadTerminalSessionIds(state, nextIds);
}
const suppressedIds = new Set(suppressedTerminalIds);
return reconcileThreadTerminalSessionIds(
state,
nextIds.filter((terminalId) => !suppressedIds.has(terminalId)),
);
},
undefined,
true,
),
clearTerminalUiState: (threadRef) =>
set((state) => {
const threadKey = terminalThreadKey(threadRef);
@@ -708,14 +828,20 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
);
const hadSuppressedTerminalIds =
state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined;
const hadCustomLabels = state.terminalCustomLabelsByThreadKey[threadKey] !== undefined;
if (
nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey &&
!hadSuppressedTerminalIds
!hadSuppressedTerminalIds &&
!hadCustomLabels
) {
return state;
}
return {
terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
terminalCustomLabelsByThreadKey: removeRecordEntry(
state.terminalCustomLabelsByThreadKey,
threadKey,
),
suppressedTerminalIdsByThreadKey: removeRecordEntry(
state.suppressedTerminalIdsByThreadKey,
threadKey,
@@ -728,7 +854,8 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
const hadTerminalUiState = state.terminalUiStateByThreadKey[threadKey] !== undefined;
const hadSuppressedTerminalIds =
state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined;
if (!hadTerminalUiState && !hadSuppressedTerminalIds) {
const hadCustomLabels = state.terminalCustomLabelsByThreadKey[threadKey] !== undefined;
if (!hadTerminalUiState && !hadSuppressedTerminalIds && !hadCustomLabels) {
return state;
}
return {
@@ -736,6 +863,10 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
state.terminalUiStateByThreadKey,
threadKey,
),
terminalCustomLabelsByThreadKey: removeRecordEntry(
state.terminalCustomLabelsByThreadKey,
threadKey,
),
suppressedTerminalIdsByThreadKey: removeRecordEntry(
state.suppressedTerminalIdsByThreadKey,
threadKey,
@@ -747,6 +878,7 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
const orphanedIds = new Set(
[
...Object.keys(state.terminalUiStateByThreadKey),
...Object.keys(state.terminalCustomLabelsByThreadKey),
...Object.keys(state.suppressedTerminalIdsByThreadKey),
].filter((key) => !activeThreadKeys.has(key)),
);
@@ -757,12 +889,17 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
const nextSuppressedTerminalIdsByThreadKey = {
...state.suppressedTerminalIdsByThreadKey,
};
const nextTerminalCustomLabelsByThreadKey = {
...state.terminalCustomLabelsByThreadKey,
};
for (const id of orphanedIds) {
delete nextTerminalUiStateByThreadKey[id];
delete nextTerminalCustomLabelsByThreadKey[id];
delete nextSuppressedTerminalIdsByThreadKey[id];
}
return {
terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
terminalCustomLabelsByThreadKey: nextTerminalCustomLabelsByThreadKey,
suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey,
};
}),
@@ -770,11 +907,12 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
},
{
name: TERMINAL_UI_STATE_STORAGE_KEY,
version: 4,
version: 5,
storage: createJSONStorage(createTerminalUiStateStorage),
migrate: migratePersistedTerminalUiStateStoreState,
partialize: (state) => ({
terminalUiStateByThreadKey: state.terminalUiStateByThreadKey,
terminalCustomLabelsByThreadKey: state.terminalCustomLabelsByThreadKey,
}),
},
),