From 765f4cd00bb05b4111f1279a8dac47b36665fccd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Feb 2026 16:19:51 -0800 Subject: [PATCH 01/10] Add terminal word and line navigation arrow shortcuts - handle platform-specific modifier+arrow combos in terminal input - reuse terminal write path for clear and navigation actions - add shortcut tests for macOS and non-macOS mappings --- .../src/components/ThreadTerminalDrawer.tsx | 21 +++++++-- apps/web/src/keybindings.test.ts | 47 +++++++++++++++++++ apps/web/src/keybindings.ts | 40 ++++++++++++++++ 3 files changed, 103 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index d9e544ab94..d74ba49a08 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -18,7 +18,10 @@ import { preferredTerminalEditor, resolvePathLinkTarget, } from "../terminal-links"; -import { isTerminalClearShortcut } from "../keybindings"; +import { + isTerminalClearShortcut, + terminalNavigationShortcutData, +} from "../keybindings"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -152,24 +155,32 @@ function TerminalViewport({ terminalRef.current = terminal; fitAddonRef.current = fitAddon; - const sendClearShortcut = async () => { + const sendTerminalInput = async (data: string, fallbackError: string) => { const activeTerminal = terminalRef.current; if (!activeTerminal) return; try { - await api.terminal.write({ threadId, terminalId, data: "\u000c" }); + await api.terminal.write({ threadId, terminalId, data }); } catch (error) { writeSystemMessage( activeTerminal, - error instanceof Error ? error.message : "Failed to clear terminal", + error instanceof Error ? error.message : fallbackError, ); } }; terminal.attachCustomKeyEventHandler((event) => { + const navigationData = terminalNavigationShortcutData(event); + if (navigationData !== null) { + event.preventDefault(); + event.stopPropagation(); + void sendTerminalInput(navigationData, "Failed to move cursor"); + return false; + } + if (!isTerminalClearShortcut(event)) return true; event.preventDefault(); event.stopPropagation(); - void sendClearShortcut(); + void sendTerminalInput("\u000c", "Failed to clear terminal"); return false; }); diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 622f2dea07..a3c88dbd91 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -15,6 +15,7 @@ import { isTerminalSplitShortcut, isTerminalToggleShortcut, shortcutLabelForCommand, + terminalNavigationShortcutData, type ShortcutEventLike, } from "./keybindings"; @@ -326,6 +327,52 @@ describe("isTerminalClearShortcut", () => { }); }); +describe("terminalNavigationShortcutData", () => { + it("maps Option+Arrow on macOS to word movement", () => { + assert.strictEqual( + terminalNavigationShortcutData(event({ key: "ArrowLeft", altKey: true }), "MacIntel"), + "\u001bb", + ); + assert.strictEqual( + terminalNavigationShortcutData(event({ key: "ArrowRight", altKey: true }), "MacIntel"), + "\u001bf", + ); + }); + + it("maps Cmd+Arrow on macOS to line movement", () => { + assert.strictEqual( + terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "MacIntel"), + "\u0001", + ); + assert.strictEqual( + terminalNavigationShortcutData(event({ key: "ArrowRight", metaKey: true }), "MacIntel"), + "\u0005", + ); + }); + + it("maps Ctrl+Arrow on non-macOS to word movement", () => { + assert.strictEqual( + terminalNavigationShortcutData(event({ key: "ArrowLeft", ctrlKey: true }), "Win32"), + "\u001bb", + ); + assert.strictEqual( + terminalNavigationShortcutData(event({ key: "ArrowRight", ctrlKey: true }), "Linux"), + "\u001bf", + ); + }); + + it("rejects unsupported combinations", () => { + assert.isNull( + terminalNavigationShortcutData( + event({ key: "ArrowLeft", shiftKey: true, altKey: true }), + "MacIntel", + ), + ); + assert.isNull(terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux")); + assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel")); + }); +}); + describe("plus key parsing", () => { it("matches the plus key shortcut", () => { const plusBindings = compile([{ shortcut: modShortcut("+"), command: "terminal.toggle" }]); diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 5b908344b8..8b7fed6e1d 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -25,6 +25,11 @@ interface ShortcutMatchOptions { context?: Partial; } +const TERMINAL_WORD_BACKWARD = "\u001bb"; +const TERMINAL_WORD_FORWARD = "\u001bf"; +const TERMINAL_LINE_START = "\u0001"; +const TERMINAL_LINE_END = "\u0005"; + function normalizeEventKey(key: string): string { const normalized = key.toLowerCase(); if (normalized === "esc") return "escape"; @@ -219,3 +224,38 @@ export function isTerminalClearShortcut( !event.shiftKey ); } + +export function terminalNavigationShortcutData( + event: ShortcutEventLike, + platform = navigator.platform, +): string | null { + if (event.shiftKey) return null; + + const key = normalizeEventKey(event.key); + if (key !== "arrowleft" && key !== "arrowright") { + return null; + } + + const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD; + const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END; + + if (isMacPlatform(platform)) { + if (event.altKey && !event.metaKey && !event.ctrlKey) { + return moveWord; + } + if (event.metaKey && !event.altKey && !event.ctrlKey) { + return moveLine; + } + return null; + } + + if (event.ctrlKey && !event.metaKey && !event.altKey) { + return moveWord; + } + + if (event.altKey && !event.metaKey && !event.ctrlKey) { + return moveWord; + } + + return null; +} From f864ef189d5def4cb2ae3f34cc461f13b3fc5a00 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Feb 2026 17:02:38 -0800 Subject: [PATCH 02/10] Ignore non-keydown terminal shortcuts - guard terminal clear/navigation shortcut handlers to only process `keydown` - add tests verifying `keyup` events are ignored --- apps/web/src/keybindings.test.ts | 13 +++++++++++++ apps/web/src/keybindings.ts | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index a3c88dbd91..4ceb1b920a 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -325,6 +325,10 @@ describe("isTerminalClearShortcut", () => { it("matches Cmd+K on macOS", () => { assert.isTrue(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel")); }); + + it("ignores non-keydown events", () => { + assert.isFalse(isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux")); + }); }); describe("terminalNavigationShortcutData", () => { @@ -371,6 +375,15 @@ describe("terminalNavigationShortcutData", () => { assert.isNull(terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux")); assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel")); }); + + it("ignores non-keydown events", () => { + assert.isNull( + terminalNavigationShortcutData( + event({ type: "keyup", key: "ArrowLeft", altKey: true }), + "MacIntel", + ), + ); + }); }); describe("plus key parsing", () => { diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 8b7fed6e1d..4efcd6fee3 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -7,6 +7,7 @@ import { import { isMacPlatform } from "./lib/utils"; export interface ShortcutEventLike { + type?: string; key: string; metaKey: boolean; ctrlKey: boolean; @@ -209,6 +210,10 @@ export function isTerminalClearShortcut( event: ShortcutEventLike, platform = navigator.platform, ): boolean { + if (event.type !== undefined && event.type !== "keydown") { + return false; + } + const key = event.key.toLowerCase(); if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) { @@ -229,6 +234,10 @@ export function terminalNavigationShortcutData( event: ShortcutEventLike, platform = navigator.platform, ): string | null { + if (event.type !== undefined && event.type !== "keydown") { + return null; + } + if (event.shiftKey) return null; const key = normalizeEventKey(event.key); From 38639010859b760c1770c717f737e5e725127f46 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Feb 2026 18:54:24 -0800 Subject: [PATCH 03/10] Auto-dismiss thread toasts after 10s of visible time - Add `dismissAfterVisibleMs` support to thread toasts - Pause/resume countdown based on tab visibility and window focus - Set Git action result toasts to dismiss after 10s when visible --- apps/web/src/components/GitActionsControl.tsx | 5 +- apps/web/src/components/ui/toast.tsx | 95 +++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 83c74e5f58..e30ff30dfc 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -312,7 +312,10 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp title: resultToast.title, description: resultToast.description, timeout: 0, - data: threadToastData, + data: { + ...threadToastData, + dismissAfterVisibleMs: 10_000, + }, ...(shouldOfferPushCta ? { actionProps: { diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx index 6c9614a91a..19f9bb6b61 100644 --- a/apps/web/src/components/ui/toast.tsx +++ b/apps/web/src/components/ui/toast.tsx @@ -1,6 +1,7 @@ "use client"; import { Toast } from "@base-ui/react/toast"; +import { useEffect } from "react"; import { CircleAlertIcon, CircleCheckIcon, @@ -16,10 +17,13 @@ import { useStore } from "~/store"; type ThreadToastData = { threadId?: string | null; tooltipStyle?: boolean; + dismissAfterVisibleMs?: number; }; const toastManager = Toast.createToastManager(); const anchoredToastManager = Toast.createToastManager(); +type ToastId = ReturnType; +const threadToastVisibleTimeoutRemainingMs = new Map(); const TOAST_ICONS = { error: CircleAlertIcon, @@ -50,6 +54,84 @@ function shouldRenderForActiveThread( return toastThreadId === activeThreadId; } +function ThreadToastVisibleAutoDismiss({ + toastId, + dismissAfterVisibleMs, +}: { + toastId: ToastId; + dismissAfterVisibleMs: number | undefined; +}) { + useEffect(() => { + if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return; + if (typeof window === "undefined" || typeof document === "undefined") return; + + let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs; + let startedAtMs: number | null = null; + let timeoutId: number | null = null; + let closed = false; + + const clearTimer = () => { + if (timeoutId === null) return; + window.clearTimeout(timeoutId); + timeoutId = null; + }; + + const closeToast = () => { + if (closed) return; + closed = true; + threadToastVisibleTimeoutRemainingMs.delete(toastId); + toastManager.close(toastId); + }; + + const pause = () => { + if (startedAtMs === null) return; + remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs)); + startedAtMs = null; + clearTimer(); + threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs); + }; + + const start = () => { + if (closed || startedAtMs !== null) return; + if (remainingMs <= 0) { + closeToast(); + return; + } + startedAtMs = Date.now(); + clearTimer(); + timeoutId = window.setTimeout(() => { + remainingMs = 0; + startedAtMs = null; + closeToast(); + }, remainingMs); + }; + + const syncTimer = () => { + const shouldRun = document.visibilityState === "visible" && document.hasFocus(); + if (shouldRun) { + start(); + return; + } + pause(); + }; + + syncTimer(); + document.addEventListener("visibilitychange", syncTimer); + window.addEventListener("focus", syncTimer); + window.addEventListener("blur", syncTimer); + + return () => { + document.removeEventListener("visibilitychange", syncTimer); + window.removeEventListener("focus", syncTimer); + window.removeEventListener("blur", syncTimer); + pause(); + clearTimer(); + }; + }, [dismissAfterVisibleMs, toastId]); + + return null; +} + function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) { return ( @@ -65,6 +147,15 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) { const activeThreadId = state.activeThreadId; const isTop = position.startsWith("top"); + useEffect(() => { + const activeToastIds = new Set(toasts.map((toast) => toast.id)); + for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) { + if (!activeToastIds.has(toastId)) { + threadToastVisibleTimeoutRemainingMs.delete(toastId); + } + } + }, [toasts]); + return ( +
{Icon && ( From 05b47e748f6a57001b9cb6b4f99d883e05b6d171 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Feb 2026 19:54:27 -0800 Subject: [PATCH 04/10] Fix collapsed toast content visibility in filtered stacks - keep the front-most visible toast readable when thread filtering hides others - extract visibility rule into `toast.logic.ts` - add unit tests for collapsed-content visibility behavior --- .../web/src/components/ui/toast.logic.test.ts | 16 ++ apps/web/src/components/ui/toast.logic.ts | 9 + apps/web/src/components/ui/toast.tsx | 185 +++++++++--------- 3 files changed, 122 insertions(+), 88 deletions(-) create mode 100644 apps/web/src/components/ui/toast.logic.test.ts create mode 100644 apps/web/src/components/ui/toast.logic.ts diff --git a/apps/web/src/components/ui/toast.logic.test.ts b/apps/web/src/components/ui/toast.logic.test.ts new file mode 100644 index 0000000000..def62c884f --- /dev/null +++ b/apps/web/src/components/ui/toast.logic.test.ts @@ -0,0 +1,16 @@ +import { assert, describe, it } from "vitest"; +import { shouldHideCollapsedToastContent } from "./toast.logic"; + +describe("shouldHideCollapsedToastContent", () => { + it("keeps a single visible toast readable", () => { + assert.equal(shouldHideCollapsedToastContent(0, 1), false); + }); + + it("keeps the front-most toast readable in a visible stack", () => { + assert.equal(shouldHideCollapsedToastContent(0, 3), false); + }); + + it("hides non-front toasts until the stack is expanded", () => { + assert.equal(shouldHideCollapsedToastContent(1, 3), true); + }); +}); diff --git a/apps/web/src/components/ui/toast.logic.ts b/apps/web/src/components/ui/toast.logic.ts new file mode 100644 index 0000000000..500203033a --- /dev/null +++ b/apps/web/src/components/ui/toast.logic.ts @@ -0,0 +1,9 @@ +export function shouldHideCollapsedToastContent( + visibleToastIndex: number, + visibleToastCount: number, +): boolean { + // Keep the front-most toast readable even if Base UI marks it as "behind" + // due to toasts hidden by thread filtering. + if (visibleToastCount <= 1) return false; + return visibleToastIndex > 0; +} diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx index 19f9bb6b61..68bef3fbaf 100644 --- a/apps/web/src/components/ui/toast.tsx +++ b/apps/web/src/components/ui/toast.tsx @@ -13,6 +13,7 @@ import { import { cn } from "~/lib/utils"; import { buttonVariants } from "~/components/ui/button"; import { useStore } from "~/store"; +import { shouldHideCollapsedToastContent } from "./toast.logic"; type ThreadToastData = { threadId?: string | null; @@ -146,6 +147,9 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) { const { toasts } = Toast.useToastManager(); const activeThreadId = state.activeThreadId; const isTop = position.startsWith("top"); + const visibleToasts = toasts.filter((toast) => + shouldRenderForActiveThread(toast.data, activeThreadId), + ); useEffect(() => { const activeToastIds = new Set(toasts.map((toast) => toast.id)); @@ -172,100 +176,105 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) { data-position={position} data-slot="toast-viewport" > - {toasts - .filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId)) - .map((toast) => { - const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null; + {visibleToasts.map((toast, visibleIndex) => { + const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null; + const hideCollapsedContent = shouldHideCollapsedToastContent( + visibleIndex, + visibleToasts.length, + ); - return ( - + + - - -
- {Icon && ( -
- -
- )} - -
- - -
-
- {toast.actionProps && ( - + {Icon && ( +
- {toast.actionProps.children} - + +
)} -
-
- ); - })} + +
+ + +
+
+ {toast.actionProps && ( + + {toast.actionProps.children} + + )} +
+ + ); + })}
); From 5242bbbaded1389ba117dae8089f6d7f505bc2a5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Feb 2026 19:57:30 -0800 Subject: [PATCH 05/10] Fix top-right toast enter and exit transforms - Add position-specific start transform for top-right toasts - Apply matching top-right end transform when dismissing without swipe --- apps/web/src/components/ui/toast.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx index 68bef3fbaf..7b4879e9f0 100644 --- a/apps/web/src/components/ui/toast.tsx +++ b/apps/web/src/components/ui/toast.tsx @@ -213,9 +213,11 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) { // Starting and ending animations "data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]", "data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]", + "data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]", "data-ending-style:opacity-0", // Ending animations (direction-aware) "data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]", + "data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]", "data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]", "data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]", "data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]", From c42d6a6a6489c89d56830cdba7fee752afef5c14 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Feb 2026 22:33:12 -0800 Subject: [PATCH 06/10] Add shortcuts for terminal close and chat with same Git state - Extend keybinding contracts/defaults with `terminal.close` and `chat.newSameGitState` - Wire web handlers for `mod+w` to close focused terminal and `mod+shift+n` to open a thread preserving branch/worktree - Update docs and keybinding tests across server, web, and contracts --- KEYBINDINGS.md | 4 ++ apps/server/src/keybindings.test.ts | 18 ++++++++- apps/server/src/keybindings.ts | 2 + apps/web/src/components/ChatView.tsx | 11 ++++++ apps/web/src/components/Sidebar.tsx | 29 ++++++++++---- apps/web/src/keybindings.test.ts | 45 +++++++++++++++++++++- apps/web/src/keybindings.ts | 16 ++++++++ packages/contracts/src/keybindings.test.ts | 6 +++ packages/contracts/src/keybindings.ts | 2 + 9 files changed, 123 insertions(+), 10 deletions(-) diff --git a/KEYBINDINGS.md b/KEYBINDINGS.md index e3be8baac5..7734d4ebe9 100644 --- a/KEYBINDINGS.md +++ b/KEYBINDINGS.md @@ -22,7 +22,9 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`]( { "key": "mod+j", "command": "terminal.toggle" }, { "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" }, { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" }, + { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" }, { "key": "mod+shift+o", "command": "chat.new" }, + { "key": "mod+shift+n", "command": "chat.newSameGitState" }, { "key": "mod+o", "command": "editor.openFavorite" } ] ``` @@ -46,7 +48,9 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged - `terminal.toggle`: open/close terminal drawer - `terminal.split`: split terminal (in focused terminal context by default) - `terminal.new`: create new terminal (in focused terminal context by default) +- `terminal.close`: close/kill the focused terminal (in focused terminal context by default) - `chat.new`: create a new chat thread for the active project +- `chat.newSameGitState`: create a new chat thread preserving the active thread's branch/worktree state - `editor.openFavorite`: open current project/worktree in the last-used editor ### Key Syntax diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index d761588e93..18ecbabc03 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -1,6 +1,10 @@ import { assert, describe, it } from "vitest"; -import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings"; +import { + DEFAULT_KEYBINDINGS, + compileResolvedKeybindingRule, + parseKeybindingShortcut, +} from "./keybindings"; describe("server keybindings", () => { it("parses shortcuts including plus key", () => { @@ -66,4 +70,16 @@ describe("server keybindings", () => { }), ); }); + + it("defines defaults for terminal.close and chat.newSameGitState", () => { + assert.deepInclude(DEFAULT_KEYBINDINGS, { + key: "mod+w", + command: "terminal.close", + when: "terminalFocus", + }); + assert.deepInclude(DEFAULT_KEYBINDINGS, { + key: "mod+shift+n", + command: "chat.newSameGitState", + }); + }); }); diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index b9a0b4d785..5750b4f4be 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -28,7 +28,9 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+j", command: "terminal.toggle" }, { key: "mod+d", command: "terminal.split", when: "terminalFocus" }, { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, + { key: "mod+w", command: "terminal.close", when: "terminalFocus" }, { key: "mod+shift+o", command: "chat.new" }, + { key: "mod+shift+n", command: "chat.newSameGitState" }, { key: "mod+o", command: "editor.openFavorite" }, ]; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 5114a24468..d308ec63f5 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -52,6 +52,7 @@ import BranchToolbar from "./BranchToolbar"; import GitActionsControl from "./GitActionsControl"; import { isOpenFavoriteEditorShortcut, + isTerminalCloseShortcut, isTerminalNewShortcut, isTerminalSplitShortcut, isTerminalToggleShortcut, @@ -554,6 +555,14 @@ export default function ChatView() { return; } + if (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) { + event.preventDefault(); + event.stopPropagation(); + if (!activeThread?.terminalOpen) return; + closeTerminal(activeThread.activeTerminalId); + return; + } + if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return; event.preventDefault(); event.stopPropagation(); @@ -570,7 +579,9 @@ export default function ChatView() { return () => window.removeEventListener("keydown", handler); }, [ activeThread?.terminalOpen, + activeThread?.activeTerminalId, activeThreadId, + closeTerminal, createNewTerminal, dispatch, splitTerminal, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 60392d0042..2a3deef38b 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -7,7 +7,7 @@ import { useTheme } from "../hooks/useTheme"; import { DEFAULT_MODEL } from "../model-logic"; import { derivePendingApprovals } from "../session-logic"; import { useStore } from "../store"; -import { isChatNewShortcut } from "../keybindings"; +import { isChatNewSameGitStateShortcut, isChatNewShortcut } from "../keybindings"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -140,7 +140,13 @@ export default function Sidebar() { }, [state.threads]); const handleNewThread = useCallback( - (projectId: string) => { + ( + projectId: string, + options?: { + branch?: string | null; + worktreePath?: string | null; + }, + ) => { dispatch({ type: "ADD_THREAD", thread: { @@ -166,8 +172,8 @@ export default function Sidebar() { events: [], error: null, createdAt: new Date().toISOString(), - branch: null, - worktreePath: null, + branch: options?.branch ?? null, + worktreePath: options?.worktreePath ?? null, }, }); }, @@ -381,12 +387,21 @@ export default function Sidebar() { useEffect(() => { const onWindowKeyDown = (event: KeyboardEvent) => { - if (!isChatNewShortcut(event, keybindings)) return; - const activeThread = state.threads.find((t) => t.id === state.activeThreadId); + if (isChatNewSameGitStateShortcut(event, keybindings)) { + const projectId = activeThread?.projectId ?? state.projects[0]?.id; + if (!projectId) return; + event.preventDefault(); + handleNewThread(projectId, { + branch: activeThread?.branch ?? null, + worktreePath: activeThread?.worktreePath ?? null, + }); + return; + } + + if (!isChatNewShortcut(event, keybindings)) return; const projectId = activeThread?.projectId ?? state.projects[0]?.id; if (!projectId) return; - event.preventDefault(); handleNewThread(projectId); }; diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 4ceb1b920a..25df37f431 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -7,10 +7,12 @@ import { type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; import { + isChatNewSameGitStateShortcut, formatShortcutLabel, isChatNewShortcut, isOpenFavoriteEditorShortcut, isTerminalClearShortcut, + isTerminalCloseShortcut, isTerminalNewShortcut, isTerminalSplitShortcut, isTerminalToggleShortcut, @@ -83,7 +85,13 @@ const DEFAULT_BINDINGS = compile([ command: "terminal.new", whenAst: whenIdentifier("terminalFocus"), }, + { + shortcut: modShortcut("w"), + command: "terminal.close", + whenAst: whenIdentifier("terminalFocus"), + }, { shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" }, + { shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newSameGitState" }, { shortcut: modShortcut("o"), command: "editor.openFavorite" }, ]); @@ -101,8 +109,8 @@ describe("isTerminalToggleShortcut", () => { }); }); -describe("split/new terminal shortcuts", () => { - it("requires terminalFocus for default split/new bindings", () => { +describe("split/new/close terminal shortcuts", () => { + it("requires terminalFocus for default split/new/close bindings", () => { assert.isFalse( isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel", @@ -115,6 +123,12 @@ describe("split/new terminal shortcuts", () => { context: { terminalFocus: false }, }), ); + assert.isFalse( + isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, { + platform: "Linux", + context: { terminalFocus: false }, + }), + ); }); it("matches split/new when terminalFocus is true", () => { @@ -130,6 +144,12 @@ describe("split/new terminal shortcuts", () => { context: { terminalFocus: true }, }), ); + assert.isTrue( + isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, { + platform: "Linux", + context: { terminalFocus: true }, + }), + ); }); it("supports when expressions", () => { @@ -225,6 +245,27 @@ describe("chat/editor shortcuts", () => { ); }); + it("matches chat.newSameGitState shortcut", () => { + assert.isTrue( + isChatNewSameGitStateShortcut( + event({ key: "n", metaKey: true, shiftKey: true }), + DEFAULT_BINDINGS, + { + platform: "MacIntel", + }, + ), + ); + assert.isTrue( + isChatNewSameGitStateShortcut( + event({ key: "n", ctrlKey: true, shiftKey: true }), + DEFAULT_BINDINGS, + { + platform: "Linux", + }, + ), + ); + }); + it("matches editor.openFavorite shortcut", () => { assert.isTrue( isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, { diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 4efcd6fee3..070dcae67b 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -190,6 +190,14 @@ export function isTerminalNewShortcut( return matchesCommandShortcut(event, keybindings, "terminal.new", options); } +export function isTerminalCloseShortcut( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + return matchesCommandShortcut(event, keybindings, "terminal.close", options); +} + export function isChatNewShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, @@ -198,6 +206,14 @@ export function isChatNewShortcut( return matchesCommandShortcut(event, keybindings, "chat.new", options); } +export function isChatNewSameGitStateShortcut( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + return matchesCommandShortcut(event, keybindings, "chat.newSameGitState", options); +} + export function isOpenFavoriteEditorShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts index 3427e581c2..7e782a3dbd 100644 --- a/packages/contracts/src/keybindings.test.ts +++ b/packages/contracts/src/keybindings.test.ts @@ -14,6 +14,12 @@ describe("keybindings contracts", () => { command: "terminal.toggle", }); assert.strictEqual(parsed.command, "terminal.toggle"); + + const parsedClose = keybindingRuleSchema.parse({ + key: "mod+w", + command: "terminal.close", + }); + assert.strictEqual(parsedClose.command, "terminal.close"); }); it("rejects invalid command values", () => { diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 921fcbd1dd..62dc840629 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -4,7 +4,9 @@ export const keybindingCommandSchema = z.enum([ "terminal.toggle", "terminal.split", "terminal.new", + "terminal.close", "chat.new", + "chat.newSameGitState", "editor.openFavorite", ]); From bc22a71f10acf5d56ebc6f7b13966a7fc8fdc504 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Feb 2026 23:02:35 -0800 Subject: [PATCH 07/10] Rename local chat shortcut and surface terminal close hints - Replace `chat.newSameGitState` with `chat.newLocal` across contracts, server/web defaults, docs, and tests - Make `chat.new` preserve branch/worktree state while `chat.newLocal` creates a local thread - Show terminal close shortcut labels in drawer action tooltips and tab close controls --- KEYBINDINGS.md | 6 +- apps/server/src/keybindings.test.ts | 4 +- apps/server/src/keybindings.ts | 2 +- apps/web/src/components/ChatView.tsx | 5 ++ apps/web/src/components/Sidebar.tsx | 14 ++-- .../src/components/ThreadTerminalDrawer.tsx | 80 ++++++++++--------- apps/web/src/keybindings.test.ts | 10 +-- apps/web/src/keybindings.ts | 4 +- packages/contracts/src/keybindings.test.ts | 6 ++ packages/contracts/src/keybindings.ts | 2 +- 10 files changed, 76 insertions(+), 57 deletions(-) diff --git a/KEYBINDINGS.md b/KEYBINDINGS.md index 7734d4ebe9..16fce1a4d9 100644 --- a/KEYBINDINGS.md +++ b/KEYBINDINGS.md @@ -24,7 +24,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`]( { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" }, { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" }, { "key": "mod+shift+o", "command": "chat.new" }, - { "key": "mod+shift+n", "command": "chat.newSameGitState" }, + { "key": "mod+shift+n", "command": "chat.newLocal" }, { "key": "mod+o", "command": "editor.openFavorite" } ] ``` @@ -49,8 +49,8 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged - `terminal.split`: split terminal (in focused terminal context by default) - `terminal.new`: create new terminal (in focused terminal context by default) - `terminal.close`: close/kill the focused terminal (in focused terminal context by default) -- `chat.new`: create a new chat thread for the active project -- `chat.newSameGitState`: create a new chat thread preserving the active thread's branch/worktree state +- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state +- `chat.newLocal`: create a new local chat thread for the active project (no worktree context) - `editor.openFavorite`: open current project/worktree in the last-used editor ### Key Syntax diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 18ecbabc03..364ebc4862 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -71,7 +71,7 @@ describe("server keybindings", () => { ); }); - it("defines defaults for terminal.close and chat.newSameGitState", () => { + it("defines defaults for terminal.close and chat.newLocal", () => { assert.deepInclude(DEFAULT_KEYBINDINGS, { key: "mod+w", command: "terminal.close", @@ -79,7 +79,7 @@ describe("server keybindings", () => { }); assert.deepInclude(DEFAULT_KEYBINDINGS, { key: "mod+shift+n", - command: "chat.newSameGitState", + command: "chat.newLocal", }); }); }); diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 5750b4f4be..a78e25b31b 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -30,7 +30,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, { key: "mod+w", command: "terminal.close", when: "terminalFocus" }, { key: "mod+shift+o", command: "chat.new" }, - { key: "mod+shift+n", command: "chat.newSameGitState" }, + { key: "mod+shift+n", command: "chat.newLocal" }, { key: "mod+o", command: "editor.openFavorite" }, ]; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d308ec63f5..ccbbd10d78 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -279,6 +279,10 @@ export default function ChatView() { () => shortcutLabelForCommand(keybindings, "terminal.new"), [keybindings], ); + const closeTerminalShortcutLabel = useMemo( + () => shortcutLabelForCommand(keybindings, "terminal.close"), + [keybindings], + ); const envLocked = Boolean( activeThread && @@ -1464,6 +1468,7 @@ export default function ChatView() { onNewTerminal={createNewTerminal} splitShortcutLabel={splitTerminalShortcutLabel ?? undefined} newShortcutLabel={newTerminalShortcutLabel ?? undefined} + closeShortcutLabel={closeTerminalShortcutLabel ?? undefined} onActiveTerminalChange={activateTerminal} onCloseTerminal={closeTerminal} onHeightChange={(height) => diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2a3deef38b..2c29a6da4f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -7,7 +7,7 @@ import { useTheme } from "../hooks/useTheme"; import { DEFAULT_MODEL } from "../model-logic"; import { derivePendingApprovals } from "../session-logic"; import { useStore } from "../store"; -import { isChatNewSameGitStateShortcut, isChatNewShortcut } from "../keybindings"; +import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -388,14 +388,11 @@ export default function Sidebar() { useEffect(() => { const onWindowKeyDown = (event: KeyboardEvent) => { const activeThread = state.threads.find((t) => t.id === state.activeThreadId); - if (isChatNewSameGitStateShortcut(event, keybindings)) { + if (isChatNewLocalShortcut(event, keybindings)) { const projectId = activeThread?.projectId ?? state.projects[0]?.id; if (!projectId) return; event.preventDefault(); - handleNewThread(projectId, { - branch: activeThread?.branch ?? null, - worktreePath: activeThread?.worktreePath ?? null, - }); + handleNewThread(projectId); return; } @@ -403,7 +400,10 @@ export default function Sidebar() { const projectId = activeThread?.projectId ?? state.projects[0]?.id; if (!projectId) return; event.preventDefault(); - handleNewThread(projectId); + handleNewThread(projectId, { + branch: activeThread?.branch ?? null, + worktreePath: activeThread?.worktreePath ?? null, + }); }; window.addEventListener("keydown", onWindowKeyDown); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index d74ba49a08..1c35459a9b 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -1,5 +1,5 @@ import { FitAddon } from "@xterm/addon-fit"; -import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react"; +import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react"; import { type NativeApi } from "@t3tools/contracts"; import { Terminal, type ITheme } from "@xterm/xterm"; import { @@ -18,10 +18,7 @@ import { preferredTerminalEditor, resolvePathLinkTarget, } from "../terminal-links"; -import { - isTerminalClearShortcut, - terminalNavigationShortcutData, -} from "../keybindings"; +import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -161,10 +158,7 @@ function TerminalViewport({ try { await api.terminal.write({ threadId, terminalId, data }); } catch (error) { - writeSystemMessage( - activeTerminal, - error instanceof Error ? error.message : fallbackError, - ); + writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError); } }; @@ -429,6 +423,7 @@ interface ThreadTerminalDrawerProps { onNewTerminal: () => void; splitShortcutLabel?: string | undefined; newShortcutLabel?: string | undefined; + closeShortcutLabel?: string | undefined; onActiveTerminalChange: (terminalId: string) => void; onCloseTerminal: (terminalId: string) => void; onHeightChange: (height: number) => void; @@ -444,15 +439,9 @@ interface TerminalActionButtonProps { function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) { return ( - - } + } > {children} @@ -483,6 +472,7 @@ export default function ThreadTerminalDrawer({ onNewTerminal, splitShortcutLabel, newShortcutLabel, + closeShortcutLabel, onActiveTerminalChange, onCloseTerminal, onHeightChange, @@ -598,6 +588,9 @@ export default function ThreadTerminalDrawer({ ), [normalizedTerminalIds], ); + const closeTerminalActionLabel = closeShortcutLabel + ? `Close Terminal (${closeShortcutLabel})` + : "Close Terminal"; useEffect(() => { onHeightChangeRef.current = onHeightChange; @@ -709,7 +702,9 @@ export default function ThreadTerminalDrawer({ @@ -725,7 +720,7 @@ export default function ThreadTerminalDrawer({ onCloseTerminal(resolvedActiveTerminalId)} - label="Close Terminal" + label={closeTerminalActionLabel} > @@ -805,16 +800,14 @@ export default function ThreadTerminalDrawer({ onCloseTerminal(resolvedActiveTerminalId)} - label="Close Terminal" + label={closeTerminalActionLabel} > @@ -852,6 +845,9 @@ export default function ThreadTerminalDrawer({ > {terminalGroup.terminalIds.map((terminalId) => { const isActive = terminalId === resolvedActiveTerminalId; + const closeTerminalLabel = `Close ${ + terminalLabelById.get(terminalId) ?? "terminal" + }${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`; return (
{normalizedTerminalIds.length > 1 && ( - + + onCloseTerminal(terminalId)} + aria-label={closeTerminalLabel} + /> + } + > + + + + {closeTerminalLabel} + + )}
); diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 25df37f431..2a3b9c3244 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -7,9 +7,9 @@ import { type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; import { - isChatNewSameGitStateShortcut, formatShortcutLabel, isChatNewShortcut, + isChatNewLocalShortcut, isOpenFavoriteEditorShortcut, isTerminalClearShortcut, isTerminalCloseShortcut, @@ -91,7 +91,7 @@ const DEFAULT_BINDINGS = compile([ whenAst: whenIdentifier("terminalFocus"), }, { shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" }, - { shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newSameGitState" }, + { shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" }, { shortcut: modShortcut("o"), command: "editor.openFavorite" }, ]); @@ -245,9 +245,9 @@ describe("chat/editor shortcuts", () => { ); }); - it("matches chat.newSameGitState shortcut", () => { + it("matches chat.newLocal shortcut", () => { assert.isTrue( - isChatNewSameGitStateShortcut( + isChatNewLocalShortcut( event({ key: "n", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, { @@ -256,7 +256,7 @@ describe("chat/editor shortcuts", () => { ), ); assert.isTrue( - isChatNewSameGitStateShortcut( + isChatNewLocalShortcut( event({ key: "n", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, { diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 070dcae67b..859602e97c 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -206,12 +206,12 @@ export function isChatNewShortcut( return matchesCommandShortcut(event, keybindings, "chat.new", options); } -export function isChatNewSameGitStateShortcut( +export function isChatNewLocalShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, options?: ShortcutMatchOptions, ): boolean { - return matchesCommandShortcut(event, keybindings, "chat.newSameGitState", options); + return matchesCommandShortcut(event, keybindings, "chat.newLocal", options); } export function isOpenFavoriteEditorShortcut( diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts index 7e782a3dbd..12726ea720 100644 --- a/packages/contracts/src/keybindings.test.ts +++ b/packages/contracts/src/keybindings.test.ts @@ -20,6 +20,12 @@ describe("keybindings contracts", () => { command: "terminal.close", }); assert.strictEqual(parsedClose.command, "terminal.close"); + + const parsedLocal = keybindingRuleSchema.parse({ + key: "mod+shift+n", + command: "chat.newLocal", + }); + assert.strictEqual(parsedLocal.command, "chat.newLocal"); }); it("rejects invalid command values", () => { diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 62dc840629..d9d8bfbf9e 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -6,7 +6,7 @@ export const keybindingCommandSchema = z.enum([ "terminal.new", "terminal.close", "chat.new", - "chat.newSameGitState", + "chat.newLocal", "editor.openFavorite", ]); From 228862ac564e8753e56286ee9936ce8352570768 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Feb 2026 23:06:28 -0800 Subject: [PATCH 08/10] doc --- KEYBINDINGS.md | 5 +++-- apps/server/src/keybindings.test.ts | 18 +----------------- apps/server/src/keybindings.ts | 5 +++-- 3 files changed, 7 insertions(+), 21 deletions(-) diff --git a/KEYBINDINGS.md b/KEYBINDINGS.md index 16fce1a4d9..a44f1f5f4f 100644 --- a/KEYBINDINGS.md +++ b/KEYBINDINGS.md @@ -23,8 +23,9 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`]( { "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" }, { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" }, { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" }, - { "key": "mod+shift+o", "command": "chat.new" }, - { "key": "mod+shift+n", "command": "chat.newLocal" }, + { "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" }, + { "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" }, + { "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" }, { "key": "mod+o", "command": "editor.openFavorite" } ] ``` diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 364ebc4862..d761588e93 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -1,10 +1,6 @@ import { assert, describe, it } from "vitest"; -import { - DEFAULT_KEYBINDINGS, - compileResolvedKeybindingRule, - parseKeybindingShortcut, -} from "./keybindings"; +import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings"; describe("server keybindings", () => { it("parses shortcuts including plus key", () => { @@ -70,16 +66,4 @@ describe("server keybindings", () => { }), ); }); - - it("defines defaults for terminal.close and chat.newLocal", () => { - assert.deepInclude(DEFAULT_KEYBINDINGS, { - key: "mod+w", - command: "terminal.close", - when: "terminalFocus", - }); - assert.deepInclude(DEFAULT_KEYBINDINGS, { - key: "mod+shift+n", - command: "chat.newLocal", - }); - }); }); diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index a78e25b31b..97e2de438f 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -29,8 +29,9 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+d", command: "terminal.split", when: "terminalFocus" }, { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, { key: "mod+w", command: "terminal.close", when: "terminalFocus" }, - { key: "mod+shift+o", command: "chat.new" }, - { key: "mod+shift+n", command: "chat.newLocal" }, + { key: "mod+n", command: "chat.new", when: "!terminalFocus" }, + { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, + { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, { key: "mod+o", command: "editor.openFavorite" }, ]; From 51dcb547edf34240a509ffb80f7486d382fd9445 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Feb 2026 00:35:58 -0800 Subject: [PATCH 09/10] Refactor ChatView into memoized subcomponents - Extract header, error, approvals, and timeline into memoized components - Memoize `ChatMarkdown`, pickers, and handlers to reduce avoidable re-renders - Reduce running-time ticker frequency from 250ms to 1000ms --- apps/web/src/components/ChatMarkdown.tsx | 5 +- apps/web/src/components/ChatView.tsx | 741 +++++++++++++---------- 2 files changed, 432 insertions(+), 314 deletions(-) diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 5104ddced5..e16d09e2a3 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1,3 +1,4 @@ +import { memo } from "react"; import type { Components } from "react-markdown"; import ReactMarkdown from "react-markdown"; import rehypeHighlight from "rehype-highlight"; @@ -13,7 +14,7 @@ const markdownComponents: Components = { }, }; -export default function ChatMarkdown({ text }: ChatMarkdownProps) { +function ChatMarkdown({ text }: ChatMarkdownProps) { return (
); } + +export default memo(ChatMarkdown); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index ccbbd10d78..3a48ad40b2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2,6 +2,7 @@ import { EDITORS, type EditorId, ModelSlug, + type NativeApi, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, @@ -15,6 +16,8 @@ import { type FormEvent, Fragment, type KeyboardEvent, + memo, + type RefObject, useCallback, useEffect, useLayoutEffect, @@ -40,6 +43,7 @@ import { derivePendingApprovals, derivePhase, deriveTimelineEntries, + type PendingApproval, deriveWorkLogEntries, formatDuration, formatElapsed, @@ -47,7 +51,7 @@ import { } from "../session-logic"; import { isScrollContainerNearBottom } from "../chat-scroll"; import { useStore } from "../store"; -import type { ChatImageAttachment } from "../types"; +import type { ChatImageAttachment, Thread } from "../types"; import BranchToolbar from "./BranchToolbar"; import GitActionsControl from "./GitActionsControl"; import { @@ -497,7 +501,7 @@ export default function ChatView() { if (phase !== "running") return; const timer = window.setInterval(() => { setNowTick(Date.now()); - }, 250); + }, 1000); return () => { window.clearInterval(timer); }; @@ -889,28 +893,31 @@ export default function ChatView() { }); }; - const onRespondToApproval = async (requestId: string, decision: ProviderApprovalDecision) => { - if (!api || !activeThread?.session) return; + const onRespondToApproval = useCallback( + async (requestId: string, decision: ProviderApprovalDecision) => { + if (!api || !activeThread?.session) return; - setRespondingRequestIds((existing) => - existing.includes(requestId) ? existing : [...existing, requestId], - ); - try { - await api.providers.respondToRequest({ - sessionId: activeThread.session.sessionId, - requestId, - decision, - }); - } catch (err) { - dispatch({ - type: "SET_ERROR", - threadId: activeThread.id, - error: err instanceof Error ? err.message : "Failed to submit approval decision.", - }); - } finally { - setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); - } - }; + setRespondingRequestIds((existing) => + existing.includes(requestId) ? existing : [...existing, requestId], + ); + try { + await api.providers.respondToRequest({ + sessionId: activeThread.session.sessionId, + requestId, + decision, + }); + } catch (err) { + dispatch({ + type: "SET_ERROR", + threadId: activeThread.id, + error: err instanceof Error ? err.message : "Failed to submit approval decision.", + }); + } finally { + setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); + } + }, + [activeThread?.id, activeThread?.session, api, dispatch], + ); const onModelSelect = useCallback( (model: ModelSlug) => { @@ -945,6 +952,18 @@ export default function ChatView() { void onSend(e as unknown as FormEvent); } }; + const onToggleWorkGroup = useCallback((groupId: string) => { + setExpandedWorkGroups((existing) => ({ + ...existing, + [groupId]: !existing[groupId], + })); + }, []); + const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => { + setExpandedImage(image); + }, []); + const onToggleDiff = useCallback(() => { + dispatch({ type: "TOGGLE_DIFF" }); + }, [dispatch]); // Empty state: no active thread if (!activeThread) { @@ -970,101 +989,24 @@ export default function ChatView() {
-
-

{activeThread.title}

- {activeProject && {activeProject.name}} -
-
- {/* Open in editor */} - {activeProject && } - {/* Git actions */} - {activeProject && } - - {/* Diff toggle */} - -
+
{/* Error banner */} - {activeThread.error && ( -
- - - - {activeThread.error} - - -
- )} - - {pendingApprovals.length > 0 && ( -
- {pendingApprovals.map((approval) => { - const isResponding = respondingRequestIds.includes(approval.requestId); - - return ( - - - - {approval.requestKind === "command" - ? "Command approval requested" - : "File-change approval requested"} - - - {approval.detail} - - - - - - - - - ); - })} -
- )} + + {/* Messages */}
- {activeThread.messages.length === 0 && !isWorking ? ( -
-

- Send a message to start the conversation. -

-
- ) : ( -
- {timelineEntries.map((timelineEntry, index) => { - if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") { - return null; - } - - const showCompletionDivider = - timelineEntry.kind === "message" && - timelineEntry.message.role === "assistant" && - completionDividerBeforeEntryId === timelineEntry.id; - - if (timelineEntry.kind === "work") { - const groupedEntries = [timelineEntry.entry]; - let cursor = index + 1; - while (cursor < timelineEntries.length) { - const nextEntry = timelineEntries[cursor]; - if (!nextEntry || nextEntry.kind !== "work") break; - groupedEntries.push(nextEntry.entry); - cursor += 1; - } - - const groupId = timelineEntry.id; - const isExpanded = expandedWorkGroups[groupId] ?? false; - const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES; - const visibleEntries = - hasOverflow && !isExpanded - ? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) - : groupedEntries; - const hiddenCount = groupedEntries.length - visibleEntries.length; - const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool"); - const groupLabel = onlyToolEntries - ? groupedEntries.length === 1 - ? "Tool call" - : `Tool calls (${groupedEntries.length})` - : groupedEntries.length === 1 - ? "Work event" - : `Work log (${groupedEntries.length})`; - - return ( - -
-
-

- {groupLabel} -

- {hasOverflow && ( - - )} -
-
- {visibleEntries.map((workEntry) => ( -
- -

- {workEntry.detail ? ( - <> - {workEntry.label} - - {workEntry.detail} - - - ) : ( - workEntry.label - )} -

-
- ))} -
-
-
- ); - } - - if (timelineEntry.message.role === "user") { - const userImages = timelineEntry.message.attachments ?? []; - return ( - -
-
- {userImages.length > 0 && ( -
- {userImages.map((image) => ( -
- {image.previewUrl ? ( - {image.name} - setExpandedImage({ src: image.previewUrl!, name: image.name }) - } - /> - ) : ( -
- {image.name} -
- )} -
- ))} -
- )} - {timelineEntry.message.text && ( -
-                            {timelineEntry.message.text}
-                          
- )} -

- {formatTimestamp(timelineEntry.message.createdAt)} -

-
-
-
- ); - } - - return ( - - {showCompletionDivider && ( -
- - - {completionSummary ? `Response • ${completionSummary}` : "Response"} - - -
- )} -
- -

- {formatMessageMeta( - timelineEntry.message.createdAt, - timelineEntry.message.streaming - ? formatElapsed(timelineEntry.message.createdAt, nowIso) - : formatElapsed( - timelineEntry.message.createdAt, - assistantCompletionByItemId.get(timelineEntry.message.id), - ), - )} -

-
-
- ); - })} - {isWorking && ( -
- -
- - - - - -
-
- )} -
-
- )} +
{/* Input bar */} @@ -1519,7 +1282,355 @@ export default function ChatView() { ); } -function ModelPicker(props: { model: ModelSlug; onModelChange: (model: ModelSlug) => void }) { +interface ChatHeaderProps { + activeThreadTitle: string; + activeProjectName: string | undefined; + keybindings: ResolvedKeybindingsConfig; + api: NativeApi | undefined; + gitCwd: string | null; + diffOpen: boolean; + onToggleDiff: () => void; +} + +const ChatHeader = memo(function ChatHeader({ + activeThreadTitle, + activeProjectName, + keybindings, + api, + gitCwd, + diffOpen, + onToggleDiff, +}: ChatHeaderProps) { + return ( + <> +
+

{activeThreadTitle}

+ {activeProjectName && {activeProjectName}} +
+
+ {activeProjectName && } + {activeProjectName && } + +
+ + ); +}); + +const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: string | null }) { + if (!error) return null; + return ( +
+ + + + {error} + + +
+ ); +}); + +interface PendingApprovalsPanelProps { + pendingApprovals: PendingApproval[]; + respondingRequestIds: string[]; + onRespondToApproval: (requestId: string, decision: ProviderApprovalDecision) => Promise; +} + +const PendingApprovalsPanel = memo(function PendingApprovalsPanel({ + pendingApprovals, + respondingRequestIds, + onRespondToApproval, +}: PendingApprovalsPanelProps) { + if (pendingApprovals.length === 0) return null; + return ( +
+ {pendingApprovals.map((approval) => { + const isResponding = respondingRequestIds.includes(approval.requestId); + + return ( + + + + {approval.requestKind === "command" + ? "Command approval requested" + : "File-change approval requested"} + + + {approval.detail} + + + + + + + + + ); + })} +
+ ); +}); + +interface MessagesTimelineProps { + activeThread: Thread; + isWorking: boolean; + timelineEntries: ReturnType; + completionDividerBeforeEntryId: string | null; + completionSummary: string | null; + assistantCompletionByItemId: Map; + nowIso: string; + expandedWorkGroups: Record; + onToggleWorkGroup: (groupId: string) => void; + onImageExpand: (image: ExpandedImagePreview) => void; + messagesEndRef: RefObject; +} + +const MessagesTimeline = memo(function MessagesTimeline({ + activeThread, + isWorking, + timelineEntries, + completionDividerBeforeEntryId, + completionSummary, + assistantCompletionByItemId, + nowIso, + expandedWorkGroups, + onToggleWorkGroup, + onImageExpand, + messagesEndRef, +}: MessagesTimelineProps) { + if (activeThread.messages.length === 0 && !isWorking) { + return ( +
+

Send a message to start the conversation.

+
+ ); + } + + return ( +
+ {timelineEntries.map((timelineEntry, index) => { + if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") { + return null; + } + + const showCompletionDivider = + timelineEntry.kind === "message" && + timelineEntry.message.role === "assistant" && + completionDividerBeforeEntryId === timelineEntry.id; + + if (timelineEntry.kind === "work") { + const groupedEntries = [timelineEntry.entry]; + let cursor = index + 1; + while (cursor < timelineEntries.length) { + const nextEntry = timelineEntries[cursor]; + if (!nextEntry || nextEntry.kind !== "work") break; + groupedEntries.push(nextEntry.entry); + cursor += 1; + } + + const groupId = timelineEntry.id; + const isExpanded = expandedWorkGroups[groupId] ?? false; + const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES; + const visibleEntries = + hasOverflow && !isExpanded + ? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) + : groupedEntries; + const hiddenCount = groupedEntries.length - visibleEntries.length; + const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool"); + const groupLabel = onlyToolEntries + ? groupedEntries.length === 1 + ? "Tool call" + : `Tool calls (${groupedEntries.length})` + : groupedEntries.length === 1 + ? "Work event" + : `Work log (${groupedEntries.length})`; + + return ( + +
+
+

+ {groupLabel} +

+ {hasOverflow && ( + + )} +
+
+ {visibleEntries.map((workEntry) => ( +
+ +

+ {workEntry.detail ? ( + <> + {workEntry.label} + + {workEntry.detail} + + + ) : ( + workEntry.label + )} +

+
+ ))} +
+
+
+ ); + } + + if (timelineEntry.message.role === "user") { + const userImages = timelineEntry.message.attachments ?? []; + return ( + +
+
+ {userImages.length > 0 && ( +
+ {userImages.map((image) => ( +
+ {image.previewUrl ? ( + {image.name} + onImageExpand({ src: image.previewUrl!, name: image.name }) + } + /> + ) : ( +
+ {image.name} +
+ )} +
+ ))} +
+ )} + {timelineEntry.message.text && ( +
+                      {timelineEntry.message.text}
+                    
+ )} +

+ {formatTimestamp(timelineEntry.message.createdAt)} +

+
+
+
+ ); + } + + return ( + + {showCompletionDivider && ( +
+ + + {completionSummary ? `Response • ${completionSummary}` : "Response"} + + +
+ )} +
+ +

+ {formatMessageMeta( + timelineEntry.message.createdAt, + timelineEntry.message.streaming + ? formatElapsed(timelineEntry.message.createdAt, nowIso) + : formatElapsed( + timelineEntry.message.createdAt, + assistantCompletionByItemId.get(timelineEntry.message.id), + ), + )} +

+
+
+ ); + })} + {isWorking && ( +
+ +
+ + + + + +
+
+ )} +
+
+ ); +}); + +const ModelPicker = memo(function ModelPicker(props: { + model: ModelSlug; + onModelChange: (model: ModelSlug) => void; +}) { return ( ); -} +}); -function ReasoningEffortPicker(props: { +const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: { effort: ReasoningEffort; onEffortChange: (effort: ReasoningEffort) => void; }) { @@ -1562,9 +1673,13 @@ function ReasoningEffortPicker(props: { ); -} +}); -function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig }) { +const OpenInPicker = memo(function OpenInPicker({ + keybindings, +}: { + keybindings: ResolvedKeybindingsConfig; +}) { const [lastEditor, setLastEditor] = useState(() => { const stored = localStorage.getItem(LAST_EDITOR_KEY); return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id; @@ -1648,4 +1763,4 @@ function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig ); -} +}); From 73fa2d66c79eb1351fbae55a81c61e1f7b88c619 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Feb 2026 00:47:08 -0800 Subject: [PATCH 10/10] Use stable IDs for approval actions in ChatView - Derive `activeSessionId` and `activeThreadId` before approval callbacks - Avoid stale thread/session captures when submitting approval decisions - Pass `hasMessages` to `MessagesTimeline` instead of the full thread --- apps/web/src/components/ChatView.tsx | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3a48ad40b2..382d30b536 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -51,7 +51,7 @@ import { } from "../session-logic"; import { isScrollContainerNearBottom } from "../chat-scroll"; import { useStore } from "../store"; -import type { ChatImageAttachment, Thread } from "../types"; +import type { ChatImageAttachment } from "../types"; import BranchToolbar from "./BranchToolbar"; import GitActionsControl from "./GitActionsControl"; import { @@ -168,6 +168,7 @@ export default function ChatView() { const activeThread = state.threads.find((t) => t.id === state.activeThreadId); const activeThreadId = activeThread?.id ?? null; + const activeSessionId = activeThread?.session?.sessionId; const activeProject = state.projects.find((p) => p.id === activeThread?.projectId); const selectedModel = resolveModelSlug( activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL, @@ -895,28 +896,28 @@ export default function ChatView() { const onRespondToApproval = useCallback( async (requestId: string, decision: ProviderApprovalDecision) => { - if (!api || !activeThread?.session) return; + if (!api || !activeSessionId || !activeThreadId) return; setRespondingRequestIds((existing) => existing.includes(requestId) ? existing : [...existing, requestId], ); try { await api.providers.respondToRequest({ - sessionId: activeThread.session.sessionId, + sessionId: activeSessionId, requestId, decision, }); } catch (err) { dispatch({ type: "SET_ERROR", - threadId: activeThread.id, + threadId: activeThreadId, error: err instanceof Error ? err.message : "Failed to submit approval decision.", }); } finally { setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); } }, - [activeThread?.id, activeThread?.session, api, dispatch], + [activeSessionId, activeThreadId, api, dispatch], ); const onModelSelect = useCallback( @@ -1015,7 +1016,7 @@ export default function ChatView() { onScroll={onMessagesScroll} > 0} isWorking={isWorking} timelineEntries={timelineEntries} completionDividerBeforeEntryId={completionDividerBeforeEntryId} @@ -1413,7 +1414,7 @@ const PendingApprovalsPanel = memo(function PendingApprovalsPanel({ }); interface MessagesTimelineProps { - activeThread: Thread; + hasMessages: boolean; isWorking: boolean; timelineEntries: ReturnType; completionDividerBeforeEntryId: string | null; @@ -1427,7 +1428,7 @@ interface MessagesTimelineProps { } const MessagesTimeline = memo(function MessagesTimeline({ - activeThread, + hasMessages, isWorking, timelineEntries, completionDividerBeforeEntryId, @@ -1439,7 +1440,7 @@ const MessagesTimeline = memo(function MessagesTimeline({ onImageExpand, messagesEndRef, }: MessagesTimelineProps) { - if (activeThread.messages.length === 0 && !isWorking) { + if (!hasMessages && !isWorking) { return (

Send a message to start the conversation.