Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d3263d69d |
No files matched your search
@@ -10,4 +10,3 @@ packages/*/dist
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,2 +1 @@
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
@@ -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",
|
||||
|
||||
|
Before Width: | Height: | Size: 279 KiB |
|
Before Width: | Height: | Size: 313 KiB |
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -17,9 +17,6 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/core": "workspace:*",
|
||||
"@t3tools/infra-sqlite": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
|
||||
@@ -163,14 +163,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath?.trim() || "codex";
|
||||
const codexHomePath = input.codexHomePath?.trim();
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
EffectFanout,
|
||||
OrchestrationEngine,
|
||||
QueueProjector,
|
||||
type AppViewState,
|
||||
} from "@t3tools/core";
|
||||
import { createSqliteStores } from "@t3tools/infra-sqlite";
|
||||
|
||||
import type { ProviderManager } from "./providerManager";
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
export class CoreRuntime {
|
||||
private readonly fanout = new EffectFanout();
|
||||
private readonly stores;
|
||||
private readonly projector: QueueProjector;
|
||||
private readonly engine: OrchestrationEngine;
|
||||
|
||||
constructor(dbDir: string) {
|
||||
const dbPath = path.join(dbDir, "event-store.sqlite");
|
||||
this.stores = createSqliteStores(dbPath);
|
||||
this.projector = new QueueProjector(this.stores.projectionStore, this.fanout);
|
||||
this.engine = new OrchestrationEngine(
|
||||
this.stores.eventStore,
|
||||
this.stores.projectionStore,
|
||||
this.projector,
|
||||
);
|
||||
}
|
||||
|
||||
async start(cwd: string, projectName: string): Promise<void> {
|
||||
await this.engine.start();
|
||||
await this.engine.execute({
|
||||
id: crypto.randomUUID(),
|
||||
type: "app.bootstrap",
|
||||
issuedAt: nowIso(),
|
||||
payload: { cwd, projectName },
|
||||
});
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.engine.stop();
|
||||
this.stores.db.close();
|
||||
}
|
||||
|
||||
async state(): Promise<AppViewState> {
|
||||
return this.engine.currentState();
|
||||
}
|
||||
|
||||
async dispatch(command: Parameters<OrchestrationEngine["execute"]>[0]): Promise<AppViewState> {
|
||||
return this.engine.execute(command);
|
||||
}
|
||||
|
||||
subscribe() {
|
||||
return this.fanout.subscribe();
|
||||
}
|
||||
|
||||
bindProviderEvents(providerManager: ProviderManager): void {
|
||||
providerManager.on("event", (event: ProviderEvent) => {
|
||||
void this.ingestProviderEvent(event);
|
||||
});
|
||||
}
|
||||
|
||||
async bindProviderSession(threadId: string, session: ProviderSession): Promise<void> {
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.updateProviderSession",
|
||||
issuedAt: nowIso(),
|
||||
payload: { threadId, session },
|
||||
});
|
||||
}
|
||||
|
||||
async clearProviderSession(threadId: string): Promise<void> {
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.updateProviderSession",
|
||||
issuedAt: nowIso(),
|
||||
payload: { threadId, session: null },
|
||||
});
|
||||
}
|
||||
|
||||
async ingestProviderEvent(event: ProviderEvent): Promise<void> {
|
||||
const state = await this.state();
|
||||
const target = state.threads.find((thread) => thread.session?.sessionId === event.sessionId);
|
||||
if (!target) return;
|
||||
await this.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.recordProviderEvent",
|
||||
issuedAt: event.createdAt,
|
||||
payload: {
|
||||
threadId: target.id,
|
||||
event,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,6 @@ async function main() {
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
stateDir,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
|
||||
@@ -296,82 +296,6 @@ describe("ProviderManager", () => {
|
||||
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 }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
...(event.payload !== undefined ? { payload: event.payload } : {}),
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const internals = manager as unknown as {
|
||||
onCodexEvent: (event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => 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",
|
||||
});
|
||||
|
||||
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?.payload).toEqual({
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("lazily initializes filesystem checkpoints before diffing when cache is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
|
||||
@@ -477,19 +477,11 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
|
||||
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);
|
||||
})
|
||||
.catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -504,29 +496,12 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
this.emitCheckpointCaptured(event.sessionId, snapshot.threadId, snapshot.turns.length);
|
||||
}).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): void {
|
||||
this.emit("event", {
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/captured",
|
||||
threadId,
|
||||
payload: {
|
||||
threadId,
|
||||
turnCount,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private emitFilesystemCheckpointError(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
|
||||
@@ -3,11 +3,9 @@ import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
EDITORS,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
@@ -35,7 +33,6 @@ import {
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { CoreRuntime } from "./coreRuntime";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -60,7 +57,6 @@ export interface ServerOptions {
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
stateDir?: string | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
authToken?: string | undefined;
|
||||
@@ -83,7 +79,6 @@ export function createServer(options: ServerOptions) {
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
stateDir,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
authToken,
|
||||
@@ -93,12 +88,8 @@ export function createServer(options: ServerOptions) {
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const runtimeStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
|
||||
const coreRuntime = new CoreRuntime(runtimeStateDir);
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
||||
@@ -112,7 +103,13 @@ export function createServer(options: ServerOptions) {
|
||||
});
|
||||
}
|
||||
|
||||
function broadcastPush(push: WsPush): void {
|
||||
// Forward provider events to all connected WebSocket clients
|
||||
providerManager.on("event", (event) => {
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.providerEvent,
|
||||
data: event,
|
||||
};
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
@@ -122,31 +119,25 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
}
|
||||
});
|
||||
|
||||
const onTerminalEvent = (event: TerminalEvent) => {
|
||||
broadcastPush({
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.terminalEvent,
|
||||
data: event,
|
||||
});
|
||||
if (event.type === "activity" || event.type === "exited" || event.type === "error") {
|
||||
void coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.setTerminalActivity",
|
||||
issuedAt: event.createdAt,
|
||||
payload: {
|
||||
threadId: event.threadId,
|
||||
terminalId: event.terminalId,
|
||||
running: event.type === "activity" ? event.hasRunningSubprocess : false,
|
||||
},
|
||||
});
|
||||
};
|
||||
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);
|
||||
};
|
||||
terminalManager.on("event", onTerminalEvent);
|
||||
coreRuntime.bindProviderEvents(providerManager);
|
||||
let stateStreamStopped = false;
|
||||
let stateStreamTask: Promise<void> | null = null;
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
@@ -244,6 +235,10 @@ export function createServer(options: ServerOptions) {
|
||||
wss.on("connection", (ws) => {
|
||||
clients.add(ws);
|
||||
|
||||
// Send welcome message with project info
|
||||
const segments = cwd.split(/[/\\]/).filter(Boolean);
|
||||
const projectName = segments[segments.length - 1] ?? "project";
|
||||
|
||||
const welcome: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
@@ -294,48 +289,12 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
|
||||
async function routeRequest(request: WsRequest): Promise<unknown> {
|
||||
const requestNow = new Date().toISOString();
|
||||
const paramsObj = (request.params ?? {}) as Record<string, unknown>;
|
||||
const state = await coreRuntime.state();
|
||||
const findThreadBySessionId = (sessionId: string | undefined) =>
|
||||
sessionId
|
||||
? state.threads.find((thread) => thread.session?.sessionId === sessionId)
|
||||
: undefined;
|
||||
|
||||
switch (request.method) {
|
||||
case WS_METHODS.providersStartSession: {
|
||||
const session = await providerManager.startSession(request.params as never);
|
||||
const uiThreadId =
|
||||
typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
|
||||
if (uiThreadId) {
|
||||
await coreRuntime.bindProviderSession(uiThreadId, session);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
case WS_METHODS.providersStartSession:
|
||||
return providerManager.startSession(request.params as never);
|
||||
|
||||
case WS_METHODS.providersSendTurn: {
|
||||
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
|
||||
const uiThreadId =
|
||||
typeof paramsObj.uiThreadId === "string" ? paramsObj.uiThreadId : undefined;
|
||||
const targetThread = uiThreadId
|
||||
? state.threads.find((thread) => thread.id === uiThreadId)
|
||||
: findThreadBySessionId(sessionId);
|
||||
const inputText = typeof paramsObj.input === "string" ? paramsObj.input : undefined;
|
||||
if (targetThread && inputText && inputText.trim().length > 0) {
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.addUserMessage",
|
||||
issuedAt: requestNow,
|
||||
payload: {
|
||||
threadId: targetThread.id,
|
||||
messageId: crypto.randomUUID(),
|
||||
text: inputText,
|
||||
createdAt: requestNow,
|
||||
},
|
||||
});
|
||||
}
|
||||
case WS_METHODS.providersSendTurn:
|
||||
return providerManager.sendTurn(request.params as never);
|
||||
}
|
||||
|
||||
case WS_METHODS.providersInterruptTurn:
|
||||
return providerManager.interruptTurn(request.params as never);
|
||||
@@ -344,12 +303,7 @@ export function createServer(options: ServerOptions) {
|
||||
return providerManager.respondToRequest(request.params as never);
|
||||
|
||||
case WS_METHODS.providersStopSession: {
|
||||
const sessionId = typeof paramsObj.sessionId === "string" ? paramsObj.sessionId : undefined;
|
||||
const boundThread = findThreadBySessionId(sessionId);
|
||||
providerManager.stopSession(request.params as never);
|
||||
if (boundThread) {
|
||||
await coreRuntime.clearProviderSession(boundThread.id);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -368,49 +322,17 @@ export function createServer(options: ServerOptions) {
|
||||
case WS_METHODS.projectsList:
|
||||
return projectRegistry.list();
|
||||
|
||||
case WS_METHODS.projectsAdd: {
|
||||
const result = projectRegistry.add(request.params as never);
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.add",
|
||||
issuedAt: requestNow,
|
||||
payload: {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
scripts: result.project.scripts,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
}
|
||||
case WS_METHODS.projectsAdd:
|
||||
return projectRegistry.add(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsRemove: {
|
||||
const projectId = typeof paramsObj.id === "string" ? paramsObj.id : undefined;
|
||||
if (projectId) {
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.remove",
|
||||
issuedAt: requestNow,
|
||||
payload: { id: projectId },
|
||||
});
|
||||
}
|
||||
case WS_METHODS.projectsRemove:
|
||||
projectRegistry.remove(request.params as never);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.projectsSearchEntries:
|
||||
return searchWorkspaceEntries(request.params as never);
|
||||
case WS_METHODS.projectsUpdateScripts: {
|
||||
const result = projectRegistry.updateScripts(request.params as never);
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "project.updateScripts",
|
||||
issuedAt: requestNow,
|
||||
payload: { id: result.project.id, scripts: result.project.scripts },
|
||||
});
|
||||
return result;
|
||||
}
|
||||
case WS_METHODS.projectsUpdateScripts:
|
||||
return projectRegistry.updateScripts(request.params as never);
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
@@ -516,61 +438,6 @@ export function createServer(options: ServerOptions) {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.stateGetSnapshot:
|
||||
return coreRuntime.state();
|
||||
|
||||
case WS_METHODS.stateCreateThread: {
|
||||
const params = request.params as {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.create",
|
||||
issuedAt: requestNow,
|
||||
payload: params,
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
case WS_METHODS.stateDeleteThread: {
|
||||
const params = request.params as { id: string };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.delete",
|
||||
issuedAt: requestNow,
|
||||
payload: params,
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
case WS_METHODS.stateMarkThreadVisited: {
|
||||
const params = request.params as { threadId: string; visitedAt?: string };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "thread.markVisited",
|
||||
issuedAt: requestNow,
|
||||
payload: { threadId: params.threadId, visitedAt: params.visitedAt ?? requestNow },
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.stateSetRuntimeMode: {
|
||||
const params = request.params as { mode: "approval-required" | "full-access" };
|
||||
await coreRuntime.dispatch({
|
||||
id: crypto.randomUUID(),
|
||||
type: "runtime.setMode",
|
||||
issuedAt: requestNow,
|
||||
payload: { mode: params.mode },
|
||||
});
|
||||
return coreRuntime.state();
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
}
|
||||
@@ -585,26 +452,7 @@ export function createServer(options: ServerOptions) {
|
||||
httpServer.once("error", onError);
|
||||
const onListening = () => {
|
||||
httpServer.off("error", onError);
|
||||
void (async () => {
|
||||
try {
|
||||
await coreRuntime.start(cwd, projectName);
|
||||
stateStreamStopped = false;
|
||||
stateStreamTask = (async () => {
|
||||
const iterable = await coreRuntime.subscribe();
|
||||
for await (const update of iterable) {
|
||||
if (stateStreamStopped) break;
|
||||
broadcastPush({
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.stateUpdated,
|
||||
data: update.state,
|
||||
});
|
||||
}
|
||||
})();
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error as Error);
|
||||
}
|
||||
})();
|
||||
resolve();
|
||||
};
|
||||
if (host) {
|
||||
httpServer.listen(port, host, onListening);
|
||||
@@ -615,7 +463,6 @@ export function createServer(options: ServerOptions) {
|
||||
}
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
stateStreamStopped = true;
|
||||
terminalManager.off("event", onTerminalEvent);
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
@@ -655,10 +502,6 @@ export function createServer(options: ServerOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
if (stateStreamTask) {
|
||||
await Promise.race([stateStreamTask, Promise.resolve()]);
|
||||
}
|
||||
await coreRuntime.stop();
|
||||
await Promise.all([closeWebSocketServer, closeHttpServer]);
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 279 KiB |
@@ -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 |
@@ -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;
|
||||
}
|
||||
@@ -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})`;
|
||||
@@ -28,16 +28,13 @@ import {
|
||||
} from "react";
|
||||
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||
import { useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { buildBootstrapInput } from "../historyBootstrap";
|
||||
import {
|
||||
type ComposerTriggerKind,
|
||||
@@ -53,9 +50,9 @@ import {
|
||||
resolveModelSlug,
|
||||
} from "../model-logic";
|
||||
import {
|
||||
countDiffStat,
|
||||
derivePendingApprovals,
|
||||
derivePhase,
|
||||
deriveTurnDiffFilesFromUnifiedDiff,
|
||||
deriveTimelineEntries,
|
||||
type TurnDiffSummary,
|
||||
type PendingApproval,
|
||||
@@ -71,7 +68,6 @@ import {
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatImageAttachment,
|
||||
type TurnDiffFileChange,
|
||||
} from "../types";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -186,33 +182,6 @@ interface ExpandedImagePreview {
|
||||
name: string;
|
||||
}
|
||||
|
||||
type TurnCheckpointFilesState =
|
||||
| {
|
||||
status: "pending" | "loading";
|
||||
files: TurnDiffFileChange[];
|
||||
errorMessage?: undefined;
|
||||
}
|
||||
| {
|
||||
status: "error";
|
||||
files: TurnDiffFileChange[];
|
||||
errorMessage: string;
|
||||
}
|
||||
| {
|
||||
status: "ready";
|
||||
files: TurnDiffFileChange[];
|
||||
errorMessage?: undefined;
|
||||
};
|
||||
|
||||
function checkpointErrorMessage(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 "Checkpoint diff is unavailable.";
|
||||
}
|
||||
|
||||
type ComposerCommandItem =
|
||||
| {
|
||||
id: string;
|
||||
@@ -377,11 +346,8 @@ interface ChatViewProps {
|
||||
|
||||
export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const { state, dispatch } = useStore();
|
||||
const navigate = useNavigate();
|
||||
const rawSearch = useSearch({ strict: false });
|
||||
const api = useNativeApi();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const queryClient = useQueryClient();
|
||||
const createWorktreeMutation = useMutation(
|
||||
gitCreateWorktreeMutationOptions({ api, queryClient }),
|
||||
@@ -414,14 +380,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const dragDepthRef = useRef(0);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
const checkpointHydrationSessionRequestRef = useRef(new Set<string>());
|
||||
const checkpointTurnCountSyncFingerprintRef = useRef(new Map<string, string>());
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === threadId);
|
||||
const diffSearch = useMemo(
|
||||
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
|
||||
[rawSearch],
|
||||
);
|
||||
const diffOpen = diffSearch.diff === "1";
|
||||
const activeThreadId = activeThread?.id ?? null;
|
||||
const activeSessionId = activeThread?.session?.sessionId ?? null;
|
||||
const activeThreadRuntimeId =
|
||||
@@ -469,69 +429,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
return byMessageId;
|
||||
}, [turnDiffSummaries]);
|
||||
const checkpointDiffInputsByTurn = useMemo(
|
||||
() =>
|
||||
turnDiffSummaries
|
||||
.filter((summary) => summary.assistantMessageId)
|
||||
.map((summary) => {
|
||||
const checkpointTurnCount =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
return {
|
||||
turnId: summary.turnId,
|
||||
checkpointTurnCount:
|
||||
typeof checkpointTurnCount === "number" ? checkpointTurnCount : null,
|
||||
};
|
||||
}),
|
||||
[inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
|
||||
);
|
||||
const checkpointDiffQueriesByTurn = useQueries({
|
||||
queries: checkpointDiffInputsByTurn.map((input) =>
|
||||
checkpointDiffQueryOptions(api, {
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount:
|
||||
typeof input.checkpointTurnCount === "number"
|
||||
? Math.max(0, input.checkpointTurnCount - 1)
|
||||
: null,
|
||||
toTurnCount: input.checkpointTurnCount,
|
||||
cacheScope: `turn:${input.turnId}`,
|
||||
}),
|
||||
),
|
||||
});
|
||||
const turnCheckpointFilesByTurnId = useMemo(() => {
|
||||
const byTurnId = new Map<string, TurnCheckpointFilesState>();
|
||||
for (let index = 0; index < checkpointDiffInputsByTurn.length; index += 1) {
|
||||
const input = checkpointDiffInputsByTurn[index];
|
||||
const query = checkpointDiffQueriesByTurn[index];
|
||||
if (!input || !query) continue;
|
||||
|
||||
if (!activeSessionId || typeof input.checkpointTurnCount !== "number") {
|
||||
byTurnId.set(input.turnId, { status: "pending", files: [] });
|
||||
continue;
|
||||
}
|
||||
|
||||
const diff = query.data?.diff;
|
||||
if (typeof diff === "string") {
|
||||
byTurnId.set(input.turnId, {
|
||||
status: "ready",
|
||||
files: deriveTurnDiffFilesFromUnifiedDiff(diff),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (query.isError) {
|
||||
byTurnId.set(input.turnId, {
|
||||
status: "error",
|
||||
files: [],
|
||||
errorMessage: checkpointErrorMessage(query.error),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
byTurnId.set(input.turnId, { status: "loading", files: [] });
|
||||
}
|
||||
return byTurnId;
|
||||
}, [activeSessionId, checkpointDiffInputsByTurn, checkpointDiffQueriesByTurn]);
|
||||
const revertTurnCountByUserMessageId = useMemo(() => {
|
||||
const byUserMessageId = new Map<string, number>();
|
||||
for (let index = 0; index < timelineEntries.length; index += 1) {
|
||||
@@ -595,6 +492,68 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
}, [activeThreadId, dispatch, inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
|
||||
|
||||
const checkpointDiffHydrationTargets = useMemo(() => {
|
||||
if (!api || !activeThreadId || !activeSessionId || turnDiffSummaries.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return turnDiffSummaries.flatMap((summary) => {
|
||||
const turnCount = inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (summary.checkpointDiffLoaded || typeof turnCount !== "number") {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
turnId: summary.turnId,
|
||||
fromTurnCount: Math.max(0, turnCount - 1),
|
||||
toTurnCount: turnCount,
|
||||
},
|
||||
];
|
||||
});
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeThreadId,
|
||||
api,
|
||||
inferredCheckpointTurnCountByTurnId,
|
||||
turnDiffSummaries,
|
||||
]);
|
||||
|
||||
const checkpointDiffHydrationQueries = useQueries({
|
||||
queries: checkpointDiffHydrationTargets.map((target) =>
|
||||
checkpointDiffQueryOptions(api, {
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount: target.fromTurnCount,
|
||||
toTurnCount: target.toTurnCount,
|
||||
cacheScope: `turn:${target.turnId}`,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || checkpointDiffHydrationTargets.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointDiffByTurnId: Record<string, string> = {};
|
||||
for (let index = 0; index < checkpointDiffHydrationTargets.length; index += 1) {
|
||||
const target = checkpointDiffHydrationTargets[index];
|
||||
const query = checkpointDiffHydrationQueries[index];
|
||||
const diff = query?.data?.diff;
|
||||
if (!target || !diff) {
|
||||
continue;
|
||||
}
|
||||
checkpointDiffByTurnId[target.turnId] = diff;
|
||||
}
|
||||
if (Object.keys(checkpointDiffByTurnId).length === 0) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: activeThreadId,
|
||||
checkpointDiffByTurnId,
|
||||
});
|
||||
}, [activeThreadId, checkpointDiffHydrationQueries, checkpointDiffHydrationTargets, dispatch]);
|
||||
|
||||
const completionSummary = useMemo(() => {
|
||||
if (!activeThread?.latestTurnStartedAt) return null;
|
||||
if (!activeThread.latestTurnCompletedAt) return null;
|
||||
@@ -653,8 +612,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const runtimeApprovalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
|
||||
const runtimeSandboxMode =
|
||||
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
|
||||
const codexBinaryPath = appSettings.codexBinaryPath.trim();
|
||||
const codexHomePath = appSettings.codexHomePath.trim();
|
||||
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
||||
const composerTrigger = useMemo(
|
||||
() => detectComposerTrigger(prompt, composerCursor),
|
||||
@@ -1074,7 +1031,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
dispatch({ type: "SET_RUNTIME_MODE", mode });
|
||||
scheduleComposerFocus();
|
||||
if (!api) return;
|
||||
await api.state.setRuntimeMode({ mode });
|
||||
|
||||
const sessionIds = state.threads
|
||||
.map((t) => t.session)
|
||||
@@ -1451,53 +1407,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
focusComposer();
|
||||
};
|
||||
|
||||
const syncCheckpointTurnCounts = useCallback(
|
||||
async (input: {
|
||||
threadId: string;
|
||||
sessionId: string;
|
||||
threadRuntimeId: string | null;
|
||||
}): Promise<void> => {
|
||||
if (!api || turnDiffSummaries.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const turnIds = turnDiffSummaries.map((summary) => summary.turnId);
|
||||
if (turnIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const syncKey = `${input.threadId}:${input.sessionId}:${input.threadRuntimeId ?? "none"}`;
|
||||
const turnFingerprint = turnIds.join(",");
|
||||
if (checkpointTurnCountSyncFingerprintRef.current.get(syncKey) === turnFingerprint) {
|
||||
return;
|
||||
}
|
||||
checkpointTurnCountSyncFingerprintRef.current.set(syncKey, turnFingerprint);
|
||||
|
||||
try {
|
||||
const result = await api.providers.listCheckpoints({
|
||||
sessionId: input.sessionId,
|
||||
});
|
||||
const turnIdSet = new Set(turnIds);
|
||||
const checkpointTurnCountByTurnId = Object.fromEntries(
|
||||
result.checkpoints
|
||||
.filter((checkpoint) => checkpoint.turnCount > 0 && turnIdSet.has(checkpoint.id))
|
||||
.map((checkpoint) => [checkpoint.id, checkpoint.turnCount] as const),
|
||||
);
|
||||
if (Object.keys(checkpointTurnCountByTurnId).length === 0) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
|
||||
threadId: input.threadId,
|
||||
checkpointTurnCountByTurnId,
|
||||
});
|
||||
} catch {
|
||||
checkpointTurnCountSyncFingerprintRef.current.delete(syncKey);
|
||||
}
|
||||
},
|
||||
[api, dispatch, turnDiffSummaries],
|
||||
);
|
||||
|
||||
const ensureSession = useCallback(
|
||||
async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
@@ -1509,11 +1418,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: sessionThreadId === activeThread.codexThreadId
|
||||
? "resumed"
|
||||
: "fallback_new";
|
||||
await syncCheckpointTurnCounts({
|
||||
threadId: activeThread.id,
|
||||
sessionId: activeThread.session.sessionId,
|
||||
threadRuntimeId: sessionThreadId,
|
||||
});
|
||||
return {
|
||||
sessionId: activeThread.session.sessionId,
|
||||
resolvedThreadId: sessionThreadId,
|
||||
@@ -1525,13 +1429,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const session = await api.providers.startSession({
|
||||
uiThreadId: activeThread.id,
|
||||
provider: "codex",
|
||||
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
|
||||
model: selectedModel || undefined,
|
||||
resumeThreadId: priorCodexThreadId ?? undefined,
|
||||
...(codexBinaryPath.length > 0 ? { codexBinaryPath } : {}),
|
||||
...(codexHomePath.length > 0 ? { codexHomePath } : {}),
|
||||
approvalPolicy: runtimeApprovalPolicy,
|
||||
sandboxMode: runtimeSandboxMode,
|
||||
});
|
||||
@@ -1547,11 +1448,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: resolvedThreadId === priorCodexThreadId
|
||||
? "resumed"
|
||||
: "fallback_new";
|
||||
await syncCheckpointTurnCounts({
|
||||
threadId: activeThread.id,
|
||||
sessionId: session.sessionId,
|
||||
threadRuntimeId: resolvedThreadId,
|
||||
});
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
resolvedThreadId,
|
||||
@@ -1572,13 +1468,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeProject,
|
||||
activeThread,
|
||||
api,
|
||||
codexBinaryPath,
|
||||
codexHomePath,
|
||||
dispatch,
|
||||
runtimeApprovalPolicy,
|
||||
runtimeSandboxMode,
|
||||
selectedModel,
|
||||
syncCheckpointTurnCounts,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1587,7 +1480,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (phase === "running" || isSending || isConnecting || isRevertingCheckpoint) return;
|
||||
const hasThreadIdentity = Boolean(activeThreadRuntimeId);
|
||||
if (!hasThreadIdentity) return;
|
||||
if (turnDiffSummaries.length === 0) return;
|
||||
const selectedDiffTurnId =
|
||||
state.diffOpen && state.diffThreadId === activeThreadId ? state.diffTurnId : null;
|
||||
const selectedDiffTurn =
|
||||
selectedDiffTurnId === null
|
||||
? undefined
|
||||
: (turnDiffSummaries.find((summary) => summary.turnId === selectedDiffTurnId) ??
|
||||
turnDiffSummaries[0]);
|
||||
const selectedTurnMissingPatchBody = Boolean(
|
||||
selectedDiffTurn &&
|
||||
!selectedDiffTurn.unifiedDiff &&
|
||||
selectedDiffTurn.files.every((file) => !file.diff),
|
||||
);
|
||||
const hasPendingDiffHydration =
|
||||
turnDiffSummaries.some((summary) => !summary.checkpointDiffLoaded) ||
|
||||
selectedTurnMissingPatchBody;
|
||||
if (!hasPendingDiffHydration) return;
|
||||
|
||||
const requestKey = `${activeThreadId}:${activeThreadRuntimeId ?? "none"}`;
|
||||
if (checkpointHydrationSessionRequestRef.current.has(requestKey)) {
|
||||
@@ -1614,6 +1522,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
isSending,
|
||||
phase,
|
||||
setThreadError,
|
||||
state.diffOpen,
|
||||
state.diffThreadId,
|
||||
state.diffTurnId,
|
||||
turnDiffSummaries,
|
||||
]);
|
||||
|
||||
@@ -1801,7 +1712,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
).text
|
||||
: trimmed || undefined;
|
||||
await api.providers.sendTurn({
|
||||
uiThreadId: activeThread.id,
|
||||
sessionId: sessionInfo.sessionId,
|
||||
...(input ? { input } : {}),
|
||||
...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}),
|
||||
@@ -1974,29 +1884,32 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setExpandedImage(image);
|
||||
}, []);
|
||||
const onToggleDiff = useCallback(() => {
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return diffOpen ? rest : { ...rest, diff: "1" };
|
||||
},
|
||||
if (state.diffOpen) {
|
||||
dispatch({ type: "CLOSE_DIFF" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeThread) {
|
||||
dispatch({ type: "TOGGLE_DIFF" });
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: "OPEN_DIFF",
|
||||
threadId: activeThread.id,
|
||||
});
|
||||
}, [diffOpen, navigate, threadId]);
|
||||
}, [activeThread, dispatch, state.diffOpen]);
|
||||
const onOpenTurnDiff = useCallback(
|
||||
(turnId: string, filePath?: string) => {
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return filePath
|
||||
? { ...rest, diff: "1", diffTurnId: turnId, diffFilePath: filePath }
|
||||
: { ...rest, diff: "1", diffTurnId: turnId };
|
||||
},
|
||||
if (!activeThread) return;
|
||||
dispatch({
|
||||
type: "OPEN_DIFF",
|
||||
threadId: activeThread.id,
|
||||
turnId,
|
||||
...(filePath ? { filePath } : {}),
|
||||
});
|
||||
},
|
||||
[navigate, threadId],
|
||||
[activeThread, dispatch],
|
||||
);
|
||||
const onRevertUserMessage = useCallback(
|
||||
(messageId: string) => {
|
||||
@@ -2044,7 +1957,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
keybindings={keybindings}
|
||||
api={api}
|
||||
gitCwd={gitCwd}
|
||||
diffOpen={diffOpen}
|
||||
diffOpen={state.diffOpen}
|
||||
onRunProjectScript={(script) => {
|
||||
void runProjectScript(script);
|
||||
}}
|
||||
@@ -2077,7 +1990,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
completionSummary={completionSummary}
|
||||
assistantCompletionByItemId={assistantCompletionByItemId}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
turnCheckpointFilesByTurnId={turnCheckpointFilesByTurnId}
|
||||
nowIso={nowIso}
|
||||
expandedWorkGroups={expandedWorkGroups}
|
||||
onToggleWorkGroup={onToggleWorkGroup}
|
||||
@@ -2543,7 +2455,6 @@ interface MessagesTimelineProps {
|
||||
completionSummary: string | null;
|
||||
assistantCompletionByItemId: Map<string, string>;
|
||||
turnDiffSummaryByAssistantMessageId: Map<string, TurnDiffSummary>;
|
||||
turnCheckpointFilesByTurnId: Map<string, TurnCheckpointFilesState>;
|
||||
nowIso: string;
|
||||
expandedWorkGroups: Record<string, boolean>;
|
||||
onToggleWorkGroup: (groupId: string) => void;
|
||||
@@ -2580,7 +2491,6 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
completionSummary,
|
||||
assistantCompletionByItemId,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
turnCheckpointFilesByTurnId,
|
||||
nowIso,
|
||||
expandedWorkGroups,
|
||||
onToggleWorkGroup,
|
||||
@@ -2829,75 +2739,70 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
row.message.id,
|
||||
);
|
||||
if (!turnSummary) return null;
|
||||
const checkpointFilesState = turnCheckpointFilesByTurnId.get(
|
||||
turnSummary.turnId,
|
||||
);
|
||||
const checkpointFiles = checkpointFilesState?.files ?? [];
|
||||
const summaryStat = checkpointFiles.reduce(
|
||||
(acc, file) => {
|
||||
if (
|
||||
typeof file.additions !== "number" ||
|
||||
typeof file.deletions !== "number"
|
||||
) {
|
||||
return acc;
|
||||
}
|
||||
return {
|
||||
additions: acc.additions + file.additions,
|
||||
deletions: acc.deletions + file.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
const changedFileCountLabel =
|
||||
checkpointFilesState?.status === "ready"
|
||||
? String(checkpointFiles.length)
|
||||
: "...";
|
||||
const isCheckpointDiffLoading =
|
||||
!turnSummary.checkpointDiffLoaded && turnSummary.files.length === 0;
|
||||
const summaryStat = turnSummary.unifiedDiff
|
||||
? countDiffStat(turnSummary.unifiedDiff)
|
||||
: turnSummary.files.reduce(
|
||||
(acc, file) => {
|
||||
const next =
|
||||
typeof file.additions === "number" &&
|
||||
typeof file.deletions === "number"
|
||||
? { additions: file.additions, deletions: file.deletions }
|
||||
: file.diff
|
||||
? countDiffStat(file.diff)
|
||||
: null;
|
||||
if (!next) {
|
||||
return acc;
|
||||
}
|
||||
return {
|
||||
additions: acc.additions + next.additions,
|
||||
deletions: acc.deletions + next.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
const changedFileCountLabel = isCheckpointDiffLoading
|
||||
? "..."
|
||||
: String(turnSummary.files.length);
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<span className="text-success">+{summaryStat.additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">
|
||||
-{summaryStat.deletions}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{!isCheckpointDiffLoading &&
|
||||
(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<span className="text-success">
|
||||
+{summaryStat.additions}
|
||||
</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">
|
||||
-{summaryStat.deletions}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||
onOpenTurnDiff(turnSummary.turnId, turnSummary.files[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
{!checkpointFilesState ||
|
||||
checkpointFilesState.status === "pending" ? (
|
||||
<p className="text-[11px] text-muted-foreground/70">
|
||||
Waiting for checkpoint metadata...
|
||||
</p>
|
||||
) : checkpointFilesState?.status === "loading" ? (
|
||||
<p className="text-[11px] text-muted-foreground/70">
|
||||
{isCheckpointDiffLoading && (
|
||||
<p className="mb-1.5 text-[11px] text-muted-foreground/70">
|
||||
Loading checkpoint diff...
|
||||
</p>
|
||||
) : checkpointFilesState?.status === "error" ? (
|
||||
<p
|
||||
className="truncate text-[11px] text-muted-foreground/70"
|
||||
title={checkpointFilesState.errorMessage}
|
||||
>
|
||||
{checkpointFilesState.errorMessage}
|
||||
</p>
|
||||
) : checkpointFiles.length > 0 ? (
|
||||
)}
|
||||
{turnSummary.files.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{checkpointFiles.map((file) => (
|
||||
{turnSummary.files.map((file) => (
|
||||
<button
|
||||
key={`${turnSummary.turnId}:${file.path}`}
|
||||
type="button"
|
||||
@@ -2912,7 +2817,9 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
}
|
||||
: null;
|
||||
: file.diff
|
||||
? countDiffStat(file.diff)
|
||||
: null;
|
||||
if (!stat) {
|
||||
return file.path;
|
||||
}
|
||||
@@ -2934,11 +2841,11 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
) : !isCheckpointDiffLoading ? (
|
||||
<p className="text-[11px] text-muted-foreground/70">
|
||||
No changed files.
|
||||
</p>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
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 {
|
||||
FileDiff,
|
||||
type FileDiffMetadata,
|
||||
Virtualizer,
|
||||
WorkerPoolContextProvider,
|
||||
} from "@pierre/diffs/react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
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 { formatTimestamp } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
@@ -67,37 +72,43 @@ 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 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>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const api = useNativeApi();
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { state } = useStore();
|
||||
const { state, dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
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 activeThreadId = state.diffThreadId ?? routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeThreadRuntimeId =
|
||||
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
|
||||
@@ -105,8 +116,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
|
||||
const selectedTurnId = diffSearch.diffTurnId ?? null;
|
||||
const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
|
||||
const canApplyStoredTarget = Boolean(activeThread && state.diffThreadId === activeThread.id);
|
||||
const selectedTurnId = canApplyStoredTarget ? state.diffTurnId : null;
|
||||
const selectedFilePath =
|
||||
canApplyStoredTarget && selectedTurnId !== null ? state.diffFilePath : null;
|
||||
const selectedTurn =
|
||||
selectedTurnId === null
|
||||
? undefined
|
||||
@@ -180,7 +193,99 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
? "Failed to load checkpoint diff."
|
||||
: null;
|
||||
|
||||
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || !selectedTurn || !selectedTurnCheckpointDiff) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: activeThread.id,
|
||||
checkpointDiffByTurnId: {
|
||||
[selectedTurn.turnId]: selectedTurnCheckpointDiff,
|
||||
},
|
||||
});
|
||||
}, [activeThread?.id, dispatch, selectedTurn, selectedTurnCheckpointDiff]);
|
||||
|
||||
const selectedPatch = useMemo(() => {
|
||||
const patchForSummary = (summary: (typeof turnDiffSummaries)[number]): string | undefined => {
|
||||
const checkpointTurnCount =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (activeSessionId && typeof checkpointTurnCount === "number") {
|
||||
const checkpointPatch = queryClient.getQueryData<{ diff: string }>(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount: Math.max(0, checkpointTurnCount - 1),
|
||||
toTurnCount: checkpointTurnCount,
|
||||
cacheScope: `turn:${summary.turnId}`,
|
||||
}),
|
||||
)?.diff;
|
||||
if (checkpointPatch) {
|
||||
return checkpointPatch;
|
||||
}
|
||||
}
|
||||
if (summary.unifiedDiff) {
|
||||
return summary.unifiedDiff;
|
||||
}
|
||||
const filePatches = summary.files
|
||||
.map((file) => file.diff?.trim())
|
||||
.filter((patch): patch is string => Boolean(patch));
|
||||
if (filePatches.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return filePatches.join("\n\n");
|
||||
};
|
||||
|
||||
if (selectedTurn) {
|
||||
return selectedTurnCheckpointDiff ?? patchForSummary(selectedTurn);
|
||||
}
|
||||
|
||||
if (conversationCheckpointDiff) {
|
||||
return conversationCheckpointDiff;
|
||||
}
|
||||
|
||||
// Fallback when a conversation checkpoint diff isn't available yet:
|
||||
// keep one patch per file path (latest change wins) so files aren't duplicated.
|
||||
const latestPatchByPath = new Map<string, string>();
|
||||
for (const summary of turnDiffSummaries) {
|
||||
for (const file of summary.files) {
|
||||
if (latestPatchByPath.has(file.path)) {
|
||||
continue;
|
||||
}
|
||||
const patch = file.diff?.trim();
|
||||
if (!patch) {
|
||||
continue;
|
||||
}
|
||||
latestPatchByPath.set(file.path, patch);
|
||||
}
|
||||
}
|
||||
if (latestPatchByPath.size > 0) {
|
||||
return Array.from(latestPatchByPath.entries())
|
||||
.toSorted(([leftPath], [rightPath]) =>
|
||||
leftPath.localeCompare(rightPath, undefined, { numeric: true, sensitivity: "base" }),
|
||||
)
|
||||
.map(([, patch]) => patch)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
const patches = turnDiffSummaries
|
||||
.toReversed()
|
||||
.map((summary) => patchForSummary(summary)?.trim())
|
||||
.filter((patch): patch is string => Boolean(patch));
|
||||
if (patches.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return patches.join("\n\n");
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeThreadRuntimeId,
|
||||
conversationCheckpointDiff,
|
||||
inferredCheckpointTurnCountByTurnId,
|
||||
queryClient,
|
||||
selectedTurn,
|
||||
selectedTurnCheckpointDiff,
|
||||
turnDiffSummaries,
|
||||
]);
|
||||
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
@@ -206,84 +311,19 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
|
||||
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 };
|
||||
},
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
turnId,
|
||||
});
|
||||
};
|
||||
const selectWholeConversation = () => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: activeThread.id },
|
||||
search: (previous) => {
|
||||
const rest = stripDiffSearchParams(previous);
|
||||
return { ...rest, diff: "1" };
|
||||
},
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
});
|
||||
};
|
||||
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";
|
||||
|
||||
@@ -298,98 +338,49 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 border-b border-border px-4",
|
||||
"flex items-center justify-between border-b border-border px-4",
|
||||
shouldUseDragRegion ? "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" />
|
||||
<div className="flex gap-1.5 overflow-x-auto pb-0.5">
|
||||
<button type="button" className="shrink-0 rounded-md" onClick={selectWholeConversation}>
|
||||
<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] font-medium">All turns</div>
|
||||
<div className="text-[8px] opacity-70">Conversation</div>
|
||||
</div>
|
||||
</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"
|
||||
>
|
||||
{turnDiffSummaries.map((summary, index) => (
|
||||
<button
|
||||
key={summary.turnId}
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={selectWholeConversation}
|
||||
data-turn-chip-selected={selectedTurnId === null}
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
title={summary.turnId}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
selectedTurnId === null
|
||||
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="text-[10px] leading-tight font-medium">All turns</div>
|
||||
<div className="text-[10px] font-medium">
|
||||
Turn {turnDiffSummaries.length - index}
|
||||
</div>
|
||||
<div className="text-[8px] opacity-70">{formatTimestamp(summary.completedAt)}</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]}
|
||||
@@ -420,6 +411,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
{!canApplyStoredTarget && state.diffThreadId && (
|
||||
<div className="px-3 pt-2">
|
||||
<p className="mb-2 text-[11px] text-muted-foreground/65">
|
||||
Showing diffs for the active thread.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
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 { type Project, type Thread } from "../types";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
@@ -18,6 +17,7 @@ import { toastManager } from "./ui/toast";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { createThread } from "../threadFactory";
|
||||
|
||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
@@ -116,7 +116,6 @@ 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({
|
||||
@@ -127,6 +126,7 @@ 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);
|
||||
@@ -140,7 +140,7 @@ export default function Sidebar() {
|
||||
}, [state.threads]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
async (
|
||||
(
|
||||
projectId: string,
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
@@ -152,21 +152,16 @@ export default function Sidebar() {
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
});
|
||||
await api?.state.createThread({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
createdAt: thread.createdAt,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread,
|
||||
});
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
},
|
||||
[api, navigate, state.projects],
|
||||
[dispatch, navigate, state.projects],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
@@ -197,11 +192,23 @@ export default function Sidebar() {
|
||||
try {
|
||||
if (isElectron && api) {
|
||||
const result = await api.projects.add({ cwd });
|
||||
const existingByCwd = state.projects.find((p) => p.cwd === result.project.cwd);
|
||||
const resolvedProjectId = existingByCwd?.id ?? result.project.id;
|
||||
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;
|
||||
|
||||
if (result.created) {
|
||||
await handleNewThread(resolvedProjectId);
|
||||
handleNewThread(resolvedProjectId);
|
||||
} else {
|
||||
focusMostRecentThreadForProject(resolvedProjectId);
|
||||
}
|
||||
@@ -211,9 +218,18 @@ export default function Sidebar() {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
return;
|
||||
}
|
||||
if (!api) return;
|
||||
const result = await api.projects.add({ cwd });
|
||||
await handleNewThread(result.project.id);
|
||||
|
||||
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);
|
||||
}
|
||||
} finally {
|
||||
setIsAddingProject(false);
|
||||
@@ -255,17 +271,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
|
||||
@@ -305,7 +310,7 @@ export default function Sidebar() {
|
||||
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||
await api.state.deleteThread({ id: threadId });
|
||||
dispatch({ type: "DELETE_THREAD", threadId });
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -343,16 +348,7 @@ export default function Sidebar() {
|
||||
});
|
||||
}
|
||||
},
|
||||
[
|
||||
api,
|
||||
appSettings.confirmThreadDelete,
|
||||
dispatch,
|
||||
navigate,
|
||||
removeWorktreeMutation,
|
||||
routeThreadId,
|
||||
state.projects,
|
||||
state.threads,
|
||||
],
|
||||
[api, dispatch, navigate, removeWorktreeMutation, routeThreadId, state.projects, state.threads],
|
||||
);
|
||||
|
||||
const handleProjectContextMenu = useCallback(
|
||||
@@ -379,18 +375,23 @@ export default function Sidebar() {
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
await api.projects.remove({ id: projectId });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error deleting project.";
|
||||
console.error("Failed to remove project", { projectId, error });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to delete "${project.name}"`,
|
||||
description: message,
|
||||
});
|
||||
return;
|
||||
if (isElectron) {
|
||||
try {
|
||||
await api.projects.remove({ id: projectId });
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Unknown error deleting project.";
|
||||
console.error("Failed to remove project", { projectId, error });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to delete "${project.name}"`,
|
||||
description: message,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
dispatch({ type: "DELETE_PROJECT", projectId });
|
||||
},
|
||||
[api, dispatch, state.projects, state.threads],
|
||||
);
|
||||
@@ -430,14 +431,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) */}
|
||||
@@ -451,7 +462,7 @@ export default function Sidebar() {
|
||||
return;
|
||||
}
|
||||
const firstProject = state.projects[0];
|
||||
if (firstProject) void handleNewThread(firstProject.id);
|
||||
if (firstProject) handleNewThread(firstProject.id);
|
||||
}}
|
||||
>
|
||||
<span className="text-foreground">+</span>
|
||||
@@ -566,9 +577,7 @@ export default function Sidebar() {
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
|
||||
onClick={() => {
|
||||
void handleNewThread(project.id);
|
||||
}}
|
||||
onClick={() => handleNewThread(project.id)}
|
||||
>
|
||||
<span>+</span> New thread
|
||||
</button>
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -52,60 +52,4 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -23,25 +23,6 @@ export const providerQueryKeys = {
|
||||
] 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,
|
||||
@@ -73,15 +54,7 @@ export function checkpointDiffQueryOptions(
|
||||
},
|
||||
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)),
|
||||
retry: 8,
|
||||
retryDelay: (attempt) => Math.min(2_000, 150 * 2 ** (attempt - 1)),
|
||||
});
|
||||
}
|
||||
@@ -9,14 +9,12 @@ import "@xterm/xterm/css/xterm.css";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
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?.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}`);
|
||||
});
|
||||
|
||||
it("hydrates persisted turn diff summaries and clears persisted loaded flags", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointDiffLoaded: true,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops malformed persisted turn diff summaries instead of rejecting the whole snapshot", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
files: [{ path: 123 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.threads[0]?.id).toBe("t-1");
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
diff: "diff --git a/src/app.ts b/src/app.ts",
|
||||
},
|
||||
],
|
||||
unifiedDiff: "diff --git a/src/app.ts b/src/app.ts",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const persisted = toPersistedState({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
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,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const persistedThread = persisted.threads[0];
|
||||
expect(persistedThread).toBeDefined();
|
||||
if (!persistedThread) return;
|
||||
|
||||
expect("error" in persistedThread).toBe(false);
|
||||
expect("session" in persistedThread).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,400 @@
|
||||
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 persistedTurnDiffFileChangeSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: z.string().min(1).optional(),
|
||||
additions: z.number().int().min(0).optional(),
|
||||
deletions: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
const persistedTurnDiffSummarySchema = z.object({
|
||||
turnId: z.string().min(1),
|
||||
completedAt: z.string().min(1),
|
||||
status: z.string().min(1).optional(),
|
||||
files: z.array(persistedTurnDiffFileChangeSchema),
|
||||
assistantMessageId: z.string().min(1).optional(),
|
||||
checkpointTurnCount: z.number().int().min(0).optional(),
|
||||
checkpointDiffLoaded: z.boolean().optional(),
|
||||
});
|
||||
|
||||
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(),
|
||||
turnDiffSummaries: z.array(persistedTurnDiffSummarySchema).catch([]).default([]),
|
||||
});
|
||||
|
||||
const persistedStateBodySchema = z.object({
|
||||
projects: z.array(persistedProjectSchema),
|
||||
threads: z.array(persistedThreadSchema),
|
||||
activeThreadId: z.string().min(1).nullable().optional(),
|
||||
});
|
||||
|
||||
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[];
|
||||
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,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
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));
|
||||
return {
|
||||
projects,
|
||||
threads,
|
||||
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,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
})),
|
||||
runtimeMode: state.runtimeMode,
|
||||
};
|
||||
}
|
||||
@@ -11,7 +11,6 @@
|
||||
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({
|
||||
@@ -23,11 +22,6 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
|
||||
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',
|
||||
@@ -37,26 +31,23 @@ const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
|
||||
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'
|
||||
fullPaths: '/' | '/$threadId'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/$threadId' | '/settings' | '/'
|
||||
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/'
|
||||
to: '/$threadId' | '/'
|
||||
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
@@ -79,13 +70,6 @@ declare module '@tanstack/react-router' {
|
||||
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'
|
||||
@@ -98,13 +82,11 @@ declare module '@tanstack/react-router' {
|
||||
|
||||
interface ChatRouteChildren {
|
||||
ChatThreadIdRoute: typeof ChatThreadIdRoute
|
||||
ChatSettingsRoute: typeof ChatSettingsRoute
|
||||
ChatIndexRoute: typeof ChatIndexRoute
|
||||
}
|
||||
|
||||
const ChatRouteChildren: ChatRouteChildren = {
|
||||
ChatThreadIdRoute: ChatThreadIdRoute,
|
||||
ChatSettingsRoute: ChatSettingsRoute,
|
||||
ChatIndexRoute: ChatIndexRoute,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,19 @@
|
||||
import {
|
||||
Outlet,
|
||||
createRootRouteWithContext,
|
||||
type ErrorComponentProps,
|
||||
useParams,
|
||||
} from "@tanstack/react-router";
|
||||
import { Outlet, createRootRouteWithContext, useParams } from "@tanstack/react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { QueryClient, useQueryClient } 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 { invalidateGitQueries } from "../lib/gitReactQuery";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { type AppState, useStore } from "../store";
|
||||
import { onServerStateUpdate, onServerWelcome } from "../wsNativeApi";
|
||||
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() {
|
||||
@@ -31,9 +23,7 @@ function RootRouteView() {
|
||||
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>
|
||||
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -51,143 +41,83 @@ function RootRouteView() {
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
const queryClient = useQueryClient();
|
||||
const activeAssistantItemRef = useRef<string | null>(null);
|
||||
const activeThreadId = useParams({
|
||||
strict: false,
|
||||
select: (params) => params.threadId,
|
||||
});
|
||||
const prevTurnCompletionsRef = useRef<Map<string, string | undefined>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
let mounted = true;
|
||||
void api.state.getSnapshot().then((snapshot) => {
|
||||
if (!mounted) return;
|
||||
dispatch({ type: "SET_SERVER_STATE", state: snapshot as AppState });
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
return onServerStateUpdate((snapshot) => {
|
||||
const serverState = snapshot as AppState;
|
||||
dispatch({ type: "SET_SERVER_STATE", state: serverState });
|
||||
|
||||
let hasNewTurnCompletion = false;
|
||||
for (const thread of serverState.threads) {
|
||||
const prev = prevTurnCompletionsRef.current.get(thread.id);
|
||||
if (thread.latestTurnCompletedAt && thread.latestTurnCompletedAt !== prev) {
|
||||
hasNewTurnCompletion = true;
|
||||
}
|
||||
}
|
||||
const nextMap = new Map<string, string | undefined>();
|
||||
for (const thread of serverState.threads) {
|
||||
nextMap.set(thread.id, thread.latestTurnCompletedAt);
|
||||
}
|
||||
prevTurnCompletionsRef.current = nextMap;
|
||||
|
||||
if (hasNewTurnCompletion) {
|
||||
return api.providers.onEvent((event) => {
|
||||
if (event.method === "turn/completed") {
|
||||
void invalidateGitQueries(queryClient);
|
||||
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
|
||||
}
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "APPLY_EVENT",
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
activeThreadId,
|
||||
});
|
||||
});
|
||||
}, [dispatch, queryClient]);
|
||||
}, [activeThreadId, api, dispatch, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
const visitedAt = new Date().toISOString();
|
||||
if (!api) return;
|
||||
void api.state.markThreadVisited({ threadId: activeThreadId, visitedAt });
|
||||
}, [activeThreadId, api]);
|
||||
return api.terminal.onEvent((event) => {
|
||||
dispatch({
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function AutoProjectBootstrap() {
|
||||
const { dispatch } = useStore();
|
||||
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(() => {
|
||||
|
||||
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;
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
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: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
});
|
||||
}, [dispatch]);
|
||||
}, [state.projects, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -195,10 +125,50 @@ function AutoProjectBootstrap() {
|
||||
function DesktopProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron || !api) return;
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
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,
|
||||
})),
|
||||
});
|
||||
dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true });
|
||||
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;
|
||||
|
||||
@@ -1,67 +1,14 @@
|
||||
import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
||||
import { 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) {
|
||||
@@ -83,30 +30,9 @@ function ChatThreadRouteView() {
|
||||
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>
|
||||
</>
|
||||
);
|
||||
return <ChatView threadId={threadId} />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/_chat/$threadId")({
|
||||
validateSearch: (search) => parseDiffRouteSearch(search),
|
||||
component: ChatThreadRouteView,
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
@@ -1,34 +1,78 @@
|
||||
import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { useEffect } from "react";
|
||||
import { Outlet, createFileRoute } from "@tanstack/react-router";
|
||||
import { Activity, Suspense, lazy, type ReactNode } from "react";
|
||||
|
||||
import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider";
|
||||
import Sidebar from "../components/Sidebar";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { useStore } from "../store";
|
||||
import { Sheet, SheetPopup } from "../components/ui/sheet";
|
||||
|
||||
const DiffPanel = lazy(() => import("../components/DiffPanel"));
|
||||
const DiffWorkerPoolProvider = lazy(() =>
|
||||
import("../components/DiffPanel").then((module) => ({
|
||||
default: module.DiffWorkerPoolProvider,
|
||||
})),
|
||||
);
|
||||
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
|
||||
|
||||
const DiffPanelWrapper = (props: { children: ReactNode; sheet: boolean }) => {
|
||||
const { state, dispatch } = useStore();
|
||||
if (props.sheet) {
|
||||
return (
|
||||
<Sheet
|
||||
open={state.diffOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
dispatch({ type: "CLOSE_DIFF" });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SheetPopup
|
||||
side="right"
|
||||
showCloseButton={false}
|
||||
keepMounted
|
||||
className="w-[min(88vw,820px)] max-w-[820px] p-0"
|
||||
>
|
||||
{props.children}
|
||||
</SheetPopup>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className={state.diffOpen ? undefined : "hidden"} aria-hidden={!state.diffOpen}>
|
||||
{props.children}
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
function ChatRouteLayout() {
|
||||
const navigate = useNavigate();
|
||||
const { state } = useStore();
|
||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
||||
|
||||
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]);
|
||||
const diffLoadingFallback =
|
||||
!state.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 (
|
||||
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
|
||||
<Sidebar />
|
||||
<DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
</DiffWorkerPoolProvider>
|
||||
<Outlet />
|
||||
<Activity mode={state.diffOpen ? "visible" : "hidden"}>
|
||||
<DiffPanelWrapper sheet={shouldUseDiffSheet}>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffWorkerPoolProvider>
|
||||
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
|
||||
</DiffWorkerPoolProvider>
|
||||
</Suspense>
|
||||
</DiffPanelWrapper>
|
||||
</Activity>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -36,4 +80,3 @@ function ChatRouteLayout() {
|
||||
export const Route = createFileRoute("/_chat")({
|
||||
component: ChatRouteLayout,
|
||||
});
|
||||
|
||||
@@ -493,11 +493,11 @@ describe("deriveTurnDiffSummaries", () => {
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
expect(summaries[0]?.unifiedDiff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
||||
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(summaries[0]?.files[0]?.kind).toBe("modified");
|
||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
||||
expect(summaries[0]).not.toHaveProperty("unifiedDiff");
|
||||
});
|
||||
|
||||
it("includes completed turns even when no fileChange tool events were emitted", () => {
|
||||
@@ -537,10 +537,9 @@ describe("deriveTurnDiffSummaries", () => {
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1,2 @@",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+older",
|
||||
"+extra",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
@@ -573,9 +572,8 @@ describe("deriveTurnDiffSummaries", () => {
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.files[0]?.path).toBe("src/example.ts");
|
||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
||||
expect(summaries[0]?.unifiedDiff).toContain("+newest");
|
||||
expect(summaries[0]?.unifiedDiff).not.toContain("+older");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -595,6 +593,8 @@ describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
|
||||
);
|
||||
|
||||
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(files[0]?.diff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
||||
expect(files[1]?.diff).toContain("diff --git a/src/b.ts b/src/b.ts");
|
||||
expect(files[0]?.additions).toBe(1);
|
||||
expect(files[0]?.deletions).toBe(1);
|
||||
});
|
||||
|
||||
@@ -453,7 +453,7 @@ interface MutableTurnDiffSummary {
|
||||
completedAt: string | undefined;
|
||||
status: string | undefined;
|
||||
assistantMessageId: string | undefined;
|
||||
hasTurnDiffUpdate: boolean;
|
||||
unifiedDiff: string | undefined;
|
||||
filesByPath: Map<string, TurnDiffFileChange>;
|
||||
}
|
||||
|
||||
@@ -485,6 +485,7 @@ function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChan
|
||||
parsed.push({
|
||||
path,
|
||||
...(kind ? { kind } : {}),
|
||||
...(diff ? { diff } : {}),
|
||||
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
|
||||
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
|
||||
});
|
||||
@@ -506,6 +507,9 @@ function mergeTurnDiffFileChange(
|
||||
if (existing.kind === undefined && incoming.kind !== undefined) {
|
||||
existing.kind = incoming.kind;
|
||||
}
|
||||
if (existing.diff === undefined && incoming.diff !== undefined) {
|
||||
existing.diff = incoming.diff;
|
||||
}
|
||||
if (existing.additions === undefined && incoming.additions !== undefined) {
|
||||
existing.additions = incoming.additions;
|
||||
}
|
||||
@@ -561,6 +565,7 @@ export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileCh
|
||||
const stat = countDiffStat(fileDiff);
|
||||
return {
|
||||
path,
|
||||
diff: fileDiff,
|
||||
additions: stat.additions,
|
||||
deletions: stat.deletions,
|
||||
};
|
||||
@@ -640,7 +645,7 @@ export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummar
|
||||
completedAt: undefined,
|
||||
status: undefined,
|
||||
assistantMessageId: undefined,
|
||||
hasTurnDiffUpdate: false,
|
||||
unifiedDiff: undefined,
|
||||
filesByPath: new Map<string, TurnDiffFileChange>(),
|
||||
};
|
||||
byTurnId.set(turnId, next);
|
||||
@@ -672,10 +677,10 @@ export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummar
|
||||
}
|
||||
}
|
||||
|
||||
if (event.method === "turn/diff/updated" && !summary.hasTurnDiffUpdate) {
|
||||
summary.hasTurnDiffUpdate = true;
|
||||
if (event.method === "turn/diff/updated" && summary.unifiedDiff === undefined) {
|
||||
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
|
||||
if (diff) {
|
||||
summary.unifiedDiff = diff;
|
||||
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
|
||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
||||
}
|
||||
@@ -698,6 +703,7 @@ export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummar
|
||||
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
|
||||
a.path.localeCompare(b.path),
|
||||
),
|
||||
...(summary.unifiedDiff ? { unifiedDiff: summary.unifiedDiff } : {}),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,971 @@
|
||||
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: [],
|
||||
turnDiffSummaries: [],
|
||||
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],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
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("opens diff panel with an explicit turn/file target", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "OPEN_DIFF",
|
||||
threadId: "thread-local-1",
|
||||
turnId: "turn-1",
|
||||
filePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(next.diffOpen).toBe(true);
|
||||
expect(next.diffThreadId).toBe("thread-local-1");
|
||||
expect(next.diffTurnId).toBe("turn-1");
|
||||
expect(next.diffFilePath).toBe("src/app.ts");
|
||||
});
|
||||
|
||||
it("sets terminal open state per thread", () => {
|
||||
const state = makeState(makeThread({ terminalOpen: true }));
|
||||
const next = reducer(state, {
|
||||
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("preserves persisted turn diffs when events were reset and appends new completed turn diffs", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
events: [],
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:01.000Z",
|
||||
files: [{ path: "src/existing.ts", kind: "modified" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const withFileChange = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "item/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
type: "fileChange",
|
||||
changes: [{ path: "src/new.ts", kind: "added" }],
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(withFileChange.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
||||
"turn-1",
|
||||
]);
|
||||
|
||||
const completed = reducer(withFileChange, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-2", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(completed.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
||||
"turn-2",
|
||||
"turn-1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("infers checkpoint turn counts when deriving turn summaries from an empty baseline", () => {
|
||||
const state = makeState(makeThread({ turnDiffSummaries: [] }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
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",
|
||||
}),
|
||||
],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: true,
|
||||
diffThreadId: "thread-b",
|
||||
diffTurnId: "turn-b",
|
||||
diffFilePath: "src/removed.ts",
|
||||
};
|
||||
|
||||
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.diffOpen).toBe(false);
|
||||
expect(next.diffThreadId).toBeNull();
|
||||
expect(next.diffTurnId).toBeNull();
|
||||
expect(next.diffFilePath).toBeNull();
|
||||
});
|
||||
|
||||
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" })],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
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("marks threads hydration state", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREADS_HYDRATED",
|
||||
hydrated: false,
|
||||
});
|
||||
|
||||
expect(next.threadsHydrated).toBe(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",
|
||||
}),
|
||||
],
|
||||
threadsHydrated: true,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: true,
|
||||
diffThreadId: "thread-a",
|
||||
diffTurnId: "turn-a",
|
||||
diffFilePath: "src/a.ts",
|
||||
};
|
||||
|
||||
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.diffOpen).toBe(false);
|
||||
expect(next.diffThreadId).toBeNull();
|
||||
expect(next.diffTurnId).toBeNull();
|
||||
expect(next.diffFilePath).toBeNull();
|
||||
});
|
||||
|
||||
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 },
|
||||
activeThreadId: "thread-local-1",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
|
||||
});
|
||||
|
||||
it("reverts thread state to a checkpoint snapshot", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
codexThreadId: "thr_before",
|
||||
session: makeSession({
|
||||
status: "running",
|
||||
threadId: "thr_before",
|
||||
activeTurnId: "turn-live",
|
||||
}),
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "First",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-2",
|
||||
role: "assistant",
|
||||
text: "First reply",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-3",
|
||||
role: "user",
|
||||
text: "Second",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [
|
||||
makeEvent({
|
||||
method: "turn/started",
|
||||
turnId: "turn-live",
|
||||
}),
|
||||
],
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn_1",
|
||||
completedAt: "2026-02-08T10:00:01.000Z",
|
||||
files: [{ path: "src/first.ts", kind: "modified" }],
|
||||
checkpointTurnCount: 1,
|
||||
},
|
||||
{
|
||||
turnId: "turn_2",
|
||||
completedAt: "2026-02-08T10:00:03.000Z",
|
||||
files: [{ path: "src/second.ts", kind: "modified" }],
|
||||
checkpointTurnCount: 2,
|
||||
},
|
||||
],
|
||||
error: "temporary failure",
|
||||
latestTurnId: "turn-live",
|
||||
latestTurnStartedAt: "2026-02-08T10:00:03.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "REVERT_TO_CHECKPOINT",
|
||||
threadId: "thread-local-1",
|
||||
sessionId: "sess-1",
|
||||
threadRuntimeId: "thr_after",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual(["m-1", "m-2"]);
|
||||
expect(next.threads[0]?.events).toEqual([]);
|
||||
expect(next.threads[0]?.error).toBeNull();
|
||||
expect(next.threads[0]?.session?.status).toBe("ready");
|
||||
expect(next.threads[0]?.session?.activeTurnId).toBeUndefined();
|
||||
expect(next.threads[0]?.session?.threadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.latestTurnId).toBeUndefined();
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn_1"]);
|
||||
});
|
||||
|
||||
it("keeps checkpoint-derived turn files when later events for the same turn arrive", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:03.000Z",
|
||||
files: [
|
||||
{
|
||||
path: "src/from-checkpoint.ts",
|
||||
diff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
||||
},
|
||||
],
|
||||
unifiedDiff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
||||
checkpointDiffLoaded: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:04.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
||||
"src/from-checkpoint.ts",
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.unifiedDiff).toContain("from-checkpoint.ts");
|
||||
});
|
||||
|
||||
it("updates turn summaries from checkpoint diffs and marks them as loaded", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:03.000Z",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: "thread-local-1",
|
||||
checkpointDiffByTurnId: {
|
||||
"turn-1": [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-a",
|
||||
"+new-a",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-b",
|
||||
"+new-b",
|
||||
].join("\n"),
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
||||
"src/a.ts",
|
||||
"src/b.ts",
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,22 @@ import {
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import { type ProviderSession, 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,
|
||||
deriveTurnDiffFilesFromUnifiedDiff,
|
||||
deriveTurnDiffSummaries,
|
||||
inferCheckpointTurnCountByTurnId,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -24,7 +35,6 @@ import {
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "SET_SERVER_STATE"; state: AppState }
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
|
||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||
@@ -39,6 +49,27 @@ 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: "OPEN_DIFF";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| {
|
||||
type: "SET_DIFF_TARGET";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| { type: "CLOSE_DIFF" }
|
||||
| {
|
||||
type: "APPLY_EVENT";
|
||||
event: ProviderEvent;
|
||||
activeAssistantItemRef: { current: string | null };
|
||||
activeThreadId?: string | null;
|
||||
}
|
||||
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| {
|
||||
type: "PUSH_USER_MESSAGE";
|
||||
@@ -63,13 +94,17 @@ type Action =
|
||||
threadId: string;
|
||||
checkpointTurnCountByTurnId: Record<string, number>;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS";
|
||||
threadId: string;
|
||||
checkpointDiffByTurnId: Record<string, string>;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
| { type: "MARK_THREAD_VISITED"; threadId: string; visitedAt?: string }
|
||||
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }
|
||||
| { type: "DELETE_THREAD"; threadId: string };
|
||||
|
||||
@@ -80,23 +115,77 @@ export interface AppState {
|
||||
threads: Thread[];
|
||||
threadsHydrated: boolean;
|
||||
runtimeMode: RuntimeMode;
|
||||
diffOpen: boolean;
|
||||
diffThreadId: string | null;
|
||||
diffTurnId: string | null;
|
||||
diffFilePath: string | null;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
"t3code:renderer-state:v6",
|
||||
"t3code:renderer-state:v5",
|
||||
"t3code:renderer-state:v4",
|
||||
"t3code:renderer-state:v3",
|
||||
"codething:renderer-state:v4",
|
||||
"codething:renderer-state:v3",
|
||||
"codething:renderer-state:v2",
|
||||
"codething:renderer-state:v1",
|
||||
] as const;
|
||||
|
||||
const initialState: AppState = {
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
return initialState;
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
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 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));
|
||||
|
||||
return {
|
||||
...hydrated,
|
||||
threads,
|
||||
threadsHydrated: threads.length > 0,
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
}
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
void state;
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
@@ -107,6 +196,102 @@ function updateThread(
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function resetDiffTargetIfMissing(state: AppState, threads: Thread[]) {
|
||||
if (!state.diffThreadId) {
|
||||
return {
|
||||
diffOpen: state.diffOpen,
|
||||
diffThreadId: state.diffThreadId,
|
||||
diffTurnId: state.diffTurnId,
|
||||
diffFilePath: state.diffFilePath,
|
||||
};
|
||||
}
|
||||
const hasThread = threads.some((thread) => thread.id === state.diffThreadId);
|
||||
if (hasThread) {
|
||||
return {
|
||||
diffOpen: state.diffOpen,
|
||||
diffThreadId: state.diffThreadId,
|
||||
diffTurnId: state.diffTurnId,
|
||||
diffFilePath: state.diffFilePath,
|
||||
};
|
||||
}
|
||||
return {
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeTurnDiffSummaries(
|
||||
existing: Thread["turnDiffSummaries"],
|
||||
next: Thread["turnDiffSummaries"],
|
||||
): Thread["turnDiffSummaries"] {
|
||||
if (next.length === 0) return existing;
|
||||
|
||||
const existingByTurnId = new Map(existing.map((summary) => [summary.turnId, summary] as const));
|
||||
const merged = next.map((summary) => {
|
||||
const previous = existingByTurnId.get(summary.turnId);
|
||||
if (!previous) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const prefersCheckpointDiff = previous.checkpointDiffLoaded || summary.checkpointDiffLoaded;
|
||||
const files =
|
||||
prefersCheckpointDiff ||
|
||||
(summary.files.length === 0 && previous.files.length > 0 && summary.unifiedDiff === undefined)
|
||||
? previous.files
|
||||
: summary.files;
|
||||
const unifiedDiff =
|
||||
prefersCheckpointDiff || summary.unifiedDiff === undefined
|
||||
? (previous.unifiedDiff ?? summary.unifiedDiff)
|
||||
: summary.unifiedDiff;
|
||||
|
||||
return {
|
||||
...summary,
|
||||
files,
|
||||
...(unifiedDiff !== undefined ? { unifiedDiff } : {}),
|
||||
...(summary.assistantMessageId
|
||||
? {}
|
||||
: previous.assistantMessageId
|
||||
? { assistantMessageId: previous.assistantMessageId }
|
||||
: {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? {}
|
||||
: typeof previous.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: previous.checkpointTurnCount }
|
||||
: {}),
|
||||
...(summary.checkpointDiffLoaded || previous.checkpointDiffLoaded
|
||||
? { checkpointDiffLoaded: true }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const mergedTurnIds = new Set(merged.map((summary) => summary.turnId));
|
||||
for (const summary of existing) {
|
||||
if (!mergedTurnIds.has(summary.turnId)) {
|
||||
merged.push(summary);
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = merged.toSorted((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return b.completedAt.localeCompare(a.completedAt);
|
||||
}
|
||||
return bTime - aTime;
|
||||
});
|
||||
|
||||
const inferredTurnCountByTurnId = inferCheckpointTurnCountByTurnId(sorted);
|
||||
return sorted.map((summary) =>
|
||||
typeof summary.checkpointTurnCount === "number"
|
||||
? summary
|
||||
: Object.assign({}, summary, {
|
||||
checkpointTurnCount: inferredTurnCountByTurnId[summary.turnId],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -127,6 +312,7 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
@@ -292,31 +478,93 @@ 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 "SET_SERVER_STATE": {
|
||||
const previousThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
return {
|
||||
...action.state,
|
||||
threads: action.state.threads.map((thread) => {
|
||||
const prev = previousThreadById.get(thread.id);
|
||||
if (!prev) return normalizeThreadTerminals(thread);
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalOpen: prev.terminalOpen,
|
||||
terminalHeight: prev.terminalHeight,
|
||||
activeTerminalId: prev.activeTerminalId,
|
||||
terminalGroups: prev.terminalGroups,
|
||||
activeTerminalGroupId: prev.activeTerminalGroupId,
|
||||
});
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "ADD_PROJECT":
|
||||
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
|
||||
return state;
|
||||
@@ -384,11 +632,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
});
|
||||
})
|
||||
.filter((thread): thread is Thread => thread !== null);
|
||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
threads: nextThreads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -407,11 +657,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
}
|
||||
|
||||
const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -461,7 +713,10 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
@@ -531,7 +786,10 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
@@ -589,6 +847,99 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
),
|
||||
};
|
||||
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "OPEN_DIFF":
|
||||
return {
|
||||
...state,
|
||||
diffOpen: true,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "SET_DIFF_TARGET":
|
||||
return {
|
||||
...state,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "CLOSE_DIFF":
|
||||
return { ...state, diffOpen: false };
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
}
|
||||
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, activeThreadId } = 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) => {
|
||||
const nextEvents = [event, ...t.events];
|
||||
const itemType = asString(asObject(asObject(event.payload)?.item)?.type);
|
||||
const normalizedItemType = itemType?.replace(/[_-]/g, "").toLowerCase();
|
||||
const shouldRederiveDiffs =
|
||||
event.method === "turn/completed" ||
|
||||
event.method === "turn/diff/updated" ||
|
||||
(event.method === "item/completed" &&
|
||||
(normalizedItemType === "agentmessage" || normalizedItemType === "filechange"));
|
||||
const turnDiffSummaries = shouldRederiveDiffs
|
||||
? mergeTurnDiffSummaries(t.turnDiffSummaries, deriveTurnDiffSummaries(nextEvents))
|
||||
: t.turnDiffSummaries;
|
||||
const eventThreadId = getEventThreadId(event);
|
||||
const shouldRebindIdentity =
|
||||
event.method === "thread/started" && t.session?.status === "connecting";
|
||||
return {
|
||||
...t,
|
||||
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: nextEvents,
|
||||
turnDiffSummaries,
|
||||
...updateTurnFields(t, event),
|
||||
...(event.method === "turn/completed" && t.id === activeThreadId
|
||||
? { lastVisitedAt: event.createdAt }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "UPDATE_SESSION":
|
||||
return {
|
||||
...state,
|
||||
@@ -719,6 +1070,59 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TURN_CHECKPOINT_DIFFS":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
let hasUpdates = false;
|
||||
const updatedSummaries = t.turnDiffSummaries.map((summary) => {
|
||||
const checkpointDiff = action.checkpointDiffByTurnId[summary.turnId];
|
||||
if (checkpointDiff === undefined) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(checkpointDiff);
|
||||
const filesUnchanged =
|
||||
files.length === summary.files.length &&
|
||||
files.every((file, index) => {
|
||||
const existing = summary.files[index];
|
||||
return (
|
||||
existing !== undefined &&
|
||||
existing.path === file.path &&
|
||||
existing.diff === file.diff &&
|
||||
existing.kind === file.kind &&
|
||||
existing.additions === file.additions &&
|
||||
existing.deletions === file.deletions
|
||||
);
|
||||
});
|
||||
if (
|
||||
summary.unifiedDiff === checkpointDiff &&
|
||||
filesUnchanged &&
|
||||
summary.checkpointDiffLoaded
|
||||
) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
hasUpdates = true;
|
||||
return {
|
||||
...summary,
|
||||
unifiedDiff: checkpointDiff,
|
||||
files,
|
||||
checkpointDiffLoaded: true,
|
||||
};
|
||||
});
|
||||
|
||||
if (!hasUpdates) {
|
||||
return t;
|
||||
}
|
||||
|
||||
return {
|
||||
...t,
|
||||
turnDiffSummaries: updatedSummaries,
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
@@ -737,28 +1141,21 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
case "MARK_THREAD_VISITED": {
|
||||
const visitedAt = action.visitedAt ?? new Date().toISOString();
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
lastVisitedAt: visitedAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
case "SET_RUNTIME_MODE":
|
||||
return {
|
||||
...state,
|
||||
runtimeMode: action.mode,
|
||||
};
|
||||
|
||||
case "DELETE_THREAD":
|
||||
case "DELETE_THREAD": {
|
||||
const threads = state.threads.filter((t) => t.id !== action.threadId);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.filter((t) => t.id !== action.threadId),
|
||||
threads,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return state;
|
||||
@@ -775,6 +1172,10 @@ const StoreContext = createContext<{
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface ChatMessage {
|
||||
export interface TurnDiffFileChange {
|
||||
path: string;
|
||||
kind?: string | undefined;
|
||||
diff?: string | undefined;
|
||||
additions?: number | undefined;
|
||||
deletions?: number | undefined;
|
||||
}
|
||||
@@ -49,8 +50,10 @@ export interface TurnDiffSummary {
|
||||
completedAt: string;
|
||||
status?: string | undefined;
|
||||
files: TurnDiffFileChange[];
|
||||
unifiedDiff?: string | undefined;
|
||||
assistantMessageId?: string | undefined;
|
||||
checkpointTurnCount?: number | undefined;
|
||||
checkpointDiffLoaded?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -5,9 +5,7 @@ import { WsTransport } from "./wsTransport";
|
||||
|
||||
let instance: { api: NativeApi; transport: WsTransport } | null = null;
|
||||
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
|
||||
const stateListeners = new Set<(state: unknown) => void>();
|
||||
let lastWelcome: WsWelcomePayload | null = null;
|
||||
let lastStateSnapshot: unknown = null;
|
||||
|
||||
/**
|
||||
* Subscribe to the server welcome message. If a welcome was already received
|
||||
@@ -31,20 +29,6 @@ export function onServerWelcome(listener: (payload: WsWelcomePayload) => void):
|
||||
};
|
||||
}
|
||||
|
||||
export function onServerStateUpdate(listener: (state: unknown) => void): () => void {
|
||||
stateListeners.add(listener);
|
||||
if (lastStateSnapshot) {
|
||||
try {
|
||||
listener(lastStateSnapshot);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
stateListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
if (instance) return instance.api;
|
||||
|
||||
@@ -63,16 +47,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.stateUpdated, (data) => {
|
||||
lastStateSnapshot = data;
|
||||
for (const listener of stateListeners) {
|
||||
try {
|
||||
listener(data);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const api: NativeApi = {
|
||||
todos: {
|
||||
@@ -121,7 +95,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, input),
|
||||
revertToCheckpoint: (input) =>
|
||||
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
|
||||
onEvent: () => () => {},
|
||||
onEvent: (callback) =>
|
||||
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
|
||||
},
|
||||
projects: {
|
||||
list: () => transport.request(WS_METHODS.projectsList),
|
||||
@@ -174,13 +149,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
},
|
||||
state: {
|
||||
getSnapshot: () => transport.request(WS_METHODS.stateGetSnapshot),
|
||||
createThread: (input) => transport.request(WS_METHODS.stateCreateThread, input),
|
||||
deleteThread: (input) => transport.request(WS_METHODS.stateDeleteThread, input),
|
||||
markThreadVisited: (input) => transport.request(WS_METHODS.stateMarkThreadVisited, input),
|
||||
setRuntimeMode: (input) => transport.request(WS_METHODS.stateSetRuntimeMode, input),
|
||||
},
|
||||
};
|
||||
|
||||
instance = { api, transport };
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
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" }]],
|
||||
},
|
||||
}),
|
||||
tailwindcss(),
|
||||
],
|
||||
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 ?? ""),
|
||||
},
|
||||
experimental: {
|
||||
enableNativePlugin: true,
|
||||
},
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
},
|
||||
server: {
|
||||
port,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
// Explicit config so Vite's HMR WebSocket connects reliably
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host: "localhost",
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
emptyOutDir: true,
|
||||
},
|
||||
});
|
||||
@@ -15,9 +15,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 ?? ""),
|
||||
|
||||
|
Before Width: | Height: | Size: 1.3 MiB |
|
Before Width: | Height: | Size: 4.5 MiB |
@@ -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 |
|
Before Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 105 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 1.1 MiB |
|
Before Width: | Height: | Size: 13 MiB |
|
Before Width: | Height: | Size: 14 KiB |
@@ -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 |
|
Before Width: | Height: | Size: 1.1 MiB |
@@ -16,7 +16,7 @@
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"electron": "40.6.0",
|
||||
"electron": "33.4.11",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.2",
|
||||
@@ -34,9 +34,6 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/core": "workspace:*",
|
||||
"@t3tools/infra-sqlite": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
@@ -97,33 +94,6 @@
|
||||
"typescript": "^5.7.3",
|
||||
},
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@t3tools/core",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"effect": "^3.18.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
"packages/infra-sqlite": {
|
||||
"name": "@t3tools/infra-sqlite",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"effect": "^3.18.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
|
||||
@@ -174,14 +144,6 @@
|
||||
|
||||
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@floating-ui/utils": "^0.2.10", "reselect": "^5.1.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-oYC7w0gp76RI5MxprlGLV0wze0SErZaRl3AAkeP3OnNB/UBMb6RqNf6ZSIlxOc9Qp68Ab3C2VOcJQyRs7Xc7Vw=="],
|
||||
|
||||
"@effect/experimental": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/platform": "^0.94.0", "effect": "^3.19.13", "ioredis": "^5", "lmdb": "^3" }, "optionalPeers": ["ioredis", "lmdb"] }, "sha512-IEP9sapjF6rFy5TkoqDPc86st/fnqUfjT7Xa3pWJrFGr1hzaMXHo+mWsYOZS9LAOVKnpHuVziDK97EP5qsCHVA=="],
|
||||
|
||||
"@effect/platform": ["@effect/[email protected]", "", { "dependencies": { "find-my-way-ts": "^0.1.6", "msgpackr": "^1.11.4", "multipasta": "^0.2.7" }, "peerDependencies": { "effect": "^3.19.17" } }, "sha512-z05APUiDDPbodhTkH/RJqOLoCU11bU2IZLfcwLFrld03+ob1VeqRnELQlmueLIYm6NZifHAtjl32V+GRt34y4A=="],
|
||||
|
||||
"@effect/sql": ["@effect/[email protected]", "", { "dependencies": { "uuid": "^11.0.3" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.0", "effect": "^3.19.13" } }, "sha512-9UEKR+z+MrI/qMAmSvb/RiD9KlgIazjZUCDSpwNgm0lEK9/Q6ExEyfziiYFVCPiptp52cBw8uBHRic8hHnwqXA=="],
|
||||
|
||||
"@effect/sql-sqlite-node": ["@effect/[email protected]", "", { "dependencies": { "better-sqlite3": "^12.6.2" }, "peerDependencies": { "@effect/experimental": "^0.58.0", "@effect/platform": "^0.94.4", "@effect/sql": "^0.49.0", "effect": "^3.19.16" } }, "sha512-L7DlHcOVl9/9V5stttFyv9wjvA9PBbaXwsp9pU+KN8KqokWgAVBNBEDf/dVfboUrynbDpDWwMU9SJmRJ1LXASQ=="],
|
||||
|
||||
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
|
||||
|
||||
"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
|
||||
@@ -282,18 +244,6 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="],
|
||||
|
||||
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],
|
||||
|
||||
"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],
|
||||
|
||||
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
|
||||
@@ -468,12 +418,8 @@
|
||||
|
||||
"@t3tools/contracts": ["@t3tools/contracts@workspace:packages/contracts"],
|
||||
|
||||
"@t3tools/core": ["@t3tools/core@workspace:packages/core"],
|
||||
|
||||
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
|
||||
|
||||
"@t3tools/infra-sqlite": ["@t3tools/infra-sqlite@workspace:packages/infra-sqlite"],
|
||||
|
||||
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
|
||||
|
||||
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "enhanced-resolve": "^5.18.3", "jiti": "^2.6.1", "lightningcss": "1.30.2", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.1.18" } }, "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ=="],
|
||||
@@ -572,7 +518,7 @@
|
||||
|
||||
"@types/ms": ["@types/[email protected]", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
|
||||
|
||||
"@types/node": ["@types/node@25.3.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A=="],
|
||||
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
|
||||
|
||||
@@ -636,28 +582,18 @@
|
||||
|
||||
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
|
||||
|
||||
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="],
|
||||
|
||||
"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA=="],
|
||||
|
||||
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
|
||||
|
||||
"bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
|
||||
|
||||
"birpc": ["[email protected]", "", {}, "sha512-LShSxJP0KTmd101b6DRyGBj57LZxSDYWKitQNW/mi8GRMvZb078Uf9+pveax1DrVL89vm7mWe+TovdI/UDOuPw=="],
|
||||
|
||||
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
|
||||
|
||||
"boolean": ["[email protected]", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
|
||||
|
||||
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
|
||||
|
||||
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
|
||||
|
||||
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
|
||||
|
||||
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
@@ -688,8 +624,6 @@
|
||||
|
||||
"chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
|
||||
|
||||
"chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
|
||||
|
||||
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
|
||||
|
||||
"cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
|
||||
@@ -722,8 +656,6 @@
|
||||
|
||||
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
|
||||
|
||||
"deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
|
||||
|
||||
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
|
||||
|
||||
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
|
||||
@@ -754,9 +686,7 @@
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"effect": ["effect@3.19.19", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-Yc8U/SVXo2dHnaP7zNBlAo83h/nzSJpi7vph6Hzyl4ulgMBIgPmz3UzOjb9sBgpFE00gC0iETR244sfXDNLHRg=="],
|
||||
|
||||
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
|
||||
"electron": ["elect[email protected].11", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^20.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-xmdAs5QWRkInC7TpXGNvzo/7exojubk+72jn1oJL7keNeIlw7xNglf8TGtJtkR4rWC5FJq0oXiIXPS9BcK2Irg=="],
|
||||
|
||||
"electron-to-chromium": ["[email protected]", "", {}, "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A=="],
|
||||
|
||||
@@ -796,32 +726,22 @@
|
||||
|
||||
"estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
|
||||
|
||||
"expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
|
||||
|
||||
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
|
||||
|
||||
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
|
||||
|
||||
"extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
|
||||
|
||||
"fast-check": ["[email protected]", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
|
||||
|
||||
"fd-slicer": ["[email protected]", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
|
||||
|
||||
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
"file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
|
||||
|
||||
"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
|
||||
|
||||
"find-my-way-ts": ["[email protected]", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
|
||||
|
||||
"follow-redirects": ["[email protected]", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
|
||||
|
||||
"form-data": ["[email protected]", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
|
||||
|
||||
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
|
||||
|
||||
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
@@ -840,8 +760,6 @@
|
||||
|
||||
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
|
||||
|
||||
"github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
|
||||
|
||||
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"global-agent": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
|
||||
@@ -890,16 +808,10 @@
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
|
||||
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
|
||||
|
||||
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
|
||||
|
||||
"import-without-cache": ["[email protected]", "", {}, "sha512-B6Lc2s6yApwnD2/pMzFh/d5AVjdsDXjgkeJ766FmFuJELIGHNycKRj+l3A39yZPM4CchqNCB4RITEAYB1KUM6A=="],
|
||||
|
||||
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
|
||||
|
||||
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
|
||||
|
||||
"is-alphabetical": ["[email protected]", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
|
||||
@@ -1094,30 +1006,16 @@
|
||||
|
||||
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
|
||||
|
||||
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
|
||||
|
||||
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
|
||||
|
||||
"msw": ["[email protected]", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-G3VUymSE0/iegFnuipujpwyTM2GuZAKXNeerUSrG2+Eg391wW63xFs5ixWsK9MWzr1AGoSkYGmyAzNgbR3+urw=="],
|
||||
|
||||
"multipasta": ["[email protected]", "", {}, "sha512-KPA58d68KgGil15oDqXjkUBEBYc00XvbPj5/X+dyzeo/lWm9Nc25pQRlf1D+gv4OpK7NM0J1odrbu9JNNGvynA=="],
|
||||
|
||||
"mute-stream": ["[email protected]", "", {}, "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA=="],
|
||||
|
||||
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
|
||||
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
|
||||
|
||||
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
|
||||
|
||||
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
|
||||
|
||||
"node-gyp-build-optional-packages": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
|
||||
|
||||
"node-pty": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
|
||||
|
||||
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
|
||||
@@ -1162,8 +1060,6 @@
|
||||
|
||||
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
|
||||
|
||||
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
|
||||
|
||||
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
|
||||
|
||||
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
|
||||
@@ -1174,14 +1070,10 @@
|
||||
|
||||
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
|
||||
|
||||
"pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
|
||||
|
||||
"quansync": ["[email protected]", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
|
||||
|
||||
"quick-lru": ["[email protected]", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
|
||||
|
||||
"rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
|
||||
|
||||
"react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
|
||||
|
||||
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
|
||||
@@ -1190,8 +1082,6 @@
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
|
||||
"readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
|
||||
|
||||
"readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
|
||||
|
||||
"recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],
|
||||
@@ -1242,8 +1132,6 @@
|
||||
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
|
||||
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||
@@ -1262,10 +1150,6 @@
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
|
||||
|
||||
"simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -1284,14 +1168,10 @@
|
||||
|
||||
"string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
|
||||
|
||||
"stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
|
||||
|
||||
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
|
||||
|
||||
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
|
||||
|
||||
"style-to-object": ["[email protected]", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
|
||||
@@ -1312,10 +1192,6 @@
|
||||
|
||||
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
|
||||
|
||||
"tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
|
||||
|
||||
"tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
|
||||
|
||||
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
|
||||
|
||||
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
|
||||
@@ -1350,8 +1226,6 @@
|
||||
|
||||
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
|
||||
|
||||
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
|
||||
|
||||
"turbo": ["[email protected]", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.7", "turbo-darwin-arm64": "2.8.7", "turbo-linux-64": "2.8.7", "turbo-linux-arm64": "2.8.7", "turbo-windows-64": "2.8.7", "turbo-windows-arm64": "2.8.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RBLh5caMAu1kFdTK1jgH2gH/z+jFsvX5rGbhgJ9nlIAWXSvxlzwId05uDlBA1+pBd3wO/UaKYzaQZQBXDd7kcA=="],
|
||||
|
||||
"turbo-darwin-64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Xr4TO/oDDwoozbDtBvunb66g//WK8uHRygl72vUthuwzmiw48pil4IuoG/QbMHd9RE8aBnVmzC0WZEWk/WWt3A=="],
|
||||
@@ -1372,7 +1246,7 @@
|
||||
|
||||
"unconfig-core": ["[email protected]", "", { "dependencies": { "@quansync/fs": "^1.0.0", "quansync": "^1.0.0" } }, "sha512-VgPCvLWugINbXvMQDf8Jh0mlbvNjNC6eSUziHsBCMpxR05OPrNrvDnyatdMjRgcHaaNsCqz+wjNXxNw1kRLHUg=="],
|
||||
|
||||
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
@@ -1402,10 +1276,6 @@
|
||||
|
||||
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
|
||||
|
||||
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
|
||||
|
||||
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
|
||||
|
||||
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
|
||||
@@ -1472,8 +1342,6 @@
|
||||
|
||||
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@t3tools/desktop/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" }, "bundled": true }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
|
||||
@@ -1498,16 +1366,6 @@
|
||||
|
||||
"@types/babel__template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
|
||||
|
||||
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/keyv/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/responselike/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@types/yauzl/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"@vitejs/plugin-react/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
|
||||
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
@@ -1518,7 +1376,7 @@
|
||||
|
||||
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
|
||||
|
||||
"electron/@types/node": ["@types/node@24.10.13", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
|
||||
"electron/@types/node": ["@types/[email protected]9.33", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw=="],
|
||||
|
||||
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
|
||||
|
||||
@@ -1534,8 +1392,6 @@
|
||||
|
||||
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
|
||||
|
||||
"t3/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
|
||||
|
||||
"unixify/normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
|
||||
|
||||
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
|
||||
@@ -1544,8 +1400,6 @@
|
||||
|
||||
"@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"@t3tools/desktop/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA=="],
|
||||
@@ -1568,20 +1422,6 @@
|
||||
|
||||
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
|
||||
|
||||
"@types/cacheable-request/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/keyv/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/responselike/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"electron/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
|
||||
|
||||
"t3/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,6 @@
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"dist:desktop:dmg": "node scripts/build-desktop-dmg.mjs",
|
||||
"dist:desktop:dmg:arm64": "node scripts/build-desktop-dmg.mjs --arch arm64",
|
||||
"dist:desktop:dmg:x64": "node scripts/build-desktop-dmg.mjs --arch x64",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
||||
},
|
||||
@@ -34,8 +31,7 @@
|
||||
"vitest": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"bun": "^1.3.9",
|
||||
"node": "^24.13.1"
|
||||
"bun": ">=1.3.9"
|
||||
},
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
@@ -42,7 +42,6 @@ import type {
|
||||
ProjectUpdateScriptsResult,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
type RuntimeMode = "approval-required" | "full-access";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -141,19 +140,4 @@ export interface NativeApi {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
};
|
||||
state: {
|
||||
getSnapshot: () => Promise<unknown>;
|
||||
createThread: (input: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}) => Promise<unknown>;
|
||||
deleteThread: (input: { id: string }) => Promise<unknown>;
|
||||
markThreadVisited: (input: { threadId: string; visitedAt?: string }) => Promise<unknown>;
|
||||
setRuntimeMode: (input: { mode: RuntimeMode }) => Promise<unknown>;
|
||||
};
|
||||
}
|
||||
@@ -37,28 +37,6 @@ describe("providerSessionStartInputSchema", () => {
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("accepts optional codex binary and home path overrides", () => {
|
||||
const parsed = providerSessionStartInputSchema.parse({
|
||||
codexBinaryPath: "/opt/codex/bin/codex",
|
||||
codexHomePath: "/Users/theo/.codex",
|
||||
});
|
||||
expect(parsed.codexBinaryPath).toBe("/opt/codex/bin/codex");
|
||||
expect(parsed.codexHomePath).toBe("/Users/theo/.codex");
|
||||
});
|
||||
|
||||
it("rejects blank codex overrides", () => {
|
||||
expect(() =>
|
||||
providerSessionStartInputSchema.parse({
|
||||
codexBinaryPath: " ",
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
providerSessionStartInputSchema.parse({
|
||||
codexHomePath: " ",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerSendTurnInputSchema", () => {
|
||||
|
||||
@@ -46,13 +46,10 @@ export const providerSessionSchema = z.object({
|
||||
});
|
||||
|
||||
export const providerSessionStartInputSchema = z.object({
|
||||
uiThreadId: z.string().trim().min(1).optional(),
|
||||
provider: providerKindSchema.default("codex"),
|
||||
cwd: z.string().min(1).optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
resumeThreadId: z.string().trim().min(1).optional(),
|
||||
codexBinaryPath: z.string().trim().min(1).optional(),
|
||||
codexHomePath: z.string().trim().min(1).optional(),
|
||||
approvalPolicy: providerApprovalPolicySchema.default("never"),
|
||||
sandboxMode: providerSandboxModeSchema.default("workspace-write"),
|
||||
});
|
||||
@@ -81,7 +78,6 @@ export const providerSendTurnAttachmentInputSchema = z.discriminatedUnion("type"
|
||||
|
||||
export const providerSendTurnInputSchema = z
|
||||
.object({
|
||||
uiThreadId: z.string().trim().min(1).optional(),
|
||||
sessionId: z.string().min(1),
|
||||
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
|
||||
attachments: z
|
||||
|
||||
@@ -46,13 +46,6 @@ export const WS_METHODS = {
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
|
||||
// Server-authoritative state
|
||||
stateGetSnapshot: "state.getSnapshot",
|
||||
stateCreateThread: "state.createThread",
|
||||
stateDeleteThread: "state.deleteThread",
|
||||
stateMarkThreadVisited: "state.markThreadVisited",
|
||||
stateSetRuntimeMode: "state.setRuntimeMode",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
@@ -61,7 +54,6 @@ export const WS_CHANNELS = {
|
||||
providerEvent: "providers.event",
|
||||
terminalEvent: "terminal.event",
|
||||
serverWelcome: "server.welcome",
|
||||
stateUpdated: "state.updated",
|
||||
} as const;
|
||||
|
||||
// ── Client → Server (request) ────────────────────────────────────────
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@t3tools/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "^3.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import type { NewDomainEvent } from "../domain/events";
|
||||
import type { AppViewState } from "../domain/models";
|
||||
|
||||
function eventFromCommand(
|
||||
command: AnyDomainCommand,
|
||||
eventType: NewDomainEvent["type"],
|
||||
payload: NewDomainEvent["payload"],
|
||||
streamId: string,
|
||||
): NewDomainEvent {
|
||||
return {
|
||||
streamId,
|
||||
type: eventType,
|
||||
payload,
|
||||
occurredAt: command.issuedAt,
|
||||
...(command.id ? { causationId: command.id } : {}),
|
||||
...(command.correlationId ? { correlationId: command.correlationId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function streamIdFromCommand(command: AnyDomainCommand): string {
|
||||
switch (command.type) {
|
||||
case "app.bootstrap":
|
||||
case "runtime.setMode":
|
||||
return "app";
|
||||
case "project.add":
|
||||
case "project.remove":
|
||||
case "project.updateScripts":
|
||||
return `project:${command.payload.id}`;
|
||||
case "thread.create":
|
||||
case "thread.delete":
|
||||
return `thread:${command.payload.id}`;
|
||||
case "thread.addUserMessage":
|
||||
case "thread.updateProviderSession":
|
||||
case "thread.recordProviderEvent":
|
||||
case "thread.setBranch":
|
||||
case "thread.setTerminalActivity":
|
||||
case "thread.markVisited":
|
||||
return `thread:${command.payload.threadId}`;
|
||||
default:
|
||||
return "app";
|
||||
}
|
||||
}
|
||||
|
||||
export function decide(command: AnyDomainCommand, currentState: AppViewState): ReadonlyArray<NewDomainEvent> {
|
||||
switch (command.type) {
|
||||
case "app.bootstrap": {
|
||||
if (currentState.projects.length > 0) return [];
|
||||
return [eventFromCommand(command, "app.bootstrapped", command.payload, streamIdFromCommand(command))];
|
||||
}
|
||||
case "project.add":
|
||||
return [eventFromCommand(command, "project.added", command.payload, streamIdFromCommand(command))];
|
||||
case "project.remove":
|
||||
return [eventFromCommand(command, "project.removed", command.payload, streamIdFromCommand(command))];
|
||||
case "project.updateScripts":
|
||||
return [eventFromCommand(command, "project.scriptsUpdated", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.create":
|
||||
return [eventFromCommand(command, "thread.created", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.delete":
|
||||
return [eventFromCommand(command, "thread.deleted", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.addUserMessage":
|
||||
return [eventFromCommand(command, "thread.userMessageAdded", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.updateProviderSession":
|
||||
return [eventFromCommand(command, "thread.providerSessionUpdated", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.recordProviderEvent":
|
||||
return [eventFromCommand(command, "thread.providerEventRecorded", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.setBranch":
|
||||
return [eventFromCommand(command, "thread.branchSet", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.setTerminalActivity":
|
||||
return [eventFromCommand(command, "thread.terminalActivitySet", command.payload, streamIdFromCommand(command))];
|
||||
case "thread.markVisited":
|
||||
return [eventFromCommand(command, "thread.markVisited", command.payload, streamIdFromCommand(command))];
|
||||
case "runtime.setMode":
|
||||
return [eventFromCommand(command, "runtime.modeSet", command.payload, streamIdFromCommand(command))];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { emptyAppViewState, type AppViewState } from "../domain/models";
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import { decide } from "./decide";
|
||||
import type { EventStorePort, ProjectionStorePort } from "../ports";
|
||||
import { QueueProjector } from "./projector";
|
||||
import { reduceEvents } from "../projections/reducer";
|
||||
|
||||
export class OrchestrationEngine {
|
||||
constructor(
|
||||
private readonly eventStore: EventStorePort,
|
||||
projectionStore: ProjectionStorePort,
|
||||
private readonly projector: QueueProjector,
|
||||
) {
|
||||
this.projectionStore = projectionStore;
|
||||
}
|
||||
|
||||
private readonly projectionStore: ProjectionStorePort;
|
||||
|
||||
async start(): Promise<void> {
|
||||
const state = await this.projectionStore.readState();
|
||||
if (!state) {
|
||||
const allEvents = await this.eventStore.loadAll();
|
||||
const next = allEvents.length === 0 ? emptyAppViewState() : reduceEvents(allEvents, emptyAppViewState());
|
||||
await this.projectionStore.writeState(next);
|
||||
}
|
||||
await this.projector.start();
|
||||
const pending = await this.eventStore.loadAfterPosition((await this.currentState()).lastPosition);
|
||||
if (pending.length > 0) {
|
||||
await this.projector.enqueue(pending);
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.projector.stop();
|
||||
}
|
||||
|
||||
async execute(command: AnyDomainCommand): Promise<AppViewState> {
|
||||
const current = await this.currentState();
|
||||
const pending = decide(command, current);
|
||||
if (pending.length === 0) return current;
|
||||
const appended = await this.eventStore.append(pending);
|
||||
await this.projector.enqueue(appended);
|
||||
return this.currentState();
|
||||
}
|
||||
|
||||
async currentState(): Promise<AppViewState> {
|
||||
return this.projector.readState();
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import type { StateUpdatedNotification } from "../domain/events";
|
||||
import type { FanoutPort } from "../ports";
|
||||
|
||||
interface Sink<T> {
|
||||
push(value: T): void;
|
||||
close(): void;
|
||||
iterable: AsyncIterable<T>;
|
||||
}
|
||||
|
||||
function createSink<T>(): Sink<T> {
|
||||
const queue: T[] = [];
|
||||
const waiters: Array<(value: IteratorResult<T>) => void> = [];
|
||||
let closed = false;
|
||||
const push = (value: T) => {
|
||||
if (closed) return;
|
||||
const waiter = waiters.shift();
|
||||
if (waiter) {
|
||||
waiter({ value, done: false });
|
||||
return;
|
||||
}
|
||||
queue.push(value);
|
||||
};
|
||||
const close = () => {
|
||||
closed = true;
|
||||
while (waiters.length > 0) {
|
||||
const waiter = waiters.shift();
|
||||
waiter?.({ value: undefined as never, done: true });
|
||||
}
|
||||
};
|
||||
const iterable: AsyncIterable<T> = {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
async next() {
|
||||
if (queue.length > 0) {
|
||||
return { value: queue.shift() as T, done: false };
|
||||
}
|
||||
if (closed) {
|
||||
return { value: undefined as never, done: true };
|
||||
}
|
||||
return new Promise<IteratorResult<T>>((resolve) => {
|
||||
waiters.push(resolve);
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
return { push, close, iterable };
|
||||
}
|
||||
|
||||
export class EffectFanout implements FanoutPort {
|
||||
private readonly sinks = new Set<Sink<StateUpdatedNotification>>();
|
||||
|
||||
async publish(notification: StateUpdatedNotification): Promise<void> {
|
||||
for (const sink of this.sinks) {
|
||||
sink.push(notification);
|
||||
}
|
||||
}
|
||||
|
||||
async subscribe(): Promise<AsyncIterable<StateUpdatedNotification>> {
|
||||
const sink = createSink<StateUpdatedNotification>();
|
||||
this.sinks.add(sink);
|
||||
return sink.iterable;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { DomainEventEnvelope } from "../domain/events";
|
||||
import { emptyAppViewState, type AppViewState } from "../domain/models";
|
||||
import type { FanoutPort, ProjectionStorePort } from "../ports";
|
||||
import { reduceEvents } from "../projections/reducer";
|
||||
|
||||
export class QueueProjector {
|
||||
private readonly queue: ReadonlyArray<DomainEventEnvelope>[] = [];
|
||||
private processing = false;
|
||||
private stopSignal = false;
|
||||
|
||||
constructor(
|
||||
private readonly projectionStore: ProjectionStorePort,
|
||||
private readonly fanout: FanoutPort,
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.processing) return;
|
||||
this.stopSignal = false;
|
||||
this.processing = true;
|
||||
void this.drain();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stopSignal = true;
|
||||
this.processing = false;
|
||||
}
|
||||
|
||||
async enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void> {
|
||||
if (events.length === 0) return;
|
||||
this.queue.push(events);
|
||||
if (this.processing) {
|
||||
void this.drain();
|
||||
}
|
||||
}
|
||||
|
||||
async readState(): Promise<AppViewState> {
|
||||
return (await this.projectionStore.readState()) ?? emptyAppViewState();
|
||||
}
|
||||
|
||||
private async drain(): Promise<void> {
|
||||
if (!this.processing) return;
|
||||
while (!this.stopSignal && this.queue.length > 0) {
|
||||
const chunk = this.queue.shift();
|
||||
if (!chunk || chunk.length === 0) continue;
|
||||
const current = (await this.projectionStore.readState()) ?? emptyAppViewState();
|
||||
const next = reduceEvents(chunk, current);
|
||||
await this.projectionStore.writeState(next);
|
||||
await this.fanout.publish({ state: next, events: chunk });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { ProjectScriptSchema, ProviderEventSchema, ProviderSessionViewSchema, RuntimeModeSchema } from "./models";
|
||||
|
||||
export const CommandTypeSchema = Schema.Literal(
|
||||
"app.bootstrap",
|
||||
"project.add",
|
||||
"project.remove",
|
||||
"project.updateScripts",
|
||||
"thread.create",
|
||||
"thread.delete",
|
||||
"thread.addUserMessage",
|
||||
"thread.updateProviderSession",
|
||||
"thread.recordProviderEvent",
|
||||
"thread.setBranch",
|
||||
"thread.setTerminalActivity",
|
||||
"thread.markVisited",
|
||||
"runtime.setMode",
|
||||
);
|
||||
export type CommandType = Schema.Schema.Type<typeof CommandTypeSchema>;
|
||||
|
||||
export interface DomainCommand<TPayload> {
|
||||
readonly id: string;
|
||||
readonly type: CommandType;
|
||||
readonly payload: TPayload;
|
||||
readonly issuedAt: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface AppBootstrapCommand
|
||||
extends DomainCommand<{
|
||||
cwd: string;
|
||||
projectName: string;
|
||||
}> {
|
||||
readonly type: "app.bootstrap";
|
||||
}
|
||||
|
||||
export interface ProjectAddCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
|
||||
}> {
|
||||
readonly type: "project.add";
|
||||
}
|
||||
|
||||
export interface ProjectRemoveCommand extends DomainCommand<{ id: string }> {
|
||||
readonly type: "project.remove";
|
||||
}
|
||||
|
||||
export interface ProjectUpdateScriptsCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
scripts: Schema.Schema.Type<typeof ProjectScriptSchema>[];
|
||||
}> {
|
||||
readonly type: "project.updateScripts";
|
||||
}
|
||||
|
||||
export interface ThreadCreateCommand
|
||||
extends DomainCommand<{
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}> {
|
||||
readonly type: "thread.create";
|
||||
}
|
||||
|
||||
export interface ThreadDeleteCommand extends DomainCommand<{ id: string }> {
|
||||
readonly type: "thread.delete";
|
||||
}
|
||||
|
||||
export interface ThreadAddUserMessageCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
previewUrl?: string;
|
||||
}>;
|
||||
}> {
|
||||
readonly type: "thread.addUserMessage";
|
||||
}
|
||||
|
||||
export interface ThreadUpdateProviderSessionCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
session: Schema.Schema.Type<typeof ProviderSessionViewSchema> | null;
|
||||
}> {
|
||||
readonly type: "thread.updateProviderSession";
|
||||
}
|
||||
|
||||
export interface ThreadRecordProviderEventCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
event: Schema.Schema.Type<typeof ProviderEventSchema>;
|
||||
}> {
|
||||
readonly type: "thread.recordProviderEvent";
|
||||
}
|
||||
|
||||
export interface ThreadSetBranchCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}> {
|
||||
readonly type: "thread.setBranch";
|
||||
}
|
||||
|
||||
export interface ThreadSetTerminalActivityCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
running: boolean;
|
||||
}> {
|
||||
readonly type: "thread.setTerminalActivity";
|
||||
}
|
||||
|
||||
export interface ThreadMarkVisitedCommand
|
||||
extends DomainCommand<{
|
||||
threadId: string;
|
||||
visitedAt: string;
|
||||
}> {
|
||||
readonly type: "thread.markVisited";
|
||||
}
|
||||
|
||||
export interface RuntimeSetModeCommand
|
||||
extends DomainCommand<{
|
||||
mode: Schema.Schema.Type<typeof RuntimeModeSchema>;
|
||||
}> {
|
||||
readonly type: "runtime.setMode";
|
||||
}
|
||||
|
||||
export type AnyDomainCommand =
|
||||
| AppBootstrapCommand
|
||||
| ProjectAddCommand
|
||||
| ProjectRemoveCommand
|
||||
| ProjectUpdateScriptsCommand
|
||||
| ThreadCreateCommand
|
||||
| ThreadDeleteCommand
|
||||
| ThreadAddUserMessageCommand
|
||||
| ThreadUpdateProviderSessionCommand
|
||||
| ThreadRecordProviderEventCommand
|
||||
| ThreadSetBranchCommand
|
||||
| ThreadSetTerminalActivityCommand
|
||||
| ThreadMarkVisitedCommand
|
||||
| RuntimeSetModeCommand;
|
||||
@@ -1,149 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import {
|
||||
type AppViewState,
|
||||
ProjectScriptSchema,
|
||||
ProviderEventSchema,
|
||||
ProviderSessionViewSchema,
|
||||
RuntimeModeSchema,
|
||||
} from "./models";
|
||||
|
||||
export const DomainEventTypeSchema = Schema.Literal(
|
||||
"app.bootstrapped",
|
||||
"project.added",
|
||||
"project.removed",
|
||||
"project.scriptsUpdated",
|
||||
"thread.created",
|
||||
"thread.deleted",
|
||||
"thread.userMessageAdded",
|
||||
"thread.providerSessionUpdated",
|
||||
"thread.providerEventRecorded",
|
||||
"thread.branchSet",
|
||||
"thread.terminalActivitySet",
|
||||
"thread.markVisited",
|
||||
"runtime.modeSet",
|
||||
);
|
||||
export type DomainEventType = Schema.Schema.Type<typeof DomainEventTypeSchema>;
|
||||
|
||||
const AppBootstrappedPayloadSchema = Schema.Struct({
|
||||
cwd: Schema.String,
|
||||
projectName: Schema.String,
|
||||
});
|
||||
|
||||
const ProjectAddedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
cwd: Schema.String,
|
||||
model: Schema.String,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
|
||||
const ProjectRemovedPayloadSchema = Schema.Struct({ id: Schema.String });
|
||||
|
||||
const ProjectScriptsUpdatedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
|
||||
const ThreadCreatedPayloadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
projectId: Schema.String,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ThreadDeletedPayloadSchema = Schema.Struct({ id: Schema.String });
|
||||
|
||||
const ThreadUserMessageAddedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
messageId: Schema.String,
|
||||
text: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
attachments: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
previewUrl: Schema.optional(Schema.String),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const ThreadProviderSessionUpdatedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
session: Schema.NullOr(ProviderSessionViewSchema),
|
||||
});
|
||||
|
||||
const ThreadProviderEventRecordedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
event: ProviderEventSchema,
|
||||
});
|
||||
|
||||
const ThreadBranchSetPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ThreadTerminalActivitySetPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
running: Schema.Boolean,
|
||||
});
|
||||
|
||||
const ThreadMarkVisitedPayloadSchema = Schema.Struct({
|
||||
threadId: Schema.String,
|
||||
visitedAt: Schema.String,
|
||||
});
|
||||
|
||||
const RuntimeModeSetPayloadSchema = Schema.Struct({
|
||||
mode: RuntimeModeSchema,
|
||||
});
|
||||
|
||||
export type DomainEventPayload =
|
||||
| Schema.Schema.Type<typeof AppBootstrappedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectAddedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectRemovedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ProjectScriptsUpdatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadCreatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadDeletedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadUserMessageAddedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadProviderSessionUpdatedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadProviderEventRecordedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadBranchSetPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadTerminalActivitySetPayloadSchema>
|
||||
| Schema.Schema.Type<typeof ThreadMarkVisitedPayloadSchema>
|
||||
| Schema.Schema.Type<typeof RuntimeModeSetPayloadSchema>;
|
||||
|
||||
export interface DomainEventEnvelope {
|
||||
readonly eventId: string;
|
||||
readonly streamId: string;
|
||||
readonly sequence: number;
|
||||
readonly position: number;
|
||||
readonly type: DomainEventType;
|
||||
readonly occurredAt: string;
|
||||
readonly payload: DomainEventPayload;
|
||||
readonly causationId?: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface NewDomainEvent {
|
||||
readonly streamId: string;
|
||||
readonly type: DomainEventType;
|
||||
readonly payload: DomainEventPayload;
|
||||
readonly occurredAt: string;
|
||||
readonly causationId?: string;
|
||||
readonly correlationId?: string;
|
||||
}
|
||||
|
||||
export interface StateUpdatedNotification {
|
||||
readonly state: AppViewState;
|
||||
readonly events: readonly DomainEventEnvelope[];
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export const RuntimeModeSchema = Schema.Literal("approval-required", "full-access");
|
||||
export type RuntimeMode = Schema.Schema.Type<typeof RuntimeModeSchema>;
|
||||
|
||||
export const ProjectScriptSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
command: Schema.String,
|
||||
keybinding: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProjectScript = Schema.Schema.Type<typeof ProjectScriptSchema>;
|
||||
|
||||
export const ProjectViewSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
cwd: Schema.String,
|
||||
model: Schema.String,
|
||||
expanded: Schema.Boolean,
|
||||
scripts: Schema.Array(ProjectScriptSchema),
|
||||
});
|
||||
export type ProjectView = Schema.Schema.Type<typeof ProjectViewSchema>;
|
||||
|
||||
export const ChatAttachmentSchema = Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
previewUrl: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ChatAttachment = Schema.Schema.Type<typeof ChatAttachmentSchema>;
|
||||
|
||||
export const ChatMessageSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
role: Schema.Literal("user", "assistant"),
|
||||
text: Schema.String,
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachmentSchema)),
|
||||
createdAt: Schema.String,
|
||||
streaming: Schema.Boolean,
|
||||
});
|
||||
export type ChatMessage = Schema.Schema.Type<typeof ChatMessageSchema>;
|
||||
|
||||
export const SessionStatusSchema = Schema.Literal(
|
||||
"connecting",
|
||||
"ready",
|
||||
"running",
|
||||
"error",
|
||||
"closed",
|
||||
);
|
||||
export type SessionStatus = Schema.Schema.Type<typeof SessionStatusSchema>;
|
||||
|
||||
export const ProviderSessionViewSchema = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
provider: Schema.Literal("codex", "claudeCode"),
|
||||
status: SessionStatusSchema,
|
||||
cwd: Schema.optional(Schema.String),
|
||||
model: Schema.optional(Schema.String),
|
||||
threadId: Schema.optional(Schema.String),
|
||||
activeTurnId: Schema.optional(Schema.String),
|
||||
createdAt: Schema.String,
|
||||
updatedAt: Schema.String,
|
||||
lastError: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProviderSessionView = Schema.Schema.Type<typeof ProviderSessionViewSchema>;
|
||||
|
||||
export const ProviderEventSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
kind: Schema.Literal("session", "notification", "request", "error"),
|
||||
method: Schema.String,
|
||||
payload: Schema.optional(Schema.Unknown),
|
||||
createdAt: Schema.String,
|
||||
sessionId: Schema.String,
|
||||
threadId: Schema.optional(Schema.String),
|
||||
turnId: Schema.optional(Schema.String),
|
||||
itemId: Schema.optional(Schema.String),
|
||||
textDelta: Schema.optional(Schema.String),
|
||||
requestId: Schema.optional(Schema.String),
|
||||
requestKind: Schema.optional(Schema.String),
|
||||
message: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ProviderEvent = Schema.Schema.Type<typeof ProviderEventSchema>;
|
||||
|
||||
export const TurnDiffFileChangeSchema = Schema.Struct({
|
||||
path: Schema.String,
|
||||
kind: Schema.optional(Schema.String),
|
||||
additions: Schema.optional(Schema.Number),
|
||||
deletions: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type TurnDiffFileChange = Schema.Schema.Type<typeof TurnDiffFileChangeSchema>;
|
||||
|
||||
export const TurnDiffSummarySchema = Schema.Struct({
|
||||
turnId: Schema.String,
|
||||
completedAt: Schema.String,
|
||||
status: Schema.optional(Schema.String),
|
||||
files: Schema.Array(TurnDiffFileChangeSchema),
|
||||
assistantMessageId: Schema.optional(Schema.String),
|
||||
checkpointTurnCount: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type TurnDiffSummary = Schema.Schema.Type<typeof TurnDiffSummarySchema>;
|
||||
|
||||
export const ThreadTerminalGroupSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
terminalIds: Schema.Array(Schema.String),
|
||||
});
|
||||
export type ThreadTerminalGroup = Schema.Schema.Type<typeof ThreadTerminalGroupSchema>;
|
||||
|
||||
export const ThreadViewSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
codexThreadId: Schema.NullOr(Schema.String),
|
||||
projectId: Schema.String,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
terminalOpen: Schema.Boolean,
|
||||
terminalHeight: Schema.Number,
|
||||
terminalIds: Schema.Array(Schema.String),
|
||||
runningTerminalIds: Schema.Array(Schema.String),
|
||||
activeTerminalId: Schema.String,
|
||||
terminalGroups: Schema.Array(ThreadTerminalGroupSchema),
|
||||
activeTerminalGroupId: Schema.String,
|
||||
session: Schema.NullOr(ProviderSessionViewSchema),
|
||||
messages: Schema.Array(ChatMessageSchema),
|
||||
events: Schema.Array(ProviderEventSchema),
|
||||
error: Schema.NullOr(Schema.String),
|
||||
createdAt: Schema.String,
|
||||
latestTurnId: Schema.optional(Schema.String),
|
||||
latestTurnStartedAt: Schema.optional(Schema.String),
|
||||
latestTurnCompletedAt: Schema.optional(Schema.String),
|
||||
latestTurnDurationMs: Schema.optional(Schema.Number),
|
||||
lastVisitedAt: Schema.optional(Schema.String),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
turnDiffSummaries: Schema.Array(TurnDiffSummarySchema),
|
||||
});
|
||||
export type ThreadView = Schema.Schema.Type<typeof ThreadViewSchema>;
|
||||
|
||||
export const AppViewStateSchema = Schema.Struct({
|
||||
projects: Schema.Array(ProjectViewSchema),
|
||||
threads: Schema.Array(ThreadViewSchema),
|
||||
threadsHydrated: Schema.Boolean,
|
||||
runtimeMode: RuntimeModeSchema,
|
||||
lastPosition: Schema.Number,
|
||||
});
|
||||
export type AppViewState = Schema.Schema.Type<typeof AppViewStateSchema>;
|
||||
|
||||
export const emptyAppViewState = (): AppViewState => ({
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
runtimeMode: "full-access",
|
||||
lastPosition: 0,
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { AppViewState } from "./models";
|
||||
|
||||
export type DomainQuery = { readonly type: "app.getState" };
|
||||
|
||||
export interface QueryResultMap {
|
||||
"app.getState": AppViewState;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
export * from "./domain/models";
|
||||
export * from "./domain/commands";
|
||||
export * from "./domain/events";
|
||||
export * from "./domain/queries";
|
||||
export * from "./ports";
|
||||
export * from "./projections/reducer";
|
||||
export * from "./application/decide";
|
||||
export * from "./application/fanout";
|
||||
export * from "./application/projector";
|
||||
export * from "./application/engine";
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { AnyDomainCommand } from "../domain/commands";
|
||||
import type { DomainEventEnvelope, NewDomainEvent, StateUpdatedNotification } from "../domain/events";
|
||||
import type { AppViewState } from "../domain/models";
|
||||
|
||||
export interface EventStorePort {
|
||||
append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>>;
|
||||
}
|
||||
|
||||
export interface ProjectionStorePort {
|
||||
readState(): Promise<AppViewState | null>;
|
||||
writeState(state: AppViewState): Promise<void>;
|
||||
}
|
||||
|
||||
export interface FanoutPort {
|
||||
publish(notification: StateUpdatedNotification): Promise<void>;
|
||||
subscribe(): Promise<AsyncIterable<StateUpdatedNotification>>;
|
||||
}
|
||||
|
||||
export interface DeterministicProjectorPort {
|
||||
start(): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
enqueue(events: ReadonlyArray<DomainEventEnvelope>): Promise<void>;
|
||||
}
|
||||
|
||||
export interface CoreApplicationPort {
|
||||
execute(command: AnyDomainCommand): Promise<AppViewState>;
|
||||
currentState(): Promise<AppViewState>;
|
||||
}
|
||||
@@ -1,436 +0,0 @@
|
||||
import type { DomainEventEnvelope } from "../domain/events";
|
||||
import type {
|
||||
AppViewState,
|
||||
ChatMessage,
|
||||
ProviderEvent,
|
||||
ProviderSessionView,
|
||||
ThreadView,
|
||||
} from "../domain/models";
|
||||
import { emptyAppViewState } from "../domain/models";
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function eventTurnId(event: ProviderEvent): string | undefined {
|
||||
if (event.turnId) return event.turnId;
|
||||
const turn = asObject(asObject(event.payload)?.turn);
|
||||
return asString(turn?.id);
|
||||
}
|
||||
|
||||
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 evolveSession(previous: ProviderSessionView, event: ProviderEvent): ProviderSessionView {
|
||||
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 };
|
||||
}
|
||||
|
||||
function applyEventToMessages(
|
||||
previous: ReadonlyArray<ChatMessage>,
|
||||
event: ProviderEvent,
|
||||
): 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];
|
||||
const seedText = asString(item?.text) ?? "";
|
||||
return [
|
||||
...previous.filter((entry) => entry.id !== itemId),
|
||||
{
|
||||
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 idx = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (idx < 0) {
|
||||
return [
|
||||
...previous,
|
||||
{ id: itemId, role: "assistant", text: delta, createdAt: event.createdAt, streaming: true },
|
||||
];
|
||||
}
|
||||
const next = [...previous];
|
||||
const current = next[idx];
|
||||
if (!current) return [...previous];
|
||||
next[idx] = { ...current, text: `${current.text}${delta}`, streaming: true };
|
||||
return next;
|
||||
}
|
||||
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 idx = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (idx < 0) {
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: fullText ?? "",
|
||||
createdAt: event.createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
const next = [...previous];
|
||||
const current = next[idx];
|
||||
if (!current) return [...previous];
|
||||
next[idx] = { ...current, text: fullText ?? current.text, streaming: false };
|
||||
return next;
|
||||
}
|
||||
if (event.method === "turn/completed") {
|
||||
return previous.map((entry) => ({ ...entry, streaming: false }));
|
||||
}
|
||||
return [...previous];
|
||||
}
|
||||
|
||||
function defaultThread(payload: {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}): ThreadView {
|
||||
return {
|
||||
id: payload.id,
|
||||
codexThreadId: null,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: payload.createdAt,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
turnDiffSummaries: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function applyDomainEvent(state: AppViewState, event: DomainEventEnvelope): AppViewState {
|
||||
switch (event.type) {
|
||||
case "app.bootstrapped": {
|
||||
const payload = event.payload as { cwd: string; projectName: string };
|
||||
if (state.projects.length > 0)
|
||||
return { ...state, threadsHydrated: true, lastPosition: event.position };
|
||||
return {
|
||||
...state,
|
||||
projects: [
|
||||
{
|
||||
id: "bootstrap-project",
|
||||
name: payload.projectName,
|
||||
cwd: payload.cwd,
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
threadsHydrated: true,
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.added": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
|
||||
};
|
||||
if (
|
||||
state.projects.some((project) => project.id === payload.id || project.cwd === payload.cwd)
|
||||
) {
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
projects: [...state.projects, { ...payload, expanded: true }],
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.removed": {
|
||||
const payload = event.payload as { id: string };
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.filter((project) => project.id !== payload.id),
|
||||
threads: state.threads.filter((thread) => thread.projectId !== payload.id),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "project.scriptsUpdated": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
scripts: Array<{ id: string; name: string; command: string; keybinding?: string }>;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((project) =>
|
||||
project.id === payload.id ? { ...project, scripts: payload.scripts } : project,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.created": {
|
||||
const payload = event.payload as {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
if (state.threads.some((thread) => thread.id === payload.id)) {
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: [...state.threads, defaultThread(payload)],
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.deleted": {
|
||||
const payload = event.payload as { id: string };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.filter((thread) => thread.id !== payload.id),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.userMessageAdded": {
|
||||
const payload = event.payload as {
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
attachments?: Array<{
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
previewUrl?: string;
|
||||
}>;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? {
|
||||
...thread,
|
||||
messages: [
|
||||
...thread.messages,
|
||||
{
|
||||
id: payload.messageId,
|
||||
role: "user",
|
||||
text: payload.text,
|
||||
attachments: payload.attachments ? [...payload.attachments] : undefined,
|
||||
createdAt: payload.createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.providerSessionUpdated": {
|
||||
const payload = event.payload as { threadId: string; session: ProviderSessionView | null };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? {
|
||||
...thread,
|
||||
session: payload.session,
|
||||
codexThreadId: payload.session?.threadId ?? thread.codexThreadId,
|
||||
...(payload.session ? {} : { events: [], messages: [], turnDiffSummaries: [] }),
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.providerEventRecorded": {
|
||||
const payload = event.payload as { threadId: string; event: ProviderEvent };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) => {
|
||||
if (thread.id !== payload.threadId) return thread;
|
||||
const nextEvents = [payload.event, ...thread.events];
|
||||
const nextSession = thread.session
|
||||
? evolveSession(thread.session, payload.event)
|
||||
: thread.session;
|
||||
const nextMessages = applyEventToMessages(thread.messages, payload.event);
|
||||
const nextTurnId =
|
||||
payload.event.method === "turn/started"
|
||||
? (eventTurnId(payload.event) ?? thread.latestTurnId)
|
||||
: thread.latestTurnId;
|
||||
const nextTurnStartedAt =
|
||||
payload.event.method === "turn/started"
|
||||
? payload.event.createdAt
|
||||
: thread.latestTurnStartedAt;
|
||||
const nextTurnCompletedAt =
|
||||
payload.event.method === "turn/completed"
|
||||
? payload.event.createdAt
|
||||
: thread.latestTurnCompletedAt;
|
||||
const nextTurnDuration =
|
||||
payload.event.method === "turn/completed" && thread.latestTurnStartedAt
|
||||
? durationMs(thread.latestTurnStartedAt, payload.event.createdAt)
|
||||
: thread.latestTurnDurationMs;
|
||||
return {
|
||||
...thread,
|
||||
events: nextEvents,
|
||||
messages: nextMessages,
|
||||
session: nextSession,
|
||||
error:
|
||||
payload.event.kind === "error" && payload.event.message
|
||||
? payload.event.message
|
||||
: thread.error,
|
||||
latestTurnId: nextTurnId,
|
||||
latestTurnStartedAt: nextTurnStartedAt,
|
||||
latestTurnCompletedAt: nextTurnCompletedAt,
|
||||
latestTurnDurationMs: nextTurnDuration,
|
||||
};
|
||||
}),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.branchSet": {
|
||||
const payload = event.payload as {
|
||||
threadId: string;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId
|
||||
? { ...thread, branch: payload.branch, worktreePath: payload.worktreePath }
|
||||
: thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.terminalActivitySet": {
|
||||
const payload = event.payload as { threadId: string; terminalId: string; running: boolean };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) => {
|
||||
if (thread.id !== payload.threadId) return thread;
|
||||
const running = new Set(thread.runningTerminalIds);
|
||||
if (payload.running) running.add(payload.terminalId);
|
||||
else running.delete(payload.terminalId);
|
||||
const terminalIds = thread.terminalIds.includes(payload.terminalId)
|
||||
? thread.terminalIds
|
||||
: [...thread.terminalIds, payload.terminalId];
|
||||
return { ...thread, terminalIds, runningTerminalIds: [...running] };
|
||||
}),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "thread.markVisited": {
|
||||
const payload = event.payload as { threadId: string; visitedAt: string };
|
||||
return {
|
||||
...state,
|
||||
threads: state.threads.map((thread) =>
|
||||
thread.id === payload.threadId ? { ...thread, lastVisitedAt: payload.visitedAt } : thread,
|
||||
),
|
||||
lastPosition: event.position,
|
||||
};
|
||||
}
|
||||
case "runtime.modeSet": {
|
||||
const payload = event.payload as { mode: "approval-required" | "full-access" };
|
||||
return { ...state, runtimeMode: payload.mode, lastPosition: event.position };
|
||||
}
|
||||
default:
|
||||
return { ...state, lastPosition: event.position };
|
||||
}
|
||||
}
|
||||
|
||||
export function reduceEvents(
|
||||
events: ReadonlyArray<DomainEventEnvelope>,
|
||||
seed?: AppViewState,
|
||||
): AppViewState {
|
||||
return events.reduce(
|
||||
(state, event) => applyDomainEvent(state, event),
|
||||
seed ?? emptyAppViewState(),
|
||||
);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@t3tools/infra-sqlite",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/sql": "^0.49.0",
|
||||
"@effect/sql-sqlite-node": "^0.50.1",
|
||||
"@t3tools/core": "workspace:*",
|
||||
"effect": "^3.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.3.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./sqliteStore";
|
||||
@@ -1,175 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
import type { AppViewState, DomainEventEnvelope, EventStorePort, NewDomainEvent, ProjectionStorePort } from "@t3tools/core";
|
||||
|
||||
interface EventRow {
|
||||
event_id: string;
|
||||
stream_id: string;
|
||||
sequence: number;
|
||||
position: number;
|
||||
type: string;
|
||||
occurred_at: string;
|
||||
payload_json: string;
|
||||
causation_id: string | null;
|
||||
correlation_id: string | null;
|
||||
}
|
||||
|
||||
function ensureDir(filePath: string): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
|
||||
function parseState(raw: string | null): AppViewState | null {
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as AppViewState;
|
||||
}
|
||||
|
||||
export class SqliteEventStore implements EventStorePort {
|
||||
constructor(private readonly db: DatabaseSync) {}
|
||||
|
||||
async append(events: ReadonlyArray<NewDomainEvent>): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
if (events.length === 0) return [];
|
||||
const out: DomainEventEnvelope[] = [];
|
||||
this.db.exec("BEGIN IMMEDIATE TRANSACTION");
|
||||
try {
|
||||
for (const event of events) {
|
||||
const sequenceStmt = this.db.prepare(
|
||||
"SELECT COALESCE(MAX(sequence), 0) + 1 AS nextSequence FROM events WHERE stream_id = ?",
|
||||
);
|
||||
const sequenceRow = sequenceStmt.get(event.streamId) as { nextSequence: number };
|
||||
const insert = this.db.prepare(
|
||||
[
|
||||
"INSERT INTO events(",
|
||||
"event_id, stream_id, sequence, type, occurred_at, payload_json, causation_id, correlation_id",
|
||||
") VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
].join(" "),
|
||||
);
|
||||
const eventId = crypto.randomUUID();
|
||||
insert.run(
|
||||
eventId,
|
||||
event.streamId,
|
||||
sequenceRow.nextSequence,
|
||||
event.type,
|
||||
event.occurredAt,
|
||||
JSON.stringify(event.payload),
|
||||
event.causationId ?? null,
|
||||
event.correlationId ?? null,
|
||||
);
|
||||
const positionRow = this.db
|
||||
.prepare("SELECT position FROM events WHERE event_id = ?")
|
||||
.get(eventId) as { position: number };
|
||||
out.push({
|
||||
eventId,
|
||||
streamId: event.streamId,
|
||||
sequence: sequenceRow.nextSequence,
|
||||
position: positionRow.position,
|
||||
type: event.type,
|
||||
occurredAt: event.occurredAt,
|
||||
payload: event.payload,
|
||||
...(event.causationId ? { causationId: event.causationId } : {}),
|
||||
...(event.correlationId ? { correlationId: event.correlationId } : {}),
|
||||
});
|
||||
}
|
||||
this.db.exec("COMMIT");
|
||||
return out;
|
||||
} catch (error) {
|
||||
this.db.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async loadAll(): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
const stmt = this.db.prepare(
|
||||
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events ORDER BY position ASC",
|
||||
);
|
||||
const rows = stmt.all() as unknown as EventRow[];
|
||||
return rows.map(mapEventRow);
|
||||
}
|
||||
|
||||
async loadAfterPosition(position: number): Promise<ReadonlyArray<DomainEventEnvelope>> {
|
||||
const stmt = this.db.prepare(
|
||||
"SELECT event_id, stream_id, sequence, position, type, occurred_at, payload_json, causation_id, correlation_id FROM events WHERE position > ? ORDER BY position ASC",
|
||||
);
|
||||
const rows = stmt.all(position) as unknown as EventRow[];
|
||||
return rows.map(mapEventRow);
|
||||
}
|
||||
}
|
||||
|
||||
function mapEventRow(row: EventRow): DomainEventEnvelope {
|
||||
return {
|
||||
eventId: row.event_id,
|
||||
streamId: row.stream_id,
|
||||
sequence: row.sequence,
|
||||
position: row.position,
|
||||
type: row.type as DomainEventEnvelope["type"],
|
||||
occurredAt: row.occurred_at,
|
||||
payload: JSON.parse(row.payload_json) as DomainEventEnvelope["payload"],
|
||||
...(row.causation_id ? { causationId: row.causation_id } : {}),
|
||||
...(row.correlation_id ? { correlationId: row.correlation_id } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export class SqliteProjectionStore implements ProjectionStorePort {
|
||||
constructor(private readonly db: DatabaseSync) {}
|
||||
|
||||
async readState(): Promise<AppViewState | null> {
|
||||
const row = this.db
|
||||
.prepare("SELECT state_json FROM projection_state WHERE projection_name = 'app_state'")
|
||||
.get() as { state_json: string } | undefined;
|
||||
return parseState(row?.state_json ?? null);
|
||||
}
|
||||
|
||||
async writeState(state: AppViewState): Promise<void> {
|
||||
this.db
|
||||
.prepare(
|
||||
[
|
||||
"INSERT INTO projection_state(projection_name, state_json, updated_at)",
|
||||
"VALUES('app_state', ?, ?)",
|
||||
"ON CONFLICT(projection_name) DO UPDATE SET",
|
||||
"state_json = excluded.state_json,",
|
||||
"updated_at = excluded.updated_at",
|
||||
].join(" "),
|
||||
)
|
||||
.run(JSON.stringify(state), new Date().toISOString());
|
||||
}
|
||||
}
|
||||
|
||||
export function createSqliteStores(dbPath: string): {
|
||||
db: DatabaseSync;
|
||||
eventStore: SqliteEventStore;
|
||||
projectionStore: SqliteProjectionStore;
|
||||
} {
|
||||
ensureDir(dbPath);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec("PRAGMA journal_mode = WAL;");
|
||||
db.exec("PRAGMA foreign_keys = ON;");
|
||||
db.exec(
|
||||
[
|
||||
"CREATE TABLE IF NOT EXISTS events(",
|
||||
"position INTEGER PRIMARY KEY AUTOINCREMENT,",
|
||||
"event_id TEXT NOT NULL UNIQUE,",
|
||||
"stream_id TEXT NOT NULL,",
|
||||
"sequence INTEGER NOT NULL,",
|
||||
"type TEXT NOT NULL,",
|
||||
"occurred_at TEXT NOT NULL,",
|
||||
"payload_json TEXT NOT NULL,",
|
||||
"causation_id TEXT,",
|
||||
"correlation_id TEXT,",
|
||||
"UNIQUE(stream_id, sequence)",
|
||||
");",
|
||||
"CREATE INDEX IF NOT EXISTS idx_events_stream_position ON events(stream_id, position);",
|
||||
"CREATE TABLE IF NOT EXISTS projection_state(",
|
||||
"projection_name TEXT PRIMARY KEY,",
|
||||
"state_json TEXT NOT NULL,",
|
||||
"updated_at TEXT NOT NULL",
|
||||
");",
|
||||
].join(" "),
|
||||
);
|
||||
return {
|
||||
db,
|
||||
eventStore: new SqliteEventStore(db),
|
||||
projectionStore: new SqliteProjectionStore(db),
|
||||
};
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
const PRODUCTION_ICON_SOURCE = path.join(repoRoot, "assets/macos-icon-1024.png");
|
||||
|
||||
const ARCH_CHOICES = new Set(["arm64", "x64", "universal"]);
|
||||
|
||||
function printUsage() {
|
||||
console.log(`Build a shareable macOS .dmg for T3 Code desktop.
|
||||
|
||||
Usage:
|
||||
node scripts/build-desktop-dmg.mjs [options]
|
||||
|
||||
Options:
|
||||
--arch <arm64|x64|universal> Target arch (default: host arch if supported)
|
||||
--version <semver> App version in DMG metadata (default: apps/server version)
|
||||
--output-dir <path> Output folder for final artifacts (default: release)
|
||||
--skip-build Skip 'bun run build:desktop' (requires existing dist artifacts)
|
||||
--keep-stage Keep temporary staging directory
|
||||
--signed Allow automatic code signing discovery
|
||||
--help Show this message
|
||||
`);
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
console.error(`[desktop-dmg] ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const defaultArch = process.arch === "arm64" || process.arch === "x64" ? process.arch : "arm64";
|
||||
const options = {
|
||||
arch: defaultArch,
|
||||
version: null,
|
||||
skipBuild: false,
|
||||
keepStage: false,
|
||||
signed: false,
|
||||
outputDir: path.join(repoRoot, "release"),
|
||||
};
|
||||
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === "--help") {
|
||||
options.help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--skip-build") {
|
||||
options.skipBuild = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--keep-stage") {
|
||||
options.keepStage = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--signed") {
|
||||
options.signed = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--arch" || arg === "--version" || arg === "--output-dir") {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.startsWith("--")) {
|
||||
fail(`Missing value for ${arg}`);
|
||||
}
|
||||
i += 1;
|
||||
if (arg === "--arch") options.arch = value;
|
||||
if (arg === "--version") options.version = value;
|
||||
if (arg === "--output-dir") options.outputDir = path.resolve(repoRoot, value);
|
||||
continue;
|
||||
}
|
||||
fail(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
if (!ARCH_CHOICES.has(options.arch)) {
|
||||
fail(`Invalid arch '${options.arch}'. Expected one of: ${Array.from(ARCH_CHOICES).join(", ")}`);
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
async function readJson(filePath) {
|
||||
const raw = await fs.readFile(filePath, "utf8");
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
async function exists(filePath) {
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function run(command, args, { cwd, env = process.env, stdio = "inherit" } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd,
|
||||
env,
|
||||
stdio,
|
||||
});
|
||||
|
||||
child.on("error", reject);
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
reject(new Error(`${command} exited via signal ${signal}`));
|
||||
return;
|
||||
}
|
||||
if (code !== 0) {
|
||||
reject(new Error(`${command} exited with code ${code}`));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function generateMacIconSet(sourcePng, targetIcns, tmpRoot) {
|
||||
const iconsetDir = path.join(tmpRoot, "icon.iconset");
|
||||
await fs.mkdir(iconsetDir, { recursive: true });
|
||||
|
||||
const iconSizes = [16, 32, 128, 256, 512];
|
||||
for (const size of iconSizes) {
|
||||
await run(
|
||||
"sips",
|
||||
["-z", String(size), String(size), sourcePng, "--out", path.join(iconsetDir, `icon_${size}x${size}.png`)],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
const retinaSize = size * 2;
|
||||
await run(
|
||||
"sips",
|
||||
[
|
||||
"-z",
|
||||
String(retinaSize),
|
||||
String(retinaSize),
|
||||
sourcePng,
|
||||
"--out",
|
||||
path.join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
}
|
||||
|
||||
await run("iconutil", ["-c", "icns", iconsetDir, "-o", targetIcns], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function stageProductionIcons(stageResourcesDir) {
|
||||
if (!(await exists(PRODUCTION_ICON_SOURCE))) {
|
||||
fail(`Production icon source is missing at ${PRODUCTION_ICON_SOURCE}`);
|
||||
}
|
||||
|
||||
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "t3code-icon-build-"));
|
||||
try {
|
||||
const iconPngPath = path.join(stageResourcesDir, "icon.png");
|
||||
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
|
||||
await run("sips", ["-z", "512", "512", PRODUCTION_ICON_SOURCE, "--out", iconPngPath], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
await generateMacIconSet(PRODUCTION_ICON_SOURCE, iconIcnsPath, tmpRoot);
|
||||
} finally {
|
||||
await fs.rm(tmpRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function validateBundledClientAssets(clientDir) {
|
||||
const indexPath = path.join(clientDir, "index.html");
|
||||
const indexHtml = await fs.readFile(indexPath, "utf8");
|
||||
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map((match) => match[1]);
|
||||
const missing = [];
|
||||
|
||||
for (const ref of refs) {
|
||||
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
|
||||
if (!normalizedRef) continue;
|
||||
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
|
||||
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
|
||||
|
||||
const ext = path.extname(normalizedRef);
|
||||
if (!ext) continue;
|
||||
|
||||
const relativePath = normalizedRef.replace(/^\/+/, "");
|
||||
const assetPath = path.join(clientDir, relativePath);
|
||||
if (!(await exists(assetPath))) {
|
||||
missing.push(normalizedRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
const preview = missing.slice(0, 6).join(", ");
|
||||
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
|
||||
fail(
|
||||
`Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
printUsage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
fail("This script only builds macOS .dmg artifacts and must run on macOS.");
|
||||
}
|
||||
|
||||
const desktopPkg = await readJson(path.join(repoRoot, "apps/desktop/package.json"));
|
||||
const serverPkg = await readJson(path.join(repoRoot, "apps/server/package.json"));
|
||||
|
||||
const electronVersion = desktopPkg.dependencies?.electron;
|
||||
if (typeof electronVersion !== "string" || electronVersion.length === 0) {
|
||||
fail("Could not resolve apps/desktop electron dependency version.");
|
||||
}
|
||||
|
||||
const dependencies = serverPkg.dependencies;
|
||||
if (!dependencies || Object.keys(dependencies).length === 0) {
|
||||
fail("Could not resolve production dependencies from apps/server/package.json.");
|
||||
}
|
||||
|
||||
const appVersion = options.version ?? serverPkg.version ?? "0.1.0";
|
||||
const stageRoot = path.join(os.tmpdir(), "t3code-desktop-dmg-stage");
|
||||
const stageAppDir = path.join(stageRoot, "app");
|
||||
const distDirs = {
|
||||
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
|
||||
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
|
||||
serverDist: path.join(repoRoot, "apps/server/dist"),
|
||||
};
|
||||
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
|
||||
|
||||
if (!options.skipBuild) {
|
||||
console.log("[desktop-dmg] Building desktop/server/web artifacts...");
|
||||
await run("bun", ["run", "build:desktop"], { cwd: repoRoot });
|
||||
}
|
||||
|
||||
for (const [label, dir] of Object.entries(distDirs)) {
|
||||
if (!(await exists(dir))) {
|
||||
fail(`Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`);
|
||||
}
|
||||
}
|
||||
if (!(await exists(bundledClientEntry))) {
|
||||
fail(
|
||||
`Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
|
||||
);
|
||||
}
|
||||
await validateBundledClientAssets(path.dirname(bundledClientEntry));
|
||||
|
||||
await fs.rm(stageRoot, { recursive: true, force: true });
|
||||
await fs.mkdir(path.join(stageAppDir, "apps/desktop"), { recursive: true });
|
||||
await fs.mkdir(path.join(stageAppDir, "apps/server"), { recursive: true });
|
||||
|
||||
console.log("[desktop-dmg] Staging release app...");
|
||||
await fs.cp(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"), {
|
||||
recursive: true,
|
||||
});
|
||||
await fs.cp(distDirs.desktopResources, path.join(stageAppDir, "apps/desktop/resources"), {
|
||||
recursive: true,
|
||||
});
|
||||
await fs.cp(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"), { recursive: true });
|
||||
await stageProductionIcons(path.join(stageAppDir, "apps/desktop/resources"));
|
||||
|
||||
const stagePackageJson = {
|
||||
name: "t3-code-desktop",
|
||||
version: appVersion,
|
||||
private: true,
|
||||
description: "T3 Code desktop build",
|
||||
author: "T3 Tools",
|
||||
main: "apps/desktop/dist-electron/main.js",
|
||||
build: {
|
||||
appId: "com.t3tools.t3code",
|
||||
productName: desktopPkg.productName ?? "T3 Code",
|
||||
artifactName: "T3-Code-${version}-${arch}.${ext}",
|
||||
directories: {
|
||||
buildResources: "apps/desktop/resources",
|
||||
},
|
||||
mac: {
|
||||
target: ["dmg"],
|
||||
icon: "icon.icns",
|
||||
category: "public.app-category.developer-tools",
|
||||
},
|
||||
},
|
||||
dependencies,
|
||||
devDependencies: {
|
||||
electron: electronVersion,
|
||||
},
|
||||
};
|
||||
|
||||
await fs.writeFile(
|
||||
path.join(stageAppDir, "package.json"),
|
||||
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
console.log("[desktop-dmg] Installing staged production dependencies...");
|
||||
await run("bun", ["install", "--production"], { cwd: stageAppDir });
|
||||
|
||||
const buildEnv = {
|
||||
...process.env,
|
||||
};
|
||||
if (!options.signed) {
|
||||
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
|
||||
}
|
||||
|
||||
const buildArgs = ["--bun", "electron-builder", "--mac", "dmg", `--${options.arch}`];
|
||||
console.log(`[desktop-dmg] Building .dmg (arch=${options.arch}, version=${appVersion})...`);
|
||||
await run("bunx", buildArgs, { cwd: stageAppDir, env: buildEnv });
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
const stageFiles = await fs.readdir(stageDistDir);
|
||||
const dmgFiles = stageFiles.filter((file) => file.endsWith(".dmg"));
|
||||
if (dmgFiles.length === 0) {
|
||||
fail(`Build completed but no .dmg found in ${stageDistDir}`);
|
||||
}
|
||||
|
||||
await fs.mkdir(options.outputDir, { recursive: true });
|
||||
const copiedArtifacts = [];
|
||||
for (const file of stageFiles) {
|
||||
if (!file.endsWith(".dmg") && !file.endsWith(".dmg.blockmap")) continue;
|
||||
const from = path.join(stageDistDir, file);
|
||||
const to = path.join(options.outputDir, file);
|
||||
await fs.copyFile(from, to);
|
||||
copiedArtifacts.push(to);
|
||||
}
|
||||
|
||||
if (!options.keepStage) {
|
||||
await fs.rm(stageRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
console.log("[desktop-dmg] Done. Artifacts:");
|
||||
for (const artifact of copiedArtifacts) {
|
||||
console.log(` - ${artifact}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
fail(message);
|
||||
});
|
||||