Compare commits

...
Author SHA1 Message Date
Julius Marminge 4d976b8bf7 Persist renderer state on server via SQLite and WS APIs
- Add shared renderer state contracts and websocket methods
- Implement server-side SQLite-backed renderer state store with Node/Bun adapters
- Migrate web store hydration/persistence from localStorage to server state, with legacy fallback
- Add contract, store, and websocket persistence tests
2026-02-17 21:15:51 -08:00
Julius Marminge 0c50a2d8e1 Persist image previews in chat state and bump schema to v8
- store image attachment `previewUrl` data URLs in persisted thread messages
- migrate renderer persistence key/schema from v7 to v8 with hydration coverage
- build message attachments from prepared image data before dispatching user messages
2026-02-17 15:54:12 -08:00
Julius Marminge f64c26e708 Add clean script to package.json for removing build artifacts
- Introduce a new "clean" script to remove node_modules and build artifacts across apps and packages
- Enhances project maintenance by simplifying cleanup process
2026-02-17 15:12:57 -08:00
Julius Marminge 6d8d39a5d1 Guard branch sync when no active thread is selected
- Prevent `SET_THREAD_BRANCH` dispatch unless both `activeThreadId` and `syncedBranch` exist
- Avoids updating thread-branch state without an active thread context
2026-02-17 15:12:07 -08:00
Julius Marminge afdfe16931 Extract branch sync logic and limit sync to local mode
- move branch-sync decision into `BranchToolbar.logic.ts`
- avoid auto-sync when env mode is `worktree` or thread has worktree path
- add unit tests for sync and no-sync cases
2026-02-17 15:12:07 -08:00
Julius Marminge 73fa2d66c7 Use stable IDs for approval actions in ChatView
- Derive `activeSessionId` and `activeThreadId` before approval callbacks
- Avoid stale thread/session captures when submitting approval decisions
- Pass `hasMessages` to `MessagesTimeline` instead of the full thread
2026-02-16 00:55:31 -08:00
Julius Marminge 51dcb547ed Refactor ChatView into memoized subcomponents
- Extract header, error, approvals, and timeline into memoized components
- Memoize `ChatMarkdown`, pickers, and handlers to reduce avoidable re-renders
- Reduce running-time ticker frequency from 250ms to 1000ms
2026-02-16 00:55:31 -08:00
Julius Marminge 228862ac56 doc 2026-02-15 23:08:37 -08:00
Julius Marminge bc22a71f10 Rename local chat shortcut and surface terminal close hints
- Replace `chat.newSameGitState` with `chat.newLocal` across contracts, server/web defaults, docs, and tests
- Make `chat.new` preserve branch/worktree state while `chat.newLocal` creates a local thread
- Show terminal close shortcut labels in drawer action tooltips and tab close controls
2026-02-15 23:08:37 -08:00
Julius Marminge c42d6a6a64 Add shortcuts for terminal close and chat with same Git state
- Extend keybinding contracts/defaults with `terminal.close` and `chat.newSameGitState`
- Wire web handlers for `mod+w` to close focused terminal and `mod+shift+n` to open a thread preserving branch/worktree
- Update docs and keybinding tests across server, web, and contracts
2026-02-15 23:08:37 -08:00
Julius Marminge 5242bbbade Fix top-right toast enter and exit transforms
- Add position-specific start transform for top-right toasts
- Apply matching top-right end transform when dismissing without swipe
2026-02-15 20:12:24 -08:00
Julius Marminge 05b47e748f Fix collapsed toast content visibility in filtered stacks
- keep the front-most visible toast readable when thread filtering hides others
- extract visibility rule into `toast.logic.ts`
- add unit tests for collapsed-content visibility behavior
2026-02-15 20:12:24 -08:00
32 changed files with 1462 additions and 509 deletions

No files matched your search

