From 361df65ffb1d19c7974ede9c8132565176e24b48 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 24 Jun 2026 14:20:45 -0700 Subject: [PATCH] Map thread panel into title bar and sidebar - Add thread-panel presentation logic for inline vs popover layouts - Move thread details controls into the chat header/sidebar flow - Add shared wait-for-atom helper and workspace display name parsing Co-authored-by: codex --- .../src/state/use-thread-composer-state.ts | 6 +- .../components/BranchToolbar.logic.test.ts | 13 + .../web/src/components/BranchToolbar.logic.ts | 7 + apps/web/src/components/BranchToolbar.tsx | 38 ++ .../BranchToolbarBranchSelector.tsx | 43 ++- .../BranchToolbarEnvModeSelector.tsx | 112 ++++-- .../BranchToolbarEnvironmentSelector.tsx | 38 +- apps/web/src/components/ChatView.logic.ts | 43 +-- apps/web/src/components/ChatView.tsx | 349 ++++++++++-------- apps/web/src/components/GitActionsControl.tsx | 92 ++++- .../src/components/ProjectScriptsControl.tsx | 70 +++- apps/web/src/components/RightPanelTabs.tsx | 3 + apps/web/src/components/chat/ChatHeader.tsx | 59 +-- .../components/chat/PanelLayoutControls.tsx | 180 ++++++--- .../components/chat/ThreadDetailsPanel.tsx | 294 +++++++++++++++ .../chat/ThreadRelationshipsControl.tsx | 345 ++++++++++------- .../chat/threadDetailsPanelStyles.ts | 24 ++ .../components/preview/PreviewPanelShell.tsx | 73 ++-- .../preview/addBrowserSurface.test.ts | 2 +- .../KeybindingsSettings.logic.test.ts | 6 +- .../settings/KeybindingsSettings.logic.ts | 6 +- apps/web/src/components/ui/popover.tsx | 7 +- apps/web/src/diffFileActions.test.ts | 2 +- apps/web/src/hooks/useElementWidth.ts | 25 ++ .../src/hooks/usePreviewPanelInlineSize.ts | 49 +++ apps/web/src/keybindings.test.ts | 13 + apps/web/src/lib/threadRelationships.test.ts | 51 +++ apps/web/src/lib/threadRelationships.ts | 31 ++ apps/web/src/rightPanelLayout.test.ts | 19 + apps/web/src/rightPanelLayout.ts | 14 + apps/web/src/rightPanelStore.test.ts | 77 +++- apps/web/src/rightPanelStore.ts | 268 +++++++++++--- .../web/src/routes/debug.orchestration-v2.tsx | 10 +- apps/web/src/state/entities.ts | 10 + apps/web/src/state/waitForAtomValue.test.ts | 57 +++ apps/web/src/state/waitForAtomValue.ts | 56 +++ apps/web/src/uiStateStore.test.ts | 1 + .../src/state/shellReducer.test.ts | 8 +- packages/contracts/src/keybindings.test.ts | 6 + packages/contracts/src/keybindings.ts | 5 +- 40 files changed, 1890 insertions(+), 622 deletions(-) create mode 100644 apps/web/src/components/chat/ThreadDetailsPanel.tsx create mode 100644 apps/web/src/components/chat/threadDetailsPanelStyles.ts create mode 100644 apps/web/src/hooks/useElementWidth.ts create mode 100644 apps/web/src/hooks/usePreviewPanelInlineSize.ts create mode 100644 apps/web/src/rightPanelLayout.test.ts create mode 100644 apps/web/src/state/waitForAtomValue.test.ts create mode 100644 apps/web/src/state/waitForAtomValue.ts diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 8ae9470c87..adeddcea29 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -122,11 +122,7 @@ export function useThreadComposerState() { return null; } - return deriveActiveWorkStartedAt( - selectedThread.latestRun, - selectedThreadSessionActivity, - null, - ); + return deriveActiveWorkStartedAt(selectedThread.latestRun, selectedThreadSessionActivity, null); }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]); const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime); diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index 94a3909a96..5d4f9128db 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -11,6 +11,7 @@ import { resolveEnvModeLabel, resolveBranchToolbarValue, resolveLockedWorkspaceLabel, + resolveWorkspaceDisplayName, shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; @@ -168,6 +169,18 @@ describe("resolveLockedWorkspaceLabel", () => { }); }); +describe("resolveWorkspaceDisplayName", () => { + it("returns the final folder for POSIX and Windows paths", () => { + expect(resolveWorkspaceDisplayName("/repo/.t3/worktrees/feature-a")).toBe("feature-a"); + expect(resolveWorkspaceDisplayName("C:\\code\\project\\feature-b\\")).toBe("feature-b"); + }); + + it("handles missing and root paths", () => { + expect(resolveWorkspaceDisplayName(null)).toBeNull(); + expect(resolveWorkspaceDisplayName("/")).toBe("/"); + }); +}); + describe("deriveLocalBranchNameFromRemoteRef", () => { it("strips the remote prefix from a remote ref", () => { expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo"); diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 65388962c0..69a9acd0f2 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -54,6 +54,13 @@ export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): return activeWorktreePath ? "Worktree" : "Local checkout"; } +export function resolveWorkspaceDisplayName(path: string | null): string | null { + if (!path) return null; + const normalizedPath = path.replace(/[\\/]+$/, ""); + if (normalizedPath.length === 0) return path; + return normalizedPath.split(/[\\/]/).at(-1) ?? normalizedPath; +} + export function resolveEffectiveEnvMode(input: { activeWorktreePath: string | null; hasServerThread: boolean; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 03f24dac8e..6520e524aa 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -38,6 +38,8 @@ import { import { Separator } from "./ui/separator"; interface BranchToolbarProps { + layout?: "composer" | "panel"; + panelSection?: "all" | "workspace" | "branch"; environmentId: EnvironmentId; threadId: ThreadId; draftId?: DraftId; @@ -191,6 +193,8 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({ }); export const BranchToolbar = memo(function BranchToolbar({ + layout = "composer", + panelSection = "all", environmentId, threadId, draftId, @@ -238,6 +242,40 @@ export const BranchToolbar = memo(function BranchToolbar({ if (!hasActiveThread || !activeProject) return null; + if (layout === "panel") { + return ( +
+ {panelSection !== "branch" ? ( + + ) : null} + {panelSection !== "workspace" ? ( + + ) : null} +
+ ); + } + return (
{isMobile ? ( diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index ba1a53b358..4ea753eb52 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -28,6 +28,10 @@ import { threadEnvironment } from "../state/threads"; import { useAtomCommand } from "../state/use-atom-command"; import { vcsEnvironment } from "../state/vcs"; import { cn } from "../lib/utils"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_ROW_CLASS, +} from "./chat/threadDetailsPanelStyles"; import { parsePullRequestReference } from "../pullRequestReference"; import { getSourceControlPresentation } from "../sourceControlPresentation"; import { @@ -60,6 +64,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; interface BranchToolbarBranchSelectorProps { className?: string; + displayMode?: "toolbar" | "panel"; environmentId: EnvironmentId; threadId: ThreadId; draftId?: DraftId; @@ -94,6 +99,7 @@ function getBranchTriggerLabel(input: { export function BranchToolbarBranchSelector({ className, + displayMode = "toolbar", environmentId, threadId, draftId, @@ -637,7 +643,13 @@ export function BranchToolbarBranchSelector({ open={isBranchMenuOpen} value={resolvedActiveBranch} > -
+
{branchPr && branchPrStatus ? ( ) : null} } - className="min-w-0 text-muted-foreground/70 hover:text-foreground/80" + render={
- +
void; + displayMode?: "toolbar" | "panel"; } export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({ envLocked, effectiveEnvMode, activeWorktreePath, + workspaceRoot = null, onEnvModeChange, + displayMode = "toolbar", }: BranchToolbarEnvModeSelectorProps) { + const workspacePath = displayMode === "panel" ? (activeWorktreePath ?? workspaceRoot) : null; + const workspaceDisplayName = resolveWorkspaceDisplayName(workspacePath); + const workspaceKind = activeWorktreePath ? "Worktree" : "Project folder"; const envModeItems = useMemo( () => [ - { value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) }, + { + value: "local", + label: workspaceDisplayName ?? resolveCurrentWorkspaceLabel(activeWorktreePath), + }, { value: "worktree", label: resolveEnvModeLabel("worktree") }, ], - [activeWorktreePath], + [activeWorktreePath, workspaceDisplayName], ); if (envLocked) { - return ( - - {activeWorktreePath ? ( - <> - - {resolveLockedWorkspaceLabel(activeWorktreePath)} - - ) : ( - <> - - {resolveLockedWorkspaceLabel(activeWorktreePath)} - + const lockedRow = ( + + {activeWorktreePath ? ( + + ) : ( + + )} + + {workspaceDisplayName ?? resolveLockedWorkspaceLabel(activeWorktreePath)} + + {displayMode === "panel" ? ( + + {workspaceKind} + + ) : null} ); + + if (!workspacePath) return lockedRow; + + return ( + + + {workspacePath} + + ); } return ( @@ -63,16 +101,42 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe onValueChange={(value) => onEnvModeChange(value as EnvMode)} items={envModeItems} > - - {effectiveEnvMode === "worktree" ? ( - - ) : activeWorktreePath ? ( - - ) : ( - - )} - - + + + } + > + {effectiveEnvMode === "worktree" ? ( + + ) : activeWorktreePath ? ( + + ) : ( + + )} + + {displayMode === "panel" ? ( + + {effectiveEnvMode === "worktree" && !activeWorktreePath ? "Create" : workspaceKind} + + ) : null} + + {workspacePath ? {workspacePath} : null} + Workspace diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx index 35fc8b6a19..86b2416c7c 100644 --- a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx @@ -3,6 +3,12 @@ import { CloudIcon, MonitorIcon } from "lucide-react"; import { memo, useMemo } from "react"; import type { EnvironmentOption } from "./BranchToolbar.logic"; +import { cn } from "../lib/utils"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS, + THREAD_DETAILS_PANEL_ROW_CLASS, +} from "./chat/threadDetailsPanelStyles"; import { Select, SelectGroup, @@ -18,6 +24,7 @@ interface BranchToolbarEnvironmentSelectorProps { environmentId: EnvironmentId; availableEnvironments: readonly EnvironmentOption[]; onEnvironmentChange: (environmentId: EnvironmentId) => void; + displayMode?: "toolbar" | "panel"; } export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({ @@ -25,6 +32,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir environmentId, availableEnvironments, onEnvironmentChange, + displayMode = "toolbar", }: BranchToolbarEnvironmentSelectorProps) { const activeEnvironment = useMemo(() => { return availableEnvironments.find((env) => env.environmentId === environmentId) ?? null; @@ -41,11 +49,20 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir if (envLocked) { return ( - + {activeEnvironment?.isPrimary ? ( - + ) : ( - + )} {activeEnvironment?.label ?? "Run on"} @@ -59,11 +76,20 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir onValueChange={(value) => onEnvironmentChange(value as EnvironmentId)} items={environmentItems} > - + {activeEnvironment?.isPrimary ? ( - + ) : ( - + )} diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index d00b18151e..01dadc7099 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -16,6 +16,7 @@ import { type ComposerImageAttachment, type DraftThreadState } from "../composer import * as Schema from "effect/Schema"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentThreadDetails } from "../state/threads"; +import { waitForAtomValue } from "../state/waitForAtomValue"; import { filterTerminalContextsWithText, stripInlineTerminalContextPlaceholders, @@ -354,43 +355,11 @@ export async function waitForStartedServerThread( timeoutMs = 1_000, ): Promise { const threadAtom = environmentThreadDetails.detailAtom(threadRef); - const getThread = () => appAtomRegistry.get(threadAtom); - const thread = getThread(); - - if (threadHasStarted(thread)) { - return true; - } - - return await new Promise((resolve) => { - let settled = false; - let timeoutId: ReturnType | null = null; - const finish = (result: boolean) => { - if (settled) { - return; - } - settled = true; - if (timeoutId !== null) { - globalThis.clearTimeout(timeoutId); - } - unsubscribe(); - resolve(result); - }; - - const unsubscribe = appAtomRegistry.subscribe(threadAtom, (thread) => { - if (!threadHasStarted(thread)) { - return; - } - finish(true); - }); - - if (threadHasStarted(getThread())) { - finish(true); - return; - } - - timeoutId = globalThis.setTimeout(() => { - finish(false); - }, timeoutMs); + return waitForAtomValue({ + registry: appAtomRegistry, + atom: threadAtom, + predicate: threadHasStarted, + timeoutMs, }); } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 4a56563d3e..210f9e495d 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -21,10 +21,7 @@ import { TerminalOpenInput, } from "@t3tools/contracts"; import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell"; -import { - connectionStatusText, - type EnvironmentConnectionPresentation, -} from "@t3tools/client-runtime/connection"; +import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { parseScopedThreadKey, scopedThreadKey, @@ -114,10 +111,16 @@ import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; import { isCommandPaletteOpen } from "../commandPaletteContext"; import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git"; import { useMediaQuery } from "../hooks/useMediaQuery"; -import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout"; +import { useElementWidth } from "../hooks/useElementWidth"; +import { usePreviewPanelInlineSize } from "../hooks/usePreviewPanelInlineSize"; +import { + RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY, + resolveThreadPanelPresentation, +} from "../rightPanelLayout"; import { selectActiveRightPanel, selectActiveRightPanelSurface, + selectThreadPanelOpen, selectThreadRightPanelState, type RightPanelSurface, useRightPanelStore, @@ -134,11 +137,10 @@ import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic"; import { PreviewAutomationOwner } from "./preview/PreviewAutomationOwner"; import { RightPanelTabs } from "./RightPanelTabs"; import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider"; -import { BranchToolbar } from "./BranchToolbar"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; -import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react"; +import { ChevronDownIcon } from "lucide-react"; import { cn, randomHex } from "~/lib/utils"; import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { stackedThreadToast, toastManager } from "./ui/toast"; @@ -201,6 +203,7 @@ import { useThreadProposedPlans, useThreadRefs, useThreadVisibleTurnItems, + waitForThreadShell, } from "../state/entities"; import { environmentShell } from "../state/shell"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; @@ -208,13 +211,17 @@ import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; import { MessagesTimeline } from "./chat/MessagesTimeline"; import { ChatHeader } from "./chat/ChatHeader"; -import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls"; +import { + PanelLayoutControls, + type PanelLayoutControlsProps, + RightPanelMaximizeControl, +} from "./chat/PanelLayoutControls"; import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview"; +import { ThreadDetailsPanel, type ThreadDetailsPanelProps } from "./chat/ThreadDetailsPanel"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { resolveEffectiveEnvMode } from "./BranchToolbar.logic"; import { ProviderStatusBanner } from "./chat/ProviderStatusBanner"; import { ThreadErrorBanner } from "./chat/ThreadErrorBanner"; -import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { QueuedRunsControl } from "./chat/QueuedRunsControl"; import type { ComposerDispatchMode } from "./chat/composerDispatch"; import { @@ -245,7 +252,6 @@ import { sanitizeThreadErrorMessage } from "~/rpc/transportError"; import { RightPanelSheet } from "./RightPanelSheet"; import { previewEnvironment } from "../state/preview"; import { useAtomCommand } from "../state/use-atom-command"; -import { Button } from "./ui/button"; import { buildVersionMismatchDismissalKey, dismissVersionMismatch, @@ -1133,6 +1139,9 @@ function ChatViewContent(props: ChatViewProps) { const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] = useState>({}); const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY); + const [workspaceLayoutRef, workspaceLayoutWidth] = useElementWidth(); + const previewPanelInlineSize = usePreviewPanelInlineSize(); + const threadPanelPopoverAnchorRef = useRef(null); // Tracks whether the user explicitly dismissed the sidebar for the active turn. const planSidebarDismissedForTurnRef = useRef(null); // When set, the thread-change reset effect will open the sidebar instead of closing it. @@ -1354,6 +1363,18 @@ function ChatViewContent(props: ChatViewProps) { const rightPanelMaximized = canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey; const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet; + const threadPanelPresentation = resolveThreadPanelPresentation( + workspaceLayoutWidth, + inlineRightPanelOwnsTitleBar ? previewPanelInlineSize.width : 0, + rightPanelMaximized, + ); + const threadPanelOpen = useRightPanelStore((state) => + selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + activeThreadRef, + threadPanelPresentation, + ), + ); useEffect(() => { if (!activeThreadRef) return; @@ -1523,8 +1544,6 @@ function ChatViewContent(props: ChatViewProps) { }); return envs; }, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]); - const hasMultipleEnvironments = logicalProjectEnvironments.length > 1; - const openPullRequestDialog = useCallback( (reference?: string) => { if (!canCheckoutPullRequestIntoThread) { @@ -1682,73 +1701,18 @@ function ChatViewContent(props: ChatViewProps) { hasMultipleRegisteredEnvironments && activeThread ? `${environmentById.get(activeThread.environmentId)?.label ?? serverConfig?.environment.label ?? activeThread.environmentId} server` : "server"; - const composerBannerItems = useMemo(() => { - const items: ComposerBannerStackItem[] = []; - if (activeEnvironmentUnavailableState) { - const connection = activeEnvironmentUnavailableState.connection; - const isReconnecting = - connection.phase === "connecting" || connection.phase === "reconnecting"; - items.push({ - id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`, - variant: connection.phase === "error" ? "error" : "warning", - icon: , - title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusText(connection)}`, - description: - connection.error ?? - "Reconnect this environment before sending messages or running actions.", - actions: ( - <> - - - - ), - }); - } - if (showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey) { - items.push({ - id: `version-mismatch:${versionMismatchDismissKey}`, - variant: "warning", - icon: , - title: "Client and server versions differ", - description: ( - <> - Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "} - {versionMismatch.serverVersion}. Sync them if RPC calls or reconnects fail. - - ), - dismissLabel: "Dismiss version mismatch warning", - onDismiss: () => { - dismissVersionMismatch(versionMismatchDismissKey); - setDismissedVersionMismatchKey(versionMismatchDismissKey); - }, - }); - } - return items; - }, [ - activeEnvironmentUnavailableState, - handleReconnectActiveEnvironment, - navigate, - showVersionMismatchBanner, - versionMismatch, - versionMismatchDismissKey, - versionMismatchServerLabel, - ]); + const reconnectActiveEnvironment = useCallback(() => { + if (!activeEnvironmentUnavailableState) return; + void handleReconnectActiveEnvironment(activeEnvironmentUnavailableState.environmentId); + }, [activeEnvironmentUnavailableState, handleReconnectActiveEnvironment]); + const openConnectionSettings = useCallback(() => { + void navigate({ to: "/settings/connections" }); + }, [navigate]); + const handleDismissVersionMismatch = useCallback(() => { + if (!versionMismatchDismissKey) return; + dismissVersionMismatch(versionMismatchDismissKey); + setDismissedVersionMismatchKey(versionMismatchDismissKey); + }, [setDismissedVersionMismatchKey, versionMismatchDismissKey]); const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const unlockedSelectedProvider = resolveSelectableProvider( providerStatuses, @@ -2816,6 +2780,9 @@ function ChatViewContent(props: ChatViewProps) { useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); }, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]); + const openChangesFromThreadPanel = useCallback(() => { + addDiffSurface(); + }, [addDiffSurface]); const addFilesSurface = useCallback(() => { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().open(activeThreadRef, "files"); @@ -2979,6 +2946,14 @@ function ChatViewContent(props: ChatViewProps) { } useRightPanelStore.getState().toggleVisibility(activeThreadRef); }, [activeThreadRef, closePlanSidebar, closePreviewPanel, planSidebarOpen, rightPanelOpen]); + const toggleThreadPanel = useCallback(() => { + if (!activeThreadRef) return; + useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation); + }, [activeThreadRef, threadPanelPresentation]); + const closeThreadPanelPopover = useCallback(() => { + if (!activeThreadRef) return; + useRightPanelStore.getState().setThreadPanelOpen(activeThreadRef, "popover", false); + }, [activeThreadRef]); const toggleRightPanelMaximized = useCallback(() => { if (!canMaximizeRightPanel) return; setMaximizedRightPanelThreadKey((threadKey) => @@ -3463,6 +3438,13 @@ function ChatViewContent(props: ChatViewProps) { return; } + if (command === "threadPanel.toggle") { + event.preventDefault(); + event.stopPropagation(); + toggleThreadPanel(); + return; + } + if (command === "terminal.split") { event.preventDefault(); event.stopPropagation(); @@ -3558,6 +3540,7 @@ function ChatViewContent(props: ChatViewProps) { keybindings, onToggleDiff, toggleRightPanel, + toggleThreadPanel, toggleTerminalVisibility, composerRef, ]); @@ -3691,6 +3674,7 @@ function ChatViewContent(props: ChatViewProps) { async (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => { if (!activeThread || activeEnvironmentUnavailable) return; const targetThreadId = newThreadId(); + const targetThreadRef = scopeThreadRef(environmentId, targetThreadId); const result = await forkThreadFromRun({ environmentId, input: { @@ -3710,9 +3694,17 @@ function ChatViewContent(props: ChatViewProps) { } return; } + const targetThreadReady = await waitForThreadShell(targetThreadRef); + if (!targetThreadReady) { + setThreadError( + activeThread.id, + "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.", + ); + return; + } await navigate({ to: "/$environmentId/$threadId", - params: buildThreadRouteParams(scopeThreadRef(environmentId, targetThreadId)), + params: buildThreadRouteParams(targetThreadRef), }); }, [ @@ -4443,6 +4435,7 @@ function ChatViewContent(props: ChatViewProps) { setComposerDraftInteractionMode, setThreadError, startThreadTurn, + activeThreadRef, autoOpenPlanSidebar, environmentId, composerRef, @@ -4780,29 +4773,6 @@ function ChatViewContent(props: ChatViewProps) { return ; } - const panelToggleControls = ( - - ); - const panelLayoutControls = ( -
- {rightPanelOpen && !shouldUsePlanSidebarSheet ? ( - - ) : null} - {panelToggleControls} -
- ); const rightPanelContent = activeThreadRef ? ( activeRightPanelSurface?.kind === "preview" ? ( @@ -4872,9 +4842,113 @@ function ChatViewContent(props: ChatViewProps) { ) : null ) : null; + const threadDetailsPanelProps: Omit = { + environmentId: activeThread.environmentId, + environmentConnection: activeEnvironment?.connection ?? null, + threadId: activeThread.id, + ...(draftId ? { draftId } : {}), + activeProjectName: activeProject?.title, + activeProjectScripts: activeProject?.scripts, + preferredScriptId: activeProject + ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) + : null, + keybindings, + gitCwd, + isGitRepo, + envLocked, + availableEnvironments: logicalProjectEnvironments, + onEnvironmentChange, + onEnvModeChange, + ...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {}), + ...(canOverrideServerThreadEnvMode + ? { + activeThreadBranchOverride: activeThreadBranch, + onActiveThreadBranchOverrideChange: setPendingServerThreadBranch, + } + : {}), + startFromOrigin, + onStartFromOriginChange, + ...(canCheckoutPullRequestIntoThread + ? { onCheckoutPullRequestRequest: openPullRequestDialog } + : {}), + onComposerFocusRequest: scheduleComposerFocus, + ...(isServerThread && isGitRepo ? { onOpenChanges: openChangesFromThreadPanel } : {}), + onReconnectEnvironment: reconnectActiveEnvironment, + onOpenConnectionSettings: openConnectionSettings, + versionMismatch: + showVersionMismatchBanner && versionMismatch + ? { + clientVersion: versionMismatch.clientVersion, + serverVersion: versionMismatch.serverVersion, + serverLabel: versionMismatchServerLabel, + } + : null, + onDismissVersionMismatch: handleDismissVersionMismatch, + onRunProjectScript: runProjectScript, + onAddProjectScript: saveProjectScript, + onUpdateProjectScript: updateProjectScript, + onDeleteProjectScript: deleteProjectScript, + }; + const panelToggleControlProps = { + terminalAvailable: activeProject !== null, + terminalOpen: terminalUiState.terminalOpen, + terminalShortcutLabel: shortcutLabelForCommand(keybindings, "terminal.toggle"), + threadPanelOpen, + threadPanelPresentation, + threadPanelPopoverAnchor: threadPanelPopoverAnchorRef, + ...(threadPanelPresentation === "popover" + ? { + threadPanelPopoverContent: ( + + ), + } + : {}), + threadPanelShortcutLabel: shortcutLabelForCommand(keybindings, "threadPanel.toggle"), + threadPanelHasAttention: + activeEnvironmentUnavailableState !== null || showVersionMismatchBanner, + rightPanelAvailable: activeProject !== null, + rightPanelOpen, + rightPanelShortcutLabel: shortcutLabelForCommand(keybindings, "rightPanel.toggle"), + onToggleTerminal: toggleTerminalVisibility, + onToggleThreadPanel: toggleThreadPanel, + onToggleRightPanel: toggleRightPanel, + } satisfies PanelLayoutControlsProps; + const panelToggleControls = ( + + ); + const threadPanelHeaderControl = ( +
+ +
+ ); + const panelLayoutControls = ( +
+ {rightPanelOpen && !shouldUsePlanSidebarSheet ? ( + + ) : null} + {panelToggleControls} +
+ ); return ( -
+
{isElectron && activeThreadRef ? ( ) : null} @@ -4888,9 +4962,10 @@ function ChatViewContent(props: ChatViewProps) { > {/* Top bar */}
- {!rightPanelOpen ? panelLayoutControls : null} + {inlineRightPanelOwnsTitleBar + ? threadPanelHeaderControl + : !rightPanelOpen + ? panelLayoutControls + : null}
@@ -5008,7 +5076,6 @@ function ChatViewContent(props: ChatViewProps) { threadId={activeThread.id} /> ) : null} -
-
- {isGitRepo && ( -
- -
- )} -
+
{pullRequestDialogState ? ( @@ -5143,6 +5174,9 @@ function ChatViewContent(props: ChatViewProps) { ) : null}
{/* end chat column */} + {threadPanelOpen && threadPanelPresentation === "inline" ? ( + + ) : null}
{/* end horizontal flex container */} @@ -5170,6 +5204,7 @@ function ChatViewContent(props: ChatViewProps) { ) : null} - {expandedImage && ( void; } interface PendingDefaultBranchAction { @@ -344,11 +355,13 @@ function GitActionItemIcon({ function GitQuickActionIcon({ quickAction, SourceControlIcon, + className = "size-3.5", }: { quickAction: GitQuickAction; SourceControlIcon: ReturnType["Icon"]; + className?: string; }) { - const iconClassName = "size-3.5"; + const iconClassName = className; if (quickAction.kind === "open_pr") return ; if (quickAction.kind === "open_publish") return ; if (quickAction.kind === "run_pull") return ; @@ -970,7 +983,11 @@ export default function GitActionsControl({ gitCwd, activeThreadRef, draftId, + displayMode = "toolbar", + onOpenChanges, }: GitActionsControlProps) { + const isPanel = displayMode === "panel"; + const ActionGroup = isPanel ? "div" : Group; const updateThreadMetadata = useAtomCommand( threadEnvironment.updateMetadata, "thread branch metadata update", @@ -1659,6 +1676,7 @@ export default function GitActionsControl({ ) : ( - + {quickActionDisabledReason ? ( @@ -1701,8 +1726,14 @@ export default function GitActionsControl({ - + {quickAction.label} @@ -1714,16 +1745,30 @@ export default function GitActionsControl({ )} - + {isPanel ? ( + + )} + {isPanel && isRepo ? ( + + ) : null} + { diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 4438a671f5..c7a48f812e 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -59,6 +59,15 @@ import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover"; import { Switch } from "./ui/switch"; import { Textarea } from "./ui/textarea"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { cn } from "~/lib/utils"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_ROW_CLASS, + THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, + THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS, + THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS, + THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS, +} from "./chat/threadDetailsPanelStyles"; const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [ { id: "play", label: "Play" }, @@ -99,6 +108,7 @@ export interface NewProjectScriptInput { export type ProjectScriptActionResult = AtomCommandResult; interface ProjectScriptsControlProps { + displayMode?: "toolbar" | "panel"; scripts: ReadonlyArray; keybindings: ResolvedKeybindingsConfig; preferredScriptId?: string | null; @@ -112,6 +122,7 @@ interface ProjectScriptsControlProps { } export default function ProjectScriptsControl({ + displayMode = "toolbar", scripts, keybindings, preferredScriptId = null, @@ -120,6 +131,8 @@ export default function ProjectScriptsControl({ onUpdateScript, onDeleteScript, }: ProjectScriptsControlProps) { + const isPanel = displayMode === "panel"; + const ActionGroup = isPanel ? "div" : Group; const addScriptFormId = React.useId(); const [editingScriptId, setEditingScriptId] = useState(null); const [dialogOpen, setDialogOpen] = useState(false); @@ -250,29 +263,53 @@ export default function ProjectScriptsControl({ return ( <> {primaryScript ? ( - + onRunScript(primaryScript)} /> } > - - + + {primaryScript.name} Run {primaryScript.name} - + {isPanel ? ( + + ) : ( + + ) : null} +
+
+ + {connectionIssue ? ( +
+
+ +
+

Environment unavailable

+

+ {props.environmentConnection?.error ?? + "Reconnect this environment before sending messages or running actions."} +

+
+ + +
+
+
+
+ ) : null} + + {props.versionMismatch ? ( +
+ +
+

Client and server versions differ

+

+ Client {props.versionMismatch.clientVersion} · {props.versionMismatch.serverLabel}{" "} + {props.versionMismatch.serverVersion} +

+
+ +
+ ) : null} + +
+ {props.availableEnvironments.length > 1 ? ( + + ) : null} + + + + {props.activeProjectScripts ? ( + + ) : null} +
+ + + {props.gitCwd ? ( +
+
+

+ Version control +

+
+
+ {props.isGitRepo ? ( + + ) : null} + {props.activeProjectName ? ( + + ) : null} +
+
+ ) : null} + + {!props.draftId ? ( + + ) : null} +
+ ); + + if (props.mode === "popover") { + return
{card}
; + } + + return ( + + ); +} diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 58e495007e..90c45715c1 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -1,59 +1,71 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; import { useNavigate } from "@tanstack/react-router"; -import { ArrowRightIcon, GitBranchIcon, GitForkIcon, NetworkIcon, UnplugIcon } from "lucide-react"; -import { useMemo, useState } from "react"; +import { + ArrowRightIcon, + BotIcon, + GitBranchIcon, + GitForkIcon, + GitMergeIcon, + LoaderCircleIcon, + MoreHorizontalIcon, + UnplugIcon, +} from "lucide-react"; +import { useState } from "react"; import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; import { deriveThreadRelationshipGraph, - walkThreadRelationships, + immediateThreadRelationships, + resolveMergeBackTargetThreadId, + type ThreadRelationshipEdge, } from "../../lib/threadRelationships"; -import { buildThreadRouteParams } from "../../threadRoutes"; import { newThreadId } from "../../lib/utils"; -import { threadEnvironment } from "../../state/threads"; +import { buildThreadRouteParams } from "../../threadRoutes"; import { useThreadProjection, useThreadShells } from "../../state/entities"; +import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; +import { cn } from "../../lib/utils"; import { Button } from "../ui/button"; -import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -function relationshipLabel( - edge: ReturnType[number]["edge"], - currentThreadId: ThreadId, -) { - if (edge.kind === "transfer") return "context transfer"; +function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) { + if (edge.kind === "transfer") return "Context transfer"; if (edge.kind === "subagent") { - return edge.sourceThreadId === currentThreadId ? "subagent" : "parent agent"; + return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent"; } - return edge.sourceThreadId === currentThreadId ? "fork" : "source"; + return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread"; } -export function ThreadRelationshipsControl(props: { +function statusDotClass(status: string | null): string { + if (status === "running" || status === "in_progress") return "bg-info"; + if (status === "failed" || status === "error") return "bg-destructive"; + if (status === "completed") return "bg-success"; + return "bg-muted-foreground/45"; +} + +const MAX_VISIBLE_RELATIONSHIPS = 5; + +export function ThreadRelationshipsPanel(props: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; }) { const ref = scopeThreadRef(props.environmentId, props.threadId); const projection = useThreadProjection(ref)?.projection ?? null; - const activeShells = useThreadShells().filter( + const threadShells = useThreadShells(); + const activeShells = threadShells.filter( (thread) => thread.environmentId === props.environmentId, ); const archived = useArchivedThreadSnapshots([props.environmentId]); - const archivedShells = - archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot - .threads ?? []; - const shells = useMemo>( - () => [...activeShells.map((thread) => thread.source), ...archivedShells], - [activeShells, archivedShells], - ); - const graph = useMemo( - () => deriveThreadRelationshipGraph({ threads: shells, projection }), - [projection, shells], - ); - const relationshipRows = useMemo( - () => walkThreadRelationships(graph, props.threadId), - [graph, props.threadId], - ); + const archivedShells = archived.snapshots.find( + (entry) => entry.environmentId === props.environmentId, + )?.snapshot.threads; + const shells: ReadonlyArray = [ + ...activeShells.map((thread) => thread.source), + ...(archivedShells ?? []), + ]; + const graph = deriveThreadRelationshipGraph({ threads: shells, projection }); const navigate = useNavigate(); const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun); const mergeBack = useAtomCommand(threadEnvironment.mergeBack); @@ -79,19 +91,22 @@ export function ThreadRelationshipsControl(props: { const canFork = latestCompletedRun !== null && (canForkNatively || capabilities?.context.supportsFullThreadHandoff === true); - const parentThreadId = - projection?.thread.forkedFrom?.type === "run" - ? projection.thread.forkedFrom.threadId - : (projection?.thread.lineage.parentThreadId ?? null); - const canMerge = - parentThreadId !== null && - projection?.thread.lineage.relationshipToParent === "fork" && - latestCompletedRun !== null; + const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection); + const relationshipRows = immediateThreadRelationships(graph, props.threadId).toSorted( + (left, right) => + Number(right.threadId === mergeTargetThreadId) - + Number(left.threadId === mergeTargetThreadId), + ); + const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null; const canDetach = projection?.providerSessions.some( (session) => session.status !== "stopped" && session.status !== "error", ) ?? false; + if (relationshipRows.length === 0 && !canFork && mergeTargetThreadId === null && !canDetach) { + return null; + } + const openThread = (threadId: ThreadId) => { void navigate({ to: "/$environmentId/$threadId", @@ -117,18 +132,18 @@ export function ThreadRelationshipsControl(props: { }; const merge = async () => { - if (!latestCompletedRun || parentThreadId === null || busyAction !== null) return; + if (!latestCompletedRun || mergeTargetThreadId === null || busyAction !== null) return; setBusyAction("merge"); const result = await mergeBack({ environmentId: props.environmentId, input: { sourceThreadId: props.threadId, - targetThreadId: parentThreadId, + targetThreadId: mergeTargetThreadId, runId: latestCompletedRun.id, }, }); setBusyAction(null); - if (result._tag === "Success") openThread(parentThreadId); + if (result._tag === "Success") openThread(mergeTargetThreadId); }; const detach = async () => { @@ -141,103 +156,165 @@ export function ThreadRelationshipsControl(props: { setBusyAction(null); }; + const visibleRows = relationshipRows.slice(0, MAX_VISIBLE_RELATIONSHIPS); + const hiddenRelationshipCount = relationshipRows.length - visibleRows.length; + const parentTitle = + mergeTargetThreadId === null + ? null + : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null); + return ( - - - - } +
+
+

+ Lineage +

+
+ {canFork ? ( + + ) : null} + {canDetach ? ( + + + } + > + + + + void detach()}> + + Disconnect agent session + + + + ) : null}
-
- {relationshipRows.length === 0 ? ( -

- This thread has no related threads yet. -

- ) : ( -
    - {relationshipRows.map(({ threadId, fromThreadId, depth, edge }) => { - const node = graph.nodes.get(threadId); - return ( -
  • -
+ + {visibleRows.length > 0 ? ( +
    + {visibleRows.map(({ threadId, edge }) => { + const node = graph.nodes.get(threadId); + const isSubagent = edge.kind === "subagent"; + const isMergeTarget = threadId === mergeTargetThreadId; + const RelationshipIcon = isSubagent ? BotIcon : GitBranchIcon; + const relationship = relationshipLabel(edge, props.threadId); + const threadTitle = node?.thread?.title ?? threadId; + return ( +
  • + + openThread(threadId)} + className="flex min-h-11 min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left disabled:cursor-not-allowed disabled:opacity-55" + > + + + - - {node?.missing - ? "Missing from the current shell" - : relationshipLabel(edge, fromThreadId)} - {edge?.status ? ` · ${edge.status}` : ""} + + + {threadTitle} + + + {node?.missing + ? "Unavailable" + : `${relationship}${edge.status ? ` · ${edge.status.replaceAll("_", " ")}` : ""}`} + - - - -
  • - ); - })} -
- )} -
-
- - - -
- - + + + } + /> + + {node?.missing + ? "This related thread is unavailable" + : `Open ${relationship.toLowerCase()} in this chat`} + + + + {isMergeTarget ? ( + + + + + } + /> + + {latestCompletedRun === null + ? "Complete a run in this fork before merging it back" + : parentTitle + ? `Merge this conversation back into ${parentTitle}` + : "Merge this conversation back into its source"} + + + ) : null} + + ); + })} + + ) : null} + + {hiddenRelationshipCount > 0 ? ( +

+ {hiddenRelationshipCount} more direct relationship + {hiddenRelationshipCount === 1 ? "" : "s"} +

+ ) : null} +
); } diff --git a/apps/web/src/components/chat/threadDetailsPanelStyles.ts b/apps/web/src/components/chat/threadDetailsPanelStyles.ts new file mode 100644 index 0000000000..6cdf4096b3 --- /dev/null +++ b/apps/web/src/components/chat/threadDetailsPanelStyles.ts @@ -0,0 +1,24 @@ +/** + * Visual primitives shared by controls when they are rendered in the thread details panel. + * + * The core control variants intentionally become denser at the `sm` breakpoint. The panel has + * its own fixed density, so every size and type override here includes its desktop counterpart. + */ +export const THREAD_DETAILS_PANEL_ROW_CLASS = + "h-9 w-full justify-start gap-2.5 rounded-lg border-transparent bg-transparent px-2.5 text-[13px] font-medium text-foreground/80 shadow-none before:shadow-none sm:h-9 sm:text-[13px]"; + +export const THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS = + "h-9 w-full justify-start gap-2.5 rounded-lg border border-transparent px-2.5 text-[13px] font-medium text-foreground/80 sm:h-9 sm:text-[13px]"; + +export const THREAD_DETAILS_PANEL_ICON_CLASS = "size-4 shrink-0 text-muted-foreground"; + +export const THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS = + "group/thread-details-action flex w-full items-center rounded-lg transition-colors hover:bg-muted/65 focus-within:bg-muted/65"; + +export const THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS = + "h-9 min-w-0 flex-1 justify-start gap-2.5 rounded-e-none border-transparent bg-transparent px-2.5 pr-2 text-[13px] font-medium text-foreground/80 shadow-none before:shadow-none sm:h-9 sm:text-[13px] [&:hover]:bg-transparent [&[data-pressed]]:bg-transparent"; + +export const THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS = + "h-9 w-8 rounded-s-none border-transparent bg-transparent px-0 shadow-none before:shadow-none sm:h-9 sm:w-8 [&:hover]:bg-transparent [&[data-pressed]]:bg-transparent"; + +export const THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS = "h-4 w-px shrink-0 bg-border/65"; diff --git a/apps/web/src/components/preview/PreviewPanelShell.tsx b/apps/web/src/components/preview/PreviewPanelShell.tsx index 6de828c1e6..a0b05e4934 100644 --- a/apps/web/src/components/preview/PreviewPanelShell.tsx +++ b/apps/web/src/components/preview/PreviewPanelShell.tsx @@ -1,41 +1,47 @@ -import { type ReactNode, useEffect, useState } from "react"; +import { type ReactNode } from "react"; import { isElectron } from "~/env"; -import { useResizableWidth } from "~/hooks/useResizableWidth"; +import { + type PreviewPanelInlineSize, + usePreviewPanelInlineSize, +} from "~/hooks/usePreviewPanelInlineSize"; import { cn } from "~/lib/utils"; import { RightPanelResizeHandle } from "./RightPanelResizeHandle"; export type PreviewPanelMode = "inline" | "sheet" | "sidebar" | "embedded"; -const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width"; -const PREVIEW_PANEL_MIN_WIDTH = 360; -/** Hard ceiling so a wide monitor can't yield a panel that swallows the chat. */ -const PREVIEW_PANEL_MAX_WIDTH_PX = 1400; -/** Fraction of the viewport allowed; the panel is min(this · vw, MAX_PX). */ -const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7; -const PREVIEW_PANEL_DEFAULT_WIDTH = 540; - /** * Shell for the preview panel. In inline mode the panel is user-resizable * via a drag handle on the left edge; width persists per browser. In * sheet/sidebar modes the parent owns the size. */ -export function PreviewPanelShell(props: { +interface PreviewPanelShellProps { mode: PreviewPanelMode; maximized?: boolean; + inlineSize?: PreviewPanelInlineSize; children: ReactNode; -}) { +} + +export function PreviewPanelShell(props: PreviewPanelShellProps) { + if (props.inlineSize) { + return ; + } + + return ; +} + +function ResizablePreviewPanelShell(props: PreviewPanelShellProps) { + const inlineSize = usePreviewPanelInlineSize(); + return ; +} + +function PreviewPanelShellFrame( + props: PreviewPanelShellProps & { inlineSize: PreviewPanelInlineSize }, +) { const useDragRegion = isElectron && props.mode !== "sheet" && props.mode !== "embedded"; const isInline = props.mode === "inline"; - const maxWidth = useViewportClampedMaxWidth(); - const { width, handlers } = useResizableWidth({ - storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY, - defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH, - minWidth: PREVIEW_PANEL_MIN_WIDTH, - maxWidth, - edge: "left", - }); + const { width, handlers } = props.inlineSize; return (
); } - -/** - * Track viewport width to derive a sensible upper bound for the panel. - * Resize-aware so dragging the OS window narrower re-clamps the stored - * width on the next render (the hook's clamp picks this up automatically). - */ -function useViewportClampedMaxWidth(): number { - const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth)); - useEffect(() => { - if (typeof window === "undefined") return; - let frame = 0; - const onResize = () => { - // Coalesce rapid resize events into one rAF tick. - if (frame !== 0) return; - frame = window.requestAnimationFrame(() => { - frame = 0; - setVw(window.innerWidth); - }); - }; - window.addEventListener("resize", onResize); - return () => { - window.removeEventListener("resize", onResize); - if (frame !== 0) window.cancelAnimationFrame(frame); - }; - }, []); - return Math.min(PREVIEW_PANEL_MAX_WIDTH_PX, Math.floor(vw * PREVIEW_PANEL_MAX_WIDTH_FRACTION)); -} diff --git a/apps/web/src/components/preview/addBrowserSurface.test.ts b/apps/web/src/components/preview/addBrowserSurface.test.ts index 5dfc1a42e9..3e8ed345e6 100644 --- a/apps/web/src/components/preview/addBrowserSurface.test.ts +++ b/apps/web/src/components/preview/addBrowserSurface.test.ts @@ -27,7 +27,7 @@ const snapshot = (tabId: string): PreviewSessionSnapshot => ({ beforeEach(() => { resetPreviewStateForTests(); - useRightPanelStore.setState({ byThreadKey: {} }); + useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} }); }); describe("addBrowserSurface", () => { diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 75235a0530..7c86e644ca 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -134,7 +134,7 @@ describe("KeybindingsSettings.logic", () => { expect(options).not.toContain("customModeActive"); }); - it("builds command options from defaults and resolved project bindings", () => { + it("builds command options from built-ins and resolved project bindings", () => { const options = buildKeybindingCommandOptions([ { command: "script.setup-db.run", @@ -149,7 +149,9 @@ describe("KeybindingsSettings.logic", () => { }, ] satisfies ResolvedKeybindingsConfig); - expect(options).toEqual(expect.arrayContaining(["chat.new", "script.setup-db.run"])); + expect(options).toEqual( + expect.arrayContaining(["chat.new", "threadPanel.toggle", "script.setup-db.run"]), + ); }); it("reports unknown when variables without rejecting parseable expressions", () => { diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index da54e86e42..80ac6ce0ad 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -1,4 +1,5 @@ import { + BUILT_IN_KEYBINDING_COMMANDS, type KeybindingCommand, type KeybindingShortcut, type KeybindingWhenNode, @@ -255,10 +256,7 @@ export function buildWhenVariableOptions(): ReadonlyArray { export function buildKeybindingCommandOptions( keybindings: ResolvedKeybindingsConfig, ): ReadonlyArray { - const commands = new Set(); - for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) { - commands.add(binding.command); - } + const commands = new Set(BUILT_IN_KEYBINDING_COMMANDS); for (const binding of keybindings) { commands.add(binding.command); } diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsx index de0e2e55df..dd64bb2c14 100644 --- a/apps/web/src/components/ui/popover.tsx +++ b/apps/web/src/components/ui/popover.tsx @@ -19,6 +19,7 @@ function PopoverTrigger({ className, children, ...props }: PopoverPrimitive.Trig function PopoverPopup({ children, className, + positionerClassName, viewportClassName, side = "bottom", align = "center", @@ -28,6 +29,7 @@ function PopoverPopup({ anchor, ...props }: PopoverPrimitive.Popup.Props & { + positionerClassName?: string; viewportClassName?: string; side?: PopoverPrimitive.Positioner.Props["side"]; align?: PopoverPrimitive.Positioner.Props["align"]; @@ -42,7 +44,10 @@ function PopoverPopup({ align={align} alignOffset={alignOffset} anchor={anchor} - className="z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none" + className={cn( + "z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none", + positionerClassName, + )} data-slot="popover-positioner" side={side} sideOffset={sideOffset} diff --git a/apps/web/src/diffFileActions.test.ts b/apps/web/src/diffFileActions.test.ts index 9c358ab1d2..37755b84c9 100644 --- a/apps/web/src/diffFileActions.test.ts +++ b/apps/web/src/diffFileActions.test.ts @@ -12,7 +12,7 @@ const THREAD_REF = scopeThreadRef( describe("openDiffFilePrimaryAction", () => { beforeEach(() => { - useRightPanelStore.setState({ byThreadKey: {} }); + useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} }); }); it("opens diff files in the thread file viewer", () => { diff --git a/apps/web/src/hooks/useElementWidth.ts b/apps/web/src/hooks/useElementWidth.ts new file mode 100644 index 0000000000..d3f60eeea1 --- /dev/null +++ b/apps/web/src/hooks/useElementWidth.ts @@ -0,0 +1,25 @@ +import { useLayoutEffect, useState } from "react"; + +export function useElementWidth() { + const [element, setElement] = useState(null); + const [width, setWidth] = useState(null); + + useLayoutEffect(() => { + if (!element) return; + + const update = (nextWidth: number) => { + setWidth((currentWidth) => (currentWidth === nextWidth ? currentWidth : nextWidth)); + }; + + update(element.getBoundingClientRect().width); + if (typeof ResizeObserver === "undefined") return; + + const observer = new ResizeObserver(([entry]) => { + if (entry) update(entry.contentRect.width); + }); + observer.observe(element); + return () => observer.disconnect(); + }, [element]); + + return [setElement, width] as const; +} diff --git a/apps/web/src/hooks/usePreviewPanelInlineSize.ts b/apps/web/src/hooks/usePreviewPanelInlineSize.ts new file mode 100644 index 0000000000..0e5de1198f --- /dev/null +++ b/apps/web/src/hooks/usePreviewPanelInlineSize.ts @@ -0,0 +1,49 @@ +import { useEffect, useState } from "react"; + +import { type ResizableWidthHandlers, useResizableWidth } from "./useResizableWidth"; + +export interface PreviewPanelInlineSize { + readonly width: number; + readonly handlers: ResizableWidthHandlers; +} + +const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width"; +const PREVIEW_PANEL_MIN_WIDTH = 360; +/** Hard ceiling so a wide monitor can't yield a panel that swallows the chat. */ +const PREVIEW_PANEL_MAX_WIDTH_PX = 1400; +/** Fraction of the viewport allowed; the panel is min(this · vw, MAX_PX). */ +const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7; +const PREVIEW_PANEL_DEFAULT_WIDTH = 540; + +export function usePreviewPanelInlineSize(): PreviewPanelInlineSize { + const maxWidth = useViewportClampedMaxWidth(); + return useResizableWidth({ + storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY, + defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH, + minWidth: PREVIEW_PANEL_MIN_WIDTH, + maxWidth, + edge: "left", + }); +} + +/** Keep the resizable panel's upper bound in sync with the current window. */ +function useViewportClampedMaxWidth(): number { + const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth)); + useEffect(() => { + if (typeof window === "undefined") return; + let frame = 0; + const onResize = () => { + if (frame !== 0) return; + frame = window.requestAnimationFrame(() => { + frame = 0; + setVw(window.innerWidth); + }); + }; + window.addEventListener("resize", onResize); + return () => { + window.removeEventListener("resize", onResize); + if (frame !== 0) window.cancelAnimationFrame(frame); + }; + }, []); + return Math.min(PREVIEW_PANEL_MAX_WIDTH_PX, Math.floor(vw * PREVIEW_PANEL_MAX_WIDTH_FRACTION)); +} diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index c0d326edd5..3785bf6229 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -514,6 +514,19 @@ describe("chat/editor shortcuts", () => { ); }); + it("resolves a user-configured thread panel shortcut without assigning a default", () => { + const bindings = compile([ + { shortcut: modShortcut("b", { shiftKey: true }), command: "threadPanel.toggle" }, + ]); + + assert.strictEqual( + resolveShortcutCommand(event({ key: "b", metaKey: true, shiftKey: true }), bindings, { + platform: "MacIntel", + }), + "threadPanel.toggle", + ); + }); + it("matches diff.toggle shortcut outside terminal focus", () => { assert.isTrue( isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, { diff --git a/apps/web/src/lib/threadRelationships.test.ts b/apps/web/src/lib/threadRelationships.test.ts index f00c37def1..3b4206e1f0 100644 --- a/apps/web/src/lib/threadRelationships.test.ts +++ b/apps/web/src/lib/threadRelationships.test.ts @@ -3,7 +3,9 @@ import { ThreadId } from "@t3tools/contracts"; import { deriveThreadRelationshipGraph, + immediateThreadRelationships, relatedThreadIds, + resolveMergeBackTargetThreadId, walkThreadRelationships, } from "./threadRelationships"; @@ -41,5 +43,54 @@ describe("thread relationships", () => { [child, 1], [missing, 2], ]); + expect(immediateThreadRelationships(graph, root).map(({ threadId }) => threadId)).toEqual([ + child, + ]); + }); + + it("resolves merge-back only for forks and prefers the recorded fork source", () => { + const source = ThreadId.make("thread-source"); + const fallbackParent = ThreadId.make("thread-parent"); + const fork = ThreadId.make("thread-fork"); + + expect( + resolveMergeBackTargetThreadId({ + thread: { + id: fork, + forkedFrom: { type: "run", threadId: source, runId: "run-source" }, + lineage: { + rootThreadId: source, + parentThreadId: fallbackParent, + relationshipToParent: "fork", + }, + }, + } as never), + ).toBe(source); + expect( + resolveMergeBackTargetThreadId({ + thread: { + id: fork, + forkedFrom: null, + lineage: { + rootThreadId: source, + parentThreadId: fallbackParent, + relationshipToParent: "fork", + }, + }, + } as never), + ).toBe(fallbackParent); + expect( + resolveMergeBackTargetThreadId({ + thread: { + id: fork, + forkedFrom: null, + lineage: { + rootThreadId: source, + parentThreadId: fallbackParent, + relationshipToParent: "subagent", + }, + }, + } as never), + ).toBeNull(); }); }); diff --git a/apps/web/src/lib/threadRelationships.ts b/apps/web/src/lib/threadRelationships.ts index c126389c9b..d57c5a468b 100644 --- a/apps/web/src/lib/threadRelationships.ts +++ b/apps/web/src/lib/threadRelationships.ts @@ -31,6 +31,15 @@ export interface ThreadRelationshipWalkRow { readonly edge: ThreadRelationshipEdge; } +export function resolveMergeBackTargetThreadId( + projection: Pick | null, +): ThreadId | null { + if (projection?.thread.lineage.relationshipToParent !== "fork") return null; + return projection.thread.forkedFrom?.type === "run" + ? projection.thread.forkedFrom.threadId + : projection.thread.lineage.parentThreadId; +} + function edgeKey(edge: ThreadRelationshipEdge): string { return `${edge.sourceThreadId}\u001f${edge.targetThreadId}\u001f${edge.kind}`; } @@ -137,3 +146,25 @@ export function walkThreadRelationships( return rows; } + +export function immediateThreadRelationships( + graph: ThreadRelationshipGraph, + threadId: ThreadId, +): ReadonlyArray { + const visited = new Set(); + const rows: ThreadRelationshipWalkRow[] = []; + + for (const edge of graph.edges) { + const relatedId = + edge.sourceThreadId === threadId + ? edge.targetThreadId + : edge.targetThreadId === threadId + ? edge.sourceThreadId + : null; + if (relatedId === null || visited.has(relatedId)) continue; + visited.add(relatedId); + rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge }); + } + + return rows; +} diff --git a/apps/web/src/rightPanelLayout.test.ts b/apps/web/src/rightPanelLayout.test.ts new file mode 100644 index 0000000000..1440aa9a17 --- /dev/null +++ b/apps/web/src/rightPanelLayout.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveThreadPanelPresentation } from "./rightPanelLayout"; + +describe("resolveThreadPanelPresentation", () => { + it("uses the stable workspace width minus the real right panel width", () => { + expect(resolveThreadPanelPresentation(null, 0, false)).toBe("inline"); + expect(resolveThreadPanelPresentation(960, 0, false)).toBe("inline"); + expect(resolveThreadPanelPresentation(959, 0, false)).toBe("popover"); + + expect(resolveThreadPanelPresentation(1_400, 0, false)).toBe("inline"); + expect(resolveThreadPanelPresentation(1_400, 540, false)).toBe("popover"); + expect(resolveThreadPanelPresentation(1_500, 540, false)).toBe("inline"); + }); + + it("uses a popover while the real right panel is maximized", () => { + expect(resolveThreadPanelPresentation(2_000, 0, true)).toBe("popover"); + }); +}); diff --git a/apps/web/src/rightPanelLayout.ts b/apps/web/src/rightPanelLayout.ts index 5528072e57..e85f24e4a4 100644 --- a/apps/web/src/rightPanelLayout.ts +++ b/apps/web/src/rightPanelLayout.ts @@ -1,3 +1,17 @@ export const RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 980px)"; +export const THREAD_PANEL_INLINE_MIN_WIDTH = 960; export const RIGHT_PANEL_SHEET_CLASS_NAME = "w-[min(42vw,28rem)] min-w-80 max-w-[28rem] p-0 max-[760px]:w-[min(88vw,24rem)] max-[760px]:min-w-0 wco:mt-[env(titlebar-area-height)] wco:h-[calc(100%-env(titlebar-area-height))] wco:max-h-[calc(100%-env(titlebar-area-height))]"; + +export type ThreadPanelPresentation = "inline" | "popover"; + +export function resolveThreadPanelPresentation( + workspaceWidth: number | null, + occupiedRightPanelWidth: number, + rightPanelMaximized: boolean, +): ThreadPanelPresentation { + if (workspaceWidth === null) return "inline"; + + const chatPaneWidth = rightPanelMaximized ? 0 : workspaceWidth - occupiedRightPanelWidth; + return chatPaneWidth < THREAD_PANEL_INLINE_MIN_WIDTH ? "popover" : "inline"; +} diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index b48f6e7ebb..94a22c5d61 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -6,6 +6,8 @@ import { migratePersistedRightPanelState, selectActiveRightPanel, selectActiveRightPanelSurface, + selectThreadPanelOpen, + selectThreadPanelVisibility, selectThreadRightPanelState, useRightPanelStore, } from "./rightPanelStore"; @@ -14,7 +16,7 @@ const refA = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-A")) const refB = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-B")); beforeEach(() => { - useRightPanelStore.setState({ byThreadKey: {} }); + useRightPanelStore.setState({ byThreadKey: {}, threadPanelVisibilityByThreadKey: {} }); }); describe("rightPanelStore", () => { @@ -39,6 +41,7 @@ describe("rightPanelStore", () => { surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }], }, }, + threadPanelVisibilityByThreadKey: {}, }); }); @@ -69,6 +72,7 @@ describe("rightPanelStore", () => { ], }, }, + threadPanelVisibilityByThreadKey: {}, }); }); @@ -99,9 +103,80 @@ describe("rightPanelStore", () => { ], }, }, + threadPanelVisibilityByThreadKey: {}, }); }); + it("persists inline preference without restoring an open popover", () => { + expect( + migratePersistedRightPanelState({ + threadPanelVisibilityByThreadKey: { + "env-1:thread-A": { inlineOpen: false, popoverOpen: true }, + "env-1:thread-B": { inlineOpen: true, popoverOpen: true }, + }, + }), + ).toEqual({ + byThreadKey: {}, + threadPanelVisibilityByThreadKey: { + "env-1:thread-A": { inlineOpen: false, popoverOpen: false }, + }, + }); + }); + + it("tracks inline and popover visibility independently", () => { + const store = useRightPanelStore.getState(); + + expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "inline")).toBe( + true, + ); + expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "popover")).toBe( + false, + ); + + store.setThreadPanelOpen(refA, "inline", false); + store.toggleThreadPanel(refA, "popover"); + + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refA, + ), + ).toEqual({ inlineOpen: false, popoverOpen: true }); + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refB, + ), + ).toEqual({ inlineOpen: true, popoverOpen: false }); + }); + + it("closes the popover atomically when the real right panel opens", () => { + useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true); + useRightPanelStore.getState().open(refA, "plan"); + + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refA, + ), + ).toEqual({ inlineOpen: true, popoverOpen: false }); + }); + + it("keeps an open popover visible by promoting it to inline when the real panel closes", () => { + const store = useRightPanelStore.getState(); + store.open(refA, "plan"); + store.setThreadPanelOpen(refA, "inline", false); + store.setThreadPanelOpen(refA, "popover", true); + store.close(refA); + + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refA, + ), + ).toEqual({ inlineOpen: true, popoverOpen: true }); + }); + it("open sets the active panel for a thread", () => { useRightPanelStore.getState().open(refA, "preview"); expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview"); diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 70d163306c..1d7af9a110 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -13,6 +13,7 @@ import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; import { resolveStorage } from "./lib/storage"; +import type { ThreadPanelPresentation } from "./rightPanelLayout"; export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const; export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number]; @@ -40,7 +41,7 @@ export type RightPanelSurface = | { id: "plan"; kind: "plan" }; const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2"; -const RIGHT_PANEL_STORAGE_VERSION = 7; +const RIGHT_PANEL_STORAGE_VERSION = 8; export interface ThreadRightPanelState { isOpen: boolean; @@ -48,8 +49,14 @@ export interface ThreadRightPanelState { surfaces: RightPanelSurface[]; } +export interface ThreadPanelVisibility { + inlineOpen: boolean; + popoverOpen: boolean; +} + interface RightPanelStoreState { byThreadKey: Record; + threadPanelVisibilityByThreadKey: Record; open: (ref: ScopedThreadRef, kind: Exclude) => void; openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void; openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void; @@ -73,6 +80,12 @@ interface RightPanelStoreState { close: (ref: ScopedThreadRef) => void; toggleVisibility: (ref: ScopedThreadRef) => void; toggle: (ref: ScopedThreadRef, kind: Exclude) => void; + setThreadPanelOpen: ( + ref: ScopedThreadRef, + presentation: ThreadPanelPresentation, + open: boolean, + ) => void; + toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void; removeThread: (ref: ScopedThreadRef) => void; } @@ -82,6 +95,11 @@ const EMPTY_THREAD_STATE: ThreadRightPanelState = { surfaces: [], }; +const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { + inlineOpen: true, + popoverOpen: false, +}; + const singletonSurface = ( kind: Exclude, ): RightPanelSurface => { @@ -132,7 +150,7 @@ const upsertSurface = ( activeSurfaceId: activate ? surface.id : current.activeSurfaceId, }); -const updateThread = ( +const updateThreadStateMap = ( byThreadKey: Record, threadKey: string, updater: (current: ThreadRightPanelState) => ThreadRightPanelState, @@ -148,6 +166,63 @@ const updateThread = ( return { ...byThreadKey, [threadKey]: next }; }; +const updateThreadPanelVisibilityMap = ( + byThreadKey: Record, + threadKey: string, + updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility, +): Record => { + const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY; + const next = updater(current); + if (next.inlineOpen && !next.popoverOpen) { + if (!(threadKey in byThreadKey)) return byThreadKey; + const { [threadKey]: _removed, ...rest } = byThreadKey; + return rest; + } + if (next === current) return byThreadKey; + return { ...byThreadKey, [threadKey]: next }; +}; + +type RightPanelStoreData = Pick< + RightPanelStoreState, + "byThreadKey" | "threadPanelVisibilityByThreadKey" +>; + +/** + * Applies a real right-panel mutation and its thread-panel transition atomically. + * This is the only path real panel actions use, so visibility never has to be + * reconciled after the fact in React. + */ +const updateThread = ( + state: RightPanelStoreData, + ref: ScopedThreadRef, + updater: (current: ThreadRightPanelState) => ThreadRightPanelState, +): RightPanelStoreData => { + const threadKey = scopedThreadKey(ref); + const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE; + const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater); + const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE; + let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey; + + if (!current.isOpen && next.isOpen) { + threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap( + threadPanelVisibilityByThreadKey, + threadKey, + (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility), + ); + } else if (current.isOpen && !next.isOpen) { + threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap( + threadPanelVisibilityByThreadKey, + threadKey, + (visibility) => + visibility.popoverOpen && !visibility.inlineOpen + ? { ...visibility, inlineOpen: true } + : visibility, + ); + } + + return { byThreadKey, threadPanelVisibilityByThreadKey }; +}; + function normalizeRevealLine(line: number | undefined): number | null { if (line === undefined || !Number.isFinite(line)) return null; return Math.max(1, Math.trunc(line)); @@ -155,9 +230,10 @@ function normalizeRevealLine(line: number | undefined): number | null { export function migratePersistedRightPanelState(persistedState: unknown): { byThreadKey: Record; + threadPanelVisibilityByThreadKey: Record; } { if (!persistedState || typeof persistedState !== "object") { - return { byThreadKey: {} }; + return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} }; } const byThreadKey = "byThreadKey" in persistedState && @@ -232,36 +308,52 @@ export function migratePersistedRightPanelState(persistedState: unknown): { ), ) : {}; - return { byThreadKey }; + const threadPanelVisibilityByThreadKey = + "threadPanelVisibilityByThreadKey" in persistedState && + persistedState.threadPanelVisibilityByThreadKey && + typeof persistedState.threadPanelVisibilityByThreadKey === "object" + ? Object.fromEntries( + Object.entries( + persistedState.threadPanelVisibilityByThreadKey as Record, + ).flatMap(([threadKey, value]) => { + if (!value || typeof value !== "object" || !("inlineOpen" in value)) return []; + return value.inlineOpen === false + ? [[threadKey, { inlineOpen: false, popoverOpen: false }]] + : []; + }), + ) + : {}; + return { byThreadKey, threadPanelVisibilityByThreadKey }; } export const useRightPanelStore = create()( persist( (set) => ({ byThreadKey: {}, + threadPanelVisibilityByThreadKey: {}, open: (ref, kind) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { if (kind === "preview") { const existing = current.surfaces.find((surface) => surface.kind === "preview"); return upsertSurface(current, existing ?? browserSurface(null)); } return upsertSurface(current, singletonSurface(kind)); }), - })), + ), openBrowser: (ref, tabId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const surface = browserSurface(tabId); const withoutPlaceholder = tabId ? current.surfaces.filter((entry) => entry.id !== "browser:new") : current.surfaces; return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface); }), - })), + ), openFile: (ref, relativePath, line) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const withoutStandaloneExplorer = current.surfaces.filter( (surface) => surface.kind !== "files", ); @@ -285,16 +377,16 @@ export const useRightPanelStore = create()( : [...withoutStandaloneExplorer, surface], }; }), - })), + ), openTerminal: (ref, terminalId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => + set((state) => + updateThread(state, ref, (current) => upsertSurface(current, terminalSurface(terminalId)), ), - })), + ), splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({ + set((state) => + updateThread(state, ref, (current) => ({ ...current, isOpen: true, activeSurfaceId: surfaceId, @@ -311,10 +403,10 @@ export const useRightPanelStore = create()( }; }), })), - })), + ), activateTerminal: (ref, surfaceId, terminalId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({ + set((state) => + updateThread(state, ref, (current) => ({ ...current, activeSurfaceId: surfaceId, surfaces: current.surfaces.map((surface) => @@ -325,10 +417,10 @@ export const useRightPanelStore = create()( : surface, ), })), - })), + ), closeTerminal: (ref, surfaceId, terminalId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const surface = current.surfaces.find( (entry) => entry.id === surfaceId && entry.kind === "terminal", ); @@ -364,18 +456,18 @@ export const useRightPanelStore = create()( ), }; }), - })), + ), activateSurface: (ref, surfaceId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => + set((state) => + updateThread(state, ref, (current) => current.surfaces.some((surface) => surface.id === surfaceId) ? { ...current, isOpen: true, activeSurfaceId: surfaceId } : current, ), - })), + ), closeSurface: (ref, surfaceId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const index = current.surfaces.findIndex((surface) => surface.id === surfaceId); if (index < 0) return current; const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId); @@ -390,10 +482,10 @@ export const useRightPanelStore = create()( activeSurfaceId: fallback?.id ?? null, }; }), - })), + ), closeOtherSurfaces: (ref, surfaceId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const surface = current.surfaces.find((entry) => entry.id === surfaceId); if (!surface || current.surfaces.length === 1) return current; return { @@ -403,10 +495,10 @@ export const useRightPanelStore = create()( activeSurfaceId: surface.id, }; }), - })), + ), closeSurfacesToRight: (ref, surfaceId) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const index = current.surfaces.findIndex((surface) => surface.id === surfaceId); if (index < 0 || index === current.surfaces.length - 1) return current; const surfaces = current.surfaces.slice(0, index + 1); @@ -419,18 +511,18 @@ export const useRightPanelStore = create()( activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId, }; }), - })), + ), closeAllSurfaces: (ref) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => + set((state) => + updateThread(state, ref, (current) => current.surfaces.length === 0 ? current : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null }, ), - })), + ), reconcileBrowserSurfaces: (ref, tabIds) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`)); const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview"); const existingBrowser = current.surfaces.filter( @@ -456,10 +548,10 @@ export const useRightPanelStore = create()( : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null), }; }), - })), + ), reconcileFileSurfaces: (ref, workspaceAvailable) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { if (workspaceAvailable) return current; const surfaces = current.surfaces.filter( (surface) => surface.kind !== "files" && surface.kind !== "file", @@ -477,29 +569,29 @@ export const useRightPanelStore = create()( : (surfaces.at(-1)?.id ?? null), }; }), - })), + ), show: (ref) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => + set((state) => + updateThread(state, ref, (current) => current.isOpen ? current : { ...current, isOpen: true }, ), - })), + ), close: (ref) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => + set((state) => + updateThread(state, ref, (current) => current.isOpen ? { ...current, isOpen: false } : current, ), - })), + ), toggleVisibility: (ref) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({ + set((state) => + updateThread(state, ref, (current) => ({ ...current, isOpen: !current.isOpen, })), - })), + ), toggle: (ref, kind) => - set((state) => ({ - byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => { + set((state) => + updateThread(state, ref, (current) => { const active = current.surfaces.find( (surface) => surface.id === current.activeSurfaceId, ); @@ -512,13 +604,42 @@ export const useRightPanelStore = create()( } return upsertSurface(current, singletonSurface(kind)); }), + ), + setThreadPanelOpen: (ref, presentation, open) => + set((state) => ({ + threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap( + state.threadPanelVisibilityByThreadKey, + scopedThreadKey(ref), + (visibility) => { + const key = presentation === "inline" ? "inlineOpen" : "popoverOpen"; + return visibility[key] === open ? visibility : { ...visibility, [key]: open }; + }, + ), + })), + toggleThreadPanel: (ref, presentation) => + set((state) => ({ + threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap( + state.threadPanelVisibilityByThreadKey, + scopedThreadKey(ref), + (visibility) => + presentation === "inline" + ? { ...visibility, inlineOpen: !visibility.inlineOpen } + : { ...visibility, popoverOpen: !visibility.popoverOpen }, + ), })), removeThread: (ref) => set((state) => { const threadKey = scopedThreadKey(ref); - if (!(threadKey in state.byThreadKey)) return state; - const { [threadKey]: _removed, ...rest } = state.byThreadKey; - return { byThreadKey: rest }; + if ( + !(threadKey in state.byThreadKey) && + !(threadKey in state.threadPanelVisibilityByThreadKey) + ) { + return state; + } + const { [threadKey]: _removedPanel, ...byThreadKey } = state.byThreadKey; + const { [threadKey]: _removedVisibility, ...threadPanelVisibilityByThreadKey } = + state.threadPanelVisibilityByThreadKey; + return { byThreadKey, threadPanelVisibilityByThreadKey }; }), }), { @@ -527,7 +648,15 @@ export const useRightPanelStore = create()( storage: createJSONStorage(() => resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), ), - partialize: (state) => ({ byThreadKey: state.byThreadKey }), + partialize: (state) => ({ + byThreadKey: state.byThreadKey, + threadPanelVisibilityByThreadKey: Object.fromEntries( + Object.entries(state.threadPanelVisibilityByThreadKey).flatMap( + ([threadKey, visibility]) => + visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]], + ), + ), + }), migrate: migratePersistedRightPanelState, }, ), @@ -541,6 +670,23 @@ export function selectThreadRightPanelState( return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE; } +export function selectThreadPanelVisibility( + byThreadKey: Record, + ref: ScopedThreadRef | null | undefined, +): ThreadPanelVisibility { + if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY; + return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY; +} + +export function selectThreadPanelOpen( + byThreadKey: Record, + ref: ScopedThreadRef | null | undefined, + presentation: ThreadPanelPresentation, +): boolean { + const visibility = selectThreadPanelVisibility(byThreadKey, ref); + return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen; +} + export function selectActiveRightPanel( byThreadKey: Record, ref: ScopedThreadRef | null | undefined, diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx index 015c78eab0..dc83bf248d 100644 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ b/apps/web/src/routes/debug.orchestration-v2.tsx @@ -31,6 +31,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ProviderModelPicker } from "../components/chat/ProviderModelPicker"; import { usePrimarySettings } from "../hooks/useSettings"; +import { resolveMergeBackTargetThreadId } from "../lib/threadRelationships"; import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils"; import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection"; import { deriveOrchestrationV2DebugProviderSnapshots } from "../orchestrationV2DebugProviders"; @@ -2694,13 +2695,8 @@ function latestCompletedRunInProjection( function deriveMergeBackCandidate( projection: OrchestrationV2ThreadProjection | null, ): MergeBackCandidate | null { - if (projection === null || projection.thread.lineage.relationshipToParent !== "fork") { - return null; - } - const targetThreadId = - projection.thread.forkedFrom?.type === "run" - ? projection.thread.forkedFrom.threadId - : projection.thread.lineage.parentThreadId; + if (projection === null) return null; + const targetThreadId = resolveMergeBackTargetThreadId(projection); if (targetThreadId === null) { return null; } diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 68e78b6407..9eac5dda7a 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -18,6 +18,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentProjects } from "./projects"; import { environmentServerConfigsAtom } from "./server"; import { environmentThreadDetails, environmentThreadShells } from "./threads"; +import { waitForAtomValue } from "./waitForAtomValue"; const EMPTY_PROJECT_REFS: ReadonlyArray = Object.freeze([]); const EMPTY_THREAD_REFS: ReadonlyArray = Object.freeze([]); @@ -198,6 +199,15 @@ export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref)); } +export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise { + return waitForAtomValue({ + registry: appAtomRegistry, + atom: environmentThreadShells.threadShellAtom(ref), + predicate: (thread) => thread !== null, + timeoutMs, + }); +} + export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null { return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref)); } diff --git a/apps/web/src/state/waitForAtomValue.test.ts b/apps/web/src/state/waitForAtomValue.test.ts new file mode 100644 index 0000000000..8b8f88a0a6 --- /dev/null +++ b/apps/web/src/state/waitForAtomValue.test.ts @@ -0,0 +1,57 @@ +import { Atom, AtomRegistry } from "effect/unstable/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { waitForAtomValue } from "./waitForAtomValue"; + +describe("waitForAtomValue", () => { + it("returns immediately when the current value is ready", async () => { + const registry = AtomRegistry.make(); + const atom = Atom.make("ready"); + + await expect( + waitForAtomValue({ + registry, + atom, + predicate: (value) => value === "ready", + timeoutMs: 1_000, + }), + ).resolves.toBe(true); + + registry.dispose(); + }); + + it("waits until a subscribed atom becomes ready", async () => { + const registry = AtomRegistry.make(); + const atom = Atom.make("pending"); + const result = waitForAtomValue({ + registry, + atom, + predicate: (value) => value === "ready", + timeoutMs: 1_000, + }); + + registry.set(atom, "ready"); + + await expect(result).resolves.toBe(true); + registry.dispose(); + }); + + it("returns false and unsubscribes when readiness times out", async () => { + vi.useFakeTimers(); + const registry = AtomRegistry.make(); + const atom = Atom.make("pending"); + const result = waitForAtomValue({ + registry, + atom, + predicate: (value) => value === "ready", + timeoutMs: 1_000, + }); + + await vi.advanceTimersByTimeAsync(1_000); + + await expect(result).resolves.toBe(false); + registry.set(atom, "ready"); + registry.dispose(); + vi.useRealTimers(); + }); +}); diff --git a/apps/web/src/state/waitForAtomValue.ts b/apps/web/src/state/waitForAtomValue.ts new file mode 100644 index 0000000000..c472833365 --- /dev/null +++ b/apps/web/src/state/waitForAtomValue.ts @@ -0,0 +1,56 @@ +import type { Atom, AtomRegistry } from "effect/unstable/reactivity"; + +export async function waitForAtomValue(input: { + readonly registry: AtomRegistry.AtomRegistry; + readonly atom: Atom.Atom; + readonly predicate: (value: A) => boolean; + readonly timeoutMs: number; +}): Promise { + const read = () => input.registry.get(input.atom); + if (input.predicate(read())) { + return true; + } + + return await new Promise((resolve) => { + let settled = false; + let timeoutId: ReturnType | null = null; + let unsubscribe: (() => void) | null = null; + let unsubscribeWhenReady = false; + + const finish = (result: boolean) => { + if (settled) { + return; + } + settled = true; + if (timeoutId !== null) { + globalThis.clearTimeout(timeoutId); + } + if (unsubscribe === null) { + unsubscribeWhenReady = true; + } else { + unsubscribe(); + } + resolve(result); + }; + + unsubscribe = input.registry.subscribe(input.atom, (value) => { + if (input.predicate(value)) { + finish(true); + } + }); + if (unsubscribeWhenReady) { + unsubscribe(); + return; + } + + // Close the gap between the initial read and subscription registration. + if (input.predicate(read())) { + finish(true); + return; + } + + timeoutId = globalThis.setTimeout(() => { + finish(false); + }, input.timeoutMs); + }); +} diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 0fbbd79ec2..1d3a8da791 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -305,5 +305,6 @@ describe("uiStateStore persistence", () => { localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}", ) as PersistedUiState; expect(resolveProjectExpanded(persisted.projectExpandedById ?? {}, ["unknown"])).toBe(true); + expect(persisted).not.toHaveProperty("threadPanelOpen"); }); }); diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index 80a68c21ad..f588f17347 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -74,10 +74,10 @@ describe("applyShellStreamEvent", () => { }); it("leaves unknown future events unchanged", () => { - const next = applyShellStreamEvent( - v2ShellSnapshot, - { kind: "future.event", sequence: 99 } as never, - ); + const next = applyShellStreamEvent(v2ShellSnapshot, { + kind: "future.event", + sequence: 99, + } as never); expect(next).toBe(v2ShellSnapshot); }); diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts index 33ecd38039..bdbc120f3c 100644 --- a/packages/contracts/src/keybindings.test.ts +++ b/packages/contracts/src/keybindings.test.ts @@ -41,6 +41,12 @@ it.effect("parses keybinding rules", () => }); assert.strictEqual(parsedRightPanelToggle.command, "rightPanel.toggle"); + const parsedThreadPanelToggle = yield* decode(KeybindingRule, { + key: "mod+shift+b", + command: "threadPanel.toggle", + }); + assert.strictEqual(parsedThreadPanelToggle.command, "threadPanel.toggle"); + const parsedClose = yield* decode(KeybindingRule, { key: "mod+w", command: "terminal.close", diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index c7cff9943c..fcdc0820bd 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -47,7 +47,7 @@ export const MODEL_PICKER_KEYBINDING_COMMANDS = [ ] as const; export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number]; -const STATIC_KEYBINDING_COMMANDS = [ +export const BUILT_IN_KEYBINDING_COMMANDS = [ "sidebar.toggle", "terminal.toggle", "terminal.split", @@ -55,6 +55,7 @@ const STATIC_KEYBINDING_COMMANDS = [ "terminal.new", "terminal.close", "rightPanel.toggle", + "threadPanel.toggle", "diff.toggle", "preview.toggle", "preview.refresh", @@ -80,7 +81,7 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([ ]); export const KeybindingCommand = Schema.Union([ - Schema.Literals(STATIC_KEYBINDING_COMMANDS), + Schema.Literals(BUILT_IN_KEYBINDING_COMMANDS), SCRIPT_RUN_COMMAND_PATTERN, ]); export type KeybindingCommand = typeof KeybindingCommand.Type;