Compare commits

..
Author SHA1 Message Date
Cursor Agent e4e943d6ef refactor: extract shared normalizeProjectScripts into @t3tools/contracts
Move the duplicated script normalization logic (dedup-by-id + single
runOnWorktreeCreate enforcement) from apps/web/src/store.ts and
apps/server/src/projectRegistry.ts into packages/contracts/src/project.ts
so both consumers share one canonical implementation.
2026-02-18 08:57:36 +00:00
Cursor Agent 58a784074b Remove dead code: unused shell env injection functions
Remove injectEnvIntoShellCommand, shellEscapePosix,
shellEscapeWindowsSetValue, ENV_KEY_PATTERN, and the now-unused
isWindowsPlatform import. These were leftover from an earlier approach
where env vars were injected into the shell command string, replaced
by passing env directly to terminal.open.

Applied via @cursor push command
2026-02-18 08:41:07 +00:00
Cursor Agent e31fcbdf26 Fix terminal stability bugs: remove autoFocus from effect deps, stabilize memo, remove dead export
- Remove autoFocus from the main terminal setup effect dependency array to
  prevent full terminal teardown/recreation when switching tabs in split view.
  Focus is already handled by a dedicated effect.
- Change threadTerminalRuntimeEnv memo dependency from activeProject to
  activeProject?.cwd so unrelated project state changes (e.g. saving scripts)
  don't trigger terminal re-initialization.
- Unexport injectEnvIntoShellCommand which is never imported by production
  code (env injection is handled server-side), and remove its tests.

Applied via @cursor push command
2026-02-18 08:20:50 +00:00
Julius Marminge b033c60d41 Handle optional terminal dimensions and preserve active terminal size
- make `cols`/`rows` optional in terminal open contracts
- default new/restarted sessions to 120x30 when size hints are missing
- reuse existing terminal dimensions unless a new size is explicitly requested
- only send script terminal size hints when creating a new terminal
2026-02-17 23:19:28 -08:00
Julius Marmingeandcodex 2a5525a9e5 Reset script dialog state after close animation
- Clear form fields only after the dialog close completes to avoid stale state during transitions
- Keep icon picker closed when the dialog closes

Co-authored-by: codex <[email protected]>
2026-02-17 23:09:09 -08:00
Julius Marminge 0e500fe025 Pass runtime env through terminal open and disable zsh prompt spacer
- add optional `env` to terminal open contract and validate env keys/limits
- propagate runtime env from web terminal/script launches to server PTY spawn
- start `zsh` with `-o nopromptsp` to avoid trailing `%` markers and add coverage
2026-02-17 23:01:21 -08:00
Julius Marmingeandcodex 442bab63e8 Require modifier keys for script keybinding capture
Co-authored-by: codex <[email protected]>
2026-02-17 22:21:13 -08:00
Julius Marmingeandcodex 191883e599 Fix keybindings parse error wrapping behavior
Co-authored-by: codex <[email protected]>
2026-02-17 22:08:13 -08:00
Julius Marmingeandcodex dca0b9fb33 Refactor project script persistence flow in ChatView
Co-authored-by: codex <[email protected]>
2026-02-17 21:50:40 -08:00
Julius Marmingeandcodex 4437965135 Label setup scripts in project action menu
Co-authored-by: codex <[email protected]>
2026-02-17 21:47:54 -08:00
Julius Marmingeandcodex 5f94bfd5fe Fix Windows percent escaping in script env injection
Co-authored-by: codex <[email protected]>
2026-02-17 21:33:22 -08:00
Julius Marmingeandcodex 718a682782 Address second-pass PR feedback on parser hardening
Co-authored-by: codex <[email protected]>
2026-02-17 21:32:30 -08:00
Julius Marmingeandcodex b7cf04ba93 Address PR review feedback for scripts/keybindings handling
Co-authored-by: codex <[email protected]>
2026-02-17 21:17:57 -08:00
Julius Marmingeandcodex 56bce5617a Fix web typecheck for optional script env
Only pass extraEnv to projectScriptRuntimeEnv when defined to satisfy exactOptionalPropertyTypes in CI.

Co-authored-by: codex <[email protected]>
2026-02-17 21:07:05 -08:00
Julius Marminge 1327646d42 Support script editing and persist project keybindings
- add server `upsertKeybinding` flow to write `~/.t3/keybindings.json` and refresh cached config
- wire project script create/edit to save optional keybindings via the WS API
- improve script action UI with edit controls, icon picker, and preferred-script recall
- add coverage for keybinding upsert behavior in server and websocket tests
2026-02-17 19:53:22 -08:00
Julius Marminge 4f36062f9b Add project script actions with run shortcuts and persistence
- add project-scoped script actions in the chat toolbar, including setup-on-worktree-create
- support dynamic `script.{id}.run` keybindings and command resolution
- persist and sync project scripts across web state, contracts, WebSocket API, and server registry
- add backend and frontend tests for script helpers, persistence, and registry behavior
2026-02-17 19:52:27 -08:00
119 changed files with 3958 additions and 9294 deletions

No files matched your search

