Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc8573d736 | ||
|
|
335d6ac076 | ||
|
|
67f95ee25a | ||
|
|
7232f23400 | ||
|
|
16d3376410 | ||
|
|
008fbdd587 | ||
|
|
923837537b |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
quality:
|
quality:
|
||||||
name: Lint, Typecheck, Test, Build
|
name: Lint, Typecheck, Test, Build
|
||||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|||||||
@@ -11,4 +11,3 @@ packages/*/dist
|
|||||||
build/
|
build/
|
||||||
.logs/
|
.logs/
|
||||||
release/
|
release/
|
||||||
.t3
|
|
||||||
@@ -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.
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
import path from "path";
|
|
||||||
import fs from "fs";
|
|
||||||
|
|
||||||
const FAVICON_CANDIDATES = [
|
|
||||||
"favicon.svg", "favicon.ico", "favicon.png",
|
|
||||||
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
|
|
||||||
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
|
|
||||||
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
|
|
||||||
];
|
|
||||||
|
|
||||||
const ICON_SOURCE_FILES = [
|
|
||||||
"index.html", "public/index.html",
|
|
||||||
"app/routes/__root.tsx", "src/routes/__root.tsx",
|
|
||||||
"app/root.tsx", "src/root.tsx", "src/index.html",
|
|
||||||
];
|
|
||||||
|
|
||||||
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
|
|
||||||
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
|
|
||||||
|
|
||||||
function test(projectCwd) {
|
|
||||||
console.log("--- Testing:", projectCwd, "---");
|
|
||||||
|
|
||||||
for (const c of FAVICON_CANDIDATES) {
|
|
||||||
const full = path.join(projectCwd, c);
|
|
||||||
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
|
|
||||||
console.log(" Phase 1 FOUND:", c);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.log(" Phase 1: no match");
|
|
||||||
|
|
||||||
for (const sf of ICON_SOURCE_FILES) {
|
|
||||||
const full = path.join(projectCwd, sf);
|
|
||||||
if (!fs.existsSync(full)) continue;
|
|
||||||
const content = fs.readFileSync(full, "utf8");
|
|
||||||
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
|
|
||||||
if (href) {
|
|
||||||
const clean = href.replace(/^\//, "");
|
|
||||||
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
|
||||||
for (const p of tryPaths) {
|
|
||||||
if (fs.existsSync(p)) {
|
|
||||||
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.log(" Phase 2 href found but file missing:", href);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.log(" Phase 2: no match");
|
|
||||||
}
|
|
||||||
|
|
||||||
function getTestPaths() {
|
|
||||||
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
|
|
||||||
if (cliPaths.length > 0) return cliPaths;
|
|
||||||
|
|
||||||
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
|
|
||||||
if (envPaths?.length) return envPaths;
|
|
||||||
|
|
||||||
return [process.cwd()];
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const p of getTestPaths()) {
|
|
||||||
test(path.resolve(p));
|
|
||||||
}
|
|
||||||
@@ -41,31 +41,3 @@ Docs:
|
|||||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||||
|
|
||||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||||
|
|
||||||
## Cursor Cloud specific instructions
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
- **Bun >= 1.3.9** (package manager; see `packageManager` in root `package.json`).
|
|
||||||
- **Node.js >= 24.13.1** (required for `node:sqlite`; see `engines` in root `package.json`).
|
|
||||||
- **Codex CLI** on PATH is needed for full E2E agent sessions but is NOT required for dev server startup, lint, typecheck, or tests.
|
|
||||||
|
|
||||||
### Key commands
|
|
||||||
|
|
||||||
All commands are documented in the root `README.md`. Quick reference:
|
|
||||||
|
|
||||||
- `bun install` — install dependencies.
|
|
||||||
- `bun run lint` — runs `oxlint` (not ESLint).
|
|
||||||
- `bun run typecheck` — Turbo-orchestrated `tsc --noEmit` across all packages.
|
|
||||||
- `bun run test` — Turbo-orchestrated Vitest across all packages.
|
|
||||||
- `bun run dev` — starts contracts watch-build + server (port 3773) + Vite web (port 5733) via Turbo. Pass `T3CODE_NO_BROWSER=1` to suppress auto-opening a browser.
|
|
||||||
- `bun run build` — production build of all packages.
|
|
||||||
|
|
||||||
### Gotchas
|
|
||||||
|
|
||||||
- The server uses `node:sqlite` (experimental in Node 24). You will see `ExperimentalWarning: SQLite is an experimental feature` in test/server output — this is expected.
|
|
||||||
- Dev state is isolated to `~/.t3/dev` by default (set via `T3CODE_STATE_DIR`).
|
|
||||||
- `bun run dev` spawns `turbo` under the hood via `scripts/dev-runner.mjs`; the runner resolves dev ports (server 3773, web 5733) and environment variables automatically.
|
|
||||||
- `packages/contracts` must be built before `apps/server` or `apps/web` can start. Turbo handles this dependency, but if running individual packages manually, build contracts first: `bun run build:contracts`.
|
|
||||||
- Lint uses `oxlint` (config: `.oxlintrc.json`), not ESLint. Formatting uses `oxfmt` (config: `.oxfmtrc.json`).
|
|
||||||
- **Desktop dev mode** (`bun run dev:desktop`): The desktop Electron app requires `apps/server/dist/index.mjs` to exist (it spawns the server backend itself). Run `bun run build:desktop` first to build both server and desktop bundles, then `bun run dev:desktop`. The `tsdown --watch` (dev:bundle) may clean `dist-electron/` and not immediately rebuild; if `wait-on` hangs, manually run `bun run build` in `apps/desktop/` to unblock.
|
|
||||||
@@ -91,7 +91,7 @@ npx t3
|
|||||||
|
|
||||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||||
|
|
||||||
- Default ports: server `3773`, web `5733`
|
- Default ports: server `3773`, web `5173`
|
||||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||||
|
|
||||||
|
|||||||
@@ -15,11 +15,11 @@
|
|||||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
- [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] 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] 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] 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)
|
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||||
|
|
||||||
## Bigger things
|
## Bigger things
|
||||||
|
|
||||||
- [ ] Queueing messages
|
- [ ] 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)
|
||||||
@@ -5,7 +5,7 @@ import waitOn from "wait-on";
|
|||||||
|
|
||||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||||
|
|
||||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||||
const devServerUrl = `http://localhost:${port}`;
|
const devServerUrl = `http://localhost:${port}`;
|
||||||
|
|
||||||
await waitOn({
|
await waitOn({
|
||||||
|
|||||||
@@ -9,17 +9,7 @@ import {
|
|||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
type OrchestrationThread,
|
type OrchestrationThread,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import {
|
import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect";
|
||||||
Effect,
|
|
||||||
Exit,
|
|
||||||
Layer,
|
|
||||||
ManagedRuntime,
|
|
||||||
Option,
|
|
||||||
Schedule,
|
|
||||||
Schema,
|
|
||||||
Scope,
|
|
||||||
Stream,
|
|
||||||
} from "effect";
|
|
||||||
|
|
||||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../src/checkpointing/Services/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}`]);
|
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||||
}
|
}
|
||||||
|
|
||||||
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
|
function waitFor<A>(
|
||||||
"WaitForTimeoutError",
|
read: Effect.Effect<A, unknown>,
|
||||||
{
|
|
||||||
description: Schema.String,
|
|
||||||
},
|
|
||||||
) {}
|
|
||||||
|
|
||||||
function waitFor<A, E>(
|
|
||||||
read: Effect.Effect<A, E>,
|
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs?: number,
|
timeoutMs?: number,
|
||||||
): Effect.Effect<A, never>;
|
): Effect.Effect<A, never>;
|
||||||
function waitFor<A, B extends A, E>(
|
function waitFor<A, B extends A>(
|
||||||
read: Effect.Effect<A, E>,
|
read: Effect.Effect<A, unknown>,
|
||||||
predicate: (value: A) => value is B,
|
predicate: (value: A) => value is B,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs?: number,
|
timeoutMs?: number,
|
||||||
): Effect.Effect<B, never>;
|
): Effect.Effect<B, never>;
|
||||||
function waitFor<A, E>(
|
function waitFor<A>(
|
||||||
read: Effect.Effect<A, E>,
|
read: Effect.Effect<A, unknown>,
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs = 3000,
|
timeoutMs = 3000,
|
||||||
@@ -123,26 +106,12 @@ function waitFor<A, E>(
|
|||||||
while: (error) => error === RETRY_SIGNAL,
|
while: (error) => error === RETRY_SIGNAL,
|
||||||
}),
|
}),
|
||||||
Effect.mapError((error) =>
|
Effect.mapError((error) =>
|
||||||
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
|
error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${description}.`) : error,
|
||||||
),
|
),
|
||||||
Effect.orDie,
|
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 {
|
export interface OrchestrationIntegrationHarness {
|
||||||
readonly rootDir: string;
|
readonly rootDir: string;
|
||||||
readonly workspaceDir: string;
|
readonly workspaceDir: string;
|
||||||
@@ -183,7 +152,8 @@ export interface OrchestrationIntegrationHarness {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
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 adapterHarness = yield* makeTestProviderAdapterHarness;
|
||||||
|
|
||||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
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 runtime = ManagedRuntime.make(layer);
|
||||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
const engine = yield* Effect.promise(() =>
|
||||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
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)),
|
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)),
|
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)),
|
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)),
|
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||||
).pipe(Effect.orDie);
|
);
|
||||||
const checkpointRepository = yield* tryRuntimePromise(
|
const checkpointRepository = yield* Effect.promise(() =>
|
||||||
"load ProjectionCheckpointRepository service",
|
runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
);
|
||||||
).pipe(Effect.orDie);
|
const pendingApprovalRepository = yield* Effect.promise(() =>
|
||||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||||
"load ProjectionPendingApprovalRepository service",
|
);
|
||||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
|
||||||
).pipe(Effect.orDie);
|
|
||||||
|
|
||||||
const scope = yield* Scope.make("sequential");
|
const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential")));
|
||||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope))));
|
||||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
|
||||||
).pipe(Effect.orDie);
|
|
||||||
yield* sleep(10);
|
yield* sleep(10);
|
||||||
|
|
||||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
ThreadId,
|
ThreadId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import { Effect, Option, Schema } from "effect";
|
import { Effect, Exit, Option } from "effect";
|
||||||
|
|
||||||
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
|
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
|
||||||
import {
|
import {
|
||||||
@@ -45,14 +45,8 @@ function nowIso() {
|
|||||||
return new Date().toISOString();
|
return new Date().toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
|
const sleep = (ms: number) =>
|
||||||
"IntegrationWaitTimeoutError",
|
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||||
{
|
|
||||||
description: Schema.String,
|
|
||||||
},
|
|
||||||
) {}
|
|
||||||
|
|
||||||
const sleep = (ms: number) => Effect.sleep(ms);
|
|
||||||
|
|
||||||
function waitForSync<A>(
|
function waitForSync<A>(
|
||||||
read: () => A,
|
read: () => A,
|
||||||
@@ -69,7 +63,7 @@ function waitForSync<A>(
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
if (Date.now() >= deadline) {
|
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);
|
yield* sleep(10);
|
||||||
}
|
}
|
||||||
@@ -136,11 +130,27 @@ const startTurn = (input: {
|
|||||||
text: input.text,
|
text: input.text,
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.live("always removes integration temp dirs when shutdown fails", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const harness = yield* makeOrchestrationIntegrationHarness;
|
||||||
|
const rootDir = harness.rootDir;
|
||||||
|
const originalStopAll = harness.providerService.stopAll.bind(harness.providerService);
|
||||||
|
|
||||||
|
(
|
||||||
|
harness.providerService as unknown as {
|
||||||
|
stopAll: typeof harness.providerService.stopAll;
|
||||||
|
}
|
||||||
|
).stopAll = () => originalStopAll().pipe(Effect.andThen(Effect.fail(new Error("boom"))));
|
||||||
|
|
||||||
|
const disposeExit = yield* Effect.exit(harness.dispose);
|
||||||
|
assert.equal(Exit.isFailure(disposeExit), true);
|
||||||
|
assert.equal(fs.existsSync(rootDir), false);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
|
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
|
||||||
withHarness((harness) =>
|
withHarness((harness) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -319,7 +329,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
|||||||
const secondTurnThread = yield* harness.waitForThread(
|
const secondTurnThread = yield* harness.waitForThread(
|
||||||
THREAD_ID,
|
THREAD_ID,
|
||||||
(entry) =>
|
(entry) =>
|
||||||
entry.latestTurn?.turnId === "turn-2" &&
|
entry.latestTurnId === "turn-2" &&
|
||||||
entry.checkpoints.length === 2 &&
|
entry.checkpoints.length === 2 &&
|
||||||
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
|
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
|
||||||
);
|
);
|
||||||
@@ -653,7 +663,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
|||||||
yield* harness.waitForThread(
|
yield* harness.waitForThread(
|
||||||
THREAD_ID,
|
THREAD_ID,
|
||||||
(entry) =>
|
(entry) =>
|
||||||
entry.latestTurn?.turnId === "turn-2" &&
|
entry.latestTurnId === "turn-2" &&
|
||||||
entry.checkpoints.length === 2 &&
|
entry.checkpoints.length === 2 &&
|
||||||
entry.activities.some((activity) => activity.turnId === "turn-2"),
|
entry.activities.some((activity) => activity.turnId === "turn-2"),
|
||||||
8000,
|
8000,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.mjs",
|
"main": "./dist/index.mjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
|
||||||
"build": "tsdown && node scripts/bundle-client.ts",
|
"build": "tsdown && node scripts/bundle-client.ts",
|
||||||
"start": "node dist/index.mjs",
|
"start": "node dist/index.mjs",
|
||||||
"prepare": "effect-language-service patch",
|
"prepare": "effect-language-service patch",
|
||||||
|
|||||||
@@ -45,14 +45,7 @@ function makeSnapshot(input: {
|
|||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: input.worktreePath,
|
worktreePath: input.worktreePath,
|
||||||
latestTurn: {
|
latestTurnId: TurnId.makeUnsafe("turn-1"),
|
||||||
turnId: TurnId.makeUnsafe("turn-1"),
|
|
||||||
state: "completed",
|
|
||||||
requestedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
startedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
completedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
assistantMessageId: null,
|
|
||||||
},
|
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
createdAt: "2026-01-01T00:00:00.000Z",
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
import { TextGenerationError } from "../Errors.ts";
|
import { TextGenerationError } from "../Errors.ts";
|
||||||
@@ -40,7 +40,7 @@ function normalizeCodexError(
|
|||||||
error: unknown,
|
error: unknown,
|
||||||
fallback: string,
|
fallback: string,
|
||||||
): TextGenerationError {
|
): TextGenerationError {
|
||||||
if (Schema.is(TextGenerationError)(error)) {
|
if (error instanceof TextGenerationError) {
|
||||||
return error;
|
return error;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,9 +129,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
const readStreamAsString = (
|
||||||
operation: string,
|
operation: string,
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
stream: Stream.Stream<Uint8Array, unknown>,
|
||||||
): Effect.Effect<string, TextGenerationError> =>
|
): Effect.Effect<string, TextGenerationError> =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
let text = "";
|
let text = "";
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { it } from "@effect/vitest";
|
|||||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||||
import { expect } from "vitest";
|
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 GitManagerShape } from "../Services/GitManager.ts";
|
||||||
import {
|
import {
|
||||||
type GitHubCliShape,
|
type GitHubCliShape,
|
||||||
@@ -23,7 +23,7 @@ interface FakeGhScenario {
|
|||||||
prListSequence?: string[];
|
prListSequence?: string[];
|
||||||
createdPrUrl?: string;
|
createdPrUrl?: string;
|
||||||
defaultBranch?: string;
|
defaultBranch?: string;
|
||||||
failWith?: GitHubCliError;
|
failWith?: Error;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FakeGitTextGeneration {
|
interface FakeGitTextGeneration {
|
||||||
@@ -32,7 +32,7 @@ interface FakeGitTextGeneration {
|
|||||||
branch: string | null;
|
branch: string | null;
|
||||||
stagedSummary: string;
|
stagedSummary: string;
|
||||||
stagedPatch: string;
|
stagedPatch: string;
|
||||||
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
|
}) => Effect.Effect<{ subject: string; body: string }, unknown>;
|
||||||
generatePrContent: (input: {
|
generatePrContent: (input: {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
baseBranch: string;
|
baseBranch: string;
|
||||||
@@ -40,7 +40,7 @@ interface FakeGitTextGeneration {
|
|||||||
commitSummary: string;
|
commitSummary: string;
|
||||||
diffSummary: string;
|
diffSummary: string;
|
||||||
diffPatch: string;
|
diffPatch: string;
|
||||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
}) => Effect.Effect<{ title: string; body: string }, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeTempDir(
|
function makeTempDir(
|
||||||
@@ -58,7 +58,7 @@ function runGit(
|
|||||||
allowNonZeroExit = false,
|
allowNonZeroExit = false,
|
||||||
): Effect.Effect<
|
): Effect.Effect<
|
||||||
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||||
GitCommandError,
|
unknown,
|
||||||
GitService
|
GitService
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
@@ -74,7 +74,7 @@ function runGit(
|
|||||||
|
|
||||||
function initRepo(
|
function initRepo(
|
||||||
cwd: string,
|
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* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
yield* runGit(cwd, ["init", "--initial-branch=main"]);
|
yield* runGit(cwd, ["init", "--initial-branch=main"]);
|
||||||
@@ -88,7 +88,7 @@ function initRepo(
|
|||||||
|
|
||||||
function createBareRemote(): Effect.Effect<
|
function createBareRemote(): Effect.Effect<
|
||||||
string,
|
string,
|
||||||
PlatformError.PlatformError | GitCommandError,
|
unknown,
|
||||||
FileSystem.FileSystem | Scope.Scope | GitService
|
FileSystem.FileSystem | Scope.Scope | GitService
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
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 = {}): {
|
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||||
service: GitHubCliShape;
|
service: GitHubCliShape;
|
||||||
ghCalls: string[];
|
ghCalls: string[];
|
||||||
@@ -151,7 +179,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
ghCalls.push(args.join(" "));
|
ghCalls.push(args.join(" "));
|
||||||
|
|
||||||
if (scenario.failWith) {
|
if (scenario.failWith) {
|
||||||
return Effect.fail(scenario.failWith);
|
return Effect.fail(normalizeGhError(scenario.failWith));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (args[0] === "pr" && args[1] === "list") {
|
if (args[0] === "pr" && args[1] === "list") {
|
||||||
@@ -345,10 +373,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const { manager } = yield* makeManager({
|
const { manager } = yield* makeManager({
|
||||||
ghScenario: {
|
ghScenario: {
|
||||||
failWith: new GitHubCliError({
|
failWith: new Error("Command not found: gh"),
|
||||||
operation: "execute",
|
|
||||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
|
||||||
}),
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -575,7 +600,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit_push",
|
action: "commit_push",
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.flip,
|
Effect.flip,
|
||||||
Effect.map((error) => error.message),
|
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||||
);
|
);
|
||||||
expect(errorMessage).toContain("detached HEAD");
|
expect(errorMessage).toContain("detached HEAD");
|
||||||
}),
|
}),
|
||||||
@@ -592,10 +617,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const { manager } = yield* makeManager({
|
const { manager } = yield* makeManager({
|
||||||
ghScenario: {
|
ghScenario: {
|
||||||
failWith: new GitHubCliError({
|
failWith: new Error("Command not found: gh"),
|
||||||
operation: "execute",
|
|
||||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
|
||||||
}),
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -604,7 +626,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.flip,
|
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");
|
expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
|
||||||
}),
|
}),
|
||||||
@@ -621,10 +643,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const { manager } = yield* makeManager({
|
const { manager } = yield* makeManager({
|
||||||
ghScenario: {
|
ghScenario: {
|
||||||
failWith: new GitHubCliError({
|
failWith: new Error("authentication failed"),
|
||||||
operation: "execute",
|
|
||||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
|
||||||
}),
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -633,7 +652,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.flip,
|
Effect.flip,
|
||||||
Effect.map((error) => error.message),
|
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||||
);
|
);
|
||||||
expect(errorMessage).toContain("gh auth login");
|
expect(errorMessage).toContain("gh auth login");
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { it, assert } from "@effect/vitest";
|
import { it, assert } from "@effect/vitest";
|
||||||
import { Effect, Layer, Schema } from "effect";
|
import { Effect, Layer } from "effect";
|
||||||
|
|
||||||
import { GitCommandError } from "../Errors.ts";
|
import { GitCommandError } from "../Errors.ts";
|
||||||
import { GitServiceLive } from "./GitService.ts";
|
import { GitServiceLive } from "./GitService.ts";
|
||||||
@@ -50,7 +50,7 @@ layer("GitServiceLive", (it) => {
|
|||||||
|
|
||||||
assert.equal(result._tag, "Failure");
|
assert.equal(result._tag, "Failure");
|
||||||
if (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.operation, "GitProcess.test.failOnNonZero");
|
||||||
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
|
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
*
|
*
|
||||||
* @module GitServiceLive
|
* @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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
import { GitCommandError } from "../Errors.ts";
|
import { GitCommandError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
@@ -28,7 +28,7 @@ function toGitCommandError(
|
|||||||
detail: string,
|
detail: string,
|
||||||
) {
|
) {
|
||||||
return (cause: unknown) =>
|
return (cause: unknown) =>
|
||||||
Schema.is(GitCommandError)(cause)
|
cause instanceof GitCommandError
|
||||||
? cause
|
? cause
|
||||||
: new GitCommandError({
|
: new GitCommandError({
|
||||||
operation: input.operation,
|
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">,
|
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
stream: Stream.Stream<Uint8Array, unknown>,
|
||||||
maxOutputBytes: number,
|
maxOutputBytes: number,
|
||||||
): Effect.fn.Return<string, GitCommandError> {
|
): Effect.fn.Return<string, GitCommandError> {
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
|
|||||||
@@ -211,7 +211,13 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
|
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) =>
|
||||||
|
// @ts-expect-error - invalid command
|
||||||
|
entry.command === "invalid.command",
|
||||||
|
),
|
||||||
|
);
|
||||||
assert.deepEqual(configState.issues, [
|
assert.deepEqual(configState.issues, [
|
||||||
{
|
{
|
||||||
kind: "keybindings.invalid-entry",
|
kind: "keybindings.invalid-entry",
|
||||||
|
|||||||
@@ -65,7 +65,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
|||||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||||
{ key: "mod+w", command: "terminal.close", 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+n", command: "chat.new", when: "!terminalFocus" },
|
||||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||||
|
|||||||
@@ -117,10 +117,7 @@ export const launchDetached = (launch: EditorLaunch) =>
|
|||||||
});
|
});
|
||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
const open = yield* Effect.tryPromise({
|
const open = yield* Effect.promise(() => import("open"));
|
||||||
try: () => import("open"),
|
|
||||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
openBrowser: (target) =>
|
openBrowser: (target) =>
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import {
|
|||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
ProviderTurnId,
|
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -41,7 +40,6 @@ import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
|||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
|
||||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||||
|
|
||||||
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
||||||
@@ -93,7 +91,7 @@ function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd
|
|||||||
async function waitForThread(
|
async function waitForThread(
|
||||||
engine: OrchestrationEngineShape,
|
engine: OrchestrationEngineShape,
|
||||||
predicate: (thread: {
|
predicate: (thread: {
|
||||||
latestTurn: { turnId: string } | null;
|
latestTurnId: string | null;
|
||||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||||
activities: ReadonlyArray<{ kind: string }>;
|
activities: ReadonlyArray<{ kind: string }>;
|
||||||
}) => boolean,
|
}) => boolean,
|
||||||
@@ -101,7 +99,7 @@ async function waitForThread(
|
|||||||
) {
|
) {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
const poll = async (): Promise<{
|
const poll = async (): Promise<{
|
||||||
latestTurn: { turnId: string } | null;
|
latestTurnId: string | null;
|
||||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||||
activities: ReadonlyArray<{ kind: string }>;
|
activities: ReadonlyArray<{ kind: string }>;
|
||||||
}> => {
|
}> => {
|
||||||
@@ -319,8 +317,6 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -336,7 +332,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asProviderTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
});
|
});
|
||||||
await waitForGitRefExists(
|
await waitForGitRefExists(
|
||||||
harness.cwd,
|
harness.cwd,
|
||||||
@@ -351,14 +347,14 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asProviderTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||||
const thread = await waitForThread(
|
const thread = await waitForThread(
|
||||||
harness.engine,
|
harness.engine,
|
||||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
(entry) => entry.latestTurnId === "turn-1" && entry.checkpoints.length === 1,
|
||||||
);
|
);
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
expect(
|
expect(
|
||||||
@@ -383,81 +379,6 @@ describe("CheckpointReactor", () => {
|
|||||||
).toBe("v2\n");
|
).toBe("v2\n");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
|
|
||||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
|
||||||
const createdAt = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.session.set",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
session: {
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
status: "running",
|
|
||||||
providerName: "codex",
|
|
||||||
providerSessionId: asSessionId("sess-1"),
|
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: asTurnId("turn-main"),
|
|
||||||
lastError: null,
|
|
||||||
updatedAt: createdAt,
|
|
||||||
},
|
|
||||||
createdAt,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
harness.provider.emit({
|
|
||||||
type: "turn.started",
|
|
||||||
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
|
||||||
turnId: asProviderTurnId("turn-main"),
|
|
||||||
});
|
|
||||||
await waitForGitRefExists(
|
|
||||||
harness.cwd,
|
|
||||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
|
||||||
);
|
|
||||||
|
|
||||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
|
||||||
|
|
||||||
harness.provider.emit({
|
|
||||||
type: "turn.completed",
|
|
||||||
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
|
|
||||||
turnId: asProviderTurnId("turn-aux"),
|
|
||||||
status: "completed",
|
|
||||||
});
|
|
||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
|
||||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(midThread?.checkpoints).toHaveLength(0);
|
|
||||||
|
|
||||||
harness.provider.emit({
|
|
||||||
type: "turn.completed",
|
|
||||||
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
|
||||||
turnId: asProviderTurnId("turn-main"),
|
|
||||||
status: "completed",
|
|
||||||
});
|
|
||||||
|
|
||||||
const thread = await waitForThread(
|
|
||||||
harness.engine,
|
|
||||||
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
|
||||||
);
|
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||||
const createdAt = new Date().toISOString();
|
const createdAt = new Date().toISOString();
|
||||||
@@ -473,8 +394,6 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -490,7 +409,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asProviderTurnId("turn-missing-baseline"),
|
turnId: asTurnId("turn-missing-baseline"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -526,8 +445,6 @@ describe("CheckpointReactor", () => {
|
|||||||
text: "start turn",
|
text: "start turn",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -564,8 +481,6 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-missing"),
|
providerSessionId: asSessionId("sess-missing"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: asTurnId("turn-missing-cwd"),
|
activeTurnId: asTurnId("turn-missing-cwd"),
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -582,7 +497,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-missing"),
|
sessionId: asSessionId("sess-missing"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||||
turnId: asProviderTurnId("turn-missing-cwd"),
|
turnId: asTurnId("turn-missing-cwd"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -614,8 +529,6 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -631,7 +544,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asProviderTurnId("turn-3"),
|
turnId: asTurnId("turn-3"),
|
||||||
turnCount: 3,
|
turnCount: 3,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
@@ -667,8 +580,6 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -684,7 +595,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asProviderTurnId("turn-runtime-failure"),
|
turnId: asTurnId("turn-runtime-failure"),
|
||||||
turnCount: 1,
|
turnCount: 1,
|
||||||
status: "completed",
|
status: "completed",
|
||||||
});
|
});
|
||||||
@@ -696,7 +607,7 @@ describe("CheckpointReactor", () => {
|
|||||||
sessionId: asSessionId("sess-1"),
|
sessionId: asSessionId("sess-1"),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
turnId: asProviderTurnId("turn-after-runtime-failure"),
|
turnId: asTurnId("turn-after-runtime-failure"),
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitForGitRefExists(
|
await waitForGitRefExists(
|
||||||
@@ -723,8 +634,6 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
@@ -775,7 +684,7 @@ describe("CheckpointReactor", () => {
|
|||||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||||
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||||
|
|
||||||
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
expect(thread.latestTurnId).toBe("turn-1");
|
||||||
expect(thread.checkpoints).toHaveLength(1);
|
expect(thread.checkpoints).toHaveLength(1);
|
||||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||||
@@ -804,8 +713,6 @@ describe("CheckpointReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import {
|
|||||||
EventId,
|
EventId,
|
||||||
MessageId,
|
MessageId,
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
ProviderThreadId,
|
|
||||||
ThreadId,
|
ThreadId,
|
||||||
TurnId,
|
TurnId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
@@ -37,17 +36,6 @@ function toTurnId(value: string | undefined): TurnId | null {
|
|||||||
return value === undefined ? null : TurnId.makeUnsafe(value);
|
return value === undefined ? null : TurnId.makeUnsafe(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
|
||||||
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
|
||||||
if (left === null || left === undefined || right === null || right === undefined) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return left === right;
|
|
||||||
}
|
|
||||||
|
|
||||||
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
|
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case "failed":
|
case "failed":
|
||||||
@@ -185,21 +173,6 @@ const make = Effect.gen(function* () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
|
|
||||||
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
|
||||||
if (
|
|
||||||
projectedProviderThreadId !== null &&
|
|
||||||
eventProviderThreadId !== null &&
|
|
||||||
!sameId(projectedProviderThreadId, eventProviderThreadId)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// When a primary turn is active, only that turn may produce completion checkpoints.
|
|
||||||
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
|
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,8 +92,6 @@ describe("OrchestrationEngine", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt,
|
createdAt,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -430,8 +428,6 @@ describe("OrchestrationEngine", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
approvalPolicy: "on-request" as const,
|
|
||||||
sandboxMode: "workspace-write" as const,
|
|
||||||
createdAt,
|
createdAt,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -590,8 +586,6 @@ describe("OrchestrationEngine", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now(),
|
createdAt: now(),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -794,8 +794,6 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
|||||||
payload: {
|
payload: {
|
||||||
threadId,
|
threadId,
|
||||||
messageId,
|
messageId,
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: turnStartedAt,
|
createdAt: turnStartedAt,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -829,8 +827,6 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: turnId,
|
activeTurnId: turnId,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: sessionSetAt,
|
updatedAt: sessionSetAt,
|
||||||
|
|||||||
@@ -473,8 +473,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
providerName: event.payload.session.providerName,
|
providerName: event.payload.session.providerName,
|
||||||
providerSessionId: event.payload.session.providerSessionId,
|
providerSessionId: event.payload.session.providerSessionId,
|
||||||
providerThreadId: event.payload.session.providerThreadId,
|
providerThreadId: event.payload.session.providerThreadId,
|
||||||
approvalPolicy: event.payload.session.approvalPolicy,
|
|
||||||
sandboxMode: event.payload.session.sandboxMode,
|
|
||||||
activeTurnId: event.payload.session.activeTurnId,
|
activeTurnId: event.payload.session.activeTurnId,
|
||||||
lastError: event.payload.session.lastError,
|
lastError: event.payload.session.lastError,
|
||||||
updatedAt: event.payload.session.updatedAt,
|
updatedAt: event.payload.session.updatedAt,
|
||||||
|
|||||||
@@ -143,8 +143,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
provider_name,
|
provider_name,
|
||||||
provider_session_id,
|
provider_session_id,
|
||||||
provider_thread_id,
|
provider_thread_id,
|
||||||
approval_policy,
|
|
||||||
sandbox_mode,
|
|
||||||
active_turn_id,
|
active_turn_id,
|
||||||
last_error,
|
last_error,
|
||||||
updated_at
|
updated_at
|
||||||
@@ -155,8 +153,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
'codex',
|
'codex',
|
||||||
'provider-session-1',
|
'provider-session-1',
|
||||||
'provider-thread-1',
|
'provider-thread-1',
|
||||||
'on-request',
|
|
||||||
'workspace-write',
|
|
||||||
'turn-1',
|
'turn-1',
|
||||||
NULL,
|
NULL,
|
||||||
'2026-02-24T00:00:07.000Z'
|
'2026-02-24T00:00:07.000Z'
|
||||||
@@ -243,14 +239,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
latestTurn: {
|
latestTurnId: asTurnId("turn-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
|
||||||
state: "completed",
|
|
||||||
requestedAt: "2026-02-24T00:00:08.000Z",
|
|
||||||
startedAt: "2026-02-24T00:00:08.000Z",
|
|
||||||
completedAt: "2026-02-24T00:00:08.000Z",
|
|
||||||
assistantMessageId: asMessageId("message-1"),
|
|
||||||
},
|
|
||||||
createdAt: "2026-02-24T00:00:02.000Z",
|
createdAt: "2026-02-24T00:00:02.000Z",
|
||||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
@@ -293,8 +282,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asProviderSessionId("provider-session-1"),
|
providerSessionId: asProviderSessionId("provider-session-1"),
|
||||||
providerThreadId: asProviderThreadId("provider-thread-1"),
|
providerThreadId: asProviderThreadId("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: asTurnId("turn-1"),
|
activeTurnId: asTurnId("turn-1"),
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||||
|
|||||||
@@ -1,12 +1,8 @@
|
|||||||
import {
|
import {
|
||||||
IsoDateTime,
|
|
||||||
MessageId,
|
|
||||||
OrchestrationCheckpointFile,
|
OrchestrationCheckpointFile,
|
||||||
OrchestrationReadModel,
|
OrchestrationReadModel,
|
||||||
ProjectScript,
|
ProjectScript,
|
||||||
TurnId,
|
|
||||||
type OrchestrationCheckpointSummary,
|
type OrchestrationCheckpointSummary,
|
||||||
type OrchestrationLatestTurn,
|
|
||||||
type OrchestrationMessage,
|
type OrchestrationMessage,
|
||||||
type OrchestrationProject,
|
type OrchestrationProject,
|
||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
@@ -59,15 +55,6 @@ const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
|
|||||||
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
|
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
|
||||||
threadId: ProjectionThread.fields.threadId,
|
|
||||||
turnId: TurnId,
|
|
||||||
state: Schema.String,
|
|
||||||
requestedAt: IsoDateTime,
|
|
||||||
startedAt: Schema.NullOr(IsoDateTime),
|
|
||||||
completedAt: Schema.NullOr(IsoDateTime),
|
|
||||||
assistantMessageId: Schema.NullOr(MessageId),
|
|
||||||
});
|
|
||||||
const ProjectionStateDbRowSchema = ProjectionState;
|
const ProjectionStateDbRowSchema = ProjectionState;
|
||||||
|
|
||||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||||
@@ -209,8 +196,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_session_id AS "providerSessionId",
|
provider_session_id AS "providerSessionId",
|
||||||
provider_thread_id AS "providerThreadId",
|
provider_thread_id AS "providerThreadId",
|
||||||
approval_policy AS "approvalPolicy",
|
|
||||||
sandbox_mode AS "sandboxMode",
|
|
||||||
active_turn_id AS "activeTurnId",
|
active_turn_id AS "activeTurnId",
|
||||||
last_error AS "lastError",
|
last_error AS "lastError",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
@@ -239,25 +224,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
`,
|
`,
|
||||||
});
|
});
|
||||||
|
|
||||||
const listLatestTurnRows = SqlSchema.findAll({
|
|
||||||
Request: Schema.Void,
|
|
||||||
Result: ProjectionLatestTurnDbRowSchema,
|
|
||||||
execute: () =>
|
|
||||||
sql`
|
|
||||||
SELECT
|
|
||||||
thread_id AS "threadId",
|
|
||||||
turn_id AS "turnId",
|
|
||||||
state,
|
|
||||||
requested_at AS "requestedAt",
|
|
||||||
started_at AS "startedAt",
|
|
||||||
completed_at AS "completedAt",
|
|
||||||
assistant_message_id AS "assistantMessageId"
|
|
||||||
FROM projection_turns
|
|
||||||
WHERE turn_id IS NOT NULL
|
|
||||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
|
||||||
`,
|
|
||||||
});
|
|
||||||
|
|
||||||
const listProjectionStateRows = SqlSchema.findAll({
|
const listProjectionStateRows = SqlSchema.findAll({
|
||||||
Request: Schema.Void,
|
Request: Schema.Void,
|
||||||
Result: ProjectionStateDbRowSchema,
|
Result: ProjectionStateDbRowSchema,
|
||||||
@@ -282,7 +248,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
activityRows,
|
activityRows,
|
||||||
sessionRows,
|
sessionRows,
|
||||||
checkpointRows,
|
checkpointRows,
|
||||||
latestTurnRows,
|
|
||||||
stateRows,
|
stateRows,
|
||||||
] = yield* Effect.all([
|
] = yield* Effect.all([
|
||||||
listProjectRows(undefined).pipe(
|
listProjectRows(undefined).pipe(
|
||||||
@@ -333,14 +298,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
listLatestTurnRows(undefined).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
toPersistenceSqlOrDecodeError(
|
|
||||||
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
|
|
||||||
"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
listProjectionStateRows(undefined).pipe(
|
listProjectionStateRows(undefined).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
toPersistenceSqlOrDecodeError(
|
toPersistenceSqlOrDecodeError(
|
||||||
@@ -355,7 +312,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||||
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
|
||||||
|
|
||||||
let updatedAt: string | null = null;
|
let updatedAt: string | null = null;
|
||||||
|
|
||||||
@@ -414,34 +370,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
checkpointsByThread.set(row.threadId, threadCheckpoints);
|
checkpointsByThread.set(row.threadId, threadCheckpoints);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const row of latestTurnRows) {
|
|
||||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
|
||||||
if (row.startedAt !== null) {
|
|
||||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
|
||||||
}
|
|
||||||
if (row.completedAt !== null) {
|
|
||||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
|
||||||
}
|
|
||||||
if (latestTurnByThread.has(row.threadId)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
latestTurnByThread.set(row.threadId, {
|
|
||||||
turnId: row.turnId,
|
|
||||||
state:
|
|
||||||
row.state === "error"
|
|
||||||
? "error"
|
|
||||||
: row.state === "interrupted"
|
|
||||||
? "interrupted"
|
|
||||||
: row.state === "completed"
|
|
||||||
? "completed"
|
|
||||||
: "running",
|
|
||||||
requestedAt: row.requestedAt,
|
|
||||||
startedAt: row.startedAt,
|
|
||||||
completedAt: row.completedAt,
|
|
||||||
assistantMessageId: row.assistantMessageId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const row of sessionRows) {
|
for (const row of sessionRows) {
|
||||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||||
sessionsByThread.set(row.threadId, {
|
sessionsByThread.set(row.threadId, {
|
||||||
@@ -450,8 +378,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
providerName: row.providerName,
|
providerName: row.providerName,
|
||||||
providerSessionId: row.providerSessionId,
|
providerSessionId: row.providerSessionId,
|
||||||
providerThreadId: row.providerThreadId,
|
providerThreadId: row.providerThreadId,
|
||||||
approvalPolicy: row.approvalPolicy,
|
|
||||||
sandboxMode: row.sandboxMode,
|
|
||||||
activeTurnId: row.activeTurnId,
|
activeTurnId: row.activeTurnId,
|
||||||
lastError: row.lastError,
|
lastError: row.lastError,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
@@ -476,7 +402,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
|||||||
model: row.model,
|
model: row.model,
|
||||||
branch: row.branch,
|
branch: row.branch,
|
||||||
worktreePath: row.worktreePath,
|
worktreePath: row.worktreePath,
|
||||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
latestTurnId: row.latestTurnId,
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
updatedAt: row.updatedAt,
|
updatedAt: row.updatedAt,
|
||||||
deletedAt: row.deletedAt,
|
deletedAt: row.deletedAt,
|
||||||
|
|||||||
@@ -71,18 +71,16 @@ describe("ProviderCommandReactor", () => {
|
|||||||
async function createHarness() {
|
async function createHarness() {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||||
let nextSessionIndex = 1;
|
const startSession = vi.fn((_: unknown, __: unknown) =>
|
||||||
const startSession = vi.fn((_: unknown, __: unknown) => {
|
Effect.succeed({
|
||||||
const sessionIndex = nextSessionIndex++;
|
sessionId: asSessionId("sess-1"),
|
||||||
return Effect.succeed({
|
|
||||||
sessionId: asSessionId(`sess-${sessionIndex}`),
|
|
||||||
provider: "codex" as const,
|
provider: "codex" as const,
|
||||||
status: "ready" as const,
|
status: "ready" as const,
|
||||||
threadId: ProviderThreadId.makeUnsafe(`provider-thread-${sessionIndex}`),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
});
|
}),
|
||||||
});
|
);
|
||||||
const sendTurn = vi.fn((_: unknown) =>
|
const sendTurn = vi.fn((_: unknown) =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
@@ -173,8 +171,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
text: "hello reactor",
|
text: "hello reactor",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -185,181 +181,11 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||||
cwd: "/tmp/provider-project",
|
cwd: "/tmp/provider-project",
|
||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||||
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
|
||||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-unchanged-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-unchanged-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
|
||||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
|
||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("restarts the provider session when runtime mode changes", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-runtime-mode-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
approvalPolicy: "never",
|
|
||||||
sandboxMode: "danger-full-access",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-runtime-mode-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
|
||||||
|
|
||||||
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ sessionId: asSessionId("sess-1") });
|
|
||||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
|
||||||
resumeThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
});
|
|
||||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
|
||||||
sessionId: asSessionId("sess-2"),
|
|
||||||
});
|
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread?.session?.providerSessionId).toBe("sess-2");
|
|
||||||
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
|
||||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not stop the active session when restart fails before rebind", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-restart-failure-1"),
|
|
||||||
role: "user",
|
|
||||||
text: "first",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
approvalPolicy: "never",
|
|
||||||
sandboxMode: "danger-full-access",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
|
||||||
|
|
||||||
harness.startSession.mockImplementationOnce((_: unknown, __: unknown) =>
|
|
||||||
Effect.fail(new Error("simulated restart failure")) as never,
|
|
||||||
);
|
|
||||||
|
|
||||||
await Effect.runPromise(
|
|
||||||
harness.engine.dispatch({
|
|
||||||
type: "thread.turn.start",
|
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-2"),
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
message: {
|
|
||||||
messageId: asMessageId("user-message-restart-failure-2"),
|
|
||||||
role: "user",
|
|
||||||
text: "second",
|
|
||||||
attachments: [],
|
|
||||||
},
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
|
||||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
|
||||||
|
|
||||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
|
||||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
|
||||||
|
|
||||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
|
||||||
expect(thread?.session?.approvalPolicy).toBe("never");
|
|
||||||
expect(thread?.session?.sandboxMode).toBe("danger-full-access");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||||
@@ -377,8 +203,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: asTurnId("turn-1"),
|
activeTurnId: asTurnId("turn-1"),
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -418,8 +242,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
@@ -462,8 +284,6 @@ describe("ProviderCommandReactor", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
|
|||||||
@@ -3,13 +3,9 @@ import {
|
|||||||
CommandId,
|
CommandId,
|
||||||
EventId,
|
EventId,
|
||||||
type OrchestrationEvent,
|
type OrchestrationEvent,
|
||||||
type ProviderApprovalPolicy,
|
|
||||||
type ProviderKind,
|
type ProviderKind,
|
||||||
type ProviderSandboxMode,
|
|
||||||
type OrchestrationSession,
|
type OrchestrationSession,
|
||||||
type ThreadId,
|
type ThreadId,
|
||||||
type ProviderSession,
|
|
||||||
type ProviderThreadId,
|
|
||||||
type TurnId,
|
type TurnId,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||||
@@ -64,8 +60,6 @@ const serverCommandId = (tag: string): CommandId =>
|
|||||||
|
|
||||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
|
||||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
|
||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
@@ -134,10 +128,6 @@ const make = Effect.gen(function* () {
|
|||||||
const ensureSessionForThread = Effect.fnUntraced(function* (
|
const ensureSessionForThread = Effect.fnUntraced(function* (
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
createdAt: string,
|
createdAt: string,
|
||||||
options?: {
|
|
||||||
readonly approvalPolicy?: ProviderApprovalPolicy;
|
|
||||||
readonly sandboxMode?: ProviderSandboxMode;
|
|
||||||
},
|
|
||||||
) {
|
) {
|
||||||
const readModel = yield* orchestrationEngine.getReadModel();
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||||
@@ -145,10 +135,11 @@ const make = Effect.gen(function* () {
|
|||||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||||
}
|
}
|
||||||
|
|
||||||
const desiredApprovalPolicy =
|
const existingSessionId = thread.session?.providerSessionId;
|
||||||
options?.approvalPolicy ?? thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY;
|
if (existingSessionId) {
|
||||||
const desiredSandboxMode =
|
return existingSessionId;
|
||||||
options?.sandboxMode ?? thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE;
|
}
|
||||||
|
|
||||||
const preferredProvider: ProviderKind | undefined =
|
const preferredProvider: ProviderKind | undefined =
|
||||||
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
||||||
? thread.session.providerName
|
? thread.session.providerName
|
||||||
@@ -158,62 +149,28 @@ const make = Effect.gen(function* () {
|
|||||||
projects: readModel.projects,
|
projects: readModel.projects,
|
||||||
});
|
});
|
||||||
|
|
||||||
const startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
|
const startedSession = yield* providerService.startSession(threadId, {
|
||||||
providerService.startSession(threadId, {
|
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
...(thread.model ? { model: thread.model } : {}),
|
||||||
...(thread.model ? { model: thread.model } : {}),
|
});
|
||||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
|
||||||
approvalPolicy: desiredApprovalPolicy,
|
|
||||||
sandboxMode: desiredSandboxMode,
|
|
||||||
});
|
|
||||||
|
|
||||||
const bindSessionToThread = (session: ProviderSession) =>
|
yield* setThreadSession({
|
||||||
setThreadSession({
|
threadId,
|
||||||
|
session: {
|
||||||
threadId,
|
threadId,
|
||||||
session: {
|
status: mapProviderSessionStatusToOrchestrationStatus(startedSession.status),
|
||||||
threadId,
|
providerName: startedSession.provider,
|
||||||
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
providerSessionId: startedSession.sessionId,
|
||||||
providerName: session.provider,
|
providerThreadId: startedSession.threadId ?? null,
|
||||||
providerSessionId: session.sessionId,
|
// Provider turn ids are not orchestration turn ids.
|
||||||
providerThreadId: session.threadId ?? null,
|
activeTurnId: null,
|
||||||
approvalPolicy: desiredApprovalPolicy,
|
lastError: startedSession.lastError ?? null,
|
||||||
sandboxMode: desiredSandboxMode,
|
updatedAt: startedSession.updatedAt,
|
||||||
// Provider turn ids are not orchestration turn ids.
|
},
|
||||||
activeTurnId: null,
|
createdAt,
|
||||||
lastError: session.lastError ?? null,
|
});
|
||||||
updatedAt: session.updatedAt,
|
|
||||||
},
|
|
||||||
createdAt,
|
|
||||||
});
|
|
||||||
|
|
||||||
const existingSessionId = thread.session?.providerSessionId;
|
|
||||||
if (existingSessionId) {
|
|
||||||
const approvalPolicyChanged =
|
|
||||||
options?.approvalPolicy !== undefined && options.approvalPolicy !== thread.session?.approvalPolicy;
|
|
||||||
const sandboxModeChanged =
|
|
||||||
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
|
||||||
|
|
||||||
if (!approvalPolicyChanged && !sandboxModeChanged) {
|
|
||||||
return existingSessionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
const restartedSession = yield* startProviderSession(thread.session?.providerThreadId ?? null);
|
|
||||||
yield* bindSessionToThread(restartedSession);
|
|
||||||
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
|
||||||
Effect.catchCause((cause) =>
|
|
||||||
Effect.logWarning("provider command reactor failed to stop superseded provider session", {
|
|
||||||
threadId,
|
|
||||||
sessionId: existingSessionId,
|
|
||||||
cause: Cause.pretty(cause),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return restartedSession.sessionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
const startedSession = yield* startProviderSession();
|
|
||||||
yield* bindSessionToThread(startedSession);
|
|
||||||
return startedSession.sessionId;
|
return startedSession.sessionId;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -223,18 +180,13 @@ const make = Effect.gen(function* () {
|
|||||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
readonly effort?: string;
|
readonly effort?: string;
|
||||||
readonly approvalPolicy: ProviderApprovalPolicy;
|
|
||||||
readonly sandboxMode: ProviderSandboxMode;
|
|
||||||
readonly createdAt: string;
|
readonly createdAt: string;
|
||||||
}) {
|
}) {
|
||||||
const thread = yield* resolveThread(input.threadId);
|
const thread = yield* resolveThread(input.threadId);
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt);
|
||||||
approvalPolicy: input.approvalPolicy,
|
|
||||||
sandboxMode: input.sandboxMode,
|
|
||||||
});
|
|
||||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||||
const normalizedAttachments = input.attachments ?? [];
|
const normalizedAttachments = input.attachments ?? [];
|
||||||
|
|
||||||
@@ -279,8 +231,6 @@ const make = Effect.gen(function* () {
|
|||||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||||
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
||||||
approvalPolicy: event.payload.approvalPolicy,
|
|
||||||
sandboxMode: event.payload.sandboxMode,
|
|
||||||
createdAt: event.payload.createdAt,
|
createdAt: event.payload.createdAt,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -357,8 +307,6 @@ const make = Effect.gen(function* () {
|
|||||||
providerName: thread.session?.providerName ?? null,
|
providerName: thread.session?.providerName ?? null,
|
||||||
providerSessionId: null,
|
providerSessionId: null,
|
||||||
providerThreadId: null,
|
providerThreadId: null,
|
||||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
|
||||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
lastError: thread.session?.lastError ?? null,
|
lastError: thread.session?.lastError ?? null,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
|||||||
import {
|
import {
|
||||||
CommandId,
|
CommandId,
|
||||||
EventId,
|
EventId,
|
||||||
MessageId,
|
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderItemId,
|
ProviderItemId,
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
@@ -31,12 +30,9 @@ import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeInge
|
|||||||
|
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
const asProviderThreadId = (value: string): ProviderThreadId =>
|
|
||||||
ProviderThreadId.makeUnsafe(value);
|
|
||||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
|
||||||
|
|
||||||
function createProviderServiceHarness() {
|
function createProviderServiceHarness() {
|
||||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||||
@@ -166,8 +162,6 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: asSessionId("sess-1"),
|
providerSessionId: asSessionId("sess-1"),
|
||||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: null,
|
activeTurnId: null,
|
||||||
updatedAt: createdAt,
|
updatedAt: createdAt,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
@@ -222,112 +216,6 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
expect(thread.session?.lastError).toBe("turn failed");
|
expect(thread.session?.lastError).toBe("turn failed");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("ignores auxiliary turn completions from a different provider thread", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
harness.emit({
|
|
||||||
type: "turn.started",
|
|
||||||
eventId: asEventId("evt-turn-started-primary"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: now,
|
|
||||||
threadId: asProviderThreadId("provider-thread-1"),
|
|
||||||
turnId: asProviderTurnId("turn-primary"),
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitForThread(
|
|
||||||
harness.engine,
|
|
||||||
(thread) =>
|
|
||||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
|
|
||||||
);
|
|
||||||
|
|
||||||
harness.emit({
|
|
||||||
type: "turn.completed",
|
|
||||||
eventId: asEventId("evt-turn-completed-aux"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
threadId: asProviderThreadId("provider-thread-aux"),
|
|
||||||
turnId: asProviderTurnId("turn-aux"),
|
|
||||||
status: "completed",
|
|
||||||
});
|
|
||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
|
||||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(midThread?.session?.status).toBe("running");
|
|
||||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
|
||||||
|
|
||||||
harness.emit({
|
|
||||||
type: "turn.completed",
|
|
||||||
eventId: asEventId("evt-turn-completed-primary"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
threadId: asProviderThreadId("provider-thread-1"),
|
|
||||||
turnId: asProviderTurnId("turn-primary"),
|
|
||||||
status: "completed",
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitForThread(
|
|
||||||
harness.engine,
|
|
||||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores non-active turn completion when runtime omits thread id", async () => {
|
|
||||||
const harness = await createHarness();
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
|
|
||||||
harness.emit({
|
|
||||||
type: "turn.started",
|
|
||||||
eventId: asEventId("evt-turn-started-guarded"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: now,
|
|
||||||
turnId: asProviderTurnId("turn-guarded-main"),
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitForThread(
|
|
||||||
harness.engine,
|
|
||||||
(thread) =>
|
|
||||||
thread.session?.status === "running" &&
|
|
||||||
thread.session?.activeTurnId === "turn-guarded-main",
|
|
||||||
);
|
|
||||||
|
|
||||||
harness.emit({
|
|
||||||
type: "turn.completed",
|
|
||||||
eventId: asEventId("evt-turn-completed-guarded-other"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
turnId: asProviderTurnId("turn-guarded-other"),
|
|
||||||
status: "completed",
|
|
||||||
});
|
|
||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
|
||||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
|
||||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
|
||||||
expect(midThread?.session?.status).toBe("running");
|
|
||||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
|
||||||
|
|
||||||
harness.emit({
|
|
||||||
type: "turn.completed",
|
|
||||||
eventId: asEventId("evt-turn-completed-guarded-main"),
|
|
||||||
provider: "codex",
|
|
||||||
sessionId: asSessionId("sess-1"),
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
turnId: asProviderTurnId("turn-guarded-main"),
|
|
||||||
status: "completed",
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitForThread(
|
|
||||||
harness.engine,
|
|
||||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps message delta/completed into finalized assistant messages", async () => {
|
it("maps message delta/completed into finalized assistant messages", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -370,203 +258,6 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
expect(message?.streaming).toBe(false);
|
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",
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
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 () => {
|
it("does not duplicate assistant completion when message.completed is followed by turn.completed", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|||||||
@@ -1,18 +1,13 @@
|
|||||||
import {
|
import {
|
||||||
type AssistantDeliveryMode,
|
|
||||||
CommandId,
|
CommandId,
|
||||||
MessageId,
|
MessageId,
|
||||||
type OrchestrationEvent,
|
|
||||||
type ProviderApprovalPolicy,
|
|
||||||
type ProviderSandboxMode,
|
|
||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
type ThreadId,
|
|
||||||
TurnId,
|
TurnId,
|
||||||
type OrchestrationThreadActivity,
|
type OrchestrationThreadActivity,
|
||||||
type ProviderRuntimeEvent,
|
type ProviderRuntimeEvent,
|
||||||
type ProviderSessionId,
|
type ProviderSessionId,
|
||||||
} from "@t3tools/contracts";
|
} 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 { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||||
@@ -24,47 +19,13 @@ import {
|
|||||||
const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
|
const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
|
||||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||||
|
|
||||||
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
|
|
||||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "on-request";
|
|
||||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
|
||||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||||
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
||||||
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
|
|
||||||
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
|
|
||||||
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
|
|
||||||
const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
|
|
||||||
|
|
||||||
type TurnStartRequestedDomainEvent = Extract<
|
|
||||||
OrchestrationEvent,
|
|
||||||
{ type: "thread.turn-start-requested" }
|
|
||||||
>;
|
|
||||||
|
|
||||||
type RuntimeIngestionInput =
|
|
||||||
| {
|
|
||||||
source: "runtime";
|
|
||||||
event: ProviderRuntimeEvent;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
source: "domain";
|
|
||||||
event: TurnStartRequestedDomainEvent;
|
|
||||||
};
|
|
||||||
|
|
||||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||||
return value === undefined ? undefined : TurnId.makeUnsafe(value);
|
return value === undefined ? undefined : TurnId.makeUnsafe(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
|
||||||
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
|
||||||
if (left === null || left === undefined || right === null || right === undefined) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return left === right;
|
|
||||||
}
|
|
||||||
|
|
||||||
function truncateDetail(value: string, limit = 180): string {
|
function truncateDetail(value: string, limit = 180): string {
|
||||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||||
}
|
}
|
||||||
@@ -127,7 +88,6 @@ function runtimeEventToActivities(
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
case "tool.completed": {
|
case "tool.completed": {
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -144,7 +104,6 @@ function runtimeEventToActivities(
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
case "tool.started": {
|
case "tool.started": {
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -171,22 +130,12 @@ const make = Effect.gen(function* () {
|
|||||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
const providerService = yield* ProviderService;
|
const providerService = yield* ProviderService;
|
||||||
|
|
||||||
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
|
|
||||||
DEFAULT_ASSISTANT_DELIVERY_MODE,
|
|
||||||
);
|
|
||||||
|
|
||||||
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
||||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||||
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
|
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
|
||||||
lookup: () => Effect.succeed(new Set<MessageId>()),
|
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 = (
|
const rememberAssistantMessageId = (
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
turnId: TurnId,
|
turnId: TurnId,
|
||||||
@@ -240,76 +189,6 @@ const make = Effect.gen(function* () {
|
|||||||
const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
|
const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
|
||||||
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, 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) =>
|
const clearTurnStateForSession = (sessionId: ProviderSessionId) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const prefix = `${sessionId}:`;
|
const prefix = `${sessionId}:`;
|
||||||
@@ -317,25 +196,12 @@ const make = Effect.gen(function* () {
|
|||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
turnKeys,
|
turnKeys,
|
||||||
(key) =>
|
(key) =>
|
||||||
Effect.gen(function* () {
|
key.startsWith(prefix) ? Cache.invalidate(turnMessageIdsByTurnKey, key) : Effect.void,
|
||||||
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);
|
|
||||||
}),
|
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
).pipe(Effect.asVoid);
|
).pipe(Effect.asVoid);
|
||||||
});
|
});
|
||||||
|
|
||||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
const processEvent = (event: ProviderRuntimeEvent) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const readModel = yield* orchestrationEngine.getReadModel();
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
const thread = readModel.threads.find(
|
const thread = readModel.threads.find(
|
||||||
@@ -344,62 +210,6 @@ const make = Effect.gen(function* () {
|
|||||||
if (!thread) return;
|
if (!thread) return;
|
||||||
|
|
||||||
const now = event.createdAt;
|
const now = event.createdAt;
|
||||||
const sessionProviderThreadId = thread.session?.providerThreadId ?? null;
|
|
||||||
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
|
||||||
const eventTurnId = toTurnId("turnId" in event ? event.turnId : undefined);
|
|
||||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
|
||||||
|
|
||||||
const matchesThreadScope =
|
|
||||||
eventProviderThreadId === null ||
|
|
||||||
sessionProviderThreadId === null ||
|
|
||||||
sameId(eventProviderThreadId, sessionProviderThreadId);
|
|
||||||
const conflictsWithActiveTurn =
|
|
||||||
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
|
||||||
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
|
|
||||||
|
|
||||||
const shouldApplyThreadLifecycle = (() => {
|
|
||||||
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
switch (event.type) {
|
|
||||||
case "session.exited":
|
|
||||||
return true;
|
|
||||||
case "session.started":
|
|
||||||
case "thread.started":
|
|
||||||
if (!matchesThreadScope) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// Never let auxiliary/provider-side spawned threads replace the primary thread binding.
|
|
||||||
if (
|
|
||||||
eventProviderThreadId !== null &&
|
|
||||||
sessionProviderThreadId !== null &&
|
|
||||||
!sameId(eventProviderThreadId, sessionProviderThreadId)
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
case "turn.started":
|
|
||||||
if (!matchesThreadScope) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return !conflictsWithActiveTurn;
|
|
||||||
case "turn.completed":
|
|
||||||
if (!matchesThreadScope) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// Only the active turn may close the lifecycle state.
|
|
||||||
if (activeTurnId !== null && eventTurnId !== undefined) {
|
|
||||||
return sameId(activeTurnId, eventTurnId);
|
|
||||||
}
|
|
||||||
// Without an active turn, only accept completion when no thread mismatch signal exists.
|
|
||||||
return eventProviderThreadId === null || sessionProviderThreadId === null;
|
|
||||||
default:
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
event.type === "session.started" ||
|
event.type === "session.started" ||
|
||||||
@@ -408,7 +218,8 @@ const make = Effect.gen(function* () {
|
|||||||
event.type === "turn.started" ||
|
event.type === "turn.started" ||
|
||||||
event.type === "turn.completed"
|
event.type === "turn.completed"
|
||||||
) {
|
) {
|
||||||
const nextActiveTurnId = event.type === "turn.started" ? (eventTurnId ?? null) : null;
|
const activeTurnId =
|
||||||
|
event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
|
||||||
const providerThreadIdFromEvent =
|
const providerThreadIdFromEvent =
|
||||||
event.type === "thread.started"
|
event.type === "thread.started"
|
||||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||||
@@ -416,7 +227,7 @@ const make = Effect.gen(function* () {
|
|||||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||||
: null;
|
: null;
|
||||||
const providerThreadId =
|
const providerThreadId =
|
||||||
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
providerThreadIdFromEvent ?? thread.session?.providerThreadId ?? null;
|
||||||
const status =
|
const status =
|
||||||
event.type === "turn.started"
|
event.type === "turn.started"
|
||||||
? "running"
|
? "running"
|
||||||
@@ -432,26 +243,22 @@ const make = Effect.gen(function* () {
|
|||||||
? null
|
? null
|
||||||
: (thread.session?.lastError ?? null);
|
: (thread.session?.lastError ?? null);
|
||||||
|
|
||||||
if (shouldApplyThreadLifecycle) {
|
yield* orchestrationEngine.dispatch({
|
||||||
yield* orchestrationEngine.dispatch({
|
type: "thread.session.set",
|
||||||
type: "thread.session.set",
|
commandId: providerCommandId(event, "thread-session-set"),
|
||||||
commandId: providerCommandId(event, "thread-session-set"),
|
threadId: thread.id,
|
||||||
|
session: {
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
session: {
|
status,
|
||||||
threadId: thread.id,
|
providerName: event.provider,
|
||||||
status,
|
providerSessionId: event.sessionId,
|
||||||
providerName: event.provider,
|
providerThreadId,
|
||||||
providerSessionId: event.sessionId,
|
activeTurnId,
|
||||||
providerThreadId,
|
lastError,
|
||||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
updatedAt: now,
|
||||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
},
|
||||||
activeTurnId: nextActiveTurnId,
|
createdAt: now,
|
||||||
lastError,
|
});
|
||||||
updatedAt: now,
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "message.delta" && event.delta.length > 0) {
|
if (event.type === "message.delta" && event.delta.length > 0) {
|
||||||
@@ -463,31 +270,15 @@ const make = Effect.gen(function* () {
|
|||||||
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
|
yield* orchestrationEngine.dispatch({
|
||||||
if (assistantDeliveryMode === "buffered") {
|
type: "thread.message.assistant.delta",
|
||||||
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, event.delta);
|
commandId: providerCommandId(event, "assistant-delta"),
|
||||||
if (spillChunk.length > 0) {
|
threadId: thread.id,
|
||||||
yield* orchestrationEngine.dispatch({
|
messageId: assistantMessageId,
|
||||||
type: "thread.message.assistant.delta",
|
delta: event.delta,
|
||||||
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
|
...(turnId ? { turnId } : {}),
|
||||||
threadId: thread.id,
|
createdAt: now,
|
||||||
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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "message.completed") {
|
if (event.type === "message.completed") {
|
||||||
@@ -497,14 +288,13 @@ const make = Effect.gen(function* () {
|
|||||||
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* finalizeAssistantMessage({
|
yield* orchestrationEngine.dispatch({
|
||||||
event,
|
type: "thread.message.assistant.complete",
|
||||||
|
commandId: providerCommandId(event, "assistant-complete"),
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
messageId: assistantMessageId,
|
messageId: assistantMessageId,
|
||||||
...(turnId ? { turnId } : {}),
|
...(turnId ? { turnId } : {}),
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
commandTag: "assistant-complete",
|
|
||||||
finalDeltaCommandTag: "assistant-delta-finalize",
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (turnId) {
|
if (turnId) {
|
||||||
@@ -516,19 +306,15 @@ const make = Effect.gen(function* () {
|
|||||||
const turnId = toTurnId(event.turnId);
|
const turnId = toTurnId(event.turnId);
|
||||||
if (turnId) {
|
if (turnId) {
|
||||||
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(event.sessionId, turnId);
|
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(event.sessionId, turnId);
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(assistantMessageIds, (assistantMessageId) =>
|
||||||
assistantMessageIds,
|
orchestrationEngine.dispatch({
|
||||||
(assistantMessageId) =>
|
type: "thread.message.assistant.complete",
|
||||||
finalizeAssistantMessage({
|
commandId: providerCommandId(event, "assistant-complete-finalize"),
|
||||||
event,
|
threadId: thread.id,
|
||||||
threadId: thread.id,
|
messageId: assistantMessageId,
|
||||||
messageId: assistantMessageId,
|
turnId,
|
||||||
turnId,
|
createdAt: now,
|
||||||
createdAt: now,
|
}),
|
||||||
commandTag: "assistant-complete-finalize",
|
|
||||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
|
||||||
}),
|
|
||||||
{ concurrency: 1 },
|
|
||||||
).pipe(Effect.asVoid);
|
).pipe(Effect.asVoid);
|
||||||
yield* clearAssistantMessageIdsForTurn(event.sessionId, turnId);
|
yield* clearAssistantMessageIdsForTurn(event.sessionId, turnId);
|
||||||
}
|
}
|
||||||
@@ -539,38 +325,27 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === "runtime.error") {
|
if (event.type === "runtime.error") {
|
||||||
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
|
|
||||||
? true
|
|
||||||
: matchesThreadScope &&
|
|
||||||
(activeTurnId === null ||
|
|
||||||
eventTurnId === undefined ||
|
|
||||||
sameId(activeTurnId, eventTurnId));
|
|
||||||
|
|
||||||
const providerThreadId =
|
const providerThreadId =
|
||||||
event.threadId !== undefined
|
event.threadId !== undefined
|
||||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||||
: (thread.session?.providerThreadId ?? null);
|
: (thread.session?.providerThreadId ?? null);
|
||||||
|
|
||||||
if (shouldApplyRuntimeError) {
|
yield* orchestrationEngine.dispatch({
|
||||||
yield* orchestrationEngine.dispatch({
|
type: "thread.session.set",
|
||||||
type: "thread.session.set",
|
commandId: providerCommandId(event, "runtime-error-session-set"),
|
||||||
commandId: providerCommandId(event, "runtime-error-session-set"),
|
threadId: thread.id,
|
||||||
|
session: {
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
session: {
|
status: "error",
|
||||||
threadId: thread.id,
|
providerName: event.provider,
|
||||||
status: "error",
|
providerSessionId: event.sessionId,
|
||||||
providerName: event.provider,
|
providerThreadId,
|
||||||
providerSessionId: event.sessionId,
|
activeTurnId: toTurnId(event.turnId) ?? null,
|
||||||
providerThreadId,
|
lastError: event.message,
|
||||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
updatedAt: now,
|
||||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
},
|
||||||
activeTurnId: eventTurnId ?? null,
|
createdAt: now,
|
||||||
lastError: event.message,
|
});
|
||||||
updatedAt: now,
|
|
||||||
},
|
|
||||||
createdAt: now,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const activities = runtimeEventToActivities(event);
|
const activities = runtimeEventToActivities(event);
|
||||||
@@ -585,50 +360,33 @@ const make = Effect.gen(function* () {
|
|||||||
).pipe(Effect.asVoid);
|
).pipe(Effect.asVoid);
|
||||||
});
|
});
|
||||||
|
|
||||||
const processDomainEvent = (event: TurnStartRequestedDomainEvent) =>
|
const processEventSafely = (event: ProviderRuntimeEvent) =>
|
||||||
Ref.set(
|
processEvent(event).pipe(
|
||||||
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(
|
|
||||||
Effect.catchCause((cause) => {
|
Effect.catchCause((cause) => {
|
||||||
if (Cause.hasInterruptsOnly(cause)) {
|
if (Cause.hasInterruptsOnly(cause)) {
|
||||||
return Effect.failCause(cause);
|
return Effect.failCause(cause);
|
||||||
}
|
}
|
||||||
return Effect.logWarning("provider runtime ingestion failed to process event", {
|
return Effect.logWarning("provider runtime ingestion failed to process event", {
|
||||||
source: input.source,
|
eventId: event.eventId,
|
||||||
eventId: input.event.eventId,
|
eventType: event.type,
|
||||||
eventType: input.event.type,
|
|
||||||
cause: Cause.pretty(cause),
|
cause: Cause.pretty(cause),
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
|
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
|
||||||
const inputQueue = yield* Queue.unbounded<RuntimeIngestionInput>();
|
const providerEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||||
yield* Effect.addFinalizer(() => Queue.shutdown(inputQueue).pipe(Effect.asVoid));
|
|
||||||
|
yield* Effect.addFinalizer(() => Queue.shutdown(providerEventQueue).pipe(Effect.asVoid));
|
||||||
|
|
||||||
yield* Effect.forkScoped(
|
yield* Effect.forkScoped(
|
||||||
Effect.forever(Queue.take(inputQueue).pipe(Effect.flatMap(processInputSafely))),
|
Effect.forever(Queue.take(providerEventQueue).pipe(Effect.flatMap(processEventSafely))),
|
||||||
);
|
);
|
||||||
yield* Effect.forkScoped(
|
yield* Effect.forkScoped(
|
||||||
Stream.runForEach(providerService.streamEvents, (event) =>
|
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 {
|
return {
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
latestTurn: null,
|
latestTurnId: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
session: null,
|
session: null,
|
||||||
activities: [],
|
activities: [],
|
||||||
@@ -70,7 +70,7 @@ const readModel: OrchestrationReadModel = {
|
|||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
latestTurn: null,
|
latestTurnId: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
session: null,
|
session: null,
|
||||||
activities: [],
|
activities: [],
|
||||||
@@ -90,8 +90,6 @@ const messageSendCommand: OrchestrationCommand = {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -152,8 +152,6 @@ describe("decider project scripts", () => {
|
|||||||
},
|
},
|
||||||
model: "gpt-5",
|
model: "gpt-5",
|
||||||
effort: "high",
|
effort: "high",
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
},
|
},
|
||||||
readModel,
|
readModel,
|
||||||
@@ -164,20 +162,7 @@ describe("decider project scripts", () => {
|
|||||||
const events = Array.isArray(result) ? result : [result];
|
const events = Array.isArray(result) ? result : [result];
|
||||||
expect(events).toHaveLength(2);
|
expect(events).toHaveLength(2);
|
||||||
expect(events[0]?.type).toBe("thread.message-sent");
|
expect(events[0]?.type).toBe("thread.message-sent");
|
||||||
const turnStartEvent = events[1];
|
expect(events[1]?.type).toBe("thread.turn-start-requested");
|
||||||
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
|
expect(events[1]?.causationEventId).toBe(events[0]?.eventId ?? null);
|
||||||
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
|
|
||||||
if (turnStartEvent?.type !== "thread.turn-start-requested") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
|
|
||||||
expect(turnStartEvent.payload).toMatchObject({
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
messageId: asMessageId("message-user-1"),
|
|
||||||
model: "gpt-5",
|
|
||||||
effort: "high",
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
} from "./commandInvariants.ts";
|
} from "./commandInvariants.ts";
|
||||||
|
|
||||||
const nowIso = () => new Date().toISOString();
|
const nowIso = () => new Date().toISOString();
|
||||||
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
|
|
||||||
|
|
||||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||||
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
|
||||||
@@ -253,9 +252,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
|||||||
messageId: command.message.messageId,
|
messageId: command.message.messageId,
|
||||||
...(command.model !== undefined ? { model: command.model } : {}),
|
...(command.model !== undefined ? { model: command.model } : {}),
|
||||||
...(command.effort !== undefined ? { effort: command.effort } : {}),
|
...(command.effort !== undefined ? { effort: command.effort } : {}),
|
||||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
|
||||||
approvalPolicy: command.approvalPolicy,
|
|
||||||
sandboxMode: command.sandboxMode,
|
|
||||||
createdAt: command.createdAt,
|
createdAt: command.createdAt,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ describe("orchestration projector", () => {
|
|||||||
model: "gpt-5-codex",
|
model: "gpt-5-codex",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
latestTurn: null,
|
latestTurnId: null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
@@ -135,8 +135,6 @@ describe("orchestration projector", () => {
|
|||||||
payload: {
|
payload: {
|
||||||
threadId: "thread-1",
|
threadId: "thread-1",
|
||||||
messageId: "message-1",
|
messageId: "message-1",
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
createdAt: "2026-01-01T00:00:00.000Z",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -195,8 +193,6 @@ describe("orchestration projector", () => {
|
|||||||
providerName: "codex",
|
providerName: "codex",
|
||||||
providerSessionId: "session-1",
|
providerSessionId: "session-1",
|
||||||
providerThreadId: "provider-thread-1",
|
providerThreadId: "provider-thread-1",
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
activeTurnId: "turn-1",
|
activeTurnId: "turn-1",
|
||||||
lastError: null,
|
lastError: null,
|
||||||
updatedAt: startedAt,
|
updatedAt: startedAt,
|
||||||
@@ -207,7 +203,7 @@ describe("orchestration projector", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const thread = afterRunning.threads[0];
|
const thread = afterRunning.threads[0];
|
||||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
expect(thread?.latestTurnId).toBe("turn-1");
|
||||||
expect(thread?.session?.status).toBe("running");
|
expect(thread?.session?.status).toBe("running");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -504,7 +500,7 @@ describe("orchestration projector", () => {
|
|||||||
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
|
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
|
||||||
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
|
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
|
||||||
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
|
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
|
||||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
expect(thread?.latestTurnId).toBe("turn-1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not fallback-retain messages tied to removed turn IDs", async () => {
|
it("does not fallback-retain messages tied to removed turn IDs", async () => {
|
||||||
|
|||||||
@@ -26,12 +26,6 @@ type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
|
|||||||
const MAX_THREAD_MESSAGES = 2_000;
|
const MAX_THREAD_MESSAGES = 2_000;
|
||||||
const MAX_THREAD_CHECKPOINTS = 500;
|
const MAX_THREAD_CHECKPOINTS = 500;
|
||||||
|
|
||||||
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
|
|
||||||
if (status === "error") return "error" as const;
|
|
||||||
if (status === "missing") return "interrupted" as const;
|
|
||||||
return "completed" as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateThread(
|
function updateThread(
|
||||||
threads: ReadonlyArray<OrchestrationThread>,
|
threads: ReadonlyArray<OrchestrationThread>,
|
||||||
threadId: ThreadId,
|
threadId: ThreadId,
|
||||||
@@ -46,10 +40,9 @@ function decodeForEvent<A>(
|
|||||||
eventType: OrchestrationEvent["type"],
|
eventType: OrchestrationEvent["type"],
|
||||||
field: string,
|
field: string,
|
||||||
): Effect.Effect<A, OrchestrationProjectorDecodeError> {
|
): Effect.Effect<A, OrchestrationProjectorDecodeError> {
|
||||||
return Effect.try({
|
return Schema.decodeUnknownEffect(schema)(value).pipe(
|
||||||
try: () => Schema.decodeUnknownSync(schema as any)(value),
|
Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
|
||||||
catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError),
|
) as Effect.Effect<A, OrchestrationProjectorDecodeError>;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function retainThreadMessagesAfterRevert(
|
function retainThreadMessagesAfterRevert(
|
||||||
@@ -226,7 +219,7 @@ export function projectEvent(
|
|||||||
model: payload.model,
|
model: payload.model,
|
||||||
branch: payload.branch,
|
branch: payload.branch,
|
||||||
worktreePath: payload.worktreePath,
|
worktreePath: payload.worktreePath,
|
||||||
latestTurn: null,
|
latestTurnId: null,
|
||||||
createdAt: payload.createdAt,
|
createdAt: payload.createdAt,
|
||||||
updatedAt: payload.updatedAt,
|
updatedAt: payload.updatedAt,
|
||||||
deletedAt: null,
|
deletedAt: null,
|
||||||
@@ -357,26 +350,7 @@ export function projectEvent(
|
|||||||
...nextBase,
|
...nextBase,
|
||||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||||
session,
|
session,
|
||||||
latestTurn:
|
latestTurnId: session.activeTurnId,
|
||||||
session.status === "running" && session.activeTurnId !== null
|
|
||||||
? {
|
|
||||||
turnId: session.activeTurnId,
|
|
||||||
state: "running",
|
|
||||||
requestedAt:
|
|
||||||
thread.latestTurn?.turnId === session.activeTurnId
|
|
||||||
? thread.latestTurn.requestedAt
|
|
||||||
: session.updatedAt,
|
|
||||||
startedAt:
|
|
||||||
thread.latestTurn?.turnId === session.activeTurnId
|
|
||||||
? (thread.latestTurn.startedAt ?? session.updatedAt)
|
|
||||||
: session.updatedAt,
|
|
||||||
completedAt: null,
|
|
||||||
assistantMessageId:
|
|
||||||
thread.latestTurn?.turnId === session.activeTurnId
|
|
||||||
? thread.latestTurn.assistantMessageId
|
|
||||||
: null,
|
|
||||||
}
|
|
||||||
: thread.latestTurn,
|
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
@@ -421,20 +395,7 @@ export function projectEvent(
|
|||||||
...nextBase,
|
...nextBase,
|
||||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||||
checkpoints,
|
checkpoints,
|
||||||
latestTurn: {
|
latestTurnId: payload.turnId,
|
||||||
turnId: payload.turnId,
|
|
||||||
state: checkpointStatusToLatestTurnState(payload.status),
|
|
||||||
requestedAt:
|
|
||||||
thread.latestTurn?.turnId === payload.turnId
|
|
||||||
? thread.latestTurn.requestedAt
|
|
||||||
: payload.completedAt,
|
|
||||||
startedAt:
|
|
||||||
thread.latestTurn?.turnId === payload.turnId
|
|
||||||
? (thread.latestTurn.startedAt ?? payload.completedAt)
|
|
||||||
: payload.completedAt,
|
|
||||||
completedAt: payload.completedAt,
|
|
||||||
assistantMessageId: payload.assistantMessageId,
|
|
||||||
},
|
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
@@ -460,18 +421,8 @@ export function projectEvent(
|
|||||||
).slice(-MAX_THREAD_MESSAGES);
|
).slice(-MAX_THREAD_MESSAGES);
|
||||||
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
||||||
|
|
||||||
const latestCheckpoint = checkpoints.at(-1) ?? null;
|
const latestTurnId =
|
||||||
const latestTurn =
|
checkpoints.length > 0 ? (checkpoints[checkpoints.length - 1]?.turnId ?? null) : null;
|
||||||
latestCheckpoint === null
|
|
||||||
? null
|
|
||||||
: {
|
|
||||||
turnId: latestCheckpoint.turnId,
|
|
||||||
state: checkpointStatusToLatestTurnState(latestCheckpoint.status),
|
|
||||||
requestedAt: latestCheckpoint.completedAt,
|
|
||||||
startedAt: latestCheckpoint.completedAt,
|
|
||||||
completedAt: latestCheckpoint.completedAt,
|
|
||||||
assistantMessageId: latestCheckpoint.assistantMessageId,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...nextBase,
|
...nextBase,
|
||||||
@@ -479,7 +430,7 @@ export function projectEvent(
|
|||||||
checkpoints,
|
checkpoints,
|
||||||
messages,
|
messages,
|
||||||
activities,
|
activities,
|
||||||
latestTurn,
|
latestTurnId,
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -25,8 +25,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
provider_name,
|
provider_name,
|
||||||
provider_session_id,
|
provider_session_id,
|
||||||
provider_thread_id,
|
provider_thread_id,
|
||||||
approval_policy,
|
|
||||||
sandbox_mode,
|
|
||||||
active_turn_id,
|
active_turn_id,
|
||||||
last_error,
|
last_error,
|
||||||
updated_at
|
updated_at
|
||||||
@@ -37,8 +35,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
${row.providerName},
|
${row.providerName},
|
||||||
${row.providerSessionId},
|
${row.providerSessionId},
|
||||||
${row.providerThreadId},
|
${row.providerThreadId},
|
||||||
${row.approvalPolicy},
|
|
||||||
${row.sandboxMode},
|
|
||||||
${row.activeTurnId},
|
${row.activeTurnId},
|
||||||
${row.lastError},
|
${row.lastError},
|
||||||
${row.updatedAt}
|
${row.updatedAt}
|
||||||
@@ -49,8 +45,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
provider_name = excluded.provider_name,
|
provider_name = excluded.provider_name,
|
||||||
provider_session_id = excluded.provider_session_id,
|
provider_session_id = excluded.provider_session_id,
|
||||||
provider_thread_id = excluded.provider_thread_id,
|
provider_thread_id = excluded.provider_thread_id,
|
||||||
approval_policy = excluded.approval_policy,
|
|
||||||
sandbox_mode = excluded.sandbox_mode,
|
|
||||||
active_turn_id = excluded.active_turn_id,
|
active_turn_id = excluded.active_turn_id,
|
||||||
last_error = excluded.last_error,
|
last_error = excluded.last_error,
|
||||||
updated_at = excluded.updated_at
|
updated_at = excluded.updated_at
|
||||||
@@ -68,8 +62,6 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
|||||||
provider_name AS "providerName",
|
provider_name AS "providerName",
|
||||||
provider_session_id AS "providerSessionId",
|
provider_session_id AS "providerSessionId",
|
||||||
provider_thread_id AS "providerThreadId",
|
provider_thread_id AS "providerThreadId",
|
||||||
approval_policy AS "approvalPolicy",
|
|
||||||
sandbox_mode AS "sandboxMode",
|
|
||||||
active_turn_id AS "activeTurnId",
|
active_turn_id AS "activeTurnId",
|
||||||
last_error AS "lastError",
|
last_error AS "lastError",
|
||||||
updated_at AS "updatedAt"
|
updated_at AS "updatedAt"
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
|
|||||||
import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
|
import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
|
||||||
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
||||||
import Migration0005 from "./Migrations/005_Projections.ts";
|
import Migration0005 from "./Migrations/005_Projections.ts";
|
||||||
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Migration loader with all migrations defined inline.
|
* Migration loader with all migrations defined inline.
|
||||||
@@ -35,7 +34,6 @@ const loader = Migrator.fromRecord({
|
|||||||
"3_CheckpointDiffBlobs": Migration0003,
|
"3_CheckpointDiffBlobs": Migration0003,
|
||||||
"4_ProviderSessionRuntime": Migration0004,
|
"4_ProviderSessionRuntime": Migration0004,
|
||||||
"5_Projections": Migration0005,
|
"5_Projections": Migration0005,
|
||||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
-30
@@ -1,30 +0,0 @@
|
|||||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
||||||
import * as Effect from "effect/Effect";
|
|
||||||
|
|
||||||
const DEFAULT_APPROVAL_POLICY = "never";
|
|
||||||
const DEFAULT_SANDBOX_MODE = "workspace-write";
|
|
||||||
|
|
||||||
export default Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
ALTER TABLE projection_thread_sessions
|
|
||||||
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
ALTER TABLE projection_thread_sessions
|
|
||||||
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
|
|
||||||
`;
|
|
||||||
|
|
||||||
yield* sql`
|
|
||||||
UPDATE projection_thread_sessions
|
|
||||||
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
|
|
||||||
WHERE approval_policy IS NULL
|
|
||||||
`;
|
|
||||||
yield* sql`
|
|
||||||
UPDATE projection_thread_sessions
|
|
||||||
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
|
|
||||||
WHERE sandbox_mode IS NULL
|
|
||||||
`;
|
|
||||||
});
|
|
||||||
@@ -4,27 +4,23 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|||||||
|
|
||||||
import * as SqliteClient from "./NodeSqliteClient.ts";
|
import * as SqliteClient from "./NodeSqliteClient.ts";
|
||||||
|
|
||||||
const layer = it.layer(SqliteClient.layerMemory());
|
it.effect("runs prepared queries and returns positional values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const sql = yield* SqlClient.SqlClient;
|
||||||
|
|
||||||
layer("NodeSqliteClient", (it) => {
|
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
|
||||||
it.effect("runs prepared queries and returns positional values", () =>
|
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
|
||||||
Effect.gen(function* () {
|
|
||||||
const sql = yield* SqlClient.SqlClient;
|
|
||||||
|
|
||||||
yield* sql`CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT NOT NULL)`;
|
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
|
||||||
yield* sql`INSERT INTO entries(name) VALUES (${"alpha"}), (${"beta"})`;
|
|
||||||
|
|
||||||
const rows = yield* sql<{ readonly id: number; readonly name: string }>`
|
|
||||||
SELECT id, name FROM entries ORDER BY id
|
SELECT id, name FROM entries ORDER BY id
|
||||||
`;
|
`;
|
||||||
assert.equal(rows.length, 2);
|
assert.equal(rows.length, 2);
|
||||||
assert.equal(rows[0]?.name, "alpha");
|
assert.equal(rows[0]?.name, "alpha");
|
||||||
assert.equal(rows[1]?.name, "beta");
|
assert.equal(rows[1]?.name, "beta");
|
||||||
|
|
||||||
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
|
const values = yield* sql`SELECT id, name FROM entries ORDER BY id`.values;
|
||||||
assert.equal(values.length, 2);
|
assert.equal(values.length, 2);
|
||||||
assert.equal(values[0]?.[1], "alpha");
|
assert.equal(values[0]?.[1], "alpha");
|
||||||
assert.equal(values[1]?.[1], "beta");
|
assert.equal(values[1]?.[1], "beta");
|
||||||
}),
|
}).pipe(Effect.provide(SqliteClient.layerMemory())),
|
||||||
);
|
);
|
||||||
});
|
|
||||||
@@ -9,8 +9,6 @@
|
|||||||
import {
|
import {
|
||||||
IsoDateTime,
|
IsoDateTime,
|
||||||
OrchestrationSessionStatus,
|
OrchestrationSessionStatus,
|
||||||
ProviderApprovalPolicy,
|
|
||||||
ProviderSandboxMode,
|
|
||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
@@ -27,8 +25,6 @@ export const ProjectionThreadSession = Schema.Struct({
|
|||||||
providerName: Schema.NullOr(Schema.String),
|
providerName: Schema.NullOr(Schema.String),
|
||||||
providerSessionId: Schema.NullOr(ProviderSessionId),
|
providerSessionId: Schema.NullOr(ProviderSessionId),
|
||||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||||
approvalPolicy: ProviderApprovalPolicy,
|
|
||||||
sandboxMode: ProviderSandboxMode,
|
|
||||||
activeTurnId: Schema.NullOr(TurnId),
|
activeTurnId: Schema.NullOr(TurnId),
|
||||||
lastError: Schema.NullOr(Schema.String),
|
lastError: Schema.NullOr(Schema.String),
|
||||||
updatedAt: IsoDateTime,
|
updatedAt: IsoDateTime,
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import http from "node:http";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
|
||||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
|
||||||
|
|
||||||
interface HttpResponse {
|
|
||||||
statusCode: number;
|
|
||||||
contentType: string | null;
|
|
||||||
body: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const tempDirs: string[] = [];
|
|
||||||
|
|
||||||
function makeTempDir(prefix: string): string {
|
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
||||||
tempDirs.push(dir);
|
|
||||||
return dir;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function withRouteServer(
|
|
||||||
run: (baseUrl: string) => Promise<void>,
|
|
||||||
): Promise<void> {
|
|
||||||
const server = http.createServer((req, res) => {
|
|
||||||
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
||||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
||||||
res.end("Not Found");
|
|
||||||
});
|
|
||||||
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
|
||||||
if (error) {
|
|
||||||
reject(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const address = server.address();
|
|
||||||
if (typeof address !== "object" || address === null) {
|
|
||||||
throw new Error("Expected server address to be an object");
|
|
||||||
}
|
|
||||||
const baseUrl = `http://127.0.0.1:${address.port}`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await run(baseUrl);
|
|
||||||
} finally {
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
server.close((error?: Error) => {
|
|
||||||
if (error) {
|
|
||||||
reject(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
|
|
||||||
const response = await fetch(`${baseUrl}${pathname}`);
|
|
||||||
return {
|
|
||||||
statusCode: response.status,
|
|
||||||
contentType: response.headers.get("content-type"),
|
|
||||||
body: await response.text(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("tryHandleProjectFaviconRequest", () => {
|
|
||||||
afterEach(() => {
|
|
||||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 400 when cwd is missing", async () => {
|
|
||||||
await withRouteServer(async (baseUrl) => {
|
|
||||||
const response = await request(baseUrl, "/api/project-favicon");
|
|
||||||
expect(response.statusCode).toBe(400);
|
|
||||||
expect(response.body).toBe("Missing cwd parameter");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("serves a well-known favicon file from the project root", async () => {
|
|
||||||
const projectDir = makeTempDir("t3code-favicon-route-root-");
|
|
||||||
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
|
|
||||||
|
|
||||||
await withRouteServer(async (baseUrl) => {
|
|
||||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
|
||||||
const response = await request(baseUrl, pathname);
|
|
||||||
expect(response.statusCode).toBe(200);
|
|
||||||
expect(response.contentType).toContain("image/svg+xml");
|
|
||||||
expect(response.body).toBe("<svg>favicon</svg>");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves icon href from source files when no well-known favicon exists", async () => {
|
|
||||||
const projectDir = makeTempDir("t3code-favicon-route-source-");
|
|
||||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
|
||||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
|
||||||
fs.writeFileSync(path.join(projectDir, "index.html"), '<link rel="icon" href="/brand/logo.svg">');
|
|
||||||
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
|
|
||||||
|
|
||||||
await withRouteServer(async (baseUrl) => {
|
|
||||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
|
||||||
const response = await request(baseUrl, pathname);
|
|
||||||
expect(response.statusCode).toBe(200);
|
|
||||||
expect(response.contentType).toContain("image/svg+xml");
|
|
||||||
expect(response.body).toBe("<svg>brand</svg>");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves icon link when href appears before rel in HTML", async () => {
|
|
||||||
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
|
|
||||||
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
|
|
||||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
|
||||||
fs.writeFileSync(path.join(projectDir, "index.html"), '<link href="/brand/logo.svg" rel="icon">');
|
|
||||||
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
|
|
||||||
|
|
||||||
await withRouteServer(async (baseUrl) => {
|
|
||||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
|
||||||
const response = await request(baseUrl, pathname);
|
|
||||||
expect(response.statusCode).toBe(200);
|
|
||||||
expect(response.contentType).toContain("image/svg+xml");
|
|
||||||
expect(response.body).toBe("<svg>brand-html-order</svg>");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves object-style icon metadata when href appears before rel", async () => {
|
|
||||||
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
|
|
||||||
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
|
|
||||||
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
|
|
||||||
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(projectDir, "src", "root.tsx"),
|
|
||||||
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
|
|
||||||
|
|
||||||
await withRouteServer(async (baseUrl) => {
|
|
||||||
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
|
|
||||||
const response = await request(baseUrl, pathname);
|
|
||||||
expect(response.statusCode).toBe(200);
|
|
||||||
expect(response.contentType).toContain("image/svg+xml");
|
|
||||||
expect(response.body).toBe("<svg>brand-obj-order</svg>");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import http from "node:http";
|
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
|
||||||
".png": "image/png",
|
|
||||||
".jpg": "image/jpeg",
|
|
||||||
".svg": "image/svg+xml",
|
|
||||||
".ico": "image/x-icon",
|
|
||||||
};
|
|
||||||
|
|
||||||
// Well-known favicon paths checked in order.
|
|
||||||
const FAVICON_CANDIDATES = [
|
|
||||||
"favicon.svg",
|
|
||||||
"favicon.ico",
|
|
||||||
"favicon.png",
|
|
||||||
"public/favicon.svg",
|
|
||||||
"public/favicon.ico",
|
|
||||||
"public/favicon.png",
|
|
||||||
"app/favicon.ico",
|
|
||||||
"app/favicon.png",
|
|
||||||
"app/icon.svg",
|
|
||||||
"app/icon.png",
|
|
||||||
"app/icon.ico",
|
|
||||||
"src/favicon.ico",
|
|
||||||
"src/favicon.svg",
|
|
||||||
"src/app/favicon.ico",
|
|
||||||
"src/app/icon.svg",
|
|
||||||
"src/app/icon.png",
|
|
||||||
"assets/icon.svg",
|
|
||||||
"assets/icon.png",
|
|
||||||
"assets/logo.svg",
|
|
||||||
"assets/logo.png",
|
|
||||||
];
|
|
||||||
|
|
||||||
// Files that may contain a <link rel="icon"> or icon metadata declaration.
|
|
||||||
const ICON_SOURCE_FILES = [
|
|
||||||
"index.html",
|
|
||||||
"public/index.html",
|
|
||||||
"app/routes/__root.tsx",
|
|
||||||
"src/routes/__root.tsx",
|
|
||||||
"app/root.tsx",
|
|
||||||
"src/root.tsx",
|
|
||||||
"src/index.html",
|
|
||||||
];
|
|
||||||
|
|
||||||
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
|
|
||||||
const LINK_ICON_HTML_RE =
|
|
||||||
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
|
|
||||||
const LINK_ICON_OBJ_RE =
|
|
||||||
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
|
|
||||||
|
|
||||||
function extractIconHref(source: string): string | null {
|
|
||||||
const htmlMatch = source.match(LINK_ICON_HTML_RE);
|
|
||||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
|
||||||
const objMatch = source.match(LINK_ICON_OBJ_RE);
|
|
||||||
if (objMatch?.[1]) return objMatch[1];
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveIconHref(projectCwd: string, href: string): string[] {
|
|
||||||
const clean = href.replace(/^\//, "");
|
|
||||||
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
|
||||||
}
|
|
||||||
|
|
||||||
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
|
|
||||||
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
|
|
||||||
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
||||||
}
|
|
||||||
|
|
||||||
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
|
||||||
const ext = path.extname(filePath).toLowerCase();
|
|
||||||
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
|
|
||||||
fs.readFile(filePath, (readErr, data) => {
|
|
||||||
if (readErr) {
|
|
||||||
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
||||||
res.end("Read error");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.writeHead(200, {
|
|
||||||
"Content-Type": contentType,
|
|
||||||
"Cache-Control": "public, max-age=3600",
|
|
||||||
});
|
|
||||||
res.end(data);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
|
||||||
if (url.pathname !== "/api/project-favicon") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectCwd = url.searchParams.get("cwd");
|
|
||||||
if (!projectCwd) {
|
|
||||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
||||||
res.end("Missing cwd parameter");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
|
|
||||||
if (index >= paths.length) {
|
|
||||||
onExhausted();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const candidate = paths[index]!;
|
|
||||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
|
||||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fs.stat(candidate, (err, stats) => {
|
|
||||||
if (err || !stats?.isFile()) {
|
|
||||||
tryResolvedPaths(paths, index + 1, onExhausted);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
serveFaviconFile(candidate, res);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const trySourceFiles = (index: number): void => {
|
|
||||||
if (index >= ICON_SOURCE_FILES.length) {
|
|
||||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
||||||
res.end("No favicon found");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
|
||||||
fs.readFile(sourceFile, "utf8", (err, content) => {
|
|
||||||
if (err) {
|
|
||||||
trySourceFiles(index + 1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const href = extractIconHref(content);
|
|
||||||
if (!href) {
|
|
||||||
trySourceFiles(index + 1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const candidates = resolveIconHref(projectCwd, href);
|
|
||||||
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const tryCandidates = (index: number): void => {
|
|
||||||
if (index >= FAVICON_CANDIDATES.length) {
|
|
||||||
trySourceFiles(0);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
|
|
||||||
if (!isPathWithinProject(projectCwd, candidate)) {
|
|
||||||
tryCandidates(index + 1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fs.stat(candidate, (err, stats) => {
|
|
||||||
if (err || !stats?.isFile()) {
|
|
||||||
tryCandidates(index + 1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
serveFaviconFile(candidate, res);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
tryCandidates(0);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
@@ -47,7 +47,6 @@ import {
|
|||||||
|
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
const asTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
|
||||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||||
@@ -565,7 +564,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: asProviderThreadId("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
};
|
};
|
||||||
@@ -613,7 +612,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: asProviderThreadId("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
toolKind: "command",
|
toolKind: "command",
|
||||||
title: "Command run",
|
title: "Command run",
|
||||||
@@ -625,7 +624,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: asProviderThreadId("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
delta: "hello",
|
delta: "hello",
|
||||||
},
|
},
|
||||||
@@ -635,7 +634,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
sessionId: session.sessionId,
|
sessionId: session.sessionId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
threadId: asProviderThreadId("thread-1"),
|
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||||
turnId: asTurnId("turn-1"),
|
turnId: asTurnId("turn-1"),
|
||||||
status: "completed",
|
status: "completed",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
|
|||||||
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
|
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
|
||||||
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
|
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
|
||||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||||
import { ProviderUnsupportedError } from "./provider/Errors";
|
|
||||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||||
@@ -36,7 +35,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
|||||||
|
|
||||||
export function makeServerProviderLayer(): Layer.Layer<
|
export function makeServerProviderLayer(): Layer.Layer<
|
||||||
ProviderService,
|
ProviderService,
|
||||||
ProviderUnsupportedError,
|
unknown,
|
||||||
SqlClient.SqlClient | ServerConfig
|
SqlClient.SqlClient | ServerConfig
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import fs from "node:fs";
|
|||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
||||||
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
|
import { Effect, Exit, Layer, PubSub, Scope, Stream } from "effect";
|
||||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||||
import { createServer } from "./wsServer";
|
import { createServer } from "./wsServer";
|
||||||
@@ -39,7 +38,7 @@ import type {
|
|||||||
TerminalWriteInput,
|
TerminalWriteInput,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager";
|
||||||
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||||
import { SqlClient } from "effect/unstable/sql";
|
import { SqlClient } from "effect/unstable/sql";
|
||||||
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
|
||||||
import { Open, type OpenShape } from "./open";
|
import { Open, type OpenShape } from "./open";
|
||||||
@@ -324,14 +323,14 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
async function createTestServer(
|
async function createTestServer(
|
||||||
options: {
|
options: {
|
||||||
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, never>;
|
persistenceLayer?: Layer.Layer<SqlClient.SqlClient, any>;
|
||||||
cwd?: string;
|
cwd?: string;
|
||||||
autoBootstrapProjectFromCwd?: boolean;
|
autoBootstrapProjectFromCwd?: boolean;
|
||||||
logWebSocketEvents?: boolean;
|
logWebSocketEvents?: boolean;
|
||||||
devUrl?: string;
|
devUrl?: string;
|
||||||
authToken?: string;
|
authToken?: string;
|
||||||
stateDir?: string;
|
stateDir?: string;
|
||||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
providerLayer?: Layer.Layer<ProviderService, unknown>;
|
||||||
open?: OpenShape;
|
open?: OpenShape;
|
||||||
gitManager?: GitManagerShape;
|
gitManager?: GitManagerShape;
|
||||||
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
||||||
@@ -449,117 +448,23 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
const ws = await connectWs(port);
|
const ws = await connectWs(port);
|
||||||
connections.push(ws);
|
connections.push(ws);
|
||||||
const welcome = (await waitForMessage(ws)) as WsPush; // welcome
|
await waitForMessage(ws); // welcome
|
||||||
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
|
||||||
expect(welcome.data).toEqual(
|
|
||||||
expect.objectContaining({
|
|
||||||
cwd: "/test/bootstrap-workspace",
|
|
||||||
projectName: "bootstrap-workspace",
|
|
||||||
bootstrapProjectId: expect.any(String),
|
|
||||||
bootstrapThreadId: expect.any(String),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
|
const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot);
|
||||||
expect(snapshotResponse.error).toBeUndefined();
|
expect(snapshotResponse.error).toBeUndefined();
|
||||||
const snapshot = snapshotResponse.result as {
|
const snapshot = snapshotResponse.result as {
|
||||||
projects: Array<{
|
projects: Array<{ workspaceRoot: string; title: string; defaultModel: string | null }>;
|
||||||
id: string;
|
|
||||||
workspaceRoot: string;
|
|
||||||
title: string;
|
|
||||||
defaultModel: string | null;
|
|
||||||
}>;
|
|
||||||
threads: Array<{
|
|
||||||
id: string;
|
|
||||||
projectId: string;
|
|
||||||
title: string;
|
|
||||||
model: string;
|
|
||||||
branch: string | null;
|
|
||||||
worktreePath: string | null;
|
|
||||||
}>;
|
|
||||||
};
|
};
|
||||||
const bootstrapProjectId = (welcome.data as { bootstrapProjectId?: string }).bootstrapProjectId;
|
|
||||||
const bootstrapThreadId = (welcome.data as { bootstrapThreadId?: string }).bootstrapThreadId;
|
|
||||||
expect(bootstrapProjectId).toBeDefined();
|
|
||||||
expect(bootstrapThreadId).toBeDefined();
|
|
||||||
|
|
||||||
expect(snapshot.projects).toEqual(
|
expect(snapshot.projects).toEqual(
|
||||||
expect.arrayContaining([
|
expect.arrayContaining([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
id: bootstrapProjectId,
|
|
||||||
workspaceRoot: "/test/bootstrap-workspace",
|
workspaceRoot: "/test/bootstrap-workspace",
|
||||||
title: "bootstrap-workspace",
|
title: "bootstrap-workspace",
|
||||||
defaultModel: "gpt-5-codex",
|
defaultModel: "gpt-5-codex",
|
||||||
}),
|
}),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
expect(snapshot.threads).toEqual(
|
|
||||||
expect.arrayContaining([
|
|
||||||
expect.objectContaining({
|
|
||||||
id: bootstrapThreadId,
|
|
||||||
projectId: bootstrapProjectId,
|
|
||||||
title: "New thread",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
branch: null,
|
|
||||||
worktreePath: null,
|
|
||||||
}),
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
|
|
||||||
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
|
|
||||||
const persistenceLayer = makeSqlitePersistenceLive(
|
|
||||||
path.join(stateDir, "state.sqlite"),
|
|
||||||
).pipe(Layer.provide(NodeServices.layer)) as unknown as Layer.Layer<SqlClient.SqlClient, never>;
|
|
||||||
const cwd = "/test/bootstrap-existing";
|
|
||||||
|
|
||||||
server = await createTestServer({
|
|
||||||
cwd,
|
|
||||||
stateDir,
|
|
||||||
persistenceLayer,
|
|
||||||
autoBootstrapProjectFromCwd: true,
|
|
||||||
});
|
|
||||||
let addr = server.address();
|
|
||||||
let port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
||||||
expect(port).toBeGreaterThan(0);
|
|
||||||
|
|
||||||
const firstWs = await connectWs(port);
|
|
||||||
connections.push(firstWs);
|
|
||||||
const firstWelcome = (await waitForMessage(firstWs)) as WsPush;
|
|
||||||
const firstBootstrapProjectId = (firstWelcome.data as { bootstrapProjectId?: string })
|
|
||||||
.bootstrapProjectId;
|
|
||||||
const firstBootstrapThreadId = (firstWelcome.data as { bootstrapThreadId?: string })
|
|
||||||
.bootstrapThreadId;
|
|
||||||
expect(firstBootstrapProjectId).toBeDefined();
|
|
||||||
expect(firstBootstrapThreadId).toBeDefined();
|
|
||||||
|
|
||||||
firstWs.close();
|
|
||||||
await closeTestServer();
|
|
||||||
server = null;
|
|
||||||
|
|
||||||
server = await createTestServer({
|
|
||||||
cwd,
|
|
||||||
stateDir,
|
|
||||||
persistenceLayer,
|
|
||||||
autoBootstrapProjectFromCwd: true,
|
|
||||||
});
|
|
||||||
addr = server.address();
|
|
||||||
port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
||||||
expect(port).toBeGreaterThan(0);
|
|
||||||
|
|
||||||
const secondWs = await connectWs(port);
|
|
||||||
connections.push(secondWs);
|
|
||||||
const secondWelcome = (await waitForMessage(secondWs)) as WsPush;
|
|
||||||
expect(secondWelcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
|
||||||
expect(secondWelcome.data).toEqual(
|
|
||||||
expect.objectContaining({
|
|
||||||
cwd,
|
|
||||||
projectName: "bootstrap-existing",
|
|
||||||
bootstrapProjectId: firstBootstrapProjectId,
|
|
||||||
bootstrapThreadId: firstBootstrapThreadId,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("logs outbound websocket push events in dev mode", async () => {
|
it("logs outbound websocket push events in dev mode", async () => {
|
||||||
@@ -1054,9 +959,6 @@ describe("WebSocket Server", () => {
|
|||||||
text: "hello",
|
text: "hello",
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
assistantDeliveryMode: "streaming",
|
|
||||||
approvalPolicy: "on-request",
|
|
||||||
sandboxMode: "workspace-write",
|
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
expect(startTurnResponse.error).toBeUndefined();
|
expect(startTurnResponse.error).toBeUndefined();
|
||||||
|
|||||||
+22
-85
@@ -16,7 +16,6 @@ import {
|
|||||||
ORCHESTRATION_WS_CHANNELS,
|
ORCHESTRATION_WS_CHANNELS,
|
||||||
ORCHESTRATION_WS_METHODS,
|
ORCHESTRATION_WS_METHODS,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
|
||||||
TerminalEvent,
|
TerminalEvent,
|
||||||
WS_CHANNELS,
|
WS_CHANNELS,
|
||||||
WS_METHODS,
|
WS_METHODS,
|
||||||
@@ -42,7 +41,6 @@ import { clamp } from "effect/Number";
|
|||||||
import { Open } from "./open";
|
import { Open } from "./open";
|
||||||
import { ServerConfig } from "./config";
|
import { ServerConfig } from "./config";
|
||||||
import { GitCore } from "./git/Services/GitCore.ts";
|
import { GitCore } from "./git/Services/GitCore.ts";
|
||||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
|
||||||
|
|
||||||
const MIME_TYPES: Record<string, string> = {
|
const MIME_TYPES: Record<string, string> = {
|
||||||
".html": "text/html; charset=utf-8",
|
".html": "text/html; charset=utf-8",
|
||||||
@@ -68,14 +66,14 @@ export interface ServerShape {
|
|||||||
*/
|
*/
|
||||||
readonly start: Effect.Effect<
|
readonly start: Effect.Effect<
|
||||||
http.Server,
|
http.Server,
|
||||||
ServerLifecycleError,
|
unknown,
|
||||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wait for process shutdown signals.
|
* Wait for process shutdown signals.
|
||||||
*/
|
*/
|
||||||
readonly stopSignal: Effect.Effect<void, never>;
|
readonly stopSignal: Effect.Effect<unknown, never>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -167,7 +165,7 @@ class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("Ro
|
|||||||
|
|
||||||
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||||
http.Server,
|
http.Server,
|
||||||
ServerLifecycleError,
|
unknown, // TODO: This should not be unknown
|
||||||
Scope.Scope | ServerRuntimeServices | ServerConfig
|
Scope.Scope | ServerRuntimeServices | ServerConfig
|
||||||
> {
|
> {
|
||||||
const serverConfig = yield* ServerConfig;
|
const serverConfig = yield* ServerConfig;
|
||||||
@@ -233,12 +231,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
// HTTP server — serves static files or redirects to Vite dev server
|
// HTTP server — serves static files or redirects to Vite dev server
|
||||||
const httpServer = http.createServer((req, res) => {
|
const httpServer = http.createServer((req, res) => {
|
||||||
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
|
||||||
|
|
||||||
if (tryHandleProjectFaviconRequest(url, res)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// In dev mode, redirect to Vite dev server
|
// In dev mode, redirect to Vite dev server
|
||||||
if (devUrl) {
|
if (devUrl) {
|
||||||
res.writeHead(302, { Location: devUrl.href });
|
res.writeHead(302, { Location: devUrl.href });
|
||||||
@@ -253,6 +245,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
||||||
let filePath = path.join(staticDir, url.pathname);
|
let filePath = path.join(staticDir, url.pathname);
|
||||||
|
|
||||||
// SPA fallback: if no file extension and not found, serve index.html
|
// SPA fallback: if no file extension and not found, serve index.html
|
||||||
@@ -344,65 +337,22 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
|
||||||
|
|
||||||
let welcomeBootstrapProjectId: ProjectId | undefined;
|
|
||||||
let welcomeBootstrapThreadId: ThreadId | undefined;
|
|
||||||
|
|
||||||
if (autoBootstrapProjectFromCwd) {
|
if (autoBootstrapProjectFromCwd) {
|
||||||
yield* Effect.gen(function* () {
|
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
||||||
const snapshot = yield* projectionReadModelQuery.getSnapshot();
|
const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd);
|
||||||
const existingProject = snapshot.projects.find(
|
if (!existing) {
|
||||||
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
|
const createdAt = new Date().toISOString();
|
||||||
);
|
const projectName = path.basename(cwd) || "project";
|
||||||
let bootstrapProjectId: ProjectId;
|
yield* orchestrationEngine.dispatch({
|
||||||
let bootstrapProjectDefaultModel: string;
|
type: "project.create",
|
||||||
|
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||||
if (!existingProject) {
|
projectId: ProjectId.makeUnsafe(crypto.randomUUID()),
|
||||||
const createdAt = new Date().toISOString();
|
title: projectName,
|
||||||
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
workspaceRoot: cwd,
|
||||||
const bootstrapProjectTitle = path.basename(cwd) || "project";
|
defaultModel: "gpt-5-codex",
|
||||||
bootstrapProjectDefaultModel = "gpt-5-codex";
|
createdAt,
|
||||||
yield* orchestrationEngine.dispatch({
|
});
|
||||||
type: "project.create",
|
}
|
||||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
|
||||||
projectId: bootstrapProjectId,
|
|
||||||
title: bootstrapProjectTitle,
|
|
||||||
workspaceRoot: cwd,
|
|
||||||
defaultModel: bootstrapProjectDefaultModel,
|
|
||||||
createdAt,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
bootstrapProjectId = existingProject.id;
|
|
||||||
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingThread = snapshot.threads.find(
|
|
||||||
(thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
|
|
||||||
);
|
|
||||||
if (!existingThread) {
|
|
||||||
const createdAt = new Date().toISOString();
|
|
||||||
const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
|
|
||||||
yield* orchestrationEngine.dispatch({
|
|
||||||
type: "thread.create",
|
|
||||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
|
||||||
threadId,
|
|
||||||
projectId: bootstrapProjectId,
|
|
||||||
title: "New thread",
|
|
||||||
model: bootstrapProjectDefaultModel,
|
|
||||||
branch: null,
|
|
||||||
worktreePath: null,
|
|
||||||
createdAt,
|
|
||||||
});
|
|
||||||
welcomeBootstrapProjectId = bootstrapProjectId;
|
|
||||||
welcomeBootstrapThreadId = threadId;
|
|
||||||
} else {
|
|
||||||
welcomeBootstrapProjectId = bootstrapProjectId;
|
|
||||||
welcomeBootstrapThreadId = existingThread.id;
|
|
||||||
}
|
|
||||||
}).pipe(
|
|
||||||
Effect.mapError(
|
|
||||||
(cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
|
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
|
||||||
@@ -439,13 +389,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
case WS_METHODS.projectsSearchEntries: {
|
case WS_METHODS.projectsSearchEntries: {
|
||||||
const body = stripRequestTag(request.body);
|
const body = stripRequestTag(request.body);
|
||||||
return yield* Effect.tryPromise({
|
return yield* Effect.promise(() => searchWorkspaceEntries(body));
|
||||||
try: () => searchWorkspaceEntries(body),
|
|
||||||
catch: (cause) =>
|
|
||||||
new RouteRequestError({
|
|
||||||
message: `Failed to search workspace entries: ${String(cause)}`,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case WS_METHODS.shellOpenInEditor: {
|
case WS_METHODS.shellOpenInEditor: {
|
||||||
@@ -625,12 +569,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
const welcome: WsPush = {
|
const welcome: WsPush = {
|
||||||
type: "push",
|
type: "push",
|
||||||
channel: WS_CHANNELS.serverWelcome,
|
channel: WS_CHANNELS.serverWelcome,
|
||||||
data: {
|
data: { cwd, projectName },
|
||||||
cwd,
|
|
||||||
projectName,
|
|
||||||
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
|
|
||||||
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
logOutgoingPush(welcome, 1);
|
logOutgoingPush(welcome, 1);
|
||||||
ws.send(JSON.stringify(welcome));
|
ws.send(JSON.stringify(welcome));
|
||||||
@@ -673,9 +612,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
);
|
);
|
||||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||||
|
|
||||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
yield* NodeHttpServer.make(() => httpServer, listenOptions);
|
||||||
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
|
|
||||||
);
|
|
||||||
|
|
||||||
yield* Effect.addFinalizer(() =>
|
yield* Effect.addFinalizer(() =>
|
||||||
Effect.all([
|
Effect.all([
|
||||||
|
|||||||
@@ -14,9 +14,7 @@
|
|||||||
"importFromBarrel": "error",
|
"importFromBarrel": "error",
|
||||||
"anyUnknownInErrorContext": "warning",
|
"anyUnknownInErrorContext": "warning",
|
||||||
"instanceOfSchema": "warning",
|
"instanceOfSchema": "warning",
|
||||||
"deterministicKeys": "warning",
|
"deterministicKeys": "warning"
|
||||||
"preferSchemaOverJson": "off",
|
|
||||||
"globalErrorInEffectFailure": "off"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -11,9 +11,6 @@ const AppSettingsSchema = Schema.Struct({
|
|||||||
Schema.withConstructorDefault(() => Option.some("")),
|
Schema.withConstructorDefault(() => Option.some("")),
|
||||||
),
|
),
|
||||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
|
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
|
||||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
|
||||||
Schema.withConstructorDefault(() => Option.some(false)),
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||||
|
|
||||||
|
|||||||
@@ -43,8 +43,7 @@ import {
|
|||||||
deriveTimelineEntries,
|
deriveTimelineEntries,
|
||||||
type PendingApproval,
|
type PendingApproval,
|
||||||
deriveWorkLogEntries,
|
deriveWorkLogEntries,
|
||||||
hasToolActivityForTurn,
|
formatDuration,
|
||||||
isLatestTurnSettled,
|
|
||||||
formatElapsed,
|
formatElapsed,
|
||||||
formatTimestamp,
|
formatTimestamp,
|
||||||
} from "../session-logic";
|
} from "../session-logic";
|
||||||
@@ -54,7 +53,6 @@ import { truncateTitle } from "../truncateTitle";
|
|||||||
import {
|
import {
|
||||||
DEFAULT_THREAD_TERMINAL_ID,
|
DEFAULT_THREAD_TERMINAL_ID,
|
||||||
MAX_THREAD_TERMINAL_COUNT,
|
MAX_THREAD_TERMINAL_COUNT,
|
||||||
type ChatMessage,
|
|
||||||
type ChatImageAttachment,
|
type ChatImageAttachment,
|
||||||
type TurnDiffSummary,
|
type TurnDiffSummary,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
@@ -84,8 +82,6 @@ import {
|
|||||||
LockOpenIcon,
|
LockOpenIcon,
|
||||||
Undo2Icon,
|
Undo2Icon,
|
||||||
XIcon,
|
XIcon,
|
||||||
CopyIcon,
|
|
||||||
CheckIcon,
|
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
|
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
|
||||||
@@ -95,7 +91,6 @@ import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"
|
|||||||
import { CursorIcon, Icon } from "./Icons";
|
import { CursorIcon, Icon } from "./Icons";
|
||||||
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||||
import { Badge } from "./ui/badge";
|
import { Badge } from "./ui/badge";
|
||||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
|
||||||
import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
|
import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
|
||||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||||
@@ -110,7 +105,6 @@ import { Toggle } from "./ui/toggle";
|
|||||||
import { SidebarTrigger } from "./ui/sidebar";
|
import { SidebarTrigger } from "./ui/sidebar";
|
||||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||||
import { readNativeApi } from "~/nativeApi";
|
import { readNativeApi } from "~/nativeApi";
|
||||||
import { useAppSettings } from "../appSettings";
|
|
||||||
|
|
||||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||||
if (!duration) return formatTimestamp(createdAt);
|
if (!duration) return formatTimestamp(createdAt);
|
||||||
@@ -193,8 +187,6 @@ type ComposerCommandItem =
|
|||||||
description: string;
|
description: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
|
|
||||||
|
|
||||||
function readFileAsDataUrl(file: File): Promise<string> {
|
function readFileAsDataUrl(file: File): Promise<string> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
@@ -336,7 +328,6 @@ interface ChatViewProps {
|
|||||||
|
|
||||||
export default function ChatView({ threadId }: ChatViewProps) {
|
export default function ChatView({ threadId }: ChatViewProps) {
|
||||||
const { state, dispatch } = useStore();
|
const { state, dispatch } = useStore();
|
||||||
const { settings } = useAppSettings();
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const rawSearch = useSearch({
|
const rawSearch = useSearch({
|
||||||
strict: false,
|
strict: false,
|
||||||
@@ -350,9 +341,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
|
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
|
||||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||||
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
|
const [isSending, setIsSending] = useState(false);
|
||||||
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
|
const [isConnecting, setIsConnecting] = useState(false);
|
||||||
const [isConnecting, _setIsConnecting] = useState(false);
|
|
||||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||||
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
|
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
|
||||||
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
|
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
|
||||||
@@ -371,7 +361,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
const composerCommandInputRef = useRef<HTMLInputElement>(null);
|
const composerCommandInputRef = useRef<HTMLInputElement>(null);
|
||||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||||
const sendInFlightRef = useRef(false);
|
|
||||||
const dragDepthRef = useRef(0);
|
const dragDepthRef = useRef(0);
|
||||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||||
|
|
||||||
@@ -382,15 +371,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
);
|
);
|
||||||
const diffOpen = diffSearch.diff === "1";
|
const diffOpen = diffSearch.diff === "1";
|
||||||
const activeThreadId = activeThread?.id ?? null;
|
const activeThreadId = activeThread?.id ?? null;
|
||||||
const activeLatestTurn = activeThread?.latestTurn ?? null;
|
|
||||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
|
||||||
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
|
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!activeThread?.id) return;
|
if (!activeThread?.id) return;
|
||||||
if (!latestTurnSettled) return;
|
if (!activeThread.latestTurnCompletedAt) return;
|
||||||
if (!activeLatestTurn?.completedAt) return;
|
const turnCompletedAt = Date.parse(activeThread.latestTurnCompletedAt);
|
||||||
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
|
|
||||||
if (Number.isNaN(turnCompletedAt)) return;
|
if (Number.isNaN(turnCompletedAt)) return;
|
||||||
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
|
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
|
||||||
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
|
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
|
||||||
@@ -402,8 +388,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
}, [
|
}, [
|
||||||
activeThread?.id,
|
activeThread?.id,
|
||||||
activeThread?.lastVisitedAt,
|
activeThread?.lastVisitedAt,
|
||||||
activeLatestTurn?.completedAt,
|
activeThread?.latestTurnCompletedAt,
|
||||||
latestTurnSettled,
|
|
||||||
dispatch,
|
dispatch,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -411,37 +396,29 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||||
);
|
);
|
||||||
const phase = derivePhase(activeThread?.session ?? null);
|
const phase = derivePhase(activeThread?.session ?? null);
|
||||||
const isSendBusy = sendPhase !== "idle";
|
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
|
||||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
|
||||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
|
||||||
const nowIso = new Date(nowTick).toISOString();
|
const nowIso = new Date(nowTick).toISOString();
|
||||||
const threadActivities = activeThread?.activities ?? [];
|
const threadActivities = activeThread?.activities ?? [];
|
||||||
const workLogEntries = useMemo(
|
const workLogEntries = useMemo(
|
||||||
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
() => deriveWorkLogEntries(threadActivities, undefined),
|
||||||
[activeLatestTurn?.turnId, threadActivities],
|
[threadActivities],
|
||||||
);
|
);
|
||||||
const latestTurnHasToolActivity = useMemo(() => {
|
const latestTurnHasToolActivity = useMemo(() => {
|
||||||
return hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId);
|
const latestTurnId = activeThread?.latestTurnId;
|
||||||
}, [activeLatestTurn?.turnId, threadActivities]);
|
if (!latestTurnId) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return threadActivities.some(
|
||||||
|
(activity) => activity.turnId === latestTurnId && activity.tone === "tool",
|
||||||
|
);
|
||||||
|
}, [activeThread?.latestTurnId, threadActivities]);
|
||||||
const pendingApprovals = useMemo(
|
const pendingApprovals = useMemo(
|
||||||
() => derivePendingApprovals(threadActivities),
|
() => derivePendingApprovals(threadActivities),
|
||||||
[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(
|
const timelineEntries = useMemo(
|
||||||
() => deriveTimelineEntries(timelineMessages, workLogEntries),
|
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
|
||||||
[timelineMessages, workLogEntries],
|
[activeThread?.messages, workLogEntries],
|
||||||
);
|
);
|
||||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||||
useTurnDiffSummaries(activeThread);
|
useTurnDiffSummaries(activeThread);
|
||||||
@@ -487,27 +464,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
|
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
|
||||||
|
|
||||||
const completionSummary = useMemo(() => {
|
const completionSummary = useMemo(() => {
|
||||||
if (!latestTurnSettled) return null;
|
if (!activeThread?.latestTurnStartedAt) return null;
|
||||||
if (!activeLatestTurn?.startedAt) return null;
|
if (!activeThread.latestTurnCompletedAt) return null;
|
||||||
if (!activeLatestTurn.completedAt) return null;
|
|
||||||
if (!latestTurnHasToolActivity) return null;
|
if (!latestTurnHasToolActivity) return null;
|
||||||
|
|
||||||
const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt);
|
if (
|
||||||
|
typeof activeThread.latestTurnDurationMs === "number" &&
|
||||||
|
Number.isFinite(activeThread.latestTurnDurationMs) &&
|
||||||
|
activeThread.latestTurnDurationMs >= 0
|
||||||
|
) {
|
||||||
|
return `Worked for ${formatDuration(activeThread.latestTurnDurationMs)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const elapsed = formatElapsed(
|
||||||
|
activeThread.latestTurnStartedAt,
|
||||||
|
activeThread.latestTurnCompletedAt,
|
||||||
|
);
|
||||||
return elapsed ? `Worked for ${elapsed}` : null;
|
return elapsed ? `Worked for ${elapsed}` : null;
|
||||||
}, [
|
}, [
|
||||||
activeLatestTurn?.completedAt,
|
activeThread?.latestTurnStartedAt,
|
||||||
activeLatestTurn?.startedAt,
|
activeThread?.latestTurnCompletedAt,
|
||||||
|
activeThread?.latestTurnDurationMs,
|
||||||
latestTurnHasToolActivity,
|
latestTurnHasToolActivity,
|
||||||
latestTurnSettled,
|
|
||||||
]);
|
]);
|
||||||
const completionDividerBeforeEntryId = useMemo(() => {
|
const completionDividerBeforeEntryId = useMemo(() => {
|
||||||
if (!latestTurnSettled) return null;
|
if (!activeThread?.latestTurnStartedAt) return null;
|
||||||
if (!activeLatestTurn?.startedAt) return null;
|
if (!activeThread.latestTurnCompletedAt) return null;
|
||||||
if (!activeLatestTurn.completedAt) return null;
|
|
||||||
if (!completionSummary) return null;
|
if (!completionSummary) return null;
|
||||||
|
|
||||||
const turnStartedAt = Date.parse(activeLatestTurn.startedAt);
|
const turnStartedAt = Date.parse(activeThread.latestTurnStartedAt);
|
||||||
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
|
const turnCompletedAt = Date.parse(activeThread.latestTurnCompletedAt);
|
||||||
if (Number.isNaN(turnStartedAt)) return null;
|
if (Number.isNaN(turnStartedAt)) return null;
|
||||||
if (Number.isNaN(turnCompletedAt)) return null;
|
if (Number.isNaN(turnCompletedAt)) return null;
|
||||||
|
|
||||||
@@ -525,10 +511,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
}
|
}
|
||||||
return inRangeMatch ?? fallbackMatch;
|
return inRangeMatch ?? fallbackMatch;
|
||||||
}, [
|
}, [
|
||||||
activeLatestTurn?.completedAt,
|
activeThread?.latestTurnCompletedAt,
|
||||||
activeLatestTurn?.startedAt,
|
activeThread?.latestTurnStartedAt,
|
||||||
completionSummary,
|
completionSummary,
|
||||||
latestTurnSettled,
|
|
||||||
timelineEntries,
|
timelineEntries,
|
||||||
]);
|
]);
|
||||||
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
||||||
@@ -630,21 +615,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
() => shortcutLabelForCommand(keybindings, "terminal.close"),
|
() => shortcutLabelForCommand(keybindings, "terminal.close"),
|
||||||
[keybindings],
|
[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(
|
const envLocked = Boolean(
|
||||||
activeThread &&
|
activeThread &&
|
||||||
@@ -974,7 +944,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
}, [lastInvokedScriptByProjectId]);
|
}, [lastInvokedScriptByProjectId]);
|
||||||
|
|
||||||
// Auto-scroll on new messages
|
// Auto-scroll on new messages
|
||||||
const messageCount = timelineMessages.length;
|
const messageCount = activeThread?.messages.length ?? 0;
|
||||||
const workLogCount = workLogEntries.length;
|
const workLogCount = workLogEntries.length;
|
||||||
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
|
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
|
||||||
const scrollContainer = messagesScrollRef.current;
|
const scrollContainer = messagesScrollRef.current;
|
||||||
@@ -1033,30 +1003,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
composerImagesRef.current = composerImages;
|
composerImagesRef.current = composerImages;
|
||||||
}, [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(() => {
|
useEffect(() => {
|
||||||
setComposerImages((existing) => {
|
setComposerImages((existing) => {
|
||||||
revokePreviewUrls(existing);
|
revokePreviewUrls(existing);
|
||||||
return [];
|
return [];
|
||||||
});
|
});
|
||||||
setOptimisticUserMessages([]);
|
|
||||||
setPrompt("");
|
setPrompt("");
|
||||||
promptRef.current = "";
|
promptRef.current = "";
|
||||||
setSendPhase("idle");
|
setIsSending(false);
|
||||||
setComposerCursor(0);
|
setComposerCursor(0);
|
||||||
setComposerHighlightedItemId(null);
|
setComposerHighlightedItemId(null);
|
||||||
dragDepthRef.current = 0;
|
dragDepthRef.current = 0;
|
||||||
@@ -1193,13 +1147,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (command === "diff.toggle") {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
onToggleDiff();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const scriptId = projectScriptIdFromCommand(command);
|
const scriptId = projectScriptIdFromCommand(command);
|
||||||
if (!scriptId || !activeProject) return;
|
if (!scriptId || !activeProject) return;
|
||||||
const script = activeProject.scripts.find((entry) => entry.id === scriptId);
|
const script = activeProject.scripts.find((entry) => entry.id === scriptId);
|
||||||
@@ -1221,7 +1168,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
runProjectScript,
|
runProjectScript,
|
||||||
splitTerminal,
|
splitTerminal,
|
||||||
keybindings,
|
keybindings,
|
||||||
onToggleDiff,
|
|
||||||
toggleTerminalVisibility,
|
toggleTerminalVisibility,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -1345,7 +1291,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!api || !activeThread || isRevertingCheckpoint) return;
|
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.");
|
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1379,122 +1325,84 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
setIsRevertingCheckpoint(false);
|
setIsRevertingCheckpoint(false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
|
[activeThread, isConnecting, isRevertingCheckpoint, isSending, phase, setThreadError],
|
||||||
);
|
);
|
||||||
|
|
||||||
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
|
const onSend = async (e: React.SubmitEvent | React.KeyboardEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
|
if (!api || !activeThread || isSending || isConnecting) return;
|
||||||
const trimmed = prompt.trim();
|
const trimmed = prompt.trim();
|
||||||
if (!trimmed && composerImages.length === 0) return;
|
if (!trimmed && composerImages.length === 0) return;
|
||||||
if (!activeProject) return;
|
if (!activeProject) return;
|
||||||
const threadIdForSend = activeThread.id;
|
const composerImagesSnapshot = [...composerImages];
|
||||||
const isFirstMessage = activeThread.messages.length === 0;
|
|
||||||
const baseBranchForWorktree =
|
|
||||||
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
|
|
||||||
? activeThread.branch
|
|
||||||
: null;
|
|
||||||
|
|
||||||
// In worktree mode, require an explicit base branch so we don't silently
|
// On first message: lock in branch + create worktree if needed.
|
||||||
// fall back to local execution when branch selection is missing.
|
if (
|
||||||
const shouldCreateWorktree =
|
activeThread.messages.length === 0 &&
|
||||||
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;
|
activeThread.branch &&
|
||||||
if (shouldCreateWorktree && !activeThread.branch) {
|
envMode === "worktree" &&
|
||||||
dispatch({
|
!activeThread.worktreePath
|
||||||
type: "SET_ERROR",
|
) {
|
||||||
threadId: threadIdForSend,
|
try {
|
||||||
error: "Select a base branch before sending in New worktree mode.",
|
const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`;
|
||||||
});
|
const result = await createWorktreeMutation.mutateAsync({
|
||||||
return;
|
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;
|
// Auto-title from first message
|
||||||
setSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
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];
|
setThreadError(activeThread.id, null);
|
||||||
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);
|
|
||||||
promptRef.current = "";
|
promptRef.current = "";
|
||||||
setPrompt("");
|
setPrompt("");
|
||||||
setComposerImages([]);
|
setComposerImages([]);
|
||||||
setComposerCursor(0);
|
setComposerCursor(0);
|
||||||
setComposerHighlightedItemId(null);
|
setComposerHighlightedItemId(null);
|
||||||
|
|
||||||
let attemptedTurnStart = false;
|
setIsSending(true);
|
||||||
try {
|
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(
|
const turnAttachments = await Promise.all(
|
||||||
composerImagesSnapshot.map(
|
composerImagesSnapshot.map(
|
||||||
async (
|
async (
|
||||||
@@ -1514,48 +1422,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
attemptedTurnStart = true;
|
|
||||||
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
|
|
||||||
const sandboxMode =
|
|
||||||
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
|
|
||||||
await api.orchestration.dispatchCommand({
|
await api.orchestration.dispatchCommand({
|
||||||
type: "thread.turn.start",
|
type: "thread.turn.start",
|
||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
threadId: threadIdForSend,
|
threadId: activeThread.id,
|
||||||
message: {
|
message: {
|
||||||
messageId: messageIdForSend,
|
messageId: newMessageId(),
|
||||||
role: "user",
|
role: "user",
|
||||||
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||||
attachments: turnAttachments,
|
attachments: turnAttachments,
|
||||||
},
|
},
|
||||||
model: selectedModel || undefined,
|
model: selectedModel || undefined,
|
||||||
effort: selectedEffort || undefined,
|
effort: selectedEffort || undefined,
|
||||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
createdAt: new Date().toISOString(),
|
||||||
approvalPolicy,
|
|
||||||
sandboxMode,
|
|
||||||
createdAt: messageCreatedAt,
|
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} 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(
|
setThreadError(
|
||||||
threadIdForSend,
|
activeThread.id,
|
||||||
err instanceof Error ? err.message : "Failed to send message.",
|
err instanceof Error ? err.message : "Failed to send message.",
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
sendInFlightRef.current = false;
|
setIsSending(false);
|
||||||
setSendPhase("idle");
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1725,6 +1612,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => {
|
const onExpandTimelineImage = useCallback((image: ExpandedImagePreview) => {
|
||||||
setExpandedImage(image);
|
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(
|
const onOpenTurnDiff = useCallback(
|
||||||
(turnId: TurnId, filePath?: string) => {
|
(turnId: TurnId, filePath?: string) => {
|
||||||
void navigate({
|
void navigate({
|
||||||
@@ -1795,7 +1692,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
|
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
|
||||||
}
|
}
|
||||||
keybindings={keybindings}
|
keybindings={keybindings}
|
||||||
diffToggleShortcutLabel={diffPanelShortcutLabel}
|
|
||||||
gitCwd={gitCwd}
|
gitCwd={gitCwd}
|
||||||
diffOpen={diffOpen}
|
diffOpen={diffOpen}
|
||||||
onRunProjectScript={(script) => {
|
onRunProjectScript={(script) => {
|
||||||
@@ -1822,7 +1718,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
onScroll={onMessagesScroll}
|
onScroll={onMessagesScroll}
|
||||||
>
|
>
|
||||||
<MessagesTimeline
|
<MessagesTimeline
|
||||||
hasMessages={timelineMessages.length > 0}
|
hasMessages={activeThread.messages.length > 0}
|
||||||
isWorking={isWorking}
|
isWorking={isWorking}
|
||||||
scrollContainerRef={messagesScrollRef}
|
scrollContainerRef={messagesScrollRef}
|
||||||
timelineEntries={timelineEntries}
|
timelineEntries={timelineEntries}
|
||||||
@@ -1940,7 +1836,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
? "Ask for follow-up changes or attach images"
|
? "Ask for follow-up changes or attach images"
|
||||||
: "Ask anything, @tag files/folders, or use /model"
|
: "Ask anything, @tag files/folders, or use /model"
|
||||||
}
|
}
|
||||||
disabled={isConnecting}
|
disabled={isSending || isConnecting}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1986,9 +1882,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
|
|
||||||
{/* Right side: send / stop button */}
|
{/* Right side: send / stop button */}
|
||||||
<div className="flex shrink-0 items-center gap-2">
|
<div className="flex shrink-0 items-center gap-2">
|
||||||
{isPreparingWorktree ? (
|
|
||||||
<span className="text-muted-foreground/70 text-xs">Preparing worktree...</span>
|
|
||||||
) : null}
|
|
||||||
{phase === "running" ? (
|
{phase === "running" ? (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -2011,19 +1904,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
|||||||
type="submit"
|
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"
|
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={
|
disabled={
|
||||||
isSendBusy || isConnecting || (!prompt.trim() && composerImages.length === 0)
|
isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
|
||||||
}
|
}
|
||||||
aria-label={
|
aria-label={
|
||||||
isConnecting
|
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
|
||||||
? "Connecting"
|
|
||||||
: isPreparingWorktree
|
|
||||||
? "Preparing worktree"
|
|
||||||
: isSendBusy
|
|
||||||
? "Sending"
|
|
||||||
: "Send message"
|
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{isConnecting || isSendBusy ? (
|
{isConnecting || isSending ? (
|
||||||
<svg
|
<svg
|
||||||
width="14"
|
width="14"
|
||||||
height="14"
|
height="14"
|
||||||
@@ -2156,7 +2043,6 @@ interface ChatHeaderProps {
|
|||||||
activeProjectScripts: ProjectScript[] | undefined;
|
activeProjectScripts: ProjectScript[] | undefined;
|
||||||
preferredScriptId: string | null;
|
preferredScriptId: string | null;
|
||||||
keybindings: ResolvedKeybindingsConfig;
|
keybindings: ResolvedKeybindingsConfig;
|
||||||
diffToggleShortcutLabel: string | null;
|
|
||||||
gitCwd: string | null;
|
gitCwd: string | null;
|
||||||
diffOpen: boolean;
|
diffOpen: boolean;
|
||||||
onRunProjectScript: (script: ProjectScript) => void;
|
onRunProjectScript: (script: ProjectScript) => void;
|
||||||
@@ -2172,7 +2058,6 @@ const ChatHeader = memo(function ChatHeader({
|
|||||||
activeProjectScripts,
|
activeProjectScripts,
|
||||||
preferredScriptId,
|
preferredScriptId,
|
||||||
keybindings,
|
keybindings,
|
||||||
diffToggleShortcutLabel,
|
|
||||||
gitCwd,
|
gitCwd,
|
||||||
diffOpen,
|
diffOpen,
|
||||||
onRunProjectScript,
|
onRunProjectScript,
|
||||||
@@ -2211,27 +2096,16 @@ const ChatHeader = memo(function ChatHeader({
|
|||||||
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
|
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
|
||||||
)}
|
)}
|
||||||
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
|
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
|
||||||
<Tooltip>
|
<Toggle
|
||||||
<TooltipTrigger
|
className="shrink-0"
|
||||||
render={
|
pressed={diffOpen}
|
||||||
<Toggle
|
onPressedChange={onToggleDiff}
|
||||||
className="shrink-0"
|
aria-label="Toggle diff panel"
|
||||||
pressed={diffOpen}
|
variant="outline"
|
||||||
onPressedChange={onToggleDiff}
|
size="xs"
|
||||||
aria-label="Toggle diff panel"
|
>
|
||||||
variant="outline"
|
<DiffIcon className="size-3" />
|
||||||
size="xs"
|
</Toggle>
|
||||||
>
|
|
||||||
<DiffIcon className="size-3" />
|
|
||||||
</Toggle>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<TooltipPopup side="bottom">
|
|
||||||
{diffToggleShortcutLabel
|
|
||||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
|
||||||
: "Toggle diff panel"}
|
|
||||||
</TooltipPopup>
|
|
||||||
</Tooltip>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -2326,28 +2200,6 @@ const PendingApprovalsPanel = memo(function PendingApprovalsPanel({
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: string }) {
|
|
||||||
const [copied, setCopied] = useState(false);
|
|
||||||
|
|
||||||
const handleCopy = useCallback(() => {
|
|
||||||
void navigator.clipboard.writeText(text);
|
|
||||||
setCopied(true);
|
|
||||||
setTimeout(() => setCopied(false), 2000);
|
|
||||||
}, [text]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
onClick={handleCopy}
|
|
||||||
title="Copy message"
|
|
||||||
>
|
|
||||||
{copied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
interface MessagesTimelineProps {
|
interface MessagesTimelineProps {
|
||||||
hasMessages: boolean;
|
hasMessages: boolean;
|
||||||
isWorking: boolean;
|
isWorking: boolean;
|
||||||
@@ -2564,7 +2416,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
|
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-end">
|
<div className="flex justify-end">
|
||||||
<div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
||||||
{userImages.length > 0 && (
|
{userImages.length > 0 && (
|
||||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||||
{userImages.map(
|
{userImages.map(
|
||||||
@@ -2598,21 +2450,17 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
|||||||
</pre>
|
</pre>
|
||||||
)}
|
)}
|
||||||
<div className="mt-1.5 flex items-center justify-end gap-2">
|
<div className="mt-1.5 flex items-center justify-end gap-2">
|
||||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
{canRevertAgentWork && (
|
||||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
<Button
|
||||||
{canRevertAgentWork && (
|
type="button"
|
||||||
<Button
|
size="xs"
|
||||||
type="button"
|
variant="outline"
|
||||||
size="xs"
|
disabled={isRevertingCheckpoint || isWorking}
|
||||||
variant="outline"
|
onClick={() => onRevertUserMessage(row.message.id)}
|
||||||
disabled={isRevertingCheckpoint || isWorking}
|
>
|
||||||
onClick={() => onRevertUserMessage(row.message.id)}
|
<Undo2Icon className="size-3" />
|
||||||
title="Revert to this message"
|
</Button>
|
||||||
>
|
)}
|
||||||
<Undo2Icon className="size-3" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="text-right text-[10px] text-muted-foreground/30">
|
<p className="text-right text-[10px] text-muted-foreground/30">
|
||||||
{formatTimestamp(row.message.createdAt)}
|
{formatTimestamp(row.message.createdAt)}
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -16,11 +16,7 @@ import { useStore } from "../store";
|
|||||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||||
|
|
||||||
type DiffRenderMode = "stacked" | "split";
|
type DiffRenderMode = "stacked" | "split";
|
||||||
type DiffThemeType = "light" | "dark";
|
type DiffThemeType = "light" | "dark" | "system";
|
||||||
|
|
||||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
|
||||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
|
||||||
}
|
|
||||||
|
|
||||||
type RenderablePatch =
|
type RenderablePatch =
|
||||||
| {
|
| {
|
||||||
@@ -33,19 +29,13 @@ type RenderablePatch =
|
|||||||
reason: string;
|
reason: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function getRenderablePatch(
|
function getRenderablePatch(patch: string | undefined): RenderablePatch | null {
|
||||||
patch: string | undefined,
|
|
||||||
cacheScope = "diff-panel",
|
|
||||||
): RenderablePatch | null {
|
|
||||||
if (!patch) return null;
|
if (!patch) return null;
|
||||||
const normalizedPatch = patch.trim();
|
const normalizedPatch = patch.trim();
|
||||||
if (normalizedPatch.length === 0) return null;
|
if (normalizedPatch.length === 0) return null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const parsedPatches = parsePatchFiles(
|
const parsedPatches = parsePatchFiles(normalizedPatch, buildPatchCacheKey(normalizedPatch));
|
||||||
normalizedPatch,
|
|
||||||
buildPatchCacheKey(normalizedPatch, cacheScope),
|
|
||||||
);
|
|
||||||
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
|
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
|
||||||
if (files.length > 0) {
|
if (files.length > 0) {
|
||||||
return { kind: "files", files };
|
return { kind: "files", files };
|
||||||
@@ -200,10 +190,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
|
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
|
||||||
const hasResolvedPatch = typeof selectedPatch === "string";
|
const hasResolvedPatch = typeof selectedPatch === "string";
|
||||||
const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
|
const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
|
||||||
const renderablePatch = useMemo(
|
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
|
||||||
() => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
|
|
||||||
[resolvedTheme, selectedPatch],
|
|
||||||
);
|
|
||||||
const renderableFiles = useMemo(() => {
|
const renderableFiles = useMemo(() => {
|
||||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||||
return [];
|
return [];
|
||||||
@@ -476,15 +463,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
{renderableFiles.map((fileDiff) => {
|
{renderableFiles.map((fileDiff) => {
|
||||||
const filePath = resolveFileDiffPath(fileDiff);
|
const filePath = resolveFileDiffPath(fileDiff);
|
||||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
|
||||||
return (
|
return (
|
||||||
<div key={themedFileKey} data-diff-file-path={filePath} className="rounded-md">
|
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||||
<FileDiff
|
<FileDiff
|
||||||
fileDiff={fileDiff}
|
fileDiff={fileDiff}
|
||||||
options={{
|
options={{
|
||||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||||
lineDiffType: "none",
|
lineDiffType: "none",
|
||||||
theme: resolveDiffThemeName(resolvedTheme),
|
|
||||||
themeType: resolvedTheme as DiffThemeType,
|
themeType: resolvedTheme as DiffThemeType,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,39 +1,8 @@
|
|||||||
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
import { WorkerPoolContextProvider } from "@pierre/diffs/react";
|
||||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||||
import { useEffect, useMemo, type ReactNode } from "react";
|
import { useMemo, type ReactNode } from "react";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
|
||||||
|
|
||||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
|
||||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
|
||||||
}
|
|
||||||
|
|
||||||
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
|
|
||||||
const workerPool = useWorkerPool();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!workerPool) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const current = workerPool.getDiffRenderOptions();
|
|
||||||
if (current.theme === themeName) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void workerPool
|
|
||||||
.setRenderOptions({
|
|
||||||
...current,
|
|
||||||
theme: themeName,
|
|
||||||
})
|
|
||||||
.catch(() => undefined);
|
|
||||||
}, [themeName, workerPool]);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||||
const { resolvedTheme } = useTheme();
|
|
||||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
|
||||||
const workerPoolSize = useMemo(() => {
|
const workerPoolSize = useMemo(() => {
|
||||||
const cores =
|
const cores =
|
||||||
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||||
@@ -48,11 +17,9 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
|||||||
totalASTLRUCacheSize: 240,
|
totalASTLRUCacheSize: 240,
|
||||||
}}
|
}}
|
||||||
highlighterOptions={{
|
highlighterOptions={{
|
||||||
theme: diffThemeName,
|
|
||||||
tokenizeMaxLineLength: 1_000,
|
tokenizeMaxLineLength: 1_000,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DiffWorkerThemeSync themeName={diffThemeName} />
|
|
||||||
{children}
|
{children}
|
||||||
</WorkerPoolContextProvider>
|
</WorkerPoolContextProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
|
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 { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||||
import { GitHubIcon } from "./Icons";
|
import { GitHubIcon } from "./Icons";
|
||||||
@@ -33,7 +33,6 @@ import { toastManager } from "~/components/ui/toast";
|
|||||||
import {
|
import {
|
||||||
gitBranchesQueryOptions,
|
gitBranchesQueryOptions,
|
||||||
gitInitMutationOptions,
|
gitInitMutationOptions,
|
||||||
gitMutationKeys,
|
|
||||||
gitPullMutationOptions,
|
gitPullMutationOptions,
|
||||||
gitRunStackedActionMutationOptions,
|
gitRunStackedActionMutationOptions,
|
||||||
gitStatusQueryOptions,
|
gitStatusQueryOptions,
|
||||||
@@ -169,10 +168,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
);
|
);
|
||||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||||
|
|
||||||
const isRunStackedActionRunning =
|
const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
|
||||||
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
|
|
||||||
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
|
|
||||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
|
||||||
const isDefaultBranch = useMemo(() => {
|
const isDefaultBranch = useMemo(() => {
|
||||||
const branchName = gitStatusForActions?.branch;
|
const branchName = gitStatusForActions?.branch;
|
||||||
if (!branchName) return false;
|
if (!branchName) return false;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";
|
import { ChevronRightIcon, TerminalIcon } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
@@ -15,7 +15,6 @@ import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
|
|||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||||
import { type Thread } from "../types";
|
import { type Thread } from "../types";
|
||||||
import { derivePendingApprovals } from "../session-logic";
|
|
||||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
@@ -51,7 +50,7 @@ function formatRelativeTime(iso: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface ThreadStatusPill {
|
interface ThreadStatusPill {
|
||||||
label: "Working" | "Connecting" | "Completed" | "Pending Approval";
|
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
|
||||||
colorClass: string;
|
colorClass: string;
|
||||||
dotClass: string;
|
dotClass: string;
|
||||||
pulse: boolean;
|
pulse: boolean;
|
||||||
@@ -64,8 +63,8 @@ interface TerminalStatusIndicator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function hasUnseenCompletion(thread: Thread): boolean {
|
function hasUnseenCompletion(thread: Thread): boolean {
|
||||||
if (!thread.latestTurn?.completedAt) return false;
|
if (!thread.latestTurnCompletedAt) return false;
|
||||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
||||||
if (Number.isNaN(completedAt)) return false;
|
if (Number.isNaN(completedAt)) return false;
|
||||||
if (!thread.lastVisitedAt) return true;
|
if (!thread.lastVisitedAt) return true;
|
||||||
|
|
||||||
@@ -77,7 +76,7 @@ function hasUnseenCompletion(thread: Thread): boolean {
|
|||||||
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
|
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
|
||||||
if (hasPendingApprovals) {
|
if (hasPendingApprovals) {
|
||||||
return {
|
return {
|
||||||
label: "Pending Approval",
|
label: "Awaiting response",
|
||||||
colorClass: "text-amber-600 dark:text-amber-300/90",
|
colorClass: "text-amber-600 dark:text-amber-300/90",
|
||||||
dotClass: "bg-amber-500 dark:bg-amber-300/90",
|
dotClass: "bg-amber-500 dark:bg-amber-300/90",
|
||||||
pulse: false,
|
pulse: false,
|
||||||
@@ -141,50 +140,6 @@ function T3Wordmark() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Derives the server's HTTP origin (scheme + host + port) from the same
|
|
||||||
* sources WsTransport uses, converting ws(s) to http(s).
|
|
||||||
*/
|
|
||||||
function getServerHttpOrigin(): string {
|
|
||||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
|
||||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
|
||||||
const wsUrl =
|
|
||||||
bridgeUrl && bridgeUrl.length > 0
|
|
||||||
? bridgeUrl
|
|
||||||
: envUrl && envUrl.length > 0
|
|
||||||
? envUrl
|
|
||||||
: `ws://${window.location.hostname}:${window.location.port}`;
|
|
||||||
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
|
|
||||||
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
|
|
||||||
try {
|
|
||||||
return new URL(httpUrl).origin;
|
|
||||||
} catch {
|
|
||||||
return httpUrl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const serverHttpOrigin = getServerHttpOrigin();
|
|
||||||
|
|
||||||
function ProjectFavicon({ cwd }: { cwd: string }) {
|
|
||||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
|
|
||||||
|
|
||||||
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
|
|
||||||
|
|
||||||
if (status === "error") {
|
|
||||||
return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<img
|
|
||||||
src={src}
|
|
||||||
alt=""
|
|
||||||
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
|
|
||||||
onLoad={() => setStatus("loaded")}
|
|
||||||
onError={() => setStatus("error")}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
const { state, dispatch } = useStore();
|
const { state, dispatch } = useStore();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -203,13 +158,7 @@ export default function Sidebar() {
|
|||||||
const [newCwd, setNewCwd] = useState("");
|
const [newCwd, setNewCwd] = useState("");
|
||||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||||
const pendingApprovalByThreadId = useMemo(() => {
|
const pendingApprovalByThreadId = useMemo(() => new Map<ThreadId, boolean>(), []);
|
||||||
const map = new Map<ThreadId, boolean>();
|
|
||||||
for (const thread of state.threads) {
|
|
||||||
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
}, [state.threads]);
|
|
||||||
|
|
||||||
const handleNewThread = useCallback(
|
const handleNewThread = useCallback(
|
||||||
(
|
(
|
||||||
@@ -332,17 +281,7 @@ export default function Sidebar() {
|
|||||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!api) return;
|
if (!api) return;
|
||||||
const clicked = await api.contextMenu.show(
|
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
|
||||||
[
|
|
||||||
{ id: "mark-unread", label: "Mark unread" },
|
|
||||||
{ id: "delete", label: "Delete" },
|
|
||||||
],
|
|
||||||
position,
|
|
||||||
);
|
|
||||||
if (clicked === "mark-unread") {
|
|
||||||
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (clicked !== "delete") return;
|
if (clicked !== "delete") return;
|
||||||
|
|
||||||
const thread = state.threads.find((t) => t.id === threadId);
|
const thread = state.threads.find((t) => t.id === threadId);
|
||||||
@@ -441,7 +380,6 @@ export default function Sidebar() {
|
|||||||
},
|
},
|
||||||
[
|
[
|
||||||
appSettings.confirmThreadDelete,
|
appSettings.confirmThreadDelete,
|
||||||
dispatch,
|
|
||||||
navigate,
|
navigate,
|
||||||
removeWorktreeMutation,
|
removeWorktreeMutation,
|
||||||
routeThreadId,
|
routeThreadId,
|
||||||
@@ -617,7 +555,6 @@ export default function Sidebar() {
|
|||||||
project.expanded ? "rotate-90" : ""
|
project.expanded ? "rotate-90" : ""
|
||||||
}`}
|
}`}
|
||||||
/>
|
/>
|
||||||
<ProjectFavicon cwd={project.cwd} />
|
|
||||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||||
{project.name}
|
{project.name}
|
||||||
</span>
|
</span>
|
||||||
@@ -641,9 +578,7 @@ export default function Sidebar() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
isActive={isActive}
|
isActive={isActive}
|
||||||
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
||||||
isActive
|
isActive ? "text-foreground" : "text-muted-foreground"
|
||||||
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
|
|
||||||
: "text-muted-foreground"
|
|
||||||
}`}
|
}`}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
void navigate({
|
void navigate({
|
||||||
@@ -689,11 +624,7 @@ export default function Sidebar() {
|
|||||||
/>
|
/>
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<span
|
<span className="text-[10px] text-muted-foreground/40">
|
||||||
className={`text-[10px] ${
|
|
||||||
isActive ? "text-foreground/65" : "text-muted-foreground/40"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{formatRelativeTime(thread.createdAt)}
|
{formatRelativeTime(thread.createdAt)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
|||||||
const SIDEBAR_WIDTH = "16rem";
|
const SIDEBAR_WIDTH = "16rem";
|
||||||
const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
|
const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
|
||||||
const SIDEBAR_WIDTH_ICON = "3rem";
|
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||||
|
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||||
const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
|
const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
|
||||||
|
|
||||||
type SidebarContextProps = {
|
type SidebarContextProps = {
|
||||||
@@ -128,6 +129,19 @@ function SidebarProvider({
|
|||||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
|
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
|
||||||
}, [isMobile, setOpen]);
|
}, [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".
|
// 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.
|
// This makes it easier to style the sidebar with Tailwind classes.
|
||||||
const state = open ? "expanded" : "collapsed";
|
const state = open ? "expanded" : "collapsed";
|
||||||
|
|||||||
@@ -41,10 +41,8 @@ export function showContextMenuFallback<T extends string>(
|
|||||||
const btn = document.createElement("button");
|
const btn = document.createElement("button");
|
||||||
btn.type = "button";
|
btn.type = "button";
|
||||||
btn.textContent = item.label;
|
btn.textContent = item.label;
|
||||||
const isDeleteAction = item.id === "delete";
|
btn.className =
|
||||||
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-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.addEventListener("click", () => cleanup(item.id));
|
btn.addEventListener("click", () => cleanup(item.id));
|
||||||
menu.appendChild(btn);
|
menu.appendChild(btn);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,11 @@
|
|||||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||||
|
|
||||||
type Theme = "light" | "dark" | "system";
|
type Theme = "light" | "dark" | "system";
|
||||||
type ThemeSnapshot = {
|
|
||||||
theme: Theme;
|
|
||||||
systemDark: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
const STORAGE_KEY = "t3code:theme";
|
const STORAGE_KEY = "t3code:theme";
|
||||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||||
|
|
||||||
let listeners: Array<() => void> = [];
|
let listeners: Array<() => void> = [];
|
||||||
let lastSnapshot: ThemeSnapshot | null = null;
|
|
||||||
function emitChange() {
|
function emitChange() {
|
||||||
for (const listener of listeners) listener();
|
for (const listener of listeners) listener();
|
||||||
}
|
}
|
||||||
@@ -44,16 +39,8 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
|||||||
// Apply immediately on module load to prevent flash
|
// Apply immediately on module load to prevent flash
|
||||||
applyTheme(getStored());
|
applyTheme(getStored());
|
||||||
|
|
||||||
function getSnapshot(): ThemeSnapshot {
|
function getSnapshot(): Theme {
|
||||||
const theme = getStored();
|
return getStored();
|
||||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
|
||||||
|
|
||||||
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
|
|
||||||
return lastSnapshot;
|
|
||||||
}
|
|
||||||
|
|
||||||
lastSnapshot = { theme, systemDark };
|
|
||||||
return lastSnapshot;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function subscribe(listener: () => void): () => void {
|
function subscribe(listener: () => void): () => void {
|
||||||
@@ -84,11 +71,10 @@ function subscribe(listener: () => void): () => void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useTheme() {
|
export function useTheme() {
|
||||||
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
|
const theme = useSyncExternalStore(subscribe, getSnapshot);
|
||||||
const theme = snapshot.theme;
|
|
||||||
|
|
||||||
const resolvedTheme: "light" | "dark" =
|
const resolvedTheme: "light" | "dark" =
|
||||||
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
theme === "system" ? (getSystemDark() ? "dark" : "light") : theme;
|
||||||
|
|
||||||
const setTheme = useCallback((next: Theme) => {
|
const setTheme = useCallback((next: Theme) => {
|
||||||
localStorage.setItem(STORAGE_KEY, next);
|
localStorage.setItem(STORAGE_KEY, next);
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
formatShortcutLabel,
|
formatShortcutLabel,
|
||||||
isChatNewShortcut,
|
isChatNewShortcut,
|
||||||
isChatNewLocalShortcut,
|
isChatNewLocalShortcut,
|
||||||
isDiffToggleShortcut,
|
|
||||||
isOpenFavoriteEditorShortcut,
|
isOpenFavoriteEditorShortcut,
|
||||||
isTerminalClearShortcut,
|
isTerminalClearShortcut,
|
||||||
isTerminalCloseShortcut,
|
isTerminalCloseShortcut,
|
||||||
@@ -92,11 +91,6 @@ const DEFAULT_BINDINGS = compile([
|
|||||||
command: "terminal.close",
|
command: "terminal.close",
|
||||||
whenAst: whenIdentifier("terminalFocus"),
|
whenAst: whenIdentifier("terminalFocus"),
|
||||||
},
|
},
|
||||||
{
|
|
||||||
shortcut: modShortcut("d"),
|
|
||||||
command: "diff.toggle",
|
|
||||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
|
||||||
},
|
|
||||||
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
||||||
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
||||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
||||||
@@ -236,7 +230,6 @@ describe("shortcutLabelForCommand", () => {
|
|||||||
|
|
||||||
it("returns labels for non-terminal commands", () => {
|
it("returns labels for non-terminal commands", () => {
|
||||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
||||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
|
|
||||||
assert.strictEqual(
|
assert.strictEqual(
|
||||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
|
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
|
||||||
"Ctrl+O",
|
"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", () => {
|
describe("cross-command precedence", () => {
|
||||||
|
|||||||
@@ -198,14 +198,6 @@ export function isTerminalCloseShortcut(
|
|||||||
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
|
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(
|
export function isChatNewShortcut(
|
||||||
event: ShortcutEventLike,
|
event: ShortcutEventLike,
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
keybindings: ResolvedKeybindingsConfig,
|
||||||
|
|||||||
@@ -20,12 +20,4 @@ describe("buildPatchCacheKey", () => {
|
|||||||
|
|
||||||
expect(buildPatchCacheKey(before)).not.toBe(buildPatchCacheKey(after));
|
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"),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { QueryClient } from "@tanstack/react-query";
|
|
||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import {
|
|
||||||
gitMutationKeys,
|
|
||||||
gitPullMutationOptions,
|
|
||||||
gitRunStackedActionMutationOptions,
|
|
||||||
} from "./gitReactQuery";
|
|
||||||
|
|
||||||
describe("gitMutationKeys", () => {
|
|
||||||
it("scopes stacked action keys by cwd", () => {
|
|
||||||
expect(gitMutationKeys.runStackedAction("/repo/a")).not.toEqual(
|
|
||||||
gitMutationKeys.runStackedAction("/repo/b"),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("scopes pull keys by cwd", () => {
|
|
||||||
expect(gitMutationKeys.pull("/repo/a")).not.toEqual(gitMutationKeys.pull("/repo/b"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("git mutation options", () => {
|
|
||||||
const queryClient = new QueryClient();
|
|
||||||
|
|
||||||
it("attaches cwd-scoped mutation key for runStackedAction", () => {
|
|
||||||
const options = gitRunStackedActionMutationOptions({ cwd: "/repo/a", queryClient });
|
|
||||||
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("attaches cwd-scoped mutation key for pull", () => {
|
|
||||||
const options = gitPullMutationOptions({ cwd: "/repo/a", queryClient });
|
|
||||||
expect(options.mutationKey).toEqual(gitMutationKeys.pull("/repo/a"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { GitStackedAction } from "@t3tools/contracts";
|
import type { GitStackedAction } from "@t3tools/contracts";
|
||||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||||
import { ensureNativeApi } from "../nativeApi";
|
import { ensureNativeApi } from "~/nativeApi";
|
||||||
|
|
||||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
||||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
||||||
@@ -13,15 +13,6 @@ export const gitQueryKeys = {
|
|||||||
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
|
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
export const gitMutationKeys = {
|
|
||||||
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
|
||||||
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
|
||||||
createBranchAndCheckout: (cwd: string | null) =>
|
|
||||||
["git", "mutation", "create-branch-and-checkout", cwd] as const,
|
|
||||||
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
|
||||||
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function invalidateGitQueries(queryClient: QueryClient) {
|
export function invalidateGitQueries(queryClient: QueryClient) {
|
||||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
|
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
|
||||||
}
|
}
|
||||||
@@ -60,7 +51,6 @@ export function gitBranchesQueryOptions(cwd: string | null) {
|
|||||||
|
|
||||||
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
export function gitInitMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
||||||
return mutationOptions({
|
return mutationOptions({
|
||||||
mutationKey: gitMutationKeys.init(input.cwd),
|
|
||||||
mutationFn: async () => {
|
mutationFn: async () => {
|
||||||
const api = ensureNativeApi();
|
const api = ensureNativeApi();
|
||||||
if (!input.cwd) throw new Error("Git init is unavailable.");
|
if (!input.cwd) throw new Error("Git init is unavailable.");
|
||||||
@@ -77,7 +67,6 @@ export function gitCheckoutMutationOptions(input: {
|
|||||||
queryClient: QueryClient;
|
queryClient: QueryClient;
|
||||||
}) {
|
}) {
|
||||||
return mutationOptions({
|
return mutationOptions({
|
||||||
mutationKey: gitMutationKeys.checkout(input.cwd),
|
|
||||||
mutationFn: async (branch: string) => {
|
mutationFn: async (branch: string) => {
|
||||||
const api = ensureNativeApi();
|
const api = ensureNativeApi();
|
||||||
if (!input.cwd) throw new Error("Git checkout is unavailable.");
|
if (!input.cwd) throw new Error("Git checkout is unavailable.");
|
||||||
@@ -94,7 +83,6 @@ export function gitCreateBranchAndCheckoutMutationOptions(input: {
|
|||||||
queryClient: QueryClient;
|
queryClient: QueryClient;
|
||||||
}) {
|
}) {
|
||||||
return mutationOptions({
|
return mutationOptions({
|
||||||
mutationKey: gitMutationKeys.createBranchAndCheckout(input.cwd),
|
|
||||||
mutationFn: async (branch: string) => {
|
mutationFn: async (branch: string) => {
|
||||||
const api = ensureNativeApi();
|
const api = ensureNativeApi();
|
||||||
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
|
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
|
||||||
@@ -112,7 +100,6 @@ export function gitRunStackedActionMutationOptions(input: {
|
|||||||
queryClient: QueryClient;
|
queryClient: QueryClient;
|
||||||
}) {
|
}) {
|
||||||
return mutationOptions({
|
return mutationOptions({
|
||||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
|
||||||
mutationFn: async ({
|
mutationFn: async ({
|
||||||
action,
|
action,
|
||||||
commitMessage,
|
commitMessage,
|
||||||
@@ -136,7 +123,6 @@ export function gitRunStackedActionMutationOptions(input: {
|
|||||||
|
|
||||||
export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
export function gitPullMutationOptions(input: { cwd: string | null; queryClient: QueryClient }) {
|
||||||
return mutationOptions({
|
return mutationOptions({
|
||||||
mutationKey: gitMutationKeys.pull(input.cwd),
|
|
||||||
mutationFn: async () => {
|
mutationFn: async () => {
|
||||||
const api = ensureNativeApi();
|
const api = ensureNativeApi();
|
||||||
if (!input.cwd) throw new Error("Git pull is unavailable.");
|
if (!input.cwd) throw new Error("Git pull is unavailable.");
|
||||||
@@ -165,7 +151,6 @@ export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClie
|
|||||||
if (!cwd) throw new Error("Git worktree creation is unavailable.");
|
if (!cwd) throw new Error("Git worktree creation is unavailable.");
|
||||||
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
|
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
|
||||||
},
|
},
|
||||||
mutationKey: ["git", "mutation", "create-worktree"] as const,
|
|
||||||
onSettled: async () => {
|
onSettled: async () => {
|
||||||
await invalidateGitQueries(input.queryClient);
|
await invalidateGitQueries(input.queryClient);
|
||||||
},
|
},
|
||||||
@@ -179,7 +164,6 @@ export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClie
|
|||||||
if (!cwd) throw new Error("Git worktree removal is unavailable.");
|
if (!cwd) throw new Error("Git worktree removal is unavailable.");
|
||||||
return api.git.removeWorktree({ cwd, path, force });
|
return api.git.removeWorktree({ cwd, path, force });
|
||||||
},
|
},
|
||||||
mutationKey: ["git", "mutation", "remove-worktree"] as const,
|
|
||||||
onSettled: async () => {
|
onSettled: async () => {
|
||||||
await invalidateGitQueries(input.queryClient);
|
await invalidateGitQueries(input.queryClient);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import { ThreadId } from "@t3tools/contracts";
|
|
||||||
import {
|
import {
|
||||||
Outlet,
|
Outlet,
|
||||||
createRootRouteWithContext,
|
createRootRouteWithContext,
|
||||||
type ErrorComponentProps,
|
type ErrorComponentProps,
|
||||||
useNavigate,
|
|
||||||
useRouterState,
|
|
||||||
} from "@tanstack/react-router";
|
} from "@tanstack/react-router";
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||||
@@ -16,7 +13,6 @@ import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQue
|
|||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { preferredTerminalEditor } from "../terminal-links";
|
import { preferredTerminalEditor } from "../terminal-links";
|
||||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
|
||||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||||
|
|
||||||
@@ -125,12 +121,7 @@ function errorDetails(error: unknown): string {
|
|||||||
function EventRouter() {
|
function EventRouter() {
|
||||||
const { dispatch } = useStore();
|
const { dispatch } = useStore();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const navigate = useNavigate();
|
|
||||||
const pathname = useRouterState({ select: (state) => state.location.pathname });
|
|
||||||
const pathnameRef = useRef(pathname);
|
|
||||||
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
|
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
|
||||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
|
||||||
pathnameRef.current = pathname;
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
@@ -179,47 +170,8 @@ function EventRouter() {
|
|||||||
}
|
}
|
||||||
void syncSnapshot();
|
void syncSnapshot();
|
||||||
});
|
});
|
||||||
const unsubTerminalEvent = api.terminal.onEvent((event) => {
|
const unsubWelcome = onServerWelcome(() => {
|
||||||
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
|
void syncSnapshot();
|
||||||
if (hasRunningSubprocess === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
dispatch({
|
|
||||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
|
||||||
threadId: ThreadId.makeUnsafe(event.threadId),
|
|
||||||
terminalId: event.terminalId,
|
|
||||||
hasRunningSubprocess,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
const unsubWelcome = onServerWelcome((payload) => {
|
|
||||||
void (async () => {
|
|
||||||
await syncSnapshot();
|
|
||||||
if (disposed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
dispatch({
|
|
||||||
type: "SET_PROJECT_EXPANDED",
|
|
||||||
projectId: payload.bootstrapProjectId,
|
|
||||||
expanded: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (pathnameRef.current !== "/") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await navigate({
|
|
||||||
to: "/$threadId",
|
|
||||||
params: { threadId: payload.bootstrapThreadId },
|
|
||||||
replace: true,
|
|
||||||
});
|
|
||||||
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
|
||||||
})().catch(() => undefined);
|
|
||||||
});
|
});
|
||||||
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
||||||
const signature = JSON.stringify(payload.issues);
|
const signature = JSON.stringify(payload.issues);
|
||||||
@@ -266,11 +218,10 @@ function EventRouter() {
|
|||||||
return () => {
|
return () => {
|
||||||
disposed = true;
|
disposed = true;
|
||||||
unsubDomainEvent();
|
unsubDomainEvent();
|
||||||
unsubTerminalEvent();
|
|
||||||
unsubWelcome();
|
unsubWelcome();
|
||||||
unsubServerConfigUpdated();
|
unsubServerConfigUpdated();
|
||||||
};
|
};
|
||||||
}, [dispatch, navigate, queryClient]);
|
}, [dispatch, queryClient]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ function ChatThreadRouteView() {
|
|||||||
if (!shouldUseDiffSheet) {
|
if (!shouldUseDiffSheet) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||||
<ChatView threadId={threadId} />
|
<ChatView threadId={threadId} />
|
||||||
</SidebarInset>
|
</SidebarInset>
|
||||||
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
|
||||||
@@ -189,7 +189,7 @@ function ChatThreadRouteView() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||||
<ChatView threadId={threadId} />
|
<ChatView threadId={threadId} />
|
||||||
</SidebarInset>
|
</SidebarInset>
|
||||||
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
|
||||||
|
|||||||
@@ -237,49 +237,6 @@ function SettingsRouteView() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="rounded-2xl border border-border bg-card p-5">
|
|
||||||
<div className="mb-4">
|
|
||||||
<h2 className="text-sm font-medium text-foreground">Responses</h2>
|
|
||||||
<p className="mt-1 text-xs text-muted-foreground">
|
|
||||||
Control how assistant output is rendered during a turn.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-foreground">Stream assistant messages</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Show token-by-token output while a response is in progress.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Switch
|
|
||||||
checked={settings.enableAssistantStreaming}
|
|
||||||
onCheckedChange={(checked) =>
|
|
||||||
updateSettings({
|
|
||||||
enableAssistantStreaming: Boolean(checked),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
aria-label="Stream assistant messages"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{settings.enableAssistantStreaming !== defaults.enableAssistantStreaming ? (
|
|
||||||
<div className="mt-3 flex justify-end">
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() =>
|
|
||||||
updateSettings({
|
|
||||||
enableAssistantStreaming: defaults.enableAssistantStreaming,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
Restore default
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="rounded-2xl border border-border bg-card p-5">
|
<section className="rounded-2xl border border-border bg-card p-5">
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<h2 className="text-sm font-medium text-foreground">Keybindings</h2>
|
<h2 className="text-sm font-medium text-foreground">Keybindings</h2>
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import {
|
import { derivePendingApprovals, deriveWorkLogEntries } from "./session-logic";
|
||||||
derivePendingApprovals,
|
|
||||||
deriveWorkLogEntries,
|
|
||||||
hasToolActivityForTurn,
|
|
||||||
isLatestTurnSettled,
|
|
||||||
} from "./session-logic";
|
|
||||||
|
|
||||||
function makeActivity(overrides: {
|
function makeActivity(overrides: {
|
||||||
id?: string;
|
id?: string;
|
||||||
@@ -131,72 +126,3 @@ describe("deriveWorkLogEntries", () => {
|
|||||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("hasToolActivityForTurn", () => {
|
|
||||||
it("returns false when turn id is missing", () => {
|
|
||||||
const activities: OrchestrationThreadActivity[] = [
|
|
||||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
|
||||||
];
|
|
||||||
|
|
||||||
expect(hasToolActivityForTurn(activities, undefined)).toBe(false);
|
|
||||||
expect(hasToolActivityForTurn(activities, null)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns true only for matching tool activity in the target turn", () => {
|
|
||||||
const activities: OrchestrationThreadActivity[] = [
|
|
||||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
|
||||||
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
|
|
||||||
];
|
|
||||||
|
|
||||||
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-1"))).toBe(true);
|
|
||||||
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-2"))).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("isLatestTurnSettled", () => {
|
|
||||||
const latestTurn = {
|
|
||||||
turnId: TurnId.makeUnsafe("turn-1"),
|
|
||||||
startedAt: "2026-02-27T21:10:00.000Z",
|
|
||||||
completedAt: "2026-02-27T21:10:06.000Z",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
it("returns false while the same turn is still active in a running session", () => {
|
|
||||||
expect(
|
|
||||||
isLatestTurnSettled(latestTurn, {
|
|
||||||
orchestrationStatus: "running",
|
|
||||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
|
||||||
}),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false while any turn is running to avoid stale latest-turn banners", () => {
|
|
||||||
expect(
|
|
||||||
isLatestTurnSettled(latestTurn, {
|
|
||||||
orchestrationStatus: "running",
|
|
||||||
activeTurnId: TurnId.makeUnsafe("turn-2"),
|
|
||||||
}),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns true once the session is no longer running that turn", () => {
|
|
||||||
expect(
|
|
||||||
isLatestTurnSettled(latestTurn, {
|
|
||||||
orchestrationStatus: "ready",
|
|
||||||
activeTurnId: undefined,
|
|
||||||
}),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false when turn timestamps are incomplete", () => {
|
|
||||||
expect(
|
|
||||||
isLatestTurnSettled(
|
|
||||||
{
|
|
||||||
turnId: TurnId.makeUnsafe("turn-1"),
|
|
||||||
startedAt: null,
|
|
||||||
completedAt: "2026-02-27T21:10:06.000Z",
|
|
||||||
},
|
|
||||||
null,
|
|
||||||
),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
type OrchestrationLatestTurn,
|
|
||||||
type OrchestrationThreadActivity,
|
type OrchestrationThreadActivity,
|
||||||
type ProviderKind,
|
type ProviderKind,
|
||||||
type TurnId,
|
type TurnId,
|
||||||
@@ -76,17 +75,6 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
|
|||||||
return formatDuration(endedAt - startedAt);
|
return formatDuration(endedAt - startedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isLatestTurnSettled(
|
|
||||||
latestTurn: Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt"> | null,
|
|
||||||
session: Pick<ThreadSession, "orchestrationStatus" | "activeTurnId"> | null,
|
|
||||||
): boolean {
|
|
||||||
if (!latestTurn?.startedAt) return false;
|
|
||||||
if (!latestTurn.completedAt) return false;
|
|
||||||
if (!session) return true;
|
|
||||||
if (session.orchestrationStatus === "running") return false;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function derivePendingApprovals(
|
export function derivePendingApprovals(
|
||||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||||
): PendingApproval[] {
|
): PendingApproval[] {
|
||||||
@@ -159,14 +147,6 @@ export function deriveWorkLogEntries(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hasToolActivityForTurn(
|
|
||||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
|
||||||
turnId: TurnId | null | undefined,
|
|
||||||
): boolean {
|
|
||||||
if (!turnId) return false;
|
|
||||||
return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deriveTimelineEntries(
|
export function deriveTimelineEntries(
|
||||||
messages: ChatMessage[],
|
messages: ChatMessage[],
|
||||||
workEntries: WorkLogEntry[],
|
workEntries: WorkLogEntry[],
|
||||||
|
|||||||
@@ -1,161 +0,0 @@
|
|||||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
|
||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { reducer, type AppState } from "./store";
|
|
||||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
|
||||||
|
|
||||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
|
||||||
return {
|
|
||||||
id: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
codexThreadId: null,
|
|
||||||
projectId: ProjectId.makeUnsafe("project-1"),
|
|
||||||
title: "Thread",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
terminalOpen: false,
|
|
||||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
|
||||||
runningTerminalIds: [],
|
|
||||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
|
||||||
terminalGroups: [
|
|
||||||
{
|
|
||||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
|
||||||
session: null,
|
|
||||||
messages: [],
|
|
||||||
turnDiffSummaries: [],
|
|
||||||
activities: [],
|
|
||||||
error: null,
|
|
||||||
createdAt: "2026-02-13T00:00:00.000Z",
|
|
||||||
latestTurn: null,
|
|
||||||
branch: null,
|
|
||||||
worktreePath: null,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeState(thread: Thread): AppState {
|
|
||||||
return {
|
|
||||||
projects: [
|
|
||||||
{
|
|
||||||
id: ProjectId.makeUnsafe("project-1"),
|
|
||||||
name: "Project",
|
|
||||||
cwd: "/tmp/project",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
expanded: true,
|
|
||||||
scripts: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
threads: [thread],
|
|
||||||
threadsHydrated: true,
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("store reducer", () => {
|
|
||||||
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
|
|
||||||
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
|
|
||||||
const initialState = makeState(
|
|
||||||
makeThread({
|
|
||||||
latestTurn: {
|
|
||||||
turnId: TurnId.makeUnsafe("turn-1"),
|
|
||||||
state: "completed",
|
|
||||||
requestedAt: "2026-02-25T12:28:00.000Z",
|
|
||||||
startedAt: "2026-02-25T12:28:30.000Z",
|
|
||||||
completedAt: latestTurnCompletedAt,
|
|
||||||
assistantMessageId: null,
|
|
||||||
},
|
|
||||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const next = reducer(initialState, {
|
|
||||||
type: "MARK_THREAD_UNREAD",
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
});
|
|
||||||
|
|
||||||
const updatedThread = next.threads[0];
|
|
||||||
expect(updatedThread).toBeDefined();
|
|
||||||
expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z");
|
|
||||||
expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan(
|
|
||||||
Date.parse(latestTurnCompletedAt),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not change a thread without a completed turn", () => {
|
|
||||||
const initialState = makeState(
|
|
||||||
makeThread({
|
|
||||||
latestTurn: null,
|
|
||||||
lastVisitedAt: "2026-02-25T12:35:00.000Z",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const next = reducer(initialState, {
|
|
||||||
type: "MARK_THREAD_UNREAD",
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next).toEqual(initialState);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("store terminal activity reducer", () => {
|
|
||||||
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
|
|
||||||
const state = makeState(
|
|
||||||
makeThread({
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
|
||||||
terminalGroups: [
|
|
||||||
{
|
|
||||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
terminalId: "alt",
|
|
||||||
hasRunningSubprocess: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
|
|
||||||
const state = makeState(
|
|
||||||
makeThread({
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
|
||||||
terminalGroups: [
|
|
||||||
{
|
|
||||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
runningTerminalIds: ["alt"],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
terminalId: "alt",
|
|
||||||
hasRunningSubprocess: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores activity events for unknown terminal ids", () => {
|
|
||||||
const state = makeState(makeThread());
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "SET_THREAD_TERMINAL_ACTIVITY",
|
|
||||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
|
||||||
terminalId: "missing",
|
|
||||||
hasRunningSubprocess: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+17
-69
@@ -33,15 +33,7 @@ import {
|
|||||||
type Action =
|
type Action =
|
||||||
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
|
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
|
||||||
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
|
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
|
||||||
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
|
|
||||||
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
|
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
|
||||||
| {
|
|
||||||
type: "SET_THREAD_TERMINAL_ACTIVITY";
|
|
||||||
threadId: ThreadId;
|
|
||||||
terminalId: string;
|
|
||||||
hasRunningSubprocess: boolean;
|
|
||||||
}
|
|
||||||
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
|
|
||||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
|
||||||
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
|
||||||
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
|
||||||
@@ -377,27 +369,6 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function setThreadTerminalActivity(
|
|
||||||
thread: Thread,
|
|
||||||
terminalId: string,
|
|
||||||
hasRunningSubprocess: boolean,
|
|
||||||
): Thread {
|
|
||||||
const normalizedThread = normalizeThreadTerminals(thread);
|
|
||||||
if (!normalizedThread.terminalIds.includes(terminalId)) {
|
|
||||||
return normalizedThread;
|
|
||||||
}
|
|
||||||
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
|
|
||||||
if (hasRunningSubprocess) {
|
|
||||||
runningTerminalIds.add(terminalId);
|
|
||||||
} else {
|
|
||||||
runningTerminalIds.delete(terminalId);
|
|
||||||
}
|
|
||||||
return normalizeThreadTerminals({
|
|
||||||
...normalizedThread,
|
|
||||||
runningTerminalIds: [...runningTerminalIds],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Reducer ──────────────────────────────────────────────────────────
|
// ── Reducer ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function reducer(state: AppState, action: Action): AppState {
|
export function reducer(state: AppState, action: Action): AppState {
|
||||||
@@ -414,6 +385,19 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
.filter((thread) => thread.deletedAt === null)
|
.filter((thread) => thread.deletedAt === null)
|
||||||
.map((thread) => {
|
.map((thread) => {
|
||||||
const existing = existingThreadById.get(thread.id);
|
const existing = existingThreadById.get(thread.id);
|
||||||
|
const latestTurnStartedAt =
|
||||||
|
thread.latestTurnId === null
|
||||||
|
? undefined
|
||||||
|
: thread.messages.find(
|
||||||
|
(message) => message.turnId === thread.latestTurnId && message.role === "user",
|
||||||
|
)?.createdAt;
|
||||||
|
const latestTurnCompletedAt = thread.checkpoints.find(
|
||||||
|
(checkpoint) => checkpoint.turnId === thread.latestTurnId,
|
||||||
|
)?.completedAt;
|
||||||
|
const latestTurnDurationMs =
|
||||||
|
latestTurnStartedAt && latestTurnCompletedAt
|
||||||
|
? Math.max(0, Date.parse(latestTurnCompletedAt) - Date.parse(latestTurnStartedAt))
|
||||||
|
: undefined;
|
||||||
|
|
||||||
return normalizeThreadTerminals({
|
return normalizeThreadTerminals({
|
||||||
id: thread.id,
|
id: thread.id,
|
||||||
@@ -471,7 +455,10 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
}),
|
}),
|
||||||
error: thread.session?.lastError ?? null,
|
error: thread.session?.lastError ?? null,
|
||||||
createdAt: thread.createdAt,
|
createdAt: thread.createdAt,
|
||||||
latestTurn: thread.latestTurn,
|
latestTurnId: thread.latestTurnId ?? undefined,
|
||||||
|
latestTurnStartedAt,
|
||||||
|
latestTurnCompletedAt,
|
||||||
|
latestTurnDurationMs,
|
||||||
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
|
||||||
branch: thread.branch,
|
branch: thread.branch,
|
||||||
worktreePath: thread.worktreePath,
|
worktreePath: thread.worktreePath,
|
||||||
@@ -517,29 +504,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
case "MARK_THREAD_UNREAD": {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
|
||||||
if (!thread.latestTurn?.completedAt) {
|
|
||||||
return thread;
|
|
||||||
}
|
|
||||||
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
|
|
||||||
if (Number.isNaN(latestTurnCompletedAtMs)) {
|
|
||||||
return thread;
|
|
||||||
}
|
|
||||||
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
|
|
||||||
if (thread.lastVisitedAt === unreadVisitedAt) {
|
|
||||||
return thread;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...thread,
|
|
||||||
lastVisitedAt: unreadVisitedAt,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
case "TOGGLE_PROJECT":
|
case "TOGGLE_PROJECT":
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
@@ -548,22 +512,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
case "SET_THREAD_TERMINAL_ACTIVITY":
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
|
||||||
setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
case "SET_PROJECT_EXPANDED":
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
projects: state.projects.map((p) =>
|
|
||||||
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
case "TOGGLE_THREAD_TERMINAL":
|
case "TOGGLE_THREAD_TERMINAL":
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
|
|||||||
@@ -1,71 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import type { TerminalEvent, TerminalSessionSnapshot } from "@t3tools/contracts";
|
|
||||||
import { terminalRunningSubprocessFromEvent } from "./terminalActivity";
|
|
||||||
|
|
||||||
const snapshot: TerminalSessionSnapshot = {
|
|
||||||
threadId: "thread-1",
|
|
||||||
terminalId: "default",
|
|
||||||
cwd: "/tmp",
|
|
||||||
status: "running",
|
|
||||||
pid: 1234,
|
|
||||||
history: "",
|
|
||||||
exitCode: null,
|
|
||||||
exitSignal: null,
|
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
};
|
|
||||||
|
|
||||||
function eventBase() {
|
|
||||||
return {
|
|
||||||
threadId: "thread-1",
|
|
||||||
terminalId: "default",
|
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("terminalRunningSubprocessFromEvent", () => {
|
|
||||||
it("returns the subprocess flag for terminal activity events", () => {
|
|
||||||
const active = terminalRunningSubprocessFromEvent({
|
|
||||||
...eventBase(),
|
|
||||||
type: "activity",
|
|
||||||
hasRunningSubprocess: true,
|
|
||||||
});
|
|
||||||
const idle = terminalRunningSubprocessFromEvent({
|
|
||||||
...eventBase(),
|
|
||||||
type: "activity",
|
|
||||||
hasRunningSubprocess: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(active).toBe(true);
|
|
||||||
expect(idle).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("clears running state when a terminal session starts/restarts/exits", () => {
|
|
||||||
const events: TerminalEvent[] = [
|
|
||||||
{ ...eventBase(), type: "started", snapshot },
|
|
||||||
{ ...eventBase(), type: "restarted", snapshot },
|
|
||||||
{ ...eventBase(), type: "exited", exitCode: 0, exitSignal: null },
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const event of events) {
|
|
||||||
expect(terminalRunningSubprocessFromEvent(event)).toBe(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores non-activity terminal events", () => {
|
|
||||||
expect(
|
|
||||||
terminalRunningSubprocessFromEvent({
|
|
||||||
...eventBase(),
|
|
||||||
type: "output",
|
|
||||||
data: "hello",
|
|
||||||
}),
|
|
||||||
).toBeNull();
|
|
||||||
expect(
|
|
||||||
terminalRunningSubprocessFromEvent({
|
|
||||||
...eventBase(),
|
|
||||||
type: "error",
|
|
||||||
message: "oops",
|
|
||||||
}),
|
|
||||||
).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import type { TerminalEvent } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolean | null {
|
|
||||||
switch (event.type) {
|
|
||||||
case "activity":
|
|
||||||
return event.hasRunningSubprocess;
|
|
||||||
case "started":
|
|
||||||
case "restarted":
|
|
||||||
case "exited":
|
|
||||||
return false;
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import type {
|
import type {
|
||||||
OrchestrationLatestTurn,
|
|
||||||
OrchestrationSessionStatus,
|
OrchestrationSessionStatus,
|
||||||
OrchestrationThreadActivity,
|
OrchestrationThreadActivity,
|
||||||
ProjectScript as ContractProjectScript,
|
ProjectScript as ContractProjectScript,
|
||||||
@@ -90,7 +89,10 @@ export interface Thread {
|
|||||||
messages: ChatMessage[];
|
messages: ChatMessage[];
|
||||||
error: string | null;
|
error: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
latestTurn: OrchestrationLatestTurn | null;
|
latestTurnId?: TurnId | undefined;
|
||||||
|
latestTurnStartedAt?: string | undefined;
|
||||||
|
latestTurnCompletedAt?: string | undefined;
|
||||||
|
latestTurnDurationMs?: number | undefined;
|
||||||
lastVisitedAt?: string | undefined;
|
lastVisitedAt?: string | undefined;
|
||||||
branch: string | null;
|
branch: string | null;
|
||||||
worktreePath: string | null;
|
worktreePath: string | null;
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
|||||||
activities: [],
|
activities: [],
|
||||||
error: null,
|
error: null,
|
||||||
createdAt: "2026-02-13T00:00:00.000Z",
|
createdAt: "2026-02-13T00:00:00.000Z",
|
||||||
latestTurn: null,
|
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
...overrides,
|
...overrides,
|
||||||
|
|||||||
@@ -65,41 +65,16 @@ describe("wsNativeApi", () => {
|
|||||||
emitPush(WS_CHANNELS.serverWelcome, payload);
|
emitPush(WS_CHANNELS.serverWelcome, payload);
|
||||||
|
|
||||||
expect(listener).toHaveBeenCalledTimes(1);
|
expect(listener).toHaveBeenCalledTimes(1);
|
||||||
expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
expect(listener).toHaveBeenCalledWith(payload);
|
||||||
|
|
||||||
const lateListener = vi.fn();
|
const lateListener = vi.fn();
|
||||||
onServerWelcome(lateListener);
|
onServerWelcome(lateListener);
|
||||||
|
|
||||||
expect(lateListener).toHaveBeenCalledTimes(1);
|
expect(lateListener).toHaveBeenCalledTimes(1);
|
||||||
expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
|
expect(lateListener).toHaveBeenCalledWith(payload);
|
||||||
expect(warnSpy).not.toHaveBeenCalled();
|
expect(warnSpy).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("preserves bootstrap ids from server.welcome payloads", async () => {
|
|
||||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
|
||||||
|
|
||||||
createWsNativeApi();
|
|
||||||
const listener = vi.fn();
|
|
||||||
onServerWelcome(listener);
|
|
||||||
|
|
||||||
emitPush(WS_CHANNELS.serverWelcome, {
|
|
||||||
cwd: "/tmp/workspace",
|
|
||||||
projectName: "t3-code",
|
|
||||||
bootstrapProjectId: "project-1",
|
|
||||||
bootstrapThreadId: "thread-1",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(listener).toHaveBeenCalledTimes(1);
|
|
||||||
expect(listener).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
cwd: "/tmp/workspace",
|
|
||||||
projectName: "t3-code",
|
|
||||||
bootstrapProjectId: "project-1",
|
|
||||||
bootstrapThreadId: "thread-1",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
|
it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
|
||||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||||
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
|
||||||
@@ -112,9 +87,7 @@ describe("wsNativeApi", () => {
|
|||||||
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
|
emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
|
||||||
|
|
||||||
expect(listener).toHaveBeenCalledTimes(1);
|
expect(listener).toHaveBeenCalledTimes(1);
|
||||||
expect(listener).toHaveBeenCalledWith(
|
expect(listener).toHaveBeenCalledWith({ cwd: "/tmp/workspace", projectName: "t3-code" });
|
||||||
expect.objectContaining({ cwd: "/tmp/workspace", projectName: "t3-code" }),
|
|
||||||
);
|
|
||||||
expect(warnSpy).toHaveBeenCalledTimes(1);
|
expect(warnSpy).toHaveBeenCalledTimes(1);
|
||||||
expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
|
expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
|
||||||
reason: "decode-failed",
|
reason: "decode-failed",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import react from "@vitejs/plugin-react";
|
|||||||
import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
|
|
||||||
const port = Number(process.env.PORT ?? 5733);
|
const port = Number(process.env.PORT ?? 5173);
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [
|
plugins: [
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
# ADR 0001: Provider Runtime Lifecycle Ownership
|
|
||||||
|
|
||||||
## Status
|
|
||||||
Accepted
|
|
||||||
|
|
||||||
## Context
|
|
||||||
Provider runtime streams can include auxiliary work (for example collab/child-agent turns) under the same provider session as a user-visible primary turn.
|
|
||||||
|
|
||||||
The previous orchestration ingestion and checkpoint flows keyed lifecycle updates by `providerSessionId` alone. This allowed auxiliary `turn.completed` events to:
|
|
||||||
|
|
||||||
- mark thread sessions as `ready` before the primary turn completed
|
|
||||||
- clear `activeTurnId` for a still-running primary turn
|
|
||||||
- emit checkpoint turn-diff summaries for auxiliary turns in the main thread timeline
|
|
||||||
|
|
||||||
## Decision
|
|
||||||
Define and enforce a lifecycle ownership invariant:
|
|
||||||
|
|
||||||
- Only events in the primary thread/turn lane may mutate thread session lifecycle state (`status`, `activeTurnId`, `providerThreadId`) and checkpoint turn completion.
|
|
||||||
- Auxiliary events may still append messages and activities.
|
|
||||||
|
|
||||||
Current enforcement is implemented with scope guards:
|
|
||||||
|
|
||||||
- Runtime ingestion only applies lifecycle transitions when the event targets the active primary scope (provider thread and active turn checks).
|
|
||||||
- Checkpoint capture ignores `turn.completed` events from non-primary provider thread scope, and ignores non-active turn completions while a primary turn is active.
|
|
||||||
|
|
||||||
## Consequences
|
|
||||||
|
|
||||||
### Positive
|
|
||||||
- Prevents premature loss of "working" state from auxiliary turn completion.
|
|
||||||
- Prevents auxiliary changed-files/checkpoint cards from appearing as if they were primary turn completion.
|
|
||||||
- Keeps useful auxiliary activity/message visibility.
|
|
||||||
|
|
||||||
### Negative
|
|
||||||
- Runtime events that omit thread/turn identifiers are treated conservatively in lifecycle transitions.
|
|
||||||
- Full explicit lane modeling is still desirable in contracts for long-term clarity.
|
|
||||||
|
|
||||||
## Follow-up
|
|
||||||
1. Add explicit runtime lane metadata (`primary` vs `auxiliary`) to canonical provider runtime events.
|
|
||||||
2. Persist orchestration-to-provider turn binding (`TurnId` <-> `ProviderTurnId`) for stronger reconciliation and replay safety.
|
|
||||||
3. Promote lifecycle ownership checks from heuristic guards to schema-level invariants once lane metadata is available.
|
|
||||||
@@ -35,12 +35,6 @@ it.effect("parses keybinding rules", () =>
|
|||||||
});
|
});
|
||||||
assert.strictEqual(parsedClose.command, "terminal.close");
|
assert.strictEqual(parsedClose.command, "terminal.close");
|
||||||
|
|
||||||
const parsedDiffToggle = yield* decode(KeybindingRule, {
|
|
||||||
key: "mod+d",
|
|
||||||
command: "diff.toggle",
|
|
||||||
});
|
|
||||||
assert.strictEqual(parsedDiffToggle.command, "diff.toggle");
|
|
||||||
|
|
||||||
const parsedLocal = yield* decode(KeybindingRule, {
|
const parsedLocal = yield* decode(KeybindingRule, {
|
||||||
key: "mod+shift+n",
|
key: "mod+shift+n",
|
||||||
command: "chat.newLocal",
|
command: "chat.newLocal",
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ export const STATIC_KEYBINDING_COMMANDS = [
|
|||||||
"terminal.split",
|
"terminal.split",
|
||||||
"terminal.new",
|
"terminal.new",
|
||||||
"terminal.close",
|
"terminal.close",
|
||||||
"diff.toggle",
|
|
||||||
"chat.new",
|
"chat.new",
|
||||||
"chat.newLocal",
|
"chat.newLocal",
|
||||||
"editor.openFavorite",
|
"editor.openFavorite",
|
||||||
|
|||||||
@@ -46,8 +46,6 @@ export const ProviderSandboxMode = Schema.Literals([
|
|||||||
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
|
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
|
||||||
export const ProviderRequestKind = Schema.Literals(["command", "file-change"]);
|
export const ProviderRequestKind = Schema.Literals(["command", "file-change"]);
|
||||||
export type ProviderRequestKind = typeof ProviderRequestKind.Type;
|
export type ProviderRequestKind = typeof ProviderRequestKind.Type;
|
||||||
export const AssistantDeliveryMode = Schema.Literals(["buffered", "streaming"]);
|
|
||||||
export type AssistantDeliveryMode = typeof AssistantDeliveryMode.Type;
|
|
||||||
export const ProviderApprovalDecision = Schema.Literals([
|
export const ProviderApprovalDecision = Schema.Literals([
|
||||||
"accept",
|
"accept",
|
||||||
"acceptForSession",
|
"acceptForSession",
|
||||||
@@ -142,8 +140,6 @@ export const OrchestrationSession = Schema.Struct({
|
|||||||
providerName: Schema.NullOr(TrimmedNonEmptyString),
|
providerName: Schema.NullOr(TrimmedNonEmptyString),
|
||||||
providerSessionId: Schema.NullOr(ProviderSessionId),
|
providerSessionId: Schema.NullOr(ProviderSessionId),
|
||||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||||
approvalPolicy: ProviderApprovalPolicy.pipe(Schema.withDecodingDefault(() => "on-failure")),
|
|
||||||
sandboxMode: ProviderSandboxMode.pipe(Schema.withDecodingDefault(() => "workspace-write")),
|
|
||||||
activeTurnId: Schema.NullOr(TurnId),
|
activeTurnId: Schema.NullOr(TurnId),
|
||||||
lastError: Schema.NullOr(TrimmedNonEmptyString),
|
lastError: Schema.NullOr(TrimmedNonEmptyString),
|
||||||
updatedAt: IsoDateTime,
|
updatedAt: IsoDateTime,
|
||||||
@@ -191,24 +187,6 @@ export const OrchestrationThreadActivity = Schema.Struct({
|
|||||||
});
|
});
|
||||||
export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
|
export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
|
||||||
|
|
||||||
export const OrchestrationLatestTurnState = Schema.Literals([
|
|
||||||
"running",
|
|
||||||
"interrupted",
|
|
||||||
"completed",
|
|
||||||
"error",
|
|
||||||
]);
|
|
||||||
export type OrchestrationLatestTurnState = typeof OrchestrationLatestTurnState.Type;
|
|
||||||
|
|
||||||
export const OrchestrationLatestTurn = Schema.Struct({
|
|
||||||
turnId: TurnId,
|
|
||||||
state: OrchestrationLatestTurnState,
|
|
||||||
requestedAt: IsoDateTime,
|
|
||||||
startedAt: Schema.NullOr(IsoDateTime),
|
|
||||||
completedAt: Schema.NullOr(IsoDateTime),
|
|
||||||
assistantMessageId: Schema.NullOr(MessageId),
|
|
||||||
});
|
|
||||||
export type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;
|
|
||||||
|
|
||||||
export const OrchestrationThread = Schema.Struct({
|
export const OrchestrationThread = Schema.Struct({
|
||||||
id: ThreadId,
|
id: ThreadId,
|
||||||
projectId: ProjectId,
|
projectId: ProjectId,
|
||||||
@@ -216,7 +194,7 @@ export const OrchestrationThread = Schema.Struct({
|
|||||||
model: TrimmedNonEmptyString,
|
model: TrimmedNonEmptyString,
|
||||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||||
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
||||||
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
|
latestTurnId: Schema.NullOr(TurnId),
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
updatedAt: IsoDateTime,
|
updatedAt: IsoDateTime,
|
||||||
deletedAt: Schema.NullOr(IsoDateTime),
|
deletedAt: Schema.NullOr(IsoDateTime),
|
||||||
@@ -301,9 +279,6 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
|||||||
}),
|
}),
|
||||||
model: Schema.optional(TrimmedNonEmptyString),
|
model: Schema.optional(TrimmedNonEmptyString),
|
||||||
effort: Schema.optional(TrimmedNonEmptyString),
|
effort: Schema.optional(TrimmedNonEmptyString),
|
||||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
|
||||||
approvalPolicy: ProviderApprovalPolicy,
|
|
||||||
sandboxMode: ProviderSandboxMode,
|
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -517,9 +492,6 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
|||||||
messageId: MessageId,
|
messageId: MessageId,
|
||||||
model: Schema.optional(TrimmedNonEmptyString),
|
model: Schema.optional(TrimmedNonEmptyString),
|
||||||
effort: Schema.optional(TrimmedNonEmptyString),
|
effort: Schema.optional(TrimmedNonEmptyString),
|
||||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
|
||||||
approvalPolicy: ProviderApprovalPolicy.pipe(Schema.withDecodingDefault(() => "on-failure")),
|
|
||||||
sandboxMode: ProviderSandboxMode.pipe(Schema.withDecodingDefault(() => "workspace-write")),
|
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -9,11 +9,15 @@ import {
|
|||||||
ProviderSessionId,
|
ProviderSessionId,
|
||||||
ProviderThreadId,
|
ProviderThreadId,
|
||||||
ProviderTurnId,
|
ProviderTurnId,
|
||||||
|
ThreadId,
|
||||||
|
TurnId,
|
||||||
IsoDateTime,
|
IsoDateTime,
|
||||||
} from "./baseSchemas";
|
} from "./baseSchemas";
|
||||||
import { ProviderApprovalDecision, ProviderKind, ProviderRequestKind } from "./orchestration";
|
import { ProviderApprovalDecision, ProviderKind, ProviderRequestKind } from "./orchestration";
|
||||||
|
|
||||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||||
|
const RuntimeThreadIdSchema = Schema.Union([ThreadId, ProviderThreadId]);
|
||||||
|
const RuntimeTurnIdSchema = Schema.Union([TurnId, ProviderTurnId]);
|
||||||
|
|
||||||
export const ProviderRuntimeToolKind = Schema.Union([ProviderRequestKind, Schema.Literal("other")]);
|
export const ProviderRuntimeToolKind = Schema.Union([ProviderRequestKind, Schema.Literal("other")]);
|
||||||
export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;
|
export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;
|
||||||
@@ -32,7 +36,7 @@ export const ProviderRuntimeSessionStartedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||||
});
|
});
|
||||||
export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;
|
export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;
|
||||||
@@ -43,7 +47,7 @@ export const ProviderRuntimeSessionExitedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||||
});
|
});
|
||||||
export type ProviderRuntimeSessionExitedEvent = typeof ProviderRuntimeSessionExitedEvent.Type;
|
export type ProviderRuntimeSessionExitedEvent = typeof ProviderRuntimeSessionExitedEvent.Type;
|
||||||
@@ -54,7 +58,7 @@ export const ProviderRuntimeThreadStartedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: ProviderThreadId,
|
threadId: RuntimeThreadIdSchema,
|
||||||
});
|
});
|
||||||
export type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type;
|
export type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type;
|
||||||
|
|
||||||
@@ -64,8 +68,8 @@ export const ProviderRuntimeTurnStartedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: ProviderTurnId,
|
turnId: RuntimeTurnIdSchema,
|
||||||
});
|
});
|
||||||
export type ProviderRuntimeTurnStartedEvent = typeof ProviderRuntimeTurnStartedEvent.Type;
|
export type ProviderRuntimeTurnStartedEvent = typeof ProviderRuntimeTurnStartedEvent.Type;
|
||||||
|
|
||||||
@@ -75,8 +79,8 @@ export const ProviderRuntimeTurnCompletedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
status: Schema.optional(ProviderRuntimeTurnStatus),
|
status: Schema.optional(ProviderRuntimeTurnStatus),
|
||||||
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
|
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||||
});
|
});
|
||||||
@@ -88,8 +92,8 @@ export const ProviderRuntimeMessageDeltaEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
itemId: Schema.optional(ProviderItemId),
|
itemId: Schema.optional(ProviderItemId),
|
||||||
delta: Schema.String,
|
delta: Schema.String,
|
||||||
});
|
});
|
||||||
@@ -102,8 +106,8 @@ export const ProviderRuntimeMessageCompletedEvent = Schema.Struct({
|
|||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
itemId: ProviderItemId,
|
itemId: ProviderItemId,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
});
|
});
|
||||||
export type ProviderRuntimeMessageCompletedEvent = typeof ProviderRuntimeMessageCompletedEvent.Type;
|
export type ProviderRuntimeMessageCompletedEvent = typeof ProviderRuntimeMessageCompletedEvent.Type;
|
||||||
|
|
||||||
@@ -113,8 +117,8 @@ export const ProviderRuntimeToolStartedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
itemId: Schema.optional(ProviderItemId),
|
itemId: Schema.optional(ProviderItemId),
|
||||||
toolKind: ProviderRuntimeToolKind,
|
toolKind: ProviderRuntimeToolKind,
|
||||||
title: TrimmedNonEmptyStringSchema,
|
title: TrimmedNonEmptyStringSchema,
|
||||||
@@ -128,8 +132,8 @@ export const ProviderRuntimeToolCompletedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
itemId: Schema.optional(ProviderItemId),
|
itemId: Schema.optional(ProviderItemId),
|
||||||
toolKind: ProviderRuntimeToolKind,
|
toolKind: ProviderRuntimeToolKind,
|
||||||
title: TrimmedNonEmptyStringSchema,
|
title: TrimmedNonEmptyStringSchema,
|
||||||
@@ -143,8 +147,8 @@ export const ProviderRuntimeApprovalRequestedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
itemId: Schema.optional(ProviderItemId),
|
itemId: Schema.optional(ProviderItemId),
|
||||||
requestId: ApprovalRequestId,
|
requestId: ApprovalRequestId,
|
||||||
requestKind: ProviderRequestKind,
|
requestKind: ProviderRequestKind,
|
||||||
@@ -159,8 +163,8 @@ export const ProviderRuntimeApprovalResolvedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
itemId: Schema.optional(ProviderItemId),
|
itemId: Schema.optional(ProviderItemId),
|
||||||
requestId: ApprovalRequestId,
|
requestId: ApprovalRequestId,
|
||||||
requestKind: Schema.optional(ProviderRequestKind),
|
requestKind: Schema.optional(ProviderRequestKind),
|
||||||
@@ -174,8 +178,8 @@ export const ProviderRuntimeCheckpointCapturedEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: ProviderThreadId,
|
threadId: RuntimeThreadIdSchema,
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
turnCount: NonNegativeInt,
|
turnCount: NonNegativeInt,
|
||||||
status: Schema.optional(ProviderRuntimeTurnStatus),
|
status: Schema.optional(ProviderRuntimeTurnStatus),
|
||||||
});
|
});
|
||||||
@@ -188,8 +192,8 @@ export const ProviderRuntimeErrorEvent = Schema.Struct({
|
|||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
sessionId: ProviderSessionId,
|
sessionId: ProviderSessionId,
|
||||||
createdAt: IsoDateTime,
|
createdAt: IsoDateTime,
|
||||||
threadId: Schema.optional(ProviderThreadId),
|
threadId: Schema.optional(RuntimeThreadIdSchema),
|
||||||
turnId: Schema.optional(ProviderTurnId),
|
turnId: Schema.optional(RuntimeTurnIdSchema),
|
||||||
itemId: Schema.optional(ProviderItemId),
|
itemId: Schema.optional(ProviderItemId),
|
||||||
message: TrimmedNonEmptyStringSchema,
|
message: TrimmedNonEmptyStringSchema,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Schema, Struct } from "effect";
|
import { Schema, Struct } from "effect";
|
||||||
import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
|
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ClientOrchestrationCommand,
|
ClientOrchestrationCommand,
|
||||||
@@ -163,7 +163,5 @@ export type WsResponse = typeof WsResponse.Type;
|
|||||||
export const WsWelcomePayload = Schema.Struct({
|
export const WsWelcomePayload = Schema.Struct({
|
||||||
cwd: TrimmedNonEmptyString,
|
cwd: TrimmedNonEmptyString,
|
||||||
projectName: TrimmedNonEmptyString,
|
projectName: TrimmedNonEmptyString,
|
||||||
bootstrapProjectId: Schema.optional(ProjectId),
|
|
||||||
bootstrapThreadId: Schema.optional(ThreadId),
|
|
||||||
});
|
});
|
||||||
export type WsWelcomePayload = typeof WsWelcomePayload.Type;
|
export type WsWelcomePayload = typeof WsWelcomePayload.Type;
|
||||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
|||||||
import { pathToFileURL } from "node:url";
|
import { pathToFileURL } from "node:url";
|
||||||
|
|
||||||
const BASE_SERVER_PORT = 3773;
|
const BASE_SERVER_PORT = 3773;
|
||||||
const BASE_WEB_PORT = 5733;
|
const BASE_WEB_PORT = 5173;
|
||||||
const MAX_HASH_OFFSET = 3000;
|
const MAX_HASH_OFFSET = 3000;
|
||||||
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
|
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
|
||||||
const MODE_ARGS = {
|
const MODE_ARGS = {
|
||||||
@@ -154,13 +154,12 @@ export function parseDevRunnerArgs(rawArgs) {
|
|||||||
function resolveStateDir(env, envOverrides) {
|
function resolveStateDir(env, envOverrides) {
|
||||||
const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim();
|
const overrideValue = envOverrides?.T3CODE_STATE_DIR?.trim();
|
||||||
if (overrideValue) {
|
if (overrideValue) {
|
||||||
// Resolve relative paths against cwd (monorepo root) before turbo changes directories
|
return overrideValue;
|
||||||
return path.resolve(overrideValue);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const envValue = env?.T3CODE_STATE_DIR?.trim();
|
const envValue = env?.T3CODE_STATE_DIR?.trim();
|
||||||
if (envValue) {
|
if (envValue) {
|
||||||
return path.resolve(envValue);
|
return envValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
return DEFAULT_DEV_STATE_DIR;
|
return DEFAULT_DEV_STATE_DIR;
|
||||||
|
|||||||
@@ -30,7 +30,6 @@
|
|||||||
},
|
},
|
||||||
"test": {
|
"test": {
|
||||||
"dependsOn": ["^build"],
|
"dependsOn": ["^build"],
|
||||||
"cache": false,
|
|
||||||
"outputs": []
|
"outputs": []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user