feat(web): add bottom terminal panel with Cmd+J hotkey (#414)

This commit is contained in:
João Salavisa
2026-03-10 23:10:16 +00:00
committed by GitHub
parent 37e6b1bd6d
commit a405e13530
10 changed files with 196 additions and 33 deletions
@@ -0,0 +1,103 @@
"use client";
import { useRef, useState, useCallback, useEffect } from "react";
import { IconMinus } from "@tabler/icons-react";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { PassthroughTerminal } from "./passthrough-terminal";
import { Button } from "@kandev/ui/button";
import { cn } from "@/lib/utils";
const MIN_HEIGHT = 150;
const MAX_HEIGHT_RATIO = 0.6;
const DEFAULT_HEIGHT = 300;
const STORAGE_KEY_HEIGHT = "bottom-terminal-height";
const STORAGE_KEY_OPEN = "bottom-terminal-open";
type Props = {
sessionId: string | null;
};
export function BottomTerminalPanel({ sessionId }: Props) {
const visible = useAppStore((s) => s.bottomTerminal.isOpen);
const storeApi = useAppStoreApi();
const toggle = useCallback(() => storeApi.getState().toggleBottomTerminal(), [storeApi]);
// Restore visibility state from localStorage on mount
useEffect(() => {
const saved = localStorage.getItem(STORAGE_KEY_OPEN);
if (saved === "true" && !storeApi.getState().bottomTerminal.isOpen) {
toggle();
}
}, [storeApi, toggle]);
const panelRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(() => {
if (typeof window === "undefined") return DEFAULT_HEIGHT;
const saved = localStorage.getItem(STORAGE_KEY_HEIGHT);
return saved ? Math.max(MIN_HEIGHT, parseInt(saved, 10) || DEFAULT_HEIGHT) : DEFAULT_HEIGHT;
});
const isDragging = useRef(false);
const handleMouseDown = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
isDragging.current = true;
const startY = e.clientY;
const startHeight = height;
const onMouseMove = (moveEvent: MouseEvent) => {
if (!isDragging.current) return;
const delta = startY - moveEvent.clientY;
const maxHeight = window.innerHeight * MAX_HEIGHT_RATIO;
const newHeight = Math.min(maxHeight, Math.max(MIN_HEIGHT, startHeight + delta));
if (panelRef.current) panelRef.current.style.height = `${newHeight}px`;
};
const onMouseUp = () => {
isDragging.current = false;
if (panelRef.current) {
const finalHeight = panelRef.current.offsetHeight;
setHeight(finalHeight);
localStorage.setItem(STORAGE_KEY_HEIGHT, String(finalHeight));
}
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
};
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
},
[height],
);
if (!visible) return null;
return (
<div
ref={panelRef}
className={cn("relative flex flex-col border-t border-border bg-background", "shrink-0")}
style={{ height }}
>
{/* Resize handle */}
<div
className="absolute top-0 left-0 right-0 h-1 cursor-ns-resize hover:bg-primary/20 z-10"
onMouseDown={handleMouseDown}
/>
{/* Header */}
<div className="flex items-center justify-between px-3 py-1 border-b border-border bg-muted/30 shrink-0">
<span className="text-xs font-medium text-muted-foreground">Terminal</span>
<Button variant="ghost" size="icon" className="h-5 w-5 cursor-pointer" onClick={toggle}>
<IconMinus className="h-3 w-3" />
</Button>
</div>
{/* Terminal content - pb-2 prevents last line from being cut off */}
<div className="flex-1 min-h-0 overflow-hidden pb-2">
<PassthroughTerminal
sessionId={sessionId}
mode="shell"
terminalId="bottom-panel"
autoFocus
/>
</div>
</div>
);
}
@@ -40,6 +40,7 @@ import { CommitDetailPanel } from "./commit-detail-panel";
import { PRDetailPanelComponent } from "@/components/github/pr-detail-panel";
import { PreviewController } from "./preview/preview-controller";
import { ReviewDialog } from "@/components/review/review-dialog";
import { BottomTerminalPanel } from "./bottom-terminal-panel";
import { stopVscode } from "@/lib/api/domains/vscode-api";
import { stopUserShell } from "@/lib/api/domains/user-shell-api";
import { useReviewDialog } from "./use-review-dialog";
@@ -705,7 +706,7 @@ export const DockviewDesktopLayout = memo(function DockviewDesktopLayout({
return (
<div
className="flex-1 min-h-0"
className="flex-1 min-h-0 grid grid-rows-[1fr_auto]"
aria-busy={isRestoringLayout}
style={{
opacity: isRestoringLayout ? 0 : 1,
@@ -713,19 +714,22 @@ export const DockviewDesktopLayout = memo(function DockviewDesktopLayout({
transition: isRestoringLayout ? "none" : "opacity 60ms ease-out",
}}
>
<PreviewController sessionId={effectiveSessionId} hasDevScript={hasDevScript} />
<DockviewReact
theme={themeKandev}
components={components}
tabComponents={tabComponents}
defaultTabComponent={ContextMenuTab}
leftHeaderActionsComponent={LeftHeaderActions}
rightHeaderActionsComponent={RightHeaderActions}
watermarkComponent={DockviewWatermark}
onReady={onReady}
defaultRenderer="always"
className="h-full"
/>
<div className="min-h-0 flex flex-col">
<PreviewController sessionId={effectiveSessionId} hasDevScript={hasDevScript} />
<DockviewReact
theme={themeKandev}
components={components}
tabComponents={tabComponents}
defaultTabComponent={ContextMenuTab}
leftHeaderActionsComponent={LeftHeaderActions}
rightHeaderActionsComponent={RightHeaderActions}
watermarkComponent={DockviewWatermark}
onReady={onReady}
defaultRenderer="always"
className="flex-1 min-h-0"
/>
</div>
<BottomTerminalPanel sessionId={effectiveSessionId} />
<PanelPortalHost renderPanel={renderPanel} />
{effectiveSessionId && (
<ReviewDialog
@@ -24,6 +24,7 @@ import {
type BaseProps = {
sessionId?: string | null;
autoFocus?: boolean;
};
type AgentTerminalProps = BaseProps & { mode: "agent"; label?: string };
type ShellTerminalProps = BaseProps & { mode: "shell"; terminalId: string; label?: string };
@@ -40,7 +41,7 @@ type PassthroughTerminalProps = AgentTerminalProps | ShellTerminalProps;
* - Resize commands sent via binary protocol: [0x01][JSON {cols, rows}]
*/
export function PassthroughTerminal(props: PassthroughTerminalProps) {
const { sessionId: propSessionId, mode, label } = props;
const { sessionId: propSessionId, mode, label, autoFocus } = props;
const terminalId = mode === "shell" ? props.terminalId : undefined;
log("Render - props:", { propSessionId, mode, terminalId, label });
@@ -64,10 +65,8 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
const wsBaseUrl = useMemo(() => {
try {
const backendUrl = getBackendConfig().apiBaseUrl;
const url = new URL(backendUrl);
const protocol = url.protocol === "https:" ? "wss:" : "ws:";
return `${protocol}//${url.host}`;
const url = new URL(getBackendConfig().apiBaseUrl);
return `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}`;
} catch {
return "ws://localhost:8080";
}
@@ -86,9 +85,9 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
const [connectedSessionId, setConnectedSessionId] = useState<string | null>(null);
const isConnected = sessionId != null && connectedSessionId === sessionId;
const onConnected = useCallback(() => {
log("WebSocket connected — hiding loading overlay for session", sessionId);
setConnectedSessionId(sessionId ?? null);
}, [sessionId]);
if (autoFocus) xtermRef.current?.focus();
}, [sessionId, autoFocus]);
const linkHandler = useTerminalLinkHandler();
const sendResize = useSendResize(wsRef);
@@ -100,6 +99,7 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
sendResize,
});
const toggleBottomTerminal = useAppStore((s) => s.toggleBottomTerminal);
useTerminalInit({
terminalRef,
xtermRef,
@@ -111,6 +111,7 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
fitAndResize,
onReady: onTerminalReady,
linkHandler,
onToggleBottomTerminal: toggleBottomTerminal,
});
useWebSocketConnection({
@@ -7,6 +7,8 @@ import { WebLinksAddon } from "@xterm/addon-web-links";
import { WebglAddon } from "@xterm/addon-webgl";
import { getTerminalTheme } from "@/lib/theme/terminal-theme";
import { startReconnectLoop } from "./ws-reconnect";
import { SHORTCUTS } from "@/lib/keyboard/constants";
import { matchesShortcut } from "@/lib/keyboard/utils";
// Debug flag - set to true to see detailed logs
const DEBUG = false;
@@ -57,6 +59,7 @@ function initTerminalInstance(
>,
fitAndResize: (force?: boolean) => void,
linkHandler?: (event: MouseEvent, uri: string) => void,
onToggleBottomTerminal?: () => void,
) {
if (refs.isInitializedRef.current || refs.xtermRef.current) return undefined;
refs.isInitializedRef.current = true;
@@ -79,14 +82,20 @@ function initTerminalInstance(
terminal.unicode.activeVersion = "11";
const webLinksAddon = new WebLinksAddon(linkHandler);
terminal.loadAddon(webLinksAddon);
log("Opening terminal in container");
terminal.open(termContainer);
// Intercept bottom terminal shortcut to toggle panel
terminal.attachCustomKeyEventHandler((event) => {
if (matchesShortcut(event, SHORTCUTS.BOTTOM_TERMINAL)) {
if (event.type === "keydown" && onToggleBottomTerminal) onToggleBottomTerminal();
return false;
}
return true;
});
try {
fitAddon.fit();
refs.lastDimensionsRef.current = { cols: terminal.cols, rows: terminal.rows };
log("Initial fit:", terminal.cols, "x", terminal.rows);
} catch (e) {
log("Initial fit failed:", e);
} catch {
/* fit failed */
}
refs.xtermRef.current = terminal;
refs.fitAddonRef.current = fitAddon;
@@ -141,6 +150,11 @@ function initTerminalInstance(
};
}
type TerminalInitHookOptions = TerminalInitOptions & {
linkHandler?: (event: MouseEvent, uri: string) => void;
onToggleBottomTerminal?: () => void;
};
export function useTerminalInit({
terminalRef,
xtermRef,
@@ -152,7 +166,8 @@ export function useTerminalInit({
fitAndResize,
onReady,
linkHandler,
}: TerminalInitOptions & { linkHandler?: (event: MouseEvent, uri: string) => void }) {
onToggleBottomTerminal,
}: TerminalInitHookOptions) {
const refs = {
xtermRef,
fitAddonRef,
@@ -178,7 +193,7 @@ export function useTerminalInit({
const rect = container.getBoundingClientRect();
log("Init check: dimensions", rect.width, "x", rect.height);
if (rect.width >= MIN_WIDTH && rect.height >= MIN_HEIGHT) {
initTerminalInstance(container, refs, fitAndResize, linkHandler);
initTerminalInstance(container, refs, fitAndResize, linkHandler, onToggleBottomTerminal);
onReady();
return true;
}
+20 -6
View File
@@ -4,6 +4,8 @@ import { useEffect, useRef } from "react";
import { useDockviewStore } from "@/lib/state/dockview-store";
import { useAppStoreApi } from "@/components/state-provider";
import { createUserShell } from "@/lib/api/domains/user-shell-api";
import { SHORTCUTS } from "@/lib/keyboard/constants";
import { matchesShortcut } from "@/lib/keyboard/utils";
import type { DockviewApi } from "dockview-react";
function handleTabNavigation(e: KeyboardEvent, api: DockviewApi) {
@@ -89,10 +91,20 @@ function handleLayoutToggle(e: KeyboardEvent): boolean {
return true;
}
if (isCmdKey(e, "KeyJ")) {
return false;
}
function handleBottomTerminal(
e: KeyboardEvent,
appStore: ReturnType<typeof useAppStoreApi>,
): boolean {
if (isEditableTarget(e)) return false;
// Cmd/Ctrl+J — toggle bottom terminal panel
if (matchesShortcut(e, SHORTCUTS.BOTTOM_TERMINAL)) {
e.preventDefault();
e.stopPropagation();
useDockviewStore.getState().toggleRightPanels();
appStore.getState().toggleBottomTerminal();
return true;
}
@@ -104,7 +116,7 @@ function handleLayoutToggle(e: KeyboardEvent): boolean {
* - Cmd/Ctrl+Shift+[ / ] — navigate prev/next tab in active group
* - Ctrl+` — toggle terminal focus
* - Cmd/Ctrl+B — toggle sidebar
* - Cmd/Ctrl+J — toggle right panels
* - Cmd/Ctrl+J — toggle bottom terminal panel
*/
export function useEditorKeybinds() {
const previousPanelIdRef = useRef<string | null>(null);
@@ -137,10 +149,12 @@ export function useEditorKeybinds() {
return;
}
handleLayoutToggle(e);
if (handleLayoutToggle(e)) return;
handleBottomTerminal(e, appStore);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
// Use capture phase so we receive events before xterm.js
window.addEventListener("keydown", handler, true);
return () => window.removeEventListener("keydown", handler, true);
}, [appStore]);
}
+4
View File
@@ -141,4 +141,8 @@ export const SHORTCUTS = {
key: KEYS.Q,
modifiers: { ctrlOrCmd: true, shift: true },
},
BOTTOM_TERMINAL: {
key: KEYS.J,
modifiers: { ctrlOrCmd: true },
},
} as const;
+1
View File
@@ -287,6 +287,7 @@ function buildVisibilityActions(set: StoreSet, get: StoreGet) {
});
}
},
setSidebarVisible: (visible: boolean) => {
const { sidebarVisible } = get();
if (sidebarVisible === visible) return;
+6
View File
@@ -69,6 +69,10 @@ export type SessionFailureNotification = {
message: string;
};
export type BottomTerminalState = {
isOpen: boolean;
};
export type UISliceState = {
previewPanel: PreviewPanelState;
rightPanel: RightPanelState;
@@ -81,6 +85,7 @@ export type UISliceState = {
systemHealth: SystemHealthState;
quickChat: QuickChatState;
sessionFailureNotification: SessionFailureNotification | null;
bottomTerminal: BottomTerminalState;
};
export type UISliceActions = {
@@ -108,6 +113,7 @@ export type UISliceActions = {
setActiveQuickChatSession: (sessionId: string) => void;
renameQuickChatSession: (sessionId: string, name: string) => void;
setSessionFailureNotification: (n: SessionFailureNotification | null) => void;
toggleBottomTerminal: () => void;
};
export type UISlice = UISliceState & UISliceActions;
+10
View File
@@ -21,6 +21,7 @@ export const defaultUIState: UISliceState = {
systemHealth: { issues: [], healthy: true, loaded: false, loading: false },
quickChat: { isOpen: false, sessions: [], activeSessionId: null },
sessionFailureNotification: null,
bottomTerminal: { isOpen: false },
};
type ImmerSet = Parameters<typeof createUISlice>[0];
@@ -188,4 +189,13 @@ export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], []
set((draft) => {
draft.sessionFailureNotification = n;
}),
toggleBottomTerminal: () =>
set((draft) => {
const newValue = !draft.bottomTerminal.isOpen;
draft.bottomTerminal.isOpen = newValue;
// Persist to localStorage
if (typeof window !== "undefined") {
localStorage.setItem("bottom-terminal-open", String(newValue));
}
}),
});
+5
View File
@@ -205,6 +205,7 @@ export type AppState = {
systemHealth: (typeof defaultUIState)["systemHealth"];
quickChat: (typeof defaultUIState)["quickChat"];
sessionFailureNotification: (typeof defaultUIState)["sessionFailureNotification"];
bottomTerminal: (typeof defaultUIState)["bottomTerminal"];
// GitHub actions
setGitHubStatus: (status: GitHubStatus | null) => void;
@@ -317,6 +318,7 @@ export type AppState = {
setSessionFailureNotification: (
n: import("./slices/ui/types").SessionFailureNotification | null,
) => void;
toggleBottomTerminal: () => void;
setMessages: (
sessionId: string,
messages: Message[],
@@ -457,6 +459,7 @@ const defaultState = {
systemHealth: defaultUIState.systemHealth,
quickChat: defaultUIState.quickChat,
sessionFailureNotification: defaultUIState.sessionFailureNotification,
bottomTerminal: defaultUIState.bottomTerminal,
};
function mergeInitialState(initialState?: Partial<AppState>): typeof defaultState {
@@ -532,6 +535,7 @@ function mergeInitialState(initialState?: Partial<AppState>): typeof defaultStat
quickChat: { ...defaultState.quickChat, ...initialState.quickChat },
sessionFailureNotification:
initialState.sessionFailureNotification ?? defaultState.sessionFailureNotification,
bottomTerminal: { ...defaultState.bottomTerminal, ...initialState.bottomTerminal },
};
}
@@ -614,6 +618,7 @@ export function createAppStore(initialState?: Partial<AppState>) {
systemHealth: merged.systemHealth,
quickChat: merged.quickChat,
sessionFailureNotification: merged.sessionFailureNotification,
bottomTerminal: merged.bottomTerminal,
// Add hydrate method
// eslint-disable-next-line @typescript-eslint/no-explicit-any
hydrate: (state, options) => set((draft) => hydrateState(draft as any, state, options)),