diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 2e30e67e75..1f25f0c8e5 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -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} /> ))} diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts index e60d1d7167..2bb76cde37 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.test.ts +++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts @@ -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( diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index cf2adaca2c..66e316af08 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -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 ( + + + } + > + {children} + + {label} + + ); +} 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; } -interface TerminalActionButtonProps { - label: string; - className: string; - onClick: () => void; - children: ReactNode; -} - -function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) { - return ( - - } - > - {children} - - - {label} - - - ); -} - 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(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(); for (const terminalId of normalizedTerminalIds) { next.set(terminalId, terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId)); } return next; }, [normalizedTerminalIds, terminalLabelsById]); + const terminalLabelById = useMemo(() => { + const next = new Map(); + 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}

No terminal sessions for this thread yet.

-
@@ -1406,7 +1495,41 @@ export default function ThreadTerminalDrawer({ } const activeTerminalLaunchLocation = resolveTerminalLaunchLocation(resolvedActiveTerminalId); - + const compactTerminalToolbar = ( + <> + + + + + + + + + + closeTerminalSafely(resolvedActiveTerminalId)} + > + + + {!isPanel && onHide ? ( + <> + + + + + + ) : null} + + ); return ( ); diff --git a/apps/web/src/hooks/useResizableWidth.ts b/apps/web/src/hooks/useResizableWidth.ts index 08c067471f..6a9a364d91 100644 --- a/apps/web/src/hooks/useResizableWidth.ts +++ b/apps/web/src/hooks/useResizableWidth.ts @@ -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(() => { - 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(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) => { 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], ); diff --git a/apps/web/src/terminalUiStateStore.test.ts b/apps/web/src/terminalUiStateStore.test.ts index b0b1df96e1..f62c735dd1 100644 --- a/apps/web/src/terminalUiStateStore.test.ts +++ b/apps/web/src/terminalUiStateStore.test.ts @@ -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", () => { diff --git a/apps/web/src/terminalUiStateStore.ts b/apps/web/src/terminalUiStateStore.ts index 290ca8e595..545e195a12 100644 --- a/apps/web/src/terminalUiStateStore.ts +++ b/apps/web/src/terminalUiStateStore.ts @@ -32,8 +32,11 @@ const TERMINAL_UI_STATE_STORAGE_KEY = "t3code:terminal-state:v1"; interface PersistedTerminalUiStateStoreState { terminalUiStateByThreadKey?: Record; terminalStateByThreadKey?: Record; + terminalCustomLabelsByThreadKey?: Record>; } +const EMPTY_TERMINAL_CUSTOM_LABELS: Readonly> = 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>, + threadRef: ScopedThreadRef | null | undefined, +): Readonly> { + if (!threadRef || threadRef.threadId.length === 0) { + return EMPTY_TERMINAL_CUSTOM_LABELS; + } + return ( + terminalCustomLabelsByThreadKey[terminalThreadKey(threadRef)] ?? EMPTY_TERMINAL_CUSTOM_LABELS + ); +} + function updateTerminalUiStateByThreadKey( terminalUiStateByThreadKey: Record, threadRef: ScopedThreadRef, @@ -562,6 +601,7 @@ function removeRecordEntry(record: Record, key: string): Record; + terminalCustomLabelsByThreadKey: Record>; /** Closed ids hidden from stale server metadata until that id is explicitly opened again. */ suppressedTerminalIdsByThreadKey: Record; 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()( 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()( 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()( ), 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()( ); 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()( 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()( state.terminalUiStateByThreadKey, threadKey, ), + terminalCustomLabelsByThreadKey: removeRecordEntry( + state.terminalCustomLabelsByThreadKey, + threadKey, + ), suppressedTerminalIdsByThreadKey: removeRecordEntry( state.suppressedTerminalIdsByThreadKey, threadKey, @@ -747,6 +878,7 @@ export const useTerminalUiStateStore = create()( 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()( 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()( }, { name: TERMINAL_UI_STATE_STORAGE_KEY, - version: 4, + version: 5, storage: createJSONStorage(createTerminalUiStateStorage), migrate: migratePersistedTerminalUiStateStoreState, partialize: (state) => ({ terminalUiStateByThreadKey: state.terminalUiStateByThreadKey, + terminalCustomLabelsByThreadKey: state.terminalCustomLabelsByThreadKey, }), }, ),