Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
707889950d | ||
|
|
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;
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -32,6 +32,7 @@ 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",
|
||||
@@ -52,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;
|
||||
}
|
||||
|
||||
@@ -74,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");
|
||||
@@ -417,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}`);
|
||||
}
|
||||
@@ -446,6 +459,7 @@ export function createServer(options: ServerOptions) {
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
terminalManager.dispose();
|
||||
await rendererStateStore.close();
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@pierre/diffs": "^1.0.11",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
|
||||
+3
-14
@@ -1,7 +1,8 @@
|
||||
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
|
||||
import { Suspense, lazy, useEffect, useRef } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import ChatView from "./components/ChatView";
|
||||
import DiffPanel from "./components/DiffPanel";
|
||||
import Sidebar from "./components/Sidebar";
|
||||
import { isElectron } from "./env";
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
@@ -12,8 +13,6 @@ import { useNativeApi } from "./hooks/useNativeApi";
|
||||
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
|
||||
import { invalidateGitQueries } from "./lib/gitReactQuery";
|
||||
|
||||
const DiffPanel = lazy(() => import("./components/DiffPanel"));
|
||||
|
||||
function EventRouter() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
@@ -194,17 +193,7 @@ function Layout() {
|
||||
<DesktopProjectBootstrap />
|
||||
<Sidebar />
|
||||
<ChatView />
|
||||
{state.diffOpen && (
|
||||
<Suspense
|
||||
fallback={
|
||||
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</aside>
|
||||
}
|
||||
>
|
||||
<DiffPanel />
|
||||
</Suspense>
|
||||
)}
|
||||
{state.diffOpen && <DiffPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -42,9 +42,7 @@ import {
|
||||
import {
|
||||
derivePendingApprovals,
|
||||
derivePhase,
|
||||
deriveTurnDiffSummaries,
|
||||
deriveTimelineEntries,
|
||||
type TurnDiffSummary,
|
||||
type PendingApproval,
|
||||
deriveWorkLogEntries,
|
||||
formatDuration,
|
||||
@@ -204,18 +202,6 @@ export default function ChatView() {
|
||||
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
|
||||
[activeThread?.messages, workLogEntries],
|
||||
);
|
||||
const turnDiffSummaries = useMemo(
|
||||
() => deriveTurnDiffSummaries(activeThread?.events ?? []),
|
||||
[activeThread?.events],
|
||||
);
|
||||
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
|
||||
const byMessageId = new Map<string, TurnDiffSummary>();
|
||||
for (const summary of turnDiffSummaries) {
|
||||
if (!summary.assistantMessageId) continue;
|
||||
byMessageId.set(summary.assistantMessageId, summary);
|
||||
}
|
||||
return byMessageId;
|
||||
}, [turnDiffSummaries]);
|
||||
const completionSummary = useMemo(() => {
|
||||
if (!activeThread?.latestTurnStartedAt) return null;
|
||||
if (!activeThread.latestTurnCompletedAt) return null;
|
||||
@@ -837,41 +823,48 @@ export default function ChatView() {
|
||||
}
|
||||
|
||||
setThreadError(activeThread.id, null);
|
||||
const messageAttachments: ChatImageAttachment[] = composerImagesSnapshot.map((image) => ({
|
||||
type: "image",
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
|
||||
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");
|
||||
@@ -977,36 +970,8 @@ export default function ChatView() {
|
||||
setExpandedImage(image);
|
||||
}, []);
|
||||
const onToggleDiff = useCallback(() => {
|
||||
if (state.diffOpen) {
|
||||
dispatch({ type: "CLOSE_DIFF" });
|
||||
return;
|
||||
}
|
||||
|
||||
const latestSummary = turnDiffSummaries[0];
|
||||
if (!activeThread || !latestSummary) {
|
||||
dispatch({ type: "TOGGLE_DIFF" });
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: "OPEN_DIFF",
|
||||
threadId: activeThread.id,
|
||||
turnId: latestSummary.turnId,
|
||||
...(latestSummary.files[0]?.path ? { filePath: latestSummary.files[0].path } : {}),
|
||||
});
|
||||
}, [activeThread, dispatch, state.diffOpen, turnDiffSummaries]);
|
||||
const onOpenTurnDiff = useCallback(
|
||||
(turnId: string, filePath?: string) => {
|
||||
if (!activeThread) return;
|
||||
dispatch({
|
||||
type: "OPEN_DIFF",
|
||||
threadId: activeThread.id,
|
||||
turnId,
|
||||
...(filePath ? { filePath } : {}),
|
||||
});
|
||||
},
|
||||
[activeThread, dispatch],
|
||||
);
|
||||
dispatch({ type: "TOGGLE_DIFF" });
|
||||
}, [dispatch]);
|
||||
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
@@ -1064,11 +1029,9 @@ export default function ChatView() {
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
completionSummary={completionSummary}
|
||||
assistantCompletionByItemId={assistantCompletionByItemId}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
nowIso={nowIso}
|
||||
expandedWorkGroups={expandedWorkGroups}
|
||||
onToggleWorkGroup={onToggleWorkGroup}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
messagesEndRef={messagesEndRef}
|
||||
/>
|
||||
@@ -1464,11 +1427,9 @@ interface MessagesTimelineProps {
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
completionSummary: string | null;
|
||||
assistantCompletionByItemId: Map<string, string>;
|
||||
turnDiffSummaryByAssistantMessageId: Map<string, TurnDiffSummary>;
|
||||
nowIso: string;
|
||||
expandedWorkGroups: Record<string, boolean>;
|
||||
onToggleWorkGroup: (groupId: string) => void;
|
||||
onOpenTurnDiff: (turnId: string, filePath?: string) => void;
|
||||
onImageExpand: (image: ExpandedImagePreview) => void;
|
||||
messagesEndRef: RefObject<HTMLDivElement | null>;
|
||||
}
|
||||
@@ -1480,11 +1441,9 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
assistantCompletionByItemId,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
nowIso,
|
||||
expandedWorkGroups,
|
||||
onToggleWorkGroup,
|
||||
onOpenTurnDiff,
|
||||
onImageExpand,
|
||||
messagesEndRef,
|
||||
}: MessagesTimelineProps) {
|
||||
@@ -1644,39 +1603,6 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
(timelineEntry.message.streaming ? "" : "(empty response)")
|
||||
}
|
||||
/>
|
||||
{(() => {
|
||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id);
|
||||
if (!turnSummary) return null;
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
Changed files ({turnSummary.files.length})
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, turnSummary.files[0]?.path)}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{turnSummary.files.map((file) => (
|
||||
<button
|
||||
key={`${turnSummary.turnId}:${file.path}`}
|
||||
type="button"
|
||||
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
|
||||
>
|
||||
{file.path}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
timelineEntry.message.createdAt,
|
||||
|
||||
@@ -1,145 +1,58 @@
|
||||
import { PatchDiff } from "@pierre/diffs/react";
|
||||
import { XIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { isElectron } from "../env";
|
||||
import { deriveTurnDiffSummaries, formatTimestamp } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { Button } from "./ui/button";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export default function DiffPanel() {
|
||||
const { state, dispatch } = useStore();
|
||||
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
|
||||
const turnDiffSummaries = useMemo(
|
||||
() => deriveTurnDiffSummaries(activeThread?.events ?? []),
|
||||
[activeThread?.events],
|
||||
);
|
||||
|
||||
const canApplyStoredTarget = Boolean(activeThread && state.diffThreadId === activeThread.id);
|
||||
const selectedTurnId = canApplyStoredTarget ? state.diffTurnId : null;
|
||||
const selectedFilePath = canApplyStoredTarget ? state.diffFilePath : null;
|
||||
const selectedTurn =
|
||||
turnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ?? turnDiffSummaries[0];
|
||||
const selectedFile =
|
||||
selectedTurn?.files.find((file) => file.path === selectedFilePath) ?? selectedTurn?.files[0];
|
||||
const selectedPatch = selectedFile?.diff ?? selectedTurn?.unifiedDiff;
|
||||
|
||||
const selectTurn = (turnId: string) => {
|
||||
if (!activeThread) return;
|
||||
const turn = turnDiffSummaries.find((summary) => summary.turnId === turnId);
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
turnId,
|
||||
...(turn?.files[0]?.path ? { filePath: turn.files[0].path } : {}),
|
||||
});
|
||||
};
|
||||
|
||||
const selectFile = (filePath: string) => {
|
||||
if (!activeThread || !selectedTurn) return;
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
turnId: selectedTurn.turnId,
|
||||
filePath,
|
||||
});
|
||||
};
|
||||
const { dispatch } = useStore();
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-[560px] shrink-0 flex-col border-l border-border bg-card">
|
||||
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
|
||||
{/* Header */}
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between border-b border-border px-4",
|
||||
isElectron ? "drag-region h-[52px]" : "py-3",
|
||||
)}
|
||||
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
>
|
||||
<h3 className="text-xs font-medium text-foreground">Turn diffs</h3>
|
||||
<Button type="button" size="icon-xs" variant="ghost" onClick={() => dispatch({ type: "CLOSE_DIFF" })}>
|
||||
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{!activeThread ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : turnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turn file changes yet.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="border-b border-border px-3 py-2.5">
|
||||
<p className="mb-1.5 text-[10px] uppercase tracking-[0.12em] text-muted-foreground/60">
|
||||
Turns
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{turnDiffSummaries.map((summary, index) => (
|
||||
<button
|
||||
key={summary.turnId}
|
||||
type="button"
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
summary.turnId === selectedTurn?.turnId
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
title={summary.turnId}
|
||||
>
|
||||
<div className="text-[10px] font-medium">Turn {turnDiffSummaries.length - index}</div>
|
||||
<div className="text-[10px] opacity-70">{formatTimestamp(summary.completedAt)}</div>
|
||||
</button>
|
||||
))}
|
||||
{/* Placeholder content */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
|
||||
M
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
|
||||
</div>
|
||||
<div className="space-y-0.5 font-mono text-[11px]">
|
||||
<div className="text-red-400/60">- const oldValue = "hello";</div>
|
||||
<div className="text-emerald-400/60">+ const newValue = "world";</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex flex-1">
|
||||
<div className="w-[220px] shrink-0 border-r border-border px-2 py-2">
|
||||
<p className="mb-1.5 px-1 text-[10px] uppercase tracking-[0.12em] text-muted-foreground/60">
|
||||
Files
|
||||
</p>
|
||||
<div className="space-y-1 overflow-y-auto">
|
||||
{selectedTurn?.files.map((file) => (
|
||||
<button
|
||||
key={`${selectedTurn.turnId}:${file.path}`}
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-2 rounded-md border px-2 py-1.5 text-left font-mono text-[11px] transition-colors",
|
||||
selectedFile?.path === file.path
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/60 bg-background/60 text-muted-foreground/85 hover:border-border hover:text-foreground/90",
|
||||
)}
|
||||
onClick={() => selectFile(file.path)}
|
||||
>
|
||||
<span className="truncate">{file.path}</span>
|
||||
{file.kind && (
|
||||
<span className="rounded-sm border border-border/60 px-1 py-0.5 text-[9px] uppercase tracking-[0.08em]">
|
||||
{file.kind}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 overflow-auto px-3 py-2">
|
||||
{!canApplyStoredTarget && state.diffThreadId && (
|
||||
<p className="mb-2 text-[11px] text-muted-foreground/65">
|
||||
Showing diffs for the active thread.
|
||||
</p>
|
||||
)}
|
||||
{!selectedPatch ? (
|
||||
<div className="flex h-full items-center justify-center text-xs text-muted-foreground/70">
|
||||
No patch available for this selection.
|
||||
</div>
|
||||
) : (
|
||||
<PatchDiff patch={selectedPatch} />
|
||||
)}
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
|
||||
A
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
|
||||
Diff integration coming soon
|
||||
</p>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -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 }
|
||||
: {}),
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type WorkLogEntry,
|
||||
applyEventToMessages,
|
||||
derivePendingApprovals,
|
||||
deriveTurnDiffSummaries,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
@@ -394,109 +393,6 @@ describe("deriveWorkLogEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTurnDiffSummaries", () => {
|
||||
it("collects per-turn file changes and links them to assistant message completion", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/a.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-updated",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
threadId: "thr-1",
|
||||
turnId: "turn-1",
|
||||
diff: [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -0,0 +1 @@",
|
||||
"+created",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-msg",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "msg-1",
|
||||
type: "agentMessage",
|
||||
text: "Done",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:04.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-2-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change-2",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/unfinished.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(summaries[0]?.files[0]?.kind).toBe("modified");
|
||||
});
|
||||
});
|
||||
|
||||
describe("derivePendingApprovals", () => {
|
||||
it("returns pending command/file-change approvals", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
|
||||
@@ -99,31 +99,12 @@ export type TimelineEntry =
|
||||
entry: WorkLogEntry;
|
||||
};
|
||||
|
||||
export interface TurnDiffFileChange {
|
||||
path: string;
|
||||
kind?: string;
|
||||
diff?: string;
|
||||
}
|
||||
|
||||
export interface TurnDiffSummary {
|
||||
turnId: string;
|
||||
completedAt: string;
|
||||
status?: string;
|
||||
files: TurnDiffFileChange[];
|
||||
unifiedDiff?: string;
|
||||
assistantMessageId?: string;
|
||||
}
|
||||
|
||||
function normalizeDetail(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function asArray(value: unknown): unknown[] | undefined {
|
||||
return Array.isArray(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function approvalDetail(event: ProviderEvent): string | undefined {
|
||||
const payload = asObject(event.payload);
|
||||
const command = asString(payload?.command);
|
||||
@@ -457,217 +438,6 @@ export function deriveWorkLogEntries(
|
||||
return entries;
|
||||
}
|
||||
|
||||
interface MutableTurnDiffFileChange {
|
||||
path: string;
|
||||
kind: string | undefined;
|
||||
diff: string | undefined;
|
||||
}
|
||||
|
||||
interface MutableTurnDiffSummary {
|
||||
turnId: string;
|
||||
completedAt: string | undefined;
|
||||
status: string | undefined;
|
||||
unifiedDiff: string | undefined;
|
||||
assistantMessageId: string | undefined;
|
||||
filesByPath: Map<string, MutableTurnDiffFileChange>;
|
||||
}
|
||||
|
||||
function parsePathFromDiff(diff: string): string | undefined {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/(.+)$/m);
|
||||
if (gitHeader && gitHeader[2]) return gitHeader[2];
|
||||
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
|
||||
if (bPath && bPath[1]) return bPath[1];
|
||||
const direct = normalized.match(/^\+\+\+ (.+)$/m);
|
||||
if (!direct || !direct[1] || direct[1] === "/dev/null") {
|
||||
return undefined;
|
||||
}
|
||||
return direct[1];
|
||||
}
|
||||
|
||||
function splitUnifiedDiffByFile(diff: string): Map<string, string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const byPath = new Map<string, string>();
|
||||
const headerMatches = [...normalized.matchAll(/^diff --git a\/(.+) b\/(.+)$/gm)];
|
||||
|
||||
if (headerMatches.length === 0) {
|
||||
const path = parsePathFromDiff(normalized);
|
||||
if (path) {
|
||||
byPath.set(path, normalized.trim());
|
||||
}
|
||||
return byPath;
|
||||
}
|
||||
|
||||
for (let index = 0; index < headerMatches.length; index += 1) {
|
||||
const match = headerMatches[index];
|
||||
if (!match) continue;
|
||||
const start = match.index ?? 0;
|
||||
const nextStart = headerMatches[index + 1]?.index ?? normalized.length;
|
||||
const segment = normalized.slice(start, nextStart).trim();
|
||||
const path = match[2] ?? match[1] ?? parsePathFromDiff(segment);
|
||||
if (!path || segment.length === 0) continue;
|
||||
byPath.set(path, segment);
|
||||
}
|
||||
|
||||
return byPath;
|
||||
}
|
||||
|
||||
function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChange[] {
|
||||
if (event.method !== "item/started" && event.method !== "item/completed") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "fileChange") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const changes = asArray(item?.changes);
|
||||
if (!changes || changes.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const files: TurnDiffFileChange[] = [];
|
||||
for (const rawChange of changes) {
|
||||
const change = asObject(rawChange);
|
||||
if (!change) continue;
|
||||
const diff = normalizeDetail(asString(change.diff));
|
||||
const path = normalizeDetail(asString(change.path)) ?? (diff ? parsePathFromDiff(diff) : undefined);
|
||||
if (!path) continue;
|
||||
const kind = normalizeDetail(asString(change.kind));
|
||||
files.push({
|
||||
path,
|
||||
...(kind ? { kind } : {}),
|
||||
...(diff ? { diff } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummary[] {
|
||||
const ordered = [...events].toReversed();
|
||||
const byTurnId = new Map<string, MutableTurnDiffSummary>();
|
||||
|
||||
const ensureSummary = (turnId: string): MutableTurnDiffSummary => {
|
||||
const existing = byTurnId.get(turnId);
|
||||
if (existing) return existing;
|
||||
const next: MutableTurnDiffSummary = {
|
||||
turnId,
|
||||
completedAt: undefined,
|
||||
status: undefined,
|
||||
unifiedDiff: undefined,
|
||||
assistantMessageId: undefined,
|
||||
filesByPath: new Map(),
|
||||
};
|
||||
byTurnId.set(turnId, next);
|
||||
return next;
|
||||
};
|
||||
|
||||
for (const event of ordered) {
|
||||
const turnId = eventTurnId(event);
|
||||
if (!turnId) continue;
|
||||
const summary = ensureSummary(turnId);
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
summary.completedAt = event.createdAt;
|
||||
const turn = asObject(asObject(event.payload)?.turn);
|
||||
summary.status = normalizeDetail(asString(turn?.status));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.method === "turn/diff/updated") {
|
||||
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
|
||||
if (diff) summary.unifiedDiff ??= diff;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(asObject(event.payload)?.item);
|
||||
if (asString(item?.type) === "agentMessage") {
|
||||
const itemId = normalizeDetail(asString(item?.id));
|
||||
if (itemId) {
|
||||
summary.assistantMessageId ??= itemId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const change of parseFileChangeEntriesFromEvent(event)) {
|
||||
const existing = summary.filesByPath.get(change.path);
|
||||
if (!existing) {
|
||||
summary.filesByPath.set(change.path, {
|
||||
path: change.path,
|
||||
kind: change.kind,
|
||||
diff: change.diff,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
summary.filesByPath.set(change.path, {
|
||||
path: change.path,
|
||||
kind: change.kind ?? existing.kind,
|
||||
diff: change.diff ?? existing.diff,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const summaries: TurnDiffSummary[] = [];
|
||||
for (const summary of byTurnId.values()) {
|
||||
if (!summary.completedAt) continue;
|
||||
|
||||
const filesByPath = new Map(summary.filesByPath);
|
||||
if (summary.unifiedDiff) {
|
||||
const fileDiffs = splitUnifiedDiffByFile(summary.unifiedDiff);
|
||||
for (const [path, diff] of fileDiffs) {
|
||||
const existing = filesByPath.get(path);
|
||||
if (!existing) {
|
||||
filesByPath.set(path, { path, kind: undefined, diff });
|
||||
continue;
|
||||
}
|
||||
if (!existing.diff) {
|
||||
filesByPath.set(path, { ...existing, diff });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const files: TurnDiffFileChange[] = [];
|
||||
for (const file of Array.from(filesByPath.values()).toSorted((a, b) =>
|
||||
a.path.localeCompare(b.path),
|
||||
)) {
|
||||
const nextFile: TurnDiffFileChange = { path: file.path };
|
||||
if (file.kind) {
|
||||
nextFile.kind = file.kind;
|
||||
}
|
||||
if (file.diff) {
|
||||
nextFile.diff = file.diff;
|
||||
}
|
||||
files.push(nextFile);
|
||||
}
|
||||
|
||||
if (files.length === 0) continue;
|
||||
|
||||
summaries.push({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files,
|
||||
...(summary.unifiedDiff ? { unifiedDiff: summary.unifiedDiff } : {}),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
summaries.sort((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return b.completedAt.localeCompare(a.completedAt);
|
||||
}
|
||||
return bTime - aTime;
|
||||
});
|
||||
|
||||
return summaries;
|
||||
}
|
||||
|
||||
function toTimestamp(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
||||
|
||||
@@ -76,9 +76,6 @@ function makeState(thread: Thread): AppState {
|
||||
activeThreadId: thread.id,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -143,21 +140,6 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.terminalOpen).toBe(true);
|
||||
});
|
||||
|
||||
it("opens diff panel with an explicit turn/file target", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "OPEN_DIFF",
|
||||
threadId: "thread-local-1",
|
||||
turnId: "turn-1",
|
||||
filePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(next.diffOpen).toBe(true);
|
||||
expect(next.diffThreadId).toBe("thread-local-1");
|
||||
expect(next.diffTurnId).toBe("turn-1");
|
||||
expect(next.diffFilePath).toBe("src/app.ts");
|
||||
});
|
||||
|
||||
it("sets terminal open state per thread", () => {
|
||||
const state = makeState(makeThread({ terminalOpen: true }));
|
||||
const next = reducer(state, {
|
||||
@@ -479,9 +461,6 @@ describe("store reducer thread continuity", () => {
|
||||
activeThreadId: "thread-b",
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
@@ -538,9 +517,6 @@ describe("store reducer thread continuity", () => {
|
||||
activeThreadId: "thread-a",
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
|
||||
+107
-78
@@ -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 }
|
||||
@@ -39,19 +46,6 @@ type Action =
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "TOGGLE_DIFF" }
|
||||
| {
|
||||
type: "OPEN_DIFF";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| {
|
||||
type: "SET_DIFF_TARGET";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| { type: "CLOSE_DIFF" }
|
||||
| {
|
||||
type: "APPLY_EVENT";
|
||||
event: ProviderEvent;
|
||||
@@ -86,13 +80,12 @@ export interface AppState {
|
||||
activeThreadId: string | null;
|
||||
runtimeMode: RuntimeMode;
|
||||
diffOpen: boolean;
|
||||
diffThreadId: string | null;
|
||||
diffTurnId: string | null;
|
||||
diffFilePath: string | null;
|
||||
}
|
||||
|
||||
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",
|
||||
@@ -109,48 +102,34 @@ const initialState: AppState = {
|
||||
activeThreadId: null,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
// ── 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,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
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.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,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;
|
||||
@@ -699,26 +688,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "OPEN_DIFF":
|
||||
return {
|
||||
...state,
|
||||
diffOpen: true,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "SET_DIFF_TARGET":
|
||||
return {
|
||||
...state,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "CLOSE_DIFF":
|
||||
return { ...state, diffOpen: false };
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
@@ -871,20 +840,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
const threads = state.threads.filter((t) => t.id !== action.threadId);
|
||||
const activeThreadId =
|
||||
state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
|
||||
const shouldClearDiffTarget = state.diffThreadId === action.threadId;
|
||||
return {
|
||||
...state,
|
||||
threads,
|
||||
activeThreadId,
|
||||
...(shouldClearDiffTarget
|
||||
? {
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
return { ...state, threads, activeThreadId };
|
||||
}
|
||||
|
||||
default:
|
||||
@@ -900,11 +856,84 @@ 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 lastPersistedStateJsonRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -141,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),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -52,7 +52,6 @@
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@pierre/diffs": "^1.0.11",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
@@ -304,8 +303,6 @@
|
||||
|
||||
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-DJbQsSJUr4KSi9uU0QqOgI7PX2C+fKGZX+YDprt3vM2sC0dWZsgVTLoN2vtkNyEWJSY2mnvRFUshWXT3bmo0Ug=="],
|
||||
|
||||
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/core": "^3.0.0", "@shikijs/engine-javascript": "^3.0.0", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-j6zIEoyImQy1HfcJqbrDwP0O5I7V2VNXAaw53FqQ+SykRfaNwABeZHs9uibXO4supaXPmTx6LEH9Lffr03e1Tw=="],
|
||||
|
||||
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
||||
|
||||
"@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-0T1k9FinuBZ/t7rZ8jN6OpUKPnUjNdYHoj/cESWrQ3ZraAJ4OMm6z7QjSfCxqj8mOp9kTKc1zHK3kGz5vMu+nQ=="],
|
||||
@@ -386,22 +383,6 @@
|
||||
|
||||
"@rollup/rollup-win32-x64-msvc": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA=="],
|
||||
|
||||
"@shikijs/core": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-iAlTtSDDbJiRpvgL5ugKEATDtHdUVkqgHDm/gbD2ZS9c88mx7G1zSYjjOxp5Qa0eaW0MAQosFRmJSk354PRoQA=="],
|
||||
|
||||
"@shikijs/engine-javascript": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-jdKhfgW9CRtj3Tor0L7+yPwdG3CgP7W+ZEqSsojrMzCjD1e0IxIbwUMDDpYlVBlC08TACg4puwFGkZfLS+56Tw=="],
|
||||
|
||||
"@shikijs/engine-oniguruma": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-DyXsOG0vGtNtl7ygvabHd7Mt5EY8gCNqR9Y7Lpbbd/PbJvgWrqaKzH1JW6H6qFkuUa8aCxoiYVv8/YfFljiQxA=="],
|
||||
|
||||
"@shikijs/langs": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0" } }, "sha512-x/42TfhWmp6H00T6uwVrdTJGKgNdFbrEdhaDwSR5fd5zhQ1Q46bHq9EO61SCEWJR0HY7z2HNDMaBZp8JRmKiIA=="],
|
||||
|
||||
"@shikijs/themes": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0" } }, "sha512-o+tlOKqsr6FE4+mYJG08tfCFDS+3CG20HbldXeVoyP+cYSUxDhrFf3GPjE60U55iOkkjbpY2uC3It/eeja35/g=="],
|
||||
|
||||
"@shikijs/transformers": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/core": "3.22.0", "@shikijs/types": "3.22.0" } }, "sha512-E7eRV7mwDBjueLF6852n2oYeJYxBq3NSsDk+uyruYAXONv4U8holGmIrT+mPRJQ1J1SNOH6L8G19KRzmBawrFw=="],
|
||||
|
||||
"@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-491iAekgKDBFE67z70Ok5a8KBMsQ2IJwOWw3us/7ffQkIBCyOQfm/aNwVMBUriP02QshIfgHCBSIYAl3u2eWjg=="],
|
||||
|
||||
"@shikijs/vscode-textmate": ["@shikijs/[email protected]", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
|
||||
|
||||
"@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
|
||||
|
||||
"@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
||||
@@ -630,8 +611,6 @@
|
||||
|
||||
"devlop": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
|
||||
|
||||
"diff": ["[email protected]", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],
|
||||
|
||||
"dts-resolver": ["[email protected]", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw=="],
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
@@ -732,8 +711,6 @@
|
||||
|
||||
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
||||
|
||||
"hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
||||
|
||||
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||
|
||||
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
||||
@@ -748,8 +725,6 @@
|
||||
|
||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||
|
||||
"html-void-elements": ["[email protected]", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="],
|
||||
|
||||
"http-cache-semantics": ["[email protected]", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="],
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
@@ -836,8 +811,6 @@
|
||||
|
||||
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||
|
||||
"lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-JJ8GVTQqFwuliifD48U6+h7DXEHdkhJ/E87kksGByII3qHxtPciVb8T8woQONHBQgHVOl7rSMrrip3SeVNy7Fg=="],
|
||||
|
||||
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
@@ -968,10 +941,6 @@
|
||||
|
||||
"once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||
|
||||
"oniguruma-parser": ["[email protected]", "", {}, "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w=="],
|
||||
|
||||
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.0.1", "regex-recursion": "^6.0.2" } }, "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA=="],
|
||||
|
||||
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
||||
|
||||
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
|
||||
@@ -1018,12 +987,6 @@
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
|
||||
"regex": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="],
|
||||
|
||||
"regex-recursion": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="],
|
||||
|
||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
||||
|
||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||
|
||||
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||
@@ -1072,8 +1035,6 @@
|
||||
|
||||
"serialize-error": ["[email protected]", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
|
||||
|
||||
"shiki": ["[email protected]", "", { "dependencies": { "@shikijs/core": "3.22.0", "@shikijs/engine-javascript": "3.22.0", "@shikijs/engine-oniguruma": "3.22.0", "@shikijs/langs": "3.22.0", "@shikijs/themes": "3.22.0", "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-LBnhsoYEe0Eou4e1VgJACes+O6S6QC0w71fCSp5Oya79inkwkm15gQ1UF6VtQ8j/taMDh79hAB49WUk8ALQW3g=="],
|
||||
|
||||
"siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
+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";
|
||||
@@ -32,6 +32,7 @@ import type {
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
import type { RendererStateSetInput, RendererStateSnapshot } from "./rendererState";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -116,5 +117,7 @@ export interface NativeApi {
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
getRendererState: () => Promise<RendererStateSnapshot | null>;
|
||||
setRendererState: (input: RendererStateSetInput) => Promise<void>;
|
||||
};
|
||||
}
|
||||
@@ -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>;
|
||||
@@ -40,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