+7 -2
View File
@@ -22,7 +22,10 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
{ "key": "mod+o", "command": "editor.openFavorite" }
]
```
@@ -46,7 +49,9 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.toggle`: open/close terminal drawer
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread for the active project
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
### Key Syntax
+11
View File
@@ -0,0 +1,11 @@
declare module "bun:sqlite" {
export class Database {
constructor(filename?: string);
exec(sql: string): void;
run(sql: string, ...params: unknown[]): unknown;
query(sql: string): {
get(...params: unknown[]): unknown;
};
close(): void;
}
}
+1
View File
@@ -118,6 +118,7 @@ async function main() {
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
stateDir,
staticDir,
devUrl,
projectRegistry,
+4 -1
View File
@@ -28,7 +28,10 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+shift+o", command: "chat.new" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
];
@@ -0,0 +1,47 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { RendererStateStore } from "./rendererStateStore";
function makeTempDir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}
describe("RendererStateStore", () => {
it("returns null when no renderer state has been saved", async () => {
const stateDir = makeTempDir("t3code-renderer-state-empty-");
const store = new RendererStateStore(stateDir);
await expect(store.get()).resolves.toBeNull();
await store.close();
fs.rmSync(stateDir, { recursive: true, force: true });
});
it("persists and reloads renderer state from sqlite", async () => {
const stateDir = makeTempDir("t3code-renderer-state-roundtrip-");
const firstStore = new RendererStateStore(stateDir);
const payload =
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}';
await firstStore.set({ stateJson: payload });
const firstRead = await firstStore.get();
expect(firstRead).toMatchObject({
stateJson: payload,
updatedAt: expect.any(String),
});
await firstStore.close();
const secondStore = new RendererStateStore(stateDir);
const secondRead = await secondStore.get();
expect(secondRead).toMatchObject({
stateJson: payload,
updatedAt: expect.any(String),
});
await secondStore.close();
fs.rmSync(stateDir, { recursive: true, force: true });
});
});
+174
View File
@@ -0,0 +1,174 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
type RendererStateSetInput,
type RendererStateSnapshot,
rendererStateSetInputSchema,
rendererStateSnapshotSchema,
} from "@t3tools/contracts";
interface RowShape {
stateJson: string;
updatedAt: string;
}
interface SqliteAdapter {
getState(): RowShape | null;
setState(stateJson: string, updatedAt: string): void;
close(): void;
}
interface BunSqliteDatabase {
exec(sql: string): void;
run(sql: string, ...params: unknown[]): unknown;
query(sql: string): {
get(...params: unknown[]): unknown;
};
close(): void;
}
interface BunSqliteModule {
Database: new (filename?: string) => BunSqliteDatabase;
}
function defaultStateDir(): string {
return path.join(os.homedir(), ".t3", "userdata");
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function parseRowShape(row: unknown): RowShape | null {
if (!isObject(row)) return null;
const stateJson = row.stateJson;
const updatedAt = row.updatedAt;
if (typeof stateJson !== "string" || typeof updatedAt !== "string") return null;
return { stateJson, updatedAt };
}
async function createNodeSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
const module = await import("node:sqlite");
const db = new module.DatabaseSync(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS renderer_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
state_json TEXT NOT NULL,
updated_at TEXT NOT NULL
)
`);
const selectStatement = db.prepare(`
SELECT state_json AS stateJson, updated_at AS updatedAt
FROM renderer_state
WHERE id = 1
`);
const upsertStatement = db.prepare(`
INSERT INTO renderer_state (id, state_json, updated_at)
VALUES (1, ?, ?)
ON CONFLICT(id) DO UPDATE SET
state_json = excluded.state_json,
updated_at = excluded.updated_at
`);
return {
getState() {
return parseRowShape(selectStatement.get());
},
setState(stateJson: string, updatedAt: string) {
upsertStatement.run(stateJson, updatedAt);
},
close() {
db.close();
},
};
}
async function createBunSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
const loadBunSqlite = new Function(
"return import('bun:sqlite')",
) as () => Promise<BunSqliteModule>;
const module = await loadBunSqlite();
const db = new module.Database(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS renderer_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
state_json TEXT NOT NULL,
updated_at TEXT NOT NULL
)
`);
const selectQuery = db.query(`
SELECT state_json AS stateJson, updated_at AS updatedAt
FROM renderer_state
WHERE id = 1
`);
const upsertSql = `
INSERT INTO renderer_state (id, state_json, updated_at)
VALUES (1, ?, ?)
ON CONFLICT(id) DO UPDATE SET
state_json = excluded.state_json,
updated_at = excluded.updated_at
`;
return {
getState() {
return parseRowShape(selectQuery.get());
},
setState(stateJson: string, updatedAt: string) {
db.run(upsertSql, stateJson, updatedAt);
},
close() {
db.close();
},
};
}
async function createSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
try {
return await createNodeSqliteAdapter(dbPath);
} catch {
return createBunSqliteAdapter(dbPath);
}
}
export class RendererStateStore {
private readonly stateDir: string;
private readonly dbPath: string;
private adapterPromise: Promise<SqliteAdapter> | null = null;
constructor(stateDir: string = defaultStateDir()) {
this.stateDir = stateDir;
this.dbPath = path.join(this.stateDir, "renderer-state.sqlite");
fs.mkdirSync(this.stateDir, { recursive: true });
}
async get(): Promise<RendererStateSnapshot | null> {
const adapter = await this.getAdapter();
const row = adapter.getState();
if (!row) return null;
const parsed = rendererStateSnapshotSchema.safeParse(row);
if (!parsed.success) return null;
return parsed.data;
}
async set(raw: RendererStateSetInput): Promise<void> {
const input = rendererStateSetInputSchema.parse(raw);
const adapter = await this.getAdapter();
adapter.setState(input.stateJson, new Date().toISOString());
}
async close(): Promise<void> {
if (!this.adapterPromise) return;
const adapter = await this.adapterPromise;
adapter.close();
this.adapterPromise = null;
}
private async getAdapter(): Promise<SqliteAdapter> {
if (!this.adapterPromise) {
this.adapterPromise = createSqliteAdapter(this.dbPath);
}
return this.adapterPromise;
}
}
+66
View File
@@ -249,6 +249,7 @@ describe("WebSocket Server", () => {
return createServer({
port: 0,
cwd: options.cwd ?? "/test/project",
stateDir,
...(options.devUrl ? { devUrl: options.devUrl } : {}),
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
@@ -342,6 +343,71 @@ describe("WebSocket Server", () => {
});
});
it("reads and writes renderer state over websocket", async () => {
const stateDir = makeTempDir("t3code-ws-renderer-state-");
server = createTestServer({ cwd: "/my/workspace", stateDir });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const empty = await sendRequest(ws, WS_METHODS.serverGetRendererState);
expect(empty.error).toBeUndefined();
expect(empty.result).toBeNull();
const setResponse = await sendRequest(ws, WS_METHODS.serverSetRendererState, {
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
});
expect(setResponse.error).toBeUndefined();
const loaded = await sendRequest(ws, WS_METHODS.serverGetRendererState);
expect(loaded.error).toBeUndefined();
expect(loaded.result).toMatchObject({
stateJson:
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
updatedAt: expect.any(String),
});
});
it("persists renderer state across server restarts", async () => {
const stateDir = makeTempDir("t3code-ws-renderer-state-restart-");
server = createTestServer({ cwd: "/workspace", stateDir });
await server.start();
const firstAddr = server.httpServer.address();
const firstPort = typeof firstAddr === "object" && firstAddr !== null ? firstAddr.port : 0;
const firstWs = await connectWs(firstPort);
connections.push(firstWs);
await waitForMessage(firstWs);
const setResponse = await sendRequest(firstWs, WS_METHODS.serverSetRendererState, {
stateJson:
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
});
expect(setResponse.error).toBeUndefined();
await server.stop();
server = createTestServer({ cwd: "/workspace", stateDir });
await server.start();
const secondAddr = server.httpServer.address();
const secondPort =
typeof secondAddr === "object" && secondAddr !== null ? secondAddr.port : 0;
const secondWs = await connectWs(secondPort);
connections.push(secondWs);
await waitForMessage(secondWs);
const loaded = await sendRequest(secondWs, WS_METHODS.serverGetRendererState);
expect(loaded.error).toBeUndefined();
expect(loaded.result).toMatchObject({
stateJson:
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
updatedAt: expect.any(String),
});
});
it("reads keybindings from ~/.t3/keybindings.json", async () => {
const fakeHome = makeTempDir("t3code-home-");
const configDir = path.join(fakeHome, ".t3");
+16 -2
View File
@@ -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();
@@ -0,0 +1,56 @@
import type { GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
const branches: GitBranch[] = [
{
name: "main",
current: true,
isDefault: true,
worktreePath: null,
},
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
];
describe("deriveSyncedLocalBranch", () => {
it("syncs to git current branch in local mode", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: null,
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBe("main");
});
it("does not sync when creating a new worktree", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: null,
envMode: "worktree",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
it("does not sync when thread already targets a worktree path", () => {
const result = deriveSyncedLocalBranch({
activeThreadId: "thread-1",
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
});
@@ -0,0 +1,28 @@
import type { GitBranch } from "@t3tools/contracts";
interface DeriveSyncedLocalBranchInput {
activeThreadId: string | undefined;
activeWorktreePath: string | null;
envMode: "local" | "worktree";
activeThreadBranch: string | null;
queryBranches: GitBranch[] | undefined;
}
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
}: DeriveSyncedLocalBranchInput): string | null {
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
return null;
}
const currentBranch = queryBranches?.find((branch) => branch.current);
if (!currentBranch || currentBranch.name === activeThreadBranch) {
return null;
}
return currentBranch.name;
}
+12 -6
View File
@@ -9,6 +9,7 @@ import {
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
@@ -86,17 +87,22 @@ export default function BranchToolbar({
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
if (!activeThreadId || activeWorktreePath) return;
const current = queryBranches?.find((branch) => branch.current);
if (!current) return;
if (current.name === activeThreadBranch) return;
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: current.name,
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
+4 -1
View File
@@ -1,3 +1,4 @@
import { memo } from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
@@ -13,7 +14,7 @@ const markdownComponents: Components = {
},
};
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
@@ -26,3 +27,5 @@ export default function ChatMarkdown({ text }: ChatMarkdownProps) {
</div>
);
}
export default memo(ChatMarkdown);
+477 -338
View File
@@ -2,6 +2,7 @@ import {
EDITORS,
type EditorId,
ModelSlug,
type NativeApi,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
@@ -15,6 +16,8 @@ import {
type FormEvent,
Fragment,
type KeyboardEvent,
memo,
type RefObject,
useCallback,
useEffect,
useLayoutEffect,
@@ -40,6 +43,7 @@ import {
derivePendingApprovals,
derivePhase,
deriveTimelineEntries,
type PendingApproval,
deriveWorkLogEntries,
formatDuration,
formatElapsed,
@@ -52,6 +56,7 @@ import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
isOpenFavoriteEditorShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
@@ -163,6 +168,7 @@ export default function ChatView() {
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const activeThreadId = activeThread?.id ?? null;
const activeSessionId = activeThread?.session?.sessionId;
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
@@ -278,6 +284,10 @@ export default function ChatView() {
() => shortcutLabelForCommand(keybindings, "terminal.new"),
[keybindings],
);
const closeTerminalShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "terminal.close"),
[keybindings],
);
const envLocked = Boolean(
activeThread &&
@@ -492,7 +502,7 @@ export default function ChatView() {
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 250);
}, 1000);
return () => {
window.clearInterval(timer);
};
@@ -554,6 +564,14 @@ export default function ChatView() {
return;
}
if (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) return;
closeTerminal(activeThread.activeTerminalId);
return;
}
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
event.preventDefault();
event.stopPropagation();
@@ -570,7 +588,9 @@ export default function ChatView() {
return () => window.removeEventListener("keydown", handler);
}, [
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
activeThreadId,
closeTerminal,
createNewTerminal,
dispatch,
splitTerminal,
@@ -803,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");
@@ -874,28 +901,31 @@ export default function ChatView() {
});
};
const onRespondToApproval = async (requestId: string, decision: ProviderApprovalDecision) => {
if (!api || !activeThread?.session) return;
const onRespondToApproval = useCallback(
async (requestId: string, decision: ProviderApprovalDecision) => {
if (!api || !activeSessionId || !activeThreadId) return;
setRespondingRequestIds((existing) =>
existing.includes(requestId) ? existing : [...existing, requestId],
);
try {
await api.providers.respondToRequest({
sessionId: activeThread.session.sessionId,
requestId,
decision,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
};
setRespondingRequestIds((existing) =>
existing.includes(requestId) ? existing : [...existing, requestId],
);
try {
await api.providers.respondToRequest({
sessionId: activeSessionId,
requestId,
decision,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: err instanceof Error ? err.message : "Failed to submit approval decision.",
});
} finally {
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
}
},
[activeSessionId, activeThreadId, api, dispatch],
);
const onModelSelect = useCallback(
(model: ModelSlug) => {
@@ -930,6 +960,18 @@ export default function ChatView() {
void onSend(e as unknown as FormEvent);
}
};
const onToggleWorkGroup = useCallback((groupId: string) => {
setExpandedWorkGroups((existing) => ({
...existing,
[groupId]: !existing[groupId],
}));
}, []);
const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => {
setExpandedImage(image);
}, []);
const onToggleDiff = useCallback(() => {
dispatch({ type: "TOGGLE_DIFF" });
}, [dispatch]);
// Empty state: no active thread
if (!activeThread) {
@@ -955,101 +997,24 @@ export default function ChatView() {
<header
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">{activeThread.title}</h2>
{activeProject && <Badge variant="outline">{activeProject.name}</Badge>}
</div>
<div className="flex items-center gap-3">
{/* Open in editor */}
{activeProject && <OpenInPicker keybindings={keybindings} />}
{/* Git actions */}
{activeProject && <GitActionsControl api={api} gitCwd={gitCwd} />}
{/* Diff toggle */}
<Button
size="xs"
variant="ghost"
className={cn(
"text-muted-foreground/70 hover:text-foreground/80",
state.diffOpen && "bg-accent text-accent-foreground",
)}
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
Diff
</Button>
</div>
<ChatHeader
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
keybindings={keybindings}
api={api}
gitCwd={gitCwd}
diffOpen={state.diffOpen}
onToggleDiff={onToggleDiff}
/>
</header>
{/* Error banner */}
{activeThread.error && (
<div className="pt-3 mx-auto max-w-3xl">
<Alert variant="error">
<CircleAlertIcon />
<AlertDescription className="line-clamp-3" title={activeThread.error}>
{activeThread.error}
</AlertDescription>
</Alert>
</div>
)}
{pendingApprovals.length > 0 && (
<div className="pt-3 mx-auto max-w-3xl space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<Alert variant="warning" key={approval.requestId}>
<InfoIcon />
<AlertTitle className="text-xs">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</AlertTitle>
<AlertDescription
className="truncate block font-mono text-[11px]"
title={approval.detail}
>
{approval.detail}
</AlertDescription>
<AlertAction className="col-start-2! -col-end-1! mt-1.5 sm:row-start-auto sm:row-end-auto">
<Button
size="xs"
variant="default"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</Button>
<Button
size="xs"
variant="outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</Button>
<Button
size="xs"
variant="destructive-outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</Button>
<Button
size="xs"
variant="ghost"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</Button>
</AlertAction>
</Alert>
);
})}
</div>
)}
<ThreadErrorBanner error={activeThread.error} />
<PendingApprovalsPanel
pendingApprovals={pendingApprovals}
respondingRequestIds={respondingRequestIds}
onRespondToApproval={onRespondToApproval}
/>
{/* Messages */}
<div
@@ -1057,198 +1022,19 @@ export default function ChatView() {
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
onScroll={onMessagesScroll}
>
{activeThread.messages.length === 0 && !isWorking ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
) : (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry, index) => {
if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") {
return null;
}
const showCompletionDivider =
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id;
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < timelineEntries.length) {
const nextEntry = timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
const groupId = timelineEntry.id;
const isExpanded = expandedWorkGroups[groupId] ?? false;
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const groupLabel = onlyToolEntries
? groupedEntries.length === 1
? "Tool call"
: `Tool calls (${groupedEntries.length})`
: groupedEntries.length === 1
? "Work event"
: `Work log (${groupedEntries.length})`;
return (
<Fragment key={timelineEntry.id}>
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
<div className="mb-1.5 flex items-center justify-between gap-3">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
{groupLabel}
</p>
{hasOverflow && (
<button
type="button"
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() =>
setExpandedWorkGroups((existing) => ({
...existing,
[groupId]: !existing[groupId],
}))
}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
<div className="space-y-1">
{visibleEntries.map((workEntry) => (
<div
key={`work-row:${workEntry.id}`}
className="flex items-start gap-2 py-0.5"
>
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
>
{workEntry.detail ? (
<>
{workEntry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={workEntry.detail}
>
{workEntry.detail}
</span>
</>
) : (
workEntry.label
)}
</p>
</div>
))}
</div>
</div>
</Fragment>
);
}
if (timelineEntry.message.role === "user") {
const userImages = timelineEntry.message.attachments ?? [];
return (
<Fragment key={timelineEntry.id}>
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() =>
setExpandedImage({ src: image.previewUrl!, name: image.name })
}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
))}
</div>
)}
{timelineEntry.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
</Fragment>
);
}
return (
<Fragment key={timelineEntry.id}>
{showCompletionDivider && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
<div className="px-1 py-0.5">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
</div>
</Fragment>
);
})}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
)}
<MessagesTimeline
hasMessages={activeThread.messages.length > 0}
isWorking={isWorking}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
assistantCompletionByItemId={assistantCompletionByItemId}
nowIso={nowIso}
expandedWorkGroups={expandedWorkGroups}
onToggleWorkGroup={onToggleWorkGroup}
onImageExpand={onExpandTimelineImage}
messagesEndRef={messagesEndRef}
/>
</div>
{/* Input bar */}
@@ -1453,6 +1239,7 @@ export default function ChatView() {
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
@@ -1503,7 +1290,355 @@ export default function ChatView() {
);
}
function ModelPicker(props: { model: ModelSlug; onModelChange: (model: ModelSlug) => void }) {
interface ChatHeaderProps {
activeThreadTitle: string;
activeProjectName: string | undefined;
keybindings: ResolvedKeybindingsConfig;
api: NativeApi | undefined;
gitCwd: string | null;
diffOpen: boolean;
onToggleDiff: () => void;
}
const ChatHeader = memo(function ChatHeader({
activeThreadTitle,
activeProjectName,
keybindings,
api,
gitCwd,
diffOpen,
onToggleDiff,
}: ChatHeaderProps) {
return (
<>
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">{activeThreadTitle}</h2>
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
</div>
<div className="flex items-center gap-3">
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
<Button
size="xs"
variant="ghost"
className={cn(
"text-muted-foreground/70 hover:text-foreground/80",
diffOpen && "bg-accent text-accent-foreground",
)}
onClick={onToggleDiff}
>
Diff
</Button>
</div>
</>
);
});
const ThreadErrorBanner = memo(function ThreadErrorBanner({ error }: { error: string | null }) {
if (!error) return null;
return (
<div className="pt-3 mx-auto max-w-3xl">
<Alert variant="error">
<CircleAlertIcon />
<AlertDescription className="line-clamp-3" title={error}>
{error}
</AlertDescription>
</Alert>
</div>
);
});
interface PendingApprovalsPanelProps {
pendingApprovals: PendingApproval[];
respondingRequestIds: string[];
onRespondToApproval: (requestId: string, decision: ProviderApprovalDecision) => Promise<void>;
}
const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
pendingApprovals,
respondingRequestIds,
onRespondToApproval,
}: PendingApprovalsPanelProps) {
if (pendingApprovals.length === 0) return null;
return (
<div className="pt-3 mx-auto max-w-3xl space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<Alert variant="warning" key={approval.requestId}>
<InfoIcon />
<AlertTitle className="text-xs">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</AlertTitle>
<AlertDescription
className="truncate block font-mono text-[11px]"
title={approval.detail}
>
{approval.detail}
</AlertDescription>
<AlertAction className="col-start-2! -col-end-1! mt-1.5 sm:row-start-auto sm:row-end-auto">
<Button
size="xs"
variant="default"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</Button>
<Button
size="xs"
variant="outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</Button>
<Button
size="xs"
variant="destructive-outline"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</Button>
<Button
size="xs"
variant="ghost"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</Button>
</AlertAction>
</Alert>
);
})}
</div>
);
});
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
assistantCompletionByItemId: Map<string, string>;
nowIso: string;
expandedWorkGroups: Record<string, boolean>;
onToggleWorkGroup: (groupId: string) => void;
onImageExpand: (image: ExpandedImagePreview) => void;
messagesEndRef: RefObject<HTMLDivElement | null>;
}
const MessagesTimeline = memo(function MessagesTimeline({
hasMessages,
isWorking,
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
assistantCompletionByItemId,
nowIso,
expandedWorkGroups,
onToggleWorkGroup,
onImageExpand,
messagesEndRef,
}: MessagesTimelineProps) {
if (!hasMessages && !isWorking) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">Send a message to start the conversation.</p>
</div>
);
}
return (
<div className="mx-auto max-w-3xl space-y-4">
{timelineEntries.map((timelineEntry, index) => {
if (timelineEntry.kind === "work" && timelineEntries[index - 1]?.kind === "work") {
return null;
}
const showCompletionDivider =
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id;
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < timelineEntries.length) {
const nextEntry = timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
const groupId = timelineEntry.id;
const isExpanded = expandedWorkGroups[groupId] ?? false;
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const groupLabel = onlyToolEntries
? groupedEntries.length === 1
? "Tool call"
: `Tool calls (${groupedEntries.length})`
: groupedEntries.length === 1
? "Work event"
: `Work log (${groupedEntries.length})`;
return (
<Fragment key={timelineEntry.id}>
<div className="rounded-lg border border-border/80 bg-card/45 px-3 py-2">
<div className="mb-1.5 flex items-center justify-between gap-3">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
{groupLabel}
</p>
{hasOverflow && (
<button
type="button"
className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-muted-foreground/80"
onClick={() => onToggleWorkGroup(groupId)}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
<div className="space-y-1">
{visibleEntries.map((workEntry) => (
<div key={`work-row:${workEntry.id}`} className="flex items-start gap-2 py-0.5">
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<p
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(workEntry.tone)}`}
>
{workEntry.detail ? (
<>
{workEntry.label}
<span
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
title={workEntry.detail}
>
{workEntry.detail}
</span>
</>
) : (
workEntry.label
)}
</p>
</div>
))}
</div>
</div>
</Fragment>
);
}
if (timelineEntry.message.role === "user") {
const userImages = timelineEntry.message.attachments ?? [];
return (
<Fragment key={timelineEntry.id}>
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() =>
onImageExpand({ src: image.previewUrl!, name: image.name })
}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
))}
</div>
)}
{timelineEntry.message.text && (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
</div>
</div>
</Fragment>
);
}
return (
<Fragment key={timelineEntry.id}>
{showCompletionDivider && (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
)}
<div className="px-1 py-0.5">
<ChatMarkdown
text={
timelineEntry.message.text ||
(timelineEntry.message.streaming ? "" : "(empty response)")
}
/>
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
{formatMessageMeta(
timelineEntry.message.createdAt,
timelineEntry.message.streaming
? formatElapsed(timelineEntry.message.createdAt, nowIso)
: formatElapsed(
timelineEntry.message.createdAt,
assistantCompletionByItemId.get(timelineEntry.message.id),
),
)}
</p>
</div>
</Fragment>
);
})}
{isWorking && (
<div className="flex items-center gap-2 py-0.5 pl-1.5">
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/30" />
<div className="flex items-center pt-1">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
);
});
const ModelPicker = memo(function ModelPicker(props: {
model: ModelSlug;
onModelChange: (model: ModelSlug) => void;
}) {
return (
<Select
items={MODEL_OPTIONS.map((option) => ({ label: option.name, value: option.slug }))}
@@ -1522,9 +1657,9 @@ function ModelPicker(props: { model: ModelSlug; onModelChange: (model: ModelSlug
</SelectPopup>
</Select>
);
}
});
function ReasoningEffortPicker(props: {
const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
effort: ReasoningEffort;
onEffortChange: (effort: ReasoningEffort) => void;
}) {
@@ -1546,9 +1681,13 @@ function ReasoningEffortPicker(props: {
</SelectPopup>
</Select>
);
}
});
function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig }) {
const OpenInPicker = memo(function OpenInPicker({
keybindings,
}: {
keybindings: ResolvedKeybindingsConfig;
}) {
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
const stored = localStorage.getItem(LAST_EDITOR_KEY);
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
@@ -1632,4 +1771,4 @@ function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig
</Menu>
</Group>
);
}
});
+23 -8
View File
@@ -7,7 +7,7 @@ import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewShortcut } from "../keybindings";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -140,7 +140,13 @@ export default function Sidebar() {
}, [state.threads]);
const handleNewThread = useCallback(
(projectId: string) => {
(
projectId: string,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
) => {
dispatch({
type: "ADD_THREAD",
thread: {
@@ -166,8 +172,8 @@ export default function Sidebar() {
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
},
});
},
@@ -381,14 +387,23 @@ export default function Sidebar() {
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
if (!isChatNewShortcut(event, keybindings)) return;
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
return;
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
handleNewThread(projectId, {
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
@@ -18,10 +18,7 @@ import {
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import {
isTerminalClearShortcut,
terminalNavigationShortcutData,
} from "../keybindings";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -161,10 +158,7 @@ function TerminalViewport({
try {
await api.terminal.write({ threadId, terminalId, data });
} catch (error) {
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : fallbackError,
);
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
}
};
@@ -429,6 +423,7 @@ interface ThreadTerminalDrawerProps {
onNewTerminal: () => void;
splitShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
closeShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
@@ -444,15 +439,9 @@ interface TerminalActionButtonProps {
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
return (
<Popover>
<PopoverTrigger openOnHover
render={
<button
type="button"
className={className}
onClick={onClick}
aria-label={label}
/>
}
<PopoverTrigger
openOnHover
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
>
{children}
</PopoverTrigger>
@@ -483,6 +472,7 @@ export default function ThreadTerminalDrawer({
onNewTerminal,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
@@ -598,6 +588,9 @@ export default function ThreadTerminalDrawer({
),
[normalizedTerminalIds],
);
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
@@ -709,7 +702,9 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
label={
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
}
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
@@ -725,7 +720,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -805,16 +800,14 @@ export default function ThreadTerminalDrawer({
<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"
}
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
>
<Plus className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
label={closeTerminalActionLabel}
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
@@ -852,6 +845,9 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
return (
<div
key={terminalId}
@@ -875,18 +871,30 @@ export default function ThreadTerminalDrawer({
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<button
type="button"
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={() => onCloseTerminal(terminalId)}
aria-label={closeTerminalLabel}
/>
}
>
<XIcon className="size-2.5" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{closeTerminalLabel}
</PopoverPopup>
</Popover>
)}
</div>
);
@@ -0,0 +1,16 @@
import { assert, describe, it } from "vitest";
import { shouldHideCollapsedToastContent } from "./toast.logic";
describe("shouldHideCollapsedToastContent", () => {
it("keeps a single visible toast readable", () => {
assert.equal(shouldHideCollapsedToastContent(0, 1), false);
});
it("keeps the front-most toast readable in a visible stack", () => {
assert.equal(shouldHideCollapsedToastContent(0, 3), false);
});
it("hides non-front toasts until the stack is expanded", () => {
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
});
});
@@ -0,0 +1,9 @@
export function shouldHideCollapsedToastContent(
visibleToastIndex: number,
visibleToastCount: number,
): boolean {
// Keep the front-most toast readable even if Base UI marks it as "behind"
// due to toasts hidden by thread filtering.
if (visibleToastCount <= 1) return false;
return visibleToastIndex > 0;
}
+99 -88
View File
@@ -13,6 +13,7 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
threadId?: string | null;
@@ -146,6 +147,9 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = state.activeThreadId;
const isTop = position.startsWith("top");
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
);
useEffect(() => {
const activeToastIds = new Set(toasts.map((toast) => toast.id));
@@ -172,100 +176,107 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
data-position={position}
data-slot="toast-viewport"
>
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
{visibleToasts.map((toast, visibleIndex) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const hideCollapsedContent = shouldHideCollapsedToastContent(
visibleIndex,
visibleToasts.length,
);
return (
<Toast.Root
return (
<Toast.Root
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<ThreadToastVisibleAutoDismiss
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
toastId={toast.id}
/>
<Toast.Content
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
"pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100",
hideCollapsedContent &&
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<ThreadToastVisibleAutoDismiss
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
toastId={toast.id}
/>
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action
className={buttonVariants({ size: "xs" })}
data-slot="toast-action"
<div className="flex gap-2">
{Icon && (
<div
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
data-slot="toast-icon"
>
{toast.actionProps.children}
</Toast.Action>
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
</div>
)}
</Toast.Content>
</Toast.Root>
);
})}
<div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description
className="text-muted-foreground"
data-slot="toast-description"
/>
</div>
</div>
{toast.actionProps && (
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
{toast.actionProps.children}
</Toast.Action>
)}
</Toast.Content>
</Toast.Root>
);
})}
</Toast.Viewport>
</Toast.Portal>
);
+43 -2
View File
@@ -9,8 +9,10 @@ import {
import {
formatShortcutLabel,
isChatNewShortcut,
isChatNewLocalShortcut,
isOpenFavoriteEditorShortcut,
isTerminalClearShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
@@ -83,7 +85,13 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("w"),
command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
]);
@@ -101,8 +109,8 @@ describe("isTerminalToggleShortcut", () => {
});
});
describe("split/new terminal shortcuts", () => {
it("requires terminalFocus for default split/new bindings", () => {
describe("split/new/close terminal shortcuts", () => {
it("requires terminalFocus for default split/new/close bindings", () => {
assert.isFalse(
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
@@ -115,6 +123,12 @@ describe("split/new terminal shortcuts", () => {
context: { terminalFocus: false },
}),
);
assert.isFalse(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: false },
}),
);
});
it("matches split/new when terminalFocus is true", () => {
@@ -130,6 +144,12 @@ describe("split/new terminal shortcuts", () => {
context: { terminalFocus: true },
}),
);
assert.isTrue(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
});
it("supports when expressions", () => {
@@ -225,6 +245,27 @@ describe("chat/editor shortcuts", () => {
);
});
it("matches chat.newLocal shortcut", () => {
assert.isTrue(
isChatNewLocalShortcut(
event({ key: "n", metaKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "MacIntel",
},
),
);
assert.isTrue(
isChatNewLocalShortcut(
event({ key: "n", ctrlKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "Linux",
},
),
);
});
it("matches editor.openFavorite shortcut", () => {
assert.isTrue(
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
+16
View File
@@ -190,6 +190,14 @@ export function isTerminalNewShortcut(
return matchesCommandShortcut(event, keybindings, "terminal.new", options);
}
export function isTerminalCloseShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
}
export function isChatNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
@@ -198,6 +206,14 @@ export function isChatNewShortcut(
return matchesCommandShortcut(event, keybindings, "chat.new", options);
}
export function isChatNewLocalShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
}
export function isOpenFavoriteEditorShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
+122 -2
View File
@@ -257,10 +257,65 @@ describe("hydratePersistedState", () => {
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("hydrates persisted image preview data urls", () => {
const payload = JSON.stringify({
version: 8,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
messages: [
{
id: "m-1",
role: "user",
text: "Here",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
previewUrl: "data:image/png;base64,AAAA",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.messages[0]?.attachments?.[0]?.previewUrl).toBe(
"data:image/png;base64,AAAA",
);
});
});
describe("toPersistedState", () => {
it("writes v7 payload and strips non-persisted thread fields", () => {
it("writes v8 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
@@ -320,7 +375,7 @@ describe("toPersistedState", () => {
runtimeMode: "full-access",
});
expect(persisted.version).toBe(7);
expect(persisted.version).toBe(8);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
@@ -367,4 +422,69 @@ describe("toPersistedState", () => {
expect("error" in persistedThread).toBe(false);
expect("session" in persistedThread).toBe(false);
});
it("persists preview data urls for image attachments", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [
{
id: "m-1",
role: "user",
text: "Image",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 1_024,
previewUrl: "data:image/png;base64,AAAA",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
events: [],
error: null,
createdAt: "2026-02-08T10:00:00.000Z",
branch: null,
worktreePath: null,
};
const persisted = toPersistedState({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [thread],
activeThreadId: "t-1",
runtimeMode: "full-access",
});
expect(persisted.threads[0]?.messages[0]?.attachments?.[0]).toMatchObject({
type: "image",
id: "img-1",
previewUrl: "data:image/png;base64,AAAA",
});
});
});
+20 -3
View File
@@ -33,6 +33,7 @@ const persistedMessageSchema = z.object({
name: z.string().min(1),
mimeType: z.string().min(1),
sizeBytes: z.number().int().min(1),
previewUrl: z.string().min(1).optional(),
}),
)
.optional(),
@@ -103,12 +104,18 @@ export const persistedStateV7Schema = persistedStateBodySchema.extend({
version: z.literal(7).optional(),
});
export const persistedStateV8Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(8).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(),
});
const persistedStateSchema = z.union([
persistedStateV8Schema,
persistedStateV7Schema,
persistedStateV6Schema,
persistedStateV5Schema,
@@ -252,7 +259,14 @@ function hydrateThread(
activeTerminalGroupId,
session: null,
messages: thread.messages.map((message) => {
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
const hydratedAttachments = message.attachments?.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
...(attachment.previewUrl ? { previewUrl: attachment.previewUrl } : {}),
}));
return {
id: message.id,
role: message.role,
@@ -312,9 +326,9 @@ export function hydratePersistedState(
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV7Schema> {
): z.infer<typeof persistedStateV8Schema> {
return {
version: 7,
version: 8,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
@@ -340,6 +354,9 @@ export function toPersistedState(
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
...(attachment.previewUrl && /^data:image\//i.test(attachment.previewUrl)
? { previewUrl: attachment.previewUrl }
: {}),
})),
}
: {}),
+110 -19
View File
@@ -5,13 +5,19 @@ import {
createElement,
useContext,
useEffect,
useRef,
useReducer,
useState,
} from "react";
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import {
type PersistedStoreSnapshot,
hydratePersistedState,
toPersistedState,
} from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession, readNativeApi } from "./session-logic";
import {
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
@@ -25,6 +31,7 @@ import {
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "HYDRATE_PERSISTED_STATE"; snapshot: PersistedStoreSnapshot }
| { type: "ADD_PROJECT"; project: Project }
| { type: "SYNC_PROJECTS"; projects: Project[] }
| { type: "TOGGLE_PROJECT"; projectId: string }
@@ -75,8 +82,10 @@ export interface AppState {
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_STATE_PRIMARY_KEY = "t3code:renderer-state:v8";
const LEGACY_PERSISTED_STATE_KEYS = [
LEGACY_PERSISTED_STATE_PRIMARY_KEY,
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
@@ -97,35 +106,30 @@ const initialState: AppState = {
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
function readLegacyPersistedStateFromLocalStorage(): PersistedStoreSnapshot | null {
if (typeof window === "undefined") return null;
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const rawCurrent = window.localStorage.getItem(LEGACY_PERSISTED_STATE_PRIMARY_KEY);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState;
if (!raw) return null;
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false };
return hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
} catch {
return initialState;
return null;
}
}
function persistState(state: AppState): void {
function clearLegacyPersistedStateFromLocalStorage(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
// Ignore storage errors.
}
}
@@ -409,6 +413,16 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "HYDRATE_PERSISTED_STATE":
return {
...state,
projects: action.snapshot.projects,
threads: action.snapshot.threads,
activeThreadId: action.snapshot.activeThreadId,
runtimeMode: action.snapshot.runtimeMode,
diffOpen: false,
};
case "ADD_PROJECT":
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
return state;
@@ -842,11 +856,88 @@ const StoreContext = createContext<{
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
const [state, dispatch] = useReducer(reducer, initialState);
const [persistenceReady, setPersistenceReady] = useState(false);
const bootstrapStartedRef = useRef(false);
const lastPersistedStateJsonRef = useRef<string | null>(null);
useEffect(() => {
persistState(state);
}, [state]);
if (bootstrapStartedRef.current) return;
bootstrapStartedRef.current = true;
let disposed = false;
const api = readNativeApi();
if (!api) {
setPersistenceReady(true);
return;
}
void (async () => {
try {
const serverSnapshot = await api.server.getRendererState();
if (disposed) return;
const hydratedFromServer = serverSnapshot
? hydratePersistedState(serverSnapshot.stateJson, false)
: null;
if (hydratedFromServer) {
lastPersistedStateJsonRef.current = serverSnapshot?.stateJson ?? null;
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedFromServer });
clearLegacyPersistedStateFromLocalStorage();
return;
}
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
if (!hydratedLegacy) return;
const migratedStateJson = JSON.stringify(toPersistedState(hydratedLegacy));
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
try {
await api.server.setRendererState({ stateJson: migratedStateJson });
if (!disposed) {
lastPersistedStateJsonRef.current = migratedStateJson;
clearLegacyPersistedStateFromLocalStorage();
}
} catch {
// Keep running with hydrated legacy state. Persist effect will retry.
}
} catch {
if (disposed) return;
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
if (hydratedLegacy) {
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
}
} finally {
if (!disposed) {
setPersistenceReady(true);
}
}
})();
return () => {
disposed = true;
};
}, [dispatch]);
useEffect(() => {
if (!persistenceReady) return;
const api = readNativeApi();
if (!api) return;
const stateJson = JSON.stringify(toPersistedState(state));
if (lastPersistedStateJsonRef.current === stateJson) return;
const persistTimer = window.setTimeout(() => {
void api.server
.setRendererState({ stateJson })
.then(() => {
lastPersistedStateJsonRef.current = stateJson;
})
.catch(() => undefined);
}, 150);
return () => {
window.clearTimeout(persistTimer);
};
}, [persistenceReady, state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
+2
View File
@@ -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),
},
};
+2 -1
View File
@@ -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",
+1
View File
@@ -7,5 +7,6 @@ export * from "./model";
export * from "./ws";
export * from "./keybindings";
export * from "./server";
export * from "./rendererState";
export * from "./project";
export * from "./git";
+3
View File
@@ -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>;
};
}
@@ -14,6 +14,18 @@ describe("keybindings contracts", () => {
command: "terminal.toggle",
});
assert.strictEqual(parsed.command, "terminal.toggle");
const parsedClose = keybindingRuleSchema.parse({
key: "mod+w",
command: "terminal.close",
});
assert.strictEqual(parsedClose.command, "terminal.close");
const parsedLocal = keybindingRuleSchema.parse({
key: "mod+shift+n",
command: "chat.newLocal",
});
assert.strictEqual(parsedLocal.command, "chat.newLocal");
});
it("rejects invalid command values", () => {
+2
View File
@@ -4,7 +4,9 @@ export const keybindingCommandSchema = z.enum([
"terminal.toggle",
"terminal.split",
"terminal.new",
"terminal.close",
"chat.new",
"chat.newLocal",
"editor.openFavorite",
]);
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { rendererStateSetInputSchema, rendererStateSnapshotSchema } from "./rendererState";
describe("rendererState contracts", () => {
it("parses renderer state snapshot", () => {
const parsed = rendererStateSnapshotSchema.parse({
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
updatedAt: "2026-02-18T10:00:00.000Z",
});
expect(parsed.updatedAt).toBe("2026-02-18T10:00:00.000Z");
});
it("requires non-empty stateJson for set input", () => {
expect(() => rendererStateSetInputSchema.parse({ stateJson: "" })).toThrow();
});
});
+15
View File
@@ -0,0 +1,15 @@
import { z } from "zod";
export const RENDERER_STATE_MAX_JSON_CHARS = 25_000_000;
export const rendererStateSnapshotSchema = z.object({
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
updatedAt: z.string().datetime(),
});
export const rendererStateSetInputSchema = z.object({
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
});
export type RendererStateSnapshot = z.infer<typeof rendererStateSnapshotSchema>;
export type RendererStateSetInput = z.input<typeof rendererStateSetInputSchema>;
+2
View File
@@ -40,6 +40,8 @@ export const WS_METHODS = {
// Server meta
serverGetConfig: "server.getConfig",
serverGetRendererState: "server.getRendererState",
serverSetRendererState: "server.setRendererState",
} as const;
// ── Push Event Channels ──────────────────────────────────────────────