Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d976b8bf7 | ||
|
|
0c50a2d8e1 | ||
|
|
f64c26e708 | ||
|
|
6d8d39a5d1 | ||
|
|
afdfe16931 |
No files matched your search
Vendored
+11
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, 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");
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
expect(paths).toContain("src");
|
||||
expect(paths).toContain("src/components");
|
||||
expect(paths).toContain("src/components/Composer.tsx");
|
||||
expect(paths).toContain("README.md");
|
||||
expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false);
|
||||
expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false);
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
|
||||
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 });
|
||||
|
||||
expect(result.entries.length).toBeGreaterThan(0);
|
||||
expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true);
|
||||
expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,186 +0,0 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
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",
|
||||
"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;
|
||||
}
|
||||
|
||||
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
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 };
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
for (const directoryEntry of directoryEntries) {
|
||||
const { relativeDir, dirents } = directoryEntry;
|
||||
if (!dirents) {
|
||||
continue;
|
||||
}
|
||||
|
||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
||||
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,
|
||||
);
|
||||
const entry: ProjectEntry = {
|
||||
path: relativePath,
|
||||
kind: dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(relativePath),
|
||||
};
|
||||
entries.push(entry);
|
||||
|
||||
if (dirent.isDirectory()) {
|
||||
pendingDirectories.push(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,
|
||||
};
|
||||
}
|
||||
@@ -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-");
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -86,17 +87,22 @@ export default function BranchToolbar({
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: current.name,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
EDITORS,
|
||||
type EditorId,
|
||||
type ProjectEntry,
|
||||
ModelSlug,
|
||||
type NativeApi,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
@@ -32,12 +31,6 @@ import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { buildBootstrapInput } from "../historyBootstrap";
|
||||
import {
|
||||
buildPromptInput,
|
||||
buildUserVisiblePrompt,
|
||||
detectComposerTrigger,
|
||||
replaceTextRange,
|
||||
} from "../composer-logic";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_REASONING,
|
||||
@@ -76,8 +69,6 @@ import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
CircleAlertIcon,
|
||||
FileIcon,
|
||||
FolderIcon,
|
||||
FolderClosedIcon,
|
||||
InfoIcon,
|
||||
LockIcon,
|
||||
@@ -92,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, CommandPanel } from "./ui/command";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -113,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 {
|
||||
@@ -137,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();
|
||||
@@ -185,7 +146,6 @@ export default function ChatView() {
|
||||
gitCreateWorktreeMutationOptions({ api, queryClient }),
|
||||
);
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [taggedPaths, setTaggedPaths] = useState<string[]>([]);
|
||||
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
@@ -198,8 +158,6 @@ 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 [composerMenuIndex, setComposerMenuIndex] = useState(0);
|
||||
const messagesScrollRef = useRef<HTMLDivElement>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const shouldAutoScrollRef = useRef(true);
|
||||
@@ -310,79 +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 branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd));
|
||||
const keybindingsQuery = useQuery({
|
||||
...serverConfigQueryOptions(api),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const workspaceEntriesQuery = useQuery({
|
||||
queryKey: [
|
||||
"composer-workspace-entries",
|
||||
gitCwd,
|
||||
composerTrigger?.kind === "path" ? composerTrigger.query : "",
|
||||
],
|
||||
enabled: Boolean(api && gitCwd && composerTrigger?.kind === "path"),
|
||||
staleTime: 15_000,
|
||||
queryFn: async () => {
|
||||
if (!api || !gitCwd || composerTrigger?.kind !== "path") {
|
||||
return { entries: [], truncated: false };
|
||||
}
|
||||
return api.projects.searchEntries({
|
||||
cwd: gitCwd,
|
||||
query: composerTrigger.query,
|
||||
limit: 80,
|
||||
});
|
||||
},
|
||||
});
|
||||
const composerMenuItems = useMemo<ComposerCommandItem[]>(() => {
|
||||
if (!composerTrigger) return [];
|
||||
if (composerTrigger.kind === "path") {
|
||||
return (workspaceEntriesQuery.data?.entries ?? [])
|
||||
.filter((entry) => !taggedPaths.includes(entry.path))
|
||||
.map((entry) => ({
|
||||
id: `path:${entry.kind}:${entry.path}`,
|
||||
type: "path",
|
||||
path: entry.path,
|
||||
pathKind: entry.kind,
|
||||
label: basenameOfPath(entry.path),
|
||||
description: entry.parentPath ?? (entry.kind === "directory" ? "Folder" : "File"),
|
||||
}));
|
||||
}
|
||||
|
||||
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 MODEL_OPTIONS.filter(({ slug, name }) => {
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return slug.toLowerCase().includes(query) || name.toLowerCase().includes(query);
|
||||
}).map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model",
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, taggedPaths, workspaceEntriesQuery.data?.entries]);
|
||||
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;
|
||||
@@ -546,10 +436,6 @@ export default function ChatView() {
|
||||
setExpandedWorkGroups({});
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
setComposerMenuIndex(0);
|
||||
}, [composerTrigger?.kind, composerTrigger?.query, composerMenuItems.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || activeThread.terminalOpen) return;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
@@ -569,9 +455,6 @@ export default function ChatView() {
|
||||
revokePreviewUrls(existing);
|
||||
return [];
|
||||
});
|
||||
setTaggedPaths([]);
|
||||
setComposerCursor(0);
|
||||
setComposerMenuIndex(0);
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
setExpandedImage(null);
|
||||
@@ -888,10 +771,7 @@ export default function ChatView() {
|
||||
e.preventDefault();
|
||||
if (!api || !activeThread || isSending || isConnecting) return;
|
||||
const trimmed = prompt.trim();
|
||||
const taggedPathsSnapshot = [...taggedPaths];
|
||||
const promptForModel = buildPromptInput(trimmed, taggedPathsSnapshot);
|
||||
const userVisiblePrompt = buildUserVisiblePrompt(trimmed, taggedPathsSnapshot);
|
||||
if (!promptForModel && composerImages.length === 0) return;
|
||||
if (!trimmed && composerImages.length === 0) return;
|
||||
if (!activeProject) return;
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
|
||||
@@ -931,7 +811,6 @@ export default function ChatView() {
|
||||
if (activeThread.messages.length === 0) {
|
||||
const titleSeed =
|
||||
trimmed ||
|
||||
(taggedPathsSnapshot.length > 0 ? `Paths: ${taggedPathsSnapshot[0]}` : "") ||
|
||||
(composerImagesSnapshot.length > 0
|
||||
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
|
||||
: "New thread");
|
||||
@@ -944,55 +823,59 @@ 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: userVisiblePrompt,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
setTaggedPaths([]);
|
||||
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");
|
||||
const latestPromptForBootstrap = promptForModel || IMAGE_ONLY_BOOTSTRAP_PROMPT;
|
||||
const latestPromptForBootstrap = trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT;
|
||||
const input = shouldBootstrap
|
||||
? buildBootstrapInput(
|
||||
previousMessages,
|
||||
latestPromptForBootstrap,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
).text
|
||||
: promptForModel || undefined;
|
||||
: trimmed || undefined;
|
||||
await api.providers.sendTurn({
|
||||
sessionId: sessionInfo.sessionId,
|
||||
...(input ? { input } : {}),
|
||||
@@ -1071,74 +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") {
|
||||
setTaggedPaths((existing) =>
|
||||
existing.includes(item.path) ? existing : [...existing, item.path],
|
||||
);
|
||||
applyPromptReplacement(composerTrigger.rangeStart, composerTrigger.rangeEnd, "");
|
||||
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 onRemoveTaggedPath = useCallback((pathToRemove: string) => {
|
||||
setTaggedPaths((existing) => existing.filter((entry) => entry !== pathToRemove));
|
||||
}, []);
|
||||
|
||||
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();
|
||||
setComposerMenuIndex((existing) => Math.min(existing + 1, composerMenuItems.length - 1));
|
||||
return;
|
||||
}
|
||||
if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setComposerMenuIndex((existing) => Math.max(existing - 1, 0));
|
||||
return;
|
||||
}
|
||||
if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
|
||||
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);
|
||||
@@ -1234,81 +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">
|
||||
<Command>
|
||||
<CommandPanel className="rounded-xl border border-border/80 bg-popover/96 backdrop-blur-xs">
|
||||
<CommandList className="max-h-64">
|
||||
{composerMenuItems.map((item, index) => (
|
||||
<CommandItem
|
||||
key={item.id}
|
||||
value={item.id}
|
||||
className={cn(
|
||||
"gap-2",
|
||||
index === composerMenuIndex && "bg-accent text-accent-foreground",
|
||||
)}
|
||||
onMouseEnter={() => setComposerMenuIndex(index)}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
onSelectComposerItem(item);
|
||||
}}
|
||||
>
|
||||
{item.type === "path" ? (
|
||||
item.pathKind === "directory" ? (
|
||||
<FolderIcon className="size-4 text-muted-foreground/80" />
|
||||
) : (
|
||||
<FileIcon className="size-4 text-muted-foreground/80" />
|
||||
)
|
||||
) : null}
|
||||
{item.type === "slash-command" ? (
|
||||
<CursorIcon className="size-4 text-muted-foreground/80" />
|
||||
) : null}
|
||||
{item.type === "model" ? (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
model
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="truncate">{item.label}</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">
|
||||
{item.description}
|
||||
</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandList>
|
||||
{composerMenuItems.length === 0 && (
|
||||
<p className="px-3 py-2 text-muted-foreground/70 text-xs">
|
||||
{workspaceEntriesQuery.isLoading
|
||||
? "Searching workspace files..."
|
||||
: composerTrigger?.kind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command."}
|
||||
</p>
|
||||
)}
|
||||
</CommandPanel>
|
||||
</Command>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{taggedPaths.length > 0 && (
|
||||
<div className="mb-3 flex flex-wrap gap-1.5">
|
||||
{taggedPaths.map((taggedPath) => (
|
||||
<button
|
||||
key={taggedPath}
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1 rounded-md border border-border/80 bg-secondary/65 px-2 py-1 text-[11px] text-foreground/85 transition-colors hover:bg-secondary"
|
||||
onClick={() => onRemoveTaggedPath(taggedPath)}
|
||||
aria-label={`Remove ${taggedPath}`}
|
||||
title={taggedPath}
|
||||
>
|
||||
<span className="text-muted-foreground/70">@</span>
|
||||
<span className="max-w-64 truncate">{taggedPath}</span>
|
||||
<XIcon className="size-3 text-muted-foreground/70" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="px-4 pt-4 pb-2">
|
||||
{composerImages.length > 0 && (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{composerImages.map((image) => (
|
||||
@@ -1348,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}
|
||||
/>
|
||||
@@ -1442,9 +1164,7 @@ export default function ChatView() {
|
||||
type="submit"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
|
||||
disabled={
|
||||
isSending ||
|
||||
isConnecting ||
|
||||
(!prompt.trim() && composerImages.length === 0 && taggedPaths.length === 0)
|
||||
isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
|
||||
}
|
||||
aria-label={
|
||||
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
+2
-1
@@ -19,7 +19,8 @@
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts"
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
|
||||
@@ -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";
|
||||
@@ -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>;
|
||||
};
|
||||
}
|
||||
@@ -3,8 +3,6 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
projectAddInputSchema,
|
||||
projectAddResultSchema,
|
||||
projectSearchEntriesInputSchema,
|
||||
projectSearchEntriesResultSchema,
|
||||
projectListResultSchema,
|
||||
projectRemoveInputSchema,
|
||||
} from "./project";
|
||||
@@ -48,38 +46,4 @@ describe("project contracts", () => {
|
||||
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
|
||||
expect(parsed.id).toBe("project-1");
|
||||
});
|
||||
|
||||
it("parses workspace entry search input with defaults", () => {
|
||||
const parsed = projectSearchEntriesInputSchema.parse({
|
||||
cwd: " /tmp/project ",
|
||||
query: " src ",
|
||||
});
|
||||
|
||||
expect(parsed).toEqual({
|
||||
cwd: "/tmp/project",
|
||||
query: "src",
|
||||
limit: 80,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses workspace entry search result", () => {
|
||||
const parsed = projectSearchEntriesResultSchema.parse({
|
||||
entries: [
|
||||
{
|
||||
path: "src/components",
|
||||
kind: "directory",
|
||||
parentPath: "src",
|
||||
},
|
||||
{
|
||||
path: "src/components/Button.tsx",
|
||||
kind: "file",
|
||||
parentPath: "src/components",
|
||||
},
|
||||
],
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
expect(parsed.entries).toHaveLength(2);
|
||||
expect(parsed.entries[0]?.kind).toBe("directory");
|
||||
});
|
||||
});
|
||||
@@ -23,33 +23,8 @@ export const projectRemoveInputSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
});
|
||||
|
||||
export const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
|
||||
|
||||
export const projectSearchEntriesInputSchema = z.object({
|
||||
cwd: z.string().trim().min(1),
|
||||
query: z.string().trim().max(256).default(""),
|
||||
limit: z.number().int().min(1).max(PROJECT_SEARCH_ENTRIES_MAX_LIMIT).default(80),
|
||||
});
|
||||
|
||||
export const projectEntryKindSchema = z.enum(["file", "directory"]);
|
||||
|
||||
export const projectEntrySchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: projectEntryKindSchema,
|
||||
parentPath: z.string().optional(),
|
||||
});
|
||||
|
||||
export const projectSearchEntriesResultSchema = z.object({
|
||||
entries: z.array(projectEntrySchema),
|
||||
truncated: z.boolean(),
|
||||
});
|
||||
|
||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
||||
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
||||
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
|
||||
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
|
||||
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
|
||||
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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>;
|
||||
@@ -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 ──────────────────────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user