Compare commits

..
Author SHA1 Message Date
Julius Marminge 4d976b8bf7 Persist renderer state on server via SQLite and WS APIs
- Add shared renderer state contracts and websocket methods
- Implement server-side SQLite-backed renderer state store with Node/Bun adapters
- Migrate web store hydration/persistence from localStorage to server state, with legacy fallback
- Add contract, store, and websocket persistence tests
2026-02-17 21:15:51 -08:00
Julius Marminge 0c50a2d8e1 Persist image previews in chat state and bump schema to v8
- store image attachment `previewUrl` data URLs in persisted thread messages
- migrate renderer persistence key/schema from v7 to v8 with hydration coverage
- build message attachments from prepared image data before dispatching user messages
2026-02-17 15:54:12 -08:00
Julius Marminge f64c26e708 Add clean script to package.json for removing build artifacts
- Introduce a new "clean" script to remove node_modules and build artifacts across apps and packages
- Enhances project maintenance by simplifying cleanup process
2026-02-17 15:12:57 -08:00
Julius Marminge 6d8d39a5d1 Guard branch sync when no active thread is selected
- Prevent `SET_THREAD_BRANCH` dispatch unless both `activeThreadId` and `syncedBranch` exist
- Avoids updating thread-branch state without an active thread context
2026-02-17 15:12:07 -08:00
Julius Marminge afdfe16931 Extract branch sync logic and limit sync to local mode
- move branch-sync decision into `BranchToolbar.logic.ts`
- avoid auto-sync when env mode is `worktree` or thread has worktree path
- add unit tests for sync and no-sync cases
2026-02-17 15:12:07 -08:00
31 changed files with 742 additions and 1620 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
declare module "bun:sqlite" {
export class Database {
constructor(filename?: string);
exec(sql: string): void;
run(sql: string, ...params: unknown[]): unknown;
query(sql: string): {
get(...params: unknown[]): unknown;
};
close(): void;
}
}
+1
View File
@@ -118,6 +118,7 @@ async function main() {
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
stateDir,
staticDir,
devUrl,
projectRegistry,
@@ -0,0 +1,47 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { RendererStateStore } from "./rendererStateStore";
function makeTempDir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}
describe("RendererStateStore", () => {
it("returns null when no renderer state has been saved", async () => {
const stateDir = makeTempDir("t3code-renderer-state-empty-");
const store = new RendererStateStore(stateDir);
await expect(store.get()).resolves.toBeNull();
await store.close();
fs.rmSync(stateDir, { recursive: true, force: true });
});
it("persists and reloads renderer state from sqlite", async () => {
const stateDir = makeTempDir("t3code-renderer-state-roundtrip-");
const firstStore = new RendererStateStore(stateDir);
const payload =
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}';
await firstStore.set({ stateJson: payload });
const firstRead = await firstStore.get();
expect(firstRead).toMatchObject({
stateJson: payload,
updatedAt: expect.any(String),
});
await firstStore.close();
const secondStore = new RendererStateStore(stateDir);
const secondRead = await secondStore.get();
expect(secondRead).toMatchObject({
stateJson: payload,
updatedAt: expect.any(String),
});
await secondStore.close();
fs.rmSync(stateDir, { recursive: true, force: true });
});
});
+174
View File
@@ -0,0 +1,174 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
type RendererStateSetInput,
type RendererStateSnapshot,
rendererStateSetInputSchema,
rendererStateSnapshotSchema,
} from "@t3tools/contracts";
interface RowShape {
stateJson: string;
updatedAt: string;
}
interface SqliteAdapter {
getState(): RowShape | null;
setState(stateJson: string, updatedAt: string): void;
close(): void;
}
interface BunSqliteDatabase {
exec(sql: string): void;
run(sql: string, ...params: unknown[]): unknown;
query(sql: string): {
get(...params: unknown[]): unknown;
};
close(): void;
}
interface BunSqliteModule {
Database: new (filename?: string) => BunSqliteDatabase;
}
function defaultStateDir(): string {
return path.join(os.homedir(), ".t3", "userdata");
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function parseRowShape(row: unknown): RowShape | null {
if (!isObject(row)) return null;
const stateJson = row.stateJson;
const updatedAt = row.updatedAt;
if (typeof stateJson !== "string" || typeof updatedAt !== "string") return null;
return { stateJson, updatedAt };
}
async function createNodeSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
const module = await import("node:sqlite");
const db = new module.DatabaseSync(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS renderer_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
state_json TEXT NOT NULL,
updated_at TEXT NOT NULL
)
`);
const selectStatement = db.prepare(`
SELECT state_json AS stateJson, updated_at AS updatedAt
FROM renderer_state
WHERE id = 1
`);
const upsertStatement = db.prepare(`
INSERT INTO renderer_state (id, state_json, updated_at)
VALUES (1, ?, ?)
ON CONFLICT(id) DO UPDATE SET
state_json = excluded.state_json,
updated_at = excluded.updated_at
`);
return {
getState() {
return parseRowShape(selectStatement.get());
},
setState(stateJson: string, updatedAt: string) {
upsertStatement.run(stateJson, updatedAt);
},
close() {
db.close();
},
};
}
async function createBunSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
const loadBunSqlite = new Function(
"return import('bun:sqlite')",
) as () => Promise<BunSqliteModule>;
const module = await loadBunSqlite();
const db = new module.Database(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS renderer_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
state_json TEXT NOT NULL,
updated_at TEXT NOT NULL
)
`);
const selectQuery = db.query(`
SELECT state_json AS stateJson, updated_at AS updatedAt
FROM renderer_state
WHERE id = 1
`);
const upsertSql = `
INSERT INTO renderer_state (id, state_json, updated_at)
VALUES (1, ?, ?)
ON CONFLICT(id) DO UPDATE SET
state_json = excluded.state_json,
updated_at = excluded.updated_at
`;
return {
getState() {
return parseRowShape(selectQuery.get());
},
setState(stateJson: string, updatedAt: string) {
db.run(upsertSql, stateJson, updatedAt);
},
close() {
db.close();
},
};
}
async function createSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
try {
return await createNodeSqliteAdapter(dbPath);
} catch {
return createBunSqliteAdapter(dbPath);
}
}
export class RendererStateStore {
private readonly stateDir: string;
private readonly dbPath: string;
private adapterPromise: Promise<SqliteAdapter> | null = null;
constructor(stateDir: string = defaultStateDir()) {
this.stateDir = stateDir;
this.dbPath = path.join(this.stateDir, "renderer-state.sqlite");
fs.mkdirSync(this.stateDir, { recursive: true });
}
async get(): Promise<RendererStateSnapshot | null> {
const adapter = await this.getAdapter();
const row = adapter.getState();
if (!row) return null;
const parsed = rendererStateSnapshotSchema.safeParse(row);
if (!parsed.success) return null;
return parsed.data;
}
async set(raw: RendererStateSetInput): Promise<void> {
const input = rendererStateSetInputSchema.parse(raw);
const adapter = await this.getAdapter();
adapter.setState(input.stateJson, new Date().toISOString());
}
async close(): Promise<void> {
if (!this.adapterPromise) return;
const adapter = await this.adapterPromise;
adapter.close();
this.adapterPromise = null;
}
private async getAdapter(): Promise<SqliteAdapter> {
if (!this.adapterPromise) {
this.adapterPromise = createSqliteAdapter(this.dbPath);
}
return this.adapterPromise;
}
}
-118
View File
@@ -1,118 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { afterEach, assert, describe, it } 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(() => {
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/")));
});
});
-348
View File
@@ -1,348 +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 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>();
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 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 checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
cwd,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxBufferBytes: 16 * 1024 * 1024,
outputMode: "truncate",
stdin: `${relativePaths.join("\0")}\0`,
}).catch(() => null);
if (!checkIgnore) {
return relativePaths;
}
// git-check-ignore exits with 1 when no paths match.
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
return relativePaths;
}
const ignoredPaths = new Set(
splitNullSeparatedPaths(checkIgnore.stdout, Boolean(checkIgnore.stdoutTruncated)),
);
if (ignoredPaths.size === 0) {
return relativePaths;
}
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]
.sort((left, right) => left.localeCompare(right))
.map((directoryPath) => ({
path: directoryPath,
kind: "directory",
parentPath: parentPathOf(directoryPath),
}));
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
.sort((left, right) => left.localeCompare(right))
.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 Promise.all(
currentDirectories.map(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 next = await buildWorkspaceIndex(cwd);
workspaceIndexCache.set(cwd, next);
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
const oldestKey = workspaceIndexCache.keys().next().value;
if (!oldestKey) break;
workspaceIndexCache.delete(oldestKey);
}
return next;
}
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,
};
}
+66 -32
View File
@@ -249,6 +249,7 @@ describe("WebSocket Server", () => {
return createServer({
port: 0,
cwd: options.cwd ?? "/test/project",
stateDir,
...(options.devUrl ? { devUrl: options.devUrl } : {}),
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
@@ -342,6 +343,71 @@ describe("WebSocket Server", () => {
});
});
it("reads and writes renderer state over websocket", async () => {
const stateDir = makeTempDir("t3code-ws-renderer-state-");
server = createTestServer({ cwd: "/my/workspace", stateDir });
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 empty = await sendRequest(ws, WS_METHODS.serverGetRendererState);
expect(empty.error).toBeUndefined();
expect(empty.result).toBeNull();
const setResponse = await sendRequest(ws, WS_METHODS.serverSetRendererState, {
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
});
expect(setResponse.error).toBeUndefined();
const loaded = await sendRequest(ws, WS_METHODS.serverGetRendererState);
expect(loaded.error).toBeUndefined();
expect(loaded.result).toMatchObject({
stateJson:
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
updatedAt: expect.any(String),
});
});
it("persists renderer state across server restarts", async () => {
const stateDir = makeTempDir("t3code-ws-renderer-state-restart-");
server = createTestServer({ cwd: "/workspace", stateDir });
await server.start();
const firstAddr = server.httpServer.address();
const firstPort = typeof firstAddr === "object" && firstAddr !== null ? firstAddr.port : 0;
const firstWs = await connectWs(firstPort);
connections.push(firstWs);
await waitForMessage(firstWs);
const setResponse = await sendRequest(firstWs, WS_METHODS.serverSetRendererState, {
stateJson:
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
});
expect(setResponse.error).toBeUndefined();
await server.stop();
server = createTestServer({ cwd: "/workspace", stateDir });
await server.start();
const secondAddr = server.httpServer.address();
const secondPort =
typeof secondAddr === "object" && secondAddr !== null ? secondAddr.port : 0;
const secondWs = await connectWs(secondPort);
connections.push(secondWs);
await waitForMessage(secondWs);
const loaded = await sendRequest(secondWs, WS_METHODS.serverGetRendererState);
expect(loaded.error).toBeUndefined();
expect(loaded.result).toMatchObject({
stateJson:
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
updatedAt: expect.any(String),
});
});
it("reads keybindings from ~/.t3/keybindings.json", async () => {
const fakeHome = makeTempDir("t3code-home-");
const configDir = path.join(fakeHome, ".t3");
@@ -766,38 +832,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-");
+16 -6
View File
@@ -32,7 +32,7 @@ import {
} from "./git";
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { RendererStateStore } from "./rendererStateStore";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -53,12 +53,14 @@ export interface ServerOptions {
port: number;
host?: string | undefined;
cwd: string;
stateDir?: string | undefined;
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
rendererStateStore?: RendererStateStore | undefined;
authToken?: string | undefined;
}
@@ -75,18 +77,21 @@ export function createServer(options: ServerOptions) {
port,
host,
cwd,
stateDir,
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
gitManager: providedGitManager,
terminalManager: providedTerminalManager,
rendererStateStore: providedRendererStateStore,
authToken,
} = options;
const providerManager = new ProviderManager();
const terminalManager = providedTerminalManager ?? new TerminalManager();
const projectRegistry =
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
const resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
const projectRegistry = providedRegistry ?? new ProjectRegistry(resolvedStateDir);
const rendererStateStore = providedRendererStateStore ?? new RendererStateStore(resolvedStateDir);
const gitManager = providedGitManager ?? new GitManager();
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
@@ -320,9 +325,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;
@@ -421,6 +423,13 @@ export function createServer(options: ServerOptions) {
keybindings: keybindingsConfig,
};
case WS_METHODS.serverGetRendererState:
return rendererStateStore.get();
case WS_METHODS.serverSetRendererState:
await rendererStateStore.set(request.params as never);
return undefined;
default:
throw new Error(`Unknown method: ${request.method}`);
}
@@ -450,6 +459,7 @@ export function createServer(options: ServerOptions) {
providerManager.stopAll();
providerManager.dispose();
terminalManager.dispose();
await rendererStateStore.close();
for (const client of clients) {
client.close();
@@ -0,0 +1,56 @@
import type { GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
const branches: GitBranch[] = [
{
name: "main",
current: true,
isDefault: true,
worktreePath: null,
},
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
];
describe("deriveSyncedLocalBranch", () => {
it("syncs to git current branch in local mode", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: null,
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBe("main");
});
it("does not sync when creating a new worktree", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: null,
envMode: "worktree",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
it("does not sync when thread already targets a worktree path", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
});
@@ -0,0 +1,28 @@
import type { GitBranch } from "@t3tools/contracts";
interface DeriveSyncedLocalBranchInput {
activeThreadId: string | undefined;
activeWorktreePath: string | null;
envMode: "local" | "worktree";
activeThreadBranch: string | null;
queryBranches: GitBranch[] | undefined;
}
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
}: DeriveSyncedLocalBranchInput): string | null {
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
return null;
}
const currentBranch = queryBranches?.find((branch) => branch.current);
if (!currentBranch || currentBranch.name === activeThreadBranch) {
return null;
}
return currentBranch.name;
}
+12 -6
View File
@@ -9,6 +9,7 @@ import {
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
@@ -86,17 +87,22 @@ export default function BranchToolbar({
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
if (!activeThreadId || activeWorktreePath) return;
const current = queryBranches?.find((branch) => branch.current);
if (!current) return;
if (current.name === activeThreadBranch) return;
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: current.name,
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
+37 -450
View File
@@ -1,7 +1,6 @@
import {
EDITORS,
type EditorId,
type ProjectEntry,
ModelSlug,
type NativeApi,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
@@ -32,11 +31,6 @@ import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
import { isElectron } from "../env";
import { buildBootstrapInput } from "../historyBootstrap";
import {
type ComposerTriggerKind,
detectComposerTrigger,
replaceTextRange,
} from "../composer-logic";
import {
DEFAULT_MODEL,
DEFAULT_REASONING,
@@ -58,8 +52,6 @@ import {
import { isScrollContainerNearBottom } from "../chat-scroll";
import { useStore } from "../store";
import type { ChatImageAttachment } from "../types";
import { getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
@@ -75,11 +67,8 @@ import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { useNativeApi } from "../hooks/useNativeApi";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import {
BotIcon,
ChevronDownIcon,
CircleAlertIcon,
FileIcon,
FolderIcon,
FolderClosedIcon,
InfoIcon,
LockIcon,
@@ -94,7 +83,6 @@ import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"
import { CursorIcon, Icon } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Command, CommandItem, CommandList } from "./ui/command";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -107,14 +95,6 @@ const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
const SEARCHABLE_MODEL_OPTIONS = MODEL_OPTIONS.map(({ slug, name }) => ({
slug,
name,
searchSlug: slug.toLowerCase(),
searchName: name.toLowerCase(),
}));
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
@@ -123,12 +103,6 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
return "text-muted-foreground/40";
}
function basenameOfPath(pathValue: string): string {
const slashIndex = pathValue.lastIndexOf("/");
if (slashIndex === -1) return pathValue;
return pathValue.slice(slashIndex + 1);
}
type SessionContinuityState = "resumed" | "new" | "fallback_new";
interface EnsuredSessionInfo {
@@ -147,29 +121,6 @@ interface ExpandedImagePreview {
name: string;
}
type ComposerCommandItem =
| {
id: string;
type: "path";
path: string;
pathKind: ProjectEntry["kind"];
label: string;
description: string;
}
| {
id: string;
type: "slash-command";
label: string;
description: string;
}
| {
id: string;
type: "model";
model: ModelSlug;
label: string;
description: string;
};
function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -187,141 +138,9 @@ function readFileAsDataUrl(file: File): Promise<string> {
});
}
const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
pathValue: string;
kind: "file" | "directory";
theme: "light" | "dark";
}) {
const [failed, setFailed] = useState(false);
const iconUrl = useMemo(
() => getVscodeIconUrlForEntry(props.pathValue, props.kind, props.theme),
[props.kind, props.pathValue, props.theme],
);
useEffect(() => {
setFailed(false);
}, [iconUrl]);
if (failed) {
return props.kind === "directory" ? (
<FolderIcon className="size-4 text-muted-foreground/80" />
) : (
<FileIcon className="size-4 text-muted-foreground/80" />
);
}
return (
<img
src={iconUrl}
alt=""
aria-hidden="true"
className="size-4 shrink-0"
loading="lazy"
onError={() => setFailed(true)}
/>
);
});
const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
item: ComposerCommandItem;
index: number;
isHighlighted: boolean;
keyboardHighlight: boolean;
resolvedTheme: "light" | "dark";
onHighlight: (index: number) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
return (
<CommandItem
value={props.item.id}
data-composer-menu-index={props.index}
className={cn(
"cursor-pointer gap-2",
props.keyboardHighlight &&
!props.isHighlighted &&
"data-highlighted:bg-transparent data-highlighted:text-inherit",
props.isHighlighted && "bg-accent text-accent-foreground",
)}
onMouseEnter={() => {
props.onHighlight(props.index);
}}
onMouseDown={(event) => {
event.preventDefault();
}}
onClick={() => {
props.onSelect(props.item);
}}
>
{props.item.type === "path" ? (
<VscodeEntryIcon
pathValue={props.item.path}
kind={props.item.pathKind}
theme={props.resolvedTheme}
/>
) : null}
{props.item.type === "slash-command" ? (
<BotIcon className="size-4 text-muted-foreground/80" />
) : null}
{props.item.type === "model" ? (
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
model
</Badge>
) : null}
<span className="truncate">{props.item.label}</span>
<span className="truncate text-muted-foreground/70 text-xs">{props.item.description}</span>
</CommandItem>
);
});
const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
items: ComposerCommandItem[];
selectedIndex: number;
keyboardHighlight: boolean;
resolvedTheme: "light" | "dark";
isLoading: boolean;
triggerKind: ComposerTriggerKind | null;
onHighlight: (index: number) => void;
onSelect: (item: ComposerCommandItem) => void;
menuRef: RefObject<HTMLDivElement | null>;
}) {
return (
<Command>
<div
ref={props.menuRef}
className="overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<CommandList className="max-h-64">
{props.items.map((item, index) => (
<ComposerCommandMenuItem
key={item.id}
item={item}
index={index}
isHighlighted={index === props.selectedIndex}
keyboardHighlight={props.keyboardHighlight}
resolvedTheme={props.resolvedTheme}
onHighlight={props.onHighlight}
onSelect={props.onSelect}
/>
))}
</CommandList>
{props.items.length === 0 && (
<p className="px-3 py-2 text-muted-foreground/70 text-xs">
{props.isLoading
? "Searching workspace files..."
: props.triggerKind === "path"
? "No matching files or folders."
: "No matching command."}
</p>
)}
</div>
</Command>
);
});
export default function ChatView() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(
gitCreateWorktreeMutationOptions({ api, queryClient }),
@@ -339,16 +158,10 @@ export default function ChatView() {
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
const [nowTick, setNowTick] = useState(() => Date.now());
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerCursor, setComposerCursor] = useState(0);
const [debouncedPathQuery, setDebouncedPathQuery] = useState("");
const [composerMenuIndex, setComposerMenuIndex] = useState(0);
const [composerKeyboardHighlight, setComposerKeyboardHighlight] = useState(false);
const messagesScrollRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerMenuRef = useRef<HTMLDivElement>(null);
const previousComposerMenuIndexRef = useRef(0);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -455,98 +268,11 @@ export default function ChatView() {
sandboxMode: "workspace-write",
} as const);
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
const composerTrigger = useMemo(
() => detectComposerTrigger(prompt, composerCursor),
[prompt, composerCursor],
);
const composerTriggerKind = composerTrigger?.kind ?? null;
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
const isPathTrigger = composerTriggerKind === "path";
const branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd));
const keybindingsQuery = useQuery({
...serverConfigQueryOptions(api),
select: (config) => config.keybindings,
});
useEffect(() => {
if (!isPathTrigger) {
setDebouncedPathQuery("");
return;
}
if (pathTriggerQuery.length === 0) {
setDebouncedPathQuery("");
return;
}
const timer = window.setTimeout(() => {
setDebouncedPathQuery(pathTriggerQuery);
}, COMPOSER_PATH_QUERY_DEBOUNCE_MS);
return () => {
window.clearTimeout(timer);
};
}, [isPathTrigger, pathTriggerQuery]);
const workspaceEntriesQuery = useQuery({
queryKey: [
"composer-workspace-entries",
gitCwd,
debouncedPathQuery,
],
enabled: Boolean(api && gitCwd && isPathTrigger),
staleTime: 15_000,
placeholderData: (previous) => previous,
queryFn: async () => {
if (!api || !gitCwd || !isPathTrigger) {
return { entries: [], truncated: false };
}
return api.projects.searchEntries({
cwd: gitCwd,
query: debouncedPathQuery,
limit: 80,
});
},
});
const workspaceEntries = workspaceEntriesQuery.data?.entries ?? EMPTY_PROJECT_ENTRIES;
const composerMenuItems = useMemo<ComposerCommandItem[]>(() => {
if (!composerTrigger) return [];
if (composerTrigger.kind === "path") {
return workspaceEntries.map((entry) => ({
id: `path:${entry.kind}:${entry.path}`,
type: "path",
path: entry.path,
pathKind: entry.kind,
label: basenameOfPath(entry.path),
description: entry.parentPath ?? "",
}));
}
if (composerTrigger.kind === "slash-command") {
if (!"model".includes(composerTrigger.query.toLowerCase())) {
return [];
}
return [
{
id: "slash:model",
type: "slash-command",
label: "/model",
description: "Switch response model for this thread",
},
];
}
return SEARCHABLE_MODEL_OPTIONS.filter(({ searchSlug, searchName }) => {
const query = composerTrigger.query.trim().toLowerCase();
if (!query) return true;
return searchSlug.includes(query) || searchName.includes(query);
}).map(({ slug, name }) => ({
id: `model:${slug}`,
type: "model",
model: slug,
label: name,
description: slug,
}));
}, [composerTrigger, workspaceEntries]);
const composerMenuOpen = Boolean(composerTrigger);
const activeComposerMenuItem =
composerMenuItems[Math.min(composerMenuIndex, Math.max(0, composerMenuItems.length - 1))] ??
null;
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
@@ -710,38 +436,6 @@ export default function ChatView() {
setExpandedWorkGroups({});
}, [activeThread?.id]);
useEffect(() => {
setComposerMenuIndex(0);
}, [composerTrigger?.kind, composerTrigger?.query, composerMenuItems.length]);
useEffect(() => {
if (!composerMenuOpen) return;
setComposerKeyboardHighlight(false);
setComposerMenuIndex(0);
}, [composerMenuOpen]);
useEffect(() => {
if (!composerMenuOpen || composerMenuItems.length === 0) {
return;
}
const clampedIndex = Math.min(composerMenuIndex, composerMenuItems.length - 1);
const previousIndex = previousComposerMenuIndexRef.current;
const direction = clampedIndex - previousIndex;
previousComposerMenuIndexRef.current = clampedIndex;
const aheadIndex =
direction > 0
? Math.min(clampedIndex + 1, composerMenuItems.length - 1)
: direction < 0
? Math.max(clampedIndex - 1, 0)
: clampedIndex;
const node = composerMenuRef.current?.querySelector<HTMLElement>(
`[data-composer-menu-index="${aheadIndex}"]`,
);
node?.scrollIntoView({ block: "nearest" });
}, [composerMenuIndex, composerMenuItems.length, composerMenuOpen]);
useEffect(() => {
if (!activeThread?.id || activeThread.terminalOpen) return;
const frame = window.requestAnimationFrame(() => {
@@ -761,8 +455,6 @@ export default function ChatView() {
revokePreviewUrls(existing);
return [];
});
setComposerCursor(0);
setComposerMenuIndex(0);
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
@@ -1131,43 +823,48 @@ export default function ChatView() {
}
setThreadError(activeThread.id, null);
const messageAttachments: ChatImageAttachment[] = composerImagesSnapshot.map((image) => ({
type: "image",
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
const previousMessages = activeThread.messages;
setPrompt("");
setComposerImages([]);
setComposerCursor(0);
setComposerMenuIndex(0);
const sessionInfo = await ensureSession(sessionCwd);
if (!sessionInfo) return;
setIsSending(true);
try {
const turnAttachments = await Promise.all(
composerImagesSnapshot.map(
async (image): Promise<ProviderSendTurnAttachmentInput> => ({
const preparedImages = await Promise.all(
composerImagesSnapshot.map(async (image) => {
const attachment: ProviderSendTurnAttachmentInput = {
type: "image",
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file),
}),
),
};
return { image, attachment };
}),
);
const turnAttachments = preparedImages.map(({ attachment }) => attachment);
const messageAttachments: ChatImageAttachment[] = preparedImages.map(
({ image, attachment }) => ({
type: "image",
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
previewUrl: attachment.dataUrl,
}),
);
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
setPrompt("");
setComposerImages((existing) => {
revokePreviewUrls(existing);
return [];
});
const sessionInfo = await ensureSession(sessionCwd);
if (!sessionInfo) return;
const shouldBootstrap =
previousMessages.length > 0 &&
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
@@ -1257,79 +954,7 @@ export default function ChatView() {
[scheduleComposerFocus],
);
const applyPromptReplacement = useCallback(
(rangeStart: number, rangeEnd: number, replacement: string) => {
setPrompt((existing) => {
const next = replaceTextRange(existing, rangeStart, rangeEnd, replacement);
window.requestAnimationFrame(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.focus();
textarea.setSelectionRange(next.cursor, next.cursor);
setComposerCursor(next.cursor);
});
return next.text;
});
},
[],
);
const onSelectComposerItem = useCallback(
(item: ComposerCommandItem) => {
if (!composerTrigger) return;
if (item.type === "path") {
applyPromptReplacement(
composerTrigger.rangeStart,
composerTrigger.rangeEnd,
`@${item.path} `,
);
return;
}
if (item.type === "slash-command") {
applyPromptReplacement(composerTrigger.rangeStart, composerTrigger.rangeEnd, "/model ");
return;
}
onModelSelect(item.model);
applyPromptReplacement(composerTrigger.rangeStart, composerTrigger.rangeEnd, "");
},
[applyPromptReplacement, composerTrigger, onModelSelect],
);
const onHighlightComposerMenuItem = useCallback((index: number) => {
setComposerKeyboardHighlight(false);
setComposerMenuIndex(index);
}, []);
const isComposerMenuLoading =
composerTriggerKind === "path" && (workspaceEntriesQuery.isLoading || workspaceEntriesQuery.isFetching);
const onPromptChange = useCallback((nextPrompt: string, nextCursor: number) => {
setPrompt(nextPrompt);
setComposerCursor(nextCursor);
}, []);
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (composerMenuOpen && composerMenuItems.length > 0) {
if (e.key === "ArrowDown") {
e.preventDefault();
setComposerKeyboardHighlight(true);
setComposerMenuIndex((existing) => Math.min(existing + 1, composerMenuItems.length - 1));
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setComposerKeyboardHighlight(true);
setComposerMenuIndex((existing) => Math.max(existing - 1, 0));
return;
}
if (e.key === "Tab" || e.key === "Enter") {
const selectedItem = activeComposerMenuItem ?? composerMenuItems[0];
if (selectedItem) {
e.preventDefault();
onSelectComposerItem(selectedItem);
return;
}
}
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void onSend(e as unknown as FormEvent);
@@ -1425,23 +1050,7 @@ export default function ChatView() {
onDrop={onComposerDrop}
>
{/* Textarea area */}
<div className="relative px-4 pt-4 pb-2">
{composerMenuOpen && (
<div className="absolute inset-x-0 bottom-full z-20 mb-2 px-1">
<ComposerCommandMenu
items={composerMenuItems}
selectedIndex={composerMenuIndex}
keyboardHighlight={composerKeyboardHighlight}
resolvedTheme={resolvedTheme}
isLoading={isComposerMenuLoading}
triggerKind={composerTriggerKind}
onHighlight={onHighlightComposerMenuItem}
onSelect={onSelectComposerItem}
menuRef={composerMenuRef}
/>
</div>
)}
<div className="px-4 pt-4 pb-2">
{composerImages.length > 0 && (
<div className="mb-3 flex flex-wrap gap-2">
{composerImages.map((image) => (
@@ -1481,33 +1090,13 @@ export default function ChatView() {
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
rows={2}
value={prompt}
onChange={(event) =>
onPromptChange(
event.target.value,
event.target.selectionStart ?? event.target.value.length,
)
}
onChange={(e) => setPrompt(e.target.value)}
onKeyDown={onKeyDown}
onKeyUp={(event) =>
setComposerCursor(
event.currentTarget.selectionStart ?? event.currentTarget.value.length,
)
}
onClick={(event) =>
setComposerCursor(
event.currentTarget.selectionStart ?? event.currentTarget.value.length,
)
}
onSelect={(event) =>
setComposerCursor(
event.currentTarget.selectionStart ?? event.currentTarget.value.length,
)
}
onPaste={onComposerPaste}
placeholder={
phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use /model"
: "Ask anything, or attach images..."
}
disabled={isSending || isConnecting}
/>
@@ -1861,9 +1450,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
if (!hasMessages && !isWorking) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
<p className="text-sm text-muted-foreground/30">Send a message to start the conversation.</p>
</div>
);
}
-72
View File
@@ -1,72 +0,0 @@
import { describe, expect, it } from "vitest";
import {
buildPromptInput,
buildUserVisiblePrompt,
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,
});
});
});
describe("tagged path prompt helpers", () => {
it("builds model input with tagged paths", () => {
const result = buildPromptInput("Fix this", ["src/app.tsx", "src/app.tsx", "README.md"]);
expect(result).toContain("Fix this");
expect(result).toContain("Referenced paths:");
expect(result).toContain("- src/app.tsx");
expect(result).toContain("- README.md");
expect(result).not.toContain("- src/app.tsx\n- src/app.tsx");
});
it("builds user-visible prompt from tags only", () => {
const result = buildUserVisiblePrompt(" ", ["src/app.tsx", "README.md"]);
expect(result).toBe("@src/app.tsx @README.md");
});
});
-128
View File
@@ -1,128 +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;
}
function dedupePaths(paths: string[]): string[] {
const unique = new Set<string>();
for (const rawPath of paths) {
const normalized = rawPath.trim();
if (!normalized) continue;
unique.add(normalized);
}
return [...unique];
}
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
const cursor = clampCursor(text, cursorInput);
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
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 };
}
export function buildPromptInput(text: string, taggedPaths: string[]): string {
const trimmedPrompt = text.trim();
const normalizedPaths = dedupePaths(taggedPaths);
if (normalizedPaths.length === 0) {
return trimmedPrompt;
}
const tagBlock = `Referenced paths:\n${normalizedPaths.map((entry) => `- ${entry}`).join("\n")}`;
if (!trimmedPrompt) {
return tagBlock;
}
return `${trimmedPrompt}\n\n${tagBlock}`;
}
export function buildUserVisiblePrompt(text: string, taggedPaths: string[]): string {
const trimmedPrompt = text.trim();
const normalizedPaths = dedupePaths(taggedPaths);
if (normalizedPaths.length === 0) {
return trimmedPrompt;
}
const tagsSummary = normalizedPaths.map((entry) => `@${entry}`).join(" ");
if (!trimmedPrompt) {
return tagsSummary;
}
return `${trimmedPrompt}\n\n${tagsSummary}`;
}
+122 -2
View File
@@ -257,10 +257,65 @@ describe("hydratePersistedState", () => {
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("hydrates persisted image preview data urls", () => {
const payload = JSON.stringify({
version: 8,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
messages: [
{
id: "m-1",
role: "user",
text: "Here",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
previewUrl: "data:image/png;base64,AAAA",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.messages[0]?.attachments?.[0]?.previewUrl).toBe(
"data:image/png;base64,AAAA",
);
});
});
describe("toPersistedState", () => {
it("writes v7 payload and strips non-persisted thread fields", () => {
it("writes v8 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
@@ -320,7 +375,7 @@ describe("toPersistedState", () => {
runtimeMode: "full-access",
});
expect(persisted.version).toBe(7);
expect(persisted.version).toBe(8);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
@@ -367,4 +422,69 @@ describe("toPersistedState", () => {
expect("error" in persistedThread).toBe(false);
expect("session" in persistedThread).toBe(false);
});
it("persists preview data urls for image attachments", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [
{
id: "m-1",
role: "user",
text: "Image",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1_024,
previewUrl: "data:image/png;base64,AAAA",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
events: [],
error: null,
createdAt: "2026-02-08T10:00:00.000Z",
branch: null,
worktreePath: null,
};
const persisted = toPersistedState({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: "t-1",
runtimeMode: "full-access",
});
expect(persisted.threads[0]?.messages[0]?.attachments?.[0]).toMatchObject({
type: "image",
id: "img-1",
previewUrl: "data:image/png;base64,AAAA",
});
});
});
+20 -3
View File
@@ -33,6 +33,7 @@ const persistedMessageSchema = z.object({
name: z.string().min(1),
mimeType: z.string().min(1),
sizeBytes: z.number().int().min(1),
previewUrl: z.string().min(1).optional(),
}),
)
.optional(),
@@ -103,12 +104,18 @@ export const persistedStateV7Schema = persistedStateBodySchema.extend({
version: z.literal(7).optional(),
});
export const persistedStateV8Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(8).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(),
});
const persistedStateSchema = z.union([
persistedStateV8Schema,
persistedStateV7Schema,
persistedStateV6Schema,
persistedStateV5Schema,
@@ -252,7 +259,14 @@ function hydrateThread(
activeTerminalGroupId,
session: null,
messages: thread.messages.map((message) => {
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
const hydratedAttachments = message.attachments?.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
...(attachment.previewUrl ? { previewUrl: attachment.previewUrl } : {}),
}));
return {
id: message.id,
role: message.role,
@@ -312,9 +326,9 @@ export function hydratePersistedState(
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV7Schema> {
): z.infer<typeof persistedStateV8Schema> {
return {
version: 7,
version: 8,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
@@ -340,6 +354,9 @@ export function toPersistedState(
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
...(attachment.previewUrl && /^data:image\//i.test(attachment.previewUrl)
? { previewUrl: attachment.previewUrl }
: {}),
})),
}
: {}),
+110 -19
View File
@@ -5,13 +5,19 @@ import {
createElement,
useContext,
useEffect,
useRef,
useReducer,
useState,
} from "react";
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import {
type PersistedStoreSnapshot,
hydratePersistedState,
toPersistedState,
} from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession, readNativeApi } from "./session-logic";
import {
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
@@ -25,6 +31,7 @@ import {
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "HYDRATE_PERSISTED_STATE"; snapshot: PersistedStoreSnapshot }
| { type: "ADD_PROJECT"; project: Project }
| { type: "SYNC_PROJECTS"; projects: Project[] }
| { type: "TOGGLE_PROJECT"; projectId: string }
@@ -75,8 +82,10 @@ export interface AppState {
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_STATE_PRIMARY_KEY = "t3code:renderer-state:v8";
const LEGACY_PERSISTED_STATE_KEYS = [
LEGACY_PERSISTED_STATE_PRIMARY_KEY,
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
@@ -97,35 +106,30 @@ const initialState: AppState = {
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
function readLegacyPersistedStateFromLocalStorage(): PersistedStoreSnapshot | null {
if (typeof window === "undefined") return null;
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const rawCurrent = window.localStorage.getItem(LEGACY_PERSISTED_STATE_PRIMARY_KEY);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState;
if (!raw) return null;
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false };
return hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
} catch {
return initialState;
return null;
}
}
function persistState(state: AppState): void {
function clearLegacyPersistedStateFromLocalStorage(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
// Ignore storage errors.
}
}
@@ -409,6 +413,16 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "HYDRATE_PERSISTED_STATE":
return {
...state,
projects: action.snapshot.projects,
threads: action.snapshot.threads,
activeThreadId: action.snapshot.activeThreadId,
runtimeMode: action.snapshot.runtimeMode,
diffOpen: false,
};
case "ADD_PROJECT":
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
return state;
@@ -842,11 +856,88 @@ const StoreContext = createContext<{
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
const [state, dispatch] = useReducer(reducer, initialState);
const [persistenceReady, setPersistenceReady] = useState(false);
const bootstrapStartedRef = useRef(false);
const lastPersistedStateJsonRef = useRef<string | null>(null);
useEffect(() => {
persistState(state);
}, [state]);
if (bootstrapStartedRef.current) return;
bootstrapStartedRef.current = true;
let disposed = false;
const api = readNativeApi();
if (!api) {
setPersistenceReady(true);
return;
}
void (async () => {
try {
const serverSnapshot = await api.server.getRendererState();
if (disposed) return;
const hydratedFromServer = serverSnapshot
? hydratePersistedState(serverSnapshot.stateJson, false)
: null;
if (hydratedFromServer) {
lastPersistedStateJsonRef.current = serverSnapshot?.stateJson ?? null;
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedFromServer });
clearLegacyPersistedStateFromLocalStorage();
return;
}
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
if (!hydratedLegacy) return;
const migratedStateJson = JSON.stringify(toPersistedState(hydratedLegacy));
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
try {
await api.server.setRendererState({ stateJson: migratedStateJson });
if (!disposed) {
lastPersistedStateJsonRef.current = migratedStateJson;
clearLegacyPersistedStateFromLocalStorage();
}
} catch {
// Keep running with hydrated legacy state. Persist effect will retry.
}
} catch {
if (disposed) return;
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
if (hydratedLegacy) {
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
}
} finally {
if (!disposed) {
setPersistenceReady(true);
}
}
})();
return () => {
disposed = true;
};
}, [dispatch]);
useEffect(() => {
if (!persistenceReady) return;
const api = readNativeApi();
if (!api) return;
const stateJson = JSON.stringify(toPersistedState(state));
if (lastPersistedStateJsonRef.current === stateJson) return;
const persistTimer = window.setTimeout(() => {
void api.server
.setRendererState({ stateJson })
.then(() => {
lastPersistedStateJsonRef.current = stateJson;
})
.catch(() => undefined);
}, 150);
return () => {
window.clearTimeout(persistTimer);
};
}, [persistenceReady, state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
@@ -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
View File
@@ -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
-50
View File
@@ -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"));
});
});
-164
View File
@@ -1,164 +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;
}
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}`;
}
+2 -1
View File
@@ -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) =>
@@ -142,6 +141,8 @@ export function createWsNativeApi(): NativeApi {
},
server: {
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
getRendererState: () => transport.request(WS_METHODS.serverGetRendererState),
setRendererState: (input) => transport.request(WS_METHODS.serverSetRendererState, input),
},
};
+1 -1
View File
@@ -20,7 +20,7 @@
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"fmt": "oxfmt",
"build:contracts": "turbo run build --filter=@t3tools/contracts",
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo"
},
"devDependencies": {
"oxfmt": "^0.28.0",
+1
View File
@@ -7,5 +7,6 @@ export * from "./model";
export * from "./ws";
export * from "./keybindings";
export * from "./server";
export * from "./rendererState";
export * from "./project";
export * from "./git";
+3 -3
View File
@@ -29,11 +29,10 @@ import type {
ProjectAddInput,
ProjectAddResult,
ProjectListResult,
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
ProjectRemoveInput,
} from "./project";
import type { ServerConfig } from "./server";
import type { RendererStateSetInput, RendererStateSnapshot } from "./rendererState";
import type {
TerminalClearInput,
TerminalCloseInput,
@@ -92,7 +91,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>;
@@ -119,5 +117,7 @@ export interface NativeApi {
};
server: {
getConfig: () => Promise<ServerConfig>;
getRendererState: () => Promise<RendererStateSnapshot | null>;
setRendererState: (input: RendererStateSetInput) => Promise<void>;
};
}
-36
View File
@@ -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");
});
});
-25
View File
@@ -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>;
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { rendererStateSetInputSchema, rendererStateSnapshotSchema } from "./rendererState";
describe("rendererState contracts", () => {
it("parses renderer state snapshot", () => {
const parsed = rendererStateSnapshotSchema.parse({
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
updatedAt: "2026-02-18T10:00:00.000Z",
});
expect(parsed.updatedAt).toBe("2026-02-18T10:00:00.000Z");
});
it("requires non-empty stateJson for set input", () => {
expect(() => rendererStateSetInputSchema.parse({ stateJson: "" })).toThrow();
});
});
+15
View File
@@ -0,0 +1,15 @@
import { z } from "zod";
export const RENDERER_STATE_MAX_JSON_CHARS = 25_000_000;
export const rendererStateSnapshotSchema = z.object({
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
updatedAt: z.string().datetime(),
});
export const rendererStateSetInputSchema = z.object({
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
});
export type RendererStateSnapshot = z.infer<typeof rendererStateSnapshotSchema>;
export type RendererStateSetInput = z.input<typeof rendererStateSetInputSchema>;
+2 -1
View File
@@ -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",
@@ -41,6 +40,8 @@ export const WS_METHODS = {
// Server meta
serverGetConfig: "server.getConfig",
serverGetRendererState: "server.getRendererState",
serverSetRendererState: "server.setRendererState",
} as const;
// ── Push Event Channels ──────────────────────────────────────────────
-153
View File
@@ -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);
});