Compare commits

..
Author SHA1 Message Date
Julius Marminge be2bb4f4c3 uncache 2026-02-26 19:26:56 -08:00
Julius MarmingeandClaude Opus 4.5 3907e5e8c5 Fix Effect type warnings to pass typecheck
- Use generic type parameter for stream errors instead of unknown
- Type ServerShape errors as ServerLifecycleError instead of unknown
- Add error mapping for autoBootstrapProject and httpServerListen
- Type makeServerProviderLayer with ProviderUnsupportedError
- Use Effect.try with decodeUnknownSync in projector to avoid unknown requirements
- Fix test layer types from any/unknown to never

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-02-26 19:23:26 -08:00
Julius Marminge c8989287d3 rm 2026-02-26 19:08:15 -08:00
Julius Marminge 8ec1958540 rm 2026-02-26 19:08:08 -08:00
Julius Marminge 86650a03bb fix some? 2026-02-26 19:07:21 -08:00
Julius Marminge 2742cd8a0c Normalize Git and PTY adapter errors across services
- Use domain errors directly in GitManager tests (`GitHubCliError`, `TextGenerationError`)
- Remove fixture-only GH error normalization in test scaffolding
- Introduce shared `PtyAdapterInitializationError` and use it in NodePTY adapter init
2026-02-26 18:47:40 -08:00
Julius Marminge 79affb0e06 Use Effect.sleep in orchestration integration tests
- replace custom Promise-based sleep helpers with `Effect.sleep`
- remove now-unused integration sleep error class and harness error mapping
2026-02-26 18:47:40 -08:00
Julius Marminge 74dbb98a40 Harden server async error handling with typed Effect errors
- Replace raw `Effect.promise`/generic errors with `Effect.tryPromise` and tagged schema errors
- Improve orchestration harness/test reliability with explicit timeout/runtime error types
- Tighten related tests and error assertions to match typed error flows
2026-02-26 18:47:40 -08:00
Julius Marminge 10c1cae6ab claude plan 2026-02-26 18:42:13 -08:00
Julius Marminge 87854c288b return yield 2026-02-26 18:40:23 -08:00
Julius Marminge b39c629dcc Validate dev runner port overrides and honor env state dir
- Prefer `T3CODE_STATE_DIR` from env when `--state-dir` is unset or blank
- Throw on invalid `T3CODE_PORT` overrides and always recompute `VITE_WS_URL`
- Add tests for env/state-dir precedence, blank overrides, and invalid ports
2026-02-26 18:40:23 -08:00
Julius Marminge b95cc59e79 || 2026-02-26 18:40:23 -08:00
Julius Marminge 7722cb6d2e Ensure harness cleanup runs even when shutdown fails
- make integration harness dispose path always remove temp root dirs via `Effect.ensuring`
- preserve shutdown failure by surfacing the first teardown error cause
- add integration test that forces `providerService.stopAll` failure and verifies temp dir cleanup
2026-02-26 18:40:23 -08:00
Julius Marminge c9a59a26bb Reject flag tokens as values in dev-runner arg parsing
- Treat `--` and `-...` tokens after value flags as missing values
- Add regression test for `--state-dir --continue` to throw the expected error
2026-02-26 18:40:23 -08:00
Julius Marminge e0fe4270aa simplify 2026-02-26 18:40:23 -08:00
Julius Marminge 0451b503a3 Isolate dev state and forward server flags in dev runner
- default root dev commands to `T3CODE_STATE_DIR=~/.t3/dev`
- add `--` flag forwarding in `scripts/dev-runner.mjs` for server env flags
- resolve desktop state dir from `T3CODE_STATE_DIR` with new tests for desktop and dev runner
2026-02-26 18:40:23 -08:00
Julius Marminge 5ec8c9f79d Scope diff patch cache key by theme
- pass a cache scope into `getRenderablePatch` and include resolved theme in DiffPanel cache keys
- add a test proving `buildPatchCacheKey` changes when cache scope changes
2026-02-26 18:09:36 -08:00
Julius Marminge 0886636760 Enhance active sidebar thread styling
- Add stronger active-state visuals for thread rows (accent bg, ring, medium text)
- Improve active thread timestamp contrast for better readability
2026-02-26 18:04:47 -08:00
19 changed files with 1041 additions and 170 deletions

No files matched your search

