Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7bbcb2054 | ||
|
|
9547718175 |
No files matched your search
+2
-7
@@ -22,10 +22,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+j", "command": "terminal.toggle" },
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new" },
|
||||
{ "key": "mod+o", "command": "editor.openFavorite" }
|
||||
]
|
||||
```
|
||||
@@ -49,9 +46,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.toggle`: open/close terminal drawer
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
|
||||
- `chat.new`: create a new chat thread for the active project
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
### Key Syntax
|
||||
|
||||
@@ -28,10 +28,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new" },
|
||||
{ key: "mod+o", command: "editor.openFavorite" },
|
||||
];
|
||||
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
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,176 +0,0 @@
|
||||
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, vi } from "vitest";
|
||||
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function writeFile(cwd: string, relativePath: string, contents = ""): void {
|
||||
const absolutePath = path.join(cwd, relativePath);
|
||||
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
||||
fs.writeFileSync(absolutePath, contents, "utf8");
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: string[]): void {
|
||||
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
}
|
||||
|
||||
describe("searchWorkspaceEntries", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns files and directories relative to cwd", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-entries-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/index.ts");
|
||||
writeFile(cwd, "README.md");
|
||||
writeFile(cwd, ".git/HEAD");
|
||||
writeFile(cwd, "node_modules/pkg/index.js");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
assert.include(paths, "README.md");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules")));
|
||||
assert.isFalse(result.truncated);
|
||||
});
|
||||
|
||||
it("filters and ranks entries by query", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/components"));
|
||||
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
|
||||
});
|
||||
|
||||
it("excludes gitignored paths for git repositories", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
writeFile(cwd, "ignored.txt", "ignore me");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.notInclude(paths, "ignored.txt");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/")));
|
||||
});
|
||||
|
||||
it("excludes tracked paths that match ignore rules", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-tracked-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
||||
writeFile(cwd, ".gitignore", ".convex/\n");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
assert.include(paths, "src/keep.ts");
|
||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
||||
});
|
||||
|
||||
it("excludes .convex in non-git workspaces", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-non-git-convex-");
|
||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
||||
writeFile(cwd, "src/keep.ts", "export {};");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.include(paths, "src");
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,433 +0,0 @@
|
||||
import fs from "node:fs/promises";
|
||||
import type { Dirent } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
import {
|
||||
projectSearchEntriesInputSchema,
|
||||
type ProjectEntry,
|
||||
type ProjectSearchEntriesInput,
|
||||
type ProjectSearchEntriesResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
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",
|
||||
"node_modules",
|
||||
".next",
|
||||
".turbo",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".cache",
|
||||
]);
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: ProjectEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
||||
|
||||
function toPosixPath(input: string): string {
|
||||
return input.split(path.sep).join("/");
|
||||
}
|
||||
|
||||
function parentPathOf(input: string): string | undefined {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return undefined;
|
||||
}
|
||||
return input.slice(0, separatorIndex);
|
||||
}
|
||||
|
||||
function basenameOf(input: string): string {
|
||||
const separatorIndex = input.lastIndexOf("/");
|
||||
if (separatorIndex === -1) {
|
||||
return input;
|
||||
}
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^[@./]+/, "")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreEntry(entry: ProjectEntry, query: string): number {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
const normalizedName = basenameOf(normalizedPath);
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
return 5;
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
const firstSegment = relativePath.split("/")[0];
|
||||
if (!firstSegment) return false;
|
||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
||||
}
|
||||
|
||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
||||
const parts = input.split("\0");
|
||||
if (parts.length === 0) return [];
|
||||
|
||||
// If output was truncated, the final token can be partial.
|
||||
if (truncated && parts[parts.length - 1]?.length) {
|
||||
parts.pop();
|
||||
}
|
||||
|
||||
return parts.filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
function directoryAncestorsOf(relativePath: string): string[] {
|
||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (segments.length <= 1) return [];
|
||||
const directories: string[] = [];
|
||||
for (let index = 1; index < segments.length; index += 1) {
|
||||
directories.push(segments.slice(0, index).join("/"));
|
||||
}
|
||||
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,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxBufferBytes: 4_096,
|
||||
}).catch(() => null);
|
||||
return Boolean(
|
||||
insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
|
||||
);
|
||||
}
|
||||
|
||||
async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
|
||||
if (relativePaths.length === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (ignoredPaths.size === 0) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
|
||||
if (!(await isInsideGitWorkTree(cwd))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedFiles = await runProcess(
|
||||
"git",
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxBufferBytes: 16 * 1024 * 1024,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
).catch(() => null);
|
||||
if (!listedFiles || listedFiles.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = splitNullSeparatedPaths(
|
||||
listedFiles.stdout,
|
||||
Boolean(listedFiles.stdoutTruncated),
|
||||
)
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
|
||||
|
||||
const directorySet = new Set<string>();
|
||||
for (const filePath of filePaths) {
|
||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
||||
directorySet.add(directoryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries: ProjectEntry[] = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((directoryPath) => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}));
|
||||
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((filePath) => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}));
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
||||
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
|
||||
if (gitIndexed) {
|
||||
return gitIndexed;
|
||||
}
|
||||
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: ProjectEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
const currentDirectories = pendingDirectories;
|
||||
pendingDirectories = [];
|
||||
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 });
|
||||
return { relativeDir, dirents };
|
||||
} catch (error) {
|
||||
if (!relativeDir) {
|
||||
throw new Error(
|
||||
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
return { relativeDir, dirents: null };
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
||||
continue;
|
||||
}
|
||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
||||
continue;
|
||||
}
|
||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const relativePath = toPosixPath(
|
||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
||||
);
|
||||
if (isPathInIgnoredDirectory(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
candidates.push({ dirent, relativePath });
|
||||
}
|
||||
return candidates;
|
||||
});
|
||||
|
||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
||||
candidateEntries.map((entry) => entry.relativePath),
|
||||
);
|
||||
const allowedPathSet = shouldFilterWithGitIgnore
|
||||
? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
|
||||
: null;
|
||||
|
||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
||||
for (const candidate of candidateEntries) {
|
||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry: ProjectEntry = {
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
};
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
pendingDirectories.push(candidate.relativePath);
|
||||
}
|
||||
|
||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (truncated) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scannedAt: Date.now(),
|
||||
entries,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const cached = workspaceIndexCache.get(cwd);
|
||||
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
|
||||
if (inFlight) {
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
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(
|
||||
input: ProjectSearchEntriesInput,
|
||||
): Promise<ProjectSearchEntriesResult> {
|
||||
const parsed = projectSearchEntriesInputSchema.parse(input);
|
||||
const index = await getWorkspaceIndex(parsed.cwd);
|
||||
const normalizedQuery = normalizeQuery(parsed.query);
|
||||
const candidates = normalizedQuery
|
||||
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
|
||||
: index.entries;
|
||||
|
||||
const ranked = candidates.toSorted((left, right) => {
|
||||
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.path.localeCompare(right.path);
|
||||
});
|
||||
|
||||
return {
|
||||
entries: ranked.slice(0, parsed.limit),
|
||||
truncated: index.truncated || ranked.length > parsed.limit,
|
||||
};
|
||||
}
|
||||
@@ -766,38 +766,6 @@ describe("WebSocket Server", () => {
|
||||
expect(afterRemove.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("supports projects.searchEntries", async () => {
|
||||
const workspace = makeTempDir("t3code-ws-workspace-entries-");
|
||||
fs.mkdirSync(path.join(workspace, "src", "components"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, "src", "components", "Composer.tsx"), "export {};", "utf8");
|
||||
fs.writeFileSync(path.join(workspace, "README.md"), "# test", "utf8");
|
||||
fs.mkdirSync(path.join(workspace, ".git"), { recursive: true });
|
||||
fs.writeFileSync(path.join(workspace, ".git", "HEAD"), "ref: refs/heads/main\n", "utf8");
|
||||
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
|
||||
cwd: workspace,
|
||||
query: "comp",
|
||||
limit: 10,
|
||||
});
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
entries: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "src/components", kind: "directory" }),
|
||||
expect.objectContaining({ path: "src/components/Composer.tsx", kind: "file" }),
|
||||
]),
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("supports git methods over websocket", async () => {
|
||||
const repoCwd = makeTempDir("t3code-ws-git-project-");
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
} from "./git";
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -320,9 +319,6 @@ export function createServer(options: ServerOptions) {
|
||||
projectRegistry.remove(request.params as never);
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.projectsSearchEntries:
|
||||
return searchWorkspaceEntries(request.params as never);
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
cwd: string;
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
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", () => {
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: string | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: GitBranch[] | undefined;
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -68,35 +67,36 @@ export default function BranchToolbar({
|
||||
: branchNames;
|
||||
// ── Mutations ─────────────────────────────────────────────────────────
|
||||
|
||||
const checkoutMutation = useMutation(
|
||||
gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
const checkoutMutation = useMutation({
|
||||
...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
|
||||
const createBranchMutation = useMutation(
|
||||
gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
);
|
||||
const createBranchMutation = useMutation({
|
||||
...gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||
onError: (error) =>
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
|
||||
});
|
||||
|
||||
// ── Effects ───────────────────────────────────────────────────────────
|
||||
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
branch: current.name,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
@@ -153,10 +153,6 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||
setIsBranchMenuOpen(true);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -171,9 +167,6 @@ export default function BranchToolbar({
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
onError: (error) => {
|
||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { memo } from "react";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
@@ -14,7 +13,7 @@ const markdownComponents: Components = {
|
||||
},
|
||||
};
|
||||
|
||||
function ChatMarkdown({ text }: ChatMarkdownProps) {
|
||||
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
|
||||
return (
|
||||
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
|
||||
<ReactMarkdown
|
||||
@@ -27,5 +26,3 @@ function ChatMarkdown({ text }: ChatMarkdownProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(ChatMarkdown);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -226,14 +226,17 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
});
|
||||
return;
|
||||
}
|
||||
void api.shell.openExternal(prUrl).catch((err) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
const promise = api.shell.openExternal(prUrl);
|
||||
toastManager.promise(promise, {
|
||||
loading: { title: "Opening PR...", data: threadToastData },
|
||||
success: { title: "PR opened", data: threadToastData },
|
||||
error: (err) => ({
|
||||
title: "Unable to open PR link",
|
||||
description: err instanceof Error ? err.message : "An error occurred.",
|
||||
data: threadToastData,
|
||||
});
|
||||
}),
|
||||
});
|
||||
void promise.catch(() => undefined);
|
||||
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
@@ -309,10 +312,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
title: resultToast.title,
|
||||
description: resultToast.description,
|
||||
timeout: 0,
|
||||
data: {
|
||||
...threadToastData,
|
||||
dismissAfterVisibleMs: 10_000,
|
||||
},
|
||||
data: threadToastData,
|
||||
...(shouldOfferPushCta
|
||||
? {
|
||||
actionProps: {
|
||||
@@ -627,8 +627,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
: gitStatusForActions.aheadCount === 0 &&
|
||||
gitStatusForActions.behindCount === 0
|
||||
? "Up to date"
|
||||
: gitStatusForActions.aheadCount > 0 &&
|
||||
gitStatusForActions.behindCount > 0
|
||||
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
|
||||
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
||||
: gitStatusForActions.aheadCount > 0
|
||||
? `Ahead by ${gitStatusForActions.aheadCount}`
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useTheme } from "../hooks/useTheme";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { isChatNewShortcut } from "../keybindings";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -140,13 +140,7 @@ export default function Sidebar() {
|
||||
}, [state.threads]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
projectId: string,
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
},
|
||||
) => {
|
||||
(projectId: string) => {
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
@@ -172,8 +166,8 @@ export default function Sidebar() {
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
});
|
||||
},
|
||||
@@ -387,23 +381,14 @@ export default function Sidebar() {
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
});
|
||||
handleNewThread(projectId);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
|
||||
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
|
||||
import { type NativeApi } from "@t3tools/contracts";
|
||||
import { Terminal, type ITheme } from "@xterm/xterm";
|
||||
import {
|
||||
@@ -18,11 +18,13 @@ import {
|
||||
preferredTerminalEditor,
|
||||
resolvePathLinkTarget,
|
||||
} from "../terminal-links";
|
||||
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
|
||||
import {
|
||||
isTerminalClearShortcut,
|
||||
terminalNavigationShortcutData,
|
||||
} from "../keybindings";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
|
||||
@@ -159,7 +161,10 @@ function TerminalViewport({
|
||||
try {
|
||||
await api.terminal.write({ threadId, terminalId, data });
|
||||
} catch (error) {
|
||||
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
|
||||
writeSystemMessage(
|
||||
activeTerminal,
|
||||
error instanceof Error ? error.message : fallbackError,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -424,7 +429,6 @@ interface ThreadTerminalDrawerProps {
|
||||
onNewTerminal: () => void;
|
||||
splitShortcutLabel?: string | undefined;
|
||||
newShortcutLabel?: string | undefined;
|
||||
closeShortcutLabel?: string | undefined;
|
||||
onActiveTerminalChange: (terminalId: string) => void;
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
@@ -440,9 +444,15 @@ interface TerminalActionButtonProps {
|
||||
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
|
||||
<PopoverTrigger openOnHover
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className={className}
|
||||
onClick={onClick}
|
||||
aria-label={label}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</PopoverTrigger>
|
||||
@@ -473,7 +483,6 @@ export default function ThreadTerminalDrawer({
|
||||
onNewTerminal,
|
||||
splitShortcutLabel,
|
||||
newShortcutLabel,
|
||||
closeShortcutLabel,
|
||||
onActiveTerminalChange,
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
@@ -582,7 +591,6 @@ 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(
|
||||
@@ -590,23 +598,6 @@ 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;
|
||||
@@ -701,7 +692,7 @@ export default function ThreadTerminalDrawer({
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
@@ -716,25 +707,17 @@ 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 ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onSplitTerminal}
|
||||
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<TerminalActionButton
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminal}
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -742,7 +725,7 @@ export default function ThreadTerminalDrawer({
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
label={closeTerminalActionLabel}
|
||||
label="Close Terminal"
|
||||
>
|
||||
<Trash2 className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -755,9 +738,9 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="min-w-0 flex-1">
|
||||
{isSplitView ? (
|
||||
<div
|
||||
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
|
||||
className="grid h-full w-full gap-0 overflow-x-auto"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{visibleTerminalIds.map((terminalId) => (
|
||||
@@ -809,31 +792,29 @@ 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 ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
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"
|
||||
}
|
||||
>
|
||||
<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 ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
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"
|
||||
}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
label={closeTerminalActionLabel}
|
||||
label="Close Terminal"
|
||||
>
|
||||
<Trash2 className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -871,9 +852,6 @@ export default function ThreadTerminalDrawer({
|
||||
>
|
||||
{terminalGroup.terminalIds.map((terminalId) => {
|
||||
const isActive = terminalId === resolvedActiveTerminalId;
|
||||
const closeTerminalLabel = `Close ${
|
||||
terminalLabelById.get(terminalId) ?? "terminal"
|
||||
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
|
||||
return (
|
||||
<div
|
||||
key={terminalId}
|
||||
@@ -897,30 +875,18 @@ export default function ThreadTerminalDrawer({
|
||||
</span>
|
||||
</button>
|
||||
{normalizedTerminalIds.length > 1 && (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
||||
onClick={() => onCloseTerminal(terminalId)}
|
||||
aria-label={closeTerminalLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon className="size-2.5" />
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
tooltipStyle
|
||||
side="bottom"
|
||||
sideOffset={6}
|
||||
align="center"
|
||||
className="pointer-events-none select-none"
|
||||
>
|
||||
{closeTerminalLabel}
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onCloseTerminal(terminalId);
|
||||
}}
|
||||
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
import { shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
describe("shouldHideCollapsedToastContent", () => {
|
||||
it("keeps a single visible toast readable", () => {
|
||||
assert.equal(shouldHideCollapsedToastContent(0, 1), false);
|
||||
});
|
||||
|
||||
it("keeps the front-most toast readable in a visible stack", () => {
|
||||
assert.equal(shouldHideCollapsedToastContent(0, 3), false);
|
||||
});
|
||||
|
||||
it("hides non-front toasts until the stack is expanded", () => {
|
||||
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
export function shouldHideCollapsedToastContent(
|
||||
visibleToastIndex: number,
|
||||
visibleToastCount: number,
|
||||
): boolean {
|
||||
// Keep the front-most toast readable even if Base UI marks it as "behind"
|
||||
// due to toasts hidden by thread filtering.
|
||||
if (visibleToastCount <= 1) return false;
|
||||
return visibleToastIndex > 0;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Toast } from "@base-ui/react/toast";
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
@@ -13,18 +12,14 @@ import {
|
||||
import { cn } from "~/lib/utils";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { useStore } from "~/store";
|
||||
import { shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
type ThreadToastData = {
|
||||
threadId?: string | null;
|
||||
tooltipStyle?: boolean;
|
||||
dismissAfterVisibleMs?: number;
|
||||
};
|
||||
|
||||
const toastManager = Toast.createToastManager<ThreadToastData>();
|
||||
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
|
||||
type ToastId = ReturnType<typeof toastManager.add>;
|
||||
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
|
||||
|
||||
const TOAST_ICONS = {
|
||||
error: CircleAlertIcon,
|
||||
@@ -55,84 +50,6 @@ function shouldRenderForActiveThread(
|
||||
return toastThreadId === activeThreadId;
|
||||
}
|
||||
|
||||
function ThreadToastVisibleAutoDismiss({
|
||||
toastId,
|
||||
dismissAfterVisibleMs,
|
||||
}: {
|
||||
toastId: ToastId;
|
||||
dismissAfterVisibleMs: number | undefined;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
|
||||
if (typeof window === "undefined" || typeof document === "undefined") return;
|
||||
|
||||
let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
|
||||
let startedAtMs: number | null = null;
|
||||
let timeoutId: number | null = null;
|
||||
let closed = false;
|
||||
|
||||
const clearTimer = () => {
|
||||
if (timeoutId === null) return;
|
||||
window.clearTimeout(timeoutId);
|
||||
timeoutId = null;
|
||||
};
|
||||
|
||||
const closeToast = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
threadToastVisibleTimeoutRemainingMs.delete(toastId);
|
||||
toastManager.close(toastId);
|
||||
};
|
||||
|
||||
const pause = () => {
|
||||
if (startedAtMs === null) return;
|
||||
remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
|
||||
startedAtMs = null;
|
||||
clearTimer();
|
||||
threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
if (closed || startedAtMs !== null) return;
|
||||
if (remainingMs <= 0) {
|
||||
closeToast();
|
||||
return;
|
||||
}
|
||||
startedAtMs = Date.now();
|
||||
clearTimer();
|
||||
timeoutId = window.setTimeout(() => {
|
||||
remainingMs = 0;
|
||||
startedAtMs = null;
|
||||
closeToast();
|
||||
}, remainingMs);
|
||||
};
|
||||
|
||||
const syncTimer = () => {
|
||||
const shouldRun = document.visibilityState === "visible" && document.hasFocus();
|
||||
if (shouldRun) {
|
||||
start();
|
||||
return;
|
||||
}
|
||||
pause();
|
||||
};
|
||||
|
||||
syncTimer();
|
||||
document.addEventListener("visibilitychange", syncTimer);
|
||||
window.addEventListener("focus", syncTimer);
|
||||
window.addEventListener("blur", syncTimer);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", syncTimer);
|
||||
window.removeEventListener("focus", syncTimer);
|
||||
window.removeEventListener("blur", syncTimer);
|
||||
pause();
|
||||
clearTimer();
|
||||
};
|
||||
}, [dismissAfterVisibleMs, toastId]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
|
||||
return (
|
||||
<Toast.Provider toastManager={toastManager} {...props}>
|
||||
@@ -147,18 +64,6 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
const { toasts } = Toast.useToastManager<ThreadToastData>();
|
||||
const activeThreadId = state.activeThreadId;
|
||||
const isTop = position.startsWith("top");
|
||||
const visibleToasts = toasts.filter((toast) =>
|
||||
shouldRenderForActiveThread(toast.data, activeThreadId),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToastIds = new Set(toasts.map((toast) => toast.id));
|
||||
for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
|
||||
if (!activeToastIds.has(toastId)) {
|
||||
threadToastVisibleTimeoutRemainingMs.delete(toastId);
|
||||
}
|
||||
}
|
||||
}, [toasts]);
|
||||
|
||||
return (
|
||||
<Toast.Portal data-slot="toast-portal">
|
||||
@@ -176,107 +81,96 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
data-position={position}
|
||||
data-slot="toast-viewport"
|
||||
>
|
||||
{visibleToasts.map((toast, visibleIndex) => {
|
||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
||||
const hideCollapsedContent = shouldHideCollapsedToastContent(
|
||||
visibleIndex,
|
||||
visibleToasts.length,
|
||||
);
|
||||
{toasts
|
||||
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
|
||||
.map((toast) => {
|
||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
||||
|
||||
return (
|
||||
<Toast.Root
|
||||
className={cn(
|
||||
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
// Base positioning using data-position
|
||||
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
|
||||
"data-[position*=left]:right-auto data-[position*=left]:left-0",
|
||||
"data-[position*=center]:right-0 data-[position*=center]:left-0",
|
||||
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
|
||||
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
|
||||
// Gap fill for hover
|
||||
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
|
||||
"data-[position*=top]:after:top-full",
|
||||
"data-[position*=bottom]:after:bottom-full",
|
||||
// Define some variables
|
||||
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
// Define offset-y variable
|
||||
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
|
||||
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
|
||||
// Default state transform
|
||||
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
// Limited state
|
||||
"data-limited:opacity-0",
|
||||
// Expanded state
|
||||
"data-expanded:h-(--toast-height)",
|
||||
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
|
||||
// Starting and ending animations
|
||||
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
|
||||
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:opacity-0",
|
||||
// Ending animations (direction-aware)
|
||||
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
// Ending animations (expanded)
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
)}
|
||||
data-position={position}
|
||||
key={toast.id}
|
||||
swipeDirection={
|
||||
position.includes("center")
|
||||
? [isTop ? "up" : "down"]
|
||||
: position.includes("left")
|
||||
? ["left", isTop ? "up" : "down"]
|
||||
: ["right", isTop ? "up" : "down"]
|
||||
}
|
||||
toast={toast}
|
||||
>
|
||||
<ThreadToastVisibleAutoDismiss
|
||||
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
|
||||
toastId={toast.id}
|
||||
/>
|
||||
<Toast.Content
|
||||
return (
|
||||
<Toast.Root
|
||||
className={cn(
|
||||
"pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100",
|
||||
hideCollapsedContent &&
|
||||
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
|
||||
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
// Base positioning using data-position
|
||||
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
|
||||
"data-[position*=left]:right-auto data-[position*=left]:left-0",
|
||||
"data-[position*=center]:right-0 data-[position*=center]:left-0",
|
||||
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
|
||||
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
|
||||
// Gap fill for hover
|
||||
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
|
||||
"data-[position*=top]:after:top-full",
|
||||
"data-[position*=bottom]:after:bottom-full",
|
||||
// Define some variables
|
||||
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
|
||||
// Define offset-y variable
|
||||
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
|
||||
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
|
||||
// Default state transform
|
||||
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
|
||||
// Limited state
|
||||
"data-limited:opacity-0",
|
||||
// Expanded state
|
||||
"data-expanded:h-(--toast-height)",
|
||||
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
|
||||
// Starting and ending animations
|
||||
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
|
||||
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-ending-style:opacity-0",
|
||||
// Ending animations (direction-aware)
|
||||
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
|
||||
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
// Ending animations (expanded)
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
|
||||
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
|
||||
)}
|
||||
data-position={position}
|
||||
key={toast.id}
|
||||
swipeDirection={
|
||||
position.includes("center")
|
||||
? [isTop ? "up" : "down"]
|
||||
: position.includes("left")
|
||||
? ["left", isTop ? "up" : "down"]
|
||||
: ["right", isTop ? "up" : "down"]
|
||||
}
|
||||
toast={toast}
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
|
||||
</div>
|
||||
)}
|
||||
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
|
||||
<div className="flex gap-2">
|
||||
{Icon && (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<Toast.Description
|
||||
className="text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
||||
<Toast.Description
|
||||
className="text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{toast.actionProps && (
|
||||
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
|
||||
{toast.actionProps.children}
|
||||
</Toast.Action>
|
||||
)}
|
||||
</Toast.Content>
|
||||
</Toast.Root>
|
||||
);
|
||||
})}
|
||||
{toast.actionProps && (
|
||||
<Toast.Action
|
||||
className={buttonVariants({ size: "xs" })}
|
||||
data-slot="toast-action"
|
||||
>
|
||||
{toast.actionProps.children}
|
||||
</Toast.Action>
|
||||
)}
|
||||
</Toast.Content>
|
||||
</Toast.Root>
|
||||
);
|
||||
})}
|
||||
</Toast.Viewport>
|
||||
</Toast.Portal>
|
||||
);
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
const text = "Please check @src/com";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "path",
|
||||
query: "src/com",
|
||||
rangeStart: "Please check ".length,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects slash command token while typing command name", () => {
|
||||
const text = "/mo";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "slash-command",
|
||||
query: "mo",
|
||||
rangeStart: 0,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects slash model query after /model", () => {
|
||||
const text = "/model spark";
|
||||
const trigger = detectComposerTrigger(text, text.length);
|
||||
|
||||
expect(trigger).toEqual({
|
||||
kind: "slash-model",
|
||||
query: "spark",
|
||||
rangeStart: 0,
|
||||
rangeEnd: text.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("replaceTextRange", () => {
|
||||
it("replaces a text range and returns new cursor", () => {
|
||||
const replaced = replaceTextRange("hello @src", 6, 10, "");
|
||||
expect(replaced).toEqual({
|
||||
text: "hello ",
|
||||
cursor: 6,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
|
||||
export interface ComposerTrigger {
|
||||
kind: ComposerTriggerKind;
|
||||
query: string;
|
||||
rangeStart: number;
|
||||
rangeEnd: number;
|
||||
}
|
||||
|
||||
function clampCursor(text: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return text.length;
|
||||
return Math.max(0, Math.min(text.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function isWhitespace(char: string): boolean {
|
||||
return char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
}
|
||||
|
||||
function tokenStartForCursor(text: string, cursor: number): number {
|
||||
let index = cursor - 1;
|
||||
while (index >= 0 && !isWhitespace(text[index] ?? "")) {
|
||||
index -= 1;
|
||||
}
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
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;
|
||||
const linePrefix = text.slice(lineStart, cursor);
|
||||
|
||||
if (linePrefix.startsWith("/")) {
|
||||
const commandMatch = /^\/(\S*)$/.exec(linePrefix);
|
||||
if (commandMatch) {
|
||||
const commandQuery = commandMatch[1] ?? "";
|
||||
if (commandQuery.toLowerCase() === "model") {
|
||||
return {
|
||||
kind: "slash-model",
|
||||
query: "",
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
if ("model".startsWith(commandQuery.toLowerCase())) {
|
||||
return {
|
||||
kind: "slash-command",
|
||||
query: commandQuery,
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix);
|
||||
if (modelMatch) {
|
||||
return {
|
||||
kind: "slash-model",
|
||||
query: (modelMatch[1] ?? "").trim(),
|
||||
rangeStart: lineStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const tokenStart = tokenStartForCursor(text, cursor);
|
||||
const token = text.slice(tokenStart, cursor);
|
||||
if (!token.startsWith("@")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "path",
|
||||
query: token.slice(1),
|
||||
rangeStart: tokenStart,
|
||||
rangeEnd: cursor,
|
||||
};
|
||||
}
|
||||
|
||||
export function replaceTextRange(
|
||||
text: string,
|
||||
rangeStart: number,
|
||||
rangeEnd: number,
|
||||
replacement: string,
|
||||
): { text: string; cursor: number } {
|
||||
const safeStart = Math.max(0, Math.min(text.length, rangeStart));
|
||||
const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
|
||||
const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
|
||||
return { text: nextText, cursor: safeStart + replacement.length };
|
||||
}
|
||||
@@ -9,10 +9,8 @@ import {
|
||||
import {
|
||||
formatShortcutLabel,
|
||||
isChatNewShortcut,
|
||||
isChatNewLocalShortcut,
|
||||
isOpenFavoriteEditorShortcut,
|
||||
isTerminalClearShortcut,
|
||||
isTerminalCloseShortcut,
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
@@ -85,22 +83,14 @@ const DEFAULT_BINDINGS = compile([
|
||||
command: "terminal.new",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("w"),
|
||||
command: "terminal.close",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
||||
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
||||
]);
|
||||
|
||||
describe("isTerminalToggleShortcut", () => {
|
||||
it("matches Cmd+J on macOS", () => {
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel" }),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -111,8 +101,8 @@ describe("isTerminalToggleShortcut", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("split/new/close terminal shortcuts", () => {
|
||||
it("requires terminalFocus for default split/new/close bindings", () => {
|
||||
describe("split/new terminal shortcuts", () => {
|
||||
it("requires terminalFocus for default split/new bindings", () => {
|
||||
assert.isFalse(
|
||||
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
@@ -125,12 +115,6 @@ describe("split/new/close terminal shortcuts", () => {
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches split/new when terminalFocus is true", () => {
|
||||
@@ -146,12 +130,6 @@ describe("split/new/close terminal shortcuts", () => {
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("supports when expressions", () => {
|
||||
@@ -221,10 +199,7 @@ 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", () => {
|
||||
@@ -250,19 +225,6 @@ describe("chat/editor shortcuts", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("matches chat.newLocal shortcut", () => {
|
||||
assert.isTrue(
|
||||
isChatNewLocalShortcut(event({ key: "n", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewLocalShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches editor.openFavorite shortcut", () => {
|
||||
assert.isTrue(
|
||||
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
@@ -341,17 +303,11 @@ 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", () => {
|
||||
@@ -371,9 +327,7 @@ 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"));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -418,9 +372,7 @@ 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"));
|
||||
});
|
||||
|
||||
|
||||
@@ -190,14 +190,6 @@ export function isTerminalNewShortcut(
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.new", options);
|
||||
}
|
||||
|
||||
export function isTerminalCloseShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
|
||||
}
|
||||
|
||||
export function isChatNewShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
@@ -206,14 +198,6 @@ export function isChatNewShortcut(
|
||||
return matchesCommandShortcut(event, keybindings, "chat.new", options);
|
||||
}
|
||||
|
||||
export function isChatNewLocalShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
|
||||
}
|
||||
|
||||
export function isOpenFavoriteEditorShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -2,11 +2,7 @@ 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,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
} from "./types";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||
@@ -259,70 +255,6 @@ 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({
|
||||
|
||||
+2
-22
@@ -16,7 +16,6 @@ import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
@@ -111,12 +110,7 @@ function readPersistedState(): AppState {
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
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 };
|
||||
return { ...hydrated, diffOpen: false };
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
@@ -145,7 +139,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)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
const unique = [...new Set(ids)];
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
@@ -556,13 +550,6 @@ 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];
|
||||
@@ -629,13 +616,6 @@ 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,7 +5,6 @@ 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;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"version":"12.17.0","source":"https://raw.githubusercontent.com/vscode-icons/vscode-icons/v12.17.0/src/iconsManifest/languages.ts","generatedAt":"2026-02-17T20:03:11.362Z","extensionToLanguageId":{"as":"actionscript","ada":"ada","prw":"advpl","affect":"affectscript","agda":"agda","al":"al","alloy":"alloy","ansible":"ansible","g4":"antlr","any":"anyscript","htaccess":"apacheconf","cls":"apex","apib":"apiblueprint","apl":"apl","applescript":"applescript","adoc":"asciidoc","asp":"asp","asm":"arm","astro":"astro","ats":"ats","ahk":"ahk","au3":"autoit","am":"automake","avcs":"avro","azcli":"azcli","azure-pipelines.yml":"azure-pipelines","bal":"ballerina","bat":"bat","bats":"bats","bzl":"bazel","bf":"befunge","bicep":"bicep","bib":"bibtex","biml":"biml","bin":"code-text-binary","rast":"biome_syntax_tree","blade.php":"blade","blitzbasic":"blitzbasic","bolt":"bolt","bsq":"bosque","bru":"bruno","buf.yaml":"buf","lockb":"bun.lockb","c":"c","c3":"c3","cal":"c-al","cabal":"cabal","capnp":"capnp","casc":"casc","cddl":"cddl","ceylon":"ceylon","cfc":"cfc","cfm":"cfmhtml","circom":"circom","clojure":"clojure","clojurescript":"clojurescript","yml":"manifest-yaml","cmake":"cmake","cbl":"cobol","ql":"ql","coffee":"coffeescript","cfml":"cfml","confluence":"confluence","ckbk":"cookbook","instructions.md":"instructions","cpp":"cpp","cr":"crystal","cs":"csharp","css":"css","wxss":"css","acss":"css","mcss":"css","pcss":"css","postcss":"css","nss":"css","ccss":"css","less":"css","scss":"css","sass":"css","csv":"csv","feature":"cucumber","cu":"cuda","cypher":"cypher","pyx":"cython","dal":"dal","dart":"dart","dhall":"dhall","html":"django-html","diff":"diff","d":"d","hcl":"dockerbake","dtx":"doctex","env":"dotenv","dot":"dotjs","dox":"doxygen","drawio":"drawio","drl":"drools","dtd":"dtd","dust":"dustjs","dylan":"dylan","earthfile":"earthfile","edge":"edge","eex":"eex","es":"es","ex":"elixir","elm":"elm","erb":"erb","erl":"erlang","yaml":"esphome","xlsx":"excel","falcon":"falcon","fql":"fql","f":"fortran","ftl":"ftl","fs":"fsharp","fthtml":"fthtml","gspec":"galen","gml":"gml-gms","gcode":"gcode","gen":"genstat","git":"git-commit","gleam":"gleam","gjs":"glimmer-js","glsl":"glsl","glyphs":"glyphs","gp":"gnuplot","go":"go","mod":"go.mod","work":"go.work","api":"goctl","gd":"gdscript","gradle.kts":"gradle-kotlin-dsl","gr":"grain","gql":"graphql","gv":"dot","grit":"grit","groovy":"groovy","haml":"haml","hbs":"handlebars","prg":"harbour","hs":"haskell","haxe":"haxe","helm.tpl":"helm","hjson":"hjson","hlsl":"hlsl","hosts":"hosts","http":"http","aff":"hunspell.aff","hy":"hy","hypr":"hypr","icl":"icl","imba":"imba","4gl":"4GL","ini":"ini","ink":"ink","iss":"innosetup","io":"io","janet":"janet","java":"java","js":"javascript","mjs":"javascript","cjs":"javascript","es6":"javascript","jake":"javascript","jsm":"javascript","jsx":"javascript","njs":"javascript","pac":"javascript","sjs":"javascript","ssjs":"javascript","xsjs":"javascript","xsjslib":"javascript","jekyll":"jekyll","jenkins":"jenkins","jest-snap":"jest-snapshot","jinja":"jinja","json":"json","jsonc":"jsonc","jsonl":"jsonl","jsonnet":"jsonnet","json5":"json5","jl":"julia","id":"iodine","k":"k","kv":"kivy","ks":"kos","kt":"kotlin","kusto":"kusto","tex":"latex","lark":"lark","lat":"latino","lean":"lean4","flex":"lex","ly":"lilypond","lisp":"lisp","lhs":"literate haskell","log":"log","lol":"lolcode","lsl":"lsl","lua":"lua","m4":"m4","mk":"makefile","md":"markdown","markdown":"markdown","mdown":"markdown","mkd":"markdown","marko":"marko","mat":"matlab","ms":"maxscript","mdx":"mdx","mediawiki":"mediawiki","mel":"mel","mmd":"mermaid","metal":"metal","mcfunction":"bc-mcfunction","mjml":"mjml","pq":"powerquery","mojo":"mojo","ep":"mojolicious","mongo":"mongo","mson":"mson","mv":"mv","mvt":"mvt","ne":"nearley","nginx":"nginx","nim":"nim","nimble":"nimble","nix":"nix","nsi":"nsis","nunjucks":"nunjucks","nu":"nushell","m":"objective-c","mm":"objective-cpp","ml":"ocaml","o3":"ogone","w":"abl","things":"openhab","org":"org","pas":"pascal","pddl":"pddl","plan":"plan","happenings":"happenings","pl":"perl","pl6":"perl6","pgsql":"pgsql","php":"php","php4":"php","php5":"php","php7":"php","phtml":"php","phps":"php","phpt":"php","phar":"php","aw":"php","ctp":"php","inc":"php","php3":"php","php8":"php","module":"php","theme":"php","tpl":"php","pine":"pine","txt":"plaintext","dbgasm":"platformio-debug.disassembly","ddl":"plsql","po":"po","dib":"polyglot-notebook","polymer":"polymer","pony":"pony","ps":"postscript","ps1":"powershell","prisma":"prisma","pde":"pde","pro":"prolog","rules":"prometheus","properties":"java-properties","proto":"proto3","pug":"jade","pp":"puppet","purs":"purescript","arr":"pyret","pyscript":"pyscript","py":"python","pyi":"python","pyw":"python","pyc":"python","pyd":"python","pyo":"python","pxd":"python","pxi":"python","rpy":"python","cpy":"python","ipy":"python","pyowo":"pythowo","qvs":"qlik","qml":"qml","qs":"qsharp","r":"r","rkt":"racket","raku":"raku","cshtml":"razor","raml":"raLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"iconDefinitions":{"_file":{"iconPath":"../../icons/default_file.svg"},"_folder":{"iconPath":"../../icons/default_folder.svg"},"_folder_open":{"iconPath":"../../icons/default_folder_opened.svg"},"_root_folder":{"iconPath":"../../icons/default_root_folder.svg"},"_root_folder_open":{"iconPath":"../../icons/default_root_folder_opened.svg"},"_file_light":{"iconPath":""},"_folder_light":{"iconPath":""},"_folder_light_open":{"iconPath":""},"_root_folder_light":{"iconPath":""},"_root_folder_light_open":{"iconPath":""},"_fd_android":{"iconPath":"../../icons/folder_type_android.svg"},"_fd_android_open":{"iconPath":"../../icons/folder_type_android_opened.svg"},"_fd_angular":{"iconPath":"../../icons/folder_type_angular.svg"},"_fd_angular_open":{"iconPath":"../../icons/folder_type_angular_opened.svg"},"_fd_apache":{"iconPath":"../../icons/folder_type_apache.svg"},"_fd_apache_open":{"iconPath":"../../icons/folder_type_apache_opened.svg"},"_fd_api":{"iconPath":"../../icons/folder_type_api.svg"},"_fd_api_open":{"iconPath":"../../icons/folder_type_api_opened.svg"},"_fd_app":{"iconPath":"../../icons/folder_type_app.svg"},"_fd_app_open":{"iconPath":"../../icons/folder_type_app_opened.svg"},"_fd_arangodb":{"iconPath":"../../icons/folder_type_arangodb.svg"},"_fd_arangodb_open":{"iconPath":"../../icons/folder_type_arangodb_opened.svg"},"_fd_asset":{"iconPath":"../../icons/folder_type_asset.svg"},"_fd_asset_open":{"iconPath":"../../icons/folder_type_asset_opened.svg"},"_fd_astro":{"iconPath":"../../icons/folder_type_astro.svg"},"_fd_astro_open":{"iconPath":"../../icons/folder_type_astro_opened.svg"},"_fd_audio":{"iconPath":"../../icons/folder_type_audio.svg"},"_fd_audio_open":{"iconPath":"../../icons/folder_type_audio_opened.svg"},"_fd_aurelia":{"iconPath":"../../icons/folder_type_aurelia.svg"},"_fd_aurelia_open":{"iconPath":"../../icons/folder_type_aurelia_opened.svg"},"_fd_aws":{"iconPath":"../../icons/folder_type_aws.svg"},"_fd_aws_open":{"iconPath":"../../icons/folder_type_aws_opened.svg"},"_fd_azure":{"iconPath":"../../icons/folder_type_azure.svg"},"_fd_azure_open":{"iconPath":"../../icons/folder_type_azure_opened.svg"},"_fd_azurepipelines":{"iconPath":"../../icons/folder_type_azurepipelines.svg"},"_fd_azurepipelines_open":{"iconPath":"../../icons/folder_type_azurepipelines_opened.svg"},"_fd_binary":{"iconPath":"../../icons/folder_type_binary.svg"},"_fd_binary_open":{"iconPath":"../../icons/folder_type_binary_opened.svg"},"_fd_bloc":{"iconPath":"../../icons/folder_type_bloc.svg"},"_fd_bloc_open":{"iconPath":"../../icons/folder_type_bloc_opened.svg"},"_fd_blueprint":{"iconPath":"../../icons/folder_type_blueprint.svg"},"_fd_blueprint_open":{"iconPath":"../../icons/folder_type_blueprint_opened.svg"},"_fd_bot":{"iconPath":"../../icons/folder_type_bot.svg"},"_fd_bot_open":{"iconPath":"../../icons/folder_type_bot_opened.svg"},"_fd_bower":{"iconPath":"../../icons/folder_type_bower.svg"},"_fd_bower_open":{"iconPath":"../../icons/folder_type_bower_opened.svg"},"_fd_buildkite":{"iconPath":"../../icons/folder_type_buildkite.svg"},"_fd_buildkite_open":{"iconPath":"../../icons/folder_type_buildkite_opened.svg"},"_fd_cake":{"iconPath":"../../icons/folder_type_cake.svg"},"_fd_cake_open":{"iconPath":"../../icons/folder_type_cake_opened.svg"},"_fd_cargo":{"iconPath":"../../icons/folder_type_cargo.svg"},"_fd_cargo_open":{"iconPath":"../../icons/folder_type_cargo_opened.svg"},"_fd_certificate":{"iconPath":"../../icons/folder_type_certificate.svg"},"_fd_certificate_open":{"iconPath":"../../icons/folder_type_certificate_opened.svg"},"_fd_changesets":{"iconPath":"../../icons/folder_type_changesets.svg"},"_fd_changesets_open":{"iconPath":"../../icons/folder_type_changesets_opened.svg"},"_fd_chef":{"iconPath":"../../icons/folder_type_chef.svg"},"_fd_chef_open":{"iconPath":"../../icons/folder_type_chef_opened.svg"},"_fd_circleci":{"iconPath":"../../icons/folder_type_circleci.svg"},"_fd_circleci_open":{"iconPath":"../../icons/folder_type_circleci_opened.svg"},"_fd_claude":{"iconPath":"../../icons/folder_type_claude.svg"},"_fd_claude_open":{"iconPath":"../../icons/folder_type_claude_opened.svg"},"_fd_cli":{"iconPath":"../../icons/folder_type_cli.svg"},"_fd_cli_open":{"iconPath":"../../icons/folder_type_cli_opened.svg"},"_fd_client":{"iconPath":"../../icons/folder_type_client.svg"},"_fd_client_open":{"iconPath":"../../icons/folder_type_client_opened.svg"},"_fd_cloudflare":{"iconPath":"../../icons/folder_type_cloudflare.svg"},"_fd_cloudflare_open":{"iconPath":"../../icons/folder_type_cloudflare_opened.svg"},"_fd_cmake":{"iconPath":"../../icons/folder_type_cmake.svg"},"_fd_cmake_open":{"iconPath":"../../icons/folder_type_cmake_opened.svg"},"_fd_common":{"iconPath":"../../icons/folder_type_common.svg"},"_fd_common_open":{"iconPath":"../../icons/folder_type_common_opened.svg"},"_fd_component":{"iconPath":"../../icons/folder_type_component.svg"},"_fd_component_open":{"iconPath":"../../icons/folder_type_component_opened.svg"},"_fd_composer":{"iconPath":".Line truncated
|
||||
@@ -1,50 +0,0 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import { getVscodeIconUrlForEntry } from "./vscode-icons";
|
||||
|
||||
describe("getVscodeIconUrlForEntry", () => {
|
||||
it("uses exact filename matches from the vscode-icons manifest", () => {
|
||||
const darkUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "dark");
|
||||
const lightUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "light");
|
||||
|
||||
assert.isTrue(darkUrl.endsWith("/file_type_pnpm.svg"));
|
||||
assert.isTrue(lightUrl.endsWith("/file_type_light_pnpm.svg"));
|
||||
});
|
||||
|
||||
it("uses longest extension match for compound extensions", () => {
|
||||
const iconUrl = getVscodeIconUrlForEntry("tsconfig.tsbuildinfo", "file", "dark");
|
||||
const manifestStyleUrl = getVscodeIconUrlForEntry("buf.yaml", "file", "dark");
|
||||
assert.isTrue(iconUrl.endsWith("/file_type_tsbuildinfo.svg"));
|
||||
assert.isTrue(manifestStyleUrl.endsWith("/file_type_buf.svg"));
|
||||
});
|
||||
|
||||
it("uses folder mappings and light-aware filename mappings", () => {
|
||||
const folderUrl = getVscodeIconUrlForEntry("packages/src", "directory", "light");
|
||||
const fileUrl = getVscodeIconUrlForEntry("AGENTS.md", "file", "light");
|
||||
|
||||
assert.isTrue(folderUrl.endsWith("/folder_type_src.svg"));
|
||||
assert.isTrue(fileUrl.endsWith("/file_type_light_agents.svg"));
|
||||
});
|
||||
|
||||
it("falls back to language-based mappings for path-only cases", () => {
|
||||
const tsxUrl = getVscodeIconUrlForEntry("checkbox.tsx", "file", "light");
|
||||
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", () => {
|
||||
const fileUrl = getVscodeIconUrlForEntry("foo.unknown-ext", "file", "dark");
|
||||
const folderUrl = getVscodeIconUrlForEntry("totally-unknown-folder", "directory", "dark");
|
||||
|
||||
assert.isTrue(fileUrl.endsWith("/default_file.svg"));
|
||||
assert.isTrue(folderUrl.endsWith("/default_folder.svg"));
|
||||
});
|
||||
});
|
||||
@@ -1,168 +0,0 @@
|
||||
import vscodeIconsManifest from "./vscode-icons-manifest.json";
|
||||
import languageAssociationsData from "./vscode-icons-language-associations.json";
|
||||
|
||||
const VSCODE_ICONS_VERSION = "v12.17.0";
|
||||
const VSCODE_ICONS_BASE_URL = `https://cdn.jsdelivr.net/gh/vscode-icons/vscode-icons@${VSCODE_ICONS_VERSION}/icons`;
|
||||
|
||||
interface IconDefinition {
|
||||
iconPath: string;
|
||||
}
|
||||
|
||||
interface IconLookupSection {
|
||||
file?: string;
|
||||
folder?: string;
|
||||
fileNames: Record<string, string>;
|
||||
fileExtensions: Record<string, string>;
|
||||
folderNames: Record<string, string>;
|
||||
languageIds?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface VscodeIconsManifest extends IconLookupSection {
|
||||
iconDefinitions: Record<string, IconDefinition>;
|
||||
light: IconLookupSection;
|
||||
}
|
||||
|
||||
interface LanguageAssociations {
|
||||
version: string;
|
||||
extensionToLanguageId: Record<string, string>;
|
||||
fileNameToLanguageId: Record<string, string>;
|
||||
}
|
||||
|
||||
const manifest = vscodeIconsManifest as VscodeIconsManifest;
|
||||
const languageAssociations = languageAssociationsData as LanguageAssociations;
|
||||
const iconDefinitions = manifest.iconDefinitions;
|
||||
|
||||
const darkFileNames = toLowercaseLookup(manifest.fileNames);
|
||||
const lightFileNames = toLowercaseLookup(manifest.light.fileNames);
|
||||
const darkFileExtensions = toLowercaseLookup(manifest.fileExtensions);
|
||||
const lightFileExtensions = toLowercaseLookup(manifest.light.fileExtensions);
|
||||
const darkFolderNames = toLowercaseLookup(manifest.folderNames);
|
||||
const lightFolderNames = toLowercaseLookup(manifest.light.folderNames);
|
||||
const darkLanguageIds = toLowercaseLookup(manifest.languageIds ?? {});
|
||||
const lightLanguageIds = toLowercaseLookup(manifest.light.languageIds ?? {});
|
||||
const languageIdByExtension = toLowercaseLookup(languageAssociations.extensionToLanguageId);
|
||||
const languageIdByFileName = toLowercaseLookup(languageAssociations.fileNameToLanguageId);
|
||||
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";
|
||||
const defaultLightFileIconDefinition = manifest.light.file ?? defaultDarkFileIconDefinition;
|
||||
const defaultDarkFolderIconDefinition = manifest.folder ?? "_folder";
|
||||
const defaultLightFolderIconDefinition = manifest.light.folder ?? defaultDarkFolderIconDefinition;
|
||||
|
||||
function toLowercaseLookup(source: Record<string, string>): Record<string, string> {
|
||||
const entries = Object.entries(source);
|
||||
const lookup: Record<string, string> = {};
|
||||
for (const [key, value] of entries) {
|
||||
lookup[key.toLowerCase()] = value;
|
||||
}
|
||||
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(".")) {
|
||||
candidates.add(fileName);
|
||||
}
|
||||
let dotIndex = fileName.indexOf(".");
|
||||
while (dotIndex !== -1 && dotIndex < fileName.length - 1) {
|
||||
const candidate = fileName.slice(dotIndex + 1);
|
||||
if (candidate.length > 0) {
|
||||
candidates.add(candidate);
|
||||
}
|
||||
dotIndex = fileName.indexOf(".", dotIndex + 1);
|
||||
}
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function resolveLanguageFallbackDefinition(
|
||||
pathValue: string,
|
||||
theme: "light" | "dark",
|
||||
): string | null {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const languageIds = theme === "light" ? lightLanguageIds : darkLanguageIds;
|
||||
|
||||
const fromBasenameLanguage = languageIdByFileName[basename];
|
||||
if (fromBasenameLanguage) {
|
||||
return languageIds[fromBasenameLanguage] ?? darkLanguageIds[fromBasenameLanguage] ?? null;
|
||||
}
|
||||
|
||||
for (const candidate of extensionCandidates(basename)) {
|
||||
const languageId =
|
||||
localLanguageIdByExtensionOverrides[
|
||||
candidate as keyof typeof localLanguageIdByExtensionOverrides
|
||||
] ?? languageIdByExtension[candidate];
|
||||
if (!languageId) continue;
|
||||
return languageIds[languageId] ?? darkLanguageIds[languageId] ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function iconFilenameForDefinitionKey(definitionKey: string | undefined): string | null {
|
||||
if (!definitionKey) return null;
|
||||
const iconPath = iconDefinitions[definitionKey]?.iconPath;
|
||||
if (!iconPath) return null;
|
||||
const slashIndex = iconPath.lastIndexOf("/");
|
||||
if (slashIndex === -1) {
|
||||
return iconPath;
|
||||
}
|
||||
return iconPath.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
function resolveFileDefinition(pathValue: string, theme: "light" | "dark"): string {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const fileNames = theme === "light" ? lightFileNames : darkFileNames;
|
||||
const fileExtensions = theme === "light" ? lightFileExtensions : darkFileExtensions;
|
||||
|
||||
const fromFileName = fileNames[basename] ?? darkFileNames[basename];
|
||||
if (fromFileName) return fromFileName;
|
||||
|
||||
for (const candidate of extensionCandidates(basename)) {
|
||||
const fromExtension = fileExtensions[candidate] ?? darkFileExtensions[candidate];
|
||||
if (fromExtension) return fromExtension;
|
||||
}
|
||||
|
||||
const fromLanguage = resolveLanguageFallbackDefinition(pathValue, theme);
|
||||
if (fromLanguage) return fromLanguage;
|
||||
|
||||
return theme === "light" ? defaultLightFileIconDefinition : defaultDarkFileIconDefinition;
|
||||
}
|
||||
|
||||
function resolveFolderDefinition(pathValue: string, theme: "light" | "dark"): string {
|
||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
||||
const folderNames = theme === "light" ? lightFolderNames : darkFolderNames;
|
||||
return (
|
||||
folderNames[basename] ??
|
||||
darkFolderNames[basename] ??
|
||||
(theme === "light" ? defaultLightFolderIconDefinition : defaultDarkFolderIconDefinition)
|
||||
);
|
||||
}
|
||||
|
||||
export function getVscodeIconUrlForEntry(
|
||||
pathValue: string,
|
||||
kind: "file" | "directory",
|
||||
theme: "light" | "dark",
|
||||
): string {
|
||||
const definitionKey =
|
||||
kind === "directory"
|
||||
? resolveFolderDefinition(pathValue, theme)
|
||||
: resolveFileDefinition(pathValue, theme);
|
||||
const iconFilename =
|
||||
iconFilenameForDefinitionKey(definitionKey) ??
|
||||
(kind === "directory" ? "default_folder.svg" : "default_file.svg");
|
||||
return `${VSCODE_ICONS_BASE_URL}/${iconFilename}`;
|
||||
}
|
||||
@@ -98,7 +98,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
list: () => transport.request(WS_METHODS.projectsList),
|
||||
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
|
||||
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
|
||||
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (cwd, editor) =>
|
||||
|
||||
@@ -53,7 +53,6 @@
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
@@ -426,20 +425,10 @@
|
||||
|
||||
"@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/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-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=="],
|
||||
|
||||
+1
-3
@@ -19,9 +19,7 @@
|
||||
"test": "turbo run test",
|
||||
"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"
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
|
||||
@@ -29,8 +29,6 @@ import type {
|
||||
ProjectAddInput,
|
||||
ProjectAddResult,
|
||||
ProjectListResult,
|
||||
ProjectSearchEntriesInput,
|
||||
ProjectSearchEntriesResult,
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
@@ -92,7 +90,6 @@ export interface NativeApi {
|
||||
list: () => Promise<ProjectListResult>;
|
||||
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
|
||||
remove: (input: ProjectRemoveInput) => Promise<void>;
|
||||
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
|
||||
};
|
||||
shell: {
|
||||
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
|
||||
|
||||
@@ -14,18 +14,6 @@ describe("keybindings contracts", () => {
|
||||
command: "terminal.toggle",
|
||||
});
|
||||
assert.strictEqual(parsed.command, "terminal.toggle");
|
||||
|
||||
const parsedClose = keybindingRuleSchema.parse({
|
||||
key: "mod+w",
|
||||
command: "terminal.close",
|
||||
});
|
||||
assert.strictEqual(parsedClose.command, "terminal.close");
|
||||
|
||||
const parsedLocal = keybindingRuleSchema.parse({
|
||||
key: "mod+shift+n",
|
||||
command: "chat.newLocal",
|
||||
});
|
||||
assert.strictEqual(parsedLocal.command, "chat.newLocal");
|
||||
});
|
||||
|
||||
it("rejects invalid command values", () => {
|
||||
|
||||
@@ -4,9 +4,7 @@ export const keybindingCommandSchema = z.enum([
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"terminal.close",
|
||||
"chat.new",
|
||||
"chat.newLocal",
|
||||
"editor.openFavorite",
|
||||
]);
|
||||
|
||||
@@ -21,16 +19,14 @@ 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 }
|
||||
@@ -61,13 +57,11 @@ 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);
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
projectAddInputSchema,
|
||||
projectAddResultSchema,
|
||||
projectSearchEntriesInputSchema,
|
||||
projectSearchEntriesResultSchema,
|
||||
projectListResultSchema,
|
||||
projectRemoveInputSchema,
|
||||
} from "./project";
|
||||
@@ -48,38 +46,4 @@ describe("project contracts", () => {
|
||||
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
|
||||
expect(parsed.id).toBe("project-1");
|
||||
});
|
||||
|
||||
it("parses workspace entry search input with defaults", () => {
|
||||
const parsed = projectSearchEntriesInputSchema.parse({
|
||||
cwd: " /tmp/project ",
|
||||
query: " src ",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
cwd: "/tmp/project",
|
||||
query: "src",
|
||||
limit: 80,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses workspace entry search result", () => {
|
||||
const parsed = projectSearchEntriesResultSchema.parse({
|
||||
entries: [
|
||||
{
|
||||
path: "src/components",
|
||||
kind: "directory",
|
||||
parentPath: "src",
|
||||
},
|
||||
{
|
||||
path: "src/components/Button.tsx",
|
||||
kind: "file",
|
||||
parentPath: "src/components",
|
||||
},
|
||||
],
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
expect(parsed.entries).toHaveLength(2);
|
||||
expect(parsed.entries[0]?.kind).toBe("directory");
|
||||
});
|
||||
});
|
||||
@@ -23,33 +23,8 @@ export const projectRemoveInputSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
});
|
||||
|
||||
export const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
|
||||
|
||||
export const projectSearchEntriesInputSchema = z.object({
|
||||
cwd: z.string().trim().min(1),
|
||||
query: z.string().trim().max(256).default(""),
|
||||
limit: z.number().int().min(1).max(PROJECT_SEARCH_ENTRIES_MAX_LIMIT).default(80),
|
||||
});
|
||||
|
||||
export const projectEntryKindSchema = z.enum(["file", "directory"]);
|
||||
|
||||
export const projectEntrySchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: projectEntryKindSchema,
|
||||
parentPath: z.string().optional(),
|
||||
});
|
||||
|
||||
export const projectSearchEntriesResultSchema = z.object({
|
||||
entries: z.array(projectEntrySchema),
|
||||
truncated: z.boolean(),
|
||||
});
|
||||
|
||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
||||
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
||||
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
|
||||
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
|
||||
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
|
||||
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
|
||||
@@ -15,7 +15,6 @@ export const WS_METHODS = {
|
||||
projectsList: "projects.list",
|
||||
projectsAdd: "projects.add",
|
||||
projectsRemove: "projects.remove",
|
||||
projectsSearchEntries: "projects.searchEntries",
|
||||
|
||||
// Shell methods
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import vm from "node:vm";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const VERSION = process.argv[2] ?? "12.17.0";
|
||||
const VERSION_TAG = `v${VERSION}`;
|
||||
const VSIX_URL = `https://open-vsx.org/api/vscode-icons-team/vscode-icons/${VERSION}/file/vscode-icons-team.vscode-icons-${VERSION}.vsix`;
|
||||
const LANGUAGES_URL = `https://raw.githubusercontent.com/vscode-icons/vscode-icons/${VERSION_TAG}/src/iconsManifest/languages.ts`;
|
||||
|
||||
const REPO_ROOT = process.cwd();
|
||||
const MANIFEST_PATH = path.join(REPO_ROOT, "apps/web/src/vscode-icons-manifest.json");
|
||||
const ASSOCIATIONS_PATH = path.join(
|
||||
REPO_ROOT,
|
||||
"apps/web/src/vscode-icons-language-associations.json",
|
||||
);
|
||||
|
||||
function normalizeExtension(value) {
|
||||
return value.trim().toLowerCase().replace(/^\./, "");
|
||||
}
|
||||
|
||||
function normalizeFileName(value) {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function putIfAbsent(target, key, value) {
|
||||
if (!(key in target)) {
|
||||
target[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadVsix(tmpDir) {
|
||||
const vsixPath = path.join(tmpDir, `vscode-icons-${VERSION}.vsix`);
|
||||
const response = await fetch(VSIX_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download VSIX: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
await fs.writeFile(vsixPath, bytes);
|
||||
return vsixPath;
|
||||
}
|
||||
|
||||
async function extractManifestFromVsix(vsixPath) {
|
||||
const { stdout } = await execFileAsync("unzip", [
|
||||
"-p",
|
||||
vsixPath,
|
||||
"extension/dist/src/vsicons-icon-theme.json",
|
||||
]);
|
||||
if (!stdout || stdout.trim().length === 0) {
|
||||
throw new Error("Could not extract vsicons-icon-theme.json from VSIX");
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
|
||||
async function loadLanguagesCollection() {
|
||||
const response = await fetch(LANGUAGES_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch languages.ts: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const rawSource = await response.text();
|
||||
const source = rawSource
|
||||
.replace(/^import[^;]+;\s*/gm, "")
|
||||
.replace(/export const languages(?:\s*:\s*[^=]+)?\s*=/, "const languages =")
|
||||
.replace(/\}\s*satisfies\s*Record<[^;]+>;/, "};");
|
||||
|
||||
const context = {};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(`${source}\n;globalThis.__languages = languages;`, context);
|
||||
const languages = context.__languages;
|
||||
if (!languages || typeof languages !== "object") {
|
||||
throw new Error("Failed to parse languages.ts into a collection");
|
||||
}
|
||||
return languages;
|
||||
}
|
||||
|
||||
function buildLanguageAssociations(manifest, languages) {
|
||||
const availableLanguageIds = new Set(Object.keys(manifest.languageIds ?? {}));
|
||||
const extensionToLanguageId = {};
|
||||
const fileNameToLanguageId = {};
|
||||
|
||||
for (const entry of Object.values(languages)) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const idsRaw = entry.ids;
|
||||
const ids = Array.isArray(idsRaw) ? idsRaw : [idsRaw];
|
||||
const knownExtensions = Array.isArray(entry.knownExtensions) ? entry.knownExtensions : [];
|
||||
const knownFilenames = Array.isArray(entry.knownFilenames) ? entry.knownFilenames : [];
|
||||
|
||||
for (const idValue of ids) {
|
||||
if (typeof idValue !== "string") continue;
|
||||
const languageId = idValue.trim();
|
||||
if (languageId.length === 0) continue;
|
||||
if (!availableLanguageIds.has(languageId)) continue;
|
||||
|
||||
for (const extensionValue of knownExtensions) {
|
||||
if (typeof extensionValue !== "string") continue;
|
||||
const extension = normalizeExtension(extensionValue);
|
||||
if (extension.length === 0) continue;
|
||||
putIfAbsent(extensionToLanguageId, extension, languageId);
|
||||
}
|
||||
|
||||
for (const fileNameValue of knownFilenames) {
|
||||
if (typeof fileNameValue !== "string") continue;
|
||||
const fileName = normalizeFileName(fileNameValue);
|
||||
if (fileName.length === 0) continue;
|
||||
putIfAbsent(fileNameToLanguageId, fileName, languageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
version: VERSION,
|
||||
source: LANGUAGES_URL,
|
||||
generatedAt: new Date().toISOString(),
|
||||
extensionToLanguageId,
|
||||
fileNameToLanguageId,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "t3-vscode-icons-sync-"));
|
||||
try {
|
||||
const vsixPath = await downloadVsix(tmpDir);
|
||||
const manifest = await extractManifestFromVsix(vsixPath);
|
||||
const languages = await loadLanguagesCollection();
|
||||
const associations = buildLanguageAssociations(manifest, languages);
|
||||
|
||||
await fs.writeFile(MANIFEST_PATH, `${JSON.stringify(manifest)}\n`, "utf8");
|
||||
await fs.writeFile(ASSOCIATIONS_PATH, `${JSON.stringify(associations)}\n`, "utf8");
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
`Synced vscode-icons ${VERSION}`,
|
||||
`manifest: ${MANIFEST_PATH}`,
|
||||
`language associations: ${ASSOCIATIONS_PATH}`,
|
||||
`extension mappings: ${Object.keys(associations.extensionToLanguageId).length}`,
|
||||
`filename mappings: ${Object.keys(associations.fileNameToLanguageId).length}`,
|
||||
].join("\n") + "\n",
|
||||
);
|
||||
} finally {
|
||||
await fs.rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user