Compare commits

..
Author SHA1 Message Date
Julius Marminge 243e8a44a9 Merge branch 'main' into t3code/pr-977/main 2026-03-19 12:06:36 -07:00
Julius Marminge 77a64493bb Harden git commit extra flags
- Move extra commit args after message flags to avoid swallowing `-m`
- Drop non-flag tokens when tokenizing user-supplied commit flags
- Add tests and clarify the settings helper text
2026-03-19 12:05:40 -07:00
Niklas Wojtkowiak c3af56e177 Merge branch 'main' into main 2026-03-14 17:04:38 -04:00
Niklas Wojtkowiak 22cf222e20 Merge branch 'main' into main 2026-03-13 21:07:44 -04:00
Niklas Wojtkowiak d2c62488b2 Merge branch 'main' into main 2026-03-13 15:08:20 -04:00
Niklas Wojtkowiak 5a57ada95b feat(git): support custom commit flags for app-run commits 2026-03-13 12:21:13 -04:00
159 changed files with 5633 additions and 20504 deletions

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --base-dir ~/.t3-2`
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
+11 -64
View File
@@ -24,32 +24,32 @@ jobs:
{
name: "size:XS",
color: "0e8a16",
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
description: "0-9 changed lines (additions + deletions).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
description: "10-29 changed lines (additions + deletions).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
description: "30-99 changed lines (additions + deletions).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
description: "100-499 changed lines (additions + deletions).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
description: "500-999 changed lines (additions + deletions).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
description: "1,000+ changed lines (additions + deletions).",
},
];
@@ -131,18 +131,12 @@ jobs:
with:
script: |
const issueNumber = context.payload.pull_request.number;
const additions = context.payload.pull_request.additions ?? 0;
const deletions = context.payload.pull_request.deletions ?? 0;
const changedLines = additions + deletions;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
// Keep this aligned with the repo's test entrypoints and test-only support files.
const testFilePatterns = [
/(^|\/)__tests__(\/|$)/,
/(^|\/)tests?(\/|$)/,
/^apps\/server\/integration\//,
/\.(test|spec|browser|integration)\.[^.\/]+$/,
];
const isTestFile = (filename) =>
testFilePatterns.some((pattern) => pattern.test(filename));
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
@@ -168,42 +162,6 @@ jobs:
return "size:XXL";
};
const files = await github.paginate(
github.rest.pulls.listFiles,
{
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: issueNumber,
per_page: 100,
},
(response) => response.data,
);
if (files.length >= 3000) {
core.warning(
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
);
}
let testChangedLines = 0;
let nonTestChangedLines = 0;
for (const file of files) {
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
if (changedLinesForFile === 0) {
continue;
}
if (isTestFile(file.filename)) {
testChangedLines += changedLinesForFile;
continue;
}
nonTestChangedLines += changedLinesForFile;
}
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
@@ -241,15 +199,4 @@ jobs:
});
}
const classification =
nonTestChangedLines === 0
? testChangedLines > 0
? "test-only PR"
: "no line changes"
: testChangedLines > 0
? "test lines excluded"
: "all non-test changes";
core.info(
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
);
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
+1 -1
View File
@@ -312,7 +312,7 @@ jobs:
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
app-id: ${{ vars.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
+1 -3
View File
@@ -17,6 +17,4 @@ release/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
.vitest-*
-441
View File
@@ -1,441 +0,0 @@
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
1. `orchestration.dispatchCommand` (client intent)
2. `OrchestrationEngine` (decide + persist + publish domain events)
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
4. `ProviderService` (adapter routing + canonical runtime stream)
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
6. `orchestration.domainEvent` (single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
---
## Current constraints to design around (post-Stage 1)
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
- `providerOptions.codex`
- `providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
### 2.1.a SDK dependency and baseline config
Add server dependency:
1. `@anthropic-ai/claude-agent-sdk`
Baseline adapter options to support from day one:
1. `cwd`
2. `model`
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
6. `resume`
7. `resumeSessionAt`
8. `includePartialMessages`
9. `canUseTool`
10. `hooks`
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
### 2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
1. Long-lived session context per adapter session.
2. Multi-turn input queue.
3. Interrupt support.
4. Approval request/response bridge.
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
#### 2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
2. Multi-turn input is supported via async-iterable prompt input.
3. Tool approval decisions are provided via `canUseTool`.
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
#### 2.2.b Effect-native session lifecycle skeleton
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
```
#### 2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
```ts
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
```
Portable fallback (already aligned with current server patterns):
```ts
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
```
### 2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
### 2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
1. `interruptTurn()` -> active query interrupt.
2. `stopSession()` -> close session resources and prevent future sends.
3. `rollbackThread()` -> see Phase 4.
---
## Phase 3: Provider service and composition
### 3.1 Register Claude adapter
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
Required validation:
1. Claude bindings survive restart.
2. resume cursor remains opaque and round-trips untouched.
3. stopAll + restart can recover Claude sessions when possible.
### 3.3 Provider start routing
Update `ProviderCommandReactor` / orchestration flow:
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1. `apps/web/src/store.ts`
2. `apps/web/src/components/ChatView.tsx`
3. `apps/web/src/types.ts`
4. `packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
---
## Phase 7: Rollout order
Recommended implementation order:
1. contracts/provider-aware models
2. provider field on turn-start
3. Claude adapter skeleton + start/send/stream
4. canonical event mapping
5. provider registry/service wiring
6. orchestration recovery + checkpoint strategy
7. web provider/model picker
8. full integration tests
---
## Non-goals
1. Reintroducing provider-specific WS methods/channels.
2. Storing provider-native thread ids as orchestration ids.
3. Bypassing orchestration engine for Claude-specific UI flows.
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
+1 -1
View File
@@ -7,7 +7,7 @@
## Project Snapshot
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
+1 -1
View File
@@ -1,6 +1,6 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
## How to use
+1 -1
View File
@@ -11,7 +11,7 @@ The T3 Code CLI accepts the following configuration options, available either as
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.13",
"version": "0.0.10",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+3 -3
View File
@@ -56,8 +56,8 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const STATE_DIR =
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -924,7 +924,7 @@ function backendEnv(): NodeJS.ProcessEnv {
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_HOME: BASE_DIR,
T3CODE_STATE_DIR: STATE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
@@ -1,20 +1,20 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
FileSystem,
Layer,
ManagedRuntime,
Option,
Path,
Ref,
Schedule,
Schema,
@@ -24,7 +24,6 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -66,7 +65,7 @@ import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { ServerConfig } from "../src/config.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -76,16 +75,14 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
});
}
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
const fileSystem = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
});
}
export function gitRefExists(cwd: string, ref: string): boolean {
try {
@@ -208,7 +205,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
readonly realCodex?: boolean;
}
@@ -216,9 +213,7 @@ export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const sleep = (ms: number) => Effect.sleep(ms);
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
@@ -235,16 +230,13 @@ export const makeOrchestrationIntegrationHarness = (
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
});
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const workspaceDir = path.join(rootDir, "workspace");
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
Effect.provideService(Path.Path, path),
);
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
yield* initializeGitWorkspace(workspaceDir);
const stateDir = path.join(rootDir, "state");
const dbPath = path.join(stateDir, "state.sqlite");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(stateDir, { recursive: true });
initializeGitWorkspace(workspaceDir);
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -269,7 +261,7 @@ export const makeOrchestrationIntegrationHarness = (
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
@@ -285,13 +277,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
CheckpointStoreLive,
providerLayer,
RuntimeReceiptBusLive,
);
@@ -320,7 +311,7 @@ export const makeOrchestrationIntegrationHarness = (
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -360,7 +351,7 @@ export const makeOrchestrationIntegrationHarness = (
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
@@ -477,7 +468,13 @@ export const makeOrchestrationIntegrationHarness = (
}
});
yield* shutdown;
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
@@ -10,7 +10,6 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -36,7 +35,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -178,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +197,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
}
function nowIso(): string {
@@ -206,7 +205,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +215,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -5,11 +5,9 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ThreadId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
@@ -27,7 +25,6 @@ import type {
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -39,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
type IntegrationProvider = "codex";
function nowIso() {
return new Date().toISOString();
@@ -52,6 +49,8 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
@@ -69,7 +68,7 @@ function waitForSync<A>(
if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* Effect.sleep(10);
yield* sleep(10);
}
});
}
@@ -90,7 +89,7 @@ function withHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
function withRealCodexHarness<A, E>(
@@ -100,14 +99,12 @@ function withRealCodexHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -115,10 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider,
model: defaultModel,
},
defaultModel: "gpt-5-codex",
createdAt,
});
@@ -128,10 +122,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider,
model: defaultModel,
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -157,14 +148,7 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
...(input.provider !== undefined
? {
modelSelection: {
provider: input.provider,
model: DEFAULT_MODEL_BY_PROVIDER[input.provider],
},
}
: {}),
...(input.provider !== undefined ? { provider: input.provider } : {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
@@ -267,10 +251,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
defaultModel: "gpt-5.3-codex",
createdAt,
});
@@ -280,10 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -904,420 +882,3 @@ it.live(
}),
),
);
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
),
);
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
provider: "claudeAgent",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.adapter.stopAll();
yield* waitForSync(
() => harness.adapterHarness!.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness!.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
),
);
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
),
);
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent(
(event) => event.type === "thread.turn-interrupt-requested",
);
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
),
);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
provider: "claudeAgent",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
);
+1 -3
View File
@@ -1,7 +1,6 @@
{
"name": "t3",
"version": "0.0.13",
"license": "MIT",
"version": "0.0.10",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
@@ -23,7 +22,6 @@
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
+2 -2
View File
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
}
export function resolveAttachmentRelativePath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
return null;
}
const attachmentsRoot = path.resolve(input.attachmentsDir);
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
+8 -6
View File
@@ -44,32 +44,34 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
});
+4 -4
View File
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
}
export function resolveAttachmentPath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
@@ -31,7 +31,7 @@ function makeSnapshot(input: {
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
@@ -43,10 +43,7 @@ function makeSnapshot(input: {
id: input.threadId,
projectId: input.projectId,
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -15,14 +15,15 @@ import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitServiceLive } from "../../git/Layers/GitService.ts";
import { GitService } from "../../git/Services/GitService.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitCore;
const git = yield* GitService;
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
@@ -276,4 +277,6 @@ const makeCheckpointStore = Effect.gen(function* () {
} satisfies CheckpointStoreShape;
});
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
Layer.provideMerge(GitServiceLive),
);
@@ -37,7 +37,6 @@ function createSendTurnHarness() {
planType: null,
sparkEnabled: true,
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -76,7 +75,6 @@ function createThreadControlHarness() {
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -119,7 +117,6 @@ function createPendingUserInputHarness() {
},
],
]),
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -138,43 +135,6 @@ function createPendingUserInputHarness() {
return { manager, context, requireSession, writeMessage, emitEvent };
}
function createCollabNotificationHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
provider: "codex",
status: "running",
threadId: asThreadId("thread_1"),
runtimeMode: "full-access",
model: "gpt-5.3-codex",
activeTurnId: "turn_parent",
resumeCursor: { threadId: "provider_parent" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map<string, string>(),
nextRequestId: 1,
stopping: false,
};
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, emitEvent, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -761,7 +721,6 @@ describe("respondToUserInput", () => {
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
@@ -789,152 +748,6 @@ describe("respondToUserInput", () => {
});
});
describe("collab child conversation routing", () => {
it("rewrites child notification turn ids onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/agentMessage/delta",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "msg_child_1",
delta: "working",
},
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/agentMessage/delta",
turnId: "turn_parent",
itemId: "msg_child_1",
}),
);
});
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
updateSession.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/started",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1" },
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/completed",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1", status: "completed" },
},
});
expect(emitEvent).not.toHaveBeenCalled();
expect(updateSession).not.toHaveBeenCalled();
});
it("rewrites child approval requests onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
}
).handleServerRequest(context, {
id: 42,
method: "item/commandExecution/requestApproval",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "call_child_1",
command: "bun install",
},
});
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
expect.objectContaining({
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/commandExecution/requestApproval",
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
+10 -94
View File
@@ -70,7 +70,6 @@ interface CodexSessionContext {
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
nextRequestId: number;
stopping: boolean;
}
@@ -572,7 +571,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -734,7 +732,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
@@ -1124,16 +1121,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context: CodexSessionContext,
notification: JsonRpcNotification,
): void {
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const isChildConversation = childParentTurnId !== undefined;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
) {
return;
}
const route = this.readRouteFields(notification.params);
const textDelta =
notification.method === "item/agentMessage/delta"
? this.readString(notification.params, "delta")
@@ -1146,10 +1134,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: notification.method,
...((childParentTurnId ?? rawRoute.turnId)
? { turnId: childParentTurnId ?? rawRoute.turnId }
: {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
turnId: route.turnId,
itemId: route.itemId,
textDelta,
payload: notification.params,
});
@@ -1165,9 +1151,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/started") {
if (isChildConversation) {
return;
}
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
this.updateSession(context, {
status: "running",
@@ -1177,10 +1160,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/completed") {
if (isChildConversation) {
return;
}
context.collabReceiverTurns.clear();
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
@@ -1193,9 +1172,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "error") {
if (isChildConversation) {
return;
}
const message = this.readString(this.readObject(notification.params)?.error, "message");
const willRetry = this.readBoolean(notification.params, "willRetry");
@@ -1207,9 +1183,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
const route = this.readRouteFields(request.params);
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
@@ -1225,8 +1199,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
: "item/fileChange/requestApproval",
requestKind,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
@@ -1237,8 +1211,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestId,
jsonRpcId: request.id,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
});
}
@@ -1249,8 +1223,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: request.method,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
turnId: route.turnId,
itemId: route.itemId,
requestId,
requestKind,
payload: request.params,
@@ -1477,64 +1451,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return route;
}
private readProviderConversationId(params: unknown): string | undefined {
return (
this.readString(params, "threadId") ??
this.readString(this.readObject(params, "thread"), "id") ??
this.readString(params, "conversationId")
);
}
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverTurns.get(providerConversationId);
}
private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
parentTurnId: TurnId | undefined,
): void {
if (!parentTurnId) {
return;
}
const payload = this.readObject(params);
const item = this.readObject(payload, "item") ?? payload;
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
if (itemType !== "collabAgentToolCall") {
return;
}
const receiverThreadIds =
this.readArray(item, "receiverThreadIds")
?.map((value) => (typeof value === "string" ? value : null))
.filter((value): value is string => value !== null) ?? [];
for (const receiverThreadId of receiverThreadIds) {
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
}
}
private shouldSuppressChildConversationNotification(method: string): boolean {
return (
method === "thread/started" ||
method === "thread/status/changed" ||
method === "thread/archived" ||
method === "thread/unarchived" ||
method === "thread/closed" ||
method === "thread/compacted" ||
method === "thread/name/updated" ||
method === "thread/tokenUsage/updated" ||
method === "turn/started" ||
method === "turn/completed" ||
method === "turn/aborted" ||
method === "turn/plan/updated" ||
method === "item/plan/delta"
);
}
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
const target =
key === undefined
+9 -62
View File
@@ -12,32 +12,16 @@ export const DEFAULT_PORT = 3773;
export type RuntimeMode = "web" | "desktop";
/**
* ServerDerivedPaths - Derived paths from the base directory.
*/
export interface ServerDerivedPaths {
readonly stateDir: string;
readonly dbPath: string;
readonly keybindingsConfigPath: string;
readonly worktreesDir: string;
readonly attachmentsDir: string;
readonly logsDir: string;
readonly serverLogPath: string;
readonly providerLogsDir: string;
readonly providerEventLogPath: string;
readonly terminalLogsDir: string;
readonly anonymousIdPath: string;
}
/**
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape extends ServerDerivedPaths {
export interface ServerConfigShape {
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
readonly cwd: string;
readonly baseDir: string;
readonly keybindingsConfigPath: string;
readonly stateDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
@@ -46,68 +30,31 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly logWebSocketEvents: boolean;
}
export const deriveServerPaths = Effect.fn(function* (
baseDir: ServerConfigShape["baseDir"],
devUrl: ServerConfigShape["devUrl"],
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
const { join } = yield* Path.Path;
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
const dbPath = join(stateDir, "state.sqlite");
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
const providerLogsDir = join(logsDir, "provider");
return {
stateDir,
dbPath,
keybindingsConfigPath: join(stateDir, "keybindings.json"),
worktreesDir: join(baseDir, "worktrees"),
attachmentsDir,
logsDir,
serverLogPath: join(logsDir, "server.log"),
providerLogsDir,
providerEventLogPath: join(providerLogsDir, "events.log"),
terminalLogsDir: join(logsDir, "terminals"),
anonymousIdPath: join(stateDir, "anonymous-id"),
};
});
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
static readonly layerTest = (cwd: string, statedir: string) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const devUrl = undefined;
const fs = yield* FileSystem.FileSystem;
const baseDir =
typeof baseDirOrPrefix === "string"
? baseDirOrPrefix
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
const path = yield* Path.Path;
return {
cwd,
baseDir,
...derivedPaths,
stateDir: statedir,
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
port: 0,
host: undefined,
authToken: undefined,
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
staticDir: undefined,
devUrl,
devUrl: undefined,
noBrowser: false,
} satisfies ServerConfigShape;
};
}),
);
}
@@ -8,14 +8,11 @@ import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(dir: string) {
return Effect.gen(function* () {
@@ -189,6 +186,8 @@ function withFakeCodexEnv<A, E, R>(
);
}
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
@@ -326,10 +325,9 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
@@ -365,10 +363,9 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
@@ -413,9 +410,8 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const textGeneration = yield* TextGeneration;
@@ -163,7 +163,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
}
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+12 -139
View File
@@ -6,7 +6,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import type { GitActionProgressEvent } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -16,10 +15,10 @@ import {
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -107,11 +106,11 @@ function runGit(
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
GitCommandError,
GitCore
GitService
> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
return yield* gitCore.execute({
const gitService = yield* GitService;
return yield* gitService.execute({
operation: "GitManager.test.runGit",
cwd,
args,
@@ -125,7 +124,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -141,7 +140,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -450,20 +449,12 @@ function runStackedAction(
input: {
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
actionId?: string;
commitMessage?: string;
featureBranch?: boolean;
filePaths?: readonly string[];
},
options?: Parameters<GitManagerShape["runStackedAction"]>[1],
) {
return manager.runStackedAction(
{
...input,
actionId: input.actionId ?? "test-action-id",
},
options,
);
return manager.runStackedAction(input);
}
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
@@ -483,20 +474,18 @@ function makeManager(input?: {
}) {
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
const textGeneration = createTextGeneration(input?.textGeneration);
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-git-manager-test-",
});
const gitCoreLayer = GitCoreLive.pipe(
Layer.provideMerge(GitServiceLive),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
gitCoreLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
NodeServices.layer,
);
return makeGitManager.pipe(
Effect.provide(managerLayer),
@@ -504,10 +493,7 @@ function makeManager(input?: {
);
}
const GitManagerTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(NodeServices.layer),
);
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status includes PR metadata when branch already has an open PR", () =>
@@ -1950,117 +1936,4 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(errorMessage).toContain("already checked out in the main repo");
}),
);
it.effect("emits ordered progress events for commit hooks", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const result = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-1",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
);
expect(result.commit.status).toBe("created");
expect(events.map((event) => event.kind)).toContain("action_started");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "phase_started",
phase: "commit",
}),
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: start",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: end",
}),
expect.objectContaining({
kind: "hook_finished",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_finished",
}),
]),
);
}),
);
it.effect("emits action_failed when a commit hook rejects", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: fail" >&2\nexit 1\n',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const errorMessage = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-2",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("hook: fail");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_failed",
phase: "commit",
}),
]),
);
}),
);
});
+80 -254
View File
@@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Effect, FileSystem, Layer, Path } from "effect";
import type { GitActionProgressEvent, GitActionProgressPhase } from "@t3tools/contracts";
import {
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
@@ -10,21 +9,11 @@ import {
} from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import {
GitManager,
type GitActionProgressReporter,
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
interface OpenPrInfo {
number: number;
title: string;
@@ -211,17 +200,6 @@ function sanitizeCommitMessage(generated: {
};
}
function sanitizeProgressText(value: string): string | null {
const trimmed = value.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {
return trimmed;
}
return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();
}
interface CommitAndBranchSuggestion {
subject: string;
body: string;
@@ -229,6 +207,23 @@ interface CommitAndBranchSuggestion {
commitMessage: string;
}
/**
* Tokenize and sanitise user-provided extra flags for `git commit`.
*
* Each token must look like a CLI flag (start with `-`). Tokens that don't
* start with a dash are silently dropped so that a malformed value like
* `--author "Foo"` (which the naive split turns into `["--author", "Foo"]`)
* cannot inject a positional argument into the git invocation.
*/
export function tokenizeCommitFlags(rawFlags?: string): string[] {
const tokens = (rawFlags ?? "")
.trim()
.split(/\s+/g)
.filter((value) => value.length > 0);
return tokens.filter((token) => token.startsWith("-"));
}
function formatCommitMessage(subject: string, body: string): string {
const trimmedBody = body.trim();
if (trimmedBody.length === 0) {
@@ -359,29 +354,6 @@ export const makeGitManager = Effect.gen(function* () {
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const createProgressEmitter = (
input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" },
options?: GitRunStackedActionOptions,
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
return {
actionId,
emit,
};
};
const configurePullRequestHeadUpstream = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
@@ -725,111 +697,33 @@ export const makeGitManager = Effect.gen(function* () {
const runCommitStep = (
cwd: string,
action: "commit" | "commit_push" | "commit_push_pr",
branch: string | null,
commitMessage?: string,
commitFlags?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
filePaths?: readonly string[],
model?: string,
progressReporter?: GitActionProgressReporter,
actionId?: string,
) =>
Effect.gen(function* () {
const emit = (event: GitActionProgressPayload) =>
progressReporter && actionId
? progressReporter.publish({
actionId,
cwd,
action,
...event,
} as GitActionProgressEvent)
: Effect.void;
let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion;
if (!suggestion) {
const needsGeneration = !commitMessage?.trim();
if (needsGeneration) {
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Generating commit message...",
});
}
suggestion = yield* resolveCommitAndBranchSuggestion({
const suggestion =
preResolvedSuggestion ??
(yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
...(model ? { model } : {}),
});
}
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
}
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
let currentHookName: string | null = null;
const commitProgress =
progressReporter && actionId
? {
onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => {
const sanitized = sanitizeProgressText(text);
if (!sanitized) {
return Effect.void;
}
return emit({
kind: "hook_output",
hookName: currentHookName,
stream,
text: sanitized,
});
},
onHookStarted: (hookName: string) => {
currentHookName = hookName;
return emit({
kind: "hook_started",
hookName,
});
},
onHookFinished: ({
hookName,
exitCode,
durationMs,
}: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => {
if (currentHookName === hookName) {
currentHookName = null;
}
return emit({
kind: "hook_finished",
hookName,
exitCode,
durationMs,
});
},
}
: null;
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, {
timeoutMs: COMMIT_TIMEOUT_MS,
...(commitProgress ? { progress: commitProgress } : {}),
});
if (currentHookName !== null) {
yield* emit({
kind: "hook_finished",
hookName: currentHookName,
exitCode: 0,
durationMs: null,
});
currentHookName = null;
}
const { commitSha } = yield* gitCore.commit(
cwd,
suggestion.subject,
suggestion.body,
tokenizeCommitFlags(commitFlags),
);
return {
status: "created" as const,
commitSha,
@@ -1139,135 +1033,67 @@ export const makeGitManager = Effect.gen(function* () {
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input, options) {
const progress = createProgressEmitter(input, options);
const phases: GitActionProgressPhase[] = [
...(input.featureBranch ? (["branch"] as const) : []),
"commit",
...(input.action !== "commit" ? (["push"] as const) : []),
...(input.action === "commit_push_pr" ? (["pr"] as const) : []),
];
let currentPhase: GitActionProgressPhase | null = null;
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const runAction = Effect.gen(function* () {
yield* progress.emit({
kind: "action_started",
phases,
});
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
if (input.featureBranch) {
currentPhase = "branch";
yield* progress.emit({
kind: "phase_started",
phase: "branch",
label: "Preparing feature branch...",
});
const result = yield* runFeatureBranchStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
input.filePaths,
input.textGenerationModel,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const currentBranch = branchStep.name ?? initialStatus.branch;
currentPhase = "commit";
const commit = yield* runCommitStep(
if (input.featureBranch) {
const result = yield* runFeatureBranchStep(
input.cwd,
input.action,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
initialStatus.branch,
input.commitMessage,
input.filePaths,
input.textGenerationModel,
options?.progressReporter,
progress.actionId,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const push = wantsPush
? yield* progress
.emit({
kind: "phase_started",
phase: "push",
label: "Pushing...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "push";
return yield* gitCore.pushCurrentBranch(input.cwd, currentBranch);
}),
),
)
: { status: "skipped_not_requested" as const };
const currentBranch = branchStep.name ?? initialStatus.branch;
const pr = wantsPr
? yield* progress
.emit({
kind: "phase_started",
phase: "pr",
label: "Creating PR...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "pr";
return yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel);
}),
),
)
: { status: "skipped_not_requested" as const };
const result = {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
yield* progress.emit({
kind: "action_finished",
result,
});
return result;
});
return yield* runAction.pipe(
Effect.catch((error) =>
progress
.emit({
kind: "action_failed",
phase: currentPhase,
message: error.message,
})
.pipe(Effect.flatMap(() => Effect.fail(error))),
),
const commit = yield* runCommitStep(
input.cwd,
currentBranch,
commitMessageForStep,
input.commitFlags,
preResolvedCommitSuggestion,
input.filePaths,
input.textGenerationModel,
);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
},
);
@@ -0,0 +1,59 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
layer("GitServiceLive", (it) => {
it.effect("runGit executes successful git commands", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.version",
cwd: process.cwd(),
args: ["--version"],
});
assert.equal(result.code, 0);
assert.ok(result.stdout.toLowerCase().includes("git version"));
}),
);
it.effect("runGit can return non-zero exit codes when allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.allowNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
allowNonZeroExit: true,
});
assert.notEqual(result.code, 0);
}),
);
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* Effect.result(
gitService.execute({
operation: "GitProcess.test.failOnNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
}),
);
assert.equal(result._tag, "Failure");
if (result._tag === "Failure") {
assert.ok(Schema.is(GitCommandError)(result.failure));
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
}
}),
);
});
+144
View File
@@ -0,0 +1,144 @@
/**
* Git process helpers - Effect-native git execution with typed errors.
*
* Centralizes child-process git invocation for server modules. This module
* only executes git commands and reports structured failures.
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
ExecuteGitInput,
ExecuteGitResult,
GitService,
GitServiceShape,
} from "../Services/GitService.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: ReadonlyArray<string>): string {
return `git ${args.join(" ")}`;
}
function toGitCommandError(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
detail: string,
) {
return (cause: unknown) =>
Schema.is(GitCommandError)(cause)
? cause
: new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
...(cause !== undefined ? { cause } : {}),
});
}
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
bytes += chunk.byteLength;
if (bytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
text += decoder.decode();
return text;
});
const makeGitService = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
} as const;
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
],
{ concurrency: "unbounded" },
);
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
});
}
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
});
return yield* commandEffect.pipe(
Effect.scoped,
Effect.timeoutOption(timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
}),
),
onSome: Effect.succeed,
}),
),
);
});
return {
execute,
} satisfies GitServiceShape;
});
export const GitServiceLive = Layer.effect(GitService, makeGitService);
+1 -52
View File
@@ -24,23 +24,6 @@ import type {
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
@@ -50,35 +33,6 @@ export interface GitPreparedCommitContext {
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
@@ -132,11 +86,6 @@ export interface GitSetBranchUpstreamInput {
* GitCoreShape - Service API for low-level Git repository interactions.
*/
export interface GitCoreShape {
/**
* Execute a raw Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
/**
* Read Git status for a repository.
*/
@@ -162,7 +111,7 @@ export interface GitCoreShape {
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
extraArgs?: readonly string[],
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
@@ -7,7 +7,6 @@
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
@@ -21,15 +20,6 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "../Errors.ts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
/**
* GitManagerShape - Service API for high-level Git workflow actions.
*/
@@ -61,7 +51,6 @@ export interface GitManagerShape {
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
@@ -0,0 +1,45 @@
/**
* GitService - Service for Git command execution.
*
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* domain errors for Git command execution.
*
* @module GitService
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
/**
* GitServiceShape - Service API for Git command execution.
*/
export interface GitServiceShape {
/**
* Execute a Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
}
/**
* GitService - Service for Git command execution.
*/
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
"t3/git/Services/GitService",
) {}
+11 -9
View File
@@ -3,7 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ServerConfig } from "./config";
import { ServerConfig, type ServerConfigShape } from "./config";
import {
DEFAULT_KEYBINDINGS,
@@ -17,17 +17,21 @@ import {
} from "./keybindings";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const makeKeybindingsLayer = () => {
return KeybindingsLive.pipe(
const makeKeybindingsLayer = () =>
KeybindingsLive.pipe(
Layer.provideMerge(
Layer.fresh(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-keybindings-test-",
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
const configPath = join(dir, "keybindings.json");
return { keybindingsConfigPath: configPath } as ServerConfigShape;
}),
),
),
);
};
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
effect.pipe(
@@ -38,9 +42,7 @@ const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
yield* fileSystem.writeFileString(configPath, encoded);
});
+7 -7
View File
@@ -60,11 +60,13 @@ const runCli = (
args: ReadonlyArray<string>,
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
) => {
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_STATE_DIR: uniqueStateDir,
...env,
},
}),
@@ -91,8 +93,8 @@ it.layer(testLayer)("server CLI command", (it) => {
"4010",
"--host",
"0.0.0.0",
"--home-dir",
"/tmp/t3-cli-home",
"--state-dir",
"/tmp/t3-cli-state",
"--dev-url",
"http://127.0.0.1:5173",
"--no-browser",
@@ -104,8 +106,7 @@ it.layer(testLayer)("server CLI command", (it) => {
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4010);
assert.equal(resolvedConfig?.host, "0.0.0.0");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "auth-secret");
@@ -130,7 +131,7 @@ it.layer(testLayer)("server CLI command", (it) => {
T3CODE_MODE: "desktop",
T3CODE_PORT: "4999",
T3CODE_HOST: "100.88.10.4",
T3CODE_HOME: "/tmp/t3-env-home",
T3CODE_STATE_DIR: "/tmp/t3-env-state",
VITE_DEV_SERVER_URL: "http://localhost:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "env-token",
@@ -140,8 +141,7 @@ it.layer(testLayer)("server CLI command", (it) => {
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4999);
assert.equal(resolvedConfig?.host, "100.88.10.4");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "env-token");
+16 -12
View File
@@ -11,13 +11,12 @@ import { Command, Flag } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import {
DEFAULT_PORT,
deriveServerPaths,
resolveStaticDir,
ServerConfig,
type RuntimeMode,
type ServerConfigShape,
} from "./config";
import { fixPath, resolveBaseDir } from "./os-jank";
import { fixPath, resolveStateDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
@@ -37,7 +36,7 @@ interface CliInput {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly t3Home: Option.Option<string>;
readonly stateDir: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
@@ -100,7 +99,10 @@ const CliEnvConfig = Config.all({
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
stateDir: Config.string("T3CODE_STATE_DIR").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
@@ -150,10 +152,10 @@ const ServerConfigLive = (input: CliInput) =>
return findAvailablePort(DEFAULT_PORT);
},
});
const stateDir = yield* resolveStateDir(
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
);
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
const baseDir = yield* resolveBaseDir(Option.getOrUndefined(input.t3Home) ?? env.t3Home);
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
@@ -165,6 +167,8 @@ const ServerConfigLive = (input: CliInput) =>
env.logWebSocketEvents ?? Boolean(devUrl),
);
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
const { join } = yield* Path.Path;
const keybindingsConfigPath = join(stateDir, "keybindings.json");
const host =
Option.getOrUndefined(input.host) ??
env.host ??
@@ -174,9 +178,9 @@ const ServerConfigLive = (input: CliInput) =>
mode,
port,
cwd: cliConfig.cwd,
keybindingsConfigPath,
host,
baseDir,
...derivedPaths,
stateDir,
staticDir,
devUrl,
noBrowser,
@@ -295,8 +299,8 @@ const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
Flag.optional,
);
const t3HomeFlag = Flag.string("home-dir").pipe(
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
const stateDirFlag = Flag.string("state-dir").pipe(
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
Flag.optional,
);
const devUrlFlag = Flag.string("dev-url").pipe(
@@ -331,7 +335,7 @@ export const t3Cli = Command.make("t3", {
mode: modeFlag,
port: portFlag,
host: hostFlag,
t3Home: t3HomeFlag,
stateDir: stateDirFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -19,7 +19,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -45,7 +44,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -236,7 +235,6 @@ describe("CheckpointReactor", () => {
readonly projectWorkspaceRoot?: string;
readonly threadWorktreePath?: string | null;
readonly providerSessionCwd?: string;
readonly providerName?: ProviderKind;
}) {
const cwd = createGitRepository();
tempDirs.push(cwd);
@@ -244,7 +242,7 @@ describe("CheckpointReactor", () => {
cwd,
options?.hasSession ?? true,
options?.providerSessionCwd ?? cwd,
options?.providerName ?? "codex",
"codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -253,16 +251,12 @@ describe("CheckpointReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-reactor-test-",
});
const layer = CheckpointReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
@@ -282,10 +276,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -296,10 +287,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -489,67 +477,6 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: "claudeAgent",
});
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
harness.provider.emit({
type: "turn.started",
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
});
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-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
const thread = await waitForThread(
harness.engine,
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
@@ -865,75 +792,6 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: createdAt,
},
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
);
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
@@ -35,15 +35,12 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
async function createOrchestrationSystem() {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(orchestrationLayer);
@@ -72,10 +69,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -86,10 +80,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -132,10 +123,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -146,10 +134,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-replay"),
projectId: asProjectId("project-replay"),
title: "replay",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -190,10 +175,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -214,10 +196,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-stream"),
projectId: asProjectId("project-stream"),
title: "domain-stream",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -251,10 +230,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -265,10 +241,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -344,17 +317,13 @@ describe("OrchestrationEngine", () => {
},
};
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-engine-test-",
});
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
),
);
@@ -368,10 +337,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -384,10 +350,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -404,10 +367,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -461,10 +421,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -475,10 +432,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-atomic"),
projectId: asProjectId("project-atomic"),
title: "atomic",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -602,10 +556,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -616,10 +567,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-sync"),
projectId: asProjectId("project-sync"),
title: "sync-before",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -687,10 +635,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -702,10 +647,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -722,10 +664,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
File diff suppressed because it is too large. Load diff
@@ -243,7 +243,7 @@ const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSid
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
const path = yield* Effect.service(Path.Path);
const attachmentsRootDir = serverConfig.attachmentsDir;
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
yield* Effect.forEach(
sideEffects.deletedThreadIds,
@@ -362,7 +362,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
projectId: event.payload.projectId,
title: event.payload.title,
workspaceRoot: event.payload.workspaceRoot,
defaultModelSelection: event.payload.defaultModelSelection,
defaultModel: event.payload.defaultModel,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -383,8 +383,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
...(event.payload.workspaceRoot !== undefined
? { workspaceRoot: event.payload.workspaceRoot }
: {}),
...(event.payload.defaultModelSelection !== undefined
? { defaultModelSelection: event.payload.defaultModelSelection }
...(event.payload.defaultModel !== undefined
? { defaultModel: event.payload.defaultModel }
: {}),
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
updatedAt: event.payload.updatedAt,
@@ -420,7 +420,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
threadId: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
modelSelection: event.payload.modelSelection,
model: event.payload.model,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
branch: event.payload.branch,
@@ -442,9 +442,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
yield* projectionThreadRepository.upsert({
...existingRow.value,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
...(event.payload.worktreePath !== undefined
? { worktreePath: event.payload.worktreePath }
@@ -810,16 +808,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId:
existingTurn.value.pendingMessageId ??
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
sourceProposedPlanThreadId:
existingTurn.value.sourceProposedPlanThreadId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null),
sourceProposedPlanId:
existingTurn.value.sourceProposedPlanId ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null),
startedAt:
existingTurn.value.startedAt ??
(Option.isSome(pendingTurnStart)
@@ -838,12 +826,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
pendingMessageId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.messageId
: null,
sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanThreadId
: null,
sourceProposedPlanId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.sourceProposedPlanId
: null,
assistantMessageId: null,
state: "running",
requestedAt: Option.isSome(pendingTurnStart)
@@ -897,8 +879,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming ? "running" : "completed",
requestedAt: event.payload.createdAt,
@@ -934,8 +914,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: null,
state: "interrupted",
requestedAt: event.payload.createdAt,
@@ -980,8 +958,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
turnId: event.payload.turnId,
threadId: event.payload.threadId,
pendingMessageId: null,
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
requestedAt: event.payload.completedAt,
@@ -34,7 +34,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
project_id,
title,
workspace_root,
default_provider,
default_model,
scripts_json,
created_at,
@@ -45,7 +44,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'project-1',
'Project 1',
'/tmp/project-1',
'codex',
'gpt-5-codex',
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
'2026-02-24T00:00:00.000Z',
@@ -59,7 +57,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
thread_id,
project_id,
title,
provider,
model,
branch,
worktree_path,
@@ -72,7 +69,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'thread-1',
'project-1',
'Thread 1',
'codex',
'gpt-5-codex',
NULL,
NULL,
@@ -182,8 +178,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -198,8 +192,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'thread-1',
'turn-1',
NULL,
'thread-1',
'plan-1',
'message-1',
'completed',
'2026-02-24T00:00:08.000Z',
@@ -238,10 +230,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
scripts: [
{
id: "script-1",
@@ -261,10 +250,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "default",
runtimeMode: "full-access",
branch: null,
@@ -276,10 +262,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
startedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
assistantMessageId: asMessageId("message-1"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-1"),
planId: "plan-1",
},
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
@@ -1,14 +1,11 @@
import {
ChatAttachment,
IsoDateTime,
ModelSelection,
MessageId,
NonNegativeInt,
OrchestrationCheckpointFile,
OrchestrationProposedPlanId,
OrchestrationReadModel,
ProjectScript,
ThreadId,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
@@ -43,19 +40,12 @@ import {
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
const decodeReadModelSync = Schema.decodeUnknownSync(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = Schema.Struct({
projectId: ProjectionProject.fields.projectId,
title: ProjectionProject.fields.title,
workspaceRoot: ProjectionProject.fields.workspaceRoot,
defaultProvider: Schema.NullOr(Schema.Literals(["codex", "claudeAgent"])),
defaultModel: Schema.NullOr(Schema.String),
defaultModelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
createdAt: ProjectionProject.fields.createdAt,
updatedAt: ProjectionProject.fields.updatedAt,
deletedAt: ProjectionProject.fields.deletedAt,
});
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
Struct.assign({
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
);
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
@@ -63,22 +53,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
}),
);
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = Schema.Struct({
threadId: ProjectionThread.fields.threadId,
projectId: ProjectionThread.fields.projectId,
title: ProjectionThread.fields.title,
provider: Schema.Literals(["codex", "claudeAgent"]),
model: Schema.String,
modelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
runtimeMode: ProjectionThread.fields.runtimeMode,
interactionMode: ProjectionThread.fields.interactionMode,
branch: ProjectionThread.fields.branch,
worktreePath: ProjectionThread.fields.worktreePath,
latestTurnId: ProjectionThread.fields.latestTurnId,
createdAt: ProjectionThread.fields.createdAt,
updatedAt: ProjectionThread.fields.updatedAt,
deletedAt: ProjectionThread.fields.deletedAt,
});
const ProjectionThreadDbRowSchema = ProjectionThread;
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
Struct.assign({
payload: Schema.fromJsonString(Schema.Unknown),
@@ -99,11 +74,8 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
startedAt: Schema.NullOr(IsoDateTime),
completedAt: Schema.NullOr(IsoDateTime),
assistantMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -153,26 +125,6 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
: toPersistenceSqlError(sqlOperation)(cause);
}
const decodeModelSelection = (input: {
readonly provider: "codex" | "claudeAgent";
readonly model: string;
readonly options: unknown;
}) =>
Effect.try({
try: () =>
decodeModelSelectionSync({
provider: input.provider,
model: input.model,
...(input.options !== null && input.options !== undefined
? { options: input.options }
: {}),
}),
catch: (error) =>
Schema.isSchemaError(error)
? toPersistenceDecodeError("ProjectionSnapshotQuery.decodeModelSelection")(error)
: toPersistenceSqlError("ProjectionSnapshotQuery.decodeModelSelection")(error),
});
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -185,9 +137,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_provider AS "defaultProvider",
default_model AS "defaultModel",
default_model_options_json AS "defaultModelOptions",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -206,9 +156,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
provider,
model,
model_options_json AS "modelOptions",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
@@ -338,9 +286,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
requested_at AS "requestedAt",
started_at AS "startedAt",
completed_at AS "completedAt",
assistant_message_id AS "assistantMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId"
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
@@ -555,14 +501,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
startedAt: row.startedAt,
completedAt: row.completedAt,
assistantMessageId: row.assistantMessageId,
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
? {
sourceProposedPlan: {
threadId: row.sourceProposedPlanThreadId,
planId: row.sourceProposedPlanId,
},
}
: {}),
});
}
@@ -579,65 +517,36 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
}
const projects: ReadonlyArray<OrchestrationProject> = yield* Effect.forEach(
projectRows,
(row) => {
const defaultModelSelectionEffect: Effect.Effect<
OrchestrationProject["defaultModelSelection"],
ProjectionRepositoryError
> =
row.defaultProvider === null || row.defaultModel === null
? Effect.succeed(null)
: decodeModelSelection({
provider: row.defaultProvider,
model: row.defaultModel,
options: row.defaultModelOptions,
});
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModel: row.defaultModel,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}));
return defaultModelSelectionEffect.pipe(
Effect.map((defaultModelSelection) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
})),
);
},
);
const threads: ReadonlyArray<OrchestrationThread> = yield* Effect.forEach(
threadRows,
(row) =>
decodeModelSelection({
provider: row.provider,
model: row.model,
options: row.modelOptions,
}).pipe(
Effect.map((modelSelection) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
})),
),
);
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
model: row.model,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
@@ -646,13 +555,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
updatedAt: updatedAt ?? new Date(0).toISOString(),
};
return yield* Effect.try({
try: () => decodeReadModelSync(snapshot),
catch: (error) =>
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel")(
error as Schema.SchemaError,
),
});
return yield* decodeReadModel(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
),
);
}),
)
.pipe(
@@ -16,7 +16,7 @@ import {
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../../git/Errors.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
@@ -41,9 +41,6 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
@@ -63,9 +60,6 @@ async function waitFor(
return poll();
}
const inferTestProviderForModel = (model: string): "codex" | "claudeAgent" =>
model.startsWith("claude-") ? "claudeAgent" : "codex";
describe("ProviderCommandReactor", () => {
let runtime: ManagedRuntime.ManagedRuntime<
OrchestrationEngineService | ProviderCommandReactor,
@@ -73,7 +67,6 @@ describe("ProviderCommandReactor", () => {
> | null = null;
let scope: Scope.Closeable | null = null;
const createdStateDirs = new Set<string>();
const createdBaseDirs = new Set<string>();
afterEach(async () => {
if (scope) {
@@ -88,23 +81,12 @@ describe("ProviderCommandReactor", () => {
fs.rmSync(stateDir, { recursive: true, force: true });
}
createdStateDirs.clear();
for (const baseDir of createdBaseDirs) {
fs.rmSync(baseDir, { recursive: true, force: true });
}
createdBaseDirs.clear();
});
async function createHarness(input?: {
readonly baseDir?: string;
readonly threadModel?: string;
}) {
async function createHarness(input?: { readonly stateDir?: string }) {
const now = new Date().toISOString();
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
createdBaseDirs.add(baseDir);
const { stateDir } = deriveServerPathsSync(baseDir, undefined);
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
createdStateDirs.add(stateDir);
const threadModel = input?.threadModel ?? "gpt-5-codex";
const threadProvider = inferTestProviderForModel(threadModel);
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
let nextSessionIndex = 1;
const runtimeSessions: Array<ProviderSession> = [];
@@ -114,7 +96,7 @@ describe("ProviderCommandReactor", () => {
typeof input === "object" &&
input !== null &&
"provider" in input &&
(input.provider === "codex" || input.provider === "claudeAgent")
input.provider === "codex"
? input.provider
: "codex";
const resumeCursor =
@@ -147,7 +129,7 @@ describe("ProviderCommandReactor", () => {
: "full-access",
...(model !== undefined ? { model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
createdAt: now,
updatedAt: now,
};
@@ -228,7 +210,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
@@ -246,10 +228,7 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
defaultModelSelection: {
provider: threadProvider,
model: threadModel,
},
defaultModel: "gpt-5-codex",
createdAt: now,
}),
);
@@ -260,10 +239,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: threadProvider,
model: threadModel,
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -338,10 +314,10 @@ describe("ProviderCommandReactor", () => {
text: "hello fast mode",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -375,106 +351,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort"),
role: "user",
text: "hello with effort",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-fast-mode"),
role: "user",
text: "hello with fast mode",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
fastMode: true,
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
});
it("forwards plan interaction mode to the provider turn request", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -513,96 +389,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("rejects a first turn when requested provider conflicts with the thread model", 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-provider-first"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-first"),
role: "user",
text: "hello claude",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session).toBeNull();
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
summary: "Provider turn start failed",
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("allows custom model strings on the thread's explicit provider", 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-custom-model"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-custom-model"),
role: "user",
text: "hello",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "claude-sonnet-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "codex",
model: "claude-sonnet-4-6",
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
model: "claude-sonnet-4-6",
});
});
it("reuses the same provider session when runtime mode is unchanged", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -649,74 +435,6 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-1"),
role: "user",
text: "first claude turn",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "medium",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
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-claude-effort-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-2"),
role: "user",
text: "second claude turn",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
effort: "max",
},
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: "claudeAgent",
resumeCursor: { opaque: "resume-1" },
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -791,7 +509,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
resumeCursor: { opaque: "resume-1" },
resumeCursor: { opaque: "cursor-1" },
runtimeMode: "approval-required",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
@@ -804,80 +522,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("rejects provider changes after a thread is already bound to a session provider", 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-provider-switch-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
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-provider-switch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-2"),
role: "user",
text: "second",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.sendTurn.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerName).toBe("codex");
expect(thread?.session?.runtimeMode).toBe("approval-required");
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("does not stop the active session when restart fails before rebind", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1153,7 +797,6 @@ describe("ProviderCommandReactor", () => {
expect(failureActivity).toBeDefined();
expect(failureActivity?.payload).toMatchObject({
requestId: "approval-request-1",
detail: expect.stringContaining("Stale pending approval request: approval-request-1"),
});
const resolvedActivity = thread?.activities.find(
@@ -1166,117 +809,6 @@ describe("ProviderCommandReactor", () => {
expect(resolvedActivity).toBeUndefined();
});
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.respondToUserInput.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "claudeAgent",
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.makeUnsafe("cmd-user-input-requested"),
threadId: ThreadId.makeUnsafe("thread-1"),
activity: {
id: EventId.makeUnsafe("activity-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
requestId: "user-input-request-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
turnId: null,
createdAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("user-input-request-1"),
answers: {
sandbox_mode: "workspace-write",
},
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
if (!thread) return false;
return thread.activities.some(
(activity) => activity.kind === "provider.user-input.respond.failed",
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread).toBeDefined();
const failureActivity = thread?.activities.find(
(activity) => activity.kind === "provider.user-input.respond.failed",
);
expect(failureActivity).toBeDefined();
expect(failureActivity?.payload).toMatchObject({
requestId: "user-input-request-1",
detail: expect.stringContaining("Stale pending user-input request: user-input-request-1"),
});
const resolvedActivity = thread?.activities.find(
(activity) =>
activity.kind === "user-input.resolved" &&
typeof activity.payload === "object" &&
activity.payload !== null &&
(activity.payload as Record<string, unknown>).requestId === "user-input-request-1",
);
expect(resolvedActivity).toBeUndefined();
});
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -3,10 +3,9 @@ import {
CommandId,
DEFAULT_GIT_TEXT_GENERATION_MODEL,
EventId,
type ModelSelection,
type OrchestrationEvent,
type ProviderModelOptions,
ProviderKind,
type ProviderKind,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
@@ -76,22 +75,6 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
const sameModelOptions = (
left: ProviderModelOptions | undefined,
right: ProviderModelOptions | undefined,
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
function toProviderModelOptions(
modelSelection: ModelSelection | undefined,
): ProviderModelOptions | undefined {
if (!modelSelection?.options) {
return undefined;
}
return modelSelection.provider === "codex"
? { codex: modelSelection.options }
: { claudeAgent: modelSelection.options };
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
@@ -108,21 +91,6 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
);
}
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
}
function stalePendingRequestDetail(
requestKind: "approval" | "user-input",
requestId: string,
): string {
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
}
function isTemporaryWorktreeBranch(branch: string): boolean {
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
}
@@ -169,7 +137,6 @@ const make = Effect.gen(function* () {
);
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const threadModelOptions = new Map<string, ProviderModelOptions>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -226,7 +193,8 @@ const make = Effect.gen(function* () {
threadId: ThreadId,
createdAt: string,
options?: {
readonly modelSelection?: ModelSelection;
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
},
@@ -238,28 +206,10 @@ const make = Effect.gen(function* () {
}
const desiredRuntimeMode = thread.runtimeMode;
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
thread.session?.providerName,
)
? thread.session.providerName
: undefined;
const requestedModelSelection = options?.modelSelection;
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
if (
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== threadProvider
) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
});
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const desiredModel = desiredModelSelection.model;
const desiredModelOptions =
options?.modelOptions ?? toProviderModelOptions(desiredModelSelection);
const currentProvider: ProviderKind | undefined =
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
const desiredModel = options?.model ?? thread.model;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
@@ -276,10 +226,12 @@ const make = Effect.gen(function* () {
}) =>
providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
...((input?.provider ?? preferredProvider)
? { provider: input?.provider ?? preferredProvider }
: {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(desiredModelOptions !== undefined ? { modelOptions: desiredModelOptions } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(options?.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
@@ -308,29 +260,16 @@ const make = Effect.gen(function* () {
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
options?.provider !== undefined && options.provider !== currentProvider;
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelOptions = threadModelOptions.get(threadId);
const shouldRestartForModelOptionsChange =
currentProvider === "claudeAgent" &&
options?.modelOptions !== undefined &&
!sameModelOptions(previousModelOptions, options.modelOptions);
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelOptionsChange
) {
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
return existingSessionThreadId;
}
@@ -342,19 +281,19 @@ const make = Effect.gen(function* () {
threadId,
existingSessionThreadId,
currentProvider,
desiredProvider: desiredModelSelection.provider,
desiredProvider: options?.provider ?? currentProvider,
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
providerChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelOptionsChange,
hasResumeCursor: resumeCursor !== undefined,
});
const restartedSession = yield* startProviderSession(
resumeCursor !== undefined ? { resumeCursor } : undefined,
);
const restartedSession = yield* startProviderSession({
...(resumeCursor !== undefined ? { resumeCursor } : {}),
...(options?.provider !== undefined ? { provider: options.provider } : {}),
});
yield* Effect.logInfo("provider command reactor restarted provider session", {
threadId,
previousSessionId: existingSessionThreadId,
@@ -366,7 +305,9 @@ const make = Effect.gen(function* () {
return restartedSession.threadId;
}
const startedSession = yield* startProviderSession(undefined);
const startedSession = yield* startProviderSession(
options?.provider !== undefined ? { provider: options.provider } : undefined,
);
yield* bindSessionToThread(startedSession);
return startedSession.threadId;
});
@@ -375,7 +316,8 @@ const make = Effect.gen(function* () {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly modelSelection?: ModelSelection;
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly interactionMode?: "default" | "plan";
@@ -385,17 +327,15 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
if (input.modelOptions !== undefined) {
threadModelOptions.set(input.threadId, input.modelOptions);
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
@@ -407,8 +347,7 @@ const make = Effect.gen(function* () {
activeSession === undefined
? "in-session"
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
const modelForTurn =
sessionModelSwitch === "unsupported" ? activeSession?.model : input.modelSelection?.model;
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
yield* providerService.sendTurn({
threadId: input.threadId,
@@ -524,35 +463,21 @@ const make = Effect.gen(function* () {
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
}).pipe(Effect.forkScoped);
const requestedModelOptions = event.payload.modelSelection
? toProviderModelOptions(event.payload.modelSelection)
: undefined;
yield* sendTurnForThread({
threadId: event.payload.threadId,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.modelOptions !== undefined
? { modelOptions: event.payload.modelOptions }
: {}),
...(requestedModelOptions !== undefined ? { modelOptions: requestedModelOptions } : {}),
...(event.payload.providerOptions !== undefined
? { providerOptions: event.payload.providerOptions }
: {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
}).pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.turn.start.failed",
summary: "Provider turn start failed",
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
}),
),
);
});
});
const processTurnInterruptRequested = Effect.fnUntraced(function* (
@@ -611,9 +536,7 @@ const make = Effect.gen(function* () {
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
summary: "Provider approval response failed",
detail: isUnknownPendingApprovalRequestError(cause)
? stalePendingRequestDetail("approval", event.payload.requestId)
: Cause.pretty(cause),
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
@@ -657,9 +580,7 @@ const make = Effect.gen(function* () {
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
@@ -705,13 +626,13 @@ const make = Effect.gen(function* () {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
const cachedModelOptions = threadModelOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedProviderOptions !== undefined
? { providerOptions: cachedProviderOptions }
: {}),
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
});
: undefined,
);
return;
}
case "thread.turn-start-requested":
@@ -4,7 +4,6 @@ import path from "node:path";
import type {
OrchestrationReadModel,
ProviderKind,
ProviderRuntimeEvent,
ProviderSession,
} from "@t3tools/contracts";
@@ -50,7 +49,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -187,10 +186,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -201,10 +197,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -435,60 +428,6 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
const harness = await createHarness();
const seededAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
}),
);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-claude-placeholder"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-claude-placeholder",
);
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-claude-placeholder"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-claude-placeholder"),
status: "completed",
});
await waitForThread(
harness.engine,
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
);
});
it("ignores auxiliary turn completions from a different provider thread", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -730,10 +669,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
@@ -765,10 +701,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -917,10 +850,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
@@ -1070,10 +1000,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
@@ -1105,10 +1032,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -1946,7 +1870,6 @@ describe("ProviderRuntimeIngestion", () => {
payload: {
taskId: "turn-task-1",
description: "Comparing the desktop rollout chunks to the app-server stream.",
summary: "Code reviewer is validating the desktop rollout chunks.",
},
});
@@ -2009,9 +1932,8 @@ describe("ProviderRuntimeIngestion", () => {
expect(started?.kind).toBe("task.started");
expect(started?.summary).toBe("Plan task started");
expect(progress?.kind).toBe("task.progress");
expect(progressPayload?.detail).toBe("Code reviewer is validating the desktop rollout chunks.");
expect(progressPayload?.summary).toBe(
"Code reviewer is validating the desktop rollout chunks.",
expect(progressPayload?.detail).toBe(
"Comparing the desktop rollout chunks to the app-server stream.",
);
expect(completed?.kind).toBe("task.completed");
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
@@ -373,8 +373,7 @@ function runtimeEventToActivities(
summary: "Reasoning update",
payload: {
taskId: event.payload.taskId,
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
detail: truncateDetail(event.payload.description),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
@@ -28,10 +28,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
scripts: [],
createdAt: now,
updatedAt: now,
@@ -41,10 +38,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
scripts: [],
createdAt: now,
updatedAt: now,
@@ -56,10 +50,7 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "Thread A",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -78,10 +69,7 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-b"),
title: "Thread B",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -156,10 +144,7 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-3"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "new",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -180,10 +165,7 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "dup",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -59,7 +59,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -113,7 +113,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -136,10 +136,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -162,10 +159,10 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -192,10 +189,10 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -223,7 +220,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -246,10 +243,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -305,7 +299,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -328,10 +322,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
+7 -11
View File
@@ -77,7 +77,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
title: command.title,
workspaceRoot: command.workspaceRoot,
defaultModelSelection: command.defaultModelSelection ?? null,
defaultModel: command.defaultModel ?? null,
scripts: [],
createdAt: command.createdAt,
updatedAt: command.createdAt,
@@ -104,9 +104,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
...(command.defaultModelSelection !== undefined
? { defaultModelSelection: command.defaultModelSelection }
: {}),
...(command.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
updatedAt: occurredAt,
},
@@ -158,7 +156,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
projectId: command.projectId,
title: command.title,
modelSelection: command.modelSelection,
model: command.model,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
branch: command.branch,
@@ -209,9 +207,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: occurredAt,
@@ -327,9 +323,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
messageId: command.message.messageId,
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined
? { providerOptions: command.providerOptions }
: {}),
@@ -56,10 +56,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -76,10 +73,7 @@ describe("orchestration projector", () => {
id: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -116,10 +110,7 @@ describe("orchestration projector", () => {
// missing required threadId
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: now,
@@ -179,10 +170,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -245,10 +233,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -302,10 +287,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -389,10 +371,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -604,10 +583,7 @@ describe("orchestration projector", () => {
threadId: "thread-revert",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -757,10 +733,7 @@ describe("orchestration projector", () => {
threadId: "thread-capped",
projectId: "project-1",
title: "capped",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
+5 -7
View File
@@ -181,7 +181,7 @@ export function projectEvent(
id: payload.projectId,
title: payload.title,
workspaceRoot: payload.workspaceRoot,
defaultModelSelection: payload.defaultModelSelection,
defaultModel: payload.defaultModel,
scripts: payload.scripts,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
@@ -211,8 +211,8 @@ export function projectEvent(
...(payload.workspaceRoot !== undefined
? { workspaceRoot: payload.workspaceRoot }
: {}),
...(payload.defaultModelSelection !== undefined
? { defaultModelSelection: payload.defaultModelSelection }
...(payload.defaultModel !== undefined
? { defaultModel: payload.defaultModel }
: {}),
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
updatedAt: payload.updatedAt,
@@ -252,7 +252,7 @@ export function projectEvent(
id: payload.threadId,
projectId: payload.projectId,
title: payload.title,
modelSelection: payload.modelSelection,
model: payload.model,
runtimeMode: payload.runtimeMode,
interactionMode: payload.interactionMode,
branch: payload.branch,
@@ -295,9 +295,7 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.modelSelection !== undefined
? { modelSelection: payload.modelSelection }
: {}),
...(payload.model !== undefined ? { model: payload.model } : {}),
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
updatedAt: payload.updatedAt,
+2 -2
View File
@@ -27,10 +27,10 @@ export const expandHomePath = Effect.fn(function* (input: string) {
return input;
});
export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
export const resolveStateDir = Effect.fn(function* (raw: string | undefined) {
const { join, resolve } = yield* Path.Path;
if (!raw || raw.trim().length === 0) {
return join(OS.homedir(), ".t3");
return join(OS.homedir(), ".t3", "userdata");
}
return resolve(yield* expandHomePath(raw.trim()));
});
@@ -35,7 +35,7 @@ layer("OrchestrationEventStore", (it) => {
projectId: ProjectId.makeUnsafe("project-roundtrip"),
title: "Roundtrip Project",
workspaceRoot: "/tmp/project-roundtrip",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -1,13 +1,9 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Option, Schema } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
import {
PersistenceDecodeError,
toPersistenceDecodeError,
toPersistenceSqlError,
} from "../Errors.ts";
import {
DeleteProjectionProjectInput,
GetProjectionProjectInput,
@@ -15,100 +11,69 @@ import {
ProjectionProjectRepository,
type ProjectionProjectRepositoryShape,
} from "../Services/ProjectionProjects.ts";
import { ProjectScript } from "@t3tools/contracts";
const ProjectionProjectDbRow = Schema.Struct({
projectId: ProjectionProject.fields.projectId,
title: ProjectionProject.fields.title,
workspaceRoot: ProjectionProject.fields.workspaceRoot,
defaultProvider: Schema.NullOr(Schema.Literals(["codex", "claudeAgent"])),
defaultModel: Schema.NullOr(Schema.String),
defaultModelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
createdAt: ProjectionProject.fields.createdAt,
updatedAt: ProjectionProject.fields.updatedAt,
deletedAt: ProjectionProject.fields.deletedAt,
});
type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;
// Makes sure that the scripts are parsed from the JSON string the DB returns
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
Struct.assign({ scripts: Schema.fromJsonString(Schema.Array(ProjectScript)) }),
);
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
function decodeDefaultModelSelection(
row: ProjectionProjectDbRow,
): Effect.Effect<ProjectionProject["defaultModelSelection"], PersistenceDecodeError> {
if (row.defaultProvider === null || row.defaultModel === null) {
return Effect.succeed(null);
}
return Effect.try({
try: () =>
decodeModelSelectionSync({
provider: row.defaultProvider,
model: row.defaultModel,
...(row.defaultModelOptions !== null ? { options: row.defaultModelOptions } : {}),
}),
catch: (error) =>
toPersistenceDecodeError("ProjectionProjectRepository.decodeDefaultModelSelection")(
error as Schema.SchemaError,
),
});
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown) =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
}
const makeProjectionProjectRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionProjectRow = SqlSchema.void({
Request: ProjectionProject,
Request: ProjectionProjectDbRowSchema,
execute: (row) =>
sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_provider,
default_model,
default_model_options_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
${row.projectId},
${row.title},
${row.workspaceRoot},
${row.defaultModelSelection?.provider ?? null},
${row.defaultModelSelection?.model ?? null},
${JSON.stringify(row.defaultModelSelection?.options ?? null)},
${JSON.stringify(row.scripts)},
${row.createdAt},
${row.updatedAt},
${row.deletedAt}
)
ON CONFLICT (project_id)
DO UPDATE SET
title = excluded.title,
workspace_root = excluded.workspace_root,
default_provider = excluded.default_provider,
default_model = excluded.default_model,
default_model_options_json = excluded.default_model_options_json,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
deleted_at = excluded.deleted_at
`,
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
${row.projectId},
${row.title},
${row.workspaceRoot},
${row.defaultModel},
${row.scripts},
${row.createdAt},
${row.updatedAt},
${row.deletedAt}
)
ON CONFLICT (project_id)
DO UPDATE SET
title = excluded.title,
workspace_root = excluded.workspace_root,
default_model = excluded.default_model,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
deleted_at = excluded.deleted_at
`,
});
const getProjectionProjectRow = SqlSchema.findOneOption({
Request: GetProjectionProjectInput,
Result: ProjectionProjectDbRow,
Result: ProjectionProjectDbRowSchema,
execute: ({ projectId }) =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_provider AS "defaultProvider",
default_model AS "defaultModel",
default_model_options_json AS "defaultModelOptions",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -120,16 +85,14 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
const listProjectionProjectRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionProjectDbRow,
Result: ProjectionProjectDbRowSchema,
execute: () =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_provider AS "defaultProvider",
default_model AS "defaultModel",
default_model_options_json AS "defaultModelOptions",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -150,53 +113,40 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) =>
upsertProjectionProjectRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")),
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionProjectRepository.upsert:query",
"ProjectionProjectRepository.upsert:encodeRequest",
),
),
);
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
getProjectionProjectRow(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
Effect.flatMap(
Option.match({
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionProjectRepository.getById:query",
"ProjectionProjectRepository.getById:decodeRow",
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeDefaultModelSelection(row).pipe(
Effect.map((defaultModelSelection) =>
Option.some({
projectId: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}),
),
),
Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionProject>)),
}),
),
);
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
listProjectionProjectRows().pipe(
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
decodeDefaultModelSelection(row).pipe(
Effect.map((defaultModelSelection) => ({
projectId: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
})),
),
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionProjectRepository.listAll:query",
"ProjectionProjectRepository.listAll:decodeRows",
),
),
Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionProject>>),
);
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
@@ -1,9 +1,8 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Option, Schema } from "effect";
import { Effect, Layer } from "effect";
import { ModelSelection } from "@t3tools/contracts";
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
DeleteProjectionThreadInput,
GetProjectionThreadInput,
@@ -13,53 +12,6 @@ import {
type ProjectionThreadRepositoryShape,
} from "../Services/ProjectionThreads.ts";
const ProjectionThreadDbRow = Schema.Struct({
threadId: ProjectionThread.fields.threadId,
projectId: ProjectionThread.fields.projectId,
title: ProjectionThread.fields.title,
provider: Schema.Literals(["codex", "claudeAgent"]),
model: Schema.String,
modelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
runtimeMode: ProjectionThread.fields.runtimeMode,
interactionMode: ProjectionThread.fields.interactionMode,
branch: ProjectionThread.fields.branch,
worktreePath: ProjectionThread.fields.worktreePath,
latestTurnId: ProjectionThread.fields.latestTurnId,
createdAt: ProjectionThread.fields.createdAt,
updatedAt: ProjectionThread.fields.updatedAt,
deletedAt: ProjectionThread.fields.deletedAt,
});
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
function decodeProjectionThread(row: ProjectionThreadDbRow) {
return Effect.try({
try: () => ({
threadId: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: decodeModelSelectionSync({
provider: row.provider,
model: row.model,
...(row.modelOptions !== null ? { options: row.modelOptions } : {}),
}),
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurnId: row.latestTurnId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}),
catch: (error) =>
toPersistenceDecodeError("ProjectionThreadRepository.decodeProjectionThread")(
error as Schema.SchemaError,
),
});
}
const makeProjectionThreadRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -71,9 +23,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id,
project_id,
title,
provider,
model,
model_options_json,
runtime_mode,
interaction_mode,
branch,
@@ -87,9 +37,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.threadId},
${row.projectId},
${row.title},
${row.modelSelection.provider},
${row.modelSelection.model},
${JSON.stringify(row.modelSelection.options ?? null)},
${row.model},
${row.runtimeMode},
${row.interactionMode},
${row.branch},
@@ -103,9 +51,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
DO UPDATE SET
project_id = excluded.project_id,
title = excluded.title,
provider = excluded.provider,
model = excluded.model,
model_options_json = excluded.model_options_json,
runtime_mode = excluded.runtime_mode,
interaction_mode = excluded.interaction_mode,
branch = excluded.branch,
@@ -119,16 +65,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
const getProjectionThreadRow = SqlSchema.findOneOption({
Request: GetProjectionThreadInput,
Result: ProjectionThreadDbRow,
Result: ProjectionThread,
execute: ({ threadId }) =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
provider,
model,
model_options_json AS "modelOptions",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
@@ -144,16 +88,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
const listProjectionThreadRows = SqlSchema.findAll({
Request: ListProjectionThreadsByProjectInput,
Result: ProjectionThreadDbRow,
Result: ProjectionThread,
execute: ({ projectId }) =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
provider,
model,
model_options_json AS "modelOptions",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
@@ -185,18 +127,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
const getById: ProjectionThreadRepositoryShape["getById"] = (input) =>
getProjectionThreadRow(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")),
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none()),
onSome: (row) => decodeProjectionThread(row).pipe(Effect.map(Option.some)),
}),
),
);
const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) =>
listProjectionThreadRows(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")),
Effect.flatMap((rows) => Effect.forEach(rows, decodeProjectionThread)),
);
const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) =>
@@ -47,8 +47,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
@@ -63,8 +61,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.pendingMessageId},
${row.sourceProposedPlanThreadId},
${row.sourceProposedPlanId},
${row.assistantMessageId},
${row.state},
${row.requestedAt},
@@ -78,8 +74,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
ON CONFLICT (thread_id, turn_id)
DO UPDATE SET
pending_message_id = excluded.pending_message_id,
source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,
source_proposed_plan_id = excluded.source_proposed_plan_id,
assistant_message_id = excluded.assistant_message_id,
state = excluded.state,
requested_at = excluded.requested_at,
@@ -174,8 +168,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
@@ -207,8 +199,6 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
pending_message_id AS "pendingMessageId",
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
source_proposed_plan_id AS "sourceProposedPlanId",
assistant_message_id AS "assistantMessageId",
state,
requested_at AS "requestedAt",
+6 -3
View File
@@ -49,6 +49,9 @@ export const SqlitePersistenceMemory = Layer.provideMerge(
makeRuntimeSqliteLayer({ filename: ":memory:" }),
);
export const layerConfig = Layer.unwrap(
Effect.map(Effect.service(ServerConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
);
export const layerConfig = Effect.gen(function* () {
const { stateDir } = yield* ServerConfig;
const { join } = yield* Path.Path;
const dbPath = join(stateDir, "state.sqlite");
return makeSqlitePersistenceLive(dbPath);
}).pipe(Layer.unwrap);
@@ -27,8 +27,6 @@ import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts"
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import Migration0016 from "./Migrations/016_ProjectionProviders.ts";
import Migration0017 from "./Migrations/017_ProjectionModelSelectionOptions.ts";
import { Effect } from "effect";
/**
@@ -57,8 +55,6 @@ const loader = Migrator.fromRecord({
"13_ProjectionThreadProposedPlans": Migration0013,
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
"16_ProjectionProviders": Migration0016,
"17_ProjectionModelSelectionOptions": Migration0017,
});
/**
@@ -1,38 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN default_provider TEXT
`;
yield* sql`
UPDATE projection_projects
SET default_provider = CASE
WHEN default_model IS NULL THEN NULL
ELSE 'codex'
END
WHERE default_provider IS NULL
`;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN provider TEXT
`;
yield* sql`
UPDATE projection_threads
SET provider = COALESCE(
(
SELECT provider_name
FROM projection_thread_sessions
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
),
'codex'
)
WHERE provider IS NULL
`;
});
@@ -1,28 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN default_model_options_json TEXT
`;
yield* sql`
UPDATE projection_projects
SET default_model_options_json = NULL
WHERE default_model_options_json IS NULL
`;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN model_options_json TEXT
`;
yield* sql`
UPDATE projection_threads
SET model_options_json = NULL
WHERE model_options_json IS NULL
`;
});
@@ -6,7 +6,7 @@
*
* @module ProjectionProjectRepository
*/
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
import { IsoDateTime, ProjectId, ProjectScript } from "@t3tools/contracts";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
@@ -16,7 +16,7 @@ export const ProjectionProject = Schema.Struct({
projectId: ProjectId,
title: Schema.String,
workspaceRoot: Schema.String,
defaultModelSelection: Schema.NullOr(ModelSelection),
defaultModel: Schema.NullOr(Schema.String),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -8,7 +8,6 @@
*/
import {
IsoDateTime,
ModelSelection,
ProjectId,
ProviderInteractionMode,
RuntimeMode,
@@ -24,7 +23,7 @@ export const ProjectionThread = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: Schema.String,
modelSelection: ModelSelection,
model: Schema.String,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
branch: Schema.NullOr(Schema.String),
@@ -35,8 +35,6 @@ export const ProjectionTurn = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
pendingMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
assistantMessageId: Schema.NullOr(MessageId),
state: ProjectionTurnState,
requestedAt: IsoDateTime,
@@ -53,8 +51,6 @@ export const ProjectionTurnById = Schema.Struct({
threadId: ThreadId,
turnId: TurnId,
pendingMessageId: Schema.NullOr(MessageId),
sourceProposedPlanThreadId: Schema.NullOr(ThreadId),
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
assistantMessageId: Schema.NullOr(MessageId),
state: ProjectionTurnState,
requestedAt: IsoDateTime,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -22,7 +22,6 @@ import {
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
@@ -157,29 +156,6 @@ const validationLayer = it.layer(
);
validationLayer("CodexAdapterLive validation", (it) => {
it.effect("returns validation error for non-codex provider on startSession", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: "claudeAgent",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
})
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
assert.deepStrictEqual(
result.failure,
new ProviderAdapterValidationError({
provider: "codex",
operation: "startSession",
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
);
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
}),
);
it.effect("maps codex model options before starting a session", () =>
Effect.gen(function* () {
validationManager.startSessionImpl.mockClear();
@@ -800,45 +776,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}
}),
);
it.effect("prefers manager-assigned turn ids for Codex task events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started-parent-turn"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-parent"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-child",
msg: {
type: "task_started",
turn_id: "turn-child",
collaboration_mode_kind: "default",
},
conversationId: "child-provider-thread",
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "task.started");
if (firstEvent.value.type !== "task.started") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-parent");
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
});
afterAll(() => {
@@ -109,14 +109,6 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function toTurnId(value: string | undefined): TurnId | undefined {
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
}
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined;
}
function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
switch (value) {
case "completed":
@@ -423,27 +415,27 @@ function codexEventBase(
): Omit<ProviderRuntimeEvent, "type" | "payload"> {
const payload = asObject(event.payload);
const msg = codexEventMessage(payload);
const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId));
const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId));
const turnId = asString(msg?.turn_id) ?? asString(msg?.turnId);
const itemId = asString(msg?.item_id) ?? asString(msg?.itemId);
const requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
const base = runtimeEventBase(event, canonicalThreadId);
const providerRefs = base.providerRefs
? {
...base.providerRefs,
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
}
: {
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: itemId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
};
return {
...base,
...(turnId ? { turnId } : {}),
...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}),
...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
};
@@ -1336,7 +1328,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment,
});
if (!attachmentPath) {
@@ -4,7 +4,6 @@ import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { ClaudeAdapter, ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
@@ -28,32 +27,9 @@ const fakeCodexAdapter: CodexAdapterShape = {
streamEvents: Stream.empty,
};
const fakeClaudeAdapter: ClaudeAdapterShape = {
provider: "claudeAgent",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
),
),
Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),
NodeServices.layer,
),
);
@@ -63,12 +39,10 @@ layer("ProviderAdapterRegistryLive", (it) => {
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeAgent"]);
assert.deepEqual(providers, ["codex"]);
}),
);
@@ -1,7 +1,7 @@
/**
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
*
* Binds provider kinds (codex/claudeAgent/...) to concrete adapter services.
* Binds provider kinds (codex/cursor/...) to concrete adapter services.
* This layer only performs adapter lookup; it does not route session-scoped
* calls or own provider lifecycle workflows.
*
@@ -15,7 +15,6 @@ import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
export interface ProviderAdapterRegistryLiveOptions {
@@ -24,10 +23,7 @@ export interface ProviderAdapterRegistryLiveOptions {
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
Effect.gen(function* () {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter];
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -5,11 +5,9 @@ import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkClaudeProviderStatus,
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
parseClaudeAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./ProviderHealth";
@@ -466,175 +464,4 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
}),
);
});
// ── checkClaudeProviderStatus tests ──────────────────────────
describe("checkClaudeProviderStatus", () => {
it.effect("returns ready when claude is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when claude is missing", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
);
it.effect("returns error when version check fails with non-zero exit code", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version")
return { stdout: "", stderr: "Something went wrong", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth status reports not logged in", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 1,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status") return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when auth status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
describe("parseClaudeAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"ok":true}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
});
+11 -207
View File
@@ -26,7 +26,6 @@ import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHe
const DEFAULT_TIMEOUT_MS = 4_000;
const CODEX_PROVIDER = "codex" as const;
const CLAUDE_AGENT_PROVIDER = "claudeAgent" as const;
// ── Pure helpers ────────────────────────────────────────────────────
@@ -45,7 +44,12 @@ function nonEmptyTrimmed(value: string | undefined): string | undefined {
function isCommandMissingCause(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const lower = error.message.toLowerCase();
return lower.includes("enoent") || lower.includes("notfound");
return (
lower.includes("command not found: codex") ||
lower.includes("spawn codex enoent") ||
lower.includes("enoent") ||
lower.includes("notfound")
);
}
function detailFromResult(
@@ -260,27 +264,6 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("claude", [...args], {
shell: process.platform === "win32",
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
// ── Health check ────────────────────────────────────────────────────
export const checkCodexProviderStatus: Effect.Effect<
@@ -407,197 +390,18 @@ export const checkCodexProviderStatus: Effect.Effect<
} satisfies ServerProviderStatus;
});
// ── Claude Agent health check ───────────────────────────────────────
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
// `claude auth status` returns JSON with a `loggedIn` boolean.
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
export const checkClaudeProviderStatus: Effect.Effect<
ServerProviderStatus,
never,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.gen(function* () {
const checkedAt = new Date().toISOString();
// Probe 1: `claude --version` — is the CLI reachable?
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
};
}
if (Option.isNone(versionProbe.success)) {
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: "Claude Agent CLI is installed but failed to run. Timed out while running command.",
};
}
const version = versionProbe.success.value;
if (version.code !== 0) {
const detail = detailFromResult(version);
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
};
}
// Probe 2: `claude auth status` — is the user authenticated?
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
};
}
if (Option.isNone(authProbe.success)) {
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Could not verify Claude authentication status. Timed out while running command.",
};
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return {
provider: CLAUDE_AGENT_PROVIDER,
status: parsed.status,
available: true,
authStatus: parsed.authStatus,
checkedAt,
...(parsed.message ? { message: parsed.message } : {}),
} satisfies ServerProviderStatus;
});
// ── Layer ───────────────────────────────────────────────────────────
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
concurrency: "unbounded",
}).pipe(Effect.forkScoped);
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
Effect.map(Array.of),
Effect.forkScoped,
);
return {
getStatuses: Fiber.join(statusesFiber),
getStatuses: Fiber.join(codexStatusFiber),
} satisfies ProviderHealthShape;
}),
);
@@ -52,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
@@ -74,7 +74,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
status: "ready",
runtimeMode: input.runtimeMode,
threadId: input.threadId,
resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` },
resumeCursor: input.resumeCursor ?? { opaque: `cursor-${String(input.threadId)}` },
cwd: input.cwd ?? process.cwd(),
createdAt: now,
updatedAt: now,
@@ -195,21 +195,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
const updateSession = (
threadId: ThreadId,
update: (session: ProviderSession) => ProviderSession,
): void => {
const existing = sessions.get(threadId);
if (!existing) {
return;
}
sessions.set(threadId, update(existing));
};
return {
adapter,
emit,
updateSession,
startSession,
sendTurn,
interruptTurn,
@@ -229,15 +217,12 @@ const sleep = (ms: number) =>
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(codex.adapter)
: provider === "claudeAgent"
? Effect.succeed(claude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex"]),
};
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
@@ -262,7 +247,6 @@ function makeProviderServiceLayer() {
return {
codex,
claude,
layer,
};
}
@@ -360,29 +344,16 @@ it.effect(
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const updatedResumeCursor = {
threadId: asThreadId("thread-1"),
resume: "resume-session-1",
resumeSessionAt: "assistant-message-1",
turnCount: 1,
};
const startedSession = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const threadId = asThreadId("thread-1");
const session = yield* provider.startSession(threadId, {
return yield* provider.startSession(threadId, {
provider: "codex",
cwd: "/tmp/project",
runtimeMode: "full-access",
threadId,
});
firstCodex.updateSession(threadId, (existing) => ({
...existing,
status: "ready",
resumeCursor: updatedResumeCursor,
updatedAt: new Date(Date.now() + 1_000).toISOString(),
}));
return session;
}).pipe(Effect.provide(firstProviderLayer));
const persistedAfterStopAll = yield* Effect.gen(function* () {
@@ -392,7 +363,7 @@ it.effect(
assert.equal(Option.isSome(persistedAfterStopAll), true);
if (Option.isSome(persistedAfterStopAll)) {
assert.equal(persistedAfterStopAll.value.status, "stopped");
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor);
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, startedSession.resumeCursor);
}
const secondCodex = makeFakeCodexAdapter();
@@ -435,7 +406,7 @@ it.effect(
};
assert.equal(startPayload.provider, "codex");
assert.equal(startPayload.cwd, "/tmp/project");
assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor);
assert.deepEqual(startPayload.resumeCursor, startedSession.resumeCursor);
assert.equal(startPayload.threadId, startedSession.threadId);
}
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
@@ -562,29 +533,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-claude"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude"),
cwd: "/tmp/project-claude",
runtimeMode: "full-access",
});
assert.equal(session.provider, "claudeAgent");
assert.equal(routing.claude.startSession.mock.calls.length, 1);
const startInput = routing.claude.startSession.mock.calls[0]?.[0];
assert.equal(typeof startInput === "object" && startInput !== null, true);
if (startInput && typeof startInput === "object") {
const startPayload = startInput as { provider?: string; cwd?: string };
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude");
}
}),
);
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -625,57 +573,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-send-turn"),
cwd: "/tmp/project-claude-send-turn",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
runtimeMode: "full-access",
});
yield* routing.claude.stopAll();
routing.claude.startSession.mockClear();
routing.claude.sendTurn.mockClear();
yield* provider.sendTurn({
threadId: initial.threadId,
input: "resume with claude",
attachments: [],
});
assert.equal(routing.claude.startSession.mock.calls.length, 1);
const resumedStartInput = routing.claude.startSession.mock.calls[0]?.[0];
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
if (resumedStartInput && typeof resumedStartInput === "object") {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
modelOptions?: unknown;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
assert.deepEqual(startPayload.modelOptions, {
claudeAgent: {
effort: "max",
},
});
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.threadId, initial.threadId);
}
assert.equal(routing.claude.sendTurn.mock.calls.length, 1);
}),
);
it.effect("lists no sessions after adapter runtime clears", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -692,7 +589,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
});
yield* routing.codex.stopAll();
yield* routing.claude.stopAll();
const remaining = yield* provider.listSessions();
assert.equal(remaining.length, 0);
@@ -741,96 +637,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}
}),
);
it.effect("reuses persisted resume cursor when startSession is called after a restart", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-start-"));
const dbPath = path.join(tempDir, "orchestration.sqlite");
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(persistenceLayer),
);
const firstClaude = makeFakeCodexAdapter("claudeAgent");
const firstRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "claudeAgent"
? Effect.succeed(firstClaude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["claudeAgent"]),
};
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const initial = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession(asThreadId("thread-claude-start"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-start"),
cwd: "/tmp/project-claude-start",
runtimeMode: "full-access",
});
}).pipe(Effect.provide(firstProviderLayer));
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.listSessions();
}).pipe(Effect.provide(firstProviderLayer));
const secondClaude = makeFakeCodexAdapter("claudeAgent");
const secondRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "claudeAgent"
? Effect.succeed(secondClaude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["claudeAgent"]),
};
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
secondClaude.startSession.mockClear();
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.startSession(initial.threadId, {
provider: "claudeAgent",
threadId: initial.threadId,
cwd: "/tmp/project-claude-start",
runtimeMode: "full-access",
});
}).pipe(Effect.provide(secondProviderLayer));
assert.equal(secondClaude.startSession.mock.calls.length, 1);
const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0];
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
if (resumedStartInput && typeof resumedStartInput === "object") {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-start");
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.threadId, initial.threadId);
}
fs.rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
});
const fanout = makeProviderServiceLayer();
@@ -848,7 +654,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
const consumer = yield* Stream.runForEach(provider.streamEvents, (event) =>
Ref.update(eventsRef, (current) => [...current, event]),
).pipe(Effect.forkChild);
yield* sleep(50);
yield* sleep(20);
const completedEvent: LegacyProviderRuntimeEvent = {
type: "turn.completed",
@@ -861,7 +667,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
};
fanout.codex.emit(completedEvent);
yield* sleep(50);
yield* sleep(20);
const events = yield* Ref.get(eventsRef);
yield* Fiber.interrupt(consumer);
@@ -887,7 +693,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])),
Effect.forkChild,
);
yield* sleep(50);
yield* sleep(20);
fanout.codex.emit({
type: "tool.started",
@@ -951,7 +757,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
Stream.runForEach(() => Effect.fail("listener crash")),
Effect.forkChild,
);
yield* sleep(50);
yield* sleep(20);
const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
{
@@ -88,38 +88,17 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: {
readonly modelOptions?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
extra?: { readonly providerOptions?: unknown },
): Record<string, unknown> {
return {
cwd: session.cwd ?? null,
model: session.model ?? null,
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
...(extra?.lastRuntimeEventAt !== undefined
? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
: {}),
};
}
function readPersistedModelOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "modelOptions" in runtimePayload ? runtimePayload.modelOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
}
function readPersistedProviderOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
@@ -171,12 +150,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelOptions?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
extra?: { readonly providerOptions?: unknown },
) =>
directory.upsert({
threadId,
@@ -191,6 +165,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const adapters = yield* Effect.forEach(providers, (provider) =>
registry.getByProvider(provider),
);
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
publishRuntimeEvent(event);
@@ -238,14 +213,12 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
@@ -308,17 +281,8 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
threadId,
provider: parsed.provider ?? "codex",
};
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider
? persistedBinding.resumeCursor
: undefined);
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
const session = yield* adapter.startSession(input);
if (session.provider !== adapter.provider) {
return yield* toValidationError(
@@ -328,7 +292,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId, {
modelOptions: input.modelOptions,
providerOptions: input.providerOptions,
});
yield* analytics.record("provider.session.started", {
@@ -535,17 +498,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const runStopAll = () =>
Effect.gen(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
).pipe(
Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
);
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
@@ -141,8 +141,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
yield* runtimeRepository.upsert({
threadId,
providerName: "claudeAgent",
adapterKey: "claudeAgent",
providerName: "cursor",
adapterKey: "cursor",
runtimeMode: "full-access",
status: "running",
lastSeenAt: new Date().toISOString(),
@@ -22,7 +22,7 @@ function decodeProviderKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
if (providerName === "codex" || providerName === "claudeAgent") {
if (providerName === "codex") {
return Effect.succeed(providerName);
}
return Effect.fail(
@@ -1,30 +0,0 @@
/**
* ClaudeAdapter - Claude Agent implementation of the generic provider adapter contract.
*
* This service owns Claude runtime/session semantics and emits canonical
* provider runtime events. It does not perform cross-provider routing, shared
* event fan-out, or checkpoint orchestration.
*
* Uses Effect `ServiceMap.Service` for dependency injection and returns the
* shared provider-adapter error channel with `provider: "claudeAgent"` context.
*
* @module ClaudeAdapter
*/
import { ServiceMap } from "effect";
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
/**
* ClaudeAdapterShape - Service API for the Claude Agent provider adapter.
*/
export interface ClaudeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
readonly provider: "claudeAgent";
}
/**
* ClaudeAdapter - Service tag for Claude Agent provider adapter operations.
*/
export class ClaudeAdapter extends ServiceMap.Service<ClaudeAdapter, ClaudeAdapterShape>()(
"t3/provider/Services/ClaudeAdapter",
) {}
@@ -1,8 +1,8 @@
/**
* ProviderHealth - Provider readiness snapshot service.
*
* Owns provider health checks (install/auth reachability) and exposes the
* latest results to transport layers.
* Owns startup-time provider health checks (install/auth reachability) and
* exposes the cached results to transport layers.
*
* @module ProviderHealth
*/
@@ -12,7 +12,7 @@ import type { Effect } from "effect";
export interface ProviderHealthShape {
/**
* Read the latest provider health statuses.
* Read provider health statuses computed at server startup.
*/
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
}
+22 -32
View File
@@ -1,5 +1,7 @@
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer, Path } from "effect";
import { Effect, FileSystem, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
@@ -17,7 +19,6 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
import { ProviderUnsupportedError } from "./provider/Errors";
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
@@ -31,33 +32,20 @@ import { GitManagerLive } from "./git/Layers/GitManager";
import { GitCoreLive } from "./git/Layers/GitCore";
import { GitHubCliLive } from "./git/Layers/GitHubCli";
import { CodexTextGenerationLive } from "./git/Layers/CodexTextGeneration";
import { PtyAdapter } from "./terminal/Services/PTY";
import { GitServiceLive } from "./git/Layers/GitService";
import { BunPtyAdapterLive } from "./terminal/Layers/BunPTY";
import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
type RuntimePtyAdapterLoader = {
layer: Layer.Layer<PtyAdapter, never, FileSystem.FileSystem | Path.Path>;
};
const runtimePtyAdapterLoaders = {
bun: () => import("./terminal/Layers/BunPTY"),
node: () => import("./terminal/Layers/NodePTY"),
} satisfies Record<string, () => Promise<RuntimePtyAdapterLoader>>;
const makeRuntimePtyAdapterLayer = () =>
Effect.gen(function* () {
const runtime = process.versions.bun !== undefined ? "bun" : "node";
const loader = runtimePtyAdapterLoaders[runtime];
const ptyAdapterModule = yield* Effect.promise<RuntimePtyAdapterLoader>(loader);
return ptyAdapterModule.layer;
}).pipe(Layer.unwrap);
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
ProviderUnsupportedError,
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
> {
return Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const { stateDir } = yield* ServerConfig;
const providerLogsDir = path.join(stateDir, "logs", "provider");
const providerEventLogPath = path.join(providerLogsDir, "events.log");
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
@@ -70,12 +58,8 @@ export function makeServerProviderLayer(): Layer.Layer<
const codexAdapterLayer = makeCodexAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const claudeAdapterLayer = makeClaudeAdapterLive(
nativeEventLogger ? { nativeEventLogger } : undefined,
);
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
Layer.provide(codexAdapterLayer),
Layer.provide(claudeAdapterLayer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
return makeProviderServiceLive(
@@ -85,8 +69,8 @@ export function makeServerProviderLayer(): Layer.Layer<
}
export function makeServerRuntimeServicesLayer() {
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
const textGenerationLayer = CodexTextGenerationLive;
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -96,13 +80,13 @@ export function makeServerRuntimeServicesLayer() {
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(checkpointStoreLayer),
Layer.provideMerge(CheckpointStoreLive),
);
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
checkpointStoreLayer,
CheckpointStoreLive,
checkpointDiffQueryLayer,
RuntimeReceiptBusLive,
);
@@ -111,7 +95,7 @@ export function makeServerRuntimeServicesLayer() {
);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
@@ -123,17 +107,23 @@ export function makeServerRuntimeServicesLayer() {
Layer.provideMerge(checkpointReactorLayer),
);
const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer()));
const terminalLayer = TerminalManagerLive.pipe(
Layer.provide(
typeof Bun !== "undefined" && process.platform !== "win32"
? BunPtyAdapterLive
: NodePtyAdapterLive,
),
);
const gitManagerLayer = GitManagerLive.pipe(
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(textGenerationLayer),
);
return Layer.mergeAll(
orchestrationReactorLayer,
GitCoreLive,
gitCoreLayer,
gitManagerLayer,
terminalLayer,
KeybindingsLive,
+7 -3
View File
@@ -1,4 +1,5 @@
import fs from "node:fs";
import path from "node:path";
import { Effect, Logger } from "effect";
import * as Layer from "effect/Layer";
@@ -6,13 +7,16 @@ import * as Layer from "effect/Layer";
import { ServerConfig } from "./config";
export const ServerLoggerLive = Effect.gen(function* () {
const { logsDir, serverLogPath } = yield* ServerConfig;
const config = yield* ServerConfig;
const logDir = path.join(config.stateDir, "logs");
const logPath = path.join(logDir, "server.log");
yield* Effect.sync(() => {
fs.mkdirSync(logsDir, { recursive: true });
fs.mkdirSync(logDir, { recursive: true });
});
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath));
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(logPath));
return Logger.layer([Logger.defaultLogger, fileLogger], {
mergeWithExisting: false,
+4 -25
View File
@@ -9,10 +9,6 @@ const CodexAuthJsonSchema = Schema.Struct({
}),
});
const ClaudeJsonSchema = Schema.Struct({
userID: Schema.String,
});
class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("IdentifyUserError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
@@ -41,23 +37,12 @@ const getCodexAccountId = Effect.gen(function* () {
return authJson.tokens.account_id;
});
const getClaudeUserId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const claudeJsonPath = path.join(homedir(), ".claude.json");
const claudeJson = yield* Effect.flatMap(
fileSystem.readFileString(claudeJsonPath),
Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema)),
);
return claudeJson.userID;
});
const upsertAnonymousId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const { anonymousIdPath } = yield* ServerConfig;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const anonymousIdPath = path.join(serverConfig.stateDir, "anonymous-id");
const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
Effect.catch(() =>
Effect.gen(function* () {
@@ -74,8 +59,7 @@ const upsertAnonymousId = Effect.gen(function* () {
/**
* getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
* 1. ~/.codex/auth.json tokens.account_id
* 2. ~/.claude.json userID
* 3. ~/.t3/telemetry/anonymous-id
* 2. ~/.t3/telemetry/anonymous-id
*/
export const getTelemetryIdentifier = Effect.gen(function* () {
const codexAccountId = yield* Effect.result(getCodexAccountId);
@@ -83,11 +67,6 @@ export const getTelemetryIdentifier = Effect.gen(function* () {
return yield* hash(codexAccountId.success);
}
const claudeUserId = yield* Effect.result(getClaudeUserId);
if (claudeUserId._tag === "Success") {
return yield* hash(claudeUserId.success);
}
const anonymousId = yield* Effect.result(upsertAnonymousId);
if (anonymousId._tag === "Success") {
return yield* hash(anonymousId.success);
@@ -1,7 +1,7 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { ConfigProvider, Effect, Layer } from "effect";
import { ConfigProvider, Effect, FileSystem, Layer } from "effect";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
@@ -37,11 +37,14 @@ interface RecordedBatchBody {
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-telemetry-base-",
const fileSystem = yield* FileSystem.FileSystem;
const stateDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-telemetry-flush-",
});
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), stateDir);
const telemetryLayer = AnalyticsServiceLayerLive.pipe(Layer.provideMerge(serverConfigLayer));
const configLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({
+2 -4
View File
@@ -86,13 +86,11 @@ class BunPtyProcess implements PtyProcess {
}
}
export const layer = Layer.effect(
export const BunPtyAdapterLive = Layer.effect(
PtyAdapter,
Effect.gen(function* () {
if (process.platform === "win32") {
return yield* Effect.die(
"Bun PTY terminal support is unavailable on Windows. Please use Node.js (e.g. by running `npx t3`) instead.",
);
return yield* Effect.die("Bun PTY terminal support is unavailable on Windows.");
}
return {
spawn: (input) =>
@@ -469,89 +469,6 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("strips replay-unsafe terminal query and reply sequences from persisted history", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("prompt ");
process.emitData("\u001b[32mok\u001b[0m ");
process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007");
process.emitData("\u001b[1;1R");
process.emitData("done\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("prompt \u001b[32mok\u001b[0m done\n");
manager.dispose();
});
it("preserves clear and style control sequences while dropping chunk-split query traffic", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before clear\n");
process.emitData("\u001b[H\u001b[2J");
process.emitData("prompt ");
process.emitData("\u001b]11;");
process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1");
process.emitData("R\u001b[36mdone\u001b[0m\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe(
"before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n",
);
manager.dispose();
});
it("does not leak final bytes from ESC sequences with intermediate bytes", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before ");
process.emitData("\u001b(B");
process.emitData("after\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("before \u001b(Bafter\n");
manager.dispose();
});
it("preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before ");
process.emitData("\u001b(");
process.emitData("Bafter\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("before \u001b(Bafter\n");
manager.dispose();
});
it("deletes history file when close(deleteHistory=true)", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
+7 -194
View File
@@ -13,7 +13,7 @@ import {
type TerminalEvent,
type TerminalSessionSnapshot,
} from "@t3tools/contracts";
import { Effect, Encoding, Layer, Schema } from "effect";
import { Effect, Encoding, Layer, Path, Schema } from "effect";
import { createLogger } from "../../logger";
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
@@ -254,180 +254,6 @@ function capHistory(history: string, maxLines: number): string {
return hasTrailingNewline ? `${capped}\n` : capped;
}
function isCsiFinalByte(codePoint: number): boolean {
return codePoint >= 0x40 && codePoint <= 0x7e;
}
function shouldStripCsiSequence(body: string, finalByte: string): boolean {
if (finalByte === "n") {
return true;
}
if (finalByte === "R" && /^[0-9;?]*$/.test(body)) {
return true;
}
if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) {
return true;
}
return false;
}
function shouldStripOscSequence(content: string): boolean {
return /^(10|11|12);(?:\?|rgb:)/.test(content);
}
function stripStringTerminator(value: string): string {
if (value.endsWith("\u001b\\")) {
return value.slice(0, -2);
}
const lastCharacter = value.at(-1);
if (lastCharacter === "\u0007" || lastCharacter === "\u009c") {
return value.slice(0, -1);
}
return value;
}
function findStringTerminatorIndex(input: string, start: number): number | null {
for (let index = start; index < input.length; index += 1) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x07 || codePoint === 0x9c) {
return index + 1;
}
if (codePoint === 0x1b && input.charCodeAt(index + 1) === 0x5c) {
return index + 2;
}
}
return null;
}
function isEscapeIntermediateByte(codePoint: number): boolean {
return codePoint >= 0x20 && codePoint <= 0x2f;
}
function isEscapeFinalByte(codePoint: number): boolean {
return codePoint >= 0x30 && codePoint <= 0x7e;
}
function findEscapeSequenceEndIndex(input: string, start: number): number | null {
let cursor = start;
while (cursor < input.length && isEscapeIntermediateByte(input.charCodeAt(cursor))) {
cursor += 1;
}
if (cursor >= input.length) {
return null;
}
return isEscapeFinalByte(input.charCodeAt(cursor)) ? cursor + 1 : start + 1;
}
function sanitizeTerminalHistoryChunk(
pendingControlSequence: string,
data: string,
): { visibleText: string; pendingControlSequence: string } {
const input = `${pendingControlSequence}${data}`;
let visibleText = "";
let index = 0;
const append = (value: string) => {
visibleText += value;
};
while (index < input.length) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x1b) {
const nextCodePoint = input.charCodeAt(index + 1);
if (Number.isNaN(nextCodePoint)) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
if (nextCodePoint === 0x5b) {
let cursor = index + 2;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
const sequence = input.slice(index, cursor + 1);
const body = input.slice(index + 2, cursor);
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
append(sequence);
}
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (
nextCodePoint === 0x5d ||
nextCodePoint === 0x50 ||
nextCodePoint === 0x5e ||
nextCodePoint === 0x5f
) {
const terminatorIndex = findStringTerminatorIndex(input, index + 2);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 2, terminatorIndex));
if (nextCodePoint !== 0x5d || !shouldStripOscSequence(content)) {
append(sequence);
}
index = terminatorIndex;
continue;
}
const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1);
if (escapeSequenceEndIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
append(input.slice(index, escapeSequenceEndIndex));
index = escapeSequenceEndIndex;
continue;
}
if (codePoint === 0x9b) {
let cursor = index + 1;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
const sequence = input.slice(index, cursor + 1);
const body = input.slice(index + 1, cursor);
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
append(sequence);
}
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) {
const terminatorIndex = findStringTerminatorIndex(input, index + 1);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 1, terminatorIndex));
if (codePoint !== 0x9d || !shouldStripOscSequence(content)) {
append(sequence);
}
index = terminatorIndex;
continue;
}
append(input[index] ?? "");
index += 1;
}
return { visibleText, pendingControlSequence: "" };
}
function legacySafeThreadId(threadId: string): string {
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
@@ -552,7 +378,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history,
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -582,12 +407,10 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
existing.cwd = input.cwd;
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
existing.runtimeEnv = nextRuntimeEnv;
@@ -646,7 +469,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId, input.terminalId);
session.history = "";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({
@@ -675,7 +497,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history: "",
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -699,7 +520,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
const rows = input.rows ?? session.rows;
session.history = "";
session.pendingHistoryControlSequence = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
await this.startSession(session, { ...input, cols, rows }, "restarted");
return this.snapshot(session);
@@ -874,16 +694,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
}
private onProcessData(session: TerminalSessionState, data: string): void {
const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data);
session.pendingHistoryControlSequence = sanitized.pendingControlSequence;
if (sanitized.visibleText.length > 0) {
session.history = capHistory(
`${session.history}${sanitized.visibleText}`,
this.historyLineLimit,
);
this.queuePersist(session.threadId, session.terminalId, session.history);
}
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.terminalId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
@@ -900,7 +713,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
session.updatedAt = new Date().toISOString();
@@ -924,7 +736,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
this.killProcessWithEscalation(process, session.threadId, session.terminalId);
this.evictInactiveSessionsIfNeeded();
@@ -1361,11 +1172,13 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
export const TerminalManagerLive = Layer.effect(
TerminalManager,
Effect.gen(function* () {
const { terminalLogsDir } = yield* ServerConfig;
const { stateDir } = yield* ServerConfig;
const { join } = yield* Path.Path;
const logsDir = join(stateDir, "logs", "terminals");
const ptyAdapter = yield* PtyAdapter;
const runtime = yield* Effect.acquireRelease(
Effect.sync(() => new TerminalManagerRuntime({ logsDir: terminalLogsDir, ptyAdapter })),
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
(r) => Effect.sync(() => r.dispose()),
);
+1 -1
View File
@@ -84,7 +84,7 @@ class NodePtyProcess implements PtyProcess {
}
}
export const layer = Layer.effect(
export const NodePtyAdapterLive = Layer.effect(
PtyAdapter,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -32,7 +32,6 @@ export interface TerminalSessionState {
status: TerminalSessionStatus;
pid: number | null;
history: string;
pendingHistoryControlSequence: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
+52 -175
View File
@@ -8,7 +8,7 @@ import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effec
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config";
import { ServerConfig, type ServerConfigShape } from "./config";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import {
@@ -451,16 +451,6 @@ function expectAvailableEditors(value: unknown): void {
}
}
function ensureParentDir(filePath: string): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
}
function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) {
return Effect.runSync(
deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)),
);
}
describe("WebSocket Server", () => {
let server: Http.Server | null = null;
let serverScope: Scope.Closeable | null = null;
@@ -484,7 +474,7 @@ describe("WebSocket Server", () => {
logWebSocketEvents?: boolean;
devUrl?: string;
authToken?: string;
baseDir?: string;
stateDir?: string;
staticDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
providerHealth?: ProviderHealthShape;
@@ -498,9 +488,7 @@ describe("WebSocket Server", () => {
throw new Error("Test server is already running");
}
const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-");
const devUrl = options.devUrl ? new URL(options.devUrl) : undefined;
const derivedPaths = deriveServerPathsSync(baseDir, devUrl);
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
const scope = await Effect.runPromise(Scope.make("sequential"));
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
@@ -514,10 +502,10 @@ describe("WebSocket Server", () => {
port: 0,
host: undefined,
cwd: options.cwd ?? "/test/project",
baseDir,
...derivedPaths,
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
stateDir,
staticDir: options.staticDir,
devUrl,
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
noBrowser: true,
authToken: options.authToken,
autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false,
@@ -602,13 +590,12 @@ describe("WebSocket Server", () => {
});
it("serves persisted attachments from stateDir", async () => {
const baseDir = makeTempDir("t3code-state-attachments-");
const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined);
const attachmentPath = path.join(attachmentsDir, "thread-a", "message-a", "0.png");
const stateDir = makeTempDir("t3code-state-attachments-");
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
server = await createTestServer({ cwd: "/test/project", baseDir });
server = await createTestServer({ cwd: "/test/project", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -621,10 +608,10 @@ describe("WebSocket Server", () => {
});
it("serves persisted attachments for URL-encoded paths", async () => {
const baseDir = makeTempDir("t3code-state-attachments-encoded-");
const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined);
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
const attachmentPath = path.join(
attachmentsDir,
stateDir,
"attachments",
"thread%20folder",
"message%20folder",
"file%20name.png",
@@ -632,7 +619,7 @@ describe("WebSocket Server", () => {
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
server = await createTestServer({ cwd: "/test/project", baseDir });
server = await createTestServer({ cwd: "/test/project", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -647,11 +634,11 @@ describe("WebSocket Server", () => {
});
it("serves static index for root path", async () => {
const baseDir = makeTempDir("t3code-state-static-root-");
const stateDir = makeTempDir("t3code-state-static-root-");
const staticDir = makeTempDir("t3code-static-root-");
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
server = await createTestServer({ cwd: "/test/project", baseDir, staticDir });
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -662,11 +649,11 @@ describe("WebSocket Server", () => {
});
it("rejects static path traversal attempts", async () => {
const baseDir = makeTempDir("t3code-state-static-traversal-");
const stateDir = makeTempDir("t3code-state-static-traversal-");
const staticDir = makeTempDir("t3code-static-traversal-");
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
server = await createTestServer({ cwd: "/test/project", baseDir, staticDir });
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -703,19 +690,13 @@ describe("WebSocket Server", () => {
id: string;
workspaceRoot: string;
title: string;
defaultModelSelection: {
provider: string;
model: string;
} | null;
defaultModel: string | null;
}>;
threads: Array<{
id: string;
projectId: string;
title: string;
modelSelection: {
provider: string;
model: string;
};
model: string;
branch: string | null;
worktreePath: string | null;
}>;
@@ -731,10 +712,7 @@ describe("WebSocket Server", () => {
id: bootstrapProjectId,
workspaceRoot: "/test/bootstrap-workspace",
title: "bootstrap-workspace",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
}),
]),
);
@@ -744,10 +722,7 @@ describe("WebSocket Server", () => {
id: bootstrapThreadId,
projectId: bootstrapProjectId,
title: "New thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
branch: null,
worktreePath: null,
}),
@@ -756,16 +731,15 @@ describe("WebSocket Server", () => {
});
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
const baseDir = makeTempDir("t3code-state-bootstrap-existing-");
const { dbPath } = deriveServerPathsSync(baseDir, undefined);
const persistenceLayer = makeSqlitePersistenceLive(dbPath).pipe(
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
Layer.provide(NodeServices.layer),
);
const cwd = "/test/bootstrap-existing";
server = await createTestServer({
cwd,
baseDir,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
@@ -788,7 +762,7 @@ describe("WebSocket Server", () => {
server = await createTestServer({
cwd,
baseDir,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
@@ -837,12 +811,11 @@ describe("WebSocket Server", () => {
});
it("responds to server.getConfig", async () => {
const baseDir = makeTempDir("t3code-state-get-config-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-get-config-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(keybindingsPath, "[]", "utf8");
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -863,11 +836,11 @@ describe("WebSocket Server", () => {
});
it("bootstraps default keybindings file when missing", async () => {
const baseDir = makeTempDir("t3code-state-bootstrap-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
const stateDir = makeTempDir("t3code-state-bootstrap-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
expect(fs.existsSync(keybindingsPath)).toBe(false);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -893,12 +866,11 @@ describe("WebSocket Server", () => {
});
it("falls back to defaults and reports malformed keybindings config issues", async () => {
const baseDir = makeTempDir("t3code-state-malformed-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-malformed-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(keybindingsPath, "{ not-json", "utf8");
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -925,9 +897,8 @@ describe("WebSocket Server", () => {
});
it("ignores invalid keybinding entries but keeps valid entries and reports issues", async () => {
const baseDir = makeTempDir("t3code-state-partial-invalid-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-partial-invalid-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([
@@ -938,7 +909,7 @@ describe("WebSocket Server", () => {
"utf8",
);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -977,12 +948,11 @@ describe("WebSocket Server", () => {
});
it("pushes server.configUpdated issues when keybindings file changes", async () => {
const baseDir = makeTempDir("t3code-state-keybindings-watch-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-keybindings-watch-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(keybindingsPath, "[]", "utf8");
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -1038,9 +1008,8 @@ describe("WebSocket Server", () => {
});
it("reads keybindings from the configured state directory", async () => {
const baseDir = makeTempDir("t3code-state-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([
@@ -1050,7 +1019,7 @@ describe("WebSocket Server", () => {
]),
"utf8",
);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -1074,16 +1043,15 @@ describe("WebSocket Server", () => {
});
it("upserts keybinding rules and updates cached server config", async () => {
const baseDir = makeTempDir("t3code-state-upsert-keybinding-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-upsert-keybinding-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
"utf8",
);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -1204,10 +1172,7 @@ describe("WebSocket Server", () => {
projectId: "project-diff",
title: "Diff Project",
workspaceRoot,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
});
expect(createProjectResponse.error).toBeUndefined();
@@ -1217,10 +1182,7 @@ describe("WebSocket Server", () => {
threadId: "thread-diff",
projectId: "project-diff",
title: "Diff Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -1288,10 +1250,7 @@ describe("WebSocket Server", () => {
projectId: "project-1",
title: "WS Project",
workspaceRoot,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
});
expect(createProjectResponse.error).toBeUndefined();
@@ -1301,10 +1260,7 @@ describe("WebSocket Server", () => {
threadId: "thread-1",
projectId: "project-1",
title: "Thread 1",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -1835,94 +1791,15 @@ describe("WebSocket Server", () => {
connections.push(ws);
const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, {
actionId: "client-action-1",
cwd: "/test",
action: "commit_push",
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("detached HEAD");
expect(runStackedAction).toHaveBeenCalledWith(
{
actionId: "client-action-1",
cwd: "/test",
action: "commit_push",
},
expect.objectContaining({
actionId: "client-action-1",
progressReporter: expect.any(Object),
}),
);
});
it("publishes git action progress only to the initiating websocket", async () => {
const runStackedAction = vi.fn(
(_input, options) =>
options?.progressReporter
?.publish({
actionId: options.actionId ?? "action-1",
cwd: "/test",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
})
.pipe(
Effect.flatMap(() =>
Effect.succeed({
action: "commit" as const,
branch: { status: "skipped_not_requested" as const },
commit: {
status: "created" as const,
commitSha: "abc1234",
subject: "Test commit",
},
push: { status: "skipped_not_requested" as const },
pr: { status: "skipped_not_requested" as const },
}),
),
) ?? Effect.void,
);
const gitManager: GitManagerShape = {
status: vi.fn(() => Effect.void as any),
resolvePullRequest: vi.fn(() => Effect.void as any),
preparePullRequestThread: vi.fn(() => Effect.void as any),
runStackedAction,
};
server = await createTestServer({ cwd: "/test", gitManager });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [initiatingWs] = await connectAndAwaitWelcome(port);
const [otherWs] = await connectAndAwaitWelcome(port);
connections.push(initiatingWs, otherWs);
const responsePromise = sendRequest(initiatingWs, WS_METHODS.gitRunStackedAction, {
actionId: "client-action-2",
expect(runStackedAction).toHaveBeenCalledWith({
cwd: "/test",
action: "commit",
action: "commit_push",
});
const progressPush = await waitForPush(initiatingWs, WS_CHANNELS.gitActionProgress);
expect(progressPush.data).toEqual({
actionId: "client-action-2",
cwd: "/test",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
await expect(
waitForPush(otherWs, WS_CHANNELS.gitActionProgress, undefined, 10, 100),
).rejects.toThrow("Timed out waiting for WebSocket message after 100ms");
await expect(responsePromise).resolves.toEqual(
expect.objectContaining({
result: expect.objectContaining({
action: "commit",
}),
}),
);
});
it("rejects websocket connections without a valid auth token", async () => {
+11 -23
View File
@@ -370,7 +370,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
};
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment: persistedAttachment,
});
if (!attachmentPath) {
@@ -440,11 +440,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
relativePath: normalizedRelativePath,
});
if (!filePath) {
@@ -631,31 +631,25 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
);
let bootstrapProjectId: ProjectId;
let bootstrapProjectDefaultModelSelection;
let bootstrapProjectDefaultModel: string;
if (!existingProject) {
const createdAt = new Date().toISOString();
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(cwd) || "project";
bootstrapProjectDefaultModelSelection = {
provider: "codex" as const,
model: "gpt-5-codex",
};
bootstrapProjectDefaultModel = "gpt-5-codex";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
defaultModelSelection: bootstrapProjectDefaultModelSelection,
defaultModel: bootstrapProjectDefaultModel,
createdAt,
});
} else {
bootstrapProjectId = existingProject.id;
bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
provider: "codex" as const,
model: "gpt-5-codex",
};
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
}
const existingThread = snapshot.threads.find(
@@ -670,7 +664,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
threadId,
projectId: bootstrapProjectId,
title: "New thread",
modelSelection: bootstrapProjectDefaultModelSelection,
model: bootstrapProjectDefaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -710,7 +704,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
);
const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) {
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
switch (request.body._tag) {
case ORCHESTRATION_WS_METHODS.getSnapshot:
return yield* projectionReadModelQuery.getSnapshot();
@@ -799,13 +793,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.gitRunStackedAction: {
const body = stripRequestTag(request.body);
return yield* gitManager.runStackedAction(body, {
actionId: body.actionId,
progressReporter: {
publish: (event) =>
pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid),
},
});
return yield* gitManager.runStackedAction(body);
}
case WS_METHODS.gitResolvePullRequest: {
@@ -927,7 +915,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
}
const result = yield* Effect.exit(routeRequest(ws, request.success));
const result = yield* Effect.exit(routeRequest(request.success));
if (Exit.isFailure(result)) {
return yield* sendWsResponse({
id: request.success.id,
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.13",
"version": "0.0.10",
"private": true,
"type": "module",
"scripts": {
@@ -51,7 +51,7 @@
"@vitejs/plugin-react": "^6.0.0",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"msw": "2.12.11",
"msw": "^2.12.10",
"playwright": "^1.58.2",
"tailwindcss": "^4.0.0",
"typescript": "catalog:",
+1 -1
View File
@@ -7,7 +7,7 @@
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.12.11'
const PACKAGE_VERSION = '2.12.10'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
+4 -190
View File
@@ -1,18 +1,9 @@
import { Schema } from "effect";
import { describe, expect, it } from "vitest";
import {
AppSettingsSchema,
DEFAULT_TIMESTAMP_FORMAT,
getAppModelOptions,
getCustomModelOptionsByProvider,
getCustomModelsByProvider,
getCustomModelsForProvider,
getDefaultCustomModelsForProvider,
getProviderStartOptions,
MODEL_PROVIDER_SETTINGS,
normalizeCustomModelSlugs,
patchCustomModels,
resolveAppModelSelection,
} from "./appSettings";
@@ -29,13 +20,6 @@ describe("normalizeCustomModelSlugs", () => {
]),
).toEqual(["custom/internal-model"]);
});
it("normalizes provider-specific aliases for claude", () => {
expect(normalizeCustomModelSlugs(["sonnet"], "claudeAgent")).toEqual([]);
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeAgent")).toEqual([
"claude/custom-sonnet",
]);
});
});
describe("getAppModelOptions", () => {
@@ -62,46 +46,17 @@ describe("getAppModelOptions", () => {
isCustom: true,
});
});
it("keeps a saved custom provider model available as an exact slug option", () => {
const options = getAppModelOptions("claudeAgent", ["claude/custom-opus"], "claude/custom-opus");
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
true,
);
});
});
describe("resolveAppModelSelection", () => {
it("preserves saved custom model slugs instead of falling back to the default", () => {
expect(
resolveAppModelSelection(
"codex",
{ codex: ["galapagos-alpha"], claudeAgent: [] },
"galapagos-alpha",
),
).toBe("galapagos-alpha");
expect(resolveAppModelSelection("codex", ["galapagos-alpha"], "galapagos-alpha")).toBe(
"galapagos-alpha",
);
});
it("falls back to the provider default when no model is selected", () => {
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "")).toBe("gpt-5.4");
});
it("resolves display names through the shared resolver", () => {
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "GPT-5.3 Codex")).toBe(
"gpt-5.3-codex",
);
});
it("resolves aliases through the shared resolver", () => {
expect(resolveAppModelSelection("claudeAgent", { codex: [], claudeAgent: [] }, "sonnet")).toBe(
"claude-sonnet-4-6",
);
});
it("resolves transient selected custom models included in app model options", () => {
expect(
resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "custom/selected-model"),
).toBe("custom/selected-model");
expect(resolveAppModelSelection("codex", [], "")).toBe("gpt-5.4");
});
});
@@ -110,144 +65,3 @@ describe("timestamp format defaults", () => {
expect(DEFAULT_TIMESTAMP_FORMAT).toBe("locale");
});
});
describe("provider-specific custom models", () => {
it("includes provider-specific custom slugs in non-codex model lists", () => {
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
});
});
describe("getProviderStartOptions", () => {
it("returns only populated provider overrides", () => {
expect(
getProviderStartOptions({
claudeBinaryPath: "/usr/local/bin/claude",
codexBinaryPath: "",
codexHomePath: "/Users/you/.codex",
}),
).toEqual({
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
},
codex: {
homePath: "/Users/you/.codex",
},
});
});
it("returns undefined when no provider overrides are configured", () => {
expect(
getProviderStartOptions({
claudeBinaryPath: "",
codexBinaryPath: "",
codexHomePath: "",
}),
).toBeUndefined();
});
});
describe("provider-indexed custom model settings", () => {
const settings = {
customCodexModels: ["custom/codex-model"],
customClaudeModels: ["claude/custom-opus"],
} as const;
it("exports one provider config per provider", () => {
expect(MODEL_PROVIDER_SETTINGS.map((config) => config.provider)).toEqual([
"codex",
"claudeAgent",
]);
});
it("reads custom models for each provider", () => {
expect(getCustomModelsForProvider(settings, "codex")).toEqual(["custom/codex-model"]);
expect(getCustomModelsForProvider(settings, "claudeAgent")).toEqual(["claude/custom-opus"]);
});
it("reads default custom models for each provider", () => {
const defaults = {
customCodexModels: ["default/codex-model"],
customClaudeModels: ["claude/default-opus"],
} as const;
expect(getDefaultCustomModelsForProvider(defaults, "codex")).toEqual(["default/codex-model"]);
expect(getDefaultCustomModelsForProvider(defaults, "claudeAgent")).toEqual([
"claude/default-opus",
]);
});
it("patches custom models for codex", () => {
expect(patchCustomModels("codex", ["custom/codex-model"])).toEqual({
customCodexModels: ["custom/codex-model"],
});
});
it("patches custom models for claude", () => {
expect(patchCustomModels("claudeAgent", ["claude/custom-opus"])).toEqual({
customClaudeModels: ["claude/custom-opus"],
});
});
it("builds a complete provider-indexed custom model record", () => {
expect(getCustomModelsByProvider(settings)).toEqual({
codex: ["custom/codex-model"],
claudeAgent: ["claude/custom-opus"],
});
});
it("builds provider-indexed model options including custom models", () => {
const modelOptionsByProvider = getCustomModelOptionsByProvider(settings);
expect(
modelOptionsByProvider.codex.some((option) => option.slug === "custom/codex-model"),
).toBe(true);
expect(
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude/custom-opus"),
).toBe(true);
});
it("normalizes and deduplicates custom model options per provider", () => {
const modelOptionsByProvider = getCustomModelOptionsByProvider({
customCodexModels: [" custom/codex-model ", "gpt-5.4", "custom/codex-model"],
customClaudeModels: [" sonnet ", "claude/custom-opus", "claude/custom-opus"],
});
expect(
modelOptionsByProvider.codex.filter((option) => option.slug === "custom/codex-model"),
).toHaveLength(1);
expect(modelOptionsByProvider.codex.some((option) => option.slug === "gpt-5.4")).toBe(true);
expect(
modelOptionsByProvider.claudeAgent.filter((option) => option.slug === "claude/custom-opus"),
).toHaveLength(1);
expect(
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude-sonnet-4-6"),
).toBe(true);
});
});
describe("AppSettingsSchema", () => {
it("fills decoding defaults for persisted settings that predate newer keys", () => {
const decode = Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema));
expect(
decode(
JSON.stringify({
codexBinaryPath: "/usr/local/bin/codex",
confirmThreadDelete: false,
}),
),
).toMatchObject({
claudeBinaryPath: "",
codexBinaryPath: "/usr/local/bin/codex",
codexHomePath: "",
defaultThreadEnvMode: "local",
confirmThreadDelete: false,
enableAssistantStreaming: false,
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
customCodexModels: [],
customClaudeModels: [],
});
});
});
+55 -157
View File
@@ -1,66 +1,42 @@
import { useCallback } from "react";
import { Option, Schema } from "effect";
import {
TrimmedNonEmptyString,
type ProviderKind,
type ProviderStartOptions,
} from "@t3tools/contracts";
import {
getDefaultModel,
getModelOptions,
normalizeModelSlug,
resolveSelectableModel,
} from "@t3tools/shared/model";
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { useLocalStorage } from "./hooks/useLocalStorage";
import { EnvMode } from "./components/BranchToolbar.logic";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
export type TimestampFormat = typeof TimestampFormat.Type;
export const TIMESTAMP_FORMAT_OPTIONS = ["locale", "12-hour", "24-hour"] as const;
export type TimestampFormat = (typeof TIMESTAMP_FORMAT_OPTIONS)[number];
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";
export type ProviderCustomModelConfig = {
provider: ProviderKind;
settingsKey: CustomModelSettingsKey;
defaultSettingsKey: CustomModelSettingsKey;
title: string;
description: string;
placeholder: string;
example: string;
};
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
};
const withDefaults =
<
S extends Schema.Top & Schema.WithoutConstructorDefault,
D extends S["~type.make.in"] & S["Encoded"],
>(
fallback: () => D,
) =>
(schema: S) =>
schema.pipe(
Schema.withConstructorDefault(() => Option.some(fallback())),
Schema.withDecodingDefault(() => fallback()),
);
export const AppSettingsSchema = Schema.Struct({
claudeBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
const AppSettingsSchema = Schema.Struct({
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
Schema.withConstructorDefault(() => Option.some("")),
),
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
Schema.withConstructorDefault(() => Option.some("")),
),
gitCommitFlags: Schema.String.check(Schema.isMaxLength(4096)).pipe(
Schema.withConstructorDefault(() => Option.some("")),
),
defaultThreadEnvMode: Schema.Literals(["local", "worktree"]).pipe(
Schema.withConstructorDefault(() => Option.some("local")),
),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
timestampFormat: Schema.Literals(["locale", "12-hour", "24-hour"]).pipe(
Schema.withConstructorDefault(() => Option.some(DEFAULT_TIMESTAMP_FORMAT)),
),
customCodexModels: Schema.Array(Schema.String).pipe(
Schema.withConstructorDefault(() => Option.some([])),
),
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
});
export type AppSettings = typeof AppSettingsSchema.Type;
@@ -71,27 +47,6 @@ export interface AppModelOption {
}
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConfig> = {
codex: {
provider: "codex",
settingsKey: "customCodexModels",
defaultSettingsKey: "customCodexModels",
title: "Codex",
description: "Save additional Codex model slugs for the picker and `/model` command.",
placeholder: "your-codex-model-slug",
example: "gpt-6.7-codex-ultra-preview",
},
claudeAgent: {
provider: "claudeAgent",
settingsKey: "customClaudeModels",
defaultSettingsKey: "customClaudeModels",
title: "Claude",
description: "Save additional Claude model slugs for the picker and `/model` command.",
placeholder: "your-claude-model-slug",
example: "claude-sonnet-5-0",
},
};
export const MODEL_PROVIDER_SETTINGS = Object.values(PROVIDER_CUSTOM_MODEL_CONFIG);
export function normalizeCustomModelSlugs(
models: Iterable<string | null | undefined>,
@@ -122,46 +77,6 @@ export function normalizeCustomModelSlugs(
return normalizedModels;
}
function normalizeAppSettings(settings: AppSettings): AppSettings {
return {
...settings,
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
};
}
export function getCustomModelsForProvider(
settings: Pick<AppSettings, CustomModelSettingsKey>,
provider: ProviderKind,
): readonly string[] {
return settings[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey];
}
export function getDefaultCustomModelsForProvider(
defaults: Pick<AppSettings, CustomModelSettingsKey>,
provider: ProviderKind,
): readonly string[] {
return defaults[PROVIDER_CUSTOM_MODEL_CONFIG[provider].defaultSettingsKey];
}
export function patchCustomModels(
provider: ProviderKind,
models: string[],
): Partial<Pick<AppSettings, CustomModelSettingsKey>> {
return {
[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey]: models,
};
}
export function getCustomModelsByProvider(
settings: Pick<AppSettings, CustomModelSettingsKey>,
): Record<ProviderKind, readonly string[]> {
return {
codex: getCustomModelsForProvider(settings, "codex"),
claudeAgent: getCustomModelsForProvider(settings, "claudeAgent"),
};
}
export function getAppModelOptions(
provider: ProviderKind,
customModels: readonly string[],
@@ -173,7 +88,6 @@ export function getAppModelOptions(
isCustom: false,
}));
const seen = new Set(options.map((option) => option.slug));
const trimmedSelectedModel = selectedModel?.trim().toLowerCase();
for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
if (seen.has(slug)) {
@@ -189,14 +103,7 @@ export function getAppModelOptions(
}
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
const selectedModelMatchesExistingName =
typeof trimmedSelectedModel === "string" &&
options.some((option) => option.name.toLowerCase() === trimmedSelectedModel);
if (
normalizedSelectedModel &&
!seen.has(normalizedSelectedModel) &&
!selectedModelMatchesExistingName
) {
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
options.push({
slug: normalizedSelectedModel,
name: normalizedSelectedModel,
@@ -209,46 +116,34 @@ export function getAppModelOptions(
export function resolveAppModelSelection(
provider: ProviderKind,
customModels: Record<ProviderKind, readonly string[]>,
customModels: readonly string[],
selectedModel: string | null | undefined,
): string {
const customModelsForProvider = customModels[provider];
const options = getAppModelOptions(provider, customModelsForProvider, selectedModel);
return resolveSelectableModel(provider, selectedModel, options) ?? getDefaultModel(provider);
}
const options = getAppModelOptions(provider, customModels, selectedModel);
const trimmedSelectedModel = selectedModel?.trim();
if (trimmedSelectedModel) {
const direct = options.find((option) => option.slug === trimmedSelectedModel);
if (direct) {
return direct.slug;
}
export function getCustomModelOptionsByProvider(
settings: Pick<AppSettings, CustomModelSettingsKey>,
): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
const customModelsByProvider = getCustomModelsByProvider(settings);
return {
codex: getAppModelOptions("codex", customModelsByProvider.codex),
claudeAgent: getAppModelOptions("claudeAgent", customModelsByProvider.claudeAgent),
};
}
const byName = options.find(
(option) => option.name.toLowerCase() === trimmedSelectedModel.toLowerCase(),
);
if (byName) {
return byName.slug;
}
}
export function getProviderStartOptions(
settings: Pick<AppSettings, "claudeBinaryPath" | "codexBinaryPath" | "codexHomePath">,
): ProviderStartOptions | undefined {
const providerOptions: ProviderStartOptions = {
...(settings.codexBinaryPath || settings.codexHomePath
? {
codex: {
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
},
}
: {}),
...(settings.claudeBinaryPath
? {
claudeAgent: {
binaryPath: settings.claudeBinaryPath,
},
}
: {}),
};
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
if (!normalizedSelectedModel) {
return getDefaultModel(provider);
}
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
return (
options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
getDefaultModel(provider)
);
}
export function useAppSettings() {
@@ -260,7 +155,10 @@ export function useAppSettings() {
const updateSettings = useCallback(
(patch: Partial<AppSettings>) => {
setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
setSettings((prev) => ({
...prev,
...patch,
}));
},
[setSettings],
);
@@ -1,8 +1,6 @@
import type { GitBranch } from "@t3tools/contracts";
import { Schema } from "effect";
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
export type EnvMode = "local" | "worktree";
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
+40 -430
View File
@@ -24,7 +24,6 @@ import { useComposerDraftStore } from "../composerDraftStore";
import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
type TerminalContextDraft,
removeInlineTerminalContextPlaceholder,
} from "../lib/terminalContext";
import { isMacPlatform } from "../lib/utils";
import { getRouter } from "../router";
@@ -221,10 +220,7 @@ function createSnapshotForTargetUser(options: {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
},
defaultModel: "gpt-5",
scripts: [],
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
@@ -236,10 +232,7 @@ function createSnapshotForTargetUser(options: {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Browser test thread",
modelSelection: {
provider: "codex",
model: "gpt-5",
},
model: "gpt-5",
interactionMode: "default",
runtimeMode: "full-access",
branch: "main",
@@ -293,10 +286,7 @@ function addThreadToSnapshot(
id: threadId,
projectId: PROJECT_ID,
title: "New thread",
modelSelection: {
provider: "codex",
model: "gpt-5",
},
model: "gpt-5",
interactionMode: "default",
runtimeMode: "full-access",
branch: "main",
@@ -334,18 +324,6 @@ function createDraftOnlySnapshot(): OrchestrationReadModel {
};
}
function withProjectScripts(
snapshot: OrchestrationReadModel,
scripts: OrchestrationReadModel["projects"][number]["scripts"],
): OrchestrationReadModel {
return {
...snapshot,
projects: snapshot.projects.map((project) =>
project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project,
),
};
}
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-plan-target" as MessageId,
@@ -597,58 +575,6 @@ async function waitForInteractionModeButton(
);
}
async function waitForServerConfigToApply(): Promise<void> {
await vi.waitFor(
() => {
expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
await waitForLayout();
}
function dispatchChatNewShortcut(): void {
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
}
async function triggerChatNewShortcutUntilPath(
router: ReturnType<typeof getRouter>,
predicate: (pathname: string) => boolean,
errorMessage: string,
): Promise<string> {
let pathname = router.state.location.pathname;
const deadline = Date.now() + 8_000;
while (Date.now() < deadline) {
dispatchChatNewShortcut();
await waitForLayout();
pathname = router.state.location.pathname;
if (predicate(pathname)) {
return pathname;
}
}
throw new Error(`${errorMessage} Last path: ${pathname}`);
}
async function waitForNewThreadShortcutLabel(): Promise<void> {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.hover();
const shortcutLabel = isMacPlatform(navigator.platform)
? "New thread (⇧⌘O)"
: "New thread (Ctrl+Shift+O)";
await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument();
}
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
const images = Array.from(scope.querySelectorAll("img"));
if (images.length === 0) {
@@ -826,7 +752,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
stickyModelSelection: null,
});
useStore.setState({
projects: [],
@@ -1053,145 +978,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("runs project scripts from local draft threads at the project cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "lint",
name: "Lint",
command: "bun run lint",
icon: "lint",
runOnWorktreeCreate: false,
},
]),
});
try {
const runButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.title === "Run Lint",
) as HTMLButtonElement | null,
"Unable to find Run Lint button.",
);
runButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalOpen,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
threadId: THREAD_ID,
cwd: "/repo/project",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
},
});
},
{ timeout: 8_000, interval: 16 },
);
await vi.waitFor(
() => {
const writeRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalWrite,
);
expect(writeRequest).toMatchObject({
_tag: WS_METHODS.terminalWrite,
threadId: THREAD_ID,
data: "bun run lint\r",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("runs project scripts from worktree draft threads at the worktree cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/draft",
worktreePath: "/repo/worktrees/feature-draft",
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "test",
name: "Test",
command: "bun run test",
icon: "test",
runOnWorktreeCreate: false,
},
]),
});
try {
const runButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.title === "Run Test",
) as HTMLButtonElement | null,
"Unable to find Run Test button.",
);
runButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalOpen,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
threadId: THREAD_ID,
cwd: "/repo/worktrees/feature-draft",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft",
},
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1257,7 +1043,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("keeps removed terminal context pills removed when a new one is added", async () => {
it("keeps backspaced terminal context pills removed when a new one is added", async () => {
const removedLabel = "Terminal 1 lines 1-2";
const addedLabel = "Terminal 2 lines 9-10";
useComposerDraftStore.getState().addTerminalContext(
@@ -1287,11 +1073,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
{ timeout: 8_000, interval: 16 },
);
const store = useComposerDraftStore.getState();
const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? "";
const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0);
store.setPrompt(THREAD_ID, nextPrompt.prompt);
store.removeTerminalContext(THREAD_ID, "ctx-removed");
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Backspace",
bubbles: true,
cancelable: true,
}),
);
await vi.waitFor(
() => {
@@ -1489,204 +1279,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("snapshots sticky codex settings into a new draft thread", async () => {
useComposerDraftStore.setState({
stickyModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "medium",
fastMode: true,
},
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-sticky-codex-traits-test" as MessageId,
targetText: "sticky codex traits test",
}),
});
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
const newThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
fastMode: true,
},
},
});
} finally {
await mounted.cleanup();
}
});
it("hydrates the provider alongside a sticky claude model", async () => {
useComposerDraftStore.setState({
stickyModelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
fastMode: true,
},
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-sticky-claude-model-test" as MessageId,
targetText: "sticky claude model test",
}),
});
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
const newThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new sticky claude draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
fastMode: true,
},
},
});
await expect.element(page.getByText("Claude Opus 4.6")).toBeInTheDocument();
} finally {
await mounted.cleanup();
}
});
it("falls back to defaults when no sticky composer settings exist", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-default-codex-traits-test" as MessageId,
targetText: "default codex traits test",
}),
});
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
const newThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toBeUndefined();
} finally {
await mounted.cleanup();
}
});
it("prefers draft state over sticky composer settings and defaults", async () => {
useComposerDraftStore.setState({
stickyModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
reasoningEffort: "medium",
fastMode: true,
},
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-codex-traits-precedence-test" as MessageId,
targetText: "draft codex traits precedence test",
}),
});
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
const threadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a sticky draft thread UUID.",
);
const threadId = threadPath.slice(1) as ThreadId;
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
fastMode: true,
},
},
});
useComposerDraftStore.getState().setModelSelection(threadId, {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "low",
fastMode: true,
},
});
await newThreadButton.click();
await waitForURL(
mounted.router,
(path) => path === threadPath,
"New-thread should reuse the existing project draft thread.",
);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "low",
fastMode: true,
},
},
});
} finally {
await mounted.cleanup();
}
});
it("creates a new thread from the global chat.new shortcut", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1719,12 +1311,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await waitForNewThreadShortcutLabel();
await waitForServerConfigToApply();
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
await waitForLayout();
await triggerChatNewShortcutUntilPath(
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID from the shortcut.",
@@ -1733,6 +1332,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await mounted.cleanup();
}
});
it("creates a fresh draft after the previous draft thread is promoted", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1767,8 +1367,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForNewThreadShortcutLabel();
await waitForServerConfigToApply();
await newThreadButton.click();
const promotedThreadPath = await waitForURL(
@@ -1782,7 +1380,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
const freshThreadPath = await triggerChatNewShortcutUntilPath(
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
const freshThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath,
"Shortcut should create a fresh draft instead of reusing the promoted thread.",
+12 -3
View File
@@ -1,6 +1,7 @@
import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts";
import { ProjectId, type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { type ChatMessage, type Thread } from "../types";
import { randomUUID } from "~/lib/utils";
import { getAppModelOptions } from "../appSettings";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
import {
@@ -17,7 +18,7 @@ export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.
export function buildLocalDraftThread(
threadId: ThreadId,
draftThread: DraftThreadState,
fallbackModelSelection: ModelSelection,
fallbackModel: string,
error: string | null,
): Thread {
return {
@@ -25,7 +26,7 @@ export function buildLocalDraftThread(
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
modelSelection: fallbackModelSelection,
model: fallbackModel,
runtimeMode: draftThread.runtimeMode,
interactionMode: draftThread.interactionMode,
session: null,
@@ -120,6 +121,14 @@ export function cloneComposerImageForRetry(
}
}
export function getCustomModelOptionsByProvider(settings: {
customCodexModels: readonly string[];
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
return {
codex: getAppModelOptions("codex", settings.customCodexModels),
};
}
export function deriveComposerSendState(options: {
prompt: string;
imageCount: number;
File diff suppressed because it is too large. Load diff
+20 -58
View File
@@ -3,13 +3,7 @@ import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/reac
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import {
ChevronLeftIcon,
ChevronRightIcon,
Columns2Icon,
Rows3Icon,
TextWrapIcon,
} from "lucide-react";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import {
type WheelEvent as ReactWheelEvent,
useCallback,
@@ -168,10 +162,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const { resolvedTheme } = useTheme();
const { settings } = useAppSettings();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
const previousDiffOpenRef = useRef(false);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
const routeThreadId = useParams({
@@ -179,7 +171,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const diffOpen = diffSearch.diff === "1";
const activeThreadId = routeThreadId;
const activeThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
@@ -302,13 +293,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
);
}, [renderablePatch]);
useEffect(() => {
if (diffOpen && !previousDiffOpenRef.current) {
setDiffWordWrap(settings.diffWordWrap);
}
previousDiffOpenRef.current = diffOpen;
}, [diffOpen, settings.diffWordWrap]);
useEffect(() => {
if (!selectedFilePath || !patchViewportRef.current) {
return;
@@ -506,39 +490,25 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
))}
</div>
</div>
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
<ToggleGroup
className="shrink-0"
variant="outline"
size="xs"
value={[diffRenderMode]}
onValueChange={(value) => {
const next = value[0];
if (next === "stacked" || next === "split") {
setDiffRenderMode(next);
}
}}
>
<Toggle aria-label="Stacked diff view" value="stacked">
<Rows3Icon className="size-3" />
</Toggle>
<Toggle aria-label="Split diff view" value="split">
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
<Toggle
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
variant="outline"
size="xs"
pressed={diffWordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
}}
>
<TextWrapIcon className="size-3" />
<ToggleGroup
className="shrink-0 [-webkit-app-region:no-drag]"
variant="outline"
size="xs"
value={[diffRenderMode]}
onValueChange={(value) => {
const next = value[0];
if (next === "stacked" || next === "split") {
setDiffRenderMode(next);
}
}}
>
<Toggle aria-label="Stacked diff view" value="stacked">
<Rows3Icon className="size-3" />
</Toggle>
</div>
<Toggle aria-label="Split diff view" value="split">
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
</>
);
@@ -612,7 +582,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
options={{
diffStyle: diffRenderMode === "split" ? "split" : "unified",
lineDiffType: "none",
overflow: diffWordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme as DiffThemeType,
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
@@ -626,14 +595,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<div className="h-full overflow-auto p-2">
<div className="space-y-2">
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
<pre
className={cn(
"max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
diffWordWrap
? "overflow-auto whitespace-pre-wrap wrap-break-word"
: "overflow-auto",
)}
>
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
{renderablePatch.text}
</pre>
</div>
+77 -176
View File
@@ -1,11 +1,6 @@
import type {
GitActionProgressEvent,
GitStackedAction,
GitStatusResult,
ThreadId,
} from "@t3tools/contracts";
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
import {
@@ -38,6 +33,7 @@ import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import { useAppSettings } from "~/appSettings";
import { openInPreferredEditor } from "~/editorPreferences";
import {
gitBranchesQueryOptions,
@@ -48,7 +44,6 @@ import {
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
@@ -69,50 +64,6 @@ interface PendingDefaultBranchAction {
type GitActionToastId = ReturnType<typeof toastManager.add>;
interface ActiveGitActionProgress {
toastId: GitActionToastId;
actionId: string;
title: string;
phaseStartedAtMs: number | null;
hookStartedAtMs: number | null;
hookName: string | null;
lastOutputLine: string | null;
currentPhaseLabel: string | null;
}
interface RunGitActionWithToastInput {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
featureBranch?: boolean;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
filePaths?: string[];
}
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
if (startedAtMs === null) {
return undefined;
}
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAtMs) / 1000));
if (elapsedSeconds < 60) {
return `Running for ${elapsedSeconds}s`;
}
const minutes = Math.floor(elapsedSeconds / 60);
const seconds = elapsedSeconds % 60;
return `Running for ${minutes}m ${seconds}s`;
}
function resolveProgressDescription(progress: ActiveGitActionProgress): string | undefined {
if (progress.lastOutputLine) {
return progress.lastOutputLine;
}
return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
}
function getMenuActionDisabledReason({
item,
gitStatus,
@@ -210,6 +161,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const { settings } = useAppSettings();
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
@@ -217,21 +169,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const [isEditingFiles, setIsEditingFiles] = useState(false);
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
const updateActiveProgressToast = useCallback(() => {
const progress = activeGitActionProgressRef.current;
if (!progress) {
return;
}
toastManager.update(progress.toastId, {
type: "loading",
title: progress.title,
description: resolveProgressDescription(progress),
timeout: 0,
data: threadToastData,
});
}, [threadToastData]);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
@@ -270,6 +207,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const configuredCommitFlags = settings.gitCommitFlags.trim();
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
@@ -297,84 +235,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
})
: null;
useEffect(() => {
const api = readNativeApi();
if (!api) {
return;
}
const applyProgressEvent = (event: GitActionProgressEvent) => {
const progress = activeGitActionProgressRef.current;
if (!progress) {
return;
}
if (gitCwd && event.cwd !== gitCwd) {
return;
}
if (progress.actionId !== event.actionId) {
return;
}
const now = Date.now();
switch (event.kind) {
case "action_started":
progress.phaseStartedAtMs = now;
progress.hookStartedAtMs = null;
progress.hookName = null;
progress.lastOutputLine = null;
break;
case "phase_started":
progress.title = event.label;
progress.currentPhaseLabel = event.label;
progress.phaseStartedAtMs = now;
progress.hookStartedAtMs = null;
progress.hookName = null;
progress.lastOutputLine = null;
break;
case "hook_started":
progress.title = `Running ${event.hookName}...`;
progress.hookName = event.hookName;
progress.hookStartedAtMs = now;
progress.lastOutputLine = null;
break;
case "hook_output":
progress.lastOutputLine = event.text;
break;
case "hook_finished":
progress.title = progress.currentPhaseLabel ?? "Committing...";
progress.hookName = null;
progress.hookStartedAtMs = null;
progress.lastOutputLine = null;
break;
case "action_finished":
progress.phaseStartedAtMs = null;
progress.hookStartedAtMs = null;
break;
case "action_failed":
progress.phaseStartedAtMs = null;
progress.hookStartedAtMs = null;
break;
}
updateActiveProgressToast();
};
return api.git.onActionProgress(applyProgressEvent);
}, [gitCwd, updateActiveProgressToast]);
useEffect(() => {
const interval = window.setInterval(() => {
if (!activeGitActionProgressRef.current) {
return;
}
updateActiveProgressToast();
}, 1000);
return () => {
window.clearInterval(interval);
};
}, [updateActiveProgressToast]);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
if (!api) {
@@ -402,9 +262,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
data: threadToastData,
});
});
}, [gitStatusForActions, threadToastData]);
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
const runGitActionWithToast = useEffectEvent(
const runGitActionWithToast = useCallback(
async ({
action,
commitMessage,
@@ -416,7 +276,18 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
isDefaultBranchOverride,
progressToastId,
filePaths,
}: RunGitActionWithToastInput) => {
}: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
featureBranch?: boolean;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
filePaths?: string[];
}) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.branch ?? null;
const actionIsDefaultBranch =
@@ -451,49 +322,50 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
forcePushOnly: forcePushOnlyProgress,
featureBranch,
});
const actionId = randomUUID();
const resolvedProgressToastId =
progressToastId ??
toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
});
activeGitActionProgressRef.current = {
toastId: resolvedProgressToastId,
actionId,
title: progressStages[0] ?? "Running git action...",
phaseStartedAtMs: null,
hookStartedAtMs: null,
hookName: null,
lastOutputLine: null,
currentPhaseLabel: progressStages[0] ?? "Running git action...",
};
if (progressToastId) {
toastManager.update(progressToastId, {
type: "loading",
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
});
}
let stageIndex = 0;
const stageInterval = setInterval(() => {
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
toastManager.update(resolvedProgressToastId, {
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
data: threadToastData,
});
}, 1100);
const stopProgressUpdates = () => {
clearInterval(stageInterval);
};
const promise = runImmediateGitActionMutation.mutateAsync({
actionId,
action,
...(commitMessage ? { commitMessage } : {}),
...(configuredCommitFlags ? { commitFlags: configuredCommitFlags } : {}),
...(featureBranch ? { featureBranch } : {}),
...(filePaths ? { filePaths } : {}),
});
try {
const result = await promise;
activeGitActionProgressRef.current = null;
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl =
@@ -569,7 +441,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
: {}),
});
} catch (err) {
activeGitActionProgressRef.current = null;
stopProgressUpdates();
toastManager.update(resolvedProgressToastId, {
type: "error",
title: "Action failed",
@@ -578,6 +450,15 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}
},
[
configuredCommitFlags,
isDefaultBranch,
runImmediateGitActionMutation,
setPendingDefaultBranchAction,
threadToastData,
gitStatusForActions,
],
);
const continuePendingDefaultBranchAction = useCallback(() => {
@@ -593,23 +474,38 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
...(filePaths ? { filePaths } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
}, [pendingDefaultBranchAction, runGitActionWithToast]);
const checkoutNewBranchAndRunAction = useCallback(
(actionParams: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
filePaths?: string[];
}) => {
void runGitActionWithToast({
...actionParams,
featureBranch: true,
skipDefaultBranchPrompt: true,
});
},
[runGitActionWithToast],
);
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
checkoutNewBranchAndRunAction({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
const runDialogActionOnNewBranch = useCallback(() => {
if (!isCommitDialogOpen) return;
@@ -620,14 +516,18 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
setExcludedFiles(new Set());
setIsEditingFiles(false);
void runGitActionWithToast({
checkoutNewBranchAndRunAction({
action: "commit",
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]);
}, [
allSelected,
isCommitDialogOpen,
dialogCommitMessage,
checkoutNewBranchAndRunAction,
selectedFiles,
]);
const runQuickAction = useCallback(() => {
if (quickAction.kind === "open_pr") {
@@ -667,7 +567,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
@@ -688,7 +588,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
},
[openExistingPr, setIsCommitDialogOpen],
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
);
const runDialogAction = useCallback(() => {
@@ -707,6 +607,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
allSelected,
dialogCommitMessage,
isCommitDialogOpen,
runGitActionWithToast,
selectedFiles,
setDialogCommitMessage,
setIsCommitDialogOpen,
+1 -1
View File
@@ -146,7 +146,7 @@ export const OpenAI: Icon = (props) => (
export const ClaudeAI: Icon = (props) => (
<svg {...props} preserveAspectRatio="xMidYMid" viewBox="0 0 256 257">
<path
fill="currentColor"
fill="#D97757"
d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"
/>
</svg>
@@ -64,10 +64,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
},
defaultModel: "gpt-5",
scripts: [],
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
@@ -79,10 +76,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Test thread",
modelSelection: {
provider: "codex",
model: "gpt-5",
},
model: "gpt-5",
interactionMode: "default",
runtimeMode: "full-access",
branch: "main",
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more