Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db5681ec87 | ||
|
|
9e877f592b | ||
|
|
f719aea047 | ||
|
|
f6136bd4c2 | ||
|
|
385d77d0c2 | ||
|
|
ee2f6bd742 | ||
|
|
e1ba603605 | ||
|
|
5d61b8b14f | ||
|
|
2743e45dbe | ||
|
|
1b409c3946 | ||
|
|
60ed67e5e1 | ||
|
|
bd6a5c85e6 | ||
|
|
9cce509013 | ||
|
|
9f48564d84 | ||
|
|
e8556bcff9 | ||
|
|
a1532d5b2d | ||
|
|
ba4a62eb03 | ||
|
|
09ac18db82 | ||
|
|
376efdd340 | ||
|
|
7a5dd62d2f | ||
|
|
f64c26e708 | ||
|
|
6d8d39a5d1 | ||
|
|
afdfe16931 |
No files matched your search
@@ -760,6 +760,35 @@ describe("git integration", () => {
|
||||
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
||||
});
|
||||
|
||||
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await using clone = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(source.path, `push -u origin ${initialBranch}`);
|
||||
|
||||
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
|
||||
await git(clone.path, "config user.email '[email protected]'");
|
||||
await git(clone.path, "config user.name 'Test'");
|
||||
await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
|
||||
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
|
||||
await git(clone.path, "add CHANGELOG.md");
|
||||
await git(clone.path, "commit -m 'remote update'");
|
||||
await git(clone.path, `push origin ${initialBranch}`);
|
||||
|
||||
const core = new GitCoreService();
|
||||
const details = await core.statusDetails(source.path);
|
||||
expect(details.branch).toBe(initialBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
});
|
||||
|
||||
it("prepares commit context by auto-staging and creates commit", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
+62
-6
@@ -65,6 +65,8 @@ interface ExecuteGitOptions {
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||
function runGit(
|
||||
@@ -216,6 +218,8 @@ async function executeGit(
|
||||
}
|
||||
|
||||
export class GitCoreService {
|
||||
private readonly lastUpstreamRefreshAt = new Map<string, number>();
|
||||
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.statusDetails(input.cwd);
|
||||
@@ -231,6 +235,8 @@ export class GitCoreService {
|
||||
}
|
||||
|
||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
|
||||
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
||||
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
||||
this.gitStdout(cwd, ["diff", "--numstat"]),
|
||||
@@ -553,7 +559,9 @@ export class GitCoreService {
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
private async resolveCurrentUpstream(
|
||||
cwd: string,
|
||||
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
|
||||
const upstreamRef = trimStdout(
|
||||
await this.gitStdout(
|
||||
cwd,
|
||||
@@ -562,24 +570,72 @@ export class GitCoreService {
|
||||
),
|
||||
);
|
||||
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
||||
if (remoteName.length === 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if (upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchUpstreamRef(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
|
||||
}
|
||||
|
||||
private async fetchUpstreamRefForStatus(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
|
||||
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
|
||||
const now = Date.now();
|
||||
const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
|
||||
if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Record attempt time first to avoid repeated fetch spikes when status is polled often.
|
||||
this.lastUpstreamRefreshAt.set(cacheKey, now);
|
||||
await this.fetchUpstreamRefForStatus(cwd, upstream);
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
await this.fetchUpstreamRef(cwd, upstream);
|
||||
}
|
||||
|
||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { assert, beforeEach, describe, it, vi } from "vitest";
|
||||
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
|
||||
|
||||
const { runProcessMock } = vi.hoisted(() => ({
|
||||
runProcessMock: vi.fn<
|
||||
(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>
|
||||
>(),
|
||||
}));
|
||||
|
||||
vi.mock("./processRunner", () => ({
|
||||
runProcess: runProcessMock,
|
||||
}));
|
||||
|
||||
function processResult(
|
||||
overrides: Partial<ProcessRunResult> & Pick<ProcessRunResult, "stdout" | "code">,
|
||||
): ProcessRunResult {
|
||||
return {
|
||||
stdout: overrides.stdout,
|
||||
code: overrides.code,
|
||||
stderr: overrides.stderr ?? "",
|
||||
signal: overrides.signal ?? null,
|
||||
timedOut: overrides.timedOut ?? false,
|
||||
stdoutTruncated: overrides.stdoutTruncated ?? false,
|
||||
stderrTruncated: overrides.stderrTruncated ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries git-ignore chunking", () => {
|
||||
beforeEach(() => {
|
||||
runProcessMock.mockReset();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("chunks git check-ignore stdin to avoid building giant strings", async () => {
|
||||
const ignoredPaths = Array.from(
|
||||
{ length: 5000 },
|
||||
(_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`,
|
||||
);
|
||||
const keptPaths = ["src/keep.ts", "docs/readme.md"];
|
||||
const listedPaths = [...ignoredPaths, ...keptPaths];
|
||||
let checkIgnoreCalls = 0;
|
||||
|
||||
runProcessMock.mockImplementation(async (_command, args, options) => {
|
||||
if (args[0] === "rev-parse") {
|
||||
return processResult({ code: 0, stdout: "true\n" });
|
||||
}
|
||||
|
||||
if (args[0] === "ls-files") {
|
||||
return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` });
|
||||
}
|
||||
|
||||
if (args[0] === "check-ignore") {
|
||||
checkIgnoreCalls += 1;
|
||||
const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0);
|
||||
const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/"));
|
||||
return processResult({
|
||||
code: chunkIgnored.length > 0 ? 0 : 1,
|
||||
stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "",
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected command: git ${args.join(" ")}`);
|
||||
});
|
||||
|
||||
const { searchWorkspaceEntries } = await import("./workspaceEntries");
|
||||
const result = await searchWorkspaceEntries({
|
||||
cwd: "/virtual/workspace",
|
||||
query: "",
|
||||
limit: 100,
|
||||
});
|
||||
|
||||
assert.isAbove(checkIgnoreCalls, 1);
|
||||
assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/")));
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts"));
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import fs from "node:fs";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { afterEach, assert, describe, it } from "vitest";
|
||||
import { afterEach, assert, describe, it, vi } from "vitest";
|
||||
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
|
||||
@@ -30,6 +31,7 @@ function runGit(cwd: string, args: string[]): void {
|
||||
|
||||
describe("searchWorkspaceEntries", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -115,4 +117,60 @@ describe("searchWorkspaceEntries", () => {
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("deduplicates concurrent index builds for the same cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-concurrent-build-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
|
||||
let rootReadCount = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
||||
if (args[0] === cwd) {
|
||||
rootReadCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir,
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
||||
]);
|
||||
|
||||
assert.equal(rootReadCount, 1);
|
||||
});
|
||||
|
||||
it("limits concurrent directory reads while walking the filesystem", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-read-concurrency-");
|
||||
for (let index = 0; index < 80; index += 1) {
|
||||
writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};");
|
||||
}
|
||||
|
||||
let activeReads = 0;
|
||||
let peakReads = 0;
|
||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
||||
const target = args[0];
|
||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
||||
activeReads += 1;
|
||||
peakReads = Math.max(peakReads, activeReads);
|
||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
||||
try {
|
||||
return await originalReaddir(...args);
|
||||
} finally {
|
||||
activeReads -= 1;
|
||||
}
|
||||
}
|
||||
return originalReaddir(...args);
|
||||
}) as typeof fsPromises.readdir,
|
||||
);
|
||||
|
||||
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
||||
|
||||
assert.isAtMost(peakReads, 32);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
".git",
|
||||
".convex",
|
||||
@@ -32,6 +34,7 @@ interface WorkspaceIndex {
|
||||
}
|
||||
|
||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.split(path.sep).join("/");
|
||||
@@ -54,7 +57,10 @@ function basenameOf(input: string): string {
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input.trim().replace(/^[@./]+/, "").toLowerCase();
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreEntry(entry: ProjectEntry, query: string): number {
|
||||
@@ -101,6 +107,31 @@ function directoryAncestorsOf(relativePath: string): string[] {
|
||||
return directories;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency<TInput, TOutput>(
|
||||
items: readonly TInput[],
|
||||
concurrency: number,
|
||||
mapper: (item: TInput, index: number) => Promise<TOutput>,
|
||||
): Promise<TOutput[]> {
|
||||
if (items.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
|
||||
const results = Array.from({ length: items.length }) as TOutput[];
|
||||
let nextIndex = 0;
|
||||
|
||||
const workers = Array.from({ length: boundedConcurrency }, async () => {
|
||||
while (nextIndex < items.length) {
|
||||
const currentIndex = nextIndex;
|
||||
nextIndex += 1;
|
||||
results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
|
||||
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
|
||||
cwd,
|
||||
@@ -118,26 +149,67 @@ async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Prom
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
stdin: `${relativePaths.join("\0")}\0`,
|
||||
}).catch(() => null);
|
||||
if (!checkIgnore) {
|
||||
const ignoredPaths = new Set<string>();
|
||||
let chunk: string[] = [];
|
||||
let chunkBytes = 0;
|
||||
|
||||
const flushChunk = async (): Promise<boolean> => {
|
||||
if (chunk.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
}).catch(() => null);
|
||||
chunk = [];
|
||||
chunkBytes = 0;
|
||||
|
||||
if (!checkIgnore) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// git-check-ignore exits with 1 when no paths match.
|
||||
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const matchedIgnoredPaths = splitNullSeparatedPaths(
|
||||
checkIgnore.stdout,
|
||||
Boolean(checkIgnore.stdoutTruncated),
|
||||
);
|
||||
for (const ignoredPath of matchedIgnoredPaths) {
|
||||
ignoredPaths.add(ignoredPath);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
for (const relativePath of relativePaths) {
|
||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
||||
if (
|
||||
chunk.length > 0 &&
|
||||
chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
|
||||
!(await flushChunk())
|
||||
) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
chunk.push(relativePath);
|
||||
chunkBytes += relativePathBytes;
|
||||
|
||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await flushChunk())) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
// git-check-ignore exits with 1 when no paths match.
|
||||
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const ignoredPaths = new Set(
|
||||
splitNullSeparatedPaths(checkIgnore.stdout, Boolean(checkIgnore.stdoutTruncated)),
|
||||
);
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
@@ -183,14 +255,14 @@ async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex |
|
||||
}
|
||||
|
||||
const directoryEntries: ProjectEntry[] = [...directorySet]
|
||||
.sort((left, right) => left.localeCompare(right))
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((directoryPath) => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}));
|
||||
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
|
||||
.sort((left, right) => left.localeCompare(right))
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((filePath) => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
@@ -201,8 +273,7 @@ async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex |
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated:
|
||||
Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -220,8 +291,10 @@ async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
const directoryEntries = await Promise.all(
|
||||
currentDirectories.map(async (relativeDir) => {
|
||||
const directoryEntries = await mapWithConcurrency(
|
||||
currentDirectories,
|
||||
WORKSPACE_SCAN_READDIR_CONCURRENCY,
|
||||
async (relativeDir) => {
|
||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
||||
try {
|
||||
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
|
||||
@@ -235,7 +308,7 @@ async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
}
|
||||
return { relativeDir, dirents: null };
|
||||
}
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
@@ -315,14 +388,26 @@ async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const next = await buildWorkspaceIndex(cwd);
|
||||
workspaceIndexCache.set(cwd, next);
|
||||
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
|
||||
const oldestKey = workspaceIndexCache.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
workspaceIndexCache.delete(oldestKey);
|
||||
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
|
||||
if (inFlight) {
|
||||
return inFlight;
|
||||
}
|
||||
return next;
|
||||
|
||||
const nextPromise = buildWorkspaceIndex(cwd)
|
||||
.then((next) => {
|
||||
workspaceIndexCache.set(cwd, next);
|
||||
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
|
||||
const oldestKey = workspaceIndexCache.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
workspaceIndexCache.delete(oldestKey);
|
||||
}
|
||||
return next;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
||||
});
|
||||
inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
|
||||
return nextPromise;
|
||||
}
|
||||
|
||||
export async function searchWorkspaceEntries(
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-hotkeys": "^0.1.0",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
|
||||
isScrollContainerNearBottom,
|
||||
} from "./chat-scroll";
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
||||
|
||||
describe("isScrollContainerNearBottom", () => {
|
||||
it("returns true when already at bottom", () => {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: string | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: GitBranch[] | undefined;
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -67,36 +68,35 @@ export default function BranchToolbar({
|
||||
: branchNames;
|
||||
// ── Mutations ─────────────────────────────────────────────────────────
|
||||
|
||||
const checkoutMutation = useMutation({
|
||||
...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
const checkoutMutation = useMutation(
|
||||
gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
|
||||
const createBranchMutation = useMutation({
|
||||
...gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) =>
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
|
||||
});
|
||||
const createBranchMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
|
||||
// ── Effects ───────────────────────────────────────────────────────────
|
||||
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: current.name,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
@@ -153,6 +153,10 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -167,6 +171,9 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -26,8 +26,11 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { getHotkeyManager, useHotkey } from "@tanstack/react-hotkeys";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer/debouncer";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
@@ -57,13 +60,14 @@ import {
|
||||
} from "../session-logic";
|
||||
import { isScrollContainerNearBottom } from "../chat-scroll";
|
||||
import { useStore } from "../store";
|
||||
import type { ChatImageAttachment } from "../types";
|
||||
import { getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { MAX_THREAD_TERMINAL_COUNT, type ChatImageAttachment } from "../types";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import GitActionsControl from "./GitActionsControl";
|
||||
import {
|
||||
isOpenFavoriteEditorShortcut,
|
||||
shortcutsForCommands,
|
||||
isTerminalCloseShortcut,
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
@@ -75,6 +79,7 @@ import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
|
||||
import {
|
||||
BotIcon,
|
||||
ChevronDownIcon,
|
||||
CircleAlertIcon,
|
||||
FileIcon,
|
||||
@@ -91,9 +96,9 @@ 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 { basenameOfPath, cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Command, CommandItem, CommandList } from "./ui/command";
|
||||
import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -217,27 +222,13 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
|
||||
const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
item: ComposerCommandItem;
|
||||
index: number;
|
||||
isHighlighted: boolean;
|
||||
keyboardHighlight: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onHighlight: (index: number) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.id}
|
||||
data-composer-menu-index={props.index}
|
||||
className={cn(
|
||||
"cursor-pointer gap-2",
|
||||
props.keyboardHighlight &&
|
||||
!props.isHighlighted &&
|
||||
"data-highlighted:bg-transparent data-highlighted:text-inherit",
|
||||
props.isHighlighted && "bg-accent text-accent-foreground",
|
||||
)}
|
||||
onMouseEnter={() => {
|
||||
props.onHighlight(props.index);
|
||||
}}
|
||||
className="cursor-pointer gap-2"
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
@@ -253,7 +244,7 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
/>
|
||||
) : null}
|
||||
{props.item.type === "slash-command" ? (
|
||||
<CursorIcon className="size-4 text-muted-foreground/80" />
|
||||
<BotIcon className="size-4 text-muted-foreground/80" />
|
||||
) : null}
|
||||
{props.item.type === "model" ? (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
@@ -268,31 +259,30 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
|
||||
const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
items: ComposerCommandItem[];
|
||||
selectedIndex: number;
|
||||
keyboardHighlight: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
isLoading: boolean;
|
||||
triggerKind: ComposerTriggerKind | null;
|
||||
onHighlight: (index: number) => void;
|
||||
onHighlightedItemChange: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
menuRef: RefObject<HTMLDivElement | null>;
|
||||
commandInputRef: RefObject<HTMLInputElement | null>;
|
||||
}) {
|
||||
return (
|
||||
<Command>
|
||||
<div
|
||||
ref={props.menuRef}
|
||||
className="overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
|
||||
>
|
||||
<Command
|
||||
mode="none"
|
||||
onItemHighlighted={(highlightedValue) => {
|
||||
props.onHighlightedItemChange(typeof highlightedValue === "string" ? highlightedValue : null);
|
||||
}}
|
||||
>
|
||||
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
|
||||
<div className="pointer-events-none absolute h-0 w-0 overflow-hidden opacity-0">
|
||||
<CommandInput autoFocus={false} ref={props.commandInputRef} />
|
||||
</div>
|
||||
<CommandList className="max-h-64">
|
||||
{props.items.map((item, index) => (
|
||||
{props.items.map((item) => (
|
||||
<ComposerCommandMenuItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
index={index}
|
||||
isHighlighted={index === props.selectedIndex}
|
||||
keyboardHighlight={props.keyboardHighlight}
|
||||
resolvedTheme={props.resolvedTheme}
|
||||
onHighlight={props.onHighlight}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
))}
|
||||
@@ -320,6 +310,7 @@ export default function ChatView() {
|
||||
gitCreateWorktreeMutationOptions({ api, queryClient }),
|
||||
);
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const promptRef = useRef(prompt);
|
||||
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
@@ -333,15 +324,12 @@ export default function ChatView() {
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
const [composerCursor, setComposerCursor] = useState(0);
|
||||
const [debouncedPathQuery, setDebouncedPathQuery] = useState("");
|
||||
const [composerMenuIndex, setComposerMenuIndex] = useState(0);
|
||||
const [composerKeyboardHighlight, setComposerKeyboardHighlight] = useState(false);
|
||||
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
|
||||
const messagesScrollRef = useRef<HTMLDivElement>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const shouldAutoScrollRef = useRef(true);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const composerMenuRef = useRef<HTMLDivElement>(null);
|
||||
const previousComposerMenuIndexRef = useRef(0);
|
||||
const composerCommandInputRef = useRef<HTMLInputElement>(null);
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const dragDepthRef = useRef(0);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
@@ -455,43 +443,26 @@ export default function ChatView() {
|
||||
const composerTriggerKind = composerTrigger?.kind ?? null;
|
||||
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
|
||||
const isPathTrigger = composerTriggerKind === "path";
|
||||
const [debouncedPathQuery, composerPathQueryDebouncer] = useDebouncedValue(
|
||||
pathTriggerQuery,
|
||||
{ wait: COMPOSER_PATH_QUERY_DEBOUNCE_MS },
|
||||
(debouncerState) => ({ isPending: debouncerState.isPending }),
|
||||
);
|
||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd));
|
||||
const keybindingsQuery = useQuery({
|
||||
...serverConfigQueryOptions(api),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (!isPathTrigger) {
|
||||
setDebouncedPathQuery("");
|
||||
return;
|
||||
}
|
||||
if (pathTriggerQuery.length === 0) {
|
||||
setDebouncedPathQuery("");
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
setDebouncedPathQuery(pathTriggerQuery);
|
||||
}, COMPOSER_PATH_QUERY_DEBOUNCE_MS);
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [isPathTrigger, pathTriggerQuery]);
|
||||
const workspaceEntriesQuery = useQuery({
|
||||
queryKey: ["composer-workspace-entries", gitCwd, debouncedPathQuery],
|
||||
enabled: Boolean(api && gitCwd && isPathTrigger),
|
||||
staleTime: 15_000,
|
||||
placeholderData: (previous) => previous,
|
||||
queryFn: async () => {
|
||||
if (!api || !gitCwd || !isPathTrigger) {
|
||||
return { entries: [], truncated: false };
|
||||
}
|
||||
return api.projects.searchEntries({
|
||||
cwd: gitCwd,
|
||||
query: debouncedPathQuery,
|
||||
limit: 80,
|
||||
});
|
||||
},
|
||||
});
|
||||
const workspaceEntriesQuery = useQuery(
|
||||
projectSearchEntriesQueryOptions({
|
||||
api,
|
||||
cwd: gitCwd,
|
||||
query: effectivePathQuery,
|
||||
enabled: isPathTrigger,
|
||||
limit: 80,
|
||||
}),
|
||||
);
|
||||
const workspaceEntries = workspaceEntriesQuery.data?.entries ?? EMPTY_PROJECT_ENTRIES;
|
||||
const composerMenuItems = useMemo<ComposerCommandItem[]>(() => {
|
||||
if (!composerTrigger) return [];
|
||||
@@ -533,9 +504,13 @@ export default function ChatView() {
|
||||
}));
|
||||
}, [composerTrigger, workspaceEntries]);
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem =
|
||||
composerMenuItems[Math.min(composerMenuIndex, Math.max(0, composerMenuItems.length - 1))] ??
|
||||
null;
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
composerMenuItems.find((item) => item.id === composerHighlightedItemId) ??
|
||||
composerMenuItems[0] ??
|
||||
null,
|
||||
[composerHighlightedItemId, composerMenuItems],
|
||||
);
|
||||
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = branchesQuery.data?.isRepo ?? true;
|
||||
@@ -551,12 +526,24 @@ export default function ChatView() {
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.close"),
|
||||
[keybindings],
|
||||
);
|
||||
const terminalHotkeys = useMemo(
|
||||
() =>
|
||||
shortcutsForCommands(keybindings, [
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.close",
|
||||
"terminal.new",
|
||||
]),
|
||||
[keybindings],
|
||||
);
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
const hasReachedTerminalLimit =
|
||||
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
@@ -585,23 +572,23 @@ export default function ChatView() {
|
||||
});
|
||||
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
|
||||
const splitTerminal = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
if (!activeThreadId || hasReachedTerminalLimit) return;
|
||||
dispatch({
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId: `terminal-${crypto.randomUUID()}`,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
}, [activeThreadId, dispatch]);
|
||||
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
|
||||
const createNewTerminal = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
if (!activeThreadId || hasReachedTerminalLimit) return;
|
||||
dispatch({
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId: `terminal-${crypto.randomUUID()}`,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
}, [activeThreadId, dispatch]);
|
||||
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
|
||||
const activateTerminal = useCallback(
|
||||
(terminalId: string) => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -700,36 +687,14 @@ export default function ChatView() {
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
setComposerMenuIndex(0);
|
||||
}, [composerTrigger?.kind, composerTrigger?.query, composerMenuItems.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!composerMenuOpen) return;
|
||||
setComposerKeyboardHighlight(false);
|
||||
setComposerMenuIndex(0);
|
||||
}, [composerMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!composerMenuOpen || composerMenuItems.length === 0) {
|
||||
if (!composerMenuOpen) {
|
||||
setComposerHighlightedItemId(null);
|
||||
return;
|
||||
}
|
||||
const clampedIndex = Math.min(composerMenuIndex, composerMenuItems.length - 1);
|
||||
const previousIndex = previousComposerMenuIndexRef.current;
|
||||
const direction = clampedIndex - previousIndex;
|
||||
previousComposerMenuIndexRef.current = clampedIndex;
|
||||
|
||||
const aheadIndex =
|
||||
direction > 0
|
||||
? Math.min(clampedIndex + 1, composerMenuItems.length - 1)
|
||||
: direction < 0
|
||||
? Math.max(clampedIndex - 1, 0)
|
||||
: clampedIndex;
|
||||
|
||||
const node = composerMenuRef.current?.querySelector<HTMLElement>(
|
||||
`[data-composer-menu-index="${aheadIndex}"]`,
|
||||
setComposerHighlightedItemId((existing) =>
|
||||
existing && composerMenuItems.some((item) => item.id === existing) ? existing : null,
|
||||
);
|
||||
node?.scrollIntoView({ block: "nearest" });
|
||||
}, [composerMenuIndex, composerMenuItems.length, composerMenuOpen]);
|
||||
}, [composerMenuItems, composerMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || activeThread.terminalOpen) return;
|
||||
@@ -751,7 +716,7 @@ export default function ChatView() {
|
||||
return [];
|
||||
});
|
||||
setComposerCursor(0);
|
||||
setComposerMenuIndex(0);
|
||||
setComposerHighlightedItemId(null);
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
setExpandedImage(null);
|
||||
@@ -763,22 +728,19 @@ export default function ChatView() {
|
||||
};
|
||||
}, [revokePreviewUrls]);
|
||||
|
||||
/**
|
||||
* Close expanded image on Escape key
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!expandedImage) {
|
||||
return;
|
||||
}
|
||||
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return;
|
||||
useHotkey(
|
||||
"Escape",
|
||||
() => {
|
||||
setExpandedImage(null);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [expandedImage]);
|
||||
},
|
||||
{
|
||||
enabled: expandedImage !== null,
|
||||
ignoreInputs: false,
|
||||
preventDefault: false,
|
||||
stopPropagation: false,
|
||||
target: typeof window === "undefined" ? null : window,
|
||||
},
|
||||
);
|
||||
|
||||
const activeWorktreePath = activeThread?.worktreePath;
|
||||
|
||||
@@ -833,56 +795,74 @@ export default function ChatView() {
|
||||
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
|
||||
};
|
||||
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (!activeThreadId || event.defaultPrevented) return;
|
||||
const shortcutContext = {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: Boolean(activeThread?.terminalOpen),
|
||||
};
|
||||
const manager = getHotkeyManager();
|
||||
const handles = terminalHotkeys.map((hotkey) =>
|
||||
manager.register(
|
||||
hotkey,
|
||||
(event) => {
|
||||
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 (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 (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 (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!activeThread?.terminalOpen) return;
|
||||
closeTerminal(activeThread.activeTerminalId);
|
||||
return;
|
||||
}
|
||||
if (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!activeThread?.terminalOpen) return;
|
||||
closeTerminal(activeThread.activeTerminalId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!activeThread?.terminalOpen) {
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: activeThreadId,
|
||||
open: true,
|
||||
});
|
||||
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!activeThread?.terminalOpen) {
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: activeThreadId,
|
||||
open: true,
|
||||
});
|
||||
}
|
||||
createNewTerminal();
|
||||
},
|
||||
{
|
||||
enabled: Boolean(activeThreadId),
|
||||
conflictBehavior: "allow",
|
||||
ignoreInputs: false,
|
||||
preventDefault: false,
|
||||
stopPropagation: false,
|
||||
target: window,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return () => {
|
||||
for (const handle of handles) {
|
||||
handle.unregister();
|
||||
}
|
||||
createNewTerminal();
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [
|
||||
activeThread?.terminalOpen,
|
||||
activeThread?.activeTerminalId,
|
||||
@@ -892,6 +872,7 @@ export default function ChatView() {
|
||||
dispatch,
|
||||
splitTerminal,
|
||||
keybindings,
|
||||
terminalHotkeys,
|
||||
toggleTerminalVisibility,
|
||||
]);
|
||||
|
||||
@@ -1136,10 +1117,11 @@ export default function ChatView() {
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
promptRef.current = "";
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
setComposerCursor(0);
|
||||
setComposerMenuIndex(0);
|
||||
setComposerHighlightedItemId(null);
|
||||
|
||||
const sessionInfo = await ensureSession(sessionCwd);
|
||||
if (!sessionInfo) return;
|
||||
@@ -1248,16 +1230,15 @@ export default function ChatView() {
|
||||
|
||||
const applyPromptReplacement = useCallback(
|
||||
(rangeStart: number, rangeEnd: number, replacement: string) => {
|
||||
setPrompt((existing) => {
|
||||
const next = replaceTextRange(existing, rangeStart, rangeEnd, replacement);
|
||||
window.requestAnimationFrame(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
textarea.focus();
|
||||
textarea.setSelectionRange(next.cursor, next.cursor);
|
||||
setComposerCursor(next.cursor);
|
||||
});
|
||||
return next.text;
|
||||
const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement);
|
||||
promptRef.current = next.text;
|
||||
setPrompt(next.text);
|
||||
window.requestAnimationFrame(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
textarea.focus();
|
||||
textarea.setSelectionRange(next.cursor, next.cursor);
|
||||
setComposerCursor(next.cursor);
|
||||
});
|
||||
},
|
||||
[],
|
||||
@@ -1283,15 +1264,24 @@ export default function ChatView() {
|
||||
},
|
||||
[applyPromptReplacement, composerTrigger, onModelSelect],
|
||||
);
|
||||
const onHighlightComposerMenuItem = useCallback((index: number) => {
|
||||
setComposerKeyboardHighlight(false);
|
||||
setComposerMenuIndex(index);
|
||||
const onComposerMenuItemHighlighted = useCallback((itemId: string | null) => {
|
||||
setComposerHighlightedItemId(itemId);
|
||||
}, []);
|
||||
const nudgeComposerMenuHighlight = useCallback((key: "ArrowDown" | "ArrowUp") => {
|
||||
const commandInput = composerCommandInputRef.current;
|
||||
if (!commandInput) return;
|
||||
commandInput.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }),
|
||||
);
|
||||
}, []);
|
||||
const isComposerMenuLoading =
|
||||
composerTriggerKind === "path" &&
|
||||
(workspaceEntriesQuery.isLoading || workspaceEntriesQuery.isFetching);
|
||||
((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) ||
|
||||
workspaceEntriesQuery.isLoading ||
|
||||
workspaceEntriesQuery.isFetching);
|
||||
|
||||
const onPromptChange = useCallback((nextPrompt: string, nextCursor: number) => {
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
setComposerCursor(nextCursor);
|
||||
}, []);
|
||||
@@ -1300,14 +1290,12 @@ export default function ChatView() {
|
||||
if (composerMenuOpen && composerMenuItems.length > 0) {
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setComposerKeyboardHighlight(true);
|
||||
setComposerMenuIndex((existing) => Math.min(existing + 1, composerMenuItems.length - 1));
|
||||
nudgeComposerMenuHighlight("ArrowDown");
|
||||
return;
|
||||
}
|
||||
if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setComposerKeyboardHighlight(true);
|
||||
setComposerMenuIndex((existing) => Math.max(existing - 1, 0));
|
||||
nudgeComposerMenuHighlight("ArrowUp");
|
||||
return;
|
||||
}
|
||||
if (e.key === "Tab" || e.key === "Enter") {
|
||||
@@ -1341,7 +1329,7 @@ export default function ChatView() {
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-background text-muted-foreground/40">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
|
||||
{isElectron && (
|
||||
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
@@ -1357,7 +1345,7 @@ export default function ChatView() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-background">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
@@ -1420,14 +1408,12 @@ export default function ChatView() {
|
||||
<div className="absolute inset-x-0 bottom-full z-20 mb-2 px-1">
|
||||
<ComposerCommandMenu
|
||||
items={composerMenuItems}
|
||||
selectedIndex={composerMenuIndex}
|
||||
keyboardHighlight={composerKeyboardHighlight}
|
||||
resolvedTheme={resolvedTheme}
|
||||
isLoading={isComposerMenuLoading}
|
||||
triggerKind={composerTriggerKind}
|
||||
onHighlight={onHighlightComposerMenuItem}
|
||||
onHighlightedItemChange={onComposerMenuItemHighlighted}
|
||||
onSelect={onSelectComposerItem}
|
||||
menuRef={composerMenuRef}
|
||||
commandInputRef={composerCommandInputRef}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -1712,11 +1698,13 @@ const ChatHeader = memo(function ChatHeader({
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="text-sm font-medium text-foreground">{activeThreadTitle}</h2>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<h2 className="truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="shrink-0 flex items-center gap-3">
|
||||
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
|
||||
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
|
||||
<Button
|
||||
@@ -2135,19 +2123,39 @@ const OpenInPicker = memo(function OpenInPicker({
|
||||
() => shortcutLabelForCommand(keybindings, "editor.openFavorite"),
|
||||
[keybindings],
|
||||
);
|
||||
const openFavoriteHotkeys = useMemo(
|
||||
() => shortcutsForCommands(keybindings, ["editor.openFavorite"]),
|
||||
[keybindings],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: globalThis.KeyboardEvent) => {
|
||||
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
|
||||
if (!api || !activeProject) return;
|
||||
const manager = getHotkeyManager();
|
||||
const handles = openFavoriteHotkeys.map((hotkey) =>
|
||||
manager.register(
|
||||
hotkey,
|
||||
(event) => {
|
||||
if (!isOpenFavoriteEditorShortcut(event, keybindings)) return;
|
||||
if (!api || !activeProject) return;
|
||||
|
||||
e.preventDefault();
|
||||
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
|
||||
void api.shell.openInEditor(cwd, lastEditor);
|
||||
event.preventDefault();
|
||||
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
|
||||
void api.shell.openInEditor(cwd, lastEditor);
|
||||
},
|
||||
{
|
||||
conflictBehavior: "allow",
|
||||
ignoreInputs: false,
|
||||
preventDefault: false,
|
||||
stopPropagation: false,
|
||||
target: window,
|
||||
},
|
||||
),
|
||||
);
|
||||
return () => {
|
||||
for (const handle of handles) {
|
||||
handle.unregister();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [api, activeProject, activeThread, keybindings, lastEditor]);
|
||||
}, [activeProject, activeThread, api, keybindings, lastEditor, openFavoriteHotkeys]);
|
||||
|
||||
return (
|
||||
<Group aria-label="Subscription actions">
|
||||
|
||||
@@ -226,17 +226,14 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
});
|
||||
return;
|
||||
}
|
||||
const promise = api.shell.openExternal(prUrl);
|
||||
toastManager.promise(promise, {
|
||||
loading: { title: "Opening PR...", data: threadToastData },
|
||||
success: { title: "PR opened", data: threadToastData },
|
||||
error: (err) => ({
|
||||
void api.shell.openExternal(prUrl).catch((err) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
}),
|
||||
});
|
||||
});
|
||||
void promise.catch(() => undefined);
|
||||
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
@@ -630,7 +627,8 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
: gitStatusForActions.aheadCount === 0 &&
|
||||
gitStatusForActions.behindCount === 0
|
||||
? "Up to date"
|
||||
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
|
||||
: gitStatusForActions.aheadCount > 0 &&
|
||||
gitStatusForActions.behindCount > 0
|
||||
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
||||
: gitStatusForActions.aheadCount > 0
|
||||
? `Ahead by ${gitStatusForActions.aheadCount}`
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { getHotkeyManager } from "@tanstack/react-hotkeys";
|
||||
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 { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutsForCommands } from "../keybindings";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -385,32 +386,50 @@ export default function Sidebar() {
|
||||
[api, dispatch, state.projects, state.threads],
|
||||
);
|
||||
|
||||
const chatHotkeys = useMemo(
|
||||
() => shortcutsForCommands(keybindings, ["chat.new", "chat.newLocal"]),
|
||||
[keybindings],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId);
|
||||
return;
|
||||
}
|
||||
const manager = getHotkeyManager();
|
||||
const handles = chatHotkeys.map((hotkey) =>
|
||||
manager.register(
|
||||
hotkey,
|
||||
(event) => {
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
});
|
||||
},
|
||||
{
|
||||
conflictBehavior: "allow",
|
||||
ignoreInputs: false,
|
||||
preventDefault: false,
|
||||
stopPropagation: false,
|
||||
target: window,
|
||||
},
|
||||
),
|
||||
);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
for (const handle of handles) {
|
||||
handle.unregister();
|
||||
}
|
||||
};
|
||||
}, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
|
||||
}, [chatHotkeys, 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">
|
||||
|
||||
@@ -22,6 +22,7 @@ import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keyb
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
|
||||
@@ -581,6 +582,7 @@ export default function ThreadTerminalDrawer({
|
||||
const showGroupHeaders =
|
||||
resolvedTerminalGroups.length > 1 ||
|
||||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
||||
const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
||||
const terminalLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -588,9 +590,23 @@ export default function ThreadTerminalDrawer({
|
||||
),
|
||||
[normalizedTerminalIds],
|
||||
);
|
||||
const splitTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal");
|
||||
const newTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal");
|
||||
const closeTerminalActionLabel = closeShortcutLabel
|
||||
? `Close Terminal (${closeShortcutLabel})`
|
||||
: "Close Terminal";
|
||||
const onSplitTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onSplitTerminal();
|
||||
}, [hasReachedTerminalLimit, onSplitTerminal]);
|
||||
const onNewTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onNewTerminal();
|
||||
}, [hasReachedTerminalLimit, onNewTerminal]);
|
||||
|
||||
useEffect(() => {
|
||||
onHeightChangeRef.current = onHeightChange;
|
||||
@@ -685,7 +701,7 @@ export default function ThreadTerminalDrawer({
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
@@ -700,19 +716,25 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onSplitTerminal}
|
||||
label={
|
||||
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
|
||||
}
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminal}
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -733,9 +755,9 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="min-w-0 flex-1">
|
||||
{isSplitView ? (
|
||||
<div
|
||||
className="grid h-full w-full gap-0 overflow-x-auto"
|
||||
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{visibleTerminalIds.map((terminalId) => (
|
||||
@@ -787,20 +809,24 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
|
||||
<div className="inline-flex h-full items-stretch">
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onSplitTerminal}
|
||||
label={
|
||||
splitShortcutLabel
|
||||
? `Split Terminal (${splitShortcutLabel})`
|
||||
: "Split Terminal"
|
||||
}
|
||||
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onNewTerminal}
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildPromptInput,
|
||||
buildUserVisiblePrompt,
|
||||
detectComposerTrigger,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
@@ -54,19 +49,3 @@ describe("replaceTextRange", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("tagged path prompt helpers", () => {
|
||||
it("builds model input with tagged paths", () => {
|
||||
const result = buildPromptInput("Fix this", ["src/app.tsx", "src/app.tsx", "README.md"]);
|
||||
expect(result).toContain("Fix this");
|
||||
expect(result).toContain("Referenced paths:");
|
||||
expect(result).toContain("- src/app.tsx");
|
||||
expect(result).toContain("- README.md");
|
||||
expect(result).not.toContain("- src/app.tsx\n- src/app.tsx");
|
||||
});
|
||||
|
||||
it("builds user-visible prompt from tags only", () => {
|
||||
const result = buildUserVisiblePrompt(" ", ["src/app.tsx", "README.md"]);
|
||||
expect(result).toBe("@src/app.tsx @README.md");
|
||||
});
|
||||
});
|
||||
@@ -24,16 +24,6 @@ function tokenStartForCursor(text: string, cursor: number): number {
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
function dedupePaths(paths: string[]): string[] {
|
||||
const unique = new Set<string>();
|
||||
for (const rawPath of paths) {
|
||||
const normalized = rawPath.trim();
|
||||
if (!normalized) continue;
|
||||
unique.add(normalized);
|
||||
}
|
||||
return [...unique];
|
||||
}
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
@@ -98,31 +88,3 @@ export function replaceTextRange(
|
||||
const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
|
||||
return { text: nextText, cursor: safeStart + replacement.length };
|
||||
}
|
||||
|
||||
export function buildPromptInput(text: string, taggedPaths: string[]): string {
|
||||
const trimmedPrompt = text.trim();
|
||||
const normalizedPaths = dedupePaths(taggedPaths);
|
||||
if (normalizedPaths.length === 0) {
|
||||
return trimmedPrompt;
|
||||
}
|
||||
|
||||
const tagBlock = `Referenced paths:\n${normalizedPaths.map((entry) => `- ${entry}`).join("\n")}`;
|
||||
if (!trimmedPrompt) {
|
||||
return tagBlock;
|
||||
}
|
||||
return `${trimmedPrompt}\n\n${tagBlock}`;
|
||||
}
|
||||
|
||||
export function buildUserVisiblePrompt(text: string, taggedPaths: string[]): string {
|
||||
const trimmedPrompt = text.trim();
|
||||
const normalizedPaths = dedupePaths(taggedPaths);
|
||||
if (normalizedPaths.length === 0) {
|
||||
return trimmedPrompt;
|
||||
}
|
||||
|
||||
const tagsSummary = normalizedPaths.map((entry) => `@${entry}`).join(" ");
|
||||
if (!trimmedPrompt) {
|
||||
return tagsSummary;
|
||||
}
|
||||
return `${trimmedPrompt}\n\n${tagsSummary}`;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { getHotkeyManager } from "@tanstack/react-hotkeys";
|
||||
|
||||
/**
|
||||
* Imperative DOM-based context menu for non-Electron environments.
|
||||
* Shows a positioned dropdown and returns a promise that resolves
|
||||
@@ -10,6 +12,7 @@ export function showContextMenuFallback<T extends string>(
|
||||
return new Promise<T | null>((resolve) => {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
|
||||
let cleanedUp = false;
|
||||
|
||||
const menu = document.createElement("div");
|
||||
menu.className =
|
||||
@@ -19,23 +22,31 @@ export function showContextMenuFallback<T extends string>(
|
||||
const y = position?.y ?? 0;
|
||||
menu.style.top = `${y}px`;
|
||||
menu.style.left = `${x}px`;
|
||||
const escapeHandle = getHotkeyManager().register(
|
||||
"Escape",
|
||||
(event) => {
|
||||
event.preventDefault();
|
||||
cleanup(null);
|
||||
},
|
||||
{
|
||||
conflictBehavior: "allow",
|
||||
ignoreInputs: false,
|
||||
preventDefault: false,
|
||||
stopPropagation: false,
|
||||
target: document,
|
||||
},
|
||||
);
|
||||
|
||||
function cleanup(result: T | null) {
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
if (cleanedUp) return;
|
||||
cleanedUp = true;
|
||||
escapeHandle.unregister();
|
||||
overlay.remove();
|
||||
menu.remove();
|
||||
resolve(result);
|
||||
}
|
||||
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
cleanup(null);
|
||||
}
|
||||
}
|
||||
|
||||
overlay.addEventListener("mousedown", () => cleanup(null));
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
|
||||
for (const item of items) {
|
||||
const btn = document.createElement("button");
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
shortcutToRawHotkey,
|
||||
shortcutsForCommands,
|
||||
shortcutLabelForCommand,
|
||||
terminalNavigationShortcutData,
|
||||
type ShortcutEventLike,
|
||||
@@ -98,7 +100,9 @@ const DEFAULT_BINDINGS = compile([
|
||||
describe("isTerminalToggleShortcut", () => {
|
||||
it("matches Cmd+J on macOS", () => {
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel" }),
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -219,7 +223,10 @@ describe("shortcutLabelForCommand", () => {
|
||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(shortcutLabelForCommand(bindings, "terminal.split", "Linux"), "Ctrl+Shift+\\");
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(bindings, "terminal.split", "Linux"),
|
||||
"Ctrl+Shift+\\",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns labels for non-terminal commands", () => {
|
||||
@@ -247,22 +254,14 @@ describe("chat/editor shortcuts", () => {
|
||||
|
||||
it("matches chat.newLocal shortcut", () => {
|
||||
assert.isTrue(
|
||||
isChatNewLocalShortcut(
|
||||
event({ key: "n", metaKey: true, shiftKey: true }),
|
||||
DEFAULT_BINDINGS,
|
||||
{
|
||||
platform: "MacIntel",
|
||||
},
|
||||
),
|
||||
isChatNewLocalShortcut(event({ key: "n", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewLocalShortcut(
|
||||
event({ key: "n", ctrlKey: true, shiftKey: true }),
|
||||
DEFAULT_BINDINGS,
|
||||
{
|
||||
platform: "Linux",
|
||||
},
|
||||
),
|
||||
isChatNewLocalShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -344,11 +343,17 @@ describe("cross-command precedence", () => {
|
||||
|
||||
describe("formatShortcutLabel", () => {
|
||||
it("formats labels for macOS", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"), "⇧⌘D");
|
||||
assert.strictEqual(
|
||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"),
|
||||
"⇧⌘D",
|
||||
);
|
||||
});
|
||||
|
||||
it("formats labels for non-macOS", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"), "Ctrl+Shift+D");
|
||||
assert.strictEqual(
|
||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"),
|
||||
"Ctrl+Shift+D",
|
||||
);
|
||||
});
|
||||
|
||||
it("formats labels for plus key", () => {
|
||||
@@ -357,6 +362,36 @@ describe("formatShortcutLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortcutToRawHotkey", () => {
|
||||
it("normalizes special key aliases and preserves modifiers", () => {
|
||||
assert.deepStrictEqual(shortcutToRawHotkey(modShortcut("esc", { shiftKey: true })), {
|
||||
key: "Escape",
|
||||
mod: true,
|
||||
shift: true,
|
||||
});
|
||||
assert.deepStrictEqual(shortcutToRawHotkey(modShortcut("arrowleft")), {
|
||||
key: "ArrowLeft",
|
||||
mod: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortcutsForCommands", () => {
|
||||
it("returns filtered deduplicated hotkeys in config order", () => {
|
||||
const keybindings = compile([
|
||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
||||
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
||||
]);
|
||||
|
||||
assert.deepStrictEqual(shortcutsForCommands(keybindings, ["chat.new", "chat.newLocal"]), [
|
||||
{ key: "N", mod: true },
|
||||
{ key: "N", mod: true, shift: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalClearShortcut", () => {
|
||||
it("matches Ctrl+L on all platforms", () => {
|
||||
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"));
|
||||
@@ -368,7 +403,9 @@ describe("isTerminalClearShortcut", () => {
|
||||
});
|
||||
|
||||
it("ignores non-keydown events", () => {
|
||||
assert.isFalse(isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"));
|
||||
assert.isFalse(
|
||||
isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -413,7 +450,9 @@ describe("terminalNavigationShortcutData", () => {
|
||||
"MacIntel",
|
||||
),
|
||||
);
|
||||
assert.isNull(terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"));
|
||||
assert.isNull(
|
||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"),
|
||||
);
|
||||
assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel"));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
type RawHotkey,
|
||||
normalizeKeyName,
|
||||
} from "@tanstack/react-hotkeys";
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type KeybindingShortcut,
|
||||
@@ -26,6 +30,17 @@ interface ShortcutMatchOptions {
|
||||
context?: Partial<ShortcutMatchContext>;
|
||||
}
|
||||
|
||||
function shortcutSignature(shortcut: KeybindingShortcut): string {
|
||||
return [
|
||||
shortcut.key,
|
||||
shortcut.metaKey ? "1" : "0",
|
||||
shortcut.ctrlKey ? "1" : "0",
|
||||
shortcut.shiftKey ? "1" : "0",
|
||||
shortcut.altKey ? "1" : "0",
|
||||
shortcut.modKey ? "1" : "0",
|
||||
].join("|");
|
||||
}
|
||||
|
||||
const TERMINAL_WORD_BACKWARD = "\u001bb";
|
||||
const TERMINAL_WORD_FORWARD = "\u001bf";
|
||||
const TERMINAL_LINE_START = "\u0001";
|
||||
@@ -166,6 +181,40 @@ export function shortcutLabelForCommand(
|
||||
return null;
|
||||
}
|
||||
|
||||
export function shortcutToRawHotkey(shortcut: KeybindingShortcut): RawHotkey {
|
||||
return {
|
||||
key: normalizeKeyName(shortcut.key),
|
||||
...(shortcut.modKey ? { mod: true } : {}),
|
||||
...(shortcut.metaKey ? { meta: true } : {}),
|
||||
...(shortcut.ctrlKey ? { ctrl: true } : {}),
|
||||
...(shortcut.shiftKey ? { shift: true } : {}),
|
||||
...(shortcut.altKey ? { alt: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function shortcutsForCommands(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
commands: readonly KeybindingCommand[],
|
||||
): RawHotkey[] {
|
||||
if (commands.length === 0 || keybindings.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const commandSet = new Set(commands);
|
||||
const seen = new Set<string>();
|
||||
const hotkeys: RawHotkey[] = [];
|
||||
|
||||
for (const binding of keybindings) {
|
||||
if (!commandSet.has(binding.command)) continue;
|
||||
const signature = shortcutSignature(binding.shortcut);
|
||||
if (seen.has(signature)) continue;
|
||||
seen.add(signature);
|
||||
hotkeys.push(shortcutToRawHotkey(binding.shortcut));
|
||||
}
|
||||
|
||||
return hotkeys;
|
||||
}
|
||||
|
||||
export function isTerminalToggleShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
|
||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
|
||||
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
export const gitQueryKeys = {
|
||||
all: ["git"] as const,
|
||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
||||
@@ -21,6 +26,10 @@ export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string |
|
||||
return api.git.status({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: "always",
|
||||
refetchOnReconnect: "always",
|
||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,6 +43,10 @@ export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string
|
||||
return api.git.listBranches({ cwd });
|
||||
},
|
||||
enabled: !!api && !!cwd,
|
||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { NativeApi, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
|
||||
export const projectQueryKeys = {
|
||||
all: ["projects"] as const,
|
||||
searchEntries: (cwd: string | null, query: string, limit: number) =>
|
||||
["projects", "search-entries", cwd, query, limit] as const,
|
||||
};
|
||||
|
||||
const DEFAULT_SEARCH_ENTRIES_LIMIT = 80;
|
||||
const DEFAULT_SEARCH_ENTRIES_STALE_TIME = 15_000;
|
||||
const EMPTY_SEARCH_ENTRIES_RESULT: ProjectSearchEntriesResult = {
|
||||
entries: [],
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
export function projectSearchEntriesQueryOptions(input: {
|
||||
api: NativeApi | undefined;
|
||||
cwd: string | null;
|
||||
query: string;
|
||||
enabled?: boolean;
|
||||
limit?: number;
|
||||
staleTime?: number;
|
||||
}) {
|
||||
const limit = input.limit ?? DEFAULT_SEARCH_ENTRIES_LIMIT;
|
||||
return queryOptions({
|
||||
queryKey: projectQueryKeys.searchEntries(input.cwd, input.query, limit),
|
||||
queryFn: async () => {
|
||||
if (!input.api || !input.cwd) {
|
||||
throw new Error("Workspace entry search is unavailable.");
|
||||
}
|
||||
return input.api.projects.searchEntries({
|
||||
cwd: input.cwd,
|
||||
query: input.query,
|
||||
limit,
|
||||
});
|
||||
},
|
||||
enabled: (input.enabled ?? true) && Boolean(input.api && input.cwd),
|
||||
staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME,
|
||||
placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT,
|
||||
});
|
||||
}
|
||||
@@ -12,9 +12,3 @@ export function isMacPlatform(platform: string): boolean {
|
||||
export function isWindowsPlatform(platform: string): boolean {
|
||||
return /^win(dows)?/i.test(platform);
|
||||
}
|
||||
|
||||
export function basenameOfPath(pathValue: string): string {
|
||||
const slashIndex = pathValue.lastIndexOf("/");
|
||||
if (slashIndex === -1) return pathValue;
|
||||
return pathValue.slice(slashIndex + 1);
|
||||
}
|
||||
@@ -2,7 +2,11 @@ import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/con
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
} from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||
@@ -255,6 +259,70 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("caps split terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
});
|
||||
|
||||
it("caps new terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
{ id: "group-term-4", terminalIds: ["term-4"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-4",
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-4");
|
||||
});
|
||||
|
||||
it("closes a terminal and keeps grouped layout coherent", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
|
||||
+22
-2
@@ -16,6 +16,7 @@ import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
@@ -110,7 +111,12 @@ function readPersistedState(): AppState {
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
return { ...hydrated, diffOpen: false };
|
||||
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
|
||||
const activeThreadId = threads.some((thread) => thread.id === hydrated.activeThreadId)
|
||||
? hydrated.activeThreadId
|
||||
: (threads[0]?.id ?? null);
|
||||
|
||||
return { ...hydrated, threads, activeThreadId, diffOpen: false };
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
@@ -139,7 +145,7 @@ function updateThread(
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)];
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
@@ -550,6 +556,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
@@ -616,6 +629,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
|
||||
@@ -5,6 +5,7 @@ export type RuntimeMode = "approval-required" | "full-access";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
|
||||
export const DEFAULT_THREAD_TERMINAL_ID = "default";
|
||||
export const MAX_THREAD_TERMINAL_COUNT = 4;
|
||||
|
||||
export interface ThreadTerminalGroup {
|
||||
id: string;
|
||||
|
||||
@@ -31,11 +31,13 @@ describe("getVscodeIconUrlForEntry", () => {
|
||||
const dockerfileUrl = getVscodeIconUrlForEntry("Dockerfile", "file", "dark");
|
||||
const shellUrl = getVscodeIconUrlForEntry("entrypoint.sh", "file", "dark");
|
||||
const cursorRulesUrl = getVscodeIconUrlForEntry("general.mdc", "file", "dark");
|
||||
const githubWorkflowUrl = getVscodeIconUrlForEntry(".github/workflows/ci.yml", "file", "light");
|
||||
|
||||
assert.isTrue(tsxUrl.endsWith("/file_type_reactts.svg"));
|
||||
assert.isTrue(dockerfileUrl.endsWith("/file_type_docker.svg"));
|
||||
assert.isTrue(shellUrl.endsWith("/file_type_shell.svg"));
|
||||
assert.isTrue(cursorRulesUrl.endsWith("/file_type_markdown.svg"));
|
||||
assert.isTrue(githubWorkflowUrl.endsWith("/file_type_light_yaml.svg"));
|
||||
});
|
||||
|
||||
it("falls back to defaults when there is no match", () => {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { basenameOfPath } from "./lib/utils";
|
||||
import vscodeIconsManifest from "./vscode-icons-manifest.json";
|
||||
import languageAssociationsData from "./vscode-icons-language-associations.json";
|
||||
|
||||
@@ -46,6 +45,11 @@ const languageIdByFileName = toLowercaseLookup(languageAssociations.fileNameToLa
|
||||
const localLanguageIdByExtensionOverrides = {
|
||||
// Cursor rules files (*.mdc) are commonly treated as markdown in VSCode/Cursor.
|
||||
mdc: "markdown",
|
||||
// Upstream languages.ts maps yml/yaml to specialized language ids that can produce
|
||||
// non-generic YAML icons (for example cloudfoundry/esphome). Prefer the base YAML icon
|
||||
// unless a more specific basename/extension match (e.g. azure-pipelines.yml) is found.
|
||||
yml: "yaml",
|
||||
yaml: "yaml",
|
||||
} as const;
|
||||
|
||||
const defaultDarkFileIconDefinition = manifest.file ?? "_file";
|
||||
@@ -62,6 +66,12 @@ function toLowercaseLookup(source: Record<string, string>): Record<string, strin
|
||||
return lookup;
|
||||
}
|
||||
|
||||
export function basenameOfPath(pathValue: string): string {
|
||||
const slashIndex = pathValue.lastIndexOf("/");
|
||||
if (slashIndex === -1) return pathValue;
|
||||
return pathValue.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
function extensionCandidates(fileName: string): string[] {
|
||||
const candidates = new Set<string>();
|
||||
if (fileName.includes(".")) {
|
||||
|
||||
@@ -53,6 +53,8 @@
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-hotkeys": "^0.1.0",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
@@ -425,10 +427,24 @@
|
||||
|
||||
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.1.18", "@tailwindcss/oxide": "4.1.18", "tailwindcss": "4.1.18" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7" } }, "sha512-jVA+/UpKL1vRLg6Hkao5jldawNmRo7mQYrZtNHMIVpLfLhDml5nMRUo/8MwoX2vNXvnaXNNMedrMfMugAVX1nA=="],
|
||||
|
||||
"@tanstack/devtools-event-client": ["@tanstack/[email protected]", "", {}, "sha512-RPfGuk2bDZgcu9bAJodvO2lnZeHuz4/71HjZ0bGb/SPg8+lyTA+RLSKQvo7fSmPSi8/vcH3aKQ8EM9ywf1olaw=="],
|
||||
|
||||
"@tanstack/hotkeys": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "^0.8.0" } }, "sha512-2ypLO3C2vKxMbCjiOfA3RzDaUIUYsQtyLc+Qwl6oKzQvWxReGlQN7DOQZSeKyX9D395d3E65e2v7Fm14BzUGew=="],
|
||||
|
||||
"@tanstack/pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.0", "@tanstack/store": "^0.8.0" } }, "sha512-qhCRSFei0hokQr3xYcQXqxsRD/LKlgHCxHXtKHrQoImp4x2Zu6tUOpUGVH4y2qexIrzSu3aibQBNNfC3Eay6Mg=="],
|
||||
|
||||
"@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg=="],
|
||||
|
||||
"@tanstack/react-hotkeys": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/hotkeys": "0.1.0", "@tanstack/react-store": "^0.8.0" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-Hteo+hdPKdR2G7uAwTmScu1JUHM/f03lVihxVfR/A3XMyVJmbzi4SJieRk/kLgYKeXFRGIUx/xSI3mHeVc6DbQ=="],
|
||||
|
||||
"@tanstack/react-pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/pacer": "0.18.0", "@tanstack/react-store": "^0.8.0" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-coj8ULAuR0qFpjAKD44gTgRuZyjxU6Xu+IX5MwwYvr4e61OtZcJshaExoOBKpCGde0Edb12jDnzzj2Im13Qm9Q=="],
|
||||
|
||||
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
|
||||
|
||||
"@tanstack/react-store": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "0.8.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-XItJt+rG8c5Wn/2L/bnxys85rBpm0BfMbhb4zmPVLXAKY9POrp1xd6IbU4PKoOI+jSEGc3vntPRfLGSgXfE2Ig=="],
|
||||
|
||||
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-PtOisLjUZPz5VyPRSCGjNOlwTvabdTBQ2K80DpVL1chGVr35WRxfeavAPdNq6pm/t7F8GhoR2qtmkkqtCEtHYw=="],
|
||||
|
||||
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
|
||||
|
||||
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -21,14 +21,16 @@ export const keybindingRuleSchema = z.object({
|
||||
|
||||
export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);
|
||||
|
||||
export const keybindingShortcutSchema = z.object({
|
||||
key: z.string().trim().min(1).max(32),
|
||||
metaKey: z.boolean(),
|
||||
ctrlKey: z.boolean(),
|
||||
shiftKey: z.boolean(),
|
||||
altKey: z.boolean(),
|
||||
modKey: z.boolean(),
|
||||
}).strict();
|
||||
export const keybindingShortcutSchema = z
|
||||
.object({
|
||||
key: z.string().trim().min(1).max(32),
|
||||
metaKey: z.boolean(),
|
||||
ctrlKey: z.boolean(),
|
||||
shiftKey: z.boolean(),
|
||||
altKey: z.boolean(),
|
||||
modKey: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type KeybindingWhenNode =
|
||||
| { type: "identifier"; name: string }
|
||||
@@ -59,11 +61,13 @@ export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(()
|
||||
]),
|
||||
);
|
||||
|
||||
export const resolvedKeybindingRuleSchema = z.object({
|
||||
command: keybindingCommandSchema,
|
||||
shortcut: keybindingShortcutSchema,
|
||||
whenAst: keybindingWhenNodeSchema.optional(),
|
||||
}).strict();
|
||||
export const resolvedKeybindingRuleSchema = z
|
||||
.object({
|
||||
command: keybindingCommandSchema,
|
||||
shortcut: keybindingShortcutSchema,
|
||||
whenAst: keybindingWhenNodeSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
|
||||
|
||||
|
||||
Reference in new issue
Block a user