Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cfabf9bd03 | ||
|
|
dcc6d9d9ae | ||
|
|
0a4c07051a |
No files matched your search
Vendored
-11
@@ -1,11 +0,0 @@
|
||||
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,7 +118,6 @@ async function main() {
|
||||
port,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
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 });
|
||||
});
|
||||
});
|
||||
@@ -1,174 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -249,7 +249,6 @@ 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),
|
||||
@@ -343,71 +342,6 @@ 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");
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
} from "./git";
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { RendererStateStore } from "./rendererStateStore";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -53,14 +52,12 @@ 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;
|
||||
}
|
||||
|
||||
@@ -77,21 +74,18 @@ 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 resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
|
||||
const projectRegistry = providedRegistry ?? new ProjectRegistry(resolvedStateDir);
|
||||
const rendererStateStore = providedRendererStateStore ?? new RendererStateStore(resolvedStateDir);
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
@@ -423,13 +417,6 @@ 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}`);
|
||||
}
|
||||
@@ -459,7 +446,6 @@ export function createServer(options: ServerOptions) {
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
terminalManager.dispose();
|
||||
await rendererStateStore.close();
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: string | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: GitBranch[] | undefined;
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -87,22 +86,17 @@ export default function BranchToolbar({
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
branch: current.name,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
|
||||
@@ -51,7 +51,7 @@ import {
|
||||
} from "../session-logic";
|
||||
import { isScrollContainerNearBottom } from "../chat-scroll";
|
||||
import { useStore } from "../store";
|
||||
import type { ChatImageAttachment } from "../types";
|
||||
import { MAX_THREAD_TERMINAL_COUNT, type ChatImageAttachment } from "../types";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import GitActionsControl from "./GitActionsControl";
|
||||
import {
|
||||
@@ -294,6 +294,8 @@ export default function ChatView() {
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
const hasReachedTerminalLimit =
|
||||
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
@@ -322,23 +324,23 @@ export default function ChatView() {
|
||||
});
|
||||
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
|
||||
const splitTerminal = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
if (!activeThreadId || hasReachedTerminalLimit) return;
|
||||
dispatch({
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId: `terminal-${crypto.randomUUID()}`,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
}, [activeThreadId, dispatch]);
|
||||
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
|
||||
const createNewTerminal = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
if (!activeThreadId || hasReachedTerminalLimit) return;
|
||||
dispatch({
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId: `terminal-${crypto.randomUUID()}`,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
}, [activeThreadId, dispatch]);
|
||||
}, [activeThreadId, dispatch, hasReachedTerminalLimit]);
|
||||
const activateTerminal = useCallback(
|
||||
(terminalId: string) => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -823,48 +825,41 @@ 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([]);
|
||||
|
||||
const sessionInfo = await ensureSession(sessionCwd);
|
||||
if (!sessionInfo) return;
|
||||
|
||||
setIsSending(true);
|
||||
try {
|
||||
const preparedImages = await Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => {
|
||||
const attachment: ProviderSendTurnAttachmentInput = {
|
||||
const turnAttachments = await Promise.all(
|
||||
composerImagesSnapshot.map(
|
||||
async (image): Promise<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");
|
||||
@@ -976,7 +971,7 @@ export default function ChatView() {
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-background text-muted-foreground/40">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
|
||||
{isElectron && (
|
||||
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
@@ -992,7 +987,7 @@ export default function ChatView() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-background">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
@@ -1311,11 +1306,13 @@ const ChatHeader = memo(function ChatHeader({
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="text-sm font-medium text-foreground">{activeThreadTitle}</h2>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<h2 className="truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="shrink-0 flex items-center gap-3">
|
||||
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
|
||||
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
|
||||
<Button
|
||||
|
||||
@@ -22,6 +22,7 @@ import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keyb
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
|
||||
@@ -581,6 +582,7 @@ export default function ThreadTerminalDrawer({
|
||||
const showGroupHeaders =
|
||||
resolvedTerminalGroups.length > 1 ||
|
||||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
||||
const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
||||
const terminalLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -588,9 +590,23 @@ export default function ThreadTerminalDrawer({
|
||||
),
|
||||
[normalizedTerminalIds],
|
||||
);
|
||||
const splitTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal");
|
||||
const newTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: (newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal");
|
||||
const closeTerminalActionLabel = closeShortcutLabel
|
||||
? `Close Terminal (${closeShortcutLabel})`
|
||||
: "Close Terminal";
|
||||
const onSplitTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onSplitTerminal();
|
||||
}, [hasReachedTerminalLimit, onSplitTerminal]);
|
||||
const onNewTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onNewTerminal();
|
||||
}, [hasReachedTerminalLimit, onNewTerminal]);
|
||||
|
||||
useEffect(() => {
|
||||
onHeightChangeRef.current = onHeightChange;
|
||||
@@ -685,7 +701,7 @@ export default function ThreadTerminalDrawer({
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
@@ -700,19 +716,25 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onSplitTerminal}
|
||||
label={
|
||||
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
|
||||
}
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminal}
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -733,7 +755,7 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="min-w-0 flex-1">
|
||||
{isSplitView ? (
|
||||
<div
|
||||
className="grid h-full w-full gap-0 overflow-x-auto"
|
||||
className="grid h-full w-full min-w-0 gap-0 overflow-x-auto"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
|
||||
}}
|
||||
@@ -787,20 +809,24 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
|
||||
<div className="inline-flex h-full items-stretch">
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onSplitTerminal}
|
||||
label={
|
||||
splitShortcutLabel
|
||||
? `Split Terminal (${splitShortcutLabel})`
|
||||
: "Split Terminal"
|
||||
}
|
||||
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onSplitTerminalAction}
|
||||
label={splitTerminalActionLabel}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onNewTerminal}
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
|
||||
@@ -257,65 +257,10 @@ 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 v8 payload and strips non-persisted thread fields", () => {
|
||||
it("writes v7 payload and strips non-persisted thread fields", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
@@ -375,7 +320,7 @@ describe("toPersistedState", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(8);
|
||||
expect(persisted.version).toBe(7);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
@@ -422,69 +367,4 @@ 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,7 +33,6 @@ 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(),
|
||||
@@ -104,18 +103,12 @@ 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,
|
||||
@@ -259,14 +252,7 @@ function hydrateThread(
|
||||
activeTerminalGroupId,
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
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 } : {}),
|
||||
}));
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
@@ -326,9 +312,9 @@ export function hydratePersistedState(
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV8Schema> {
|
||||
): z.infer<typeof persistedStateV7Schema> {
|
||||
return {
|
||||
version: 8,
|
||||
version: 7,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
@@ -354,9 +340,6 @@ export function toPersistedState(
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
...(attachment.previewUrl && /^data:image\//i.test(attachment.previewUrl)
|
||||
? { previewUrl: attachment.previewUrl }
|
||||
: {}),
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -2,7 +2,11 @@ import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/con
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
} from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||
@@ -255,6 +259,70 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("caps split terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
});
|
||||
|
||||
it("caps new terminals at four per thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
||||
activeTerminalId: "term-4",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
{ id: "group-term-4", terminalIds: ["term-4"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-4",
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-5",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
"term-2",
|
||||
"term-3",
|
||||
"term-4",
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-4");
|
||||
});
|
||||
|
||||
it("closes a terminal and keeps grouped layout coherent", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
|
||||
+40
-111
@@ -5,23 +5,18 @@ import {
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useReducer,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
type PersistedStoreSnapshot,
|
||||
hydratePersistedState,
|
||||
toPersistedState,
|
||||
} from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession, readNativeApi } from "./session-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
@@ -31,7 +26,6 @@ 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 }
|
||||
@@ -82,10 +76,8 @@ export interface AppState {
|
||||
diffOpen: boolean;
|
||||
}
|
||||
|
||||
const LEGACY_PERSISTED_STATE_PRIMARY_KEY = "t3code:renderer-state:v8";
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
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",
|
||||
@@ -106,30 +98,40 @@ const initialState: AppState = {
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readLegacyPersistedStateFromLocalStorage(): PersistedStoreSnapshot | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const rawCurrent = window.localStorage.getItem(LEGACY_PERSISTED_STATE_PRIMARY_KEY);
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_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 null;
|
||||
if (!raw) return initialState;
|
||||
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
|
||||
return hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
|
||||
const activeThreadId = threads.some((thread) => thread.id === hydrated.activeThreadId)
|
||||
? hydrated.activeThreadId
|
||||
: (threads[0]?.id ?? null);
|
||||
|
||||
return { ...hydrated, threads, activeThreadId, diffOpen: false };
|
||||
} catch {
|
||||
return null;
|
||||
return initialState;
|
||||
}
|
||||
}
|
||||
|
||||
function clearLegacyPersistedStateFromLocalStorage(): void {
|
||||
function persistState(state: AppState): 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 storage errors.
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +145,7 @@ function updateThread(
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)];
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
@@ -413,16 +415,6 @@ 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;
|
||||
@@ -564,6 +556,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
@@ -630,6 +629,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
@@ -856,88 +862,11 @@ const StoreContext = createContext<{
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const [persistenceReady, setPersistenceReady] = useState(false);
|
||||
const bootstrapStartedRef = useRef(false);
|
||||
const lastPersistedStateJsonRef = useRef<string | null>(null);
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
|
||||
useEffect(() => {
|
||||
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]);
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ export type RuntimeMode = "approval-required" | "full-access";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
|
||||
export const DEFAULT_THREAD_TERMINAL_ID = "default";
|
||||
export const MAX_THREAD_TERMINAL_COUNT = 4;
|
||||
|
||||
export interface ThreadTerminalGroup {
|
||||
id: string;
|
||||
|
||||
@@ -141,8 +141,6 @@ 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
-2
@@ -19,8 +19,7 @@
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo"
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
|
||||
@@ -7,6 +7,5 @@ export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./rendererState";
|
||||
export * from "./project";
|
||||
export * from "./git";
|
||||
@@ -32,7 +32,6 @@ import type {
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
import type { RendererStateSetInput, RendererStateSnapshot } from "./rendererState";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -117,7 +116,5 @@ export interface NativeApi {
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
getRendererState: () => Promise<RendererStateSnapshot | null>;
|
||||
setRendererState: (input: RendererStateSetInput) => Promise<void>;
|
||||
};
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
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>;
|
||||
@@ -40,8 +40,6 @@ 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