diff --git a/KEYBINDINGS.md b/KEYBINDINGS.md index e3be8baac5..a44f1f5f4f 100644 --- a/KEYBINDINGS.md +++ b/KEYBINDINGS.md @@ -22,7 +22,10 @@ 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+shift+o", "command": "chat.new" }, + { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" }, + { "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" } ] ``` @@ -46,7 +49,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) -- `chat.new`: create a new chat thread for the active project +- `terminal.close`: close/kill the focused terminal (in focused terminal context by default) +- `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.ts b/apps/server/src/keybindings.ts index b9a0b4d785..97e2de438f 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -28,7 +28,10 @@ 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+shift+o", command: "chat.new" }, + { key: "mod+w", command: "terminal.close", when: "terminalFocus" }, + { 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/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 b9e38527c2..3a54834d61 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, @@ -52,6 +56,7 @@ import BranchToolbar from "./BranchToolbar"; import GitActionsControl from "./GitActionsControl"; import { isOpenFavoriteEditorShortcut, + isTerminalCloseShortcut, isTerminalNewShortcut, isTerminalSplitShortcut, isTerminalToggleShortcut, @@ -163,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, @@ -278,6 +284,10 @@ export default function ChatView() { () => shortcutLabelForCommand(keybindings, "terminal.new"), [keybindings], ); + const closeTerminalShortcutLabel = useMemo( + () => shortcutLabelForCommand(keybindings, "terminal.close"), + [keybindings], + ); const envLocked = Boolean( activeThread && @@ -492,7 +502,7 @@ export default function ChatView() { if (phase !== "running") return; const timer = window.setInterval(() => { setNowTick(Date.now()); - }, 250); + }, 1000); return () => { window.clearInterval(timer); }; @@ -554,6 +564,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 +588,9 @@ export default function ChatView() { return () => window.removeEventListener("keydown", handler); }, [ activeThread?.terminalOpen, + activeThread?.activeTerminalId, activeThreadId, + closeTerminal, createNewTerminal, dispatch, splitTerminal, @@ -874,28 +894,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 || !activeSessionId || !activeThreadId) 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: activeSessionId, + requestId, + decision, + }); + } catch (err) { + dispatch({ + type: "SET_ERROR", + threadId: activeThreadId, + error: err instanceof Error ? err.message : "Failed to submit approval decision.", + }); + } finally { + setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); + } + }, + [activeSessionId, activeThreadId, api, dispatch], + ); const onModelSelect = useCallback( (model: ModelSlug) => { @@ -930,6 +953,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) { @@ -955,101 +990,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 && ( -
- -
- - - - - -
-
- )} -
-
- )} + 0} + isWorking={isWorking} + timelineEntries={timelineEntries} + completionDividerBeforeEntryId={completionDividerBeforeEntryId} + completionSummary={completionSummary} + assistantCompletionByItemId={assistantCompletionByItemId} + nowIso={nowIso} + expandedWorkGroups={expandedWorkGroups} + onToggleWorkGroup={onToggleWorkGroup} + onImageExpand={onExpandTimelineImage} + messagesEndRef={messagesEndRef} + />
{/* Input bar */} @@ -1455,6 +1234,7 @@ export default function ChatView() { onNewTerminal={createNewTerminal} splitShortcutLabel={splitTerminalShortcutLabel ?? undefined} newShortcutLabel={newTerminalShortcutLabel ?? undefined} + closeShortcutLabel={closeTerminalShortcutLabel ?? undefined} onActiveTerminalChange={activateTerminal} onCloseTerminal={closeTerminal} onHeightChange={(height) => @@ -1505,7 +1285,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 { + hasMessages: boolean; + 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({ + hasMessages, + isWorking, + timelineEntries, + completionDividerBeforeEntryId, + completionSummary, + assistantCompletionByItemId, + nowIso, + expandedWorkGroups, + onToggleWorkGroup, + onImageExpand, + messagesEndRef, +}: MessagesTimelineProps) { + if (!hasMessages && !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; }) { @@ -1548,9 +1676,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; @@ -1634,4 +1766,4 @@ function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig ); -} +}); 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/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2cbe226639..667a613c84 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 { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -151,7 +151,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: { @@ -178,8 +184,8 @@ export default function Sidebar() { events: [], error: null, createdAt: new Date().toISOString(), - branch: null, - worktreePath: null, + branch: options?.branch ?? null, + worktreePath: options?.worktreePath ?? null, }, }); }, @@ -403,14 +409,23 @@ 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 (isChatNewLocalShortcut(event, keybindings)) { + const projectId = activeThread?.projectId ?? state.projects[0]?.id; + if (!projectId) return; + event.preventDefault(); + handleNewThread(projectId); + return; + } + + if (!isChatNewShortcut(event, keybindings)) return; 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 41cb7c5e16..836286c999 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 { Globe, Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react"; +import { Globe, Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react"; import { type NativeApi } from "@t3tools/contracts"; import { Terminal, type ITheme } from "@xterm/xterm"; import { @@ -16,7 +16,7 @@ import { preferredTerminalEditor, resolvePathLinkTarget, } from "../terminal-links"; -import { isTerminalClearShortcut } from "../keybindings"; +import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -189,24 +189,29 @@ 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", - ); + writeSystemMessage(activeTerminal, 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; }); @@ -457,6 +462,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; @@ -472,15 +478,9 @@ interface TerminalActionButtonProps { function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) { return ( - - } + } > {children} @@ -513,6 +513,7 @@ export default function ThreadTerminalDrawer({ onNewTerminal, splitShortcutLabel, newShortcutLabel, + closeShortcutLabel, onActiveTerminalChange, onCloseTerminal, onHeightChange, @@ -632,6 +633,9 @@ export default function ThreadTerminalDrawer({ () => new Set(runningTerminalIds.map((terminalId) => terminalId.trim())), [runningTerminalIds], ); + const closeTerminalActionLabel = closeShortcutLabel + ? `Close Terminal (${closeShortcutLabel})` + : "Close Terminal"; useEffect(() => { onHeightChangeRef.current = onHeightChange; @@ -752,7 +756,9 @@ export default function ThreadTerminalDrawer({ @@ -768,7 +774,7 @@ export default function ThreadTerminalDrawer({ onCloseTerminal(resolvedActiveTerminalId)} - label="Close Terminal" + label={closeTerminalActionLabel} > @@ -848,16 +854,14 @@ export default function ThreadTerminalDrawer({ onCloseTerminal(resolvedActiveTerminalId)} - label="Close Terminal" + label={closeTerminalActionLabel} > @@ -900,6 +904,9 @@ export default function ThreadTerminalDrawer({ runningTerminalIdSet, runningTerminalPorts, ); + 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/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 6c9614a91a..7b4879e9f0 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, @@ -12,14 +13,18 @@ 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; 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 +55,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 ( @@ -64,6 +147,18 @@ 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)); + for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) { + if (!activeToastIds.has(toastId)) { + threadToastVisibleTimeoutRemainingMs.delete(toastId); + } + } + }, [toasts]); return ( @@ -81,96 +176,107 @@ 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} + + )} + + + ); + })} ); diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 622f2dea07..2a3b9c3244 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -9,12 +9,15 @@ import { import { formatShortcutLabel, isChatNewShortcut, + isChatNewLocalShortcut, isOpenFavoriteEditorShortcut, isTerminalClearShortcut, + isTerminalCloseShortcut, isTerminalNewShortcut, isTerminalSplitShortcut, isTerminalToggleShortcut, shortcutLabelForCommand, + terminalNavigationShortcutData, type ShortcutEventLike, } from "./keybindings"; @@ -82,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.newLocal" }, { shortcut: modShortcut("o"), command: "editor.openFavorite" }, ]); @@ -100,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", @@ -114,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", () => { @@ -129,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", () => { @@ -224,6 +245,27 @@ describe("chat/editor shortcuts", () => { ); }); + it("matches chat.newLocal shortcut", () => { + assert.isTrue( + isChatNewLocalShortcut( + event({ key: "n", metaKey: true, shiftKey: true }), + DEFAULT_BINDINGS, + { + platform: "MacIntel", + }, + ), + ); + assert.isTrue( + isChatNewLocalShortcut( + 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, { @@ -324,6 +366,65 @@ 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", () => { + 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")); + }); + + 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 5b908344b8..859602e97c 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; @@ -25,6 +26,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"; @@ -184,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, @@ -192,6 +206,14 @@ export function isChatNewShortcut( return matchesCommandShortcut(event, keybindings, "chat.new", options); } +export function isChatNewLocalShortcut( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + return matchesCommandShortcut(event, keybindings, "chat.newLocal", options); +} + export function isOpenFavoriteEditorShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, @@ -204,6 +226,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) { @@ -219,3 +245,42 @@ export function isTerminalClearShortcut( !event.shiftKey ); } + +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); + 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; +} diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts index 3427e581c2..12726ea720 100644 --- a/packages/contracts/src/keybindings.test.ts +++ b/packages/contracts/src/keybindings.test.ts @@ -14,6 +14,18 @@ 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"); + + 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 921fcbd1dd..d9d8bfbf9e 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.newLocal", "editor.openFavorite", ]);