Compare commits

..
Author SHA1 Message Date
Julius Marminge 70752a0675 Auto-dismiss thread toasts after 10s of visible time
- Add `dismissAfterVisibleMs` support to thread toasts
- Pause/resume countdown based on tab visibility and window focus
- Set Git action result toasts to dismiss after 10s when visible
2026-02-15 18:54:24 -08:00
Julius Marminge 748ea2ae20 Block deletion of projects that still have threads
- Show warning toast when attempting to delete a non-empty project
- Simplify confirmation copy to emphasize irreversible deletion
- Remove thread/worktree/session cleanup from project delete flow
2026-02-15 16:35:17 -08:00
Julius Marminge 56a09ad1aa Confirm project deletion and clean up orphaned worktrees
- Prompt before deleting a project with thread and linked worktree counts
- Best-effort remove orphaned worktrees when project threads are deleted
- Show toast with error details if project deletion fails
2026-02-15 16:35:17 -08:00
Julius Marminge be1c8c4656 Delete projects from the sidebar context menu
- Add project right-click Delete action in `Sidebar` and clean up sessions/terminals before removal
- Add `DELETE_PROJECT` reducer action to remove the project, its threads, and reset active thread
- Add reducer test coverage for project deletion behavior
2026-02-15 16:35:17 -08:00
Julius Marminge b7fb0b8fed Memoize ChatView selection handlers with useCallback
- Wrap model, effort, and env mode handlers in `useCallback`
- Stabilize callback identities while preserving composer focus behavior
2026-02-15 16:27:25 -08:00
Julius Marminge 5656f294d0 Simplify env mode change handler in ChatView
- Remove unnecessary `useCallback` wrapping from `onEnvModeChange`
- Keep env mode update and composer refocus behavior unchanged
2026-02-15 16:27:25 -08:00
Julius Marminge dd23bd73d9 Keep composer focused after toolbar and mode changes
- Add a shared composer-focus scheduler in `ChatView`
- Refocus composer after runtime mode, model, effort, and env mode selections
- Let `BranchToolbar` request composer focus after branch/worktree actions
2026-02-15 16:27:25 -08:00
Julius Marminge 8dd107429e Prevent config refetches and tighten Windows platform detection
- set server config query `staleTime` to `Infinity` to avoid unnecessary refetches
- narrow `isWindowsPlatform` matching to Windows-prefixed identifiers
- add unit tests for Windows and non-Windows platform cases
2026-02-15 15:51:05 -08:00
Julius Marminge 1269b52580 change defailt for new termial 2026-02-15 15:51:05 -08:00
Julius Marminge fe79c8e9ee nit 2026-02-15 15:51:05 -08:00
Julius Marminge 0a5aaf3e0e tidy up 2026-02-15 15:51:05 -08:00
Julius Marminge 3d7ef8a833 rm 2026-02-15 15:51:05 -08:00
Julius Marminge 66ebadb448 update doc 2026-02-15 15:51:05 -08:00
Julius Marminge 6667992753 Harden keybinding schemas and align tests with server defaults
- make resolved keybinding/shortcut schemas strict to reject unknown fields
- export server `DEFAULT_KEYBINDINGS` as source of truth and reuse it in ws tests
- simplify keybinding test fixtures and update docs to reference server defaults
2026-02-15 15:51:05 -08:00
Julius Marminge 41ba1ec7a8 Extract keybindings config loading into keybindings module
- Move default keybindings, config parsing, validation, and merge logic out of `wsServer`
- Add `loadResolvedKeybindingsConfig(logger)` in `apps/server/src/keybindings.ts`
- Update server wiring docs to point to `server.getConfig` integration
2026-02-15 15:51:05 -08:00
Julius Marminge 3db020a683 Simplify resolved keybinding payload and remove unused LRU cache
- drop `key` and `when` from resolved keybinding rule schema/payload
- update server/web/contracts tests and keybindings docs for `whenAst`-only resolution
- delete unused web `LruCache` implementation and tests
2026-02-15 15:51:05 -08:00
Julius Marminge 20d3ad5d50 Use Vitest assert API in keybindings tests
- Replace `expect` assertions with `assert` in server and contracts keybinding tests
- Keep existing coverage while standardizing assertion style
2026-02-15 15:51:05 -08:00
Julius Marminge 54fa15c72e Inline keybinding when AST type and update keybindings tests
- Move `KeybindingWhenNode` into `packages/contracts/src/keybindings.ts`
- Remove deprecated `keybindingsWhen` module/export
- Update web keybinding tests to build `whenAst` directly in fixtures
2026-02-15 15:51:05 -08:00
Julius Marminge 370127760a Resolve and validate keybindings on server before sending to web
- add server keybinding compiler for shortcuts and `when` AST parsing
- switch websocket/server config payload to resolved keybinding rules
- update web keybinding logic/types to consume resolved payload directly
- add/adjust contract, server, and web tests (including plus-key parsing) and docs
2026-02-15 15:51:05 -08:00
Julius Marminge dd3babdcad Use LRU cache for keybinding when-expression AST parsing
- add reusable `LruCache` utility with bounded eviction
- replace keybinding AST cache clear-all behavior with true LRU lookups
- add unit tests for eviction, recency updates, and capacity validation
2026-02-15 15:51:05 -08:00
Julius Marmingeandcodex 7aa717c5c2 Harden keybinding parsing and config resolution
Co-authored-by: codex <[email protected]>
2026-02-15 15:51:05 -08:00
Julius Marminge 8beba3e16b Refactor Sidebar component to streamline keybindings handling 2026-02-15 15:51:05 -08:00
Julius Marminge 38c93a2abd Resolve keybinding precedence across commands
- Evaluate shortcut matches by resolving the last matching key+when rule, regardless of command
- Add cross-command precedence tests and switch assertions to `vitest` `assert`
- Clarify precedence behavior in `KEYBINDINGS.md`
2026-02-15 15:51:05 -08:00
Julius Marminge ef4ce2e1ec Add configurable shortcuts for new chat and open-in-editor
- add `chat.new` and `editor.openFavorite` to keybinding contracts and server defaults
- use shared keybinding matching in sidebar/chat view instead of hardcoded Cmd/Ctrl combos
- document new commands/defaults and extend server/web keybinding tests
2026-02-15 15:51:05 -08:00
Julius Marminge 61e9ba4b19 Load terminal keybindings via React Query server config helper
- add `serverConfigQueryOptions` in new `serverReactQuery` utility
- switch `ChatView` from manual `getConfig` effect/state to `useQuery`
- default to empty keybindings while config is unavailable
2026-02-15 15:51:05 -08:00
Julius Marminge ad6247577e Add source links to keybinding schema references
- convert schema and server file references in `KEYBINDINGS.md` to clickable Markdown links
2026-02-15 15:51:05 -08:00
Julius Marminge f1cd76c17a Resolve terminal keybindings on server before sending config
- Move default keybinding resolution/override merging into `server.getConfig`
- Return server-resolved keybindings to the web client instead of resolving in UI
- Update docs and tests to reflect server-side defaults, overrides, and truncation behavior
2026-02-15 15:51:05 -08:00
Julius Marminge 31aa32b83b Extract keybindings contracts into dedicated module
- add `packages/contracts/src/keybindings.ts` with keybinding schemas and types
- import keybindings config schema from `server.ts`
- re-export keybindings contracts from `packages/contracts/src/index.ts`
2026-02-15 15:51:05 -08:00
Julius Marminge 53c367420c Align web keybinding types with shared contract aliases
- Reuse `KeybindingRule` and `KeybindingsConfig` directly for resolved keybinding types
- Update normalization helper to accept `KeybindingRule` for consistent typing
2026-02-15 15:51:05 -08:00
Julius Marminge ace5803581 Rename terminal-shortcuts module to keybindings
- Rename `terminal-shortcuts.ts` and its test to `keybindings`
- Update ChatView and ThreadTerminalDrawer imports to use new module path
2026-02-15 15:51:05 -08:00
Julius Marminge 645b037c9e Add configurable terminal keybindings loaded from ~/.t3
- extend `server.getConfig` to return sanitized keybinding rules from `~/.t3/keybindings.json`
- apply resolved bindings in the web app for toggle/split/new terminal shortcuts and labels
- add contracts/docs and tests for config parsing, validation, and shortcut behavior
2026-02-15 15:51:05 -08:00
Julius Marmingeandcodex 7fc53dadc7 Respect chat scroll position during streaming updates
- only auto-scroll when the user is already near the bottom
- centralize near-bottom detection in `chat-scroll.ts` with a 64px threshold
- add unit tests covering threshold and edge-case behavior

Co-authored-by: codex <[email protected]>
2026-02-15 12:38:55 -08:00
Julius Marmingeandcodex 98c4b7c724 fetch in background
Co-authored-by: codex <[email protected]>
2026-02-15 01:23:10 -08:00
Julius Marmingeandcodex 60111b2b91 Guard git quick actions for diverged and stale branch status
- Disable the quick sync action when local and upstream branches have diverged
- Treat mismatched branch/status data as out-of-sync and refresh before enabling actions
- Update GitActionsControl logic tests for diverged branch behavior

