Compare commits

..
Author SHA1 Message Date
Julius Marminge dcc6d9d9ae Cap thread terminals at four and disable add/split controls
- enforce max 4 terminals per thread in reducer and terminal normalization
- block split/new terminal actions in chat and drawer when limit is reached
- add reducer tests for split/new terminal cap behavior
2026-02-17 12:10:06 -08:00
Julius Marminge 0a4c07051a Prevent ChatView header overflow with long thread titles
- add `min-w-0` to ChatView container wrappers to allow proper flex shrinking
- make thread title truncatable with `truncate` and `title` tooltip
- keep action controls fixed-width with `shrink-0` to preserve header layout
2026-02-16 11:09:43 -08:00
Julius Marminge 73fa2d66c7 Use stable IDs for approval actions in ChatView
- Derive `activeSessionId` and `activeThreadId` before approval callbacks
- Avoid stale thread/session captures when submitting approval decisions
- Pass `hasMessages` to `MessagesTimeline` instead of the full thread
2026-02-16 00:55:31 -08:00
Julius Marminge 51dcb547ed Refactor ChatView into memoized subcomponents
- Extract header, error, approvals, and timeline into memoized components
- Memoize `ChatMarkdown`, pickers, and handlers to reduce avoidable re-renders
- Reduce running-time ticker frequency from 250ms to 1000ms
2026-02-16 00:55:31 -08:00
Julius Marminge 228862ac56 doc 2026-02-15 23:08:37 -08:00
Julius Marminge bc22a71f10 Rename local chat shortcut and surface terminal close hints
- Replace `chat.newSameGitState` with `chat.newLocal` across contracts, server/web defaults, docs, and tests
- Make `chat.new` preserve branch/worktree state while `chat.newLocal` creates a local thread
- Show terminal close shortcut labels in drawer action tooltips and tab close controls
2026-02-15 23:08:37 -08:00
Julius Marminge c42d6a6a64 Add shortcuts for terminal close and chat with same Git state
- Extend keybinding contracts/defaults with `terminal.close` and `chat.newSameGitState`
- Wire web handlers for `mod+w` to close focused terminal and `mod+shift+n` to open a thread preserving branch/worktree
- Update docs and keybinding tests across server, web, and contracts
2026-02-15 23:08:37 -08:00
Julius Marminge 5242bbbade Fix top-right toast enter and exit transforms
- Add position-specific start transform for top-right toasts
- Apply matching top-right end transform when dismissing without swipe
2026-02-15 20:12:24 -08:00
Julius Marminge 05b47e748f Fix collapsed toast content visibility in filtered stacks
- keep the front-most visible toast readable when thread filtering hides others
- extract visibility rule into `toast.logic.ts`
- add unit tests for collapsed-content visibility behavior
2026-02-15 20:12:24 -08:00
Julius Marminge 3863901085 Auto-dismiss thread toasts after 10s of visible time
- Add `dismissAfterVisibleMs` support to thread toasts
- Pause/resume countdown based on tab visibility and window focus
- Set Git action result toasts to dismiss after 10s when visible
2026-02-15 19:16:49 -08:00
Julius Marminge f864ef189d Ignore non-keydown terminal shortcuts
- guard terminal clear/navigation shortcut handlers to only process `keydown`
- add tests verifying `keyup` events are ignored
2026-02-15 17:06:16 -08:00
Julius Marminge 765f4cd00b Add terminal word and line navigation arrow shortcuts
- handle platform-specific modifier+arrow combos in terminal input
- reuse terminal write path for clear and navigation actions
- add shortcut tests for macOS and non-macOS mappings
2026-02-15 17:06:16 -08:00
16 changed files with 989 additions and 477 deletions

No files matched your search

