Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15959097e5 | ||
|
|
ba4a62eb03 | ||
|
|
09ac18db82 | ||
|
|
376efdd340 | ||
|
|
7a5dd62d2f | ||
|
|
f64c26e708 | ||
|
|
6d8d39a5d1 | ||
|
|
afdfe16931 | ||
|
|
73fa2d66c7 | ||
|
|
51dcb547ed | ||
|
|
228862ac56 | ||
|
|
bc22a71f10 | ||
|
|
c42d6a6a64 | ||
|
|
5242bbbade | ||
|
|
05b47e748f | ||
|
|
3863901085 | ||
|
|
f864ef189d | ||
|
|
765f4cd00b |
No files matched your search
+7
-2
@@ -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
|
||||
|
||||
@@ -760,6 +760,35 @@ describe("git integration", () => {
|
||||
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
||||
});
|
||||
|
||||
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await using clone = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(source.path, `push -u origin ${initialBranch}`);
|
||||
|
||||
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
|
||||
await git(clone.path, "config user.email '[email protected]'");
|
||||
await git(clone.path, "config user.name 'Test'");
|
||||
await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
|
||||
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
|
||||
await git(clone.path, "add CHANGELOG.md");
|
||||
await git(clone.path, "commit -m 'remote update'");
|
||||
await git(clone.path, `push origin ${initialBranch}`);
|
||||
|
||||
const core = new GitCoreService();
|
||||
const details = await core.statusDetails(source.path);
|
||||
expect(details.branch).toBe(initialBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
});
|
||||
|
||||
it("prepares commit context by auto-staging and creates commit", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
+62
-6
@@ -65,6 +65,8 @@ interface ExecuteGitOptions {
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||
function runGit(
|
||||
@@ -216,6 +218,8 @@ async function executeGit(
|
||||
}
|
||||
|
||||
export class GitCoreService {
|
||||
private readonly lastUpstreamRefreshAt = new Map<string, number>();
|
||||
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.statusDetails(input.cwd);
|
||||
@@ -231,6 +235,8 @@ export class GitCoreService {
|
||||
}
|
||||
|
||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
|
||||
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
||||
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
||||
this.gitStdout(cwd, ["diff", "--numstat"]),
|
||||
@@ -553,7 +559,9 @@ export class GitCoreService {
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
private async resolveCurrentUpstream(
|
||||
cwd: string,
|
||||
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
|
||||
const upstreamRef = trimStdout(
|
||||
await this.gitStdout(
|
||||
cwd,
|
||||
@@ -562,24 +570,72 @@ export class GitCoreService {
|
||||
),
|
||||
);
|
||||
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
||||
if (remoteName.length === 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if (upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchUpstreamRef(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
|
||||
}
|
||||
|
||||
private async fetchUpstreamRefForStatus(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
|
||||
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
|
||||
const now = Date.now();
|
||||
const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
|
||||
if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Record attempt time first to avoid repeated fetch spikes when status is polled often.
|
||||
this.lastUpstreamRefreshAt.set(cacheKey, now);
|
||||
await this.fetchUpstreamRefForStatus(cwd, upstream);
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
await this.fetchUpstreamRef(cwd, upstream);
|
||||
}
|
||||
|
||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||
|
||||
@@ -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" },
|
||||
];
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
|
||||
isScrollContainerNearBottom,
|
||||
} from "./chat-scroll";
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
||||
|
||||
describe("isScrollContainerNearBottom", () => {
|
||||
it("returns true when already at bottom", () => {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
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;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -86,17 +87,22 @@ export default function BranchToolbar({
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: current.name,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
|
||||
@@ -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);
|
||||
@@ -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,359 @@ 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 +1656,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 +1680,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 +1770,4 @@ function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig
|
||||
</Menu>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -226,17 +226,14 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
});
|
||||
return;
|
||||
}
|
||||
const promise = api.shell.openExternal(prUrl);
|
||||
toastManager.promise(promise, {
|
||||
loading: { title: "Opening PR...", data: threadToastData },
|
||||
success: { title: "PR opened", data: threadToastData },
|
||||
error: (err) => ({
|
||||
void api.shell.openExternal(prUrl).catch((err) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
}),
|
||||
});
|
||||
});
|
||||
void promise.catch(() => undefined);
|
||||
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
@@ -312,7 +309,10 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
title: resultToast.title,
|
||||
description: resultToast.description,
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
data: {
|
||||
...threadToastData,
|
||||
dismissAfterVisibleMs: 10_000,
|
||||
},
|
||||
...(shouldOfferPushCta
|
||||
? {
|
||||
actionProps: {
|
||||
@@ -627,7 +627,8 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
: gitStatusForActions.aheadCount === 0 &&
|
||||
gitStatusForActions.behindCount === 0
|
||||
? "Up to date"
|
||||
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
|
||||
: gitStatusForActions.aheadCount > 0 &&
|
||||
gitStatusForActions.behindCount > 0
|
||||
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
||||
: gitStatusForActions.aheadCount > 0
|
||||
? `Ahead by ${gitStatusForActions.aheadCount}`
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Toast } from "@base-ui/react/toast";
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
@@ -12,14 +13,18 @@ import {
|
||||
import { cn } from "~/lib/utils";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { useStore } from "~/store";
|
||||
import { shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
type ThreadToastData = {
|
||||
threadId?: string | null;
|
||||
tooltipStyle?: boolean;
|
||||
dismissAfterVisibleMs?: number;
|
||||
};
|
||||
|
||||
const toastManager = Toast.createToastManager<ThreadToastData>();
|
||||
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
|
||||
type ToastId = ReturnType<typeof toastManager.add>;
|
||||
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
|
||||
|
||||
const TOAST_ICONS = {
|
||||
error: CircleAlertIcon,
|
||||
@@ -50,6 +55,84 @@ function shouldRenderForActiveThread(
|
||||
return toastThreadId === activeThreadId;
|
||||
}
|
||||
|
||||
function ThreadToastVisibleAutoDismiss({
|
||||
toastId,
|
||||
dismissAfterVisibleMs,
|
||||
}: {
|
||||
toastId: ToastId;
|
||||
dismissAfterVisibleMs: number | undefined;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
|
||||
if (typeof window === "undefined" || typeof document === "undefined") return;
|
||||
|
||||
let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
|
||||
let startedAtMs: number | null = null;
|
||||
let timeoutId: number | null = null;
|
||||
let closed = false;
|
||||
|
||||
const clearTimer = () => {
|
||||
if (timeoutId === null) return;
|
||||
window.clearTimeout(timeoutId);
|
||||
timeoutId = null;
|
||||
};
|
||||
|
||||
const closeToast = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
threadToastVisibleTimeoutRemainingMs.delete(toastId);
|
||||
toastManager.close(toastId);
|
||||
};
|
||||
|
||||
const pause = () => {
|
||||
if (startedAtMs === null) return;
|
||||
remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
|
||||
startedAtMs = null;
|
||||
clearTimer();
|
||||
threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
if (closed || startedAtMs !== null) return;
|
||||
if (remainingMs <= 0) {
|
||||
closeToast();
|
||||
return;
|
||||
}
|
||||
startedAtMs = Date.now();
|
||||
clearTimer();
|
||||
timeoutId = window.setTimeout(() => {
|
||||
remainingMs = 0;
|
||||
startedAtMs = null;
|
||||
closeToast();
|
||||
}, remainingMs);
|
||||
};
|
||||
|
||||
const syncTimer = () => {
|
||||
const shouldRun = document.visibilityState === "visible" && document.hasFocus();
|
||||
if (shouldRun) {
|
||||
start();
|
||||
return;
|
||||
}
|
||||
pause();
|
||||
};
|
||||
|
||||
syncTimer();
|
||||
document.addEventListener("visibilitychange", syncTimer);
|
||||
window.addEventListener("focus", syncTimer);
|
||||
window.addEventListener("blur", syncTimer);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", syncTimer);
|
||||
window.removeEventListener("focus", syncTimer);
|
||||
window.removeEventListener("blur", syncTimer);
|
||||
pause();
|
||||
clearTimer();
|
||||
};
|
||||
}, [dismissAfterVisibleMs, toastId]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
|
||||
return (
|
||||
<Toast.Provider toastManager={toastManager} {...props}>
|
||||
@@ -64,6 +147,18 @@ 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">
|
||||
@@ -81,96 +176,107 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
data-position={position}
|
||||
data-slot="toast-viewport"
|
||||
>
|
||||
{toasts
|
||||
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
|
||||
.map((toast) => {
|
||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
||||
{visibleToasts.map((toast, visibleIndex) => {
|
||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
||||
const hideCollapsedContent = shouldHideCollapsedToastContent(
|
||||
visibleIndex,
|
||||
visibleToasts.length,
|
||||
);
|
||||
|
||||
return (
|
||||
<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}
|
||||
>
|
||||
<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>
|
||||
);
|
||||
|
||||
@@ -9,12 +9,15 @@ import {
|
||||
import {
|
||||
formatShortcutLabel,
|
||||
isChatNewShortcut,
|
||||
isChatNewLocalShortcut,
|
||||
isOpenFavoriteEditorShortcut,
|
||||
isTerminalClearShortcut,
|
||||
isTerminalCloseShortcut,
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
shortcutLabelForCommand,
|
||||
terminalNavigationShortcutData,
|
||||
type ShortcutEventLike,
|
||||
} from "./keybindings";
|
||||
|
||||
@@ -82,14 +85,22 @@ 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" },
|
||||
]);
|
||||
|
||||
describe("isTerminalToggleShortcut", () => {
|
||||
it("matches Cmd+J on macOS", () => {
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel" }),
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -100,8 +111,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 +125,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 +146,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", () => {
|
||||
@@ -198,7 +221,10 @@ describe("shortcutLabelForCommand", () => {
|
||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(shortcutLabelForCommand(bindings, "terminal.split", "Linux"), "Ctrl+Shift+\\");
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(bindings, "terminal.split", "Linux"),
|
||||
"Ctrl+Shift+\\",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns labels for non-terminal commands", () => {
|
||||
@@ -224,6 +250,19 @@ 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, {
|
||||
@@ -302,11 +341,17 @@ describe("cross-command precedence", () => {
|
||||
|
||||
describe("formatShortcutLabel", () => {
|
||||
it("formats labels for macOS", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"), "⇧⌘D");
|
||||
assert.strictEqual(
|
||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"),
|
||||
"⇧⌘D",
|
||||
);
|
||||
});
|
||||
|
||||
it("formats labels for non-macOS", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"), "Ctrl+Shift+D");
|
||||
assert.strictEqual(
|
||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"),
|
||||
"Ctrl+Shift+D",
|
||||
);
|
||||
});
|
||||
|
||||
it("formats labels for plus key", () => {
|
||||
@@ -324,6 +369,69 @@ 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", () => {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
|
||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
|
||||
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
export const gitQueryKeys = {
|
||||
all: ["git"] as const,
|
||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
||||
@@ -21,6 +26,10 @@ export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string |
|
||||
return api.git.status({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: "always",
|
||||
refetchOnReconnect: "always",
|
||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,6 +43,10 @@ export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string
|
||||
return api.git.listBranches({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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];
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2
-1
@@ -19,7 +19,8 @@
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts"
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -4,7 +4,9 @@ export const keybindingCommandSchema = z.enum([
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"terminal.close",
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
]);
|
||||
|
||||
@@ -19,14 +21,16 @@ export const keybindingRuleSchema = z.object({
|
||||
|
||||
export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);
|
||||
|
||||
export const keybindingShortcutSchema = z.object({
|
||||
key: z.string().trim().min(1).max(32),
|
||||
metaKey: z.boolean(),
|
||||
ctrlKey: z.boolean(),
|
||||
shiftKey: z.boolean(),
|
||||
altKey: z.boolean(),
|
||||
modKey: z.boolean(),
|
||||
}).strict();
|
||||
export const keybindingShortcutSchema = z
|
||||
.object({
|
||||
key: z.string().trim().min(1).max(32),
|
||||
metaKey: z.boolean(),
|
||||
ctrlKey: z.boolean(),
|
||||
shiftKey: z.boolean(),
|
||||
altKey: z.boolean(),
|
||||
modKey: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type KeybindingWhenNode =
|
||||
| { type: "identifier"; name: string }
|
||||
@@ -57,11 +61,13 @@ export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(()
|
||||
]),
|
||||
);
|
||||
|
||||
export const resolvedKeybindingRuleSchema = z.object({
|
||||
command: keybindingCommandSchema,
|
||||
shortcut: keybindingShortcutSchema,
|
||||
whenAst: keybindingWhenNodeSchema.optional(),
|
||||
}).strict();
|
||||
export const resolvedKeybindingRuleSchema = z
|
||||
.object({
|
||||
command: keybindingCommandSchema,
|
||||
shortcut: keybindingShortcutSchema,
|
||||
whenAst: keybindingWhenNodeSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
|
||||
|
||||
|
||||
Reference in new issue
Block a user