Co-authored-by: codex <[email protected]>
2026-02-15 01:23:10 -08:00
Julius Marminge 1f17e9c429 scope toasts per thread 2026-02-15 01:08:34 -08:00
Julius Marminge 6708fe996a Scope branch refresh fetch to checked-out upstream refspec
- derive upstream branch from `branch@{upstream}` and guard empty values
- fetch only `+refs/heads/<branch>:refs/remotes/<remote>/<branch>` instead of all remote refs
- add integration test asserting scoped fetch args during `checkoutBranch`
2026-02-15 00:53:20 -08:00
Julius Marminge 72d7fccc52 Make checkout tolerate upstream refresh failures
- treat post-checkout upstream fetch as best effort so checkout still succeeds
- route refresh fetch through `this.git(...)` for consistent behavior
- add regression test for fetch-timeout during branch checkout
2026-02-15 00:53:20 -08:00
Julius Marminge f145a453b5 Refresh branch upstream after checkout and invalidate git queries
- fetch tracked remote after checkout to update ahead/behind counts
- add integration test for behind count when remote branch advances
- invalidate git React Query data on `turn/completed` events in the web app
2026-02-15 00:53:20 -08:00
33 changed files with 2455 additions and 389 deletions

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
# Keybindings
T3 Code reads keybindings from:
- `~/.t3/keybindings.json`
The file must be a JSON array of rules:
```json
[
{ "key": "mod+g", "command": "terminal.toggle" },
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
]
```
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
## Defaults
```json
[
{ "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+o", "command": "editor.openFavorite" }
]
```
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
## Configuration
### Rule Shape
Each entry supports:
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
- `command` (required): action ID
- `when` (optional): boolean expression controlling when the shortcut is active
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
### Available Commands
- `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
- `editor.openFavorite`: open current project/worktree in the last-used editor
### Key Syntax
Supported modifiers:
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
- `cmd` / `meta`
- `ctrl` / `control`
- `shift`
- `alt` / `option`
Examples:
- `mod+j`
- `mod+shift+d`
- `ctrl+l`
- `cmd+k`
### `when` Conditions
Currently available context keys:
- `terminalFocus`
- `terminalOpen`
Supported operators:
- `!` (not)
- `&&` (and)
- `||` (or)
- parentheses: `(` `)`
Examples:
- `"when": "terminalFocus"`
- `"when": "terminalOpen && !terminalFocus"`
- `"when": "terminalFocus || terminalOpen"`
Unknown condition keys evaluate to `false`.
### Precedence
- Rules are evaluated in array order.
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
- That means precedence is across commands, not only within the same command.
+73 -6
View File
@@ -272,11 +272,12 @@ describe("git integration", () => {
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
const core = new GitCoreService();
const details = await core.statusDetails(source.path);
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
await vi.waitFor(async () => {
const details = await core.statusDetails(source.path);
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
});
});
it("keeps checkout successful when upstream refresh fails", async () => {
@@ -320,7 +321,9 @@ describe("git integration", () => {
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
undefined,
);
expect(core.refreshFetchAttempts).toBe(1);
await vi.waitFor(() => {
expect(core.refreshFetchAttempts).toBe(1);
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
});
@@ -362,6 +365,9 @@ describe("git integration", () => {
const core = new FetchRecordingGitCoreService();
await core.checkoutBranch({ cwd: source.path, branch: featureBranch });
await vi.waitFor(() => {
expect(core.fetchArgs).not.toBeNull();
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
expect(core.fetchArgs).toEqual([
@@ -373,6 +379,67 @@ describe("git integration", () => {
]);
});
it("returns checkout result before background upstream refresh completes", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
await git(remote.path, "init --bare");
await initRepoWithCommit(source.path);
const defaultBranch = (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 ${defaultBranch}`);
const featureBranch = "feature/background-refresh";
await git(source.path, `checkout -b ${featureBranch}`);
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
await git(source.path, "add feature.txt");
await git(source.path, "commit -m 'feature base'");
await git(source.path, `push -u origin ${featureBranch}`);
await git(source.path, `checkout ${defaultBranch}`);
class SlowRefreshGitCoreService extends GitCoreService {
fetchStarted = false;
private readonly waitForReleasePromise: Promise<void>;
private releaseWait: () => void = () => undefined;
constructor() {
super();
this.waitForReleasePromise = new Promise<void>((resolve) => {
this.releaseWait = resolve;
});
}
releaseFetch(): void {
this.releaseWait();
}
override async git(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<void> {
if (args[0] === "fetch") {
this.fetchStarted = true;
await this.waitForReleasePromise;
return;
}
await super.git(cwd, args, allowNonZeroExit);
}
}
const core = new SlowRefreshGitCoreService();
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
undefined,
);
await vi.waitFor(() => {
expect(core.fetchStarted).toBe(true);
});
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
core.releaseFetch();
});
it("throws when branch does not exist", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
+2 -5
View File
@@ -587,11 +587,8 @@ export class GitCoreService {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
try {
await this.refreshCheckedOutBranchUpstream(input.cwd);
} catch {
// Best effort: checkout already succeeded, so avoid surfacing refresh failures.
}
// Refresh upstream refs in the background so checkout remains responsive.
void this.refreshCheckedOutBranchUpstream(input.cwd).catch(() => undefined);
}
async initRepo(input: GitInitInput): Promise<void> {
+69
View File
@@ -0,0 +1,69 @@
import { assert, describe, it } from "vitest";
import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings";
describe("server keybindings", () => {
it("parses shortcuts including plus key", () => {
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
});
assert.deepEqual(parseKeybindingShortcut("mod++"), {
key: "+",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
});
});
it("compiles valid rule with parsed when AST", () => {
const compiled = compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalOpen && !terminalFocus",
});
assert.deepEqual(compiled, {
command: "terminal.split",
shortcut: {
key: "d",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "and",
left: { type: "identifier", name: "terminalOpen" },
right: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
});
});
it("rejects invalid rules", () => {
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+shift+d+o",
command: "terminal.new",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: "terminalFocus && (",
}),
);
});
});
+352
View File
@@ -0,0 +1,352 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
KeybindingRule,
KeybindingsConfig,
KeybindingShortcut,
KeybindingWhenNode,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { keybindingRuleSchema } from "@t3tools/contracts";
interface KeybindingsLogger {
warn(message: string, context?: Record<string, unknown>): void;
}
type WhenToken =
| { type: "identifier"; value: string }
| { type: "not" }
| { type: "and" }
| { type: "or" }
| { type: "lparen" }
| { type: "rparen" };
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+o", command: "editor.openFavorite" },
];
function normalizeKeyToken(token: string): string {
if (token === "space") return " ";
if (token === "esc") return "escape";
return token;
}
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
const rawTokens = value
.toLowerCase()
.split("+")
.map((token) => token.trim());
const tokens = [...rawTokens];
let trailingEmptyCount = 0;
while (tokens[tokens.length - 1] === "") {
trailingEmptyCount += 1;
tokens.pop();
}
if (trailingEmptyCount > 0) {
tokens.push("+");
}
if (tokens.some((token) => token.length === 0)) {
return null;
}
if (tokens.length === 0) return null;
let key: string | null = null;
let metaKey = false;
let ctrlKey = false;
let shiftKey = false;
let altKey = false;
let modKey = false;
for (const token of tokens) {
switch (token) {
case "cmd":
case "meta":
metaKey = true;
break;
case "ctrl":
case "control":
ctrlKey = true;
break;
case "shift":
shiftKey = true;
break;
case "alt":
case "option":
altKey = true;
break;
case "mod":
modKey = true;
break;
default: {
if (key !== null) return null;
key = normalizeKeyToken(token);
}
}
}
if (key === null) return null;
return {
key,
metaKey,
ctrlKey,
shiftKey,
altKey,
modKey,
};
}
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
const tokens: WhenToken[] = [];
let index = 0;
while (index < expression.length) {
const current = expression[index];
if (!current) break;
if (/\s/.test(current)) {
index += 1;
continue;
}
if (expression.startsWith("&&", index)) {
tokens.push({ type: "and" });
index += 2;
continue;
}
if (expression.startsWith("||", index)) {
tokens.push({ type: "or" });
index += 2;
continue;
}
if (current === "!") {
tokens.push({ type: "not" });
index += 1;
continue;
}
if (current === "(") {
tokens.push({ type: "lparen" });
index += 1;
continue;
}
if (current === ")") {
tokens.push({ type: "rparen" });
index += 1;
continue;
}
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
if (!identifier) {
return null;
}
tokens.push({ type: "identifier", value: identifier[0] });
index += identifier[0].length;
}
return tokens;
}
export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
const tokens = tokenizeWhenExpression(expression);
if (!tokens || tokens.length === 0) return null;
let index = 0;
const parsePrimary = (): KeybindingWhenNode | null => {
const token = tokens[index];
if (!token) return null;
if (token.type === "identifier") {
index += 1;
return { type: "identifier", name: token.value };
}
if (token.type === "lparen") {
index += 1;
const expressionNode = parseOr();
const closeToken = tokens[index];
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
return null;
}
index += 1;
return expressionNode;
}
return null;
};
const parseUnary = (): KeybindingWhenNode | null => {
const token = tokens[index];
if (token?.type === "not") {
index += 1;
const node = parseUnary();
if (!node) return null;
return { type: "not", node };
}
return parsePrimary();
};
const parseAnd = (): KeybindingWhenNode | null => {
let left = parseUnary();
if (!left) return null;
while (tokens[index]?.type === "and") {
index += 1;
const right = parseUnary();
if (!right) return null;
left = { type: "and", left, right };
}
return left;
};
const parseOr = (): KeybindingWhenNode | null => {
let left = parseAnd();
if (!left) return null;
while (tokens[index]?.type === "or") {
index += 1;
const right = parseAnd();
if (!right) return null;
left = { type: "or", left, right };
}
return left;
};
const ast = parseOr();
if (!ast || index !== tokens.length) return null;
return ast;
}
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
const key = rule.key.trim();
if (key.length === 0) return null;
const shortcut = parseKeybindingShortcut(key);
if (!shortcut) return null;
const when = rule.when?.trim();
if (when && when.length > 0) {
const whenAst = parseKeybindingWhenExpression(when);
if (!whenAst) return null;
return {
command: rule.command,
shortcut,
whenAst,
};
}
return {
command: rule.command,
shortcut,
};
}
export function compileResolvedKeybindingsConfig(
config: KeybindingsConfig,
): ResolvedKeybindingsConfig {
const compiled: ResolvedKeybindingsConfig = [];
for (const rule of config) {
const resolved = compileResolvedKeybindingRule(rule);
if (!resolved) continue;
compiled.push(resolved);
}
return compiled;
}
function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
const resolved: ResolvedKeybindingsConfig = [];
for (const rule of DEFAULT_KEYBINDINGS) {
const compiled = compileResolvedKeybindingRule(rule);
if (!compiled) {
throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
}
resolved.push(compiled);
}
return resolved;
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
if (custom.length === 0) {
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
const overriddenCommands = new Set(custom.map((binding) => binding.command));
const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
(binding) => !overriddenCommands.has(binding.command),
);
const merged = [...retainedDefaults, ...custom];
if (merged.length <= 256) {
return merged;
}
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
return merged.slice(-256);
}
export function loadResolvedKeybindingsConfig(
logger: KeybindingsLogger,
): ResolvedKeybindingsConfig {
const configPath = path.join(os.homedir(), ".t3", "keybindings.json");
try {
const raw = fs.readFileSync(configPath, "utf8");
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
});
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
const sanitized: ResolvedKeybindingsConfig = [];
let invalidEntries = 0;
for (const entry of parsed) {
const result = keybindingRuleSchema.safeParse(entry);
if (result.success) {
const compiled = compileResolvedKeybindingRule(result.data);
if (!compiled) {
invalidEntries += 1;
continue;
}
sanitized.push(compiled);
continue;
}
invalidEntries += 1;
}
if (invalidEntries > 0) {
logger.warn("ignoring invalid keybinding entries", {
path: configPath,
invalidEntries,
totalEntries: parsed.length,
});
}
const overriddenCommands = new Set(sanitized.map((entry) => entry.command));
const mergedBeforeCapLength =
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
.length + sanitized.length;
const merged = mergeWithDefaultKeybindings(sanitized);
if (mergedBeforeCapLength > 256) {
logger.warn("truncating merged keybindings config to max entries", {
path: configPath,
maxEntries: 256,
});
}
return merged;
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
logger.warn("ignoring malformed keybindings config", {
path: configPath,
error: error instanceof Error ? error.message : String(error),
});
}
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
+248 -1
View File
@@ -11,10 +11,13 @@ import {
DEFAULT_TERMINAL_ID,
WS_CHANNELS,
WS_METHODS,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type WsPush,
type WsResponse,
} from "@t3tools/contracts";
import { ProjectRegistry } from "./projectRegistry";
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
import type {
TerminalClearInput,
TerminalCloseInput,
@@ -192,6 +195,32 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
}
}
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
const resolved: ResolvedKeybindingsConfig = [];
for (const binding of bindings) {
const compiled = compileResolvedKeybindingRule(binding);
if (!compiled) {
throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`);
}
resolved.push(compiled);
}
return resolved;
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
function mergeWithDefaultsForTest(custom: KeybindingsConfig): ResolvedKeybindingsConfig {
if (custom.length === 0) {
return DEFAULT_RESOLVED_KEYBINDINGS;
}
const overriddenCommands = new Set(custom.map((binding) => binding.command));
const retainedDefaults = DEFAULT_KEYBINDINGS.filter(
(binding) => !overriddenCommands.has(binding.command),
);
return compileKeybindings([...retainedDefaults, ...custom].slice(-256));
}
describe("WebSocket Server", () => {
let server: ReturnType<typeof createServer> | null = null;
const connections: WebSocket[] = [];
@@ -307,7 +336,225 @@ describe("WebSocket Server", () => {
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({ cwd: "/my/workspace" });
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
});
it("reads keybindings from ~/.t3/keybindings.json", async () => {
const fakeHome = makeTempDir("t3code-home-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify([
{ key: "cmd+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: mergeWithDefaultsForTest([
{ key: "cmd+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
]),
});
});
it("warns and ignores invalid keybinding entries", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-invalid-entry-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+z", command: "invalid.command", when: "terminalFocus" },
]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: mergeWithDefaultsForTest([{ key: "mod+j", command: "terminal.toggle" }]),
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("ignoring invalid keybinding entries"),
),
).toBe(true);
});
it("warns and ignores keybindings with malformed when expressions", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-invalid-when-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify([{ key: "mod+j", command: "terminal.toggle", when: "terminalFocus && (" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("ignoring invalid keybinding entries"),
),
).toBe(true);
});
it("reads keybindings once at startup and caches the resolved config", async () => {
const fakeHome = makeTempDir("t3code-home-cached-config-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const keybindingsPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([{ key: "cmd+j", command: "terminal.toggle" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const firstResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(firstResponse.error).toBeUndefined();
expect(firstResponse.result).toEqual({
cwd: "/my/workspace",
keybindings: mergeWithDefaultsForTest([{ key: "cmd+j", command: "terminal.toggle" }]),
});
fs.writeFileSync(
keybindingsPath,
JSON.stringify([{ key: "cmd+k", command: "terminal.toggle" }]),
"utf8",
);
const secondResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(secondResponse.error).toBeUndefined();
expect(secondResponse.result).toEqual(firstResponse.result);
});
it("warns and ignores unsupported keybindings config format", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-unsupported-format-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(
path.join(configDir, "keybindings.json"),
JSON.stringify({ "terminal.toggle": "mod+j" }),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("unsupported format; expected array"),
),
).toBe(true);
});
it("warns and ignores malformed keybindings config files", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-invalid-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(path.join(configDir, "keybindings.json"), "{not-json", "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
expect(
warnSpy.mock.calls.some(([message]) =>
String(message).includes("ignoring malformed keybindings config"),
),
).toBe(true);
});
it("returns error for unknown methods", async () => {
+6 -1
View File
@@ -31,6 +31,7 @@ import {
removeGitWorktree,
} from "./git";
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig } from "./keybindings";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -90,6 +91,7 @@ export function createServer(options: ServerOptions) {
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
const keybindingsConfig = loadResolvedKeybindingsConfig(logger);
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
@@ -410,7 +412,10 @@ export function createServer(options: ServerOptions) {
return undefined;
case WS_METHODS.serverGetConfig:
return { cwd };
return {
cwd,
keybindings: keybindingsConfig,
};
default:
throw new Error(`Unknown method: ${request.method}`);
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import {
AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
isScrollContainerNearBottom,
} from "./chat-scroll";
describe("isScrollContainerNearBottom", () => {
it("returns true when already at bottom", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 600,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(true);
});
it("returns true when within the auto-scroll threshold", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 540,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(true);
});
it("returns false when the user is meaningfully above the bottom", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 520,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(false);
});
it("clamps negative thresholds to zero", () => {
expect(
isScrollContainerNearBottom(
{
scrollTop: 539,
clientHeight: 400,
scrollHeight: 1_000,
},
-1,
),
).toBe(false);
});
it("falls back to the default threshold for non-finite values", () => {
expect(
isScrollContainerNearBottom(
{
scrollTop: 540,
clientHeight: 400,
scrollHeight: 1_000,
},
Number.NaN,
),
).toBe(true);
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
});
});
+24
View File
@@ -0,0 +1,24 @@
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
interface ScrollPosition {
scrollTop: number;
clientHeight: number;
scrollHeight: number;
}
export function isScrollContainerNearBottom(
position: ScrollPosition,
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
): boolean {
const threshold = Number.isFinite(thresholdPx)
? Math.max(0, thresholdPx)
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
const { scrollTop, clientHeight, scrollHeight } = position;
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
return true;
}
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
return distanceFromBottom <= threshold;
}
+11 -1
View File
@@ -25,9 +25,15 @@ interface BranchToolbarProps {
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
onComposerFocusRequest?: () => void;
}
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
export default function BranchToolbar({
envMode,
onEnvModeChange,
envLocked,
onComposerFocusRequest,
}: BranchToolbarProps) {
const { state, dispatch } = useStore();
const api = useNativeApi();
const queryClient = useQueryClient();
@@ -123,6 +129,7 @@ export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: B
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
@@ -135,6 +142,7 @@ export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: B
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
@@ -143,6 +151,7 @@ export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: B
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
});
};
@@ -156,6 +165,7 @@ export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: B
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
});
};
+171 -50
View File
@@ -1,10 +1,13 @@
import {
EDITORS,
type EditorId,
ModelSlug,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type ProviderSendTurnAttachmentInput,
type ResolvedKeybindingsConfig,
type ProviderApprovalDecision,
ModelSlug,
type ProviderSendTurnAttachmentInput,
} from "@t3tools/contracts";
import {
type ClipboardEvent,
@@ -20,12 +23,9 @@ import {
useState,
} from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
gitBranchesQueryOptions,
gitCreateWorktreeMutationOptions,
} from "~/lib/gitReactQuery";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { isElectron } from "../env";
import { buildBootstrapInput } from "../historyBootstrap";
import {
@@ -45,11 +45,18 @@ import {
formatElapsed,
formatTimestamp,
} from "../session-logic";
import { isScrollContainerNearBottom } from "../chat-scroll";
import { useStore } from "../store";
import type { ChatImageAttachment } from "../types";
import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import { isTerminalToggleShortcut } from "../terminal-shortcuts";
import {
isOpenFavoriteEditorShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
shortcutLabelForCommand,
} from "../keybindings";
import ChatMarkdown from "./ChatMarkdown";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { useNativeApi } from "../hooks/useNativeApi";
@@ -69,7 +76,7 @@ import { Separator } from "./ui/separator";
import { Group, GroupSeparator } from "./ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
import { CursorIcon, Icon } from "./Icons";
import { cn } from "~/lib/utils";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
function formatMessageMeta(createdAt: string, duration: string | null): string {
@@ -82,6 +89,7 @@ const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
@@ -129,7 +137,9 @@ export default function ChatView() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ api, queryClient }));
const createWorktreeMutation = useMutation(
gitCreateWorktreeMutationOptions({ api, queryClient }),
);
const [prompt, setPrompt] = useState("");
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
@@ -145,6 +155,7 @@ export default function ChatView() {
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const messagesScrollRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const dragDepthRef = useRef(0);
@@ -252,14 +263,28 @@ export default function ChatView() {
} as const);
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
const branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd));
const keybindingsQuery = useQuery({
...serverConfigQueryOptions(api),
select: (config) => config.keybindings,
});
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const splitTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.split"),
[keybindings],
);
const newTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.new"),
[keybindings],
);
const envLocked = Boolean(
activeThread &&
(activeThread.messages.length > 0 ||
(activeThread.session !== null && activeThread.session.status !== "closed")),
);
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
for (const image of images) {
if (!image.previewUrl) continue;
@@ -273,6 +298,11 @@ export default function ChatView() {
const cursor = textarea.value.length;
textarea.setSelectionRange(cursor, cursor);
}, []);
const scheduleComposerFocus = useCallback(() => {
window.requestAnimationFrame(() => {
focusComposer();
});
}, [focusComposer]);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
dispatch({
@@ -344,6 +374,7 @@ export default function ChatView() {
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
dispatch({ type: "SET_RUNTIME_MODE", mode });
scheduleComposerFocus();
if (!api) return;
const sessionIds = state.threads
@@ -366,19 +397,30 @@ export default function ChatView() {
// Auto-scroll on new messages
const messageCount = activeThread?.messages.length ?? 0;
const workLogCount = workLogEntries.length;
useLayoutEffect(() => {
if (!activeThread?.id) return;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}, [activeThread?.id]);
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior });
shouldAutoScrollRef.current = true;
}, []);
const onMessagesScroll = useCallback(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
shouldAutoScrollRef.current = isScrollContainerNearBottom(scrollContainer);
}, []);
useLayoutEffect(() => {
if (!activeThread?.id) return;
scrollMessagesToBottom();
}, [activeThread?.id, scrollMessagesToBottom]);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messageCount]);
if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth");
}, [messageCount, scrollMessagesToBottom]);
useEffect(() => {
if (phase !== "running") return;
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [phase, workLogCount]);
if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth");
}, [phase, workLogCount, scrollMessagesToBottom]);
useEffect(() => {
setExpandedWorkGroups({});
@@ -477,15 +519,64 @@ export default function ChatView() {
}, [activeThread?.terminalOpen, activeThreadId, focusComposer]);
useEffect(() => {
const isTerminalFocused = (): boolean => {
const activeElement = document.activeElement;
if (!(activeElement instanceof HTMLElement)) return false;
if (activeElement.classList.contains("xterm-helper-textarea")) return true;
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
};
const handler = (event: globalThis.KeyboardEvent) => {
if (!activeThreadId) return;
if (!isTerminalToggleShortcut(event)) return;
if (!activeThreadId || event.defaultPrevented) return;
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(activeThread?.terminalOpen),
};
if (isTerminalToggleShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
toggleTerminalVisibility();
return;
}
if (isTerminalSplitShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
splitTerminal();
return;
}
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
event.preventDefault();
toggleTerminalVisibility();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
createNewTerminal();
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [activeThreadId, toggleTerminalVisibility]);
}, [
activeThread?.terminalOpen,
activeThreadId,
createNewTerminal,
dispatch,
splitTerminal,
keybindings,
toggleTerminalVisibility,
]);
const setThreadError = (threadId: string | null, error: string | null) => {
if (!threadId) return;
@@ -806,14 +897,32 @@ export default function ChatView() {
}
};
const onModelSelect = (model: ModelSlug) => {
if (!activeThread) return;
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
};
const onModelSelect = useCallback(
(model: ModelSlug) => {
if (!activeThread) return;
dispatch({
type: "SET_THREAD_MODEL",
threadId: activeThread.id,
model: resolveModelSlug(model),
});
scheduleComposerFocus();
},
[activeThread, dispatch, scheduleComposerFocus],
);
const onEffortSelect = useCallback(
(effort: ReasoningEffort) => {
setSelectedEffort(effort);
scheduleComposerFocus();
},
[scheduleComposerFocus],
);
const onEnvModeChange = useCallback(
(mode: "local" | "worktree") => {
setEnvMode(mode);
scheduleComposerFocus();
},
[scheduleComposerFocus],
);
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -852,7 +961,7 @@ export default function ChatView() {
</div>
<div className="flex items-center gap-3">
{/* Open in editor */}
{activeProject && <OpenInPicker />}
{activeProject && <OpenInPicker keybindings={keybindings} />}
{/* Git actions */}
{activeProject && <GitActionsControl api={api} gitCwd={gitCwd} />}
@@ -943,7 +1052,11 @@ export default function ChatView() {
)}
{/* Messages */}
<div ref={messagesScrollRef} className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
<div
ref={messagesScrollRef}
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">
@@ -1213,7 +1326,7 @@ export default function ChatView() {
<Separator orientation="vertical" className="mx-0.5 h-4" />
{/* Reasoning effort */}
<ReasoningEffortPicker effort={selectedEffort} onEffortChange={setSelectedEffort} />
<ReasoningEffortPicker effort={selectedEffort} onEffortChange={onEffortSelect} />
{/* Divider */}
<Separator orientation="vertical" className="mx-0.5 h-4" />
@@ -1316,7 +1429,12 @@ export default function ChatView() {
</div>
{isGitRepo && (
<BranchToolbar envMode={envMode} onEnvModeChange={setEnvMode} envLocked={envLocked} />
<BranchToolbar
envMode={envMode}
onEnvModeChange={onEnvModeChange}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
/>
)}
{activeThread.terminalOpen && api && activeProject && (
@@ -1333,6 +1451,8 @@ export default function ChatView() {
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
@@ -1428,7 +1548,7 @@ function ReasoningEffortPicker(props: {
);
}
function OpenInPicker() {
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;
@@ -1441,9 +1561,9 @@ function OpenInPicker() {
value: "cursor",
},
{
label: navigator.platform.includes("Mac")
label: isMacPlatform(navigator.platform)
? "Finder"
: navigator.platform.includes("Win")
: isWindowsPlatform(navigator.platform)
? "Explorer"
: "Files",
Icon: FolderClosedIcon,
@@ -1469,20 +1589,23 @@ function OpenInPicker() {
[api, activeProject, activeThread, lastEditor, setLastEditor],
);
// Cmd+O / Ctrl+O to open in last-used editor
const openFavoriteEditorShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "editor.openFavorite"),
[keybindings],
);
useEffect(() => {
const handler = (e: globalThis.KeyboardEvent) => {
if (e.key === "o" && (e.metaKey || e.ctrlKey) && !e.shiftKey) {
if (api && activeProject) {
e.preventDefault();
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, lastEditor);
}
}
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!api || !activeProject) return;
e.preventDefault();
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, lastEditor);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [api, activeProject, activeThread, lastEditor]);
}, [api, activeProject, activeThread, keybindings, lastEditor]);
return (
<Group aria-label="Subscription actions">
@@ -1500,10 +1623,8 @@ function OpenInPicker() {
<MenuItem key={value} onClick={() => openInEditor(value)}>
<Icon aria-hidden="true" className="text-muted-foreground" />
{label}
{value === lastEditor && (
<MenuShortcut>
{navigator.platform.includes("Mac") ? "\u2318O" : "Ctrl+O"}
</MenuShortcut>
{value === lastEditor && openFavoriteEditorShortcutLabel && (
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
)}
</MenuItem>
))}
@@ -320,6 +320,18 @@ describe("when: branch is behind upstream", () => {
});
});
describe("when: branch has diverged from upstream", () => {
it("resolveQuickAction returns a disabled sync hint", () => {
const quick = resolveQuickAction(status({ aheadCount: 2, behindCount: 1 }), false);
assert.deepEqual(quick, {
label: "Sync branch",
disabled: true,
kind: "show_hint",
hint: "Branch has diverged from upstream. Rebase/merge first.",
});
});
});
describe("when: working tree has local changes", () => {
it("resolveQuickAction returns commit, push, and create PR", () => {
const quick = resolveQuickAction(status({ hasWorkingTreeChanges: true }), false);
@@ -181,6 +181,7 @@ export function resolveQuickAction(
const hasOpenPr = gitStatus.openPr !== null;
const isAhead = gitStatus.aheadCount > 0;
const isBehind = gitStatus.behindCount > 0;
const isDiverged = isAhead && isBehind;
if (!hasBranch) {
return {
@@ -203,6 +204,15 @@ export function resolveQuickAction(
};
}
if (isDiverged) {
return {
label: "Sync branch",
disabled: true,
kind: "show_hint",
hint: "Branch has diverged from upstream. Rebase/merge first.",
};
}
if (isBehind) {
return {
label: "Pull",
+110 -51
View File
@@ -1,6 +1,6 @@
import { type GitStatusResult, type GitStackedAction, type NativeApi } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
import {
@@ -38,6 +38,7 @@ import {
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { useStore } from "~/store";
import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
interface GitActionsControlProps {
@@ -136,6 +137,12 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
}
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
const { state } = useStore();
const activeThreadId = state.activeThreadId;
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const queryClient = useQueryClient();
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
@@ -147,6 +154,16 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(api, gitCwd));
// Default to true while loading so we don't flash init controls.
const isRepo = branchList?.isRepo ?? true;
const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
const isGitStatusOutOfSync =
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
useEffect(() => {
if (!isGitStatusOutOfSync) return;
void invalidateGitQueries(queryClient);
}, [isGitStatusOutOfSync, queryClient]);
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
const initMutation = useMutation(gitInitMutationOptions({ api, cwd: gitCwd, queryClient }));
@@ -157,19 +174,19 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
const isDefaultBranch = useMemo(() => {
const currentBranch = gitStatus?.branch;
if (!currentBranch) return false;
const current = branchList?.branches.find((branch) => branch.name === currentBranch);
return current?.isDefault ?? (currentBranch === "main" || currentBranch === "master");
}, [branchList?.branches, gitStatus?.branch]);
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
const current = branchList?.branches.find((branch) => branch.name === branchName);
return current?.isDefault ?? (branchName === "main" || branchName === "master");
}, [branchList?.branches, gitStatusForActions?.branch]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatus, isGitActionRunning),
[gitStatus, isGitActionRunning],
() => buildMenuItems(gitStatusForActions, isGitActionRunning),
[gitStatusForActions, isGitActionRunning],
);
const quickAction = useMemo(
() => resolveQuickAction(gitStatus, isGitActionRunning, isDefaultBranch),
[gitStatus, isDefaultBranch, isGitActionRunning],
() => resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch),
[gitStatusForActions, isDefaultBranch, isGitActionRunning],
);
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
@@ -178,37 +195,49 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
const maybeConfirmPushToDefaultBranch = useCallback(
async (action: GitStackedAction): Promise<boolean> => {
if (!api) return false;
if (!requiresDefaultBranchConfirmation(action, isDefaultBranch) || !gitStatus?.branch) {
if (
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
!gitStatusForActions?.branch
) {
return true;
}
return api.dialogs.confirm(
`You're about to push to the default branch "${gitStatus.branch}". Continue?`,
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
);
},
[api, gitStatus?.branch, isDefaultBranch],
[api, gitStatusForActions?.branch, isDefaultBranch],
);
const openExistingPr = useCallback(async () => {
if (!api) {
toastManager.add({ type: "error", title: "Link opening is unavailable." });
toastManager.add({
type: "error",
title: "Link opening is unavailable.",
data: threadToastData,
});
return;
}
const prUrl = gitStatus?.openPr?.url ?? null;
const prUrl = gitStatusForActions?.openPr?.url ?? null;
if (!prUrl) {
toastManager.add({ type: "error", title: "No open PR found." });
toastManager.add({
type: "error",
title: "No open PR found.",
data: threadToastData,
});
return;
}
const promise = api.shell.openExternal(prUrl);
toastManager.promise(promise, {
loading: { title: "Opening PR..." },
success: { title: "PR opened" },
loading: { title: "Opening PR...", data: threadToastData },
success: { title: "PR opened", data: threadToastData },
error: (err) => ({
title: "Unable to open PR link",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
}),
});
void promise.catch(() => undefined);
}, [api, gitStatus?.openPr?.url]);
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
const runGitActionWithToast = useCallback(
async ({
@@ -226,11 +255,13 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
if (!confirmed) return;
onConfirmed?.();
const pushTarget = gitStatus?.branch ? `origin/${gitStatus.branch}` : undefined;
const pushTarget = gitStatusForActions?.branch
? `origin/${gitStatusForActions.branch}`
: undefined;
const progressStages = buildGitActionProgressStages({
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!gitStatus?.hasWorkingTreeChanges,
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
...(pushTarget ? { pushTarget } : {}),
});
@@ -238,6 +269,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
let stageIndex = 0;
@@ -247,6 +279,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
data: threadToastData,
});
}, 1100);
@@ -264,7 +297,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const prUrl = result.pr.url ?? gitStatus?.openPr?.url;
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
@@ -279,6 +312,10 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
title: resultToast.title,
description: resultToast.description,
timeout: 0,
data: {
...threadToastData,
dismissAfterVisibleMs: 10_000,
},
...(shouldOfferPushCta
? {
actionProps: {
@@ -320,18 +357,20 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
});
}
},
[
api,
gitStatus?.branch,
gitStatus?.hasWorkingTreeChanges,
gitStatus?.openPr?.url,
gitStatusForActions?.branch,
gitStatusForActions?.hasWorkingTreeChanges,
gitStatusForActions?.openPr?.url,
isDefaultBranch,
maybeConfirmPushToDefaultBranch,
runImmediateGitActionMutation,
setActiveDialogAction,
threadToastData,
],
);
@@ -343,17 +382,19 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
if (quickAction.kind === "run_pull") {
const promise = pullMutation.mutateAsync();
toastManager.promise(promise, {
loading: { title: "Pulling..." },
loading: { title: "Pulling...", data: threadToastData },
success: (result) => ({
title: result.status === "pulled" ? "Pulled" : "Already up to date",
description:
result.status === "pulled"
? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
: `${result.branch} is already synchronized.`,
data: threadToastData,
}),
error: (err) => ({
title: "Pull failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
}),
});
void promise.catch(() => undefined);
@@ -364,13 +405,14 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
type: "info",
title: quickAction.label,
description: quickAction.hint,
data: threadToastData,
});
return;
}
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast]);
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
@@ -414,6 +456,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
toastManager.add({
type: "error",
title: "Editor opening is unavailable.",
data: threadToastData,
});
return;
}
@@ -423,10 +466,11 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
type: "error",
title: "Unable to open file",
description: error instanceof Error ? error.message : "An error occurred.",
data: threadToastData,
});
});
},
[api, gitCwd],
[api, gitCwd, threadToastData],
);
if (!gitCwd) return null;
@@ -491,7 +535,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
{gitActionMenuItems.map((item) => {
const disabledReason = getMenuActionDisabledReason(
item,
gitStatus,
gitStatusForActions,
isGitActionRunning,
);
if (item.disabled && disabledReason) {
@@ -527,19 +571,25 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
</MenuItem>
);
})}
{gitStatus?.branch === null && (
{gitStatusForActions?.branch === null && (
<p className="px-2 py-1.5 text-xs text-warning">
Detached HEAD: create and checkout a branch to enable push and PR actions.
</p>
)}
{gitStatus &&
gitStatus.branch !== null &&
!gitStatus.hasWorkingTreeChanges &&
gitStatus.behindCount > 0 && (
{gitStatusForActions &&
gitStatusForActions.branch !== null &&
!gitStatusForActions.hasWorkingTreeChanges &&
gitStatusForActions.behindCount > 0 &&
gitStatusForActions.aheadCount === 0 && (
<p className="px-2 py-1.5 text-xs text-warning">
Behind upstream. Pull/rebase first.
</p>
)}
{isGitStatusOutOfSync && (
<p className="px-2 py-1.5 text-xs text-muted-foreground">
Refreshing git status...
</p>
)}
{gitStatusError && (
<p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
)}
@@ -568,37 +618,42 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="font-medium">{gitStatus?.branch ?? "(detached HEAD)"}</span>
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
</span>
{activeDialogAction !== "commit" && (
<>
<span className="text-muted-foreground">Upstream</span>
<span className="font-medium">
{!gitStatus || !gitStatus.hasUpstream
{!gitStatusForActions || !gitStatusForActions.hasUpstream
? "No upstream configured"
: gitStatus.aheadCount === 0 && gitStatus.behindCount === 0
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatus.aheadCount > 0 && gitStatus.behindCount > 0
? `Diverged (+${gitStatus.aheadCount} / -${gitStatus.behindCount})`
: gitStatus.aheadCount > 0
? `Ahead by ${gitStatus.aheadCount}`
: `Behind by ${gitStatus.behindCount}`}
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
: `Behind by ${gitStatusForActions.behindCount}`}
</span>
<span className="text-muted-foreground">Working tree</span>
<span className="font-medium">
{!gitStatus || !gitStatus.hasWorkingTreeChanges
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
? "Clean"
: `${gitStatus.workingTree.files.length} file(s)`}
: `${gitStatusForActions.workingTree.files.length} file(s)`}
</span>
<span className="text-muted-foreground">Diff</span>
<span className="font-mono">
{!gitStatus || !gitStatus.hasWorkingTreeChanges ? (
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
"none"
) : (
<>
<span className="text-success">+{gitStatus.workingTree.insertions}</span>
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatus.workingTree.deletions}
-{gitStatusForActions.workingTree.deletions}
</span>
</>
)}
@@ -608,13 +663,13 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
</div>
<div className="space-y-1">
<p className="text-muted-foreground">Files</p>
{!gitStatus || gitStatus.workingTree.files.length === 0 ? (
{!gitStatusForActions || gitStatusForActions.workingTree.files.length === 0 ? (
<p className="font-medium">none</p>
) : (
<div className="space-y-2">
<ScrollArea className="h-44 rounded-md border border-input bg-background">
<div className="space-y-1 p-1">
{gitStatus.workingTree.files.map((file) => (
{gitStatusForActions.workingTree.files.map((file) => (
<button
type="button"
key={file.path}
@@ -632,9 +687,13 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
</div>
</ScrollArea>
<div className="flex justify-end font-mono">
<span className="text-success">+{gitStatus.workingTree.insertions}</span>
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">-{gitStatus.workingTree.deletions}</span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</div>
</div>
)}
+68 -10
View File
@@ -1,11 +1,13 @@
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isElectron } from "../env";
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 {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -14,9 +16,13 @@ import {
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { toastManager } from "./ui/toast";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const minutes = Math.floor(diff / 60_000);
@@ -112,8 +118,14 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
...serverConfigQueryOptions(api),
select: (config) => config.keybindings,
});
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ api, queryClient }));
const removeWorktreeMutation = useMutation(
gitRemoveWorktreeMutationOptions({ api, queryClient }),
);
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
@@ -322,15 +334,54 @@ export default function Sidebar() {
[api, dispatch, removeWorktreeMutation, state.projects, state.threads],
);
const handleProjectContextMenu = useCallback(
async (projectId: string, position: { x: number; y: number }) => {
if (!api) return;
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
const project = state.projects.find((entry) => entry.id === projectId);
if (!project) return;
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
if (projectThreads.length > 0) {
toastManager.add({
type: "warning",
title: "Project is not empty",
description: "Delete all threads in this project before deleting it.",
});
return;
}
const confirmed = await api.dialogs.confirm(
[`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
);
if (!confirmed) return;
if (isElectron) {
try {
await api.projects.remove({ id: projectId });
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error deleting project.";
console.error("Failed to remove project", { projectId, error });
toastManager.add({
type: "error",
title: `Failed to delete "${project.name}"`,
description: message,
});
return;
}
}
dispatch({ type: "DELETE_PROJECT", projectId });
},
[api, dispatch, state.projects, state.threads],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const isNewThreadShortcut =
event.metaKey &&
event.shiftKey &&
!event.ctrlKey &&
!event.altKey &&
event.key.toLowerCase() === "o";
if (!isNewThreadShortcut) return;
if (!isChatNewShortcut(event, keybindings)) return;
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
@@ -344,7 +395,7 @@ export default function Sidebar() {
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [handleNewThread, state.activeThreadId, state.projects, state.threads]);
}, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
@@ -408,6 +459,13 @@ export default function Sidebar() {
type="button"
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
onContextMenu={(e) => {
e.preventDefault();
void handleProjectContextMenu(project.id, {
x: e.clientX,
y: e.clientY,
});
}}
>
<span className="text-[10px] text-muted-foreground/70">
{project.expanded ? "▼" : "▶"}
@@ -18,7 +18,7 @@ import {
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../terminal-shortcuts";
import { isTerminalClearShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -416,6 +416,8 @@ interface ThreadTerminalDrawerProps {
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
splitShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
@@ -468,6 +470,8 @@ export default function ThreadTerminalDrawer({
focusRequestId,
onSplitTerminal,
onNewTerminal,
splitShortcutLabel,
newShortcutLabel,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
@@ -694,7 +698,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label="Split Terminal"
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
@@ -702,7 +706,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminal}
label="New Terminal"
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
>
<Plus className="size-3.25" />
</TerminalActionButton>
@@ -779,14 +783,20 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onSplitTerminal}
label="Split Terminal"
label={
splitShortcutLabel
? `Split Terminal (${splitShortcutLabel})`
: "Split Terminal"
}
>
<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="New Terminal"
label={
newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"
}
>
<Plus className="size-3.25" />
</TerminalActionButton>
+267 -146
View File
@@ -1,6 +1,7 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import {
CircleAlertIcon,
CircleCheckIcon,
@@ -11,9 +12,18 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store";
const toastManager = Toast.createToastManager();
const anchoredToastManager = Toast.createToastManager();
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,
@@ -35,6 +45,93 @@ interface ToastProviderProps extends Toast.Provider.Props {
position?: ToastPosition;
}
function shouldRenderForActiveThread(
data: ThreadToastData | undefined,
activeThreadId: string | null,
): boolean {
const toastThreadId = data?.threadId;
if (!toastThreadId) return true;
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}>
@@ -45,9 +142,20 @@ function ToastProvider({ children, position = "top-right", ...props }: ToastProv
}
function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager();
const { state } = useStore();
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = state.activeThreadId;
const isTop = position.startsWith("top");
useEffect(() => {
const activeToastIds = new Set(toasts.map((toast) => toast.id));
for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
if (!activeToastIds.has(toastId)) {
threadToastVisibleTimeoutRemainingMs.delete(toastId);
}
}
}, [toasts]);
return (
<Toast.Portal data-slot="toast-portal">
<Toast.Viewport
@@ -64,91 +172,100 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
data-position={position}
data-slot="toast-viewport"
>
{toasts.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
return (
<Toast.Root
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<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">
{toast.actionProps.children}
</Toast.Action>
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-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)))]",
)}
</Toast.Content>
</Toast.Root>
);
})}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<ThreadToastVisibleAutoDismiss
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
toastId={toast.id}
/>
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
>
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
</Toast.Root>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
@@ -164,76 +281,80 @@ function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
}
function AnchoredToasts() {
const { toasts } = Toast.useToastManager();
const { state } = useStore();
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = state.activeThreadId;
return (
<Toast.Portal data-slot="toast-portal-anchored">
<Toast.Viewport className="outline-none" data-slot="toast-viewport-anchored">
{toasts.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const tooltipStyle = (toast.data as { tooltipStyle?: boolean })?.tooltipStyle ?? false;
const positionerProps = toast.positionerProps;
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const tooltipStyle = toast.data?.tooltipStyle ?? false;
const positionerProps = toast.positionerProps;
if (!positionerProps?.anchor) {
return null;
}
if (!positionerProps?.anchor) {
return null;
}
return (
<Toast.Positioner
className="z-50 max-w-[min(--spacing(64),var(--available-width))]"
data-slot="toast-positioner"
key={toast.id}
sideOffset={positionerProps.sideOffset ?? 4}
toast={toast}
>
<Toast.Root
className={cn(
"relative text-balance border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
tooltipStyle
? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"
: "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",
)}
data-slot="toast-popup"
return (
<Toast.Positioner
className="z-50 max-w-[min(--spacing(64),var(--available-width))]"
data-slot="toast-positioner"
key={toast.id}
sideOffset={positionerProps.sideOffset ?? 4}
toast={toast}
>
{tooltipStyle ? (
<Toast.Content className="pointer-events-auto px-2 py-1">
<Toast.Title data-slot="toast-title" />
</Toast.Content>
) : (
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<Toast.Root
className={cn(
"relative text-balance border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
tooltipStyle
? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"
: "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",
)}
data-slot="toast-popup"
toast={toast}
>
{tooltipStyle ? (
<Toast.Content className="pointer-events-auto px-2 py-1">
<Toast.Title data-slot="toast-title" />
</Toast.Content>
) : (
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
>
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
)}
</Toast.Root>
</Toast.Positioner>
);
})}
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
>
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
)}
</Toast.Root>
</Toast.Positioner>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
+343
View File
@@ -0,0 +1,343 @@
import { assert, describe, it } from "vitest";
import {
type KeybindingCommand,
type KeybindingShortcut,
type KeybindingWhenNode,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import {
formatShortcutLabel,
isChatNewShortcut,
isOpenFavoriteEditorShortcut,
isTerminalClearShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
shortcutLabelForCommand,
type ShortcutEventLike,
} from "./keybindings";
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
return {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
...overrides,
};
}
function modShortcut(
key: string,
overrides: Partial<Omit<KeybindingShortcut, "key">> = {},
): KeybindingShortcut {
return {
key,
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
...overrides,
};
}
function whenIdentifier(name: string): KeybindingWhenNode {
return { type: "identifier", name };
}
function whenNot(node: KeybindingWhenNode): KeybindingWhenNode {
return { type: "not", node };
}
function whenAnd(left: KeybindingWhenNode, right: KeybindingWhenNode): KeybindingWhenNode {
return { type: "and", left, right };
}
interface TestBinding {
shortcut: KeybindingShortcut;
command: KeybindingCommand;
whenAst?: KeybindingWhenNode;
}
function compile(bindings: TestBinding[]): ResolvedKeybindingsConfig {
return bindings.map((binding) => ({
command: binding.command,
shortcut: binding.shortcut,
...(binding.whenAst ? { whenAst: binding.whenAst } : {}),
}));
}
const DEFAULT_BINDINGS = compile([
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
{
shortcut: modShortcut("d"),
command: "terminal.split",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("d", { shiftKey: true }),
command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
]);
describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => {
assert.isTrue(
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel" }),
);
});
it("matches Ctrl+J on non-macOS", () => {
assert.isTrue(
isTerminalToggleShortcut(event({ ctrlKey: true }), DEFAULT_BINDINGS, { platform: "Win32" }),
);
});
});
describe("split/new terminal shortcuts", () => {
it("requires terminalFocus for default split/new bindings", () => {
assert.isFalse(
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
);
assert.isFalse(
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: false },
}),
);
});
it("matches split/new when terminalFocus is true", () => {
assert.isTrue(
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
);
assert.isTrue(
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
});
it("supports when expressions", () => {
const keybindings = compile([
{
shortcut: modShortcut("\\"),
command: "terminal.split",
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
},
{
shortcut: modShortcut("n", { shiftKey: true }),
command: "terminal.new",
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
},
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
]);
assert.isTrue(
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
platform: "Win32",
context: { terminalOpen: true, terminalFocus: false },
}),
);
assert.isFalse(
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
platform: "Win32",
context: { terminalOpen: false, terminalFocus: false },
}),
);
assert.isTrue(
isTerminalNewShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), keybindings, {
platform: "Win32",
context: { terminalOpen: true, terminalFocus: false },
}),
);
});
it("supports when boolean literals", () => {
const keybindings = compile([
{ shortcut: modShortcut("n"), command: "terminal.new", whenAst: whenIdentifier("true") },
{ shortcut: modShortcut("m"), command: "terminal.new", whenAst: whenIdentifier("false") },
]);
assert.isTrue(
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
platform: "Linux",
}),
);
assert.isFalse(
isTerminalNewShortcut(event({ key: "m", ctrlKey: true }), keybindings, {
platform: "Linux",
}),
);
});
});
describe("shortcutLabelForCommand", () => {
it("returns the most recent binding label", () => {
const bindings = compile([
{
shortcut: modShortcut("\\"),
command: "terminal.split",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("\\", { shiftKey: true }),
command: "terminal.split",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
]);
assert.strictEqual(shortcutLabelForCommand(bindings, "terminal.split", "Linux"), "Ctrl+Shift+\\");
});
it("returns labels for non-terminal commands", () => {
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
"Ctrl+O",
);
});
});
describe("chat/editor shortcuts", () => {
it("matches chat.new shortcut", () => {
assert.isTrue(
isChatNewShortcut(event({ key: "o", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
}),
);
assert.isTrue(
isChatNewShortcut(event({ key: "o", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
}),
);
});
it("matches editor.openFavorite shortcut", () => {
assert.isTrue(
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
}),
);
assert.isTrue(
isOpenFavoriteEditorShortcut(event({ key: "o", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
}),
);
});
});
describe("cross-command precedence", () => {
it("uses when + order so a later focused rule overrides a global rule", () => {
const keybindings = compile([
{ shortcut: modShortcut("n"), command: "chat.new" },
{
shortcut: modShortcut("n"),
command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"),
},
]);
assert.isTrue(
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
);
assert.isFalse(
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
);
assert.isFalse(
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
);
assert.isTrue(
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
);
});
it("still lets a later global rule win when both rules match", () => {
const keybindings = compile([
{
shortcut: modShortcut("n"),
command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"),
},
{ shortcut: modShortcut("n"), command: "chat.new" },
]);
assert.isFalse(
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
assert.isTrue(
isChatNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
});
});
describe("formatShortcutLabel", () => {
it("formats labels for macOS", () => {
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");
});
it("formats labels for plus key", () => {
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "MacIntel"), "⌘+");
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "Linux"), "Ctrl++");
});
});
describe("isTerminalClearShortcut", () => {
it("matches Ctrl+L on all platforms", () => {
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"));
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"));
});
it("matches Cmd+K on macOS", () => {
assert.isTrue(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"));
});
});
describe("plus key parsing", () => {
it("matches the plus key shortcut", () => {
const plusBindings = compile([{ shortcut: modShortcut("+"), command: "terminal.toggle" }]);
assert.isTrue(
isTerminalToggleShortcut(event({ key: "+", metaKey: true }), plusBindings, {
platform: "MacIntel",
}),
);
assert.isTrue(
isTerminalToggleShortcut(event({ key: "+", ctrlKey: true }), plusBindings, {
platform: "Linux",
}),
);
});
});
+221
View File
@@ -0,0 +1,221 @@
import {
type KeybindingCommand,
type KeybindingShortcut,
type KeybindingWhenNode,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { isMacPlatform } from "./lib/utils";
export interface ShortcutEventLike {
key: string;
metaKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
}
export interface ShortcutMatchContext {
terminalFocus: boolean;
terminalOpen: boolean;
[key: string]: boolean;
}
interface ShortcutMatchOptions {
platform?: string;
context?: Partial<ShortcutMatchContext>;
}
function normalizeEventKey(key: string): string {
const normalized = key.toLowerCase();
if (normalized === "esc") return "escape";
return normalized;
}
function matchesShortcut(
event: ShortcutEventLike,
shortcut: KeybindingShortcut,
platform = navigator.platform,
): boolean {
const key = normalizeEventKey(event.key);
if (key !== shortcut.key) return false;
const useMetaForMod = isMacPlatform(platform);
const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
return (
event.metaKey === expectedMeta &&
event.ctrlKey === expectedCtrl &&
event.shiftKey === shortcut.shiftKey &&
event.altKey === shortcut.altKey
);
}
function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
return options?.platform ?? navigator.platform;
}
function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
return {
terminalFocus: false,
terminalOpen: false,
...options?.context,
};
}
function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
switch (node.type) {
case "identifier":
if (node.name === "true") return true;
if (node.name === "false") return false;
return Boolean(context[node.name]);
case "not":
return !evaluateWhenNode(node.node, context);
case "and":
return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
case "or":
return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
}
}
function matchesWhenClause(
whenAst: KeybindingWhenNode | undefined,
context: ShortcutMatchContext,
): boolean {
if (!whenAst) return true;
return evaluateWhenNode(whenAst, context);
}
function matchesCommandShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
command: KeybindingCommand,
options?: ShortcutMatchOptions,
): boolean {
return resolveShortcutCommand(event, keybindings, options) === command;
}
function resolveShortcutCommand(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): KeybindingCommand | null {
const platform = resolvePlatform(options);
const context = resolveContext(options);
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
const binding = keybindings[index];
if (!binding) continue;
if (!matchesWhenClause(binding.whenAst, context)) continue;
if (!matchesShortcut(event, binding.shortcut, platform)) continue;
return binding.command;
}
return null;
}
function formatShortcutKeyLabel(key: string): string {
if (key === " ") return "Space";
if (key.length === 1) return key.toUpperCase();
if (key === "escape") return "Esc";
if (key === "arrowup") return "Up";
if (key === "arrowdown") return "Down";
if (key === "arrowleft") return "Left";
if (key === "arrowright") return "Right";
return key.slice(0, 1).toUpperCase() + key.slice(1);
}
export function formatShortcutLabel(
shortcut: KeybindingShortcut,
platform = navigator.platform,
): string {
const keyLabel = formatShortcutKeyLabel(shortcut.key);
const useMetaForMod = isMacPlatform(platform);
const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
const showAlt = shortcut.altKey;
const showShift = shortcut.shiftKey;
if (useMetaForMod) {
return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
}
const parts: string[] = [];
if (showCtrl) parts.push("Ctrl");
if (showAlt) parts.push("Alt");
if (showShift) parts.push("Shift");
if (showMeta) parts.push("Meta");
parts.push(keyLabel);
return parts.join("+");
}
export function shortcutLabelForCommand(
keybindings: ResolvedKeybindingsConfig,
command: KeybindingCommand,
platform = navigator.platform,
): string | null {
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
const binding = keybindings[index];
if (!binding || binding.command !== command) continue;
return formatShortcutLabel(binding.shortcut, platform);
}
return null;
}
export function isTerminalToggleShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
}
export function isTerminalSplitShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.split", options);
}
export function isTerminalNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.new", options);
}
export function isChatNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "chat.new", options);
}
export function isOpenFavoriteEditorShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
}
export function isTerminalClearShortcut(
event: ShortcutEventLike,
platform = navigator.platform,
): boolean {
const key = event.key.toLowerCase();
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
return true;
}
return (
isMacPlatform(platform) &&
key === "k" &&
event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.shiftKey
);
}
+21
View File
@@ -0,0 +1,21 @@
import type { NativeApi } from "@t3tools/contracts";
import { queryOptions } from "@tanstack/react-query";
export const serverQueryKeys = {
all: ["server"] as const,
config: () => ["server", "config"] as const,
};
export function serverConfigQueryOptions(api: NativeApi | undefined) {
return queryOptions({
queryKey: serverQueryKeys.config(),
queryFn: async () => {
if (!api || !api.server || typeof api.server.getConfig !== "function") {
throw new Error("Server config is unavailable.");
}
return api.server.getConfig();
},
enabled: !!api && !!api.server && typeof api.server.getConfig === "function",
staleTime: Infinity,
});
}
+15
View File
@@ -0,0 +1,15 @@
import { assert, describe, it } from "vitest";
import { isWindowsPlatform } from "./utils";
describe("isWindowsPlatform", () => {
it("matches Windows platform identifiers", () => {
assert.isTrue(isWindowsPlatform("Win32"));
assert.isTrue(isWindowsPlatform("Windows"));
assert.isTrue(isWindowsPlatform("windows_nt"));
});
it("does not match darwin", () => {
assert.isFalse(isWindowsPlatform("darwin"));
});
});
+8
View File
@@ -4,3 +4,11 @@ import { twMerge } from "tailwind-merge";
export function cn(...inputs: CxOptions) {
return twMerge(cx(inputs));
}
export function isMacPlatform(platform: string): boolean {
return /mac|iphone|ipad|ipod/i.test(platform);
}
export function isWindowsPlatform(platform: string): boolean {
return /^win(dows)?/i.test(platform);
}
+45
View File
@@ -486,6 +486,51 @@ describe("store reducer thread continuity", () => {
expect(next.activeThreadId).toBe("thread-a");
});
it("deletes a project and all of its threads", () => {
const state: AppState = {
projects: [
{
id: "project-1",
name: "One",
cwd: "/tmp/one",
model: "gpt-5.3-codex",
expanded: true,
},
{
id: "project-2",
name: "Two",
cwd: "/tmp/two",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
makeThread({
id: "thread-a",
projectId: "project-1",
}),
makeThread({
id: "thread-b",
projectId: "project-2",
}),
],
activeThreadId: "thread-a",
runtimeMode: "full-access",
diffOpen: false,
};
const next = reducer(state, {
type: "DELETE_PROJECT",
projectId: "project-1",
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe("project-2");
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-b");
expect(next.activeThreadId).toBe("thread-b");
});
it("marks the active thread as visited when selected", () => {
const state = makeState(
makeThread({
+20
View File
@@ -28,6 +28,7 @@ type Action =
| { type: "ADD_PROJECT"; project: Project }
| { type: "SYNC_PROJECTS"; projects: Project[] }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "DELETE_PROJECT"; projectId: string }
| { type: "ADD_THREAD"; thread: Thread }
| { type: "SET_ACTIVE_THREAD"; threadId: string }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
@@ -473,6 +474,25 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "DELETE_PROJECT": {
const projects = state.projects.filter((project) => project.id !== action.projectId);
if (projects.length === state.projects.length) {
return state;
}
const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
const activeThreadId = threads.some((thread) => thread.id === state.activeThreadId)
? state.activeThreadId
: (threads[0]?.id ?? null);
return {
...state,
projects,
threads,
activeThreadId,
};
}
case "ADD_THREAD": {
const nextThread = normalizeThreadTerminals({
...action.thread,
+1 -4
View File
@@ -1,4 +1,5 @@
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { isMacPlatform } from "./lib/utils";
export type TerminalLinkKind = "url" | "path";
@@ -15,10 +16,6 @@ const FILE_PATH_PATTERN =
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
const LAST_EDITOR_KEY = "t3code:last-editor";
function isMacPlatform(platform: string): boolean {
return /mac|iphone|ipad|ipod/i.test(platform);
}
function trimClosingDelimiters(value: string): string {
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
if (output.length === 0) return output;
-63
View File
@@ -1,63 +0,0 @@
import { describe, expect, it } from "vitest";
import {
isTerminalClearShortcut,
isTerminalToggleShortcut,
type ShortcutEventLike,
} from "./terminal-shortcuts";
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
return {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
...overrides,
};
}
describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => {
expect(isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
});
it("matches Ctrl+J on non-macOS", () => {
expect(isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32")).toBe(true);
});
it("rejects wrong modifiers", () => {
expect(isTerminalToggleShortcut(event({ ctrlKey: true, shiftKey: true }), "Win32")).toBe(false);
expect(isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel")).toBe(
false,
);
});
it("rejects non-j keys", () => {
expect(isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux")).toBe(false);
});
});
describe("isTerminalClearShortcut", () => {
it("matches Ctrl+L on all platforms", () => {
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux")).toBe(true);
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel")).toBe(true);
});
it("matches Cmd+K on macOS", () => {
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel")).toBe(true);
});
it("rejects Cmd+K on non-macOS", () => {
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32")).toBe(false);
});
it("rejects wrong modifiers", () => {
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true, shiftKey: true }), "Linux"),
).toBe(false);
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true, altKey: true }), "MacIntel"),
).toBe(false);
});
});
-46
View File
@@ -1,46 +0,0 @@
export interface ShortcutEventLike {
key: string;
metaKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
}
function isMacPlatform(platform: string): boolean {
return /mac|iphone|ipad|ipod/i.test(platform);
}
export function isTerminalToggleShortcut(
event: ShortcutEventLike,
platform = navigator.platform,
): boolean {
const key = event.key.toLowerCase();
if (key !== "j") return false;
if (event.shiftKey || event.altKey) return false;
if (isMacPlatform(platform)) {
return event.metaKey && !event.ctrlKey;
}
return event.ctrlKey && !event.metaKey;
}
export function isTerminalClearShortcut(
event: ShortcutEventLike,
platform = navigator.platform,
): boolean {
const key = event.key.toLowerCase();
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
return true;
}
return (
isMacPlatform(platform) &&
key === "k" &&
event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.shiftKey
);
}
+3
View File
@@ -139,6 +139,9 @@ export function createWsNativeApi(): NativeApi {
return showContextMenuFallback(items, position);
},
},
server: {
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
},
};
instance = { api, transport };
+2
View File
@@ -5,5 +5,7 @@ export * from "./terminal";
export * from "./provider";
export * from "./model";
export * from "./ws";
export * from "./keybindings";
export * from "./server";
export * from "./project";
export * from "./git";
+4
View File
@@ -31,6 +31,7 @@ import type {
ProjectListResult,
ProjectRemoveInput,
} from "./project";
import type { ServerConfig } from "./server";
import type {
TerminalClearInput,
TerminalCloseInput,
@@ -113,4 +114,7 @@ export interface NativeApi {
position?: { x: number; y: number },
) => Promise<T | null>;
};
server: {
getConfig: () => Promise<ServerConfig>;
};
}
@@ -0,0 +1,92 @@
import { assert, describe, it } from "vitest";
import {
keybindingRuleSchema,
keybindingsConfigSchema,
resolvedKeybindingRuleSchema,
resolvedKeybindingsConfigSchema,
} from "./keybindings";
describe("keybindings contracts", () => {
it("parses keybinding rules", () => {
const parsed = keybindingRuleSchema.parse({
key: "mod+j",
command: "terminal.toggle",
});
assert.strictEqual(parsed.command, "terminal.toggle");
});
it("rejects invalid command values", () => {
assert.throws(() =>
keybindingRuleSchema.parse({
key: "mod+j",
command: "invalid.command",
}),
);
});
it("parses keybindings array payload", () => {
const parsed = keybindingsConfigSchema.parse([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
]);
assert.lengthOf(parsed, 2);
});
it("parses resolved keybinding rules", () => {
const parsed = resolvedKeybindingRuleSchema.parse({
command: "terminal.split",
shortcut: {
key: "d",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "and",
left: { type: "identifier", name: "terminalOpen" },
right: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
});
assert.strictEqual(parsed.shortcut.key, "d");
});
it("parses resolved keybindings arrays", () => {
const parsed = resolvedKeybindingsConfigSchema.parse([
{
command: "terminal.toggle",
shortcut: {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
},
]);
assert.lengthOf(parsed, 1);
});
it("rejects unknown fields in resolved keybinding rules", () => {
assert.throws(() =>
resolvedKeybindingRuleSchema.parse({
command: "terminal.toggle",
shortcut: {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
key: "mod+j",
}),
);
});
});
+73
View File
@@ -0,0 +1,73 @@
import { z } from "zod";
export const keybindingCommandSchema = z.enum([
"terminal.toggle",
"terminal.split",
"terminal.new",
"chat.new",
"editor.openFavorite",
]);
const keybindingValueSchema = z.string().trim().min(1).max(64);
const keybindingWhenSchema = z.string().trim().min(1).max(256);
export const keybindingRuleSchema = z.object({
key: keybindingValueSchema,
command: keybindingCommandSchema,
when: keybindingWhenSchema.optional(),
});
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 type KeybindingWhenNode =
| { type: "identifier"; name: string }
| { type: "not"; node: KeybindingWhenNode }
| { type: "and"; left: KeybindingWhenNode; right: KeybindingWhenNode }
| { type: "or"; left: KeybindingWhenNode; right: KeybindingWhenNode };
export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(() =>
z.union([
z.object({
type: z.literal("identifier"),
name: z.string().min(1),
}),
z.object({
type: z.literal("not"),
node: keybindingWhenNodeSchema,
}),
z.object({
type: z.literal("and"),
left: keybindingWhenNodeSchema,
right: keybindingWhenNodeSchema,
}),
z.object({
type: z.literal("or"),
left: keybindingWhenNodeSchema,
right: keybindingWhenNodeSchema,
}),
]),
);
export const resolvedKeybindingRuleSchema = z.object({
command: keybindingCommandSchema,
shortcut: keybindingShortcutSchema,
whenAst: keybindingWhenNodeSchema.optional(),
}).strict();
export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
export type KeybindingCommand = z.infer<typeof keybindingCommandSchema>;
export type KeybindingRule = z.infer<typeof keybindingRuleSchema>;
export type KeybindingsConfig = z.infer<typeof keybindingsConfigSchema>;
export type KeybindingShortcut = z.infer<typeof keybindingShortcutSchema>;
export type ResolvedKeybindingRule = z.infer<typeof resolvedKeybindingRuleSchema>;
export type ResolvedKeybindingsConfig = z.infer<typeof resolvedKeybindingsConfigSchema>;
+9
View File
@@ -0,0 +1,9 @@
import { z } from "zod";
import { resolvedKeybindingsConfigSchema } from "./keybindings";
export const serverConfigSchema = z.object({
cwd: z.string().min(1),
keybindings: resolvedKeybindingsConfigSchema.default([]),
});
export type ServerConfig = z.infer<typeof serverConfigSchema>;