Compare commits

..
Author SHA1 Message Date
Julius Marminge 51dbea28c2 keybindings 2026-02-26 14:24:03 -08:00
121 changed files with 787 additions and 2890 deletions

No files matched your search

-1
View File
@@ -11,4 +11,3 @@ packages/*/dist
build/
.logs/
release/
.t3
+1 -3
View File
@@ -15,8 +15,6 @@
"perf": "warn"
},
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
"react-in-jsx-scope": "off"
}
}
-546
View File
@@ -1,546 +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
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,9 +68,6 @@ 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.
+2 -2
View File
@@ -15,11 +15,11 @@
- [x] "Response" bar should ONLY appear above the FINAL message in a series
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
- [x] Insta focus input on new thread creation
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
- [x] Making new thread should auto-focus input box
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
## Bigger things
- [ ] Queueing messages
- [x] External runners (i.e. running the cli on a mac mini)
- [ ] External runners (i.e. running the cli on a mac mini)
+11 -4
View File
@@ -5,8 +5,16 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, protocol, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
type MenuItemConstructorOptions,
protocol,
shell,
} from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
@@ -18,8 +26,7 @@ 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 =
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
const STATE_DIR = 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);
@@ -3,23 +3,13 @@ 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 { NodeServices } from "@effect/platform-node";
import {
ApprovalRequestId,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
Layer,
ManagedRuntime,
Option,
Schedule,
Schema,
Scope,
Stream,
} from "effect";
import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect";
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
@@ -85,27 +75,20 @@ export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): st
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
"WaitForTimeoutError",
{
description: Schema.String,
},
) {}
function waitFor<A, E>(
read: Effect.Effect<A, E>,
function waitFor<A>(
read: Effect.Effect<A, unknown>,
predicate: (value: A) => boolean,
description: string,
timeoutMs?: number,
): Effect.Effect<A, never>;
function waitFor<A, B extends A, E>(
read: Effect.Effect<A, E>,
function waitFor<A, B extends A>(
read: Effect.Effect<A, unknown>,
predicate: (value: A) => value is B,
description: string,
timeoutMs?: number,
): Effect.Effect<B, never>;
function waitFor<A, E>(
read: Effect.Effect<A, E>,
function waitFor<A>(
read: Effect.Effect<A, unknown>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 3000,
@@ -123,26 +106,12 @@ function waitFor<A, E>(
while: (error) => error === RETRY_SIGNAL,
}),
Effect.mapError((error) =>
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${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;
@@ -183,7 +152,8 @@ export interface OrchestrationIntegrationHarness {
}
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
const sleep = (ms: number) => Effect.sleep(ms);
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const adapterHarness = yield* makeTestProviderAdapterHarness;
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
@@ -245,34 +215,30 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
);
const runtime = ManagedRuntime.make(layer);
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
const engine = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(OrchestrationEngineService)),
).pipe(Effect.orDie);
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
);
const reactor = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(OrchestrationReactor)),
).pipe(Effect.orDie);
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
);
const snapshotQuery = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
).pipe(Effect.orDie);
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
);
const providerService = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProviderService)),
).pipe(Effect.orDie);
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
);
const checkpointStore = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(CheckpointStore)),
).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 checkpointRepository = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
);
const pendingApprovalRepository = yield* Effect.promise(() =>
runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
);
const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential")));
yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope))));
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
@@ -351,35 +317,12 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
}
disposed = 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* 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 });
});
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, Schema } from "effect";
import { Effect, Option } from "effect";
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
import {
@@ -45,14 +45,8 @@ function nowIso() {
return new Date().toISOString();
}
class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
"IntegrationWaitTimeoutError",
{
description: Schema.String,
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
function waitForSync<A>(
read: () => A,
@@ -69,7 +63,7 @@ function waitForSync<A>(
return value;
}
if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
return yield* Effect.die(new Error(`Timed out waiting for ${description}.`));
}
yield* sleep(10);
}
@@ -1,6 +1,6 @@
import type { ProviderRuntimeEvent, ProviderSessionId } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
+4 -4
View File
@@ -18,17 +18,17 @@
"test": "vitest run"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@effect/platform-node": "4.0.0-beta.10",
"@effect/sql-sqlite-bun": "4.0.0-beta.10",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"effect": "4.0.0-beta.10",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/language-service": "0.75.1",
"@effect/vitest": "catalog:",
"@effect/vitest": "4.0.0-beta.10",
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "^1.3.9",
@@ -46,4 +46,4 @@ export interface CheckpointDiffQueryShape {
export class CheckpointDiffQuery extends ServiceMap.Service<
CheckpointDiffQuery,
CheckpointDiffQueryShape
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
>()("checkpointing/CheckpointDiffQuery") {}
@@ -96,5 +96,5 @@ export interface CheckpointStoreShape {
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
*/
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
"t3/checkpointing/Services/CheckpointStore",
"checkpointing/CheckpointStore",
) {}
+7 -7
View File
@@ -35,7 +35,7 @@ export interface ServerConfigShape {
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
"server/ServerConfig",
) {}
// Helpers
@@ -61,7 +61,7 @@ export interface NetServiceShape {
* NetService - Service tag for startup networking helpers.
*/
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
"t3/config/NetService",
"server/NetService",
) {
static readonly layer = Layer.succeed(NetService, {
findAvailablePort: (preferred) =>
@@ -102,18 +102,18 @@ export class NetService extends ServiceMap.Service<NetService, NetServiceShape>(
export const resolveStaticDir = Effect.fn(function* () {
const { join, resolve } = yield* Path.Path;
const { exists } = yield* FileSystem.FileSystem;
const { stat } = yield* FileSystem.FileSystem;
const bundledClient = resolve(join(import.meta.dirname, "client"));
const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
Effect.orElseSucceed(() => false),
const bundledStat = yield* stat(join(bundledClient, "index.html")).pipe(
Effect.orElseSucceed(() => undefined),
);
if (bundledStat) {
return bundledClient;
}
const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
Effect.orElseSucceed(() => false),
const monorepoStat = yield* stat(join(monorepoClient, "index.html")).pipe(
Effect.orElseSucceed(() => undefined),
);
if (monorepoStat) {
return monorepoClient;
@@ -1,4 +1,4 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { Effect, FileSystem, Layer, Option, Path, 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 (Schema.is(TextGenerationError)(error)) {
if (error instanceof TextGenerationError) {
return error;
}
@@ -129,9 +129,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const readStreamAsString = <E>(
const readStreamAsString = (
operation: string,
stream: Stream.Stream<Uint8Array, E>,
stream: Stream.Stream<Uint8Array, unknown>,
): Effect.Effect<string, TextGenerationError> =>
Effect.gen(function* () {
let text = "";
+1 -1
View File
@@ -1,7 +1,7 @@
import { existsSync } from "node:fs";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect, vi } from "vitest";
+43 -24
View File
@@ -1,12 +1,12 @@
import fs from "node:fs";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { 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?: GitHubCliError;
failWith?: Error;
}
interface FakeGitTextGeneration {
@@ -32,7 +32,7 @@ interface FakeGitTextGeneration {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
}) => Effect.Effect<{ subject: string; body: string }, unknown>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
@@ -40,7 +40,7 @@ interface FakeGitTextGeneration {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
}) => Effect.Effect<{ title: string; body: string }, unknown>;
}
function makeTempDir(
@@ -58,7 +58,7 @@ function runGit(
allowNonZeroExit = false,
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
GitCommandError,
unknown,
GitService
> {
return Effect.gen(function* () {
@@ -74,7 +74,7 @@ function runGit(
function initRepo(
cwd: string,
): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {
): Effect.Effect<void, unknown, 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,
PlatformError.PlatformError | GitCommandError,
unknown,
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
@@ -139,6 +139,34 @@ 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[];
@@ -151,7 +179,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
ghCalls.push(args.join(" "));
if (scenario.failWith) {
return Effect.fail(scenario.failWith);
return Effect.fail(normalizeGhError(scenario.failWith));
}
if (args[0] === "pr" && args[1] === "list") {
@@ -345,10 +373,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
failWith: new Error("Command not found: gh"),
},
});
@@ -575,7 +600,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push",
}).pipe(
Effect.flip,
Effect.map((error) => error.message),
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
);
expect(errorMessage).toContain("detached HEAD");
}),
@@ -592,10 +617,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
failWith: new Error("Command not found: gh"),
},
});
@@ -604,7 +626,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
}).pipe(
Effect.flip,
Effect.map((error) => error.message),
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
);
expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
}),
@@ -621,10 +643,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCliError({
operation: "execute",
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
}),
failWith: new Error("authentication failed"),
},
});
@@ -633,7 +652,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
action: "commit_push_pr",
}).pipe(
Effect.flip,
Effect.map((error) => error.message),
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
);
expect(errorMessage).toContain("gh auth login");
}),
+40 -43
View File
@@ -29,7 +29,10 @@ function limitContext(value: string, maxChars: number): string {
return `${value.slice(0, maxChars)}\n\n[truncated]`;
}
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
function sanitizeCommitMessage(generated: {
subject: string;
body: string;
}): {
subject: string;
body: string;
} {
@@ -158,14 +161,12 @@ export const makeGitManager = Effect.gen(function* () {
let generated = parseCustomCommitMessage(commitMessage ?? "");
if (!generated) {
generated = yield* textGeneration
.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
generated = yield* textGeneration.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
}).pipe(Effect.map((result) => sanitizeCommitMessage(result)));
}
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
@@ -181,10 +182,7 @@ export const makeGitManager = Effect.gen(function* () {
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
return yield* gitManagerError(
"runPrStep",
"Cannot create a pull request from detached HEAD.",
);
return yield* gitManagerError("runPrStep", "Cannot create a pull request from detached HEAD.");
}
if (!details.hasUpstream) {
return yield* gitManagerError(
@@ -222,7 +220,11 @@ export const makeGitManager = Effect.gen(function* () {
.writeFileString(bodyFile, generated.body)
.pipe(
Effect.mapError((cause) =>
gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
gitManagerError(
"runPrStep",
"Failed to write pull request body temp file.",
cause,
),
),
);
yield* gitHubCli
@@ -277,40 +279,35 @@ export const makeGitManager = Effect.gen(function* () {
};
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot create a pull request from detached HEAD.");
}
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
commit,
push,
pr,
};
},
);
return {
action: input.action,
commit,
push,
pr,
};
});
return {
status,
@@ -1,6 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { Effect, Layer } 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(Schema.is(GitCommandError)(result.failure));
assert.ok(result.failure instanceof GitCommandError);
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, Schema, Stream } from "effect";
import { Effect, Layer, Option, 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) =>
Schema.is(GitCommandError)(cause)
cause instanceof GitCommandError
? cause
: new GitCommandError({
operation: input.operation,
@@ -39,9 +39,9 @@ function toGitCommandError(
});
}
const collectOutput = Effect.fn(function* <E>(
const collectOutput = Effect.fn(function* (
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
stream: Stream.Stream<Uint8Array, unknown>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
+1 -3
View File
@@ -143,6 +143,4 @@ export interface GitCoreShape {
/**
* GitCore - Service tag for low-level Git repository operations.
*/
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(
"t3/git/Services/GitCore",
) {}
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()("git/GitCore") {}
+1 -3
View File
@@ -63,6 +63,4 @@ export interface GitHubCliShape {
/**
* GitHubCli - Service tag for GitHub CLI process execution.
*/
export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()(
"t3/git/Services/GitHubCli",
) {}
export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()("git/GitHubCli") {}
+2 -4
View File
@@ -23,9 +23,7 @@ export interface GitManagerShape {
/**
* Read current repository Git status plus open PR metadata when available.
*/
readonly status: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
@@ -39,5 +37,5 @@ export interface GitManagerShape {
* GitManager - Service tag for stacked Git workflow orchestration.
*/
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
"t3/git/Services/GitManager",
"git/GitManager",
) {}
+1 -1
View File
@@ -41,5 +41,5 @@ export interface GitServiceShape {
* GitService - Service for Git command execution.
*/
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
"t3/git/Services/GitService",
"git/GitService",
) {}
@@ -67,5 +67,5 @@ export interface TextGenerationShape {
* TextGeneration - Service tag for commit and PR text generation.
*/
export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
"t3/git/Services/TextGeneration",
"git/TextGeneration",
) {}
+5 -16
View File
@@ -1,5 +1,5 @@
import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
@@ -178,10 +178,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
return yield* keybindings.loadConfigState;
});
assert.deepEqual(
configState.keybindings,
compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS),
);
assert.deepEqual(configState.keybindings, compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS));
assert.deepEqual(configState.issues, [
{
kind: "keybindings.malformed-config",
@@ -211,18 +208,10 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
});
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command"));
assert.isFalse(configState.keybindings.some((entry) => entry.command === "invalid.command"));
assert.deepEqual(configState.issues, [
{
kind: "keybindings.invalid-entry",
index: 1,
message: configState.issues[0]?.message ?? "",
},
{
kind: "keybindings.invalid-entry",
index: 2,
message: configState.issues[1]?.message ?? "",
},
{ kind: "keybindings.invalid-entry", index: 1, message: configState.issues[0]?.message ?? "" },
{ kind: "keybindings.invalid-entry", index: 2, message: configState.issues[1]?.message ?? "" },
]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
+1 -2
View File
@@ -65,7 +65,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
@@ -499,7 +498,7 @@ export interface KeybindingsShape {
* Keybindings - Service tag for keybinding configuration operations.
*/
export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
"t3/keybindings",
"server/Keybindings",
) {}
const makeKeybindings = Effect.gen(function* () {
+1 -1
View File
@@ -1,5 +1,5 @@
import * as Http from "node:http";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { assert, it, vi } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
+1 -3
View File
@@ -63,9 +63,7 @@ export interface CliConfigShape {
/**
* CliConfig - Service tag for startup CLI/runtime helpers.
*/
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
"t3/main/CliConfig",
) {
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()("server/CliConfig") {
static readonly layer = Layer.effect(
CliConfig,
Effect.gen(function* () {
-22
View File
@@ -18,28 +18,6 @@ describe("resolveEditorLaunch", () => {
}),
);
it.effect("uses --goto when cursor target includes line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineOnly, {
command: "cursor",
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
});
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
}),
);
it.effect("maps file-manager editor to OS open commands", () =>
Effect.gen(function* () {
const launch1 = yield* resolveEditorLaunch(
+3 -14
View File
@@ -30,12 +30,6 @@ interface EditorLaunch {
readonly args: ReadonlyArray<string>;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
return editorId === "cursor" && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
/**
* OpenShape - Service API for browser and editor launch actions.
*/
@@ -56,7 +50,7 @@ export interface OpenShape {
/**
* Open - Service tag for browser/editor launch operations.
*/
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
export class Open extends ServiceMap.Service<Open, OpenShape>()("server/Open") {}
// ==============================
// Implementations
@@ -72,9 +66,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
}
if (editorDef.command) {
return shouldUseGotoFlag(editorDef.id, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
return { command: editorDef.command, args: [input.cwd] };
}
if (editorDef.id !== "file-manager") {
@@ -117,10 +109,7 @@ export const launchDetached = (launch: EditorLaunch) =>
});
const make = Effect.gen(function* () {
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
const open = yield* Effect.promise(() => import("open"));
return {
openBrowser: (target) =>
@@ -14,7 +14,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -561,9 +561,7 @@ describe("OrchestrationEngine", () => {
).rejects.toThrow("projection failed");
const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
const updatedThread = readModelAfterFailure.threads.find(
(thread) => thread.id === "thread-sync",
);
const updatedThread = readModelAfterFailure.threads.find((thread) => thread.id === "thread-sync");
expect(readModelAfterFailure.snapshotSequence).toBe(3);
expect(updatedThread?.title).toBe("sync-after-failed-projection");
@@ -5,7 +5,7 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { OrchestrationCommand } from "@t3tools/contracts";
import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";
import { Deferred, Effect, Layer, Option, PubSub, Queue, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { toPersistenceSqlError } from "../../persistence/Errors.ts";
@@ -181,7 +181,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
if (error instanceof OrchestrationCommandInvariantError) {
const aggregateRef = commandToAggregateRef(envelope.command);
yield* commandReceiptRepository
.upsert({
@@ -10,7 +10,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import fs from "node:fs";
@@ -412,127 +412,125 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect(
"resolves turn-count conflicts when checkpoint completion rewrites provisional turns",
() =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
it.effect("resolves turn-count conflicts when checkpoint completion rewrites provisional turns", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.makeUnsafe("evt-conflict-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-conflict"),
occurredAt: "2026-02-26T13:00:00.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-1"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-conflict"),
title: "Project Conflict",
workspaceRoot: "/tmp/project-conflict",
defaultModel: null,
scripts: [],
createdAt: "2026-02-26T13:00:00.000Z",
updatedAt: "2026-02-26T13:00:00.000Z",
},
});
yield* appendAndProject({
type: "project.created",
eventId: EventId.makeUnsafe("evt-conflict-1"),
aggregateKind: "project",
aggregateId: ProjectId.makeUnsafe("project-conflict"),
occurredAt: "2026-02-26T13:00:00.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-1"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-1"),
metadata: {},
payload: {
projectId: ProjectId.makeUnsafe("project-conflict"),
title: "Project Conflict",
workspaceRoot: "/tmp/project-conflict",
defaultModel: null,
scripts: [],
createdAt: "2026-02-26T13:00:00.000Z",
updatedAt: "2026-02-26T13:00:00.000Z",
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-conflict-2"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:01.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-2"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-2"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
projectId: ProjectId.makeUnsafe("project-conflict"),
title: "Thread Conflict",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: "2026-02-26T13:00:01.000Z",
updatedAt: "2026-02-26T13:00:01.000Z",
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.makeUnsafe("evt-conflict-2"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:01.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-2"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-2"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
projectId: ProjectId.makeUnsafe("project-conflict"),
title: "Thread Conflict",
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: "2026-02-26T13:00:01.000Z",
updatedAt: "2026-02-26T13:00:01.000Z",
},
});
yield* appendAndProject({
type: "thread.turn-interrupt-requested",
eventId: EventId.makeUnsafe("evt-conflict-3"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:02.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-3"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-3"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
turnId: TurnId.makeUnsafe("turn-interrupted"),
createdAt: "2026-02-26T13:00:02.000Z",
},
});
yield* appendAndProject({
type: "thread.turn-interrupt-requested",
eventId: EventId.makeUnsafe("evt-conflict-3"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:02.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-3"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-3"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
turnId: TurnId.makeUnsafe("turn-interrupted"),
createdAt: "2026-02-26T13:00:02.000Z",
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-conflict-4"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:03.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-4"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-4"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
messageId: MessageId.makeUnsafe("assistant-conflict"),
role: "assistant",
text: "done",
turnId: TurnId.makeUnsafe("turn-completed"),
streaming: false,
createdAt: "2026-02-26T13:00:03.000Z",
updatedAt: "2026-02-26T13:00:03.000Z",
},
});
yield* appendAndProject({
type: "thread.message-sent",
eventId: EventId.makeUnsafe("evt-conflict-4"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:03.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-4"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-4"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
messageId: MessageId.makeUnsafe("assistant-conflict"),
role: "assistant",
text: "done",
turnId: TurnId.makeUnsafe("turn-completed"),
streaming: false,
createdAt: "2026-02-26T13:00:03.000Z",
updatedAt: "2026-02-26T13:00:03.000Z",
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.makeUnsafe("evt-conflict-5"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:04.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-5"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-5"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
turnId: TurnId.makeUnsafe("turn-completed"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-conflict/turn/1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-conflict"),
completedAt: "2026-02-26T13:00:04.000Z",
},
});
yield* appendAndProject({
type: "thread.turn-diff-completed",
eventId: EventId.makeUnsafe("evt-conflict-5"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
occurredAt: "2026-02-26T13:00:04.000Z",
commandId: CommandId.makeUnsafe("cmd-conflict-5"),
causationEventId: null,
correlationId: CorrelationId.makeUnsafe("cmd-conflict-5"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-conflict"),
turnId: TurnId.makeUnsafe("turn-completed"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-conflict/turn/1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-conflict"),
completedAt: "2026-02-26T13:00:04.000Z",
},
});
const turnRows = yield* sql<{
readonly turnId: string;
readonly checkpointTurnCount: number | null;
readonly status: string;
}>`
const turnRows = yield* sql<{
readonly turnId: string;
readonly checkpointTurnCount: number | null;
readonly status: string;
}>`
SELECT
turn_id AS "turnId",
checkpoint_turn_count AS "checkpointTurnCount",
@@ -547,11 +545,11 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
checkpoint_turn_count ASC,
requested_at ASC
`;
assert.deepEqual(turnRows, [
{ turnId: "turn-completed", checkpointTurnCount: 1, status: "completed" },
{ turnId: "turn-interrupted", checkpointTurnCount: null, status: "interrupted" },
]);
}),
assert.deepEqual(turnRows, [
{ turnId: "turn-completed", checkpointTurnCount: 1, status: "completed" },
{ turnId: "turn-interrupted", checkpointTurnCount: null, status: "interrupted" },
]);
}),
);
it.effect("does not fallback-retain messages whose turnId is removed by revert", () =>
@@ -755,6 +753,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
]);
}),
);
});
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
@@ -14,10 +14,7 @@ import {
ProjectionThreadMessageRepository,
} from "../../persistence/Services/ProjectionThreadMessages.ts";
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
import {
type ProjectionTurn,
ProjectionTurnRepository,
} from "../../persistence/Services/ProjectionTurns.ts";
import { type ProjectionTurn, ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts";
import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
@@ -67,10 +64,7 @@ function retainProjectionMessagesAfterRevert(
const retainedMessageIds = new Set<string>();
const retainedTurnIds = new Set<string>();
const keptTurns = turns.filter(
(turn) =>
turn.turnId !== null &&
turn.checkpointTurnCount !== null &&
turn.checkpointTurnCount <= turnCount,
(turn) => turn.turnId !== null && turn.checkpointTurnCount !== null && turn.checkpointTurnCount <= turnCount,
);
for (const turn of keptTurns) {
if (turn.turnId !== null) {
@@ -517,22 +511,16 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
startedAt:
existingTurn.value.startedAt ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.requestedAt
: event.occurredAt),
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.requestedAt : event.occurredAt),
requestedAt:
existingTurn.value.requestedAt ??
(Option.isSome(pendingTurnStart)
? pendingTurnStart.value.requestedAt
: event.occurredAt),
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.requestedAt : event.occurredAt),
});
} else {
yield* projectionTurnRepository.upsertByTurnId({
turnId,
threadId: event.payload.threadId,
pendingMessageId: Option.isSome(pendingTurnStart)
? pendingTurnStart.value.messageId
: null,
pendingMessageId: Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null,
assistantMessageId: null,
state: "running",
requestedAt: Option.isSome(pendingTurnStart)
@@ -149,11 +149,14 @@ const make = Effect.gen(function* () {
projects: readModel.projects,
});
const startedSession = yield* providerService.startSession(threadId, {
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(thread.model ? { model: thread.model } : {}),
});
const startedSession = yield* providerService.startSession(
threadId,
{
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(thread.model ? { model: thread.model } : {}),
},
);
yield* setThreadSession({
threadId,
@@ -2,7 +2,6 @@ import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import {
CommandId,
EventId,
MessageId,
ProjectId,
ProviderItemId,
ProviderSessionId,
@@ -34,7 +33,6 @@ const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.make
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
function createProviderServiceHarness() {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
@@ -260,201 +258,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("buffers assistant deltas by default until completion", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffered"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffered"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
);
harness.emit({
type: "message.delta",
eventId: asEventId("evt-message-delta-buffered"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
delta: "buffer me",
});
await Effect.runPromise(Effect.sleep("30 millis"));
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(midThread?.messages.some((message) => message.id === "assistant:item-buffered")).toBe(
false,
);
harness.emit({
type: "message.completed",
eventId: asEventId("evt-message-completed-buffered"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffered"),
itemId: asItemId("item-buffered"),
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some((message) => message.id === "assistant:item-buffered" && !message.streaming),
);
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
expect(message?.text).toBe("buffer me");
expect(message?.streaming).toBe(false);
});
it("streams assistant deltas when thread.turn.start requests streaming mode", 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-streaming-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("message-streaming-mode"),
role: "user",
text: "stream please",
attachments: [],
},
assistantDeliveryMode: "streaming",
createdAt: now,
}),
);
await Effect.runPromise(Effect.sleep("30 millis"));
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-streaming-mode"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-streaming-mode"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-streaming-mode",
);
harness.emit({
type: "message.delta",
eventId: asEventId("evt-message-delta-streaming-mode"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-streaming-mode"),
itemId: asItemId("item-streaming-mode"),
delta: "hello live",
});
const liveThread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) =>
message.id === "assistant:item-streaming-mode" &&
message.streaming &&
message.text === "hello live",
),
);
const liveMessage = liveThread.messages.find(
(entry) => entry.id === "assistant:item-streaming-mode",
);
expect(liveMessage?.streaming).toBe(true);
harness.emit({
type: "message.completed",
eventId: asEventId("evt-message-completed-streaming-mode"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-streaming-mode"),
itemId: asItemId("item-streaming-mode"),
});
const finalThread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
),
);
const finalMessage = finalThread.messages.find(
(entry) => entry.id === "assistant:item-streaming-mode",
);
expect(finalMessage?.text).toBe("hello live");
expect(finalMessage?.streaming).toBe(false);
});
it("spills oversized buffered deltas and still finalizes full assistant text", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const oversizedText = "x".repeat(40_000);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-buffer-spill"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffer-spill"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-buffer-spill",
);
harness.emit({
type: "message.delta",
eventId: asEventId("evt-message-delta-buffer-spill"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffer-spill"),
itemId: asItemId("item-buffer-spill"),
delta: oversizedText,
});
harness.emit({
type: "message.completed",
eventId: asEventId("evt-message-completed-buffer-spill"),
provider: "codex",
sessionId: asSessionId("sess-1"),
createdAt: now,
turnId: asProviderTurnId("turn-buffer-spill"),
itemId: asItemId("item-buffer-spill"),
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.messages.some(
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
),
);
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
expect(message?.text.length).toBe(oversizedText.length);
expect(message?.text).toBe(oversizedText);
expect(message?.streaming).toBe(false);
});
it("does not duplicate assistant completion when message.completed is followed by turn.completed", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -471,8 +274,7 @@ describe("ProviderRuntimeIngestion", () => {
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" &&
thread.session?.activeTurnId === "turn-complete-dedup",
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-complete-dedup",
);
harness.emit({
@@ -515,17 +317,14 @@ describe("ProviderRuntimeIngestion", () => {
);
const events = await Effect.runPromise(
Stream.runCollect(harness.engine.readEvents(0)).pipe(
Effect.map((chunk) => Array.from(chunk)),
),
Stream.runCollect(harness.engine.readEvents(0)).pipe(Effect.map((chunk) => Array.from(chunk))),
);
const completionEvents = events.filter((event) => {
if (event.type !== "thread.message-sent") {
return false;
}
return (
event.payload.messageId === "assistant:item-complete-dedup" &&
event.payload.streaming === false
event.payload.messageId === "assistant:item-complete-dedup" && event.payload.streaming === false
);
});
expect(completionEvents).toHaveLength(1);
@@ -1,16 +1,13 @@
import {
type AssistantDeliveryMode,
CommandId,
MessageId,
type OrchestrationEvent,
ProviderThreadId,
type ThreadId,
TurnId,
type OrchestrationThreadActivity,
type ProviderRuntimeEvent,
type ProviderSessionId,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -22,28 +19,8 @@ import {
const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
type TurnStartRequestedDomainEvent = Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" }
>;
type RuntimeIngestionInput =
| {
source: "runtime";
event: ProviderRuntimeEvent;
}
| {
source: "domain";
event: TurnStartRequestedDomainEvent;
};
function toTurnId(value: string | undefined): TurnId | undefined {
return value === undefined ? undefined : TurnId.makeUnsafe(value);
@@ -111,7 +88,6 @@ function runtimeEventToActivities(
},
];
}
case "tool.completed": {
return [
{
@@ -128,7 +104,6 @@ function runtimeEventToActivities(
},
];
}
case "tool.started": {
return [
{
@@ -155,22 +130,12 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
DEFAULT_ASSISTANT_DELIVERY_MODE,
);
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
lookup: () => Effect.succeed(new Set<MessageId>()),
});
const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({
capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
lookup: () => Effect.succeed(""),
});
const rememberAssistantMessageId = (
sessionId: ProviderSessionId,
turnId: TurnId,
@@ -224,76 +189,6 @@ const make = Effect.gen(function* () {
const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId));
const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
Effect.gen(function* () {
const nextText = Option.match(existingText, {
onNone: () => delta,
onSome: (text) => `${text}${delta}`,
});
if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {
yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);
return "";
}
// Safety valve: flush full buffered text as an assistant delta to cap memory.
yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
return nextText;
}),
),
);
const takeBufferedAssistantText = (messageId: MessageId) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.as(Option.getOrElse(existingText, () => "")),
),
),
);
const clearBufferedAssistantText = (messageId: MessageId) =>
Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
const clearAssistantMessageState = (messageId: MessageId) =>
clearBufferedAssistantText(messageId);
const finalizeAssistantMessage = (input: {
event: ProviderRuntimeEvent;
threadId: ThreadId;
messageId: MessageId;
turnId?: TurnId;
createdAt: string;
commandTag: string;
finalDeltaCommandTag: string;
}) =>
Effect.gen(function* () {
const text = yield* takeBufferedAssistantText(input.messageId);
if (text.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: text,
...(input.turnId ? { turnId: input.turnId } : {}),
createdAt: input.createdAt,
});
}
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: providerCommandId(input.event, input.commandTag),
threadId: input.threadId,
messageId: input.messageId,
...(input.turnId ? { turnId: input.turnId } : {}),
createdAt: input.createdAt,
});
yield* clearAssistantMessageState(input.messageId);
});
const clearTurnStateForSession = (sessionId: ProviderSessionId) =>
Effect.gen(function* () {
const prefix = `${sessionId}:`;
@@ -301,25 +196,12 @@ const make = Effect.gen(function* () {
yield* Effect.forEach(
turnKeys,
(key) =>
Effect.gen(function* () {
if (!key.startsWith(prefix)) {
return;
}
const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);
if (Option.isSome(messageIds)) {
yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {
concurrency: 1,
}).pipe(Effect.asVoid);
}
yield* Cache.invalidate(turnMessageIdsByTurnKey, key);
}),
key.startsWith(prefix) ? Cache.invalidate(turnMessageIdsByTurnKey, key) : Effect.void,
{ concurrency: 1 },
).pipe(Effect.asVoid);
});
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
const processEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find(
@@ -388,31 +270,15 @@ const make = Effect.gen(function* () {
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
}
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
if (assistantDeliveryMode === "buffered") {
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, event.delta);
if (spillChunk.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
threadId: thread.id,
messageId: assistantMessageId,
delta: spillChunk,
...(turnId ? { turnId } : {}),
createdAt: now,
});
}
} else {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta"),
threadId: thread.id,
messageId: assistantMessageId,
delta: event.delta,
...(turnId ? { turnId } : {}),
createdAt: now,
});
}
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: providerCommandId(event, "assistant-delta"),
threadId: thread.id,
messageId: assistantMessageId,
delta: event.delta,
...(turnId ? { turnId } : {}),
createdAt: now,
});
}
if (event.type === "message.completed") {
@@ -422,14 +288,13 @@ const make = Effect.gen(function* () {
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
}
yield* finalizeAssistantMessage({
event,
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: providerCommandId(event, "assistant-complete"),
threadId: thread.id,
messageId: assistantMessageId,
...(turnId ? { turnId } : {}),
createdAt: now,
commandTag: "assistant-complete",
finalDeltaCommandTag: "assistant-delta-finalize",
});
if (turnId) {
@@ -441,19 +306,15 @@ const make = Effect.gen(function* () {
const turnId = toTurnId(event.turnId);
if (turnId) {
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(event.sessionId, turnId);
yield* Effect.forEach(
assistantMessageIds,
(assistantMessageId) =>
finalizeAssistantMessage({
event,
threadId: thread.id,
messageId: assistantMessageId,
turnId,
createdAt: now,
commandTag: "assistant-complete-finalize",
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
}),
{ concurrency: 1 },
yield* Effect.forEach(assistantMessageIds, (assistantMessageId) =>
orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: providerCommandId(event, "assistant-complete-finalize"),
threadId: thread.id,
messageId: assistantMessageId,
turnId,
createdAt: now,
}),
).pipe(Effect.asVoid);
yield* clearAssistantMessageIdsForTurn(event.sessionId, turnId);
}
@@ -499,50 +360,33 @@ const make = Effect.gen(function* () {
).pipe(Effect.asVoid);
});
const processDomainEvent = (event: TurnStartRequestedDomainEvent) =>
Ref.set(
assistantDeliveryModeRef,
event.payload.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
);
const processInput = (input: RuntimeIngestionInput) =>
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
const processInputSafely = (input: RuntimeIngestionInput) =>
processInput(input).pipe(
const processEventSafely = (event: ProviderRuntimeEvent) =>
processEvent(event).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logWarning("provider runtime ingestion failed to process event", {
source: input.source,
eventId: input.event.eventId,
eventType: input.event.type,
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
});
}),
);
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
const inputQueue = yield* Queue.unbounded<RuntimeIngestionInput>();
yield* Effect.addFinalizer(() => Queue.shutdown(inputQueue).pipe(Effect.asVoid));
const providerEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Effect.addFinalizer(() => Queue.shutdown(providerEventQueue).pipe(Effect.asVoid));
yield* Effect.forkScoped(
Effect.forever(Queue.take(inputQueue).pipe(Effect.flatMap(processInputSafely))),
Effect.forever(Queue.take(providerEventQueue).pipe(Effect.flatMap(processEventSafely))),
);
yield* Effect.forkScoped(
Stream.runForEach(providerService.streamEvents, (event) =>
Queue.offer(inputQueue, { source: "runtime", event }).pipe(Effect.asVoid),
Queue.offer(providerEventQueue, event).pipe(Effect.asVoid),
),
);
yield* Effect.forkScoped(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (event.type !== "thread.turn-start-requested") {
return Effect.void;
}
return Queue.offer(inputQueue, { source: "domain", event }).pipe(Effect.asVoid);
}),
);
});
return {
@@ -31,4 +31,4 @@ export interface CheckpointReactorShape {
export class CheckpointReactor extends ServiceMap.Service<
CheckpointReactor,
CheckpointReactorShape
>()("t3/orchestration/Services/CheckpointReactor") {}
>()("orchestration/CheckpointReactor") {}
@@ -77,4 +77,4 @@ export interface OrchestrationEngineShape {
export class OrchestrationEngineService extends ServiceMap.Service<
OrchestrationEngineService,
OrchestrationEngineShape
>()("t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService") {}
>()("orchestration/Engine") {}
@@ -28,4 +28,4 @@ export interface OrchestrationReactorShape {
export class OrchestrationReactor extends ServiceMap.Service<
OrchestrationReactor,
OrchestrationReactorShape
>()("t3/orchestration/Services/OrchestrationReactor") {}
>()("orchestration/OrchestrationReactor") {}
@@ -39,4 +39,4 @@ export interface OrchestrationProjectionPipelineShape {
export class OrchestrationProjectionPipeline extends ServiceMap.Service<
OrchestrationProjectionPipeline,
OrchestrationProjectionPipelineShape
>()("t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline") {}
>()("orchestration/ProjectionPipeline") {}
@@ -31,4 +31,4 @@ export interface ProjectionSnapshotQueryShape {
export class ProjectionSnapshotQuery extends ServiceMap.Service<
ProjectionSnapshotQuery,
ProjectionSnapshotQueryShape
>()("t3/orchestration/Services/ProjectionSnapshotQuery") {}
>()("orchestration/ProjectionSnapshotQuery") {}
@@ -31,4 +31,4 @@ export interface ProviderCommandReactorShape {
export class ProviderCommandReactor extends ServiceMap.Service<
ProviderCommandReactor,
ProviderCommandReactorShape
>()("t3/orchestration/Services/ProviderCommandReactor") {}
>()("orchestration/ProviderCommandReactor") {}
@@ -31,4 +31,4 @@ export interface ProviderRuntimeIngestionShape {
export class ProviderRuntimeIngestionService extends ServiceMap.Service<
ProviderRuntimeIngestionService,
ProviderRuntimeIngestionShape
>()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {}
>()("orchestration/ProviderRuntimeIngestion") {}
@@ -162,12 +162,7 @@ describe("decider project scripts", () => {
const events = Array.isArray(result) ? result : [result];
expect(events).toHaveLength(2);
expect(events[0]?.type).toBe("thread.message-sent");
const turnStartEvent = events[1];
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
if (turnStartEvent?.type !== "thread.turn-start-requested") {
return;
}
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
expect(events[1]?.type).toBe("thread.turn-start-requested");
expect(events[1]?.causationEventId).toBe(events[0]?.eventId ?? null);
});
});
-2
View File
@@ -14,7 +14,6 @@ import {
} from "./commandInvariants.ts";
const nowIso = () => new Date().toISOString();
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
@@ -253,7 +252,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
messageId: command.message.messageId,
...(command.model !== undefined ? { model: command.model } : {}),
...(command.effort !== undefined ? { effort: command.effort } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
createdAt: command.createdAt,
},
};
@@ -702,9 +702,7 @@ describe("orchestration projector", () => {
},
}),
);
const afterMessages = await messageEvents.reduce<
Promise<ReturnType<typeof createEmptyReadModel>>
>(
const afterMessages = await messageEvents.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
(statePromise, event) =>
statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
Promise.resolve(afterCreate),
@@ -732,9 +730,7 @@ describe("orchestration projector", () => {
},
}),
);
const finalState = await checkpointEvents.reduce<
Promise<ReturnType<typeof createEmptyReadModel>>
>(
const finalState = await checkpointEvents.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
(statePromise, event) =>
statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
Promise.resolve(afterMessages),
+3 -4
View File
@@ -40,10 +40,9 @@ function decodeForEvent<A>(
eventType: OrchestrationEvent["type"],
field: string,
): Effect.Effect<A, OrchestrationProjectorDecodeError> {
return Effect.try({
try: () => Schema.decodeUnknownSync(schema as any)(value),
catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError),
});
return Schema.decodeUnknownEffect(schema)(value).pipe(
Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
) as Effect.Effect<A, OrchestrationProjectorDecodeError>;
}
function retainThreadMessagesAfterRevert(
@@ -1,6 +1,6 @@
import { CommandId, EventId, ProjectId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Schema, Stream } from "effect";
import { Effect, Layer, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { PersistenceDecodeError } from "../Errors.ts";
@@ -107,7 +107,7 @@ layer("OrchestrationEventStore", (it) => {
);
assert.equal(replayResult._tag, "Failure");
if (replayResult._tag === "Failure") {
assert.ok(Schema.is(PersistenceDecodeError)(replayResult.failure));
assert.ok(replayResult.failure instanceof PersistenceDecodeError);
assert.ok(
replayResult.failure.operation.includes(
"OrchestrationEventStore.readFromSequence:decodeRows",
@@ -260,21 +260,23 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
),
);
const getPendingTurnStartByThreadId: ProjectionTurnRepositoryShape["getPendingTurnStartByThreadId"] =
(input) =>
getPendingProjectionTurn(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionTurnRepository.getPendingTurnStartByThreadId:query"),
),
);
const getPendingTurnStartByThreadId: ProjectionTurnRepositoryShape["getPendingTurnStartByThreadId"] = (
input,
) =>
getPendingProjectionTurn(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionTurnRepository.getPendingTurnStartByThreadId:query"),
),
);
const deletePendingTurnStartByThreadId: ProjectionTurnRepositoryShape["deletePendingTurnStartByThreadId"] =
(input) =>
clearPendingProjectionTurnsByThread(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionTurnRepository.deletePendingTurnStartByThreadId:query"),
),
);
const deletePendingTurnStartByThreadId: ProjectionTurnRepositoryShape["deletePendingTurnStartByThreadId"] = (
input,
) =>
clearPendingProjectionTurnsByThread(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionTurnRepository.deletePendingTurnStartByThreadId:query"),
),
);
const listByThreadId: ProjectionTurnRepositoryShape["listByThreadId"] = (input) =>
listProjectionTurnsByThread(input).pipe(
@@ -304,13 +306,12 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
),
);
const clearCheckpointTurnConflict: ProjectionTurnRepositoryShape["clearCheckpointTurnConflict"] =
(input) =>
clearCheckpointTurnConflictRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionTurnRepository.clearCheckpointTurnConflict:query"),
),
);
const clearCheckpointTurnConflict: ProjectionTurnRepositoryShape["clearCheckpointTurnConflict"] = (
input,
) =>
clearCheckpointTurnConflictRow(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionTurnRepository.clearCheckpointTurnConflict:query")),
);
const deleteByThreadId: ProjectionTurnRepositoryShape["deleteByThreadId"] = (input) =>
deleteProjectionTurnsByThread(input).pipe(
@@ -51,10 +51,14 @@ function toValidationError(
});
}
function decodeInput<S extends Schema.Top>(schema: S, input: unknown, operation: string) {
function decodeInput<A>(
schema: Schema.Schema<A>,
input: unknown,
operation: string,
): Effect.Effect<A, ProviderSessionRepositoryValidationError> {
return Schema.decodeUnknownEffect(schema)(input).pipe(
Effect.mapError((cause) => toValidationError(operation, cause)),
);
) as Effect.Effect<A, ProviderSessionRepositoryValidationError>;
}
function toPersistenceError(
@@ -32,7 +32,7 @@ export type TypeId = "~local/sqlite-node/SqliteClient";
/**
* SqliteClient - Effect service tag for the sqlite SQL client.
*/
export const SqliteClient = ServiceMap.Service<Client.SqlClient>("t3/persistence/NodeSqliteClient");
export const SqliteClient = ServiceMap.Service<Client.SqlClient>("@local/sqlite-node/SqliteClient");
export interface SqliteClientConfig {
readonly filename: string;
@@ -66,4 +66,4 @@ export interface OrchestrationCommandReceiptRepositoryShape {
export class OrchestrationCommandReceiptRepository extends ServiceMap.Service<
OrchestrationCommandReceiptRepository,
OrchestrationCommandReceiptRepositoryShape
>()("t3/persistence/Services/OrchestrationCommandReceipts/OrchestrationCommandReceiptRepository") {}
>()("persistence/OrchestrationCommandReceiptRepository") {}
@@ -67,4 +67,4 @@ export interface OrchestrationEventStoreShape {
export class OrchestrationEventStore extends ServiceMap.Service<
OrchestrationEventStore,
OrchestrationEventStoreShape
>()("t3/persistence/Services/OrchestrationEventStore") {}
>()("orchestration/EventStore") {}
@@ -90,4 +90,4 @@ export interface ProjectionCheckpointRepositoryShape {
export class ProjectionCheckpointRepository extends ServiceMap.Service<
ProjectionCheckpointRepository,
ProjectionCheckpointRepositoryShape
>()("t3/persistence/Services/ProjectionCheckpoints/ProjectionCheckpointRepository") {}
>()("persistence/ProjectionCheckpointRepository") {}
@@ -88,4 +88,4 @@ export interface ProjectionPendingApprovalRepositoryShape {
export class ProjectionPendingApprovalRepository extends ServiceMap.Service<
ProjectionPendingApprovalRepository,
ProjectionPendingApprovalRepositoryShape
>()("t3/persistence/Services/ProjectionPendingApprovals/ProjectionPendingApprovalRepository") {}
>()("persistence/ProjectionPendingApprovalRepository") {}
@@ -76,4 +76,4 @@ export interface ProjectionProjectRepositoryShape {
export class ProjectionProjectRepository extends ServiceMap.Service<
ProjectionProjectRepository,
ProjectionProjectRepositoryShape
>()("t3/persistence/Services/ProjectionProjects/ProjectionProjectRepository") {}
>()("persistence/ProjectionProjectRepository") {}
@@ -61,4 +61,4 @@ export interface ProjectionStateRepositoryShape {
export class ProjectionStateRepository extends ServiceMap.Service<
ProjectionStateRepository,
ProjectionStateRepositoryShape
>()("t3/persistence/Services/ProjectionState/ProjectionStateRepository") {}
>()("persistence/ProjectionStateRepository") {}
@@ -77,4 +77,4 @@ export interface ProjectionThreadActivityRepositoryShape {
export class ProjectionThreadActivityRepository extends ServiceMap.Service<
ProjectionThreadActivityRepository,
ProjectionThreadActivityRepositoryShape
>()("t3/persistence/Services/ProjectionThreadActivities/ProjectionThreadActivityRepository") {}
>()("persistence/ProjectionThreadActivityRepository") {}
@@ -76,4 +76,4 @@ export interface ProjectionThreadMessageRepositoryShape {
export class ProjectionThreadMessageRepository extends ServiceMap.Service<
ProjectionThreadMessageRepository,
ProjectionThreadMessageRepositoryShape
>()("t3/persistence/Services/ProjectionThreadMessages/ProjectionThreadMessageRepository") {}
>()("persistence/ProjectionThreadMessageRepository") {}
@@ -73,4 +73,4 @@ export interface ProjectionThreadSessionRepositoryShape {
export class ProjectionThreadSessionRepository extends ServiceMap.Service<
ProjectionThreadSessionRepository,
ProjectionThreadSessionRepositoryShape
>()("t3/persistence/Services/ProjectionThreadSessions/ProjectionThreadSessionRepository") {}
>()("persistence/ProjectionThreadSessionRepository") {}
@@ -82,4 +82,4 @@ export interface ProjectionThreadRepositoryShape {
export class ProjectionThreadRepository extends ServiceMap.Service<
ProjectionThreadRepository,
ProjectionThreadRepositoryShape
>()("t3/persistence/Services/ProjectionThreads/ProjectionThreadRepository") {}
>()("persistence/ProjectionThreadRepository") {}
@@ -158,4 +158,4 @@ export interface ProjectionTurnRepositoryShape {
export class ProjectionTurnRepository extends ServiceMap.Service<
ProjectionTurnRepository,
ProjectionTurnRepositoryShape
>()("t3/persistence/Services/ProjectionTurns/ProjectionTurnRepository") {}
>()("persistence/ProjectionTurnRepository") {}
@@ -84,4 +84,4 @@ export interface ProviderSessionRuntimeRepositoryShape {
export class ProviderSessionRuntimeRepository extends ServiceMap.Service<
ProviderSessionRuntimeRepository,
ProviderSessionRuntimeRepositoryShape
>()("t3/persistence/Services/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
>()("persistence/ProviderSessionRuntimeRepository") {}
@@ -78,4 +78,4 @@ export interface ProviderSessionRepositoryShape {
export class ProviderSessionRepository extends ServiceMap.Service<
ProviderSessionRepository,
ProviderSessionRepositoryShape
>()("t3/persistence/Services/ProviderSessions/ProviderSessionRepository") {}
>()("persistence/ProviderSessionRepository") {}
@@ -8,7 +8,7 @@ import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
const fakeCodexAdapter: CodexAdapterShape = {
provider: "codex",
@@ -37,7 +37,7 @@ import { ProviderService } from "../Services/ProviderService.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { makeProviderServiceLive } from "./ProviderService.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
import {
@@ -323,10 +323,13 @@ it.effect(
const startedSession = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
cwd: "/tmp/project",
});
return yield* provider.startSession(
asThreadId("thread-1"),
{
provider: "codex",
cwd: "/tmp/project",
},
);
}).pipe(Effect.provide(firstProviderLayer));
yield* Effect.gen(function* () {
@@ -395,10 +398,13 @@ routing.layer("ProviderServiceLive routing", (it) => {
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
cwd: "/tmp/project",
});
const session = yield* provider.startSession(
asThreadId("thread-1"),
{
provider: "codex",
cwd: "/tmp/project",
},
);
assert.equal(session.provider, "codex");
const sessions = yield* provider.listSessions();
@@ -447,10 +453,13 @@ routing.layer("ProviderServiceLive routing", (it) => {
Effect.gen(function* () {
const provider = yield* ProviderService;
const initial = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
cwd: "/tmp/project",
});
const initial = yield* provider.startSession(
asThreadId("thread-1"),
{
provider: "codex",
cwd: "/tmp/project",
},
);
yield* routing.codex.stopSession(initial.sessionId);
routing.codex.startSession.mockClear();
routing.codex.rollbackThread.mockClear();
@@ -478,12 +487,18 @@ routing.layer("ProviderServiceLive routing", (it) => {
Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
});
yield* provider.startSession(asThreadId("thread-2"), {
provider: "codex",
});
yield* provider.startSession(
asThreadId("thread-1"),
{
provider: "codex",
},
);
yield* provider.startSession(
asThreadId("thread-2"),
{
provider: "codex",
},
);
yield* provider.stopAll();
@@ -497,9 +512,12 @@ routing.layer("ProviderServiceLive routing", (it) => {
const provider = yield* ProviderService;
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
const session = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
});
const session = yield* provider.startSession(
asThreadId("thread-1"),
{
provider: "codex",
},
);
yield* provider.sendTurn({
sessionId: session.sessionId,
input: "hello",
@@ -548,9 +566,12 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
it.effect("fans out adapter turn completion events", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
});
const session = yield* provider.startSession(
asThreadId("thread-1"),
{
provider: "codex",
},
);
const eventsRef = yield* Ref.make<Array<ProviderRuntimeEvent>>([]);
const consumer = yield* Stream.runForEach(provider.streamEvents, (event) =>
@@ -585,9 +606,12 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
it.effect("keeps subscriber delivery ordered and isolates failing subscribers", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-1"), {
provider: "codex",
});
const session = yield* provider.startSession(
asThreadId("thread-1"),
{
provider: "codex",
},
);
const receivedByHealthy: string[] = [];
const expectedEventIds = new Set<string>(["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"]);
@@ -662,9 +686,12 @@ validation.layer("ProviderServiceLive validation", (it) => {
const provider = yield* ProviderService;
const failure = yield* Effect.result(
provider.startSession(asThreadId("thread-validation"), {
provider: "invalid-provider",
} as never),
provider.startSession(
asThreadId("thread-validation"),
{
provider: "invalid-provider",
} as never,
),
);
assert.equal(failure._tag, "Failure");
@@ -699,10 +726,13 @@ validation.layer("ProviderServiceLive validation", (it) => {
);
const failure = yield* Effect.result(
provider.startSession(asThreadId("thread-missing"), {
provider: "codex",
cwd: "/tmp/project",
}),
provider.startSession(
asThreadId("thread-missing"),
{
provider: "codex",
cwd: "/tmp/project",
},
),
);
assertFailure(
@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { ProviderSessionId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
import { it, assert } from "@effect/vitest";
import { assertFailure, assertSome } from "@effect/vitest/utils";
@@ -26,5 +26,5 @@ export interface CodexAdapterShape extends ProviderAdapterShape<ProviderAdapterE
* CodexAdapter - Service tag for Codex provider adapter operations.
*/
export class CodexAdapter extends ServiceMap.Service<CodexAdapter, CodexAdapterShape>()(
"t3/provider/Services/CodexAdapter",
"provider/CodexAdapter",
) {}
@@ -37,6 +37,6 @@ export interface ProviderAdapterRegistryShape {
export class ProviderAdapterRegistry extends ServiceMap.Service<
ProviderAdapterRegistry,
ProviderAdapterRegistryShape
>()("t3/provider/Services/ProviderAdapterRegistry") {}
>()("provider/ProviderAdapterRegistry") {}
// Dummy comment for workflow testing.
@@ -105,5 +105,5 @@ export interface ProviderServiceShape {
* ProviderService - Service tag for provider orchestration.
*/
export class ProviderService extends ServiceMap.Service<ProviderService, ProviderServiceShape>()(
"t3/provider/Services/ProviderService",
"provider/ProviderService",
) {}
@@ -99,4 +99,4 @@ export interface ProviderSessionDirectoryShape {
export class ProviderSessionDirectory extends ServiceMap.Service<
ProviderSessionDirectory,
ProviderSessionDirectoryShape
>()("t3/provider/Services/ProviderSessionDirectory") {}
>()("provider/ProviderSessionDirectory") {}
+2 -3
View File
@@ -1,6 +1,6 @@
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -17,7 +17,6 @@ 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";
@@ -36,7 +35,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
ProviderUnsupportedError,
unknown,
SqlClient.SqlClient | ServerConfig
> {
return Effect.gen(function* () {
@@ -9,13 +9,7 @@ import {
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
PtySpawnError,
type PtyAdapterShape,
type PtyExitEvent,
type PtyProcess,
type PtySpawnInput,
} from "../Services/PTY";
import type { PtyAdapterShape, PtyExitEvent, PtyProcess, PtySpawnInput } from "../Services/PTY";
import { TerminalManagerRuntime } from "./Manager";
import { Effect, Encoding } from "effect";
@@ -75,33 +69,14 @@ class FakePtyAdapter implements PtyAdapterShape {
readonly spawnFailures: Error[] = [];
private nextPid = 9000;
constructor(private readonly mode: "sync" | "async" = "sync") {}
spawn(input: PtySpawnInput): Effect.Effect<PtyProcess, PtySpawnError> {
spawn(input: PtySpawnInput): Effect.Effect<PtyProcess> {
this.spawnInputs.push(input);
const failure = this.spawnFailures.shift();
if (failure) {
return Effect.fail(
new PtySpawnError({
adapter: "fake",
message: "Failed to spawn PTY process",
cause: failure,
}),
);
throw failure;
}
const process = new FakePtyProcess(this.nextPid++);
this.processes.push(process);
if (this.mode === "async") {
return Effect.tryPromise({
try: async () => process,
catch: (cause) =>
new PtySpawnError({
adapter: "fake",
message: "Failed to spawn PTY process",
cause,
}),
});
}
return Effect.succeed(process);
}
}
@@ -175,12 +150,11 @@ describe("TerminalManager", () => {
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
ptyAdapter?: FakePtyAdapter;
} = {},
) {
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
tempDirs.push(logsDir);
const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter();
const ptyAdapter = new FakePtyAdapter();
const manager = new TerminalManagerRuntime({
logsDir,
ptyAdapter,
@@ -215,18 +189,6 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("supports asynchronous PTY spawn effects", async () => {
const { manager, ptyAdapter } = makeManager(5, { ptyAdapter: new FakePtyAdapter("async") });
const snapshot = await manager.open(openInput());
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs).toHaveLength(1);
expect(ptyAdapter.processes).toHaveLength(1);
manager.dispose();
});
it("forwards write and resize to active pty process", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
+20 -79
View File
@@ -117,43 +117,8 @@ function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
}
function isRetryableShellSpawnError(error: unknown): boolean {
const queue: unknown[] = [error];
const seen = new Set<unknown>();
const messages: string[] = [];
while (queue.length > 0) {
const current = queue.shift();
if (!current || seen.has(current)) {
continue;
}
seen.add(current);
if (typeof current === "string") {
messages.push(current);
continue;
}
if (current instanceof Error) {
messages.push(current.message);
const cause = (current as { cause?: unknown }).cause;
if (cause) {
queue.push(cause);
}
continue;
}
if (typeof current === "object") {
const value = current as { message?: unknown; cause?: unknown };
if (typeof value.message === "string") {
messages.push(value.message);
}
if (value.cause) {
queue.push(value.cause);
}
}
}
const message = messages.join(" ").toLowerCase();
if (!(error instanceof Error)) return false;
const message = error.message.toLowerCase();
return (
message.includes("posix_spawnp failed") ||
message.includes("enoent") ||
@@ -389,7 +354,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
};
this.sessions.set(sessionKey, session);
this.evictInactiveSessionsIfNeeded();
await this.startSession(session, { ...input, cols, rows }, "started");
this.startSession(session, { ...input, cols, rows }, "started");
return this.snapshot(session);
}
@@ -415,11 +380,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
}
if (!existing.process) {
await this.startSession(
existing,
{ ...input, cols: targetCols, rows: targetRows },
"started",
);
this.startSession(existing, { ...input, cols: targetCols, rows: targetRows }, "started");
return this.snapshot(existing);
}
@@ -516,7 +477,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.history = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
await this.startSession(session, { ...input, cols, rows }, "restarted");
this.startSession(session, { ...input, cols, rows }, "restarted");
return this.snapshot(session);
});
}
@@ -567,11 +528,11 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
this.persistQueues.clear();
}
private async startSession(
private startSession(
session: TerminalSessionState,
input: TerminalStartInput,
eventType: "started" | "restarted",
): Promise<void> {
): void {
this.stopProcess(session);
session.status = "starting";
@@ -590,46 +551,26 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
let lastSpawnError: unknown = null;
const spawnWithCandidate = (candidate: ShellCandidate) =>
Effect.runPromise(
this.ptyAdapter.spawn({
shell: candidate.shell,
...(candidate.args ? { args: candidate.args } : {}),
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: terminalEnv,
}),
);
const trySpawn = async (
candidates: ShellCandidate[],
index = 0,
): Promise<{ process: PtyProcess; shellLabel: string } | null> => {
if (index >= candidates.length) {
return null;
}
const candidate = candidates[index];
if (!candidate) {
return null;
}
for (const candidate of shellCandidates) {
try {
const process = await spawnWithCandidate(candidate);
return { process, shellLabel: formatShellCandidate(candidate) };
ptyProcess = Effect.runSync(
this.ptyAdapter.spawn({
shell: candidate.shell,
...(candidate.args ? { args: candidate.args } : {}),
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: terminalEnv,
}),
);
startedShell = formatShellCandidate(candidate);
break;
} catch (error) {
lastSpawnError = error;
if (!isRetryableShellSpawnError(error)) {
throw error;
}
return trySpawn(candidates, index + 1);
}
};
const spawnResult = await trySpawn(shellCandidates);
if (spawnResult) {
ptyProcess = spawnResult.process;
startedShell = spawnResult.shellLabel;
}
if (!ptyProcess) {
@@ -2,7 +2,7 @@ import { FileSystem, Path, Effect } from "effect";
import { assert, it } from "@effect/vitest";
import { ensureNodePtySpawnHelperExecutable } from "./NodePTY";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NodeServices } from "@effect/platform-node";
it.layer(NodeServices.layer)("ensureNodePtySpawnHelperExecutable", (it) => {
it.effect("adds executable bits when helper exists but is not executable", () =>
+4 -5
View File
@@ -37,12 +37,11 @@ export const ensureNodePtySpawnHelperExecutable = Effect.fn(function* (explicitP
didEnsureSpawnHelperExecutable = true;
}
if (!(yield* fs.exists(helperPath))) {
return;
const stat = yield* fs.stat(helperPath);
const mode = stat.mode & 0o777;
if ((mode & 0o111) === 0) {
yield* fs.chmod(helperPath, mode | 0o111);
}
// Best-effort: avoid FileSystem.stat in packaged mode where some fs metadata can be missing.
yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined));
});
class NodePtyProcess implements PtyProcess {
+1 -1
View File
@@ -113,5 +113,5 @@ export interface TerminalManagerShape {
* TerminalManager - Service tag for terminal session orchestration.
*/
export class TerminalManager extends ServiceMap.Service<TerminalManager, TerminalManagerShape>()(
"t3/terminal/Services/Manager/TerminalManager",
"terminal/TerminalManager",
) {}
+3 -12
View File
@@ -6,16 +6,7 @@
*
* @module PtyAdapter
*/
import { Effect, Schema, ServiceMap } from "effect";
/**
* PtyError - Error type for PTY adapter operations.
*/
export class PtySpawnError extends Schema.TaggedErrorClass<PtySpawnError>()("PtySpawnError", {
adapter: Schema.String,
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
import { Effect, ServiceMap } from "effect";
export interface PtyExitEvent {
exitCode: number;
@@ -47,12 +38,12 @@ export interface PtyAdapterShape {
/**
* Spawn a PTY process for a terminal session.
*/
spawn(input: PtySpawnInput): Effect.Effect<PtyProcess, PtySpawnError>;
spawn(input: PtySpawnInput): Effect.Effect<PtyProcess>;
}
/**
* PtyAdapter - Service tag for PTY process integration.
*/
export class PtyAdapter extends ServiceMap.Service<PtyAdapter, PtyAdapterShape>()(
"t3/terminal/Services/PTY/PtyAdapter",
"terminal/PtyAdapter",
) {}
+5 -12
View File
@@ -323,14 +323,14 @@ describe("WebSocket Server", () => {
async function createTestServer(
options: {
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, any>;
cwd?: string;
autoBootstrapProjectFromCwd?: boolean;
logWebSocketEvents?: boolean;
devUrl?: string;
authToken?: string;
stateDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
providerLayer?: Layer.Layer<ProviderService, unknown>;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
@@ -543,9 +543,7 @@ describe("WebSocket Server", () => {
issues: [],
});
const persistedConfig = JSON.parse(
fs.readFileSync(keybindingsPath, "utf8"),
) as KeybindingsConfig;
const persistedConfig = JSON.parse(fs.readFileSync(keybindingsPath, "utf8")) as KeybindingsConfig;
expect(persistedConfig).toEqual(DEFAULT_KEYBINDINGS);
});
@@ -713,9 +711,7 @@ describe("WebSocket Server", () => {
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(response.error).toBeUndefined();
const persistedConfig = JSON.parse(
fs.readFileSync(keybindingsPath, "utf8"),
) as KeybindingsConfig;
const persistedConfig = JSON.parse(fs.readFileSync(keybindingsPath, "utf8")) as KeybindingsConfig;
expect(response.result).toEqual({
cwd: "/my/workspace",
keybindingsConfigPath: keybindingsPath,
@@ -746,9 +742,7 @@ describe("WebSocket Server", () => {
command: "script.run-tests.run",
});
expect(upsertResponse.error).toBeUndefined();
const persistedConfig = JSON.parse(
fs.readFileSync(keybindingsPath, "utf8"),
) as KeybindingsConfig;
const persistedConfig = JSON.parse(fs.readFileSync(keybindingsPath, "utf8")) as KeybindingsConfig;
const persistedCommands = new Set(persistedConfig.map((entry) => entry.command));
for (const defaultRule of DEFAULT_KEYBINDINGS) {
expect(persistedCommands.has(defaultRule.command)).toBe(true);
@@ -959,7 +953,6 @@ describe("WebSocket Server", () => {
text: "hello",
attachments: [],
},
assistantDeliveryMode: "streaming",
createdAt,
});
expect(startTurnResponse.error).toBeUndefined();
+34 -44
View File
@@ -23,7 +23,7 @@ import {
WsPush,
WsResponse,
} from "@t3tools/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import { NodeHttpServer } from "@effect/platform-node";
import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
import { WebSocketServer, type WebSocket } from "ws";
@@ -66,20 +66,20 @@ export interface ServerShape {
*/
readonly start: Effect.Effect<
http.Server,
ServerLifecycleError,
unknown,
Scope.Scope | ServerRuntimeServices | ServerConfig
>;
/**
* Wait for process shutdown signals.
*/
readonly stopSignal: Effect.Effect<void, never>;
readonly stopSignal: Effect.Effect<unknown, never>;
}
/**
* Server - Service tag for HTTP/WebSocket lifecycle management.
*/
export class Server extends ServiceMap.Service<Server, ServerShape>()("t3/wsServer/Server") {}
export class Server extends ServiceMap.Service<Server, ServerShape>()("server/Server") {}
const isServerNotRunningError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
@@ -165,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
export const createServer = Effect.fn(function* (): Effect.fn.Return<
http.Server,
ServerLifecycleError,
unknown, // TODO: This should not be unknown
Scope.Scope | ServerRuntimeServices | ServerConfig
> {
const serverConfig = yield* ServerConfig;
@@ -320,45 +320,43 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
broadcastPush({
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
Effect.gen(function* () {
yield* broadcastPush({
type: "push",
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
});
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Stream.runForEach(keybindingsManager.changes, (event) =>
broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: event,
Effect.gen(function* () {
yield* broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: event,
});
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
if (autoBootstrapProjectFromCwd) {
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 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,
});
}
}
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
@@ -395,13 +393,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.projectsSearchEntries: {
const body = stripRequestTag(request.body);
return yield* Effect.tryPromise({
try: () => searchWorkspaceEntries(body),
catch: (cause) =>
new RouteRequestError({
message: `Failed to search workspace entries: ${String(cause)}`,
}),
});
return yield* Effect.promise(() => searchWorkspaceEntries(body));
}
case WS_METHODS.shellOpenInEditor: {
@@ -624,9 +616,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
);
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
);
yield* NodeHttpServer.make(() => httpServer, listenOptions);
yield* Effect.addFinalizer(() =>
Effect.all([
+1 -8
View File
@@ -8,14 +8,7 @@
"allowImportingTsExtensions": true,
"plugins": [
{
"name": "@effect/language-service",
"namespaceImportPackages": ["@effect/platform-node"],
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
}
"name": "@effect/language-service"
}
]
},
+1 -2
View File
@@ -21,7 +21,7 @@
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"effect": "4.0.0-beta.10",
"highlight.js": "^11.11.1",
"lucide-react": "^0.564.0",
"react": "^19.0.0",
@@ -32,7 +32,6 @@
"tailwind-merge": "^3.4.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@tailwindcss/vite": "^4.0.0",
"@tanstack/router-plugin": "^1.161.0",
"@types/react": "^19.0.0",
-3
View File
@@ -11,9 +11,6 @@ const AppSettingsSchema = Schema.Struct({
Schema.withConstructorDefault(() => Option.some("")),
),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
enableAssistantStreaming: Schema.Boolean.pipe(
Schema.withConstructorDefault(() => Option.some(false)),
),
});
export type AppSettings = typeof AppSettingsSchema.Type;
+97 -225
View File
@@ -53,7 +53,6 @@ import { truncateTitle } from "../truncateTitle";
import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type ChatImageAttachment,
type TurnDiffSummary,
} from "../types";
@@ -92,7 +91,6 @@ import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"
import { CursorIcon, Icon } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
@@ -107,7 +105,6 @@ import { Toggle } from "./ui/toggle";
import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
import { useAppSettings } from "../appSettings";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -190,8 +187,6 @@ type ComposerCommandItem =
description: string;
};
type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
function readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -333,7 +328,6 @@ interface ChatViewProps {
export default function ChatView({ threadId }: ChatViewProps) {
const { state, dispatch } = useStore();
const { settings } = useAppSettings();
const navigate = useNavigate();
const rawSearch = useSearch({
strict: false,
@@ -347,9 +341,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
const [isConnecting, _setIsConnecting] = useState(false);
const [isSending, setIsSending] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
@@ -368,7 +361,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const sendInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -404,9 +396,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
);
const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle";
const isPreparingWorktree = sendPhase === "preparing-worktree";
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const threadActivities = activeThread?.activities ?? [];
const workLogEntries = useMemo(
@@ -426,21 +416,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => derivePendingApprovals(threadActivities),
[threadActivities],
);
const timelineMessages = useMemo(() => {
const serverMessages = activeThread?.messages ?? [];
if (optimisticUserMessages.length === 0) {
return serverMessages;
}
const serverIds = new Set(serverMessages.map((message) => message.id));
const pendingMessages = optimisticUserMessages.filter((message) => !serverIds.has(message.id));
if (pendingMessages.length === 0) {
return serverMessages;
}
return [...serverMessages, ...pendingMessages];
}, [activeThread?.messages, optimisticUserMessages]);
const timelineEntries = useMemo(
() => deriveTimelineEntries(timelineMessages, workLogEntries),
[timelineMessages, workLogEntries],
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
[activeThread?.messages, workLogEntries],
);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
@@ -637,21 +615,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => shortcutLabelForCommand(keybindings, "terminal.close"),
[keybindings],
);
const diffPanelShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "diff.toggle"),
[keybindings],
);
const onToggleDiff = useCallback(() => {
void navigate({
to: "/$threadId",
params: { threadId },
replace: true,
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return diffOpen ? rest : { ...rest, diff: "1" };
},
});
}, [diffOpen, navigate, threadId]);
const envLocked = Boolean(
activeThread &&
@@ -981,7 +944,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}, [lastInvokedScriptByProjectId]);
// Auto-scroll on new messages
const messageCount = timelineMessages.length;
const messageCount = activeThread?.messages.length ?? 0;
const workLogCount = workLogEntries.length;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const scrollContainer = messagesScrollRef.current;
@@ -1040,30 +1003,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerImagesRef.current = composerImages;
}, [composerImages]);
useEffect(() => {
if (!activeThread?.id) {
setOptimisticUserMessages([]);
return;
}
if (activeThread.messages.length === 0) {
return;
}
const serverIds = new Set(activeThread.messages.map((message) => message.id));
setOptimisticUserMessages((existing) => {
const next = existing.filter((message) => !serverIds.has(message.id));
return next.length === existing.length ? existing : next;
});
}, [activeThread?.id, activeThread?.messages]);
useEffect(() => {
setComposerImages((existing) => {
revokePreviewUrls(existing);
return [];
});
setOptimisticUserMessages([]);
setPrompt("");
promptRef.current = "";
setSendPhase("idle");
setIsSending(false);
setComposerCursor(0);
setComposerHighlightedItemId(null);
dragDepthRef.current = 0;
@@ -1200,13 +1147,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
return;
}
if (command === "diff.toggle") {
event.preventDefault();
event.stopPropagation();
onToggleDiff();
return;
}
const scriptId = projectScriptIdFromCommand(command);
if (!scriptId || !activeProject) return;
const script = activeProject.scripts.find((entry) => entry.id === scriptId);
@@ -1228,7 +1168,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
runProjectScript,
splitTerminal,
keybindings,
onToggleDiff,
toggleTerminalVisibility,
]);
@@ -1352,7 +1291,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSendBusy || isConnecting) {
if (phase === "running" || isSending || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
}
@@ -1386,122 +1325,84 @@ export default function ChatView({ threadId }: ChatViewProps) {
setIsRevertingCheckpoint(false);
}
},
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
[activeThread, isConnecting, isRevertingCheckpoint, isSending, phase, setThreadError],
);
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
e.preventDefault();
const api = readNativeApi();
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return;
const threadIdForSend = activeThread.id;
const isFirstMessage = activeThread.messages.length === 0;
const baseBranchForWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
? activeThread.branch
: null;
const composerImagesSnapshot = [...composerImages];
// In worktree mode, require an explicit base branch so we don't silently
// fall back to local execution when branch selection is missing.
const shouldCreateWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
if (shouldCreateWorktree && !activeThread.branch) {
dispatch({
type: "SET_ERROR",
threadId: threadIdForSend,
error: "Select a base branch before sending in New worktree mode.",
});
return;
// On first message: lock in branch + create worktree if needed.
if (
activeThread.messages.length === 0 &&
activeThread.branch &&
envMode === "worktree" &&
!activeThread.worktreePath
) {
try {
const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`;
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
branch: activeThread.branch,
newBranch,
});
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThread.id,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
void runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path,
rememberAsLastInvoked: false,
});
}
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to create worktree",
});
return;
}
}
sendInFlightRef.current = true;
setSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
// Auto-title from first message
if (activeThread.messages.length === 0) {
const titleSeed =
trimmed ||
(composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
if (api) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThread.id,
title,
});
}
}
const composerImagesSnapshot = [...composerImages];
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: "image" as const,
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
setOptimisticUserMessages((existing) => [
...existing,
{
id: messageIdForSend,
role: "user",
text: trimmed,
...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
createdAt: messageCreatedAt,
streaming: false,
},
]);
setThreadError(threadIdForSend, null);
setThreadError(activeThread.id, null);
promptRef.current = "";
setPrompt("");
setComposerImages([]);
setComposerCursor(0);
setComposerHighlightedItemId(null);
let attemptedTurnStart = false;
setIsSending(true);
try {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
setSendPhase("preparing-worktree");
const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`;
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
branch: baseBranchForWorktree,
newBranch,
});
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
dispatch({
type: "SET_THREAD_BRANCH",
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
await runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path,
rememberAsLastInvoked: false,
});
}
}
// Auto-title from first message
if (isFirstMessage) {
const titleSeed =
trimmed ||
(composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: threadIdForSend,
title,
});
}
setSendPhase("sending-turn");
const turnAttachments = await Promise.all(
composerImagesSnapshot.map(
async (
@@ -1521,43 +1422,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
}),
),
);
attemptedTurnStart = true;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: threadIdForSend,
threadId: activeThread.id,
message: {
messageId: messageIdForSend,
messageId: newMessageId(),
role: "user",
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
attachments: turnAttachments,
},
model: selectedModel || undefined,
effort: selectedEffort || undefined,
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
createdAt: messageCreatedAt,
createdAt: new Date().toISOString(),
});
} catch (err) {
if (
!attemptedTurnStart &&
promptRef.current.length === 0 &&
composerImagesRef.current.length === 0
) {
setOptimisticUserMessages((existing) =>
existing.filter((message) => message.id !== messageIdForSend),
);
promptRef.current = trimmed;
setPrompt(trimmed);
setComposerImages(composerImagesSnapshot);
setComposerCursor(trimmed.length);
}
setThreadError(
threadIdForSend,
activeThread.id,
err instanceof Error ? err.message : "Failed to send message.",
);
} finally {
sendInFlightRef.current = false;
setSendPhase("idle");
setIsSending(false);
}
};
@@ -1727,6 +1612,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => {
setExpandedImage(image);
}, []);
const onToggleDiff = useCallback(() => {
void navigate({
to: "/$threadId",
params: { threadId },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return diffOpen ? rest : { ...rest, diff: "1" };
},
});
}, [diffOpen, navigate, threadId]);
const onOpenTurnDiff = useCallback(
(turnId: TurnId, filePath?: string) => {
void navigate({
@@ -1797,7 +1692,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd}
diffOpen={diffOpen}
onRunProjectScript={(script) => {
@@ -1824,7 +1718,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
onScroll={onMessagesScroll}
>
<MessagesTimeline
hasMessages={timelineMessages.length > 0}
hasMessages={activeThread.messages.length > 0}
isWorking={isWorking}
scrollContainerRef={messagesScrollRef}
timelineEntries={timelineEntries}
@@ -1942,7 +1836,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use /model"
}
disabled={isConnecting}
disabled={isSending || isConnecting}
/>
</div>
@@ -1988,9 +1882,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* Right side: send / stop button */}
<div className="flex shrink-0 items-center gap-2">
{isPreparingWorktree ? (
<span className="text-muted-foreground/70 text-xs">Preparing worktree...</span>
) : null}
{phase === "running" ? (
<button
type="button"
@@ -2013,19 +1904,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={
isSendBusy || isConnecting || (!prompt.trim() && composerImages.length === 0)
isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
}
aria-label={
isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
}
>
{isConnecting || isSendBusy ? (
{isConnecting || isSending ? (
<svg
width="14"
height="14"
@@ -2158,7 +2043,6 @@ interface ChatHeaderProps {
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
diffToggleShortcutLabel: string | null;
gitCwd: string | null;
diffOpen: boolean;
onRunProjectScript: (script: ProjectScript) => void;
@@ -2174,7 +2058,6 @@ const ChatHeader = memo(function ChatHeader({
activeProjectScripts,
preferredScriptId,
keybindings,
diffToggleShortcutLabel,
gitCwd,
diffOpen,
onRunProjectScript,
@@ -2213,27 +2096,16 @@ const ChatHeader = memo(function ChatHeader({
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
)}
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0"
pressed={diffOpen}
onPressedChange={onToggleDiff}
aria-label="Toggle diff panel"
variant="outline"
size="xs"
>
<DiffIcon className="size-3" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{diffToggleShortcutLabel
? `Toggle diff panel (${diffToggleShortcutLabel})`
: "Toggle diff panel"}
</TooltipPopup>
</Tooltip>
<Toggle
className="shrink-0"
pressed={diffOpen}
onPressedChange={onToggleDiff}
aria-label="Toggle diff panel"
variant="outline"
size="xs"
>
<DiffIcon className="size-3" />
</Toggle>
</div>
</div>
);
+3 -12
View File
@@ -29,19 +29,13 @@ type RenderablePatch =
reason: string;
};
function getRenderablePatch(
patch: string | undefined,
cacheScope = "diff-panel",
): RenderablePatch | null {
function getRenderablePatch(patch: string | undefined): RenderablePatch | null {
if (!patch) return null;
const normalizedPatch = patch.trim();
if (normalizedPatch.length === 0) return null;
try {
const parsedPatches = parsePatchFiles(
normalizedPatch,
buildPatchCacheKey(normalizedPatch, cacheScope),
);
const parsedPatches = parsePatchFiles(normalizedPatch, buildPatchCacheKey(normalizedPatch));
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
if (files.length > 0) {
return { kind: "files", files };
@@ -196,10 +190,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
const hasResolvedPatch = typeof selectedPatch === "string";
const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
const renderablePatch = useMemo(
() => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
[resolvedTheme, selectedPatch],
);
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
const renderableFiles = useMemo(() => {
if (!renderablePatch || renderablePatch.kind !== "files") {
return [];
@@ -1,5 +1,4 @@
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
import { useMemo, type ReactNode } from "react";
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
@@ -12,7 +11,8 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
return (
<WorkerPoolContextProvider
poolOptions={{
workerFactory: () => new DiffsWorker(),
workerFactory: () =>
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
poolSize: workerPoolSize,
totalASTLRUCacheSize: 240,
}}
@@ -1,5 +1,5 @@
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
@@ -33,7 +33,6 @@ import { toastManager } from "~/components/ui/toast";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
@@ -169,10 +168,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
);
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const isRunStackedActionRunning =
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
@@ -16,15 +16,8 @@ import {
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
import {
keybindingValueForCommand,
decodeProjectScriptKeybindingRule,
} from "~/lib/projectScriptKeybindings";
import {
commandForProjectScript,
nextProjectScriptId,
primaryProjectScript,
} from "~/projectScripts";
import { keybindingValueForCommand, decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
import { commandForProjectScript, nextProjectScriptId, primaryProjectScript } from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
import { isMacPlatform } from "~/lib/utils";
import { Button } from "./ui/button";
@@ -195,11 +188,7 @@ export default function ProjectScriptsControl({
setValidationError(null);
try {
const scriptIdForValidation =
editingScriptId ??
nextProjectScriptId(
trimmedName,
scripts.map((script) => script.id),
);
editingScriptId ?? nextProjectScriptId(trimmedName, scripts.map((script) => script.id));
const keybindingRule = decodeProjectScriptKeybindingRule({
keybinding,
command: commandForProjectScript(scriptIdForValidation),
+3 -20
View File
@@ -281,17 +281,7 @@ export default function Sidebar() {
async (threadId: ThreadId, position: { x: number; y: number }) => {
const api = readNativeApi();
if (!api) return;
const clicked = await api.contextMenu.show(
[
{ id: "mark-unread", label: "Mark unread" },
{ id: "delete", label: "Delete" },
],
position,
);
if (clicked === "mark-unread") {
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
return;
}
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
const thread = state.threads.find((t) => t.id === threadId);
@@ -390,7 +380,6 @@ export default function Sidebar() {
},
[
appSettings.confirmThreadDelete,
dispatch,
navigate,
removeWorktreeMutation,
routeThreadId,
@@ -589,9 +578,7 @@ 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
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
: "text-muted-foreground"
isActive ? "text-foreground" : "text-muted-foreground"
}`}
onClick={() => {
void navigate({
@@ -637,11 +624,7 @@ export default function Sidebar() {
/>
</span>
)}
<span
className={`text-[10px] ${
isActive ? "text-foreground/65" : "text-muted-foreground/40"
}`}
>
<span className="text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
</div>
+1 -3
View File
@@ -21,9 +21,7 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
) {
const chipsRef = React.useRef<Element | null>(null);
return (
<ComboboxContext.Provider
value={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
>
<ComboboxContext.Provider value={{ chipsRef, multiple: !!props.multiple }}>
<ComboboxPrimitive.Root {...props} />
</ComboboxContext.Provider>
);
+14
View File
@@ -24,6 +24,7 @@ const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
type SidebarContextProps = {
@@ -128,6 +129,19 @@ function SidebarProvider({
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed";
+1 -3
View File
@@ -42,9 +42,7 @@ function ToggleGroup({
orientation={orientation}
{...props}
>
<ToggleGroupContext.Provider
value={React.useMemo(() => ({ size, variant }), [size, variant])}
>
<ToggleGroupContext.Provider value={{ size, variant }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive>
+2 -4
View File
@@ -41,10 +41,8 @@ export function showContextMenuFallback<T extends string>(
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.label;
const isDeleteAction = item.id === "delete";
btn.className = isDeleteAction
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
btn.className =
"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default";
btn.addEventListener("click", () => cleanup(item.id));
menu.appendChild(btn);
}
-2
View File
@@ -294,7 +294,6 @@ label:has(> select#reasoning-effort) select {
background: var(--muted);
padding: 0.1rem 0.35rem;
color: var(--foreground);
font-size: 0.75rem;
}
.chat-markdown pre {
@@ -311,7 +310,6 @@ label:has(> select#reasoning-effort) select {
background: transparent;
padding: 0;
line-height: 1.5;
font-size: 0.875rem;
}
.chat-markdown table {
-22
View File
@@ -10,7 +10,6 @@ import {
formatShortcutLabel,
isChatNewShortcut,
isChatNewLocalShortcut,
isDiffToggleShortcut,
isOpenFavoriteEditorShortcut,
isTerminalClearShortcut,
isTerminalCloseShortcut,
@@ -92,11 +91,6 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("d"),
command: "diff.toggle",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
@@ -236,7 +230,6 @@ describe("shortcutLabelForCommand", () => {
it("returns labels for non-terminal commands", () => {
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
"Ctrl+O",
@@ -283,21 +276,6 @@ describe("chat/editor shortcuts", () => {
}),
);
});
it("matches diff.toggle shortcut outside terminal focus", () => {
assert.isTrue(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: false },
}),
);
assert.isFalse(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { terminalFocus: true },
}),
);
});
});
describe("cross-command precedence", () => {
-8
View File
@@ -198,14 +198,6 @@ export function isTerminalCloseShortcut(
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
}
export function isDiffToggleShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
}
export function isChatNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
-8
View File
@@ -20,12 +20,4 @@ describe("buildPatchCacheKey", () => {
expect(buildPatchCacheKey(before)).not.toBe(buildPatchCacheKey(after));
});
it("changes when cache scope changes", () => {
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
expect(buildPatchCacheKey(patch, "diff-panel:light")).not.toBe(
buildPatchCacheKey(patch, "diff-panel:dark"),
);
});
});
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more