-1
View File
@@ -10,4 +10,3 @@ packages/*/dist
.env.local
build/
.logs/
release/
+1 -8
View File
@@ -1,13 +1,6 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
],
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
+2 -16
View File
@@ -56,9 +56,6 @@ T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
bun run build
bun run start
# Build a shareable macOS .dmg (arm64 by default)
bun run dist:desktop:dmg
# Or from any project directory after publishing:
npx t3
```
@@ -72,17 +69,6 @@ npx t3
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
### Desktop `.dmg` packaging notes
- Default build is unsigned/not notarized for local sharing.
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
### Running multiple dev instances
@@ -106,12 +92,12 @@ T3 Code has a global runtime mode switch in the chat toolbar:
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
- `providers.respondToRequest`, `providers.stopSession`
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
- `shell.openInEditor`, `server.getConfig`
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
+1 -3
View File
@@ -2,8 +2,6 @@
## Small things
- [ ] Plan mode
- [ ] Submitting new messages should scroll to bottom
- [ ] 1 click copy in codeblocks
- [x] Pasting/adding images to submit with prompts
- [ ] Only show last 10 threads for a given project
@@ -14,7 +12,7 @@
- [x] "Response" bar should ONLY appear on work completed
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [x] Insta focus input on new thread creation
- [ ] Insta focus input on new thread creation
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
-1
View File
@@ -1,2 +1 @@
dist-electron/
.electron-runtime/
+2 -3
View File
@@ -2,20 +2,19 @@
"name": "@t3tools/desktop",
"version": "0.0.0",
"private": true,
"productName": "T3 Code (Alpha)",
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "tsdown",
"start": "bun run scripts/start-electron.mjs",
"start": "electron dist-electron/main.js",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"electron": "40.6.0"
"electron": "33.4.11"
},
"devDependencies": {
"@types/node": "^22.10.2",
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 313 KiB

+6 -48
View File
@@ -1,10 +1,7 @@
import { spawnSync } from "node:child_process";
import { spawn } from "node:child_process";
import electronmon from "electronmon";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const devServerUrl = `http://localhost:${port}`;
@@ -17,57 +14,18 @@ await waitOn({
],
});
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const monitor = await electronmon({
cwd: desktopDir,
args: ["dist-electron/main.js"],
const child = spawn(command, ["dist-electron/main.js"], {
stdio: "inherit",
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
electronPath: resolveElectronPath(),
});
let shuttingDown = false;
function killChildTree(signal) {
if (process.platform === "win32") {
return;
}
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
}
async function shutdown(exitCode) {
if (shuttingDown) return;
shuttingDown = true;
try {
await Promise.race([
monitor.destroy(),
new Promise((resolve) => setTimeout(resolve, 1_500)),
]);
} catch {
// Best effort only; fallback process kill below handles stubborn children.
}
killChildTree("TERM");
setTimeout(() => {
killChildTree("KILL");
}, 1_200).unref();
process.exit(exitCode);
}
process.once("SIGINT", () => {
void shutdown(130);
});
process.once("SIGTERM", () => {
void shutdown(143);
});
process.once("SIGHUP", () => {
void shutdown(129);
child.on("exit", (code) => {
process.exit(code ?? 0);
});
-173
View File
@@ -1,173 +0,0 @@
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
import { spawnSync } from "node:child_process";
import {
copyFileSync,
cpSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
export const desktopDir = resolve(__dirname, "..");
function setPlistString(plistPath, key, value) {
const replaceResult = spawnSync(
"plutil",
["-replace", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (replaceResult.status === 0) {
return;
}
const insertResult = spawnSync(
"plutil",
["-insert", key, "-string", value, plistPath],
{
encoding: "utf8",
},
);
if (insertResult.status === 0) {
return;
}
const details = [replaceResult.stderr, insertResult.stderr]
.filter(Boolean)
.join("\n");
throw new Error(
`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim(),
);
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
const resourcesDir = join(appBundlePath, "Contents", "Resources");
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
}
function patchHelperBundleInfoPlists(appBundlePath) {
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
if (!existsSync(frameworksDir)) {
return;
}
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
continue;
}
if (!entry.name.startsWith("Electron Helper")) {
continue;
}
const helperPlistPath = join(
frameworksDir,
entry.name,
"Contents",
"Info.plist",
);
if (!existsSync(helperPlistPath)) {
continue;
}
const suffix = entry.name
.replace("Electron Helper", "")
.replace(".app", "")
.trim();
const helperName = suffix
? `${APP_DISPLAY_NAME} Helper ${suffix}`
: `${APP_DISPLAY_NAME} Helper`;
const helperIdSuffix = suffix
.replace(/[()]/g, "")
.trim()
.toLowerCase()
.replace(/\s+/g, "-");
const helperBundleId = helperIdSuffix
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
: `${APP_BUNDLE_ID}.helper`;
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
setPlistString(helperPlistPath, "CFBundleName", helperName);
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
}
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, "utf8"));
} catch {
return null;
}
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(
targetAppBundlePath,
"Contents",
"MacOS",
"Electron",
);
const iconPath = join(desktopDir, "resources", "icon.icns");
const metadataPath = join(runtimeDir, "metadata.json");
mkdirSync(runtimeDir, { recursive: true });
const expectedMetadata = {
launcherVersion: LAUNCHER_VERSION,
sourceAppBundlePath,
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
iconMtimeMs: statSync(iconPath).mtimeMs,
};
const currentMetadata = readJson(metadataPath);
if (
existsSync(targetBinaryPath) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
return targetBinaryPath;
}
rmSync(targetAppBundlePath, { recursive: true, force: true });
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchHelperBundleInfoPlists(targetAppBundlePath);
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
return targetBinaryPath;
}
export function resolveElectronPath() {
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (process.platform !== "darwin") {
return electronBinaryPath;
}
return buildMacLauncher(electronBinaryPath);
}
-20
View File
@@ -1,20 +0,0 @@
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
+14 -289
View File
@@ -5,16 +5,7 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
type MenuItemConstructorOptions,
protocol,
shell,
} from "electron";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
@@ -25,13 +16,11 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
@@ -41,235 +30,6 @@ let backendWsUrl = "";
let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
let desktopProtocolRegistered = false;
protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
function resolveAppRoot(): string {
if (!app.isPackaged) {
return ROOT_DIR;
}
return app.getAppPath();
}
function resolveBackendEntry(): string {
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
if (!app.isPackaged) {
return resolveAppRoot();
}
return os.homedir();
}
function resolveDesktopStaticDir(): string | null {
const appRoot = resolveAppRoot();
const candidates = [
path.join(appRoot, "apps/server/dist/client"),
path.join(appRoot, "apps/web/dist"),
];
for (const candidate of candidates) {
if (fs.existsSync(path.join(candidate, "index.html"))) {
return candidate;
}
}
return null;
}
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
const url = new URL(requestUrl);
const rawPath = decodeURIComponent(url.pathname);
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
if (normalizedPath.includes("..")) {
return path.join(staticRoot, "index.html");
}
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
const resolvedPath = path.join(staticRoot, requestedPath);
if (path.extname(resolvedPath)) {
return resolvedPath;
}
const nestedIndex = path.join(resolvedPath, "index.html");
if (fs.existsSync(nestedIndex)) {
return nestedIndex;
}
return path.join(staticRoot, "index.html");
}
function isStaticAssetRequest(requestUrl: string): boolean {
try {
const url = new URL(requestUrl);
return path.extname(url.pathname).length > 0;
} catch {
return false;
}
}
function registerDesktopProtocol(): void {
if (isDevelopment || desktopProtocolRegistered) return;
const staticRoot = resolveDesktopStaticDir();
if (!staticRoot) {
throw new Error("Desktop static bundle missing. Build apps/server (with bundled client) first.");
}
const staticRootResolved = path.resolve(staticRoot);
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
const fallbackIndex = path.join(staticRootResolved, "index.html");
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
try {
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
const resolvedCandidate = path.resolve(candidate);
const isInRoot =
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
const isAssetRequest = isStaticAssetRequest(request.url);
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
if (isAssetRequest) {
callback({ error: -6 });
return;
}
callback({ path: fallbackIndex });
return;
}
callback({ path: resolvedCandidate });
} catch {
callback({ path: fallbackIndex });
}
});
desktopProtocolRegistered = true;
}
function dispatchMenuAction(action: string): void {
const existingWindow = BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
const targetWindow = existingWindow ?? createWindow();
if (!existingWindow) {
mainWindow = targetWindow;
}
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
if (!targetWindow.isVisible()) {
targetWindow.show();
}
targetWindow.focus();
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
}
function configureApplicationMenu(): void {
const template: MenuItemConstructorOptions[] = [];
if (process.platform === "darwin") {
template.push({
label: app.name,
submenu: [
{ role: "about" },
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
});
}
template.push(
{
label: "File",
submenu: [
...(process.platform === "darwin"
? []
: [
{
label: "Settings...",
accelerator: "CmdOrCtrl+,",
click: () => dispatchMenuAction("open-settings"),
},
{ type: "separator" as const },
]),
{ role: process.platform === "darwin" ? "close" : "quit" },
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
);
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
function resolveResourcePath(fileName: string): string | null {
const candidates = [
path.join(__dirname, "../resources", fileName),
path.join(process.resourcesPath, "resources", fileName),
path.join(process.resourcesPath, fileName),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
}
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
return resolveResourcePath(`icon.${ext}`);
}
function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME);
app.setAboutPanelOptions({
applicationName: APP_DISPLAY_NAME,
});
if (process.platform === "win32") {
app.setAppUserModelId(APP_USER_MODEL_ID);
}
if (process.platform === "darwin" && app.dock) {
const iconPath = resolveIconPath("png");
if (iconPath) {
app.dock.setIcon(iconPath);
}
}
}
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
@@ -316,14 +76,13 @@ function scheduleBackendRestart(reason: string): void {
function startBackend(): void {
if (isQuitting || backendProcess) return;
const backendEntry = resolveBackendEntry();
if (!fs.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
if (!fs.existsSync(BACKEND_ENTRY)) {
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
return;
}
const child = spawn(process.execPath, [backendEntry], {
cwd: resolveBackendCwd(),
const child = spawn(process.execPath, [BACKEND_ENTRY], {
cwd: ROOT_DIR,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
@@ -365,10 +124,10 @@ function stopBackend(): void {
backendProcess = null;
if (!child) return;
if (child.exitCode === null && child.signalCode === null) {
if (!child.killed) {
child.kill("SIGTERM");
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
if (!child.killed) {
child.kill("SIGKILL");
}
}, 2_000).unref();
@@ -445,13 +204,6 @@ function registerIpcHandlers(): void {
});
}
function getIconOption(): { icon: string } | Record<string, never> {
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
const ext = process.platform === "win32" ? "ico" : "png";
const iconPath = resolveIconPath(ext);
return iconPath ? { icon: iconPath } : {};
}
function createWindow(): BrowserWindow {
const window = new BrowserWindow({
width: 1100,
@@ -460,8 +212,6 @@ function createWindow(): BrowserWindow {
minHeight: 620,
show: false,
autoHideMenuBar: true,
...getIconOption(),
title: APP_DISPLAY_NAME,
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 16, y: 18 },
webPreferences: {
@@ -473,13 +223,6 @@ function createWindow(): BrowserWindow {
});
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(APP_DISPLAY_NAME);
});
window.webContents.on("did-finish-load", () => {
window.setTitle(APP_DISPLAY_NAME);
});
window.once("ready-to-show", () => {
window.show();
});
@@ -488,7 +231,10 @@ function createWindow(): BrowserWindow {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
}
window.on("closed", () => {
@@ -500,8 +246,6 @@ function createWindow(): BrowserWindow {
return window;
}
configureAppIdentity();
async function bootstrap(): Promise<void> {
backendPort = await reserveLoopbackPort();
backendAuthToken = randomBytes(24).toString("hex");
@@ -519,9 +263,6 @@ app.on("before-quit", () => {
});
app.whenReady().then(() => {
configureAppIdentity();
configureApplicationMenu();
registerDesktopProtocol();
void bootstrap();
app.on("activate", () => {
@@ -536,19 +277,3 @@ app.on("window-all-closed", () => {
app.quit();
}
});
if (process.platform !== "win32") {
process.on("SIGINT", () => {
if (isQuitting) return;
isQuitting = true;
stopBackend();
app.quit();
});
process.on("SIGTERM", () => {
if (isQuitting) return;
isQuitting = true;
stopBackend();
app.quit();
});
}
-12
View File
@@ -4,7 +4,6 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
@@ -14,15 +13,4 @@ contextBridge.exposeInMainWorld("desktopBridge", {
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
onMenuAction: (listener: (action: string) => void) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
listener(action);
};
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
};
},
});
-5
View File
@@ -17,11 +17,6 @@
"test": "vitest run"
},
"dependencies": {
"@effect/platform": "^0.94.5",
"@effect/platform-node": "^0.104.1",
"@effect/sql": "^0.49.0",
"@effect/sql-sqlite-node": "^0.50.1",
"effect": "^3.19.19",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
@@ -43,36 +43,6 @@ function createSendTurnHarness() {
return { manager, context, requireSession, sendRequest, updateSession };
}
function createThreadControlHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
);
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -143,40 +113,6 @@ describe("isRecoverableThreadResumeError", () => {
});
});
describe("startSession", () => {
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = new CodexAppServerManager();
const events: Array<{ method: string; kind: string; message?: string }> = [];
manager.on("event", (event) => {
events.push({
method: event.method,
kind: event.kind,
...(event.message ? { message: event.message } : {}),
});
});
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
throw new Error("cwd missing");
});
try {
await expect(
manager.startSession({
provider: "codex",
}),
).rejects.toThrow("cwd missing");
expect(events).toHaveLength(1);
expect(events[0]).toEqual({
method: "session/startFailed",
kind: "error",
message: "cwd missing",
});
} finally {
processCwd.mockRestore();
manager.stopAll();
}
});
});
describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } =
@@ -262,91 +198,3 @@ describe("sendTurn", () => {
).rejects.toThrow("Turn input must include text or attachments.");
});
});
describe("thread checkpoint control", () => {
it("reads thread turns from thread/read", async () => {
const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
sendRequest.mockResolvedValue({
thread: {
id: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
},
});
const result = await manager.readThread("sess_1");
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
includeTurns: true,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
});
it("reads thread turns from flat thread/read responses", async () => {
const { manager, context, sendRequest } = createThreadControlHarness();
sendRequest.mockResolvedValue({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
const result = await manager.readThread("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
threadId: "thread_1",
includeTurns: true,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [
{
id: "turn_1",
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
},
],
});
});
it("rolls back turns via thread/rollback and resets session running state", async () => {
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
sendRequest.mockResolvedValue({
thread: {
id: "thread_1",
turns: [],
},
});
const result = await manager.rollbackThread("sess_1", 2);
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
threadId: "thread_1",
numTurns: 2,
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "ready",
activeTurnId: undefined,
});
expect(result).toEqual({
threadId: "thread_1",
turns: [],
});
});
});
+38 -138
View File
@@ -65,16 +65,6 @@ interface JsonRpcNotification {
params?: unknown;
}
export interface CodexThreadTurnSnapshot {
id: string;
items: unknown[];
}
export interface CodexThreadSnapshot {
threadId: string;
turns: CodexThreadTurnSnapshot[];
}
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
const CODEX_STDERR_LOG_REGEX =
@@ -148,48 +138,40 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
const sessionId = randomUUID();
const now = new Date().toISOString();
let context: CodexSessionContext | undefined;
const session: ProviderSession = {
sessionId,
provider: "codex",
status: "connecting",
model: normalizeCodexModelSlug(input.model),
cwd: input.cwd,
createdAt: now,
updatedAt: now,
};
const child = spawn("codex", ["app-server"], {
cwd: input.cwd,
env: process.env,
stdio: ["pipe", "pipe", "pipe"],
});
const output = readline.createInterface({ input: child.stdout });
const context: CodexSessionContext = {
session,
child,
output,
pending: new Map(),
pendingApprovals: new Map(),
nextRequestId: 1,
stopping: false,
};
this.sessions.set(sessionId, context);
this.attachProcessListeners(context);
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
try {
const resolvedCwd = input.cwd ?? process.cwd();
const session: ProviderSession = {
sessionId,
provider: "codex",
status: "connecting",
model: normalizeCodexModelSlug(input.model),
cwd: resolvedCwd,
createdAt: now,
updatedAt: now,
};
const codexBinaryPath = input.codexBinaryPath?.trim() || "codex";
const codexHomePath = input.codexHomePath?.trim();
const child = spawn(codexBinaryPath, ["app-server"], {
cwd: resolvedCwd,
env: {
...process.env,
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
});
const output = readline.createInterface({ input: child.stdout });
context = {
session,
child,
output,
pending: new Map(),
pendingApprovals: new Map(),
nextRequestId: 1,
stopping: false,
};
this.sessions.set(sessionId, context);
this.attachProcessListeners(context);
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
await this.sendRequest(context, "initialize", {
clientInfo: {
name: "t3code_desktop",
@@ -259,24 +241,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return { ...context.session };
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
if (context) {
this.updateSession(context, {
status: "error",
lastError: message,
});
this.emitErrorEvent(context, "session/startFailed", message);
this.stopSession(sessionId);
} else {
this.emitEvent({
id: randomUUID(),
kind: "error",
provider: "codex",
sessionId,
createdAt: new Date().toISOString(),
method: "session/startFailed",
message,
});
}
this.updateSession(context, {
status: "error",
lastError: message,
});
this.emitErrorEvent(context, "session/startFailed", message);
this.stopSession(sessionId);
throw new Error(message, { cause: error });
}
}
@@ -361,41 +331,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
});
}
async readThread(sessionId: string): Promise<CodexThreadSnapshot> {
const context = this.requireSession(sessionId);
const threadId = context.session.threadId;
if (!threadId) {
throw new Error("Session is missing a thread id.");
}
const response = await this.sendRequest(context, "thread/read", {
threadId,
includeTurns: true,
});
return this.parseThreadSnapshot("thread/read", response);
}
async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
const context = this.requireSession(sessionId);
const threadId = context.session.threadId;
if (!threadId) {
throw new Error("Session is missing a thread id.");
}
if (!Number.isInteger(numTurns) || numTurns < 1) {
throw new Error("numTurns must be an integer >= 1.");
}
const response = await this.sendRequest(context, "thread/rollback", {
threadId,
numTurns,
});
this.updateSession(context, {
status: "ready",
activeTurnId: undefined,
});
return this.parseThreadSnapshot("thread/rollback", response);
}
async respondToRequest(
sessionId: string,
requestId: string,
@@ -807,31 +742,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return undefined;
}
private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
const responseRecord = this.readObject(response);
const thread = this.readObject(responseRecord, "thread");
const threadId = this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
if (!threadId) {
throw new Error(`${method} response did not include a thread id.`);
}
const turnsRaw = this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
const turns = turnsRaw.map((turnValue, index) => {
const turn = this.readObject(turnValue);
const turnId = this.readString(turn, "id") ?? `${threadId}:turn:${index + 1}`;
const items = this.readArray(turn, "items") ?? [];
return {
id: turnId,
items,
};
});
return {
threadId,
turns,
};
}
private isServerRequest(value: unknown): value is JsonRpcRequest {
if (!value || typeof value !== "object") {
return false;
@@ -913,16 +823,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return target as Record<string, unknown>;
}
private readArray(value: unknown, key?: string): unknown[] | undefined {
const target =
key === undefined
? value
: value && typeof value === "object"
? (value as Record<string, unknown>)[key]
: undefined;
return Array.isArray(target) ? target : undefined;
}
private readString(value: unknown, key: string): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
@@ -1,243 +0,0 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { checkpointRefForThreadTurn, FilesystemCheckpointStore } from "./filesystemCheckpointStore";
import { runProcess } from "./processRunner";
async function runGit(cwd: string, args: readonly string[]): Promise<string> {
const result = await runProcess("git", args, {
cwd,
allowNonZeroExit: true,
});
if (result.code !== 0) {
throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed`);
}
return result.stdout.trim();
}
function exists(filePath: string): boolean {
return fs.existsSync(filePath);
}
async function createRepo(): Promise<string> {
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-test-"));
await runGit(cwd, ["init", "--initial-branch=main"]);
await runGit(cwd, ["config", "user.email", "[email protected]"]);
await runGit(cwd, ["config", "user.name", "Test User"]);
await writeFile(path.join(cwd, "README.md"), "v1\n");
await writeFile(path.join(cwd, "tracked.txt"), "tracked-v1\n");
await runGit(cwd, ["add", "."]);
await runGit(cwd, ["commit", "-m", "Initial"]);
return cwd;
}
async function createRepoWithoutHead(): Promise<string> {
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-empty-test-"));
await runGit(cwd, ["init", "--initial-branch=main"]);
return cwd;
}
describe("FilesystemCheckpointStore", () => {
it("captures refs without mutating branch history and restores workspace state", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_1";
try {
const headBefore = await runGit(cwd, ["rev-parse", "HEAD"]);
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
const rootRef = checkpointRefForThreadTurn(threadId, 0);
const rootCommit = await runGit(cwd, ["rev-parse", "--verify", `${rootRef}^{commit}`]);
expect(rootCommit.length).toBeGreaterThan(0);
expect(await runGit(cwd, ["rev-parse", "HEAD"])).toBe(headBefore);
await writeFile(path.join(cwd, "README.md"), "v2\n");
await rm(path.join(cwd, "tracked.txt"));
await writeFile(path.join(cwd, "notes.md"), "notes\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
await writeFile(path.join(cwd, "README.md"), "v3\n");
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
await writeFile(path.join(cwd, "tracked.txt"), "tracked-new\n");
const restoredRoot = await store.restoreCheckpoint({ cwd, threadId, turnCount: 0 });
expect(restoredRoot).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
expect(await readFile(path.join(cwd, "tracked.txt"), "utf8")).toBe("tracked-v1\n");
expect(exists(path.join(cwd, "notes.md"))).toBe(false);
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
const restoredTurn1 = await store.restoreCheckpoint({ cwd, threadId, turnCount: 1 });
expect(restoredTurn1).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v2\n");
expect(exists(path.join(cwd, "tracked.txt"))).toBe(false);
expect(await readFile(path.join(cwd, "notes.md"), "utf8")).toBe("notes\n");
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("returns false when restoring a missing checkpoint", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
try {
const restored = await store.restoreCheckpoint({
cwd,
threadId: "thr_2",
turnCount: 999,
});
expect(restored).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("falls back to HEAD when restoring turn 0 and root checkpoint ref is missing", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_2b";
try {
await writeFile(path.join(cwd, "README.md"), "v2\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
await writeFile(path.join(cwd, "README.md"), "v3\n");
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
const restored = await store.restoreCheckpoint({
cwd,
threadId,
turnCount: 0,
});
expect(restored).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("prunes refs newer than the retained turn", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_3";
try {
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
await writeFile(path.join(cwd, "README.md"), "turn1\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
await writeFile(path.join(cwd, "README.md"), "turn2\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 2 });
await store.pruneAfterTurn({
cwd,
threadId,
maxTurnCount: 1,
});
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 0 })).toBe(true);
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 1 })).toBe(true);
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 2 })).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("returns a unified patch between checkpoint turns", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_4";
try {
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
await writeFile(path.join(cwd, "README.md"), "v2\n");
await writeFile(path.join(cwd, "new.txt"), "new file\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
const diff = await store.diffCheckpoints({
cwd,
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
expect(diff).toContain("diff --git a/README.md b/README.md");
expect(diff).toContain("diff --git a/new.txt b/new.txt");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("falls back to HEAD as diff base when turn 0 checkpoint is missing", async () => {
const cwd = await createRepo();
const store = new FilesystemCheckpointStore();
const threadId = "thr_5";
try {
await writeFile(path.join(cwd, "README.md"), "v2\n");
await writeFile(path.join(cwd, "new.txt"), "new file\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
const diff = await store.diffCheckpoints({
cwd,
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
expect(diff).toContain("diff --git a/README.md b/README.md");
expect(diff).toContain("diff --git a/new.txt b/new.txt");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("detects non-repo folders", async () => {
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-nonrepo-"));
const store = new FilesystemCheckpointStore();
try {
expect(await store.isGitRepository(cwd)).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
it("returns false when repository path does not exist", async () => {
const store = new FilesystemCheckpointStore();
const cwd = path.join(os.tmpdir(), `t3-fs-checkpoints-missing-${Date.now()}`);
expect(await store.isGitRepository(cwd)).toBe(false);
});
it("restores checkpoint without reset when repository has no HEAD commit", async () => {
const cwd = await createRepoWithoutHead();
const store = new FilesystemCheckpointStore();
const threadId = "thr-no-head";
try {
await writeFile(path.join(cwd, "README.md"), "first\n");
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
await writeFile(path.join(cwd, "README.md"), "second\n");
const restored = await store.restoreCheckpoint({
cwd,
threadId,
turnCount: 0,
});
expect(restored).toBe(true);
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("first\n");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
});
@@ -1,322 +0,0 @@
import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { runProcess } from "./processRunner";
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function checkpointRefThreadSegment(threadId: string): string {
return Buffer.from(threadId, "utf8").toString("base64url");
}
export function checkpointRefForThreadTurn(threadId: string, turnCount: number): string {
if (!Number.isInteger(turnCount) || turnCount < 0) {
throw new Error(`Invalid checkpoint turn count: ${turnCount}`);
}
return `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/${turnCount}`;
}
interface GitOptions {
env?: NodeJS.ProcessEnv;
stdin?: string;
allowNonZeroExit?: boolean;
}
export class FilesystemCheckpointStore {
async isGitRepository(cwd: string): Promise<boolean> {
try {
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
allowNonZeroExit: true,
});
return result.code === 0 && result.stdout.trim() === "true";
} catch {
return false;
}
}
async captureCheckpoint(input: {
cwd: string;
threadId: string;
turnCount: number;
}): Promise<void> {
const { cwd, threadId, turnCount } = input;
const ref = checkpointRefForThreadTurn(threadId, turnCount);
const tempDir = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoint-"));
try {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const hasHead = await this.hasHeadCommit(cwd);
if (hasHead) {
await this.runGit(cwd, ["read-tree", "HEAD"], { env: commitEnv });
}
await this.runGit(cwd, ["add", "-A", "--", "."], { env: commitEnv });
const writeTreeResult = await this.runGit(cwd, ["write-tree"], { env: commitEnv });
const treeOid = writeTreeResult.stdout.trim();
if (!treeOid) {
throw new Error("git write-tree returned an empty tree oid.");
}
const message = `t3 checkpoint thread=${threadId} turn=${turnCount}`;
const commitTreeResult = await this.runGit(cwd, ["commit-tree", treeOid], {
env: commitEnv,
stdin: `${message}\n`,
});
const commitOid = commitTreeResult.stdout.trim();
if (!commitOid) {
throw new Error("git commit-tree returned an empty commit oid.");
}
await this.runGit(cwd, ["update-ref", ref, commitOid]);
} finally {
await rm(tempDir, { recursive: true, force: true });
}
}
async hasCheckpoint(input: {
cwd: string;
threadId: string;
turnCount: number;
}): Promise<boolean> {
const { cwd, threadId, turnCount } = input;
const ref = checkpointRefForThreadTurn(threadId, turnCount);
const commit = await this.resolveCheckpointCommit(cwd, ref);
return commit !== null;
}
async ensureRootCheckpoint(input: { cwd: string; threadId: string }): Promise<boolean> {
const { cwd, threadId } = input;
const rootRef = checkpointRefForThreadTurn(threadId, 0);
const existing = await this.resolveCheckpointCommit(cwd, rootRef);
if (existing) {
return true;
}
const headCommit = await this.resolveHeadCommit(cwd);
if (!headCommit) {
return false;
}
await this.runGit(cwd, ["update-ref", rootRef, headCommit]);
return true;
}
async restoreCheckpoint(input: {
cwd: string;
threadId: string;
turnCount: number;
}): Promise<boolean> {
const { cwd, threadId, turnCount } = input;
const ref = checkpointRefForThreadTurn(threadId, turnCount);
let commitOid = await this.resolveCheckpointCommit(cwd, ref);
if (!commitOid && turnCount === 0) {
commitOid = await this.resolveHeadCommit(cwd);
}
if (!commitOid) {
return false;
}
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
if (await this.hasHeadCommit(cwd)) {
await this.runGit(cwd, ["reset", "--quiet", "--", "."]);
}
return true;
}
async diffCheckpoints(input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}): Promise<string> {
const { cwd, threadId, fromTurnCount, toTurnCount } = input;
if (!Number.isInteger(fromTurnCount) || fromTurnCount < 0) {
throw new Error(`Invalid from turn count: ${fromTurnCount}`);
}
if (!Number.isInteger(toTurnCount) || toTurnCount < 0) {
throw new Error(`Invalid to turn count: ${toTurnCount}`);
}
if (fromTurnCount > toTurnCount) {
throw new Error(`Invalid checkpoint range: ${fromTurnCount}..${toTurnCount}`);
}
const fromRef = checkpointRefForThreadTurn(threadId, fromTurnCount);
const toRef = checkpointRefForThreadTurn(threadId, toTurnCount);
let fromCommitOid = await this.resolveCheckpointCommit(cwd, fromRef);
const toCommitOid = await this.resolveCheckpointCommit(cwd, toRef);
if (!fromCommitOid && fromTurnCount === 0) {
const headCommit = await this.resolveHeadCommit(cwd);
if (headCommit) {
fromCommitOid = headCommit;
}
}
if (!fromCommitOid) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${fromTurnCount} in thread ${threadId}.`,
);
}
if (!toCommitOid) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${toTurnCount} in thread ${threadId}.`,
);
}
const result = await this.runGit(cwd, [
"diff",
"--patch",
"--minimal",
"--no-color",
fromCommitOid,
toCommitOid,
]);
return result.stdout;
}
private async resolveHeadCommit(cwd: string): Promise<string | null> {
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], {
allowNonZeroExit: true,
});
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}
async pruneAfterTurn(input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}): Promise<void> {
const { cwd, threadId, maxTurnCount } = input;
if (!Number.isInteger(maxTurnCount) || maxTurnCount < 0) {
throw new Error(`Invalid max turn count: ${maxTurnCount}`);
}
const threadRefPrefix = `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/`;
const result = await this.runGit(
cwd,
["for-each-ref", "--format=%(refname)", threadRefPrefix],
{
allowNonZeroExit: true,
},
);
if (result.code !== 0) {
return;
}
const refsToDelete = result.stdout
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.filter((refName) => {
const turn = this.readRefTurnCount(refName);
return turn !== null && turn > maxTurnCount;
});
const batchSize = 32;
const batches = Array.from(
{ length: Math.ceil(refsToDelete.length / batchSize) },
(_, index) => refsToDelete.slice(index * batchSize, (index + 1) * batchSize),
);
await batches.reduce<Promise<void>>((pending, batch) => {
return pending.then(async () => {
await Promise.all(
batch.map((refName) =>
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
),
);
});
}, Promise.resolve());
}
private async hasHeadCommit(cwd: string): Promise<boolean> {
const result = await this.runGit(cwd, ["rev-parse", "--verify", "HEAD"], {
allowNonZeroExit: true,
});
return result.code === 0;
}
private async resolveCheckpointCommit(cwd: string, ref: string): Promise<string | null> {
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
allowNonZeroExit: true,
});
if (result.code !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}
private readRefTurnCount(ref: string): number | null {
const segments = ref.split("/");
const rawTurn = segments.at(-1);
if (!rawTurn) {
return null;
}
const turn = Number.parseInt(rawTurn, 10);
return Number.isInteger(turn) && turn >= 0 ? turn : null;
}
private async runGit(
cwd: string,
args: readonly string[],
options: GitOptions = {},
): Promise<Awaited<ReturnType<typeof runProcess>>> {
let result: Awaited<ReturnType<typeof runProcess>>;
try {
result = await runProcess("git", args, {
cwd,
env: options.env,
stdin: options.stdin,
timeoutMs: DEFAULT_TIMEOUT_MS,
allowNonZeroExit: true,
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
outputMode: "truncate",
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to run ${quoteGitCommand(args)}: ${message}`, { cause: error });
}
if (result.timedOut) {
throw new Error(`${quoteGitCommand(args)} timed out.`);
}
if (result.stdoutTruncated || result.stderrTruncated) {
throw new Error(
`${quoteGitCommand(args)} output exceeded ${DEFAULT_MAX_OUTPUT_BYTES} bytes and was truncated.`,
);
}
if (!options.allowNonZeroExit && result.code !== 0) {
const stderr = result.stderr.trim();
throw new Error(
stderr.length > 0
? `${quoteGitCommand(args)} failed: ${stderr}`
: `${quoteGitCommand(args)} failed with code ${result.code ?? "null"}.`,
);
}
return result;
}
}
-44
View File
@@ -617,32 +617,6 @@ describe("git integration", () => {
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
expect(existsSync(wtPath)).toBe(false);
});
it("removeGitWorktree force removes a dirty worktree", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const wtPath = path.join(tmp.path, "wt-dirty-dir");
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(b) => b.current,
)!.name;
await createGitWorktree({
cwd: tmp.path,
branch: currentBranch,
newBranch: "wt-dirty",
path: wtPath,
});
expect(existsSync(wtPath)).toBe(true);
await writeFile(path.join(wtPath, "README.md"), "dirty change\n");
await expect(removeGitWorktree({ cwd: tmp.path, path: wtPath })).rejects.toThrow();
expect(existsSync(wtPath)).toBe(true);
await removeGitWorktree({ cwd: tmp.path, path: wtPath, force: true });
expect(existsSync(wtPath)).toBe(false);
});
});
// ── Full flow: local branch checkout ──
@@ -786,24 +760,6 @@ describe("git integration", () => {
expect(dirty.hasWorkingTreeChanges).toBe(true);
});
it("includes command context when worktree removal fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const missingWorktreePath = path.join(tmp.path, "missing-worktree");
const error = await core
.removeWorktree({ cwd: tmp.path, path: missingWorktreePath })
.then(() => null)
.catch((err: unknown) => err);
expect(error).toBeInstanceOf(Error);
const message = (error as Error).message;
expect(message).toContain("git worktree remove");
expect(message).toContain(`cwd: ${tmp.path}`);
expect(message).toContain(missingWorktreePath);
});
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
await using remote = await makeTmpDir();
await using source = await makeTmpDir();
+4 -16
View File
@@ -546,22 +546,10 @@ export class GitCoreService {
}
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
const args = ["worktree", "remove"];
if (input.force) {
args.push("--force");
}
args.push(input.path);
try {
await executeGit(input.cwd, args, {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
});
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`${commandLabel(args)} failed (cwd: ${input.cwd}): ${detail}`, {
cause: error,
});
}
await executeGit(input.cwd, ["worktree", "remove", input.path], {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
});
}
async createBranch(input: GitCreateBranchInput): Promise<void> {
-1
View File
@@ -118,7 +118,6 @@ async function main() {
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
cwd,
stateDir,
staticDir,
devUrl,
projectRegistry,
@@ -1,388 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Effect } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import type { OrchestrationEventRepositoryShape } from "../persistence/Services/OrchestrationEvents";
import { OrchestrationEngine } from "./engine";
import { createOrchestrationSystem } from "./runtime";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("OrchestrationEngine", () => {
it("replays to the same deterministic snapshot", async () => {
const stateDir = makeTempDir("t3code-orchestration-");
const createdAt = new Date().toISOString();
const projectId = "project-1";
const threadId = "thread-1";
const firstSystem = await createOrchestrationSystem(stateDir);
const engineA = firstSystem.engine;
await engineA.dispatch({
type: "project.create",
commandId: "cmd-1",
projectId,
name: "demo",
cwd: "/tmp/demo",
model: "gpt-5-codex",
createdAt,
});
await engineA.dispatch({
type: "thread.create",
commandId: "cmd-2",
threadId,
projectId,
title: "Thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
});
await engineA.dispatch({
type: "message.send",
commandId: "cmd-3",
threadId,
messageId: "msg-1",
role: "user",
text: "hello",
streaming: false,
createdAt,
});
const snapshotA = engineA.getSnapshot();
await firstSystem.dispose();
const secondSystem = await createOrchestrationSystem(stateDir);
const engineB = secondSystem.engine;
const snapshotB = engineB.getSnapshot();
expect(snapshotB).toEqual(snapshotA);
await secondSystem.dispose();
});
it("fans out read-model updates to subscribers", async () => {
const stateDir = makeTempDir("t3code-orchestration-fanout-");
const system = await createOrchestrationSystem(stateDir);
const engine = system.engine;
const updates: number[] = [];
const unsubscribe = engine.subscribeToReadModel((snapshot) => {
updates.push(snapshot.sequence);
});
await engine.dispatch({
type: "project.create",
commandId: "cmd-project",
projectId: "project-2",
name: "fanout",
cwd: "/tmp/fanout",
model: "gpt-5-codex",
createdAt: new Date().toISOString(),
});
unsubscribe();
expect(updates.length).toBeGreaterThan(0);
await system.dispose();
});
it("replays append-only events from sequence", async () => {
const stateDir = makeTempDir("t3code-orchestration-replay-");
const system = await createOrchestrationSystem(stateDir);
const engine = system.engine;
await engine.dispatch({
type: "project.create",
commandId: "cmd-a",
projectId: "project-replay",
name: "replay",
cwd: "/tmp/replay",
model: "gpt-5-codex",
createdAt: new Date().toISOString(),
});
await engine.dispatch({
type: "project.delete",
commandId: "cmd-b",
projectId: "project-replay",
createdAt: new Date().toISOString(),
});
const events = await engine.replayEvents(0);
expect(events.length).toBe(2);
expect(events[0]?.type).toBe("project.created");
expect(events[1]?.type).toBe("project.deleted");
await system.dispose();
});
it("stores completed turn summaries even when no files changed", async () => {
const stateDir = makeTempDir("t3code-orchestration-turn-diff-");
const firstSystem = await createOrchestrationSystem(stateDir);
const engine = firstSystem.engine;
const completedAt = new Date().toISOString();
await engine.dispatch({
type: "project.create",
commandId: "cmd-project-turn-diff",
projectId: "project-turn-diff",
name: "turn-diff",
cwd: "/tmp/turn-diff",
model: "gpt-5-codex",
createdAt: completedAt,
});
await engine.dispatch({
type: "thread.create",
commandId: "cmd-thread-turn-diff",
threadId: "thread-turn-diff",
projectId: "project-turn-diff",
title: "Turn diff thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: completedAt,
});
await engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-diff-complete",
threadId: "thread-turn-diff",
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
createdAt: completedAt,
});
const firstThread = engine.getSnapshot().threads.find((thread) => thread.id === "thread-turn-diff");
expect(firstThread?.turnDiffSummaries).toEqual([
{
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
},
]);
await firstSystem.dispose();
const secondSystem = await createOrchestrationSystem(stateDir);
const restartedEngine = secondSystem.engine;
const restartedThread = restartedEngine
.getSnapshot()
.threads.find((thread) => thread.id === "thread-turn-diff");
expect(restartedThread?.turnDiffSummaries).toEqual([
{
turnId: "turn-1",
completedAt,
status: "completed",
files: [],
checkpointTurnCount: 1,
},
]);
await secondSystem.dispose();
});
it("reverts thread messages and turn summaries to a checkpoint", async () => {
const stateDir = makeTempDir("t3code-orchestration-revert-");
const firstSystem = await createOrchestrationSystem(stateDir);
const engine = firstSystem.engine;
const createdAt = new Date().toISOString();
await engine.dispatch({
type: "project.create",
commandId: "cmd-project-revert",
projectId: "project-revert",
name: "revert",
cwd: "/tmp/revert",
model: "gpt-5-codex",
createdAt,
});
await engine.dispatch({
type: "thread.create",
commandId: "cmd-thread-revert",
threadId: "thread-revert",
projectId: "project-revert",
title: "Revert thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt,
});
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-1-user",
threadId: "thread-revert",
messageId: "user-1",
role: "user",
text: "first",
streaming: false,
createdAt,
});
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-1-assistant",
threadId: "thread-revert",
messageId: "assistant:turn-1",
role: "assistant",
text: "first-response",
streaming: false,
createdAt,
});
await engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-1-complete",
threadId: "thread-revert",
turnId: "turn-1",
completedAt: createdAt,
status: "completed",
files: [],
assistantMessageId: "assistant:turn-1",
checkpointTurnCount: 1,
createdAt,
});
const createdAtSecond = new Date(Date.now() + 1_000).toISOString();
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-2-user",
threadId: "thread-revert",
messageId: "user-2",
role: "user",
text: "second",
streaming: false,
createdAt: createdAtSecond,
});
await engine.dispatch({
type: "message.send",
commandId: "cmd-msg-2-assistant",
threadId: "thread-revert",
messageId: "assistant:turn-2",
role: "assistant",
text: "second-response",
streaming: false,
createdAt: createdAtSecond,
});
await engine.dispatch({
type: "thread.turnDiff.complete",
commandId: "cmd-turn-2-complete",
threadId: "thread-revert",
turnId: "turn-2",
completedAt: createdAtSecond,
status: "completed",
files: [],
assistantMessageId: "assistant:turn-2",
checkpointTurnCount: 2,
createdAt: createdAtSecond,
});
await engine.dispatch({
type: "thread.revert",
commandId: "cmd-thread-revert-apply",
threadId: "thread-revert",
turnCount: 1,
messageCount: 2,
createdAt: createdAtSecond,
});
const thread = engine.getSnapshot().threads.find((entry) => entry.id === "thread-revert");
expect(thread?.messages.map((message) => message.id)).toEqual(["user-1", "assistant:turn-1"]);
expect(thread?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
expect(thread?.latestTurnId).toBe("turn-1");
await firstSystem.dispose();
const secondSystem = await createOrchestrationSystem(stateDir);
const restarted = secondSystem.engine;
const restartedThread = restarted
.getSnapshot()
.threads.find((entry) => entry.id === "thread-revert");
expect(restartedThread?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant:turn-1",
]);
expect(restartedThread?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn-1"]);
await secondSystem.dispose();
});
it("allows stop to be called multiple times", async () => {
const inMemoryStore: OrchestrationEventRepositoryShape = {
append(event) {
return Effect.succeed({ ...event, sequence: 1 });
},
readFromSequence() {
return Effect.succeed([]);
},
readAll() {
return Effect.succeed([]);
},
};
const engine = new OrchestrationEngine(inMemoryStore);
await engine.start();
await engine.stop();
await expect(engine.stop()).resolves.toBeUndefined();
});
it("keeps processing queued commands after a storage failure", async () => {
const events: OrchestrationEvent[] = [];
let nextSequence = 1;
let shouldFailFirstAppend = true;
const flakyStore: OrchestrationEventRepositoryShape = {
append(event) {
if (shouldFailFirstAppend) {
shouldFailFirstAppend = false;
return Effect.sync(() => {
throw new Error("append failed");
});
}
const savedEvent = {
...event,
sequence: nextSequence,
} satisfies OrchestrationEvent;
nextSequence += 1;
events.push(savedEvent);
return Effect.succeed(savedEvent);
},
readFromSequence(sequenceExclusive) {
return Effect.succeed(events.filter((event) => event.sequence > sequenceExclusive));
},
readAll() {
return Effect.succeed(events);
},
};
const engine = new OrchestrationEngine(flakyStore);
const createdAt = new Date().toISOString();
await engine.start();
await expect(
engine.dispatch({
type: "project.create",
commandId: "cmd-flaky-1",
projectId: "project-flaky-fail",
name: "flaky-fail",
cwd: "/tmp/flaky-fail",
model: "gpt-5-codex",
createdAt,
}),
).rejects.toThrow("append failed");
const result = await engine.dispatch({
type: "project.create",
commandId: "cmd-flaky-2",
projectId: "project-flaky-ok",
name: "flaky-ok",
cwd: "/tmp/flaky-ok",
model: "gpt-5-codex",
createdAt,
});
expect(result.sequence).toBe(1);
expect(engine.getSnapshot().projects.map((project) => project.id)).toEqual(["project-flaky-ok"]);
await engine.stop();
});
});
-371
View File
@@ -1,371 +0,0 @@
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import { OrchestrationCommandSchema } from "@t3tools/contracts";
import {
PubSub,
Queue,
Schema,
Stream,
Effect,
Fiber,
Runtime,
Either,
Deferred,
Cause,
} from "effect";
import { createLogger } from "../logger";
import type { OrchestrationEventRepositoryShape } from "../persistence/Services/OrchestrationEvents";
import { createEmptyReadModel, reduceEvent } from "./reducer";
import { UI_ENTITY_CONTRACTS } from "./uiContractInventory";
type CommandEnvelope = {
command: OrchestrationCommand;
result: Deferred.Deferred<{ sequence: number }, Error>;
volatile?: boolean;
};
function asError(error: unknown, fallbackMessage: string): Error {
return error instanceof Error ? error : new Error(fallbackMessage);
}
function mapCommandToEvent(command: OrchestrationCommand): Omit<OrchestrationEvent, "sequence"> {
const eventId = crypto.randomUUID();
switch (command.type) {
case "project.create":
return {
eventId,
type: "project.created",
aggregateType: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.projectId,
name: command.name,
cwd: command.cwd,
model: command.model,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
case "project.delete":
return {
eventId,
type: "project.deleted",
aggregateType: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.projectId,
deletedAt: command.createdAt,
},
};
case "thread.create":
return {
eventId,
type: "thread.created",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.threadId,
projectId: command.projectId,
title: command.title,
model: command.model,
branch: command.branch,
worktreePath: command.worktreePath,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
case "thread.delete":
return {
eventId,
type: "thread.deleted",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.threadId,
deletedAt: command.createdAt,
},
};
case "thread.meta.update":
return {
eventId,
type: "thread.meta-updated",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: command.createdAt,
},
};
case "message.send":
return {
eventId,
type: "message.sent",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
id: command.messageId,
role: command.role,
text: command.text,
threadId: command.threadId,
createdAt: command.createdAt,
streaming: command.streaming === true,
},
};
case "thread.session":
return {
eventId,
type: "thread.session-set",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
session: command.session,
},
};
case "git.readModel.upsert":
return {
eventId,
type: "git.read-model-upsert",
aggregateType: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
projectId: command.projectId,
branch: command.branch,
hasWorkingTreeChanges: command.hasWorkingTreeChanges,
aheadCount: command.aheadCount,
behindCount: command.behindCount,
updatedAt: command.createdAt,
},
};
case "thread.turnDiff.complete":
return {
eventId,
type: "thread.turn-diff-completed",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
turnId: command.turnId,
completedAt: command.completedAt,
...(command.status !== undefined ? { status: command.status } : {}),
files: command.files,
...(command.assistantMessageId !== undefined
? { assistantMessageId: command.assistantMessageId }
: {}),
...(command.checkpointTurnCount !== undefined
? { checkpointTurnCount: command.checkpointTurnCount }
: {}),
},
};
case "thread.revert":
return {
eventId,
type: "thread.reverted",
aggregateType: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
payload: {
threadId: command.threadId,
turnCount: command.turnCount,
messageCount: command.messageCount,
},
};
}
}
export class OrchestrationEngine {
private readonly logger = createLogger("orchestration");
private readonly runtime = Runtime.defaultRuntime;
private readonly eventStore: OrchestrationEventRepositoryShape;
private readModel: OrchestrationReadModel;
private commandQueue: Queue.Queue<CommandEnvelope>;
private readModelPubSub: PubSub.PubSub<OrchestrationReadModel>;
private eventPubSub: PubSub.PubSub<OrchestrationEvent>;
private workerFiber: Fiber.RuntimeFiber<void, unknown> | null = null;
private readonly readModelListeners = new Set<(snapshot: OrchestrationReadModel) => void>();
private readonly domainEventListeners = new Set<(event: OrchestrationEvent) => void>();
constructor(eventStore: OrchestrationEventRepositoryShape) {
this.eventStore = eventStore;
this.readModel = createEmptyReadModel(new Date().toISOString());
this.commandQueue = Runtime.runSync(this.runtime)(Queue.unbounded<CommandEnvelope>());
this.readModelPubSub = Runtime.runSync(this.runtime)(
PubSub.unbounded<OrchestrationReadModel>(),
);
this.eventPubSub = Runtime.runSync(this.runtime)(PubSub.unbounded<OrchestrationEvent>());
}
private processEnvelope(envelope: CommandEnvelope): Effect.Effect<void> {
return Effect.gen(this, function* () {
const eventBase = mapCommandToEvent(envelope.command);
let savedEvent: OrchestrationEvent;
if (envelope.volatile) {
savedEvent = { ...eventBase, sequence: this.readModel.sequence };
} else {
savedEvent = yield* this.eventStore.append(eventBase);
}
yield* Effect.sync(() => {
this.readModel = reduceEvent(this.readModel, savedEvent);
});
const snapshot = this.readModel;
if (!envelope.volatile) {
yield* Effect.all([
PubSub.publish(this.eventPubSub, savedEvent),
PubSub.publish(this.readModelPubSub, snapshot),
]);
}
yield* Effect.sync(() => {
if (!envelope.volatile) {
for (const listener of this.domainEventListeners) {
listener(savedEvent);
}
}
for (const listener of this.readModelListeners) {
listener(snapshot);
}
});
yield* Deferred.succeed(envelope.result, { sequence: savedEvent.sequence });
}).pipe(
Effect.catchAllCause((cause) =>
Deferred.fail(
envelope.result,
asError(Cause.squash(cause), "Unknown command processing error"),
).pipe(Effect.asVoid),
),
);
}
private bootstrapReadModel(): Effect.Effect<void> {
return Effect.gen(this, function* () {
const existingEvents = yield* this.eventStore.readAll();
yield* Effect.sync(() => {
for (const event of existingEvents) {
this.readModel = reduceEvent(this.readModel, event);
}
});
});
}
async start(): Promise<void> {
if (this.workerFiber) {
return;
}
await Runtime.runPromise(this.runtime)(this.bootstrapReadModel());
const worker = Stream.fromQueue(this.commandQueue).pipe(
Stream.runForEach((envelope) => this.processEnvelope(envelope)),
);
this.workerFiber = Runtime.runFork(this.runtime)(worker);
this.logger.info("orchestration engine started", {
sequence: this.readModel.sequence,
contracts: UI_ENTITY_CONTRACTS.length,
});
}
async stop(): Promise<void> {
if (this.workerFiber) {
await Runtime.runPromise(this.runtime)(Fiber.interrupt(this.workerFiber));
this.workerFiber = null;
}
}
getSnapshot(): OrchestrationReadModel {
return this.readModel;
}
async replayEvents(fromSequenceExclusive: number): Promise<OrchestrationEvent[]> {
return Runtime.runPromise(this.runtime)(
this.eventStore.readFromSequence(fromSequenceExclusive),
);
}
async dispatchUnknown(command: unknown): Promise<{ sequence: number }> {
const decode = Schema.decodeUnknownEither(OrchestrationCommandSchema);
let payload: unknown = command;
if (typeof command === "string") {
try {
payload = JSON.parse(command) as unknown;
} catch {
throw new Error("Invalid orchestration command: payload is not valid JSON");
}
}
const decoded = decode(payload);
if (Either.isLeft(decoded)) {
const issues = decoded.left.toString();
throw new Error(`Invalid orchestration command: ${issues}`);
}
return this.dispatch(decoded.right);
}
async dispatch(command: OrchestrationCommand): Promise<{ sequence: number }> {
const program = Effect.gen(this, function* () {
const result = yield* Deferred.make<{ sequence: number }, Error>();
yield* Queue.offer(this.commandQueue, { command, result });
return yield* Deferred.await(result);
});
return Runtime.runPromise(this.runtime)(program).catch((error) => {
throw asError(error, "Queue offer failed");
});
}
async dispatchVolatile(command: OrchestrationCommand): Promise<{ sequence: number }> {
const program = Effect.gen(this, function* () {
const result = yield* Deferred.make<{ sequence: number }, Error>();
yield* Queue.offer(this.commandQueue, { command, result, volatile: true });
return yield* Deferred.await(result);
});
return Runtime.runPromise(this.runtime)(program).catch((error) => {
throw asError(error, "Queue offer failed");
});
}
subscribeToReadModel(callback: (snapshot: OrchestrationReadModel) => void): () => void {
this.readModelListeners.add(callback);
return () => {
this.readModelListeners.delete(callback);
};
}
subscribeToDomainEvents(callback: (event: OrchestrationEvent) => void): () => void {
this.domainEventListeners.add(callback);
return () => {
this.domainEventListeners.delete(callback);
};
}
}
@@ -1,47 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createOrchestrationSystem } from "./runtime";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("orchestration layers", () => {
it("creates an engine through Context.Tag wiring", async () => {
const stateDir = makeTempDir("t3code-orchestration-layer-");
const createdAt = new Date().toISOString();
const firstSystem = await createOrchestrationSystem(stateDir);
const { engine } = firstSystem;
await engine.dispatch({
type: "project.create",
commandId: "cmd-layer-1",
projectId: "project-layer-1",
name: "layer",
cwd: "/tmp/layer",
model: "gpt-5-codex",
createdAt,
});
const firstSnapshot = engine.getSnapshot();
await firstSystem.dispose();
const secondSystem = await createOrchestrationSystem(stateDir);
const restarted = secondSystem.engine;
expect(restarted.getSnapshot()).toEqual(firstSnapshot);
await secondSystem.dispose();
});
});
-32
View File
@@ -1,32 +0,0 @@
import path from "node:path";
import { Effect, Layer } from "effect";
import { OrchestrationEventRepository } from "../persistence/Services/OrchestrationEvents";
import { makeSqliteOrchestrationEventRepositoryLive } from "../persistence/Layers/OrchestrationEvents";
import { OrchestrationEngine } from "./engine";
import { OrchestrationConfig, OrchestrationEngineService } from "./services";
export const OrchestrationEventRepositoryLive = Layer.unwrapEffect(
Effect.map(OrchestrationConfig, ({ stateDir }) => {
const dbPath = path.join(stateDir, "orchestration.sqlite");
return makeSqliteOrchestrationEventRepositoryLive(dbPath);
}),
);
export const OrchestrationEngineLive = Layer.scoped(
OrchestrationEngineService,
Effect.acquireRelease(
Effect.gen(function* () {
const eventRepository = yield* OrchestrationEventRepository;
const engine = new OrchestrationEngine(eventRepository);
yield* Effect.promise(() => engine.start());
return engine;
}),
(engine) => Effect.promise(() => engine.stop()),
),
);
export const OrchestrationLive = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationEventRepositoryLive),
);
-322
View File
@@ -1,322 +0,0 @@
import type {
OrchestrationEvent,
OrchestrationGitReadModel,
OrchestrationMessage,
OrchestrationProject,
OrchestrationReadModel,
OrchestrationSession,
OrchestrationThread,
} from "@t3tools/contracts";
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: string,
patch: ThreadPatch,
): OrchestrationThread[] {
return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));
}
function asObject(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object") return null;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function asNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function asArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
return {
sequence: 0,
projects: [],
threads: [],
gitByProjectId: {},
updatedAt: nowIso,
};
}
export function reduceEvent(
model: OrchestrationReadModel,
event: OrchestrationEvent,
): OrchestrationReadModel {
const payload = asObject(event.payload);
const nextBase: OrchestrationReadModel = {
...model,
sequence: event.sequence,
updatedAt: event.occurredAt,
};
switch (event.type) {
case "project.created": {
if (!payload) return nextBase;
const project: OrchestrationProject = {
id: asString(payload.id) ?? event.aggregateId,
name: asString(payload.name) ?? "project",
cwd: asString(payload.cwd) ?? "",
model: asString(payload.model) ?? "gpt-5-codex",
createdAt: asString(payload.createdAt) ?? event.occurredAt,
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
};
const existing = nextBase.projects.find((entry) => entry.id === project.id);
return {
...nextBase,
projects: existing
? nextBase.projects.map((entry) => (entry.id === project.id ? project : entry))
: [...nextBase.projects, project],
};
}
case "project.deleted":
return {
...nextBase,
projects: nextBase.projects.filter((project) => project.id !== event.aggregateId),
threads: nextBase.threads.filter((thread) => thread.projectId !== event.aggregateId),
};
case "thread.created": {
if (!payload) return nextBase;
const thread: OrchestrationThread = {
id: asString(payload.id) ?? event.aggregateId,
projectId: asString(payload.projectId) ?? "",
title: asString(payload.title) ?? "New thread",
model: asString(payload.model) ?? "gpt-5-codex",
branch: asString(payload.branch),
worktreePath: asString(payload.worktreePath),
createdAt: asString(payload.createdAt) ?? event.occurredAt,
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
latestTurnId: null,
latestTurnStartedAt: null,
latestTurnCompletedAt: null,
latestTurnDurationMs: null,
messages: [],
session: null,
turnDiffSummaries: [],
error: null,
};
const existing = nextBase.threads.find((entry) => entry.id === thread.id);
return {
...nextBase,
threads: existing
? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))
: [...nextBase.threads, thread],
};
}
case "thread.deleted":
return {
...nextBase,
threads: nextBase.threads.filter((thread) => thread.id !== event.aggregateId),
};
case "thread.meta-updated": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
if (!thread) return nextBase;
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
...(asString(payload.title) !== null ? { title: asString(payload.title) ?? thread.title } : {}),
...(asString(payload.model) !== null ? { model: asString(payload.model) ?? thread.model } : {}),
...(payload.branch !== undefined ? { branch: asString(payload.branch) } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: asString(payload.worktreePath) } : {}),
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
}),
};
}
case "message.sent": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const message: OrchestrationMessage = {
id: asString(payload.id) ?? crypto.randomUUID(),
role: (asString(payload.role) as OrchestrationMessage["role"] | null) ?? "user",
text: asString(payload.text) ?? "",
createdAt: asString(payload.createdAt) ?? event.occurredAt,
streaming: payload.streaming === true,
};
const targetThread = nextBase.threads.find((thread) => thread.id === threadId);
if (!targetThread) return nextBase;
const existingMessage = targetThread.messages.find((entry) => entry.id === message.id);
const nextMessages = existingMessage
? targetThread.messages.map((entry) =>
entry.id === message.id
? {
...entry,
text:
message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
createdAt: message.createdAt,
}
: entry,
)
: [...targetThread.messages, message];
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
messages: nextMessages,
updatedAt: event.occurredAt,
}),
};
}
case "thread.session-set": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
if (!thread) return nextBase;
const sessionPayload = asObject(payload.session);
if (!sessionPayload) return nextBase;
const session: OrchestrationSession = {
sessionId: asString(sessionPayload.sessionId) ?? crypto.randomUUID(),
status:
(asString(sessionPayload.status) as OrchestrationSession["status"] | null) ?? "connecting",
provider:
(asString(sessionPayload.provider) as OrchestrationSession["provider"] | null) ?? "codex",
threadId: asString(sessionPayload.threadId) ?? threadId,
activeTurnId: asString(sessionPayload.activeTurnId),
createdAt: asString(sessionPayload.createdAt) ?? event.occurredAt,
updatedAt: asString(sessionPayload.updatedAt) ?? event.occurredAt,
lastError: asString(sessionPayload.lastError),
};
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
session,
updatedAt: event.occurredAt,
error: session.lastError,
}),
};
}
case "thread.turn-diff-completed": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
const turnId = asString(payload.turnId);
if (!thread || !turnId) return nextBase;
const files = asArray(payload.files).flatMap((filePayload) => {
const file = asObject(filePayload);
const filePath = asString(file?.path);
if (!filePath) {
return [];
}
const nextFile: {
path: string;
kind?: string;
additions?: number;
deletions?: number;
} = { path: filePath };
const kind = asString(file?.kind);
if (kind !== null) {
nextFile.kind = kind;
}
const additions = asNumber(file?.additions);
if (additions !== null) {
nextFile.additions = additions;
}
const deletions = asNumber(file?.deletions);
if (deletions !== null) {
nextFile.deletions = deletions;
}
return [nextFile];
});
const nextSummary = {
turnId,
completedAt: asString(payload.completedAt) ?? event.occurredAt,
...(asString(payload.status) !== null ? { status: asString(payload.status) ?? undefined } : {}),
files,
...(asString(payload.assistantMessageId) !== null
? { assistantMessageId: asString(payload.assistantMessageId) ?? undefined }
: {}),
...(asNumber(payload.checkpointTurnCount) !== null
? { checkpointTurnCount: asNumber(payload.checkpointTurnCount) ?? undefined }
: {}),
};
const turnDiffSummaries = [...thread.turnDiffSummaries.filter((summary) => summary.turnId !== turnId), nextSummary]
.toSorted((left, right) => left.completedAt.localeCompare(right.completedAt));
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
latestTurnId: turnId,
latestTurnCompletedAt: nextSummary.completedAt,
turnDiffSummaries,
updatedAt: event.occurredAt,
}),
};
}
case "thread.reverted": {
if (!payload) return nextBase;
const threadId = asString(payload.threadId) ?? event.aggregateId;
const thread = nextBase.threads.find((entry) => entry.id === threadId);
if (!thread) return nextBase;
const targetTurnCount = Math.max(0, Math.floor(asNumber(payload.turnCount) ?? 0));
const targetMessageCount = Math.max(0, Math.floor(asNumber(payload.messageCount) ?? 0));
const sortedSummaries = [...thread.turnDiffSummaries].toSorted((left, right) =>
left.completedAt.localeCompare(right.completedAt),
);
const inferredTurnCountByTurnId = new Map<string, number>();
for (let index = 0; index < sortedSummaries.length; index += 1) {
const summary = sortedSummaries[index];
if (!summary) continue;
inferredTurnCountByTurnId.set(summary.turnId, index + 1);
}
const turnDiffSummaries = thread.turnDiffSummaries
.filter((summary) => {
const checkpointTurnCount =
summary.checkpointTurnCount ?? inferredTurnCountByTurnId.get(summary.turnId) ?? 0;
return checkpointTurnCount <= targetTurnCount;
})
.toSorted((left, right) => left.completedAt.localeCompare(right.completedAt));
const latestSummary =
turnDiffSummaries.length > 0 ? turnDiffSummaries[turnDiffSummaries.length - 1] : null;
return {
...nextBase,
threads: updateThread(nextBase.threads, threadId, {
messages: thread.messages.slice(0, Math.min(targetMessageCount, thread.messages.length)),
turnDiffSummaries,
latestTurnId: latestSummary?.turnId ?? null,
latestTurnStartedAt: null,
latestTurnCompletedAt: latestSummary?.completedAt ?? null,
latestTurnDurationMs: null,
updatedAt: event.occurredAt,
}),
};
}
case "git.read-model-upsert": {
if (!payload) return nextBase;
const projectId = asString(payload.projectId) ?? event.aggregateId;
const gitReadModel: OrchestrationGitReadModel = {
projectId,
branch: asString(payload.branch),
hasWorkingTreeChanges: payload.hasWorkingTreeChanges === true,
aheadCount: asNumber(payload.aheadCount) ?? 0,
behindCount: asNumber(payload.behindCount) ?? 0,
updatedAt: asString(payload.updatedAt) ?? event.occurredAt,
};
return {
...nextBase,
gitByProjectId: {
...nextBase.gitByProjectId,
[projectId]: gitReadModel,
},
};
}
default:
return nextBase;
}
}
-22
View File
@@ -1,22 +0,0 @@
import { Layer, ManagedRuntime } from "effect";
import type { OrchestrationEngine } from "./engine";
import { OrchestrationLive } from "./layers";
import { OrchestrationConfig, OrchestrationEngineService } from "./services";
export interface OrchestrationSystem {
readonly engine: OrchestrationEngine;
readonly dispose: () => Promise<void>;
}
export async function createOrchestrationSystem(stateDir: string): Promise<OrchestrationSystem> {
const orchestrationLayer = OrchestrationLive.pipe(
Layer.provide(Layer.succeed(OrchestrationConfig, { stateDir })),
);
const runtime = ManagedRuntime.make(orchestrationLayer);
const engine = await runtime.runPromise(OrchestrationEngineService);
return {
engine,
dispose: () => runtime.dispose(),
};
}
-17
View File
@@ -1,17 +0,0 @@
import { Context } from "effect";
import { OrchestrationEngine } from "./engine";
export interface OrchestrationConfigShape {
readonly stateDir: string;
}
export class OrchestrationConfig extends Context.Tag("orchestration/Config")<
OrchestrationConfig,
OrchestrationConfigShape
>() {}
export class OrchestrationEngineService extends Context.Tag("orchestration/Engine")<
OrchestrationEngineService,
OrchestrationEngine
>() {}
@@ -1,66 +0,0 @@
export interface UiEntityContract {
entity: string;
requiredFields: string[];
consumedBy: string[];
}
// Explicit UI inventory used to keep server read models aligned
// with what the current frontend renders.
export const UI_ENTITY_CONTRACTS: UiEntityContract[] = [
{
entity: "Project",
requiredFields: ["id", "name", "cwd", "model"],
consumedBy: ["apps/web/src/components/Sidebar.tsx"],
},
{
entity: "Thread",
requiredFields: [
"id",
"projectId",
"title",
"model",
"branch",
"worktreePath",
"createdAt",
"latestTurnId",
"latestTurnStartedAt",
"latestTurnCompletedAt",
"latestTurnDurationMs",
"error",
],
consumedBy: [
"apps/web/src/components/Sidebar.tsx",
"apps/web/src/components/ChatView.tsx",
"apps/web/src/components/BranchToolbar.tsx",
],
},
{
entity: "Message",
requiredFields: ["id", "role", "text", "createdAt", "streaming"],
consumedBy: ["apps/web/src/components/ChatView.tsx"],
},
{
entity: "ProviderSession",
requiredFields: [
"sessionId",
"provider",
"status",
"threadId",
"activeTurnId",
"createdAt",
"updatedAt",
"lastError",
],
consumedBy: ["apps/web/src/components/ChatView.tsx", "apps/web/src/components/Sidebar.tsx"],
},
{
entity: "TurnDiffSummary",
requiredFields: ["turnId", "completedAt", "status", "files"],
consumedBy: ["apps/web/src/components/DiffPanel.tsx", "apps/web/src/components/ChatView.tsx"],
},
{
entity: "GitReadModel",
requiredFields: ["projectId", "branch", "hasWorkingTreeChanges", "aheadCount", "behindCount"],
consumedBy: ["apps/web/src/components/GitActionsControl.tsx", "apps/web/src/components/BranchToolbar.tsx"],
},
];
@@ -1,99 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { Runtime, ManagedRuntime } from "effect";
import { afterEach, describe, expect, it } from "vitest";
import { OrchestrationEventRepository } from "../Services/OrchestrationEvents";
import { makeSqliteOrchestrationEventRepositoryLive } from "./OrchestrationEvents";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("OrchestrationEventRepository", () => {
it("persists and replays events across restarts", async () => {
const stateDir = makeTempDir("t3code-event-store-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const runtime = Runtime.defaultRuntime;
const createdAt = new Date().toISOString();
const firstRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const first = await firstRuntime.runPromise(OrchestrationEventRepository);
const saved = await Runtime.runPromise(runtime)(
first.append({
eventId: "event-1",
type: "project.created",
aggregateType: "project",
aggregateId: "project-1",
occurredAt: createdAt,
commandId: "cmd-1",
payload: { id: "project-1", name: "demo" },
}),
);
expect(saved.sequence).toBe(1);
await firstRuntime.dispose();
const secondRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const second = await secondRuntime.runPromise(OrchestrationEventRepository);
const replayed = await Runtime.runPromise(runtime)(second.readFromSequence(0));
expect(replayed).toEqual([saved]);
await secondRuntime.dispose();
});
it("creates and reuses the migrator tracking table", async () => {
const stateDir = makeTempDir("t3code-event-store-migrations-");
const dbPath = path.join(stateDir, "orchestration.sqlite");
const runtime = Runtime.defaultRuntime;
const firstRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const first = await firstRuntime.runPromise(OrchestrationEventRepository);
await Runtime.runPromise(runtime)(first.readAll());
await firstRuntime.dispose();
const secondRuntime = ManagedRuntime.make(makeSqliteOrchestrationEventRepositoryLive(dbPath));
const second = await secondRuntime.runPromise(OrchestrationEventRepository);
await Runtime.runPromise(runtime)(second.readAll());
await secondRuntime.dispose();
const db = new DatabaseSync(dbPath, { readOnly: true });
const tableRow = db
.prepare(
`
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name IN ('effect_sql_migrations', 'orchestration_sql_migrations')
ORDER BY name ASC
`,
)
.get() as { name: string } | undefined;
expect(tableRow?.name).toBeDefined();
if (!tableRow) {
throw new Error("Expected migrations table to exist");
}
const migrationRows = db
.prepare(
`
SELECT *
FROM ${tableRow.name}
`,
)
.all() as Array<Record<string, unknown>>;
expect(migrationRows).toHaveLength(1);
expect(Object.values(migrationRows[0] ?? {}).length).toBeGreaterThan(0);
db.close();
});
});
@@ -1,178 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import type { OrchestrationEvent } from "@t3tools/contracts";
import { OrchestrationEventSchema } from "@t3tools/contracts";
import type { SqlClient as SqlClientService } from "@effect/sql/SqlClient";
import * as SqlClient from "@effect/sql/SqlClient";
import * as SqlSchema from "@effect/sql/SqlSchema";
import * as SqliteClient from "@effect/sql-sqlite-node/SqliteClient";
import { Context, Effect, Layer, Schema } from "effect";
import { runMigrations } from "../Migrations";
import {
OrchestrationEventRepository,
type OrchestrationEventRepositoryShape,
} from "../Services/OrchestrationEvents";
const decodeEvent = Schema.decodeUnknownSync(OrchestrationEventSchema);
const EventRowSchema = Schema.Struct({
sequence: Schema.Number,
eventId: Schema.String,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: Schema.String,
commandId: Schema.NullOr(Schema.String),
payloadJson: Schema.String,
});
type EventRow = Schema.Schema.Type<typeof EventRowSchema>;
const AppendEventRequestSchema = Schema.Struct({
eventId: Schema.String,
type: Schema.String,
aggregateType: Schema.String,
aggregateId: Schema.String,
occurredAt: Schema.String,
commandId: Schema.NullOr(Schema.String),
payloadJson: Schema.String,
});
const ReadFromSequenceRequestSchema = Schema.Struct({
sequenceExclusive: Schema.Number,
limit: Schema.Number,
});
class OrchestrationSql extends Context.Tag("persistence/OrchestrationSql")<
OrchestrationSql,
SqlClientService
>() {}
function eventRowToOrchestrationEvent(row: EventRow): OrchestrationEvent {
return decodeEvent({
sequence: row.sequence,
eventId: row.eventId,
type: row.type,
aggregateType: row.aggregateType,
aggregateId: row.aggregateId,
occurredAt: row.occurredAt,
commandId: row.commandId,
payload: JSON.parse(row.payloadJson) as unknown,
});
}
const makeRepository = Effect.gen(function* () {
const sql = yield* OrchestrationSql;
const appendEventRow = SqlSchema.single({
Request: AppendEventRequestSchema,
Result: EventRowSchema,
execute: (request) =>
sql`
INSERT INTO orchestration_events (
event_id,
event_type,
aggregate_type,
aggregate_id,
occurred_at,
command_id,
payload_json
)
VALUES (
${request.eventId},
${request.type},
${request.aggregateType},
${request.aggregateId},
${request.occurredAt},
${request.commandId},
${request.payloadJson}
)
RETURNING
sequence,
event_id AS "eventId",
event_type AS "type",
aggregate_type AS "aggregateType",
aggregate_id AS "aggregateId",
occurred_at AS "occurredAt",
command_id AS "commandId",
payload_json AS "payloadJson"
`,
});
const readEventRowsFromSequence = SqlSchema.findAll({
Request: ReadFromSequenceRequestSchema,
Result: EventRowSchema,
execute: (request) =>
sql`
SELECT
sequence,
event_id AS "eventId",
event_type AS "type",
aggregate_type AS "aggregateType",
aggregate_id AS "aggregateId",
occurred_at AS "occurredAt",
command_id AS "commandId",
payload_json AS "payloadJson"
FROM orchestration_events
WHERE sequence > ${request.sequenceExclusive}
ORDER BY sequence ASC
LIMIT ${request.limit}
`,
});
const append: OrchestrationEventRepositoryShape["append"] = (event) =>
appendEventRow({
eventId: event.eventId,
type: event.type,
aggregateType: event.aggregateType,
aggregateId: event.aggregateId,
occurredAt: event.occurredAt,
commandId: event.commandId,
payloadJson: JSON.stringify(event.payload),
}).pipe(Effect.map(eventRowToOrchestrationEvent), Effect.orDie);
const readFromSequence: OrchestrationEventRepositoryShape["readFromSequence"] = (
sequenceExclusive,
limit = 1_000,
) =>
readEventRowsFromSequence({ sequenceExclusive, limit }).pipe(
Effect.map((rows) => rows.map(eventRowToOrchestrationEvent)),
Effect.orDie,
);
return {
append,
readFromSequence,
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
} satisfies OrchestrationEventRepositoryShape;
});
export const OrchestrationEventRepositoryLive = Layer.effect(
OrchestrationEventRepository,
makeRepository,
);
export function makeSqliteOrchestrationEventRepositoryLive(dbPath: string) {
const SqliteClientLive = Effect.gen(function* () {
yield* Effect.try({
try: () => fs.mkdirSync(path.dirname(dbPath), { recursive: true }),
catch: (error) => Effect.die(error),
})
return SqliteClient.layer({ filename: dbPath });
}).pipe(Layer.unwrapEffect)
const OrchestrationSqlLive = Layer.scoped(
OrchestrationSql,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* runMigrations;
return sql;
}),
).pipe(Layer.provide(SqliteClientLive));
return OrchestrationEventRepositoryLive.pipe(Layer.provide(OrchestrationSqlLive));
}
-67
View File
@@ -1,67 +0,0 @@
/**
* MigrationsLive - Migration runner with inline loader
*
* Uses Migrator.make with fromRecord to define migrations inline.
* All migrations are statically imported - no dynamic file system loading.
*
* Migrations run automatically when the MigrationLayer is provided,
* ensuring the database schema is always up-to-date before the application starts.
*/
import * as Migrator from "@effect/sql/Migrator";
import * as Layer from "effect/Layer";
// Import all migrations statically
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
/**
* Migration loader with all migrations defined inline.
*
* Key format: "{id}_{name}" where:
* - id: numeric migration ID (determines execution order)
* - name: descriptive name for the migration
*
* Uses Migrator.fromRecord which parses the key format and
* returns migrations sorted by ID.
*/
const loader = Migrator.fromRecord({
"1_OrchestrationEvents": Migration0001,
});
/**
* Migrator run function - no schema dumping needed
* Uses the base Migrator.make without platform dependencies
*/
const run = Migrator.make({});
/**
* Run all pending migrations.
*
* Creates the migrations tracking table (effect_sql_migrations) if it doesn't exist,
* then runs any migrations with ID greater than the latest recorded migration.
*
* Returns array of [id, name] tuples for migrations that were run.
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = run({ loader });
/**
* Layer that runs migrations when the layer is built.
*
* Use this to ensure migrations run before your application starts.
* Migrations are run automatically - no separate script is needed.
*
* @example
* ```typescript
* import { MigrationsLive } from "@acme/db/Migrations"
* import { PgClient } from "@effect/sql-pg"
*
* // Migrations run automatically when PgClient is provided
* const AppLayer = MigrationsLive.pipe(
* Layer.provideMerge(PgClient.layer({ url: Redacted.make("postgresql://...") }))
* )
* ```
*/
export const MigrationsLive = Layer.effectDiscard(runMigrations);
@@ -1,24 +0,0 @@
import { SqlClient } from "@effect/sql";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS orchestration_events (
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
event_id TEXT NOT NULL UNIQUE,
event_type TEXT NOT NULL,
aggregate_type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
occurred_at TEXT NOT NULL,
command_id TEXT,
payload_json TEXT NOT NULL
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_orch_events_aggregate
ON orchestration_events(aggregate_type, aggregate_id, sequence)
`;
});
@@ -1,19 +0,0 @@
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
export interface OrchestrationEventRepositoryShape {
readonly append: (
event: Omit<OrchestrationEvent, "sequence">,
) => Effect.Effect<OrchestrationEvent>;
readonly readFromSequence: (
sequenceExclusive: number,
limit?: number,
) => Effect.Effect<OrchestrationEvent[]>;
readonly readAll: () => Effect.Effect<OrchestrationEvent[]>;
}
export class OrchestrationEventRepository extends Context.Tag("orchestration/EventRepository")<
OrchestrationEventRepository,
OrchestrationEventRepositoryShape
>() {}
+1 -831
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import { ProviderManager } from "./providerManager";
@@ -59,834 +59,4 @@ describe("ProviderManager", () => {
manager.dispose();
});
it("rejects checkpoint operations for unknown sessions", async () => {
const manager = new ProviderManager();
await expect(
manager.listCheckpoints({
sessionId: "missing-session",
}),
).rejects.toThrow("Unknown provider session: missing-session");
await expect(
manager.revertToCheckpoint({
sessionId: "missing-session",
turnCount: 0,
}),
).rejects.toThrow("Unknown provider session: missing-session");
await expect(
manager.getCheckpointDiff({
sessionId: "missing-session",
fromTurnCount: 0,
toTurnCount: 1,
}),
).rejects.toThrow("Unknown provider session: missing-session");
manager.dispose();
});
it("derives checkpoints from thread turns", async () => {
const manager = new ProviderManager();
const codex = (
manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
}
).codex;
codex.hasSession = () => true;
codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{
id: "turn_1",
items: [
{
type: "userMessage",
content: [{ type: "text", text: "Refactor the logger" }],
},
{
type: "agentMessage",
text: "I refactored it.",
},
],
},
],
});
const result = await manager.listCheckpoints({
sessionId: "sess_1",
});
expect(result).toEqual({
threadId: "thr_1",
checkpoints: [
{
id: "root",
turnCount: 0,
messageCount: 0,
label: "Start of conversation",
isCurrent: false,
},
{
id: "turn_1",
turnCount: 1,
messageCount: 2,
label: "Turn 1",
preview: "Refactor the logger",
isCurrent: true,
},
],
});
manager.dispose();
});
it("rolls back from a selected checkpoint turn count", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
restoreCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
pruneAfterTurn: (input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}) => Promise<void>;
};
sessionCheckpointCwds: Map<string, string>;
};
const rollbackCalls: Array<{ sessionId: string; numTurns: number }> = [];
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
{ id: "turn_3", items: [] },
],
});
internals.codex.rollbackThread = async (sessionId, numTurns) => {
rollbackCalls.push({ sessionId, numTurns });
return {
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
};
};
const hasCheckpoint = vi.fn(async () => true);
const restoreCheckpoint = vi.fn(async () => true);
const pruneAfterTurn = vi.fn(async () => undefined);
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
});
expect(rollbackCalls).toEqual([{ sessionId: "sess_1", numTurns: 2 }]);
expect(result.threadId).toBe("thr_1");
expect(result.turnCount).toBe(1);
expect(result.messageCount).toBe(0);
expect(result.rolledBackTurns).toBe(2);
expect(result.checkpoints).toHaveLength(2);
expect(hasCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(restoreCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(pruneAfterTurn).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
maxTurnCount: 1,
});
manager.dispose();
});
it("returns diff text for a checkpoint range", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
diffCheckpoints: (input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}) => Promise<string>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 1,
toTurnCount: 2,
});
expect(result).toEqual({
threadId: "thr_1",
fromTurnCount: 1,
toTurnCount: 2,
diff: "diff --git a/a.ts b/a.ts",
});
expect(diffCheckpoints).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
fromTurnCount: 1,
toTurnCount: 2,
});
manager.dispose();
});
it("emits checkpoint/captured after turn completion checkpoint capture", async () => {
const manager = new ProviderManager();
const events: Array<{ method: string; payload?: unknown; threadId?: string; turnId?: string }> =
[];
manager.on("event", (event) => {
events.push({
method: event.method,
...(event.payload !== undefined ? { payload: event.payload } : {}),
...(event.threadId ? { threadId: event.threadId } : {}),
...(event.turnId ? { turnId: event.turnId } : {}),
});
});
const internals = manager as unknown as {
onCodexEvent: (event: {
id: string;
kind: "notification";
provider: "codex";
sessionId: string;
createdAt: string;
method: string;
threadId: string;
turnId?: string;
payload?: unknown;
}) => void;
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
captureCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<void>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
});
const captureCheckpoint = vi.fn(async () => undefined);
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
internals.onCodexEvent({
id: "evt-turn-complete",
kind: "notification",
provider: "codex",
sessionId: "sess_1",
createdAt: "2026-02-19T00:00:00.000Z",
method: "turn/completed",
threadId: "thr_1",
turnId: "turn_1",
payload: {
turn: {
status: "completed",
},
},
});
await vi.waitFor(() => {
expect(captureCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(events.some((event) => event.method === "checkpoint/captured")).toBe(true);
});
const checkpointCapturedEvent = events.find((event) => event.method === "checkpoint/captured");
expect(checkpointCapturedEvent?.threadId).toBe("thr_1");
expect(checkpointCapturedEvent?.turnId).toBe("turn_1");
expect(checkpointCapturedEvent?.payload).toEqual({
threadId: "thr_1",
turnCount: 1,
turnId: "turn_1",
status: "completed",
});
manager.dispose();
});
it("lazily initializes filesystem checkpoints before diffing when cache is missing", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
captureCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<void>;
diffCheckpoints: (input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}) => Promise<string>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
cwd: "/repo",
},
];
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
const isGitRepository = vi.fn(async () => true);
const ensureRootCheckpoint = vi.fn(async () => true);
const captureCheckpoint = vi.fn(async () => undefined);
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
internals.sessionCheckpointCwds.delete("sess_1");
const result = await manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 1,
toTurnCount: 2,
});
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
expect(isGitRepository).toHaveBeenCalledWith("/repo");
expect(captureCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 2,
});
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
});
expect(diffCheckpoints).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
fromTurnCount: 1,
toTurnCount: 2,
});
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/repo");
manager.dispose();
});
it("falls back to process cwd for lazy checkpoint init when session cwd is missing", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
captureCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<void>;
diffCheckpoints: (input: {
cwd: string;
threadId: string;
fromTurnCount: number;
toTurnCount: number;
}) => Promise<string>;
};
sessionCheckpointCwds: Map<string, string>;
};
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
try {
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
},
];
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
});
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
const ensureRootCheckpoint = vi.fn(async () => true);
const captureCheckpoint = vi.fn(async () => undefined);
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
internals.sessionCheckpointCwds.delete("sess_1");
const result = await manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 0,
toTurnCount: 1,
});
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
expect(isGitRepository).toHaveBeenCalledWith("/fallback-repo");
expect(captureCheckpoint).toHaveBeenCalledWith({
cwd: "/fallback-repo",
threadId: "thr_1",
turnCount: 1,
});
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
cwd: "/fallback-repo",
threadId: "thr_1",
});
expect(diffCheckpoints).toHaveBeenCalledWith({
cwd: "/fallback-repo",
threadId: "thr_1",
fromTurnCount: 0,
toTurnCount: 1,
});
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/fallback-repo");
} finally {
processCwd.mockRestore();
manager.dispose();
}
});
it("does not fall back to process cwd when a session cwd exists but is not a git repo", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
};
sessionCheckpointCwds: Map<string, string>;
};
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
try {
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
cwd: "/session-cwd",
},
];
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
internals.sessionCheckpointCwds.delete("sess_1");
await expect(
manager.getCheckpointDiff({
sessionId: "sess_1",
fromTurnCount: 0,
toTurnCount: 1,
}),
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
expect(isGitRepository).toHaveBeenCalledWith("/session-cwd");
expect(isGitRepository).not.toHaveBeenCalledWith("/fallback-repo");
} finally {
processCwd.mockRestore();
manager.dispose();
}
});
it("fails revert when filesystem checkpoints are unavailable for the session", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
listSessions: () => Array<{
sessionId: string;
provider: "codex";
status: "ready";
createdAt: string;
updatedAt: string;
cwd?: string;
}>;
};
filesystemCheckpointStore: {
isGitRepository: (cwd: string) => Promise<boolean>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.listSessions = () => [
{
sessionId: "sess_1",
provider: "codex",
status: "ready",
createdAt: "2026-02-18T00:00:00.000Z",
updatedAt: "2026-02-18T00:00:00.000Z",
},
];
internals.filesystemCheckpointStore.isGitRepository = async () => false;
internals.sessionCheckpointCwds.delete("sess_1");
await expect(
manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
}),
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
manager.dispose();
});
it("restores filesystem checkpoint when reverting and checkpointing is enabled", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
restoreCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
pruneAfterTurn: (input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}) => Promise<void>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
const callOrder: string[] = [];
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
internals.codex.rollbackThread = async () => {
callOrder.push("rollback");
return {
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
};
};
const hasCheckpoint = vi.fn(async () => true);
const restoreCheckpoint = vi.fn(async () => {
callOrder.push("restore");
return true;
});
const pruneAfterTurn = vi.fn(async () => {
callOrder.push("prune");
return undefined;
});
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
});
expect(result.turnCount).toBe(1);
expect(hasCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(restoreCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 1,
});
expect(pruneAfterTurn).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
maxTurnCount: 1,
});
expect(callOrder).toEqual(["restore", "rollback", "prune"]);
manager.dispose();
});
it("reverts to turn 0 without requiring an explicit turn 0 checkpoint ref", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
restoreCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
pruneAfterTurn: (input: {
cwd: string;
threadId: string;
maxTurnCount: number;
}) => Promise<void>;
};
sessionCheckpointCwds: Map<string, string>;
};
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
internals.codex.rollbackThread = async () => ({
threadId: "thr_1",
turns: [],
});
const hasCheckpoint = vi.fn(async () => false);
const restoreCheckpoint = vi.fn(async () => true);
const pruneAfterTurn = vi.fn(async () => undefined);
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
const result = await manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 0,
});
expect(result.turnCount).toBe(0);
expect(hasCheckpoint).not.toHaveBeenCalled();
expect(restoreCheckpoint).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
turnCount: 0,
});
expect(pruneAfterTurn).toHaveBeenCalledWith({
cwd: "/repo",
threadId: "thr_1",
maxTurnCount: 0,
});
manager.dispose();
});
it("fails before rollback when filesystem checkpoint is missing", async () => {
const manager = new ProviderManager();
const internals = manager as unknown as {
codex: {
hasSession: (sessionId: string) => boolean;
readThread: (sessionId: string) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
rollbackThread: (
sessionId: string,
numTurns: number,
) => Promise<{
threadId: string;
turns: Array<{ id: string; items: unknown[] }>;
}>;
};
filesystemCheckpointStore: {
hasCheckpoint: (input: {
cwd: string;
threadId: string;
turnCount: number;
}) => Promise<boolean>;
};
sessionCheckpointCwds: Map<string, string>;
};
const rollbackSpy = vi.fn(async () => ({
threadId: "thr_1",
turns: [{ id: "turn_1", items: [] }],
}));
internals.codex.hasSession = () => true;
internals.codex.readThread = async () => ({
threadId: "thr_1",
turns: [
{ id: "turn_1", items: [] },
{ id: "turn_2", items: [] },
],
});
internals.codex.rollbackThread = rollbackSpy;
internals.filesystemCheckpointStore.hasCheckpoint = async () => false;
internals.sessionCheckpointCwds.set("sess_1", "/repo");
await expect(
manager.revertToCheckpoint({
sessionId: "sess_1",
turnCount: 1,
}),
).rejects.toThrow("Filesystem checkpoint is unavailable for turn 1 in thread thr_1.");
expect(rollbackSpy).not.toHaveBeenCalled();
manager.dispose();
});
});
-468
View File
@@ -1,18 +1,10 @@
import { EventEmitter } from "node:events";
import fs from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import {
type ProviderCheckpoint,
type ProviderEvent,
type ProviderGetCheckpointDiffInput,
type ProviderGetCheckpointDiffResult,
type ProviderInterruptTurnInput,
type ProviderListCheckpointsInput,
type ProviderListCheckpointsResult,
type ProviderRevertToCheckpointInput,
type ProviderRevertToCheckpointResult,
type ProviderRespondToRequestInput,
type ProviderSendTurnInput,
type ProviderSession,
@@ -20,161 +12,23 @@ import {
type ProviderStopSessionInput,
type ProviderTurnStartResult,
providerInterruptTurnInputSchema,
providerGetCheckpointDiffInputSchema,
providerListCheckpointsInputSchema,
providerRevertToCheckpointInputSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
providerSessionStartInputSchema,
providerStopSessionInputSchema,
} from "@t3tools/contracts";
import type { CodexThreadTurnSnapshot } from "./codexAppServerManager";
import { CodexAppServerManager } from "./codexAppServerManager";
import { FilesystemCheckpointStore } from "./filesystemCheckpointStore";
export interface ProviderManagerEvents {
event: [event: ProviderEvent];
}
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function trimToPreview(value: string): string {
const normalized = value.replace(/\s+/g, " ").trim();
if (normalized.length <= 120) {
return normalized;
}
return `${normalized.slice(0, 117)}...`;
}
function summarizeUserMessageContent(content: unknown[]): string | undefined {
const segments: string[] = [];
for (const part of content) {
const record = asObject(part);
const type = asString(record?.type);
if (!type) continue;
if (type === "text") {
const text = asString(record?.text);
if (text && text.trim().length > 0) {
segments.push(text.trim());
}
continue;
}
if (type === "image") {
segments.push("[Image attachment]");
continue;
}
if (type === "localImage") {
segments.push("[Local image attachment]");
continue;
}
}
if (segments.length === 0) {
return undefined;
}
return trimToPreview(segments.join(" "));
}
function summarizeTurn(turn: CodexThreadTurnSnapshot): {
messageCountDelta: number;
preview?: string;
} {
let messageCountDelta = 0;
let preview: string | undefined;
for (const item of turn.items) {
const record = asObject(item);
const type = asString(record?.type);
if (!type) continue;
if (type === "userMessage") {
messageCountDelta += 1;
if (!preview) {
const content = asArray(record?.content);
preview = summarizeUserMessageContent(content);
}
continue;
}
if (type === "agentMessage") {
messageCountDelta += 1;
if (!preview) {
const text = asString(record?.text);
if (text && text.trim().length > 0) {
preview = trimToPreview(text);
}
}
}
}
return {
messageCountDelta,
...(preview ? { preview } : {}),
};
}
function readTurnCompletionStatus(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.status);
}
function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[] {
const checkpoints: ProviderCheckpoint[] = [];
let messageCount = 0;
const isEmpty = turns.length === 0;
checkpoints.push({
id: "root",
turnCount: 0,
messageCount: 0,
label: "Start of conversation",
isCurrent: isEmpty,
});
for (let index = 0; index < turns.length; index += 1) {
const turn = turns[index];
if (!turn) continue;
const turnSummary = summarizeTurn(turn);
messageCount += turnSummary.messageCountDelta;
checkpoints.push({
id: turn.id,
turnCount: index + 1,
messageCount,
label: `Turn ${index + 1}`,
...(turnSummary.preview ? { preview: turnSummary.preview } : {}),
isCurrent: index === turns.length - 1,
});
}
return checkpoints;
}
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
private readonly codex = new CodexAppServerManager();
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
private readonly threadLogsDir: string;
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
private readonly sessionThreadIds = new Map<string, string>();
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
private readonly sessionCheckpointCwds = new Map<string, string>();
private readonly filesystemLocks = new Map<string, Promise<void>>();
private disposed = false;
private readonly onCodexEvent = (event: ProviderEvent) => {
if (this.disposed) {
@@ -183,7 +37,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.routeEventToThreadLog(event);
this.emit("event", event);
this.maybeCaptureFilesystemCheckpoint(event);
};
constructor() {
@@ -207,11 +60,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.sessionThreadIds.set(session.sessionId, session.threadId);
this.flushPendingSessionEvents(session.sessionId, session.threadId);
}
await this.initializeFilesystemCheckpointing(session, input.cwd).catch((error) => {
const message =
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
});
return session;
}
@@ -247,138 +95,12 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.codex.stopSession(input.sessionId);
this.sessionThreadIds.delete(input.sessionId);
this.pendingEventsBySession.delete(input.sessionId);
this.sessionCheckpointCwds.delete(input.sessionId);
this.filesystemLocks.delete(input.sessionId);
}
listSessions(): ProviderSession[] {
return this.codex.listSessions();
}
async listCheckpoints(raw: ProviderListCheckpointsInput): Promise<ProviderListCheckpointsResult> {
const input = providerListCheckpointsInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
const snapshot = await this.codex.readThread(input.sessionId);
return {
threadId: snapshot.threadId,
checkpoints: buildCheckpoints(snapshot.turns),
};
}
async getCheckpointDiff(
raw: ProviderGetCheckpointDiffInput,
): Promise<ProviderGetCheckpointDiffResult> {
const input = providerGetCheckpointDiffInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
if (!checkpointCwd) {
throw new Error("Filesystem checkpoints are unavailable for this session.");
}
return this.withFilesystemLock(input.sessionId, async () => {
const snapshot = await this.codex.readThread(input.sessionId);
if (input.toTurnCount > snapshot.turns.length) {
throw new Error(
`Checkpoint turn count ${input.toTurnCount} exceeds current turn count ${snapshot.turns.length}.`,
);
}
const diff = await this.filesystemCheckpointStore.diffCheckpoints({
cwd: checkpointCwd,
threadId: snapshot.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
});
return {
threadId: snapshot.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
});
}
async revertToCheckpoint(
raw: ProviderRevertToCheckpointInput,
): Promise<ProviderRevertToCheckpointResult> {
const input = providerRevertToCheckpointInputSchema.parse(raw);
if (!this.codex.hasSession(input.sessionId)) {
throw new Error(`Unknown provider session: ${input.sessionId}`);
}
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
if (!checkpointCwd) {
throw new Error("Filesystem checkpoints are unavailable for this session.");
}
return this.withFilesystemLock(input.sessionId, async () => {
const beforeSnapshot = await this.codex.readThread(input.sessionId);
const currentTurnCount = beforeSnapshot.turns.length;
if (input.turnCount > currentTurnCount) {
throw new Error(
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
);
}
if (checkpointCwd && input.turnCount > 0) {
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
cwd: checkpointCwd,
threadId: beforeSnapshot.threadId,
turnCount: input.turnCount,
});
if (!hasCheckpoint) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
);
}
}
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
cwd: checkpointCwd,
threadId: beforeSnapshot.threadId,
turnCount: input.turnCount,
});
if (!restored) {
throw new Error(
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
);
}
const requestedRollbackTurns = currentTurnCount - input.turnCount;
const afterSnapshot =
requestedRollbackTurns > 0
? await this.codex.rollbackThread(input.sessionId, requestedRollbackTurns)
: beforeSnapshot;
await this.filesystemCheckpointStore.pruneAfterTurn({
cwd: checkpointCwd,
threadId: afterSnapshot.threadId,
maxTurnCount: afterSnapshot.turns.length,
});
const checkpoints = buildCheckpoints(afterSnapshot.turns);
const currentCheckpoint =
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
checkpoints[checkpoints.length - 1] ??
checkpoints[0];
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
return {
threadId: afterSnapshot.threadId,
turnCount: currentCheckpoint?.turnCount ?? 0,
messageCount: currentCheckpoint?.messageCount ?? 0,
rolledBackTurns,
checkpoints,
};
});
}
stopAll(): void {
this.codex.stopAll();
}
@@ -396,196 +118,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.threadLogStreams.clear();
this.sessionThreadIds.clear();
this.pendingEventsBySession.clear();
this.sessionCheckpointCwds.clear();
this.filesystemLocks.clear();
}
private async initializeFilesystemCheckpointing(
session: ProviderSession,
preferredCwd?: string,
): Promise<void> {
const cwd = preferredCwd ?? session.cwd ?? process.cwd();
await this.withFilesystemLock(session.sessionId, async () => {
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
if (!supportsGit) {
this.sessionCheckpointCwds.delete(session.sessionId);
return;
}
const snapshot = await this.codex.readThread(session.sessionId);
await this.filesystemCheckpointStore.ensureRootCheckpoint({
cwd,
threadId: snapshot.threadId,
});
await this.filesystemCheckpointStore.captureCheckpoint({
cwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
if (this.codex.hasSession(session.sessionId)) {
this.sessionCheckpointCwds.set(session.sessionId, cwd);
}
});
}
private async getOrInitializeFilesystemCheckpointCwd(sessionId: string): Promise<string | null> {
const existingCwd = this.sessionCheckpointCwds.get(sessionId);
if (existingCwd) {
return existingCwd;
}
const session = this.codex
.listSessions()
.find((candidate) => candidate.sessionId === sessionId);
const candidateCwds = session?.cwd ? [session.cwd] : [process.cwd()];
await this.withFilesystemLock(sessionId, async () => {
const currentCwd = this.sessionCheckpointCwds.get(sessionId);
if (currentCwd) {
return;
}
const cwdSupport = await Promise.all(
candidateCwds.map(async (cwd) => ({
cwd,
supportsGit: await this.filesystemCheckpointStore.isGitRepository(cwd),
})),
);
const supportedCwd = cwdSupport.find((entry) => entry.supportsGit)?.cwd;
if (supportedCwd) {
const snapshot = await this.codex.readThread(sessionId);
await this.filesystemCheckpointStore.ensureRootCheckpoint({
cwd: supportedCwd,
threadId: snapshot.threadId,
});
await this.filesystemCheckpointStore.captureCheckpoint({
cwd: supportedCwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
if (this.codex.hasSession(sessionId)) {
this.sessionCheckpointCwds.set(sessionId, supportedCwd);
}
return;
}
this.sessionCheckpointCwds.delete(sessionId);
});
return this.sessionCheckpointCwds.get(sessionId) ?? null;
}
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
if (event.kind !== "notification" || event.method !== "turn/completed") {
return;
}
const turnStatus = readTurnCompletionStatus(event);
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
if (!checkpointCwd) {
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId)
.then(async (initializedCwd) => {
if (!initializedCwd || !this.codex.hasSession(event.sessionId)) {
return;
}
const snapshot = await this.codex.readThread(event.sessionId);
this.emitCheckpointCaptured(
event.sessionId,
snapshot.threadId,
snapshot.turns.length,
event.turnId,
turnStatus,
);
})
.catch((error) => {
const message =
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
});
return;
}
void this.withFilesystemLock(event.sessionId, async () => {
if (!this.codex.hasSession(event.sessionId)) {
return;
}
const snapshot = await this.codex.readThread(event.sessionId);
await this.filesystemCheckpointStore.captureCheckpoint({
cwd: checkpointCwd,
threadId: snapshot.threadId,
turnCount: snapshot.turns.length,
});
this.emitCheckpointCaptured(
event.sessionId,
snapshot.threadId,
snapshot.turns.length,
event.turnId,
turnStatus,
);
}).catch((error) => {
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
});
}
private emitCheckpointCaptured(
sessionId: string,
threadId: string,
turnCount: number,
turnId?: string,
status?: string,
): void {
this.emit("event", {
id: randomUUID(),
kind: "notification",
provider: "codex",
sessionId,
createdAt: new Date().toISOString(),
method: "checkpoint/captured",
threadId,
...(turnId ? { turnId } : {}),
payload: {
threadId,
turnCount,
...(turnId ? { turnId } : {}),
...(status ? { status } : {}),
},
});
}
private emitFilesystemCheckpointError(
sessionId: string,
message: string,
threadId?: string,
): void {
this.emit("event", {
id: randomUUID(),
kind: "error",
provider: "codex",
sessionId,
createdAt: new Date().toISOString(),
method: "checkpoint/filesystemError",
message,
...(threadId ? { threadId } : {}),
});
}
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
const next = previous.catch(() => undefined).then(fn);
const completion = next.then(
() => undefined,
() => undefined,
);
this.filesystemLocks.set(sessionId, completion);
return next.finally(() => {
const tracked = this.filesystemLocks.get(sessionId);
if (tracked === completion) {
this.filesystemLocks.delete(sessionId);
}
});
}
private routeEventToThreadLog(event: ProviderEvent): void {
+10 -38
View File
@@ -621,8 +621,7 @@ describe("WebSocket Server", () => {
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome + initial orchestration snapshot pushes
await waitForMessage(ws);
// Consume welcome
await waitForMessage(ws);
const response = await sendRequest(ws, "nonexistent.method");
@@ -630,7 +629,7 @@ describe("WebSocket Server", () => {
expect(response.error!.message).toContain("Unknown method");
});
it("returns unknown-session errors for checkpoint RPCs without an active provider session", async () => {
it("responds to providers.listSessions with empty array", async () => {
server = createTestServer({ cwd: "/test" });
await server.start();
const addr = server.httpServer.address();
@@ -638,28 +637,13 @@ describe("WebSocket Server", () => {
const ws = await connectWs(port);
connections.push(ws);
// Consume welcome
await waitForMessage(ws);
const listResponse = await sendRequest(ws, WS_METHODS.providersListCheckpoints, {
sessionId: "missing-session",
});
expect(listResponse.result).toBeUndefined();
expect(listResponse.error?.message).toContain("Unknown provider session");
const revertResponse = await sendRequest(ws, WS_METHODS.providersRevertToCheckpoint, {
sessionId: "missing-session",
turnCount: 0,
});
expect(revertResponse.result).toBeUndefined();
expect(revertResponse.error?.message).toContain("Unknown provider session");
const diffResponse = await sendRequest(ws, WS_METHODS.providersGetCheckpointDiff, {
sessionId: "missing-session",
fromTurnCount: 0,
toTurnCount: 1,
});
expect(diffResponse.result).toBeUndefined();
expect(diffResponse.error?.message).toContain("Unknown provider session");
const response = await sendRequest(ws, WS_METHODS.providersListSessions);
expect(response.error).toBeUndefined();
expect(response.result).toEqual([]);
});
it("routes terminal RPC methods and broadcasts terminal events", async () => {
@@ -784,21 +768,9 @@ describe("WebSocket Server", () => {
// Send garbage
ws.send("not json at all");
let response: WsResponse | null = null;
for (let attempt = 0; attempt < 5; attempt += 1) {
const message = (await waitForMessage(ws)) as Record<string, unknown>;
if (typeof message.id === "string" && message.id === "unknown") {
response = message as WsResponse;
break;
}
if (message.error) {
response = message as WsResponse;
break;
}
}
expect(response).toBeDefined();
expect(response!.error).toBeDefined();
expect(response!.error!.message).toContain("Invalid request format");
const response = (await waitForMessage(ws)) as WsResponse;
expect(response.error).toBeDefined();
expect(response.error!.message).toContain("Invalid request format");
});
it("supports projects list/add/dedupe/remove", async () => {
+21 -318
View File
@@ -7,11 +7,8 @@ import type { Duplex } from "node:stream";
import {
EDITORS,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
WS_CHANNELS,
WS_METHODS,
type OrchestrationReadModelPush,
type TerminalEvent,
type WsPush,
type WsRequest,
@@ -36,7 +33,6 @@ import {
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { createOrchestrationSystem, type OrchestrationSystem } from "./orchestration/runtime";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -57,7 +53,6 @@ export interface ServerOptions {
port: number;
host?: string | undefined;
cwd: string;
stateDir?: string | undefined;
staticDir?: string | undefined;
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
@@ -75,27 +70,11 @@ function parseBooleanEnv(value: string | undefined): boolean | undefined {
return undefined;
}
function asObject(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object") return null;
return value as Record<string, unknown>;
}
function asString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function asNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
const noop = () => {};
export function createServer(options: ServerOptions) {
const {
port,
host,
cwd,
stateDir,
staticDir,
devUrl,
logWebSocketEvents: explicitLogWsEvents,
@@ -109,15 +88,11 @@ export function createServer(options: ServerOptions) {
const projectRegistry =
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
const gitManager = providedGitManager ?? new GitManager();
const resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
let orchestrationSystem: OrchestrationSystem | null = null;
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
let unsubscribeReadModel = noop;
let unsubscribeDomainEvents = noop;
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
@@ -128,155 +103,22 @@ export function createServer(options: ServerOptions) {
});
}
function requireOrchestrationEngine() {
if (!orchestrationSystem) {
throw new Error("Orchestration engine is not started");
}
return orchestrationSystem.engine;
}
function attachOrchestrationSubscriptions() {
const orchestrationEngine = requireOrchestrationEngine();
unsubscribeReadModel = orchestrationEngine.subscribeToReadModel((snapshot) => {
const push: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.readModel,
data: {
sequence: snapshot.sequence,
snapshot,
} satisfies OrchestrationReadModelPush,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
});
unsubscribeDomainEvents = orchestrationEngine.subscribeToDomainEvents((event) => {
const push: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
}
logOutgoingPush(push, recipients);
});
}
const streamingTextBuffers = new Map<string, string>();
// Forward provider events to all connected WebSocket clients
providerManager.on("event", (event) => {
void (async () => {
const liveOrchestrationSystem = orchestrationSystem;
if (!liveOrchestrationSystem) {
return;
const push: WsPush = {
type: "push",
channel: WS_CHANNELS.providerEvent,
data: event,
};
const message = JSON.stringify(push);
let recipients = 0;
for (const client of clients) {
if (client.readyState === client.OPEN) {
client.send(message);
recipients += 1;
}
const orchestrationEngine = liveOrchestrationSystem.engine;
const snapshot = orchestrationEngine.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.session?.sessionId === event.sessionId);
if (!thread) return;
const now = event.createdAt;
if (event.method === "turn/started" || event.method === "turn/completed") {
await orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: event.method === "turn/started" ? "running" : "ready",
threadId: event.threadId ?? thread.session?.threadId ?? thread.id,
activeTurnId: event.method === "turn/started" ? (event.turnId ?? null) : null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError: null,
},
createdAt: now,
});
}
if (event.textDelta && event.textDelta.length > 0) {
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
const current = streamingTextBuffers.get(assistantMessageId) ?? "";
streamingTextBuffers.set(assistantMessageId, current + event.textDelta);
await orchestrationEngine.dispatchVolatile({
type: "message.send",
commandId: crypto.randomUUID(),
threadId: thread.id,
messageId: assistantMessageId,
role: "assistant",
text: event.textDelta,
streaming: true,
createdAt: now,
});
}
if (event.method === "turn/completed") {
const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`;
const accumulatedText = streamingTextBuffers.get(assistantMessageId) ?? "";
streamingTextBuffers.delete(assistantMessageId);
await orchestrationEngine.dispatch({
type: "message.send",
commandId: crypto.randomUUID(),
threadId: thread.id,
messageId: assistantMessageId,
role: "assistant",
text: accumulatedText,
streaming: false,
createdAt: now,
});
}
if (event.method === "checkpoint/captured") {
const payload = asObject(event.payload);
const turnId = event.turnId ?? asString(payload?.turnId);
if (turnId) {
await orchestrationEngine.dispatch({
type: "thread.turnDiff.complete",
commandId: crypto.randomUUID(),
threadId: thread.id,
turnId,
completedAt: now,
...(asString(payload?.status) !== null ? { status: asString(payload?.status) ?? undefined } : {}),
files: [],
assistantMessageId: `assistant:${turnId}`,
...(asNumber(payload?.turnCount) !== null
? { checkpointTurnCount: asNumber(payload?.turnCount) ?? undefined }
: {}),
createdAt: now,
});
}
}
if (event.kind === "error" && event.message) {
await orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
sessionId: event.sessionId,
provider: event.provider,
status: "error",
threadId: event.threadId ?? thread.session?.threadId ?? thread.id,
activeTurnId: event.turnId ?? null,
createdAt: thread.session?.createdAt ?? now,
updatedAt: now,
lastError: event.message,
},
createdAt: now,
});
}
})().catch(() => undefined);
}
logOutgoingPush(push, recipients);
});
const onTerminalEvent = (event: TerminalEvent) => {
@@ -392,7 +234,6 @@ export function createServer(options: ServerOptions) {
wss.on("connection", (ws) => {
clients.add(ws);
const orchestrationEngine = requireOrchestrationEngine();
// Send welcome message with project info
const segments = cwd.split(/[/\\]/).filter(Boolean);
@@ -406,17 +247,6 @@ export function createServer(options: ServerOptions) {
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
const snapshotPush: WsPush = {
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.readModel,
data: {
sequence: orchestrationEngine.getSnapshot().sequence,
snapshot: orchestrationEngine.getSnapshot(),
} satisfies OrchestrationReadModelPush,
};
logOutgoingPush(snapshotPush, 1);
ws.send(JSON.stringify(snapshotPush));
ws.on("message", (raw) => {
void handleMessage(ws, raw);
});
@@ -459,8 +289,6 @@ export function createServer(options: ServerOptions) {
}
async function routeRequest(request: WsRequest): Promise<unknown> {
const orchestrationEngine = requireOrchestrationEngine();
switch (request.method) {
case WS_METHODS.providersStartSession:
return providerManager.startSession(request.params as never);
@@ -479,80 +307,18 @@ export function createServer(options: ServerOptions) {
return undefined;
}
case WS_METHODS.providersListCheckpoints:
return providerManager.listCheckpoints(request.params as never);
case WS_METHODS.providersGetCheckpointDiff:
return providerManager.getCheckpointDiff(request.params as never);
case WS_METHODS.providersRevertToCheckpoint:
{
const result = await providerManager.revertToCheckpoint(request.params as never);
const params = request.params as { sessionId?: string };
const sessionId = params.sessionId;
if (typeof sessionId === "string") {
const snapshot = orchestrationEngine.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.session?.sessionId === sessionId);
if (thread) {
const now = new Date().toISOString();
await orchestrationEngine.dispatch({
type: "thread.revert",
commandId: crypto.randomUUID(),
threadId: thread.id,
turnCount: result.turnCount,
messageCount: result.messageCount,
createdAt: now,
});
if (thread.session) {
await orchestrationEngine.dispatch({
type: "thread.session",
commandId: crypto.randomUUID(),
threadId: thread.id,
session: {
...thread.session,
status: "ready",
activeTurnId: null,
updatedAt: now,
lastError: null,
},
createdAt: now,
});
}
}
}
return result;
}
case WS_METHODS.providersListSessions:
return providerManager.listSessions();
case WS_METHODS.projectsList:
return projectRegistry.list();
case WS_METHODS.projectsAdd:
{
const result = await projectRegistry.add(request.params as never);
await orchestrationEngine.dispatch({
type: "project.create",
commandId: crypto.randomUUID(),
projectId: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: "gpt-5-codex",
createdAt: new Date().toISOString(),
});
return result;
}
return projectRegistry.add(request.params as never);
case WS_METHODS.projectsRemove:
{
const params = request.params as { id: string };
projectRegistry.remove(request.params as never);
await orchestrationEngine.dispatch({
type: "project.delete",
commandId: crypto.randomUUID(),
projectId: params.id,
createdAt: new Date().toISOString(),
});
return undefined;
}
projectRegistry.remove(request.params as never);
return undefined;
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
@@ -604,24 +370,7 @@ export function createServer(options: ServerOptions) {
}
case WS_METHODS.gitStatus:
{
const params = request.params as { cwd: string };
const status = await gitManager.status(request.params as never);
const project = projectRegistry.list().find((entry) => entry.cwd === params.cwd);
if (project) {
await orchestrationEngine.dispatch({
type: "git.readModel.upsert",
commandId: crypto.randomUUID(),
projectId: project.id,
branch: status.branch,
hasWorkingTreeChanges: status.hasWorkingTreeChanges,
aheadCount: status.aheadCount,
behindCount: status.behindCount,
createdAt: new Date().toISOString(),
});
}
return status;
}
return gitManager.status(request.params as never);
case WS_METHODS.gitPull:
return pullGitBranch(request.params as never);
@@ -680,61 +429,16 @@ export function createServer(options: ServerOptions) {
keybindings: keybindingsConfig,
};
case ORCHESTRATION_WS_METHODS.getSnapshot:
return orchestrationEngine.getSnapshot();
case ORCHESTRATION_WS_METHODS.dispatchCommand:
return orchestrationEngine.dispatchUnknown(request.params);
case ORCHESTRATION_WS_METHODS.replayEvents:
return orchestrationEngine.replayEvents(
Math.max(
0,
Math.floor(
Number(
(request.params as { fromSequenceExclusive?: number } | undefined)
?.fromSequenceExclusive ?? 0,
),
),
),
);
default:
throw new Error(`Unknown method: ${request.method}`);
}
}
async function ensureOrchestrationSystemStarted() {
if (orchestrationSystem) {
return;
}
orchestrationSystem = await createOrchestrationSystem(resolvedStateDir);
attachOrchestrationSubscriptions();
}
async function disposeOrchestrationSystem() {
unsubscribeReadModel();
unsubscribeDomainEvents();
unsubscribeReadModel = noop;
unsubscribeDomainEvents = noop;
if (!orchestrationSystem) {
return;
}
const system = orchestrationSystem;
orchestrationSystem = null;
await system.dispose();
}
async function start() {
await ensureOrchestrationSystemStarted();
function start() {
return new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
httpServer.off("error", onError);
void disposeOrchestrationSystem().finally(() => reject(error));
reject(error);
};
httpServer.once("error", onError);
const onListening = () => {
@@ -750,7 +454,6 @@ export function createServer(options: ServerOptions) {
}
async function stop(): Promise<void> {
await disposeOrchestrationSystem();
terminalManager.off("event", onTerminalEvent);
providerManager.stopAll();
providerManager.dispose();
+1 -3
View File
@@ -3,9 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node"],
"lib": ["ES2023", "esnext.disposable"],
"noEmit": true,
"allowImportingTsExtensions": true
"lib": ["ES2023", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
+1 -3
View File
@@ -3,15 +3,13 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300..800;1,9..40,300..800&display=swap"
rel="stylesheet"
/>
<title>T3 Code (Alpha)</title>
<title>T3 Code</title>
</head>
<body>
<div id="root"></div>
-4
View File
@@ -12,12 +12,9 @@
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@tanstack/react-router": "^1.160.2",
"@tanstack/react-virtual": "^3.13.18",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
@@ -33,7 +30,6 @@
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@tanstack/router-plugin": "^1.161.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^5.1.4",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

-4
View File
@@ -1,4 +0,0 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

+217
View File
@@ -0,0 +1,217 @@
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
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";
import { StoreProvider, useStore } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import { onServerWelcome } from "./wsNativeApi";
import { useNativeApi } from "./hooks/useNativeApi";
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
import { invalidateGitQueries } from "./lib/gitReactQuery";
function EventRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
const queryClient = useQueryClient();
const activeAssistantItemRef = useRef<string | null>(null);
useEffect(() => {
if (!api) return;
return api.providers.onEvent((event) => {
if (event.method === "turn/completed") {
void invalidateGitQueries(queryClient);
}
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
});
});
}, [api, dispatch, queryClient]);
useEffect(() => {
if (!api) return;
return api.terminal.onEvent((event) => {
dispatch({
type: "APPLY_TERMINAL_EVENT",
event,
});
});
}, [api, dispatch]);
return null;
}
function AutoProjectBootstrap() {
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
return onServerWelcome((payload) => {
if (bootstrappedRef.current) return;
// Don't create duplicate projects for the same cwd
const existing = state.projects.find((p) => p.cwd === payload.cwd);
if (existing) {
bootstrappedRef.current = true;
// Ensure a thread is active
const existingThread = state.threads.find((t) => t.projectId === existing.id);
if (existingThread && !state.activeThreadId) {
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: existingThread.id,
});
}
return;
}
bootstrappedRef.current = true;
// Create project + thread from server cwd
const projectId = crypto.randomUUID();
dispatch({
type: "ADD_PROJECT",
project: {
id: projectId,
name: payload.projectName,
cwd: payload.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: [],
},
});
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: DEFAULT_MODEL,
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: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: null,
worktreePath: null,
},
});
});
}, [state.projects, state.threads, state.activeThreadId, dispatch]);
return null;
}
function DesktopProjectBootstrap() {
const api = useNativeApi();
const { dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!isElectron || !api || bootstrappedRef.current) return;
let disposed = false;
let retryDelayMs = 500;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const attemptBootstrap = async () => {
try {
const projects = await api.projects.list();
if (disposed) return;
dispatch({
type: "SYNC_PROJECTS",
projects: projects.map((project) => ({
id: project.id,
name: project.name,
cwd: project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: project.scripts,
})),
});
bootstrappedRef.current = true;
} catch {
if (disposed) return;
retryTimer = setTimeout(() => {
retryTimer = null;
void attemptBootstrap();
}, retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
}
};
void attemptBootstrap();
return () => {
disposed = true;
if (retryTimer) {
clearTimeout(retryTimer);
}
};
}, [api, dispatch]);
return null;
}
function Layout() {
const api = useNativeApi();
const { state } = useStore();
if (!api) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
</div>
</div>
);
}
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
<EventRouter />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
<Sidebar />
<ChatView />
{state.diffOpen && <DiffPanel />}
</div>
);
}
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<StoreProvider>
<ToastProvider>
<AnchoredToastProvider>
<Layout />
</AnchoredToastProvider>
</ToastProvider>
</StoreProvider>
</QueryClientProvider>
);
}
-109
View File
@@ -1,109 +0,0 @@
import { useCallback, useSyncExternalStore } from "react";
import { z } from "zod";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const appSettingsSchema = z.object({
codexBinaryPath: z.string().trim().max(4096).default(""),
codexHomePath: z.string().trim().max(4096).default(""),
confirmThreadDelete: z.boolean().default(true),
});
export type AppSettings = z.infer<typeof appSettingsSchema>;
const DEFAULT_APP_SETTINGS: AppSettings = appSettingsSchema.parse({});
let listeners: Array<() => void> = [];
let cachedRawSettings: string | null | undefined;
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
function emitChange(): void {
for (const listener of listeners) {
listener();
}
}
function parsePersistedSettings(value: string | null): AppSettings {
if (!value) {
return DEFAULT_APP_SETTINGS;
}
try {
const parsed = JSON.parse(value) as unknown;
return appSettingsSchema.parse(parsed);
} catch {
return DEFAULT_APP_SETTINGS;
}
}
export function getAppSettingsSnapshot(): AppSettings {
if (typeof window === "undefined") {
return DEFAULT_APP_SETTINGS;
}
const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
if (raw === cachedRawSettings) {
return cachedSnapshot;
}
cachedRawSettings = raw;
cachedSnapshot = parsePersistedSettings(raw);
return cachedSnapshot;
}
function persistSettings(next: AppSettings): void {
if (typeof window === "undefined") return;
const raw = JSON.stringify(next);
try {
if (raw !== cachedRawSettings) {
window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
}
} catch {
// Best-effort persistence only.
}
cachedRawSettings = raw;
cachedSnapshot = next;
}
function subscribe(listener: () => void): () => void {
listeners.push(listener);
const onStorage = (event: StorageEvent) => {
if (event.key === APP_SETTINGS_STORAGE_KEY) {
emitChange();
}
};
window.addEventListener("storage", onStorage);
return () => {
listeners = listeners.filter((entry) => entry !== listener);
window.removeEventListener("storage", onStorage);
};
}
export function useAppSettings() {
const settings = useSyncExternalStore(subscribe, getAppSettingsSnapshot, () => DEFAULT_APP_SETTINGS);
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
const next = appSettingsSchema.parse({
...getAppSettingsSnapshot(),
...patch,
});
persistSettings(next);
emitChange();
}, []);
const resetSettings = useCallback(() => {
persistSettings(DEFAULT_APP_SETTINGS);
emitChange();
}, []);
return {
settings,
updateSettings,
resetSettings,
defaults: DEFAULT_APP_SETTINGS,
} as const;
}
-3
View File
@@ -1,3 +0,0 @@
export const APP_BASE_NAME = "T3 Code";
export const APP_STAGE_LABEL = import.meta.env.DEV ? "Dev" : "Alpha";
export const APP_DISPLAY_NAME = `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
+2 -24
View File
@@ -23,7 +23,6 @@ import {
import { ChevronDownIcon } from "lucide-react";
interface BranchToolbarProps {
threadId: string;
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
@@ -31,7 +30,6 @@ interface BranchToolbarProps {
}
export default function BranchToolbar({
threadId,
envMode,
onEnvModeChange,
envLocked,
@@ -44,7 +42,7 @@ export default function BranchToolbar({
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const activeThread = state.threads.find((thread) => thread.id === threadId);
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThreadId = activeThread?.id;
const activeThreadBranch = activeThread?.branch ?? null;
@@ -92,23 +90,13 @@ export default function BranchToolbar({
});
if (!activeThreadId || !syncedBranch) return;
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
createdAt: new Date().toISOString(),
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch, api]);
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
@@ -130,16 +118,6 @@ export default function BranchToolbar({
if (sessionId && worktreePath !== activeWorktreePath) {
void api?.providers.stopSession({ sessionId }).catch(() => undefined);
}
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: crypto.randomUUID(),
threadId: activeThreadId,
branch,
worktreePath,
createdAt: new Date().toISOString(),
});
}
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
File diff suppressed because it is too large. Load diff
+44 -462
View File
@@ -1,476 +1,58 @@
import { parsePatchFiles } from "@pierre/diffs";
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { XIcon } from "lucide-react";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { useTheme } from "../hooks/useTheme";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useStore } from "../store";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { Button } from "./ui/button";
type DiffRenderMode = "stacked" | "split";
type DiffThemeType = "light" | "dark" | "system";
type RenderablePatch =
| {
kind: "files";
files: FileDiffMetadata[];
}
| {
kind: "raw";
text: string;
reason: string;
};
function getRenderablePatch(patch: string | undefined): RenderablePatch | null {
if (!patch) return null;
const normalizedPatch = patch.trim();
if (normalizedPatch.length === 0) return null;
try {
const parsedPatches = parsePatchFiles(normalizedPatch, buildPatchCacheKey(normalizedPatch));
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
if (files.length > 0) {
return { kind: "files", files };
}
return {
kind: "raw",
text: normalizedPatch,
reason: "Unsupported diff format. Showing raw patch.",
};
} catch {
return {
kind: "raw",
text: normalizedPatch,
reason: "Failed to parse patch. Showing raw patch.",
};
}
}
function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
const raw = fileDiff.name ?? fileDiff.prevName ?? "";
if (raw.startsWith("a/") || raw.startsWith("b/")) {
return raw.slice(2);
}
return raw;
}
function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
}
function formatTurnChipTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).format(new Date(isoDate));
}
interface DiffPanelProps {
mode?: "inline" | "sheet";
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const api = useNativeApi();
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { state } = useStore();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
const params = useParams({ strict: false });
const rawSearch = useSearch({ strict: false });
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
);
const activeThreadId = routeThreadId;
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
const activeThreadRuntimeId =
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
const activeSessionId = activeThread?.session?.sessionId ?? null;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const selectedTurnId = diffSearch.diffTurnId ?? null;
const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
const selectedTurn =
selectedTurnId === null
? undefined
: (turnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
turnDiffSummaries[0]);
const selectedCheckpointTurnCount =
selectedTurn &&
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
const selectedCheckpointRange = useMemo(
() =>
typeof selectedCheckpointTurnCount === "number"
? {
fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
toTurnCount: selectedCheckpointTurnCount,
}
: null,
[selectedCheckpointTurnCount],
);
const conversationCheckpointTurnCount = useMemo(() => {
const turnCounts = turnDiffSummaries
.map(
(summary) =>
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
)
.filter((value): value is number => typeof value === "number");
if (turnCounts.length === 0) {
return undefined;
}
const latest = Math.max(...turnCounts);
return latest > 0 ? latest : undefined;
}, [inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
const conversationCheckpointRange = useMemo(
() =>
!selectedTurn && typeof conversationCheckpointTurnCount === "number"
? {
fromTurnCount: 0,
toTurnCount: conversationCheckpointTurnCount,
}
: null,
[conversationCheckpointTurnCount, selectedTurn],
);
const activeCheckpointRange = selectedTurn
? selectedCheckpointRange
: conversationCheckpointRange;
const conversationCacheScope = useMemo(() => {
if (selectedTurn || turnDiffSummaries.length === 0) {
return null;
}
return `conversation:${turnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
}, [selectedTurn, turnDiffSummaries]);
const activeCheckpointDiffQuery = useQuery(
checkpointDiffQueryOptions(api, {
sessionId: activeSessionId,
threadRuntimeId: activeThreadRuntimeId,
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
}),
);
const selectedTurnCheckpointDiff = selectedTurn
? activeCheckpointDiffQuery.data?.diff
: undefined;
const conversationCheckpointDiff = selectedTurn
? undefined
: activeCheckpointDiffQuery.data?.diff;
const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
const checkpointDiffError =
activeCheckpointDiffQuery.error instanceof Error
? activeCheckpointDiffQuery.error.message
: activeCheckpointDiffQuery.error
? "Failed to load checkpoint diff."
: null;
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
const renderableFiles = useMemo(() => {
if (!renderablePatch || renderablePatch.kind !== "files") {
return [];
}
return renderablePatch.files.toSorted((left, right) =>
resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
numeric: true,
sensitivity: "base",
}),
);
}, [renderablePatch]);
useEffect(() => {
if (!selectedFilePath || !patchViewportRef.current) {
return;
}
const target = Array.from(
patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
).find((element) => element.dataset.diffFilePath === selectedFilePath);
target?.scrollIntoView({ block: "nearest" });
}, [selectedFilePath, renderableFiles]);
const selectTurn = (turnId: string) => {
if (!activeThread) return;
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1", diffTurnId: turnId };
},
});
};
const selectWholeConversation = () => {
if (!activeThread) return;
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1" };
},
});
};
const updateTurnStripScrollState = useCallback(() => {
const element = turnStripRef.current;
if (!element) {
setCanScrollTurnStripLeft(false);
setCanScrollTurnStripRight(false);
return;
}
const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
setCanScrollTurnStripLeft(element.scrollLeft > 4);
setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
}, []);
const scrollTurnStripBy = useCallback((offset: number) => {
const element = turnStripRef.current;
if (!element) return;
element.scrollBy({ left: offset, behavior: "smooth" });
}, []);
const onTurnStripWheel = useCallback((event: WheelEvent) => {
const element = turnStripRef.current;
if (!element) return;
if (element.scrollWidth <= element.clientWidth + 1) return;
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
event.preventDefault();
element.scrollBy({ left: event.deltaY, behavior: "auto" });
}, []);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
updateTurnStripScrollState();
const onScroll = () => updateTurnStripScrollState();
element.addEventListener("scroll", onScroll, { passive: true });
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
resizeObserver.observe(element);
return () => {
element.removeEventListener("scroll", onScroll);
element.removeEventListener("wheel", onTurnStripWheel);
resizeObserver.disconnect();
};
}, [updateTurnStripScrollState, onTurnStripWheel]);
useEffect(() => {
updateTurnStripScrollState();
}, [turnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
}, [selectedTurn?.turnId, selectedTurnId]);
const shouldUseDragRegion = isElectron && mode === "inline";
export default function DiffPanel() {
const { dispatch } = useStore();
return (
<aside
className={cn(
"flex h-full min-w-0 flex-col bg-card",
mode === "inline"
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
: "w-full",
)}
>
<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 gap-2 border-b border-border px-4",
shouldUseDragRegion ? "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"}`}
>
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
{canScrollTurnStripLeft && (
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-gradient-to-r from-card to-transparent" />
)}
{canScrollTurnStripRight && (
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-gradient-to-l from-card to-transparent" />
)}
<button
type="button"
className={cn(
"absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripLeft
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(-180)}
disabled={!canScrollTurnStripLeft}
aria-label="Scroll turn list left"
>
<ChevronLeftIcon className="size-3.5" />
</button>
<button
type="button"
className={cn(
"absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripRight
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(180)}
disabled={!canScrollTurnStripRight}
aria-label="Scroll turn list right"
>
<ChevronRightIcon className="size-3.5" />
</button>
<div
ref={turnStripRef}
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
>
<button
type="button"
className="shrink-0 rounded-md"
onClick={selectWholeConversation}
data-turn-chip-selected={selectedTurnId === null}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
selectedTurnId === null
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="text-[10px] leading-tight font-medium">All turns</div>
</div>
</button>
{turnDiffSummaries.map((summary, index) => (
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
>
<div
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",
)}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn {turnDiffSummaries.length - index}
</span>
<span className="text-[9px] leading-tight opacity-70">
{formatTurnChipTimestamp(summary.completedAt)}
</span>
</div>
</div>
</button>
))}
</div>
</div>
<ToggleGroup
className="shrink-0 [-webkit-app-region:no-drag]"
variant="outline"
size="xs"
value={[diffRenderMode]}
onValueChange={(value) => {
const next = value[0];
if (next === "stacked" || next === "split") {
setDiffRenderMode(next);
}
}}
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<Button
type="button"
size="icon-xs"
variant="ghost"
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
<Toggle aria-label="Stacked diff view" value="stacked">
<Rows3Icon className="size-3" />
</Toggle>
<Toggle aria-label="Split diff view" value="split">
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
<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 turns yet.
</div>
) : (
<>
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
{checkpointDiffError && !renderablePatch && (
<div className="px-3">
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
</div>
)}
{!renderablePatch ? (
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
<p>
{isLoadingCheckpointDiff
? "Loading checkpoint diff..."
: "No patch available for this selection."}
</p>
</div>
) : renderablePatch.kind === "files" ? (
<Virtualizer
className="h-full min-h-0 overflow-auto px-3 py-2"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
}}
>
{renderableFiles.map((fileDiff) => {
const filePath = resolveFileDiffPath(fileDiff);
const fileKey = buildFileDiffRenderKey(fileDiff);
return (
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
<FileDiff
fileDiff={fileDiff}
options={{
diffStyle: diffRenderMode === "split" ? "split" : "unified",
lineDiffType: "none",
themeType: resolvedTheme as DiffThemeType,
}}
/>
</div>
);
})}
</Virtualizer>
) : (
<div className="h-full overflow-auto px-3 py-2">
<div className="space-y-2">
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
{renderablePatch.text}
</pre>
</div>
</div>
)}
{/* 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="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>
);
}
@@ -1,26 +0,0 @@
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
import { useMemo, type ReactNode } from "react";
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
const workerPoolSize = useMemo(() => {
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
}, []);
return (
<WorkerPoolContextProvider
poolOptions={{
workerFactory: () =>
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
poolSize: workerPoolSize,
totalASTLRUCacheSize: 240,
}}
highlighterOptions={{
tokenizeMaxLineLength: 1_000,
}}
>
{children}
</WorkerPoolContextProvider>
);
}
@@ -67,13 +67,13 @@ export function buildGitActionProgressStages(input: {
return [...commitStages, pushStage, "Creating PR..."];
}
const withDescription = (title: string, description: string | undefined) =>
description ? { title, description } : { title };
export function summarizeGitResult(result: GitRunStackedActionResult): {
title: string;
description?: string;
} {
const withDescription = (title: string, description: string | undefined) =>
description ? { title, description } : { title };
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
@@ -38,12 +38,12 @@ import {
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { useStore } from "~/store";
import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
interface GitActionsControlProps {
api: NativeApi | undefined;
gitCwd: string | null;
activeThreadId: string | null;
}
function getMenuActionDisabledReason(
@@ -136,11 +136,9 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
return <InfoIcon className={iconClassName} />;
}
export default function GitActionsControl({
api,
gitCwd,
activeThreadId,
}: GitActionsControlProps) {
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
const { state } = useStore();
const activeThreadId = state.activeThreadId;
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
+123 -135
View File
@@ -1,21 +1,26 @@
import { TerminalIcon } from "lucide-react";
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { type Thread } from "../types";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type Project,
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { toastManager } from "./ui/toast";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
function formatRelativeTime(iso: string): string {
@@ -113,10 +118,6 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
export default function Sidebar() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const navigate = useNavigate();
const { settings: appSettings } = useAppSettings();
const params = useParams({ strict: false });
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
...serverConfigQueryOptions(api),
select: (config) => config.keybindings,
@@ -125,11 +126,18 @@ export default function Sidebar() {
const removeWorktreeMutation = useMutation(
gitRemoveWorktreeMutationOptions({ api, queryClient }),
);
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => new Map<string, boolean>(), []);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<string, boolean>();
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
}
return map;
}, [state.threads]);
const handleNewThread = useCallback(
(
@@ -139,27 +147,37 @@ export default function Sidebar() {
worktreePath?: string | null;
},
) => {
if (!api) return;
const threadId = crypto.randomUUID();
const createdAt = new Date().toISOString();
const model = state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
void api.orchestration.dispatchCommand({
type: "thread.create",
commandId: crypto.randomUUID(),
threadId,
projectId,
title: "New thread",
model,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
createdAt,
});
void navigate({
to: "/$threadId",
params: { threadId },
dispatch({
type: "ADD_THREAD",
thread: {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: "New thread",
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
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: [],
events: [],
error: null,
createdAt: new Date().toISOString(),
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
},
});
},
[api, dispatch, navigate, state.projects],
[dispatch, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
@@ -173,12 +191,12 @@ export default function Sidebar() {
})[0];
if (!latestThread) return;
void navigate({
to: "/$threadId",
params: { threadId: latestThread.id },
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: latestThread.id,
});
},
[navigate, state.threads],
[dispatch, state.threads],
);
const addProjectFromPath = useCallback(
@@ -188,30 +206,47 @@ export default function Sidebar() {
setIsAddingProject(true);
try {
if (!api) return;
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
if (isElectron && api) {
const result = await api.projects.add({ cwd });
const project: Project = {
id: result.project.id,
name: result.project.name,
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: result.project.scripts,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
if (!existingById && !existingByCwd) {
dispatch({ type: "ADD_PROJECT", project });
}
const resolvedProjectId = existingByCwd?.id ?? project.id;
const projectId = crypto.randomUUID();
const now = new Date().toISOString();
const name = inferProjectName(cwd);
if (isElectron) {
// Keep project registry in sync for desktop integrations.
await api.projects.add({ cwd });
if (result.created) {
handleNewThread(resolvedProjectId);
} else {
focusMostRecentThreadForProject(resolvedProjectId);
}
} else {
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
const name = inferProjectName(cwd);
const project: Project = {
id: crypto.randomUUID(),
name,
cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: [],
};
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
}
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: crypto.randomUUID(),
projectId,
name,
cwd,
model: DEFAULT_MODEL,
createdAt: now,
});
handleNewThread(projectId);
} finally {
setIsAddingProject(false);
setNewCwd("");
@@ -252,17 +287,6 @@ export default function Sidebar() {
const thread = state.threads.find((t) => t.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
[
`Delete thread \"${thread.title}\"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
);
if (!confirmed) {
return;
}
}
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const displayWorktreePath = orphanedWorktreePath
@@ -300,25 +324,7 @@ export default function Sidebar() {
// Terminal may already be closed
}
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: crypto.randomUUID(),
threadId,
createdAt: new Date().toISOString(),
});
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
to: "/$threadId",
params: { threadId: fallbackThreadId },
replace: true,
});
} else {
void navigate({ to: "/", replace: true });
}
}
dispatch({ type: "DELETE_THREAD", threadId });
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
@@ -328,33 +334,12 @@ export default function Sidebar() {
await removeWorktreeMutation.mutateAsync({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
threadId,
projectCwd: threadProject.cwd,
worktreePath: orphanedWorktreePath,
error,
});
toastManager.add({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
});
} catch {
// Worktree deletion is best-effort and should not block thread deletion.
}
},
[
api,
appSettings.confirmThreadDelete,
dispatch,
navigate,
removeWorktreeMutation,
routeThreadId,
state.projects,
state.threads,
],
[api, dispatch, removeWorktreeMutation, state.projects, state.threads],
);
const handleProjectContextMenu = useCallback(
@@ -395,23 +380,16 @@ export default function Sidebar() {
});
return;
}
} else {
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: crypto.randomUUID(),
projectId,
createdAt: new Date().toISOString(),
});
}
dispatch({ type: "DELETE_PROJECT", projectId });
},
[api, dispatch, state.projects, state.threads],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const activeThread = routeThreadId
? state.threads.find((thread) => thread.id === routeThreadId)
: undefined;
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;
@@ -434,7 +412,7 @@ export default function Sidebar() {
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
}, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
@@ -442,14 +420,24 @@ export default function Sidebar() {
<div
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
>
<div className="flex min-w-0 flex-1 items-center gap-2">
<span className="truncate text-sm font-semibold tracking-tight text-foreground">
T3 <span className="font-normal text-muted-foreground">Code</span>
</span>
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
{APP_STAGE_LABEL}
</span>
</div>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
T3 <span className="font-normal text-muted-foreground">Code</span>
</span>
<button
type="button"
className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
onClick={() => setTheme(THEME_CYCLE[theme])}
aria-label={`Theme: ${theme}`}
title={`Theme: ${theme}`}
>
{theme === "system" ? (
<MonitorIcon className="size-3.5" />
) : theme === "light" ? (
<SunIcon className="size-3.5" />
) : (
<MoonIcon className="size-3.5" />
)}
</button>
</div>
{/* New thread (global) */}
@@ -509,7 +497,7 @@ export default function Sidebar() {
{project.expanded && (
<div className="ml-2 border-l border-border/80 pl-2">
{threads.map((thread) => {
const isActive = routeThreadId === thread.id;
const isActive = state.activeThreadId === thread.id;
const threadStatus = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
@@ -524,12 +512,12 @@ export default function Sidebar() {
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-secondary"
}`}
onClick={() => {
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
}}
onClick={() =>
dispatch({
type: "SET_ACTIVE_THREAD",
threadId: thread.id,
})
}
onContextMenu={(e) => {
e.preventDefault();
void handleThreadContextMenu(thread.id, {
+1 -3
View File
@@ -60,18 +60,16 @@ function SheetPopup({
className,
children,
showCloseButton = true,
keepMounted = false,
side = "right",
variant = "default",
...props
}: SheetPrimitive.Popup.Props & {
showCloseButton?: boolean;
keepMounted?: boolean;
side?: "right" | "left" | "top" | "bottom";
variant?: "default" | "inset";
}) {
return (
<SheetPortal keepMounted={keepMounted}>
<SheetPortal>
<SheetBackdrop />
<SheetViewport side={side} variant={variant}>
<SheetPrimitive.Popup
+5 -10
View File
@@ -2,7 +2,6 @@
import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import { useParams } from "@tanstack/react-router";
import {
CircleAlertIcon,
CircleCheckIcon,
@@ -13,6 +12,7 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
@@ -55,13 +55,6 @@ function shouldRenderForActiveThread(
return toastThreadId === activeThreadId;
}
function useActiveThreadIdFromRoute(): string | null {
return useParams({
strict: false,
select: (params) => params.threadId ?? null,
});
}
function ThreadToastVisibleAutoDismiss({
toastId,
dismissAfterVisibleMs,
@@ -150,8 +143,9 @@ function ToastProvider({ children, position = "top-right", ...props }: ToastProv
}
function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { state } = useStore();
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = useActiveThreadIdFromRoute();
const activeThreadId = state.activeThreadId;
const isTop = position.startsWith("top");
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
@@ -298,8 +292,9 @@ function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
}
function AnchoredToasts() {
const { state } = useStore();
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = useActiveThreadIdFromRoute();
const activeThreadId = state.activeThreadId;
return (
<Toast.Portal data-slot="toast-portal-anchored">
@@ -1,97 +0,0 @@
"use client";
import type { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group";
import type { VariantProps } from "class-variance-authority";
import * as React from "react";
import { cn } from "~/lib/utils";
import { Separator } from "~/components/ui/separator";
import { Toggle as ToggleComponent, type toggleVariants } from "~/components/ui/toggle";
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
size: "default",
variant: "default",
});
function ToggleGroup({
className,
variant = "default",
size = "default",
orientation = "horizontal",
children,
...props
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive
className={cn(
"flex w-fit *:focus-visible:z-10 dark:*:[[data-slot=separator]:has(+[data-slot=toggle]:hover)]:before:bg-input/64 dark:*:[[data-slot=separator]:has(+[data-slot=toggle][data-pressed])]:before:bg-input dark:*:[[data-slot=toggle]:hover+[data-slot=separator]]:before:bg-input/64 dark:*:[[data-slot=toggle][data-pressed]+[data-slot=separator]]:before:bg-input",
orientation === "horizontal"
? "*:pointer-coarse:after:min-w-auto"
: "*:pointer-coarse:after:min-h-auto",
variant === "default"
? "gap-0.5"
: orientation === "horizontal"
? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
: "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
className,
)}
data-size={size}
data-slot="toggle-group"
data-variant={variant}
orientation={orientation}
{...props}
>
<ToggleGroupContext.Provider value={{ size, variant }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive>
);
}
function Toggle({
className,
children,
variant,
size,
...props
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext);
const resolvedVariant = variant ?? context.variant;
const resolvedSize = size ?? context.size;
return (
<ToggleComponent
className={className}
data-size={resolvedSize}
data-variant={resolvedVariant}
size={resolvedSize}
variant={resolvedVariant}
{...props}
>
{children}
</ToggleComponent>
);
}
function ToggleGroupSeparator({
className,
orientation = "vertical",
...props
}: {
className?: string;
} & React.ComponentProps<typeof Separator>) {
return (
<Separator
className={cn(
"pointer-events-none relative bg-input before:absolute before:inset-0 dark:before:bg-input/32",
className,
)}
orientation={orientation}
{...props}
/>
);
}
export { ToggleGroup, Toggle, Toggle as ToggleGroupItem, ToggleGroupSeparator };
-46
View File
@@ -1,46 +0,0 @@
"use client";
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "~/lib/utils";
const toggleVariants = cva(
"[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center gap-2 whitespace-nowrap rounded-lg border font-medium text-base text-foreground outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 data-pressed:bg-input/64 data-pressed:text-accent-foreground sm:text-sm [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
defaultVariants: {
size: "default",
variant: "default",
},
variants: {
size: {
default: "h-9 min-w-9 px-[calc(--spacing(2)-1px)] sm:h-8 sm:min-w-8",
lg: "h-10 min-w-10 px-[calc(--spacing(2.5)-1px)] sm:h-9 sm:min-w-9",
sm: "h-8 min-w-8 px-[calc(--spacing(1.5)-1px)] sm:h-7 sm:min-w-7",
xs: "h-7 min-w-7 px-[calc(--spacing(1)-1px)] sm:h-6 sm:min-w-6 rounded-md",
},
variant: {
default: "border-transparent",
outline:
"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:data-pressed:bg-input dark:hover:bg-input/64 dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:not-disabled:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/2%)] [:disabled,:active,[data-pressed]]:shadow-none",
},
},
},
);
function Toggle({
className,
variant,
size,
...props
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive
className={cn(toggleVariants({ className, size, variant }))}
data-slot="toggle"
{...props}
/>
);
}
export { Toggle, toggleVariants };
-74
View File
@@ -1,74 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseDiffRouteSearch } from "./diffRouteSearch";
describe("parseDiffRouteSearch", () => {
it("parses valid diff search values", () => {
const parsed = parseDiffRouteSearch({
diff: "1",
diffTurnId: "turn-1",
diffFilePath: "src/app.ts",
});
expect(parsed).toEqual({
diff: "1",
diffTurnId: "turn-1",
diffFilePath: "src/app.ts",
});
});
it("treats numeric and boolean diff toggles as open", () => {
expect(
parseDiffRouteSearch({
diff: 1,
diffTurnId: "turn-1",
}),
).toEqual({
diff: "1",
diffTurnId: "turn-1",
});
expect(
parseDiffRouteSearch({
diff: true,
diffTurnId: "turn-1",
}),
).toEqual({
diff: "1",
diffTurnId: "turn-1",
});
});
it("drops turn and file values when diff is closed", () => {
const parsed = parseDiffRouteSearch({
diff: "0",
diffTurnId: "turn-1",
diffFilePath: "src/app.ts",
});
expect(parsed).toEqual({});
});
it("drops file value when turn is not selected", () => {
const parsed = parseDiffRouteSearch({
diff: "1",
diffFilePath: "src/app.ts",
});
expect(parsed).toEqual({
diff: "1",
});
});
it("normalizes whitespace-only values", () => {
const parsed = parseDiffRouteSearch({
diff: "1",
diffTurnId: " ",
diffFilePath: " ",
});
expect(parsed).toEqual({
diff: "1",
});
});
});
-36
View File
@@ -1,36 +0,0 @@
export interface DiffRouteSearch {
diff?: "1";
diffTurnId?: string;
diffFilePath?: string;
}
function isDiffOpenValue(value: unknown): boolean {
return value === "1" || value === 1 || value === true;
}
function normalizeSearchString(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const normalized = value.trim();
return normalized.length > 0 ? normalized : undefined;
}
export function stripDiffSearchParams<T extends Record<string, unknown>>(
params: T,
): Omit<T, "diff" | "diffTurnId" | "diffFilePath"> {
const { diff: _diff, diffTurnId: _diffTurnId, diffFilePath: _diffFilePath, ...rest } = params;
return rest as Omit<T, "diff" | "diffTurnId" | "diffFilePath">;
}
export function parseDiffRouteSearch(search: Record<string, unknown>): DiffRouteSearch {
const diff = isDiffOpenValue(search.diff) ? "1" : undefined;
const diffTurnId = diff ? normalizeSearchString(search.diffTurnId) : undefined;
const diffFilePath = diff && diffTurnId ? normalizeSearchString(search.diffFilePath) : undefined;
return {
...(diff ? { diff } : {}),
...(diffTurnId ? { diffTurnId } : {}),
...(diffFilePath ? { diffFilePath } : {}),
};
}
-27
View File
@@ -1,27 +0,0 @@
import { useEffect, useState } from "react";
function getMediaQueryMatch(query: string): boolean {
if (typeof window === "undefined") {
return false;
}
return window.matchMedia(query).matches;
}
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(() => getMediaQueryMatch(query));
useEffect(() => {
const mediaQueryList = window.matchMedia(query);
const handleChange = () => {
setMatches(mediaQueryList.matches);
};
setMatches(mediaQueryList.matches);
mediaQueryList.addEventListener("change", handleChange);
return () => {
mediaQueryList.removeEventListener("change", handleChange);
};
}, [query]);
return matches;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { useMemo } from "react";
import { readNativeApi } from "../nativeApi";
import { readNativeApi } from "../session-logic";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
-1
View File
@@ -28,7 +28,6 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
document.documentElement.classList.toggle("dark", isDark);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
// oxlint-disable-next-line no-unused-expressions
document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
@@ -1,19 +0,0 @@
import { useMemo } from "react";
import { inferCheckpointTurnCountByTurnId } from "../session-logic";
import type { Thread, TurnDiffSummary } from "../types";
export function useTurnDiffSummaries(activeThread: Thread | undefined) {
const turnDiffSummaries = useMemo(() => {
if (!activeThread) {
return [];
}
return activeThread.turnDiffSummaries;
}, [activeThread]);
const inferredCheckpointTurnCountByTurnId = useMemo(
() => inferCheckpointTurnCountByTurnId(turnDiffSummaries),
[turnDiffSummaries],
);
return { turnDiffSummaries, inferredCheckpointTurnCountByTurnId };
}
-10
View File
@@ -190,16 +190,6 @@ input {
background: rgba(255, 255, 255, 0.18);
}
.turn-chip-strip {
scrollbar-width: none;
-ms-overflow-style: none;
overscroll-behavior-x: contain;
}
.turn-chip-strip::-webkit-scrollbar {
display: none;
}
/* Terminal drawer scrollbar parity with chat */
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
width: 6px !important;
-23
View File
@@ -1,23 +0,0 @@
import { describe, expect, it } from "vitest";
import { buildPatchCacheKey } from "./diffRendering";
describe("buildPatchCacheKey", () => {
it("returns a stable cache key for identical content", () => {
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
expect(buildPatchCacheKey(patch)).toBe(buildPatchCacheKey(patch));
});
it("normalizes outer whitespace before hashing", () => {
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
expect(buildPatchCacheKey(`\n${patch}\n`)).toBe(buildPatchCacheKey(patch));
});
it("changes when diff content changes", () => {
const before = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
const after = "diff --git a/a.ts b/a.ts\n+console.log('hello world')";
expect(buildPatchCacheKey(before)).not.toBe(buildPatchCacheKey(after));
});
});
-24
View File
@@ -1,24 +0,0 @@
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
const FNV_PRIME_32 = 0x01000193;
const SECONDARY_HASH_SEED = 0x9e3779b9;
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
function fnv1a32(input: string, seed: number, multiplier: number): number {
let hash = seed >>> 0;
for (let index = 0; index < input.length; index += 1) {
hash ^= input.charCodeAt(index);
hash = Math.imul(hash, multiplier) >>> 0;
}
return hash >>> 0;
}
export function buildPatchCacheKey(patch: string, scope = "diff-panel"): string {
const normalizedPatch = patch.trim();
const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
const secondary = fnv1a32(
normalizedPatch,
SECONDARY_HASH_SEED,
SECONDARY_HASH_MULTIPLIER,
).toString(36);
return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
}
+2 -2
View File
@@ -173,11 +173,11 @@ export function gitRemoveWorktreeMutationOptions(input: {
queryClient: QueryClient;
}) {
return mutationOptions({
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
mutationFn: async ({ cwd, path }: { cwd: string; path: string }) => {
if (!input.api) {
throw new Error("Git worktree removal is unavailable.");
}
return input.api.git.removeWorktree({ cwd, path, force });
return input.api.git.removeWorktree({ cwd, path });
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
-111
View File
@@ -1,111 +0,0 @@
import type { NativeApi } from "@t3tools/contracts";
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { checkpointDiffQueryOptions, providerQueryKeys } from "./providerReactQuery";
describe("providerQueryKeys.checkpointDiff", () => {
it("includes cacheScope so reused turn counts do not collide", () => {
const baseInput = {
sessionId: "session-id",
threadRuntimeId: "thread-id",
fromTurnCount: 1,
toTurnCount: 2,
} as const;
expect(
providerQueryKeys.checkpointDiff({
...baseInput,
cacheScope: "turn:old-turn",
}),
).not.toEqual(
providerQueryKeys.checkpointDiff({
...baseInput,
cacheScope: "turn:new-turn",
}),
);
});
});
describe("checkpointDiffQueryOptions", () => {
it("forwards checkpoint range to the provider API", async () => {
const getCheckpointDiff = vi.fn().mockResolvedValue({ diff: "patch" });
const api = {
providers: {
getCheckpointDiff,
},
} as unknown as NativeApi;
const options = checkpointDiffQueryOptions(api, {
sessionId: "session-id",
threadRuntimeId: "thread-id",
fromTurnCount: 3,
toTurnCount: 4,
cacheScope: "turn:abc",
});
const queryClient = new QueryClient();
await queryClient.fetchQuery(options);
expect(getCheckpointDiff).toHaveBeenCalledWith({
sessionId: "session-id",
fromTurnCount: 3,
toTurnCount: 4,
});
});
it("retries checkpoint-not-ready errors longer than generic failures", () => {
const options = checkpointDiffQueryOptions(undefined, {
sessionId: "session-id",
threadRuntimeId: "thread-id",
fromTurnCount: 1,
toTurnCount: 2,
cacheScope: "turn:abc",
});
const retry = options.retry;
expect(typeof retry).toBe("function");
if (typeof retry !== "function") {
throw new Error("Expected retry to be a function.");
}
expect(retry(1, new Error("Checkpoint turn count 2 exceeds current turn count 1."))).toBe(true);
expect(
retry(
11,
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
),
).toBe(true);
expect(
retry(
12,
new Error("Filesystem checkpoint is unavailable for turn 2 in thread thread-1."),
),
).toBe(false);
expect(retry(2, new Error("Something else failed."))).toBe(true);
expect(retry(3, new Error("Something else failed."))).toBe(false);
});
it("backs off longer for checkpoint-not-ready errors", () => {
const options = checkpointDiffQueryOptions(undefined, {
sessionId: "session-id",
threadRuntimeId: "thread-id",
fromTurnCount: 1,
toTurnCount: 2,
cacheScope: "turn:abc",
});
const retryDelay = options.retryDelay;
expect(typeof retryDelay).toBe("function");
if (typeof retryDelay !== "function") {
throw new Error("Expected retryDelay to be a function.");
}
const checkpointDelay = retryDelay(
4,
new Error("Checkpoint turn count 2 exceeds current turn count 1."),
);
const genericDelay = retryDelay(4, new Error("Network failure"));
expect(typeof checkpointDelay).toBe("number");
expect(typeof genericDelay).toBe("number");
expect((checkpointDelay ?? 0) > (genericDelay ?? 0)).toBe(true);
});
});
-87
View File
@@ -1,87 +0,0 @@
import type { NativeApi } from "@t3tools/contracts";
import { queryOptions } from "@tanstack/react-query";
export interface CheckpointDiffQueryInput {
sessionId: string | null;
threadRuntimeId: string | null;
fromTurnCount: number | null;
toTurnCount: number | null;
cacheScope?: string | null;
}
export const providerQueryKeys = {
all: ["providers"] as const,
checkpointDiff: (input: CheckpointDiffQueryInput) =>
[
"providers",
"checkpointDiff",
input.sessionId,
input.threadRuntimeId,
input.fromTurnCount,
input.toTurnCount,
input.cacheScope ?? null,
] as const,
};
function asCheckpointErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return "";
}
function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
const message = asCheckpointErrorMessage(error).toLowerCase();
return (
message.includes("exceeds current turn count") ||
message.includes("checkpoint is unavailable for turn") ||
message.includes("filesystem checkpoint is unavailable")
);
}
export function checkpointDiffQueryOptions(
api: NativeApi | undefined,
input: CheckpointDiffQueryInput,
) {
const hasValidRange =
typeof input.fromTurnCount === "number" &&
typeof input.toTurnCount === "number" &&
Number.isInteger(input.fromTurnCount) &&
Number.isInteger(input.toTurnCount) &&
input.fromTurnCount >= 0 &&
input.toTurnCount >= 0 &&
input.fromTurnCount <= input.toTurnCount;
return queryOptions({
queryKey: providerQueryKeys.checkpointDiff(input),
queryFn: async () => {
if (!api || !input.sessionId || !hasValidRange) {
throw new Error("Checkpoint diff is unavailable.");
}
const { fromTurnCount, toTurnCount } = input;
if (typeof fromTurnCount !== "number" || typeof toTurnCount !== "number") {
throw new Error("Checkpoint diff range is invalid.");
}
return api.providers.getCheckpointDiff({
sessionId: input.sessionId,
fromTurnCount,
toTurnCount,
});
},
enabled: !!api && !!input.sessionId && hasValidRange,
staleTime: Infinity,
retry: (failureCount, error) => {
if (isCheckpointTemporarilyUnavailable(error)) {
return failureCount < 12;
}
return failureCount < 3;
},
retryDelay: (attempt, error) =>
isCheckpointTemporarilyUnavailable(error)
? Math.min(5_000, 250 * 2 ** (attempt - 1))
: Math.min(1_000, 100 * 2 ** (attempt - 1)),
});
}
+3 -34
View File
@@ -1,44 +1,13 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider } from "@tanstack/react-router";
import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack/react-router";
import { StoreProvider } from "./store";
import "@xterm/xterm/css/xterm.css";
import "highlight.js/styles/github-dark.css";
import App from "./App";
import "./index.css";
import { APP_DISPLAY_NAME } from "./branding";
import { isElectron } from "./env";
import { routeTree } from "./routeTree.gen";
const history = isElectron ? createHashHistory() : createBrowserHistory();
const queryClient = new QueryClient();
document.title = APP_DISPLAY_NAME;
const router = createRouter({
routeTree,
history,
context: {
queryClient,
},
Wrap: ({ children }) => (
<QueryClientProvider client={queryClient}>
<StoreProvider>{children}</StoreProvider>
</QueryClientProvider>
),
});
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<RouterProvider router={router} />
<App />
</React.StrictMode>,
);
-18
View File
@@ -1,18 +0,0 @@
import type { NativeApi } from "@t3tools/contracts";
import { createWsNativeApi } from "./wsNativeApi";
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
cachedApi = createWsNativeApi();
return cachedApi;
}
+377
View File
@@ -0,0 +1,377 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
it("returns null for invalid payloads", () => {
expect(hydratePersistedState('{"projects":"bad"}', false)).toBeNull();
expect(hydratePersistedState("not-json", false)).toBeNull();
});
it("migrates the legacy default model to the current default", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.2-codex",
expanded: true,
scripts: [],
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.2-codex",
messages: [
{
id: "m-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, true);
expect(hydrated).not.toBeNull();
expect(hydrated?.projects[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.model).toBe(DEFAULT_MODEL);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("filters unknown project references and repairs active thread", () => {
const payload = JSON.stringify({
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
threads: [
{
id: "t-1",
projectId: "p-1",
title: "Valid thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
{
id: "t-2",
projectId: "p-missing",
title: "Dangling thread",
model: "gpt-5.3-codex",
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-2",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated).not.toBeNull();
expect(hydrated?.threads.map((thread) => thread.id)).toEqual(["t-1"]);
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access");
});
it("hydrates runtime mode from v3 payload", () => {
const payload = JSON.stringify({
version: 3,
runtimeMode: "approval-required",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
threads: [],
activeThreadId: null,
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.runtimeMode).toBe("approval-required");
});
it("hydrates terminal fields from legacy v6 payload", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
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, "term-2"],
activeTerminalId: "term-2",
terminalLayout: "tabs",
splitTerminalIds: [],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:01:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("hydrates legacy split layout into a grouped split", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
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, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalLayout: "split",
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("defaults terminalHeight when hydrating v5 payloads", () => {
const payload = JSON.stringify({
version: 5,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
});
describe("toPersistedState", () => {
it("writes v7 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: [],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
session: null,
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
previewUrl: "blob:preview-1",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:02: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,
scripts: [],
},
],
threads: [thread],
activeThreadId: "t-1",
runtimeMode: "full-access",
});
expect(persisted.version).toBe(7);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
codexThreadId: "thr_1",
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: null,
worktreePath: null,
});
const persistedThread = persisted.threads[0];
expect(persistedThread).toBeDefined();
if (!persistedThread) return;
expect("error" in persistedThread).toBe(false);
expect("session" in persistedThread).toBe(false);
});
});
+360
View File
@@ -0,0 +1,360 @@
import { z } from "zod";
import { projectScriptSchema } from "@t3tools/contracts";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
const persistedProjectSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
cwd: z.string().min(1),
model: z.string().min(1),
expanded: z.boolean(),
scripts: z.array(projectScriptSchema).default([]),
});
const persistedMessageSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
attachments: z
.array(
z.object({
type: z.literal("image"),
id: z.string().min(1),
name: z.string().min(1),
mimeType: z.string().min(1),
sizeBytes: z.number().int().min(1),
}),
)
.optional(),
createdAt: z.string().min(1),
streaming: z.boolean(),
});
const persistedTerminalGroupSchema = z.object({
id: z.string().trim().min(1),
terminalIds: z.array(z.string().trim().min(1)),
});
const persistedThreadSchema = z.object({
id: z.string().min(1),
codexThreadId: z.string().min(1).nullable().default(null),
projectId: z.string().min(1),
title: z.string().min(1),
model: z.string().min(1),
terminalOpen: z.boolean().default(false),
terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
activeTerminalGroupId: z.string().trim().min(1).optional(),
// Legacy v6 and older fields retained for migration.
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
messages: z.array(persistedMessageSchema),
createdAt: z.string().min(1),
lastVisitedAt: z.string().min(1).optional(),
branch: z.string().min(1).nullable().optional(),
worktreePath: z.string().min(1).nullable().optional(),
});
const persistedStateBodySchema = z.object({
projects: z.array(persistedProjectSchema),
threads: z.array(persistedThreadSchema),
activeThreadId: z.string().min(1).nullable(),
});
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
export const persistedStateV1Schema = persistedStateBodySchema.extend({
version: z.literal(1).optional(),
});
export const persistedStateV2Schema = persistedStateBodySchema.extend({
version: z.literal(2).optional(),
});
export const persistedStateV3Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(3).optional(),
});
export const persistedStateV4Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(4).optional(),
});
export const persistedStateV6Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(6).optional(),
});
export const persistedStateV7Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(7).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(),
});
const persistedStateSchema = z.union([
persistedStateV7Schema,
persistedStateV6Schema,
persistedStateV5Schema,
persistedStateV4Schema,
persistedStateV3Schema,
persistedStateV2Schema,
persistedStateV1Schema,
]);
export interface PersistedStoreSnapshot {
projects: Project[];
threads: Thread[];
activeThreadId: string | null;
runtimeMode: RuntimeMode;
}
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
if (!isLegacyPayload) {
return model;
}
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
}
function hydrateProject(
project: z.infer<typeof persistedProjectSchema>,
isLegacyPayload: boolean,
): Project {
return {
...project,
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
scripts: project.scripts,
};
}
function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean,
): Thread {
const terminalIds = [
...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
];
const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const safeTerminalIdSet = new Set(safeTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const normalizedGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of thread.terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!safeTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
normalizedGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
const splitTerminalIds = [
...new Set(
(thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
),
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
if (splitTerminalIds.length >= 2) {
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
for (const terminalId of splitGroupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
normalizedGroups.push({
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
terminalIds: splitGroupTerminalIds,
});
}
}
for (const terminalId of safeTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
normalizedGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
const activeGroupIndexFromId = normalizedGroups.findIndex(
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(activeTerminalId),
);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
normalizedGroups[activeGroupIndex]?.id ??
normalizedGroups[0]?.id ??
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
return {
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
terminalOpen: thread.terminalOpen ?? false,
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: safeTerminalIds,
runningTerminalIds: [],
activeTerminalId,
terminalGroups: normalizedGroups,
activeTerminalGroupId,
session: null,
messages: thread.messages.map((message) => {
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
return {
id: message.id,
role: message.role,
text: message.text,
...(hydratedAttachments && hydratedAttachments.length > 0
? { attachments: hydratedAttachments }
: {}),
createdAt: message.createdAt,
streaming: false,
};
}),
events: [],
error: null,
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
};
}
export function hydratePersistedState(
raw: string,
isLegacyPayload: boolean,
): PersistedStoreSnapshot | null {
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
return null;
}
const parsedState = persistedStateSchema.safeParse(parsedJson);
if (!parsedState.success) {
return null;
}
const projects = parsedState.data.projects.map((project) =>
hydrateProject(project, isLegacyPayload),
);
const projectIds = new Set(projects.map((project) => project.id));
const threads = parsedState.data.threads
.map((thread) => hydrateThread(thread, isLegacyPayload))
.filter((thread) => projectIds.has(thread.projectId));
const hasActiveThread = Boolean(
parsedState.data.activeThreadId &&
threads.some((thread) => thread.id === parsedState.data.activeThreadId),
);
return {
projects,
threads,
activeThreadId: hasActiveThread ? parsedState.data.activeThreadId : (threads[0]?.id ?? null),
runtimeMode:
"runtimeMode" in parsedState.data ? parsedState.data.runtimeMode : DEFAULT_RUNTIME_MODE,
};
}
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV7Schema> {
return {
version: 7,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
codexThreadId: thread.codexThreadId,
projectId: thread.projectId,
title: thread.title,
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
messages: thread.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
...(message.attachments && message.attachments.length > 0
? {
attachments: message.attachments.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
})),
}
: {}),
createdAt: message.createdAt,
streaming: message.streaming,
})),
createdAt: thread.createdAt,
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
branch: thread.branch,
worktreePath: thread.worktreePath,
})),
activeThreadId: state.activeThreadId,
runtimeMode: state.runtimeMode,
};
}
-118
View File
@@ -1,118 +0,0 @@
/* eslint-disable */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
const ChatRoute = ChatRouteImport.update({
id: '/_chat',
getParentRoute: () => rootRouteImport,
} as any)
const ChatIndexRoute = ChatIndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => ChatRoute,
} as any)
const ChatSettingsRoute = ChatSettingsRouteImport.update({
id: '/settings',
path: '/settings',
getParentRoute: () => ChatRoute,
} as any)
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
id: '/$threadId',
path: '/$threadId',
getParentRoute: () => ChatRoute,
} as any)
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
}
export interface FileRoutesByTo {
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
'/': typeof ChatIndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/_chat/$threadId': typeof ChatThreadIdRoute
'/_chat/settings': typeof ChatSettingsRoute
'/_chat/': typeof ChatIndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/$threadId' | '/settings'
fileRoutesByTo: FileRoutesByTo
to: '/$threadId' | '/settings' | '/'
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/_chat': {
id: '/_chat'
path: ''
fullPath: '/'
preLoaderRoute: typeof ChatRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat/': {
id: '/_chat/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof ChatIndexRouteImport
parentRoute: typeof ChatRoute
}
'/_chat/settings': {
id: '/_chat/settings'
path: '/settings'
fullPath: '/settings'
preLoaderRoute: typeof ChatSettingsRouteImport
parentRoute: typeof ChatRoute
}
'/_chat/$threadId': {
id: '/_chat/$threadId'
path: '/$threadId'
fullPath: '/$threadId'
preLoaderRoute: typeof ChatThreadIdRouteImport
parentRoute: typeof ChatRoute
}
}
}
interface ChatRouteChildren {
ChatThreadIdRoute: typeof ChatThreadIdRoute
ChatSettingsRoute: typeof ChatSettingsRoute
ChatIndexRoute: typeof ChatIndexRoute
}
const ChatRouteChildren: ChatRouteChildren = {
ChatThreadIdRoute: ChatThreadIdRoute,
ChatSettingsRoute: ChatSettingsRoute,
ChatIndexRoute: ChatIndexRoute,
}
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()
-205
View File
@@ -1,205 +0,0 @@
import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { isElectron } from "../env";
import { useNativeApi } from "../hooks/useNativeApi";
import { DEFAULT_MODEL } from "../model-logic";
import { useStore } from "../store";
import { onServerWelcome } from "../wsNativeApi";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
}>()({
component: RootRouteView,
errorComponent: RootRouteErrorView,
});
function RootRouteView() {
const api = useNativeApi();
if (!api) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">
Connecting to {APP_DISPLAY_NAME} server...
</p>
</div>
</div>
);
}
return (
<ToastProvider>
<AnchoredToastProvider>
<EventRouter />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
<Outlet />
</AnchoredToastProvider>
</ToastProvider>
);
}
function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
const message = errorMessage(error);
const details = errorDetails(error);
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-80">
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
</div>
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
{APP_DISPLAY_NAME}
</p>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
Something went wrong.
</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
<div className="mt-5 flex flex-wrap gap-2">
<Button size="sm" onClick={() => reset()}>
Try again
</Button>
<Button size="sm" variant="outline" onClick={() => window.location.reload()}>
Reload app
</Button>
</div>
<details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
<summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
<span className="group-open:hidden">Show error details</span>
<span className="hidden group-open:inline">Hide error details</span>
</summary>
<pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
{details}
</pre>
</details>
</section>
</div>
);
}
function errorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
if (typeof error === "string" && error.trim().length > 0) {
return error;
}
return "An unexpected router error occurred.";
}
function errorDetails(error: unknown): string {
if (error instanceof Error) {
return error.stack ?? error.message;
}
if (typeof error === "string") {
return error;
}
try {
return JSON.stringify(error, null, 2);
} catch {
return "No additional error details are available.";
}
}
function EventRouter() {
const api = useNativeApi();
const { dispatch } = useStore();
useEffect(() => {
if (!api) return;
void api.orchestration
.getSnapshot()
.then((snapshot) => {
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
})
.catch(() => undefined);
const unsubReadModel = api.orchestration.onReadModel((snapshot) => {
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
});
return () => {
unsubReadModel();
};
}, [api, dispatch]);
return null;
}
function AutoProjectBootstrap() {
const api = useNativeApi();
const { state, dispatch } = useStore();
const bootstrappedRef = useRef(false);
useEffect(() => {
if (!api) return;
// Browser mode bootstraps from server welcome.
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
if (isElectron) return;
if (!state.threadsHydrated) return;
return onServerWelcome((payload) => {
if (bootstrappedRef.current) return;
// Don't create duplicate projects for the same cwd
const existing = state.projects.find((project) => project.cwd === payload.cwd);
if (existing) {
bootstrappedRef.current = true;
return;
}
bootstrappedRef.current = true;
const projectId = crypto.randomUUID();
const threadId = crypto.randomUUID();
const now = new Date().toISOString();
void api.orchestration
.dispatchCommand({
type: "project.create",
commandId: crypto.randomUUID(),
projectId,
name: payload.projectName,
cwd: payload.cwd,
model: DEFAULT_MODEL,
createdAt: now,
})
.then(() =>
api.orchestration.dispatchCommand({
type: "thread.create",
commandId: crypto.randomUUID(),
threadId,
projectId,
title: "New thread",
model: DEFAULT_MODEL,
branch: null,
worktreePath: null,
createdAt: now,
}),
)
.catch(() => undefined);
});
}, [api, state.projects, state.threadsHydrated, dispatch]);
return null;
}
function DesktopProjectBootstrap() {
// Desktop now hydrates from orchestration read-model snapshots.
return null;
}
-112
View File
@@ -1,112 +0,0 @@
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
import ChatView from "../components/ChatView";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store";
import { Sheet, SheetPopup } from "../components/ui/sheet";
const DiffPanel = lazy(() => import("../components/DiffPanel"));
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
const DiffPanelWrapper = (props: {
children: ReactNode;
sheet: boolean;
diffOpen: boolean;
onCloseDiff: () => void;
}) => {
if (props.sheet) {
return (
<Sheet
open={props.diffOpen}
onOpenChange={(open) => {
if (!open) {
props.onCloseDiff();
}
}}
>
<SheetPopup
side="right"
showCloseButton={false}
keepMounted
className="w-[min(88vw,820px)] max-w-[820px] p-0"
>
{props.children}
</SheetPopup>
</Sheet>
);
}
return (
<aside className={props.diffOpen ? undefined : "hidden"} aria-hidden={!props.diffOpen}>
{props.children}
</aside>
);
};
function ChatThreadRouteView() {
const { state } = useStore();
const navigate = useNavigate();
const { threadId } = Route.useParams();
const search = Route.useSearch();
const threadExists = threadId ? state.threads.some((thread) => thread.id === threadId) : false;
const diffOpen = search.diff === "1";
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const closeDiff = useCallback(() => {
void navigate({
to: "/$threadId",
params: { threadId },
search: (previous) => {
return stripDiffSearchParams(previous);
},
});
}, [navigate, threadId]);
useEffect(() => {
if (!threadId) {
void navigate({ to: "/", replace: true });
return;
}
if (!state.threadsHydrated) {
return;
}
if (!threadExists) {
void navigate({ to: "/", replace: true });
return;
}
}, [navigate, state.threadsHydrated, threadExists, threadId]);
if (!threadId || !state.threadsHydrated || !threadExists) {
return null;
}
const diffLoadingFallback =
!diffOpen || shouldUseDiffSheet ? (
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
Loading diff viewer...
</div>
) : (
<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>
);
return (
<>
<ChatView threadId={threadId} />
<DiffPanelWrapper sheet={shouldUseDiffSheet} diffOpen={diffOpen} onCloseDiff={closeDiff}>
<Suspense fallback={diffLoadingFallback}>
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
</Suspense>
</DiffPanelWrapper>
</>
);
}
export const Route = createFileRoute("/_chat/$threadId")({
validateSearch: (search) => parseDiffRouteSearch(search),
component: ChatThreadRouteView,
});
-25
View File
@@ -1,25 +0,0 @@
import { createFileRoute } from "@tanstack/react-router";
import { isElectron } from "../env";
function ChatIndexRouteView() {
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-muted-foreground/40">
{isElectron && (
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
<span className="text-xs text-muted-foreground/50">No active thread</span>
</div>
)}
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
<p className="text-sm">Select a thread or create a new one to get started.</p>
</div>
</div>
</div>
);
}
export const Route = createFileRoute("/_chat/")({
component: ChatIndexRouteView,
});
-259
View File
@@ -1,259 +0,0 @@
import { createFileRoute } from "@tanstack/react-router";
import { useAppSettings } from "../appSettings";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { useStore } from "../store";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Switch } from "../components/ui/switch";
const THEME_OPTIONS = [
{
value: "system",
label: "System",
description: "Match your OS appearance setting.",
},
{
value: "light",
label: "Light",
description: "Always use the light theme.",
},
{
value: "dark",
label: "Dark",
description: "Always use the dark theme.",
},
] as const;
const RUNTIME_MODE_OPTIONS = [
{
value: "full-access",
label: "Full access",
description: "Allow commands to run without confirmation prompts.",
},
{
value: "approval-required",
label: "Supervised",
description: "Require approval prompts before command execution.",
},
] as const;
function SettingsRouteView() {
const { theme, setTheme, resolvedTheme } = useTheme();
const { state, dispatch } = useStore();
const { settings, defaults, updateSettings } = useAppSettings();
const codexBinaryPath = settings.codexBinaryPath;
const codexHomePath = settings.codexHomePath;
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
{isElectron && (
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
<span className="text-xs font-medium tracking-wide text-muted-foreground/70">Settings</span>
</div>
)}
<div className="flex-1 overflow-y-auto p-6">
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6">
<header className="space-y-1">
<h1 className="text-2xl font-semibold tracking-tight text-foreground">Settings</h1>
<p className="text-sm text-muted-foreground">
Configure app-level preferences for this device.
</p>
</header>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Appearance</h2>
<p className="mt-1 text-xs text-muted-foreground">
Choose how T3 Code handles light and dark mode.
</p>
</div>
<div className="space-y-2" role="radiogroup" aria-label="Theme preference">
{THEME_OPTIONS.map((option) => {
const selected = theme === option.value;
return (
<button
key={option.value}
type="button"
role="radio"
aria-checked={selected}
className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
selected
? "border-primary/60 bg-primary/8 text-foreground"
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => setTheme(option.value)}
>
<span className="flex flex-col">
<span className="text-sm font-medium">{option.label}</span>
<span className="text-xs">{option.description}</span>
</span>
{selected ? (
<span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
Selected
</span>
) : null}
</button>
);
})}
</div>
<p className="mt-4 text-xs text-muted-foreground">
Active theme: <span className="font-medium text-foreground">{resolvedTheme}</span>
</p>
</section>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Codex App Server</h2>
<p className="mt-1 text-xs text-muted-foreground">
These overrides apply to new sessions and let you use a non-default Codex install.
</p>
</div>
<div className="space-y-4">
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">Codex binary path</span>
<Input
value={codexBinaryPath}
onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
placeholder="codex"
spellCheck={false}
/>
<span className="text-xs text-muted-foreground">
Leave blank to use <code>codex</code> from your PATH.
</span>
</label>
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
<Input
value={codexHomePath}
onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
placeholder="/Users/you/.codex"
spellCheck={false}
/>
<span className="text-xs text-muted-foreground">
Optional custom Codex home/config directory.
</span>
</label>
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
<p>
Binary source: <span className="font-medium text-foreground">{codexBinaryPath || "PATH"}</span>
</p>
<Button
size="xs"
variant="outline"
onClick={() =>
updateSettings({
codexBinaryPath: defaults.codexBinaryPath,
codexHomePath: defaults.codexHomePath,
})
}
>
Reset codex overrides
</Button>
</div>
</div>
</section>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
<p className="mt-1 text-xs text-muted-foreground">
Select the default execution policy for this client.
</p>
</div>
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
{RUNTIME_MODE_OPTIONS.map((option) => {
const selected = state.runtimeMode === option.value;
return (
<button
key={option.value}
type="button"
role="radio"
aria-checked={selected}
className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
selected
? "border-primary/60 bg-primary/8 text-foreground"
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => {
dispatch({
type: "SET_RUNTIME_MODE",
mode: option.value,
});
}}
>
<span className="flex flex-col">
<span className="text-sm font-medium">{option.label}</span>
<span className="text-xs">{option.description}</span>
</span>
{selected ? (
<span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
Selected
</span>
) : null}
</button>
);
})}
</div>
</section>
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4">
<h2 className="text-sm font-medium text-foreground">Safety</h2>
<p className="mt-1 text-xs text-muted-foreground">
Additional guardrails for destructive local actions.
</p>
</div>
<div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
<div>
<p className="text-sm font-medium text-foreground">Confirm thread deletion</p>
<p className="text-xs text-muted-foreground">
Ask for confirmation before deleting a thread and its chat history.
</p>
</div>
<Switch
checked={settings.confirmThreadDelete}
onCheckedChange={(checked) =>
updateSettings({
confirmThreadDelete: Boolean(checked),
})
}
aria-label="Confirm thread deletion"
/>
</div>
{settings.confirmThreadDelete !== defaults.confirmThreadDelete ? (
<div className="mt-3 flex justify-end">
<Button
size="xs"
variant="outline"
onClick={() =>
updateSettings({
confirmThreadDelete: defaults.confirmThreadDelete,
})
}
>
Restore default
</Button>
</div>
) : null}
</section>
</div>
</div>
</div>
);
}
export const Route = createFileRoute("/_chat/settings")({
component: SettingsRouteView,
});
-39
View File
@@ -1,39 +0,0 @@
import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect } from "react";
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
import Sidebar from "../components/Sidebar";
function ChatRouteLayout() {
const navigate = useNavigate();
useEffect(() => {
const onMenuAction = window.desktopBridge?.onMenuAction;
if (typeof onMenuAction !== "function") {
return;
}
const unsubscribe = onMenuAction((action) => {
if (action !== "open-settings") return;
void navigate({ to: "/settings" });
});
return () => {
unsubscribe?.();
};
}, [navigate]);
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
<Sidebar />
<DiffWorkerPoolProvider>
<Outlet />
</DiffWorkerPoolProvider>
</div>
);
}
export const Route = createFileRoute("/_chat")({
component: ChatRouteLayout,
});
+700
View File
@@ -0,0 +1,700 @@
import { describe, expect, it } from "vitest";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
} from "./session-logic";
import type { ChatMessage } from "./types";
function makeEvent(overrides: Partial<ProviderEvent>): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-08T10:00:00.000Z",
method: "noop",
...overrides,
};
}
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-08T09:59:00.000Z",
updatedAt: "2026-02-08T09:59:00.000Z",
...overrides,
};
}
describe("deriveTimelineEntries", () => {
it("interleaves messages and work entries by timestamp", () => {
const messages: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:05:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:02:00.000Z",
tone: "tool",
},
{
id: "w-2",
label: "Preamble",
createdAt: "2026-02-08T10:03:00.000Z",
tone: "thinking",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual([
"message:m-user",
"work:w-1",
"work:w-2",
"message:m-assistant",
]);
});
it("prefers work entries when timestamps are equal", () => {
const messages: ChatMessage[] = [
{
id: "m-1",
role: "assistant",
text: "Done",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
];
const workEntries: WorkLogEntry[] = [
{
id: "w-1",
label: "Tool call",
createdAt: "2026-02-08T10:00:00.000Z",
tone: "tool",
},
];
const timeline = deriveTimelineEntries(messages, workEntries);
expect(timeline.map((entry) => entry.id)).toEqual(["work:w-1", "message:m-1"]);
});
});
describe("deriveWorkLogEntries", () => {
it("drops preamble/work events from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-1",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { item: { type: "preamble", text: "thinking" } },
}),
makeEvent({
id: "evt-2",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "work", text: "planning" } },
}),
makeEvent({
id: "evt-3",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
});
it("does not surface successful turn completion as a work-log row", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("shows failed turn completion in the work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:10.000Z",
payload: {
turn: {
id: "turn-1",
status: "failed",
error: { message: "sandbox denied" },
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Turn failed");
expect(entries[0]?.detail).toBe("sandbox denied");
});
it("hides reasoning and agent-message noise from the visible work log", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-start",
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:00.000Z",
}),
makeEvent({
id: "evt-summary-part",
method: "item/reasoning/summaryPartAdded",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-summary-delta",
method: "item/reasoning/summaryTextDelta",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
}),
makeEvent({
id: "evt-agent-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:03.000Z",
payload: {
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
},
}),
makeEvent({
id: "evt-agent-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:04.000Z",
payload: {
item: {
id: "item-msg",
type: "agentMessage",
text: "Done response",
},
},
}),
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-tool-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:06.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
},
}),
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:08.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
],
"turn-1",
);
expect(entries.map((entry) => entry.label)).toEqual(["Tool call"]);
});
it("coalesces command start/completed lifecycle into one entry", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-command-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
makeEvent({
id: "evt-command-complete",
method: "item/completed",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-command",
type: "command_execution",
command: "git status --short",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Command run");
expect(entries[0]?.detail).toBe("git status --short");
});
it("preserves full tool-call detail text without data truncation", () => {
const longCommand =
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call", command: longCommand },
},
}),
],
"turn-1",
);
expect(entries[0]?.detail).toBe(longCommand);
});
it("hides generic tool-call rows that have no identifying detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-tool-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: { id: "item-tool", type: "tool_call" },
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(0);
});
it("includes collab tool-call rows with tool name detail", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-collab-start",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:05.000Z",
payload: {
item: {
id: "item-collab",
type: "collabAgentToolCall",
tool: "spawnAgent",
},
},
}),
],
"turn-1",
);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Tool call");
expect(entries[0]?.detail).toBe("spawnAgent");
});
it("can derive work-log entries across all turns when not scoped", () => {
const entries = deriveWorkLogEntries(
[
makeEvent({
id: "evt-turn-1-tool",
method: "item/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { item: { type: "tool_call", command: "ls -la" } },
}),
makeEvent({
id: "evt-turn-2-tool",
method: "item/started",
turnId: "turn-2",
createdAt: "2026-02-08T10:00:02.000Z",
payload: { item: { type: "tool_call", command: "pwd" } },
}),
],
undefined,
);
expect(entries).toHaveLength(2);
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
});
});
describe("derivePendingApprovals", () => {
it("returns pending command/file-change approvals", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { command: "git commit -m 'msg'" },
}),
]);
expect(approvals).toEqual([
{
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
detail: "git commit -m 'msg'",
},
]);
});
it("removes approvals after a decision event", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-decision",
method: "item/requestApproval/decision",
requestId: "req-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/fileChange/requestApproval",
requestId: "req-1",
requestKind: "file-change",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
it("clears pending approvals after turn completion", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "thread/started",
createdAt: "2026-02-08T10:01:00.000Z",
payload: { thread: { id: "thread-1" } },
}),
);
expect(next.threadId).toBe("thread-1");
expect(next.updatedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("moves to running and records active turn on turn start", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
method: "turn/started",
turnId: "turn-1",
createdAt: "2026-02-08T10:02:00.000Z",
}),
);
expect(next.status).toBe("running");
expect(next.activeTurnId).toBe("turn-1");
expect(next.updatedAt).toBe("2026-02-08T10:02:00.000Z");
});
it("returns to ready and clears active turn on successful completion", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
lastError: "older error",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
);
expect(next.status).toBe("ready");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("older error");
});
it("marks session as error when turn fails", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "turn/completed",
createdAt: "2026-02-08T10:03:00.000Z",
payload: {
turn: { id: "turn-1", status: "failed", error: { message: "boom" } },
},
}),
);
expect(next.status).toBe("error");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("boom");
});
it("moves to error on runtime error events", () => {
const previous = makeSession();
const next = evolveSession(
previous,
makeEvent({
kind: "error",
method: "runtime/error",
createdAt: "2026-02-08T10:04:00.000Z",
message: "runtime failure",
}),
);
expect(next.status).toBe("error");
expect(next.lastError).toBe("runtime failure");
});
it("closes session on close lifecycle events", () => {
const previous = makeSession({
status: "running",
activeTurnId: "turn-1",
});
const next = evolveSession(
previous,
makeEvent({
method: "session/closed",
createdAt: "2026-02-08T10:05:00.000Z",
message: "closed",
}),
);
expect(next.status).toBe("closed");
expect(next.activeTurnId).toBeUndefined();
expect(next.lastError).toBe("closed");
});
});
describe("applyEventToMessages", () => {
it("handles start/delta/completed flow for assistant messages", () => {
const activeAssistantItemRef = { current: null as string | null };
const started = applyEventToMessages(
[],
makeEvent({
method: "item/started",
createdAt: "2026-02-08T10:00:00.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello",
},
},
}),
activeAssistantItemRef,
);
expect(started).toEqual([
{
id: "item-1",
role: "assistant",
text: "Hello",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: true,
},
]);
expect(activeAssistantItemRef.current).toBe("item-1");
const withDelta = applyEventToMessages(
started,
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-1",
textDelta: " world",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.text).toBe("Hello world");
expect(withDelta[0]?.streaming).toBe(true);
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-1",
type: "agentMessage",
text: "Hello world!",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Hello world!");
expect(completed[0]?.streaming).toBe(false);
expect(activeAssistantItemRef.current).toBeNull();
});
it("supports out-of-order delta before started/completed", () => {
const activeAssistantItemRef = { current: null as string | null };
const withDelta = applyEventToMessages(
[],
makeEvent({
method: "item/agentMessage/delta",
createdAt: "2026-02-08T10:00:01.000Z",
itemId: "item-2",
textDelta: "Partial",
}),
activeAssistantItemRef,
);
expect(withDelta[0]?.id).toBe("item-2");
expect(withDelta[0]?.text).toBe("Partial");
expect(withDelta[0]?.streaming).toBe(true);
expect(activeAssistantItemRef.current).toBe("item-2");
const completed = applyEventToMessages(
withDelta,
makeEvent({
method: "item/completed",
createdAt: "2026-02-08T10:00:02.000Z",
payload: {
item: {
id: "item-2",
type: "agentMessage",
text: "Partial + final",
},
},
}),
activeAssistantItemRef,
);
expect(completed[0]?.text).toBe("Partial + final");
expect(completed[0]?.streaming).toBe(false);
});
it("clears all streaming flags when turn completes", () => {
const previous: ChatMessage[] = [
{
id: "m-user",
role: "user",
text: "Hi",
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
{
id: "m-assistant",
role: "assistant",
text: "Typing",
createdAt: "2026-02-08T10:00:01.000Z",
streaming: true,
},
];
const next = applyEventToMessages(
previous,
makeEvent({
method: "turn/completed",
}),
{ current: null },
);
expect(next.every((entry) => entry.streaming === false)).toBe(true);
});
});
+606 -70
View File
@@ -1,6 +1,6 @@
import type { ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase, TurnDiffFileChange, TurnDiffSummary } from "./types";
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
import type { ChatMessage, SessionPhase } from "./types";
import { createWsNativeApi } from "./wsNativeApi";
export const PROVIDER_OPTIONS: Array<{
value: ProviderKind;
@@ -11,6 +11,65 @@ export const PROVIDER_OPTIONS: Array<{
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
];
let cachedApi: NativeApi | undefined;
export function readNativeApi(): NativeApi | undefined {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
// Prefer Electron preload bridge if available
if (window.nativeApi) {
cachedApi = window.nativeApi;
return cachedApi;
}
// Fall back to WebSocket transport
cachedApi = createWsNativeApi();
return cachedApi;
}
export function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
}
export function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
return null;
}
return formatDuration(endedAt - startedAt);
}
export interface WorkLogEntry {
id: string;
createdAt: string;
@@ -40,94 +99,412 @@ export type TimelineEntry =
entry: WorkLogEntry;
};
export function formatTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
second: "2-digit",
}).format(new Date(isoDate));
function normalizeDetail(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1_000);
if (seconds === 0) return `${minutes}m`;
if (seconds === 60) return `${minutes + 1}m`;
return `${minutes}m ${seconds}s`;
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
if (!endIso) return null;
const startedAt = Date.parse(startIso);
const endedAt = Date.parse(endIso);
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
const pending = new Map<string, PendingApproval>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited" ||
event.method === "turn/completed"
) {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[._/-]/g, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase();
}
function shouldDropItemType(type: string): boolean {
if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) {
return true;
}
return type === "work" || type.startsWith("work ");
}
function shouldShowItemLifecycle(type: string): boolean {
return type.includes("tool") || type.includes("command") || type.includes("file change");
}
function shouldDropMethod(method: string): boolean {
return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
}
function itemTypeMeta(type: string): {
label: string;
tone: WorkLogEntry["tone"];
} {
if (type.includes("command")) {
return { label: "Command run", tone: "tool" };
}
if (type.includes("file change")) {
return { label: "File change", tone: "tool" };
}
if (type.includes("tool")) {
return { label: "Tool call", tone: "tool" };
}
return { label: "Work item", tone: "info" };
}
interface ItemLifecycleCandidate {
id: string;
itemId?: string;
createdAt: string;
label: string;
detail?: string;
tone: WorkLogEntry["tone"];
phase: "started" | "completed";
}
function extractDetail(
payload: Record<string, unknown> | undefined,
item: Record<string, unknown> | undefined,
): string | undefined {
const candidates = [
asString(item?.command),
asString(item?.tool),
asString(item?.name),
asString(item?.title),
asString(item?.summary),
asString(item?.text),
asString(item?.prompt),
asString(payload?.message),
asString(payload?.prompt),
asString(payload?.command),
];
for (const candidate of candidates) {
const detail = normalizeDetail(candidate);
if (detail) return detail;
}
return undefined;
}
function lifecycleCandidateFromItemEvent(event: ProviderEvent): ItemLifecycleCandidate | null {
const payload = asObject(event.payload);
const item = asObject(payload?.item);
const normalizedType = normalizeItemType(asString(item?.type));
if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
return null;
}
return formatDuration(endedAt - startedAt);
if (!shouldShowItemLifecycle(normalizedType)) {
return null;
}
const meta = itemTypeMeta(normalizedType);
const isStarted = event.method === "item/started";
const isCompleted = event.method === "item/completed";
if (!isStarted && !isCompleted) {
return null;
}
const detail = extractDetail(payload, item);
const itemId = event.itemId ?? asString(item?.id);
return {
id: event.id,
...(itemId ? { itemId } : {}),
createdAt: event.createdAt,
label: meta.label,
...(detail ? { detail } : {}),
tone: meta.tone,
phase: isCompleted ? "completed" : "started",
};
}
export function derivePendingApprovals(_events: unknown[]): PendingApproval[] {
return [];
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "request") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method.includes("commandExecution")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Command approval requested",
tone: "tool",
};
}
if (event.method.includes("fileChange")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "File-change approval requested",
tone: "tool",
};
}
if (event.method.includes("requestUserInput")) {
return {
id: event.id,
createdAt: event.createdAt,
label: "Tool requested user input",
tone: "tool",
};
}
return {
id: event.id,
createdAt: event.createdAt,
label: `Request: ${event.method}`,
tone: "info",
};
}
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "notification") return null;
if (shouldDropMethod(event.method)) return null;
if (event.method === "item/agentMessage/delta") return null;
if (event.method === "turn/started") {
return null;
}
if (event.method === "thread/started") return null;
if (event.method === "turn/completed") {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
if (status !== "failed") {
return null;
}
const turnError = asObject(turn?.error);
const turnErrorMessage = asString(turnError?.message);
const turnErrorDetail = normalizeDetail(turnErrorMessage);
return {
id: event.id,
createdAt: event.createdAt,
label: "Turn failed",
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
tone: "error",
};
}
if (event.method.startsWith("item/")) return null;
return null;
}
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
if (event.kind !== "error") return null;
if (shouldDropMethod(event.method)) return null;
const detail = normalizeDetail(event.message);
return {
id: event.id,
createdAt: event.createdAt,
label: "Runtime error",
...(detail ? { detail } : {}),
tone: "error",
};
}
function eventTurnId(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return event.turnId ?? asString(turn?.id);
}
export function deriveWorkLogEntries(
_events: unknown[],
_latestTurnId: string | undefined,
events: ProviderEvent[],
turnId: string | undefined,
): WorkLogEntry[] {
return [];
const ordered = [...events].toReversed();
const entries: WorkLogEntry[] = [];
const turnStartedAtIso = turnId
? ordered.find((event) => {
if (event.method !== "turn/started") return false;
return eventTurnId(event) === turnId;
})?.createdAt
: undefined;
const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
const shouldIncludeEvent = (event: ProviderEvent): boolean => {
if (!turnId) return true;
const scopedTurnId = eventTurnId(event);
if (scopedTurnId && scopedTurnId !== turnId) {
return false;
}
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
const eventAt = Date.parse(event.createdAt);
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
return false;
}
}
return true;
};
const completedLifecycleItemIds = new Set<string>();
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const candidate = lifecycleCandidateFromItemEvent(event);
if (candidate?.phase === "completed" && candidate.itemId) {
completedLifecycleItemIds.add(candidate.itemId);
}
}
for (const event of ordered) {
if (!shouldIncludeEvent(event)) continue;
const lifecycleCandidate = lifecycleCandidateFromItemEvent(event);
if (lifecycleCandidate) {
if (
lifecycleCandidate.phase === "started" &&
lifecycleCandidate.itemId &&
completedLifecycleItemIds.has(lifecycleCandidate.itemId)
) {
continue;
}
if (lifecycleCandidate.label === "Tool call" && !lifecycleCandidate.detail) {
continue;
}
entries.push({
id: lifecycleCandidate.id,
createdAt: lifecycleCandidate.createdAt,
label: lifecycleCandidate.label,
...(lifecycleCandidate.detail ? { detail: lifecycleCandidate.detail } : {}),
tone: lifecycleCandidate.tone,
});
continue;
}
const fromRequest = entryFromRequest(event);
if (fromRequest) {
entries.push(fromRequest);
continue;
}
const fromNotification = entryFromNotification(event);
if (fromNotification) {
entries.push(fromNotification);
continue;
}
const fromError = entryFromError(event);
if (fromError) {
entries.push(fromError);
}
}
return entries;
}
function toTimestamp(isoDate: string): number {
const parsed = Date.parse(isoDate);
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
}
export function deriveTimelineEntries(
messages: ChatMessage[],
workEntries: WorkLogEntry[],
): TimelineEntry[] {
const messageRows: TimelineEntry[] = messages.map((message) => ({
id: message.id,
kind: "message",
createdAt: message.createdAt,
message,
}));
const workRows: TimelineEntry[] = workEntries.map((entry) => ({
id: entry.id,
kind: "work",
createdAt: entry.createdAt,
entry,
}));
return [...messageRows, ...workRows].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
}
const timeline: TimelineEntry[] = [];
let messageIndex = 0;
let workIndex = 0;
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
const files: TurnDiffFileChange[] = [];
const lines = diff.split("\n");
for (const line of lines) {
if (!line.startsWith("diff --git ")) continue;
const match = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
const filePath = match?.[2] ?? match?.[1];
if (!filePath) continue;
files.push({ path: filePath });
while (messageIndex < messages.length || workIndex < workEntries.length) {
const message = messages[messageIndex];
const workEntry = workEntries[workIndex];
if (!message && workEntry) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
if (!workEntry && message) {
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
continue;
}
if (!message || !workEntry) {
break;
}
const messageAt = toTimestamp(message.createdAt);
const workAt = toTimestamp(workEntry.createdAt);
if (workAt <= messageAt) {
timeline.push({
id: `work:${workEntry.id}`,
kind: "work",
createdAt: workEntry.createdAt,
entry: workEntry,
});
workIndex += 1;
continue;
}
timeline.push({
id: `message:${message.id}`,
kind: "message",
createdAt: message.createdAt,
message,
});
messageIndex += 1;
}
return files;
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<string, number> {
const sorted = [...summaries].sort((a, b) => a.completedAt.localeCompare(b.completedAt));
const result: Record<string, number> = {};
for (let index = 0; index < sorted.length; index += 1) {
const summary = sorted[index];
if (!summary) continue;
result[summary.turnId] = index + 1;
}
return result;
}
export function deriveTurnDiffSummaries(_events: unknown[]): TurnDiffSummary[] {
return [];
return timeline;
}
export function derivePhase(session: ProviderSession | null): SessionPhase {
@@ -136,3 +513,162 @@ export function derivePhase(session: ProviderSession | null): SessionPhase {
if (session.status === "running") return "running";
return "ready";
}
export function evolveSession(previous: ProviderSession, event: ProviderEvent): ProviderSession {
const payload = asObject(event.payload);
if (event.method === "thread/started") {
const thread = asObject(payload?.thread);
return {
...previous,
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/started") {
const turn = asObject(payload?.turn);
return {
...previous,
status: "running",
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
updatedAt: event.createdAt,
};
}
if (event.method === "turn/completed") {
const turn = asObject(payload?.turn);
const status = asString(turn?.status);
const turnError = asObject(turn?.error);
return {
...previous,
status: status === "failed" ? "error" : "ready",
activeTurnId: undefined,
lastError: asString(turnError?.message) ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.kind === "error") {
return {
...previous,
status: "error",
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
if (event.method === "session/closed" || event.method === "session/exited") {
return {
...previous,
status: "closed",
activeTurnId: undefined,
lastError: event.message ?? previous.lastError,
updatedAt: event.createdAt,
};
}
return { ...previous, updatedAt: event.createdAt };
}
export function applyEventToMessages(
previous: ChatMessage[],
event: ProviderEvent,
activeAssistantItemRef: { current: string | null },
): ChatMessage[] {
const payload = asObject(event.payload);
if (event.method === "item/started") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
activeAssistantItemRef.current = itemId;
const seedText = asString(item?.text) ?? "";
const filtered = previous.filter((entry) => entry.id !== itemId);
return [
...filtered,
{
id: itemId,
role: "assistant",
text: seedText,
createdAt: event.createdAt,
streaming: true,
},
];
}
if (event.method === "item/agentMessage/delta") {
const itemId = event.itemId ?? asString(payload?.itemId);
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
if (!itemId || !delta) return previous;
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
activeAssistantItemRef.current = itemId;
return [
...previous,
{
id: itemId,
role: "assistant",
text: delta,
createdAt: event.createdAt,
streaming: true,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: `${existing.text}${delta}`,
streaming: true,
};
return updated;
}
if (event.method === "item/completed") {
const item = asObject(payload?.item);
if (asString(item?.type) !== "agentMessage") return previous;
const itemId = asString(item?.id);
if (!itemId) return previous;
const fullText = asString(item?.text);
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
if (existingIndex === -1) {
return [
...previous,
{
id: itemId,
role: "assistant",
text: fullText ?? "",
createdAt: event.createdAt,
streaming: false,
},
];
}
const updated = [...previous];
const existing = updated[existingIndex];
if (!existing) return previous;
updated[existingIndex] = {
...existing,
text: fullText ?? existing.text,
streaming: false,
};
if (activeAssistantItemRef.current === itemId) {
activeAssistantItemRef.current = null;
}
return updated;
}
if (event.method === "turn/completed") {
return previous.map((entry) => ({ ...entry, streaming: false }));
}
return previous;
}
+721
View File
@@ -0,0 +1,721 @@
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
} from "./types";
import type { Thread } from "./types";
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
type TerminalActivityEvent = Extract<TerminalEvent, { type: "activity" }>;
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
provider: "codex",
status: "ready",
createdAt: "2026-02-09T00:00:00.000Z",
updatedAt: "2026-02-09T00:00:00.000Z",
...overrides,
};
}
function makeEvent(overrides: Partial<ProviderEvent> = {}): ProviderEvent {
return {
id: "evt-1",
kind: "notification",
provider: "codex",
sessionId: "sess-1",
createdAt: "2026-02-09T00:00:01.000Z",
method: "thread/started",
...overrides,
};
}
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-local-1",
codexThreadId: null,
projectId: "project-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: makeSession(),
messages: [],
events: [],
error: null,
createdAt: "2026-02-09T00:00:00.000Z",
branch: null,
worktreePath: null,
...overrides,
};
}
function makeState(thread: Thread): AppState {
return {
projects: [
{
id: "project-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [thread],
activeThreadId: thread.id,
runtimeMode: "full-access",
diffOpen: false,
};
}
function makeTerminalStartedEvent(
overrides: Partial<TerminalStartedEvent> = {},
): TerminalStartedEvent {
return {
type: "started",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:01.000Z",
snapshot: {
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
cwd: "/tmp/project",
status: "running",
pid: 1234,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-02-09T00:00:01.000Z",
},
...overrides,
};
}
function makeTerminalActivityEvent(
overrides: Partial<TerminalActivityEvent> = {},
): TerminalActivityEvent {
return {
type: "activity",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:02.000Z",
hasRunningSubprocess: true,
...overrides,
};
}
describe("store reducer thread continuity", () => {
it("stores codexThreadId from UPDATE_SESSION", () => {
const state = makeState(
makeThread({
session: null,
}),
);
const next = reducer(state, {
type: "UPDATE_SESSION",
threadId: "thread-local-1",
session: makeSession({ threadId: "thr_123" }),
});
expect(next.threads[0]?.codexThreadId).toBe("thr_123");
});
it("toggles terminal open state per thread", () => {
const state = makeState(makeThread({ terminalOpen: false }));
const next = reducer(state, {
type: "TOGGLE_THREAD_TERMINAL",
threadId: "thread-local-1",
});
expect(next.threads[0]?.terminalOpen).toBe(true);
});
it("sets terminal open state per thread", () => {
const state = makeState(makeThread({ terminalOpen: true }));
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_OPEN",
threadId: "thread-local-1",
open: false,
});
expect(next.threads[0]?.terminalOpen).toBe(false);
});
it("sets terminal height per thread", () => {
const state = makeState(makeThread({ terminalHeight: 280 }));
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_HEIGHT",
threadId: "thread-local-1",
height: 360,
});
expect(next.threads[0]?.terminalHeight).toBe(360);
});
it("splits the active terminal into side-by-side mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("creates a new full-width terminal and switches to tab mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "NEW_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
});
it("switches the active terminal and restores its owning group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: "group-term-3",
}),
);
const next = reducer(state, {
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("supports splitting beyond two terminals in the same group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-3",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"]);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
},
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-3");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("caps split terminals at four per thread", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
activeTerminalId: "term-4",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-5",
});
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
expect(next.threads[0]?.terminalIds).toEqual([
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
"term-4",
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
});
it("caps new terminals at four per thread", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
activeTerminalId: "term-4",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-2", terminalIds: ["term-2"] },
{ id: "group-term-3", terminalIds: ["term-3"] },
{ id: "group-term-4", terminalIds: ["term-4"] },
],
activeTerminalGroupId: "group-term-4",
}),
);
const next = reducer(state, {
type: "NEW_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-5",
});
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
expect(next.threads[0]?.terminalIds).toEqual([
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
"term-4",
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-4");
});
it("closes a terminal and keeps grouped layout coherent", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
});
it("closes the final terminal and hides the drawer", () => {
const state = makeState(
makeThread({
terminalOpen: true,
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID],
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
});
expect(next.threads[0]?.terminalOpen).toBe(false);
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
]);
});
it("tracks running terminals from subprocess activity events", () => {
const state = makeState(makeThread());
const started = reducer(state, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalStartedEvent(),
});
expect(started.threads[0]?.runningTerminalIds).toEqual([]);
const active = reducer(started, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalActivityEvent(),
});
expect(active.threads[0]?.runningTerminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
const idle = reducer(active, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalActivityEvent({ hasRunningSubprocess: false }),
});
expect(idle.threads[0]?.runningTerminalIds).toEqual([]);
const exited = reducer(active, {
type: "APPLY_TERMINAL_EVENT",
event: {
type: "exited",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:05.000Z",
exitCode: 0,
exitSignal: null,
},
});
expect(exited.threads[0]?.runningTerminalIds).toEqual([]);
});
it("keeps running status when another terminal in the thread is still running", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "APPLY_TERMINAL_EVENT",
event: {
type: "exited",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:07.000Z",
exitCode: 0,
exitSignal: null,
},
});
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
});
it("backfills codexThreadId from routed provider events", () => {
const state = makeState(makeThread({ codexThreadId: null }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "thread/started",
payload: { thread: { id: "thr_backfilled" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_backfilled");
});
it("ignores events from a foreign thread within the same session", () => {
const state = makeState(makeThread({ codexThreadId: "thr_expected" }));
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/started",
threadId: "thr_unexpected",
payload: { turn: { id: "turn-1" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next).toBe(state);
});
it("rebases thread identity on thread/started during connect", () => {
const state = makeState(
makeThread({
codexThreadId: "thr_old",
session: makeSession({
status: "connecting",
threadId: "thr_old",
}),
}),
);
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "thread/started",
threadId: "thr_new",
payload: { thread: { id: "thr_new" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.codexThreadId).toBe("thr_new");
expect(next.threads[0]?.session?.threadId).toBe("thr_new");
});
it("reconciles project ids by cwd when syncing backend projects", () => {
const state: AppState = {
projects: [
{
id: "project-old-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
{
id: "project-old-b",
name: "B",
cwd: "/tmp/b",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
makeThread({
id: "thread-a",
projectId: "project-old-a",
}),
makeThread({
id: "thread-b",
projectId: "project-old-b",
}),
],
activeThreadId: "thread-b",
runtimeMode: "full-access",
diffOpen: false,
};
const next = reducer(state, {
type: "SYNC_PROJECTS",
projects: [
{
id: "project-new-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe("project-new-a");
// Preserve existing project UI preferences by cwd
expect(next.projects[0]?.expanded).toBe(false);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-a");
expect(next.threads[0]?.projectId).toBe("project-new-a");
expect(next.activeThreadId).toBe("thread-a");
});
it("treats empty scripts from sync as authoritative", () => {
const state: AppState = {
projects: [
{
id: "project-old-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: true,
scripts: [
{
id: "test",
name: "Test",
command: "bun test",
icon: "test",
runOnWorktreeCreate: false,
},
],
},
],
threads: [makeThread({ id: "thread-a", projectId: "project-old-a" })],
activeThreadId: "thread-a",
runtimeMode: "full-access",
diffOpen: false,
};
const next = reducer(state, {
type: "SYNC_PROJECTS",
projects: [
{
id: "project-new-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
});
expect(next.projects[0]?.scripts).toEqual([]);
});
it("updates project scripts", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_PROJECT_SCRIPTS",
projectId: "project-1",
scripts: [
{
id: "test",
name: "Test",
command: "bun test",
icon: "test",
runOnWorktreeCreate: false,
},
],
});
expect(next.projects[0]?.scripts).toEqual([
{
id: "test",
name: "Test",
command: "bun test",
icon: "test",
runOnWorktreeCreate: false,
},
]);
});
it("deletes a project and all of its threads", () => {
const state: AppState = {
projects: [
{
id: "project-1",
name: "One",
cwd: "/tmp/one",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
{
id: "project-2",
name: "Two",
cwd: "/tmp/two",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
makeThread({
id: "thread-a",
projectId: "project-1",
}),
makeThread({
id: "thread-b",
projectId: "project-2",
}),
],
activeThreadId: "thread-a",
runtimeMode: "full-access",
diffOpen: false,
};
const next = reducer(state, {
type: "DELETE_PROJECT",
projectId: "project-1",
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe("project-2");
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.id).toBe("thread-b");
expect(next.activeThreadId).toBe("thread-b");
});
it("marks the active thread as visited when selected", () => {
const state = makeState(
makeThread({
lastVisitedAt: "2000-01-01T00:00:00.000Z",
}),
);
const next = reducer(state, {
type: "SET_ACTIVE_THREAD",
threadId: "thread-local-1",
});
expect(next.activeThreadId).toBe("thread-local-1");
expect(next.threads[0]?.lastVisitedAt).toBeDefined();
expect(next.threads[0]?.lastVisitedAt).not.toBe("2000-01-01T00:00:00.000Z");
});
it("marks completion as seen immediately for the active thread", () => {
const state = makeState(
makeThread({
session: makeSession({
status: "running",
activeTurnId: "turn-1",
}),
lastVisitedAt: "2026-02-08T10:00:00.000Z",
}),
);
const completedAt = "2026-02-08T10:00:10.000Z";
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/completed",
turnId: "turn-1",
createdAt: completedAt,
payload: { turn: { id: "turn-1", status: "completed" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
});
});
+350 -110
View File
@@ -8,13 +8,12 @@ import {
useReducer,
} from "react";
import {
type OrchestrationReadModel,
normalizeProjectScripts,
} from "@t3tools/contracts";
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
@@ -28,10 +27,13 @@ import {
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
| { type: "ADD_PROJECT"; project: Project }
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
| { type: "SET_THREADS_HYDRATED"; hydrated: boolean }
| { type: "SYNC_PROJECTS"; projects: Project[] }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "DELETE_PROJECT"; projectId: string }
| { type: "ADD_THREAD"; thread: Thread }
| { type: "SET_ACTIVE_THREAD"; threadId: string }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
@@ -39,22 +41,41 @@ type Action =
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "TOGGLE_DIFF" }
| {
type: "APPLY_EVENT";
event: ProviderEvent;
activeAssistantItemRef: { current: string | null };
}
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| {
type: "PUSH_USER_MESSAGE";
threadId: string;
id: string;
text: string;
attachments?: ChatAttachment[];
}
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
| {
type: "SET_THREAD_BRANCH";
threadId: string;
branch: string | null;
worktreePath: string | null;
}
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
| { type: "DELETE_THREAD"; threadId: string };
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
projects: Project[];
threads: Thread[];
threadsHydrated: boolean;
activeThreadId: string | null;
runtimeMode: RuntimeMode;
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
@@ -72,10 +93,10 @@ const LEGACY_PERSISTED_STATE_KEYS = [
const initialState: AppState = {
projects: [],
threads: [],
threadsHydrated: false,
activeThreadId: null,
runtimeMode: DEFAULT_RUNTIME_MODE,
diffOpen: false,
};
const persistedExpandedProjectCwds = new Set<string>();
// ── Helpers ──────────────────────────────────────────────────────────
@@ -83,25 +104,21 @@ function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState;
const parsed = JSON.parse(raw) as {
runtimeMode?: RuntimeMode;
expandedProjectCwds?: string[];
};
persistedExpandedProjectCwds.clear();
for (const cwd of parsed.expandedProjectCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0) {
persistedExpandedProjectCwds.add(cwd);
}
}
return {
...initialState,
runtimeMode:
parsed.runtimeMode === "approval-required" || parsed.runtimeMode === "full-access"
? parsed.runtimeMode
: DEFAULT_RUNTIME_MODE,
};
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
if (!hydrated) return initialState;
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
const activeThreadId = threads.some((thread) => thread.id === hydrated.activeThreadId)
? hydrated.activeThreadId
: (threads[0]?.id ?? null);
return { ...hydrated, threads, activeThreadId, diffOpen: false };
} catch {
return initialState;
}
@@ -111,15 +128,7 @@ function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
runtimeMode: state.runtimeMode,
expandedProjectCwds: state.projects
.filter((project) => project.expanded)
.map((project) => project.cwd),
}),
);
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
@@ -136,7 +145,6 @@ function updateThread(
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
@@ -323,80 +331,108 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
});
}
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
return threads.find((t) => t.session?.sessionId === sessionId);
}
function getEventTurnId(event: ProviderEvent): string | undefined {
if (event.turnId) return event.turnId;
const payload = asObject(event.payload);
const turn = asObject(payload?.turn);
return asString(turn?.id);
}
function getEventThreadId(event: ProviderEvent): string | undefined {
if (event.threadId) return event.threadId;
const payload = asObject(event.payload);
const payloadThread = asObject(payload?.thread);
const payloadMessage = asObject(payload?.msg);
return (
asString(payload?.threadId) ??
asString(payloadThread?.id) ??
asString(payload?.conversationId) ??
asString(payload?.thread_id) ??
asString(payloadMessage?.thread_id)
);
}
function shouldIgnoreForeignThreadEvent(thread: Thread, event: ProviderEvent): boolean {
const eventThreadId = getEventThreadId(event);
if (!eventThreadId) {
return false;
}
const expectedThreadId = thread.session?.threadId ?? thread.codexThreadId;
if (!expectedThreadId || eventThreadId === expectedThreadId) {
return false;
}
// During connect, accept a thread/started notification as an identity rebind.
if (event.method === "thread/started" && thread.session?.status === "connecting") {
return false;
}
return true;
}
function durationMs(startIso: string, endIso: string): number | undefined {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
return undefined;
}
return end - start;
}
function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread> {
if (event.method === "turn/started") {
return {
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
latestTurnStartedAt: event.createdAt,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
};
}
if (event.method === "turn/completed") {
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
const startedAt =
completedTurnId && completedTurnId === thread.latestTurnId
? thread.latestTurnStartedAt
: undefined;
const elapsed =
startedAt && startedAt.length > 0 ? durationMs(startedAt, event.createdAt) : undefined;
return {
latestTurnId: completedTurnId ?? thread.latestTurnId,
latestTurnCompletedAt: event.createdAt,
latestTurnDurationMs: elapsed,
};
}
return {};
}
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "SYNC_SERVER_READ_MODEL": {
const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
const projects = action.readModel.projects.map((project) => {
const existing = state.projects.find((entry) => entry.id === project.id);
return {
id: project.id,
name: project.name,
cwd: project.cwd,
model: resolveModelSlug(project.model),
expanded:
existing?.expanded ??
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.cwd)
: true),
scripts: existing?.scripts ?? [],
};
});
const threads = action.readModel.threads.map((thread) => {
const existing = existingThreadById.get(thread.id);
return normalizeThreadTerminals({
id: thread.id,
codexThreadId: thread.session?.threadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
terminalOpen: existing?.terminalOpen ?? false,
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: existing?.runningTerminalIds ?? [],
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: existing?.terminalGroups ?? [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
],
activeTerminalGroupId: existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: thread.session
? {
sessionId: thread.session.sessionId,
provider: thread.session.provider,
status: thread.session.status,
threadId: thread.session.threadId,
activeTurnId: thread.session.activeTurnId ?? undefined,
createdAt: thread.session.createdAt,
updatedAt: thread.session.updatedAt,
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
}
: null,
messages: thread.messages.map((message) => ({ ...message })),
error: thread.error,
createdAt: thread.createdAt,
latestTurnId: thread.latestTurnId ?? undefined,
latestTurnStartedAt: thread.latestTurnStartedAt ?? undefined,
latestTurnCompletedAt: thread.latestTurnCompletedAt ?? undefined,
latestTurnDurationMs: thread.latestTurnDurationMs ?? undefined,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
...summary,
files: summary.files.map((file) => ({ ...file })),
})),
});
});
case "ADD_PROJECT":
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
return state;
}
return {
...state,
projects,
threads,
threadsHydrated: true,
projects: [
...state.projects,
{
...action.project,
model: resolveModelSlug(action.project.model),
scripts: normalizeProjectScripts(action.project.scripts),
},
],
};
}
case "SET_PROJECT_SCRIPTS":
return {
@@ -408,14 +444,49 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "SET_THREADS_HYDRATED":
if (state.threadsHydrated === action.hydrated) {
return state;
}
case "SYNC_PROJECTS": {
const previousByCwd = new Map(
state.projects.map((project) => [project.cwd, project] as const),
);
const nextProjects = action.projects.map((project) => {
const previous = previousByCwd.get(project.cwd);
const scripts = normalizeProjectScripts(project.scripts);
return {
...project,
model: resolveModelSlug(previous?.model ?? project.model),
expanded: previous?.expanded ?? project.expanded,
scripts,
};
});
const previousProjectById = new Map(
state.projects.map((project) => [project.id, project] as const),
);
const nextProjectIdByCwd = new Map(
nextProjects.map((project) => [project.cwd, project.id] as const),
);
const nextThreads = state.threads
.map((thread) => {
const previousProject = previousProjectById.get(thread.projectId);
if (!previousProject) return null;
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
if (!mappedProjectId) return null;
return normalizeThreadTerminals({
...thread,
projectId: mappedProjectId,
});
})
.filter((thread): thread is Thread => thread !== null);
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
? state.activeThreadId
: (nextThreads[0]?.id ?? null);
return {
...state,
threadsHydrated: action.hydrated,
projects: nextProjects,
threads: nextThreads,
activeThreadId,
};
}
case "TOGGLE_PROJECT":
return {
@@ -425,6 +496,50 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "DELETE_PROJECT": {
const projects = state.projects.filter((project) => project.id !== action.projectId);
if (projects.length === state.projects.length) {
return state;
}
const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
const activeThreadId = threads.some((thread) => thread.id === state.activeThreadId)
? state.activeThreadId
: (threads[0]?.id ?? null);
return {
...state,
projects,
threads,
activeThreadId,
};
}
case "ADD_THREAD": {
const nextThread = normalizeThreadTerminals({
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
});
return {
...state,
threads: [...state.threads, nextThread],
activeThreadId: action.thread.id,
};
}
case "SET_ACTIVE_THREAD": {
const visitedAt = new Date().toISOString();
return {
...state,
activeThreadId: action.threadId,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
lastVisitedAt: visitedAt,
})),
};
}
case "TOGGLE_THREAD_TERMINAL":
return {
...state,
@@ -592,6 +707,106 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
case "APPLY_TERMINAL_EVENT":
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
return state;
}
return {
...state,
threads: updateThread(state.threads, action.event.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
if (action.event.type === "started" || action.event.type === "restarted") {
runningTerminalIdSet.delete(action.event.terminalId);
} else if (action.event.type === "activity") {
if (action.event.hasRunningSubprocess) {
runningTerminalIdSet.add(action.event.terminalId);
} else {
runningTerminalIdSet.delete(action.event.terminalId);
}
} else if (action.event.type === "exited" || action.event.type === "error") {
runningTerminalIdSet.delete(action.event.terminalId);
}
return normalizeThreadTerminals({
...normalizedThread,
runningTerminalIds: [...runningTerminalIdSet],
});
}),
};
case "APPLY_EVENT": {
const { event, activeAssistantItemRef } = action;
const target = findThreadBySessionId(state.threads, event.sessionId);
if (!target) return state;
if (shouldIgnoreForeignThreadEvent(target, event)) return state;
return {
...state,
threads: updateThread(state.threads, target.id, (t) => ({
...t,
...(() => {
const eventThreadId = getEventThreadId(event);
const shouldRebindIdentity =
event.method === "thread/started" && t.session?.status === "connecting";
return {
codexThreadId: shouldRebindIdentity
? (eventThreadId ?? t.codexThreadId)
: (t.codexThreadId ?? eventThreadId ?? null),
error: event.kind === "error" && event.message ? event.message : t.error,
};
})(),
session: t.session ? evolveSession(t.session, event) : t.session,
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
events: [event, ...t.events],
...updateTurnFields(t, event),
...(event.method === "turn/completed" && t.id === state.activeThreadId
? { lastVisitedAt: event.createdAt }
: {}),
})),
};
}
case "UPDATE_SESSION":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
session: action.session,
codexThreadId: action.session.threadId ?? t.codexThreadId,
events: [],
error: null,
latestTurnId: undefined,
latestTurnStartedAt: undefined,
latestTurnCompletedAt: undefined,
latestTurnDurationMs: undefined,
})),
};
case "PUSH_USER_MESSAGE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
messages: [
...t.messages,
{
id: action.id,
role: "user" as const,
text: action.text,
...(action.attachments && action.attachments.length > 0
? { attachments: action.attachments }
: {}),
createdAt: new Date().toISOString(),
streaming: false,
},
],
})),
};
case "SET_ERROR":
return {
...state,
@@ -601,6 +816,24 @@ export function reducer(state: AppState, action: Action): AppState {
})),
};
case "SET_THREAD_TITLE":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
title: action.title,
})),
};
case "SET_THREAD_MODEL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
model: resolveModelSlug(action.model),
})),
};
case "SET_THREAD_BRANCH": {
return {
...state,
@@ -625,6 +858,13 @@ export function reducer(state: AppState, action: Action): AppState {
runtimeMode: action.mode,
};
case "DELETE_THREAD": {
const threads = state.threads.filter((t) => t.id !== action.threadId);
const activeThreadId =
state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
return { ...state, threads, activeThreadId };
}
default:
return state;
}
-41
View File
@@ -1,41 +0,0 @@
import { DEFAULT_MODEL } from "./model-logic";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
interface CreateThreadOptions {
branch?: string | null;
createdAt?: string;
model?: string;
title?: string;
worktreePath?: string | null;
}
export function createThread(projectId: string, options: CreateThreadOptions = {}): Thread {
const createdAt = options.createdAt ?? new Date().toISOString();
return {
id: crypto.randomUUID(),
codexThreadId: null,
projectId,
title: options.title ?? "New thread",
model: options.model ?? DEFAULT_MODEL,
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: [],
turnDiffSummaries: [],
error: null,
createdAt,
branch: options.branch ?? null,
worktreePath: options.worktreePath ?? null,
};
}
-17
View File
@@ -1,17 +0,0 @@
import { describe, expect, it } from "vitest";
import { truncateTitle } from "./truncateTitle";
describe("truncateTitle", () => {
it("trims surrounding whitespace", () => {
expect(truncateTitle(" hello world ")).toBe("hello world");
});
it("returns trimmed text when within max length", () => {
expect(truncateTitle("alpha", 10)).toBe("alpha");
});
it("appends ellipsis when text exceeds max length", () => {
expect(truncateTitle("abcdefghij", 5)).toBe("abcde...");
});
});
-7
View File
@@ -1,7 +0,0 @@
export function truncateTitle(text: string, maxLength = 50): string {
const trimmed = text.trim();
if (trimmed.length <= maxLength) {
return trimmed;
}
return `${trimmed.slice(0, maxLength)}...`;
}
+2 -17
View File
@@ -1,5 +1,6 @@
import type {
ProjectScript as ContractProjectScript,
ProviderEvent,
ProviderSession,
} from "@t3tools/contracts";
@@ -36,22 +37,6 @@ export interface ChatMessage {
streaming: boolean;
}
export interface TurnDiffFileChange {
path: string;
kind?: string | undefined;
additions?: number | undefined;
deletions?: number | undefined;
}
export interface TurnDiffSummary {
turnId: string;
completedAt: string;
status?: string | undefined;
files: TurnDiffFileChange[];
assistantMessageId?: string | undefined;
checkpointTurnCount?: number | undefined;
}
export interface Project {
id: string;
name: string;
@@ -76,6 +61,7 @@ export interface Thread {
activeTerminalGroupId: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
error: string | null;
createdAt: string;
latestTurnId?: string | undefined;
@@ -85,5 +71,4 @@ export interface Thread {
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
turnDiffSummaries: TurnDiffSummary[];
}
-1
View File
@@ -8,7 +8,6 @@ interface DesktopBridge {
confirm: (message: string) => Promise<boolean>;
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
openExternal: (url: string) => Promise<boolean>;
onMenuAction: (listener: (action: string) => void) => () => void;
}
declare global {
-1
View File
@@ -1 +0,0 @@
import "@pierre/diffs/worker/worker.js";
+1 -1
View File
@@ -24,7 +24,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
turnDiffSummaries: [],
events: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
branch: null,
+4 -34
View File
@@ -1,13 +1,4 @@
import {
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
type NativeApi,
WS_CHANNELS,
WS_METHODS,
type OrchestrationEvent,
type OrchestrationReadModel,
type WsWelcomePayload,
} from "@t3tools/contracts";
import { type NativeApi, WS_CHANNELS, WS_METHODS, type WsWelcomePayload } from "@t3tools/contracts";
import { showContextMenuFallback } from "./contextMenuFallback";
import { WsTransport } from "./wsTransport";
@@ -99,10 +90,9 @@ export function createWsNativeApi(): NativeApi {
interruptTurn: (input) => transport.request(WS_METHODS.providersInterruptTurn, input),
respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input),
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
listCheckpoints: (input) => transport.request(WS_METHODS.providersListCheckpoints, input),
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, input),
revertToCheckpoint: (input) =>
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
listSessions: () => transport.request(WS_METHODS.providersListSessions),
onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
},
projects: {
list: () => transport.request(WS_METHODS.projectsList),
@@ -155,26 +145,6 @@ export function createWsNativeApi(): NativeApi {
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
},
orchestration: {
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
dispatchCommand: (command) =>
transport.request(ORCHESTRATION_WS_METHODS.dispatchCommand, command),
replayEvents: (fromSequenceExclusive) =>
transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }),
onReadModel: (callback) =>
transport.subscribe(
ORCHESTRATION_WS_CHANNELS.readModel,
(data: unknown) => {
const payload = data as { snapshot: OrchestrationReadModel };
callback(payload.snapshot);
},
),
onDomainEvent: (callback) =>
transport.subscribe(
ORCHESTRATION_WS_CHANNELS.domainEvent,
callback as (data: unknown) => void,
),
},
};
instance = { api, transport };
-3
View File
@@ -37,9 +37,6 @@ export class WsTransport {
}
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
if (typeof method !== "string" || method.length === 0) {
throw new Error("Request method is required");
}
const id = String(this.nextId++);
const message: WsRequest = { id, method, ...(params !== undefined ? { params } : {}) };
-5
View File
@@ -1,13 +1,11 @@
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { tanstackRouter } from "@tanstack/router-plugin/vite";
import { defineConfig } from "vite";
const port = Number(process.env.PORT ?? 5173);
export default defineConfig({
plugins: [
tanstackRouter(),
react({
babel: {
plugins: [["babel-plugin-react-compiler", { target: "19" }]],
@@ -15,9 +13,6 @@ export default defineConfig({
}),
tailwindcss(),
],
optimizeDeps: {
include: ["@pierre/diffs", "@pierre/diffs/react", "@pierre/diffs/worker/worker.js"],
},
define: {
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 MiB

-4
View File
@@ -1,4 +0,0 @@
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 10C0 4.47715 4.47715 0 10 0H118C123.523 0 128 4.47715 128 10V118C128 123.523 123.523 128 118 128H10C4.47715 128 0 123.523 0 118V10Z" fill="black"/>
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="white"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more