+7 -2
View File
@@ -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
+4 -1
View File
@@ -28,7 +28,10 @@ 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+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" },
];
+4 -1
View File
@@ -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 (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
@@ -26,3 +27,5 @@ export default function ChatMarkdown({ text }: ChatMarkdownProps) {
</div>
);
}
export default memo(ChatMarkdown);
+455 -319
View File
@@ -2,6 +2,7 @@ import {
EDITORS,
type EditorId,
ModelSlug,
type NativeApi,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
@@ -15,6 +16,8 @@ import {
type FormEvent,
Fragment,
type KeyboardEvent,
memo,
type RefObject,
useCallback,
useEffect,
useLayoutEffect,
@@ -40,6 +43,7 @@ import {
derivePendingApprovals,
derivePhase,
deriveTimelineEntries,
type PendingApproval,
deriveWorkLogEntries,
formatDuration,
formatElapsed,
@@ -47,11 +51,12 @@ import {
} from "../session-logic";
import { isScrollContainerNearBottom } from "../chat-scroll";
import { useStore } from "../store";
import type { ChatImageAttachment } from "../types";
import { MAX_THREAD_TERMINAL_COUNT, type ChatImageAttachment } from "../types";
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,12 +284,18 @@ export default function ChatView() {
() => shortcutLabelForCommand(keybindings, "terminal.new"),
[keybindings],
);
const closeTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.close"),
[keybindings],
);
const envLocked = Boolean(
activeThread &&
(activeThread.messages.length > 0 ||
(activeThread.session !== null && activeThread.session.status !== "closed")),
);
const hasReachedTerminalLimit =
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
for (const image of images) {
@@ -312,23 +324,23 @@ export default function ChatView() {
});
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
const splitTerminal = useCallback(() => {
if (!activeThreadId) return;
if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({
type: "SPLIT_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch]);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId) return;
if (!activeThreadId || hasReachedTerminalLimit) return;
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch]);
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
@@ -492,7 +504,7 @@ export default function ChatView() {
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 250);
}, 1000);
return () => {
window.clearInterval(timer);
};
@@ -554,6 +566,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 +590,9 @@ export default function ChatView() {
return () => window.removeEventListener("keydown", handler);
}, [
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
activeThreadId,
closeTerminal,
createNewTerminal,
dispatch,
splitTerminal,
@@ -874,28 +896,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,11 +955,23 @@ 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) {
return (
<div className="flex min-h-0 flex-1 flex-col bg-background text-muted-foreground/40">
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
{isElectron && (
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
<span className="text-xs text-muted-foreground/50">No active thread</span>
@@ -950,106 +987,29 @@ export default function ChatView() {
}
return (
<div className="flex min-h-0 flex-1 flex-col bg-background">
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
{/* Top bar */}
<header
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<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>
<ChatHeader
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
keybindings={keybindings}
api={api}
gitCwd={gitCwd}
diffOpen={state.diffOpen}
onToggleDiff={onToggleDiff}
/>
</header>
{/* Error banner */}
{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>
)}
<ThreadErrorBanner error={activeThread.error} />
<PendingApprovalsPanel
pendingApprovals={pendingApprovals}
respondingRequestIds={respondingRequestIds}
onRespondToApproval={onRespondToApproval}
/>
{/* Messages */}
<div
@@ -1057,198 +1017,19 @@ export default function ChatView() {
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
onScroll={onMessagesScroll}
>
{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>
)}
<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}
/>
</div>
{/* Input bar */}
@@ -1453,6 +1234,7 @@ export default function ChatView() {
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
@@ -1503,7 +1285,357 @@ 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 (
<>
<div className="flex min-w-0 flex-1 items-center gap-3">
<h2 className="truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
{activeThreadTitle}
</h2>
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
</div>
<div className="shrink-0 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;
}) {
return (
<Select
items={MODEL_OPTIONS.map((option) => ({ label: option.name, value: option.slug }))}
@@ -1522,9 +1654,9 @@ function ModelPicker(props: { model: ModelSlug; onModelChange: (model: ModelSlug
</SelectPopup>
</Select>
);
}
});
function ReasoningEffortPicker(props: {
const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
effort: ReasoningEffort;
onEffortChange: (effort: ReasoningEffort) => void;
}) {
@@ -1546,9 +1678,13 @@ function ReasoningEffortPicker(props: {
</SelectPopup>
</Select>
);
}
});
function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig }) {
const OpenInPicker = memo(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;
@@ -1632,4 +1768,4 @@ function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig
</Menu>
</Group>
);
}
});
+23 -8
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 { isChatNewShortcut } from "../keybindings";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -140,7 +140,13 @@ export default function Sidebar() {
}, [state.threads]);
const handleNewThread = useCallback(
(projectId: string) => {
(
projectId: string,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
) => {
dispatch({
type: "ADD_THREAD",
thread: {
@@ -166,8 +172,8 @@ export default function Sidebar() {
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
},
});
},
@@ -381,14 +387,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);
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
@@ -18,10 +18,11 @@ import {
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../keybindings";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ThreadTerminalGroup,
} from "../types";
@@ -152,24 +153,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;
});
@@ -418,6 +424,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;
@@ -433,15 +440,9 @@ 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,6 +473,7 @@ export default function ThreadTerminalDrawer({
onNewTerminal,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
@@ -580,6 +582,7 @@ export default function ThreadTerminalDrawer({
const showGroupHeaders =
resolvedTerminalGroups.length > 1 ||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
const terminalLabelById = useMemo(
() =>
new Map(
@@ -587,6 +590,23 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const splitTerminalActionLabel = hasReachedTerminalLimit
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
: (splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal");
const newTerminalActionLabel = hasReachedTerminalLimit
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
: (newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal");
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
const onSplitTerminalAction = useCallback(() => {
if (hasReachedTerminalLimit) return;
onSplitTerminal();
}, [hasReachedTerminalLimit, onSplitTerminal]);
const onNewTerminalAction = useCallback(() => {
if (hasReachedTerminalLimit) return;
onNewTerminal();
}, [hasReachedTerminalLimit, onNewTerminal]);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
@@ -681,7 +701,7 @@ export default function ThreadTerminalDrawer({
return (
<aside
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }}
>
<div
@@ -696,17 +716,25 @@ export default function ThreadTerminalDrawer({
<div className="pointer-events-none absolute right-2 top-2 z-20">
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
className={`p-1 text-foreground/90 transition-colors ${
hasReachedTerminalLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent"
}`}
onClick={onSplitTerminalAction}
label={splitTerminalActionLabel}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminal}
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
className={`p-1 text-foreground/90 transition-colors ${
hasReachedTerminalLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent"
}`}
onClick={onNewTerminalAction}
label={newTerminalActionLabel}
>
<Plus className="size-3.25" />
</TerminalActionButton>
@@ -714,7 +742,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -727,9 +755,9 @@ export default function ThreadTerminalDrawer({
<div className="min-w-0 flex-1">
{isSplitView ? (
<div
className="grid h-full w-full gap-0 overflow-x-auto"
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
style={{
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}}
>
{visibleTerminalIds.map((terminalId) => (
@@ -781,29 +809,31 @@ export default function ThreadTerminalDrawer({
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
<div className="inline-flex h-full items-stretch">
<TerminalActionButton
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onSplitTerminal}
label={
splitShortcutLabel
? `Split Terminal (${splitShortcutLabel})`
: "Split Terminal"
}
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
hasReachedTerminalLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent/70"
}`}
onClick={onSplitTerminalAction}
label={splitTerminalActionLabel}
>
<SquareSplitHorizontal 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={onNewTerminal}
label={
newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"
}
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
hasReachedTerminalLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent/70"
}`}
onClick={onNewTerminalAction}
label={newTerminalActionLabel}
>
<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="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -841,6 +871,9 @@ 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}
@@ -864,18 +897,30 @@ export default function ThreadTerminalDrawer({
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<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>
<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>
)}
</div>
);
@@ -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);
});
});
@@ -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;
}
+99 -88
View File
@@ -13,6 +13,7 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
threadId?: string | null;
@@ -146,6 +147,9 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager<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));
@@ -172,100 +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 (
<Toast.Root
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
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-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)))]",
"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",
)}
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 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>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
<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"
>
{toast.actionProps.children}
</Toast.Action>
<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>
</Toast.Root>
);
})}
<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>
{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>
);
+103 -2
View File
@@ -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", () => {
+65
View File
@@ -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<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";
@@ -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;
}
+69 -1
View File
@@ -2,7 +2,11 @@ import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/con
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
} from "./types";
import type { Thread } from "./types";
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
@@ -255,6 +259,70 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("caps split terminals at four per thread", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
activeTerminalId: "term-4",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-5",
});
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
expect(next.threads[0]?.terminalIds).toEqual([
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
"term-4",
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
});
it("caps new terminals at four per thread", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
activeTerminalId: "term-4",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-2", terminalIds: ["term-2"] },
{ id: "group-term-3", terminalIds: ["term-3"] },
{ id: "group-term-4", terminalIds: ["term-4"] },
],
activeTerminalGroupId: "group-term-4",
}),
);
const next = reducer(state, {
type: "NEW_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-5",
});
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
expect(next.threads[0]?.terminalIds).toEqual([
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
"term-4",
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-4");
});
it("closes a terminal and keeps grouped layout coherent", () => {
const state = makeState(
makeThread({
+22 -2
View File
@@ -16,6 +16,7 @@ import {
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
type Project,
type RuntimeMode,
type Thread,
@@ -110,7 +111,12 @@ function readPersistedState(): AppState {
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false };
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
const activeThreadId = threads.some((thread) => thread.id === hydrated.activeThreadId)
? hydrated.activeThreadId
: (threads[0]?.id ?? null);
return { ...hydrated, threads, activeThreadId, diffOpen: false };
} catch {
return initialState;
}
@@ -139,7 +145,7 @@ function updateThread(
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)];
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
if (unique.length > 0) {
return unique;
}
@@ -550,6 +556,13 @@ export function reducer(state: AppState, action: Action): AppState {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (
isNewTerminal &&
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
@@ -616,6 +629,13 @@ export function reducer(state: AppState, action: Action): AppState {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (
isNewTerminal &&
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
+1
View File
@@ -5,6 +5,7 @@ export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
export const DEFAULT_THREAD_TERMINAL_ID = "default";
export const MAX_THREAD_TERMINAL_COUNT = 4;
export interface ThreadTerminalGroup {
id: string;
@@ -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", () => {
+2
View File
@@ -4,7 +4,9 @@ export const keybindingCommandSchema = z.enum([
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
]);