Compare commits

...
Author SHA1 Message Date
maria-rcks 63ecfa9b64 feat(web): improve terminal workspace controls 2026-08-15 22:10:38 -04:00
maria-rcks 2dd5525de4 feat(web): refresh pull request details 2026-08-15 22:10:34 -04:00
17 changed files with 1382 additions and 968 deletions

No files matched your search

+26 -11
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;
@@ -6160,7 +6175,6 @@ function ChatViewContent(props: ChatViewProps) {
? "thread"
: "page"
}
chromeVariant="collapse"
composerDraftTarget={composerDraftTarget}
onStateChange={handlePullRequestTabStatusChange}
/>
@@ -6605,6 +6619,7 @@ function ChatViewContent(props: ChatViewProps) {
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
keybindings={keybindings}
onHide={hideTerminal}
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
+19 -2
View File
@@ -1,4 +1,5 @@
import { ChevronDownIcon } from "lucide-react";
import type { ReactNode } from "react";
import { Button } from "./ui/button";
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
@@ -6,6 +7,8 @@ import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./u
export interface HeaderFilterMenuOption<Value extends string> {
value: Value;
label: string;
icon?: ReactNode;
disabledReason?: string;
}
export function HeaderFilterMenu<Value extends string>({
@@ -38,8 +41,22 @@ export function HeaderFilterMenu<Value extends string>({
<MenuPopup align={align} side="bottom" className={popupClassName ?? "min-w-40"}>
<MenuRadioGroup value={current.value} onValueChange={(next) => onChange(next as Value)}>
{options.map((option) => (
<MenuRadioItem key={option.value} value={option.value}>
{option.label}
<MenuRadioItem
key={option.value}
value={option.value}
disabled={option.disabledReason !== undefined}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
<span className="flex min-w-0 items-center gap-2">
{option.icon}
{option.label}
</span>
{option.disabledReason !== undefined ? (
<span className="ms-auto text-xs text-muted-foreground">
{option.disabledReason || "Unavailable"}
</span>
) : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
@@ -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>
);
@@ -12,6 +12,7 @@ interface PanelLayoutControlsProps {
rightPanelAvailable: boolean;
rightPanelOpen: boolean;
rightPanelShortcutLabel: string | null;
rightPanelUnavailableLabel?: string;
/** Running + waiting subagents in this thread; badges the right panel toggle. */
liveAgentCount: number;
onToggleTerminal: () => void;
@@ -26,6 +27,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
rightPanelAvailable,
rightPanelOpen,
rightPanelShortcutLabel,
rightPanelUnavailableLabel = "Right panel is unavailable",
liveAgentCount,
onToggleTerminal,
onToggleRightPanel,
@@ -94,7 +96,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
? ` · ${liveAgentCount} ${liveAgentCount === 1 ? "agent" : "agents"} working`
: ""
}`
: "Right panel is unavailable"}
: rightPanelUnavailableLabel}
</TooltipPopup>
</Tooltip>
</div>
File diff suppressed because it is too large. Load diff
@@ -45,13 +45,11 @@ export function PullRequestListGhost({
<GhostBar className="size-4 rounded-full" />
<div className="min-w-0 space-y-1.5">
<GhostBar className={cn("h-3.5", TITLE_WIDTHS[index % TITLE_WIDTHS.length])} />
<GhostBar
className={cn("bg-muted-foreground/10", META_WIDTHS[index % META_WIDTHS.length])}
/>
<GhostBar className={META_WIDTHS[index % META_WIDTHS.length]} />
</div>
<div className="flex flex-col items-end gap-1.5">
<GhostBar className="w-12" />
<GhostBar className="w-16 bg-muted-foreground/10" />
<GhostBar className="w-16" />
</div>
</div>
))}
@@ -59,32 +57,101 @@ export function PullRequestListGhost({
);
}
/** The summary's own shape: a title, a byline, the facts rows, the description. */
/**
* The detail panel's current expanded shape. Keeping the chrome, summary facts, and description
* boundaries in the ghost prevents the loaded pull request from replacing one layout with
* another a moment later.
*/
export function PullRequestDetailGhost() {
return (
<div
role="status"
aria-label="Loading pull request"
className="animate-ghost-pulse space-y-6 px-4 py-5"
className="animate-ghost-pulse flex h-full min-h-0 flex-col overflow-hidden bg-background"
>
<div className="space-y-2">
<GhostBar className="h-5 w-4/5" />
<GhostBar className="w-2/5 bg-muted-foreground/10" />
</div>
<div className="space-y-3">
{Array.from({ length: 4 }, (_, index) => (
<div key={index} className="flex items-center gap-3">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-20 bg-muted-foreground/10" />
<GhostBar className={TITLE_WIDTHS[(index + 1) % TITLE_WIDTHS.length]} />
<div className="shrink-0 border-b border-border/60">
<div className="flex h-7 items-center justify-between gap-3 px-4">
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<GhostBar className="w-24" />
<GhostBar className="w-9" />
</div>
))}
<div className="flex shrink-0 items-center gap-1">
<GhostBar className="h-5 w-16 rounded-md" />
<GhostBar className="size-5 rounded-md" />
</div>
</div>
<div className="px-4 pb-4 pt-1">
<GhostBar className="h-5 w-4/5 max-w-md" />
<div className="mt-2 flex items-center gap-1.5">
<GhostBar className="size-4 rounded-full" />
<GhostBar className="w-24" />
</div>
<div className="mt-4 flex min-w-0 items-center gap-2">
<GhostBar className="h-6 w-24 rounded-md" />
<GhostBar className="size-3 rounded-full" />
<GhostBar className="h-6 w-32 rounded-md" />
<div className="ml-auto flex shrink-0 items-center gap-2">
<GhostBar className="w-10" />
<GhostBar className="w-20" />
</div>
</div>
</div>
<div className="flex min-h-10 items-center justify-between gap-3 border-t border-border/60 px-4 py-2">
<div className="flex items-center gap-1 p-0.5">
<GhostBar className="h-6 w-16 rounded-md" />
<GhostBar className="h-6 w-16 rounded-md" />
<GhostBar className="h-6 w-12 rounded-md" />
</div>
<GhostBar className="w-20" />
</div>
</div>
<div className="space-y-2 pt-1">
<GhostBar className="w-full bg-muted-foreground/10" />
<GhostBar className="w-11/12 bg-muted-foreground/10" />
<GhostBar className="w-4/5 bg-muted-foreground/10" />
<GhostBar className="w-2/3 bg-muted-foreground/10" />
<div className="min-h-0 flex-1 overflow-hidden">
<section className="px-4 py-3">
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2">
<div className="flex items-center gap-1.5">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-14" />
</div>
<div className="flex items-center gap-1">
<GhostBar className="size-4 rounded-full" />
<GhostBar className="size-4 rounded-full" />
<GhostBar className="ml-1 size-5 rounded-md" />
</div>
</div>
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2">
<div className="flex items-center gap-1.5">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-10" />
</div>
<div className="flex items-center gap-1">
<GhostBar className="h-5 w-24 rounded-full" />
<GhostBar className="h-5 w-20 rounded-full" />
</div>
</div>
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2">
<div className="flex items-center gap-1.5">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-14" />
</div>
<GhostBar className="w-20" />
</div>
</section>
<section className="border-t border-border/60">
<div className="flex min-h-11 items-center gap-1.5 px-4 py-3">
<GhostBar className="h-4 w-24" />
<GhostBar className="size-3.5 rounded-full" />
</div>
<div className="space-y-2 px-4 pb-4">
<GhostBar className="w-full" />
<GhostBar className="w-11/12" />
<GhostBar className="w-4/5" />
<GhostBar className="w-2/3" />
</div>
</section>
</div>
</div>
);
@@ -113,7 +180,7 @@ export function PullRequestTimelineGhost({ rows = 6 }: { rows?: number }) {
<div key={index} className="relative pb-5">
<GhostBar className="absolute -left-[1.55rem] top-1 size-2 rounded-full" />
<GhostBar className={cn("h-3.5", TITLE_WIDTHS[index % TITLE_WIDTHS.length])} />
<GhostBar className="mt-1.5 w-16 bg-muted-foreground/10" />
<GhostBar className="mt-1.5 w-16" />
</div>
))}
</div>
@@ -134,8 +201,8 @@ export function PullRequestConversationGhost({ rows = 3 }: { rows?: number }) {
<GhostBar className="size-5 shrink-0 rounded-full" />
<div className="flex-1 space-y-1.5">
<GhostBar className={META_WIDTHS[index % META_WIDTHS.length]} />
<GhostBar className="w-full bg-muted-foreground/10" />
<GhostBar className="w-3/4 bg-muted-foreground/10" />
<GhostBar className="w-full" />
<GhostBar className="w-3/4" />
</div>
</div>
))}
@@ -25,6 +25,7 @@ import { cn } from "~/lib/utils";
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
import { ProjectFavicon } from "../ProjectFavicon";
import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
import { Button } from "../ui/button";
import {
Menu,
@@ -261,12 +262,14 @@ export function PullRequestFiltersMenu({
return (
<Menu>
<MenuTrigger
className={cn(
// The icon-button size that pairs with a full-height input, so the two read as one strip.
"relative inline-flex size-9 shrink-0 items-center justify-center rounded-lg border border-input text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground sm:size-8",
filtered && "text-foreground",
)}
aria-label="Filter pull requests"
render={
<Button
className={cn("relative", filtered && "[--control-icon-color:currentColor]")}
size="icon"
variant="outline"
aria-label="Filter pull requests"
/>
}
>
<ListFilterIcon className="size-4" />
{filtered ? (
@@ -196,12 +196,12 @@ function MetaRow({
children: ReactNode;
}) {
return (
<div className="flex items-center gap-2 py-1.5 text-xs">
<span className="flex w-24 shrink-0 items-center gap-1.5 text-muted-foreground">
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2 py-1.5 text-xs">
<span className="flex min-w-0 items-center gap-1.5 text-muted-foreground">
{icon}
{label}
</span>
<span className="min-w-0 flex-1 text-foreground">{children}</span>
<span className="min-w-0 text-foreground">{children}</span>
</div>
);
}
@@ -16,6 +16,7 @@ import {
groupPullRequestTimelineConversations,
handoffPrompt,
handoffReviewComments,
isStackedPullRequestBase,
isThreadOwnPullRequest,
orderPullRequestComments,
pullRequestActionMenuHasGroup,
@@ -101,6 +102,47 @@ describe("pull request composer target", () => {
});
});
describe("stacked pull request classification", () => {
it("requires a known default branch", () => {
expect(isStackedPullRequestBase("main", [{ name: "main", isDefault: false }])).toBe(false);
});
it("recognizes local and remote forms of the default branch", () => {
expect(
isStackedPullRequestBase("main", [{ name: "main", isDefault: true, isRemote: false }]),
).toBe(false);
expect(
isStackedPullRequestBase("main", [
{ name: "origin/main", isDefault: true, isRemote: true, remoteName: "origin" },
]),
).toBe(false);
});
it("classifies a non-default base as stacked once the default is known", () => {
expect(
isStackedPullRequestBase("feature-base", [
{ name: "origin/main", isDefault: true, isRemote: true, remoteName: "origin" },
]),
).toBe(true);
});
it("does not mistake a nested branch suffix for the default branch", () => {
expect(
isStackedPullRequestBase("main", [
{
name: "origin/feature/main",
isDefault: true,
isRemote: true,
remoteName: "origin",
},
]),
).toBe(true);
expect(
isStackedPullRequestBase("1.0", [{ name: "release/1.0", isDefault: true, isRemote: false }]),
).toBe(true);
});
});
describe("ordering comments", () => {
it("reverses the chronological list for newest first, and leaves oldest first alone", () => {
const comments = [{ createdAt: "a" }, { createdAt: "b" }, { createdAt: "c" }];
@@ -10,6 +10,7 @@ import type {
PullRequestReviewThread,
PullRequestState,
PullRequestUpdateMethod,
VcsRef,
} from "@t3tools/contracts";
import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/reviewCommentContext";
@@ -73,6 +74,20 @@ export function pullRequestActionMenuHasGroup(
return showsDraftToggle || showsAutoMerge || showsMergeMethods;
}
export function isStackedPullRequestBase(
baseBranch: string,
refs: ReadonlyArray<Pick<VcsRef, "name" | "isDefault" | "isRemote" | "remoteName">>,
): boolean {
const defaultRef = refs.find((refName) => refName.isDefault);
if (!defaultRef) return false;
if (defaultRef.isRemote !== true) return defaultRef.name !== baseBranch;
const remotePrefix = `${defaultRef.remoteName ?? defaultRef.name.split("/")[0]}/`;
const defaultBranch = defaultRef.name.startsWith(remotePrefix)
? defaultRef.name.slice(remotePrefix.length)
: defaultRef.name;
return defaultBranch !== baseBranch;
}
/** Plain-language state, shown beside the author. Conflicts are a merge signal, not a state. */
export function describePullRequestState(state: PullRequestState, isDraft: boolean): string {
if (state === "merged") return "Merged";
+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],
);
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
changeRequestRepositoryUrl,
findProjectForChangeRequest,
openPullRequestLink,
parseChangeRequestUrl,
@@ -8,6 +9,24 @@ import {
shouldOpenPullRequestExternally,
} from "./openPullRequestLink";
describe("changeRequestRepositoryUrl", () => {
it("preserves repository path casing", () => {
expect(
changeRequestRepositoryUrl(
"https://gitlab.example.test/Team/Platform/Repo/-/merge_requests/42/diffs#note_1",
),
).toBe("https://gitlab.example.test/Team/Platform/Repo");
});
it("keeps pull-like segments inside nested GitLab repository paths", () => {
expect(
changeRequestRepositoryUrl(
"https://gitlab.example.test/group/pull/123/repo/-/merge_requests/42",
),
).toBe("https://gitlab.example.test/group/pull/123/repo");
});
});
describe("openPullRequestLink", () => {
it("opens the requested pull request URL", async () => {
const openExternal = vi.fn(async () => undefined);
+17
View File
@@ -118,6 +118,23 @@ export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | nu
return null;
}
/** The repository root behind a recognised change-request URL, without PR-specific state. */
export function changeRequestRepositoryUrl(targetUrl: string): string | null {
const changeRequest = parseChangeRequestUrl(targetUrl);
if (changeRequest === null) return null;
const url = new URL(targetUrl);
const repositoryPath =
/^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
/^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
url.pathname,
)?.[1];
if (!repositoryPath) return null;
url.pathname = repositoryPath;
url.search = "";
url.hash = "";
return url.toString();
}
function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
const repository = match?.[1];
const number = Number(match?.[2]);
+80 -73
View File
@@ -13,7 +13,6 @@ import type {
} from "@t3tools/contracts";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {
ChevronDownIcon,
EyeIcon,
MonitorIcon,
ServerIcon,
@@ -69,14 +68,20 @@ import { PullRequestListGhost } from "../components/pullRequest/PullRequestGhost
import { PullRequestRow } from "../components/pullRequest/PullRequestRow";
import { PullRequestsUnavailableState } from "../components/pullRequest/PullRequestsUnavailableState";
import { RightPanelTabs, type PullRequestTabStatus } from "../components/RightPanelTabs";
import { HeaderFilterMenu, type HeaderFilterMenuOption } from "../components/HeaderFilterMenu";
import {
WorkspaceBreadcrumb,
WorkspaceBreadcrumbItem,
WorkspaceBreadcrumbSeparator,
} from "../components/WorkspaceBreadcrumb";
import {
WorkspacePageContainer,
WorkspacePageHeader,
WorkspacePageHeaderEdgeControl,
} from "../components/WorkspacePageContainer";
import { isElectron } from "../env";
import { PanelLayoutControls } from "../components/chat/PanelLayoutControls";
import { Button } from "../components/ui/button";
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../components/ui/menu";
import { SidebarInset } from "../components/ui/sidebar";
import { useLiveRefresh } from "../hooks/useLiveRefresh";
import {
@@ -99,7 +104,6 @@ import {
import { useAtomCommand } from "../state/use-atom-command";
import { cn } from "~/lib/utils";
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
export interface PullRequestsSearch {
readonly involvement: PullRequestInvolvement;
@@ -1181,6 +1185,17 @@ function PullRequestsRouteView() {
: null,
[search.number, search.repository, selectedProject],
);
const linkedSelectionMatchesSurface =
linkedSelection !== null &&
selectedPullRequestSurface !== null &&
linkedSelection.environmentId === selectedPullRequestSurface.environmentId &&
linkedSelection.projectId === selectedPullRequestSurface.projectId &&
linkedSelection.repository === selectedPullRequestSurface.repository &&
linkedSelection.number === selectedPullRequestSurface.number;
// A closed panel keeps its tabs so reopening does not discard work. Those retained tabs are
// history, though, not a current selection: without this check they leave the toggle looking
// available after the selected pull request has been cleared.
const rightPanelAvailable = activePullRequestSurface !== null || linkedSelectionMatchesSurface;
useEffect(() => {
if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
@@ -1294,9 +1309,10 @@ function PullRequestsRouteView() {
terminalAvailable={false}
terminalOpen={false}
terminalShortcutLabel={null}
rightPanelAvailable={rightPanelState.surfaces.length > 0}
rightPanelAvailable={rightPanelAvailable}
rightPanelOpen={rightPanelState.isOpen}
rightPanelShortcutLabel={null}
rightPanelUnavailableLabel="Select a pull request first"
liveAgentCount={0}
onToggleTerminal={() => undefined}
onToggleRightPanel={toggleRightPanel}
@@ -1603,7 +1619,6 @@ function PullRequestsRouteView() {
reviewingQuery.refresh();
}}
onStateChange={handlePullRequestTabStatusChange}
chromeVariant="collapse"
/>
</RightPanelTabs>
) : null}
@@ -1612,10 +1627,7 @@ function PullRequestsRouteView() {
);
}
/**
* A compact stand-in for one pill group: the trigger wears the current choice, the choices
* live in a menu. Same options, same handler — only the footprint changes.
*/
/** Adapts pull-request filter metadata to the shared header menu. */
function CompactFilterMenu<Value extends string>({
label,
value,
@@ -1627,37 +1639,18 @@ function CompactFilterMenu<Value extends string>({
options: ReadonlyArray<PullRequestFilterOption<Value>>;
onChange: (value: Value) => void;
}) {
const current = options.find((option) => option.value === value) ?? options[0]!;
const headerOptions = useMemo<ReadonlyArray<HeaderFilterMenuOption<Value>>>(
() =>
options.map((option) => ({
value: option.value,
label: option.label,
icon: <option.Icon aria-hidden className="size-3.5" />,
...(option.unavailable !== undefined ? { disabledReason: option.unavailable } : {}),
})),
[options],
);
return (
<Menu>
<MenuTrigger
aria-label={label}
className="inline-flex h-7 shrink-0 items-center gap-1 rounded-md px-1.5 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
>
{current.label}
<ChevronDownIcon aria-hidden className="size-3 text-muted-foreground/70" />
</MenuTrigger>
<MenuPopup align="start" side="bottom" className="min-w-40">
<MenuRadioGroup value={value} onValueChange={(next) => onChange(next as Value)}>
{options.map((option) => (
<MenuRadioItem
key={option.value}
value={option.value}
// A host the server has already said it cannot read is not a choice here either.
// The pills disable it; a menu that offers it would answer the press by replacing
// a working list with the same failure the pill row exists to explain.
disabled={option.unavailable !== undefined}
title={option.unavailable}
>
<span className="flex min-w-0 items-center gap-2">
<option.Icon aria-hidden className="size-3.5" />
{option.label}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuPopup>
</Menu>
<HeaderFilterMenu label={label} value={value} options={headerOptions} onChange={onChange} />
);
}
@@ -1827,18 +1820,10 @@ function PullRequestsColumn({
// Painted flat like the chat column: the inset underneath carries the chrome grain, and a
// content surface that lets it show reads as a different background than every thread.
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
<header
className={cn(
"drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1.5 px-3 sm:px-5",
// A closed right panel leaves this column full-width, so its header runs
// underneath the native window controls on Windows; reserve the inset the
// way Settings and the chat view do. While the panel is open the column
// ends at the panel's left edge and the absolute controls strip (already
// WCO-aware) owns the top-right corner.
!rightPanelOpen && "wco:pr-[var(--workspace-native-controls-inset)]",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
{/* A closed right panel leaves this column full-width, so the shared header
reserves native window controls. While the panel is open, the column ends
at the panel and the absolute controls strip owns the top-right corner. */}
<WorkspacePageHeader electron={isElectron} reserveNativeControls={!rightPanelOpen}>
{condensed ? (
<WorkspaceBreadcrumb ariaLabel="Pull request scope">
{/* The page name remains the foreground anchor in both states; the live filters are
@@ -1880,27 +1865,24 @@ function PullRequestsColumn({
)}
<div className="min-w-0 flex-1" />
{condensed ? (
<ExpandableSearch
searchInput={searchInput}
searchValue={searchValue}
open={searchOpen}
onOpenChange={setSearchOpen}
focusToken={searchFocusToken}
onFocusWithin={(focused) => {
topbarSearchFocusedRef.current = focused;
}}
/>
<div className="flex shrink-0 items-center gap-1.5">
<ExpandableSearch
searchInput={searchInput}
searchValue={searchValue}
open={searchOpen}
onOpenChange={setSearchOpen}
focusToken={searchFocusToken}
onFocusWithin={(focused) => {
topbarSearchFocusedRef.current = focused;
}}
/>
<PullRequestRefreshControl compact refreshing={refreshing} onRefresh={onRefresh} />
</div>
) : null}
<Button
size="icon-sm"
variant="ghost"
aria-label="Refresh pull requests"
onClick={onRefresh}
>
<RefreshCwIcon className={cn("size-4", refreshing && "animate-spin")} />
</Button>
{rightPanelControl}
</header>
{rightPanelControl ? (
<WorkspacePageHeaderEdgeControl>{rightPanelControl}</WorkspacePageHeaderEdgeControl>
) : null}
</WorkspacePageHeader>
<div
ref={scrollRef}
@@ -1909,19 +1891,44 @@ function PullRequestsColumn({
{/* The top padding is the fade band's own height (1.5rem here), the same pairing the
settings page makes: at rest the controls sit fully below the mask, and only
content actually passing under the chrome fades. */}
<div className="mx-auto flex w-full max-w-4xl flex-col gap-4 px-5 pt-6 pb-12">
<WorkspacePageContainer className="gap-4">
<div className="flex flex-col gap-3">
<div ref={inFlowSearchRef} className="flex items-center gap-2">
{searchInput}
{filtersMenu}
{!condensed ? (
<PullRequestRefreshControl refreshing={refreshing} onRefresh={onRefresh} />
) : null}
</div>
{/* Scrolled past this marker, the controls are gone and the title takes over. */}
<div ref={markerRef} aria-hidden className="-mt-3 h-px w-full" />
</div>
{listBody}
</div>
</WorkspacePageContainer>
</div>
</div>
);
}
function PullRequestRefreshControl({
compact = false,
refreshing,
onRefresh,
}: {
compact?: boolean;
refreshing: boolean;
onRefresh: () => void;
}) {
return (
<Button
size={compact ? "icon-sm" : "icon"}
variant={compact ? "ghost" : "outline"}
aria-label="Refresh pull requests"
onClick={onRefresh}
disabled={refreshing}
>
<RefreshCwIcon className={cn("size-4", refreshing && "animate-spin")} />
</Button>
);
}
+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,
}),
},
),