Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 91d174407d Add desktop dev mode gotcha to AGENTS.md
Co-authored-by: Julius Marminge <[email protected]>
2026-02-28 00:44:51 +00:00
Cursor AgentandJulius Marminge 173bc00b32 Add Cursor Cloud specific instructions to AGENTS.md
Co-authored-by: Julius Marminge <[email protected]>
2026-02-28 00:31:50 +00:00
Julius Marminge e6c5a4a4bb Handle favicon links when href precedes rel
- Update favicon regex parsing to support rel/href in either order
- Add route tests for HTML link tags and object-style metadata with href-first ordering
2026-02-27 15:21:31 -08:00
Julius Marminge 732b3abf99 match assets/{icon,logo} as well 2026-02-27 15:21:31 -08:00
Julius Marminge ffbf541ff8 Extract project favicon route and tighten turn-settled logic
- move `/api/project-favicon` handling into a dedicated server route with coverage for root and source-linked icons
- wire `wsServer` to use the new route helper
- treat any running session as unsettled in `isLatestTurnSettled` to prevent stale latest-turn banners, with test coverage
2026-02-27 15:21:31 -08:00
Julius Marminge 709f961e1c Gate latest-turn completion UI on settled turn state
- Add `isLatestTurnSettled` to avoid treating an active running turn as complete
- Use the guard in `ChatView` for visited timestamps and completion summary/divider rendering
- Add unit tests covering running, ready, and incomplete-timestamp cases
2026-02-27 15:21:31 -08:00
Theo Browne 1653383573 Remove my junk paths 2026-02-27 15:21:31 -08:00
Theo Browne c7ae6b9471 Favicons + custom port during dev 2026-02-27 15:21:31 -08:00
Julius Marminge bbcf9ba9db Show pending approvals in sidebar thread status
- derive pending approvals from thread activities and label status as "Pending Approval"
- remove `isolate` class from chat `SidebarInset` containers
2026-02-27 14:49:27 -08:00
Julius Marminge 3f81f9dcb4 Replace thread latestTurnId with structured latestTurn metadata
- add `OrchestrationLatestTurn` schema and store full turn state/timestamps/message linkage
- update server projector/snapshot queries to populate `latestTurn` from session + projection_turns
- migrate web store/components to consume `latestTurn` and adjust related tests
2026-02-27 14:10:34 -08:00
Julius Marminge b073fea5fb Handle provider turn IDs correctly in runtime ingestion
- Use `ProviderTurnId` in `CheckpointReactor` tests instead of `TurnId`
- Guard `event.turnId` access in provider runtime ingestion when the field is absent
2026-02-27 14:10:34 -08:00
Julius Marminge 834236931e Inline provider thread and turn ID schemas in runtime events
- Remove redundant runtime schema aliases for thread and turn IDs
- Use `ProviderThreadId` and `ProviderTurnId` directly across runtime event contracts
2026-02-27 14:10:34 -08:00
Julius Marminge 872b907372 Guard provider lifecycle updates to primary thread and active turn
- Ignore auxiliary/non-active turn completions for session lifecycle and checkpoints
- Restrict runtime thread/turn IDs to provider IDs in contracts
- Add regression tests and ADR for lifecycle ownership rules
2026-02-27 14:10:34 -08:00
Theo Browne 0b8e098c10 copy on hover, better button treatments (#110) 2026-02-27 14:06:09 -08:00
blacksmith-sh[bot] 7c6a0f869d Migrate workflows to Blacksmith (#111)
Co-authored-by: blacksmith-sh[bot] <157653362+blacksmith-sh[bot]@users.noreply.github.com>
2026-02-27 14:05:22 -08:00
Julius Marminge 3a43047102 Sync diff renderer theme with app theme changes
- Pass explicit Pierre light/dark theme into diff render options
- Re-key file diffs on resolved theme so views rerender on theme switch
- Stabilize `useTheme` snapshots to propagate system theme updates reliably
2026-02-27 11:09:21 -08:00
Julius Marminge 041acf158a fix nullability 2026-02-26 21:36:44 -08:00
Julius Marminge f9752d7c08 migr 2026-02-26 21:26:35 -08:00
Julius Marminge 766592b83b tone down defautls 2026-02-26 21:26:35 -08:00
Julius Marminge 1c3c412ce4 Disable two Effect lint rules in server tsconfig
- Turn off `preferSchemaOverJson`
- Turn off `globalErrorInEffectFailure`
2026-02-26 21:26:35 -08:00
Julius Marminge f9e6d1290d Handle session restart failures without dropping active thread session
- Reorder restart flow to bind the new provider session before stopping the old one
- Log (and swallow) stop-session failures for superseded sessions
- Add regression test ensuring failed restart does not stop the active session
2026-02-26 21:26:35 -08:00
Julius Marminge 8ef653fcc0 Persist required approval policy and sandbox mode for sessions
- Make `approvalPolicy` and `sandboxMode` required in orchestration contracts and turn-start flow
- Add defaults in provider reactors/ingestion to guarantee values are always set
- Store and hydrate both fields in projection persistence, snapshots, and related tests
2026-02-26 21:26:35 -08:00
Julius Marminge fb8d66b8d3 rm 2026-02-26 21:26:35 -08:00
Julius MarmingeandClaude Opus 4.5 e70b34de62 Fix type error with optional approvalPolicy and sandboxMode
Use conditional spreading for these properties to handle undefined
values correctly with exactOptionalPropertyTypes.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-26 21:26:35 -08:00
Julius Marminge b1584fab8f Add .t3 keybindings and initial local runtime state files
- add default `.t3/keybindings.json` for terminal/chat/editor/diff shortcuts
- include initial provider log files and SQLite state artifacts under `apps/server/.t3`
2026-02-26 21:26:35 -08:00
Julius Marminge 718084065e Restart provider sessions when runtime mode changes
- Persist `approvalPolicy` and `sandboxMode` on orchestration sessions
- Reuse existing sessions when runtime mode is unchanged
- Stop and recreate provider sessions when runtime mode settings change
- Add reactor tests for reuse vs restart behavior
2026-02-26 21:26:35 -08:00
Julius Marminge 57dd091e05 Propagate runtime approval and sandbox settings to turn startup
- Add `approvalPolicy` and `sandboxMode` to turn-start command and requested payload contracts
- Pass runtime mode-derived values from `ChatView` when dispatching `thread.turn.start`
- Thread provider options through decider/reactor into session startup, with tests updated
2026-02-26 21:26:35 -08:00
Julius Marminge a1f208f1e6 Provide NodeServices layer in wsServer bootstrap test
- inject `NodeServices.layer` into sqlite persistence setup in `wsServer.test.ts`
- fixes test runtime dependencies for existing-state bootstrap path
2026-02-26 21:05:53 -08:00
Julius Marminge 581aa7279f Require bootstrap IDs for root thread auto-navigation
- Remove snapshot fallback lookup for missing bootstrap project/thread IDs
- Only expand project and navigate when server payload includes both IDs
2026-02-26 21:05:53 -08:00
Julius Marminge 0b29924648 Recover bootstrap thread from snapshot when IDs are missing
- Fetch orchestration snapshot when bootstrap project/thread IDs are absent
- Resolve project by current workspace and choose latest non-deleted thread
- Continue auto-navigation and expansion using resolved fallback IDs
2026-02-26 21:05:53 -08:00
Julius Marminge 49472da669 Return existing bootstrap thread IDs in welcome and guard root navigatio
- Server welcome now includes bootstrap project/thread IDs when cwd project/thread already exist
- Added regression test for reconnecting with persisted bootstrap state
- Root route ignores post-dispose welcome handling and marks thread as handled after navigate
2026-02-26 21:05:53 -08:00
Julius Marminge 69a2eac2ff Use pathname ref in EventRouter bootstrap navigation
- Track latest `pathname` in a ref for bootstrap event handling
- Prevent effect resubscriptions by removing `pathname` from deps
- Keep auto-navigation gated to root route using current path
2026-02-26 21:05:53 -08:00
Julius Marminge 5fd632c357 Bootstrap default thread and route to it on server welcome
- Create or reuse cwd project, create initial thread, and include bootstrap IDs in `server.welcome`
- Update web event routing to expand the project and auto-navigate from `/` to the bootstrapped thread
- Extend WebSocket welcome contract and add server/web tests for bootstrap payload handling
2026-02-26 21:05:53 -08:00
Julius Marminge bb2164c945 Prevent duplicate sends and sync worktree branch state
- Guard `onSend` with an in-flight ref to block double submits
- Set send phase before worktree prep and always clear in-flight state in `finally`
- Sync thread branch/worktree path immediately and await setup script execution
2026-02-26 20:51:29 -08:00
Julius Marminge 8c91aa5570 Prevent duplicate sends while composer request is in flight
- Add `sendInFlightRef` guard in `ChatView` send handler
- Set sending state before async work and always clear it in `finally`
- Wrap early send flow in one `try/finally` to avoid double-submit races
2026-02-26 20:51:29 -08:00
Julius Marminge 6db8257b1e Stop forcing setup script to open a new terminal
- Remove `preferNewTerminal` when invoking `runProjectScript` in `ChatView`
- Lets setup scripts use default terminal behavior for worktree runs
2026-02-26 20:51:29 -08:00
Julius Marminge f6e7166e79 Capture threadId before async send flow
- Store `activeThread.id` once at send start and reuse it
- Prevents updates/errors from targeting the wrong thread during async worktree/send steps
2026-02-26 20:51:29 -08:00
Julius Marmingeandcodex 2da8290040 Require base branch before first send in worktree mode
- show an explicit error when New worktree mode has no base branch selected
- sync thread branch/worktree path immediately after creation
- run setup script in the new worktree terminal before continuing

Co-authored-by: codex <[email protected]>
2026-02-26 20:51:29 -08:00
Julius Marminge 4d6e8e1ca5 rm redundant gen 2026-02-26 20:43:22 -08:00
Julius Marminge 7e4da5b157 Remove assistant-complete text payload from orchestration flow
- Drop optional `text` from `ThreadMessageAssistantCompleteCommand`
- Stop passing text on assistant-complete ingestion and decider paths
- Ensure completion events no longer overwrite message content
2026-02-26 20:43:22 -08:00
Julius Marminge 9acce6ddaa todo 2026-02-26 20:43:22 -08:00
Julius Marminge 8054a32417 update todo 2026-02-26 20:43:22 -08:00
Julius Marminge ed3958daa8 Clarify assistant buffer flush safety-valve comment
- Update wording to say buffered text is flushed as an assistant delta
- Keeps intent clear: memory is capped by emitting the current buffer
2026-02-26 20:43:22 -08:00
Julius Marminge 9d5c515680 Always flush buffered assistant text as final delta
- Remove spilled-state cache tracking for buffered assistant messages
- Emit any remaining buffered text as a finalize delta on completion
- Keep assistant completion payload text empty in buffered mode
2026-02-26 20:43:22 -08:00
Julius Marminge 0e9677965c Spill full buffered assistant text when buffer exceeds cap
- Change provider runtime ingestion to flush the entire buffered assistant text once it crosses the max size
- Remove partial-retention logic and its keep-chars constant to simplify memory safety behavior
2026-02-26 20:43:22 -08:00
Julius Marminge cc29ceea80 Spill oversized buffered assistant deltas without losing final text
- cap buffered assistant text memory and spill older chunks as delta events
- finalize buffered messages by emitting retained remainder before completion when spilled
- add regression coverage for oversized buffered deltas and tighten type-safe test assertions
2026-02-26 20:43:22 -08:00
Julius Marminge 32a17b9109 Simplify assistant delivery mode state in runtime ingestion
- Replace per-thread/turn/message delivery-mode caches with a single `Ref`
- Always complete assistant messages with buffered text from message state
- Remove obsolete delivery-mode cleanup and resolution paths
2026-02-26 20:43:22 -08:00
Julius MarmingeandClaude Opus 4.5 e119e18ed3 Fix type errors with exactOptionalPropertyTypes
Use conditional spread for turnId to avoid passing undefined
explicitly when the target type expects an optional property.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-26 20:43:22 -08:00
Julius Marminge 001902c881 Add configurable assistant delivery mode across server and web
- add `AssistantDeliveryMode` contracts and carry mode through turn-start events
- default assistant responses to buffered mode and preserve buffered text until completion
- support streaming mode end-to-end with ingestion/decider updates and test coverage
- add a Settings toggle to enable assistant streaming in the chat UI
2026-02-26 20:43:22 -08:00
55 changed files with 1965 additions and 258 deletions

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ on:
jobs:
quality:
name: Lint, Typecheck, Test, Build
runs-on: ubuntu-latest
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
uses: actions/checkout@v4
+64
View File
@@ -0,0 +1,64 @@
import path from "path";
import fs from "fs";
const FAVICON_CANDIDATES = [
"favicon.svg", "favicon.ico", "favicon.png",
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
];
const ICON_SOURCE_FILES = [
"index.html", "public/index.html",
"app/routes/__root.tsx", "src/routes/__root.tsx",
"app/root.tsx", "src/root.tsx", "src/index.html",
];
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
function test(projectCwd) {
console.log("--- Testing:", projectCwd, "---");
for (const c of FAVICON_CANDIDATES) {
const full = path.join(projectCwd, c);
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
console.log(" Phase 1 FOUND:", c);
return;
}
}
console.log(" Phase 1: no match");
for (const sf of ICON_SOURCE_FILES) {
const full = path.join(projectCwd, sf);
if (!fs.existsSync(full)) continue;
const content = fs.readFileSync(full, "utf8");
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
if (href) {
const clean = href.replace(/^\//, "");
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
for (const p of tryPaths) {
if (fs.existsSync(p)) {
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
return;
}
}
console.log(" Phase 2 href found but file missing:", href);
}
}
console.log(" Phase 2: no match");
}
function getTestPaths() {
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
if (cliPaths.length > 0) return cliPaths;
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
if (envPaths?.length) return envPaths;
return [process.cwd()];
}
for (const p of getTestPaths()) {
test(path.resolve(p));
}
+28
View File
@@ -41,3 +41,31 @@ Docs:
- 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.
## Cursor Cloud specific instructions
### Prerequisites
- **Bun >= 1.3.9** (package manager; see `packageManager` in root `package.json`).
- **Node.js >= 24.13.1** (required for `node:sqlite`; see `engines` in root `package.json`).
- **Codex CLI** on PATH is needed for full E2E agent sessions but is NOT required for dev server startup, lint, typecheck, or tests.
### Key commands
All commands are documented in the root `README.md`. Quick reference:
- `bun install` — install dependencies.
- `bun run lint` — runs `oxlint` (not ESLint).
- `bun run typecheck` — Turbo-orchestrated `tsc --noEmit` across all packages.
- `bun run test` — Turbo-orchestrated Vitest across all packages.
- `bun run dev` — starts contracts watch-build + server (port 3773) + Vite web (port 5733) via Turbo. Pass `T3CODE_NO_BROWSER=1` to suppress auto-opening a browser.
- `bun run build` — production build of all packages.
### Gotchas
- The server uses `node:sqlite` (experimental in Node 24). You will see `ExperimentalWarning: SQLite is an experimental feature` in test/server output — this is expected.
- Dev state is isolated to `~/.t3/dev` by default (set via `T3CODE_STATE_DIR`).
- `bun run dev` spawns `turbo` under the hood via `scripts/dev-runner.mjs`; the runner resolves dev ports (server 3773, web 5733) and environment variables automatically.
- `packages/contracts` must be built before `apps/server` or `apps/web` can start. Turbo handles this dependency, but if running individual packages manually, build contracts first: `bun run build:contracts`.
- Lint uses `oxlint` (config: `.oxlintrc.json`), not ESLint. Formatting uses `oxfmt` (config: `.oxfmtrc.json`).
- **Desktop dev mode** (`bun run dev:desktop`): The desktop Electron app requires `apps/server/dist/index.mjs` to exist (it spawns the server backend itself). Run `bun run build:desktop` first to build both server and desktop bundles, then `bun run dev:desktop`. The `tsdown --watch` (dev:bundle) may clean `dist-electron/` and not immediately rebuild; if `wait-on` hangs, manually run `bun run build` in `apps/desktop/` to unblock.
+1 -1
View File
@@ -91,7 +91,7 @@ npx t3
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5173`
- Default ports: server `3773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
+1 -1
View File
@@ -5,7 +5,7 @@ import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
await waitOn({
@@ -136,6 +136,8 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: nowIso(),
});
@@ -317,7 +319,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
const secondTurnThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurnId === "turn-2" &&
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
);
@@ -651,7 +653,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurnId === "turn-2" &&
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.activities.some((activity) => activity.turnId === "turn-2"),
8000,
+1 -1
View File
@@ -10,7 +10,7 @@
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
"build": "tsdown && node scripts/bundle-client.ts",
"start": "node dist/index.mjs",
"prepare": "effect-language-service patch",
@@ -45,7 +45,14 @@ function makeSnapshot(input: {
model: "gpt-5-codex",
branch: null,
worktreePath: input.worktreePath,
latestTurnId: TurnId.makeUnsafe("turn-1"),
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:00.000Z",
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
@@ -11,6 +11,7 @@ import {
ProjectId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -40,6 +41,7 @@ import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
@@ -91,7 +93,7 @@ function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd
async function waitForThread(
engine: OrchestrationEngineShape,
predicate: (thread: {
latestTurnId: string | null;
latestTurn: { turnId: string } | null;
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
@@ -99,7 +101,7 @@ async function waitForThread(
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<{
latestTurnId: string | null;
latestTurn: { turnId: string } | null;
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}> => {
@@ -317,6 +319,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -332,7 +336,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-1"),
turnId: asProviderTurnId("turn-1"),
});
await waitForGitRefExists(
harness.cwd,
@@ -347,14 +351,14 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-1"),
turnId: asProviderTurnId("turn-1"),
status: "completed",
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurnId === "turn-1" && entry.checkpoints.length === 1,
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
@@ -379,6 +383,81 @@ describe("CheckpointReactor", () => {
).toBe("v2\n");
});
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-main"),
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-main"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
turnId: asProviderTurnId("turn-aux"),
status: "completed",
});
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(midThread?.checkpoints).toHaveLength(0);
harness.provider.emit({
type: "turn.completed",
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asProviderTurnId("turn-main"),
status: "completed",
});
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
@@ -394,6 +473,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -409,7 +490,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-missing-baseline"),
turnId: asProviderTurnId("turn-missing-baseline"),
status: "completed",
});
@@ -445,6 +526,8 @@ describe("CheckpointReactor", () => {
text: "start turn",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: new Date().toISOString(),
}),
);
@@ -481,6 +564,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-missing"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-missing-cwd"),
lastError: null,
updatedAt: createdAt,
@@ -497,7 +582,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-missing"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
turnId: asTurnId("turn-missing-cwd"),
turnId: asProviderTurnId("turn-missing-cwd"),
status: "completed",
});
@@ -529,6 +614,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -544,7 +631,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-3"),
turnId: asProviderTurnId("turn-3"),
turnCount: 3,
status: "completed",
});
@@ -580,6 +667,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -595,7 +684,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-runtime-failure"),
turnId: asProviderTurnId("turn-runtime-failure"),
turnCount: 1,
status: "completed",
});
@@ -607,7 +696,7 @@ describe("CheckpointReactor", () => {
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
turnId: asTurnId("turn-after-runtime-failure"),
turnId: asProviderTurnId("turn-after-runtime-failure"),
});
await waitForGitRefExists(
@@ -634,6 +723,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -684,7 +775,7 @@ describe("CheckpointReactor", () => {
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
expect(thread.latestTurnId).toBe("turn-1");
expect(thread.latestTurn?.turnId).toBe("turn-1");
expect(thread.checkpoints).toHaveLength(1);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
@@ -713,6 +804,8 @@ describe("CheckpointReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
@@ -3,6 +3,7 @@ import {
EventId,
MessageId,
ProviderSessionId,
ProviderThreadId,
ThreadId,
TurnId,
type OrchestrationEvent,
@@ -36,6 +37,17 @@ function toTurnId(value: string | undefined): TurnId | null {
return value === undefined ? null : TurnId.makeUnsafe(value);
}
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
}
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
if (left === null || left === undefined || right === null || right === undefined) {
return false;
}
return left === right;
}
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
switch (status) {
case "failed":
@@ -173,6 +185,21 @@ const make = Effect.gen(function* () {
return;
}
const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
const eventProviderThreadId = toProviderThreadId(event.threadId);
if (
projectedProviderThreadId !== null &&
eventProviderThreadId !== null &&
!sameId(projectedProviderThreadId, eventProviderThreadId)
) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
return;
}
@@ -92,6 +92,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt,
}),
);
@@ -428,6 +430,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request" as const,
sandboxMode: "workspace-write" as const,
createdAt,
};
@@ -586,6 +590,8 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now(),
}),
),
@@ -794,6 +794,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
payload: {
threadId,
messageId,
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: turnStartedAt,
},
});
@@ -827,6 +829,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
providerName: "codex",
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: turnId,
lastError: null,
updatedAt: sessionSetAt,
@@ -473,6 +473,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
providerName: event.payload.session.providerName,
providerSessionId: event.payload.session.providerSessionId,
providerThreadId: event.payload.session.providerThreadId,
approvalPolicy: event.payload.session.approvalPolicy,
sandboxMode: event.payload.session.sandboxMode,
activeTurnId: event.payload.session.activeTurnId,
lastError: event.payload.session.lastError,
updatedAt: event.payload.session.updatedAt,
@@ -143,6 +143,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
provider_name,
provider_session_id,
provider_thread_id,
approval_policy,
sandbox_mode,
active_turn_id,
last_error,
updated_at
@@ -153,6 +155,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'codex',
'provider-session-1',
'provider-thread-1',
'on-request',
'workspace-write',
'turn-1',
NULL,
'2026-02-24T00:00:07.000Z'
@@ -239,7 +243,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
model: "gpt-5-codex",
branch: null,
worktreePath: null,
latestTurnId: asTurnId("turn-1"),
latestTurn: {
turnId: asTurnId("turn-1"),
state: "completed",
requestedAt: "2026-02-24T00:00:08.000Z",
startedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
assistantMessageId: asMessageId("message-1"),
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
deletedAt: null,
@@ -282,6 +293,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
providerName: "codex",
providerSessionId: asProviderSessionId("provider-session-1"),
providerThreadId: asProviderThreadId("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-1"),
lastError: null,
updatedAt: "2026-02-24T00:00:07.000Z",
@@ -1,8 +1,12 @@
import {
IsoDateTime,
MessageId,
OrchestrationCheckpointFile,
OrchestrationReadModel,
ProjectScript,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
type OrchestrationMessage,
type OrchestrationProject,
type OrchestrationSession,
@@ -55,6 +59,15 @@ const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
}),
);
const ProjectionLatestTurnDbRowSchema = Schema.Struct({
threadId: ProjectionThread.fields.threadId,
turnId: TurnId,
state: Schema.String,
requestedAt: IsoDateTime,
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
});
const ProjectionStateDbRowSchema = ProjectionState;
const REQUIRED_SNAPSHOT_PROJECTORS = [
@@ -196,6 +209,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
provider_name AS "providerName",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
updated_at AS "updatedAt"
@@ -224,6 +239,25 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
turn_id AS "turnId",
state,
requested_at AS "requestedAt",
started_at AS "startedAt",
completed_at AS "completedAt",
assistant_message_id AS "assistantMessageId"
FROM projection_turns
WHERE turn_id IS NOT NULL
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
`,
});
const listProjectionStateRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionStateDbRowSchema,
@@ -248,6 +282,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
activityRows,
sessionRows,
checkpointRows,
latestTurnRows,
stateRows,
] = yield* Effect.all([
listProjectRows(undefined).pipe(
@@ -298,6 +333,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
),
),
),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -312,6 +355,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
let updatedAt: string | null = null;
@@ -370,6 +414,34 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
checkpointsByThread.set(row.threadId, threadCheckpoints);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
if (latestTurnByThread.has(row.threadId)) {
continue;
}
latestTurnByThread.set(row.threadId, {
turnId: row.turnId,
state:
row.state === "error"
? "error"
: row.state === "interrupted"
? "interrupted"
: row.state === "completed"
? "completed"
: "running",
requestedAt: row.requestedAt,
startedAt: row.startedAt,
completedAt: row.completedAt,
assistantMessageId: row.assistantMessageId,
});
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
sessionsByThread.set(row.threadId, {
@@ -378,6 +450,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
providerName: row.providerName,
providerSessionId: row.providerSessionId,
providerThreadId: row.providerThreadId,
approvalPolicy: row.approvalPolicy,
sandboxMode: row.sandboxMode,
activeTurnId: row.activeTurnId,
lastError: row.lastError,
updatedAt: row.updatedAt,
@@ -402,7 +476,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
model: row.model,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurnId: row.latestTurnId,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
@@ -71,16 +71,18 @@ describe("ProviderCommandReactor", () => {
async function createHarness() {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const startSession = vi.fn((_: unknown, __: unknown) =>
Effect.succeed({
sessionId: asSessionId("sess-1"),
let nextSessionIndex = 1;
const startSession = vi.fn((_: unknown, __: unknown) => {
const sessionIndex = nextSessionIndex++;
return Effect.succeed({
sessionId: asSessionId(`sess-${sessionIndex}`),
provider: "codex" as const,
status: "ready" as const,
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
threadId: ProviderThreadId.makeUnsafe(`provider-thread-${sessionIndex}`),
createdAt: now,
updatedAt: now,
}),
);
});
});
const sendTurn = vi.fn((_: unknown) =>
Effect.succeed({
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
@@ -171,6 +173,8 @@ describe("ProviderCommandReactor", () => {
text: "hello reactor",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
@@ -181,11 +185,181 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
model: "gpt-5-codex",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-1");
expect(thread?.session?.approvalPolicy).toBe("on-request");
expect(thread?.session?.sandboxMode).toBe("workspace-write");
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unchanged-1"),
role: "user",
text: "first",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unchanged-2"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts the provider session when runtime mode changes", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-runtime-mode-1"),
role: "user",
text: "first",
attachments: [],
},
approvalPolicy: "never",
sandboxMode: "danger-full-access",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-runtime-mode-2"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.stopSession.mock.calls.length === 1);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ sessionId: asSessionId("sess-1") });
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
sessionId: asSessionId("sess-2"),
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-2");
expect(thread?.session?.approvalPolicy).toBe("on-request");
expect(thread?.session?.sandboxMode).toBe("workspace-write");
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-1"),
role: "user",
text: "first",
attachments: [],
},
approvalPolicy: "never",
sandboxMode: "danger-full-access",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
harness.startSession.mockImplementationOnce((_: unknown, __: unknown) =>
Effect.fail(new Error("simulated restart failure")) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-2"),
role: "user",
text: "second",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await Effect.runPromise(Effect.sleep("30 millis"));
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.sendTurn.mock.calls.length).toBe(1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.providerSessionId).toBe("sess-1");
expect(thread?.session?.approvalPolicy).toBe("never");
expect(thread?.session?.sandboxMode).toBe("danger-full-access");
});
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
@@ -203,6 +377,8 @@ describe("ProviderCommandReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: asTurnId("turn-1"),
lastError: null,
updatedAt: now,
@@ -242,6 +418,8 @@ describe("ProviderCommandReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: now,
@@ -284,6 +462,8 @@ describe("ProviderCommandReactor", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
lastError: null,
updatedAt: now,
@@ -3,9 +3,13 @@ import {
CommandId,
EventId,
type OrchestrationEvent,
type ProviderApprovalPolicy,
type ProviderKind,
type ProviderSandboxMode,
type OrchestrationSession,
type ThreadId,
type ProviderSession,
type ProviderThreadId,
type TurnId,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
@@ -60,6 +64,8 @@ const serverCommandId = (tag: string): CommandId =>
const HANDLED_TURN_START_KEY_MAX = 10_000;
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
@@ -128,6 +134,10 @@ const make = Effect.gen(function* () {
const ensureSessionForThread = Effect.fnUntraced(function* (
threadId: ThreadId,
createdAt: string,
options?: {
readonly approvalPolicy?: ProviderApprovalPolicy;
readonly sandboxMode?: ProviderSandboxMode;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
@@ -135,11 +145,10 @@ const make = Effect.gen(function* () {
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
}
const existingSessionId = thread.session?.providerSessionId;
if (existingSessionId) {
return existingSessionId;
}
const desiredApprovalPolicy =
options?.approvalPolicy ?? thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY;
const desiredSandboxMode =
options?.sandboxMode ?? thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE;
const preferredProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
? thread.session.providerName
@@ -149,28 +158,62 @@ const make = Effect.gen(function* () {
projects: readModel.projects,
});
const startedSession = yield* providerService.startSession(threadId, {
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(thread.model ? { model: thread.model } : {}),
});
const startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
providerService.startSession(threadId, {
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(thread.model ? { model: thread.model } : {}),
...(resumeThreadId ? { resumeThreadId } : {}),
approvalPolicy: desiredApprovalPolicy,
sandboxMode: desiredSandboxMode,
});
yield* setThreadSession({
threadId,
session: {
const bindSessionToThread = (session: ProviderSession) =>
setThreadSession({
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(startedSession.status),
providerName: startedSession.provider,
providerSessionId: startedSession.sessionId,
providerThreadId: startedSession.threadId ?? null,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: startedSession.lastError ?? null,
updatedAt: startedSession.updatedAt,
},
createdAt,
});
session: {
threadId,
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
providerName: session.provider,
providerSessionId: session.sessionId,
providerThreadId: session.threadId ?? null,
approvalPolicy: desiredApprovalPolicy,
sandboxMode: desiredSandboxMode,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
createdAt,
});
const existingSessionId = thread.session?.providerSessionId;
if (existingSessionId) {
const approvalPolicyChanged =
options?.approvalPolicy !== undefined && options.approvalPolicy !== thread.session?.approvalPolicy;
const sandboxModeChanged =
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
if (!approvalPolicyChanged && !sandboxModeChanged) {
return existingSessionId;
}
const restartedSession = yield* startProviderSession(thread.session?.providerThreadId ?? null);
yield* bindSessionToThread(restartedSession);
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to stop superseded provider session", {
threadId,
sessionId: existingSessionId,
cause: Cause.pretty(cause),
}),
),
);
return restartedSession.sessionId;
}
const startedSession = yield* startProviderSession();
yield* bindSessionToThread(startedSession);
return startedSession.sessionId;
});
@@ -180,13 +223,18 @@ const make = Effect.gen(function* () {
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly model?: string;
readonly effort?: string;
readonly approvalPolicy: ProviderApprovalPolicy;
readonly sandboxMode: ProviderSandboxMode;
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
if (!thread) {
return;
}
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt);
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
approvalPolicy: input.approvalPolicy,
sandboxMode: input.sandboxMode,
});
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
@@ -231,6 +279,8 @@ const make = Effect.gen(function* () {
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
approvalPolicy: event.payload.approvalPolicy,
sandboxMode: event.payload.sandboxMode,
createdAt: event.payload.createdAt,
});
});
@@ -307,6 +357,8 @@ const make = Effect.gen(function* () {
providerName: thread.session?.providerName ?? null,
providerSessionId: null,
providerThreadId: null,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
activeTurnId: null,
lastError: thread.session?.lastError ?? null,
updatedAt: now,
@@ -31,6 +31,8 @@ import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeInge
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId =>
ProviderThreadId.makeUnsafe(value);
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
@@ -164,6 +166,8 @@ describe("ProviderRuntimeIngestion", () => {
providerName: "codex",
providerSessionId: asSessionId("sess-1"),
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
@@ -218,6 +222,112 @@ describe("ProviderRuntimeIngestion", () => {
expect(thread.session?.lastError).toBe("turn failed");
});
it("ignores auxiliary turn completions from a different provider thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-primary"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
threadId: asProviderThreadId("provider-thread-1"),
turnId: asProviderTurnId("turn-primary"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-aux"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("provider-thread-aux"),
turnId: asProviderTurnId("turn-aux"),
status: "completed",
});
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-primary"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
threadId: asProviderThreadId("provider-thread-1"),
turnId: asProviderTurnId("turn-primary"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("ignores non-active turn completion when runtime omits thread id", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-guarded"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-guarded-main"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-guarded-main",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-other"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
turnId: asProviderTurnId("turn-guarded-other"),
status: "completed",
});
await Effect.runPromise(Effect.sleep("40 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-guarded-main"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: new Date().toISOString(),
turnId: asProviderTurnId("turn-guarded-main"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("maps message delta/completed into finalized assistant messages", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -332,6 +442,8 @@ describe("ProviderRuntimeIngestion", () => {
attachments: [],
},
assistantDeliveryMode: "streaming",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
@@ -3,6 +3,8 @@ import {
CommandId,
MessageId,
type OrchestrationEvent,
type ProviderApprovalPolicy,
type ProviderSandboxMode,
ProviderThreadId,
type ThreadId,
TurnId,
@@ -24,11 +26,14 @@ const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "on-request";
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
type TurnStartRequestedDomainEvent = Extract<
OrchestrationEvent,
@@ -49,6 +54,17 @@ function toTurnId(value: string | undefined): TurnId | undefined {
return value === undefined ? undefined : TurnId.makeUnsafe(value);
}
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
}
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
if (left === null || left === undefined || right === null || right === undefined) {
return false;
}
return left === right;
}
function truncateDetail(value: string, limit = 180): string {
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
}
@@ -328,6 +344,62 @@ const make = Effect.gen(function* () {
if (!thread) return;
const now = event.createdAt;
const sessionProviderThreadId = thread.session?.providerThreadId ?? null;
const eventProviderThreadId = toProviderThreadId(event.threadId);
const eventTurnId = toTurnId("turnId" in event ? event.turnId : undefined);
const activeTurnId = thread.session?.activeTurnId ?? null;
const matchesThreadScope =
eventProviderThreadId === null ||
sessionProviderThreadId === null ||
sameId(eventProviderThreadId, sessionProviderThreadId);
const conflictsWithActiveTurn =
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
}
switch (event.type) {
case "session.exited":
return true;
case "session.started":
case "thread.started":
if (!matchesThreadScope) {
return false;
}
// Never let auxiliary/provider-side spawned threads replace the primary thread binding.
if (
eventProviderThreadId !== null &&
sessionProviderThreadId !== null &&
!sameId(eventProviderThreadId, sessionProviderThreadId)
) {
return false;
}
return true;
case "turn.started":
if (!matchesThreadScope) {
return false;
}
return !conflictsWithActiveTurn;
case "turn.completed":
if (!matchesThreadScope) {
return false;
}
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
}
// Only the active turn may close the lifecycle state.
if (activeTurnId !== null && eventTurnId !== undefined) {
return sameId(activeTurnId, eventTurnId);
}
// Without an active turn, only accept completion when no thread mismatch signal exists.
return eventProviderThreadId === null || sessionProviderThreadId === null;
default:
return true;
}
})();
if (
event.type === "session.started" ||
@@ -336,8 +408,7 @@ const make = Effect.gen(function* () {
event.type === "turn.started" ||
event.type === "turn.completed"
) {
const activeTurnId =
event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
const nextActiveTurnId = event.type === "turn.started" ? (eventTurnId ?? null) : null;
const providerThreadIdFromEvent =
event.type === "thread.started"
? ProviderThreadId.makeUnsafe(event.threadId)
@@ -345,7 +416,7 @@ const make = Effect.gen(function* () {
? ProviderThreadId.makeUnsafe(event.threadId)
: null;
const providerThreadId =
providerThreadIdFromEvent ?? thread.session?.providerThreadId ?? null;
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
const status =
event.type === "turn.started"
? "running"
@@ -361,22 +432,26 @@ const make = Effect.gen(function* () {
? null
: (thread.session?.lastError ?? null);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
threadId: thread.id,
session: {
if (shouldApplyThreadLifecycle) {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "thread-session-set"),
threadId: thread.id,
status,
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
activeTurnId,
lastError,
updatedAt: now,
},
createdAt: now,
});
session: {
threadId: thread.id,
status,
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
activeTurnId: nextActiveTurnId,
lastError,
updatedAt: now,
},
createdAt: now,
});
}
}
if (event.type === "message.delta" && event.delta.length > 0) {
@@ -464,27 +539,38 @@ const make = Effect.gen(function* () {
}
if (event.type === "runtime.error") {
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
? true
: matchesThreadScope &&
(activeTurnId === null ||
eventTurnId === undefined ||
sameId(activeTurnId, eventTurnId));
const providerThreadId =
event.threadId !== undefined
? ProviderThreadId.makeUnsafe(event.threadId)
: (thread.session?.providerThreadId ?? null);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "runtime-error-session-set"),
threadId: thread.id,
session: {
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: providerCommandId(event, "runtime-error-session-set"),
threadId: thread.id,
status: "error",
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
activeTurnId: toTurnId(event.turnId) ?? null,
lastError: event.message,
updatedAt: now,
},
createdAt: now,
});
session: {
threadId: thread.id,
status: "error",
providerName: event.provider,
providerSessionId: event.sessionId,
providerThreadId,
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
activeTurnId: eventTurnId ?? null,
lastError: event.message,
updatedAt: now,
},
createdAt: now,
});
}
}
const activities = runtimeEventToActivities(event);
@@ -54,7 +54,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
latestTurnId: null,
latestTurn: null,
messages: [],
session: null,
activities: [],
@@ -70,7 +70,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
latestTurnId: null,
latestTurn: null,
messages: [],
session: null,
activities: [],
@@ -90,6 +90,8 @@ const messageSendCommand: OrchestrationCommand = {
text: "hello",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
};
@@ -152,6 +152,8 @@ describe("decider project scripts", () => {
},
model: "gpt-5",
effort: "high",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
},
readModel,
@@ -169,5 +171,13 @@ describe("decider project scripts", () => {
return;
}
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: asMessageId("message-user-1"),
model: "gpt-5",
effort: "high",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
});
});
});
+2
View File
@@ -254,6 +254,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.model !== undefined ? { model: command.model } : {}),
...(command.effort !== undefined ? { effort: command.effort } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
approvalPolicy: command.approvalPolicy,
sandboxMode: command.sandboxMode,
createdAt: command.createdAt,
},
};
@@ -75,7 +75,7 @@ describe("orchestration projector", () => {
model: "gpt-5-codex",
branch: null,
worktreePath: null,
latestTurnId: null,
latestTurn: null,
createdAt: now,
updatedAt: now,
deletedAt: null,
@@ -135,6 +135,8 @@ describe("orchestration projector", () => {
payload: {
threadId: "thread-1",
messageId: "message-1",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: "2026-01-01T00:00:00.000Z",
},
}),
@@ -193,6 +195,8 @@ describe("orchestration projector", () => {
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
@@ -203,7 +207,7 @@ describe("orchestration projector", () => {
);
const thread = afterRunning.threads[0];
expect(thread?.latestTurnId).toBe("turn-1");
expect(thread?.latestTurn?.turnId).toBe("turn-1");
expect(thread?.session?.status).toBe("running");
});
@@ -500,7 +504,7 @@ describe("orchestration projector", () => {
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
expect(thread?.latestTurnId).toBe("turn-1");
expect(thread?.latestTurn?.turnId).toBe("turn-1");
});
it("does not fallback-retain messages tied to removed turn IDs", async () => {
+54 -6
View File
@@ -26,6 +26,12 @@ type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
const MAX_THREAD_MESSAGES = 2_000;
const MAX_THREAD_CHECKPOINTS = 500;
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
if (status === "error") return "error" as const;
if (status === "missing") return "interrupted" as const;
return "completed" as const;
}
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: ThreadId,
@@ -220,7 +226,7 @@ export function projectEvent(
model: payload.model,
branch: payload.branch,
worktreePath: payload.worktreePath,
latestTurnId: null,
latestTurn: null,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
deletedAt: null,
@@ -351,7 +357,26 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
session,
latestTurnId: session.activeTurnId,
latestTurn:
session.status === "running" && session.activeTurnId !== null
? {
turnId: session.activeTurnId,
state: "running",
requestedAt:
thread.latestTurn?.turnId === session.activeTurnId
? thread.latestTurn.requestedAt
: session.updatedAt,
startedAt:
thread.latestTurn?.turnId === session.activeTurnId
? (thread.latestTurn.startedAt ?? session.updatedAt)
: session.updatedAt,
completedAt: null,
assistantMessageId:
thread.latestTurn?.turnId === session.activeTurnId
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -396,7 +421,20 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
checkpoints,
latestTurnId: payload.turnId,
latestTurn: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
updatedAt: event.occurredAt,
}),
};
@@ -422,8 +460,18 @@ export function projectEvent(
).slice(-MAX_THREAD_MESSAGES);
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
const latestTurnId =
checkpoints.length > 0 ? (checkpoints[checkpoints.length - 1]?.turnId ?? null) : null;
const latestCheckpoint = checkpoints.at(-1) ?? null;
const latestTurn =
latestCheckpoint === null
? null
: {
turnId: latestCheckpoint.turnId,
state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
requestedAt: latestCheckpoint.completedAt,
startedAt: latestCheckpoint.completedAt,
completedAt: latestCheckpoint.completedAt,
assistantMessageId: latestCheckpoint.assistantMessageId,
};
return {
...nextBase,
@@ -431,7 +479,7 @@ export function projectEvent(
checkpoints,
messages,
activities,
latestTurnId,
latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -25,6 +25,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
provider_name,
provider_session_id,
provider_thread_id,
approval_policy,
sandbox_mode,
active_turn_id,
last_error,
updated_at
@@ -35,6 +37,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
${row.providerName},
${row.providerSessionId},
${row.providerThreadId},
${row.approvalPolicy},
${row.sandboxMode},
${row.activeTurnId},
${row.lastError},
${row.updatedAt}
@@ -45,6 +49,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
provider_name = excluded.provider_name,
provider_session_id = excluded.provider_session_id,
provider_thread_id = excluded.provider_thread_id,
approval_policy = excluded.approval_policy,
sandbox_mode = excluded.sandbox_mode,
active_turn_id = excluded.active_turn_id,
last_error = excluded.last_error,
updated_at = excluded.updated_at
@@ -62,6 +68,8 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
provider_name AS "providerName",
provider_session_id AS "providerSessionId",
provider_thread_id AS "providerThreadId",
approval_policy AS "approvalPolicy",
sandbox_mode AS "sandboxMode",
active_turn_id AS "activeTurnId",
last_error AS "lastError",
updated_at AS "updatedAt"
@@ -17,6 +17,7 @@ import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
import Migration0005 from "./Migrations/005_Projections.ts";
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
/**
* Migration loader with all migrations defined inline.
@@ -34,6 +35,7 @@ const loader = Migrator.fromRecord({
"3_CheckpointDiffBlobs": Migration0003,
"4_ProviderSessionRuntime": Migration0004,
"5_Projections": Migration0005,
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
});
/**
@@ -0,0 +1,30 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
const DEFAULT_APPROVAL_POLICY = "never";
const DEFAULT_SANDBOX_MODE = "workspace-write";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_sessions
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
`;
yield* sql`
ALTER TABLE projection_thread_sessions
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
`;
yield* sql`
UPDATE projection_thread_sessions
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
WHERE approval_policy IS NULL
`;
yield* sql`
UPDATE projection_thread_sessions
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
WHERE sandbox_mode IS NULL
`;
});
@@ -4,23 +4,27 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqliteClient from "./NodeSqliteClient.ts";
it.effect("runs prepared queries and returns positional values", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const layer = it.layer(SqliteClient.layerMemory());
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
layer("NodeSqliteClient", (it) => {
it.effect("runs prepared queries and returns positional values", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
SELECT id, name FROM entries ORDER BY id
`;
assert.equal(rows.length, 2);
assert.equal(rows[0]?.name, "alpha");
assert.equal(rows[1]?.name, "beta");
assert.equal(rows.length, 2);
assert.equal(rows[0]?.name, "alpha");
assert.equal(rows[1]?.name, "beta");
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
assert.equal(values.length, 2);
assert.equal(values[0]?.[1], "alpha");
assert.equal(values[1]?.[1], "beta");
}).pipe(Effect.provide(SqliteClient.layerMemory())),
);
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
assert.equal(values.length, 2);
assert.equal(values[0]?.[1], "alpha");
assert.equal(values[1]?.[1], "beta");
}),
);
});
@@ -9,6 +9,8 @@
import {
IsoDateTime,
OrchestrationSessionStatus,
ProviderApprovalPolicy,
ProviderSandboxMode,
ProviderSessionId,
ProviderThreadId,
ThreadId,
@@ -25,6 +27,8 @@ export const ProjectionThreadSession = Schema.Struct({
providerName: Schema.NullOr(Schema.String),
providerSessionId: Schema.NullOr(ProviderSessionId),
providerThreadId: Schema.NullOr(ProviderThreadId),
approvalPolicy: ProviderApprovalPolicy,
sandboxMode: ProviderSandboxMode,
activeTurnId: Schema.NullOr(TurnId),
lastError: Schema.NullOr(Schema.String),
updatedAt: IsoDateTime,
+155
View File
@@ -0,0 +1,155 @@
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
interface HttpResponse {
statusCode: number;
contentType: string | null;
body: string;
}
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function withRouteServer(
run: (baseUrl: string) => Promise<void>,
): Promise<void> {
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (tryHandleProjectFaviconRequest(url, res)) {
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
});
await new Promise<void>((resolve, reject) => {
server.listen(0, "127.0.0.1", (error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
const address = server.address();
if (typeof address !== "object" || address === null) {
throw new Error("Expected server address to be an object");
}
const baseUrl = `http://127.0.0.1:${address.port}`;
try {
await run(baseUrl);
} finally {
await new Promise<void>((resolve, reject) => {
server.close((error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
}
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
const response = await fetch(`${baseUrl}${pathname}`);
return {
statusCode: response.status,
contentType: response.headers.get("content-type"),
body: await response.text(),
};
}
describe("tryHandleProjectFaviconRequest", () => {
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("returns 400 when cwd is missing", async () => {
await withRouteServer(async (baseUrl) => {
const response = await request(baseUrl, "/api/project-favicon");
expect(response.statusCode).toBe(400);
expect(response.body).toBe("Missing cwd parameter");
});
});
it("serves a well-known favicon file from the project root", async () => {
const projectDir = makeTempDir("t3code-favicon-route-root-");
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>favicon</svg>");
});
});
it("resolves icon href from source files when no well-known favicon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-source-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(path.join(projectDir, "index.html"), '<link rel="icon" href="/brand/logo.svg">');
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand</svg>");
});
});
it("resolves icon link when href appears before rel in HTML", async () => {
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(path.join(projectDir, "index.html"), '<link href="/brand/logo.svg" rel="icon">');
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand-html-order</svg>");
});
});
it("resolves object-style icon metadata when href appears before rel", async () => {
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
fs.writeFileSync(
path.join(projectDir, "src", "root.tsx"),
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
"utf8",
);
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand-obj-order</svg>");
});
});
});
+162
View File
@@ -0,0 +1,162 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
const FAVICON_MIME_TYPES: Record<string, string> = {
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
};
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
"favicon.svg",
"favicon.ico",
"favicon.png",
"public/favicon.svg",
"public/favicon.ico",
"public/favicon.png",
"app/favicon.ico",
"app/favicon.png",
"app/icon.svg",
"app/icon.png",
"app/icon.ico",
"src/favicon.ico",
"src/favicon.svg",
"src/app/favicon.ico",
"src/app/icon.svg",
"src/app/icon.png",
"assets/icon.svg",
"assets/icon.png",
"assets/logo.svg",
"assets/logo.png",
];
// Files that may contain a <link rel="icon"> or icon metadata declaration.
const ICON_SOURCE_FILES = [
"index.html",
"public/index.html",
"app/routes/__root.tsx",
"src/routes/__root.tsx",
"app/root.tsx",
"src/root.tsx",
"src/index.html",
];
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
const LINK_ICON_HTML_RE =
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
const LINK_ICON_OBJ_RE =
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
function extractIconHref(source: string): string | null {
const htmlMatch = source.match(LINK_ICON_HTML_RE);
if (htmlMatch?.[1]) return htmlMatch[1];
const objMatch = source.match(LINK_ICON_OBJ_RE);
if (objMatch?.[1]) return objMatch[1];
return null;
}
function resolveIconHref(projectCwd: string, href: string): string[] {
const clean = href.replace(/^\//, "");
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
}
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
const ext = path.extname(filePath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Read error");
return;
}
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
});
res.end(data);
});
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
}
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing cwd parameter");
return true;
}
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
if (index >= paths.length) {
onExhausted();
return;
}
const candidate = paths[index]!;
if (!isPathWithinProject(projectCwd, candidate)) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
serveFaviconFile(candidate, res);
});
};
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("No favicon found");
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
fs.readFile(sourceFile, "utf8", (err, content) => {
if (err) {
trySourceFiles(index + 1);
return;
}
const href = extractIconHref(content);
if (!href) {
trySourceFiles(index + 1);
return;
}
const candidates = resolveIconHref(projectCwd, href);
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
});
};
const tryCandidates = (index: number): void => {
if (index >= FAVICON_CANDIDATES.length) {
trySourceFiles(0);
return;
}
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
if (!isPathWithinProject(projectCwd, candidate)) {
tryCandidates(index + 1);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryCandidates(index + 1);
return;
}
serveFaviconFile(candidate, res);
});
};
tryCandidates(0);
return true;
}
@@ -47,6 +47,7 @@ import {
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
@@ -564,7 +565,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
status: "completed",
};
@@ -612,7 +613,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
toolKind: "command",
title: "Command run",
@@ -624,7 +625,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
delta: "hello",
},
@@ -634,7 +635,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
provider: "codex",
sessionId: session.sessionId,
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
threadId: asProviderThreadId("thread-1"),
turnId: asTurnId("turn-1"),
status: "completed",
},
+100 -3
View File
@@ -3,6 +3,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
@@ -38,7 +39,7 @@ import type {
TerminalWriteInput,
} from "@t3tools/contracts";
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { SqlClient } from "effect/unstable/sql";
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
import { Open, type OpenShape } from "./open";
@@ -448,23 +449,117 @@ describe("WebSocket Server", () => {
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws); // welcome
const welcome = (await waitForMessage(ws)) as WsPush; // welcome
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
expect(welcome.data).toEqual(
expect.objectContaining({
cwd: "/test/bootstrap-workspace",
projectName: "bootstrap-workspace",
bootstrapProjectId: expect.any(String),
bootstrapThreadId: expect.any(String),
}),
);
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
expect(snapshotResponse.error).toBeUndefined();
const snapshot = snapshotResponse.result as {
projects: Array<{ workspaceRoot: string; title: string; defaultModel: string | null }>;
projects: Array<{
id: string;
workspaceRoot: string;
title: string;
defaultModel: string | null;
}>;
threads: Array<{
id: string;
projectId: string;
title: string;
model: string;
branch: string | null;
worktreePath: string | null;
}>;
};
const bootstrapProjectId = (welcome.data as { bootstrapProjectId?: string }).bootstrapProjectId;
const bootstrapThreadId = (welcome.data as { bootstrapThreadId?: string }).bootstrapThreadId;
expect(bootstrapProjectId).toBeDefined();
expect(bootstrapThreadId).toBeDefined();
expect(snapshot.projects).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: bootstrapProjectId,
workspaceRoot: "/test/bootstrap-workspace",
title: "bootstrap-workspace",
defaultModel: "gpt-5-codex",
}),
]),
);
expect(snapshot.threads).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: bootstrapThreadId,
projectId: bootstrapProjectId,
title: "New thread",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
}),
]),
);
});
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
const persistenceLayer = makeSqlitePersistenceLive(
path.join(stateDir, "state.sqlite"),
).pipe(Layer.provide(NodeServices.layer)) as unknown as Layer.Layer<SqlClient.SqlClient, never>;
const cwd = "/test/bootstrap-existing";
server = await createTestServer({
cwd,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
let addr = server.address();
let port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const firstWs = await connectWs(port);
connections.push(firstWs);
const firstWelcome = (await waitForMessage(firstWs)) as WsPush;
const firstBootstrapProjectId = (firstWelcome.data as { bootstrapProjectId?: string })
.bootstrapProjectId;
const firstBootstrapThreadId = (firstWelcome.data as { bootstrapThreadId?: string })
.bootstrapThreadId;
expect(firstBootstrapProjectId).toBeDefined();
expect(firstBootstrapThreadId).toBeDefined();
firstWs.close();
await closeTestServer();
server = null;
server = await createTestServer({
cwd,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
addr = server.address();
port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
const secondWs = await connectWs(port);
connections.push(secondWs);
const secondWelcome = (await waitForMessage(secondWs)) as WsPush;
expect(secondWelcome.channel).toBe(WS_CHANNELS.serverWelcome);
expect(secondWelcome.data).toEqual(
expect.objectContaining({
cwd,
projectName: "bootstrap-existing",
bootstrapProjectId: firstBootstrapProjectId,
bootstrapThreadId: firstBootstrapThreadId,
}),
);
});
it("logs outbound websocket push events in dev mode", async () => {
@@ -960,6 +1055,8 @@ describe("WebSocket Server", () => {
attachments: [],
},
assistantDeliveryMode: "streaming",
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt,
});
expect(startTurnResponse.error).toBeUndefined();
+57 -8
View File
@@ -16,6 +16,7 @@ import {
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
ProjectId,
ThreadId,
TerminalEvent,
WS_CHANNELS,
WS_METHODS,
@@ -41,6 +42,7 @@ import { clamp } from "effect/Number";
import { Open } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -231,6 +233,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
// HTTP server — serves static files or redirects to Vite dev server
const httpServer = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
if (tryHandleProjectFaviconRequest(url, res)) {
return;
}
// In dev mode, redirect to Vite dev server
if (devUrl) {
res.writeHead(302, { Location: devUrl.href });
@@ -245,7 +253,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
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
@@ -337,22 +344,59 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
let welcomeBootstrapProjectId: ProjectId | undefined;
let welcomeBootstrapThreadId: ThreadId | undefined;
if (autoBootstrapProjectFromCwd) {
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
if (!existing) {
const existingProject = snapshot.projects.find(
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
);
let bootstrapProjectId: ProjectId;
let bootstrapProjectDefaultModel: string;
if (!existingProject) {
const createdAt = new Date().toISOString();
const projectName = path.basename(cwd) || "project";
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(cwd) || "project";
bootstrapProjectDefaultModel = "gpt-5-codex";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
title: projectName,
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
defaultModel: "gpt-5-codex",
defaultModel: bootstrapProjectDefaultModel,
createdAt,
});
} else {
bootstrapProjectId = existingProject.id;
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
}
const existingThread = snapshot.threads.find(
(thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
);
if (!existingThread) {
const createdAt = new Date().toISOString();
const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
yield* orchestrationEngine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
threadId,
projectId: bootstrapProjectId,
title: "New thread",
model: bootstrapProjectDefaultModel,
branch: null,
worktreePath: null,
createdAt,
});
welcomeBootstrapProjectId = bootstrapProjectId;
welcomeBootstrapThreadId = threadId;
} else {
welcomeBootstrapProjectId = bootstrapProjectId;
welcomeBootstrapThreadId = existingThread.id;
}
}).pipe(
Effect.mapError(
@@ -581,7 +625,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const welcome: WsPush = {
type: "push",
channel: WS_CHANNELS.serverWelcome,
data: { cwd, projectName },
data: {
cwd,
projectName,
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
},
};
logOutgoingPush(welcome, 1);
ws.send(JSON.stringify(welcome));
+3 -1
View File
@@ -14,7 +14,9 @@
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
"deterministicKeys": "warning",
"preferSchemaOverJson": "off",
"globalErrorInEffectFailure": "off"
}
}
]
+102 -51
View File
@@ -43,7 +43,8 @@ import {
deriveTimelineEntries,
type PendingApproval,
deriveWorkLogEntries,
formatDuration,
hasToolActivityForTurn,
isLatestTurnSettled,
formatElapsed,
formatTimestamp,
} from "../session-logic";
@@ -83,6 +84,8 @@ import {
LockOpenIcon,
Undo2Icon,
XIcon,
CopyIcon,
CheckIcon,
} from "lucide-react";
import { Button } from "./ui/button";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
@@ -368,6 +371,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const sendInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -378,12 +382,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const diffOpen = diffSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
useEffect(() => {
if (!activeThread?.id) return;
if (!activeThread.latestTurnCompletedAt) return;
const turnCompletedAt = Date.parse(activeThread.latestTurnCompletedAt);
if (!latestTurnSettled) return;
if (!activeLatestTurn?.completedAt) return;
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnCompletedAt)) return;
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
@@ -395,7 +402,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [
activeThread?.id,
activeThread?.lastVisitedAt,
activeThread?.latestTurnCompletedAt,
activeLatestTurn?.completedAt,
latestTurnSettled,
dispatch,
]);
@@ -409,18 +417,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const nowIso = new Date(nowTick).toISOString();
const threadActivities = activeThread?.activities ?? [];
const workLogEntries = useMemo(
() => deriveWorkLogEntries(threadActivities, undefined),
[threadActivities],
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
[activeLatestTurn?.turnId, threadActivities],
);
const latestTurnHasToolActivity = useMemo(() => {
const latestTurnId = activeThread?.latestTurnId;
if (!latestTurnId) {
return false;
}
return threadActivities.some(
(activity) => activity.turnId === latestTurnId && activity.tone === "tool",
);
}, [activeThread?.latestTurnId, threadActivities]);
return hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId);
}, [activeLatestTurn?.turnId, threadActivities]);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
[threadActivities],
@@ -485,36 +487,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
const completionSummary = useMemo(() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
if (!latestTurnSettled) return null;
if (!activeLatestTurn?.startedAt) return null;
if (!activeLatestTurn.completedAt) return null;
if (!latestTurnHasToolActivity) 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,
);
const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt);
return elapsed ? `Worked for ${elapsed}` : null;
}, [
activeThread?.latestTurnStartedAt,
activeThread?.latestTurnCompletedAt,
activeThread?.latestTurnDurationMs,
activeLatestTurn?.completedAt,
activeLatestTurn?.startedAt,
latestTurnHasToolActivity,
latestTurnSettled,
]);
const completionDividerBeforeEntryId = useMemo(() => {
if (!activeThread?.latestTurnStartedAt) return null;
if (!activeThread.latestTurnCompletedAt) return null;
if (!latestTurnSettled) return null;
if (!activeLatestTurn?.startedAt) return null;
if (!activeLatestTurn.completedAt) return null;
if (!completionSummary) return null;
const turnStartedAt = Date.parse(activeThread.latestTurnStartedAt);
const turnCompletedAt = Date.parse(activeThread.latestTurnCompletedAt);
const turnStartedAt = Date.parse(activeLatestTurn.startedAt);
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnStartedAt)) return null;
if (Number.isNaN(turnCompletedAt)) return null;
@@ -532,9 +525,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return inRangeMatch ?? fallbackMatch;
}, [
activeThread?.latestTurnCompletedAt,
activeThread?.latestTurnStartedAt,
activeLatestTurn?.completedAt,
activeLatestTurn?.startedAt,
completionSummary,
latestTurnSettled,
timelineEntries,
]);
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
@@ -1391,7 +1385,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
e.preventDefault();
const api = readNativeApi();
if (!api || !activeThread || isSendBusy || isConnecting) return;
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
const trimmed = prompt.trim();
if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return;
@@ -1401,6 +1395,23 @@ export default function ChatView({ threadId }: ChatViewProps) {
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
? activeThread.branch
: null;
// In worktree mode, require an explicit base branch so we don't silently
// fall back to local execution when branch selection is missing.
const shouldCreateWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
if (shouldCreateWorktree && !activeThread.branch) {
dispatch({
type: "SET_ERROR",
threadId: threadIdForSend,
error: "Select a base branch before sending in New worktree mode.",
});
return;
}
sendInFlightRef.current = true;
setSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
const composerImagesSnapshot = [...composerImages];
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
@@ -1449,9 +1460,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
void runProjectScript(setupScript, {
await runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path,
rememberAsLastInvoked: false,
@@ -1496,6 +1515,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
),
);
attemptedTurnStart = true;
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
const sandboxMode =
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
@@ -1509,6 +1531,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
model: selectedModel || undefined,
effort: selectedEffort || undefined,
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
approvalPolicy,
sandboxMode,
createdAt: messageCreatedAt,
});
} catch (err) {
@@ -1530,6 +1554,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
err instanceof Error ? err.message : "Failed to send message.",
);
} finally {
sendInFlightRef.current = false;
setSendPhase("idle");
}
};
@@ -2301,6 +2326,28 @@ const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
);
});
const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
const handleCopy = useCallback(() => {
void navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [text]);
return (
<Button
type="button"
size="xs"
variant="outline"
onClick={handleCopy}
title="Copy message"
>
{copied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
</Button>
);
});
interface MessagesTimelineProps {
hasMessages: boolean;
isWorking: boolean;
@@ -2517,7 +2564,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
return (
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
<div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map(
@@ -2551,17 +2598,21 @@ const MessagesTimeline = memo(function MessagesTimeline({
</pre>
)}
<div className="mt-1.5 flex items-center justify-end gap-2">
{canRevertAgentWork && (
<Button
type="button"
size="xs"
variant="outline"
disabled={isRevertingCheckpoint || isWorking}
onClick={() => onRevertUserMessage(row.message.id)}
>
<Undo2Icon className="size-3" />
</Button>
)}
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
{row.message.text && <MessageCopyButton text={row.message.text} />}
{canRevertAgentWork && (
<Button
type="button"
size="xs"
variant="outline"
disabled={isRevertingCheckpoint || isWorking}
onClick={() => onRevertUserMessage(row.message.id)}
title="Revert to this message"
>
<Undo2Icon className="size-3" />
</Button>
)}
</div>
<p className="text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(row.message.createdAt)}
</p>
+8 -2
View File
@@ -16,7 +16,11 @@ import { useStore } from "../store";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
type DiffRenderMode = "stacked" | "split";
type DiffThemeType = "light" | "dark" | "system";
type DiffThemeType = "light" | "dark";
function resolveDiffThemeName(theme: "light" | "dark") {
return theme === "dark" ? "pierre-dark" : "pierre-light";
}
type RenderablePatch =
| {
@@ -472,13 +476,15 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
{renderableFiles.map((fileDiff) => {
const filePath = resolveFileDiffPath(fileDiff);
const fileKey = buildFileDiffRenderKey(fileDiff);
const themedFileKey = `${fileKey}:${resolvedTheme}`;
return (
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
<div key={themedFileKey} data-diff-file-path={filePath} className="rounded-md">
<FileDiff
fileDiff={fileDiff}
options={{
diffStyle: diffRenderMode === "split" ? "split" : "unified",
lineDiffType: "none",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme as DiffThemeType,
}}
/>
@@ -1,8 +1,39 @@
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
import { useMemo, type ReactNode } from "react";
import { useEffect, useMemo, type ReactNode } from "react";
import { useTheme } from "../hooks/useTheme";
function resolveDiffThemeName(theme: "light" | "dark") {
return theme === "dark" ? "pierre-dark" : "pierre-light";
}
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
const workerPool = useWorkerPool();
useEffect(() => {
if (!workerPool) {
return;
}
const current = workerPool.getDiffRenderOptions();
if (current.theme === themeName) {
return;
}
void workerPool
.setRenderOptions({
...current,
theme: themeName,
})
.catch(() => undefined);
}, [themeName, workerPool]);
return null;
}
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
const { resolvedTheme } = useTheme();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const workerPoolSize = useMemo(() => {
const cores =
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
@@ -17,9 +48,11 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
totalASTLRUCacheSize: 240,
}}
highlighterOptions={{
theme: diffThemeName,
tokenizeMaxLineLength: 1_000,
}}
>
<DiffWorkerThemeSync themeName={diffThemeName} />
{children}
</WorkerPoolContextProvider>
);
+58 -6
View File
@@ -1,4 +1,4 @@
import { ChevronRightIcon, TerminalIcon } from "lucide-react";
import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
DEFAULT_MODEL,
@@ -15,6 +15,7 @@ import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { type Thread } from "../types";
import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
@@ -50,7 +51,7 @@ function formatRelativeTime(iso: string): string {
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
label: "Working" | "Connecting" | "Completed" | "Pending Approval";
colorClass: string;
dotClass: string;
pulse: boolean;
@@ -63,8 +64,8 @@ interface TerminalStatusIndicator {
}
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurnCompletedAt) return false;
const completedAt = Date.parse(thread.latestTurnCompletedAt);
if (!thread.latestTurn?.completedAt) return false;
const completedAt = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
@@ -76,7 +77,7 @@ function hasUnseenCompletion(thread: Thread): boolean {
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
if (hasPendingApprovals) {
return {
label: "Awaiting response",
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
@@ -140,6 +141,50 @@ function T3Wordmark() {
);
}
/**
* Derives the server's HTTP origin (scheme + host + port) from the same
* sources WsTransport uses, converting ws(s) to http(s).
*/
function getServerHttpOrigin(): string {
const bridgeUrl = window.desktopBridge?.getWsUrl();
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsUrl =
bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `ws://${window.location.hostname}:${window.location.port}`;
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
try {
return new URL(httpUrl).origin;
} catch {
return httpUrl;
}
}
const serverHttpOrigin = getServerHttpOrigin();
function ProjectFavicon({ cwd }: { cwd: string }) {
const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
if (status === "error") {
return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
}
return (
<img
src={src}
alt=""
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
onLoad={() => setStatus("loaded")}
onError={() => setStatus("error")}
/>
);
}
export default function Sidebar() {
const { state, dispatch } = useStore();
const navigate = useNavigate();
@@ -158,7 +203,13 @@ export default function Sidebar() {
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => new Map<ThreadId, boolean>(), []);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
}
return map;
}, [state.threads]);
const handleNewThread = useCallback(
(
@@ -566,6 +617,7 @@ export default function Sidebar() {
project.expanded ? "rotate-90" : ""
}`}
/>
<ProjectFavicon cwd={project.cwd} />
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
+18 -4
View File
@@ -1,11 +1,16 @@
import { useCallback, useEffect, useSyncExternalStore } from "react";
type Theme = "light" | "dark" | "system";
type ThemeSnapshot = {
theme: Theme;
systemDark: boolean;
};
const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
function emitChange() {
for (const listener of listeners) listener();
}
@@ -39,8 +44,16 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
// Apply immediately on module load to prevent flash
applyTheme(getStored());
function getSnapshot(): Theme {
return getStored();
function getSnapshot(): ThemeSnapshot {
const theme = getStored();
const systemDark = theme === "system" ? getSystemDark() : false;
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
return lastSnapshot;
}
lastSnapshot = { theme, systemDark };
return lastSnapshot;
}
function subscribe(listener: () => void): () => void {
@@ -71,10 +84,11 @@ function subscribe(listener: () => void): () => void {
}
export function useTheme() {
const theme = useSyncExternalStore(subscribe, getSnapshot);
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
const theme = snapshot.theme;
const resolvedTheme: "light" | "dark" =
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
const setTheme = useCallback((next: Theme) => {
localStorage.setItem(STORAGE_KEY, next);
+42 -4
View File
@@ -1,5 +1,11 @@
import { ThreadId } from "@t3tools/contracts";
import { Outlet, createRootRouteWithContext, type ErrorComponentProps } from "@tanstack/react-router";
import {
Outlet,
createRootRouteWithContext,
type ErrorComponentProps,
useNavigate,
useRouterState,
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
@@ -119,7 +125,12 @@ function errorDetails(error: unknown): string {
function EventRouter() {
const { dispatch } = useStore();
const queryClient = useQueryClient();
const navigate = useNavigate();
const pathname = useRouterState({ select: (state) => state.location.pathname });
const pathnameRef = useRef(pathname);
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
pathnameRef.current = pathname;
useEffect(() => {
const api = readNativeApi();
@@ -180,8 +191,35 @@ function EventRouter() {
hasRunningSubprocess,
});
});
const unsubWelcome = onServerWelcome(() => {
void syncSnapshot();
const unsubWelcome = onServerWelcome((payload) => {
void (async () => {
await syncSnapshot();
if (disposed) {
return;
}
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
dispatch({
type: "SET_PROJECT_EXPANDED",
projectId: payload.bootstrapProjectId,
expanded: true,
});
if (pathnameRef.current !== "/") {
return;
}
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
return;
}
await navigate({
to: "/$threadId",
params: { threadId: payload.bootstrapThreadId },
replace: true,
});
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
})().catch(() => undefined);
});
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
const signature = JSON.stringify(payload.issues);
@@ -232,7 +270,7 @@ function EventRouter() {
unsubWelcome();
unsubServerConfigUpdated();
};
}, [dispatch, queryClient]);
}, [dispatch, navigate, queryClient]);
return null;
}
+2 -2
View File
@@ -179,7 +179,7 @@ function ChatThreadRouteView() {
if (!shouldUseDiffSheet) {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView threadId={threadId} />
</SidebarInset>
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
@@ -189,7 +189,7 @@ function ChatThreadRouteView() {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView threadId={threadId} />
</SidebarInset>
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
+75 -1
View File
@@ -1,7 +1,12 @@
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { derivePendingApprovals, deriveWorkLogEntries } from "./session-logic";
import {
derivePendingApprovals,
deriveWorkLogEntries,
hasToolActivityForTurn,
isLatestTurnSettled,
} from "./session-logic";
function makeActivity(overrides: {
id?: string;
@@ -126,3 +131,72 @@ describe("deriveWorkLogEntries", () => {
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
});
});
describe("hasToolActivityForTurn", () => {
it("returns false when turn id is missing", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
];
expect(hasToolActivityForTurn(activities, undefined)).toBe(false);
expect(hasToolActivityForTurn(activities, null)).toBe(false);
});
it("returns true only for matching tool activity in the target turn", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
];
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-1"))).toBe(true);
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-2"))).toBe(false);
});
});
describe("isLatestTurnSettled", () => {
const latestTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
startedAt: "2026-02-27T21:10:00.000Z",
completedAt: "2026-02-27T21:10:06.000Z",
} as const;
it("returns false while the same turn is still active in a running session", () => {
expect(
isLatestTurnSettled(latestTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
}),
).toBe(false);
});
it("returns false while any turn is running to avoid stale latest-turn banners", () => {
expect(
isLatestTurnSettled(latestTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-2"),
}),
).toBe(false);
});
it("returns true once the session is no longer running that turn", () => {
expect(
isLatestTurnSettled(latestTurn, {
orchestrationStatus: "ready",
activeTurnId: undefined,
}),
).toBe(true);
});
it("returns false when turn timestamps are incomplete", () => {
expect(
isLatestTurnSettled(
{
turnId: TurnId.makeUnsafe("turn-1"),
startedAt: null,
completedAt: "2026-02-27T21:10:06.000Z",
},
null,
),
).toBe(false);
});
});
+20
View File
@@ -1,5 +1,6 @@
import {
ApprovalRequestId,
type OrchestrationLatestTurn,
type OrchestrationThreadActivity,
type ProviderKind,
type TurnId,
@@ -75,6 +76,17 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
return formatDuration(endedAt - startedAt);
}
export function isLatestTurnSettled(
latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt"> | null,
session: Pick<ThreadSession, "orchestrationStatus" | "activeTurnId"> | null,
): boolean {
if (!latestTurn?.startedAt) return false;
if (!latestTurn.completedAt) return false;
if (!session) return true;
if (session.orchestrationStatus === "running") return false;
return true;
}
export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
@@ -147,6 +159,14 @@ export function deriveWorkLogEntries(
});
}
export function hasToolActivityForTurn(
activities: ReadonlyArray<OrchestrationThreadActivity>,
turnId: TurnId | null | undefined,
): boolean {
if (!turnId) return false;
return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
}
export function deriveTimelineEntries(
messages: ChatMessage[],
workEntries: WorkLogEntry[],
+11 -3
View File
@@ -1,4 +1,4 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { reducer, type AppState } from "./store";
@@ -29,6 +29,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
activities: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
latestTurn: null,
branch: null,
worktreePath: null,
...overrides,
@@ -58,7 +59,14 @@ describe("store reducer", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
latestTurnCompletedAt,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-25T12:28:00.000Z",
startedAt: "2026-02-25T12:28:30.000Z",
completedAt: latestTurnCompletedAt,
assistantMessageId: null,
},
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
@@ -79,7 +87,7 @@ describe("store reducer", () => {
it("does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurnCompletedAt: undefined,
latestTurn: null,
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
+12 -19
View File
@@ -41,6 +41,7 @@ type Action =
terminalId: string;
hasRunningSubprocess: boolean;
}
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
@@ -413,19 +414,6 @@ export function reducer(state: AppState, action: Action): AppState {
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
const existing = existingThreadById.get(thread.id);
const latestTurnStartedAt =
thread.latestTurnId === null
? undefined
: thread.messages.find(
(message) => message.turnId === thread.latestTurnId && message.role === "user",
)?.createdAt;
const latestTurnCompletedAt = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === thread.latestTurnId,
)?.completedAt;
const latestTurnDurationMs =
latestTurnStartedAt && latestTurnCompletedAt
? Math.max(0, Date.parse(latestTurnCompletedAt) - Date.parse(latestTurnStartedAt))
: undefined;
return normalizeThreadTerminals({
id: thread.id,
@@ -483,10 +471,7 @@ export function reducer(state: AppState, action: Action): AppState {
}),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
latestTurnId: thread.latestTurnId ?? undefined,
latestTurnStartedAt,
latestTurnCompletedAt,
latestTurnDurationMs,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
@@ -536,10 +521,10 @@ export function reducer(state: AppState, action: Action): AppState {
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
if (!thread.latestTurnCompletedAt) {
if (!thread.latestTurn?.completedAt) {
return thread;
}
const latestTurnCompletedAtMs = Date.parse(thread.latestTurnCompletedAt);
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return thread;
}
@@ -571,6 +556,14 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "SET_PROJECT_EXPANDED":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
),
};
case "TOGGLE_THREAD_TERMINAL":
return {
...state,
+2 -4
View File
@@ -1,4 +1,5 @@
import type {
OrchestrationLatestTurn,
OrchestrationSessionStatus,
OrchestrationThreadActivity,
ProjectScript as ContractProjectScript,
@@ -89,10 +90,7 @@ export interface Thread {
messages: ChatMessage[];
error: string | null;
createdAt: string;
latestTurnId?: TurnId | undefined;
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
latestTurn: OrchestrationLatestTurn | null;
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
+1
View File
@@ -29,6 +29,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
activities: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
latestTurn: null,
branch: null,
worktreePath: null,
...overrides,
+30 -3
View File
@@ -65,16 +65,41 @@ describe("wsNativeApi", () => {
emitPush(WS_CHANNELS.serverWelcome, payload);
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith(payload);
expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload));
const lateListener = vi.fn();
onServerWelcome(lateListener);
expect(lateListener).toHaveBeenCalledTimes(1);
expect(lateListener).toHaveBeenCalledWith(payload);
expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
expect(warnSpy).not.toHaveBeenCalled();
});
it("preserves bootstrap ids from server.welcome payloads", async () => {
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
createWsNativeApi();
const listener = vi.fn();
onServerWelcome(listener);
emitPush(WS_CHANNELS.serverWelcome, {
cwd: "/tmp/workspace",
projectName: "t3-code",
bootstrapProjectId: "project-1",
bootstrapThreadId: "thread-1",
});
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
cwd: "/tmp/workspace",
projectName: "t3-code",
bootstrapProjectId: "project-1",
bootstrapThreadId: "thread-1",
}),
);
});
it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
@@ -87,7 +112,9 @@ describe("wsNativeApi", () => {
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith({ cwd: "/tmp/workspace", projectName: "t3-code" });
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({ cwd: "/tmp/workspace", projectName: "t3-code" }),
);
expect(warnSpy).toHaveBeenCalledTimes(1);
expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
reason: "decode-failed",
+1 -1
View File
@@ -3,7 +3,7 @@ import react from "@vitejs/plugin-react";
import { tanstackRouter } from "@tanstack/router-plugin/vite";
import { defineConfig } from "vite";
const port = Number(process.env.PORT ?? 5173);
const port = Number(process.env.PORT ?? 5733);
export default defineConfig({
plugins: [
@@ -0,0 +1,40 @@
# ADR 0001: Provider Runtime Lifecycle Ownership
## Status
Accepted
## Context
Provider runtime streams can include auxiliary work (for example collab/child-agent turns) under the same provider session as a user-visible primary turn.
The previous orchestration ingestion and checkpoint flows keyed lifecycle updates by `providerSessionId` alone. This allowed auxiliary `turn.completed` events to:
- mark thread sessions as `ready` before the primary turn completed
- clear `activeTurnId` for a still-running primary turn
- emit checkpoint turn-diff summaries for auxiliary turns in the main thread timeline
## Decision
Define and enforce a lifecycle ownership invariant:
- Only events in the primary thread/turn lane may mutate thread session lifecycle state (`status`, `activeTurnId`, `providerThreadId`) and checkpoint turn completion.
- Auxiliary events may still append messages and activities.
Current enforcement is implemented with scope guards:
- Runtime ingestion only applies lifecycle transitions when the event targets the active primary scope (provider thread and active turn checks).
- Checkpoint capture ignores `turn.completed` events from non-primary provider thread scope, and ignores non-active turn completions while a primary turn is active.
## Consequences
### Positive
- Prevents premature loss of "working" state from auxiliary turn completion.
- Prevents auxiliary changed-files/checkpoint cards from appearing as if they were primary turn completion.
- Keeps useful auxiliary activity/message visibility.
### Negative
- Runtime events that omit thread/turn identifiers are treated conservatively in lifecycle transitions.
- Full explicit lane modeling is still desirable in contracts for long-term clarity.
## Follow-up
1. Add explicit runtime lane metadata (`primary` vs `auxiliary`) to canonical provider runtime events.
2. Persist orchestration-to-provider turn binding (`TurnId` <-> `ProviderTurnId`) for stronger reconciliation and replay safety.
3. Promote lifecycle ownership checks from heuristic guards to schema-level invariants once lane metadata is available.
+25 -1
View File
@@ -142,6 +142,8 @@ export const OrchestrationSession = Schema.Struct({
providerName: Schema.NullOr(TrimmedNonEmptyString),
providerSessionId: Schema.NullOr(ProviderSessionId),
providerThreadId: Schema.NullOr(ProviderThreadId),
approvalPolicy: ProviderApprovalPolicy.pipe(Schema.withDecodingDefault(() => "on-failure")),
sandboxMode: ProviderSandboxMode.pipe(Schema.withDecodingDefault(() => "workspace-write")),
activeTurnId: Schema.NullOr(TurnId),
lastError: Schema.NullOr(TrimmedNonEmptyString),
updatedAt: IsoDateTime,
@@ -189,6 +191,24 @@ export const OrchestrationThreadActivity = Schema.Struct({
});
export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
export const OrchestrationLatestTurnState = Schema.Literals([
"running",
"interrupted",
"completed",
"error",
]);
export type OrchestrationLatestTurnState = typeof OrchestrationLatestTurnState.Type;
export const OrchestrationLatestTurn = Schema.Struct({
turnId: TurnId,
state: OrchestrationLatestTurnState,
requestedAt: IsoDateTime,
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
});
export type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;
export const OrchestrationThread = Schema.Struct({
id: ThreadId,
projectId: ProjectId,
@@ -196,7 +216,7 @@ export const OrchestrationThread = Schema.Struct({
model: TrimmedNonEmptyString,
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
latestTurnId: Schema.NullOr(TurnId),
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
deletedAt: Schema.NullOr(IsoDateTime),
@@ -282,6 +302,8 @@ export const ThreadTurnStartCommand = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyString),
effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
approvalPolicy: ProviderApprovalPolicy,
sandboxMode: ProviderSandboxMode,
createdAt: IsoDateTime,
});
@@ -496,6 +518,8 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyString),
effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
approvalPolicy: ProviderApprovalPolicy.pipe(Schema.withDecodingDefault(() => "on-failure")),
sandboxMode: ProviderSandboxMode.pipe(Schema.withDecodingDefault(() => "workspace-write")),
createdAt: IsoDateTime,
});
+23 -27
View File
@@ -9,15 +9,11 @@ import {
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
TurnId,
IsoDateTime,
} from "./baseSchemas";
import { ProviderApprovalDecision, ProviderKind, ProviderRequestKind } from "./orchestration";
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
const RuntimeThreadIdSchema = Schema.Union([ThreadId, ProviderThreadId]);
const RuntimeTurnIdSchema = Schema.Union([TurnId, ProviderTurnId]);
export const ProviderRuntimeToolKind = Schema.Union([ProviderRequestKind, Schema.Literal("other")]);
export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;
@@ -36,7 +32,7 @@ export const ProviderRuntimeSessionStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
threadId: Schema.optional(ProviderThreadId),
message: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;
@@ -47,7 +43,7 @@ export const ProviderRuntimeSessionExitedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
threadId: Schema.optional(ProviderThreadId),
message: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ProviderRuntimeSessionExitedEvent = typeof ProviderRuntimeSessionExitedEvent.Type;
@@ -58,7 +54,7 @@ export const ProviderRuntimeThreadStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: RuntimeThreadIdSchema,
threadId: ProviderThreadId,
});
export type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type;
@@ -68,8 +64,8 @@ export const ProviderRuntimeTurnStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: RuntimeTurnIdSchema,
threadId: Schema.optional(ProviderThreadId),
turnId: ProviderTurnId,
});
export type ProviderRuntimeTurnStartedEvent = typeof ProviderRuntimeTurnStartedEvent.Type;
@@ -79,8 +75,8 @@ export const ProviderRuntimeTurnCompletedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
status: Schema.optional(ProviderRuntimeTurnStatus),
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
});
@@ -92,8 +88,8 @@ export const ProviderRuntimeMessageDeltaEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
delta: Schema.String,
});
@@ -106,8 +102,8 @@ export const ProviderRuntimeMessageCompletedEvent = Schema.Struct({
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
itemId: ProviderItemId,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
});
export type ProviderRuntimeMessageCompletedEvent = typeof ProviderRuntimeMessageCompletedEvent.Type;
@@ -117,8 +113,8 @@ export const ProviderRuntimeToolStartedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
toolKind: ProviderRuntimeToolKind,
title: TrimmedNonEmptyStringSchema,
@@ -132,8 +128,8 @@ export const ProviderRuntimeToolCompletedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
toolKind: ProviderRuntimeToolKind,
title: TrimmedNonEmptyStringSchema,
@@ -147,8 +143,8 @@ export const ProviderRuntimeApprovalRequestedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
requestId: ApprovalRequestId,
requestKind: ProviderRequestKind,
@@ -163,8 +159,8 @@ export const ProviderRuntimeApprovalResolvedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
requestId: ApprovalRequestId,
requestKind: Schema.optional(ProviderRequestKind),
@@ -178,8 +174,8 @@ export const ProviderRuntimeCheckpointCapturedEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: RuntimeThreadIdSchema,
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: ProviderThreadId,
turnId: Schema.optional(ProviderTurnId),
turnCount: NonNegativeInt,
status: Schema.optional(ProviderRuntimeTurnStatus),
});
@@ -192,8 +188,8 @@ export const ProviderRuntimeErrorEvent = Schema.Struct({
provider: ProviderKind,
sessionId: ProviderSessionId,
createdAt: IsoDateTime,
threadId: Schema.optional(RuntimeThreadIdSchema),
turnId: Schema.optional(RuntimeTurnIdSchema),
threadId: Schema.optional(ProviderThreadId),
turnId: Schema.optional(ProviderTurnId),
itemId: Schema.optional(ProviderItemId),
message: TrimmedNonEmptyStringSchema,
});
+3 -1
View File
@@ -1,5 +1,5 @@
import { Schema, Struct } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas";
import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
import {
ClientOrchestrationCommand,
@@ -163,5 +163,7 @@ export type WsResponse = typeof WsResponse.Type;
export const WsWelcomePayload = Schema.Struct({
cwd: TrimmedNonEmptyString,
projectName: TrimmedNonEmptyString,
bootstrapProjectId: Schema.optional(ProjectId),
bootstrapThreadId: Schema.optional(ThreadId),
});
export type WsWelcomePayload = typeof WsWelcomePayload.Type;
+1 -1
View File
@@ -4,7 +4,7 @@ import path from "node:path";
import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5173;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {