Compare commits

..
Author SHA1 Message Date
Julius Marminge 4c49b8a514 Block deletion of projects that still have threads
- Show warning toast when attempting to delete a non-empty project
- Simplify confirmation copy to emphasize irreversible deletion
- Remove thread/worktree/session cleanup from project delete flow
2026-02-15 16:20:15 -08:00
Julius Marminge f6a0b67e89 Confirm project deletion and clean up orphaned worktrees
- Prompt before deleting a project with thread and linked worktree counts
- Best-effort remove orphaned worktrees when project threads are deleted
- Show toast with error details if project deletion fails
2026-02-15 16:20:15 -08:00
Julius Marminge ebac75593e Delete projects from the sidebar context menu
- Add project right-click Delete action in `Sidebar` and clean up sessions/terminals before removal
- Add `DELETE_PROJECT` reducer action to remove the project, its threads, and reset active thread
- Add reducer test coverage for project deletion behavior
2026-02-15 16:19:17 -08:00
17 changed files with 464 additions and 1084 deletions

No files matched your search

+2 -7
View File
@@ -22,10 +22,7 @@ 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+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+shift+o", "command": "chat.new" },
{ "key": "mod+o", "command": "editor.openFavorite" }
]
```
@@ -49,9 +46,7 @@ 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 preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `chat.new`: create a new chat thread for the active project
- `editor.openFavorite`: open current project/worktree in the last-used editor
### Key Syntax
+1 -4
View File
@@ -28,10 +28,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ 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+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+shift+o", command: "chat.new" },
{ key: "mod+o", command: "editor.openFavorite" },
];
@@ -1,56 +0,0 @@
import type { GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
const branches: GitBranch[] = [
{
name: "main",
current: true,
isDefault: true,
worktreePath: null,
},
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
];
describe("deriveSyncedLocalBranch", () => {
it("syncs to git current branch in local mode", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: null,
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBe("main");
});
it("does not sync when creating a new worktree", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: null,
envMode: "worktree",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
it("does not sync when thread already targets a worktree path", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
});
@@ -1,28 +0,0 @@
import type { GitBranch } from "@t3tools/contracts";
interface DeriveSyncedLocalBranchInput {
activeThreadId: string | undefined;
activeWorktreePath: string | null;
envMode: "local" | "worktree";
activeThreadBranch: string | null;
queryBranches: GitBranch[] | undefined;
}
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
}: DeriveSyncedLocalBranchInput): string | null {
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
return null;
}
const currentBranch = queryBranches?.find((branch) => branch.current);
if (!currentBranch || currentBranch.name === activeThreadBranch) {
return null;
}
return currentBranch.name;
}
+7 -23
View File
@@ -9,7 +9,6 @@ import {
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
@@ -26,15 +25,9 @@ interface BranchToolbarProps {
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
onComposerFocusRequest?: () => void;
}
export default function BranchToolbar({
envMode,
onEnvModeChange,
envLocked,
onComposerFocusRequest,
}: BranchToolbarProps) {
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
const { state, dispatch } = useStore();
const api = useNativeApi();
const queryClient = useQueryClient();
@@ -87,22 +80,17 @@ export default function BranchToolbar({
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
if (!activeThreadId || activeWorktreePath) return;
const current = queryBranches?.find((branch) => branch.current);
if (!current) return;
if (current.name === activeThreadBranch) return;
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
branch: current.name,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
@@ -135,7 +123,6 @@ export default function BranchToolbar({
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
@@ -148,7 +135,6 @@ export default function BranchToolbar({
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
@@ -157,7 +143,6 @@ export default function BranchToolbar({
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
});
};
@@ -171,7 +156,6 @@ export default function BranchToolbar({
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
});
};
+1 -4
View File
@@ -1,4 +1,3 @@
import { memo } from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
@@ -14,7 +13,7 @@ const markdownComponents: Components = {
},
};
function ChatMarkdown({ text }: ChatMarkdownProps) {
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
@@ -27,5 +26,3 @@ function ChatMarkdown({ text }: ChatMarkdownProps) {
</div>
);
}
export default memo(ChatMarkdown);
+322 -483
View File
@@ -2,7 +2,6 @@ import {
EDITORS,
type EditorId,
ModelSlug,
type NativeApi,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
@@ -16,8 +15,6 @@ import {
type FormEvent,
Fragment,
type KeyboardEvent,
memo,
type RefObject,
useCallback,
useEffect,
useLayoutEffect,
@@ -43,7 +40,6 @@ import {
derivePendingApprovals,
derivePhase,
deriveTimelineEntries,
type PendingApproval,
deriveWorkLogEntries,
formatDuration,
formatElapsed,
@@ -56,7 +52,6 @@ import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
isOpenFavoriteEditorShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
@@ -168,7 +163,6 @@ 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,
@@ -284,10 +278,6 @@ export default function ChatView() {
() => shortcutLabelForCommand(keybindings, "terminal.new"),
[keybindings],
);
const closeTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.close"),
[keybindings],
);
const envLocked = Boolean(
activeThread &&
@@ -308,11 +298,6 @@ export default function ChatView() {
const cursor = textarea.value.length;
textarea.setSelectionRange(cursor, cursor);
}, []);
const scheduleComposerFocus = useCallback(() => {
window.requestAnimationFrame(() => {
focusComposer();
});
}, [focusComposer]);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
dispatch({
@@ -384,7 +369,6 @@ export default function ChatView() {
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
scheduleComposerFocus();
if (!api) return;
const sessionIds = state.threads
@@ -502,7 +486,7 @@ export default function ChatView() {
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 1000);
}, 250);
return () => {
window.clearInterval(timer);
};
@@ -564,14 +548,6 @@ 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();
@@ -588,9 +564,7 @@ export default function ChatView() {
return () => window.removeEventListener("keydown", handler);
}, [
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
activeThreadId,
closeTerminal,
createNewTerminal,
dispatch,
splitTerminal,
@@ -894,58 +868,37 @@ export default function ChatView() {
});
};
const onRespondToApproval = useCallback(
async (requestId: string, decision: ProviderApprovalDecision) => {
if (!api || !activeSessionId || !activeThreadId) return;
const onRespondToApproval = async (requestId: string, decision: ProviderApprovalDecision) => {
if (!api || !activeThread?.session) return;
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) => {
if (!activeThread) return;
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
setRespondingRequestIds((existing) =>
existing.includes(requestId) ? existing : [...existing, requestId],
);
try {
await api.providers.respondToRequest({
sessionId: activeThread.session.sessionId,
requestId,
decision,
});
scheduleComposerFocus();
},
[activeThread, dispatch, scheduleComposerFocus],
);
const onEffortSelect = useCallback(
(effort: ReasoningEffort) => {
setSelectedEffort(effort);
scheduleComposerFocus();
},
[scheduleComposerFocus],
);
const onEnvModeChange = useCallback(
(mode: "local" | "worktree") => {
setEnvMode(mode);
scheduleComposerFocus();
},
[scheduleComposerFocus],
);
} 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));
}
};
const onModelSelect = (model: ModelSlug) => {
if (!activeThread) return;
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
};
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -953,18 +906,6 @@ 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) {
@@ -990,24 +931,101 @@ export default function ChatView() {
<header
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<ChatHeader
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
keybindings={keybindings}
api={api}
gitCwd={gitCwd}
diffOpen={state.diffOpen}
onToggleDiff={onToggleDiff}
/>
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">{activeThread.title}</h2>
{activeProject && <Badge variant="outline">{activeProject.name}</Badge>}
</div>
<div className="flex items-center gap-3">
{/* Open in editor */}
{activeProject && <OpenInPicker keybindings={keybindings} />}
{/* Git actions */}
{activeProject && <GitActionsControl api={api} gitCwd={gitCwd} />}
{/* Diff toggle */}
<Button
size="xs"
variant="ghost"
className={cn(
"text-muted-foreground/70 hover:text-foreground/80",
state.diffOpen && "bg-accent text-accent-foreground",
)}
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
Diff
</Button>
</div>
</header>
{/* Error banner */}
<ThreadErrorBanner error={activeThread.error} />
<PendingApprovalsPanel
pendingApprovals={pendingApprovals}
respondingRequestIds={respondingRequestIds}
onRespondToApproval={onRespondToApproval}
/>
{activeThread.error && (
<div className="pt-3 mx-auto max-w-3xl">
<Alert variant="error">
<CircleAlertIcon />
<AlertDescription className="line-clamp-3" title={activeThread.error}>
{activeThread.error}
</AlertDescription>
</Alert>
</div>
)}
{pendingApprovals.length > 0 && (
<div className="pt-3 mx-auto max-w-3xl space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<Alert variant="warning" key={approval.requestId}>
<InfoIcon />
<AlertTitle className="text-xs">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</AlertTitle>
<AlertDescription
className="truncate block font-mono text-[11px]"
title={approval.detail}
>
{approval.detail}
</AlertDescription>
<AlertAction className="col-start-2! -col-end-1! mt-1.5 sm:row-start-auto sm:row-end-auto">
<Button
size="xs"
variant="default"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</Button>
<Button
size="xs"
variant="outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</Button>
<Button
size="xs"
variant="destructive-outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</Button>
<Button
size="xs"
variant="ghost"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</Button>
</AlertAction>
</Alert>
);
})}
</div>
)}
{/* Messages */}
<div
@@ -1015,19 +1033,198 @@ export default function ChatView() {
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
onScroll={onMessagesScroll}
>
<MessagesTimeline
hasMessages={activeThread.messages.length > 0}
isWorking={isWorking}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
assistantCompletionByItemId={assistantCompletionByItemId}
nowIso={nowIso}
expandedWorkGroups={expandedWorkGroups}
onToggleWorkGroup={onToggleWorkGroup}
onImageExpand={onExpandTimelineImage}
messagesEndRef={messagesEndRef}
/>
{activeThread.messages.length === 0 && !isWorking ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
) : (
<div className="mx-auto max-w-3xl space-y-4">
{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 (
<Fragment key={timelineEntry.id}>
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
<div className="mb-1.5 flex items-center justify-between gap-3">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
{groupLabel}
</p>
{hasOverflow && (
<button
type="button"
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() =>
setExpandedWorkGroups((existing) => ({
...existing,
[groupId]: !existing[groupId],
}))
}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
<div className="space-y-1">
{visibleEntries.map((workEntry) => (
<div
key={`work-row:${workEntry.id}`}
className="flex items-start gap-2 py-0.5"
>
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
>
{workEntry.detail ? (
<>
{workEntry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={workEntry.detail}
>
{workEntry.detail}
</span>
</>
) : (
workEntry.label
)}
</p>
</div>
))}
</div>
</div>
</Fragment>
);
}
if (timelineEntry.message.role === "user") {
const userImages = timelineEntry.message.attachments ?? [];
return (
<Fragment key={timelineEntry.id}>
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() =>
setExpandedImage({ src: image.previewUrl!, name: image.name })
}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
))}
</div>
)}
{timelineEntry.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
</Fragment>
);
}
return (
<Fragment key={timelineEntry.id}>
{showCompletionDivider && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
<div className="px-1 py-0.5">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
</div>
</Fragment>
);
})}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
)}
</div>
{/* Input bar */}
@@ -1105,7 +1302,7 @@ export default function ChatView() {
<Separator orientation="vertical" className="mx-0.5 h-4" />
{/* Reasoning effort */}
<ReasoningEffortPicker effort={selectedEffort} onEffortChange={onEffortSelect} />
<ReasoningEffortPicker effort={selectedEffort} onEffortChange={setSelectedEffort} />
{/* Divider */}
<Separator orientation="vertical" className="mx-0.5 h-4" />
@@ -1208,12 +1405,7 @@ export default function ChatView() {
</div>
{isGitRepo && (
<BranchToolbar
envMode={envMode}
onEnvModeChange={onEnvModeChange}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
/>
<BranchToolbar envMode={envMode} onEnvModeChange={setEnvMode} envLocked={envLocked} />
)}
{activeThread.terminalOpen && api && activeProject && (
@@ -1232,7 +1424,6 @@ export default function ChatView() {
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
@@ -1283,355 +1474,7 @@ export default function ChatView() {
);
}
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 (
<>
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">{activeThreadTitle}</h2>
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
</div>
<div className="flex items-center gap-3">
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
<Button
size="xs"
variant="ghost"
className={cn(
"text-muted-foreground/70 hover:text-foreground/80",
diffOpen && "bg-accent text-accent-foreground",
)}
onClick={onToggleDiff}
>
Diff
</Button>
</div>
</>
);
});
const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: string | null }) {
if (!error) return null;
return (
<div className="pt-3 mx-auto max-w-3xl">
<Alert variant="error">
<CircleAlertIcon />
<AlertDescription className="line-clamp-3" title={error}>
{error}
</AlertDescription>
</Alert>
</div>
);
});
interface PendingApprovalsPanelProps {
pendingApprovals: PendingApproval[];
respondingRequestIds: string[];
onRespondToApproval: (requestId: string, decision: ProviderApprovalDecision) => Promise<void>;
}
const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
pendingApprovals,
respondingRequestIds,
onRespondToApproval,
}: PendingApprovalsPanelProps) {
if (pendingApprovals.length === 0) return null;
return (
<div className="pt-3 mx-auto max-w-3xl space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<Alert variant="warning" key={approval.requestId}>
<InfoIcon />
<AlertTitle className="text-xs">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</AlertTitle>
<AlertDescription
className="truncate block font-mono text-[11px]"
title={approval.detail}
>
{approval.detail}
</AlertDescription>
<AlertAction className="col-start-2! -col-end-1! mt-1.5 sm:row-start-auto sm:row-end-auto">
<Button
size="xs"
variant="default"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</Button>
<Button
size="xs"
variant="outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</Button>
<Button
size="xs"
variant="destructive-outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</Button>
<Button
size="xs"
variant="ghost"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</Button>
</AlertAction>
</Alert>
);
})}
</div>
);
});
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
assistantCompletionByItemId: Map<string, string>;
nowIso: string;
expandedWorkGroups: Record<string, boolean>;
onToggleWorkGroup: (groupId: string) => void;
onImageExpand: (image: ExpandedImagePreview) => void;
messagesEndRef: RefObject<HTMLDivElement | null>;
}
const MessagesTimeline = memo(function MessagesTimeline({
hasMessages,
isWorking,
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
assistantCompletionByItemId,
nowIso,
expandedWorkGroups,
onToggleWorkGroup,
onImageExpand,
messagesEndRef,
}: MessagesTimelineProps) {
if (!hasMessages && !isWorking) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">Send a message to start the conversation.</p>
</div>
);
}
return (
<div className="mx-auto max-w-3xl space-y-4">
{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 (
<Fragment key={timelineEntry.id}>
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
<div className="mb-1.5 flex items-center justify-between gap-3">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
{groupLabel}
</p>
{hasOverflow && (
<button
type="button"
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => onToggleWorkGroup(groupId)}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
<div className="space-y-1">
{visibleEntries.map((workEntry) => (
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
>
{workEntry.detail ? (
<>
{workEntry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={workEntry.detail}
>
{workEntry.detail}
</span>
</>
) : (
workEntry.label
)}
</p>
</div>
))}
</div>
</div>
</Fragment>
);
}
if (timelineEntry.message.role === "user") {
const userImages = timelineEntry.message.attachments ?? [];
return (
<Fragment key={timelineEntry.id}>
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() =>
onImageExpand({ src: image.previewUrl!, name: image.name })
}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
))}
</div>
)}
{timelineEntry.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
</Fragment>
);
}
return (
<Fragment key={timelineEntry.id}>
{showCompletionDivider && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
<div className="px-1 py-0.5">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
</div>
</Fragment>
);
})}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
);
});
const ModelPicker = memo(function ModelPicker(props: {
model: ModelSlug;
onModelChange: (model: ModelSlug) => void;
}) {
function ModelPicker(props: { model: ModelSlug; onModelChange: (model: ModelSlug) => void }) {
return (
<Select
items={MODEL_OPTIONS.map((option) => ({ label: option.name, value: option.slug }))}
@@ -1650,9 +1493,9 @@ const ModelPicker = memo(function ModelPicker(props: {
</SelectPopup>
</Select>
);
});
}
const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
function ReasoningEffortPicker(props: {
effort: ReasoningEffort;
onEffortChange: (effort: ReasoningEffort) => void;
}) {
@@ -1674,13 +1517,9 @@ const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
</SelectPopup>
</Select>
);
});
}
const OpenInPicker = memo(function OpenInPicker({
keybindings,
}: {
keybindings: ResolvedKeybindingsConfig;
}) {
function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig }) {
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
const stored = localStorage.getItem(LAST_EDITOR_KEY);
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
@@ -1764,4 +1603,4 @@ const OpenInPicker = memo(function OpenInPicker({
</Menu>
</Group>
);
});
}
@@ -312,10 +312,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
title: resultToast.title,
description: resultToast.description,
timeout: 0,
data: {
...threadToastData,
dismissAfterVisibleMs: 10_000,
},
data: threadToastData,
...(shouldOfferPushCta
? {
actionProps: {
+8 -23
View File
@@ -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 { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { isChatNewShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -140,13 +140,7 @@ export default function Sidebar() {
}, [state.threads]);
const handleNewThread = useCallback(
(
projectId: string,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
) => {
(projectId: string) => {
dispatch({
type: "ADD_THREAD",
thread: {
@@ -172,8 +166,8 @@ export default function Sidebar() {
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
branch: null,
worktreePath: null,
},
});
},
@@ -387,23 +381,14 @@ export default function Sidebar() {
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
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 activeThread = state.threads.find((t) => t.id === state.activeThreadId);
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);
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
@@ -18,7 +18,7 @@ import {
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import { isTerminalClearShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -152,29 +152,24 @@ function TerminalViewport({
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
const sendTerminalInput = async (data: string, fallbackError: string) => {
const sendClearShortcut = async () => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await api.terminal.write({ threadId, terminalId, data });
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
} catch (error) {
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : "Failed to clear terminal",
);
}
};
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 sendTerminalInput("\u000c", "Failed to clear terminal");
void sendClearShortcut();
return false;
});
@@ -423,7 +418,6 @@ 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;
@@ -439,9 +433,15 @@ interface TerminalActionButtonProps {
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
return (
<Popover>
<PopoverTrigger
openOnHover
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
<PopoverTrigger openOnHover
render={
<button
type="button"
className={className}
onClick={onClick}
aria-label={label}
/>
}
>
{children}
</PopoverTrigger>
@@ -472,7 +472,6 @@ export default function ThreadTerminalDrawer({
onNewTerminal,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
@@ -588,9 +587,6 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
@@ -702,9 +698,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label={
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
}
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
@@ -720,7 +714,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
label="Close Terminal"
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -800,14 +794,16 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal}
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
label={
newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"
}
>
<Plus className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
label="Close Terminal"
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -845,9 +841,6 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
return (
<div
key={terminalId}
@@ -871,30 +864,18 @@ export default function ThreadTerminalDrawer({
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={() => onCloseTerminal(terminalId)}
aria-label={closeTerminalLabel}
/>
}
>
<XIcon className="size-2.5" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{closeTerminalLabel}
</PopoverPopup>
</Popover>
<button
type="button"
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
)}
</div>
);
@@ -1,16 +0,0 @@
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);
});
});
@@ -1,9 +0,0 @@
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;
}
+84 -190
View File
@@ -1,7 +1,6 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import {
CircleAlertIcon,
CircleCheckIcon,
@@ -13,18 +12,14 @@ 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<ThreadToastData>();
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
type ToastId = ReturnType<typeof toastManager.add>;
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
const TOAST_ICONS = {
error: CircleAlertIcon,
@@ -55,84 +50,6 @@ 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 (
<Toast.Provider toastManager={toastManager} {...props}>
@@ -147,18 +64,6 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager<ThreadToastData>();
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 (
<Toast.Portal data-slot="toast-portal">
@@ -176,107 +81,96 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
data-position={position}
data-slot="toast-viewport"
>
{visibleToasts.map((toast, visibleIndex) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const hideCollapsedContent = shouldHideCollapsedToastContent(
visibleIndex,
visibleToasts.length,
);
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
return (
<Toast.Root
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// 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)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded: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-expanded: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-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<ThreadToastVisibleAutoDismiss
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
toastId={toast.id}
/>
<Toast.Content
return (
<Toast.Root
className={cn(
"pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100",
hideCollapsedContent &&
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// 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-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-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)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded: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-expanded: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-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
</div>
{toast.actionProps && (
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
</Toast.Root>
);
})}
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
>
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
</Toast.Root>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
+2 -103
View File
@@ -9,15 +9,12 @@ import {
import {
formatShortcutLabel,
isChatNewShortcut,
isChatNewLocalShortcut,
isOpenFavoriteEditorShortcut,
isTerminalClearShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
shortcutLabelForCommand,
terminalNavigationShortcutData,
type ShortcutEventLike,
} from "./keybindings";
@@ -85,13 +82,7 @@ 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" },
]);
@@ -109,8 +100,8 @@ describe("isTerminalToggleShortcut", () => {
});
});
describe("split/new/close terminal shortcuts", () => {
it("requires terminalFocus for default split/new/close bindings", () => {
describe("split/new terminal shortcuts", () => {
it("requires terminalFocus for default split/new bindings", () => {
assert.isFalse(
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
@@ -123,12 +114,6 @@ describe("split/new/close 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", () => {
@@ -144,12 +129,6 @@ describe("split/new/close terminal shortcuts", () => {
context: { terminalFocus: true },
}),
);
assert.isTrue(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
});
it("supports when expressions", () => {
@@ -245,27 +224,6 @@ 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, {
@@ -366,65 +324,6 @@ 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", () => {
-65
View File
@@ -7,7 +7,6 @@ import {
import { isMacPlatform } from "./lib/utils";
export interface ShortcutEventLike {
type?: string;
key: string;
metaKey: boolean;
ctrlKey: boolean;
@@ -26,11 +25,6 @@ interface ShortcutMatchOptions {
context?: Partial<ShortcutMatchContext>;
}
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";
@@ -190,14 +184,6 @@ 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,
@@ -206,14 +192,6 @@ 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,
@@ -226,10 +204,6 @@ 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) {
@@ -245,42 +219,3 @@ 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;
}
@@ -14,18 +14,6 @@ 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", () => {
-2
View File
@@ -4,9 +4,7 @@ export const keybindingCommandSchema = z.enum([
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
]);