Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36314bb3bb | ||
|
|
84b71e0a01 | ||
|
|
c8f33b89c6 | ||
|
|
6204eaf5e1 | ||
|
|
3303d9a7fa |
No files matched your search
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
name: Lint, Typecheck, Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.1.38
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v4
|
||||
@@ -40,11 +40,3 @@ jobs:
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
@@ -5,6 +5,7 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
apps/*/dist-electron
|
||||
packages/*/dist
|
||||
.env
|
||||
.env.local
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo"
|
||||
],
|
||||
"experimentalSortPackageJson": {}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
"suspicious": "warn",
|
||||
"perf": "warn"
|
||||
},
|
||||
"rules": {
|
||||
"react-in-jsx-scope": "off"
|
||||
}
|
||||
}
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"recommendations": ["oxc.oxc-vscode"]
|
||||
}
|
||||
Vendored
-8
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"editor.formatOnSave": true,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode",
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.oxc": "always"
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn"
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
## Project Snapshot
|
||||
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||
|
||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||
|
||||
## Core Priorities
|
||||
1. Performance first.
|
||||
2. Reliability first.
|
||||
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Package Roles
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Provider WS API Docs Sync (Required)
|
||||
- The canonical provider API spec lives at `docs/provider-ws-api.md`.
|
||||
- Any change to provider WS contracts, methods/channels, canonical event shapes, normalization mappings, replay/backpressure behavior, or client apply semantics must update `docs/provider-ws-api.md` in the same PR.
|
||||
- If code and docs diverge, treat it as a bug and resolve before merge.
|
||||
|
||||
## Codex App Server (Important)
|
||||
T3 Code is currently Codex-first. The server starts `codex app-server` (JSON-RPC over stdio) per provider session, then streams structured events to the browser through WebSocket push messages.
|
||||
|
||||
How we use it in this codebase:
|
||||
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
|
||||
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
|
||||
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
|
||||
- Web app consumes canonical provider stream frames via WebSocket push on channel `providers.stream`.
|
||||
|
||||
Docs:
|
||||
- Codex App Server docs: https://developers.openai.com/codex/sdk/#app-server
|
||||
|
||||
## Reference Repos
|
||||
- Open-source Codex repo: https://github.com/openai/codex
|
||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
@@ -1,97 +1,54 @@
|
||||
# T3 Code
|
||||
# CodeThing (Electron + Vite + Bun)
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||
CodeThing is a desktop shell for coding agents. This first implementation is:
|
||||
|
||||
Run `npx t3` in any project directory to launch the web interface.
|
||||
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
|
||||
|
||||
## Architecture
|
||||
|
||||
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Browser (React + Vite) │
|
||||
│ Connected via WebSocket │
|
||||
└──────────┬──────────────────────┘
|
||||
│ ws://localhost:3773
|
||||
┌──────────▼──────────────────────┐
|
||||
│ apps/server (Node.js) │
|
||||
│ WebSocket + HTTP static server │
|
||||
│ ProviderManager │
|
||||
│ CodexAppServerManager │
|
||||
└──────────┬──────────────────────┘
|
||||
│ JSON-RPC over stdio
|
||||
┌──────────▼──────────────────────┐
|
||||
│ codex app-server │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
1. Codex-first: connects to `codex app-server` and streams turn/item events.
|
||||
2. Provider-ready: renderer speaks a provider abstraction so Claude Code can plug in later.
|
||||
3. Typed end-to-end: contracts validate payloads at preload/main boundaries.
|
||||
|
||||
## Workspace layout
|
||||
|
||||
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
|
||||
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
|
||||
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
|
||||
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
- `/apps/desktop`: Electron main + preload process, includes provider and Codex session managers.
|
||||
- `/apps/renderer`: React + Vite UI for session control, conversation, and protocol event stream.
|
||||
- `/packages/contracts`: shared Zod schemas + TypeScript types for IPC and provider events.
|
||||
|
||||
## Codex prerequisites
|
||||
|
||||
- Install Codex CLI so `codex` is on your PATH.
|
||||
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
|
||||
- T3 Code starts the server via `codex app-server` per session.
|
||||
- Authenticate Codex before running CodeThing (for example via API key or ChatGPT auth supported by Codex).
|
||||
- CodeThing starts the server via `codex app-server` per session.
|
||||
|
||||
## Quick start
|
||||
## Security and boundary model
|
||||
|
||||
```bash
|
||||
# Development (with hot reload)
|
||||
bun run dev
|
||||
|
||||
# Desktop development
|
||||
bun run dev:desktop
|
||||
|
||||
# Production
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
```
|
||||
- `nodeIntegration: false`
|
||||
- `contextIsolation: true`
|
||||
- `sandbox: true`
|
||||
- Renderer talks only to `window.nativeApi` exposed by preload.
|
||||
- Preload and main both validate inputs using shared Zod schemas.
|
||||
|
||||
## Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web dev tasks via Turborepo's parallel task runner.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses tsx for TS execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `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.
|
||||
|
||||
## Runtime modes
|
||||
|
||||
T3 Code has a global runtime mode switch in the chat toolbar:
|
||||
|
||||
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
|
||||
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
|
||||
|
||||
## Provider architecture
|
||||
|
||||
The web app communicates with the server via WebSocket using a JSON-RPC-style request/response layer plus a single canonical provider stream:
|
||||
|
||||
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
|
||||
- **Push stream**: `{ type: "push", channel: "providers.stream", data: ProviderStreamFrame }`
|
||||
|
||||
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
|
||||
|
||||
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
|
||||
- `providers.respondToApproval`, `providers.stopSession`, `providers.listSessions`
|
||||
- `providers.openStream`, `providers.closeStream`
|
||||
- `shell.openInEditor`, `server.getConfig`
|
||||
|
||||
The stream contract is `snapshot + delta` with cursor replay (`afterSeq`) for reconnect safety. The server normalizes provider-native events (currently Codex raw app-server events) into canonical events so UI rendering stays provider-agnostic.
|
||||
|
||||
See `docs/provider-ws-api.md` for the full canonical schema, event mapping, and replay/gap semantics.
|
||||
- `bun run dev`: starts contract build/watch, renderer dev server, and Electron process.
|
||||
- `bun run build`: builds contracts, renderer, and desktop bundles through Turbo.
|
||||
- `bun run typecheck`: strict TypeScript checks for all packages.
|
||||
- `bun run test`: runs workspace tests.
|
||||
|
||||
## CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
|
||||
Optional:
|
||||
- `ELECTRON_RENDERER_PORT=5180 bun run dev` if `5173` is already in use.
|
||||
|
||||
## Provider architecture
|
||||
|
||||
The renderer now depends on `nativeApi.providers.*`:
|
||||
|
||||
1. `startSession`
|
||||
2. `sendTurn`
|
||||
3. `interruptTurn`
|
||||
4. `stopSession`
|
||||
5. `listSessions`
|
||||
6. `onEvent`
|
||||
|
||||
Codex is the only implemented provider right now. `claudeCode` is reserved in contracts/UI but returns a not-implemented error in main-process dispatch.
|
||||
@@ -1,12 +1,6 @@
|
||||
## TODO
|
||||
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [ ] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
- [ ] Thread archiving
|
||||
- [ ] Selecting folder should instantly create project
|
||||
- [ ] New projects should go on top
|
||||
- [ ] Projects should be sorted by latest thread update
|
||||
- [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] Remove model picker from new project menu
|
||||
- [x] CMD+Shift+O to create new thread in current project
|
||||
- [x] Remove project title pill from input box and topnav
|
||||
- [x] Remove connection status from topnav
|
||||
@@ -1 +0,0 @@
|
||||
dist-electron/
|
||||
@@ -1,28 +1,32 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"name": "@acme/desktop",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --cwd ../server build && concurrently -k -n BUNDLE,WEB,ELECTRON \"bun run dev:bundle\" \"bun run --cwd ../web dev\" \"bun run dev:electron\"",
|
||||
"dev": "concurrently -k -n BUNDLE,ELECTRON \"bun run dev:bundle\" \"bun run dev:electron\"",
|
||||
"dev:bundle": "tsup --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsup",
|
||||
"start": "electron dist-electron/main.js",
|
||||
"postinstall": "electron-rebuild",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"lint": "biome check src/",
|
||||
"test": "vitest run",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron": "33.4.11"
|
||||
"@acme/contracts": "workspace:*",
|
||||
"electron": "33.4.11",
|
||||
"node-pty": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron/rebuild": "^3.7.0",
|
||||
"@types/node": "^22.10.2",
|
||||
"concurrently": "^9.1.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsup": "^8.3.5",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.0",
|
||||
"wait-on": "^8.0.2"
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,11 @@ await waitOn({
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.js",
|
||||
],
|
||||
});
|
||||
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const command =
|
||||
process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
|
||||
@@ -1,61 +1,84 @@
|
||||
import { execSync, spawn } from "node:child_process";
|
||||
/**
|
||||
* Smoke test: builds desktop + renderer, launches Electron against the
|
||||
* production bundle, waits for the renderer to confirm it loaded, then exits.
|
||||
*
|
||||
* Catches the two categories of regression we've hit:
|
||||
* 1. Module resolution failures (preload can't find @acme/contracts, etc.)
|
||||
* 2. CSP / script blocking (React fails to mount)
|
||||
*
|
||||
* The test works by injecting a tiny check via ELECTRON_ENABLE_LOGGING —
|
||||
* Electron forwards renderer console.log to the main process stdout when
|
||||
* that env var is set. We look for React's "Download the React DevTools"
|
||||
* message as proof that React successfully mounted (it only fires after
|
||||
* the first render). For production mode (no React DevTools message), we
|
||||
* instead check that no fatal errors appeared.
|
||||
*/
|
||||
import { spawn, execSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const root = resolve(__dirname, "../../..");
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const rootDir = resolve(__dirname, "../../..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.js");
|
||||
|
||||
console.log("Building contracts + web + server + desktop...");
|
||||
execSync("bun run build", { cwd: rootDir, stdio: "inherit" });
|
||||
// ── Build first ──────────────────────────────────────────────────────
|
||||
console.log("Building contracts + renderer + desktop...");
|
||||
execSync("bun run build", { cwd: root, stdio: "inherit" });
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
// ── Launch Electron (production mode — no VITE_DEV_SERVER_URL) ──────
|
||||
console.log("\nLaunching Electron (production mode)...");
|
||||
|
||||
const child = spawn(electronBin, [mainJs], {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
VITE_DEV_SERVER_URL: "",
|
||||
VITE_DEV_SERVER_URL: "", // ensure production path
|
||||
ELECTRON_ENABLE_LOGGING: "1",
|
||||
},
|
||||
});
|
||||
|
||||
let output = "";
|
||||
child.stdout.on("data", (chunk) => {
|
||||
output += chunk.toString();
|
||||
|
||||
child.stdout.on("data", (d) => {
|
||||
output += d.toString();
|
||||
});
|
||||
child.stderr.on("data", (chunk) => {
|
||||
output += chunk.toString();
|
||||
child.stderr.on("data", (d) => {
|
||||
output += d.toString();
|
||||
});
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
const TIMEOUT_MS = 8_000;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
child.kill();
|
||||
}, 8_000);
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
child.on("exit", () => {
|
||||
clearTimeout(timeout);
|
||||
clearTimeout(timer);
|
||||
|
||||
// Fatal patterns that indicate broken builds
|
||||
const fatalPatterns = [
|
||||
"Cannot find module",
|
||||
"MODULE_NOT_FOUND",
|
||||
"Refused to execute",
|
||||
"Refused to execute", // CSP blocking scripts
|
||||
"can't detect preamble", // @vitejs/plugin-react failure
|
||||
"Uncaught Error",
|
||||
"Uncaught TypeError",
|
||||
"Uncaught ReferenceError",
|
||||
];
|
||||
const failures = fatalPatterns.filter((pattern) => output.includes(pattern));
|
||||
|
||||
const failures = fatalPatterns.filter((p) => output.includes(p));
|
||||
|
||||
if (failures.length > 0) {
|
||||
console.error("\nDesktop smoke test failed:");
|
||||
for (const failure of failures) {
|
||||
console.error(` - ${failure}`);
|
||||
console.error("\n❌ Smoke test FAILED. Matched fatal patterns:");
|
||||
for (const f of failures) {
|
||||
console.error(` • ${f}`);
|
||||
}
|
||||
console.error("\nFull output:\n" + output);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("Desktop smoke test passed.");
|
||||
console.log("✅ Smoke test passed — no fatal errors detected");
|
||||
process.exit(0);
|
||||
});
|
||||
+5
-29
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyCodexStderrLine,
|
||||
isRecoverableThreadResumeError,
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
@@ -24,7 +23,8 @@ describe("classifyCodexStderrLine", () => {
|
||||
});
|
||||
|
||||
it("keeps unknown structured errors", () => {
|
||||
const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
|
||||
const line =
|
||||
"2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
|
||||
expect(classifyCodexStderrLine(line)).toEqual({
|
||||
message: line,
|
||||
});
|
||||
@@ -45,7 +45,9 @@ describe("normalizeCodexModelSlug", () => {
|
||||
});
|
||||
|
||||
it("prefers codex id when model differs", () => {
|
||||
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
|
||||
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe(
|
||||
"gpt-5.3-codex",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps non-aliased models as-is", () => {
|
||||
@@ -53,29 +55,3 @@ describe("normalizeCodexModelSlug", () => {
|
||||
expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRecoverableThreadResumeError", () => {
|
||||
it("matches not-found resume errors", () => {
|
||||
expect(
|
||||
isRecoverableThreadResumeError(
|
||||
new Error("thread/resume failed: thread not found"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores non-resume errors", () => {
|
||||
expect(
|
||||
isRecoverableThreadResumeError(
|
||||
new Error("thread/start failed: permission denied"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores non-recoverable resume errors", () => {
|
||||
expect(
|
||||
isRecoverableThreadResumeError(
|
||||
new Error("thread/resume failed: timed out waiting for server"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
+114
-220
@@ -4,15 +4,13 @@ import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
|
||||
import type {
|
||||
ProviderApprovalDecision,
|
||||
ProviderRawEvent,
|
||||
ProviderRequestKind,
|
||||
ProviderEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/contracts";
|
||||
} from "@acme/contracts";
|
||||
import { normalizeModelSlug } from "@acme/contracts";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -23,24 +21,11 @@ interface PendingRequest {
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface PendingApprovalRequest {
|
||||
requestId: string;
|
||||
jsonRpcId: string | number;
|
||||
method:
|
||||
| "item/commandExecution/requestApproval"
|
||||
| "item/fileChange/requestApproval";
|
||||
requestKind: ProviderRequestKind;
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
itemId?: string;
|
||||
}
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<string, PendingApprovalRequest>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
@@ -75,14 +60,6 @@ const BENIGN_ERROR_LOG_SNIPPETS = [
|
||||
"state db missing rollout path for thread",
|
||||
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
|
||||
];
|
||||
const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"not found",
|
||||
"missing thread",
|
||||
"no such thread",
|
||||
"unknown thread",
|
||||
"does not exist",
|
||||
];
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
model: string | undefined | null,
|
||||
preferredId?: string,
|
||||
@@ -99,7 +76,9 @@ export function normalizeCodexModelSlug(
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function classifyCodexStderrLine(rawLine: string): { message: string } | null {
|
||||
export function classifyCodexStderrLine(
|
||||
rawLine: string,
|
||||
): { message: string } | null {
|
||||
const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
|
||||
if (!line) {
|
||||
return null;
|
||||
@@ -112,7 +91,9 @@ export function classifyCodexStderrLine(rawLine: string): { message: string } |
|
||||
return null;
|
||||
}
|
||||
|
||||
const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet));
|
||||
const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) =>
|
||||
line.includes(snippet),
|
||||
);
|
||||
if (isBenignError) {
|
||||
return null;
|
||||
}
|
||||
@@ -121,27 +102,16 @@ export function classifyCodexStderrLine(rawLine: string): { message: string } |
|
||||
return { message: line };
|
||||
}
|
||||
|
||||
export function isRecoverableThreadResumeError(error: unknown): boolean {
|
||||
const message = (
|
||||
error instanceof Error ? error.message : String(error)
|
||||
).toLowerCase();
|
||||
if (!message.includes("thread/resume")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) =>
|
||||
message.includes(snippet),
|
||||
);
|
||||
}
|
||||
|
||||
export interface CodexAppServerManagerEvents {
|
||||
event: [event: ProviderRawEvent];
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<string, CodexSessionContext>();
|
||||
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
async startSession(
|
||||
input: ProviderSessionStartInput,
|
||||
): Promise<ProviderSession> {
|
||||
const sessionId = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -167,7 +137,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
@@ -175,13 +144,17 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
this.emitLifecycleEvent(
|
||||
context,
|
||||
"session/connecting",
|
||||
"Starting codex app-server",
|
||||
);
|
||||
|
||||
try {
|
||||
await this.sendRequest(context, "initialize", {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
name: "codething_desktop",
|
||||
title: "CodeThing Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
@@ -191,87 +164,50 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
this.writeMessage(context, { method: "initialized" });
|
||||
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||
const sessionOverrides = {
|
||||
model: normalizedModel ?? null,
|
||||
const threadStart = await this.sendRequest(context, "thread/start", {
|
||||
model: null,
|
||||
cwd: input.cwd ?? null,
|
||||
approvalPolicy: input.approvalPolicy,
|
||||
sandbox: input.sandboxMode,
|
||||
};
|
||||
|
||||
const threadStartParams = {
|
||||
...sessionOverrides,
|
||||
experimentalRawEvents: false,
|
||||
};
|
||||
});
|
||||
|
||||
let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
|
||||
let threadOpenResponse: unknown;
|
||||
if (input.resumeThreadId) {
|
||||
try {
|
||||
threadOpenMethod = "thread/resume";
|
||||
threadOpenResponse = await this.sendRequest(
|
||||
context,
|
||||
"thread/resume",
|
||||
{
|
||||
...sessionOverrides,
|
||||
threadId: input.resumeThreadId,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isRecoverableThreadResumeError(error)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
threadOpenMethod = "thread/start";
|
||||
this.emitLifecycleEvent(
|
||||
context,
|
||||
"session/threadResumeFallback",
|
||||
`Could not resume thread ${input.resumeThreadId}; started a new thread instead.`,
|
||||
);
|
||||
threadOpenResponse = await this.sendRequest(
|
||||
context,
|
||||
"thread/start",
|
||||
threadStartParams,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
threadOpenMethod = "thread/start";
|
||||
threadOpenResponse = await this.sendRequest(
|
||||
context,
|
||||
"thread/start",
|
||||
threadStartParams,
|
||||
);
|
||||
}
|
||||
|
||||
const threadOpenRecord = this.readObject(threadOpenResponse);
|
||||
const threadId =
|
||||
this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
|
||||
this.readString(threadOpenRecord, "threadId");
|
||||
const threadId = this.readString(
|
||||
this.readObject(threadStart)?.thread,
|
||||
"id",
|
||||
);
|
||||
if (!threadId) {
|
||||
throw new Error(
|
||||
`${threadOpenMethod} response did not include a thread id.`,
|
||||
);
|
||||
throw new Error("thread/start response did not include a thread id.");
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
threadId,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${threadId}`);
|
||||
this.emitLifecycleEvent(
|
||||
context,
|
||||
"session/ready",
|
||||
`Connected to thread ${threadId}`,
|
||||
);
|
||||
return { ...context.session };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to start Codex session.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
throw new Error(message, { cause: error });
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
async sendTurn(
|
||||
input: ProviderSendTurnInput,
|
||||
): Promise<ProviderTurnStartResult> {
|
||||
const context = this.requireSession(input.sessionId);
|
||||
if (!context.session.threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
@@ -300,7 +236,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
turnStartParams.effort = input.effort;
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "turn/start", turnStartParams);
|
||||
const response = await this.sendRequest(
|
||||
context,
|
||||
"turn/start",
|
||||
turnStartParams,
|
||||
);
|
||||
|
||||
const turn = this.readObject(this.readObject(response), "turn");
|
||||
const turnId = this.readString(turn, "id");
|
||||
@@ -333,45 +273,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
async respondToApproval(
|
||||
sessionId: string,
|
||||
approvalId: string,
|
||||
decision: ProviderApprovalDecision,
|
||||
): Promise<void> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const pendingRequest = context.pendingApprovals.get(approvalId);
|
||||
if (!pendingRequest) {
|
||||
throw new Error(`Unknown pending approval request: ${approvalId}`);
|
||||
}
|
||||
|
||||
context.pendingApprovals.delete(approvalId);
|
||||
this.writeMessage(context, {
|
||||
id: pendingRequest.jsonRpcId,
|
||||
result: {
|
||||
decision,
|
||||
},
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/requestApproval/decision",
|
||||
threadId: pendingRequest.threadId,
|
||||
turnId: pendingRequest.turnId,
|
||||
itemId: pendingRequest.itemId,
|
||||
requestId: pendingRequest.requestId,
|
||||
requestKind: pendingRequest.requestKind,
|
||||
payload: {
|
||||
requestId: pendingRequest.requestId,
|
||||
requestKind: pendingRequest.requestKind,
|
||||
decision,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
stopSession(sessionId: string): void {
|
||||
const context = this.sessions.get(sessionId);
|
||||
if (!context) {
|
||||
@@ -385,7 +286,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
pending.reject(new Error("Session stopped before request completed."));
|
||||
}
|
||||
context.pending.clear();
|
||||
context.pendingApprovals.clear();
|
||||
|
||||
context.output.close();
|
||||
|
||||
@@ -542,7 +442,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
if (notification.method === "thread/started") {
|
||||
const threadId = this.readString(this.readObject(notification.params)?.thread, "id");
|
||||
const threadId = this.readString(
|
||||
this.readObject(notification.params)?.thread,
|
||||
"id",
|
||||
);
|
||||
if (threadId) {
|
||||
this.updateSession(context, { threadId });
|
||||
}
|
||||
@@ -550,7 +453,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "turn/started") {
|
||||
const turnId = this.readString(this.readObject(notification.params)?.turn, "id");
|
||||
const turnId = this.readString(
|
||||
this.readObject(notification.params)?.turn,
|
||||
"id",
|
||||
);
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
@@ -561,7 +467,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
if (notification.method === "turn/completed") {
|
||||
const turn = this.readObject(notification.params, "turn");
|
||||
const status = this.readString(turn, "status");
|
||||
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
||||
const errorMessage = this.readString(
|
||||
this.readObject(turn, "error"),
|
||||
"message",
|
||||
);
|
||||
this.updateSession(context, {
|
||||
status: status === "failed" ? "error" : "ready",
|
||||
activeTurnId: undefined,
|
||||
@@ -571,7 +480,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "error") {
|
||||
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
||||
const message = this.readString(
|
||||
this.readObject(notification.params)?.error,
|
||||
"message",
|
||||
);
|
||||
const willRetry = this.readBoolean(notification.params, "willRetry");
|
||||
|
||||
this.updateSession(context, {
|
||||
@@ -581,30 +493,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
}
|
||||
|
||||
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
||||
private handleServerRequest(
|
||||
context: CodexSessionContext,
|
||||
request: JsonRpcRequest,
|
||||
): void {
|
||||
const route = this.readRouteFields(request.params);
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
const isUserInputRequest = request.method === "item/tool/requestUserInput";
|
||||
let requestId: string | undefined;
|
||||
if (requestKind || isUserInputRequest) {
|
||||
requestId = randomUUID();
|
||||
}
|
||||
if (requestKind && requestId) {
|
||||
const pendingRequest: PendingApprovalRequest = {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
method:
|
||||
requestKind === "command"
|
||||
? "item/commandExecution/requestApproval"
|
||||
: "item/fileChange/requestApproval",
|
||||
requestKind,
|
||||
...(route.threadId ? { threadId: route.threadId } : {}),
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||
};
|
||||
context.pendingApprovals.set(requestId, pendingRequest);
|
||||
}
|
||||
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "request",
|
||||
@@ -615,39 +508,30 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: route.threadId,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
requestId,
|
||||
requestKind,
|
||||
payload: request.params,
|
||||
});
|
||||
|
||||
if (requestKind) {
|
||||
if (request.method === "item/commandExecution/requestApproval") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { decision: "decline" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isUserInputRequest) {
|
||||
if (request.method === "item/fileChange/requestApproval") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { decision: "decline" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { answers: {} },
|
||||
});
|
||||
|
||||
if (requestId) {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/requestApproval/decision",
|
||||
threadId: route.threadId,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
requestId,
|
||||
payload: {
|
||||
requestId,
|
||||
decision: "accept",
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -660,7 +544,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
private handleResponse(context: CodexSessionContext, response: JsonRpcResponse): void {
|
||||
private handleResponse(
|
||||
context: CodexSessionContext,
|
||||
response: JsonRpcResponse,
|
||||
): void {
|
||||
const key = String(response.id);
|
||||
const pending = context.pending.get(key);
|
||||
if (!pending) {
|
||||
@@ -671,7 +558,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
context.pending.delete(key);
|
||||
|
||||
if (response.error?.message) {
|
||||
pending.reject(new Error(`${pending.method} failed: ${String(response.error.message)}`));
|
||||
pending.reject(
|
||||
new Error(
|
||||
`${pending.method} failed: ${String(response.error.message)}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -718,7 +609,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
context.child.stdin.write(`${encoded}\n`);
|
||||
}
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
private emitLifecycleEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "session",
|
||||
@@ -730,7 +625,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
private emitErrorEvent(
|
||||
context: CodexSessionContext,
|
||||
method: string,
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
@@ -742,11 +641,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
private emitEvent(event: ProviderRawEvent): void {
|
||||
private emitEvent(event: ProviderEvent): void {
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
|
||||
private updateSession(
|
||||
context: CodexSessionContext,
|
||||
updates: Partial<ProviderSession>,
|
||||
): void {
|
||||
context.session = {
|
||||
...context.session,
|
||||
...updates,
|
||||
@@ -754,20 +656,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
}
|
||||
|
||||
private requestKindForMethod(
|
||||
method: string,
|
||||
): ProviderRequestKind | undefined {
|
||||
if (method === "item/commandExecution/requestApproval") {
|
||||
return "command";
|
||||
}
|
||||
|
||||
if (method === "item/fileChange/requestApproval") {
|
||||
return "file-change";
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
@@ -795,7 +683,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const hasId = typeof candidate.id === "string" || typeof candidate.id === "number";
|
||||
const hasId =
|
||||
typeof candidate.id === "string" || typeof candidate.id === "number";
|
||||
const hasMethod = typeof candidate.method === "string";
|
||||
return hasId && !hasMethod;
|
||||
}
|
||||
@@ -815,9 +704,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.readString(params, "threadId") ??
|
||||
this.readString(this.readObject(params, "thread"), "id");
|
||||
const turnId =
|
||||
this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id");
|
||||
this.readString(params, "turnId") ??
|
||||
this.readString(this.readObject(params, "turn"), "id");
|
||||
const itemId =
|
||||
this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id");
|
||||
this.readString(params, "itemId") ??
|
||||
this.readString(this.readObject(params, "item"), "id");
|
||||
|
||||
if (threadId) {
|
||||
route.threadId = threadId;
|
||||
@@ -834,7 +725,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return route;
|
||||
}
|
||||
|
||||
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
||||
private readObject(
|
||||
value: unknown,
|
||||
key?: string,
|
||||
): Record<string, unknown> | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
? value
|
||||
@@ -13,6 +13,6 @@ export function fixPath(): void {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited PATH if shell lookup fails.
|
||||
// Silently ignore — keep default PATH
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { withParsedArgs, withParsedPayload } from "./ipcHelpers";
|
||||
|
||||
describe("withParsedPayload", () => {
|
||||
it("parses payload and passes typed input to handler", async () => {
|
||||
const handler = vi.fn(async (_event: unknown, payload: { value: string }) =>
|
||||
payload.value.toUpperCase(),
|
||||
);
|
||||
const wrapped = withParsedPayload(
|
||||
{
|
||||
parse(payload: unknown): { value: string } {
|
||||
if (
|
||||
!payload ||
|
||||
typeof payload !== "object" ||
|
||||
typeof (payload as { value?: unknown }).value !== "string"
|
||||
) {
|
||||
throw new Error("Invalid payload");
|
||||
}
|
||||
|
||||
return { value: (payload as { value: string }).value };
|
||||
},
|
||||
},
|
||||
handler,
|
||||
);
|
||||
|
||||
const result = await wrapped({}, { value: "hello" });
|
||||
expect(result).toBe("HELLO");
|
||||
expect(handler).toHaveBeenCalledWith({}, { value: "hello" });
|
||||
});
|
||||
|
||||
it("throws and does not call handler on invalid payload", async () => {
|
||||
const handler = vi.fn(async () => "ok");
|
||||
const wrapped = withParsedPayload(
|
||||
{
|
||||
parse(payload: unknown): { value: string } {
|
||||
if (
|
||||
!payload ||
|
||||
typeof payload !== "object" ||
|
||||
typeof (payload as { value?: unknown }).value !== "string"
|
||||
) {
|
||||
throw new Error("Invalid payload");
|
||||
}
|
||||
|
||||
return { value: (payload as { value: string }).value };
|
||||
},
|
||||
},
|
||||
handler,
|
||||
);
|
||||
|
||||
expect(() => wrapped({}, { value: 123 })).toThrow();
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("withParsedArgs", () => {
|
||||
it("parses tuple arguments before invoking handler", () => {
|
||||
const handler = vi.fn(
|
||||
(_event: unknown, sessionId: string, data: string) => {
|
||||
return `${sessionId}:${data}`;
|
||||
},
|
||||
);
|
||||
const wrapped = withParsedArgs(
|
||||
{
|
||||
parse(args: unknown[]): [string, string] {
|
||||
const [sessionId, data] = args;
|
||||
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
||||
throw new Error("Invalid sessionId");
|
||||
}
|
||||
if (typeof data !== "string") {
|
||||
throw new Error("Invalid data");
|
||||
}
|
||||
|
||||
return [sessionId, data];
|
||||
},
|
||||
},
|
||||
handler,
|
||||
);
|
||||
|
||||
expect(wrapped({}, "abc", "input")).toBe("abc:input");
|
||||
expect(handler).toHaveBeenCalledWith({}, "abc", "input");
|
||||
});
|
||||
|
||||
it("throws and does not call handler when args are invalid", () => {
|
||||
const handler = vi.fn();
|
||||
const wrapped = withParsedArgs(
|
||||
{
|
||||
parse(args: unknown[]): [string, string] {
|
||||
const [sessionId, data] = args;
|
||||
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
||||
throw new Error("Invalid sessionId");
|
||||
}
|
||||
if (typeof data !== "string") {
|
||||
throw new Error("Invalid data");
|
||||
}
|
||||
|
||||
return [sessionId, data];
|
||||
},
|
||||
},
|
||||
handler,
|
||||
);
|
||||
|
||||
expect(() => wrapped({}, 123, "input")).toThrow();
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
type Parser<T> = {
|
||||
parse: (value: unknown) => T;
|
||||
};
|
||||
type ArgsParser<T extends unknown[]> = {
|
||||
parse: (value: unknown[]) => T;
|
||||
};
|
||||
|
||||
export function withParsedPayload<TPayload, TResult>(
|
||||
schema: Parser<TPayload>,
|
||||
handler: (event: unknown, payload: TPayload) => MaybePromise<TResult>,
|
||||
): (event: unknown, payload: unknown) => MaybePromise<TResult> {
|
||||
return (event, payload) => handler(event, schema.parse(payload));
|
||||
}
|
||||
|
||||
export function withParsedArgs<TArgs extends unknown[], TResult>(
|
||||
schema: ArgsParser<TArgs>,
|
||||
handler: (event: unknown, ...args: TArgs) => MaybePromise<TResult>,
|
||||
): (event: unknown, ...args: unknown[]) => MaybePromise<TResult> {
|
||||
return (event, ...args) => {
|
||||
const parsedArgs = schema.parse(args);
|
||||
return handler(event, ...parsedArgs);
|
||||
};
|
||||
}
|
||||
+297
-160
@@ -1,145 +1,45 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain } from "electron";
|
||||
|
||||
import { fixPath } from "./fixPath";
|
||||
|
||||
fixPath();
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.js");
|
||||
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
import { spawn } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { BrowserWindow, app, dialog, ipcMain, session, shell } from "electron";
|
||||
|
||||
import {
|
||||
EDITORS,
|
||||
IPC_CHANNELS,
|
||||
type TerminalCommandInput,
|
||||
type TerminalCommandResult,
|
||||
agentConfigSchema,
|
||||
agentSessionIdSchema,
|
||||
newTodoInputSchema,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
terminalCommandInputSchema,
|
||||
todoIdSchema,
|
||||
} from "@acme/contracts";
|
||||
import { withParsedArgs, withParsedPayload } from "./ipcHelpers";
|
||||
import { ProcessManager } from "./processManager";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { TodoStore } from "./todoStore";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
let backendPort = 0;
|
||||
let backendAuthToken = "";
|
||||
let backendWsUrl = "";
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const probe = net.createServer();
|
||||
probe.listen(0, "127.0.0.1", () => {
|
||||
const address = probe.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
probe.close(() => {
|
||||
if (port > 0) {
|
||||
resolve(port);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Failed to reserve backend port"));
|
||||
});
|
||||
});
|
||||
probe.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function backendEnv(): NodeJS.ProcessEnv {
|
||||
return {
|
||||
...process.env,
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "1",
|
||||
T3CODE_PORT: String(backendPort),
|
||||
T3CODE_STATE_DIR: STATE_DIR,
|
||||
T3CODE_AUTH_TOKEN: backendAuthToken,
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBackendRestart(reason: string): void {
|
||||
if (isQuitting || restartTimer) return;
|
||||
|
||||
const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
|
||||
restartAttempt += 1;
|
||||
console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
|
||||
|
||||
restartTimer = setTimeout(() => {
|
||||
restartTimer = null;
|
||||
startBackend();
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
if (!fs.existsSync(BACKEND_ENTRY)) {
|
||||
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
||||
cwd: ROOT_DIR,
|
||||
env: backendEnv(),
|
||||
stdio: "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
|
||||
child.once("spawn", () => {
|
||||
restartAttempt = 0;
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
let todoStore: TodoStore;
|
||||
const processManager = new ProcessManager();
|
||||
const providerManager = new ProviderManager();
|
||||
const agentWriteArgsParser = {
|
||||
parse(args: unknown[]): [string, string] {
|
||||
const [sessionId, data] = args;
|
||||
if (typeof data !== "string") {
|
||||
throw new Error("agent:write data must be a string");
|
||||
}
|
||||
scheduleBackendRestart(error.message);
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
if (isQuitting) return;
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
}
|
||||
|
||||
const child = backendProcess;
|
||||
backendProcess = null;
|
||||
if (!child) return;
|
||||
|
||||
if (!child.killed) {
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (!child.killed) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 2_000).unref();
|
||||
}
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
const result = owner
|
||||
? await dialog.showOpenDialog(owner, {
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
})
|
||||
: await dialog.showOpenDialog({
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
});
|
||||
if (result.canceled) return null;
|
||||
return result.filePaths[0] ?? null;
|
||||
});
|
||||
}
|
||||
return [agentSessionIdSchema.parse(sessionId), data];
|
||||
},
|
||||
};
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
@@ -160,52 +60,289 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
});
|
||||
|
||||
setupEventForwarding(window);
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
} else {
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
}
|
||||
void window.loadFile(WEB_ENTRY);
|
||||
return window;
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
if (mainWindow === window) {
|
||||
mainWindow = null;
|
||||
}
|
||||
});
|
||||
|
||||
void window.loadFile(path.join(__dirname, "../../renderer/dist/index.html"));
|
||||
return window;
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
// Todo handlers
|
||||
ipcMain.handle(IPC_CHANNELS.todosList, async () => {
|
||||
return todoStore.list();
|
||||
});
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.todosAdd,
|
||||
withParsedPayload(newTodoInputSchema, async (_event, payload) => {
|
||||
return todoStore.add(payload);
|
||||
}),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.todosToggle,
|
||||
withParsedPayload(todoIdSchema, async (_event, id) => {
|
||||
return todoStore.toggle(id);
|
||||
}),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.todosRemove,
|
||||
withParsedPayload(todoIdSchema, async (_event, id) => {
|
||||
return todoStore.remove(id);
|
||||
}),
|
||||
);
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.dialogPickFolder, async () => {
|
||||
const owner =
|
||||
BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];
|
||||
const result = owner
|
||||
? await dialog.showOpenDialog(owner, {
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
})
|
||||
: await dialog.showOpenDialog({
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
});
|
||||
|
||||
if (result.canceled) return null;
|
||||
return result.filePaths[0] ?? null;
|
||||
});
|
||||
|
||||
// Terminal handlers
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.terminalRun,
|
||||
withParsedPayload(terminalCommandInputSchema, async (_event, payload) => {
|
||||
return runTerminalCommand(payload);
|
||||
}),
|
||||
);
|
||||
|
||||
// Shell handlers
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.shellOpenInEditor,
|
||||
async (_event, cwd: string, editor: string) => {
|
||||
if (!cwd) throw new Error("cwd is required");
|
||||
const editorDef = EDITORS.find((e) => e.id === editor);
|
||||
if (!editorDef) throw new Error(`Unknown editor: ${editor}`);
|
||||
if (!editorDef.command) {
|
||||
const error = await shell.openPath(cwd);
|
||||
if (error) throw new Error(error);
|
||||
return;
|
||||
}
|
||||
const child = spawn(editorDef.command, [cwd], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
child.on("error", () => {
|
||||
/* ignore spawn failures for detached editors */
|
||||
});
|
||||
child.unref();
|
||||
},
|
||||
);
|
||||
|
||||
// Agent handlers
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.agentSpawn,
|
||||
withParsedPayload(agentConfigSchema, async (_event, config) => {
|
||||
return processManager.spawn(config);
|
||||
}),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.agentKill,
|
||||
withParsedPayload(agentSessionIdSchema, async (_event, sessionId) => {
|
||||
processManager.kill(sessionId);
|
||||
}),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.agentWrite,
|
||||
withParsedArgs(agentWriteArgsParser, async (_event, sessionId, data) => {
|
||||
processManager.write(sessionId, data);
|
||||
}),
|
||||
);
|
||||
|
||||
// Provider handlers
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerSessionStart,
|
||||
withParsedPayload(
|
||||
providerSessionStartInputSchema,
|
||||
async (_event, payload) => {
|
||||
return providerManager.startSession(payload);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerTurnStart,
|
||||
withParsedPayload(providerSendTurnInputSchema, async (_event, payload) => {
|
||||
return providerManager.sendTurn(payload);
|
||||
}),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerTurnInterrupt,
|
||||
withParsedPayload(
|
||||
providerInterruptTurnInputSchema,
|
||||
async (_event, payload) => {
|
||||
await providerManager.interruptTurn(payload);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerSessionStop,
|
||||
withParsedPayload(
|
||||
providerStopSessionInputSchema,
|
||||
async (_event, payload) => {
|
||||
providerManager.stopSession(payload);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.providerSessionList, async () => {
|
||||
return providerManager.listSessions();
|
||||
});
|
||||
}
|
||||
|
||||
async function runTerminalCommand(
|
||||
input: TerminalCommandInput,
|
||||
): Promise<TerminalCommandResult> {
|
||||
const shellPath =
|
||||
process.platform === "win32"
|
||||
? (process.env.ComSpec ?? "cmd.exe")
|
||||
: (process.env.SHELL ?? "/bin/sh");
|
||||
|
||||
const args =
|
||||
process.platform === "win32"
|
||||
? ["/d", "/s", "/c", input.command]
|
||||
: ["-lc", input.command];
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(shellPath, args, {
|
||||
cwd: input.cwd,
|
||||
env: process.env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let timedOut = false;
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (!child.killed) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 1_000).unref();
|
||||
}, input.timeoutMs ?? 30_000);
|
||||
|
||||
child.stdout?.on("data", (chunk: Buffer) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
child.on("close", (code, signal) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
code: code ?? null,
|
||||
signal: signal ?? null,
|
||||
timedOut,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function setupEventForwarding(window: BrowserWindow): void {
|
||||
const onOutput = (chunk: unknown) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(IPC_CHANNELS.agentOutput, chunk);
|
||||
}
|
||||
};
|
||||
|
||||
const onExit = (exit: unknown) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(IPC_CHANNELS.agentExit, exit);
|
||||
}
|
||||
};
|
||||
|
||||
const onProviderEvent = (event: unknown) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(IPC_CHANNELS.providerEvent, event);
|
||||
}
|
||||
};
|
||||
|
||||
processManager.on("output", onOutput);
|
||||
processManager.on("exit", onExit);
|
||||
providerManager.on("event", onProviderEvent);
|
||||
|
||||
window.on("closed", () => {
|
||||
processManager.off("output", onOutput);
|
||||
processManager.off("exit", onExit);
|
||||
providerManager.off("event", onProviderEvent);
|
||||
});
|
||||
}
|
||||
|
||||
function setupCSP(): void {
|
||||
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
|
||||
const csp = isDevelopment
|
||||
? "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws://localhost:* http://localhost:*"
|
||||
: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'";
|
||||
|
||||
callback({
|
||||
responseHeaders: {
|
||||
...details.responseHeaders,
|
||||
"Content-Security-Policy": [csp],
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||
setupCSP();
|
||||
|
||||
todoStore = new TodoStore(path.join(app.getPath("userData"), "todos.json"));
|
||||
await todoStore.init();
|
||||
|
||||
registerIpcHandlers();
|
||||
startBackend();
|
||||
mainWindow = createWindow();
|
||||
createWindow();
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
processManager.killAll();
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
void bootstrap();
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
|
||||
@@ -1,9 +1,61 @@
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
import { IPC_CHANNELS, type NativeApi } from "@acme/contracts";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
|
||||
});
|
||||
const nativeApi: NativeApi = {
|
||||
todos: {
|
||||
list: () => ipcRenderer.invoke(IPC_CHANNELS.todosList),
|
||||
add: (input) => ipcRenderer.invoke(IPC_CHANNELS.todosAdd, input),
|
||||
toggle: (id) => ipcRenderer.invoke(IPC_CHANNELS.todosToggle, id),
|
||||
remove: (id) => ipcRenderer.invoke(IPC_CHANNELS.todosRemove, id),
|
||||
},
|
||||
dialogs: {
|
||||
pickFolder: () => ipcRenderer.invoke(IPC_CHANNELS.dialogPickFolder),
|
||||
},
|
||||
terminal: {
|
||||
run: (input) => ipcRenderer.invoke(IPC_CHANNELS.terminalRun, input),
|
||||
},
|
||||
agent: {
|
||||
spawn: (config) => ipcRenderer.invoke(IPC_CHANNELS.agentSpawn, config),
|
||||
kill: (sessionId) => ipcRenderer.invoke(IPC_CHANNELS.agentKill, sessionId),
|
||||
write: (sessionId, data) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.agentWrite, sessionId, data),
|
||||
onOutput: (callback) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, chunk: unknown) =>
|
||||
callback(chunk as Parameters<typeof callback>[0]);
|
||||
ipcRenderer.on(IPC_CHANNELS.agentOutput, listener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IPC_CHANNELS.agentOutput, listener);
|
||||
},
|
||||
onExit: (callback) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, exit: unknown) =>
|
||||
callback(exit as Parameters<typeof callback>[0]);
|
||||
ipcRenderer.on(IPC_CHANNELS.agentExit, listener);
|
||||
return () => ipcRenderer.removeListener(IPC_CHANNELS.agentExit, listener);
|
||||
},
|
||||
},
|
||||
providers: {
|
||||
startSession: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerSessionStart, input),
|
||||
sendTurn: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerTurnStart, input),
|
||||
interruptTurn: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerTurnInterrupt, input),
|
||||
stopSession: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerSessionStop, input),
|
||||
listSessions: () => ipcRenderer.invoke(IPC_CHANNELS.providerSessionList),
|
||||
onEvent: (callback) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, payload: unknown) =>
|
||||
callback(payload as Parameters<typeof callback>[0]);
|
||||
ipcRenderer.on(IPC_CHANNELS.providerEvent, listener);
|
||||
return () =>
|
||||
ipcRenderer.removeListener(IPC_CHANNELS.providerEvent, listener);
|
||||
},
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (cwd: string, editor: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.shellOpenInEditor, cwd, editor),
|
||||
},
|
||||
};
|
||||
|
||||
contextBridge.exposeInMainWorld("nativeApi", nativeApi);
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProcessManager } from "./processManager";
|
||||
|
||||
describe("ProcessManager", () => {
|
||||
it("can be instantiated", () => {
|
||||
const pm = new ProcessManager();
|
||||
expect(pm).toBeInstanceOf(ProcessManager);
|
||||
});
|
||||
|
||||
it("spawns a process and receives output", async () => {
|
||||
const pm = new ProcessManager();
|
||||
const chunks: string[] = [];
|
||||
|
||||
const done = new Promise<void>((resolve) => {
|
||||
pm.on("output", (chunk) => {
|
||||
chunks.push(chunk.data);
|
||||
});
|
||||
pm.on("exit", () => {
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const sessionId = pm.spawn({ command: "echo", args: ["hello"] });
|
||||
expect(typeof sessionId).toBe("string");
|
||||
expect(sessionId.length).toBeGreaterThan(0);
|
||||
|
||||
await done;
|
||||
|
||||
expect(chunks.join("").trim()).toBe("hello");
|
||||
});
|
||||
|
||||
it("can kill a spawned process", async () => {
|
||||
const pm = new ProcessManager();
|
||||
|
||||
const exited = new Promise<number | null>((resolve) => {
|
||||
pm.on("exit", (exit) => {
|
||||
resolve(exit.code);
|
||||
});
|
||||
});
|
||||
|
||||
const sessionId = pm.spawn({ command: "sleep", args: ["10"] });
|
||||
pm.kill(sessionId);
|
||||
|
||||
const code = await exited;
|
||||
expect(code).not.toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { type ChildProcess, spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
import {
|
||||
type AgentConfig,
|
||||
type AgentExit,
|
||||
type OutputChunk,
|
||||
agentConfigSchema,
|
||||
} from "@acme/contracts";
|
||||
import type { IPty } from "node-pty";
|
||||
|
||||
export interface ProcessManagerEvents {
|
||||
output: [chunk: OutputChunk];
|
||||
exit: [exit: AgentExit];
|
||||
}
|
||||
|
||||
export class ProcessManager extends EventEmitter<ProcessManagerEvents> {
|
||||
private sessions = new Map<string, ChildProcess>();
|
||||
private ptySessions = new Map<string, IPty>();
|
||||
|
||||
spawn(raw: AgentConfig): string {
|
||||
const config = agentConfigSchema.parse(raw);
|
||||
const sessionId = randomUUID();
|
||||
|
||||
if (config.usePty) {
|
||||
return this.spawnPty(sessionId, config);
|
||||
}
|
||||
|
||||
return this.spawnProcess(sessionId, config);
|
||||
}
|
||||
|
||||
private spawnProcess(sessionId: string, config: AgentConfig): string {
|
||||
const child = spawn(config.command, config.args, {
|
||||
cwd: config.cwd,
|
||||
env: config.env ? { ...process.env, ...config.env } : process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
this.sessions.set(sessionId, child);
|
||||
|
||||
child.stdout?.on("data", (data: Buffer) => {
|
||||
this.emit("output", {
|
||||
sessionId,
|
||||
stream: "stdout",
|
||||
data: data.toString(),
|
||||
});
|
||||
});
|
||||
|
||||
child.stderr?.on("data", (data: Buffer) => {
|
||||
this.emit("output", {
|
||||
sessionId,
|
||||
stream: "stderr",
|
||||
data: data.toString(),
|
||||
});
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
this.sessions.delete(sessionId);
|
||||
this.emit("exit", {
|
||||
sessionId,
|
||||
code: code ?? null,
|
||||
signal: signal ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
private spawnPty(sessionId: string, config: AgentConfig): string {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const pty = require("node-pty") as typeof import("node-pty");
|
||||
|
||||
const ptyProcess = pty.spawn(config.command, config.args, {
|
||||
name: "xterm-256color",
|
||||
cols: 120,
|
||||
rows: 30,
|
||||
cwd: config.cwd ?? process.cwd(),
|
||||
env: (config.env
|
||||
? { ...process.env, ...config.env }
|
||||
: process.env) as Record<string, string>,
|
||||
});
|
||||
|
||||
this.ptySessions.set(sessionId, ptyProcess);
|
||||
|
||||
ptyProcess.onData((data) => {
|
||||
this.emit("output", {
|
||||
sessionId,
|
||||
stream: "stdout",
|
||||
data,
|
||||
});
|
||||
});
|
||||
|
||||
ptyProcess.onExit(({ exitCode, signal }) => {
|
||||
this.ptySessions.delete(sessionId);
|
||||
this.emit("exit", {
|
||||
sessionId,
|
||||
code: exitCode,
|
||||
signal: signal !== undefined ? String(signal) : null,
|
||||
});
|
||||
});
|
||||
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
write(sessionId: string, data: string): void {
|
||||
const child = this.sessions.get(sessionId);
|
||||
if (child) {
|
||||
child.stdin?.write(data);
|
||||
return;
|
||||
}
|
||||
|
||||
const pty = this.ptySessions.get(sessionId);
|
||||
if (pty) {
|
||||
pty.write(data);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`No session: ${sessionId}`);
|
||||
}
|
||||
|
||||
kill(sessionId: string): void {
|
||||
const child = this.sessions.get(sessionId);
|
||||
if (child) {
|
||||
child.kill();
|
||||
return;
|
||||
}
|
||||
|
||||
const pty = this.ptySessions.get(sessionId);
|
||||
if (pty) {
|
||||
pty.kill();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
killAll(): void {
|
||||
for (const child of this.sessions.values()) {
|
||||
child.kill();
|
||||
}
|
||||
this.sessions.clear();
|
||||
|
||||
for (const pty of this.ptySessions.values()) {
|
||||
pty.kill();
|
||||
}
|
||||
this.ptySessions.clear();
|
||||
}
|
||||
}
|
||||
@@ -48,18 +48,4 @@ describe("ProviderManager", () => {
|
||||
manager.dispose();
|
||||
expect(() => manager.dispose()).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects approval responses for unknown sessions", async () => {
|
||||
const manager = new ProviderManager();
|
||||
|
||||
await expect(
|
||||
manager.respondToApproval({
|
||||
sessionId: "missing-session",
|
||||
approvalId: "approval-1",
|
||||
decision: "accept",
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -3,24 +3,22 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderRawEvent,
|
||||
type ProviderRespondToApprovalInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerRespondToApprovalInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
} from "@acme/contracts";
|
||||
import { CodexAppServerManager } from "./codexAppServerManager";
|
||||
|
||||
export interface ProviderManagerEvents {
|
||||
event: [event: ProviderRawEvent];
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
@@ -28,9 +26,9 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly threadLogsDir: string;
|
||||
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
|
||||
private readonly sessionThreadIds = new Map<string, string>();
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderRawEvent[]>();
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
|
||||
private disposed = false;
|
||||
private readonly onCodexEvent = (event: ProviderRawEvent) => {
|
||||
private readonly onCodexEvent = (event: ProviderEvent) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
@@ -81,19 +79,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
await this.codex.interruptTurn(input.sessionId, input.turnId);
|
||||
}
|
||||
|
||||
async respondToApproval(raw: ProviderRespondToApprovalInput): Promise<void> {
|
||||
const input = providerRespondToApprovalInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
await this.codex.respondToApproval(
|
||||
input.sessionId,
|
||||
input.approvalId,
|
||||
input.decision,
|
||||
);
|
||||
}
|
||||
|
||||
stopSession(raw: ProviderStopSessionInput): void {
|
||||
const input = providerStopSessionInputSchema.parse(raw);
|
||||
this.codex.stopSession(input.sessionId);
|
||||
@@ -124,7 +109,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.pendingEventsBySession.clear();
|
||||
}
|
||||
|
||||
private routeEventToThreadLog(event: ProviderRawEvent): void {
|
||||
private routeEventToThreadLog(event: ProviderEvent): void {
|
||||
const threadId = this.resolveThreadId(event);
|
||||
if (!threadId) {
|
||||
const pending = this.pendingEventsBySession.get(event.sessionId) ?? [];
|
||||
@@ -149,7 +134,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.pendingEventsBySession.delete(sessionId);
|
||||
}
|
||||
|
||||
private resolveThreadId(event: ProviderRawEvent): string | undefined {
|
||||
private resolveThreadId(event: ProviderEvent): string | undefined {
|
||||
const fromPayload = this.readThreadIdFromPayload(event.payload);
|
||||
const threadId =
|
||||
event.threadId ??
|
||||
@@ -187,7 +172,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private writeThreadEvent(threadId: string, event: ProviderRawEvent): void {
|
||||
private writeThreadEvent(threadId: string, event: ProviderEvent): void {
|
||||
const stream = this.getOrCreateThreadLogStream(threadId);
|
||||
stream.write(`${JSON.stringify(event)}\n`);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
type NewTodoInput,
|
||||
type Todo,
|
||||
newTodoInputSchema,
|
||||
todoIdSchema,
|
||||
todoListSchema,
|
||||
} from "@acme/contracts";
|
||||
|
||||
export class TodoStore {
|
||||
private todos: Todo[] = [];
|
||||
private queue: Promise<void> = Promise.resolve();
|
||||
|
||||
public constructor(private readonly filePath: string) {}
|
||||
|
||||
public async init(): Promise<void> {
|
||||
return this.runExclusive(async () => {
|
||||
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
|
||||
|
||||
try {
|
||||
const raw = await fs.readFile(this.filePath, "utf8");
|
||||
const parsed = todoListSchema.safeParse(JSON.parse(raw));
|
||||
|
||||
if (parsed.success) {
|
||||
this.todos = parsed.data;
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isNotFoundError(error)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
this.todos = [];
|
||||
await this.persist();
|
||||
});
|
||||
}
|
||||
|
||||
public async list(): Promise<Todo[]> {
|
||||
return this.runExclusive(async () => [...this.todos]);
|
||||
}
|
||||
|
||||
public async add(input: NewTodoInput): Promise<Todo[]> {
|
||||
return this.runExclusive(async () => {
|
||||
const { title } = newTodoInputSchema.parse(input);
|
||||
const todo: Todo = {
|
||||
id: randomUUID(),
|
||||
title,
|
||||
completed: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
this.todos = [todo, ...this.todos];
|
||||
await this.persist();
|
||||
return [...this.todos];
|
||||
});
|
||||
}
|
||||
|
||||
public async toggle(id: string): Promise<Todo[]> {
|
||||
return this.runExclusive(async () => {
|
||||
const parsedId = todoIdSchema.parse(id);
|
||||
this.todos = this.todos.map((todo) =>
|
||||
todo.id === parsedId ? { ...todo, completed: !todo.completed } : todo,
|
||||
);
|
||||
|
||||
await this.persist();
|
||||
return [...this.todos];
|
||||
});
|
||||
}
|
||||
|
||||
public async remove(id: string): Promise<Todo[]> {
|
||||
return this.runExclusive(async () => {
|
||||
const parsedId = todoIdSchema.parse(id);
|
||||
this.todos = this.todos.filter((todo) => todo.id !== parsedId);
|
||||
|
||||
await this.persist();
|
||||
return [...this.todos];
|
||||
});
|
||||
}
|
||||
|
||||
private async persist(): Promise<void> {
|
||||
await fs.writeFile(
|
||||
this.filePath,
|
||||
JSON.stringify(this.todos, null, 2),
|
||||
"utf8",
|
||||
);
|
||||
}
|
||||
|
||||
private async runExclusive<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const next = this.queue.then(operation, operation);
|
||||
this.queue = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
function isNotFoundError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
(error as { code?: string }).code === "ENOENT"
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node", "electron"],
|
||||
"lib": ["ES2023", "DOM"]
|
||||
"lib": ["ES2022", "DOM"]
|
||||
},
|
||||
"include": ["src", "tsup.config.ts"]
|
||||
}
|
||||
@@ -6,5 +6,5 @@ export default defineConfig({
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
noExternal: ["@acme/contracts"],
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Electron Todo</title>
|
||||
</head>
|
||||
<body class="bg-slate-100">
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"name": "@acme/renderer",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -8,15 +8,15 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "biome check src/",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@acme/contracts": "workspace:*",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.563.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"zod": "^3.24.1"
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import ChatView from "./components/ChatView";
|
||||
import DiffPanel from "./components/DiffPanel";
|
||||
import Sidebar from "./components/Sidebar";
|
||||
import { readNativeApi } from "./session-logic";
|
||||
import { StoreProvider, useStore } from "./store";
|
||||
|
||||
function EventRouter() {
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { dispatch } = useStore();
|
||||
const activeAssistantItemRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.providers.onEvent((event) => {
|
||||
dispatch({
|
||||
type: "APPLY_EVENT",
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function Layout() {
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { state } = useStore();
|
||||
|
||||
if (!api) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-[#0c0c0c] text-[#e0e0e0]">
|
||||
<div className="drag-region h-[52px] shrink-0" />
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-[#a0a0a0]/60">
|
||||
Native bridge unavailable. Launch through Electron.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-[#0c0c0c] text-[#e0e0e0]">
|
||||
<EventRouter />
|
||||
<Sidebar />
|
||||
<ChatView />
|
||||
{state.diffOpen && <DiffPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<StoreProvider>
|
||||
<Layout />
|
||||
</StoreProvider>
|
||||
);
|
||||
}
|
||||
+4
-2
@@ -15,10 +15,12 @@ const markdownComponents: Components = {
|
||||
|
||||
export default function ChatMarkdown({ text }: ChatMarkdownProps) {
|
||||
return (
|
||||
<div className="chat-markdown text-sm leading-relaxed text-foreground/80">
|
||||
<div className="chat-markdown text-sm leading-relaxed text-[#d0d0d0]">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
||||
rehypePlugins={[
|
||||
[rehypeHighlight, { detect: true, ignoreMissing: true }],
|
||||
]}
|
||||
components={markdownComponents}
|
||||
>
|
||||
{text}
|
||||
@@ -0,0 +1,762 @@
|
||||
import {
|
||||
type FormEvent,
|
||||
Fragment,
|
||||
type KeyboardEvent,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import { EDITORS, type EditorId } from "@acme/contracts";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_REASONING,
|
||||
MODEL_OPTIONS,
|
||||
REASONING_OPTIONS,
|
||||
resolveModelSlug,
|
||||
} from "../model-logic";
|
||||
import {
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
formatDuration,
|
||||
formatElapsed,
|
||||
formatTimestamp,
|
||||
readNativeApi,
|
||||
} from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import ChatMarkdown from "./ChatMarkdown";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
return `${formatTimestamp(createdAt)} • ${duration}`;
|
||||
}
|
||||
|
||||
const FILE_MANAGER_LABEL = navigator.platform.includes("Mac")
|
||||
? "Finder"
|
||||
: navigator.platform.includes("Win")
|
||||
? "Explorer"
|
||||
: "Files";
|
||||
|
||||
function editorLabel(editor: (typeof EDITORS)[number]): string {
|
||||
return editor.command ? editor.label : FILE_MANAGER_LABEL;
|
||||
}
|
||||
|
||||
const LAST_EDITOR_KEY = "codething:last-editor";
|
||||
|
||||
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
if (tone === "error") return "text-rose-300/50";
|
||||
if (tone === "tool") return "text-[#8a8a8a]";
|
||||
if (tone === "thinking") return "text-[#707070]";
|
||||
return "text-[#606060]";
|
||||
}
|
||||
|
||||
export default function ChatView() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
|
||||
const [isEditorMenuOpen, setIsEditorMenuOpen] = useState(false);
|
||||
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
|
||||
const stored = localStorage.getItem(LAST_EDITOR_KEY);
|
||||
return EDITORS.some((e) => e.id === stored)
|
||||
? (stored as EditorId)
|
||||
: EDITORS[0].id;
|
||||
});
|
||||
const [selectedEffort, setSelectedEffort] =
|
||||
useState<string>(DEFAULT_REASONING);
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const modelMenuRef = useRef<HTMLDivElement>(null);
|
||||
const editorMenuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
const activeProject = state.projects.find(
|
||||
(p) => p.id === activeThread?.projectId,
|
||||
);
|
||||
const selectedModel = resolveModelSlug(
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isWorking = phase === "running" || isSending || isConnecting;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const modelOptions = MODEL_OPTIONS;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
[activeThread?.events],
|
||||
);
|
||||
const assistantCompletionByItemId = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
const ordered = [...(activeThread?.events ?? [])].reverse();
|
||||
for (const event of ordered) {
|
||||
if (event.method !== "item/completed") continue;
|
||||
if (!event.itemId) continue;
|
||||
map.set(event.itemId, event.createdAt);
|
||||
}
|
||||
return map;
|
||||
}, [activeThread?.events]);
|
||||
const timelineEntries = useMemo(
|
||||
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
|
||||
[activeThread?.messages, workLogEntries],
|
||||
);
|
||||
const completionSummary = useMemo(() => {
|
||||
if (!activeThread?.latestTurnStartedAt) return null;
|
||||
if (!activeThread.latestTurnCompletedAt) return null;
|
||||
if (workLogEntries.length === 0) return null;
|
||||
|
||||
if (
|
||||
typeof activeThread.latestTurnDurationMs === "number" &&
|
||||
Number.isFinite(activeThread.latestTurnDurationMs) &&
|
||||
activeThread.latestTurnDurationMs >= 0
|
||||
) {
|
||||
return `Worked for ${formatDuration(activeThread.latestTurnDurationMs)}`;
|
||||
}
|
||||
|
||||
const elapsed = formatElapsed(
|
||||
activeThread.latestTurnStartedAt,
|
||||
activeThread.latestTurnCompletedAt,
|
||||
);
|
||||
return elapsed ? `Worked for ${elapsed}` : null;
|
||||
}, [
|
||||
activeThread?.latestTurnStartedAt,
|
||||
activeThread?.latestTurnCompletedAt,
|
||||
activeThread?.latestTurnDurationMs,
|
||||
workLogEntries.length,
|
||||
]);
|
||||
const completionDividerBeforeEntryId = useMemo(() => {
|
||||
if (!activeThread?.latestTurnStartedAt) return null;
|
||||
if (!activeThread.latestTurnCompletedAt) return null;
|
||||
if (workLogEntries.length === 0) return null;
|
||||
|
||||
const turnStartedAt = Date.parse(activeThread.latestTurnStartedAt);
|
||||
if (Number.isNaN(turnStartedAt)) return null;
|
||||
|
||||
const entry = timelineEntries.find((timelineEntry) => {
|
||||
if (timelineEntry.kind !== "message") return false;
|
||||
if (timelineEntry.message.role !== "assistant") return false;
|
||||
const messageAt = Date.parse(timelineEntry.message.createdAt);
|
||||
return !Number.isNaN(messageAt) && messageAt >= turnStartedAt;
|
||||
});
|
||||
return entry?.id ?? null;
|
||||
}, [
|
||||
activeThread?.latestTurnStartedAt,
|
||||
activeThread?.latestTurnCompletedAt,
|
||||
timelineEntries,
|
||||
workLogEntries.length,
|
||||
]);
|
||||
|
||||
// Auto-scroll on new messages
|
||||
const messageCount = activeThread?.messages.length ?? 0;
|
||||
const workLogCount = workLogEntries.length;
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: trigger on message count change
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messageCount]);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: auto-scroll while active work-log events stream in
|
||||
useEffect(() => {
|
||||
if (phase !== "running") return;
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [phase, workLogCount]);
|
||||
|
||||
// Auto-resize textarea
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: trigger on prompt change
|
||||
useEffect(() => {
|
||||
const ta = textareaRef.current;
|
||||
if (!ta) return;
|
||||
ta.style.height = "auto";
|
||||
ta.style.height = `${Math.min(ta.scrollHeight, 200)}px`;
|
||||
}, [prompt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (phase !== "running") return;
|
||||
const timer = window.setInterval(() => {
|
||||
setNowTick(Date.now());
|
||||
}, 250);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [phase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isModelMenuOpen) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (!modelMenuRef.current) return;
|
||||
if (
|
||||
event.target instanceof Node &&
|
||||
!modelMenuRef.current.contains(event.target)
|
||||
) {
|
||||
setIsModelMenuOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("mousedown", handleClickOutside);
|
||||
return () => {
|
||||
window.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [isModelMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEditorMenuOpen) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (!editorMenuRef.current) return;
|
||||
if (
|
||||
event.target instanceof Node &&
|
||||
!editorMenuRef.current.contains(event.target)
|
||||
) {
|
||||
setIsEditorMenuOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("mousedown", handleClickOutside);
|
||||
return () => {
|
||||
window.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [isEditorMenuOpen]);
|
||||
|
||||
// Cmd+O / Ctrl+O to open in last-used editor
|
||||
useEffect(() => {
|
||||
const handler = (e: globalThis.KeyboardEvent) => {
|
||||
if (e.key === "o" && (e.metaKey || e.ctrlKey) && !e.shiftKey) {
|
||||
if (api && activeProject) {
|
||||
e.preventDefault();
|
||||
void api.shell.openInEditor(activeProject.cwd, lastEditor);
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [api, activeProject, lastEditor]);
|
||||
|
||||
const openInEditor = (editorId: EditorId) => {
|
||||
if (!api || !activeProject) return;
|
||||
void api.shell.openInEditor(activeProject.cwd, editorId);
|
||||
setLastEditor(editorId);
|
||||
localStorage.setItem(LAST_EDITOR_KEY, editorId);
|
||||
setIsEditorMenuOpen(false);
|
||||
};
|
||||
|
||||
const ensureSession = async (): Promise<string | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
if (activeThread.session && activeThread.session.status !== "closed") {
|
||||
return activeThread.session.sessionId;
|
||||
}
|
||||
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const session = await api.providers.startSession({
|
||||
provider: "codex",
|
||||
cwd: activeProject.cwd || undefined,
|
||||
model: selectedModel || undefined,
|
||||
});
|
||||
dispatch({
|
||||
type: "UPDATE_SESSION",
|
||||
threadId: activeThread.id,
|
||||
session,
|
||||
});
|
||||
return session.sessionId;
|
||||
} catch (err) {
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error: err instanceof Error ? err.message : "Failed to connect.",
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onSend = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!api || !activeThread || isSending || isConnecting) return;
|
||||
const trimmed = prompt.trim();
|
||||
if (!trimmed) return;
|
||||
|
||||
// Auto-title from first message
|
||||
if (activeThread.messages.length === 0) {
|
||||
const title =
|
||||
trimmed.length > 50 ? `${trimmed.slice(0, 50)}...` : trimmed;
|
||||
dispatch({
|
||||
type: "SET_THREAD_TITLE",
|
||||
threadId: activeThread.id,
|
||||
title,
|
||||
});
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error: null,
|
||||
});
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
});
|
||||
setPrompt("");
|
||||
|
||||
const sessionId = await ensureSession();
|
||||
if (!sessionId) return;
|
||||
|
||||
setIsSending(true);
|
||||
try {
|
||||
await api.providers.sendTurn({
|
||||
sessionId,
|
||||
input: trimmed,
|
||||
model: selectedModel || undefined,
|
||||
effort: selectedEffort || undefined,
|
||||
});
|
||||
} catch (err) {
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error: err instanceof Error ? err.message : "Failed to send message.",
|
||||
});
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onInterrupt = async () => {
|
||||
if (!api || !activeThread?.session) return;
|
||||
await api.providers.interruptTurn({
|
||||
sessionId: activeThread.session.sessionId,
|
||||
turnId: activeThread.session.activeTurnId,
|
||||
});
|
||||
};
|
||||
|
||||
const onModelSelect = (model: string) => {
|
||||
if (!activeThread) return;
|
||||
dispatch({
|
||||
type: "SET_THREAD_MODEL",
|
||||
threadId: activeThread.id,
|
||||
model: resolveModelSlug(model),
|
||||
});
|
||||
setIsModelMenuOpen(false);
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
void onSend(e as unknown as FormEvent);
|
||||
}
|
||||
};
|
||||
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col bg-[#0c0c0c] text-[#a0a0a0]/40">
|
||||
<div className="drag-region h-[52px] shrink-0" />
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-sm">
|
||||
Select a thread or create a new one to get started.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col bg-[#0c0c0c]">
|
||||
{/* Top bar */}
|
||||
<header className="drag-region flex items-center justify-between border-b border-white/[0.08] px-5 pt-[28px] pb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="text-sm font-medium text-[#e0e0e0]">
|
||||
{activeThread.title}
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Open in editor */}
|
||||
{activeProject && (
|
||||
<div className="relative" ref={editorMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md px-2 py-1 text-[10px] text-[#a0a0a0]/40 transition-colors duration-150 hover:text-[#a0a0a0]/60"
|
||||
onClick={() => setIsEditorMenuOpen((v) => !v)}
|
||||
>
|
||||
Open in…
|
||||
</button>
|
||||
{isEditorMenuOpen && (
|
||||
<div className="absolute right-0 top-full z-50 mt-1 min-w-[120px] rounded-md border border-white/[0.08] bg-[#1b1b1d] py-1 shadow-xl">
|
||||
{EDITORS.map((editor) => (
|
||||
<button
|
||||
key={editor.id}
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-[#e0e0e0] hover:bg-white/[0.06]"
|
||||
onClick={() => openInEditor(editor.id)}
|
||||
>
|
||||
{editorLabel(editor)}
|
||||
{editor.id === lastEditor && (
|
||||
<kbd className="ml-auto text-[9px] text-[#a0a0a0]/40">
|
||||
{navigator.platform.includes("Mac")
|
||||
? "\u2318O"
|
||||
: "Ctrl+O"}
|
||||
</kbd>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* Diff toggle */}
|
||||
<button
|
||||
type="button"
|
||||
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
|
||||
state.diffOpen
|
||||
? "bg-white/10 text-white"
|
||||
: "text-[#a0a0a0]/40 hover:text-[#a0a0a0]/60"
|
||||
}`}
|
||||
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||
>
|
||||
Diff
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Error banner */}
|
||||
{activeThread.error && (
|
||||
<div className="mx-4 mt-3 rounded-lg border border-rose-400/20 bg-rose-900/20 px-3 py-2 text-xs text-rose-200">
|
||||
{activeThread.error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Messages */}
|
||||
<div className="flex-1 overflow-y-auto px-5 py-4">
|
||||
{activeThread.messages.length === 0 && !isWorking ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-[#a0a0a0]/30">
|
||||
Send a message to start the conversation.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mx-auto max-w-3xl space-y-4">
|
||||
{timelineEntries.map((timelineEntry, index) => (
|
||||
<Fragment key={timelineEntry.id}>
|
||||
{timelineEntry.kind === "message" &&
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
(completionDividerBeforeEntryId === timelineEntry.id ||
|
||||
timelineEntries[index - 1]?.kind === "work") && (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-white/[0.1]" />
|
||||
<span className="rounded-full border border-white/[0.12] bg-[#121212] px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-[#9a9a9a]/80">
|
||||
{completionSummary
|
||||
? `Response • ${completionSummary}`
|
||||
: "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-white/[0.1]" />
|
||||
</div>
|
||||
)}
|
||||
{timelineEntry.kind === "work" ? (
|
||||
<div className="flex items-start gap-2 py-0.5 pl-1.5">
|
||||
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-white/[0.18]" />
|
||||
<p
|
||||
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(timelineEntry.entry.tone)}`}
|
||||
>
|
||||
{timelineEntry.entry.detail ? (
|
||||
<>
|
||||
{timelineEntry.entry.label}
|
||||
<span
|
||||
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
||||
title={timelineEntry.entry.detail}
|
||||
>
|
||||
{timelineEntry.entry.detail}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
timelineEntry.entry.label
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : timelineEntry.message.role === "user" ? (
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-white/[0.08] bg-white/[0.05] px-4 py-3">
|
||||
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-[#e0e0e0]">
|
||||
{timelineEntry.message.text}
|
||||
</pre>
|
||||
<p className="mt-1.5 text-right text-[10px] text-[#a0a0a0]/30">
|
||||
{formatTimestamp(timelineEntry.message.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={
|
||||
timelineEntry.message.text ||
|
||||
(timelineEntry.message.streaming
|
||||
? ""
|
||||
: "(empty response)")
|
||||
}
|
||||
/>
|
||||
{timelineEntry.message.streaming && (
|
||||
<div className="pt-1.5">
|
||||
<span className="inline-flex items-center gap-2 rounded-full border border-sky-400/25 bg-sky-500/[0.08] px-2 py-0.5 text-[10px] text-sky-100/90">
|
||||
<span className="inline-flex gap-1">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:150ms]" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:300ms]" />
|
||||
</span>
|
||||
<span>Thinking</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-1.5 text-[10px] text-[#a0a0a0]/30">
|
||||
{formatMessageMeta(
|
||||
timelineEntry.message.createdAt,
|
||||
timelineEntry.message.streaming
|
||||
? formatElapsed(
|
||||
timelineEntry.message.createdAt,
|
||||
nowIso,
|
||||
)
|
||||
: formatElapsed(
|
||||
timelineEntry.message.createdAt,
|
||||
assistantCompletionByItemId.get(
|
||||
timelineEntry.message.id,
|
||||
),
|
||||
),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
{isWorking && (
|
||||
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
||||
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-white/[0.18]" />
|
||||
<div className="flex items-center pt-1">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-white/20 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-white/20 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-white/20 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input bar */}
|
||||
<div className="px-5 pb-4 pt-2">
|
||||
<form onSubmit={onSend} className="mx-auto max-w-3xl">
|
||||
<div className="group rounded-[20px] border border-white/[0.08] bg-[#141416] transition-colors duration-200 focus-within:border-white/[0.16]">
|
||||
{/* Textarea area */}
|
||||
<div className="px-4 pt-4 pb-2">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-[#e0e0e0] placeholder:text-[#a0a0a0]/35 focus:outline-none"
|
||||
rows={2}
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={
|
||||
phase === "disconnected"
|
||||
? "Ask for follow-up changes"
|
||||
: "Ask anything..."
|
||||
}
|
||||
disabled={isSending || isConnecting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Bottom toolbar */}
|
||||
<div className="flex items-center justify-between px-3 pb-3">
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Model picker */}
|
||||
<div className="relative" ref={modelMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-[#a0a0a0]/70 transition-colors duration-150 hover:bg-white/[0.06] hover:text-[#d0d0d0]"
|
||||
onClick={() => setIsModelMenuOpen((open) => !open)}
|
||||
>
|
||||
<span className="max-w-[180px] truncate">
|
||||
{selectedModel}
|
||||
</span>
|
||||
<svg
|
||||
width="10"
|
||||
height="10"
|
||||
viewBox="0 0 10 10"
|
||||
fill="none"
|
||||
className="opacity-50"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M2.5 4L5 6.5L7.5 4"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
{isModelMenuOpen && (
|
||||
<div className="absolute bottom-full left-0 z-20 mb-2 w-[320px] rounded-2xl border border-white/[0.1] bg-[#1b1b1d]/95 p-2 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur">
|
||||
<p className="px-2 py-1 text-[11px] text-[#a0a0a0]/70">
|
||||
Select model
|
||||
</p>
|
||||
<div className="max-h-72 overflow-y-auto">
|
||||
{modelOptions.map((model) => {
|
||||
const isSelected = model === selectedModel;
|
||||
return (
|
||||
<button
|
||||
key={model}
|
||||
type="button"
|
||||
className={`mb-0.5 flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left font-mono text-sm transition-colors duration-150 ${
|
||||
isSelected
|
||||
? "bg-white/[0.08] text-white"
|
||||
: "text-[#d4d4d4] hover:bg-white/[0.05]"
|
||||
}`}
|
||||
onClick={() => onModelSelect(model)}
|
||||
>
|
||||
<span className="truncate">{model}</span>
|
||||
<span
|
||||
className={`pt-0.5 text-sm ${
|
||||
isSelected ? "text-white" : "text-transparent"
|
||||
}`}
|
||||
>
|
||||
✓
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="mx-0.5 h-4 w-px bg-white/[0.08]" />
|
||||
|
||||
{/* Reasoning effort */}
|
||||
<label
|
||||
className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[13px] text-[#a0a0a0]/70 transition-colors duration-150 hover:bg-white/[0.06] hover:text-[#d0d0d0]"
|
||||
htmlFor="reasoning-effort"
|
||||
>
|
||||
<span>
|
||||
{selectedEffort.charAt(0).toUpperCase() +
|
||||
selectedEffort.slice(1)}
|
||||
</span>
|
||||
<select
|
||||
id="reasoning-effort"
|
||||
className="absolute opacity-0 w-0 h-0"
|
||||
value={selectedEffort}
|
||||
onChange={(event) => setSelectedEffort(event.target.value)}
|
||||
>
|
||||
{REASONING_OPTIONS.map((effort) => (
|
||||
<option
|
||||
key={effort}
|
||||
value={effort}
|
||||
className="bg-[#1b1b1d]"
|
||||
>
|
||||
{effort}
|
||||
{effort === DEFAULT_REASONING ? " (default)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<svg
|
||||
width="10"
|
||||
height="10"
|
||||
viewBox="0 0 10 10"
|
||||
fill="none"
|
||||
className="opacity-50"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M2.5 4L5 6.5L7.5 4"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Right side: send / stop button */}
|
||||
<div className="flex items-center gap-2">
|
||||
{phase === "running" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105"
|
||||
onClick={() => void onInterrupt()}
|
||||
aria-label="Stop generation"
|
||||
>
|
||||
<svg
|
||||
width="12"
|
||||
height="12"
|
||||
viewBox="0 0 12 12"
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<rect x="2" y="2" width="8" height="8" rx="1.5" />
|
||||
</svg>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-white/90 text-[#0c0c0c] transition-all duration-150 hover:bg-white hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
|
||||
disabled={isSending || isConnecting || !prompt.trim()}
|
||||
aria-label={
|
||||
isConnecting
|
||||
? "Connecting"
|
||||
: isSending
|
||||
? "Sending"
|
||||
: "Send message"
|
||||
}
|
||||
>
|
||||
{isConnecting || isSending ? (
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 14 14"
|
||||
fill="none"
|
||||
className="animate-spin"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<circle
|
||||
cx="7"
|
||||
cy="7"
|
||||
r="5.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeDasharray="20 12"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 14 14"
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+18
-11
@@ -1,17 +1,18 @@
|
||||
import { isElectron } from "../env";
|
||||
import { useStore } from "../store";
|
||||
|
||||
export default function DiffPanel() {
|
||||
const { dispatch } = useStore();
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
|
||||
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-white/[0.08] bg-[#141414]">
|
||||
{/* Header */}
|
||||
<div className={`flex items-center justify-between border-b border-border px-4 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}>
|
||||
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
|
||||
<div className="drag-region flex items-center justify-between border-b border-white/[0.08] px-4 pt-[28px] pb-3">
|
||||
<h3 className="text-xs font-medium text-[#e0e0e0]">
|
||||
Uncommitted changes
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
|
||||
className="text-[#a0a0a0]/40 transition-colors duration-150 hover:text-[#a0a0a0]/70"
|
||||
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||
>
|
||||
<span className="text-sm">×</span>
|
||||
@@ -21,30 +22,36 @@ export default function DiffPanel() {
|
||||
{/* Placeholder content */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="rounded-lg border border-white/[0.06] bg-white/[0.02] p-3">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
|
||||
M
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
|
||||
<span className="font-mono text-xs text-[#a0a0a0]/60">
|
||||
src/App.tsx
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-0.5 font-mono text-[11px]">
|
||||
<div className="text-red-400/60">- const oldValue = "hello";</div>
|
||||
<div className="text-emerald-400/60">+ const newValue = "world";</div>
|
||||
<div className="text-emerald-400/60">
|
||||
+ const newValue = "world";
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="rounded-lg border border-white/[0.06] bg-white/[0.02] p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
|
||||
A
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
|
||||
<span className="font-mono text-xs text-[#a0a0a0]/60">
|
||||
src/utils.ts
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
|
||||
<p className="mt-6 text-center text-[10px] text-[#a0a0a0]/25">
|
||||
Diff integration coming soon
|
||||
</p>
|
||||
</div>
|
||||
@@ -1,13 +1,9 @@
|
||||
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { readNativeApi } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import type { Project } from "../types";
|
||||
|
||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const minutes = Math.floor(diff / 60_000);
|
||||
@@ -18,13 +14,6 @@ function formatRelativeTime(iso: string): string {
|
||||
return `${Math.floor(hours / 24)}d ago`;
|
||||
}
|
||||
|
||||
function inferProjectName(cwd: string): string {
|
||||
const normalized = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
const parts = normalized.split("/");
|
||||
const last = parts[parts.length - 1];
|
||||
return last && last.length > 0 ? last : "project";
|
||||
}
|
||||
|
||||
function threadStatusLabel(
|
||||
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
|
||||
): "Working" | "Connecting" | null {
|
||||
@@ -36,11 +25,25 @@ function threadStatusLabel(
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||
|
||||
const handleAddProject = () => {
|
||||
const cwd = newCwd.trim();
|
||||
if (!cwd) return;
|
||||
const name = cwd.split("/").filter(Boolean).pop() ?? "project";
|
||||
const project: Project = {
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
};
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
};
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(projectId: string) => {
|
||||
@@ -48,10 +51,11 @@ export default function Sidebar() {
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
id: crypto.randomUUID(),
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "New thread",
|
||||
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
|
||||
model:
|
||||
state.projects.find((p) => p.id === projectId)?.model ??
|
||||
DEFAULT_MODEL,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
@@ -63,98 +67,13 @@ export default function Sidebar() {
|
||||
[dispatch, state.projects],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
(projectId: string) => {
|
||||
const latestThread = state.threads
|
||||
.filter((thread) => thread.projectId === projectId)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
if (byDate !== 0) return byDate;
|
||||
return b.id.localeCompare(a.id);
|
||||
})[0];
|
||||
if (!latestThread) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_ACTIVE_THREAD",
|
||||
threadId: latestThread.id,
|
||||
});
|
||||
},
|
||||
[dispatch, state.threads],
|
||||
);
|
||||
|
||||
const addProjectFromPath = useCallback(
|
||||
async (rawCwd: string) => {
|
||||
const cwd = rawCwd.trim();
|
||||
if (!cwd || isAddingProject) return;
|
||||
|
||||
setIsAddingProject(true);
|
||||
try {
|
||||
if (isElectron && api) {
|
||||
const result = await api.projects.add({ cwd });
|
||||
const project: Project = {
|
||||
id: result.project.id,
|
||||
name: result.project.name,
|
||||
cwd: result.project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
};
|
||||
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) {
|
||||
handleNewThread(resolvedProjectId);
|
||||
} else {
|
||||
focusMostRecentThreadForProject(resolvedProjectId);
|
||||
}
|
||||
} else {
|
||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
||||
if (existing) {
|
||||
focusMostRecentThreadForProject(existing.id);
|
||||
return;
|
||||
}
|
||||
|
||||
const name = inferProjectName(cwd);
|
||||
const project: Project = {
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
};
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
handleNewThread(project.id);
|
||||
}
|
||||
} finally {
|
||||
setIsAddingProject(false);
|
||||
setNewCwd("");
|
||||
setAddingProject(false);
|
||||
}
|
||||
},
|
||||
[
|
||||
api,
|
||||
dispatch,
|
||||
focusMostRecentThreadForProject,
|
||||
handleNewThread,
|
||||
isAddingProject,
|
||||
state.projects,
|
||||
],
|
||||
);
|
||||
|
||||
const handleAddProject = () => {
|
||||
void addProjectFromPath(newCwd);
|
||||
};
|
||||
|
||||
const handlePickFolder = async () => {
|
||||
if (!api || isPickingFolder) return;
|
||||
setIsPickingFolder(true);
|
||||
try {
|
||||
const pickedPath = await api.dialogs.pickFolder();
|
||||
if (!pickedPath) return;
|
||||
await addProjectFromPath(pickedPath);
|
||||
setNewCwd(pickedPath);
|
||||
} finally {
|
||||
setIsPickingFolder(false);
|
||||
}
|
||||
@@ -183,7 +102,9 @@ export default function Sidebar() {
|
||||
}
|
||||
}
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
const activeThread = state.threads.find(
|
||||
(t) => t.id === state.activeThreadId,
|
||||
);
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
|
||||
@@ -198,36 +119,24 @@ export default function Sidebar() {
|
||||
}, [handleNewThread, state.activeThreadId, state.projects, state.threads]);
|
||||
|
||||
return (
|
||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
|
||||
{/* Drag region / traffic light space (Electron only) */}
|
||||
{isElectron && <div className="drag-region h-[52px] shrink-0" />}
|
||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-white/[0.08] bg-[#141414]">
|
||||
{/* Drag region / traffic light space */}
|
||||
<div className="drag-region h-[52px] shrink-0" />
|
||||
{/* Branding */}
|
||||
<div className={`flex items-center gap-2.5 px-4 pb-4 ${isElectron ? "" : "pt-4"}`}>
|
||||
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
|
||||
T3 <span className="font-normal text-muted-foreground">Code</span>
|
||||
<div className="flex items-center gap-2 px-4 pb-4">
|
||||
<div className="flex h-7 w-7 items-center justify-center rounded-lg bg-white text-xs font-bold text-[#0c0c0c]">
|
||||
CT
|
||||
</div>
|
||||
<span className="text-sm font-semibold tracking-tight text-[#e0e0e0]">
|
||||
CodeThing
|
||||
</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) */}
|
||||
<div className="px-3 pb-3">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
|
||||
className="flex w-full items-center gap-2 rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-2 text-xs text-[#a0a0a0]/80 transition-colors duration-150 hover:bg-white/[0.07]"
|
||||
onClick={() => {
|
||||
if (state.projects.length === 0) {
|
||||
setAddingProject(true);
|
||||
@@ -237,7 +146,7 @@ export default function Sidebar() {
|
||||
if (firstProject) handleNewThread(firstProject.id);
|
||||
}}
|
||||
>
|
||||
<span className="text-foreground">+</span>
|
||||
<span className="text-white">+</span>
|
||||
New thread
|
||||
</button>
|
||||
</div>
|
||||
@@ -247,8 +156,10 @@ export default function Sidebar() {
|
||||
{state.projects.map((project) => {
|
||||
const threads = state.threads
|
||||
.filter((t) => t.projectId === project.id)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
.sort((a, b) => {
|
||||
const byDate =
|
||||
new Date(b.createdAt).getTime() -
|
||||
new Date(a.createdAt).getTime();
|
||||
if (byDate !== 0) return byDate;
|
||||
return b.id.localeCompare(a.id);
|
||||
});
|
||||
@@ -257,32 +168,38 @@ export default function Sidebar() {
|
||||
{/* Project header */}
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
|
||||
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
|
||||
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-white/[0.05]"
|
||||
onClick={() =>
|
||||
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })
|
||||
}
|
||||
>
|
||||
<span className="text-[10px] text-muted-foreground/70">
|
||||
<span className="text-[10px] text-[#a0a0a0]/50">
|
||||
{project.expanded ? "▼" : "▶"}
|
||||
</span>
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
<span className="flex-1 truncate text-xs font-medium text-[#e0e0e0]/90">
|
||||
{project.name}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
|
||||
<span className="text-[10px] text-[#a0a0a0]/40">
|
||||
{threads.length}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* Threads */}
|
||||
{project.expanded && (
|
||||
<div className="ml-2 border-l border-border/80 pl-2">
|
||||
<div className="ml-2 border-l border-white/[0.06] pl-2">
|
||||
{threads.map((thread) => {
|
||||
const isActive = state.activeThreadId === thread.id;
|
||||
const threadStatus = threadStatusLabel(thread.session?.status);
|
||||
const threadStatus = threadStatusLabel(
|
||||
thread.session?.status,
|
||||
);
|
||||
return (
|
||||
<button
|
||||
key={thread.id}
|
||||
type="button"
|
||||
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
|
||||
isActive
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground hover:bg-secondary"
|
||||
? "bg-white/10 text-white"
|
||||
: "text-[#a0a0a0]/70 hover:bg-white/[0.04]"
|
||||
}`}
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
@@ -293,14 +210,18 @@ export default function Sidebar() {
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
{threadStatus && (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-sky-600 dark:text-sky-300/80">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500 dark:bg-sky-300/80" />
|
||||
<span className="hidden xl:inline">{threadStatus}</span>
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-[#7ed8ff]/80">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-300/80" />
|
||||
<span className="hidden xl:inline">
|
||||
{threadStatus}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-xs">
|
||||
{thread.title}
|
||||
</span>
|
||||
</div>
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/40">
|
||||
<span className="shrink-0 text-[10px] text-[#a0a0a0]/30">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
</button>
|
||||
@@ -310,7 +231,7 @@ export default function Sidebar() {
|
||||
{/* New thread within project */}
|
||||
<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"
|
||||
className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-[#a0a0a0]/40 transition-colors duration-150 hover:text-[#a0a0a0]/60"
|
||||
onClick={() => handleNewThread(project.id)}
|
||||
>
|
||||
<span>+</span> New thread
|
||||
@@ -322,7 +243,7 @@ export default function Sidebar() {
|
||||
})}
|
||||
|
||||
{state.projects.length === 0 && !addingProject && (
|
||||
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
|
||||
<div className="px-2 pt-4 text-center text-xs text-[#a0a0a0]/40">
|
||||
No projects yet.
|
||||
<br />
|
||||
Add one to get started.
|
||||
@@ -332,12 +253,12 @@ export default function Sidebar() {
|
||||
|
||||
{/* Add project form */}
|
||||
{addingProject ? (
|
||||
<div className="border-t border-border p-3">
|
||||
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
|
||||
<div className="border-t border-white/[0.08] p-3">
|
||||
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-[#a0a0a0]/50">
|
||||
Add project
|
||||
</p>
|
||||
<input
|
||||
className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
|
||||
className="mb-2 w-full rounded-md border border-white/[0.1] bg-white/[0.04] px-2 py-1.5 font-mono text-xs text-[#e0e0e0] placeholder:text-[#a0a0a0]/30 focus:border-white/30 focus:outline-none"
|
||||
placeholder="/path/to/project"
|
||||
value={newCwd}
|
||||
onChange={(e) => setNewCwd(e.target.value)}
|
||||
@@ -346,12 +267,12 @@ export default function Sidebar() {
|
||||
if (e.key === "Escape") setAddingProject(false);
|
||||
}}
|
||||
/>
|
||||
{isElectron && api && (
|
||||
{api && (
|
||||
<button
|
||||
type="button"
|
||||
className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
|
||||
className="mb-2 flex w-full items-center justify-center rounded-md border border-white/[0.1] px-2 py-1.5 text-xs text-[#a0a0a0]/70 transition-colors duration-150 hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={() => void handlePickFolder()}
|
||||
disabled={isPickingFolder || isAddingProject}
|
||||
disabled={isPickingFolder}
|
||||
>
|
||||
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
|
||||
</button>
|
||||
@@ -359,15 +280,14 @@ export default function Sidebar() {
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"
|
||||
className="flex-1 rounded-md bg-white px-2 py-1 text-xs font-medium text-[#0c0c0c] transition-colors duration-150 hover:bg-white/90"
|
||||
onClick={handleAddProject}
|
||||
disabled={isAddingProject}
|
||||
>
|
||||
{isAddingProject ? "Adding..." : "Add"}
|
||||
Add
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"
|
||||
className="flex-1 rounded-md border border-white/[0.1] px-2 py-1 text-xs text-[#a0a0a0]/60 transition-colors duration-150 hover:bg-white/[0.04]"
|
||||
onClick={() => setAddingProject(false)}
|
||||
>
|
||||
Cancel
|
||||
@@ -375,10 +295,10 @@ export default function Sidebar() {
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border-t border-border p-3">
|
||||
<div className="border-t border-white/[0.08] p-3">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"
|
||||
className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-white/[0.12] py-2 text-xs text-[#a0a0a0]/50 transition-colors duration-150 hover:border-white/[0.2] hover:text-[#a0a0a0]/70"
|
||||
onClick={() => setAddingProject(true)}
|
||||
>
|
||||
+ Add project
|
||||
@@ -0,0 +1,160 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
"Helvetica Neue", Arial, sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-height: 100vh;
|
||||
color: #e0e0e0;
|
||||
background: #0c0c0c;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
opacity: 0.035;
|
||||
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
|
||||
background-repeat: repeat;
|
||||
background-size: 256px 256px;
|
||||
}
|
||||
|
||||
pre,
|
||||
code,
|
||||
textarea,
|
||||
input {
|
||||
font-family: "SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo,
|
||||
monospace;
|
||||
}
|
||||
|
||||
/* Window drag region (frameless titlebar) */
|
||||
.drag-region {
|
||||
-webkit-app-region: drag;
|
||||
}
|
||||
|
||||
.drag-region button,
|
||||
.drag-region input,
|
||||
.drag-region textarea,
|
||||
.drag-region select,
|
||||
.drag-region a {
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
|
||||
/* Scrollbar styling */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
/* Reasoning select — clickable label surface */
|
||||
label:has(> select#reasoning-effort) {
|
||||
position: relative;
|
||||
}
|
||||
label:has(> select#reasoning-effort) select {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Chat markdown rendering */
|
||||
.chat-markdown {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.chat-markdown > :first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.chat-markdown > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.chat-markdown p,
|
||||
.chat-markdown ul,
|
||||
.chat-markdown ol,
|
||||
.chat-markdown blockquote,
|
||||
.chat-markdown pre,
|
||||
.chat-markdown table {
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown ul,
|
||||
.chat-markdown ol {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
.chat-markdown li + li {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.chat-markdown a {
|
||||
color: #93c5fd;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: rgba(147, 197, 253, 0.4);
|
||||
}
|
||||
|
||||
.chat-markdown a:hover {
|
||||
color: #bfdbfe;
|
||||
}
|
||||
|
||||
.chat-markdown blockquote {
|
||||
border-left: 2px solid rgba(255, 255, 255, 0.2);
|
||||
padding-left: 0.8rem;
|
||||
color: rgba(224, 224, 224, 0.75);
|
||||
}
|
||||
|
||||
.chat-markdown :not(pre) > code {
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 0.375rem;
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
padding: 0.1rem 0.35rem;
|
||||
color: #f4f4f5;
|
||||
}
|
||||
|
||||
.chat-markdown pre {
|
||||
overflow-x: auto;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 0.75rem;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
padding: 0.8rem 0.9rem;
|
||||
}
|
||||
|
||||
.chat-markdown pre code {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.chat-markdown th,
|
||||
.chat-markdown td {
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
padding: 0.35rem 0.45rem;
|
||||
text-align: left;
|
||||
}
|
||||
File renamed without changes.
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_MODEL, normalizeModelSlug, resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlug,
|
||||
} from "./model-logic";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
it("maps 5.3 aliases to canonical codex slug", () => {
|
||||
@@ -3,7 +3,7 @@ export {
|
||||
MODEL_OPTIONS,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlug,
|
||||
} from "@t3tools/contracts";
|
||||
} from "@acme/contracts";
|
||||
|
||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
export const DEFAULT_REASONING = "high";
|
||||
+2
-31
@@ -46,9 +46,7 @@ describe("hydratePersistedState", () => {
|
||||
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]?.messages[0]?.streaming).toBe(false);
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("filters unknown project references and repairs active thread", () => {
|
||||
@@ -86,38 +84,14 @@ describe("hydratePersistedState", () => {
|
||||
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?.activeThreadId).toBe("t-1");
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("hydrates runtime mode from v3 payload", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 3,
|
||||
runtimeMode: "approval-required",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: false,
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
activeThreadId: null,
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
it("writes v4 payload and strips non-persisted thread fields", () => {
|
||||
it("writes v2 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",
|
||||
@@ -148,14 +122,11 @@ describe("toPersistedState", () => {
|
||||
],
|
||||
threads: [thread],
|
||||
activeThreadId: "t-1",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(4);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.version).toBe(2);
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
@@ -1,12 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
} from "./types";
|
||||
import type { Project, Thread } from "./types";
|
||||
|
||||
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
|
||||
@@ -28,7 +23,6 @@ const persistedMessageSchema = z.object({
|
||||
|
||||
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),
|
||||
@@ -42,8 +36,6 @@ const persistedStateBodySchema = z.object({
|
||||
activeThreadId: z.string().min(1).nullable(),
|
||||
});
|
||||
|
||||
const runtimeModeSchema = z.enum(["approval-required", "full-access"]);
|
||||
|
||||
export const persistedStateV1Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(1).optional(),
|
||||
});
|
||||
@@ -52,19 +44,7 @@ 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(),
|
||||
});
|
||||
|
||||
const persistedStateSchema = z.union([
|
||||
persistedStateV4Schema,
|
||||
persistedStateV3Schema,
|
||||
persistedStateV2Schema,
|
||||
persistedStateV1Schema,
|
||||
]);
|
||||
@@ -73,10 +53,12 @@ export interface PersistedStoreSnapshot {
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
activeThreadId: string | null;
|
||||
runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
function maybeMigrateLegacyModel(model: string, isLegacyPayload: boolean): string {
|
||||
function maybeMigrateLegacyModel(
|
||||
model: string,
|
||||
isLegacyPayload: boolean,
|
||||
): string {
|
||||
if (!isLegacyPayload) {
|
||||
return model;
|
||||
}
|
||||
@@ -90,7 +72,9 @@ function hydrateProject(
|
||||
): Project {
|
||||
return {
|
||||
...project,
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
|
||||
model: resolveModelSlug(
|
||||
maybeMigrateLegacyModel(project.model, isLegacyPayload),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -100,10 +84,11 @@ function hydrateThread(
|
||||
): Thread {
|
||||
return {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
|
||||
model: resolveModelSlug(
|
||||
maybeMigrateLegacyModel(thread.model, isLegacyPayload),
|
||||
),
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => ({
|
||||
...message,
|
||||
@@ -140,7 +125,7 @@ export function hydratePersistedState(
|
||||
.filter((thread) => projectIds.has(thread.projectId));
|
||||
const hasActiveThread = Boolean(
|
||||
parsedState.data.activeThreadId &&
|
||||
threads.some((thread) => thread.id === parsedState.data.activeThreadId),
|
||||
threads.some((thread) => thread.id === parsedState.data.activeThreadId),
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -149,22 +134,17 @@ export function hydratePersistedState(
|
||||
activeThreadId: hasActiveThread
|
||||
? parsedState.data.activeThreadId
|
||||
: (threads[0]?.id ?? null),
|
||||
runtimeMode:
|
||||
"runtimeMode" in parsedState.data
|
||||
? parsedState.data.runtimeMode
|
||||
: DEFAULT_RUNTIME_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV4Schema> {
|
||||
): z.infer<typeof persistedStateV2Schema> {
|
||||
return {
|
||||
version: 4,
|
||||
version: 2,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
model: thread.model,
|
||||
@@ -172,6 +152,5 @@ export function toPersistedState(
|
||||
createdAt: thread.createdAt,
|
||||
})),
|
||||
activeThreadId: state.activeThreadId,
|
||||
runtimeMode: state.runtimeMode,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
|
||||
import {
|
||||
type WorkLogEntry,
|
||||
applyEventToMessages,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import type { ChatMessage } from "./types";
|
||||
|
||||
function makeEvent(overrides: Partial<ProviderEvent>): ProviderEvent {
|
||||
return {
|
||||
id: "evt-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
method: "noop",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(
|
||||
overrides: Partial<ProviderSession> = {},
|
||||
): ProviderSession {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-08T09:59:00.000Z",
|
||||
updatedAt: "2026-02-08T09:59:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveTimelineEntries", () => {
|
||||
it("interleaves messages and work entries by timestamp", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
id: "m-user",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-assistant",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:05:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const workEntries: WorkLogEntry[] = [
|
||||
{
|
||||
id: "w-1",
|
||||
label: "Tool call",
|
||||
createdAt: "2026-02-08T10:02:00.000Z",
|
||||
tone: "tool",
|
||||
},
|
||||
{
|
||||
id: "w-2",
|
||||
label: "Preamble",
|
||||
createdAt: "2026-02-08T10:03:00.000Z",
|
||||
tone: "thinking",
|
||||
},
|
||||
];
|
||||
|
||||
const timeline = deriveTimelineEntries(messages, workEntries);
|
||||
|
||||
expect(timeline.map((entry) => entry.id)).toEqual([
|
||||
"message:m-user",
|
||||
"work:w-1",
|
||||
"work:w-2",
|
||||
"message:m-assistant",
|
||||
]);
|
||||
});
|
||||
|
||||
it("prefers work entries when timestamps are equal", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const workEntries: WorkLogEntry[] = [
|
||||
{
|
||||
id: "w-1",
|
||||
label: "Tool call",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
tone: "tool",
|
||||
},
|
||||
];
|
||||
|
||||
const timeline = deriveTimelineEntries(messages, workEntries);
|
||||
|
||||
expect(timeline.map((entry) => entry.id)).toEqual([
|
||||
"work:w-1",
|
||||
"message:m-1",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries", () => {
|
||||
it("drops preamble/work events from the visible work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-1",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
payload: { item: { type: "preamble", text: "thinking" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-2",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { item: { type: "work", text: "planning" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-3",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: { item: { type: "tool_call", command: "ls -la" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Tool call");
|
||||
});
|
||||
|
||||
it("logs turn completion with elapsed time", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-complete",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:10.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries[0]?.label).toBe("Turn complete in 10s");
|
||||
});
|
||||
|
||||
it("hides reasoning and agent-message noise from the visible work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-summary-part",
|
||||
method: "item/reasoning/summaryPartAdded",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-summary-delta",
|
||||
method: "item/reasoning/summaryTextDelta",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-complete",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:04.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-msg",
|
||||
type: "agentMessage",
|
||||
text: "Done response",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-tool-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-tool-complete",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:06.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-complete",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:08.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries.map((entry) => entry.label)).toEqual([
|
||||
"Turn complete in 8.0s",
|
||||
"Tool call complete",
|
||||
"Tool call",
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves full tool-call detail text without data truncation", () => {
|
||||
const longCommand =
|
||||
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-tool-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: longCommand },
|
||||
},
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries[0]?.detail).toBe(longCommand);
|
||||
});
|
||||
|
||||
it("can derive work-log entries across all turns when not scoped", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-turn-1-tool",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { item: { type: "tool_call", command: "ls -la" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-2-tool",
|
||||
method: "item/started",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: { item: { type: "tool_call", command: "pwd" } },
|
||||
}),
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(2);
|
||||
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evolveSession", () => {
|
||||
it("updates thread id when thread starts", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "thread/started",
|
||||
createdAt: "2026-02-08T10:01:00.000Z",
|
||||
payload: { thread: { id: "thread-1" } },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.threadId).toBe("thread-1");
|
||||
expect(next.updatedAt).toBe("2026-02-08T10:01:00.000Z");
|
||||
});
|
||||
|
||||
it("moves to running and records active turn on turn start", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:02:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("running");
|
||||
expect(next.activeTurnId).toBe("turn-1");
|
||||
expect(next.updatedAt).toBe("2026-02-08T10:02:00.000Z");
|
||||
});
|
||||
|
||||
it("returns to ready and clears active turn on successful completion", () => {
|
||||
const previous = makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: "older error",
|
||||
});
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/completed",
|
||||
createdAt: "2026-02-08T10:03:00.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("ready");
|
||||
expect(next.activeTurnId).toBeUndefined();
|
||||
expect(next.lastError).toBe("older error");
|
||||
});
|
||||
|
||||
it("marks session as error when turn fails", () => {
|
||||
const previous = makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/completed",
|
||||
createdAt: "2026-02-08T10:03:00.000Z",
|
||||
payload: {
|
||||
turn: { id: "turn-1", status: "failed", error: { message: "boom" } },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("error");
|
||||
expect(next.activeTurnId).toBeUndefined();
|
||||
expect(next.lastError).toBe("boom");
|
||||
});
|
||||
|
||||
it("moves to error on runtime error events", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
kind: "error",
|
||||
method: "runtime/error",
|
||||
createdAt: "2026-02-08T10:04:00.000Z",
|
||||
message: "runtime failure",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("error");
|
||||
expect(next.lastError).toBe("runtime failure");
|
||||
});
|
||||
|
||||
it("closes session on close lifecycle events", () => {
|
||||
const previous = makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "session/closed",
|
||||
createdAt: "2026-02-08T10:05:00.000Z",
|
||||
message: "closed",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(next.status).toBe("closed");
|
||||
expect(next.activeTurnId).toBeUndefined();
|
||||
expect(next.lastError).toBe("closed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyEventToMessages", () => {
|
||||
it("handles start/delta/completed flow for assistant messages", () => {
|
||||
const activeAssistantItemRef = { current: null as string | null };
|
||||
const started = applyEventToMessages(
|
||||
[],
|
||||
makeEvent({
|
||||
method: "item/started",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-1",
|
||||
type: "agentMessage",
|
||||
text: "Hello",
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
|
||||
expect(started).toEqual([
|
||||
{
|
||||
id: "item-1",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
]);
|
||||
expect(activeAssistantItemRef.current).toBe("item-1");
|
||||
|
||||
const withDelta = applyEventToMessages(
|
||||
started,
|
||||
makeEvent({
|
||||
method: "item/agentMessage/delta",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
itemId: "item-1",
|
||||
textDelta: " world",
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
expect(withDelta[0]?.text).toBe("Hello world");
|
||||
expect(withDelta[0]?.streaming).toBe(true);
|
||||
|
||||
const completed = applyEventToMessages(
|
||||
withDelta,
|
||||
makeEvent({
|
||||
method: "item/completed",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-1",
|
||||
type: "agentMessage",
|
||||
text: "Hello world!",
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
expect(completed[0]?.text).toBe("Hello world!");
|
||||
expect(completed[0]?.streaming).toBe(false);
|
||||
expect(activeAssistantItemRef.current).toBeNull();
|
||||
});
|
||||
|
||||
it("supports out-of-order delta before started/completed", () => {
|
||||
const activeAssistantItemRef = { current: null as string | null };
|
||||
const withDelta = applyEventToMessages(
|
||||
[],
|
||||
makeEvent({
|
||||
method: "item/agentMessage/delta",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
itemId: "item-2",
|
||||
textDelta: "Partial",
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
expect(withDelta[0]?.id).toBe("item-2");
|
||||
expect(withDelta[0]?.text).toBe("Partial");
|
||||
expect(withDelta[0]?.streaming).toBe(true);
|
||||
expect(activeAssistantItemRef.current).toBe("item-2");
|
||||
|
||||
const completed = applyEventToMessages(
|
||||
withDelta,
|
||||
makeEvent({
|
||||
method: "item/completed",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-2",
|
||||
type: "agentMessage",
|
||||
text: "Partial + final",
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef,
|
||||
);
|
||||
|
||||
expect(completed[0]?.text).toBe("Partial + final");
|
||||
expect(completed[0]?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("clears all streaming flags when turn completes", () => {
|
||||
const previous: ChatMessage[] = [
|
||||
{
|
||||
id: "m-user",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-assistant",
|
||||
role: "assistant",
|
||||
text: "Typing",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
|
||||
const next = applyEventToMessages(
|
||||
previous,
|
||||
makeEvent({
|
||||
method: "turn/completed",
|
||||
}),
|
||||
{ current: null },
|
||||
);
|
||||
|
||||
expect(next.every((entry) => entry.streaming === false)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,591 @@
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderKind,
|
||||
ProviderSession,
|
||||
} from "@acme/contracts";
|
||||
import type { ChatMessage, SessionPhase } from "./types";
|
||||
|
||||
export const PROVIDER_OPTIONS: Array<{
|
||||
value: ProviderKind;
|
||||
label: string;
|
||||
available: boolean;
|
||||
}> = [
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
|
||||
];
|
||||
|
||||
export function readNativeApi() {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
return window.nativeApi;
|
||||
}
|
||||
|
||||
export function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function formatTimestamp(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
}).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
export function formatDuration(durationMs: number): string {
|
||||
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
|
||||
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
|
||||
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
|
||||
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
|
||||
|
||||
const minutes = Math.floor(durationMs / 60_000);
|
||||
const seconds = Math.round((durationMs % 60_000) / 1_000);
|
||||
if (seconds === 0) return `${minutes}m`;
|
||||
if (seconds === 60) return `${minutes + 1}m`;
|
||||
return `${minutes}m ${seconds}s`;
|
||||
}
|
||||
|
||||
export function formatElapsed(
|
||||
startIso: string,
|
||||
endIso: string | undefined,
|
||||
): string | null {
|
||||
if (!endIso) return null;
|
||||
|
||||
const startedAt = Date.parse(startIso);
|
||||
const endedAt = Date.parse(endIso);
|
||||
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return formatDuration(endedAt - startedAt);
|
||||
}
|
||||
|
||||
export interface WorkLogEntry {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
label: string;
|
||||
detail?: string;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
}
|
||||
|
||||
export type TimelineEntry =
|
||||
| {
|
||||
id: string;
|
||||
kind: "message";
|
||||
createdAt: string;
|
||||
message: ChatMessage;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
kind: "work";
|
||||
createdAt: string;
|
||||
entry: WorkLogEntry;
|
||||
};
|
||||
|
||||
function normalizeDetail(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeItemType(raw: string | undefined): string {
|
||||
if (!raw) return "item";
|
||||
return raw
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/[._/-]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function shouldDropItemType(type: string): boolean {
|
||||
if (
|
||||
type.includes("preamble") ||
|
||||
type.includes("reasoning") ||
|
||||
type.includes("thought")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return type === "work" || type.startsWith("work ");
|
||||
}
|
||||
|
||||
function shouldShowItemLifecycle(type: string): boolean {
|
||||
return (
|
||||
type.includes("tool") ||
|
||||
type.includes("command") ||
|
||||
type.includes("file change")
|
||||
);
|
||||
}
|
||||
|
||||
function shouldDropMethod(method: string): boolean {
|
||||
return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
|
||||
}
|
||||
|
||||
function itemTypeMeta(type: string): {
|
||||
label: string;
|
||||
tone: WorkLogEntry["tone"];
|
||||
} {
|
||||
if (type.includes("command")) {
|
||||
return { label: "Command run", tone: "tool" };
|
||||
}
|
||||
if (type.includes("file change")) {
|
||||
return { label: "File change", tone: "tool" };
|
||||
}
|
||||
if (type.includes("tool")) {
|
||||
return { label: "Tool call", tone: "tool" };
|
||||
}
|
||||
return { label: "Work item", tone: "info" };
|
||||
}
|
||||
|
||||
function extractDetail(
|
||||
payload: Record<string, unknown> | undefined,
|
||||
item: Record<string, unknown> | undefined,
|
||||
): string | undefined {
|
||||
const candidates = [
|
||||
asString(item?.title),
|
||||
asString(item?.summary),
|
||||
asString(item?.text),
|
||||
asString(item?.command),
|
||||
asString(payload?.message),
|
||||
asString(payload?.prompt),
|
||||
asString(payload?.command),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const detail = normalizeDetail(candidate);
|
||||
if (detail) return detail;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
const normalizedType = normalizeItemType(asString(item?.type));
|
||||
if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
|
||||
return null;
|
||||
}
|
||||
if (!shouldShowItemLifecycle(normalizedType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meta = itemTypeMeta(normalizedType);
|
||||
const isStarted = event.method === "item/started";
|
||||
const isCompleted = event.method === "item/completed";
|
||||
if (!isStarted && !isCompleted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const label = isCompleted ? `${meta.label} complete` : meta.label;
|
||||
const detail = extractDetail(payload, item);
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label,
|
||||
...(detail ? { detail } : {}),
|
||||
tone: meta.tone,
|
||||
};
|
||||
}
|
||||
|
||||
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
|
||||
if (event.kind !== "request") return null;
|
||||
if (shouldDropMethod(event.method)) return null;
|
||||
|
||||
if (event.method.includes("commandExecution")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "Command approval requested",
|
||||
tone: "tool",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method.includes("fileChange")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "File-change approval requested",
|
||||
tone: "tool",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method.includes("requestUserInput")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "Tool requested user input",
|
||||
tone: "tool",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: `Request: ${event.method}`,
|
||||
tone: "info",
|
||||
};
|
||||
}
|
||||
|
||||
function entryFromNotification(
|
||||
event: ProviderEvent,
|
||||
turnStartedAt: number,
|
||||
): WorkLogEntry | null {
|
||||
if (event.kind !== "notification") return null;
|
||||
if (shouldDropMethod(event.method)) return null;
|
||||
if (event.method === "item/agentMessage/delta") return null;
|
||||
if (event.method === "turn/started") {
|
||||
return null;
|
||||
}
|
||||
if (event.method === "thread/started") return null;
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
const status = asString(turn?.status);
|
||||
const turnError = asObject(turn?.error);
|
||||
const turnErrorMessage = asString(turnError?.message);
|
||||
const turnErrorDetail = normalizeDetail(turnErrorMessage);
|
||||
const eventAt = Date.parse(event.createdAt);
|
||||
const durationMs =
|
||||
Number.isNaN(turnStartedAt) ||
|
||||
Number.isNaN(eventAt) ||
|
||||
eventAt < turnStartedAt
|
||||
? undefined
|
||||
: eventAt - turnStartedAt;
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label:
|
||||
status === "failed"
|
||||
? "Turn failed"
|
||||
: durationMs !== undefined
|
||||
? `Turn complete in ${formatDuration(durationMs)}`
|
||||
: "Turn complete",
|
||||
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
|
||||
tone: status === "failed" ? "error" : "info",
|
||||
};
|
||||
}
|
||||
|
||||
const lifecycleEntry = entryFromItemLifecycle(event);
|
||||
if (lifecycleEntry) return lifecycleEntry;
|
||||
|
||||
if (event.method.startsWith("item/")) return null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
|
||||
if (event.kind !== "error") return null;
|
||||
if (shouldDropMethod(event.method)) return null;
|
||||
const detail = normalizeDetail(event.message);
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "Runtime error",
|
||||
...(detail ? { detail } : {}),
|
||||
tone: "error",
|
||||
};
|
||||
}
|
||||
|
||||
function eventTurnId(event: ProviderEvent): string | undefined {
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
return event.turnId ?? asString(turn?.id);
|
||||
}
|
||||
|
||||
export function deriveWorkLogEntries(
|
||||
events: ProviderEvent[],
|
||||
turnId: string | undefined,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = [...events].reverse();
|
||||
const entries: WorkLogEntry[] = [];
|
||||
const turnStartedAtIso = turnId
|
||||
? ordered.find((event) => {
|
||||
if (event.method !== "turn/started") return false;
|
||||
return eventTurnId(event) === turnId;
|
||||
})?.createdAt
|
||||
: undefined;
|
||||
const turnStartedAt = turnStartedAtIso
|
||||
? Date.parse(turnStartedAtIso)
|
||||
: Number.NaN;
|
||||
|
||||
for (const event of ordered) {
|
||||
if (turnId) {
|
||||
const scopedTurnId = eventTurnId(event);
|
||||
if (scopedTurnId && scopedTurnId !== turnId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
|
||||
const eventAt = Date.parse(event.createdAt);
|
||||
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fromRequest = entryFromRequest(event);
|
||||
if (fromRequest) {
|
||||
entries.push(fromRequest);
|
||||
continue;
|
||||
}
|
||||
|
||||
const fromNotification = entryFromNotification(event, turnStartedAt);
|
||||
if (fromNotification) {
|
||||
entries.push(fromNotification);
|
||||
continue;
|
||||
}
|
||||
|
||||
const fromError = entryFromError(event);
|
||||
if (fromError) {
|
||||
entries.push(fromError);
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function toTimestamp(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
||||
}
|
||||
|
||||
export function deriveTimelineEntries(
|
||||
messages: ChatMessage[],
|
||||
workEntries: WorkLogEntry[],
|
||||
): TimelineEntry[] {
|
||||
const timeline: TimelineEntry[] = [];
|
||||
let messageIndex = 0;
|
||||
let workIndex = 0;
|
||||
|
||||
while (messageIndex < messages.length || workIndex < workEntries.length) {
|
||||
const message = messages[messageIndex];
|
||||
const workEntry = workEntries[workIndex];
|
||||
|
||||
if (!message && workEntry) {
|
||||
timeline.push({
|
||||
id: `work:${workEntry.id}`,
|
||||
kind: "work",
|
||||
createdAt: workEntry.createdAt,
|
||||
entry: workEntry,
|
||||
});
|
||||
workIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!workEntry && message) {
|
||||
timeline.push({
|
||||
id: `message:${message.id}`,
|
||||
kind: "message",
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
});
|
||||
messageIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!message || !workEntry) {
|
||||
break;
|
||||
}
|
||||
|
||||
const messageAt = toTimestamp(message.createdAt);
|
||||
const workAt = toTimestamp(workEntry.createdAt);
|
||||
|
||||
if (workAt <= messageAt) {
|
||||
timeline.push({
|
||||
id: `work:${workEntry.id}`,
|
||||
kind: "work",
|
||||
createdAt: workEntry.createdAt,
|
||||
entry: workEntry,
|
||||
});
|
||||
workIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
timeline.push({
|
||||
id: `message:${message.id}`,
|
||||
kind: "message",
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
});
|
||||
messageIndex += 1;
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
export function derivePhase(session: ProviderSession | null): SessionPhase {
|
||||
if (!session || session.status === "closed") return "disconnected";
|
||||
if (session.status === "connecting") return "connecting";
|
||||
if (session.status === "running") return "running";
|
||||
return "ready";
|
||||
}
|
||||
|
||||
export function evolveSession(
|
||||
previous: ProviderSession,
|
||||
event: ProviderEvent,
|
||||
): ProviderSession {
|
||||
const payload = asObject(event.payload);
|
||||
|
||||
if (event.method === "thread/started") {
|
||||
const thread = asObject(payload?.thread);
|
||||
return {
|
||||
...previous,
|
||||
threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "turn/started") {
|
||||
const turn = asObject(payload?.turn);
|
||||
return {
|
||||
...previous,
|
||||
status: "running",
|
||||
activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
const turn = asObject(payload?.turn);
|
||||
const status = asString(turn?.status);
|
||||
const turnError = asObject(turn?.error);
|
||||
return {
|
||||
...previous,
|
||||
status: status === "failed" ? "error" : "ready",
|
||||
activeTurnId: undefined,
|
||||
lastError: asString(turnError?.message) ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.kind === "error") {
|
||||
return {
|
||||
...previous,
|
||||
status: "error",
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "session/closed" || event.method === "session/exited") {
|
||||
return {
|
||||
...previous,
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: event.message ?? previous.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
return { ...previous, updatedAt: event.createdAt };
|
||||
}
|
||||
|
||||
export function applyEventToMessages(
|
||||
previous: ChatMessage[],
|
||||
event: ProviderEvent,
|
||||
activeAssistantItemRef: { current: string | null },
|
||||
): ChatMessage[] {
|
||||
const payload = asObject(event.payload);
|
||||
|
||||
if (event.method === "item/started") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") return previous;
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) return previous;
|
||||
|
||||
activeAssistantItemRef.current = itemId;
|
||||
const seedText = asString(item?.text) ?? "";
|
||||
const filtered = previous.filter((entry) => entry.id !== itemId);
|
||||
return [
|
||||
...filtered,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: seedText,
|
||||
createdAt: event.createdAt,
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/agentMessage/delta") {
|
||||
const itemId = event.itemId ?? asString(payload?.itemId);
|
||||
const delta = event.textDelta ?? asString(payload?.delta) ?? "";
|
||||
if (!itemId || !delta) return previous;
|
||||
|
||||
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (existingIndex === -1) {
|
||||
activeAssistantItemRef.current = itemId;
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: delta,
|
||||
createdAt: event.createdAt,
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const updated = [...previous];
|
||||
const existing = updated[existingIndex];
|
||||
if (!existing) return previous;
|
||||
updated[existingIndex] = {
|
||||
...existing,
|
||||
text: `${existing.text}${delta}`,
|
||||
streaming: true,
|
||||
};
|
||||
return updated;
|
||||
}
|
||||
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(payload?.item);
|
||||
if (asString(item?.type) !== "agentMessage") return previous;
|
||||
const itemId = asString(item?.id);
|
||||
if (!itemId) return previous;
|
||||
|
||||
const fullText = asString(item?.text);
|
||||
const existingIndex = previous.findIndex((entry) => entry.id === itemId);
|
||||
if (existingIndex === -1) {
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: itemId,
|
||||
role: "assistant",
|
||||
text: fullText ?? "",
|
||||
createdAt: event.createdAt,
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const updated = [...previous];
|
||||
const existing = updated[existingIndex];
|
||||
if (!existing) return previous;
|
||||
updated[existingIndex] = {
|
||||
...existing,
|
||||
text: fullText ?? existing.text,
|
||||
streaming: false,
|
||||
};
|
||||
|
||||
if (activeAssistantItemRef.current === itemId) {
|
||||
activeAssistantItemRef.current = null;
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
return previous.map((entry) => ({ ...entry, streaming: false }));
|
||||
}
|
||||
|
||||
return previous;
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import {
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import {
|
||||
applyEventToMessages,
|
||||
asObject,
|
||||
asString,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import type { Project, Thread } from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: string }
|
||||
| { type: "ADD_THREAD"; thread: Thread }
|
||||
| { type: "SET_ACTIVE_THREAD"; threadId: string }
|
||||
| { type: "TOGGLE_DIFF" }
|
||||
| {
|
||||
type: "APPLY_EVENT";
|
||||
event: ProviderEvent;
|
||||
activeAssistantItemRef: { current: string | null };
|
||||
}
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
|
||||
| { type: "SET_ERROR"; threadId: string; error: string | null }
|
||||
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
|
||||
| { type: "SET_THREAD_MODEL"; threadId: string; model: string };
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AppState {
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
activeThreadId: string | null;
|
||||
diffOpen: boolean;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "codething:renderer-state:v2";
|
||||
const LEGACY_PERSISTED_STATE_KEY = "codething:renderer-state:v1";
|
||||
|
||||
const initialState: AppState = {
|
||||
projects: [],
|
||||
threads: [],
|
||||
activeThreadId: null,
|
||||
diffOpen: false,
|
||||
};
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const rawLegacy = window.localStorage.getItem(LEGACY_PERSISTED_STATE_KEY);
|
||||
const raw = rawCurrent ?? rawLegacy;
|
||||
if (!raw) return initialState;
|
||||
const hydrated = hydratePersistedState(
|
||||
raw,
|
||||
!rawCurrent && Boolean(rawLegacy),
|
||||
);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
return { ...hydrated, diffOpen: false };
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
}
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
PERSISTED_STATE_KEY,
|
||||
JSON.stringify(toPersistedState(state)),
|
||||
);
|
||||
window.localStorage.removeItem(LEGACY_PERSISTED_STATE_KEY);
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
threads: Thread[],
|
||||
threadId: string,
|
||||
updater: (t: Thread) => Thread,
|
||||
): Thread[] {
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
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 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 ──────────────────────────────────────────────────────────
|
||||
|
||||
function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "ADD_PROJECT":
|
||||
return {
|
||||
...state,
|
||||
projects: [
|
||||
...state.projects,
|
||||
{
|
||||
...action.project,
|
||||
model: resolveModelSlug(action.project.model),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
case "TOGGLE_PROJECT":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "ADD_THREAD":
|
||||
return {
|
||||
...state,
|
||||
threads: [
|
||||
...state.threads,
|
||||
{
|
||||
...action.thread,
|
||||
model: resolveModelSlug(action.thread.model),
|
||||
},
|
||||
],
|
||||
activeThreadId: action.thread.id,
|
||||
};
|
||||
|
||||
case "SET_ACTIVE_THREAD":
|
||||
return { ...state, activeThreadId: action.threadId };
|
||||
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "APPLY_EVENT": {
|
||||
const { event, activeAssistantItemRef } = action;
|
||||
const target = findThreadBySessionId(state.threads, event.sessionId);
|
||||
if (!target) return state;
|
||||
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, target.id, (t) => ({
|
||||
...t,
|
||||
session: t.session ? evolveSession(t.session, event) : t.session,
|
||||
messages: applyEventToMessages(
|
||||
t.messages,
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
),
|
||||
events: [event, ...t.events],
|
||||
error:
|
||||
event.kind === "error" && event.message ? event.message : t.error,
|
||||
...updateTurnFields(t, event),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
case "UPDATE_SESSION":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
session: action.session,
|
||||
events: [],
|
||||
error: null,
|
||||
latestTurnId: undefined,
|
||||
latestTurnStartedAt: undefined,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
})),
|
||||
};
|
||||
|
||||
case "PUSH_USER_MESSAGE":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
messages: [
|
||||
...t.messages,
|
||||
{
|
||||
id: action.id,
|
||||
role: "user" as const,
|
||||
text: action.text,
|
||||
createdAt: new Date().toISOString(),
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_ERROR":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
error: action.error,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TITLE":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
title: action.title,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_MODEL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
model: resolveModelSlug(action.model),
|
||||
})),
|
||||
};
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Context ──────────────────────────────────────────────────────────
|
||||
|
||||
const StoreContext = createContext<{
|
||||
state: AppState;
|
||||
dispatch: Dispatch<Action>;
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
export function useStore() {
|
||||
return useContext(StoreContext);
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { ProviderCoreEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
|
||||
|
||||
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
export type RuntimeMode = "approval-required" | "full-access";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
@@ -22,13 +20,12 @@ export interface Project {
|
||||
|
||||
export interface Thread {
|
||||
id: string;
|
||||
codexThreadId: string | null;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
session: ProviderSession | null;
|
||||
messages: ChatMessage[];
|
||||
events: ThreadEvent[];
|
||||
events: ProviderEvent[];
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
latestTurnId?: string | undefined;
|
||||
@@ -36,9 +33,3 @@ export interface Thread {
|
||||
latestTurnCompletedAt?: string | undefined;
|
||||
latestTurnDurationMs?: number | undefined;
|
||||
}
|
||||
|
||||
export interface ThreadEvent {
|
||||
seq: number;
|
||||
at: string;
|
||||
event: ProviderCoreEvent;
|
||||
}
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
import type { NativeApi } from "@acme/contracts";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
nativeApi?: NativeApi;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"jsx": "react-jsx",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
@@ -11,14 +11,8 @@ export default defineConfig({
|
||||
}),
|
||||
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 ?? "",
|
||||
),
|
||||
},
|
||||
server: {
|
||||
port: Number(process.env.PORT ?? 5173),
|
||||
port: Number(process.env.ELECTRON_RENDERER_PORT ?? 5173),
|
||||
strictPort: true,
|
||||
},
|
||||
build: {
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.1.0",
|
||||
"bin": {
|
||||
"t3": "./dist/index.js"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"scripts": {
|
||||
"dev": "VITE_DEV_SERVER_URL=http://localhost:5173 tsx src/index.ts",
|
||||
"dev:desktop": "T3CODE_MODE=desktop T3CODE_NO_BROWSER=1 tsx src/index.ts",
|
||||
"build": "tsup && node scripts/bundle-client.mjs",
|
||||
"start": "node dist/index.js",
|
||||
"start:desktop": "T3CODE_MODE=desktop T3CODE_NO_BROWSER=1 node dist/index.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsup": "^8.3.5",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/**
|
||||
* Copies the built web app into dist/client/ so the published npm package
|
||||
* includes the web UI. This runs as a post-build step.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webDist = path.resolve(__dirname, "../../web/dist");
|
||||
const target = path.resolve(__dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.cpSync(webDist, target, { recursive: true });
|
||||
console.log("✓ Bundled web app into dist/client");
|
||||
@@ -1,18 +0,0 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { fixPath } from "./fixPath";
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { createServer } from "./wsServer";
|
||||
|
||||
fixPath();
|
||||
|
||||
const DEFAULT_PORT = 3773;
|
||||
const cwd = process.cwd();
|
||||
const logger = createLogger("server");
|
||||
|
||||
type RuntimeMode = "web" | "desktop";
|
||||
|
||||
function parseBooleanEnv(value: string | undefined): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) return true;
|
||||
if (["0", "false", "no", "off"].includes(normalized)) return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePort(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
|
||||
throw new Error(`Invalid T3CODE_PORT: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function expandHomePath(input: string): string {
|
||||
if (input === "~") return os.homedir();
|
||||
if (input.startsWith("~/")) {
|
||||
return path.join(os.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function resolveStateDir(raw: string | undefined): string {
|
||||
if (!raw || raw.trim().length === 0) {
|
||||
return path.join(os.homedir(), ".t3", "userdata");
|
||||
}
|
||||
return path.resolve(expandHomePath(raw.trim()));
|
||||
}
|
||||
|
||||
async function findAvailablePort(preferred: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.listen(preferred, () => {
|
||||
server.close(() => resolve(preferred));
|
||||
});
|
||||
server.on("error", () => {
|
||||
// Preferred port busy — let the OS pick one
|
||||
const fallback = net.createServer();
|
||||
fallback.listen(0, () => {
|
||||
const addr = fallback.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
fallback.close(() => {
|
||||
if (port > 0) resolve(port);
|
||||
else reject(new Error("Could not find an available port."));
|
||||
});
|
||||
});
|
||||
fallback.on("error", reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function resolveStaticDir(): string | undefined {
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// Check for bundled client (npm publish / npx scenario):
|
||||
// dist/client/ lives alongside dist/index.js
|
||||
const bundledClient = path.resolve(__dirname, "client");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(bundledClient, "index.html"));
|
||||
if (stat.isFile()) return bundledClient;
|
||||
} catch {
|
||||
// Not bundled — check monorepo layout
|
||||
}
|
||||
|
||||
// Monorepo layout: apps/server/dist/index.js → apps/web/dist/
|
||||
const monorepoClient = path.resolve(__dirname, "../../web/dist");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(monorepoClient, "index.html"));
|
||||
if (stat.isFile()) return monorepoClient;
|
||||
} catch {
|
||||
// Not found — probably dev mode, Vite will serve
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web";
|
||||
const requestedPort = parsePort(process.env.T3CODE_PORT);
|
||||
const port =
|
||||
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
|
||||
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const projectRegistry = new ProjectRegistry(stateDir);
|
||||
const devUrl = process.env.VITE_DEV_SERVER_URL;
|
||||
const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
|
||||
const authToken = process.env.T3CODE_AUTH_TOKEN;
|
||||
const staticDir = devUrl ? undefined : resolveStaticDir();
|
||||
|
||||
if (!devUrl && !staticDir) {
|
||||
logger.warn("web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", {
|
||||
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
});
|
||||
}
|
||||
|
||||
const server = createServer({
|
||||
port,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
|
||||
const url = `http://localhost:${port}`;
|
||||
logger.info("T3 Code running", {
|
||||
url,
|
||||
cwd,
|
||||
mode,
|
||||
stateDir,
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
// Open browser (dynamic import because `open` is ESM-only)
|
||||
if (!noBrowser) {
|
||||
try {
|
||||
const open = await import("open");
|
||||
const target = devUrl ?? url;
|
||||
await open.default(target);
|
||||
} catch {
|
||||
logger.info("browser auto-open unavailable", {
|
||||
hint: `Open ${devUrl ?? url} in your browser.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
let shuttingDown = false;
|
||||
async function shutdown() {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
logger.info("shutting down");
|
||||
try {
|
||||
await server.stop();
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
logger.error("failed to stop server cleanly", { error });
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
void shutdown();
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
void shutdown();
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
logger.error("failed to start T3 Code", { error: err });
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,103 +0,0 @@
|
||||
import util from "node:util";
|
||||
|
||||
type LogLevel = "info" | "warn" | "error" | "event";
|
||||
|
||||
type LogContext = Record<string, unknown>;
|
||||
|
||||
const ANSI = {
|
||||
reset: "\u001b[0m",
|
||||
dim: "\u001b[2m",
|
||||
cyan: "\u001b[36m",
|
||||
yellow: "\u001b[33m",
|
||||
red: "\u001b[31m",
|
||||
magenta: "\u001b[35m",
|
||||
} as const;
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
info: "INFO",
|
||||
warn: "WARN",
|
||||
error: "ERROR",
|
||||
event: "EVENT",
|
||||
};
|
||||
|
||||
const LEVEL_COLOR: Record<LogLevel, string> = {
|
||||
info: ANSI.cyan,
|
||||
warn: ANSI.yellow,
|
||||
error: ANSI.red,
|
||||
event: ANSI.magenta,
|
||||
};
|
||||
|
||||
function useColors() {
|
||||
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
|
||||
}
|
||||
|
||||
function colorize(value: string, color: string, enabled: boolean) {
|
||||
return enabled ? `${color}${value}${ANSI.reset}` : value;
|
||||
}
|
||||
|
||||
function timeStamp() {
|
||||
return new Date().toISOString().slice(11, 23);
|
||||
}
|
||||
|
||||
function formatValue(value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean" ||
|
||||
value === null ||
|
||||
value === undefined
|
||||
) {
|
||||
return String(value);
|
||||
}
|
||||
return util.inspect(value, {
|
||||
depth: 4,
|
||||
breakLength: Infinity,
|
||||
compact: true,
|
||||
maxArrayLength: 25,
|
||||
maxStringLength: 320,
|
||||
});
|
||||
}
|
||||
|
||||
function formatContext(context: LogContext | undefined) {
|
||||
if (!context) return "";
|
||||
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
|
||||
if (entries.length === 0) return "";
|
||||
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
|
||||
}
|
||||
|
||||
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
|
||||
const colorEnabled = useColors();
|
||||
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
|
||||
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
|
||||
const contextText = formatContext(context);
|
||||
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
|
||||
|
||||
if (level === "warn") {
|
||||
console.warn(line);
|
||||
return;
|
||||
}
|
||||
if (level === "error") {
|
||||
console.error(line);
|
||||
return;
|
||||
}
|
||||
console.log(line);
|
||||
}
|
||||
|
||||
export function createLogger(scope: string) {
|
||||
return {
|
||||
info(message: string, context?: LogContext) {
|
||||
write("info", scope, message, context);
|
||||
},
|
||||
warn(message: string, context?: LogContext) {
|
||||
write("warn", scope, message, context);
|
||||
},
|
||||
error(message: string, context?: LogContext) {
|
||||
write("error", scope, message, context);
|
||||
},
|
||||
event(message: string, context?: LogContext) {
|
||||
write("event", scope, message, context);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
type ProjectAddInput,
|
||||
type ProjectAddResult,
|
||||
type ProjectListResult,
|
||||
type ProjectRecord,
|
||||
type ProjectRemoveInput,
|
||||
projectAddInputSchema,
|
||||
projectRecordSchema,
|
||||
projectRemoveInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
function normalizeCwd(rawCwd: string): string {
|
||||
const resolved = path.resolve(rawCwd.trim());
|
||||
const normalized = path.normalize(resolved);
|
||||
if (process.platform === "win32") {
|
||||
return normalized.toLowerCase();
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function isDirectory(cwd: string): boolean {
|
||||
try {
|
||||
return fs.statSync(cwd).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function inferProjectName(cwd: string): string {
|
||||
const name = path.basename(cwd);
|
||||
return name.length > 0 ? name : "project";
|
||||
}
|
||||
|
||||
export class ProjectRegistry {
|
||||
private readonly stateDir: string;
|
||||
private readonly filePath: string;
|
||||
private projects: ProjectRecord[];
|
||||
|
||||
constructor(stateDir: string) {
|
||||
this.stateDir = stateDir;
|
||||
this.filePath = path.join(this.stateDir, "projects.json");
|
||||
fs.mkdirSync(this.stateDir, { recursive: true });
|
||||
this.projects = this.loadFromDisk();
|
||||
}
|
||||
|
||||
list(): ProjectListResult {
|
||||
return this.projects.map((project) => ({ ...project }));
|
||||
}
|
||||
|
||||
add(raw: ProjectAddInput): ProjectAddResult {
|
||||
const input = projectAddInputSchema.parse(raw);
|
||||
const normalizedCwd = normalizeCwd(input.cwd);
|
||||
if (!isDirectory(normalizedCwd)) {
|
||||
throw new Error(`Project path does not exist: ${normalizedCwd}`);
|
||||
}
|
||||
|
||||
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
|
||||
if (existing) {
|
||||
return { project: { ...existing }, created: false };
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const project: ProjectRecord = {
|
||||
id: randomUUID(),
|
||||
cwd: normalizedCwd,
|
||||
name: inferProjectName(normalizedCwd),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.projects = [project, ...this.projects];
|
||||
this.persist();
|
||||
return { project: { ...project }, created: true };
|
||||
}
|
||||
|
||||
remove(raw: ProjectRemoveInput): void {
|
||||
const input = projectRemoveInputSchema.parse(raw);
|
||||
const next = this.projects.filter((project) => project.id !== input.id);
|
||||
if (next.length === this.projects.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.projects = next;
|
||||
this.persist();
|
||||
}
|
||||
|
||||
private loadFromDisk(): ProjectRecord[] {
|
||||
const loaded = this.readPersistedProjects();
|
||||
const deduped = new Map<string, ProjectRecord>();
|
||||
const normalizedProjects: ProjectRecord[] = [];
|
||||
|
||||
for (const project of loaded) {
|
||||
const normalizedCwd = normalizeCwd(project.cwd);
|
||||
if (!isDirectory(normalizedCwd)) {
|
||||
continue;
|
||||
}
|
||||
if (deduped.has(normalizedCwd)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedProject: ProjectRecord = {
|
||||
...project,
|
||||
cwd: normalizedCwd,
|
||||
name:
|
||||
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
|
||||
};
|
||||
deduped.set(normalizedCwd, normalizedProject);
|
||||
normalizedProjects.push(normalizedProject);
|
||||
}
|
||||
|
||||
const changed =
|
||||
normalizedProjects.length !== loaded.length ||
|
||||
normalizedProjects.some((project, index) => {
|
||||
const source = loaded[index];
|
||||
if (!source) return true;
|
||||
return (
|
||||
source.id !== project.id ||
|
||||
source.cwd !== project.cwd ||
|
||||
source.name !== project.name ||
|
||||
source.createdAt !== project.createdAt ||
|
||||
source.updatedAt !== project.updatedAt
|
||||
);
|
||||
});
|
||||
|
||||
if (changed) {
|
||||
this.projects = normalizedProjects;
|
||||
this.persist();
|
||||
}
|
||||
|
||||
return normalizedProjects;
|
||||
}
|
||||
|
||||
private readPersistedProjects(): ProjectRecord[] {
|
||||
try {
|
||||
const raw = fs.readFileSync(this.filePath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { projects?: unknown };
|
||||
if (!parsed || !Array.isArray(parsed.projects)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const projects: ProjectRecord[] = [];
|
||||
for (const candidate of parsed.projects) {
|
||||
const row = projectRecordSchema.safeParse(candidate);
|
||||
if (!row.success) {
|
||||
continue;
|
||||
}
|
||||
projects.push(row.data);
|
||||
}
|
||||
return projects;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
projects: this.projects,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const tempFile = `${this.filePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
fs.writeFileSync(tempFile, payload);
|
||||
fs.renameSync(tempFile, this.filePath);
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
import type { CanonicalSessionState, ProviderRawEvent } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProviderEventNormalizer } from "./providerEventNormalizer";
|
||||
|
||||
function makeRawEvent(overrides: Partial<ProviderRawEvent> = {}): ProviderRawEvent {
|
||||
return {
|
||||
id: "raw-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
method: "turn/started",
|
||||
payload: {
|
||||
thread: { id: "thread-1" },
|
||||
turn: { id: "turn-1" },
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(overrides: Partial<CanonicalSessionState> = {}): CanonicalSessionState {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProviderEventNormalizer", () => {
|
||||
it("maps turn start notifications to canonical session and turn events", () => {
|
||||
const normalizer = new ProviderEventNormalizer();
|
||||
|
||||
const normalized = normalizer.normalize(
|
||||
makeRawEvent({
|
||||
method: "turn/started",
|
||||
}),
|
||||
makeSession(),
|
||||
);
|
||||
|
||||
expect(normalized).toHaveLength(2);
|
||||
expect(normalized[0]?.type).toBe("session.updated");
|
||||
expect(normalized[1]?.type).toBe("turn.started");
|
||||
});
|
||||
|
||||
it("maps command approval requests and decision notifications", () => {
|
||||
const normalizer = new ProviderEventNormalizer();
|
||||
|
||||
const requested = normalizer.normalize(
|
||||
makeRawEvent({
|
||||
kind: "request",
|
||||
method: "item/commandExecution/requestApproval",
|
||||
requestId: "approval-1",
|
||||
payload: {
|
||||
thread: { id: "thread-1" },
|
||||
turn: { id: "turn-1" },
|
||||
command: "git status --short",
|
||||
},
|
||||
}),
|
||||
makeSession(),
|
||||
);
|
||||
|
||||
expect(requested.some((event) => event.type === "approval.requested")).toBe(true);
|
||||
|
||||
const resolved = normalizer.normalize(
|
||||
makeRawEvent({
|
||||
kind: "notification",
|
||||
method: "item/requestApproval/decision",
|
||||
requestId: "approval-1",
|
||||
payload: {
|
||||
requestId: "approval-1",
|
||||
decision: "acceptForSession",
|
||||
},
|
||||
}),
|
||||
makeSession(),
|
||||
);
|
||||
|
||||
const approvalResolved = resolved.find((event) => event.type === "approval.resolved");
|
||||
expect(approvalResolved).toBeDefined();
|
||||
if (!approvalResolved || approvalResolved.type !== "approval.resolved") {
|
||||
throw new Error("expected approval.resolved event");
|
||||
}
|
||||
expect(approvalResolved.decision).toBe("accept_for_session");
|
||||
});
|
||||
|
||||
it("drops unmapped methods from the core stream", () => {
|
||||
const normalizer = new ProviderEventNormalizer();
|
||||
|
||||
const normalized = normalizer.normalize(
|
||||
makeRawEvent({
|
||||
method: "item/reasoning/summaryPartAdded",
|
||||
payload: {
|
||||
text: "partial summary",
|
||||
},
|
||||
}),
|
||||
makeSession(),
|
||||
);
|
||||
|
||||
expect(normalized).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("maps message delta events when payload uses msg/message fallback fields", () => {
|
||||
const normalizer = new ProviderEventNormalizer();
|
||||
|
||||
const normalized = normalizer.normalize(
|
||||
makeRawEvent({
|
||||
method: "item/agentMessage/delta",
|
||||
threadId: undefined,
|
||||
turnId: undefined,
|
||||
itemId: undefined,
|
||||
payload: {
|
||||
msg: {
|
||||
id: "msg-1",
|
||||
thread_id: "thread-1",
|
||||
turn_id: "turn-1",
|
||||
},
|
||||
delta: "hello",
|
||||
},
|
||||
}),
|
||||
makeSession(),
|
||||
);
|
||||
|
||||
const delta = normalized.find((event) => event.type === "message.delta");
|
||||
expect(delta).toBeDefined();
|
||||
if (!delta || delta.type !== "message.delta") {
|
||||
throw new Error("expected message.delta event");
|
||||
}
|
||||
|
||||
expect(delta.messageId).toBe("msg-1");
|
||||
expect(delta.threadId).toBe("thread-1");
|
||||
expect(delta.turnId).toBe("turn-1");
|
||||
expect(delta.delta).toBe("hello");
|
||||
});
|
||||
|
||||
it("maps assistant message completion with assistantMessage type aliases", () => {
|
||||
const normalizer = new ProviderEventNormalizer();
|
||||
|
||||
const normalized = normalizer.normalize(
|
||||
makeRawEvent({
|
||||
method: "item/completed",
|
||||
itemId: "msg_abc",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
item: {
|
||||
id: "msg_abc",
|
||||
type: "assistant_message",
|
||||
text: "done",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeSession(),
|
||||
);
|
||||
|
||||
const completed = normalized.find((event) => event.type === "message.completed");
|
||||
expect(completed).toBeDefined();
|
||||
if (!completed || completed.type !== "message.completed") {
|
||||
throw new Error("expected message.completed event");
|
||||
}
|
||||
|
||||
expect(completed.messageId).toBe("msg_abc");
|
||||
expect(completed.text).toBe("done");
|
||||
});
|
||||
|
||||
it("creates debug.raw wrappers", () => {
|
||||
const normalizer = new ProviderEventNormalizer();
|
||||
const raw = makeRawEvent({ method: "item/reasoning/summaryPartAdded" });
|
||||
|
||||
const debug = normalizer.toDebugRaw(raw);
|
||||
|
||||
expect(debug.type).toBe("debug.raw");
|
||||
if (debug.type !== "debug.raw") {
|
||||
throw new Error("expected debug.raw event");
|
||||
}
|
||||
expect(debug.provider).toBe("codex");
|
||||
expect(debug.method).toBe("item/reasoning/summaryPartAdded");
|
||||
});
|
||||
});
|
||||
@@ -1,491 +0,0 @@
|
||||
import type {
|
||||
CanonicalSessionState,
|
||||
ProviderCoreEvent,
|
||||
ProviderRawEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function asBoolean(value: unknown): boolean | undefined {
|
||||
return typeof value === "boolean" ? value : undefined;
|
||||
}
|
||||
|
||||
function normalizeType(raw: string | undefined): string {
|
||||
if (!raw) return "";
|
||||
return raw.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
|
||||
}
|
||||
|
||||
function isAgentMessageType(raw: string | undefined): boolean {
|
||||
const normalized = normalizeType(raw);
|
||||
return normalized.includes("agentmessage") || normalized.includes("assistantmessage");
|
||||
}
|
||||
|
||||
function readThreadId(event: ProviderRawEvent): string | undefined {
|
||||
if (event.threadId) return event.threadId;
|
||||
const payload = asObject(event.payload);
|
||||
const thread = asObject(payload?.thread);
|
||||
const message = asObject(payload?.message);
|
||||
const msg = asObject(payload?.msg);
|
||||
return (
|
||||
asString(payload?.threadId) ??
|
||||
asString(payload?.thread_id) ??
|
||||
asString(payload?.conversationId) ??
|
||||
asString(thread?.id) ??
|
||||
asString(message?.threadId) ??
|
||||
asString(message?.thread_id) ??
|
||||
asString(msg?.threadId) ??
|
||||
asString(msg?.thread_id)
|
||||
);
|
||||
}
|
||||
|
||||
function readTurnId(event: ProviderRawEvent): string | undefined {
|
||||
if (event.turnId) return event.turnId;
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
const message = asObject(payload?.message);
|
||||
const msg = asObject(payload?.msg);
|
||||
return (
|
||||
asString(payload?.turnId) ??
|
||||
asString(payload?.turn_id) ??
|
||||
asString(turn?.id) ??
|
||||
asString(message?.turnId) ??
|
||||
asString(message?.turn_id) ??
|
||||
asString(msg?.turnId) ??
|
||||
asString(msg?.turn_id)
|
||||
);
|
||||
}
|
||||
|
||||
function readItemId(event: ProviderRawEvent): string | undefined {
|
||||
if (event.itemId) return event.itemId;
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
const message = asObject(payload?.message);
|
||||
const msg = asObject(payload?.msg);
|
||||
return (
|
||||
asString(payload?.itemId) ??
|
||||
asString(payload?.item_id) ??
|
||||
asString(payload?.messageId) ??
|
||||
asString(payload?.message_id) ??
|
||||
asString(payload?.msgId) ??
|
||||
asString(payload?.msg_id) ??
|
||||
asString(item?.id) ??
|
||||
asString(message?.id) ??
|
||||
asString(msg?.id)
|
||||
);
|
||||
}
|
||||
|
||||
function mapApprovalDecision(decision: string): "accept" | "accept_for_session" | "decline" | "cancel" | "timed_out" {
|
||||
switch (decision) {
|
||||
case "accept":
|
||||
return "accept";
|
||||
case "acceptForSession":
|
||||
return "accept_for_session";
|
||||
case "decline":
|
||||
return "decline";
|
||||
case "cancel":
|
||||
return "cancel";
|
||||
default:
|
||||
return "cancel";
|
||||
}
|
||||
}
|
||||
|
||||
function nextSessionState(
|
||||
raw: ProviderRawEvent,
|
||||
current: CanonicalSessionState | undefined,
|
||||
): CanonicalSessionState | undefined {
|
||||
const now = raw.createdAt;
|
||||
const base: CanonicalSessionState =
|
||||
current ?? {
|
||||
sessionId: raw.sessionId,
|
||||
provider: raw.provider,
|
||||
status: "ready",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const threadId = readThreadId(raw);
|
||||
const turnId = readTurnId(raw);
|
||||
const payload = asObject(raw.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
const turnStatus = asString(turn?.status);
|
||||
const turnError = asString(asObject(turn?.error)?.message);
|
||||
|
||||
if (raw.kind === "session") {
|
||||
if (raw.method === "session/connecting") {
|
||||
return {
|
||||
...base,
|
||||
status: "connecting",
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
if (raw.method === "session/ready") {
|
||||
return {
|
||||
...base,
|
||||
status: "ready",
|
||||
threadId: threadId ?? base.threadId,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
if (raw.method === "session/closed" || raw.method === "session/exited") {
|
||||
return {
|
||||
...base,
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: raw.message ?? base.lastError,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
if (raw.method === "session/startFailed") {
|
||||
return {
|
||||
...base,
|
||||
status: "error",
|
||||
lastError: raw.message ?? base.lastError,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (raw.method === "thread/started") {
|
||||
return {
|
||||
...base,
|
||||
threadId: threadId ?? base.threadId,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
if (raw.method === "turn/started") {
|
||||
return {
|
||||
...base,
|
||||
status: "running",
|
||||
threadId: threadId ?? base.threadId,
|
||||
activeTurnId: turnId ?? base.activeTurnId,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
if (raw.method === "turn/completed") {
|
||||
return {
|
||||
...base,
|
||||
status: turnStatus === "failed" ? "error" : "ready",
|
||||
threadId: threadId ?? base.threadId,
|
||||
activeTurnId: undefined,
|
||||
lastError: turnError ?? base.lastError,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
if (raw.kind === "error") {
|
||||
return {
|
||||
...base,
|
||||
status: "error",
|
||||
lastError: raw.message ?? base.lastError,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
if (raw.method === "error") {
|
||||
const errorMessage = asString(asObject(payload?.error)?.message);
|
||||
return {
|
||||
...base,
|
||||
status: "error",
|
||||
lastError: errorMessage ?? raw.message ?? base.lastError,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isActionableItemType(type: string | undefined): boolean {
|
||||
if (!type) return false;
|
||||
const normalized = type.toLowerCase();
|
||||
if (
|
||||
normalized.includes("agentmessage") ||
|
||||
normalized.includes("reasoning") ||
|
||||
normalized.includes("preamble")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function mapActivityLabel(type: string | undefined): string {
|
||||
const normalized = type?.toLowerCase() ?? "";
|
||||
if (normalized.includes("command")) return "Command run";
|
||||
if (normalized.includes("filechange") || normalized.includes("file_change")) {
|
||||
return "File change";
|
||||
}
|
||||
if (normalized.includes("tool")) return "Tool call";
|
||||
return "Activity";
|
||||
}
|
||||
|
||||
function mapActivityKind(type: string | undefined): "tool" | "plan" | "system" {
|
||||
const normalized = type?.toLowerCase() ?? "";
|
||||
if (normalized.includes("plan")) return "plan";
|
||||
if (normalized.includes("system")) return "system";
|
||||
return "tool";
|
||||
}
|
||||
|
||||
export interface ProviderEventAdapter {
|
||||
normalize(
|
||||
raw: ProviderRawEvent,
|
||||
currentSession: CanonicalSessionState | undefined,
|
||||
): ProviderCoreEvent[];
|
||||
toDebugRaw(raw: ProviderRawEvent): ProviderCoreEvent;
|
||||
}
|
||||
|
||||
export class ProviderEventNormalizer implements ProviderEventAdapter {
|
||||
normalize(
|
||||
raw: ProviderRawEvent,
|
||||
currentSession: CanonicalSessionState | undefined,
|
||||
): ProviderCoreEvent[] {
|
||||
const events: ProviderCoreEvent[] = [];
|
||||
const payload = asObject(raw.payload);
|
||||
const threadId = readThreadId(raw);
|
||||
const turnId = readTurnId(raw);
|
||||
const itemId = readItemId(raw);
|
||||
|
||||
const sessionUpdate = nextSessionState(raw, currentSession);
|
||||
if (sessionUpdate) {
|
||||
events.push({
|
||||
type: "session.updated",
|
||||
session: sessionUpdate,
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.method === "turn/started" && threadId && turnId) {
|
||||
events.push({
|
||||
type: "turn.started",
|
||||
sessionId: raw.sessionId,
|
||||
threadId,
|
||||
turnId,
|
||||
startedAt: raw.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.method === "turn/completed" && threadId && turnId) {
|
||||
const turn = asObject(payload?.turn);
|
||||
const status = asString(turn?.status);
|
||||
const turnError = asString(asObject(turn?.error)?.message);
|
||||
let outcome: "completed" | "failed" | "interrupted" = "completed";
|
||||
if (status === "failed") {
|
||||
outcome = "failed";
|
||||
} else if (status === "interrupted") {
|
||||
outcome = "interrupted";
|
||||
}
|
||||
events.push({
|
||||
type: "turn.completed",
|
||||
sessionId: raw.sessionId,
|
||||
threadId,
|
||||
turnId,
|
||||
completedAt: raw.createdAt,
|
||||
outcome,
|
||||
...(turnError ? { error: turnError } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.method === "item/agentMessage/delta" && threadId && itemId) {
|
||||
const delta =
|
||||
raw.textDelta ??
|
||||
asString(payload?.delta) ??
|
||||
asString(asObject(payload?.message)?.delta) ??
|
||||
asString(asObject(payload?.msg)?.delta) ??
|
||||
"";
|
||||
if (delta.length > 0) {
|
||||
events.push({
|
||||
type: "message.delta",
|
||||
sessionId: raw.sessionId,
|
||||
threadId,
|
||||
...(turnId ? { turnId } : {}),
|
||||
messageId: itemId,
|
||||
role: "assistant",
|
||||
delta,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (raw.method === "item/completed" && threadId) {
|
||||
const item = asObject(payload?.item);
|
||||
const itemType = asString(item?.type);
|
||||
const isAgentMessage =
|
||||
isAgentMessageType(itemType) ||
|
||||
(!!raw.itemId && raw.itemId.startsWith("msg_"));
|
||||
if (isAgentMessage) {
|
||||
const messageId = asString(item?.id) ?? itemId;
|
||||
const text = asString(item?.text) ?? "";
|
||||
if (messageId) {
|
||||
events.push({
|
||||
type: "message.completed",
|
||||
sessionId: raw.sessionId,
|
||||
threadId,
|
||||
...(turnId ? { turnId } : {}),
|
||||
messageId,
|
||||
role: "assistant",
|
||||
text,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
raw.method === "item/commandExecution/requestApproval" &&
|
||||
raw.requestId
|
||||
) {
|
||||
const command = asString(payload?.command);
|
||||
const reason = asString(payload?.reason);
|
||||
events.push({
|
||||
type: "approval.requested",
|
||||
sessionId: raw.sessionId,
|
||||
...(threadId ? { threadId } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
approvalId: raw.requestId,
|
||||
approvalKind: "command",
|
||||
title: "Command approval requested",
|
||||
...(command ? { detail: command } : reason ? { detail: reason } : {}),
|
||||
payload: raw.payload,
|
||||
requestedAt: raw.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.method === "item/fileChange/requestApproval" && raw.requestId) {
|
||||
const reason = asString(payload?.reason);
|
||||
events.push({
|
||||
type: "approval.requested",
|
||||
sessionId: raw.sessionId,
|
||||
...(threadId ? { threadId } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
approvalId: raw.requestId,
|
||||
approvalKind: "file_change",
|
||||
title: "File change approval requested",
|
||||
...(reason ? { detail: reason } : {}),
|
||||
payload: raw.payload,
|
||||
requestedAt: raw.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.method === "item/tool/requestUserInput") {
|
||||
const approvalId = raw.requestId ?? raw.id;
|
||||
events.push({
|
||||
type: "approval.requested",
|
||||
sessionId: raw.sessionId,
|
||||
...(threadId ? { threadId } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
approvalId,
|
||||
approvalKind: "user_input",
|
||||
title: "Tool requested user input",
|
||||
payload: raw.payload,
|
||||
requestedAt: raw.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.method === "item/requestApproval/decision" && raw.requestId) {
|
||||
const decision = mapApprovalDecision(
|
||||
asString(payload?.decision) ?? "cancel",
|
||||
);
|
||||
events.push({
|
||||
type: "approval.resolved",
|
||||
sessionId: raw.sessionId,
|
||||
approvalId: raw.requestId,
|
||||
decision,
|
||||
resolvedAt: raw.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.method === "item/started" || raw.method === "item/completed") {
|
||||
const item = asObject(payload?.item);
|
||||
const itemType = asString(item?.type);
|
||||
const itemText = asString(item?.text);
|
||||
const isAgentMessage = isAgentMessageType(itemType);
|
||||
if (raw.method === "item/started" && threadId && itemId && isAgentMessage) {
|
||||
if (itemText && itemText.length > 0) {
|
||||
events.push({
|
||||
type: "message.delta",
|
||||
sessionId: raw.sessionId,
|
||||
threadId,
|
||||
...(turnId ? { turnId } : {}),
|
||||
messageId: itemId,
|
||||
role: "assistant",
|
||||
delta: itemText,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (threadId && itemId && isActionableItemType(itemType)) {
|
||||
events.push({
|
||||
type: "activity",
|
||||
sessionId: raw.sessionId,
|
||||
threadId,
|
||||
...(turnId ? { turnId } : {}),
|
||||
activityId: itemId,
|
||||
activityKind: mapActivityKind(itemType),
|
||||
label: mapActivityLabel(itemType),
|
||||
...(asString(item?.command) ? { detail: asString(item?.command) } : {}),
|
||||
status: raw.method === "item/started" ? "created" : "success",
|
||||
...(raw.method === "item/started"
|
||||
? { startedAt: raw.createdAt }
|
||||
: { completedAt: raw.createdAt }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (raw.method === "turn/plan/updated" && threadId) {
|
||||
const explanation = asString(payload?.explanation);
|
||||
const plan = payload?.plan;
|
||||
events.push({
|
||||
type: "activity",
|
||||
sessionId: raw.sessionId,
|
||||
threadId,
|
||||
...(turnId ? { turnId } : {}),
|
||||
activityId: raw.id,
|
||||
activityKind: "plan",
|
||||
label: "Plan updated",
|
||||
...(explanation ? { detail: explanation } : {}),
|
||||
status: "success",
|
||||
completedAt: raw.createdAt,
|
||||
...(explanation || plan
|
||||
? {
|
||||
extensions: {
|
||||
"codex.turn.plan": {
|
||||
explanation: explanation ?? null,
|
||||
plan: plan ?? null,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.kind === "error" || raw.method === "error") {
|
||||
const notificationMessage = asString(asObject(payload?.error)?.message);
|
||||
const retryable = asBoolean(payload?.willRetry) ?? asBoolean(payload?.will_retry);
|
||||
const message = notificationMessage ?? raw.message ?? "Provider error";
|
||||
events.push({
|
||||
type: "error",
|
||||
sessionId: raw.sessionId,
|
||||
...(threadId ? { threadId } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
code: raw.method,
|
||||
message,
|
||||
...(retryable !== undefined ? { retryable } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
toDebugRaw(raw: ProviderRawEvent): ProviderCoreEvent {
|
||||
return {
|
||||
type: "debug.raw",
|
||||
provider: raw.provider,
|
||||
sessionId: raw.sessionId,
|
||||
method: raw.method,
|
||||
payload: raw.payload ?? null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
import type { CanonicalSessionState } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROVIDER_STREAM_MAX_REPLAY_EVENTS,
|
||||
ProviderStreamStore,
|
||||
providerStreamEventKindOf,
|
||||
} from "./providerStreamStore";
|
||||
|
||||
function makeSessionState(overrides: Partial<CanonicalSessionState> = {}): CanonicalSessionState {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProviderStreamStore", () => {
|
||||
it("stores events in seq order and builds snapshot state", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
const baseMs = Date.now();
|
||||
const at = (offsetSeconds: number) => new Date(baseMs + offsetSeconds * 1_000).toISOString();
|
||||
|
||||
store.appendEvent(
|
||||
{
|
||||
type: "session.updated",
|
||||
session: makeSessionState(),
|
||||
},
|
||||
at(0),
|
||||
);
|
||||
|
||||
store.appendEvent(
|
||||
{
|
||||
type: "turn.started",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
startedAt: at(1),
|
||||
},
|
||||
at(1),
|
||||
);
|
||||
|
||||
store.appendEvent(
|
||||
{
|
||||
type: "message.delta",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
messageId: "msg-1",
|
||||
role: "assistant",
|
||||
delta: "Hello",
|
||||
},
|
||||
at(2),
|
||||
);
|
||||
|
||||
store.appendEvent(
|
||||
{
|
||||
type: "approval.requested",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
approvalId: "approval-1",
|
||||
approvalKind: "command",
|
||||
title: "Command approval requested",
|
||||
requestedAt: at(3),
|
||||
},
|
||||
at(3),
|
||||
);
|
||||
|
||||
const snapshot = store.getSnapshot();
|
||||
expect(snapshot.sessions).toHaveLength(1);
|
||||
expect(snapshot.activeTurns).toHaveLength(1);
|
||||
expect(snapshot.activeMessages).toHaveLength(1);
|
||||
expect(snapshot.pendingApprovals).toHaveLength(1);
|
||||
|
||||
const replay = store.selectReplay(1, 10);
|
||||
expect(replay.ok).toBe(true);
|
||||
if (!replay.ok) {
|
||||
throw new Error("expected replay selection");
|
||||
}
|
||||
expect(replay.events.map((entry) => entry.seq)).toEqual([2, 3, 4]);
|
||||
});
|
||||
|
||||
it("returns cursor_ahead and replay_limit_exceeded when needed", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
const baseMs = Date.now();
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
store.appendEvent(
|
||||
{
|
||||
type: "error",
|
||||
sessionId: "sess-1",
|
||||
code: "runtime/error",
|
||||
message: `err-${i}`,
|
||||
},
|
||||
new Date(baseMs + i * 1_000).toISOString(),
|
||||
);
|
||||
}
|
||||
|
||||
const ahead = store.selectReplay(30, 10);
|
||||
expect(ahead.ok).toBe(false);
|
||||
if (ahead.ok) {
|
||||
throw new Error("expected gap selection");
|
||||
}
|
||||
expect(ahead.reason).toBe("cursor_ahead");
|
||||
|
||||
const overLimit = store.selectReplay(0, 10);
|
||||
expect(overLimit.ok).toBe(false);
|
||||
if (overLimit.ok) {
|
||||
throw new Error("expected replay_limit_exceeded");
|
||||
}
|
||||
expect(overLimit.reason).toBe("replay_limit_exceeded");
|
||||
});
|
||||
|
||||
it("evicts old events and reports cursor_too_old", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
|
||||
for (let i = 0; i < PROVIDER_STREAM_MAX_REPLAY_EVENTS + 10; i += 1) {
|
||||
store.appendEvent(
|
||||
{
|
||||
type: "error",
|
||||
sessionId: "sess-1",
|
||||
code: "runtime/error",
|
||||
message: `err-${i}`,
|
||||
},
|
||||
"2026-02-10T00:00:00.000Z",
|
||||
);
|
||||
}
|
||||
|
||||
const oldestSeq = store.oldestSeq;
|
||||
expect(oldestSeq).toBeGreaterThan(1);
|
||||
|
||||
const stale = store.selectReplay(Math.max(0, oldestSeq - 2), 100);
|
||||
expect(stale.ok).toBe(false);
|
||||
if (stale.ok) {
|
||||
throw new Error("expected cursor_too_old");
|
||||
}
|
||||
expect(stale.reason).toBe("cursor_too_old");
|
||||
});
|
||||
|
||||
it("filters snapshot by session id", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
|
||||
store.appendEvent({
|
||||
type: "session.updated",
|
||||
session: makeSessionState({ sessionId: "sess-a" }),
|
||||
});
|
||||
store.appendEvent({
|
||||
type: "session.updated",
|
||||
session: makeSessionState({ sessionId: "sess-b" }),
|
||||
});
|
||||
|
||||
const filtered = store.getSnapshot(new Set(["sess-a"]));
|
||||
expect(filtered.sessions).toHaveLength(1);
|
||||
expect(filtered.sessions[0]?.sessionId).toBe("sess-a");
|
||||
});
|
||||
|
||||
it("classifies provider stream event kinds", () => {
|
||||
expect(
|
||||
providerStreamEventKindOf({
|
||||
type: "message.delta",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
messageId: "msg-1",
|
||||
role: "assistant",
|
||||
delta: "x",
|
||||
}),
|
||||
).toBe("message");
|
||||
|
||||
expect(
|
||||
providerStreamEventKindOf({
|
||||
type: "debug.raw",
|
||||
provider: "codex",
|
||||
method: "thread/started",
|
||||
payload: null,
|
||||
}),
|
||||
).toBe("debug.raw");
|
||||
});
|
||||
});
|
||||
@@ -1,428 +0,0 @@
|
||||
import type {
|
||||
CanonicalApprovalState,
|
||||
CanonicalMessageState,
|
||||
CanonicalSessionState,
|
||||
CanonicalTurnState,
|
||||
ProviderCoreEvent,
|
||||
ProviderSnapshot,
|
||||
ProviderStreamEventKind,
|
||||
ProviderStreamFrame,
|
||||
ProviderStreamGapReason,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export const PROVIDER_STREAM_MAX_REPLAY_EVENTS = 20_000;
|
||||
export const PROVIDER_STREAM_MAX_REPLAY_BYTES = 64 * 1024 * 1024;
|
||||
export const PROVIDER_STREAM_MAX_REPLAY_AGE_MS = 60 * 60 * 1_000;
|
||||
export const PROVIDER_STREAM_REPLAY_OPEN_LIMIT = 10_000;
|
||||
|
||||
interface StoredStreamEvent {
|
||||
seq: number;
|
||||
at: string;
|
||||
data: ProviderCoreEvent;
|
||||
encodedSize: number;
|
||||
}
|
||||
|
||||
export type ReplaySelection =
|
||||
| {
|
||||
ok: true;
|
||||
currentSeq: number;
|
||||
oldestSeq: number;
|
||||
events: Array<Pick<StoredStreamEvent, "seq" | "at" | "data">>;
|
||||
}
|
||||
| {
|
||||
ok: false;
|
||||
currentSeq: number;
|
||||
oldestSeq: number;
|
||||
reason: ProviderStreamGapReason;
|
||||
};
|
||||
|
||||
function parseIsoToMs(value: string): number {
|
||||
const parsed = Date.parse(value);
|
||||
if (Number.isNaN(parsed)) {
|
||||
return Date.now();
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function sessionEventKey(sessionId: string, id: string): string {
|
||||
return `${sessionId}:${id}`;
|
||||
}
|
||||
|
||||
function eventSizeBytes(seq: number, at: string, data: ProviderCoreEvent): number {
|
||||
return Buffer.byteLength(JSON.stringify({ kind: "event", seq, at, data }));
|
||||
}
|
||||
|
||||
function eventKindOf(event: ProviderCoreEvent): ProviderStreamEventKind {
|
||||
if (event.type === "session.updated") {
|
||||
return "session";
|
||||
}
|
||||
if (event.type === "turn.started" || event.type === "turn.completed") {
|
||||
return "turn";
|
||||
}
|
||||
if (event.type === "message.delta" || event.type === "message.completed") {
|
||||
return "message";
|
||||
}
|
||||
if (event.type === "approval.requested" || event.type === "approval.resolved") {
|
||||
return "approval";
|
||||
}
|
||||
if (event.type === "activity") {
|
||||
return "activity";
|
||||
}
|
||||
if (event.type === "error") {
|
||||
return "error";
|
||||
}
|
||||
return "debug.raw";
|
||||
}
|
||||
|
||||
export function providerStreamEventKindOf(
|
||||
event: ProviderCoreEvent,
|
||||
): ProviderStreamEventKind {
|
||||
return eventKindOf(event);
|
||||
}
|
||||
|
||||
export function providerStreamEventSessionId(
|
||||
event: ProviderCoreEvent,
|
||||
): string | undefined {
|
||||
if (event.type === "session.updated") {
|
||||
return event.session.sessionId;
|
||||
}
|
||||
|
||||
if (event.type === "debug.raw") {
|
||||
return event.sessionId;
|
||||
}
|
||||
|
||||
return event.sessionId;
|
||||
}
|
||||
|
||||
export function filterEventExtensions(
|
||||
event: ProviderCoreEvent,
|
||||
includeExtensions: ReadonlySet<string>,
|
||||
): ProviderCoreEvent {
|
||||
if (!("extensions" in event)) {
|
||||
return event;
|
||||
}
|
||||
|
||||
if (!event.extensions || includeExtensions.size === 0) {
|
||||
const withoutExtensions = { ...event };
|
||||
delete withoutExtensions.extensions;
|
||||
return withoutExtensions;
|
||||
}
|
||||
|
||||
const filtered: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(event.extensions)) {
|
||||
if (includeExtensions.has(key)) {
|
||||
filtered[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(filtered).length === 0) {
|
||||
const withoutExtensions = { ...event };
|
||||
delete withoutExtensions.extensions;
|
||||
return withoutExtensions;
|
||||
}
|
||||
|
||||
return {
|
||||
...event,
|
||||
extensions: filtered,
|
||||
};
|
||||
}
|
||||
|
||||
function isFromSessionFilter(
|
||||
sessionIds: ReadonlySet<string> | undefined,
|
||||
sessionId: string,
|
||||
): boolean {
|
||||
if (!sessionIds || sessionIds.size === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return sessionIds.has(sessionId);
|
||||
}
|
||||
|
||||
export class ProviderStreamStore {
|
||||
private nextSeq = 1;
|
||||
private replayLog: StoredStreamEvent[] = [];
|
||||
private replayBytes = 0;
|
||||
|
||||
private readonly sessionsById = new Map<string, CanonicalSessionState>();
|
||||
private readonly activeTurnsByKey = new Map<string, CanonicalTurnState>();
|
||||
private readonly activeMessagesByKey = new Map<string, CanonicalMessageState>();
|
||||
private readonly pendingApprovalsByKey = new Map<string, CanonicalApprovalState>();
|
||||
|
||||
appendEvent(event: ProviderCoreEvent, at = new Date().toISOString()): ProviderStreamFrame {
|
||||
const seq = this.nextSeq;
|
||||
this.nextSeq += 1;
|
||||
|
||||
this.applyEvent(event, at);
|
||||
|
||||
const encodedSize = eventSizeBytes(seq, at, event);
|
||||
this.replayLog.push({
|
||||
seq,
|
||||
at,
|
||||
data: event,
|
||||
encodedSize,
|
||||
});
|
||||
this.replayBytes += encodedSize;
|
||||
|
||||
this.pruneReplayLog(parseIsoToMs(at));
|
||||
|
||||
return {
|
||||
kind: "event",
|
||||
seq,
|
||||
at,
|
||||
data: event,
|
||||
};
|
||||
}
|
||||
|
||||
buildSnapshotFrame(
|
||||
at = new Date().toISOString(),
|
||||
sessionIds?: ReadonlySet<string>,
|
||||
): ProviderStreamFrame {
|
||||
return {
|
||||
kind: "snapshot",
|
||||
seq: this.currentSeq,
|
||||
at,
|
||||
data: this.getSnapshot(sessionIds),
|
||||
};
|
||||
}
|
||||
|
||||
buildGapFrame(
|
||||
reason: ProviderStreamGapReason,
|
||||
at = new Date().toISOString(),
|
||||
): ProviderStreamFrame {
|
||||
return {
|
||||
kind: "gap",
|
||||
seq: this.currentSeq,
|
||||
at,
|
||||
data: {
|
||||
reason,
|
||||
oldestSeq: this.oldestSeq,
|
||||
currentSeq: this.currentSeq,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
selectReplay(afterSeq: number, replayLimit: number): ReplaySelection {
|
||||
const currentSeq = this.currentSeq;
|
||||
const oldestSeq = this.oldestSeq;
|
||||
const minimumValidCursor = Math.max(0, oldestSeq - 1);
|
||||
|
||||
if (afterSeq > currentSeq) {
|
||||
return {
|
||||
ok: false,
|
||||
currentSeq,
|
||||
oldestSeq,
|
||||
reason: "cursor_ahead",
|
||||
};
|
||||
}
|
||||
|
||||
if (afterSeq < minimumValidCursor) {
|
||||
return {
|
||||
ok: false,
|
||||
currentSeq,
|
||||
oldestSeq,
|
||||
reason: "cursor_too_old",
|
||||
};
|
||||
}
|
||||
|
||||
const firstMissingIndex = this.replayLog.findIndex((entry) => entry.seq > afterSeq);
|
||||
const replayStartIndex = firstMissingIndex === -1 ? this.replayLog.length : firstMissingIndex;
|
||||
const missingCount = this.replayLog.length - replayStartIndex;
|
||||
|
||||
if (missingCount > replayLimit) {
|
||||
return {
|
||||
ok: false,
|
||||
currentSeq,
|
||||
oldestSeq,
|
||||
reason: "replay_limit_exceeded",
|
||||
};
|
||||
}
|
||||
|
||||
const events = this.replayLog
|
||||
.slice(replayStartIndex)
|
||||
.map((entry) => ({
|
||||
seq: entry.seq,
|
||||
at: entry.at,
|
||||
data: entry.data,
|
||||
}));
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
currentSeq,
|
||||
oldestSeq,
|
||||
events,
|
||||
};
|
||||
}
|
||||
|
||||
getSession(sessionId: string): CanonicalSessionState | undefined {
|
||||
return this.sessionsById.get(sessionId);
|
||||
}
|
||||
|
||||
getSnapshot(sessionIds?: ReadonlySet<string>): ProviderSnapshot {
|
||||
const sessions = Array.from(this.sessionsById.values()).filter((session) =>
|
||||
isFromSessionFilter(sessionIds, session.sessionId),
|
||||
);
|
||||
const allowedSessionIds = new Set(sessions.map((session) => session.sessionId));
|
||||
|
||||
const activeTurns = Array.from(this.activeTurnsByKey.values()).filter((turn) =>
|
||||
allowedSessionIds.has(turn.sessionId),
|
||||
);
|
||||
const activeMessages = Array.from(this.activeMessagesByKey.values()).filter((message) =>
|
||||
allowedSessionIds.has(message.sessionId),
|
||||
);
|
||||
const pendingApprovals = Array.from(this.pendingApprovalsByKey.values()).filter((approval) =>
|
||||
allowedSessionIds.has(approval.sessionId),
|
||||
);
|
||||
|
||||
return {
|
||||
sessions,
|
||||
activeTurns,
|
||||
activeMessages,
|
||||
pendingApprovals,
|
||||
};
|
||||
}
|
||||
|
||||
get currentSeq(): number {
|
||||
if (this.nextSeq <= 1) {
|
||||
return 0;
|
||||
}
|
||||
return this.nextSeq - 1;
|
||||
}
|
||||
|
||||
get oldestSeq(): number {
|
||||
const first = this.replayLog[0];
|
||||
if (first) {
|
||||
return first.seq;
|
||||
}
|
||||
return this.currentSeq;
|
||||
}
|
||||
|
||||
private pruneReplayLog(nowMs: number): void {
|
||||
while (this.replayLog.length > 0) {
|
||||
const first = this.replayLog[0];
|
||||
if (!first) {
|
||||
return;
|
||||
}
|
||||
|
||||
const overCount = this.replayLog.length > PROVIDER_STREAM_MAX_REPLAY_EVENTS;
|
||||
const overBytes = this.replayBytes > PROVIDER_STREAM_MAX_REPLAY_BYTES;
|
||||
const tooOld = nowMs - parseIsoToMs(first.at) > PROVIDER_STREAM_MAX_REPLAY_AGE_MS;
|
||||
|
||||
if (!overCount && !overBytes && !tooOld) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.replayLog.shift();
|
||||
this.replayBytes -= first.encodedSize;
|
||||
}
|
||||
}
|
||||
|
||||
private applyEvent(event: ProviderCoreEvent, at: string): void {
|
||||
if (event.type === "session.updated") {
|
||||
this.sessionsById.set(event.session.sessionId, event.session);
|
||||
|
||||
if (event.session.status === "closed") {
|
||||
this.removeSessionState(event.session.sessionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "turn.started") {
|
||||
this.activeTurnsByKey.set(
|
||||
sessionEventKey(event.sessionId, event.turnId),
|
||||
{
|
||||
sessionId: event.sessionId,
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId,
|
||||
startedAt: event.startedAt,
|
||||
...(event.model ? { model: event.model } : {}),
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
this.activeTurnsByKey.delete(sessionEventKey(event.sessionId, event.turnId));
|
||||
this.removeTurnTransientState(event.sessionId, event.turnId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "message.delta") {
|
||||
const key = sessionEventKey(event.sessionId, event.messageId);
|
||||
const previous = this.activeMessagesByKey.get(key);
|
||||
this.activeMessagesByKey.set(key, {
|
||||
sessionId: event.sessionId,
|
||||
threadId: event.threadId,
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
messageId: event.messageId,
|
||||
role: "assistant",
|
||||
text: `${previous?.text ?? ""}${event.delta}`,
|
||||
startedAt: previous?.startedAt ?? at,
|
||||
updatedAt: at,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "message.completed") {
|
||||
this.activeMessagesByKey.delete(sessionEventKey(event.sessionId, event.messageId));
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "approval.requested") {
|
||||
this.pendingApprovalsByKey.set(
|
||||
sessionEventKey(event.sessionId, event.approvalId),
|
||||
{
|
||||
sessionId: event.sessionId,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
approvalId: event.approvalId,
|
||||
approvalKind: event.approvalKind,
|
||||
title: event.title,
|
||||
...(event.detail ? { detail: event.detail } : {}),
|
||||
...(event.payload !== undefined ? { payload: event.payload } : {}),
|
||||
...(event.timeoutAt ? { timeoutAt: event.timeoutAt } : {}),
|
||||
requestedAt: event.requestedAt,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "approval.resolved") {
|
||||
this.pendingApprovalsByKey.delete(sessionEventKey(event.sessionId, event.approvalId));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private removeSessionState(sessionId: string): void {
|
||||
for (const key of this.activeTurnsByKey.keys()) {
|
||||
if (key.startsWith(`${sessionId}:`)) {
|
||||
this.activeTurnsByKey.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of this.activeMessagesByKey.keys()) {
|
||||
if (key.startsWith(`${sessionId}:`)) {
|
||||
this.activeMessagesByKey.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of this.pendingApprovalsByKey.keys()) {
|
||||
if (key.startsWith(`${sessionId}:`)) {
|
||||
this.pendingApprovalsByKey.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private removeTurnTransientState(sessionId: string, turnId: string): void {
|
||||
for (const [key, message] of this.activeMessagesByKey.entries()) {
|
||||
if (message.sessionId === sessionId && message.turnId === turnId) {
|
||||
this.activeMessagesByKey.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, approval] of this.pendingApprovalsByKey.entries()) {
|
||||
if (approval.sessionId === sessionId && approval.turnId === turnId) {
|
||||
this.pendingApprovalsByKey.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ProviderStreamStore } from "./providerStreamStore";
|
||||
import { ProviderStreamSubscriptionManager } from "./providerStreamSubscriptionManager";
|
||||
|
||||
interface FakeSocket {
|
||||
OPEN: number;
|
||||
readyState: number;
|
||||
bufferedAmount: number;
|
||||
sent: unknown[];
|
||||
send: (payload: string) => void;
|
||||
close: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
function makeSocket(): FakeSocket {
|
||||
const socket: FakeSocket = {
|
||||
OPEN: 1,
|
||||
readyState: 1,
|
||||
bufferedAmount: 0,
|
||||
sent: [],
|
||||
send(payload: string) {
|
||||
this.sent.push(JSON.parse(payload));
|
||||
},
|
||||
close: vi.fn(function close() {
|
||||
socket.readyState = 3;
|
||||
}),
|
||||
};
|
||||
return socket;
|
||||
}
|
||||
|
||||
function lastPush(socket: FakeSocket): Record<string, unknown> {
|
||||
const last = socket.sent.at(-1);
|
||||
if (!last || typeof last !== "object") {
|
||||
throw new Error("no push payload found");
|
||||
}
|
||||
return last as Record<string, unknown>;
|
||||
}
|
||||
|
||||
describe("ProviderStreamSubscriptionManager", () => {
|
||||
it("opens with snapshot mode and emits snapshot frame", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
store.appendEvent({
|
||||
type: "session.updated",
|
||||
session: {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
const manager = new ProviderStreamSubscriptionManager(store);
|
||||
const socket = makeSocket();
|
||||
|
||||
const result = manager.openStream(socket as never, undefined);
|
||||
expect(result.mode).toBe("snapshot");
|
||||
|
||||
const push = lastPush(socket);
|
||||
expect(push.channel).toBe("providers.stream");
|
||||
expect((push.data as { kind: string }).kind).toBe("snapshot");
|
||||
});
|
||||
|
||||
it("replays missing events for valid cursor", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
store.appendEvent({
|
||||
type: "session.updated",
|
||||
session: {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
store.appendEvent({
|
||||
type: "error",
|
||||
sessionId: "sess-1",
|
||||
code: "runtime/error",
|
||||
message: "boom",
|
||||
});
|
||||
|
||||
const manager = new ProviderStreamSubscriptionManager(store);
|
||||
const socket = makeSocket();
|
||||
|
||||
const result = manager.openStream(socket as never, { afterSeq: 1 });
|
||||
expect(result.mode).toBe("replay");
|
||||
expect(result.replayedCount).toBe(1);
|
||||
|
||||
const push = lastPush(socket);
|
||||
expect((push.data as { kind: string }).kind).toBe("event");
|
||||
});
|
||||
|
||||
it("returns snapshot_resync for stale cursors", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
for (let i = 0; i < 12_000; i += 1) {
|
||||
store.appendEvent({
|
||||
type: "error",
|
||||
sessionId: "sess-1",
|
||||
code: "runtime/error",
|
||||
message: `err-${i}`,
|
||||
});
|
||||
}
|
||||
|
||||
const manager = new ProviderStreamSubscriptionManager(store);
|
||||
const socket = makeSocket();
|
||||
|
||||
const result = manager.openStream(socket as never, { afterSeq: 0 });
|
||||
expect(result.mode).toBe("snapshot_resync");
|
||||
|
||||
const kinds = socket.sent
|
||||
.map((payload) => ((payload as Record<string, unknown>).data as { kind: string }).kind);
|
||||
expect(kinds).toContain("gap");
|
||||
expect(kinds).toContain("snapshot");
|
||||
});
|
||||
|
||||
it("filters by session and debug flags", () => {
|
||||
const store = new ProviderStreamStore();
|
||||
const manager = new ProviderStreamSubscriptionManager(store);
|
||||
const socket = makeSocket();
|
||||
|
||||
manager.openStream(socket as never, {
|
||||
sessionIds: ["sess-1"],
|
||||
includeDebugRaw: false,
|
||||
});
|
||||
|
||||
manager.publish(
|
||||
store.appendEvent({
|
||||
type: "error",
|
||||
sessionId: "sess-2",
|
||||
code: "runtime/error",
|
||||
message: "hidden",
|
||||
}),
|
||||
);
|
||||
|
||||
manager.publish(
|
||||
store.appendEvent({
|
||||
type: "debug.raw",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
method: "thread/started",
|
||||
payload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
manager.publish(
|
||||
store.appendEvent({
|
||||
type: "error",
|
||||
sessionId: "sess-1",
|
||||
code: "runtime/error",
|
||||
message: "visible",
|
||||
}),
|
||||
);
|
||||
|
||||
const pushedKinds = socket.sent
|
||||
.map((payload) => ((payload as Record<string, unknown>).data as { kind: string }).kind)
|
||||
.filter((kind) => kind === "event");
|
||||
|
||||
// Only the final sess-1 error event should pass filters.
|
||||
expect(pushedKinds).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,298 +0,0 @@
|
||||
import {
|
||||
WS_CHANNELS,
|
||||
type ProviderCoreEvent,
|
||||
type ProviderStreamEventKind,
|
||||
type ProviderStreamFrame,
|
||||
type ProvidersOpenStreamInput,
|
||||
type ProvidersOpenStreamResult,
|
||||
providersOpenStreamInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import type { WsPush } from "@t3tools/contracts";
|
||||
import type { WebSocket } from "ws";
|
||||
|
||||
import {
|
||||
PROVIDER_STREAM_REPLAY_OPEN_LIMIT,
|
||||
ProviderStreamStore,
|
||||
filterEventExtensions,
|
||||
providerStreamEventKindOf,
|
||||
providerStreamEventSessionId,
|
||||
} from "./providerStreamStore";
|
||||
|
||||
const BACKPRESSURE_HIGH_WATER_MARK_BYTES = 2 * 1_024 * 1_024;
|
||||
const BACKPRESSURE_HIGH_WATER_DURATION_MS = 5_000;
|
||||
|
||||
interface StreamFilter {
|
||||
sessionIds?: Set<string>;
|
||||
eventKinds: Set<ProviderStreamEventKind>;
|
||||
includeExtensions: Set<string>;
|
||||
includeDebugRaw: boolean;
|
||||
}
|
||||
|
||||
interface StreamSubscription {
|
||||
filter: StreamFilter;
|
||||
overHighWaterSinceMs: number | null;
|
||||
}
|
||||
|
||||
interface SubscriptionManagerOptions {
|
||||
onPush?: ((push: WsPush) => void) | undefined;
|
||||
}
|
||||
|
||||
const DEFAULT_EVENT_KINDS: ReadonlyArray<ProviderStreamEventKind> = [
|
||||
"session",
|
||||
"turn",
|
||||
"message",
|
||||
"approval",
|
||||
"activity",
|
||||
"error",
|
||||
"debug.raw",
|
||||
];
|
||||
|
||||
function normalizeFilter(input: ProvidersOpenStreamInput): StreamFilter {
|
||||
const sessionIds = input.sessionIds && input.sessionIds.length > 0
|
||||
? new Set(input.sessionIds)
|
||||
: undefined;
|
||||
const eventKinds = new Set(input.eventKinds ?? DEFAULT_EVENT_KINDS);
|
||||
|
||||
return {
|
||||
...(sessionIds ? { sessionIds } : {}),
|
||||
eventKinds,
|
||||
includeExtensions: new Set(input.includeExtensions ?? []),
|
||||
includeDebugRaw: input.includeDebugRaw ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
export class ProviderStreamSubscriptionManager {
|
||||
private readonly subscriptions = new Map<WebSocket, StreamSubscription>();
|
||||
private readonly onPush: ((push: WsPush) => void) | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly store: ProviderStreamStore,
|
||||
options: SubscriptionManagerOptions = {},
|
||||
) {
|
||||
this.onPush = options.onPush;
|
||||
}
|
||||
|
||||
openStream(
|
||||
ws: WebSocket,
|
||||
rawInput: ProvidersOpenStreamInput | undefined,
|
||||
): ProvidersOpenStreamResult {
|
||||
const input = providersOpenStreamInputSchema.parse(rawInput ?? {});
|
||||
const filter = normalizeFilter(input);
|
||||
|
||||
this.subscriptions.set(ws, {
|
||||
filter,
|
||||
overHighWaterSinceMs: null,
|
||||
});
|
||||
|
||||
const nowIso = new Date().toISOString();
|
||||
|
||||
if (input.afterSeq === undefined) {
|
||||
this.sendFrame(ws, {
|
||||
kind: "snapshot",
|
||||
seq: this.store.currentSeq,
|
||||
at: nowIso,
|
||||
data: this.store.getSnapshot(filter.sessionIds),
|
||||
});
|
||||
|
||||
return {
|
||||
mode: "snapshot",
|
||||
currentSeq: this.store.currentSeq,
|
||||
oldestSeq: this.store.oldestSeq,
|
||||
replayedCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const replay = this.store.selectReplay(
|
||||
input.afterSeq,
|
||||
PROVIDER_STREAM_REPLAY_OPEN_LIMIT,
|
||||
);
|
||||
|
||||
if (!replay.ok) {
|
||||
this.sendFrame(ws, {
|
||||
kind: "gap",
|
||||
seq: replay.currentSeq,
|
||||
at: nowIso,
|
||||
data: {
|
||||
reason: replay.reason,
|
||||
oldestSeq: replay.oldestSeq,
|
||||
currentSeq: replay.currentSeq,
|
||||
},
|
||||
});
|
||||
this.sendFrame(ws, {
|
||||
kind: "snapshot",
|
||||
seq: replay.currentSeq,
|
||||
at: nowIso,
|
||||
data: this.store.getSnapshot(filter.sessionIds),
|
||||
});
|
||||
|
||||
return {
|
||||
mode: "snapshot_resync",
|
||||
currentSeq: replay.currentSeq,
|
||||
oldestSeq: replay.oldestSeq,
|
||||
replayedCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let replayedCount = 0;
|
||||
for (const event of replay.events) {
|
||||
const delivered = this.sendFrame(ws, {
|
||||
kind: "event",
|
||||
seq: event.seq,
|
||||
at: event.at,
|
||||
data: event.data,
|
||||
});
|
||||
if (delivered) {
|
||||
replayedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
mode: "replay",
|
||||
currentSeq: replay.currentSeq,
|
||||
oldestSeq: replay.oldestSeq,
|
||||
replayedCount,
|
||||
};
|
||||
}
|
||||
|
||||
closeStream(ws: WebSocket): void {
|
||||
this.subscriptions.delete(ws);
|
||||
}
|
||||
|
||||
closeAll(): void {
|
||||
this.subscriptions.clear();
|
||||
}
|
||||
|
||||
publish(frame: ProviderStreamFrame): void {
|
||||
for (const [ws] of this.subscriptions) {
|
||||
if (!this.isSocketOpen(ws)) {
|
||||
this.subscriptions.delete(ws);
|
||||
continue;
|
||||
}
|
||||
this.sendFrame(ws, frame);
|
||||
}
|
||||
}
|
||||
|
||||
private sendFrame(ws: WebSocket, frame: ProviderStreamFrame): boolean {
|
||||
const subscription = this.subscriptions.get(ws);
|
||||
if (!subscription) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.isSocketOpen(ws)) {
|
||||
this.subscriptions.delete(ws);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.checkBackpressure(ws, subscription)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const filteredFrame = this.filteredFrameForSubscription(frame, subscription.filter);
|
||||
if (!filteredFrame) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const push: WsPush = {
|
||||
type: "push",
|
||||
channel: WS_CHANNELS.providerStream,
|
||||
data: filteredFrame,
|
||||
};
|
||||
|
||||
try {
|
||||
ws.send(JSON.stringify(push));
|
||||
} catch {
|
||||
this.subscriptions.delete(ws);
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
// Ignore close errors on already-failed sockets.
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
this.onPush?.(push);
|
||||
this.checkBackpressure(ws, subscription);
|
||||
return true;
|
||||
}
|
||||
|
||||
private filteredFrameForSubscription(
|
||||
frame: ProviderStreamFrame,
|
||||
filter: StreamFilter,
|
||||
): ProviderStreamFrame | null {
|
||||
if (frame.kind === "snapshot") {
|
||||
return {
|
||||
...frame,
|
||||
data: this.store.getSnapshot(filter.sessionIds),
|
||||
};
|
||||
}
|
||||
|
||||
if (frame.kind === "gap") {
|
||||
return frame;
|
||||
}
|
||||
|
||||
if (!this.shouldIncludeEvent(frame.data, filter)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...frame,
|
||||
data: filterEventExtensions(frame.data, filter.includeExtensions),
|
||||
};
|
||||
}
|
||||
|
||||
private shouldIncludeEvent(event: ProviderCoreEvent, filter: StreamFilter): boolean {
|
||||
const kind = providerStreamEventKindOf(event);
|
||||
|
||||
if (!filter.eventKinds.has(kind)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (kind === "debug.raw" && !filter.includeDebugRaw) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!filter.sessionIds || filter.sessionIds.size === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const sessionId = providerStreamEventSessionId(event);
|
||||
if (!sessionId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return filter.sessionIds.has(sessionId);
|
||||
}
|
||||
|
||||
private checkBackpressure(
|
||||
ws: WebSocket,
|
||||
subscription: StreamSubscription,
|
||||
): boolean {
|
||||
const buffered = ws.bufferedAmount;
|
||||
if (buffered <= BACKPRESSURE_HIGH_WATER_MARK_BYTES) {
|
||||
subscription.overHighWaterSinceMs = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
const nowMs = Date.now();
|
||||
if (subscription.overHighWaterSinceMs === null) {
|
||||
subscription.overHighWaterSinceMs = nowMs;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (nowMs - subscription.overHighWaterSinceMs < BACKPRESSURE_HIGH_WATER_DURATION_MS) {
|
||||
return true;
|
||||
}
|
||||
|
||||
this.subscriptions.delete(ws);
|
||||
try {
|
||||
ws.close(1013, "provider stream backpressure");
|
||||
} catch {
|
||||
// Ignore close errors on failed sockets.
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private isSocketOpen(ws: WebSocket): boolean {
|
||||
return ws.readyState === ws.OPEN;
|
||||
}
|
||||
}
|
||||
@@ -1,395 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
|
||||
import { WS_CHANNELS, WS_METHODS, type WsPush, type WsResponse } from "@t3tools/contracts";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
waiters: Array<(message: unknown) => void>;
|
||||
}
|
||||
|
||||
const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
|
||||
|
||||
function connectWs(port: number, token?: string): Promise<WebSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
|
||||
const pending: PendingMessages = { queue: [], waiters: [] };
|
||||
pendingBySocket.set(ws, pending);
|
||||
|
||||
ws.on("message", (raw) => {
|
||||
const parsed = JSON.parse(String(raw));
|
||||
const waiter = pending.waiters.shift();
|
||||
if (waiter) {
|
||||
waiter(parsed);
|
||||
return;
|
||||
}
|
||||
pending.queue.push(parsed);
|
||||
});
|
||||
|
||||
ws.once("open", () => resolve(ws));
|
||||
ws.once("error", () => reject(new Error("WebSocket connection failed")));
|
||||
});
|
||||
}
|
||||
|
||||
function waitForMessage(ws: WebSocket): Promise<unknown> {
|
||||
const pending = pendingBySocket.get(ws);
|
||||
if (!pending) {
|
||||
return Promise.reject(new Error("WebSocket not initialized"));
|
||||
}
|
||||
|
||||
const queued = pending.queue.shift();
|
||||
if (queued !== undefined) {
|
||||
return Promise.resolve(queued);
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
pending.waiters.push(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
async function sendRequest(ws: WebSocket, method: string, params?: unknown): Promise<WsResponse> {
|
||||
const id = crypto.randomUUID();
|
||||
const message = JSON.stringify({ id, method, ...(params !== undefined ? { params } : {}) });
|
||||
ws.send(message);
|
||||
|
||||
// Wait for response with matching id
|
||||
while (true) {
|
||||
const parsed = (await waitForMessage(ws)) as Record<string, unknown>;
|
||||
if (parsed.id === id) {
|
||||
return parsed as WsResponse;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("WebSocket Server", () => {
|
||||
let server: ReturnType<typeof createServer> | null = null;
|
||||
const connections: WebSocket[] = [];
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function createTestServer(
|
||||
options: {
|
||||
cwd?: string;
|
||||
devUrl?: string;
|
||||
authToken?: string;
|
||||
stateDir?: string;
|
||||
} = {},
|
||||
): ReturnType<typeof createServer> {
|
||||
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
|
||||
return createServer({
|
||||
port: 0,
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
...(options.devUrl ? { devUrl: options.devUrl } : {}),
|
||||
...(options.authToken ? { authToken: options.authToken } : {}),
|
||||
projectRegistry: new ProjectRegistry(stateDir),
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
for (const ws of connections) {
|
||||
ws.close();
|
||||
}
|
||||
connections.length = 0;
|
||||
if (server) {
|
||||
await server.stop();
|
||||
}
|
||||
server = null;
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("sends welcome message on connect", async () => {
|
||||
server = createTestServer({ cwd: "/test/project" });
|
||||
// Get the actual port after listen
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
const message = (await waitForMessage(ws)) as WsPush;
|
||||
expect(message.type).toBe("push");
|
||||
expect(message.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||
expect(message.data).toEqual({
|
||||
cwd: "/test/project",
|
||||
projectName: "project",
|
||||
});
|
||||
});
|
||||
|
||||
it("logs outbound websocket push events in dev mode", async () => {
|
||||
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {
|
||||
// Keep test output clean while verifying websocket logs.
|
||||
});
|
||||
|
||||
server = createTestServer({
|
||||
cwd: "/test/project",
|
||||
devUrl: "http://localhost:5173",
|
||||
});
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
expect(
|
||||
logSpy.mock.calls.some(([message]) => {
|
||||
if (typeof message !== "string") return false;
|
||||
return (
|
||||
message.includes("[ws]") &&
|
||||
message.includes("outgoing push") &&
|
||||
message.includes(`channel="${WS_CHANNELS.serverWelcome}"`)
|
||||
);
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("responds to server.getConfig", async () => {
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
// Consume welcome message
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({ cwd: "/my/workspace" });
|
||||
});
|
||||
|
||||
it("returns error for unknown methods", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
// Consume welcome
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, "nonexistent.method");
|
||||
expect(response.error).toBeDefined();
|
||||
expect(response.error!.message).toContain("Unknown method");
|
||||
});
|
||||
|
||||
it("responds to providers.listSessions with empty array", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
// Consume welcome
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.providersListSessions);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("opens provider stream with snapshot and returns stream metadata", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
// Consume welcome
|
||||
await waitForMessage(ws);
|
||||
|
||||
const id = crypto.randomUUID();
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
id,
|
||||
method: WS_METHODS.providersOpenStream,
|
||||
params: {},
|
||||
}),
|
||||
);
|
||||
|
||||
const first = (await waitForMessage(ws)) as Record<string, unknown>;
|
||||
const second = (await waitForMessage(ws)) as Record<string, unknown>;
|
||||
const messages = [first, second];
|
||||
|
||||
let response: WsResponse | null = null;
|
||||
const sawSnapshotPush = messages.some(
|
||||
(message) =>
|
||||
message.type === "push" &&
|
||||
message.channel === WS_CHANNELS.providerStream &&
|
||||
typeof message.data === "object" &&
|
||||
message.data !== null &&
|
||||
(message.data as { kind?: string }).kind === "snapshot",
|
||||
);
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.id === id) {
|
||||
response = message as WsResponse;
|
||||
}
|
||||
}
|
||||
|
||||
expect(sawSnapshotPush).toBe(true);
|
||||
expect(response).not.toBeNull();
|
||||
expect(response?.error).toBeUndefined();
|
||||
const result = response?.result as { mode?: string };
|
||||
expect(result?.mode).toBe("snapshot");
|
||||
});
|
||||
|
||||
it("handles invalid JSON gracefully", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
// Consume welcome
|
||||
await waitForMessage(ws);
|
||||
|
||||
// Send garbage
|
||||
ws.send("not json at all");
|
||||
|
||||
const response = (await waitForMessage(ws)) as WsResponse;
|
||||
expect(response.error).toBeDefined();
|
||||
expect(response.error!.message).toContain("Invalid request format");
|
||||
});
|
||||
|
||||
it("supports projects list/add/dedupe/remove", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-projects-state-");
|
||||
const firstProjectCwd = makeTempDir("t3code-ws-project-a-");
|
||||
|
||||
server = createTestServer({ stateDir, cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const emptyList = await sendRequest(ws, WS_METHODS.projectsList);
|
||||
expect(emptyList.error).toBeUndefined();
|
||||
expect(emptyList.result).toEqual([]);
|
||||
|
||||
const created = await sendRequest(ws, WS_METHODS.projectsAdd, {
|
||||
cwd: firstProjectCwd,
|
||||
});
|
||||
expect(created.error).toBeUndefined();
|
||||
expect((created.result as { created: boolean }).created).toBe(true);
|
||||
|
||||
const duplicate = await sendRequest(ws, WS_METHODS.projectsAdd, {
|
||||
cwd: firstProjectCwd,
|
||||
});
|
||||
expect(duplicate.error).toBeUndefined();
|
||||
expect((duplicate.result as { created: boolean }).created).toBe(false);
|
||||
|
||||
const listed = await sendRequest(ws, WS_METHODS.projectsList);
|
||||
expect(listed.error).toBeUndefined();
|
||||
const listedProjects = listed.result as Array<{ id: string; cwd: string }>;
|
||||
expect(listedProjects).toHaveLength(1);
|
||||
|
||||
const projectId = listedProjects[0]?.id;
|
||||
expect(projectId).toBeTruthy();
|
||||
if (!projectId) return;
|
||||
|
||||
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
|
||||
id: projectId,
|
||||
});
|
||||
expect(removed.error).toBeUndefined();
|
||||
|
||||
const afterRemove = await sendRequest(ws, WS_METHODS.projectsList);
|
||||
expect(afterRemove.error).toBeUndefined();
|
||||
expect(afterRemove.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("prunes missing projects on startup", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-prune-state-");
|
||||
const existing = makeTempDir("t3code-ws-existing-project-");
|
||||
const missing = path.join(stateDir, "definitely-missing");
|
||||
const now = new Date().toISOString();
|
||||
const projectsFile = path.join(stateDir, "projects.json");
|
||||
|
||||
fs.writeFileSync(
|
||||
projectsFile,
|
||||
JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
projects: [
|
||||
{
|
||||
id: "project-existing",
|
||||
cwd: existing,
|
||||
name: "existing",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "project-missing",
|
||||
cwd: missing,
|
||||
name: "missing",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
server = createTestServer({ stateDir, cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.projectsList);
|
||||
expect(response.error).toBeUndefined();
|
||||
const listed = response.result as Array<{ id: string }>;
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.id).toBe("project-existing");
|
||||
});
|
||||
|
||||
it("rejects websocket connections without a valid auth token", async () => {
|
||||
server = createTestServer({ cwd: "/test", authToken: "secret-token" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
|
||||
|
||||
const authorizedWs = await connectWs(port, "secret-token");
|
||||
connections.push(authorizedWs);
|
||||
const welcome = (await waitForMessage(authorizedWs)) as WsPush;
|
||||
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||
});
|
||||
});
|
||||
@@ -1,399 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Duplex } from "node:stream";
|
||||
|
||||
import {
|
||||
EDITORS,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type ProviderCoreEvent,
|
||||
type WsPush,
|
||||
type WsRequest,
|
||||
type WsResponse,
|
||||
wsRequestSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { ProviderEventNormalizer } from "./providerEventNormalizer";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { ProviderStreamStore } from "./providerStreamStore";
|
||||
import { ProviderStreamSubscriptionManager } from "./providerStreamSubscriptionManager";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "application/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
".woff": "font/woff",
|
||||
".woff2": "font/woff2",
|
||||
".ttf": "font/ttf",
|
||||
".map": "application/json",
|
||||
};
|
||||
|
||||
export interface ServerOptions {
|
||||
port: number;
|
||||
host?: string | undefined;
|
||||
cwd: string;
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
authToken?: string | undefined;
|
||||
}
|
||||
|
||||
function parseBooleanEnv(value: string | undefined): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) return true;
|
||||
if (["0", "false", "no", "off"].includes(normalized)) return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function createServer(options: ServerOptions) {
|
||||
const {
|
||||
port,
|
||||
host,
|
||||
cwd,
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
authToken,
|
||||
} = options;
|
||||
const providerManager = new ProviderManager();
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const providerEventNormalizer = new ProviderEventNormalizer();
|
||||
const providerStreamStore = new ProviderStreamStore();
|
||||
const providerStreamSubscriptions = new ProviderStreamSubscriptionManager(
|
||||
providerStreamStore,
|
||||
{
|
||||
onPush: (push) => {
|
||||
logOutgoingPush(push, 1);
|
||||
},
|
||||
},
|
||||
);
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||
|
||||
function logOutgoingPush(push: WsPush, recipients: number) {
|
||||
if (!logWebSocketEvents) return;
|
||||
logger.event("outgoing push", {
|
||||
channel: push.channel,
|
||||
recipients,
|
||||
payload: push.data,
|
||||
});
|
||||
}
|
||||
|
||||
providerManager.on("event", (rawEvent) => {
|
||||
const currentSession = providerStreamStore.getSession(rawEvent.sessionId);
|
||||
const normalized = providerEventNormalizer.normalize(rawEvent, currentSession);
|
||||
const at = rawEvent.createdAt;
|
||||
|
||||
const publish = (event: ProviderCoreEvent) => {
|
||||
const frame = providerStreamStore.appendEvent(event, at);
|
||||
providerStreamSubscriptions.publish(frame);
|
||||
};
|
||||
|
||||
if (normalized.length === 0) {
|
||||
publish(providerEventNormalizer.toDebugRaw(rawEvent));
|
||||
return;
|
||||
}
|
||||
|
||||
for (const event of normalized) {
|
||||
publish(event);
|
||||
}
|
||||
});
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
// In dev mode, redirect to Vite dev server
|
||||
if (devUrl) {
|
||||
res.writeHead(302, { Location: devUrl });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Serve static files from the web app build
|
||||
if (!staticDir) {
|
||||
res.writeHead(503, { "Content-Type": "text/plain" });
|
||||
res.end("No static directory configured and no dev URL set.");
|
||||
return;
|
||||
}
|
||||
|
||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||
let filePath = path.join(staticDir, url.pathname);
|
||||
|
||||
// SPA fallback: if no file extension and not found, serve index.html
|
||||
const ext = path.extname(filePath);
|
||||
if (!ext) {
|
||||
filePath = path.join(filePath, "index.html");
|
||||
}
|
||||
|
||||
fs.stat(filePath, (err, stats) => {
|
||||
if (err || !stats?.isFile()) {
|
||||
// SPA fallback
|
||||
const indexPath = path.join(staticDir, "index.html");
|
||||
fs.readFile(indexPath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("Not Found");
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
||||
res.end(data);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const fileExt = path.extname(filePath);
|
||||
const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
|
||||
|
||||
fs.readFile(filePath, (readErr, data) => {
|
||||
if (readErr) {
|
||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
||||
res.end("Internal Server Error");
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": contentType });
|
||||
res.end(data);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// WebSocket server — upgrades from the HTTP server
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
|
||||
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
|
||||
socket.write(
|
||||
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
|
||||
"Connection: close\r\n" +
|
||||
"Content-Type: text/plain\r\n" +
|
||||
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
|
||||
"\r\n" +
|
||||
message,
|
||||
);
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
data: { cwd, projectName },
|
||||
};
|
||||
logOutgoingPush(welcome, 1);
|
||||
ws.send(JSON.stringify(welcome));
|
||||
|
||||
ws.on("message", (raw) => {
|
||||
void handleMessage(ws, raw);
|
||||
});
|
||||
|
||||
ws.on("close", () => {
|
||||
providerStreamSubscriptions.closeStream(ws);
|
||||
clients.delete(ws);
|
||||
});
|
||||
|
||||
ws.on("error", () => {
|
||||
providerStreamSubscriptions.closeStream(ws);
|
||||
clients.delete(ws);
|
||||
});
|
||||
});
|
||||
|
||||
async function handleMessage(ws: WebSocket, raw: unknown) {
|
||||
let request: WsRequest;
|
||||
try {
|
||||
const parsed = JSON.parse(String(raw));
|
||||
request = wsRequestSchema.parse(parsed);
|
||||
} catch {
|
||||
const errorResponse: WsResponse = {
|
||||
id: "unknown",
|
||||
error: { message: "Invalid request format" },
|
||||
};
|
||||
ws.send(JSON.stringify(errorResponse));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await routeRequest(ws, request);
|
||||
const response: WsResponse = { id: request.id, result };
|
||||
ws.send(JSON.stringify(response));
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Unknown server error";
|
||||
const response: WsResponse = {
|
||||
id: request.id,
|
||||
error: { message },
|
||||
};
|
||||
ws.send(JSON.stringify(response));
|
||||
}
|
||||
}
|
||||
|
||||
async function routeRequest(ws: WebSocket, request: WsRequest): Promise<unknown> {
|
||||
switch (request.method) {
|
||||
case WS_METHODS.providersStartSession:
|
||||
return providerManager.startSession(request.params as never);
|
||||
|
||||
case WS_METHODS.providersSendTurn:
|
||||
return providerManager.sendTurn(request.params as never);
|
||||
|
||||
case WS_METHODS.providersInterruptTurn:
|
||||
return providerManager.interruptTurn(request.params as never);
|
||||
|
||||
case WS_METHODS.providersRespondToApproval:
|
||||
return providerManager.respondToApproval(request.params as never);
|
||||
|
||||
case WS_METHODS.providersStopSession: {
|
||||
providerManager.stopSession(request.params as never);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.providersListSessions:
|
||||
return providerManager.listSessions();
|
||||
|
||||
case WS_METHODS.providersOpenStream:
|
||||
return providerStreamSubscriptions.openStream(ws, request.params as never);
|
||||
|
||||
case WS_METHODS.providersCloseStream:
|
||||
providerStreamSubscriptions.closeStream(ws);
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.projectsList:
|
||||
return projectRegistry.list();
|
||||
|
||||
case WS_METHODS.projectsAdd:
|
||||
return projectRegistry.add(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsRemove:
|
||||
projectRegistry.remove(request.params as never);
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.shellOpenInEditor: {
|
||||
const params = request.params as {
|
||||
cwd: string;
|
||||
editor: string;
|
||||
};
|
||||
if (!params?.cwd) throw new Error("cwd is required");
|
||||
const editorDef = EDITORS.find((e) => e.id === params.editor);
|
||||
if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`);
|
||||
if (!editorDef.command) {
|
||||
// Can't open file manager programmatically from server, just succeed silently
|
||||
return undefined;
|
||||
}
|
||||
const child = spawn(editorDef.command, [params.cwd], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
child.on("error", () => {
|
||||
/* ignore spawn failures for detached editors */
|
||||
});
|
||||
child.unref();
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.serverGetConfig:
|
||||
return { cwd };
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => {
|
||||
httpServer.off("error", onError);
|
||||
reject(error);
|
||||
};
|
||||
httpServer.once("error", onError);
|
||||
const onListening = () => {
|
||||
httpServer.off("error", onError);
|
||||
resolve();
|
||||
};
|
||||
if (host) {
|
||||
httpServer.listen(port, host, onListening);
|
||||
return;
|
||||
}
|
||||
httpServer.listen(port, onListening);
|
||||
});
|
||||
}
|
||||
|
||||
async function stop(): Promise<void> {
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
providerStreamSubscriptions.closeAll();
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
}
|
||||
clients.clear();
|
||||
|
||||
const isServerNotRunningError = (error: unknown): boolean => {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const maybeCode = (error as NodeJS.ErrnoException).code;
|
||||
return maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running");
|
||||
};
|
||||
|
||||
const closeWebSocketServer = new Promise<void>((resolve, reject) => {
|
||||
wss.close((error) => {
|
||||
if (error && !isServerNotRunningError(error)) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const closeHttpServer = new Promise<void>((resolve, reject) => {
|
||||
httpServer.close((error) => {
|
||||
if (error && !isServerNotRunningError(error)) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
await Promise.all([closeWebSocketServer, closeHttpServer]);
|
||||
}
|
||||
|
||||
return { start, stop, httpServer };
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node"],
|
||||
"lib": ["ES2023"]
|
||||
},
|
||||
"include": ["src", "tsup.config.ts"]
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: "esm",
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
banner: {
|
||||
js: '#!/usr/bin/env node\n',
|
||||
},
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<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</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,175 +0,0 @@
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import ChatView from "./components/ChatView";
|
||||
import DiffPanel from "./components/DiffPanel";
|
||||
import Sidebar from "./components/Sidebar";
|
||||
import { isElectron } from "./env";
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
import { readNativeApi } from "./session-logic";
|
||||
import { StoreProvider, useStore } from "./store";
|
||||
import { onServerWelcome } from "./wsNativeApi";
|
||||
|
||||
function EventRouter() {
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { dispatch } = useStore();
|
||||
const activeAssistantMessageRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.providers.onStream((frame) => {
|
||||
dispatch({
|
||||
type: "APPLY_STREAM_FRAME",
|
||||
frame,
|
||||
activeAssistantMessageRef,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function AutoProjectBootstrap() {
|
||||
const { state, dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Browser mode bootstraps from server welcome.
|
||||
// Electron bootstraps from persisted projects via DesktopProjectBootstrap.
|
||||
if (isElectron) return;
|
||||
|
||||
return onServerWelcome((payload) => {
|
||||
if (bootstrappedRef.current) return;
|
||||
|
||||
// Don't create duplicate projects for the same cwd
|
||||
const existing = state.projects.find((p) => p.cwd === payload.cwd);
|
||||
if (existing) {
|
||||
bootstrappedRef.current = true;
|
||||
// Ensure a thread is active
|
||||
const existingThread = state.threads.find((t) => t.projectId === existing.id);
|
||||
if (existingThread && !state.activeThreadId) {
|
||||
dispatch({
|
||||
type: "SET_ACTIVE_THREAD",
|
||||
threadId: existingThread.id,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
bootstrappedRef.current = true;
|
||||
|
||||
// Create project + thread from server cwd
|
||||
const projectId = crypto.randomUUID();
|
||||
dispatch({
|
||||
type: "ADD_PROJECT",
|
||||
project: {
|
||||
id: projectId,
|
||||
name: payload.projectName,
|
||||
cwd: payload.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
},
|
||||
});
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
id: crypto.randomUUID(),
|
||||
codexThreadId: null,
|
||||
projectId,
|
||||
title: "New thread",
|
||||
model: DEFAULT_MODEL,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
});
|
||||
}, [state.projects, state.threads, state.activeThreadId, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function DesktopProjectBootstrap() {
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron || !api || bootstrappedRef.current) return;
|
||||
|
||||
let disposed = false;
|
||||
let retryDelayMs = 500;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const attemptBootstrap = async () => {
|
||||
try {
|
||||
const projects = await api.projects.list();
|
||||
if (disposed) return;
|
||||
dispatch({
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: projects.map((project) => ({
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
cwd: project.cwd,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
})),
|
||||
});
|
||||
bootstrappedRef.current = true;
|
||||
} catch {
|
||||
if (disposed) return;
|
||||
retryTimer = setTimeout(() => {
|
||||
retryTimer = null;
|
||||
void attemptBootstrap();
|
||||
}, retryDelayMs);
|
||||
retryDelayMs = Math.min(retryDelayMs * 2, 5_000);
|
||||
}
|
||||
};
|
||||
|
||||
void attemptBootstrap();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (retryTimer) {
|
||||
clearTimeout(retryTimer);
|
||||
}
|
||||
};
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function Layout() {
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { state } = useStore();
|
||||
|
||||
if (!api) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">Connecting to T3 Code server...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-background text-foreground">
|
||||
<EventRouter />
|
||||
<AutoProjectBootstrap />
|
||||
<DesktopProjectBootstrap />
|
||||
<Sidebar />
|
||||
<ChatView />
|
||||
{state.diffOpen && <DiffPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<StoreProvider>
|
||||
<Layout />
|
||||
</StoreProvider>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +0,0 @@
|
||||
/**
|
||||
* True when running inside the Electron preload bridge, false in a regular browser.
|
||||
* The preload script sets window.nativeApi via contextBridge before any web-app
|
||||
* code executes, so this is reliable at module load time.
|
||||
*/
|
||||
export const isElectron =
|
||||
typeof window !== "undefined" &&
|
||||
(window.desktopBridge !== undefined || window.nativeApi !== undefined);
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildBootstrapInput } from "./historyBootstrap";
|
||||
|
||||
describe("buildBootstrapInput", () => {
|
||||
it("includes full transcript when under budget", () => {
|
||||
const result = buildBootstrapInput(
|
||||
[
|
||||
{
|
||||
id: "u-1",
|
||||
role: "user",
|
||||
text: "hello",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "a-1",
|
||||
role: "assistant",
|
||||
text: "world",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"what's next?",
|
||||
1_500,
|
||||
);
|
||||
|
||||
expect(result.includedCount).toBe(2);
|
||||
expect(result.omittedCount).toBe(0);
|
||||
expect(result.truncated).toBe(false);
|
||||
expect(result.text).toContain("USER:\nhello");
|
||||
expect(result.text).toContain("ASSISTANT:\nworld");
|
||||
expect(result.text).toContain("Latest user request (answer this now):");
|
||||
expect(result.text).toContain("what's next?");
|
||||
});
|
||||
|
||||
it("truncates older transcript messages when over budget", () => {
|
||||
const result = buildBootstrapInput(
|
||||
[
|
||||
{
|
||||
id: "u-1",
|
||||
role: "user",
|
||||
text: "first question with details",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "a-1",
|
||||
role: "assistant",
|
||||
text: "first answer with details",
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "u-2",
|
||||
role: "user",
|
||||
text: "second question with details",
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"final request",
|
||||
320,
|
||||
);
|
||||
|
||||
expect(result.truncated).toBe(true);
|
||||
expect(result.omittedCount).toBeGreaterThan(0);
|
||||
expect(result.includedCount).toBeLessThan(3);
|
||||
expect(result.text).toContain("omitted to stay within input limits");
|
||||
expect(result.text.length).toBeLessThanOrEqual(320);
|
||||
});
|
||||
|
||||
it("preserves the latest prompt when prompt-only fallback is required", () => {
|
||||
const latestPrompt = "Please keep this exact latest prompt.";
|
||||
const result = buildBootstrapInput(
|
||||
[
|
||||
{
|
||||
id: "u-1",
|
||||
role: "user",
|
||||
text: "old context",
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
latestPrompt,
|
||||
latestPrompt.length + 3,
|
||||
);
|
||||
|
||||
expect(result.text).toBe(latestPrompt);
|
||||
expect(result.includedCount).toBe(0);
|
||||
expect(result.omittedCount).toBe(1);
|
||||
expect(result.truncated).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,120 +0,0 @@
|
||||
import type { ChatMessage } from "./types";
|
||||
|
||||
export interface BootstrapInputResult {
|
||||
text: string;
|
||||
includedCount: number;
|
||||
omittedCount: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
const BOOTSTRAP_PREAMBLE =
|
||||
"Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";
|
||||
const TRANSCRIPT_HEADER = "Transcript context:";
|
||||
const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";
|
||||
const OMITTED_SUMMARY = (count: number) =>
|
||||
`[${count} earlier message(s) omitted to stay within input limits.]`;
|
||||
|
||||
function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
|
||||
return message.role === "assistant" ? "ASSISTANT" : "USER";
|
||||
}
|
||||
|
||||
function buildMessageBlock(message: ChatMessage): string {
|
||||
return `${messageRoleLabel(message)}:\n${message.text}`;
|
||||
}
|
||||
|
||||
function finalizeWithPrompt(
|
||||
transcriptBody: string,
|
||||
latestPrompt: string,
|
||||
maxChars: number,
|
||||
): string | null {
|
||||
const text = `${BOOTSTRAP_PREAMBLE}\n\n${TRANSCRIPT_HEADER}\n${transcriptBody}\n\n${LATEST_PROMPT_HEADER}\n${latestPrompt}`;
|
||||
return text.length <= maxChars ? text : null;
|
||||
}
|
||||
|
||||
export function buildBootstrapInput(
|
||||
previousMessages: ChatMessage[],
|
||||
latestPrompt: string,
|
||||
maxChars: number,
|
||||
): BootstrapInputResult {
|
||||
const budget = Number.isFinite(maxChars)
|
||||
? Math.max(1, Math.floor(maxChars))
|
||||
: 1;
|
||||
const promptOnly =
|
||||
latestPrompt.length <= budget
|
||||
? latestPrompt
|
||||
: latestPrompt.slice(0, budget);
|
||||
|
||||
if (previousMessages.length === 0) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
omittedCount: 0,
|
||||
truncated: promptOnly.length !== latestPrompt.length,
|
||||
};
|
||||
}
|
||||
|
||||
const newestFirstBlocks: string[] = [];
|
||||
for (let index = previousMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = previousMessages[index];
|
||||
if (!message) continue;
|
||||
newestFirstBlocks.push(buildMessageBlock(message));
|
||||
}
|
||||
|
||||
if (newestFirstBlocks.length === 0) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
omittedCount: previousMessages.length,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Include a contiguous suffix from newest to oldest, then reverse to chronological.
|
||||
let includedNewestFirst: string[] = [];
|
||||
for (const block of newestFirstBlocks) {
|
||||
const nextNewestFirst = [...includedNewestFirst, block];
|
||||
const nextChronological = [...nextNewestFirst].reverse();
|
||||
const omittedCount = newestFirstBlocks.length - nextChronological.length;
|
||||
const transcriptBody =
|
||||
omittedCount > 0
|
||||
? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`
|
||||
: nextChronological.join("\n\n");
|
||||
if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {
|
||||
break;
|
||||
}
|
||||
includedNewestFirst = nextNewestFirst;
|
||||
}
|
||||
|
||||
let includedChronological = [...includedNewestFirst].reverse();
|
||||
while (true) {
|
||||
const omittedCount =
|
||||
newestFirstBlocks.length - includedChronological.length;
|
||||
const transcriptBody =
|
||||
omittedCount > 0
|
||||
? includedChronological.length > 0
|
||||
? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`
|
||||
: OMITTED_SUMMARY(omittedCount)
|
||||
: includedChronological.join("\n\n");
|
||||
const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);
|
||||
if (finalized) {
|
||||
return {
|
||||
text: finalized,
|
||||
includedCount: includedChronological.length,
|
||||
omittedCount,
|
||||
truncated:
|
||||
omittedCount > 0 || latestPrompt.length !== promptOnly.length,
|
||||
};
|
||||
}
|
||||
|
||||
if (includedChronological.length === 0) {
|
||||
return {
|
||||
text: promptOnly,
|
||||
includedCount: 0,
|
||||
omittedCount: previousMessages.length,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
includedChronological = includedChronological.slice(1);
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
|
||||
type Theme = "light" | "dark" | "system";
|
||||
|
||||
const STORAGE_KEY = "t3code:theme";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
function emitChange() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function getSystemDark(): boolean {
|
||||
return window.matchMedia(MEDIA_QUERY).matches;
|
||||
}
|
||||
|
||||
function getStored(): Theme {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw === "light" || raw === "dark" || raw === "system") return raw;
|
||||
return "system";
|
||||
}
|
||||
|
||||
function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
if (suppressTransitions) {
|
||||
document.documentElement.classList.add("no-transitions");
|
||||
}
|
||||
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Apply immediately on module load to prevent flash
|
||||
applyTheme(getStored());
|
||||
|
||||
function getSnapshot(): Theme {
|
||||
return getStored();
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.push(listener);
|
||||
|
||||
// Listen for system preference changes
|
||||
const mq = window.matchMedia(MEDIA_QUERY);
|
||||
const handleChange = () => {
|
||||
if (getStored() === "system") applyTheme("system", true);
|
||||
emitChange();
|
||||
};
|
||||
mq.addEventListener("change", handleChange);
|
||||
|
||||
// Listen for storage changes from other tabs
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEY) {
|
||||
applyTheme(getStored(), true);
|
||||
emitChange();
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", handleStorage);
|
||||
|
||||
return () => {
|
||||
listeners = listeners.filter((l) => l !== listener);
|
||||
mq.removeEventListener("change", handleChange);
|
||||
window.removeEventListener("storage", handleStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const theme = useSyncExternalStore(subscribe, getSnapshot);
|
||||
|
||||
const resolvedTheme: "light" | "dark" =
|
||||
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
applyTheme(next, true);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
// Keep DOM in sync on mount/change
|
||||
useEffect(() => {
|
||||
applyTheme(theme);
|
||||
}, [theme]);
|
||||
|
||||
return { theme, setTheme, resolvedTheme } as const;
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:is(.dark, .dark *));
|
||||
|
||||
@theme inline {
|
||||
--animate-skeleton: skeleton 2s -1s infinite linear;
|
||||
--color-warning-foreground: var(--warning-foreground);
|
||||
--color-warning: var(--warning);
|
||||
--color-success-foreground: var(--success-foreground);
|
||||
--color-success: var(--success);
|
||||
--color-info-foreground: var(--info-foreground);
|
||||
--color-info: var(--info);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-background: var(--background);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
@keyframes skeleton {
|
||||
to {
|
||||
background-position: -200% 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* Suppress all transitions during theme changes */
|
||||
.no-transitions,
|
||||
.no-transitions *,
|
||||
.no-transitions *::before,
|
||||
.no-transitions *::after {
|
||||
transition-duration: 0s !important;
|
||||
animation-duration: 0s !important;
|
||||
}
|
||||
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--radius: 0.625rem;
|
||||
--background: var(--color-white);
|
||||
--foreground: var(--color-neutral-800);
|
||||
--card: var(--color-white);
|
||||
--card-foreground: var(--color-neutral-800);
|
||||
--popover: var(--color-white);
|
||||
--popover-foreground: var(--color-neutral-800);
|
||||
--primary: oklch(0.488 0.217 264);
|
||||
--primary-foreground: var(--color-white);
|
||||
--secondary: --alpha(var(--color-black) / 4%);
|
||||
--secondary-foreground: var(--color-neutral-800);
|
||||
--muted: --alpha(var(--color-black) / 4%);
|
||||
--muted-foreground: color-mix(
|
||||
in srgb,
|
||||
var(--color-neutral-500) 90%,
|
||||
var(--color-black)
|
||||
);
|
||||
--accent: --alpha(var(--color-black) / 5%);
|
||||
--accent-foreground: var(--color-neutral-800);
|
||||
--destructive: var(--color-red-500);
|
||||
--border: --alpha(var(--color-black) / 8%);
|
||||
--input: --alpha(var(--color-black) / 10%);
|
||||
--ring: oklch(0.488 0.217 264);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.141 0.005 285.823);
|
||||
--sidebar-primary: oklch(0.21 0.006 285.885);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.967 0.001 286.375);
|
||||
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
|
||||
--sidebar-border: oklch(0.92 0.004 286.32);
|
||||
--sidebar-ring: oklch(0.705 0.015 286.067);
|
||||
--destructive-foreground: var(--color-red-700);
|
||||
--info: var(--color-blue-500);
|
||||
--info-foreground: var(--color-blue-700);
|
||||
--success: var(--color-emerald-500);
|
||||
--success-foreground: var(--color-emerald-700);
|
||||
--warning: var(--color-amber-500);
|
||||
--warning-foreground: var(--color-amber-700);
|
||||
|
||||
@variant dark {
|
||||
color-scheme: dark;
|
||||
--background: color-mix(
|
||||
in srgb,
|
||||
var(--color-neutral-950) 95%,
|
||||
var(--color-white)
|
||||
);
|
||||
--foreground: var(--color-neutral-100);
|
||||
--card: color-mix(in srgb, var(--background) 98%, var(--color-white));
|
||||
--card-foreground: var(--color-neutral-100);
|
||||
--popover: color-mix(in srgb, var(--background) 98%, var(--color-white));
|
||||
--popover-foreground: var(--color-neutral-100);
|
||||
--primary: oklch(0.588 0.217 264);
|
||||
--primary-foreground: var(--color-white);
|
||||
--secondary: --alpha(var(--color-white) / 4%);
|
||||
--secondary-foreground: var(--color-neutral-100);
|
||||
--muted: --alpha(var(--color-white) / 4%);
|
||||
--muted-foreground: color-mix(
|
||||
in srgb,
|
||||
var(--color-neutral-500) 90%,
|
||||
var(--color-white)
|
||||
);
|
||||
--accent: --alpha(var(--color-white) / 4%);
|
||||
--accent-foreground: var(--color-neutral-100);
|
||||
--destructive: color-mix(
|
||||
in srgb,
|
||||
var(--color-red-500) 90%,
|
||||
var(--color-white)
|
||||
);
|
||||
--border: --alpha(var(--color-white) / 6%);
|
||||
--input: --alpha(var(--color-white) / 8%);
|
||||
--ring: oklch(0.588 0.217 264);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.21 0.006 285.885);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.274 0.006 286.033);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.552 0.016 285.938);
|
||||
--destructive-foreground: var(--color-red-400);
|
||||
--info: var(--color-blue-500);
|
||||
--info-foreground: var(--color-blue-400);
|
||||
--success: var(--color-emerald-500);
|
||||
--success-foreground: var(--color-emerald-400);
|
||||
--warning: var(--color-amber-500);
|
||||
--warning-foreground: var(--color-amber-400);
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
"DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
opacity: 0.035;
|
||||
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
|
||||
background-repeat: repeat;
|
||||
background-size: 256px 256px;
|
||||
}
|
||||
|
||||
pre,
|
||||
code,
|
||||
textarea,
|
||||
input {
|
||||
font-family: "SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
|
||||
}
|
||||
|
||||
/* Window drag region (frameless titlebar) */
|
||||
.drag-region {
|
||||
-webkit-app-region: drag;
|
||||
}
|
||||
|
||||
.drag-region button,
|
||||
.drag-region input,
|
||||
.drag-region textarea,
|
||||
.drag-region select,
|
||||
.drag-region a {
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
|
||||
/* Scrollbar styling */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
/* Reasoning select -- clickable label surface */
|
||||
label:has(> select#reasoning-effort) {
|
||||
position: relative;
|
||||
}
|
||||
label:has(> select#reasoning-effort) select {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Chat markdown rendering */
|
||||
.chat-markdown {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.chat-markdown > :first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.chat-markdown > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.chat-markdown p,
|
||||
.chat-markdown ul,
|
||||
.chat-markdown ol,
|
||||
.chat-markdown blockquote,
|
||||
.chat-markdown pre,
|
||||
.chat-markdown table {
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown ul,
|
||||
.chat-markdown ol {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
.chat-markdown li + li {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.chat-markdown a {
|
||||
color: var(--info-foreground);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: color-mix(
|
||||
in srgb,
|
||||
var(--info-foreground) 40%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
.chat-markdown a:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.chat-markdown blockquote {
|
||||
border-left: 2px solid var(--border);
|
||||
padding-left: 0.8rem;
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.chat-markdown :not(pre) > code {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.375rem;
|
||||
background: var(--muted);
|
||||
padding: 0.1rem 0.35rem;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.chat-markdown pre {
|
||||
overflow-x: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.75rem;
|
||||
background: var(--muted);
|
||||
padding: 0.8rem 0.9rem;
|
||||
}
|
||||
|
||||
.chat-markdown pre code {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.chat-markdown th,
|
||||
.chat-markdown td {
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.35rem 0.45rem;
|
||||
text-align: left;
|
||||
}
|
||||
@@ -1,394 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ProviderCoreEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
type WorkLogEntry,
|
||||
applyEventToMessages,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import type { ChatMessage, ThreadEvent } from "./types";
|
||||
|
||||
function makeEventRecord(
|
||||
event: ProviderCoreEvent,
|
||||
overrides: Partial<ThreadEvent> = {},
|
||||
): ThreadEvent {
|
||||
return {
|
||||
seq: overrides.seq ?? 1,
|
||||
at: overrides.at ?? "2026-02-08T10:00:00.000Z",
|
||||
event,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-08T09:59:00.000Z",
|
||||
updatedAt: "2026-02-08T09:59:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveTimelineEntries", () => {
|
||||
it("interleaves messages and work entries by timestamp", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
id: "m-user",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-assistant",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:05:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const workEntries: WorkLogEntry[] = [
|
||||
{
|
||||
id: "w-1",
|
||||
label: "Tool call",
|
||||
createdAt: "2026-02-08T10:02:00.000Z",
|
||||
tone: "tool",
|
||||
},
|
||||
{
|
||||
id: "w-2",
|
||||
label: "Plan updated",
|
||||
createdAt: "2026-02-08T10:03:00.000Z",
|
||||
tone: "thinking",
|
||||
},
|
||||
];
|
||||
|
||||
const timeline = deriveTimelineEntries(messages, workEntries);
|
||||
|
||||
expect(timeline.map((entry) => entry.id)).toEqual([
|
||||
"message:m-user",
|
||||
"work:w-1",
|
||||
"work:w-2",
|
||||
"message:m-assistant",
|
||||
]);
|
||||
});
|
||||
|
||||
it("prefers work entries when timestamps are equal", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
const workEntries: WorkLogEntry[] = [
|
||||
{
|
||||
id: "w-1",
|
||||
label: "Tool call",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
tone: "tool",
|
||||
},
|
||||
];
|
||||
|
||||
const timeline = deriveTimelineEntries(messages, workEntries);
|
||||
|
||||
expect(timeline.map((entry) => entry.id)).toEqual(["work:w-1", "message:m-1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries", () => {
|
||||
it("shows approvals, activities, and runtime errors", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEventRecord(
|
||||
{
|
||||
type: "error",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
code: "runtime/error",
|
||||
message: "sandbox denied",
|
||||
},
|
||||
{ seq: 3, at: "2026-02-08T10:00:02.000Z" },
|
||||
),
|
||||
makeEventRecord(
|
||||
{
|
||||
type: "activity",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
activityId: "tool-1",
|
||||
activityKind: "tool",
|
||||
label: "Tool call",
|
||||
detail: "spawnAgent",
|
||||
status: "success",
|
||||
completedAt: "2026-02-08T10:00:01.000Z",
|
||||
},
|
||||
{ seq: 2, at: "2026-02-08T10:00:01.000Z" },
|
||||
),
|
||||
makeEventRecord({
|
||||
type: "approval.requested",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
approvalId: "approval-1",
|
||||
approvalKind: "command",
|
||||
title: "Command approval requested",
|
||||
detail: "git status --short",
|
||||
requestedAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(3);
|
||||
expect(entries.map((entry) => entry.label)).toEqual([
|
||||
"Command approval requested",
|
||||
"Tool call",
|
||||
"Runtime error",
|
||||
]);
|
||||
});
|
||||
|
||||
it("suppresses created activity rows when a completion exists", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEventRecord({
|
||||
type: "activity",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
activityId: "tool-1",
|
||||
activityKind: "tool",
|
||||
label: "Tool call",
|
||||
detail: "ls -la",
|
||||
status: "created",
|
||||
startedAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEventRecord(
|
||||
{
|
||||
type: "activity",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
activityId: "tool-1",
|
||||
activityKind: "tool",
|
||||
label: "Tool call",
|
||||
detail: "ls -la",
|
||||
status: "success",
|
||||
completedAt: "2026-02-08T10:00:01.000Z",
|
||||
},
|
||||
{ seq: 2, at: "2026-02-08T10:00:01.000Z" },
|
||||
),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.detail).toBe("ls -la");
|
||||
});
|
||||
|
||||
it("shows failed turn completion", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEventRecord({
|
||||
type: "turn.completed",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:00:10.000Z",
|
||||
outcome: "failed",
|
||||
error: "boom",
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Turn failed");
|
||||
expect(entries[0]?.detail).toBe("boom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("evolveSession", () => {
|
||||
it("replaces session on session.updated", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
{
|
||||
type: "session.updated",
|
||||
session: {
|
||||
...previous,
|
||||
status: "running",
|
||||
threadId: "thread-1",
|
||||
activeTurnId: "turn-1",
|
||||
updatedAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
},
|
||||
"2026-02-08T10:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(next.status).toBe("running");
|
||||
expect(next.threadId).toBe("thread-1");
|
||||
expect(next.activeTurnId).toBe("turn-1");
|
||||
});
|
||||
|
||||
it("moves to running on turn.started", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
{
|
||||
type: "turn.started",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
startedAt: "2026-02-08T10:02:00.000Z",
|
||||
},
|
||||
"2026-02-08T10:02:00.000Z",
|
||||
);
|
||||
|
||||
expect(next.status).toBe("running");
|
||||
expect(next.activeTurnId).toBe("turn-1");
|
||||
});
|
||||
|
||||
it("returns to ready on successful completion", () => {
|
||||
const previous = makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
{
|
||||
type: "turn.completed",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:03:00.000Z",
|
||||
outcome: "completed",
|
||||
},
|
||||
"2026-02-08T10:03:00.000Z",
|
||||
);
|
||||
|
||||
expect(next.status).toBe("ready");
|
||||
expect(next.activeTurnId).toBeUndefined();
|
||||
});
|
||||
|
||||
it("marks session as error on runtime error", () => {
|
||||
const previous = makeSession();
|
||||
const next = evolveSession(
|
||||
previous,
|
||||
{
|
||||
type: "error",
|
||||
sessionId: "sess-1",
|
||||
code: "runtime/error",
|
||||
message: "runtime failure",
|
||||
},
|
||||
"2026-02-08T10:04:00.000Z",
|
||||
);
|
||||
|
||||
expect(next.status).toBe("error");
|
||||
expect(next.lastError).toBe("runtime failure");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyEventToMessages", () => {
|
||||
it("handles delta/completed flow for assistant messages", () => {
|
||||
const activeAssistantMessageRef = { current: null as string | null };
|
||||
const withDelta = applyEventToMessages(
|
||||
[],
|
||||
{
|
||||
type: "message.delta",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
messageId: "message-1",
|
||||
role: "assistant",
|
||||
delta: "Hello",
|
||||
},
|
||||
"2026-02-08T10:00:00.000Z",
|
||||
activeAssistantMessageRef,
|
||||
);
|
||||
|
||||
expect(withDelta).toEqual([
|
||||
{
|
||||
id: "message-1",
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
]);
|
||||
|
||||
const withMoreDelta = applyEventToMessages(
|
||||
withDelta,
|
||||
{
|
||||
type: "message.delta",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
messageId: "message-1",
|
||||
role: "assistant",
|
||||
delta: " world",
|
||||
},
|
||||
"2026-02-08T10:00:01.000Z",
|
||||
activeAssistantMessageRef,
|
||||
);
|
||||
expect(withMoreDelta[0]?.text).toBe("Hello world");
|
||||
|
||||
const completed = applyEventToMessages(
|
||||
withMoreDelta,
|
||||
{
|
||||
type: "message.completed",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
messageId: "message-1",
|
||||
role: "assistant",
|
||||
text: "Hello world!",
|
||||
},
|
||||
"2026-02-08T10:00:02.000Z",
|
||||
activeAssistantMessageRef,
|
||||
);
|
||||
|
||||
expect(completed[0]?.text).toBe("Hello world!");
|
||||
expect(completed[0]?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("clears streaming flags when a turn completes", () => {
|
||||
const previous: ChatMessage[] = [
|
||||
{
|
||||
id: "m-user",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-assistant",
|
||||
role: "assistant",
|
||||
text: "Typing",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
|
||||
const next = applyEventToMessages(
|
||||
previous,
|
||||
{
|
||||
type: "turn.completed",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:00:02.000Z",
|
||||
outcome: "completed",
|
||||
},
|
||||
"2026-02-08T10:00:02.000Z",
|
||||
{ current: null },
|
||||
);
|
||||
|
||||
expect(next.every((entry) => entry.streaming === false)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,440 +0,0 @@
|
||||
import type {
|
||||
NativeApi,
|
||||
ProviderCoreEvent,
|
||||
ProviderKind,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ChatMessage, SessionPhase, ThreadEvent } from "./types";
|
||||
import { createWsNativeApi } from "./wsNativeApi";
|
||||
|
||||
export const PROVIDER_OPTIONS: Array<{
|
||||
value: ProviderKind;
|
||||
label: string;
|
||||
available: boolean;
|
||||
}> = [
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code (soon)", available: false },
|
||||
];
|
||||
|
||||
let cachedApi: NativeApi | undefined;
|
||||
|
||||
export function readNativeApi(): NativeApi | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
if (cachedApi) return cachedApi;
|
||||
|
||||
// Prefer Electron preload bridge if available
|
||||
if (window.nativeApi) {
|
||||
cachedApi = window.nativeApi;
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
// Fall back to WebSocket transport
|
||||
cachedApi = createWsNativeApi();
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
export function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function formatTimestamp(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
}).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
export function formatDuration(durationMs: number): string {
|
||||
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
|
||||
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
|
||||
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
|
||||
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
|
||||
|
||||
const minutes = Math.floor(durationMs / 60_000);
|
||||
const seconds = Math.round((durationMs % 60_000) / 1_000);
|
||||
if (seconds === 0) return `${minutes}m`;
|
||||
if (seconds === 60) return `${minutes + 1}m`;
|
||||
return `${minutes}m ${seconds}s`;
|
||||
}
|
||||
|
||||
export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
|
||||
if (!endIso) return null;
|
||||
|
||||
const startedAt = Date.parse(startIso);
|
||||
const endedAt = Date.parse(endIso);
|
||||
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return formatDuration(endedAt - startedAt);
|
||||
}
|
||||
|
||||
export interface WorkLogEntry {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
label: string;
|
||||
detail?: string;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
}
|
||||
|
||||
export type TimelineEntry =
|
||||
| {
|
||||
id: string;
|
||||
kind: "message";
|
||||
createdAt: string;
|
||||
message: ChatMessage;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
kind: "work";
|
||||
createdAt: string;
|
||||
entry: WorkLogEntry;
|
||||
};
|
||||
|
||||
function normalizeDetail(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function eventTurnId(event: ProviderCoreEvent): string | undefined {
|
||||
switch (event.type) {
|
||||
case "turn.started":
|
||||
case "turn.completed":
|
||||
case "message.delta":
|
||||
case "message.completed":
|
||||
case "approval.requested":
|
||||
case "activity":
|
||||
case "error":
|
||||
return event.turnId;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function activityTone(event: Extract<ProviderCoreEvent, { type: "activity" }>): WorkLogEntry["tone"] {
|
||||
if (["failed", "denied", "timed_out"].includes(event.status)) {
|
||||
return "error";
|
||||
}
|
||||
|
||||
if (event.activityKind === "plan") {
|
||||
return "thinking";
|
||||
}
|
||||
|
||||
if (event.activityKind === "tool") {
|
||||
return "tool";
|
||||
}
|
||||
|
||||
return "info";
|
||||
}
|
||||
|
||||
function toWorkLogEntry(eventRecord: ThreadEvent): WorkLogEntry | null {
|
||||
const event = eventRecord.event;
|
||||
|
||||
if (event.type === "activity") {
|
||||
const detail = normalizeDetail(event.detail);
|
||||
if (event.label === "Tool call" && !detail) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: `activity:${event.activityId}`,
|
||||
createdAt: event.startedAt ?? event.completedAt ?? eventRecord.at,
|
||||
label: event.label,
|
||||
...(detail ? { detail } : {}),
|
||||
tone: activityTone(event),
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === "approval.requested") {
|
||||
const detail = normalizeDetail(event.detail);
|
||||
const label =
|
||||
event.approvalKind === "command"
|
||||
? "Command approval requested"
|
||||
: event.approvalKind === "file_change"
|
||||
? "File-change approval requested"
|
||||
: "Tool requested user input";
|
||||
|
||||
return {
|
||||
id: `approval:${event.approvalId}`,
|
||||
createdAt: event.requestedAt,
|
||||
label,
|
||||
...(detail ? { detail } : {}),
|
||||
tone: "tool",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed" && event.outcome === "failed") {
|
||||
return {
|
||||
id: `turn-failed:${event.turnId}`,
|
||||
createdAt: event.completedAt,
|
||||
label: "Turn failed",
|
||||
...(event.error ? { detail: event.error } : {}),
|
||||
tone: "error",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === "error") {
|
||||
const detail = normalizeDetail(event.message);
|
||||
return {
|
||||
id: `error:${event.code}:${eventRecord.seq}`,
|
||||
createdAt: eventRecord.at,
|
||||
label: "Runtime error",
|
||||
...(detail ? { detail } : {}),
|
||||
tone: "error",
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function deriveWorkLogEntries(
|
||||
events: ThreadEvent[],
|
||||
turnId: string | undefined,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = [...events].toReversed();
|
||||
const completedActivityIds = new Set<string>();
|
||||
|
||||
for (const eventRecord of ordered) {
|
||||
const event = eventRecord.event;
|
||||
if (event.type !== "activity") continue;
|
||||
if (turnId && event.turnId && event.turnId !== turnId) continue;
|
||||
if (["success", "failed", "denied", "timed_out"].includes(event.status)) {
|
||||
completedActivityIds.add(event.activityId);
|
||||
}
|
||||
}
|
||||
|
||||
const entries: WorkLogEntry[] = [];
|
||||
for (const eventRecord of ordered) {
|
||||
const event = eventRecord.event;
|
||||
|
||||
if (turnId) {
|
||||
const scopedTurnId = eventTurnId(event);
|
||||
if (scopedTurnId && scopedTurnId !== turnId) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
event.type === "activity" &&
|
||||
event.status === "created" &&
|
||||
completedActivityIds.has(event.activityId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry = toWorkLogEntry(eventRecord);
|
||||
if (entry) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function toTimestamp(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
||||
}
|
||||
|
||||
export function deriveTimelineEntries(
|
||||
messages: ChatMessage[],
|
||||
workEntries: WorkLogEntry[],
|
||||
): TimelineEntry[] {
|
||||
const timeline: TimelineEntry[] = [];
|
||||
let messageIndex = 0;
|
||||
let workIndex = 0;
|
||||
|
||||
while (messageIndex < messages.length || workIndex < workEntries.length) {
|
||||
const message = messages[messageIndex];
|
||||
const workEntry = workEntries[workIndex];
|
||||
|
||||
if (!message && workEntry) {
|
||||
timeline.push({
|
||||
id: `work:${workEntry.id}`,
|
||||
kind: "work",
|
||||
createdAt: workEntry.createdAt,
|
||||
entry: workEntry,
|
||||
});
|
||||
workIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!workEntry && message) {
|
||||
timeline.push({
|
||||
id: `message:${message.id}`,
|
||||
kind: "message",
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
});
|
||||
messageIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!message || !workEntry) {
|
||||
break;
|
||||
}
|
||||
|
||||
const messageAt = toTimestamp(message.createdAt);
|
||||
const workAt = toTimestamp(workEntry.createdAt);
|
||||
|
||||
if (workAt <= messageAt) {
|
||||
timeline.push({
|
||||
id: `work:${workEntry.id}`,
|
||||
kind: "work",
|
||||
createdAt: workEntry.createdAt,
|
||||
entry: workEntry,
|
||||
});
|
||||
workIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
timeline.push({
|
||||
id: `message:${message.id}`,
|
||||
kind: "message",
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
});
|
||||
messageIndex += 1;
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
export function derivePhase(session: ProviderSession | null): SessionPhase {
|
||||
if (!session || session.status === "closed") return "disconnected";
|
||||
if (session.status === "connecting") return "connecting";
|
||||
if (session.status === "running") return "running";
|
||||
return "ready";
|
||||
}
|
||||
|
||||
export function evolveSession(
|
||||
previous: ProviderSession,
|
||||
event: ProviderCoreEvent,
|
||||
frameAt: string,
|
||||
): ProviderSession {
|
||||
if (event.type === "session.updated") {
|
||||
return event.session;
|
||||
}
|
||||
|
||||
if (event.type === "turn.started") {
|
||||
return {
|
||||
...previous,
|
||||
status: "running",
|
||||
threadId: event.threadId,
|
||||
activeTurnId: event.turnId,
|
||||
...(event.model ? { model: event.model } : {}),
|
||||
updatedAt: event.startedAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
return {
|
||||
...previous,
|
||||
status: event.outcome === "failed" ? "error" : "ready",
|
||||
threadId: event.threadId,
|
||||
activeTurnId: undefined,
|
||||
...(event.error ? { lastError: event.error } : {}),
|
||||
updatedAt: event.completedAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === "error") {
|
||||
return {
|
||||
...previous,
|
||||
...(event.retryable ? {} : { status: "error" }),
|
||||
lastError: event.message,
|
||||
updatedAt: frameAt,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...previous,
|
||||
updatedAt: frameAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function applyEventToMessages(
|
||||
previous: ChatMessage[],
|
||||
event: ProviderCoreEvent,
|
||||
frameAt: string,
|
||||
activeAssistantMessageRef: { current: string | null },
|
||||
): ChatMessage[] {
|
||||
if (event.type === "message.delta") {
|
||||
const messageId = event.messageId;
|
||||
const delta = event.delta;
|
||||
if (!delta) return previous;
|
||||
|
||||
const existingIndex = previous.findIndex((entry) => entry.id === messageId);
|
||||
if (existingIndex === -1) {
|
||||
activeAssistantMessageRef.current = messageId;
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: messageId,
|
||||
role: "assistant",
|
||||
text: delta,
|
||||
createdAt: frameAt,
|
||||
streaming: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const updated = [...previous];
|
||||
const existing = updated[existingIndex];
|
||||
if (!existing) return previous;
|
||||
|
||||
updated[existingIndex] = {
|
||||
...existing,
|
||||
text: `${existing.text}${delta}`,
|
||||
streaming: true,
|
||||
};
|
||||
return updated;
|
||||
}
|
||||
|
||||
if (event.type === "message.completed") {
|
||||
const messageId = event.messageId;
|
||||
const existingIndex = previous.findIndex((entry) => entry.id === messageId);
|
||||
|
||||
if (existingIndex === -1) {
|
||||
return [
|
||||
...previous,
|
||||
{
|
||||
id: messageId,
|
||||
role: "assistant",
|
||||
text: event.text,
|
||||
createdAt: frameAt,
|
||||
streaming: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const updated = [...previous];
|
||||
const existing = updated[existingIndex];
|
||||
if (!existing) return previous;
|
||||
|
||||
updated[existingIndex] = {
|
||||
...existing,
|
||||
text: event.text || existing.text,
|
||||
streaming: false,
|
||||
};
|
||||
|
||||
if (activeAssistantMessageRef.current === messageId) {
|
||||
activeAssistantMessageRef.current = null;
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
return previous.map((entry) => ({ ...entry, streaming: false }));
|
||||
}
|
||||
|
||||
return previous;
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
import type {
|
||||
ProviderCoreEvent,
|
||||
ProviderSession,
|
||||
ProviderStreamFrame,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
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 makeEventFrame(
|
||||
event: ProviderCoreEvent,
|
||||
overrides: Partial<Pick<ProviderStreamFrame, "seq" | "at">> = {},
|
||||
): ProviderStreamFrame {
|
||||
return {
|
||||
kind: "event",
|
||||
seq: 1,
|
||||
at: "2026-02-09T00:00:01.000Z",
|
||||
data: event,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: "thread-local-1",
|
||||
codexThreadId: null,
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
session: makeSession(),
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeState(thread: Thread): AppState {
|
||||
return {
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
activeThreadId: thread.id,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
lastProviderSeq: 0,
|
||||
};
|
||||
}
|
||||
|
||||
describe("store reducer stream integration", () => {
|
||||
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("backfills codexThreadId from session.updated stream events", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: null }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STREAM_FRAME",
|
||||
frame: makeEventFrame({
|
||||
type: "session.updated",
|
||||
session: makeSession({
|
||||
threadId: "thr_backfilled",
|
||||
updatedAt: "2026-02-09T00:00:01.000Z",
|
||||
}),
|
||||
}),
|
||||
activeAssistantMessageRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_backfilled");
|
||||
expect(next.lastProviderSeq).toBe(1);
|
||||
});
|
||||
|
||||
it("ignores events from a foreign thread within the same session", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: "thr_expected" }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STREAM_FRAME",
|
||||
frame: makeEventFrame({
|
||||
type: "turn.started",
|
||||
sessionId: "sess-1",
|
||||
threadId: "thr_unexpected",
|
||||
turnId: "turn-1",
|
||||
startedAt: "2026-02-09T00:00:01.000Z",
|
||||
}),
|
||||
activeAssistantMessageRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]).toEqual(state.threads[0]);
|
||||
expect(next.lastProviderSeq).toBe(1);
|
||||
});
|
||||
|
||||
it("always applies session.updated even when thread id changes", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: "thr_old" }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STREAM_FRAME",
|
||||
frame: makeEventFrame({
|
||||
type: "session.updated",
|
||||
session: makeSession({
|
||||
threadId: "thr_new",
|
||||
updatedAt: "2026-02-09T00:00:01.000Z",
|
||||
}),
|
||||
}),
|
||||
activeAssistantMessageRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_new");
|
||||
expect(next.threads[0]?.session?.threadId).toBe("thr_new");
|
||||
});
|
||||
|
||||
it("applies snapshot frames as authoritative baseline", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
codexThreadId: "thr_old",
|
||||
session: makeSession({
|
||||
threadId: "thr_old",
|
||||
status: "running",
|
||||
activeTurnId: "turn_old",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_STREAM_FRAME",
|
||||
frame: {
|
||||
kind: "snapshot",
|
||||
seq: 10,
|
||||
at: "2026-02-09T00:00:10.000Z",
|
||||
data: {
|
||||
sessions: [
|
||||
makeSession({
|
||||
threadId: "thr_new",
|
||||
status: "running",
|
||||
activeTurnId: "turn_new",
|
||||
updatedAt: "2026-02-09T00:00:10.000Z",
|
||||
}),
|
||||
],
|
||||
activeTurns: [
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
threadId: "thr_new",
|
||||
turnId: "turn_new",
|
||||
startedAt: "2026-02-09T00:00:09.000Z",
|
||||
},
|
||||
],
|
||||
activeMessages: [
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
threadId: "thr_new",
|
||||
turnId: "turn_new",
|
||||
messageId: "msg-1",
|
||||
role: "assistant",
|
||||
text: "streaming",
|
||||
startedAt: "2026-02-09T00:00:09.100Z",
|
||||
updatedAt: "2026-02-09T00:00:09.500Z",
|
||||
},
|
||||
],
|
||||
pendingApprovals: [
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
threadId: "thr_new",
|
||||
turnId: "turn_new",
|
||||
approvalId: "approval-1",
|
||||
approvalKind: "command",
|
||||
title: "Command approval requested",
|
||||
detail: "git status --short",
|
||||
requestedAt: "2026-02-09T00:00:09.200Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
activeAssistantMessageRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.lastProviderSeq).toBe(10);
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_new");
|
||||
expect(next.threads[0]?.latestTurnId).toBe("turn_new");
|
||||
expect(next.threads[0]?.messages.at(-1)?.id).toBe("msg-1");
|
||||
expect(next.threads[0]?.messages.at(-1)?.streaming).toBe(true);
|
||||
expect(next.threads[0]?.events[0]?.event.type).toBe("approval.requested");
|
||||
});
|
||||
|
||||
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,
|
||||
},
|
||||
{
|
||||
id: "project-old-b",
|
||||
name: "B",
|
||||
cwd: "/tmp/b",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
makeThread({
|
||||
id: "thread-a",
|
||||
projectId: "project-old-a",
|
||||
}),
|
||||
makeThread({
|
||||
id: "thread-b",
|
||||
projectId: "project-old-b",
|
||||
}),
|
||||
],
|
||||
activeThreadId: "thread-b",
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
lastProviderSeq: 0,
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SYNC_PROJECTS",
|
||||
projects: [
|
||||
{
|
||||
id: "project-new-a",
|
||||
name: "A",
|
||||
cwd: "/tmp/a",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.id).toBe("project-new-a");
|
||||
// Preserve existing project UI preferences by cwd
|
||||
expect(next.projects[0]?.expanded).toBe(false);
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-a");
|
||||
expect(next.threads[0]?.projectId).toBe("project-new-a");
|
||||
expect(next.activeThreadId).toBe("thread-a");
|
||||
});
|
||||
});
|
||||
@@ -1,629 +0,0 @@
|
||||
import {
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from "react";
|
||||
import type {
|
||||
ProviderCoreEvent,
|
||||
ProviderSession,
|
||||
ProviderSnapshot,
|
||||
ProviderStreamFrame,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, evolveSession } from "./session-logic";
|
||||
import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadEvent,
|
||||
} from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: string }
|
||||
| { type: "ADD_THREAD"; thread: Thread }
|
||||
| { type: "SET_ACTIVE_THREAD"; threadId: string }
|
||||
| { type: "TOGGLE_DIFF" }
|
||||
| {
|
||||
type: "APPLY_STREAM_FRAME";
|
||||
frame: ProviderStreamFrame;
|
||||
activeAssistantMessageRef: { current: string | null };
|
||||
}
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
|
||||
| { type: "SET_ERROR"; threadId: string; error: string | null }
|
||||
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
|
||||
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
|
||||
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AppState {
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
activeThreadId: string | null;
|
||||
runtimeMode: RuntimeMode;
|
||||
diffOpen: boolean;
|
||||
lastProviderSeq: number;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v4";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
"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: [],
|
||||
activeThreadId: null,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
diffOpen: false,
|
||||
lastProviderSeq: 0,
|
||||
};
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const [legacyV3Key, legacyV2Key, legacyV1Key] = LEGACY_PERSISTED_STATE_KEYS;
|
||||
const rawLegacyV3 = window.localStorage.getItem(legacyV3Key);
|
||||
const rawLegacyV2 = window.localStorage.getItem(legacyV2Key);
|
||||
const rawLegacyV1 = window.localStorage.getItem(legacyV1Key);
|
||||
const raw = rawCurrent ?? rawLegacyV3 ?? rawLegacyV2 ?? rawLegacyV1;
|
||||
if (!raw) return initialState;
|
||||
const hydrated = hydratePersistedState(
|
||||
raw,
|
||||
!rawCurrent && !rawLegacyV3 && !rawLegacyV2 && Boolean(rawLegacyV1),
|
||||
);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
return { ...hydrated, diffOpen: false, lastProviderSeq: 0 };
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
}
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
threads: Thread[],
|
||||
threadId: string,
|
||||
updater: (t: Thread) => Thread,
|
||||
): Thread[] {
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
|
||||
return threads.find((t) => t.session?.sessionId === sessionId);
|
||||
}
|
||||
|
||||
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 eventSessionId(event: ProviderCoreEvent): string | undefined {
|
||||
if (event.type === "session.updated") {
|
||||
return event.session.sessionId;
|
||||
}
|
||||
|
||||
if (event.type === "debug.raw") {
|
||||
return event.sessionId;
|
||||
}
|
||||
|
||||
return event.sessionId;
|
||||
}
|
||||
|
||||
function eventThreadId(event: ProviderCoreEvent): string | undefined {
|
||||
if (event.type === "session.updated") {
|
||||
return event.session.threadId;
|
||||
}
|
||||
|
||||
if (event.type === "turn.started") {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
if (event.type === "message.delta") {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
if (event.type === "message.completed") {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
if (event.type === "approval.requested") {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
if (event.type === "activity") {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
if (event.type === "error") {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function shouldIgnoreForeignThreadEvent(thread: Thread, event: ProviderCoreEvent): boolean {
|
||||
if (event.type === "session.updated") {
|
||||
// Session snapshots are authoritative for thread identity and should never
|
||||
// be blocked by stale local thread bindings.
|
||||
return false;
|
||||
}
|
||||
|
||||
const emittedThreadId = eventThreadId(event);
|
||||
if (!emittedThreadId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expectedThreadId = thread.session?.threadId ?? thread.codexThreadId;
|
||||
if (!expectedThreadId || emittedThreadId === expectedThreadId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function updateTurnFields(
|
||||
thread: Thread,
|
||||
event: ProviderCoreEvent,
|
||||
): Partial<Thread> {
|
||||
if (event.type === "turn.started") {
|
||||
return {
|
||||
latestTurnId: event.turnId,
|
||||
latestTurnStartedAt: event.startedAt,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const startedAt =
|
||||
event.turnId === thread.latestTurnId
|
||||
? thread.latestTurnStartedAt
|
||||
: undefined;
|
||||
const elapsed =
|
||||
event.durationMs ??
|
||||
(startedAt && startedAt.length > 0
|
||||
? durationMs(startedAt, event.completedAt)
|
||||
: undefined);
|
||||
|
||||
return {
|
||||
latestTurnId: event.turnId,
|
||||
latestTurnCompletedAt: event.completedAt,
|
||||
latestTurnDurationMs: elapsed,
|
||||
};
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
function shouldPersistThreadEvent(event: ProviderCoreEvent): boolean {
|
||||
if (event.type === "message.delta") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (event.type === "debug.raw") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (event.type === "session.updated") {
|
||||
return event.session.status === "error" || event.session.status === "closed";
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function appendThreadEvent(
|
||||
events: ThreadEvent[],
|
||||
eventRecord: ThreadEvent,
|
||||
): ThreadEvent[] {
|
||||
return [eventRecord, ...events].slice(0, 2_000);
|
||||
}
|
||||
|
||||
function approvalEventsFromSnapshot(
|
||||
approvals: ProviderSnapshot["pendingApprovals"],
|
||||
seq: number,
|
||||
): ThreadEvent[] {
|
||||
return approvals
|
||||
.map((approval) => ({
|
||||
seq,
|
||||
at: approval.requestedAt,
|
||||
event: {
|
||||
type: "approval.requested",
|
||||
sessionId: approval.sessionId,
|
||||
...(approval.threadId ? { threadId: approval.threadId } : {}),
|
||||
...(approval.turnId ? { turnId: approval.turnId } : {}),
|
||||
approvalId: approval.approvalId,
|
||||
approvalKind: approval.approvalKind,
|
||||
title: approval.title,
|
||||
...(approval.detail ? { detail: approval.detail } : {}),
|
||||
...(approval.payload !== undefined ? { payload: approval.payload } : {}),
|
||||
...(approval.timeoutAt ? { timeoutAt: approval.timeoutAt } : {}),
|
||||
requestedAt: approval.requestedAt,
|
||||
} satisfies ProviderCoreEvent,
|
||||
}))
|
||||
.toSorted((left, right) => Date.parse(right.at) - Date.parse(left.at));
|
||||
}
|
||||
|
||||
function applySnapshotToThread(
|
||||
thread: Thread,
|
||||
snapshot: ProviderSnapshot,
|
||||
seq: number,
|
||||
): Thread {
|
||||
if (!thread.session) {
|
||||
return thread;
|
||||
}
|
||||
|
||||
const sessionId = thread.session.sessionId;
|
||||
const snapshotSession = snapshot.sessions.find((session) => session.sessionId === sessionId);
|
||||
if (!snapshotSession) {
|
||||
return {
|
||||
...thread,
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => ({
|
||||
...message,
|
||||
streaming: false,
|
||||
})),
|
||||
events: [],
|
||||
error: null,
|
||||
latestTurnId: undefined,
|
||||
latestTurnStartedAt: undefined,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const activeTurns = snapshot.activeTurns
|
||||
.filter((turn) => turn.sessionId === sessionId)
|
||||
.toSorted((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt));
|
||||
const activeTurn = activeTurns[0];
|
||||
|
||||
const activeMessages = snapshot.activeMessages
|
||||
.filter((message) => message.sessionId === sessionId)
|
||||
.toSorted((left, right) => Date.parse(left.startedAt) - Date.parse(right.startedAt));
|
||||
const activeMessageIds = new Set(activeMessages.map((message) => message.messageId));
|
||||
|
||||
const keptMessages = thread.messages
|
||||
.filter((message) => !message.streaming)
|
||||
.filter((message) => !activeMessageIds.has(message.id));
|
||||
|
||||
const hydratedMessages = activeMessages.map((message) => ({
|
||||
id: message.messageId,
|
||||
role: "assistant" as const,
|
||||
text: message.text,
|
||||
createdAt: message.startedAt,
|
||||
streaming: true,
|
||||
}));
|
||||
|
||||
const pendingApprovals = snapshot.pendingApprovals.filter(
|
||||
(approval) => approval.sessionId === sessionId,
|
||||
);
|
||||
|
||||
return {
|
||||
...thread,
|
||||
codexThreadId: snapshotSession.threadId ?? thread.codexThreadId,
|
||||
session: snapshotSession,
|
||||
messages: [...keptMessages, ...hydratedMessages],
|
||||
events: approvalEventsFromSnapshot(pendingApprovals, seq),
|
||||
error: snapshotSession.lastError ?? (snapshotSession.status === "error" ? thread.error : null),
|
||||
latestTurnId: activeTurn?.turnId,
|
||||
latestTurnStartedAt: activeTurn?.startedAt,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function applySnapshotToThreads(
|
||||
threads: Thread[],
|
||||
snapshot: ProviderSnapshot,
|
||||
seq: number,
|
||||
): Thread[] {
|
||||
return threads.map((thread) => applySnapshotToThread(thread, snapshot, seq));
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "ADD_PROJECT":
|
||||
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
projects: [
|
||||
...state.projects,
|
||||
{
|
||||
...action.project,
|
||||
model: resolveModelSlug(action.project.model),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
case "SYNC_PROJECTS": {
|
||||
const previousByCwd = new Map(
|
||||
state.projects.map((project) => [project.cwd, project] as const),
|
||||
);
|
||||
const nextProjects = action.projects.map((project) => {
|
||||
const previous = previousByCwd.get(project.cwd);
|
||||
return {
|
||||
...project,
|
||||
model: resolveModelSlug(previous?.model ?? project.model),
|
||||
expanded: previous?.expanded ?? project.expanded,
|
||||
};
|
||||
});
|
||||
const previousProjectById = new Map(
|
||||
state.projects.map((project) => [project.id, project] as const),
|
||||
);
|
||||
const nextProjectIdByCwd = new Map(
|
||||
nextProjects.map((project) => [project.cwd, project.id] as const),
|
||||
);
|
||||
const nextThreads = state.threads
|
||||
.map((thread) => {
|
||||
const previousProject = previousProjectById.get(thread.projectId);
|
||||
if (!previousProject) return null;
|
||||
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
|
||||
if (!mappedProjectId) return null;
|
||||
return {
|
||||
...thread,
|
||||
projectId: mappedProjectId,
|
||||
};
|
||||
})
|
||||
.filter((thread): thread is Thread => thread !== null);
|
||||
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
|
||||
? state.activeThreadId
|
||||
: (nextThreads[0]?.id ?? null);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
threads: nextThreads,
|
||||
activeThreadId,
|
||||
};
|
||||
}
|
||||
|
||||
case "TOGGLE_PROJECT":
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
};
|
||||
|
||||
case "ADD_THREAD":
|
||||
return {
|
||||
...state,
|
||||
threads: [
|
||||
...state.threads,
|
||||
{
|
||||
...action.thread,
|
||||
model: resolveModelSlug(action.thread.model),
|
||||
},
|
||||
],
|
||||
activeThreadId: action.thread.id,
|
||||
};
|
||||
|
||||
case "SET_ACTIVE_THREAD":
|
||||
return { ...state, activeThreadId: action.threadId };
|
||||
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "APPLY_STREAM_FRAME": {
|
||||
const { frame, activeAssistantMessageRef } = action;
|
||||
if (frame.seq <= state.lastProviderSeq) {
|
||||
return state;
|
||||
}
|
||||
|
||||
if (frame.kind === "gap") {
|
||||
return {
|
||||
...state,
|
||||
lastProviderSeq: frame.seq,
|
||||
};
|
||||
}
|
||||
|
||||
if (frame.kind === "snapshot") {
|
||||
return {
|
||||
...state,
|
||||
threads: applySnapshotToThreads(state.threads, frame.data, frame.seq),
|
||||
lastProviderSeq: frame.seq,
|
||||
};
|
||||
}
|
||||
|
||||
const sessionId = eventSessionId(frame.data);
|
||||
if (!sessionId) {
|
||||
return {
|
||||
...state,
|
||||
lastProviderSeq: frame.seq,
|
||||
};
|
||||
}
|
||||
|
||||
const target = findThreadBySessionId(state.threads, sessionId);
|
||||
if (!target) {
|
||||
return {
|
||||
...state,
|
||||
lastProviderSeq: frame.seq,
|
||||
};
|
||||
}
|
||||
|
||||
if (shouldIgnoreForeignThreadEvent(target, frame.data)) {
|
||||
return {
|
||||
...state,
|
||||
lastProviderSeq: frame.seq,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
lastProviderSeq: frame.seq,
|
||||
threads: updateThread(state.threads, target.id, (thread) => {
|
||||
const nextSession =
|
||||
frame.data.type === "session.updated"
|
||||
? frame.data.session
|
||||
: thread.session
|
||||
? evolveSession(thread.session, frame.data, frame.at)
|
||||
: thread.session;
|
||||
|
||||
return {
|
||||
...thread,
|
||||
codexThreadId: nextSession?.threadId ?? thread.codexThreadId,
|
||||
session: nextSession,
|
||||
messages: applyEventToMessages(
|
||||
thread.messages,
|
||||
frame.data,
|
||||
frame.at,
|
||||
activeAssistantMessageRef,
|
||||
),
|
||||
events: shouldPersistThreadEvent(frame.data)
|
||||
? appendThreadEvent(thread.events, {
|
||||
seq: frame.seq,
|
||||
at: frame.at,
|
||||
event: frame.data,
|
||||
})
|
||||
: thread.events,
|
||||
error:
|
||||
frame.data.type === "error"
|
||||
? frame.data.message
|
||||
: frame.data.type === "turn.completed" && frame.data.outcome === "failed"
|
||||
? (frame.data.error ?? thread.error)
|
||||
: frame.data.type === "session.updated" && frame.data.session.status === "error"
|
||||
? (frame.data.session.lastError ?? thread.error)
|
||||
: thread.error,
|
||||
...updateTurnFields(thread, frame.data),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
case "UPDATE_SESSION":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
session: action.session,
|
||||
codexThreadId: action.session.threadId ?? t.codexThreadId,
|
||||
events: [],
|
||||
error: null,
|
||||
latestTurnId: undefined,
|
||||
latestTurnStartedAt: undefined,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
})),
|
||||
};
|
||||
|
||||
case "PUSH_USER_MESSAGE":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
messages: [
|
||||
...t.messages,
|
||||
{
|
||||
id: action.id,
|
||||
role: "user" as const,
|
||||
text: action.text,
|
||||
createdAt: new Date().toISOString(),
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_ERROR":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
error: action.error,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TITLE":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
title: action.title,
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_THREAD_MODEL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
model: resolveModelSlug(action.model),
|
||||
})),
|
||||
};
|
||||
|
||||
case "SET_RUNTIME_MODE":
|
||||
return {
|
||||
...state,
|
||||
runtimeMode: action.mode,
|
||||
};
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Context ──────────────────────────────────────────────────────────
|
||||
|
||||
const StoreContext = createContext<{
|
||||
state: AppState;
|
||||
dispatch: Dispatch<Action>;
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function useStore() {
|
||||
return useContext(StoreContext);
|
||||
}
|
||||
Vendored
-15
@@ -1,15 +0,0 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
|
||||
interface DesktopBridge {
|
||||
getWsUrl: () => string | null;
|
||||
pickFolder: () => Promise<string | null>;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
nativeApi?: NativeApi;
|
||||
desktopBridge?: DesktopBridge;
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type ProvidersOpenStreamResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
type PushListener = (data: unknown) => void;
|
||||
type ConnectionState = "open" | "closed";
|
||||
type ConnectionListener = (state: ConnectionState) => void;
|
||||
|
||||
function createDeferred<T>() {
|
||||
let resolve!: (value: T | PromiseLike<T>) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
const transportState = {
|
||||
openRequests: [] as Array<{ params: unknown }>,
|
||||
closeRequests: [] as Array<{ params: unknown }>,
|
||||
openDeferredQueue: [] as Array<ReturnType<typeof createDeferred<ProvidersOpenStreamResult>>>,
|
||||
latest: null as MockWsTransport | null,
|
||||
reset() {
|
||||
this.openRequests = [];
|
||||
this.closeRequests = [];
|
||||
this.openDeferredQueue = [];
|
||||
this.latest = null;
|
||||
},
|
||||
};
|
||||
|
||||
class MockWsTransport {
|
||||
private readonly listeners = new Map<string, Set<PushListener>>();
|
||||
private readonly connectionListeners = new Set<ConnectionListener>();
|
||||
|
||||
constructor() {
|
||||
transportState.latest = this;
|
||||
}
|
||||
|
||||
request<T = unknown>(method: string, params?: unknown): Promise<T> {
|
||||
if (method === WS_METHODS.providersOpenStream) {
|
||||
transportState.openRequests.push({ params });
|
||||
const deferred = transportState.openDeferredQueue.shift();
|
||||
if (!deferred) {
|
||||
return Promise.resolve({
|
||||
mode: "snapshot",
|
||||
currentSeq: 0,
|
||||
oldestSeq: 0,
|
||||
replayedCount: 0,
|
||||
} as T);
|
||||
}
|
||||
return deferred.promise as Promise<T>;
|
||||
}
|
||||
|
||||
if (method === WS_METHODS.providersCloseStream) {
|
||||
transportState.closeRequests.push({ params });
|
||||
return Promise.resolve(undefined as T);
|
||||
}
|
||||
|
||||
return Promise.resolve(undefined as T);
|
||||
}
|
||||
|
||||
subscribe(channel: string, listener: PushListener): () => void {
|
||||
const listeners = this.listeners.get(channel) ?? new Set<PushListener>();
|
||||
listeners.add(listener);
|
||||
this.listeners.set(channel, listeners);
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0) {
|
||||
this.listeners.delete(channel);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
onConnectionStateChange(listener: ConnectionListener): () => void {
|
||||
this.connectionListeners.add(listener);
|
||||
return () => {
|
||||
this.connectionListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
emitPush(channel: string, data: unknown): void {
|
||||
const listeners = this.listeners.get(channel);
|
||||
if (!listeners) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const listener of listeners) {
|
||||
listener(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock("./wsTransport", () => ({
|
||||
WsTransport: MockWsTransport,
|
||||
}));
|
||||
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
describe("createWsNativeApi stream lifecycle", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
transportState.reset();
|
||||
});
|
||||
|
||||
it("does not close the stream when open is in flight and a listener re-subscribes", async () => {
|
||||
const openDeferred = createDeferred<ProvidersOpenStreamResult>();
|
||||
transportState.openDeferredQueue.push(openDeferred);
|
||||
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
const api = createWsNativeApi();
|
||||
|
||||
const frames: unknown[] = [];
|
||||
const unsubscribeA = api.providers.onStream((frame) => {
|
||||
frames.push(frame);
|
||||
});
|
||||
|
||||
expect(transportState.openRequests).toHaveLength(1);
|
||||
|
||||
unsubscribeA();
|
||||
expect(transportState.closeRequests).toHaveLength(0);
|
||||
|
||||
const unsubscribeB = api.providers.onStream((frame) => {
|
||||
frames.push(frame);
|
||||
});
|
||||
expect(transportState.openRequests).toHaveLength(1);
|
||||
|
||||
openDeferred.resolve({
|
||||
mode: "snapshot",
|
||||
currentSeq: 10,
|
||||
oldestSeq: 1,
|
||||
replayedCount: 0,
|
||||
});
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(transportState.closeRequests).toHaveLength(0);
|
||||
|
||||
transportState.latest?.emitPush(WS_CHANNELS.providerStream, {
|
||||
kind: "event",
|
||||
seq: 11,
|
||||
at: "2026-02-10T08:30:00.000Z",
|
||||
data: {
|
||||
type: "error",
|
||||
code: "runtime/error",
|
||||
message: "boom",
|
||||
},
|
||||
});
|
||||
|
||||
expect(frames).toHaveLength(1);
|
||||
|
||||
unsubscribeB();
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(transportState.closeRequests).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,258 +0,0 @@
|
||||
import {
|
||||
type NativeApi,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
providerStreamFrameSchema,
|
||||
type ProviderStreamFrame,
|
||||
type ProvidersOpenStreamInput,
|
||||
type ProvidersOpenStreamResult,
|
||||
type WsWelcomePayload,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { WsTransport } from "./wsTransport";
|
||||
|
||||
let instance: { api: NativeApi; transport: WsTransport } | null = null;
|
||||
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
|
||||
let lastWelcome: WsWelcomePayload | null = null;
|
||||
|
||||
/**
|
||||
* Subscribe to the server welcome message. If a welcome was already received
|
||||
* before this call, the listener fires synchronously with the cached payload.
|
||||
* This avoids the race between WebSocket connect and React effect registration.
|
||||
*/
|
||||
export function onServerWelcome(listener: (payload: WsWelcomePayload) => void): () => void {
|
||||
welcomeListeners.add(listener);
|
||||
|
||||
if (lastWelcome) {
|
||||
try {
|
||||
listener(lastWelcome);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
welcomeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeOpenInput(input: ProvidersOpenStreamInput): ProvidersOpenStreamInput {
|
||||
const sanitized: ProvidersOpenStreamInput = {};
|
||||
|
||||
if (input.afterSeq !== undefined) {
|
||||
sanitized.afterSeq = input.afterSeq;
|
||||
}
|
||||
if (input.sessionIds && input.sessionIds.length > 0) {
|
||||
sanitized.sessionIds = [...input.sessionIds];
|
||||
}
|
||||
if (input.eventKinds && input.eventKinds.length > 0) {
|
||||
sanitized.eventKinds = [...input.eventKinds];
|
||||
}
|
||||
if (input.includeExtensions && input.includeExtensions.length > 0) {
|
||||
sanitized.includeExtensions = [...input.includeExtensions];
|
||||
}
|
||||
if (input.includeDebugRaw !== undefined) {
|
||||
sanitized.includeDebugRaw = input.includeDebugRaw;
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
if (instance) return instance.api;
|
||||
|
||||
const transport = new WsTransport();
|
||||
const providerStreamListeners = new Set<(frame: ProviderStreamFrame) => void>();
|
||||
let lastAppliedSeq = 0;
|
||||
let streamConfig: ProvidersOpenStreamInput = {};
|
||||
let streamOpenInFlight: Promise<ProvidersOpenStreamResult> | null = null;
|
||||
let streamOpen = false;
|
||||
let streamOpening = false;
|
||||
let pendingCloseAfterOpen = false;
|
||||
|
||||
const openStream = async (
|
||||
overrides?: ProvidersOpenStreamInput,
|
||||
): Promise<ProvidersOpenStreamResult> => {
|
||||
if (overrides) {
|
||||
streamConfig = sanitizeOpenInput(overrides);
|
||||
}
|
||||
|
||||
if (streamOpenInFlight) {
|
||||
return streamOpenInFlight;
|
||||
}
|
||||
|
||||
const openInput: ProvidersOpenStreamInput = {
|
||||
...streamConfig,
|
||||
...(lastAppliedSeq > 0 ? { afterSeq: lastAppliedSeq } : {}),
|
||||
};
|
||||
|
||||
streamOpening = true;
|
||||
streamOpenInFlight = transport
|
||||
.request<ProvidersOpenStreamResult>(WS_METHODS.providersOpenStream, openInput)
|
||||
.then((result) => {
|
||||
const hasActiveListeners = providerStreamListeners.size > 0;
|
||||
const shouldCloseAfterOpen = pendingCloseAfterOpen && !hasActiveListeners;
|
||||
|
||||
streamOpen = !shouldCloseAfterOpen;
|
||||
pendingCloseAfterOpen = false;
|
||||
|
||||
if (shouldCloseAfterOpen) {
|
||||
void transport.request(WS_METHODS.providersCloseStream).catch(() => {
|
||||
// Ignore close errors while reconnect logic restores transport.
|
||||
});
|
||||
}
|
||||
|
||||
if (result.mode !== "replay") {
|
||||
// Resync modes can legally move the cursor backwards after server restart.
|
||||
lastAppliedSeq = result.currentSeq;
|
||||
}
|
||||
|
||||
return result;
|
||||
})
|
||||
.finally(() => {
|
||||
streamOpening = false;
|
||||
streamOpenInFlight = null;
|
||||
});
|
||||
|
||||
return streamOpenInFlight;
|
||||
};
|
||||
|
||||
const ensureStreamOpen = () => {
|
||||
if (providerStreamListeners.size === 0 || streamOpen) {
|
||||
return;
|
||||
}
|
||||
pendingCloseAfterOpen = false;
|
||||
|
||||
void openStream().catch(() => {
|
||||
// Ignore open failures. Reconnect lifecycle retries automatically.
|
||||
});
|
||||
};
|
||||
|
||||
transport.onConnectionStateChange((state) => {
|
||||
if (state === "open") {
|
||||
streamOpen = false;
|
||||
ensureStreamOpen();
|
||||
return;
|
||||
}
|
||||
|
||||
streamOpen = false;
|
||||
});
|
||||
|
||||
// Listen for server welcome and forward to registered listeners.
|
||||
// Also cache it so late subscribers (React effects) get it immediately.
|
||||
transport.subscribe(WS_CHANNELS.serverWelcome, (data) => {
|
||||
const payload = data as WsWelcomePayload;
|
||||
lastWelcome = payload;
|
||||
for (const listener of welcomeListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
transport.subscribe(WS_CHANNELS.providerStream, (data) => {
|
||||
const parsed = providerStreamFrameSchema.safeParse(data);
|
||||
if (!parsed.success) {
|
||||
return;
|
||||
}
|
||||
|
||||
const frame = parsed.data;
|
||||
|
||||
if (frame.kind === "snapshot" && streamOpening) {
|
||||
lastAppliedSeq = frame.seq;
|
||||
} else if (frame.seq <= lastAppliedSeq) {
|
||||
return;
|
||||
} else {
|
||||
lastAppliedSeq = frame.seq;
|
||||
}
|
||||
|
||||
for (const listener of providerStreamListeners) {
|
||||
try {
|
||||
listener(frame);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const api: NativeApi = {
|
||||
todos: {
|
||||
list: async () => [],
|
||||
add: async () => [],
|
||||
toggle: async () => [],
|
||||
remove: async () => [],
|
||||
},
|
||||
dialogs: {
|
||||
pickFolder: async () => {
|
||||
if (!window.desktopBridge) return null;
|
||||
return window.desktopBridge.pickFolder();
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
run: async () => ({
|
||||
stdout: "",
|
||||
stderr: "Terminal not available in web mode",
|
||||
code: 1,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
}),
|
||||
},
|
||||
agent: {
|
||||
spawn: async () => "",
|
||||
kill: async () => {},
|
||||
write: async () => {},
|
||||
onOutput: () => () => {},
|
||||
onExit: () => () => {},
|
||||
},
|
||||
providers: {
|
||||
startSession: (input) => transport.request(WS_METHODS.providersStartSession, input),
|
||||
sendTurn: (input) => transport.request(WS_METHODS.providersSendTurn, input),
|
||||
interruptTurn: (input) => transport.request(WS_METHODS.providersInterruptTurn, input),
|
||||
respondToApproval: (input) =>
|
||||
transport.request(WS_METHODS.providersRespondToApproval, input),
|
||||
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
|
||||
listSessions: () => transport.request(WS_METHODS.providersListSessions),
|
||||
openStream: (input) => openStream(input),
|
||||
closeStream: async () => {
|
||||
pendingCloseAfterOpen = false;
|
||||
streamOpen = false;
|
||||
await transport.request(WS_METHODS.providersCloseStream);
|
||||
},
|
||||
onStream: (callback) => {
|
||||
providerStreamListeners.add(callback);
|
||||
pendingCloseAfterOpen = false;
|
||||
ensureStreamOpen();
|
||||
|
||||
return () => {
|
||||
providerStreamListeners.delete(callback);
|
||||
if (providerStreamListeners.size === 0) {
|
||||
if (streamOpenInFlight) {
|
||||
pendingCloseAfterOpen = true;
|
||||
return;
|
||||
}
|
||||
|
||||
streamOpen = false;
|
||||
pendingCloseAfterOpen = false;
|
||||
void transport.request(WS_METHODS.providersCloseStream).catch(() => {
|
||||
// Ignore close errors while transport reconnects.
|
||||
});
|
||||
}
|
||||
};
|
||||
},
|
||||
},
|
||||
projects: {
|
||||
list: () => transport.request(WS_METHODS.projectsList),
|
||||
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
|
||||
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (cwd, editor) =>
|
||||
transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
|
||||
},
|
||||
};
|
||||
|
||||
instance = { api, transport };
|
||||
return api;
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
import type { WsPush, WsRequest, WsResponse } from "@t3tools/contracts";
|
||||
|
||||
type PushListener = (data: unknown) => void;
|
||||
type ConnectionState = "open" | "closed";
|
||||
type ConnectionStateListener = (state: ConnectionState) => void;
|
||||
|
||||
interface PendingRequest {
|
||||
resolve: (result: unknown) => void;
|
||||
reject: (error: Error) => void;
|
||||
timeout: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 60_000;
|
||||
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
||||
|
||||
export class WsTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
private nextId = 1;
|
||||
private readonly pending = new Map<string, PendingRequest>();
|
||||
private readonly listeners = new Map<string, Set<PushListener>>();
|
||||
private reconnectAttempt = 0;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private disposed = false;
|
||||
private readonly url: string;
|
||||
private readonly connectionListeners = new Set<ConnectionStateListener>();
|
||||
|
||||
constructor(url?: string) {
|
||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
|
||||
// In production, the page is served by the WS server on the same host:port.
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
this.url =
|
||||
url ??
|
||||
(bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`);
|
||||
this.connect();
|
||||
}
|
||||
|
||||
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
|
||||
const id = String(this.nextId++);
|
||||
const message: WsRequest = { id, method, ...(params !== undefined ? { params } : {}) };
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Request timed out: ${method}`));
|
||||
}, REQUEST_TIMEOUT_MS);
|
||||
|
||||
this.pending.set(id, {
|
||||
resolve: resolve as (result: unknown) => void,
|
||||
reject,
|
||||
timeout,
|
||||
});
|
||||
|
||||
this.send(message);
|
||||
});
|
||||
}
|
||||
|
||||
subscribe(channel: string, listener: PushListener): () => void {
|
||||
let channelListeners = this.listeners.get(channel);
|
||||
if (!channelListeners) {
|
||||
channelListeners = new Set();
|
||||
this.listeners.set(channel, channelListeners);
|
||||
}
|
||||
channelListeners.add(listener);
|
||||
|
||||
return () => {
|
||||
channelListeners!.delete(listener);
|
||||
if (channelListeners!.size === 0) {
|
||||
this.listeners.delete(channel);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
onConnectionStateChange(listener: ConnectionStateListener): () => void {
|
||||
this.connectionListeners.add(listener);
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
listener("open");
|
||||
}
|
||||
|
||||
return () => {
|
||||
this.connectionListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.disposed = true;
|
||||
if (this.reconnectTimer !== null) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
for (const pending of this.pending.values()) {
|
||||
clearTimeout(pending.timeout);
|
||||
pending.reject(new Error("Transport disposed"));
|
||||
}
|
||||
this.pending.clear();
|
||||
this.ws?.close();
|
||||
this.ws = null;
|
||||
this.emitConnectionState("closed");
|
||||
}
|
||||
|
||||
private connect() {
|
||||
if (this.disposed) return;
|
||||
|
||||
const ws = new WebSocket(this.url);
|
||||
|
||||
ws.addEventListener("open", () => {
|
||||
this.ws = ws;
|
||||
this.reconnectAttempt = 0;
|
||||
this.emitConnectionState("open");
|
||||
});
|
||||
|
||||
ws.addEventListener("message", (event) => {
|
||||
this.handleMessage(event.data);
|
||||
});
|
||||
|
||||
ws.addEventListener("close", () => {
|
||||
this.ws = null;
|
||||
this.emitConnectionState("closed");
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
|
||||
ws.addEventListener("error", () => {
|
||||
// close event will fire after error
|
||||
});
|
||||
}
|
||||
|
||||
private handleMessage(raw: unknown) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(String(raw));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== "object") return;
|
||||
|
||||
const message = parsed as Record<string, unknown>;
|
||||
|
||||
// Push event
|
||||
if (message.type === "push") {
|
||||
const push = message as unknown as WsPush;
|
||||
const channelListeners = this.listeners.get(push.channel);
|
||||
if (channelListeners) {
|
||||
for (const listener of channelListeners) {
|
||||
try {
|
||||
listener(push.data);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Response to a request
|
||||
if (typeof message.id === "string") {
|
||||
const response = message as unknown as WsResponse;
|
||||
const pending = this.pending.get(response.id);
|
||||
if (!pending) return;
|
||||
|
||||
clearTimeout(pending.timeout);
|
||||
this.pending.delete(response.id);
|
||||
|
||||
if (response.error) {
|
||||
pending.reject(new Error(response.error.message));
|
||||
} else {
|
||||
pending.resolve(response.result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private send(message: WsRequest) {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
return;
|
||||
}
|
||||
|
||||
// If not connected, wait for connection
|
||||
const waitForOpen = () => {
|
||||
const check = setInterval(() => {
|
||||
if (this.disposed) {
|
||||
clearInterval(check);
|
||||
return;
|
||||
}
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
clearInterval(check);
|
||||
this.ws.send(JSON.stringify(message));
|
||||
}
|
||||
}, 50);
|
||||
|
||||
// Give up after timeout (the pending request will time out on its own)
|
||||
setTimeout(() => clearInterval(check), REQUEST_TIMEOUT_MS);
|
||||
};
|
||||
waitForOpen();
|
||||
}
|
||||
|
||||
private scheduleReconnect() {
|
||||
if (this.disposed) return;
|
||||
|
||||
const delay =
|
||||
RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ??
|
||||
RECONNECT_DELAYS_MS[0]!;
|
||||
|
||||
this.reconnectAttempt++;
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.connect();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private emitConnectionState(state: ConnectionState) {
|
||||
for (const listener of this.connectionListeners) {
|
||||
try {
|
||||
listener(state);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.9.0/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"correctness": {
|
||||
"noUnusedImports": "warn",
|
||||
"noUnusedVariables": "warn"
|
||||
}
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"indentStyle": "space",
|
||||
"indentWidth": 2
|
||||
},
|
||||
"files": {
|
||||
"ignore": [
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -5,56 +5,36 @@
|
||||
"": {
|
||||
"name": "ct-round-5",
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
"oxlint": "^1.43.0",
|
||||
"@biomejs/biome": "^1.9.0",
|
||||
"turbo": "^2.3.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.0",
|
||||
},
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"name": "@acme/desktop",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@acme/contracts": "workspace:*",
|
||||
"electron": "33.4.11",
|
||||
"node-pty": "^1.0.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron/rebuild": "^3.7.0",
|
||||
"@types/node": "^22.10.2",
|
||||
"concurrently": "^9.1.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsup": "^8.3.5",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.0",
|
||||
"wait-on": "^8.0.2",
|
||||
},
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.1.0",
|
||||
"bin": {
|
||||
"t3": "./dist/index.js",
|
||||
},
|
||||
"dependencies": {
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsup": "^8.3.5",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.7.3",
|
||||
},
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"apps/renderer": {
|
||||
"name": "@acme/renderer",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@acme/contracts": "workspace:*",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.563.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -74,7 +54,7 @@
|
||||
},
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"name": "@acme/contracts",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"zod": "^3.24.1",
|
||||
@@ -86,6 +66,12 @@
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@acme/contracts": ["@acme/contracts@workspace:packages/contracts"],
|
||||
|
||||
"@acme/desktop": ["@acme/desktop@workspace:apps/desktop"],
|
||||
|
||||
"@acme/renderer": ["@acme/renderer@workspace:apps/renderer"],
|
||||
|
||||
"@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=="],
|
||||
|
||||
"@babel/compat-data": ["@babel/[email protected]", "", {}, "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg=="],
|
||||
@@ -124,8 +110,30 @@
|
||||
|
||||
"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
|
||||
|
||||
"@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "1.9.4", "@biomejs/cli-darwin-x64": "1.9.4", "@biomejs/cli-linux-arm64": "1.9.4", "@biomejs/cli-linux-arm64-musl": "1.9.4", "@biomejs/cli-linux-x64": "1.9.4", "@biomejs/cli-linux-x64-musl": "1.9.4", "@biomejs/cli-win32-arm64": "1.9.4", "@biomejs/cli-win32-x64": "1.9.4" }, "bin": { "biome": "bin/biome" } }, "sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog=="],
|
||||
|
||||
"@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-bFBsPWrNvkdKrNCYeAp+xo2HecOGPAy9WyNyB/jKnnedgzl4W4Hb9ZMzYNbf8dMCGmUdSavlYHiR01QaYR58cw=="],
|
||||
|
||||
"@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-ngYBh/+bEedqkSevPVhLP4QfVPCpb+4BBe2p7Xs32dBgs7rh9nY2AIYUL6BgLw1JVXV8GlpKmb/hNiuIxfPfZg=="],
|
||||
|
||||
"@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-fJIW0+LYujdjUgJJuwesP4EjIBl/N/TcOX3IvIHJQNsAqvV2CHIogsmA94BPG6jZATS4Hi+xv4SkBBQSt1N4/g=="],
|
||||
|
||||
"@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-v665Ct9WCRjGa8+kTr0CzApU0+XXtRgwmzIf1SeKSGAv+2scAlW6JR5PMFo6FzqqZ64Po79cKODKf3/AAmECqA=="],
|
||||
|
||||
"@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-lRCJv/Vi3Vlwmbd6K+oQ0KhLHMAysN8lXoCI7XeHlxaajk06u7G+UsFSO01NAs5iYuWKmVZjmiOzJ0OJmGsMwg=="],
|
||||
|
||||
"@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-gEhi/jSBhZ2m6wjV530Yy8+fNqG8PAinM3oV7CyO+6c3CEh16Eizm21uHVsyVBEB6RIM8JHIl6AGYCv6Q6Q9Tg=="],
|
||||
|
||||
"@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-tlbhLk+WXZmgwoIKwHIHEBZUwxml7bRJgk0X2sPyNR3S93cdRq6XulAZRQJ17FYGGzWne0fgrXBKpl7l4M87Hg=="],
|
||||
|
||||
"@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-8Y5wMhVIPaWe6jw2H+KlEm4wP/f7EW3810ZLmDlrEEy5KvBsb9ECEfu/kMWD484ijfQ8+nIi0giMgu9g1UAuuA=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
"@electron/node-gyp": ["@electron/node-gyp@github:electron/node-gyp#06b29aa", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "glob": "^8.1.0", "graceful-fs": "^4.2.6", "make-fetch-happen": "^10.2.1", "nopt": "^6.0.0", "proc-log": "^2.0.1", "semver": "^7.3.5", "tar": "^6.2.1", "which": "^2.0.2" }, "bin": "./bin/node-gyp.js" }, "electron-node-gyp-06b29aa"],
|
||||
|
||||
"@electron/rebuild": ["@electron/[email protected]", "", { "dependencies": { "@electron/node-gyp": "git+https://github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2", "@malept/cross-spawn-promise": "^2.0.0", "chalk": "^4.0.0", "debug": "^4.1.1", "detect-libc": "^2.0.1", "fs-extra": "^10.0.0", "got": "^11.7.0", "node-abi": "^3.45.0", "node-api-version": "^0.2.0", "ora": "^5.1.0", "read-binary-file-arch": "^1.0.6", "semver": "^7.3.5", "tar": "^6.0.5", "yargs": "^17.0.1" }, "bin": { "electron-rebuild": "lib/cli.js" } }, "sha512-19/KbIR/DAxbsCkiaGMXIdPnMCJLkcf8AvGnduJtWBs/CBwiAjY1apCqOLVxrXg+rtXFCngbXhBanWjxLUt1Mg=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA=="],
|
||||
@@ -178,6 +186,8 @@
|
||||
|
||||
"@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="],
|
||||
|
||||
"@gar/promisify": ["@gar/[email protected]", "", {}, "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw=="],
|
||||
|
||||
"@hapi/address": ["@hapi/[email protected]", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA=="],
|
||||
|
||||
"@hapi/formula": ["@hapi/[email protected]", "", {}, "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw=="],
|
||||
@@ -200,37 +210,11 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@oxfmt/darwin-arm64": ["@oxfmt/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-jmUfF7cNJPw57bEK7sMIqrYRgn4LH428tSgtgLTCtjuGuu1ShREyrkeB7y8HtkXRfhBs4lVY+HMLhqElJvZ6ww=="],
|
||||
"@malept/cross-spawn-promise": ["@malept/[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.1" } }, "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg=="],
|
||||
|
||||
"@oxfmt/darwin-x64": ["@oxfmt/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-S6vlV8S7jbjzJOSjfVg2CimUC0r7/aHDLdUm/3+/B/SU/s1jV7ivqWkMv1/8EB43d1BBwT9JQ60ZMTkBqeXSFA=="],
|
||||
"@npmcli/fs": ["@npmcli/[email protected]", "", { "dependencies": { "@gar/promisify": "^1.1.3", "semver": "^7.3.5" } }, "sha512-yOJKRvohFOaLqipNtwYB9WugyZKhC/DZC4VYPmpaCzDBrA8YpK3qHZ8/HGscMnE4GqbkLNuVcCnxkeQEdGt6LQ=="],
|
||||
|
||||
"@oxfmt/linux-arm64-gnu": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-TfJkMZjePbLiskmxFXVAbGI/OZtD+y+fwS0wyW8O6DWG0ARTf0AipY9zGwGoOdpFuXOJceXvN4SHGLbYNDMY4Q=="],
|
||||
|
||||
"@oxfmt/linux-arm64-musl": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-7fyQUdW203v4WWGr1T3jwTz4L7KX9y5DeATryQ6fLT6QQp9GEuct8/k0lYhd+ys42iTV/IkJF20e3YkfSOOILg=="],
|
||||
|
||||
"@oxfmt/linux-x64-gnu": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-sRKqAvEonuz0qr1X1ncUZceOBJerKzkO2gZIZmosvy/JmqyffpIFL3OE2tqacFkeDhrC+dNYQpusO8zsfHo3pw=="],
|
||||
|
||||
"@oxfmt/linux-x64-musl": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-fW6czbXutX/tdQe8j4nSIgkUox9RXqjyxwyWXUDItpoDkoXllq17qbD7GVc0whrEhYQC6hFE1UEAcDypLJoSzw=="],
|
||||
|
||||
"@oxfmt/win32-arm64": ["@oxfmt/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-D/HDeQBAQRjTbD9OLV6kRDcStrIfO+JsUODDCdGmhRfNX8LPCx95GpfyybpZfn3wVF8Jq/yjPXV1xLkQ+s7RcA=="],
|
||||
|
||||
"@oxfmt/win32-x64": ["@oxfmt/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-4+S2j4OxOIyo8dz5osm5dZuL0yVmxXvtmNdHB5xyGwAWVvyWNvf7tCaQD7w2fdSsAXQLOvK7KFQrHFe33nJUCA=="],
|
||||
|
||||
"@oxlint/darwin-arm64": ["@oxlint/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-C/GhObv/pQZg34NOzB6Mk8x0wc9AKj8fXzJF8ZRKTsBPyHusC6AZ6bba0QG0TUufw1KWuD0j++oebQfWeiFXNw=="],
|
||||
|
||||
"@oxlint/darwin-x64": ["@oxlint/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-4NjfUtEEH8ewRQ2KlZGmm6DyrvypMdHwBnQT92vD0dLScNOQzr0V9O8Ua4IWXdeCNl/XMVhAV3h4/3YEYern5A=="],
|
||||
|
||||
"@oxlint/linux-arm64-gnu": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-75tf1HvwdZ3ebk83yMbSB+moAEWK98mYqpXiaFAi6Zshie7r+Cx5PLXZFUEqkscenoZ+fcNXakHxfn94V6nf1g=="],
|
||||
|
||||
"@oxlint/linux-arm64-musl": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-BHV4fb36T2p/7bpA9fiJ5ayt7oJbiYX10nklW5arYp4l9/9yG/FQC5J4G1evzbJ/YbipF9UH0vYBAm5xbqGrvw=="],
|
||||
|
||||
"@oxlint/linux-x64-gnu": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-1l3nvnzWWse1YHibzZ4HQXdF/ibfbKZhp9IguElni3bBqEyPEyurzZ0ikWynDxKGXqZa+UNXTFuU1NRVX1RJ3g=="],
|
||||
|
||||
"@oxlint/linux-x64-musl": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-+jNYgLGRFTJxJuaSOZJBwlYo5M0TWRw0+3y5MHOL4ArrIdHyCthg6r4RbVWrsR1qUfUE1VSSHQ2bfbC99RXqMg=="],
|
||||
|
||||
"@oxlint/win32-arm64": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-dvs1C/HCjCyGTURMagiHprsOvVTT3omDiSzi5Qw0D4QFJ1pEaNlfBhVnOUYgUfS6O7Mcmj4+G+sidRsQcWQ/kA=="],
|
||||
|
||||
"@oxlint/win32-x64": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-bSuItSU8mTSDsvmmLTepTdCL2FkJI6dwt9tot/k0EmiYF+ArRzmsl4lXVLssJNRV5lJEc5IViyTrh7oiwrjUqA=="],
|
||||
"@npmcli/move-file": ["@npmcli/[email protected]", "", { "dependencies": { "mkdirp": "^1.0.4", "rimraf": "^3.0.2" } }, "sha512-mJd2Z5TjYWq/ttPLLGqArdtnC74J6bOzg4rMDnN+p1xTacZ2yPRCk2y0oSWQtygLR9YVQXgOcONrwtnk3JupxQ=="],
|
||||
|
||||
"@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA=="],
|
||||
|
||||
@@ -290,12 +274,6 @@
|
||||
|
||||
"@szmarczak/http-timer": ["@szmarczak/[email protected]", "", { "dependencies": { "defer-to-connect": "^2.0.0" } }, "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w=="],
|
||||
|
||||
"@t3tools/contracts": ["@t3tools/contracts@workspace:packages/contracts"],
|
||||
|
||||
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
|
||||
|
||||
"@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=="],
|
||||
|
||||
"@tailwindcss/oxide": ["@tailwindcss/[email protected]", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.1.18", "@tailwindcss/oxide-darwin-arm64": "4.1.18", "@tailwindcss/oxide-darwin-x64": "4.1.18", "@tailwindcss/oxide-freebsd-x64": "4.1.18", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.1.18", "@tailwindcss/oxide-linux-arm64-gnu": "4.1.18", "@tailwindcss/oxide-linux-arm64-musl": "4.1.18", "@tailwindcss/oxide-linux-x64-gnu": "4.1.18", "@tailwindcss/oxide-linux-x64-musl": "4.1.18", "@tailwindcss/oxide-wasm32-wasi": "4.1.18", "@tailwindcss/oxide-win32-arm64-msvc": "4.1.18", "@tailwindcss/oxide-win32-x64-msvc": "4.1.18" } }, "sha512-EgCR5tTS5bUSKQgzeMClT6iCY3ToqE1y+ZB0AKldj809QXk1Y+3jB0upOYZrn9aGIzPtUsP7sX4QQ4XtjBB95A=="],
|
||||
@@ -326,6 +304,8 @@
|
||||
|
||||
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.1.18", "@tailwindcss/oxide": "4.1.18", "tailwindcss": "4.1.18" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7" } }, "sha512-jVA+/UpKL1vRLg6Hkao5jldawNmRo7mQYrZtNHMIVpLfLhDml5nMRUo/8MwoX2vNXvnaXNNMedrMfMugAVX1nA=="],
|
||||
|
||||
"@tootallnate/once": ["@tootallnate/[email protected]", "", {}, "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A=="],
|
||||
|
||||
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
|
||||
|
||||
"@types/babel__generator": ["@types/[email protected]", "", { "dependencies": { "@babel/types": "^7.0.0" } }, "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg=="],
|
||||
@@ -366,8 +346,6 @@
|
||||
|
||||
"@types/unist": ["@types/[email protected]", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
|
||||
|
||||
"@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
|
||||
|
||||
"@types/yauzl": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
|
||||
|
||||
"@ungap/structured-clone": ["@ungap/[email protected]", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="],
|
||||
@@ -388,8 +366,16 @@
|
||||
|
||||
"@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],
|
||||
|
||||
"abbrev": ["[email protected]", "", {}, "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q=="],
|
||||
|
||||
"acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="],
|
||||
|
||||
"agent-base": ["[email protected]", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="],
|
||||
|
||||
"agentkeepalive": ["[email protected]", "", { "dependencies": { "humanize-ms": "^1.2.1" } }, "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ=="],
|
||||
|
||||
"aggregate-error": ["[email protected]", "", { "dependencies": { "clean-stack": "^2.0.0", "indent-string": "^4.0.0" } }, "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA=="],
|
||||
|
||||
"ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
|
||||
|
||||
"ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
@@ -400,28 +386,38 @@
|
||||
|
||||
"asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],
|
||||
|
||||
"axios": ["[email protected].5", "", { "dependencies": { "follow-redirects": "^1.15.11", "form-data": "^4.0.5", "proxy-from-env": "^1.1.0" } }, "sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q=="],
|
||||
"axios": ["[email protected].4", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, "sha512-1wVkUaAO6WyaYtCkcYCOx12ZgpGf9Zif+qXa4n+oYzK558YryKqiL6UWwd5DqiH3VRW0GYhTZQ/vlgJrCoNQlg=="],
|
||||
|
||||
"babel-plugin-react-compiler": ["[email protected]", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-q84bNR9JG1crykAlJUt5Ud0/5BUyMFuQww/mrwIQDFBaxsikqBDj3f/FNDsVd2iR26A1HvXKWPEIfgJDv8/V2g=="],
|
||||
|
||||
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
"balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
|
||||
"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=="],
|
||||
|
||||
"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=="],
|
||||
|
||||
"brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="],
|
||||
|
||||
"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-crc32": ["buffer[email protected].13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
"buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
"buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"bundle-require": ["[email protected]", "", { "dependencies": { "load-tsconfig": "^0.2.3" }, "peerDependencies": { "esbuild": ">=0.18" } }, "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA=="],
|
||||
|
||||
"cac": ["[email protected]", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
|
||||
|
||||
"cacache": ["[email protected]", "", { "dependencies": { "@npmcli/fs": "^2.1.0", "@npmcli/move-file": "^2.0.0", "chownr": "^2.0.0", "fs-minipass": "^2.1.0", "glob": "^8.0.1", "infer-owner": "^1.0.4", "lru-cache": "^7.7.1", "minipass": "^3.1.6", "minipass-collect": "^1.0.2", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "mkdirp": "^1.0.4", "p-map": "^4.0.0", "promise-inflight": "^1.0.1", "rimraf": "^3.0.2", "ssri": "^9.0.0", "tar": "^6.1.11", "unique-filename": "^2.0.0" } }, "sha512-/+Emcj9DAXxX4cwlLmRI9c166RuL3w30zp4R7Joiv2cQTtTtA+jeuCAjH3ZlGnYS3tKENSrKhAzVVP9GVyzeYQ=="],
|
||||
|
||||
"cacheable-lookup": ["[email protected]", "", {}, "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA=="],
|
||||
|
||||
"cacheable-request": ["[email protected]", "", { "dependencies": { "clone-response": "^1.0.2", "get-stream": "^5.1.0", "http-cache-semantics": "^4.0.0", "keyv": "^4.0.0", "lowercase-keys": "^2.0.0", "normalize-url": "^6.0.1", "responselike": "^2.0.0" } }, "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg=="],
|
||||
@@ -448,8 +444,18 @@
|
||||
|
||||
"chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="],
|
||||
|
||||
"chownr": ["[email protected]", "", {}, "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ=="],
|
||||
|
||||
"clean-stack": ["[email protected]", "", {}, "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A=="],
|
||||
|
||||
"cli-cursor": ["[email protected]", "", { "dependencies": { "restore-cursor": "^3.1.0" } }, "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw=="],
|
||||
|
||||
"cli-spinners": ["[email protected]", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="],
|
||||
|
||||
"cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
|
||||
|
||||
"clone": ["[email protected]", "", {}, "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg=="],
|
||||
|
||||
"clone-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^1.0.0" } }, "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA=="],
|
||||
|
||||
"color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
|
||||
@@ -462,6 +468,8 @@
|
||||
|
||||
"commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],
|
||||
|
||||
"concat-map": ["[email protected]", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
|
||||
|
||||
"concurrently": ["[email protected]", "", { "dependencies": { "chalk": "4.1.2", "rxjs": "7.8.2", "shell-quote": "1.8.3", "supports-color": "8.1.1", "tree-kill": "1.2.2", "yargs": "17.7.2" }, "bin": { "conc": "dist/bin/concurrently.js", "concurrently": "dist/bin/concurrently.js" } }, "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng=="],
|
||||
|
||||
"confbox": ["[email protected]", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="],
|
||||
@@ -470,6 +478,8 @@
|
||||
|
||||
"convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
|
||||
|
||||
"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
|
||||
|
||||
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
@@ -480,16 +490,12 @@
|
||||
|
||||
"deep-eql": ["[email protected]", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="],
|
||||
|
||||
"default-browser": ["default[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=="],
|
||||
"defaults": ["default[email protected]", "", { "dependencies": { "clone": "^1.0.2" } }, "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A=="],
|
||||
|
||||
"defer-to-connect": ["[email protected]", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="],
|
||||
|
||||
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
|
||||
|
||||
"define-lazy-prop": ["[email protected]", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="],
|
||||
|
||||
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
|
||||
|
||||
"delayed-stream": ["[email protected]", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="],
|
||||
@@ -512,12 +518,16 @@
|
||||
|
||||
"emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
"encoding": ["[email protected]", "", { "dependencies": { "iconv-lite": "^0.6.2" } }, "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A=="],
|
||||
|
||||
"end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
|
||||
|
||||
"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.0" } }, "sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg=="],
|
||||
|
||||
"env-paths": ["[email protected]", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
|
||||
|
||||
"err-code": ["[email protected]", "", {}, "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA=="],
|
||||
|
||||
"es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
|
||||
|
||||
"es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
|
||||
@@ -542,6 +552,8 @@
|
||||
|
||||
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
|
||||
|
||||
"exponential-backoff": ["[email protected]", "", {}, "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA=="],
|
||||
|
||||
"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=="],
|
||||
@@ -558,7 +570,11 @@
|
||||
|
||||
"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-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
"fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="],
|
||||
|
||||
"fs-minipass": ["[email protected]", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg=="],
|
||||
|
||||
"fs.realpath": ["[email protected]", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="],
|
||||
|
||||
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
@@ -574,7 +590,7 @@
|
||||
|
||||
"get-stream": ["[email protected]", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
|
||||
|
||||
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
|
||||
"glob": ["[email protected]", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^5.0.1", "once": "^1.3.0" } }, "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ=="],
|
||||
|
||||
"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=="],
|
||||
|
||||
@@ -610,31 +626,55 @@
|
||||
|
||||
"http-cache-semantics": ["[email protected]", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="],
|
||||
|
||||
"http-proxy-agent": ["[email protected]", "", { "dependencies": { "@tootallnate/once": "2", "agent-base": "6", "debug": "4" } }, "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w=="],
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
|
||||
"https-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="],
|
||||
|
||||
"humanize-ms": ["[email protected]", "", { "dependencies": { "ms": "^2.0.0" } }, "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ=="],
|
||||
|
||||
"iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
|
||||
|
||||
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
|
||||
|
||||
"import-from": ["[email protected]", "", { "dependencies": { "resolve-from": "^5.0.0" } }, "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ=="],
|
||||
|
||||
"imurmurhash": ["[email protected]", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="],
|
||||
|
||||
"indent-string": ["[email protected]", "", {}, "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg=="],
|
||||
|
||||
"infer-owner": ["[email protected]", "", {}, "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A=="],
|
||||
|
||||
"inflight": ["[email protected]", "", { "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA=="],
|
||||
|
||||
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
|
||||
|
||||
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
|
||||
|
||||
"ip-address": ["[email protected]", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
|
||||
|
||||
"is-alphabetical": ["[email protected]", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
|
||||
|
||||
"is-alphanumerical": ["[email protected]", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="],
|
||||
|
||||
"is-decimal": ["[email protected]", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="],
|
||||
|
||||
"is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="],
|
||||
|
||||
"is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
|
||||
|
||||
"is-hexadecimal": ["[email protected]", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="],
|
||||
|
||||
"is-inside-container": ["[email protected]", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="],
|
||||
"is-interactive": ["[email protected]", "", {}, "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w=="],
|
||||
|
||||
"is-lambda": ["[email protected]", "", {}, "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ=="],
|
||||
|
||||
"is-number": ["[email protected]", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
|
||||
|
||||
"is-plain-obj": ["[email protected]", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
|
||||
|
||||
"is-wsl": ["[email protected]", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw=="],
|
||||
"is-unicode-supported": ["is-[email protected]", "", {}, "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw=="],
|
||||
|
||||
"isexe": ["[email protected]", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
|
||||
|
||||
"jiti": ["[email protected]", "", { "bin": { "jiti": "bin/jiti.js" } }, "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A=="],
|
||||
|
||||
@@ -652,7 +692,7 @@
|
||||
|
||||
"json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
|
||||
|
||||
"jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
|
||||
"jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="],
|
||||
|
||||
"keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
|
||||
|
||||
@@ -690,6 +730,8 @@
|
||||
|
||||
"lodash.difference": ["[email protected]", "", {}, "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA=="],
|
||||
|
||||
"log-symbols": ["[email protected]", "", { "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" } }, "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg=="],
|
||||
|
||||
"longest-streak": ["[email protected]", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],
|
||||
|
||||
"loupe": ["[email protected]", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="],
|
||||
@@ -698,12 +740,12 @@
|
||||
|
||||
"lowlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.0.0", "highlight.js": "~11.11.0" } }, "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ=="],
|
||||
|
||||
"lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-8dXPB2GI4dI8jV4MgUDGBeLdGk8ekfqVZ0BdLcrRzocGgG75ltNEmWS+gE7uokKF/0oSUuczNDT+g9hFJ23FkA=="],
|
||||
"lru-cache": ["lru-cache@7.18.3", "", {}, "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA=="],
|
||||
|
||||
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
|
||||
"make-fetch-happen": ["[email protected]", "", { "dependencies": { "agentkeepalive": "^4.2.1", "cacache": "^16.1.0", "http-cache-semantics": "^4.1.0", "http-proxy-agent": "^5.0.0", "https-proxy-agent": "^5.0.0", "is-lambda": "^1.0.1", "lru-cache": "^7.7.1", "minipass": "^3.1.6", "minipass-collect": "^1.0.2", "minipass-fetch": "^2.0.3", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^0.6.3", "promise-retry": "^2.0.1", "socks-proxy-agent": "^7.0.0", "ssri": "^9.0.0" } }, "sha512-NgOPbRiaQM10DYXvN3/hhGVI2M5MtITFryzBGxHM5p4wnFxsVCbxkrBrDsk+EZ5OB4jEOT7AjDxtdF+KVEFT7w=="],
|
||||
|
||||
"markdown-table": ["[email protected]", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="],
|
||||
|
||||
"matcher": ["[email protected]", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="],
|
||||
@@ -802,10 +844,30 @@
|
||||
|
||||
"mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
|
||||
|
||||
"mimic-fn": ["[email protected]", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="],
|
||||
|
||||
"mimic-response": ["[email protected]", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="],
|
||||
|
||||
"minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g=="],
|
||||
|
||||
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
|
||||
|
||||
"minipass": ["[email protected]", "", {}, "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ=="],
|
||||
|
||||
"minipass-collect": ["[email protected]", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA=="],
|
||||
|
||||
"minipass-fetch": ["[email protected]", "", { "dependencies": { "minipass": "^3.1.6", "minipass-sized": "^1.0.3", "minizlib": "^2.1.2" }, "optionalDependencies": { "encoding": "^0.1.13" } }, "sha512-LT49Zi2/WMROHYoqGgdlQIZh8mLPZmOrN2NdJjMXxYe4nkN6FUyuPuOAOedNJDrx0IRGg9+4guZewtp8hE6TxA=="],
|
||||
|
||||
"minipass-flush": ["[email protected]", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw=="],
|
||||
|
||||
"minipass-pipeline": ["[email protected]", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A=="],
|
||||
|
||||
"minipass-sized": ["[email protected]", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g=="],
|
||||
|
||||
"minizlib": ["[email protected]", "", { "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" } }, "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg=="],
|
||||
|
||||
"mkdirp": ["[email protected]", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="],
|
||||
|
||||
"mlly": ["[email protected]", "", { "dependencies": { "acorn": "^8.15.0", "pathe": "^2.0.3", "pkg-types": "^1.3.1", "ufo": "^1.6.1" } }, "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g=="],
|
||||
|
||||
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
@@ -814,8 +876,20 @@
|
||||
|
||||
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
|
||||
"negotiator": ["[email protected]", "", {}, "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w=="],
|
||||
|
||||
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
|
||||
|
||||
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
|
||||
|
||||
"node-api-version": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q=="],
|
||||
|
||||
"node-pty": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
|
||||
|
||||
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
|
||||
|
||||
"nopt": ["[email protected]", "", { "dependencies": { "abbrev": "^1.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-ZwLpbTgdhuZUnZzjd7nb1ZV+4DoiC6/sfiVKok72ym/4Tlf+DFdlHYmT2JPmcNNWV6Pi3SDf1kT+A4r9RTuT9g=="],
|
||||
|
||||
"normalize-path": ["[email protected]", "", { "dependencies": { "remove-trailing-separator": "^1.0.1" } }, "sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w=="],
|
||||
|
||||
"normalize-url": ["[email protected]", "", {}, "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A=="],
|
||||
@@ -826,16 +900,20 @@
|
||||
|
||||
"once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||
|
||||
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
||||
"onetime": ["[email protected]", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],
|
||||
|
||||
"oxfmt": ["o[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/darwin-arm64": "0.28.0", "@oxfmt/darwin-x64": "0.28.0", "@oxfmt/linux-arm64-gnu": "0.28.0", "@oxfmt/linux-arm64-musl": "0.28.0", "@oxfmt/linux-x64-gnu": "0.28.0", "@oxfmt/linux-x64-musl": "0.28.0", "@oxfmt/win32-arm64": "0.28.0", "@oxfmt/win32-x64": "0.28.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-3+hhBqPE6Kp22KfJmnstrZbl+KdOVSEu1V0ABaFIg1rYLtrMgrupx9znnHgHLqKxAVHebjTdiCJDk30CXOt6cw=="],
|
||||
|
||||
"oxlint": ["[email protected]", "", { "optionalDependencies": { "@oxlint/darwin-arm64": "1.43.0", "@oxlint/darwin-x64": "1.43.0", "@oxlint/linux-arm64-gnu": "1.43.0", "@oxlint/linux-arm64-musl": "1.43.0", "@oxlint/linux-x64-gnu": "1.43.0", "@oxlint/linux-x64-musl": "1.43.0", "@oxlint/win32-arm64": "1.43.0", "@oxlint/win32-x64": "1.43.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.11.2" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-xiqTCsKZch+R61DPCjyqUVP2MhkQlRRYxLRBeBDi+dtQJ90MOgdcjIktvDCgXz0bgtx94EQzHEndsizZjMX2OA=="],
|
||||
"ora": ["o[email protected]", "", { "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", "cli-cursor": "^3.1.0", "cli-spinners": "^2.5.0", "is-interactive": "^1.0.0", "is-unicode-supported": "^0.1.0", "log-symbols": "^4.1.0", "strip-ansi": "^6.0.0", "wcwidth": "^1.0.1" } }, "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ=="],
|
||||
|
||||
"p-cancelable": ["[email protected]", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="],
|
||||
|
||||
"p-map": ["[email protected]", "", { "dependencies": { "aggregate-error": "^3.0.0" } }, "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ=="],
|
||||
|
||||
"parse-entities": ["[email protected]", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
|
||||
|
||||
"path-is-absolute": ["[email protected]", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="],
|
||||
|
||||
"path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
|
||||
|
||||
"pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
|
||||
|
||||
"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
|
||||
@@ -856,8 +934,14 @@
|
||||
|
||||
"postcss-load-config": ["[email protected]", "", { "dependencies": { "lilconfig": "^3.1.1" }, "peerDependencies": { "jiti": ">=1.21.0", "postcss": ">=8.0.9", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["jiti", "postcss", "tsx", "yaml"] }, "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g=="],
|
||||
|
||||
"proc-log": ["[email protected]", "", {}, "sha512-Kcmo2FhfDTXdcbfDH76N7uBYHINxc/8GW7UAVuVP9I+Va3uHSerrnKV6dLooga/gh7GlgzuCCr/eoldnL1muGw=="],
|
||||
|
||||
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
|
||||
|
||||
"promise-inflight": ["[email protected]", "", {}, "sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g=="],
|
||||
|
||||
"promise-retry": ["[email protected]", "", { "dependencies": { "err-code": "^2.0.2", "retry": "^0.12.0" } }, "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g=="],
|
||||
|
||||
"property-information": ["[email protected]", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
|
||||
|
||||
"proxy-from-env": ["[email protected]", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="],
|
||||
@@ -874,6 +958,10 @@
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ=="],
|
||||
|
||||
"read-binary-file-arch": ["[email protected]", "", { "dependencies": { "debug": "^4.3.4" }, "bin": { "read-binary-file-arch": "cli.js" } }, "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg=="],
|
||||
|
||||
"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]", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="],
|
||||
|
||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||
@@ -894,32 +982,50 @@
|
||||
|
||||
"resolve-from": ["[email protected]", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="],
|
||||
|
||||
"resolve-pkg-maps": ["[email protected]", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
|
||||
|
||||
"responselike": ["[email protected]", "", { "dependencies": { "lowercase-keys": "^2.0.0" } }, "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw=="],
|
||||
|
||||
"restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA=="],
|
||||
|
||||
"retry": ["[email protected]", "", {}, "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow=="],
|
||||
|
||||
"rimraf": ["[email protected]", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="],
|
||||
|
||||
"roarr": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "detect-node": "^2.0.4", "globalthis": "^1.0.1", "json-stringify-safe": "^5.0.1", "semver-compare": "^1.0.0", "sprintf-js": "^1.1.2" } }, "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A=="],
|
||||
|
||||
"rollup": ["[email protected]", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.57.1", "@rollup/rollup-android-arm64": "4.57.1", "@rollup/rollup-darwin-arm64": "4.57.1", "@rollup/rollup-darwin-x64": "4.57.1", "@rollup/rollup-freebsd-arm64": "4.57.1", "@rollup/rollup-freebsd-x64": "4.57.1", "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", "@rollup/rollup-linux-arm-musleabihf": "4.57.1", "@rollup/rollup-linux-arm64-gnu": "4.57.1", "@rollup/rollup-linux-arm64-musl": "4.57.1", "@rollup/rollup-linux-loong64-gnu": "4.57.1", "@rollup/rollup-linux-loong64-musl": "4.57.1", "@rollup/rollup-linux-ppc64-gnu": "4.57.1", "@rollup/rollup-linux-ppc64-musl": "4.57.1", "@rollup/rollup-linux-riscv64-gnu": "4.57.1", "@rollup/rollup-linux-riscv64-musl": "4.57.1", "@rollup/rollup-linux-s390x-gnu": "4.57.1", "@rollup/rollup-linux-x64-gnu": "4.57.1", "@rollup/rollup-linux-x64-musl": "4.57.1", "@rollup/rollup-openbsd-x64": "4.57.1", "@rollup/rollup-openharmony-arm64": "4.57.1", "@rollup/rollup-win32-arm64-msvc": "4.57.1", "@rollup/rollup-win32-ia32-msvc": "4.57.1", "@rollup/rollup-win32-x64-gnu": "4.57.1", "@rollup/rollup-win32-x64-msvc": "4.57.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A=="],
|
||||
|
||||
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
|
||||
|
||||
"runtime-required": ["[email protected]", "", {}, "sha512-yX97f5E0WfNpcQnfVjap6vzQcvErkYYCx6eTK4siqGEdC8lglwypUFgZVTX7ShvIlgfkC4XGFl9O1KTYcff0pw=="],
|
||||
|
||||
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
|
||||
|
||||
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
|
||||
|
||||
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
|
||||
"semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
"semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||
|
||||
"semver-compare": ["[email protected]", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="],
|
||||
|
||||
"serialize-error": ["[email protected]", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
|
||||
|
||||
"shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
"shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
"shell-quote": ["[email protected]", "", {}, "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw=="],
|
||||
|
||||
"siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
|
||||
|
||||
"smart-buffer": ["[email protected]", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="],
|
||||
|
||||
"socks": ["[email protected]", "", { "dependencies": { "ip-address": "^10.0.1", "smart-buffer": "^4.2.0" } }, "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A=="],
|
||||
|
||||
"socks-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^6.0.2", "debug": "^4.3.3", "socks": "^2.6.2" } }, "sha512-Fgl0YPZ902wEsAyiQ+idGd1A7rSFx/ayC1CQVMw5P+EQx2V0SgpGtf6OKFhVjPflPUl9YMmEOnmfjCdMUsygww=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -928,12 +1034,16 @@
|
||||
|
||||
"sprintf-js": ["[email protected]", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
|
||||
|
||||
"ssri": ["[email protected]", "", { "dependencies": { "minipass": "^3.1.1" } }, "sha512-o57Wcn66jMQvfHG1FlYbWeZWW/dHZhJXjpIcTfXldXEk5nz5lStPo3mK0OJQfGR3RbZUlbISexbljkJzuEj/8Q=="],
|
||||
|
||||
"stackback": ["[email protected]", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
|
||||
|
||||
"std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
|
||||
|
||||
"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=="],
|
||||
@@ -950,12 +1060,12 @@
|
||||
|
||||
"supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],
|
||||
|
||||
"t3": ["t3@workspace:apps/server"],
|
||||
|
||||
"tailwindcss": ["[email protected]", "", {}, "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw=="],
|
||||
|
||||
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
|
||||
|
||||
"tar": ["[email protected]", "", { "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" } }, "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A=="],
|
||||
|
||||
"thenify": ["[email protected]", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="],
|
||||
|
||||
"thenify-all": ["[email protected]", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="],
|
||||
@@ -966,7 +1076,7 @@
|
||||
|
||||
"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
|
||||
|
||||
"tinypool": ["tinypool@2.1.0", "", {}, "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw=="],
|
||||
"tinypool": ["tinypool@1.1.1", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="],
|
||||
|
||||
"tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],
|
||||
|
||||
@@ -986,8 +1096,6 @@
|
||||
|
||||
"tsup": ["[email protected]", "", { "dependencies": { "bundle-require": "^5.1.0", "cac": "^6.7.14", "chokidar": "^4.0.3", "consola": "^3.4.0", "debug": "^4.4.0", "esbuild": "^0.27.0", "fix-dts-default-cjs-exports": "^1.0.0", "joycon": "^3.1.1", "picocolors": "^1.1.1", "postcss-load-config": "^6.0.1", "resolve-from": "^5.0.0", "rollup": "^4.34.8", "source-map": "^0.7.6", "sucrase": "^3.35.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.11", "tree-kill": "^1.2.2" }, "peerDependencies": { "@microsoft/api-extractor": "^7.36.0", "@swc/core": "^1", "postcss": "^8.4.12", "typescript": ">=4.5.0" }, "optionalPeers": ["@microsoft/api-extractor", "@swc/core", "postcss", "typescript"], "bin": { "tsup": "dist/cli-default.js", "tsup-node": "dist/cli-node.js" } }, "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing=="],
|
||||
|
||||
"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=="],
|
||||
|
||||
"turbo": ["[email protected]", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.3", "turbo-darwin-arm64": "2.8.3", "turbo-linux-64": "2.8.3", "turbo-linux-arm64": "2.8.3", "turbo-windows-64": "2.8.3", "turbo-windows-arm64": "2.8.3" }, "bin": { "turbo": "bin/turbo" } }, "sha512-8Osxz5Tu/Dw2kb31EAY+nhq/YZ3wzmQSmYa1nIArqxgCAldxv9TPlrAiaBUDVnKA4aiPn0OFBD1ACcpc5VFOAQ=="],
|
||||
|
||||
"turbo-darwin-64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-4kXRLfcygLOeNcP6JquqRLmGB/ATjjfehiojL2dJkL7GFm3SPSXbq7oNj8UbD8XriYQ5hPaSuz59iF1ijPHkTw=="],
|
||||
@@ -1012,6 +1120,10 @@
|
||||
|
||||
"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=="],
|
||||
|
||||
"unique-filename": ["[email protected]", "", { "dependencies": { "unique-slug": "^3.0.0" } }, "sha512-ODWHtkkdx3IAR+veKxFV+VBkUMcN+FaqzUUd7IZzt+0zhDZFPFxhlqwPF3YQvMHx1TD0tdgYl+kuPnJ8E6ql7A=="],
|
||||
|
||||
"unique-slug": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4" } }, "sha512-8EyMynh679x/0gqE9fT9oilG+qEt+ibFyqjuVTsZn1+CMxH+XLlpvr2UZx4nVcCwTpx81nICr2JQFkM+HPLq4w=="],
|
||||
|
||||
"unist-util-find-after": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ=="],
|
||||
|
||||
"unist-util-is": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
|
||||
@@ -1024,12 +1136,14 @@
|
||||
|
||||
"unist-util-visit-parents": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
|
||||
|
||||
"universalify": ["[email protected].2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
|
||||
"universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
|
||||
|
||||
"unixify": ["[email protected]", "", { "dependencies": { "normalize-path": "^2.1.1" } }, "sha512-6bc58dPYhCMHHuwxldQxO3RRNZ4eCogZ/st++0+fcC1nr0jiGUtAdBJ2qzmLQWSxbtz42pWt4QQMiZ9HvZf5cg=="],
|
||||
|
||||
"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
|
||||
|
||||
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"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=="],
|
||||
@@ -1044,19 +1158,19 @@
|
||||
|
||||
"watchboy": ["[email protected]", "", { "dependencies": { "lodash.difference": "^4.5.0", "micromatch": "^4.0.2", "pify": "^4.0.1", "unixify": "^1.0.0" } }, "sha512-GHs1HxwvxSMBsqd/WfTOZhj5gBdMqf5HQpfgtKxDfZRxrlYPDdVLRB61LCeRzJaWANmvSIMlfmRVDwVmJFgAKA=="],
|
||||
|
||||
"wcwidth": ["[email protected]", "", { "dependencies": { "defaults": "^1.0.3" } }, "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg=="],
|
||||
|
||||
"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"why-is-node-running": ["[email protected]", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
|
||||
|
||||
"wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
|
||||
|
||||
"wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
|
||||
|
||||
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
|
||||
|
||||
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
|
||||
|
||||
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
|
||||
|
||||
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
|
||||
"yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
|
||||
|
||||
"yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
|
||||
|
||||
@@ -1070,6 +1184,16 @@
|
||||
|
||||
"@babel/code-frame/js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
||||
|
||||
"@babel/core/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@babel/helper-compilation-targets/lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"@babel/helper-compilation-targets/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@electron/get/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@tailwindcss/node/jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
|
||||
|
||||
"@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=="],
|
||||
@@ -1084,6 +1208,8 @@
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||
|
||||
"cacache/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
|
||||
|
||||
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
|
||||
@@ -1092,20 +1218,44 @@
|
||||
|
||||
"electronmon/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg=="],
|
||||
|
||||
"global-agent/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
|
||||
"fs-minipass/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"make-fetch-happen/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
|
||||
|
||||
"micromatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"minipass-collect/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"minipass-fetch/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"minipass-flush/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"minipass-pipeline/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"minipass-sized/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"minizlib/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
|
||||
|
||||
"rimraf/glob": ["[email protected]", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
|
||||
|
||||
"ssri/minipass": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
|
||||
|
||||
"vite/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
|
||||
|
||||
"vitest/tinypool": ["[email protected]", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="],
|
||||
"@babel/helper-compilation-targets/lru-cache/yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
|
||||
|
||||
"@electron/get/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
|
||||
|
||||
"@electron/get/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
|
||||
|
||||
"electronmon/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
|
||||
|
||||
"rimraf/glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw=="],
|
||||
|
||||
"vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="],
|
||||
|
||||
"vite/esbuild/@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="],
|
||||
@@ -1157,5 +1307,7 @@
|
||||
"vite/esbuild/@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ=="],
|
||||
|
||||
"vite/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],
|
||||
|
||||
"rimraf/glob/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg=="],
|
||||
}
|
||||
}
|
||||
@@ -1,322 +0,0 @@
|
||||
# Unified Provider WebSocket API
|
||||
|
||||
This document is the canonical spec for the provider WebSocket API in T3 Code.
|
||||
|
||||
## Status
|
||||
|
||||
- `providers.stream` is the only provider push channel.
|
||||
- Stream model is `snapshot + delta` with cursor replay (`afterSeq`).
|
||||
- Server normalizes provider-native events (currently Codex app-server raw events) into canonical UI events.
|
||||
- Debug/raw provider events are opt-in.
|
||||
|
||||
## Source-of-Truth Files
|
||||
|
||||
These files define behavior and must stay in sync with this document:
|
||||
|
||||
- Contracts:
|
||||
- `packages/contracts/src/providerStream.ts`
|
||||
- `packages/contracts/src/ws.ts`
|
||||
- `packages/contracts/src/ipc.ts`
|
||||
- `packages/contracts/src/provider.ts`
|
||||
- Server:
|
||||
- `apps/server/src/providerEventNormalizer.ts`
|
||||
- `apps/server/src/providerStreamStore.ts`
|
||||
- `apps/server/src/providerStreamSubscriptionManager.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- Web client:
|
||||
- `apps/web/src/wsNativeApi.ts`
|
||||
- `apps/web/src/store.ts`
|
||||
- `apps/web/src/session-logic.ts`
|
||||
|
||||
## Synchronization Policy (Required)
|
||||
|
||||
Any change to provider WS contracts or behavior must update this doc in the same PR.
|
||||
|
||||
Changes that require doc updates include:
|
||||
|
||||
- New/removed/renamed provider RPC methods.
|
||||
- New/removed channels or frame shapes.
|
||||
- Changes to canonical event union or snapshot state fields.
|
||||
- Normalization mapping changes.
|
||||
- Replay retention or backpressure threshold changes.
|
||||
- Client apply/dedupe/resync behavior changes.
|
||||
|
||||
If code and docs diverge, treat it as a bug.
|
||||
|
||||
## Wire Surface
|
||||
|
||||
### Request Methods
|
||||
|
||||
- `providers.startSession`
|
||||
- `providers.sendTurn`
|
||||
- `providers.interruptTurn`
|
||||
- `providers.respondToApproval`
|
||||
- `providers.stopSession`
|
||||
- `providers.listSessions`
|
||||
- `providers.openStream`
|
||||
- `providers.closeStream`
|
||||
|
||||
### Push Channels
|
||||
|
||||
- `providers.stream`
|
||||
- `server.welcome` (non-provider channel)
|
||||
|
||||
`providers.event` is removed.
|
||||
|
||||
## Stream Contracts
|
||||
|
||||
### `providers.openStream` Input
|
||||
|
||||
```ts
|
||||
type ProvidersOpenStreamInput = {
|
||||
afterSeq?: number;
|
||||
sessionIds?: string[];
|
||||
eventKinds?: Array<
|
||||
| "session"
|
||||
| "turn"
|
||||
| "message"
|
||||
| "approval"
|
||||
| "activity"
|
||||
| "error"
|
||||
| "debug.raw"
|
||||
>;
|
||||
includeExtensions?: string[];
|
||||
includeDebugRaw?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
Defaults:
|
||||
|
||||
- `afterSeq`: not set
|
||||
- `sessionIds`: all sessions
|
||||
- `eventKinds`: all kinds
|
||||
- `includeExtensions`: none
|
||||
- `includeDebugRaw`: `false`
|
||||
|
||||
### `providers.openStream` Result
|
||||
|
||||
```ts
|
||||
type ProvidersOpenStreamResult = {
|
||||
mode: "snapshot" | "replay" | "snapshot_resync";
|
||||
currentSeq: number;
|
||||
oldestSeq: number;
|
||||
replayedCount: number;
|
||||
};
|
||||
```
|
||||
|
||||
### `providers.stream` Frames
|
||||
|
||||
```ts
|
||||
type ProviderStreamFrame =
|
||||
| { kind: "snapshot"; seq: number; at: string; data: ProviderSnapshot }
|
||||
| { kind: "event"; seq: number; at: string; data: ProviderCoreEvent }
|
||||
| {
|
||||
kind: "gap";
|
||||
seq: number;
|
||||
at: string;
|
||||
data: {
|
||||
reason: "cursor_too_old" | "cursor_ahead" | "replay_limit_exceeded";
|
||||
oldestSeq: number;
|
||||
currentSeq: number;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
## Canonical Snapshot
|
||||
|
||||
```ts
|
||||
type ProviderSnapshot = {
|
||||
sessions: CanonicalSessionState[];
|
||||
activeTurns: CanonicalTurnState[];
|
||||
activeMessages: CanonicalMessageState[];
|
||||
pendingApprovals: CanonicalApprovalState[];
|
||||
};
|
||||
```
|
||||
|
||||
## Canonical Events
|
||||
|
||||
`ProviderCoreEvent` variants:
|
||||
|
||||
- `session.updated`
|
||||
- `turn.started`
|
||||
- `turn.completed`
|
||||
- `message.delta`
|
||||
- `message.completed`
|
||||
- `approval.requested`
|
||||
- `approval.resolved`
|
||||
- `activity`
|
||||
- `error`
|
||||
- `debug.raw`
|
||||
|
||||
### Event Invariants
|
||||
|
||||
- Stream ordering is by increasing `seq`.
|
||||
- `snapshot` is authoritative baseline state.
|
||||
- `message.delta` and `message.completed` are assistant-only.
|
||||
- `approval.resolved.decision` is snake_case:
|
||||
- `accept`
|
||||
- `accept_for_session`
|
||||
- `decline`
|
||||
- `cancel`
|
||||
- `timed_out`
|
||||
- `debug.raw` is never required for primary UI behavior.
|
||||
|
||||
## Server Pipeline
|
||||
|
||||
### Flow
|
||||
|
||||
1. `CodexAppServerManager` emits `ProviderRawEvent`.
|
||||
2. `ProviderEventNormalizer` maps raw -> canonical allowlist events.
|
||||
3. `ProviderStreamStore` assigns global `seq`, applies snapshot state, stores replay log.
|
||||
4. `ProviderStreamSubscriptionManager` filters and pushes frames per socket.
|
||||
5. `wsServer` exposes open/close RPC methods and broadcasts stream frames.
|
||||
|
||||
### Unmapped Raw Methods
|
||||
|
||||
- Unmapped methods produce no core canonical event.
|
||||
- For unmapped methods, server emits `debug.raw` into the canonical stream pipeline.
|
||||
- Subscribers only receive `debug.raw` if `includeDebugRaw=true` and filters allow it.
|
||||
|
||||
## Codex Normalization Map
|
||||
|
||||
Implemented in `apps/server/src/providerEventNormalizer.ts`.
|
||||
|
||||
- `thread/started` -> `session.updated`
|
||||
- `turn/started` -> `turn.started` + `session.updated(status=running)`
|
||||
- `turn/completed` -> `turn.completed` + `session.updated(status=ready|error)`
|
||||
- `item/agentMessage/delta` -> `message.delta`
|
||||
- `item/completed` with `item.type=agentMessage` -> `message.completed`
|
||||
- `item/commandExecution/requestApproval` -> `approval.requested(approvalKind=command)`
|
||||
- `item/fileChange/requestApproval` -> `approval.requested(approvalKind=file_change)`
|
||||
- `item/tool/requestUserInput` -> `approval.requested(approvalKind=user_input)`
|
||||
- `item/requestApproval/decision` -> `approval.resolved`
|
||||
- actionable `item/started` / `item/completed` -> `activity`
|
||||
- `turn/plan/updated` -> `activity(activityKind=plan)` + `extensions["codex.turn.plan"]`
|
||||
- provider/runtime/protocol/process error signals -> `error`
|
||||
|
||||
Notes:
|
||||
|
||||
- `requestKind` raw values can be legacy (`file-change`) and are normalized at canonical layer (`file_change`).
|
||||
- User-input requests are auto-answered in Codex manager and represented canonically as approval request/resolution semantics.
|
||||
|
||||
## Replay and Cursor Semantics
|
||||
|
||||
Implemented in `apps/server/src/providerStreamStore.ts` and `apps/server/src/providerStreamSubscriptionManager.ts`.
|
||||
|
||||
### Sequence Rules
|
||||
|
||||
- `seq` is global, process-local, monotonic.
|
||||
- First emitted event has `seq=1`.
|
||||
- `currentSeq=0` before first event.
|
||||
|
||||
### Retention Limits
|
||||
|
||||
- Max replay events: `20_000`
|
||||
- Max replay bytes: `64MB`
|
||||
- Max replay age: `60m`
|
||||
- Max replay delivery per `openStream`: `10_000`
|
||||
|
||||
### Cursor Validation
|
||||
|
||||
Given `afterSeq`:
|
||||
|
||||
- `afterSeq > currentSeq` -> `gap(reason=cursor_ahead)` + snapshot resync
|
||||
- `afterSeq < oldestSeq - 1` -> `gap(reason=cursor_too_old)` + snapshot resync
|
||||
- missing events count `> 10_000` -> `gap(reason=replay_limit_exceeded)` + snapshot resync
|
||||
- otherwise -> replay only missing events (`seq > afterSeq`)
|
||||
|
||||
### `openStream` Modes
|
||||
|
||||
- `snapshot`: no cursor provided
|
||||
- `replay`: valid cursor replay path
|
||||
- `snapshot_resync`: invalid/stale/ahead/excessive cursor
|
||||
|
||||
### Push Order on Resync
|
||||
|
||||
For resync paths server sends:
|
||||
|
||||
1. `gap`
|
||||
2. `snapshot`
|
||||
|
||||
## Filtering and Extensions
|
||||
|
||||
Per-socket filters (set by `openStream` input):
|
||||
|
||||
- `sessionIds`: include only events/snapshot state for listed sessions
|
||||
- `eventKinds`: include only selected canonical kinds
|
||||
- `includeDebugRaw`: additionally required for `debug.raw`
|
||||
- `includeExtensions`: allowlist of extension keys to keep
|
||||
|
||||
Extension behavior:
|
||||
|
||||
- Events with `extensions` drop all extensions by default.
|
||||
- If `includeExtensions` is set, only requested keys are retained.
|
||||
|
||||
## Backpressure Behavior
|
||||
|
||||
Per socket:
|
||||
|
||||
- If `bufferedAmount > 2MB` for more than `5s`, server closes socket with `1013`.
|
||||
- Server does not silently drop canonical events for active subscribers.
|
||||
- Client is expected to reconnect and resume via `afterSeq`.
|
||||
|
||||
## Client Behavior
|
||||
|
||||
Implemented in:
|
||||
|
||||
- `apps/web/src/wsNativeApi.ts`
|
||||
- `apps/web/src/store.ts`
|
||||
|
||||
### Transport + Stream Lifecycle
|
||||
|
||||
- Web client subscribes to `providers.stream` push channel.
|
||||
- On connection open, it auto-opens stream if there are stream listeners.
|
||||
- It reuses `lastAppliedSeq` for resume (`afterSeq`).
|
||||
|
||||
### Dedupe and Apply Rules
|
||||
|
||||
- Ignore frames with `seq <= lastAppliedSeq`.
|
||||
- Apply `snapshot` as authoritative state reset for matching sessions.
|
||||
- Apply `event` deltas in `seq` order.
|
||||
- `gap` is a signal frame; subsequent snapshot is authoritative.
|
||||
|
||||
## Process Restart Semantics
|
||||
|
||||
- Replay guarantees are process-lifetime scoped.
|
||||
- On server restart, `seq` and replay log reset.
|
||||
- Clients recover by opening stream and applying snapshot baseline.
|
||||
|
||||
## Claude Compatibility Contract
|
||||
|
||||
Future Claude adapter requirements:
|
||||
|
||||
- Adapter emits only canonical `ProviderCoreEvent`.
|
||||
- No UI protocol changes for adding Claude support.
|
||||
|
||||
## Testing Expectations
|
||||
|
||||
Required coverage when changing the API:
|
||||
|
||||
- Contracts parse tests (`providerStream`, method/channel constants).
|
||||
- Server tests for:
|
||||
- open snapshot path
|
||||
- replay path
|
||||
- stale/ahead/excessive cursor -> gap + snapshot
|
||||
- session/event/debug filtering
|
||||
- backpressure close behavior
|
||||
- normalizer mapping coverage
|
||||
- Web tests for:
|
||||
- stream reducer/snapshot behavior
|
||||
- reconnect/dedupe logic
|
||||
- approvals/messages/turn lifecycle from canonical events
|
||||
|
||||
## Change Checklist (PR Gate)
|
||||
|
||||
For any provider WS API change:
|
||||
|
||||
1. Update contracts in `packages/contracts`.
|
||||
2. Update this doc (`docs/provider-ws-api.md`).
|
||||
3. Update server normalizer/store/subscriptions as needed.
|
||||
4. Update client stream/reducer logic as needed.
|
||||
5. Update tests in contracts/server/web.
|
||||
6. Run `bun run typecheck` and `bun run test`.
|
||||
+10
-22
@@ -1,35 +1,23 @@
|
||||
{
|
||||
"name": "@t3tools/monorepo",
|
||||
"name": "ct-round-5",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"apps/*",
|
||||
"packages/*"
|
||||
],
|
||||
"packageManager": "[email protected]",
|
||||
"workspaces": ["apps/*", "packages/*"],
|
||||
"scripts": {
|
||||
"dev": "T3CODE_LOG_WS_EVENTS=1 VITE_WS_URL=ws://localhost:3773 turbo run dev --ui=tui --filter=@t3tools/contracts --filter=@t3tools/web --filter=t3 --parallel",
|
||||
"dev:server": "bun run build:contracts && bun run --cwd apps/server dev",
|
||||
"dev:web": "VITE_WS_URL=ws://localhost:3773 bun run --cwd apps/web dev",
|
||||
"dev:desktop": "bun run --cwd apps/desktop dev",
|
||||
"start": "node apps/server/dist/index.js",
|
||||
"start:desktop": "bun run --cwd apps/desktop start",
|
||||
"dev": "bun run build:contracts && turbo run dev --parallel",
|
||||
"build": "turbo run build",
|
||||
"build:desktop": "bun run build:contracts && bun run --cwd apps/web build && bun run --cwd apps/server build && bun run --cwd apps/desktop build",
|
||||
"typecheck": "turbo run typecheck",
|
||||
"lint": "oxlint --report-unused-disable-directives",
|
||||
"lint": "turbo run lint",
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "bun run --cwd apps/desktop smoke-test",
|
||||
"fmt": "oxfmt",
|
||||
"format": "biome format --write .",
|
||||
"check": "biome check .",
|
||||
"smoke-test": "turbo run smoke-test",
|
||||
"build:contracts": "bun run --cwd packages/contracts build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
"oxlint": "^1.43.0",
|
||||
"@biomejs/biome": "^1.9.0",
|
||||
"turbo": "^2.3.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"bun": ">=1.3.9"
|
||||
},
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"name": "@acme/contracts",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
@@ -16,10 +13,12 @@
|
||||
"require": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"files": ["dist"],
|
||||
"scripts": {
|
||||
"dev": "tsup src/index.ts --format esm,cjs --dts --watch --clean",
|
||||
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "biome check src/",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -3,7 +3,4 @@ export * from "./ipc";
|
||||
export * from "./agent";
|
||||
export * from "./terminal";
|
||||
export * from "./provider";
|
||||
export * from "./providerStream";
|
||||
export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./project";
|
||||
@@ -1,24 +1,13 @@
|
||||
import type { AgentConfig, AgentExit, OutputChunk } from "./agent";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderRespondToApprovalInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "./provider";
|
||||
import type {
|
||||
ProviderStreamFrame,
|
||||
ProvidersOpenStreamInput,
|
||||
ProvidersOpenStreamResult,
|
||||
} from "./providerStream";
|
||||
import type {
|
||||
ProjectAddInput,
|
||||
ProjectAddResult,
|
||||
ProjectListResult,
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type { TerminalCommandInput, TerminalCommandResult } from "./terminal";
|
||||
import type { NewTodoInput, Todo } from "./todo";
|
||||
|
||||
@@ -29,6 +18,27 @@ export const EDITORS = [
|
||||
|
||||
export type EditorId = (typeof EDITORS)[number]["id"];
|
||||
|
||||
export const IPC_CHANNELS = {
|
||||
todosList: "todos:list",
|
||||
todosAdd: "todos:add",
|
||||
todosToggle: "todos:toggle",
|
||||
todosRemove: "todos:remove",
|
||||
dialogPickFolder: "dialog:pick-folder",
|
||||
terminalRun: "terminal:run",
|
||||
agentSpawn: "agent:spawn",
|
||||
agentKill: "agent:kill",
|
||||
agentWrite: "agent:write",
|
||||
agentOutput: "agent:output",
|
||||
agentExit: "agent:exit",
|
||||
providerSessionStart: "provider:session:start",
|
||||
providerTurnStart: "provider:turn:start",
|
||||
providerTurnInterrupt: "provider:turn:interrupt",
|
||||
providerSessionStop: "provider:session:stop",
|
||||
providerSessionList: "provider:session:list",
|
||||
providerEvent: "provider:event",
|
||||
shellOpenInEditor: "shell:open-in-editor",
|
||||
} as const;
|
||||
|
||||
export interface NativeApi {
|
||||
todos: {
|
||||
list: () => Promise<Todo[]>;
|
||||
@@ -50,20 +60,16 @@ export interface NativeApi {
|
||||
onExit: (callback: (exit: AgentExit) => void) => () => void;
|
||||
};
|
||||
providers: {
|
||||
startSession: (input: ProviderSessionStartInput) => Promise<ProviderSession>;
|
||||
sendTurn: (input: ProviderSendTurnInput) => Promise<ProviderTurnStartResult>;
|
||||
startSession: (
|
||||
input: ProviderSessionStartInput,
|
||||
) => Promise<ProviderSession>;
|
||||
sendTurn: (
|
||||
input: ProviderSendTurnInput,
|
||||
) => Promise<ProviderTurnStartResult>;
|
||||
interruptTurn: (input: ProviderInterruptTurnInput) => Promise<void>;
|
||||
respondToApproval: (input: ProviderRespondToApprovalInput) => Promise<void>;
|
||||
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
|
||||
listSessions: () => Promise<ProviderSession[]>;
|
||||
openStream: (input: ProvidersOpenStreamInput) => Promise<ProvidersOpenStreamResult>;
|
||||
closeStream: () => Promise<void>;
|
||||
onStream: (callback: (frame: ProviderStreamFrame) => void) => () => void;
|
||||
};
|
||||
projects: {
|
||||
list: () => Promise<ProjectListResult>;
|
||||
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
|
||||
remove: (input: ProjectRemoveInput) => Promise<void>;
|
||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||
};
|
||||
shell: {
|
||||
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_MODEL, MODEL_OPTIONS, normalizeModelSlug, resolveModelSlug } from "./model";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
MODEL_OPTIONS,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlug,
|
||||
} from "./model";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
it("maps known aliases to canonical slugs", () => {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
export const MODEL_OPTIONS = ["gpt-5.3-codex", "gpt-5.2-codex", "gpt-5.2"] as const;
|
||||
export const MODEL_OPTIONS = [
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
@@ -7,7 +11,9 @@ export const MODEL_SLUG_ALIASES: Record<string, string> = {
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
};
|
||||
|
||||
export function normalizeModelSlug(model: string | null | undefined): string | null {
|
||||
export function normalizeModelSlug(
|
||||
model: string | null | undefined,
|
||||
): string | null {
|
||||
if (typeof model !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
projectAddInputSchema,
|
||||
projectAddResultSchema,
|
||||
projectListResultSchema,
|
||||
projectRemoveInputSchema,
|
||||
} from "./project";
|
||||
|
||||
describe("project contracts", () => {
|
||||
it("parses project list result", () => {
|
||||
const result = projectListResultSchema.parse([
|
||||
{
|
||||
id: "project-1",
|
||||
cwd: "/tmp/project",
|
||||
name: "project",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.id).toBe("project-1");
|
||||
});
|
||||
|
||||
it("trims add input cwd", () => {
|
||||
const parsed = projectAddInputSchema.parse({ cwd: " /tmp/project " });
|
||||
expect(parsed.cwd).toBe("/tmp/project");
|
||||
});
|
||||
|
||||
it("requires add result created flag", () => {
|
||||
const parsed = projectAddResultSchema.parse({
|
||||
project: {
|
||||
id: "project-1",
|
||||
cwd: "/tmp/project",
|
||||
name: "project",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
created: true,
|
||||
});
|
||||
expect(parsed.created).toBe(true);
|
||||
});
|
||||
|
||||
it("parses remove input", () => {
|
||||
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
|
||||
expect(parsed.id).toBe("project-1");
|
||||
});
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const projectRecordSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
cwd: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
createdAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const projectListResultSchema = z.array(projectRecordSchema);
|
||||
|
||||
export const projectAddInputSchema = z.object({
|
||||
cwd: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const projectAddResultSchema = z.object({
|
||||
project: projectRecordSchema,
|
||||
created: z.boolean(),
|
||||
});
|
||||
|
||||
export const projectRemoveInputSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
});
|
||||
|
||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
||||
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
||||
@@ -1,8 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
providerRawEventSchema,
|
||||
providerRespondToApprovalInputSchema,
|
||||
providerEventSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
} from "./provider";
|
||||
@@ -14,21 +13,6 @@ describe("providerSessionStartInputSchema", () => {
|
||||
expect(parsed.approvalPolicy).toBe("never");
|
||||
expect(parsed.sandboxMode).toBe("workspace-write");
|
||||
});
|
||||
|
||||
it("accepts optional resumeThreadId", () => {
|
||||
const parsed = providerSessionStartInputSchema.parse({
|
||||
resumeThreadId: "thread_123",
|
||||
});
|
||||
expect(parsed.resumeThreadId).toBe("thread_123");
|
||||
});
|
||||
|
||||
it("rejects blank resumeThreadId", () => {
|
||||
expect(() =>
|
||||
providerSessionStartInputSchema.parse({
|
||||
resumeThreadId: " ",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerSendTurnInputSchema", () => {
|
||||
@@ -45,9 +29,9 @@ describe("providerSendTurnInputSchema", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerRawEventSchema", () => {
|
||||
describe("providerEventSchema", () => {
|
||||
it("accepts notification events with routing metadata", () => {
|
||||
const parsed = providerRawEventSchema.parse({
|
||||
const parsed = providerEventSchema.parse({
|
||||
id: "evt_1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
@@ -61,40 +45,4 @@ describe("providerRawEventSchema", () => {
|
||||
});
|
||||
expect(parsed.method).toBe("item/agentMessage/delta");
|
||||
});
|
||||
|
||||
it("accepts request approval metadata", () => {
|
||||
const parsed = providerRawEventSchema.parse({
|
||||
id: "evt_2",
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
sessionId: "sess_1",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "item/commandExecution/requestApproval",
|
||||
requestId: "req_123",
|
||||
requestKind: "command",
|
||||
});
|
||||
expect(parsed.requestId).toBe("req_123");
|
||||
expect(parsed.requestKind).toBe("command");
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerRespondToApprovalInputSchema", () => {
|
||||
it("accepts valid decisions", () => {
|
||||
const parsed = providerRespondToApprovalInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
approvalId: "approval_1",
|
||||
decision: "acceptForSession",
|
||||
});
|
||||
expect(parsed.decision).toBe("acceptForSession");
|
||||
});
|
||||
|
||||
it("rejects unknown decisions", () => {
|
||||
expect(() =>
|
||||
providerRespondToApprovalInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
approvalId: "approval_1",
|
||||
decision: "always",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -15,15 +15,6 @@ export const providerSandboxModeSchema = z.enum([
|
||||
"danger-full-access",
|
||||
]);
|
||||
|
||||
export const providerRequestKindSchema = z.enum(["command", "file-change"]);
|
||||
|
||||
export const providerApprovalDecisionSchema = z.enum([
|
||||
"accept",
|
||||
"acceptForSession",
|
||||
"decline",
|
||||
"cancel",
|
||||
]);
|
||||
|
||||
export const providerSessionStatusSchema = z.enum([
|
||||
"connecting",
|
||||
"ready",
|
||||
@@ -49,16 +40,13 @@ export const providerSessionStartInputSchema = z.object({
|
||||
provider: providerKindSchema.default("codex"),
|
||||
cwd: z.string().min(1).optional(),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
resumeThreadId: z.string().trim().min(1).optional(),
|
||||
approvalPolicy: providerApprovalPolicySchema.default("never"),
|
||||
sandboxMode: providerSandboxModeSchema.default("workspace-write"),
|
||||
});
|
||||
|
||||
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
|
||||
|
||||
export const providerSendTurnInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS),
|
||||
input: z.string().trim().min(1).max(120_000),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
effort: z.string().trim().min(1).optional(),
|
||||
});
|
||||
@@ -77,22 +65,16 @@ export const providerStopSessionInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerRespondToApprovalInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
approvalId: z.string().min(1),
|
||||
decision: providerApprovalDecisionSchema,
|
||||
});
|
||||
|
||||
export const providerRawEventKindSchema = z.enum([
|
||||
export const providerEventKindSchema = z.enum([
|
||||
"session",
|
||||
"notification",
|
||||
"request",
|
||||
"error",
|
||||
]);
|
||||
|
||||
export const providerRawEventSchema = z.object({
|
||||
export const providerEventSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
kind: providerRawEventKindSchema,
|
||||
kind: providerEventKindSchema,
|
||||
provider: providerKindSchema,
|
||||
sessionId: z.string().min(1),
|
||||
createdAt: z.string().datetime(),
|
||||
@@ -101,22 +83,20 @@ export const providerRawEventSchema = z.object({
|
||||
threadId: z.string().min(1).optional(),
|
||||
turnId: z.string().min(1).optional(),
|
||||
itemId: z.string().min(1).optional(),
|
||||
requestId: z.string().min(1).optional(),
|
||||
requestKind: providerRequestKindSchema.optional(),
|
||||
textDelta: z.string().optional(),
|
||||
payload: z.unknown().optional(),
|
||||
});
|
||||
|
||||
export type ProviderKind = z.infer<typeof providerKindSchema>;
|
||||
export type ProviderApprovalPolicy = z.infer<typeof providerApprovalPolicySchema>;
|
||||
export type ProviderSandboxMode = z.infer<typeof providerSandboxModeSchema>;
|
||||
export type ProviderRequestKind = z.infer<typeof providerRequestKindSchema>;
|
||||
export type ProviderApprovalDecision = z.infer<
|
||||
typeof providerApprovalDecisionSchema
|
||||
export type ProviderApprovalPolicy = z.infer<
|
||||
typeof providerApprovalPolicySchema
|
||||
>;
|
||||
export type ProviderSandboxMode = z.infer<typeof providerSandboxModeSchema>;
|
||||
export type ProviderSessionStatus = z.infer<typeof providerSessionStatusSchema>;
|
||||
export type ProviderSession = z.infer<typeof providerSessionSchema>;
|
||||
export type ProviderSessionStartInput = z.input<typeof providerSessionStartInputSchema>;
|
||||
export type ProviderSessionStartInput = z.input<
|
||||
typeof providerSessionStartInputSchema
|
||||
>;
|
||||
export type ProviderSendTurnInput = z.input<typeof providerSendTurnInputSchema>;
|
||||
export type ProviderTurnStartResult = z.infer<
|
||||
typeof providerTurnStartResultSchema
|
||||
@@ -127,8 +107,5 @@ export type ProviderInterruptTurnInput = z.input<
|
||||
export type ProviderStopSessionInput = z.input<
|
||||
typeof providerStopSessionInputSchema
|
||||
>;
|
||||
export type ProviderRespondToApprovalInput = z.input<
|
||||
typeof providerRespondToApprovalInputSchema
|
||||
>;
|
||||
export type ProviderRawEventKind = z.infer<typeof providerRawEventKindSchema>;
|
||||
export type ProviderRawEvent = z.infer<typeof providerRawEventSchema>;
|
||||
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
|
||||
export type ProviderEvent = z.infer<typeof providerEventSchema>;
|
||||
@@ -1,79 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
providerCoreEventSchema,
|
||||
providerStreamFrameSchema,
|
||||
providersOpenStreamInputSchema,
|
||||
providersOpenStreamResultSchema,
|
||||
} from "./providerStream";
|
||||
|
||||
describe("providersOpenStreamInputSchema", () => {
|
||||
it("accepts optional cursor and filters", () => {
|
||||
const parsed = providersOpenStreamInputSchema.parse({
|
||||
afterSeq: 42,
|
||||
sessionIds: ["sess_1"],
|
||||
eventKinds: ["message", "turn"],
|
||||
includeExtensions: ["codex.turn.plan"],
|
||||
includeDebugRaw: true,
|
||||
});
|
||||
expect(parsed.afterSeq).toBe(42);
|
||||
expect(parsed.sessionIds).toEqual(["sess_1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerCoreEventSchema", () => {
|
||||
it("accepts message delta events", () => {
|
||||
const parsed = providerCoreEventSchema.parse({
|
||||
type: "message.delta",
|
||||
sessionId: "sess_1",
|
||||
threadId: "thr_1",
|
||||
turnId: "turn_1",
|
||||
messageId: "msg_1",
|
||||
role: "assistant",
|
||||
delta: "hello",
|
||||
});
|
||||
expect(parsed.type).toBe("message.delta");
|
||||
});
|
||||
|
||||
it("accepts approval events with snake-case decisions", () => {
|
||||
const parsed = providerCoreEventSchema.parse({
|
||||
type: "approval.resolved",
|
||||
sessionId: "sess_1",
|
||||
approvalId: "approval_1",
|
||||
decision: "accept_for_session",
|
||||
resolvedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(parsed.type).toBe("approval.resolved");
|
||||
if (parsed.type !== "approval.resolved") {
|
||||
throw new Error("unexpected event variant");
|
||||
}
|
||||
expect(parsed.decision).toBe("accept_for_session");
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerStreamFrameSchema", () => {
|
||||
it("accepts snapshot frames", () => {
|
||||
const parsed = providerStreamFrameSchema.parse({
|
||||
kind: "snapshot",
|
||||
seq: 100,
|
||||
at: "2026-01-01T00:00:00.000Z",
|
||||
data: {
|
||||
sessions: [],
|
||||
activeTurns: [],
|
||||
activeMessages: [],
|
||||
pendingApprovals: [],
|
||||
},
|
||||
});
|
||||
expect(parsed.kind).toBe("snapshot");
|
||||
});
|
||||
|
||||
it("accepts open stream result payloads", () => {
|
||||
const parsed = providersOpenStreamResultSchema.parse({
|
||||
mode: "replay",
|
||||
currentSeq: 200,
|
||||
oldestSeq: 150,
|
||||
replayedCount: 10,
|
||||
});
|
||||
expect(parsed.mode).toBe("replay");
|
||||
});
|
||||
});
|
||||
@@ -1,294 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { providerKindSchema, providerSessionSchema } from "./provider";
|
||||
|
||||
export const providerStreamEventKindSchema = z.enum([
|
||||
"session",
|
||||
"turn",
|
||||
"message",
|
||||
"approval",
|
||||
"activity",
|
||||
"error",
|
||||
"debug.raw",
|
||||
]);
|
||||
|
||||
export const canonicalSessionStateSchema = providerSessionSchema;
|
||||
|
||||
export const canonicalTurnStateSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1),
|
||||
startedAt: z.string().datetime(),
|
||||
model: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
export const canonicalMessageStateSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1).optional(),
|
||||
messageId: z.string().min(1),
|
||||
role: z.literal("assistant"),
|
||||
text: z.string(),
|
||||
startedAt: z.string().datetime(),
|
||||
updatedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const canonicalApprovalKindSchema = z.enum([
|
||||
"command",
|
||||
"file_change",
|
||||
"user_input",
|
||||
]);
|
||||
|
||||
export const canonicalApprovalStateSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1).optional(),
|
||||
turnId: z.string().min(1).optional(),
|
||||
approvalId: z.string().min(1),
|
||||
approvalKind: canonicalApprovalKindSchema,
|
||||
title: z.string().min(1),
|
||||
detail: z.string().min(1).optional(),
|
||||
payload: z.unknown().optional(),
|
||||
timeoutAt: z.string().datetime().optional(),
|
||||
requestedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const providerCoreEventExtensionsSchema = z.record(z.string(), z.unknown());
|
||||
|
||||
export const sessionUpdatedEventSchema = z.object({
|
||||
type: z.literal("session.updated"),
|
||||
session: canonicalSessionStateSchema,
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const turnStartedEventSchema = z.object({
|
||||
type: z.literal("turn.started"),
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1),
|
||||
startedAt: z.string().datetime(),
|
||||
model: z.string().min(1).optional(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const turnCompletedOutcomeSchema = z.enum([
|
||||
"completed",
|
||||
"failed",
|
||||
"interrupted",
|
||||
]);
|
||||
|
||||
export const turnCompletedEventSchema = z.object({
|
||||
type: z.literal("turn.completed"),
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1),
|
||||
completedAt: z.string().datetime(),
|
||||
outcome: turnCompletedOutcomeSchema,
|
||||
error: z.string().min(1).optional(),
|
||||
durationMs: z.number().nonnegative().optional(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const messageDeltaEventSchema = z.object({
|
||||
type: z.literal("message.delta"),
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1).optional(),
|
||||
messageId: z.string().min(1),
|
||||
role: z.literal("assistant"),
|
||||
delta: z.string(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const messageCompletedEventSchema = z.object({
|
||||
type: z.literal("message.completed"),
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1).optional(),
|
||||
messageId: z.string().min(1),
|
||||
role: z.literal("assistant"),
|
||||
text: z.string(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const approvalRequestedEventSchema = z.object({
|
||||
type: z.literal("approval.requested"),
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1).optional(),
|
||||
turnId: z.string().min(1).optional(),
|
||||
approvalId: z.string().min(1),
|
||||
approvalKind: canonicalApprovalKindSchema,
|
||||
title: z.string().min(1),
|
||||
detail: z.string().min(1).optional(),
|
||||
payload: z.unknown().optional(),
|
||||
timeoutAt: z.string().datetime().optional(),
|
||||
requestedAt: z.string().datetime(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const approvalResolvedDecisionSchema = z.enum([
|
||||
"accept",
|
||||
"accept_for_session",
|
||||
"decline",
|
||||
"cancel",
|
||||
"timed_out",
|
||||
]);
|
||||
|
||||
export const approvalResolvedEventSchema = z.object({
|
||||
type: z.literal("approval.resolved"),
|
||||
sessionId: z.string().min(1),
|
||||
approvalId: z.string().min(1),
|
||||
decision: approvalResolvedDecisionSchema,
|
||||
resolvedAt: z.string().datetime(),
|
||||
reason: z.string().min(1).optional(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const activityKindSchema = z.enum(["tool", "plan", "system"]);
|
||||
|
||||
export const activityStatusSchema = z.enum([
|
||||
"created",
|
||||
"in_progress",
|
||||
"success",
|
||||
"failed",
|
||||
"denied",
|
||||
"timed_out",
|
||||
]);
|
||||
|
||||
export const activityEventSchema = z.object({
|
||||
type: z.literal("activity"),
|
||||
sessionId: z.string().min(1),
|
||||
threadId: z.string().min(1).optional(),
|
||||
turnId: z.string().min(1).optional(),
|
||||
activityId: z.string().min(1),
|
||||
activityKind: activityKindSchema,
|
||||
label: z.string().min(1),
|
||||
detail: z.string().min(1).optional(),
|
||||
status: activityStatusSchema,
|
||||
startedAt: z.string().datetime().optional(),
|
||||
completedAt: z.string().datetime().optional(),
|
||||
durationMs: z.number().nonnegative().optional(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const errorEventSchema = z.object({
|
||||
type: z.literal("error"),
|
||||
sessionId: z.string().min(1).optional(),
|
||||
threadId: z.string().min(1).optional(),
|
||||
turnId: z.string().min(1).optional(),
|
||||
code: z.string().min(1),
|
||||
message: z.string().min(1),
|
||||
retryable: z.boolean().optional(),
|
||||
extensions: providerCoreEventExtensionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const debugRawEventSchema = z.object({
|
||||
type: z.literal("debug.raw"),
|
||||
provider: providerKindSchema,
|
||||
sessionId: z.string().min(1).optional(),
|
||||
method: z.string().min(1),
|
||||
payload: z.unknown(),
|
||||
});
|
||||
|
||||
export const providerCoreEventSchema = z.discriminatedUnion("type", [
|
||||
sessionUpdatedEventSchema,
|
||||
turnStartedEventSchema,
|
||||
turnCompletedEventSchema,
|
||||
messageDeltaEventSchema,
|
||||
messageCompletedEventSchema,
|
||||
approvalRequestedEventSchema,
|
||||
approvalResolvedEventSchema,
|
||||
activityEventSchema,
|
||||
errorEventSchema,
|
||||
debugRawEventSchema,
|
||||
]);
|
||||
|
||||
export const providerSnapshotSchema = z.object({
|
||||
sessions: z.array(canonicalSessionStateSchema),
|
||||
activeTurns: z.array(canonicalTurnStateSchema),
|
||||
activeMessages: z.array(canonicalMessageStateSchema),
|
||||
pendingApprovals: z.array(canonicalApprovalStateSchema),
|
||||
});
|
||||
|
||||
export const providerStreamGapReasonSchema = z.enum([
|
||||
"cursor_too_old",
|
||||
"cursor_ahead",
|
||||
"replay_limit_exceeded",
|
||||
]);
|
||||
|
||||
export const providerStreamGapSchema = z.object({
|
||||
reason: providerStreamGapReasonSchema,
|
||||
oldestSeq: z.number().int().nonnegative(),
|
||||
currentSeq: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
export const providerStreamFrameSchema = z.discriminatedUnion("kind", [
|
||||
z.object({
|
||||
kind: z.literal("snapshot"),
|
||||
seq: z.number().int().nonnegative(),
|
||||
at: z.string().datetime(),
|
||||
data: providerSnapshotSchema,
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("event"),
|
||||
seq: z.number().int().nonnegative(),
|
||||
at: z.string().datetime(),
|
||||
data: providerCoreEventSchema,
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal("gap"),
|
||||
seq: z.number().int().nonnegative(),
|
||||
at: z.string().datetime(),
|
||||
data: providerStreamGapSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
export const providersOpenStreamInputSchema = z.object({
|
||||
afterSeq: z.number().int().nonnegative().optional(),
|
||||
sessionIds: z.array(z.string().min(1)).optional(),
|
||||
eventKinds: z.array(providerStreamEventKindSchema).optional(),
|
||||
includeExtensions: z.array(z.string().min(1)).optional(),
|
||||
includeDebugRaw: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const providersOpenStreamModeSchema = z.enum([
|
||||
"snapshot",
|
||||
"replay",
|
||||
"snapshot_resync",
|
||||
]);
|
||||
|
||||
export const providersOpenStreamResultSchema = z.object({
|
||||
mode: providersOpenStreamModeSchema,
|
||||
currentSeq: z.number().int().nonnegative(),
|
||||
oldestSeq: z.number().int().nonnegative(),
|
||||
replayedCount: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
export type ProviderStreamEventKind = z.infer<typeof providerStreamEventKindSchema>;
|
||||
export type CanonicalSessionState = z.infer<typeof canonicalSessionStateSchema>;
|
||||
export type CanonicalTurnState = z.infer<typeof canonicalTurnStateSchema>;
|
||||
export type CanonicalMessageState = z.infer<typeof canonicalMessageStateSchema>;
|
||||
export type CanonicalApprovalKind = z.infer<typeof canonicalApprovalKindSchema>;
|
||||
export type CanonicalApprovalState = z.infer<typeof canonicalApprovalStateSchema>;
|
||||
export type ProviderCoreEventExtensions = z.infer<typeof providerCoreEventExtensionsSchema>;
|
||||
export type SessionUpdatedEvent = z.infer<typeof sessionUpdatedEventSchema>;
|
||||
export type TurnStartedEvent = z.infer<typeof turnStartedEventSchema>;
|
||||
export type TurnCompletedOutcome = z.infer<typeof turnCompletedOutcomeSchema>;
|
||||
export type TurnCompletedEvent = z.infer<typeof turnCompletedEventSchema>;
|
||||
export type MessageDeltaEvent = z.infer<typeof messageDeltaEventSchema>;
|
||||
export type MessageCompletedEvent = z.infer<typeof messageCompletedEventSchema>;
|
||||
export type ApprovalRequestedEvent = z.infer<typeof approvalRequestedEventSchema>;
|
||||
export type ApprovalResolvedDecision = z.infer<typeof approvalResolvedDecisionSchema>;
|
||||
export type ApprovalResolvedEvent = z.infer<typeof approvalResolvedEventSchema>;
|
||||
export type ActivityKind = z.infer<typeof activityKindSchema>;
|
||||
export type ActivityStatus = z.infer<typeof activityStatusSchema>;
|
||||
export type ActivityEvent = z.infer<typeof activityEventSchema>;
|
||||
export type ErrorEvent = z.infer<typeof errorEventSchema>;
|
||||
export type DebugRawEvent = z.infer<typeof debugRawEventSchema>;
|
||||
export type ProviderCoreEvent = z.infer<typeof providerCoreEventSchema>;
|
||||
export type ProviderSnapshot = z.infer<typeof providerSnapshotSchema>;
|
||||
export type ProviderStreamGapReason = z.infer<typeof providerStreamGapReasonSchema>;
|
||||
export type ProviderStreamGap = z.infer<typeof providerStreamGapSchema>;
|
||||
export type ProviderStreamFrame = z.infer<typeof providerStreamFrameSchema>;
|
||||
export type ProvidersOpenStreamInput = z.input<typeof providersOpenStreamInputSchema>;
|
||||
export type ProvidersOpenStreamMode = z.infer<typeof providersOpenStreamModeSchema>;
|
||||
export type ProvidersOpenStreamResult = z.infer<typeof providersOpenStreamResultSchema>;
|
||||
@@ -1,80 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── WebSocket RPC Method Names ───────────────────────────────────────
|
||||
|
||||
export const WS_METHODS = {
|
||||
// Provider methods (mirrors NativeApi.providers)
|
||||
providersStartSession: "providers.startSession",
|
||||
providersSendTurn: "providers.sendTurn",
|
||||
providersInterruptTurn: "providers.interruptTurn",
|
||||
providersRespondToApproval: "providers.respondToApproval",
|
||||
providersStopSession: "providers.stopSession",
|
||||
providersListSessions: "providers.listSessions",
|
||||
providersOpenStream: "providers.openStream",
|
||||
providersCloseStream: "providers.closeStream",
|
||||
|
||||
// Project registry methods
|
||||
projectsList: "projects.list",
|
||||
projectsAdd: "projects.add",
|
||||
projectsRemove: "projects.remove",
|
||||
|
||||
// Shell methods
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
|
||||
export const WS_CHANNELS = {
|
||||
providerStream: "providers.stream",
|
||||
serverWelcome: "server.welcome",
|
||||
} as const;
|
||||
|
||||
// ── Client → Server (request) ────────────────────────────────────────
|
||||
|
||||
export const wsRequestSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
method: z.string().min(1),
|
||||
params: z.unknown().optional(),
|
||||
});
|
||||
|
||||
export type WsRequest = z.infer<typeof wsRequestSchema>;
|
||||
|
||||
// ── Server → Client (response to request) ────────────────────────────
|
||||
|
||||
export const wsResponseSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
result: z.unknown().optional(),
|
||||
error: z
|
||||
.object({
|
||||
message: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type WsResponse = z.infer<typeof wsResponseSchema>;
|
||||
|
||||
// ── Server → Client (push event) ─────────────────────────────────────
|
||||
|
||||
export const wsPushSchema = z.object({
|
||||
type: z.literal("push"),
|
||||
channel: z.string().min(1),
|
||||
data: z.unknown(),
|
||||
});
|
||||
|
||||
export type WsPush = z.infer<typeof wsPushSchema>;
|
||||
|
||||
// ── Union of all server → client messages ─────────────────────────────
|
||||
|
||||
export type WsServerMessage = WsResponse | WsPush;
|
||||
|
||||
// ── Server welcome payload ───────────────────────────────────────────
|
||||
|
||||
export const wsWelcomePayloadSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
projectName: z.string().min(1),
|
||||
});
|
||||
|
||||
export type WsWelcomePayload = z.infer<typeof wsWelcomePayloadSchema>;
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
|
||||
+10
-13
@@ -1,24 +1,12 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"globalEnv": [
|
||||
"PORT",
|
||||
"VITE_WS_URL",
|
||||
"VITE_DEV_SERVER_URL",
|
||||
"T3CODE_LOG_WS_EVENTS",
|
||||
"T3CODE_MODE",
|
||||
"T3CODE_PORT",
|
||||
"T3CODE_NO_BROWSER",
|
||||
"T3CODE_STATE_DIR",
|
||||
"T3CODE_AUTH_TOKEN",
|
||||
"T3CODE_DESKTOP_WS_URL"
|
||||
],
|
||||
"globalEnv": ["ELECTRON_RENDERER_PORT"],
|
||||
"tasks": {
|
||||
"build": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": ["dist/**", "dist-electron/**"]
|
||||
},
|
||||
"dev": {
|
||||
"dependsOn": ["@t3tools/contracts#build"],
|
||||
"cache": false,
|
||||
"persistent": true
|
||||
},
|
||||
@@ -26,9 +14,18 @@
|
||||
"dependsOn": ["^typecheck"],
|
||||
"outputs": []
|
||||
},
|
||||
"lint": {
|
||||
"dependsOn": ["^lint"],
|
||||
"outputs": []
|
||||
},
|
||||
"test": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": []
|
||||
},
|
||||
"smoke-test": {
|
||||
"dependsOn": ["build"],
|
||||
"cache": false,
|
||||
"outputs": []
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user