+546
View File
@@ -0,0 +1,546 @@
# 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
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. `ProviderService.startSession` currently defaults to `provider: "codex"` unless explicitly provided.
3. `thread.turn.start` has no provider field today, so first-turn provider selection cannot be explicitly requested.
4. `ProviderService` 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
Update `packages/contracts/src/provider.ts`:
1. Extend `ProviderSessionStartInput` with optional Claude-specific fields (for example `claudeBinaryPath`, `permissionMode`, `maxThinkingTokens`).
2. Keep fields optional so current call sites remain valid.
3. Continue using generic `resumeThreadId` + `resumeCursor` as the cross-provider recovery mechanism.
### 1.4 Contract tests
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Backward compatibility of existing command/schema decoding.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.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 `claudeBinaryPath`)
4. `permissionMode`
5. `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 `resumeThreadId` / `resumeCursor`.
#### 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`.
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 abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(input.sessionId),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: input.permissionMode,
maxThinkingTokens: input.maxThinkingTokens,
pathToClaudeCodeExecutable: input.claudeBinaryPath,
resume: input.resumeThreadId,
resumeSessionAt: readResumeCursor(input.resumeCursor),
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(input.sessionId),
hooks: makeClaudeHooks(input.sessionId),
},
});
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 queue = yield* Queue.unbounded<ClaudeSdkMessage>();
yield* Effect.forkScoped(
Effect.tryPromise({
try: async () => {
for await (const message of session.result) {
Queue.offerAllUnsafe(queue, [message]);
}
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream pump failed.",
cause,
}),
}),
);
const sdkMessageStream = Stream.fromQueue(queue);
```
#### 2.2.d Multi-turn prompt queue pattern (Effect)
Use an Effect queue as the single input boundary:
```ts
const promptQueue = yield* Queue.unbounded<ClaudePromptEnvelope>();
const prompt: AsyncIterable<ClaudePromptEnvelope> = {
[Symbol.asyncIterator]() {
return {
next: async () => {
const item = await Effect.runPromise(Queue.take(promptQueue));
if (item.type === "terminate") {
return { done: true, value: undefined };
}
return { done: false, value: item };
},
};
},
};
```
`sendTurn()` enqueues a user envelope, while `stopSession()` enqueues terminate and aborts.
#### 2.2.e Approval bridge with `canUseTool`
Map SDK approval checks to existing orchestration approval flows:
```ts
const canUseTool = async (toolName: string, toolInput: Record<string, unknown>) => {
if (approvalModeIsFullAccess(sessionId)) {
return { behavior: "allow", updatedInput: toolInput };
}
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
emitRuntimeEvent({
type: "approval.requested",
provider: "claudeCode",
sessionId,
requestId,
requestKind: classifyTool(toolName),
detail: summarizeToolRequest(toolName, toolInput),
// ... eventId/createdAt
});
const decision = await waitForApprovalDecision(requestId);
emitRuntimeEvent({
type: "approval.resolved",
provider: "claudeCode",
sessionId,
requestId,
decision,
// ... eventId/createdAt
});
return decision === "accept" || decision === "acceptForSession"
? { behavior: "allow", updatedInput: toolInput }
: { behavior: "deny", message: "User declined tool execution." };
};
```
#### 2.2.f Hooks and checkpoint signals
If Claude hooks provide cleaner turn boundaries, convert them into canonical runtime events (`turn.completed` and optionally `checkpoint.captured`) so `CheckpointReactor` remains unchanged:
```ts
hooks: {
Stop: [
{
matcher: {},
hooks: [
async () => {
emitRuntimeEvent({
type: "checkpoint.captured",
provider: "claudeCode",
sessionId,
threadId,
turnId: activeTurnId,
turnCount: nextTurnCount(),
// ... eventId/createdAt
});
},
],
},
],
}
```
#### 2.2.g Runtime control method wiring
Adapter should expose SDK controls through existing service methods and runtime payload updates:
1. `interruptTurn()` -> `result.interrupt()`
2. Model override on send turn -> `result.setModel(model)` before enqueuing prompt
3. Runtime mode changes -> `result.setPermissionMode(mode)` if we support live mode switching
4. Thinking budget updates -> `result.setMaxThinkingTokens(tokens)` when configured
### 2.3 Canonical event mapping
Map Claude SDK events to `ProviderRuntimeEvent`:
1. `session.started` / `session.exited`
2. `turn.started` / `turn.completed`
3. `message.delta` / `message.completed`
4. `tool.started` / `tool.completed`
5. `approval.requested` / `approval.resolved`
6. `runtime.error`
No provider-native event methods should leak beyond the adapter boundary.
Reference mapping table:
| Claude SDK message/callback | Canonical runtime event(s) | Notes |
|---|---|---|
| assistant partial text | `message.delta` | Emit deltas only (do not resend full content each chunk). |
| assistant final message | `message.completed` | Must include stable `itemId` for dedupe/finalize behavior. |
| result (success) | `turn.completed` (`status: "completed"`) | This is the main turn boundary for checkpointing. |
| result (interrupted/cancelled) | `turn.completed` (`status: "interrupted"`/`"cancelled"`) | Preserve state semantics used by ingestion + UI. |
| result (error) | `runtime.error` and `turn.completed` (`status: "failed"`) | Include concise error message. |
| tool start | `tool.started` | Set `toolKind` using shared classifier (`command`, `file-change`, `other`). |
| tool result | `tool.completed` | Include detail summary used by activity feed. |
| canUseTool prompt | `approval.requested` | Source of request id shown in UI. |
| approval decision returned | `approval.resolved` | Must correlate using same request id. |
| session initialization | `session.started`, optional `thread.started` | Ensure `threadId` is emitted early and consistently. |
| process exit/close | `session.exited` | Required for session status projection cleanup. |
### 2.4 Session/thread/resume identifiers
Define explicit adapter semantics:
1. `sessionId`: adapter-owned stable session id.
2. `threadId`: Claude conversation/session identifier returned as `ProviderThreadId`.
3. `resumeCursor`: provider-specific cursor (for example message id) needed for precise recovery/rollback.
### 2.5 Rollback/read strategy
Implement `readThread()` and `rollbackThread()` in a way compatible with `CheckpointReactor`.
Preferred:
1. Track per-turn resume cursors and reconstruct session state on rollback.
2. Keep adapter `sessionId` stable across internal rehydration/restart.
Fallback (explicitly documented if chosen):
1. Filesystem revert succeeds even when conversation rewind is partial.
2. Reactor behavior is updated to surface a clear warning activity instead of silent drift.
### 2.6 Adapter unit tests
Add tests mirroring Codex adapter coverage:
1. Provider validation (`provider === "claudeCode"`).
2. Event mapping to canonical runtime events.
3. Approval request lifecycle.
4. Resume/recovery behavior.
5. Rollback behavior.
---
## Phase 3: Register adapter in runtime composition
### 3.1 Adapter registry wiring
Update:
1. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
Register both Codex and Claude adapters.
### 3.2 Server layer composition
Update:
1. `apps/server/src/serverLayers.ts`
Provide `ClaudeCodeAdapterLive` alongside Codex in `makeServerProviderLayer()`.
### 3.3 Composition tests
Update integration tests to ensure:
1. Registry exposes Claude provider.
2. Provider service can route Claude sessions.
---
## Phase 4: Orchestration command/reactor updates
### 4.1 Decider propagation
Update `apps/server/src/orchestration/decider.ts`:
1. Carry optional `provider` from `thread.turn.start` command into `thread.turn-start-requested` event payload.
### 4.2 ProviderCommandReactor provider selection
Update `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`:
1. Prefer provider from turn-start event payload when starting a new session.
2. Fallback to existing thread session provider when payload omitted.
3. Fallback to default provider only when neither is present.
Switch behavior policy (explicit in implementation):
1. If active session provider differs from requested provider, stop and recreate session before sending turn.
2. Keep current provider when request omits provider.
### 4.3 Reactor/invariant tests
Update/add tests in:
1. `apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts`
2. `apps/server/src/orchestration/*.test.ts` as needed
Validate first-turn provider choice, provider switching semantics, and backward compatibility when provider is omitted.
---
## Phase 5: Web provider UX enablement
### 5.1 Enable Claude option
Update `apps/web/src/session-logic.ts`:
1. Mark Claude provider option as available.
### 5.2 Provider selection in composer
Update `apps/web/src/components/ChatView.tsx`:
1. Add provider picker near model/runtime controls.
2. Include selected provider in `thread.turn.start` command payload.
3. Keep selected provider sticky per thread in client state (or derive from active session provider when present).
### 5.3 Provider-aware model picker
Update model picker usage so model options reflect selected provider.
### 5.4 Web tests
Update/add tests for:
1. Provider picker interactions.
2. Turn-start command includes provider.
3. Model list switches by provider.
---
## Phase 6: Checkpoint and revert compatibility
### 6.1 Validate checkpoint reactor expectations
Exercise `apps/server/src/orchestration/Layers/CheckpointReactor.ts` flows with Claude:
1. Turn baseline capture.
2. Turn completion checkpoint capture.
3. Revert + provider rollback coordination.
### 6.2 Policy for partial rollback support
If Claude cannot support full conversation rewind at parity with Codex:
1. Document behavior clearly.
2. Emit explicit thread activity for degraded rollback behavior.
3. Ensure filesystem state remains correct and predictable.
### 6.3 Checkpoint tests
Add/update tests in checkpoint + provider service integration suites for Claude revert behavior.
---
## Phase 7: End-to-end hardening and observability
### 7.1 Integration tests
Add integration coverage for:
1. `thread.turn.start` with `provider: "claudeCode"` from fresh thread.
2. Session recovery after restart (provider session alias/recovery path).
3. Approval request/respond flow.
4. Interrupt behavior.
5. Revert flow with rollback.
### 7.2 WS behavior regression check
Ensure no contract regressions:
1. Client still consumes only `orchestration.domainEvent`.
2. No new provider-specific WS channels introduced.
### 7.3 Logging
Confirm both native and canonical provider logs remain useful with multi-adapter setup:
1. `provider-native.ndjson`
2. `provider-canonical.ndjson`
---
## File checklist
Likely files to touch:
1. `packages/contracts/src/model.ts`
2. `packages/contracts/src/orchestration.ts`
3. `packages/contracts/src/provider.ts`
4. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts` (new)
5. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts` (new)
6. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
7. `apps/server/src/serverLayers.ts`
8. `apps/server/src/orchestration/decider.ts`
9. `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
10. `apps/web/src/session-logic.ts`
11. `apps/web/src/components/ChatView.tsx`
12. Related tests under `packages/contracts/src`, `apps/server/src/provider/Layers`, `apps/server/src/orchestration/Layers`, `apps/server/integration`, and `apps/web/src`.
---
## Delivery order
1. Contracts for provider selection + models.
2. Claude adapter + unit tests.
3. Registry/layer wiring.
4. Reactor updates for provider-aware session start.
5. Web provider picker + provider-aware models.
6. Checkpoint/revert compatibility.
7. End-to-end integration tests and stabilization.
This order keeps risk isolated and maintains a working orchestrated path at each stage.
+3
View File
@@ -68,6 +68,9 @@ npx t3
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `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 -- --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.
+4 -11
View File
@@ -5,16 +5,8 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
type MenuItemConstructorOptions,
protocol,
shell,
} from "electron";
import { app, BrowserWindow, dialog, ipcMain, Menu, protocol, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
@@ -26,7 +18,8 @@ const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const 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);
@@ -9,7 +9,17 @@ import {
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect";
import {
Effect,
Exit,
Layer,
ManagedRuntime,
Option,
Schedule,
Schema,
Scope,
Stream,
} from "effect";
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
@@ -75,20 +85,27 @@ export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): st
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
function waitFor<A>(
read: Effect.Effect<A, unknown>,
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
"WaitForTimeoutError",
{
description: Schema.String,
},
) {}
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs?: number,
): Effect.Effect<A, never>;
function waitFor<A, B extends A>(
read: Effect.Effect<A, unknown>,
function waitFor<A, B extends A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => value is B,
description: string,
timeoutMs?: number,
): Effect.Effect<B, never>;
function waitFor<A>(
read: Effect.Effect<A, unknown>,
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 3000,
@@ -106,12 +123,26 @@ function waitFor<A>(
while: (error) => error === RETRY_SIGNAL,
}),
Effect.mapError((error) =>
error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${description}.`) : error,
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
),
Effect.orDie,
);
}
class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
"OrchestrationHarnessRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
Effect.tryPromise({
try: run,
catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
});
export interface OrchestrationIntegrationHarness {
readonly rootDir: string;
readonly workspaceDir: string;
@@ -152,8 +183,7 @@ export interface OrchestrationIntegrationHarness {
}
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const sleep = (ms: number) => Effect.sleep(ms);
const adapterHarness = yield* makeTestProviderAdapterHarness;
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
@@ -215,30 +245,34 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
);
const runtime = ManagedRuntime.make(layer);
const engine = yield* Effect.promise(() =>
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
runtime.runPromise(Effect.service(OrchestrationEngineService)),
);
const reactor = yield* Effect.promise(() =>
).pipe(Effect.orDie);
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
runtime.runPromise(Effect.service(OrchestrationReactor)),
);
const snapshotQuery = yield* Effect.promise(() =>
).pipe(Effect.orDie);
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
);
const providerService = yield* Effect.promise(() =>
).pipe(Effect.orDie);
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
runtime.runPromise(Effect.service(ProviderService)),
);
const checkpointStore = yield* Effect.promise(() =>
).pipe(Effect.orDie);
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
runtime.runPromise(Effect.service(CheckpointStore)),
);
const checkpointRepository = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
);
const pendingApprovalRepository = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
);
).pipe(Effect.orDie);
const checkpointRepository = yield* tryRuntimePromise(
"load ProjectionCheckpointRepository service",
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
).pipe(Effect.orDie);
const pendingApprovalRepository = yield* tryRuntimePromise(
"load ProjectionPendingApprovalRepository service",
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
).pipe(Effect.orDie);
const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential")));
yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope))));
const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
@@ -317,12 +351,35 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
}
disposed = true;
yield* Effect.promise(() => runtime.runPromise(providerService.stopAll()));
yield* Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void)));
yield* Effect.promise(() => runtime.dispose());
yield* Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
const shutdown = Effect.gen(function* () {
const stopAllExit = yield* Effect.exit(
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
);
const closeScopeExit = yield* Effect.exit(
Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
);
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
const failureCause = Exit.isFailure(stopAllExit)
? stopAllExit.cause
: Exit.isFailure(closeScopeExit)
? closeScopeExit.cause
: Exit.isFailure(disposeRuntimeExit)
? disposeRuntimeExit.cause
: null;
if (failureCause) {
return yield* Effect.failCause(failureCause);
}
});
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
@@ -13,7 +13,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option } from "effect";
import { Effect, Option, Schema } from "effect";
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
import {
@@ -45,8 +45,14 @@ function nowIso() {
return new Date().toISOString();
}
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
"IntegrationWaitTimeoutError",
{
description: Schema.String,
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
@@ -63,7 +69,7 @@ function waitForSync<A>(
return value;
}
if (Date.now() >= deadline) {
return yield* Effect.die(new Error(`Timed out waiting for ${description}.`));
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* sleep(10);
}
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { TextGenerationError } from "../Errors.ts";
@@ -40,7 +40,7 @@ function normalizeCodexError(
error: unknown,
fallback: string,
): TextGenerationError {
if (error instanceof TextGenerationError) {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
@@ -129,9 +129,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const readStreamAsString = (
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, unknown>,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
Effect.gen(function* () {
let text = "";
+23 -42
View File
@@ -6,7 +6,7 @@ import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import { GitHubCliError, TextGenerationError } from "../Errors.ts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
import {
type GitHubCliShape,
@@ -23,7 +23,7 @@ interface FakeGhScenario {
prListSequence?: string[];
createdPrUrl?: string;
defaultBranch?: string;
failWith?: Error;
failWith?: GitHubCliError;
}
interface FakeGitTextGeneration {
@@ -32,7 +32,7 @@ interface FakeGitTextGeneration {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Effect.Effect<{ subject: string; body: string }, unknown>;
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
@@ -40,7 +40,7 @@ interface FakeGitTextGeneration {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}) => Effect.Effect<{ title: string; body: string }, unknown>;
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
}
function makeTempDir(
@@ -58,7 +58,7 @@ function runGit(
allowNonZeroExit = false,
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
unknown,
GitCommandError,
GitService
> {
return Effect.gen(function* () {
@@ -74,7 +74,7 @@ function runGit(
function initRepo(
cwd: string,
): Effect.Effect<void, unknown, FileSystem.FileSystem | Scope.Scope | GitService> {
): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* runGit(cwd, ["init", "--initial-branch=main"]);
@@ -88,7 +88,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
unknown,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
@@ -139,34 +139,6 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
};
}
const normalizeGhError = (error: Error): GitHubCliError => {
if (error.message.includes("Command not found: gh")) {
return new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
return new GitHubCliError({
operation: "execute",
detail: error.message,
cause: error,
});
};
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
service: GitHubCliShape;
ghCalls: string[];
@@ -179,7 +151,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
ghCalls.push(args.join(" "));
if (scenario.failWith) {
return Effect.fail(normalizeGhError(scenario.failWith));
return Effect.fail(scenario.failWith);
}
if (args[0] === "pr" && args[1] === "list") {
@@ -373,7 +345,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new Error("Command not found: gh"),
failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -600,7 +575,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push",
}).pipe(
Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("detached HEAD");
}),
@@ -617,7 +592,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new Error("Command not found: gh"),
failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -626,7 +604,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
}).pipe(
Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
}),
@@ -643,7 +621,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new Error("authentication failed"),
failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
}),
},
});
@@ -652,7 +633,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
}).pipe(
Effect.flip,
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("gh auth login");
}),
@@ -1,6 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
@@ -50,7 +50,7 @@ layer("GitServiceLive", (it) => {
assert.equal(result._tag, "Failure");
if (result._tag === "Failure") {
assert.ok(result.failure instanceof GitCommandError);
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__");
}
+4 -4
View File
@@ -6,7 +6,7 @@
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Stream } from "effect";
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
@@ -28,7 +28,7 @@ function toGitCommandError(
detail: string,
) {
return (cause: unknown) =>
cause instanceof GitCommandError
Schema.is(GitCommandError)(cause)
? cause
: new GitCommandError({
operation: input.operation,
@@ -39,9 +39,9 @@ function toGitCommandError(
});
}
const collectOutput = Effect.fn(function* (
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, unknown>,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
+1 -7
View File
@@ -211,13 +211,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
});
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse(
configState.keybindings.some(
(entry) =>
// @ts-expect-error - invalid command
entry.command === "invalid.command",
),
);
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command"));
assert.deepEqual(configState.issues, [
{
kind: "keybindings.invalid-entry",
+4 -1
View File
@@ -117,7 +117,10 @@ export const launchDetached = (launch: EditorLaunch) =>
});
const make = Effect.gen(function* () {
const open = yield* Effect.promise(() => import("open"));
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
return {
openBrowser: (target) =>
+4 -3
View File
@@ -40,9 +40,10 @@ function decodeForEvent<A>(
eventType: OrchestrationEvent["type"],
field: string,
): Effect.Effect<A, OrchestrationProjectorDecodeError> {
return Schema.decodeUnknownEffect(schema)(value).pipe(
Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
) as Effect.Effect<A, OrchestrationProjectorDecodeError>;
return Effect.try({
try: () => Schema.decodeUnknownSync(schema as any)(value),
catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError),
});
}
function retainThreadMessagesAfterRevert(
+2 -1
View File
@@ -17,6 +17,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
import { ProviderUnsupportedError } from "./provider/Errors";
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
@@ -35,7 +36,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
unknown,
ProviderUnsupportedError,
SqlClient.SqlClient | ServerConfig
> {
return Effect.gen(function* () {
+2 -2
View File
@@ -323,14 +323,14 @@ describe("WebSocket Server", () => {
async function createTestServer(
options: {
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, any>;
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
cwd?: string;
autoBootstrapProjectFromCwd?: boolean;
logWebSocketEvents?: boolean;
devUrl?: string;
authToken?: string;
stateDir?: string;
providerLayer?: Layer.Layer<ProviderService, unknown>;
providerLayer?: Layer.Layer<ProviderService, never>;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
+34 -20
View File
@@ -66,14 +66,14 @@ export interface ServerShape {
*/
readonly start: Effect.Effect<
http.Server,
unknown,
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig
>;
/**
* Wait for process shutdown signals.
*/
readonly stopSignal: Effect.Effect<unknown, never>;
readonly stopSignal: Effect.Effect<void, never>;
}
/**
@@ -165,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server,
unknown, // TODO: This should not be unknown
ServerLifecycleError,
Scope.Scope | ServerRuntimeServices | ServerConfig
> {
const serverConfig = yield* ServerConfig;
@@ -338,21 +338,27 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
if (autoBootstrapProjectFromCwd) {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
if (!existing) {
const createdAt = new Date().toISOString();
const projectName = path.basename(cwd) || "project";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
title: projectName,
workspaceRoot: cwd,
defaultModel: "gpt-5-codex",
createdAt,
});
}
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
if (!existing) {
const createdAt = new Date().toISOString();
const projectName = path.basename(cwd) || "project";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
title: projectName,
workspaceRoot: cwd,
defaultModel: "gpt-5-codex",
createdAt,
});
}
}).pipe(
Effect.mapError(
(cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
),
);
}
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
@@ -389,7 +395,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsSearchEntries: {
const body = stripRequestTag(request.body);
return yield* Effect.promise(() => searchWorkspaceEntries(body));
return yield* Effect.tryPromise({
try: () => searchWorkspaceEntries(body),
catch: (cause) =>
new RouteRequestError({
message: `Failed to search workspace entries: ${String(cause)}`,
}),
});
}
case WS_METHODS.shellOpenInEditor: {
@@ -612,7 +624,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
);
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* NodeHttpServer.make(() => httpServer, listenOptions);
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
);
yield* Effect.addFinalizer(() =>
Effect.all([
+8 -2
View File
@@ -578,7 +578,9 @@ export default function Sidebar() {
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
isActive ? "text-foreground" : "text-muted-foreground"
isActive
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
: "text-muted-foreground"
}`}
onClick={() => {
void navigate({
@@ -624,7 +626,11 @@ export default function Sidebar() {
/>
</span>
)}
<span className="text-[10px] text-muted-foreground/40">
<span
className={`text-[10px] ${
isActive ? "text-foreground/65" : "text-muted-foreground/40"
}`}
>
{formatRelativeTime(thread.createdAt)}
</span>
</div>
+174 -34
View File
@@ -1,8 +1,12 @@
import { spawn } from "node:child_process";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5173;
const MAX_HASH_OFFSET = 3000;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {
dev: [
"run",
@@ -17,6 +21,21 @@ const MODE_ARGS = {
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
};
const FORWARDED_ENV_FLAGS = {
"state-dir": { envName: "T3CODE_STATE_DIR", expectsValue: true },
"auth-token": { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
token: { envName: "T3CODE_AUTH_TOKEN", expectsValue: true },
"no-browser": { envName: "T3CODE_NO_BROWSER", expectsValue: false },
"auto-bootstrap-project-from-cwd": {
envName: "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD",
expectsValue: false,
},
"log-websocket-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
"log-ws-events": { envName: "T3CODE_LOG_WS_EVENTS", expectsValue: false },
host: { envName: "T3CODE_HOST", expectsValue: true },
port: { envName: "T3CODE_PORT", expectsValue: true },
"dev-url": { envName: "VITE_DEV_SERVER_URL", expectsValue: true },
};
function parseInteger(value, envName) {
const parsed = Number(value);
@@ -35,8 +54,8 @@ function hashSeed(seed) {
return hash >>> 0;
}
function resolveOffset() {
const explicitOffset = process.env.T3CODE_PORT_OFFSET?.trim();
export function resolveOffset(env = process.env) {
const explicitOffset = env.T3CODE_PORT_OFFSET?.trim();
if (explicitOffset) {
const parsed = parseInteger(explicitOffset, "T3CODE_PORT_OFFSET");
if (parsed < 0) {
@@ -45,7 +64,7 @@ function resolveOffset() {
return { offset: parsed, source: `T3CODE_PORT_OFFSET=${explicitOffset}` };
}
const seed = process.env.T3CODE_DEV_INSTANCE?.trim();
const seed = env.T3CODE_DEV_INSTANCE?.trim();
if (!seed) {
return { offset: 0, source: "default ports" };
}
@@ -58,9 +77,140 @@ function resolveOffset() {
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
}
function main() {
const mode = process.argv[2];
const isDryRun = process.argv.includes("--dry-run");
function parseLongFlag(raw) {
if (!raw.startsWith("--")) return null;
const normalized = raw.slice(2);
const equalsIndex = normalized.indexOf("=");
if (equalsIndex === -1) {
return { name: normalized, value: undefined };
}
return {
name: normalized.slice(0, equalsIndex),
value: normalized.slice(equalsIndex + 1),
};
}
function toBooleanEnvValue(value) {
if (value === undefined) return "1";
const normalized = value.trim().toLowerCase();
if (normalized === "false" || normalized === "0" || normalized === "no") return "0";
return "1";
}
export function parseDevRunnerArgs(rawArgs) {
const args = rawArgs[0] === "--" ? rawArgs.slice(1) : rawArgs.slice();
const envOverrides = {};
const turboArgs = [];
let isDryRun = false;
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === "--dry-run") {
isDryRun = true;
continue;
}
if (arg === "--") {
turboArgs.push(...args.slice(index + 1));
break;
}
const parsedFlag = parseLongFlag(arg);
if (!parsedFlag) {
turboArgs.push(arg);
continue;
}
const definition = FORWARDED_ENV_FLAGS[parsedFlag.name];
if (!definition) {
turboArgs.push(arg);
continue;
}
if (definition.expectsValue) {
let value = parsedFlag.value;
if (value === undefined) {
const next = args[index + 1];
if (next === undefined || next === "--" || next.startsWith("-")) {
throw new Error(`Missing value for --${parsedFlag.name}`);
}
value = next;
index += 1;
}
envOverrides[definition.envName] = value;
continue;
}
envOverrides[definition.envName] = toBooleanEnvValue(parsedFlag.value);
}
return {
isDryRun,
envOverrides,
turboArgs,
};
}
function resolveStateDir(env, envOverrides) {
const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim();
if (overrideValue) {
return overrideValue;
}
const envValue = env?.T3CODE_STATE_DIR?.trim();
if (envValue) {
return envValue;
}
return DEFAULT_DEV_STATE_DIR;
}
export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const output = {
...env,
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
...envOverrides,
};
output.T3CODE_STATE_DIR = resolveStateDir(env, envOverrides);
const parsedServerPort = Number(output.T3CODE_PORT);
if (!Number.isInteger(parsedServerPort) || parsedServerPort < 1 || parsedServerPort > 65535) {
throw new Error(
`Invalid T3CODE_PORT override: '${String(output.T3CODE_PORT)}'. Expected an integer between 1 and 65535.`,
);
}
output.VITE_WS_URL = `ws://localhost:${parsedServerPort}`;
if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
// Running server/web in browser mode should not inherit desktop launcher state.
output.T3CODE_MODE = "web";
if (!("T3CODE_NO_BROWSER" in envOverrides)) {
delete output.T3CODE_NO_BROWSER;
}
if (!("T3CODE_AUTH_TOKEN" in envOverrides)) {
delete output.T3CODE_AUTH_TOKEN;
}
delete output.T3CODE_DESKTOP_WS_URL;
}
if (mode === "dev" && !output.T3CODE_LOG_WS_EVENTS) {
output.T3CODE_LOG_WS_EVENTS = "1";
}
return output;
}
export function runDevRunner(argv = process.argv) {
const mode = argv[2];
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
if (!mode || !(mode in MODE_ARGS)) {
const supportedModes = Object.keys(MODE_ARGS).join(", ");
throw new Error(`Usage: bun scripts/dev-runner.mjs <mode>. Supported modes: ${supportedModes}`);
@@ -76,37 +226,23 @@ function main() {
);
}
const env = {
...process.env,
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
};
if (mode === "dev" || mode === "dev:server" || mode === "dev:web") {
// Running server/web in browser mode should not inherit desktop launcher state.
env.T3CODE_MODE = "web";
delete env.T3CODE_NO_BROWSER;
delete env.T3CODE_AUTH_TOKEN;
delete env.T3CODE_DESKTOP_WS_URL;
}
if (mode === "dev" && !env.T3CODE_LOG_WS_EVENTS) {
env.T3CODE_LOG_WS_EVENTS = "1";
}
const env = createDevRunnerEnv({
mode,
env: process.env,
offset,
envOverrides: parsedArgs.envOverrides,
});
console.info(
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}`,
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort} stateDir=${env.T3CODE_STATE_DIR}`,
);
if (isDryRun) {
if (parsedArgs.isDryRun) {
return;
}
const command = process.platform === "win32" ? "turbo.cmd" : "turbo";
const child = spawn(command, MODE_ARGS[mode], {
const child = spawn(command, [...MODE_ARGS[mode], ...parsedArgs.turboArgs], {
stdio: "inherit",
env,
});
@@ -125,9 +261,13 @@ function main() {
});
}
try {
main();
} catch (error) {
console.error("[dev-runner]", error);
process.exit(1);
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === entrypointPath) {
try {
runDevRunner();
} catch (error) {
console.error("[dev-runner]", error);
process.exit(1);
}
}
+125
View File
@@ -0,0 +1,125 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_DEV_STATE_DIR,
createDevRunnerEnv,
parseDevRunnerArgs,
} from "./dev-runner.mjs";
describe("parseDevRunnerArgs", () => {
it("maps supported server flags to env overrides and keeps other flags for turbo", () => {
const parsed = parseDevRunnerArgs([
"--",
"--state-dir",
"~/alt-state",
"--token=abc123",
"--no-browser=false",
"--dry-run",
"--continue",
]);
expect(parsed.isDryRun).toBe(true);
expect(parsed.envOverrides).toEqual({
T3CODE_STATE_DIR: "~/alt-state",
T3CODE_AUTH_TOKEN: "abc123",
T3CODE_NO_BROWSER: "0",
});
expect(parsed.turboArgs).toEqual(["--continue"]);
});
it("throws when a value flag is missing its value", () => {
expect(() => parseDevRunnerArgs(["--state-dir"])).toThrow("Missing value for --state-dir");
});
it("throws when a value flag is followed by another flag token", () => {
expect(() => parseDevRunnerArgs(["--state-dir", "--continue"])).toThrow(
"Missing value for --state-dir",
);
});
});
describe("createDevRunnerEnv", () => {
it("defaults state dir to ~/.t3/dev when not provided", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: {},
});
expect(env.T3CODE_STATE_DIR).toBe(DEFAULT_DEV_STATE_DIR);
});
it("uses existing env state dir when --state-dir is not provided", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: {},
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
});
it("lets --state-dir override existing env state dir", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: { T3CODE_STATE_DIR: "/tmp/override-state" },
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/override-state");
});
it("treats whitespace-only --state-dir as missing and falls back to env/default", () => {
const env = createDevRunnerEnv({
mode: "dev:server",
env: { T3CODE_STATE_DIR: "/tmp/existing-state" },
offset: 0,
envOverrides: { T3CODE_STATE_DIR: " " },
});
expect(env.T3CODE_STATE_DIR).toBe("/tmp/existing-state");
});
it("recomputes websocket url when port is overridden", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: { T3CODE_PORT: "4222" },
});
expect(env.T3CODE_PORT).toBe("4222");
expect(env.VITE_WS_URL).toBe("ws://localhost:4222");
});
it("keeps explicitly forwarded web-mode flags", () => {
const env = createDevRunnerEnv({
mode: "dev",
env: {
T3CODE_AUTH_TOKEN: "desktop-token",
},
offset: 0,
envOverrides: {
T3CODE_NO_BROWSER: "1",
T3CODE_AUTH_TOKEN: "cli-token",
},
});
expect(env.T3CODE_NO_BROWSER).toBe("1");
expect(env.T3CODE_AUTH_TOKEN).toBe("cli-token");
});
it("fails fast for invalid port overrides", () => {
expect(() =>
createDevRunnerEnv({
mode: "dev",
env: {},
offset: 0,
envOverrides: { T3CODE_PORT: "not-a-port" },
}),
).toThrow("Invalid T3CODE_PORT override");
});
});
+1
View File
@@ -30,6 +30,7 @@
},
"test": {
"dependsOn": ["^build"],
"cache": false,
"outputs": []
}
}