Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82756816ef | ||
|
|
b5e9e47b11 | ||
|
|
1310045629 | ||
|
|
579a69eb77 | ||
|
|
9ee8c4f543 | ||
|
|
55560f5116 | ||
|
|
3710ddb611 | ||
|
|
3fce14bbcf | ||
|
|
d430a0624b |
No files matched your search
@@ -308,11 +308,31 @@ jobs:
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ vars.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
persist-credentials: true
|
||||
|
||||
- id: app_bot
|
||||
name: Resolve GitHub App bot identity
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app_token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
|
||||
run: |
|
||||
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
|
||||
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
|
||||
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -349,8 +369,8 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
|
||||
@@ -17,3 +17,4 @@ release/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
@@ -1,441 +0,0 @@
|
||||
# Plan: Claude Code Integration (Orchestration Architecture)
|
||||
|
||||
## Why this plan was rewritten
|
||||
|
||||
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
|
||||
|
||||
1. `orchestration.dispatchCommand` (client intent)
|
||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
||||
6. `orchestration.domainEvent` (single push channel consumed by web)
|
||||
|
||||
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
|
||||
|
||||
---
|
||||
|
||||
## Current constraints to design around (post-Stage 1)
|
||||
|
||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
||||
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
|
||||
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
|
||||
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
||||
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
|
||||
|
||||
---
|
||||
|
||||
## Architecture target
|
||||
|
||||
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
|
||||
|
||||
Key decisions:
|
||||
|
||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
||||
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Contracts and command shape updates
|
||||
|
||||
### 1.1 Provider-aware model contract
|
||||
|
||||
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
|
||||
|
||||
Expected outcomes:
|
||||
|
||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
||||
2. Add helpers that resolve model by provider.
|
||||
3. Preserve backwards compatibility for existing Codex defaults.
|
||||
|
||||
### 1.2 Turn-start provider intent
|
||||
|
||||
Update `packages/contracts/src/orchestration.ts`:
|
||||
|
||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
||||
3. Keep existing command valid when provider is omitted.
|
||||
|
||||
This removes the implicit “Codex unless session already exists” behavior as the only path.
|
||||
|
||||
### 1.3 Provider session start input for Claude runtime knobs (completed)
|
||||
|
||||
Update `packages/contracts/src/provider.ts`:
|
||||
|
||||
1. Move provider-specific start fields into typed `providerOptions`:
|
||||
- `providerOptions.codex`
|
||||
- `providerOptions.claudeCode`
|
||||
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
|
||||
3. Deprecate/remove `resumeThreadId` from the generic start contract.
|
||||
4. Treat `resumeCursor` as adapter-owned opaque state.
|
||||
|
||||
### 1.4 Contract tests (completed)
|
||||
|
||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
||||
|
||||
1. New command payload shape.
|
||||
2. Provider-aware model resolution behavior.
|
||||
3. Breaking-change expectations for removed top-level provider fields.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Claude adapter implementation
|
||||
|
||||
### 2.1 Add adapter service + layer
|
||||
|
||||
Create:
|
||||
|
||||
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
|
||||
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
|
||||
|
||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
|
||||
### 2.1.a SDK dependency and baseline config
|
||||
|
||||
Add server dependency:
|
||||
|
||||
1. `@anthropic-ai/claude-agent-sdk`
|
||||
|
||||
Baseline adapter options to support from day one:
|
||||
|
||||
1. `cwd`
|
||||
2. `model`
|
||||
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
|
||||
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
|
||||
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
|
||||
6. `resume`
|
||||
7. `resumeSessionAt`
|
||||
8. `includePartialMessages`
|
||||
9. `canUseTool`
|
||||
10. `hooks`
|
||||
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
|
||||
|
||||
### 2.2 Claude runtime bridge
|
||||
|
||||
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
|
||||
|
||||
Required capabilities:
|
||||
|
||||
1. Long-lived session context per adapter session.
|
||||
2. Multi-turn input queue.
|
||||
3. Interrupt support.
|
||||
4. Approval request/response bridge.
|
||||
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
|
||||
|
||||
#### 2.2.a Agent SDK details to preserve
|
||||
|
||||
The adapter should explicitly rely on these SDK capabilities:
|
||||
|
||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
||||
2. Multi-turn input is supported via async-iterable prompt input.
|
||||
3. Tool approval decisions are provided via `canUseTool`.
|
||||
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
|
||||
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
|
||||
|
||||
#### 2.2.b Effect-native session lifecycle skeleton
|
||||
|
||||
```ts
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { Effect } from "effect";
|
||||
|
||||
const acquireSession = (input: ProviderSessionStartInput) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const claudeOptions = input.providerOptions?.claudeCode;
|
||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
||||
const abortController = new AbortController();
|
||||
const result = query({
|
||||
prompt: makePromptAsyncIterable(),
|
||||
options: {
|
||||
cwd: input.cwd,
|
||||
model: input.model,
|
||||
permissionMode: claudeOptions?.permissionMode,
|
||||
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
|
||||
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
|
||||
resume: resumeState?.threadId,
|
||||
resumeSessionAt: resumeState?.sessionAt,
|
||||
signal: abortController.signal,
|
||||
includePartialMessages: true,
|
||||
canUseTool: makeCanUseTool(),
|
||||
hooks: makeClaudeHooks(),
|
||||
},
|
||||
});
|
||||
return { abortController, result };
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId: "pending",
|
||||
detail: "Failed to start Claude runtime session.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
({ abortController }) => Effect.sync(() => abortController.abort()),
|
||||
);
|
||||
```
|
||||
|
||||
#### 2.2.c AsyncIterable -> Effect Stream integration
|
||||
|
||||
Preferred when available in the pinned Effect version:
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.fromAsyncIterable(
|
||||
session.result,
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Portable fallback (already aligned with current server patterns):
|
||||
|
||||
```ts
|
||||
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
for await (const message of session.result) {
|
||||
if (cancelled) break;
|
||||
emit.single(message);
|
||||
}
|
||||
emit.end();
|
||||
} catch (cause) {
|
||||
emit.fail(
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
return Effect.sync(() => {
|
||||
cancelled = true;
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### 2.3 Canonical event mapping
|
||||
|
||||
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
|
||||
|
||||
Initial mapping target:
|
||||
|
||||
1. assistant text deltas -> `content.delta`
|
||||
2. final assistant text -> `item.completed` and/or `turn.completed`
|
||||
3. approval requests -> `request.opened`
|
||||
4. approval results -> `request.resolved`
|
||||
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
|
||||
6. errors -> `runtime.error`
|
||||
7. plan/proposed-plan content when derivable
|
||||
|
||||
Implementation note:
|
||||
|
||||
1. Keep raw Claude message on `raw` for debugging.
|
||||
2. Prefer canonical item/request kinds over provider-native enums.
|
||||
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
|
||||
|
||||
### 2.4 Resume cursor strategy
|
||||
|
||||
Define Claude-owned opaque resume state, e.g.:
|
||||
|
||||
```ts
|
||||
interface ClaudeResumeCursor {
|
||||
readonly version: 1;
|
||||
readonly threadId?: string;
|
||||
readonly sessionAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Serialize only adapter-owned state into `resumeCursor`.
|
||||
2. Parse/validate only inside Claude adapter.
|
||||
3. Store updated cursor when Claude runtime yields enough data to resume safely.
|
||||
4. Never overload orchestration thread id as Claude thread id.
|
||||
|
||||
### 2.5 Interrupt and stop semantics
|
||||
|
||||
Map orchestration stop/interrupt expectations onto SDK controls:
|
||||
|
||||
1. `interruptTurn()` -> active query interrupt.
|
||||
2. `stopSession()` -> close session resources and prevent future sends.
|
||||
3. `rollbackThread()` -> see Phase 4.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Provider service and composition
|
||||
|
||||
### 3.1 Register Claude adapter
|
||||
|
||||
Update provider registry layer to include Claude:
|
||||
|
||||
1. add `claudeCode` -> `ClaudeAdapter`
|
||||
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
|
||||
|
||||
### 3.2 Persist provider binding
|
||||
|
||||
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
|
||||
|
||||
Required validation:
|
||||
|
||||
1. Claude bindings survive restart.
|
||||
2. resume cursor remains opaque and round-trips untouched.
|
||||
3. stopAll + restart can recover Claude sessions when possible.
|
||||
|
||||
### 3.3 Provider start routing
|
||||
|
||||
Update `ProviderCommandReactor` / orchestration flow:
|
||||
|
||||
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
|
||||
2. If a thread already has Claude session binding, reuse it.
|
||||
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Checkpoint and revert strategy
|
||||
|
||||
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
|
||||
|
||||
Pick one explicit strategy:
|
||||
|
||||
### Option A: provider-native rewind
|
||||
|
||||
If SDK/runtime supports safe rewind:
|
||||
|
||||
1. implement in Claude adapter
|
||||
2. keep `CheckpointReactor` unchanged
|
||||
|
||||
### Option B: session restart + state truncation shim
|
||||
|
||||
If no native rewind exists:
|
||||
|
||||
1. Claude adapter returns successful rollback by:
|
||||
- stopping current Claude session
|
||||
- clearing/rewriting stored Claude resume cursor to last safe resumable point
|
||||
- forcing next turn to recreate session from persisted orchestration state
|
||||
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
|
||||
|
||||
Whichever option is chosen:
|
||||
|
||||
1. behavior must be deterministic
|
||||
2. checkpoint revert tests must pass under orchestration expectations
|
||||
3. user-visible activity log should explain failures clearly when provider rollback is impossible
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Web integration
|
||||
|
||||
### 5.1 Provider picker and model picker
|
||||
|
||||
Update web state/UI:
|
||||
|
||||
1. allow choosing Claude as thread provider before first turn
|
||||
2. show Claude model list from provider-aware model helpers
|
||||
3. preserve existing Codex default behavior when provider omitted
|
||||
|
||||
Likely touch points:
|
||||
|
||||
1. `apps/web/src/store.ts`
|
||||
2. `apps/web/src/components/ChatView.tsx`
|
||||
3. `apps/web/src/types.ts`
|
||||
4. `packages/shared/src/model.ts`
|
||||
|
||||
### 5.2 Settings for Claude executable/options
|
||||
|
||||
Add app settings if needed for:
|
||||
|
||||
1. Claude binary path
|
||||
2. default permission mode
|
||||
3. default max thinking tokens
|
||||
|
||||
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
|
||||
|
||||
### 5.3 Session rendering
|
||||
|
||||
No new WS channel should be needed. Claude should appear through existing:
|
||||
|
||||
1. thread messages
|
||||
2. activities/worklog
|
||||
3. approvals
|
||||
4. session state
|
||||
5. checkpoints/diffs
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Testing strategy
|
||||
|
||||
### 6.1 Contract tests
|
||||
|
||||
Cover:
|
||||
|
||||
1. provider-aware model schemas
|
||||
2. provider field on turn-start command
|
||||
3. provider-specific start options schema
|
||||
|
||||
### 6.2 Adapter layer tests
|
||||
|
||||
Add `ClaudeAdapter.test.ts` covering:
|
||||
|
||||
1. session start
|
||||
2. event mapping
|
||||
3. approval bridge
|
||||
4. resume cursor parse/serialize
|
||||
5. interrupt behavior
|
||||
6. rollback behavior or explicit unsupported error path
|
||||
|
||||
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
|
||||
|
||||
### 6.3 Provider service integration tests
|
||||
|
||||
Extend provider integration coverage so Claude is exercised through `ProviderService`:
|
||||
|
||||
1. start Claude session
|
||||
2. send turn
|
||||
3. receive canonical runtime events
|
||||
4. restart/recover using persisted binding
|
||||
|
||||
### 6.4 Orchestration integration tests
|
||||
|
||||
Add/extend integration tests around:
|
||||
|
||||
1. first-turn provider selection
|
||||
2. Claude approval requests routed through orchestration
|
||||
3. Claude runtime ingestion -> messages/activities/session updates
|
||||
4. checkpoint revert behavior under Claude
|
||||
5. stopAll/restart recovery
|
||||
|
||||
These should validate real orchestration flows, not just adapter behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: Rollout order
|
||||
|
||||
Recommended implementation order:
|
||||
|
||||
1. contracts/provider-aware models
|
||||
2. provider field on turn-start
|
||||
3. Claude adapter skeleton + start/send/stream
|
||||
4. canonical event mapping
|
||||
5. provider registry/service wiring
|
||||
6. orchestration recovery + checkpoint strategy
|
||||
7. web provider/model picker
|
||||
8. full integration tests
|
||||
|
||||
---
|
||||
|
||||
## Non-goals
|
||||
|
||||
1. Reintroducing provider-specific WS methods/channels.
|
||||
2. Storing provider-native thread ids as orchestration ids.
|
||||
3. Bypassing orchestration engine for Claude-specific UI flows.
|
||||
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
|
||||
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||
|
||||
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||
|
||||
## How to use
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import { execFileSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
ProviderKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -206,7 +205,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly provider?: "codex";
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -36,7 +35,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -178,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: "codex";
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -198,7 +197,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly provider?: "codex";
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -206,7 +205,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: ProviderKind,
|
||||
provider: "codex",
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -216,7 +215,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: ProviderKind,
|
||||
provider: "codex",
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
@@ -37,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = ProviderKind;
|
||||
type IntegrationProvider = "codex";
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -883,420 +882,3 @@ it.live(
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Claude first turn.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-initial",
|
||||
messageId: "msg-user-claude-initial",
|
||||
text: "Use Claude",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeAgent" &&
|
||||
entry.session.status === "ready" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
|
||||
),
|
||||
);
|
||||
assert.equal(thread.session?.providerName, "claudeAgent");
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn before restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-1",
|
||||
messageId: "msg-user-claude-recover-1",
|
||||
text: "Before restart",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness!.adapter.stopAll();
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness!.listActiveSessionIds(),
|
||||
(sessionIds) => sessionIds.length === 0,
|
||||
"provider stopAll",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn after restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-2",
|
||||
messageId: "msg-user-claude-recover-2",
|
||||
text: "After restart",
|
||||
});
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness!.getStartCount(),
|
||||
(count) => count === 2,
|
||||
"claude provider recovery start",
|
||||
);
|
||||
|
||||
const recoveredThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeAgent" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "user" && message.text === "After restart",
|
||||
) &&
|
||||
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
);
|
||||
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Approve Claude tool call",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-approval",
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "approval.requested"),
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
yield* harness.waitForPendingApproval(
|
||||
"req-approval-1",
|
||||
(row) => row.status === "resolved" && row.decision === "accept",
|
||||
);
|
||||
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
|
||||
(responses) => responses.length === 1,
|
||||
"claude provider approval response",
|
||||
);
|
||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Long running output.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-interrupt",
|
||||
messageId: "msg-user-claude-interrupt",
|
||||
text: "Start long turn",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.session?.threadId === "thread-1",
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
yield* harness.waitForDomainEvent(
|
||||
(event) => event.type === "thread.turn-interrupt-requested",
|
||||
);
|
||||
|
||||
const interruptCalls = yield* waitForSync(
|
||||
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
|
||||
(calls) => calls.length === 1,
|
||||
"claude provider interrupt call",
|
||||
);
|
||||
assert.equal(interruptCalls.length, 1);
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v2\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-1",
|
||||
messageId: "msg-user-claude-revert-1",
|
||||
text: "First Claude edit",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v3\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-2",
|
||||
messageId: "msg-user-claude-revert-2",
|
||||
text: "Second Claude edit",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.session?.providerName === "claudeAgent",
|
||||
);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const revertedThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
|
||||
);
|
||||
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
@@ -22,7 +22,6 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.76",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface ServerConfigShape {
|
||||
readonly host: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly themesConfigPath: string;
|
||||
readonly stateDir: string;
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
@@ -51,6 +52,7 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||
themesConfigPath: path.join(statedir, "themes.json"),
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
@@ -17,7 +18,6 @@ import {
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
|
||||
const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -187,6 +187,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
model,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
@@ -194,6 +195,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson: S;
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
model?: string;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
@@ -212,7 +214,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
@@ -353,6 +355,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -398,6 +401,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -449,6 +453,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
branch: Schema.String,
|
||||
}),
|
||||
imagePaths,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -639,6 +639,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
model?: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
@@ -665,6 +666,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
@@ -682,6 +684,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
@@ -691,6 +694,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
@@ -704,7 +708,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
@@ -748,6 +752,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
||||
@@ -972,6 +977,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
@@ -980,6 +986,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
@@ -1028,6 +1035,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
@@ -1044,6 +1052,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
@@ -1051,7 +1060,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface CommitMessageGenerationInput {
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
@@ -35,6 +37,8 @@ export interface PrContentGenerationInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
@@ -46,6 +50,8 @@ export interface BranchNameGenerationInput {
|
||||
cwd: string;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface BranchNameGenerationResult {
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { fixPath, resolveStateDir } from "./os-jank";
|
||||
import { fixPath, resolveStateDir, resolveThemesConfigPath } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
@@ -169,6 +169,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const { join } = yield* Path.Path;
|
||||
const keybindingsConfigPath = join(stateDir, "keybindings.json");
|
||||
const themesConfigPath = yield* resolveThemesConfigPath(stateDir);
|
||||
const host =
|
||||
Option.getOrUndefined(input.host) ??
|
||||
env.host ??
|
||||
@@ -179,6 +180,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
keybindingsConfigPath,
|
||||
themesConfigPath,
|
||||
host,
|
||||
stateDir,
|
||||
staticDir,
|
||||
|
||||
@@ -3,7 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -44,7 +44,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -235,7 +235,6 @@ describe("CheckpointReactor", () => {
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: ProviderKind;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -243,7 +242,7 @@ describe("CheckpointReactor", () => {
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
options?.providerName ?? "codex",
|
||||
"codex",
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -478,67 +477,6 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
providerName: "claudeAgent",
|
||||
});
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
@@ -854,75 +792,6 @@ describe("CheckpointReactor", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
|
||||
const harness = await createHarness({ providerName: "claudeAgent" });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
@@ -96,7 +96,7 @@ describe("ProviderCommandReactor", () => {
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
(input.provider === "codex" || input.provider === "claudeAgent")
|
||||
input.provider === "codex"
|
||||
? input.provider
|
||||
: "codex";
|
||||
const resumeCursor =
|
||||
@@ -129,7 +129,7 @@ describe("ProviderCommandReactor", () => {
|
||||
: "full-access",
|
||||
...(model !== undefined ? { model } : {}),
|
||||
threadId,
|
||||
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
||||
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
@@ -389,102 +389,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-first"),
|
||||
role: "user",
|
||||
text: "hello claude",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
expect(harness.startSession).not.toHaveBeenCalled();
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session).toBeNull();
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
summary: "Provider turn start failed",
|
||||
payload: {
|
||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a turn when the requested model belongs to a different provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-model-provider-mismatch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-model-provider-mismatch"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
model: "claude-sonnet-4-6",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
expect(harness.startSession).not.toHaveBeenCalled();
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("does not belong to provider 'codex'"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -605,7 +509,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
resumeCursor: { opaque: "cursor-1" },
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
@@ -618,77 +522,6 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("rejects provider changes after a thread is already bound to a session provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("codex");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
ProviderKind,
|
||||
type ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
@@ -25,7 +26,6 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -206,30 +206,9 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const desiredRuntimeMode = thread.runtimeMode;
|
||||
const currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
|
||||
thread.session?.providerName,
|
||||
)
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const threadProvider: ProviderKind = currentProvider ?? inferProviderForModel(thread.model);
|
||||
if (options?.provider !== undefined && options.provider !== threadProvider) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${options.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
options?.model !== undefined &&
|
||||
inferProviderForModel(options.model, threadProvider) !== threadProvider
|
||||
) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const currentProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
|
||||
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
@@ -413,6 +392,7 @@ const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -497,21 +477,7 @@ const make = Effect.gen(function* () {
|
||||
: {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const processTurnInterruptRequested = Effect.fnUntraced(function* (
|
||||
|
||||
@@ -2,11 +2,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -49,7 +45,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -406,60 +402,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
|
||||
const harness = await createHarness();
|
||||
const seededAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: seededAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt: seededAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-claude-placeholder"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-claude-placeholder"),
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-claude-placeholder",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-claude-placeholder"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-claude-placeholder"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores auxiliary turn completions from a different provider thread", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -34,3 +34,12 @@ export const resolveStateDir = Effect.fn(function* (raw: string | undefined) {
|
||||
}
|
||||
return resolve(yield* expandHomePath(raw.trim()));
|
||||
});
|
||||
|
||||
export const resolveThemesConfigPath = Effect.fn(function* (stateDir: string) {
|
||||
const path = yield* Path.Path;
|
||||
const normalizedStateDir = path.resolve(stateDir);
|
||||
if (path.basename(normalizedStateDir) === "userdata") {
|
||||
return path.join(path.dirname(normalizedStateDir), "themes.json");
|
||||
}
|
||||
return path.join(normalizedStateDir, "themes.json");
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -22,7 +22,6 @@ import {
|
||||
type CodexAppServerSendTurnInput,
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
@@ -157,29 +156,6 @@ const validationLayer = it.layer(
|
||||
);
|
||||
|
||||
validationLayer("CodexAdapterLive validation", (it) => {
|
||||
it.effect("returns validation error for non-codex provider on startSession", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const result = yield* adapter
|
||||
.startSession({
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
assert.deepStrictEqual(
|
||||
result.failure,
|
||||
new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "startSession",
|
||||
issue: "Expected provider 'codex' but received 'claudeAgent'.",
|
||||
}),
|
||||
);
|
||||
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
it.effect("maps codex model options before starting a session", () =>
|
||||
Effect.gen(function* () {
|
||||
validationManager.startSessionImpl.mockClear();
|
||||
|
||||
@@ -4,7 +4,6 @@ import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Layer, Stream } from "effect";
|
||||
|
||||
import { ClaudeAdapter, ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
@@ -28,32 +27,9 @@ const fakeCodexAdapter: CodexAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
provider: "claudeAgent",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
Layer.provide(
|
||||
ProviderAdapterRegistryLive,
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
|
||||
),
|
||||
),
|
||||
Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),
|
||||
NodeServices.layer,
|
||||
),
|
||||
);
|
||||
@@ -63,12 +39,10 @@ layer("ProviderAdapterRegistryLive", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const codex = yield* registry.getByProvider("codex");
|
||||
const claude = yield* registry.getByProvider("claudeAgent");
|
||||
assert.equal(codex, fakeCodexAdapter);
|
||||
assert.equal(claude, fakeClaudeAdapter);
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent"]);
|
||||
assert.deepEqual(providers, ["codex"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* ProviderAdapterRegistryLive - In-memory provider adapter lookup layer.
|
||||
*
|
||||
* Binds provider kinds (codex/claudeAgent/...) to concrete adapter services.
|
||||
* Binds provider kinds (codex/cursor/...) to concrete adapter services.
|
||||
* This layer only performs adapter lookup; it does not route session-scoped
|
||||
* calls or own provider lifecycle workflows.
|
||||
*
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
ProviderAdapterRegistry,
|
||||
type ProviderAdapterRegistryShape,
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
|
||||
export interface ProviderAdapterRegistryLiveOptions {
|
||||
@@ -24,10 +23,7 @@ export interface ProviderAdapterRegistryLiveOptions {
|
||||
|
||||
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter];
|
||||
const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
@@ -5,11 +5,9 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
checkClaudeProviderStatus,
|
||||
checkCodexProviderStatus,
|
||||
hasCustomModelProvider,
|
||||
parseAuthStatusFromOutput,
|
||||
parseClaudeAuthStatusFromOutput,
|
||||
readCodexConfigModelProvider,
|
||||
} from "./ProviderHealth";
|
||||
|
||||
@@ -466,175 +464,4 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkClaudeProviderStatus tests ──────────────────────────
|
||||
|
||||
describe("checkClaudeProviderStatus", () => {
|
||||
it.effect("returns ready when claude is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when claude is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
|
||||
);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns error when version check fails with non-zero exit code", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version")
|
||||
return { stdout: "", stderr: "Something went wrong", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth status reports not logged in", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 1,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status") return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when auth status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
|
||||
|
||||
describe("parseClaudeAuthStatusFromOutput", () => {
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=true is authenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=false is unauthenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"ok":true}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,7 +26,6 @@ import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHe
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
const CLAUDE_AGENT_PROVIDER = "claudeAgent" as const;
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
@@ -45,7 +44,12 @@ function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
function isCommandMissingCause(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const lower = error.message.toLowerCase();
|
||||
return lower.includes("enoent") || lower.includes("notfound");
|
||||
return (
|
||||
lower.includes("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
lower.includes("enoent") ||
|
||||
lower.includes("notfound")
|
||||
);
|
||||
}
|
||||
|
||||
function detailFromResult(
|
||||
@@ -260,27 +264,6 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("claude", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
const child = yield* spawner.spawn(command);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
@@ -407,197 +390,18 @@ export const checkCodexProviderStatus: Effect.Effect<
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Claude Agent health check ───────────────────────────────────────
|
||||
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: ServerProviderStatusState;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
lowerOutput.includes("unknown command") ||
|
||||
lowerOutput.includes("unrecognized command") ||
|
||||
lowerOutput.includes("unexpected argument")
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lowerOutput.includes("not logged in") ||
|
||||
lowerOutput.includes("login required") ||
|
||||
lowerOutput.includes("authentication required") ||
|
||||
lowerOutput.includes("run `claude login`") ||
|
||||
lowerOutput.includes("run claude login")
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
|
||||
// `claude auth status` returns JSON with a `loggedIn` boolean.
|
||||
const parsedAuth = (() => {
|
||||
const trimmed = result.stdout.trim();
|
||||
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
try {
|
||||
return {
|
||||
attemptedJsonParse: true as const,
|
||||
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||
};
|
||||
} catch {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Claude authentication status. ${detail}`
|
||||
: "Could not verify Claude authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
export const checkClaudeProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `claude --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Claude Agent CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `claude auth status` — is the user authenticated?
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude authentication status: ${error.message}.`
|
||||
: "Could not verify Claude authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Could not verify Claude authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CLAUDE_AGENT_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.forkScoped);
|
||||
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
|
||||
Effect.map(Array.of),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getStatuses: Fiber.join(statusesFiber),
|
||||
getStatuses: Fiber.join(codexStatusFiber),
|
||||
} satisfies ProviderHealthShape;
|
||||
}),
|
||||
);
|
||||
@@ -52,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -74,7 +74,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId: input.threadId,
|
||||
resumeCursor: input.resumeCursor ?? { opaque: `resume-${String(input.threadId)}` },
|
||||
resumeCursor: input.resumeCursor ?? { opaque: `cursor-${String(input.threadId)}` },
|
||||
cwd: input.cwd ?? process.cwd(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -217,15 +217,12 @@ const sleep = (ms: number) =>
|
||||
|
||||
function makeProviderServiceLayer() {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
const claude = makeFakeCodexAdapter("claudeAgent");
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(codex.adapter)
|
||||
: provider === "claudeAgent"
|
||||
? Effect.succeed(claude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
@@ -250,7 +247,6 @@ function makeProviderServiceLayer() {
|
||||
|
||||
return {
|
||||
codex,
|
||||
claude,
|
||||
layer,
|
||||
};
|
||||
}
|
||||
@@ -537,29 +533,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-claude"), {
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-claude"),
|
||||
cwd: "/tmp/project-claude",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "claudeAgent");
|
||||
assert.equal(routing.claude.startSession.mock.calls.length, 1);
|
||||
const startInput = routing.claude.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof startInput === "object" && startInput !== null, true);
|
||||
if (startInput && typeof startInput === "object") {
|
||||
const startPayload = startInput as { provider?: string; cwd?: string };
|
||||
assert.equal(startPayload.provider, "claudeAgent");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
@@ -616,7 +589,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
});
|
||||
|
||||
yield* routing.codex.stopAll();
|
||||
yield* routing.claude.stopAll();
|
||||
|
||||
const remaining = yield* provider.listSessions();
|
||||
assert.equal(remaining.length, 0);
|
||||
|
||||
@@ -141,8 +141,8 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
providerName: "cursor",
|
||||
adapterKey: "cursor",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
|
||||
@@ -22,7 +22,7 @@ function decodeProviderKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
|
||||
if (providerName === "codex" || providerName === "claudeAgent") {
|
||||
if (providerName === "codex") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.fail(
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* ClaudeAdapter - Claude Agent implementation of the generic provider adapter contract.
|
||||
*
|
||||
* This service owns Claude runtime/session semantics and emits canonical
|
||||
* provider runtime events. It does not perform cross-provider routing, shared
|
||||
* event fan-out, or checkpoint orchestration.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and returns the
|
||||
* shared provider-adapter error channel with `provider: "claudeAgent"` context.
|
||||
*
|
||||
* @module ClaudeAdapter
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* ClaudeAdapterShape - Service API for the Claude Agent provider adapter.
|
||||
*/
|
||||
export interface ClaudeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "claudeAgent";
|
||||
}
|
||||
|
||||
/**
|
||||
* ClaudeAdapter - Service tag for Claude Agent provider adapter operations.
|
||||
*/
|
||||
export class ClaudeAdapter extends ServiceMap.Service<ClaudeAdapter, ClaudeAdapterShape>()(
|
||||
"t3/provider/Services/ClaudeAdapter",
|
||||
) {}
|
||||
@@ -19,7 +19,6 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
|
||||
import { ProviderUnsupportedError } from "./provider/Errors";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
@@ -29,6 +28,7 @@ import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
|
||||
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager";
|
||||
import { KeybindingsLive } from "./keybindings";
|
||||
import { ThemesLive } from "./themes";
|
||||
import { GitManagerLive } from "./git/Layers/GitManager";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore";
|
||||
import { GitHubCliLive } from "./git/Layers/GitHubCli";
|
||||
@@ -59,12 +59,8 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const claudeAdapterLayer = makeClaudeAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
@@ -132,5 +128,6 @@ export function makeServerRuntimeServicesLayer() {
|
||||
gitManagerLayer,
|
||||
terminalLayer,
|
||||
KeybindingsLive,
|
||||
ThemesLive,
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { ThemePaletteConfig, type ThemePaletteDefinition } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Themes, ThemesLive } from "./themes";
|
||||
|
||||
const ThemePaletteConfigJson = Schema.fromJsonString(ThemePaletteConfig);
|
||||
|
||||
const makeThemesLayer = () =>
|
||||
ThemesLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { join } = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-themes-test-" });
|
||||
const configPath = join(dir, "themes.json");
|
||||
return { themesConfigPath: configPath } as ServerConfigShape;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const writeThemesConfig = (configPath: string, themes: readonly ThemePaletteDefinition[]) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const encoded = yield* Schema.encodeEffect(ThemePaletteConfigJson)(themes);
|
||||
yield* fileSystem.writeFileString(configPath, encoded);
|
||||
});
|
||||
|
||||
const readThemesConfig = (configPath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const rawConfig = yield* fileSystem.readFileString(configPath);
|
||||
return yield* Schema.decodeUnknownEffect(ThemePaletteConfigJson)(rawConfig);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("themes", (it) => {
|
||||
it.effect("bootstraps an empty themes config when the file is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { themesConfigPath } = yield* ServerConfig;
|
||||
assert.isFalse(yield* fs.exists(themesConfigPath));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const themes = yield* Themes;
|
||||
yield* themes.syncDefaultThemesOnStartup;
|
||||
});
|
||||
|
||||
const persisted = yield* readThemesConfig(themesConfigPath);
|
||||
assert.deepEqual(persisted, []);
|
||||
}).pipe(Effect.provide(makeThemesLayer())),
|
||||
);
|
||||
|
||||
it.effect("reports malformed config while falling back to no custom themes", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { themesConfigPath } = yield* ServerConfig;
|
||||
yield* fs.writeFileString(themesConfigPath, "{ not-json");
|
||||
|
||||
const configState = yield* Effect.gen(function* () {
|
||||
const themes = yield* Themes;
|
||||
return yield* themes.loadConfigState;
|
||||
});
|
||||
|
||||
assert.deepEqual(configState.themes, []);
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "themes.malformed-config",
|
||||
message: configState.issues[0]?.message ?? "",
|
||||
},
|
||||
]);
|
||||
assert.equal(yield* fs.readFileString(themesConfigPath), "{ not-json");
|
||||
}).pipe(Effect.provide(makeThemesLayer())),
|
||||
);
|
||||
|
||||
it.effect("keeps valid custom themes and reports invalid entries", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { themesConfigPath } = yield* ServerConfig;
|
||||
yield* fs.writeFileString(
|
||||
themesConfigPath,
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "midnight-mint",
|
||||
label: "Midnight Mint",
|
||||
dark: {
|
||||
background: "oklch(0.17 0.02 220)",
|
||||
primary: "oklch(0.79 0.16 170)",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "Invalid Id",
|
||||
label: "Broken",
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
const configState = yield* Effect.gen(function* () {
|
||||
const themes = yield* Themes;
|
||||
return yield* themes.loadConfigState;
|
||||
});
|
||||
|
||||
assert.deepEqual(configState.themes, [
|
||||
{
|
||||
id: "midnight-mint",
|
||||
label: "Midnight Mint",
|
||||
dark: {
|
||||
background: "oklch(0.17 0.02 220)",
|
||||
primary: "oklch(0.79 0.16 170)",
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "themes.invalid-entry",
|
||||
index: 1,
|
||||
message: configState.issues[0]?.message ?? "",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(makeThemesLayer())),
|
||||
);
|
||||
|
||||
it.effect("persists valid custom themes without mutation", () =>
|
||||
Effect.gen(function* () {
|
||||
const { themesConfigPath } = yield* ServerConfig;
|
||||
yield* writeThemesConfig(themesConfigPath, [
|
||||
{
|
||||
id: "aurora",
|
||||
label: "Aurora",
|
||||
light: {
|
||||
primary: "oklch(0.61 0.17 210)",
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const configState = yield* Effect.gen(function* () {
|
||||
const themes = yield* Themes;
|
||||
return yield* themes.loadConfigState;
|
||||
});
|
||||
|
||||
assert.deepEqual(configState.themes, [
|
||||
{
|
||||
id: "aurora",
|
||||
label: "Aurora",
|
||||
light: {
|
||||
primary: "oklch(0.61 0.17 210)",
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(configState.issues, []);
|
||||
}).pipe(Effect.provide(makeThemesLayer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,283 @@
|
||||
import {
|
||||
ThemePaletteConfig,
|
||||
ThemePaletteDefinition,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Cache,
|
||||
Cause,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
PubSub,
|
||||
Schema,
|
||||
SchemaGetter,
|
||||
Ref,
|
||||
Scope,
|
||||
ServiceMap,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
export class ThemesConfigError extends Schema.TaggedErrorClass<ThemesConfigError>()(
|
||||
"ThemesConfigError",
|
||||
{
|
||||
configPath: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unable to parse themes config at ${this.configPath}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const RawThemeEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown));
|
||||
const ThemePaletteConfigJson = Schema.fromJsonString(ThemePaletteConfig);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
);
|
||||
const ThemePaletteConfigPrettyJson = ThemePaletteConfigJson.pipe(
|
||||
Schema.encode({
|
||||
decode: PrettyJsonString,
|
||||
encode: PrettyJsonString,
|
||||
}),
|
||||
);
|
||||
|
||||
export interface ThemesConfigState {
|
||||
readonly themes: readonly ThemePaletteDefinition[];
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
}
|
||||
|
||||
export interface ThemesChangeEvent {
|
||||
readonly themes: readonly ThemePaletteDefinition[];
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
}
|
||||
|
||||
function trimIssueMessage(message: string): string {
|
||||
const trimmed = message.trim();
|
||||
return trimmed.length > 0 ? trimmed : "Invalid themes configuration.";
|
||||
}
|
||||
|
||||
function malformedConfigIssue(detail: string): ServerConfigIssue {
|
||||
return {
|
||||
kind: "themes.malformed-config",
|
||||
message: trimIssueMessage(detail),
|
||||
};
|
||||
}
|
||||
|
||||
function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
|
||||
return {
|
||||
kind: "themes.invalid-entry",
|
||||
index,
|
||||
message: trimIssueMessage(detail),
|
||||
};
|
||||
}
|
||||
|
||||
export interface ThemesShape {
|
||||
readonly start: Effect.Effect<void, ThemesConfigError>;
|
||||
readonly ready: Effect.Effect<void, ThemesConfigError>;
|
||||
readonly syncDefaultThemesOnStartup: Effect.Effect<void, ThemesConfigError>;
|
||||
readonly loadConfigState: Effect.Effect<ThemesConfigState, ThemesConfigError>;
|
||||
readonly getSnapshot: Effect.Effect<ThemesConfigState, ThemesConfigError>;
|
||||
readonly streamChanges: Stream.Stream<ThemesChangeEvent>;
|
||||
}
|
||||
|
||||
export class Themes extends ServiceMap.Service<Themes, ThemesShape>()("t3/themes") {}
|
||||
|
||||
const makeThemes = Effect.gen(function* () {
|
||||
const { themesConfigPath } = yield* ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const updateSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* PubSub.unbounded<ThemesChangeEvent>();
|
||||
const startedRef = yield* Ref.make(false);
|
||||
const startedDeferred = yield* Deferred.make<void, ThemesConfigError>();
|
||||
const watcherScope = yield* Scope.make("sequential");
|
||||
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
|
||||
|
||||
const emitChange = (configState: ThemesConfigState) =>
|
||||
PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
|
||||
|
||||
const readConfigExists = fs.exists(themesConfigPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ThemesConfigError({
|
||||
configPath: themesConfigPath,
|
||||
detail: "failed to access themes config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const readRawConfig = fs.readFileString(themesConfigPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ThemesConfigError({
|
||||
configPath: themesConfigPath,
|
||||
detail: "failed to read themes config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeConfigAtomically = (themes: readonly ThemePaletteDefinition[]) => {
|
||||
const tempPath = `${themesConfigPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
|
||||
return Schema.encodeEffect(ThemePaletteConfigPrettyJson)(themes).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(themesConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, themesConfigPath)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ThemesConfigError({
|
||||
configPath: themesConfigPath,
|
||||
detail: "failed to write themes config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const loadConfigStateFromDisk = Effect.gen(function* (): Effect.fn.Return<
|
||||
ThemesConfigState,
|
||||
ThemesConfigError
|
||||
> {
|
||||
if (!(yield* readConfigExists)) {
|
||||
return { themes: [], issues: [] };
|
||||
}
|
||||
|
||||
const rawConfig = yield* readRawConfig;
|
||||
const decodedEntries = Schema.decodeUnknownExit(RawThemeEntries)(rawConfig);
|
||||
if (decodedEntries._tag === "Failure") {
|
||||
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
|
||||
return {
|
||||
themes: [],
|
||||
issues: [malformedConfigIssue(detail)],
|
||||
};
|
||||
}
|
||||
|
||||
const themes: ThemePaletteDefinition[] = [];
|
||||
const issues: ServerConfigIssue[] = [];
|
||||
for (const [index, entry] of decodedEntries.value.entries()) {
|
||||
const decodedTheme = Schema.decodeUnknownExit(ThemePaletteDefinition)(entry);
|
||||
if (decodedTheme._tag === "Failure") {
|
||||
const detail = Cause.pretty(decodedTheme.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
yield* Effect.logWarning("ignoring invalid theme entry", {
|
||||
path: themesConfigPath,
|
||||
index,
|
||||
entry,
|
||||
error: detail,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
themes.push(decodedTheme.value);
|
||||
}
|
||||
|
||||
return { themes, issues };
|
||||
});
|
||||
|
||||
const configCacheKey = "themes" as const;
|
||||
const configCache = yield* Cache.make<
|
||||
typeof configCacheKey,
|
||||
ThemesConfigState,
|
||||
ThemesConfigError
|
||||
>({
|
||||
capacity: 1,
|
||||
lookup: () => loadConfigStateFromDisk,
|
||||
});
|
||||
const loadConfigStateFromCacheOrDisk = Cache.get(configCache, configCacheKey);
|
||||
|
||||
const revalidateAndEmit = updateSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
yield* Cache.invalidate(configCache, configCacheKey);
|
||||
const configState = yield* loadConfigStateFromCacheOrDisk;
|
||||
yield* emitChange(configState);
|
||||
}),
|
||||
);
|
||||
|
||||
const syncDefaultThemesOnStartup = updateSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
if (yield* readConfigExists) {
|
||||
yield* Cache.invalidate(configCache, configCacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeConfigAtomically([]);
|
||||
yield* Cache.invalidate(configCache, configCacheKey);
|
||||
}),
|
||||
);
|
||||
|
||||
const startWatcher = Effect.gen(function* () {
|
||||
const themesConfigDir = path.dirname(themesConfigPath);
|
||||
const themesConfigFile = path.basename(themesConfigPath);
|
||||
const themesConfigPathResolved = path.resolve(themesConfigPath);
|
||||
|
||||
yield* fs.makeDirectory(themesConfigDir, { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ThemesConfigError({
|
||||
configPath: themesConfigPath,
|
||||
detail: "failed to prepare themes config directory",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
yield* Stream.runForEach(fs.watch(themesConfigDir), (event) => {
|
||||
const isTargetConfigEvent =
|
||||
event.path === themesConfigFile ||
|
||||
event.path === themesConfigPath ||
|
||||
path.resolve(themesConfigDir, event.path) === themesConfigPathResolved;
|
||||
if (!isTargetConfigEvent) {
|
||||
return Effect.void;
|
||||
}
|
||||
return revalidateAndEmitSafely;
|
||||
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
const alreadyStarted = yield* Ref.get(startedRef);
|
||||
if (alreadyStarted) {
|
||||
return yield* Deferred.await(startedDeferred);
|
||||
}
|
||||
|
||||
yield* Ref.set(startedRef, true);
|
||||
const startup = Effect.gen(function* () {
|
||||
yield* startWatcher;
|
||||
yield* syncDefaultThemesOnStartup;
|
||||
yield* Cache.invalidate(configCache, configCacheKey);
|
||||
yield* loadConfigStateFromCacheOrDisk;
|
||||
});
|
||||
|
||||
const startupExit = yield* Effect.exit(startup);
|
||||
if (startupExit._tag === "Failure") {
|
||||
yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
|
||||
return yield* Effect.failCause(startupExit.cause);
|
||||
}
|
||||
|
||||
yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
ready: Deferred.await(startedDeferred),
|
||||
syncDefaultThemesOnStartup,
|
||||
loadConfigState: loadConfigStateFromCacheOrDisk,
|
||||
getSnapshot: loadConfigStateFromCacheOrDisk,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ThemesShape;
|
||||
});
|
||||
|
||||
export const ThemesLive = Layer.effect(Themes, makeThemes);
|
||||
@@ -503,6 +503,7 @@ describe("WebSocket Server", () => {
|
||||
host: undefined,
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
themesConfigPath: path.join(stateDir, "themes.json"),
|
||||
stateDir,
|
||||
staticDir: options.staticDir,
|
||||
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
|
||||
@@ -827,7 +828,9 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
themesConfigPath: path.join(stateDir, "themes.json"),
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
customThemes: [],
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
@@ -852,7 +855,9 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
themesConfigPath: path.join(stateDir, "themes.json"),
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
customThemes: [],
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
@@ -882,7 +887,9 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
themesConfigPath: path.join(stateDir, "themes.json"),
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
customThemes: [],
|
||||
issues: [
|
||||
{
|
||||
kind: "keybindings.malformed-config",
|
||||
@@ -921,13 +928,17 @@ describe("WebSocket Server", () => {
|
||||
const result = response.result as {
|
||||
cwd: string;
|
||||
keybindingsConfigPath: string;
|
||||
themesConfigPath: string;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
customThemes: Array<{ id: string }>;
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
providers: ReadonlyArray<ServerProviderStatus>;
|
||||
availableEditors: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||
expect(result.themesConfigPath).toBe(path.join(stateDir, "themes.json"));
|
||||
expect(result.customThemes).toEqual([]);
|
||||
expect(result.issues).toEqual([
|
||||
{
|
||||
kind: "keybindings.invalid-entry",
|
||||
@@ -971,6 +982,7 @@ describe("WebSocket Server", () => {
|
||||
expect(malformedPush.data).toEqual({
|
||||
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
|
||||
providers: defaultProviderStatuses,
|
||||
updated: ["keybindings"],
|
||||
});
|
||||
|
||||
const successPush = await rewriteKeybindingsAndWaitForPush(
|
||||
@@ -979,7 +991,11 @@ describe("WebSocket Server", () => {
|
||||
"[]",
|
||||
(push) => Array.isArray(push.data.issues) && push.data.issues.length === 0,
|
||||
);
|
||||
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
|
||||
expect(successPush.data).toEqual({
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
updated: ["keybindings"],
|
||||
});
|
||||
});
|
||||
|
||||
it("routes shell.openInEditor through the injected open service", async () => {
|
||||
@@ -1034,7 +1050,9 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
themesConfigPath: path.join(stateDir, "themes.json"),
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
customThemes: [],
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
@@ -1081,7 +1099,9 @@ describe("WebSocket Server", () => {
|
||||
expect(configResponse.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindingsConfigPath: keybindingsPath,
|
||||
themesConfigPath: path.join(stateDir, "themes.json"),
|
||||
keybindings: compileKeybindings(persistedConfig),
|
||||
customThemes: [],
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
|
||||
@@ -49,6 +49,7 @@ import { createLogger } from "./logger";
|
||||
import { GitManager } from "./git/Services/GitManager.ts";
|
||||
import { TerminalManager } from "./terminal/Services/Manager.ts";
|
||||
import { Keybindings } from "./keybindings";
|
||||
import { Themes } from "./themes";
|
||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
@@ -216,6 +217,7 @@ export type ServerRuntimeServices =
|
||||
| GitCore
|
||||
| TerminalManager
|
||||
| Keybindings
|
||||
| Themes
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
|
||||
@@ -241,6 +243,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
port,
|
||||
cwd,
|
||||
keybindingsConfigPath,
|
||||
themesConfigPath,
|
||||
staticDir,
|
||||
devUrl,
|
||||
authToken,
|
||||
@@ -253,6 +256,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const themesManager = yield* Themes;
|
||||
const providerHealth = yield* ProviderHealth;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -267,6 +271,15 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* themesManager.syncDefaultThemesOnStartup.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to sync themes defaults on startup", {
|
||||
path: error.configPath,
|
||||
detail: error.detail,
|
||||
cause: error.cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const providerStatuses = yield* providerHealth.getStatuses;
|
||||
|
||||
@@ -294,6 +307,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
(cause) => new ServerLifecycleError({ operation: "keybindingsRuntimeStart", cause }),
|
||||
),
|
||||
);
|
||||
yield* themesManager.start.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ServerLifecycleError({ operation: "themesRuntimeStart", cause }),
|
||||
),
|
||||
);
|
||||
yield* readiness.markKeybindingsReady;
|
||||
|
||||
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
|
||||
@@ -615,6 +633,15 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: event.issues,
|
||||
providers: providerStatuses,
|
||||
updated: ["keybindings"],
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
yield* Stream.runForEach(themesManager.streamChanges, (event) =>
|
||||
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: event.issues,
|
||||
providers: providerStatuses,
|
||||
updated: ["themes"],
|
||||
}),
|
||||
).pipe(Effect.forkIn(subscriptionsScope));
|
||||
|
||||
@@ -868,11 +895,14 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.serverGetConfig:
|
||||
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
|
||||
const themesConfig = yield* themesManager.loadConfigState;
|
||||
return {
|
||||
cwd,
|
||||
keybindingsConfigPath,
|
||||
themesConfigPath,
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
customThemes: themesConfig.themes,
|
||||
issues: [...keybindingsConfig.issues, ...themesConfig.issues],
|
||||
providers: providerStatuses,
|
||||
availableEditors,
|
||||
};
|
||||
|
||||
@@ -54,6 +54,7 @@ describe("makeServerPushBus", () => {
|
||||
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "queued-before-connect" }],
|
||||
providers: [],
|
||||
updated: ["keybindings"],
|
||||
});
|
||||
|
||||
const delivered = yield* pushBus.publishClient(
|
||||
@@ -71,6 +72,7 @@ describe("makeServerPushBus", () => {
|
||||
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [],
|
||||
providers: [],
|
||||
updated: ["themes"],
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => client.waitForSentCount(2));
|
||||
@@ -96,6 +98,7 @@ describe("makeServerPushBus", () => {
|
||||
data: {
|
||||
issues: [],
|
||||
providers: [],
|
||||
updated: ["themes"],
|
||||
},
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.9'
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
@@ -20,13 +20,6 @@ describe("normalizeCustomModelSlugs", () => {
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
|
||||
it("normalizes provider-specific aliases for claude", () => {
|
||||
expect(normalizeCustomModelSlugs(["sonnet"], "claudeAgent")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeAgent")).toEqual([
|
||||
"claude/custom-sonnet",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
@@ -35,6 +28,7 @@ describe("getAppModelOptions", () => {
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.4",
|
||||
"gpt-5.4-mini",
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
@@ -52,13 +46,6 @@ describe("getAppModelOptions", () => {
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
it("keeps a saved custom provider model available as an exact slug option", () => {
|
||||
const options = getAppModelOptions("claudeAgent", ["claude/custom-opus"], "claude/custom-opus");
|
||||
|
||||
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAppModelSelection", () => {
|
||||
@@ -78,11 +65,3 @@ describe("timestamp format defaults", () => {
|
||||
expect(DEFAULT_TIMESTAMP_FORMAT).toBe("locale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider-specific custom models", () => {
|
||||
it("includes provider-specific custom slugs in non-codex model lists", () => {
|
||||
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
|
||||
|
||||
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
||||
|
||||
@@ -12,7 +12,6 @@ export type TimestampFormat = (typeof TIMESTAMP_FORMAT_OPTIONS)[number];
|
||||
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
@@ -35,9 +34,7 @@ const AppSettingsSchema = Schema.Struct({
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
@@ -77,13 +74,6 @@ export function normalizeCustomModelSlugs(
|
||||
return normalizedModels;
|
||||
}
|
||||
|
||||
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
|
||||
};
|
||||
}
|
||||
export function getAppModelOptions(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
@@ -162,7 +152,10 @@ export function useAppSettings() {
|
||||
|
||||
const updateSettings = useCallback(
|
||||
(patch: Partial<AppSettings>) => {
|
||||
setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
|
||||
setSettings((prev) => ({
|
||||
...prev,
|
||||
...patch,
|
||||
}));
|
||||
},
|
||||
[setSettings],
|
||||
);
|
||||
|
||||
@@ -21,6 +21,10 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
@@ -99,7 +103,9 @@ function createBaseServerConfig(): ServerConfig {
|
||||
return {
|
||||
cwd: "/repo/project",
|
||||
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
|
||||
themesConfigPath: "/repo/project/.t3/themes.json",
|
||||
keybindings: [],
|
||||
customThemes: [],
|
||||
issues: [],
|
||||
providers: [
|
||||
{
|
||||
@@ -150,6 +156,25 @@ function createAssistantMessage(options: { id: MessageId; text: string; offsetSe
|
||||
};
|
||||
}
|
||||
|
||||
function createTerminalContext(input: {
|
||||
id: string;
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
text: string;
|
||||
}): TerminalContextDraft {
|
||||
return {
|
||||
id: input.id,
|
||||
threadId: THREAD_ID,
|
||||
terminalId: `terminal-${input.id}`,
|
||||
terminalLabel: input.terminalLabel,
|
||||
lineStart: input.lineStart,
|
||||
lineEnd: input.lineEnd,
|
||||
text: input.text,
|
||||
createdAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
@@ -531,6 +556,13 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForSendButton(): Promise<HTMLButtonElement> {
|
||||
return waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Send message"]'),
|
||||
"Unable to find send button.",
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForInteractionModeButton(
|
||||
expectedLabel: "Chat" | "Plan",
|
||||
): Promise<HTMLButtonElement> {
|
||||
@@ -1011,6 +1043,166 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps backspaced terminal context pills removed when a new one is added", async () => {
|
||||
const removedLabel = "Terminal 1 lines 1-2";
|
||||
const addedLabel = "Terminal 2 lines 9-10";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-removed",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 1,
|
||||
lineEnd: 2,
|
||||
text: "bun i\nno changes",
|
||||
}),
|
||||
);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-terminal-pill-backspace" as MessageId,
|
||||
targetText: "terminal pill backspace target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
composerEditor.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Backspace",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]).toBeUndefined();
|
||||
expect(document.body.textContent).not.toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-added",
|
||||
terminalLabel: "Terminal 2",
|
||||
lineStart: 9,
|
||||
lineEnd: 10,
|
||||
text: "git status\nOn branch main",
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[THREAD_ID];
|
||||
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]);
|
||||
expect(document.body.textContent).toContain(addedLabel);
|
||||
expect(document.body.textContent).not.toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("disables send when the composer only contains an expired terminal pill", async () => {
|
||||
const expiredLabel = "Terminal 1 line 4";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-expired-only",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
}),
|
||||
);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-expired-pill-disabled" as MessageId,
|
||||
targetText: "expired pill disabled target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(expiredLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(true);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("warns when sending text while omitting expired terminal pills", async () => {
|
||||
const expiredLabel = "Terminal 1 line 4";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-expired-send-warning",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
}),
|
||||
);
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.setPrompt(THREAD_ID, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-expired-pill-warning" as MessageId,
|
||||
targetText: "expired pill warning target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(expiredLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(false);
|
||||
sendButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(
|
||||
"Expired terminal context omitted from message",
|
||||
);
|
||||
expect(document.body.textContent).not.toContain(expiredLabel);
|
||||
expect(document.body.textContent).toContain("yoowaddup");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a pointer cursor for the running stop button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
|
||||
|
||||
describe("deriveComposerSendState", () => {
|
||||
it("treats expired terminal pills as non-sendable content", () => {
|
||||
const state = deriveComposerSendState({
|
||||
prompt: "\uFFFC",
|
||||
imageCount: 0,
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T12:52:29.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(state.trimmedPrompt).toBe("");
|
||||
expect(state.sendableTerminalContexts).toEqual([]);
|
||||
expect(state.expiredTerminalContextCount).toBe(1);
|
||||
expect(state.hasSendableContent).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps text sendable while excluding expired terminal pills", () => {
|
||||
const state = deriveComposerSendState({
|
||||
prompt: `yoo \uFFFC waddup`,
|
||||
imageCount: 0,
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T12:52:29.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(state.trimmedPrompt).toBe("yoo waddup");
|
||||
expect(state.expiredTerminalContextCount).toBe(1);
|
||||
expect(state.hasSendableContent).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
it("formats clear empty-state guidance", () => {
|
||||
expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
|
||||
title: "Expired terminal context won't be sent",
|
||||
description: "Remove it or re-add it to include terminal output.",
|
||||
});
|
||||
});
|
||||
|
||||
it("formats omission guidance for sent messages", () => {
|
||||
expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
|
||||
title: "Expired terminal contexts omitted from message",
|
||||
description: "Re-add it if you want that terminal output included.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,11 @@ import { randomUUID } from "~/lib/utils";
|
||||
import { getAppModelOptions } from "../appSettings";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { Schema } from "effect";
|
||||
import {
|
||||
filterTerminalContextsWithText,
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
|
||||
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
@@ -118,10 +123,49 @@ export function cloneComposerImageForRetry(
|
||||
|
||||
export function getCustomModelOptionsByProvider(settings: {
|
||||
customCodexModels: readonly string[];
|
||||
customClaudeModels: readonly string[];
|
||||
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
return {
|
||||
codex: getAppModelOptions("codex", settings.customCodexModels),
|
||||
claudeAgent: getAppModelOptions("claudeAgent", settings.customClaudeModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveComposerSendState(options: {
|
||||
prompt: string;
|
||||
imageCount: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
}): {
|
||||
trimmedPrompt: string;
|
||||
sendableTerminalContexts: TerminalContextDraft[];
|
||||
expiredTerminalContextCount: number;
|
||||
hasSendableContent: boolean;
|
||||
} {
|
||||
const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
|
||||
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
|
||||
const expiredTerminalContextCount =
|
||||
options.terminalContexts.length - sendableTerminalContexts.length;
|
||||
return {
|
||||
trimmedPrompt,
|
||||
sendableTerminalContexts,
|
||||
expiredTerminalContextCount,
|
||||
hasSendableContent:
|
||||
trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount: number,
|
||||
variant: "omitted" | "empty",
|
||||
): { title: string; description: string } {
|
||||
const count = Math.max(1, Math.floor(expiredTerminalContextCount));
|
||||
const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
|
||||
if (variant === "empty") {
|
||||
return {
|
||||
title: `${noun} won't be sent`,
|
||||
description: "Remove it or re-add it to include terminal output.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: `${noun} omitted from message`,
|
||||
description: "Re-add it if you want that terminal output included.",
|
||||
};
|
||||
}
|
||||
@@ -127,6 +127,14 @@ import {
|
||||
useComposerDraftStore,
|
||||
useComposerThreadDraft,
|
||||
} from "../composerDraftStore";
|
||||
import {
|
||||
appendTerminalContextsToPrompt,
|
||||
formatTerminalContextLabel,
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
type TerminalContextDraft,
|
||||
type TerminalContextSelection,
|
||||
} from "../lib/terminalContext";
|
||||
import { shouldUseCompactComposerFooter } from "./composerFooterLayout";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
|
||||
@@ -145,10 +153,12 @@ import { ComposerPlanFollowUpBanner } from "./chat/ComposerPlanFollowUpBanner";
|
||||
import { ProviderHealthBanner } from "./chat/ProviderHealthBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import {
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildTemporaryWorktreeBranchName,
|
||||
cloneComposerImageForRetry,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
deriveComposerSendState,
|
||||
getCustomModelOptionsByProvider,
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
LastInvokedScriptByProjectSchema,
|
||||
@@ -185,6 +195,23 @@ const extendReplacementRangeForTrailingSpace = (
|
||||
return text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd;
|
||||
};
|
||||
|
||||
const syncTerminalContextsByIds = (
|
||||
contexts: ReadonlyArray<TerminalContextDraft>,
|
||||
ids: ReadonlyArray<string>,
|
||||
): TerminalContextDraft[] => {
|
||||
const contextsById = new Map(contexts.map((context) => [context.id, context]));
|
||||
return ids.flatMap((id) => {
|
||||
const context = contextsById.get(id);
|
||||
return context ? [context] : [];
|
||||
});
|
||||
};
|
||||
|
||||
const terminalContextIdListsEqual = (
|
||||
contexts: ReadonlyArray<TerminalContextDraft>,
|
||||
ids: ReadonlyArray<string>,
|
||||
): boolean =>
|
||||
contexts.length === ids.length && contexts.every((context, index) => context.id === ids[index]);
|
||||
|
||||
interface ChatViewProps {
|
||||
threadId: ThreadId;
|
||||
}
|
||||
@@ -209,6 +236,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const composerDraft = useComposerThreadDraft(threadId);
|
||||
const prompt = composerDraft.prompt;
|
||||
const composerImages = composerDraft.images;
|
||||
const composerTerminalContexts = composerDraft.terminalContexts;
|
||||
const composerSendState = useMemo(
|
||||
() =>
|
||||
deriveComposerSendState({
|
||||
prompt,
|
||||
imageCount: composerImages.length,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
}),
|
||||
[composerImages.length, composerTerminalContexts, prompt],
|
||||
);
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
|
||||
@@ -222,6 +259,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
|
||||
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
|
||||
const insertComposerDraftTerminalContext = useComposerDraftStore(
|
||||
(store) => store.insertTerminalContext,
|
||||
);
|
||||
const addComposerDraftTerminalContexts = useComposerDraftStore(
|
||||
(store) => store.addTerminalContexts,
|
||||
);
|
||||
const removeComposerDraftTerminalContext = useComposerDraftStore(
|
||||
(store) => store.removeTerminalContext,
|
||||
);
|
||||
const setComposerDraftTerminalContexts = useComposerDraftStore(
|
||||
(store) => store.setTerminalContexts,
|
||||
);
|
||||
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.clearPersistedAttachments,
|
||||
);
|
||||
@@ -248,6 +297,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
|
||||
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
|
||||
optimisticUserMessagesRef.current = optimisticUserMessages;
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>(composerTerminalContexts);
|
||||
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
|
||||
Record<ThreadId, string | null>
|
||||
>({});
|
||||
@@ -270,7 +320,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
|
||||
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
|
||||
// When set, the thread-change reset effect will open the sidebar instead of closing it.
|
||||
// Used by "Implement in new thread" to carry the sidebar-open intent across navigation.
|
||||
// Used by "Implement in a new thread" to carry the sidebar-open intent across navigation.
|
||||
const planSidebarOpenOnNextThreadRef = useRef(false);
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
@@ -350,12 +400,40 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
},
|
||||
[addComposerDraftImages, threadId],
|
||||
);
|
||||
const addComposerTerminalContextsToDraft = useCallback(
|
||||
(contexts: TerminalContextDraft[]) => {
|
||||
addComposerDraftTerminalContexts(threadId, contexts);
|
||||
},
|
||||
[addComposerDraftTerminalContexts, threadId],
|
||||
);
|
||||
const removeComposerImageFromDraft = useCallback(
|
||||
(imageId: string) => {
|
||||
removeComposerDraftImage(threadId, imageId);
|
||||
},
|
||||
[removeComposerDraftImage, threadId],
|
||||
);
|
||||
const removeComposerTerminalContextFromDraft = useCallback(
|
||||
(contextId: string) => {
|
||||
const contextIndex = composerTerminalContexts.findIndex(
|
||||
(context) => context.id === contextId,
|
||||
);
|
||||
if (contextIndex < 0) {
|
||||
return;
|
||||
}
|
||||
const nextPrompt = removeInlineTerminalContextPlaceholder(promptRef.current, contextIndex);
|
||||
promptRef.current = nextPrompt.prompt;
|
||||
setPrompt(nextPrompt.prompt);
|
||||
removeComposerDraftTerminalContext(threadId, contextId);
|
||||
setComposerCursor(nextPrompt.cursor);
|
||||
setComposerTrigger(
|
||||
detectComposerTrigger(
|
||||
nextPrompt.prompt,
|
||||
expandCollapsedComposerCursor(nextPrompt.prompt, nextPrompt.cursor),
|
||||
),
|
||||
);
|
||||
},
|
||||
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
|
||||
);
|
||||
|
||||
const serverThread = threads.find((t) => t.id === threadId);
|
||||
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
|
||||
@@ -500,14 +578,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
selectedProvider,
|
||||
activeThread?.model ?? activeProject?.model ?? getDefaultModel(selectedProvider),
|
||||
);
|
||||
const customModelsByProvider = useMemo(
|
||||
() => ({
|
||||
codex: settings.customCodexModels,
|
||||
claudeAgent: settings.customClaudeModels,
|
||||
}),
|
||||
[settings.customClaudeModels, settings.customCodexModels],
|
||||
);
|
||||
const customModelsForSelectedProvider = customModelsByProvider[selectedProvider];
|
||||
const customModelsForSelectedProvider = settings.customCodexModels;
|
||||
const selectedModel = useMemo(() => {
|
||||
const draftModel = composerDraft.model;
|
||||
if (!draftModel) {
|
||||
@@ -1100,6 +1171,48 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
focusComposer();
|
||||
});
|
||||
}, [focusComposer]);
|
||||
const addTerminalContextToDraft = useCallback(
|
||||
(selection: TerminalContextSelection) => {
|
||||
if (!activeThread) {
|
||||
return;
|
||||
}
|
||||
const snapshot = composerEditorRef.current?.readSnapshot() ?? {
|
||||
value: promptRef.current,
|
||||
cursor: composerCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor),
|
||||
terminalContextIds: composerTerminalContexts.map((context) => context.id),
|
||||
};
|
||||
const insertion = insertInlineTerminalContextPlaceholder(
|
||||
snapshot.value,
|
||||
snapshot.expandedCursor,
|
||||
);
|
||||
const nextCollapsedCursor = collapseExpandedComposerCursor(
|
||||
insertion.prompt,
|
||||
insertion.cursor,
|
||||
);
|
||||
const inserted = insertComposerDraftTerminalContext(
|
||||
activeThread.id,
|
||||
insertion.prompt,
|
||||
{
|
||||
id: randomUUID(),
|
||||
threadId: activeThread.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
...selection,
|
||||
},
|
||||
insertion.contextIndex,
|
||||
);
|
||||
if (!inserted) {
|
||||
return;
|
||||
}
|
||||
promptRef.current = insertion.prompt;
|
||||
setComposerCursor(nextCollapsedCursor);
|
||||
setComposerTrigger(detectComposerTrigger(insertion.prompt, insertion.cursor));
|
||||
window.requestAnimationFrame(() => {
|
||||
composerEditorRef.current?.focusAt(nextCollapsedCursor);
|
||||
});
|
||||
},
|
||||
[activeThread, composerCursor, composerTerminalContexts, insertComposerDraftTerminalContext],
|
||||
);
|
||||
const setTerminalOpen = useCallback(
|
||||
(open: boolean) => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -1737,6 +1850,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
composerImagesRef.current = composerImages;
|
||||
}, [composerImages]);
|
||||
|
||||
useEffect(() => {
|
||||
composerTerminalContextsRef.current = composerTerminalContexts;
|
||||
}, [composerTerminalContexts]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
if (activeThread.messages.length === 0) {
|
||||
@@ -2211,7 +2328,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onAdvanceActivePendingUserInput();
|
||||
return;
|
||||
}
|
||||
const trimmed = prompt.trim();
|
||||
const promptForSend = promptRef.current;
|
||||
const {
|
||||
trimmedPrompt: trimmed,
|
||||
sendableTerminalContexts: sendableComposerTerminalContexts,
|
||||
expiredTerminalContextCount,
|
||||
hasSendableContent,
|
||||
} = deriveComposerSendState({
|
||||
prompt: promptForSend,
|
||||
imageCount: composerImages.length,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
});
|
||||
if (showPlanFollowUpPrompt && activeProposedPlan) {
|
||||
const followUp = resolvePlanFollowUpSubmission({
|
||||
draftText: trimmed,
|
||||
@@ -2229,7 +2356,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const standaloneSlashCommand =
|
||||
composerImages.length === 0 ? parseStandaloneComposerSlashCommand(trimmed) : null;
|
||||
composerImages.length === 0 && sendableComposerTerminalContexts.length === 0
|
||||
? parseStandaloneComposerSlashCommand(trimmed)
|
||||
: null;
|
||||
if (standaloneSlashCommand) {
|
||||
await handleInteractionModeChange(standaloneSlashCommand);
|
||||
promptRef.current = "";
|
||||
@@ -2239,7 +2368,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerTrigger(null);
|
||||
return;
|
||||
}
|
||||
if (!trimmed && composerImages.length === 0) return;
|
||||
if (!hasSendableContent) {
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
const toastCopy = buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount,
|
||||
"empty",
|
||||
);
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!activeProject) return;
|
||||
const threadIdForSend = activeThread.id;
|
||||
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
|
||||
@@ -2264,6 +2406,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
|
||||
const messageTextForSend = appendTerminalContextsToPrompt(
|
||||
promptForSend,
|
||||
composerTerminalContextsSnapshot,
|
||||
);
|
||||
const messageIdForSend = newMessageId();
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const turnAttachmentsPromise = Promise.all(
|
||||
@@ -2288,7 +2435,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{
|
||||
id: messageIdForSend,
|
||||
role: "user",
|
||||
text: trimmed,
|
||||
text: messageTextForSend,
|
||||
...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
|
||||
createdAt: messageCreatedAt,
|
||||
streaming: false,
|
||||
@@ -2299,6 +2446,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
forceStickToBottom();
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
const toastCopy = buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount,
|
||||
"omitted",
|
||||
);
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
});
|
||||
}
|
||||
promptRef.current = "";
|
||||
clearComposerDraftContent(threadIdForSend);
|
||||
setComposerHighlightedItemId(null);
|
||||
@@ -2346,6 +2504,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (!titleSeed) {
|
||||
if (firstComposerImageName) {
|
||||
titleSeed = `Image: ${firstComposerImageName}`;
|
||||
} else if (composerTerminalContextsSnapshot.length > 0) {
|
||||
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
|
||||
} else {
|
||||
titleSeed = "New thread";
|
||||
}
|
||||
@@ -2426,7 +2586,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
message: {
|
||||
messageId: messageIdForSend,
|
||||
role: "user",
|
||||
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
attachments: turnAttachments,
|
||||
},
|
||||
model: selectedModel || undefined,
|
||||
@@ -2454,7 +2614,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (
|
||||
!turnStartSucceeded &&
|
||||
promptRef.current.length === 0 &&
|
||||
composerImagesRef.current.length === 0
|
||||
composerImagesRef.current.length === 0 &&
|
||||
composerTerminalContextsRef.current.length === 0
|
||||
) {
|
||||
setOptimisticUserMessages((existing) => {
|
||||
const removed = existing.filter((message) => message.id === messageIdForSend);
|
||||
@@ -2464,11 +2625,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const next = existing.filter((message) => message.id !== messageIdForSend);
|
||||
return next.length === existing.length ? existing : next;
|
||||
});
|
||||
promptRef.current = trimmed;
|
||||
setPrompt(trimmed);
|
||||
setComposerCursor(collapseExpandedComposerCursor(trimmed, trimmed.length));
|
||||
promptRef.current = promptForSend;
|
||||
setPrompt(promptForSend);
|
||||
setComposerCursor(collapseExpandedComposerCursor(promptForSend, promptForSend.length));
|
||||
addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
|
||||
setComposerTrigger(detectComposerTrigger(trimmed, trimmed.length));
|
||||
addComposerTerminalContextsToDraft(composerTerminalContextsSnapshot);
|
||||
setComposerTrigger(detectComposerTrigger(promptForSend, promptForSend.length));
|
||||
}
|
||||
setThreadError(
|
||||
threadIdForSend,
|
||||
@@ -2889,17 +3051,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerDraftProvider(activeThread.id, provider);
|
||||
setComposerDraftModel(
|
||||
activeThread.id,
|
||||
resolveAppModelSelection(provider, customModelsByProvider[provider], model),
|
||||
resolveAppModelSelection(provider, settings.customCodexModels, model),
|
||||
);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
customModelsByProvider,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModel,
|
||||
setComposerDraftProvider,
|
||||
settings.customCodexModels,
|
||||
],
|
||||
);
|
||||
const onEffortSelect = useCallback(
|
||||
@@ -2976,6 +3138,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
} => {
|
||||
const editorSnapshot = composerEditorRef.current?.readSnapshot();
|
||||
if (editorSnapshot) {
|
||||
@@ -2985,8 +3148,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
value: promptRef.current,
|
||||
cursor: composerCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor),
|
||||
terminalContextIds: composerTerminalContexts.map((context) => context.id),
|
||||
};
|
||||
}, [composerCursor]);
|
||||
}, [composerCursor, composerTerminalContexts]);
|
||||
|
||||
const resolveActiveComposerTrigger = useCallback((): {
|
||||
snapshot: { value: string; cursor: number; expandedCursor: number };
|
||||
@@ -3102,6 +3266,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
nextCursor: number,
|
||||
expandedCursor: number,
|
||||
cursorAdjacentToMention: boolean,
|
||||
terminalContextIds: string[],
|
||||
) => {
|
||||
if (activePendingProgress?.activeQuestion && activePendingUserInput) {
|
||||
onChangeActivePendingUserInputCustomAnswer(
|
||||
@@ -3115,6 +3280,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
if (!terminalContextIdListsEqual(composerTerminalContexts, terminalContextIds)) {
|
||||
setComposerDraftTerminalContexts(
|
||||
threadId,
|
||||
syncTerminalContextsByIds(composerTerminalContexts, terminalContextIds),
|
||||
);
|
||||
}
|
||||
setComposerCursor(nextCursor);
|
||||
setComposerTrigger(
|
||||
cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
|
||||
@@ -3123,8 +3294,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
[
|
||||
activePendingProgress?.activeQuestion,
|
||||
activePendingUserInput,
|
||||
composerTerminalContexts,
|
||||
onChangeActivePendingUserInputCustomAnswer,
|
||||
setPrompt,
|
||||
setComposerDraftTerminalContexts,
|
||||
threadId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3391,75 +3565,77 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isComposerApprovalState &&
|
||||
pendingUserInputs.length === 0 &&
|
||||
composerImages.length > 0 && (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{composerImages.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(
|
||||
composerImages,
|
||||
image.id,
|
||||
);
|
||||
if (!preview) return;
|
||||
setExpandedImage(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-64 whitespace-normal leading-tight"
|
||||
>
|
||||
Draft attachment could not be saved locally and may be lost on
|
||||
navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
{!isComposerApprovalState && pendingUserInputs.length === 0 && (
|
||||
<>
|
||||
{composerImages.length > 0 && (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{composerImages.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(
|
||||
composerImages,
|
||||
image.id,
|
||||
);
|
||||
if (!preview) return;
|
||||
setExpandedImage(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-64 whitespace-normal leading-tight"
|
||||
>
|
||||
Draft attachment could not be saved locally and may be lost on
|
||||
navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<ComposerPromptEditor
|
||||
ref={composerEditorRef}
|
||||
value={
|
||||
@@ -3470,6 +3646,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: prompt
|
||||
}
|
||||
cursor={composerCursor}
|
||||
terminalContexts={
|
||||
!isComposerApprovalState && pendingUserInputs.length === 0
|
||||
? composerTerminalContexts
|
||||
: []
|
||||
}
|
||||
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
|
||||
onChange={onPromptChange}
|
||||
onCommandKeyDown={onComposerCommandKey}
|
||||
onPaste={onComposerPaste}
|
||||
@@ -3736,7 +3918,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
disabled={isSendBusy || isConnecting}
|
||||
onClick={() => void onImplementPlanInNewThread()}
|
||||
>
|
||||
Implement in new thread
|
||||
Implement in a new thread
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
@@ -3747,9 +3929,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
type="submit"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
disabled={
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
(!prompt.trim() && composerImages.length === 0)
|
||||
isSendBusy || isConnecting || !composerSendState.hasSendableContent
|
||||
}
|
||||
aria-label={
|
||||
isConnecting
|
||||
@@ -3880,6 +4060,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onActiveTerminalChange={activateTerminal}
|
||||
onCloseTerminal={closeTerminal}
|
||||
onHeightChange={setTerminalHeight}
|
||||
onAddTerminalContext={addTerminalContextToDraft}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -26,8 +26,10 @@ import {
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
$getRoot,
|
||||
DecoratorNode,
|
||||
type ElementNode,
|
||||
type LexicalNode,
|
||||
type SerializedLexicalNode,
|
||||
TextNode,
|
||||
type EditorConfig,
|
||||
type EditorState,
|
||||
@@ -36,14 +38,17 @@ import {
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import {
|
||||
createContext,
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ClipboardEventHandler,
|
||||
type ReactElement,
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
@@ -51,11 +56,21 @@ import {
|
||||
clampCollapsedComposerCursor,
|
||||
collapseExpandedComposerCursor,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
} from "~/composer-logic";
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
} from "./composerInlineChip";
|
||||
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
@@ -68,6 +83,21 @@ type SerializedComposerMentionNode = Spread<
|
||||
SerializedTextNode
|
||||
>;
|
||||
|
||||
type SerializedComposerTerminalContextNode = Spread<
|
||||
{
|
||||
context: TerminalContextDraft;
|
||||
type: "composer-terminal-context";
|
||||
version: 1;
|
||||
},
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
const ComposerTerminalContextActionsContext = createContext<{
|
||||
onRemoveTerminalContext: (contextId: string) => void;
|
||||
}>({
|
||||
onRemoveTerminalContext: () => {},
|
||||
});
|
||||
|
||||
class ComposerMentionNode extends TextNode {
|
||||
__path: string;
|
||||
|
||||
@@ -100,8 +130,7 @@ class ComposerMentionNode extends TextNode {
|
||||
|
||||
override createDOM(_config: EditorConfig): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className =
|
||||
"inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
|
||||
dom.contentEditable = "false";
|
||||
dom.setAttribute("spellcheck", "false");
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
@@ -141,15 +170,76 @@ function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
function inferMentionPathKind(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
|
||||
return <ComposerPendingTerminalContextChip context={props.context} />;
|
||||
}
|
||||
|
||||
class ComposerTerminalContextNode extends DecoratorNode<ReactElement> {
|
||||
__context: TerminalContextDraft;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-terminal-context";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
|
||||
static override clone(node: ComposerTerminalContextNode): ComposerTerminalContextNode {
|
||||
return new ComposerTerminalContextNode(node.__context, node.__key);
|
||||
}
|
||||
return "directory";
|
||||
|
||||
static override importJSON(
|
||||
serializedNode: SerializedComposerTerminalContextNode,
|
||||
): ComposerTerminalContextNode {
|
||||
return $createComposerTerminalContextNode(serializedNode.context);
|
||||
}
|
||||
|
||||
constructor(context: TerminalContextDraft, key?: NodeKey) {
|
||||
super(key);
|
||||
this.__context = context;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerTerminalContextNode {
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
context: this.__context,
|
||||
type: "composer-terminal-context",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = "inline-flex align-middle leading-none";
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
return INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
return <ComposerTerminalContextDecorator context={this.__context} />;
|
||||
}
|
||||
}
|
||||
|
||||
function $createComposerTerminalContextNode(
|
||||
context: TerminalContextDraft,
|
||||
): ComposerTerminalContextNode {
|
||||
return $applyNodeReplacement(new ComposerTerminalContextNode(context));
|
||||
}
|
||||
|
||||
type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode;
|
||||
|
||||
function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
|
||||
return (
|
||||
candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode
|
||||
);
|
||||
}
|
||||
|
||||
function resolvedThemeFromDocument(): "light" | "dark" {
|
||||
@@ -165,25 +255,91 @@ function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||
const icon = document.createElement("img");
|
||||
icon.alt = "";
|
||||
icon.ariaHidden = "true";
|
||||
icon.className = "size-3.5 shrink-0 opacity-85";
|
||||
icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
|
||||
icon.loading = "lazy";
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "truncate select-none leading-tight";
|
||||
label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
|
||||
label.textContent = basenameOfPath(pathValue);
|
||||
|
||||
container.append(icon, label);
|
||||
}
|
||||
|
||||
function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>): string {
|
||||
return contexts
|
||||
.map((context) =>
|
||||
[
|
||||
context.id,
|
||||
context.threadId,
|
||||
context.terminalId,
|
||||
context.terminalLabel,
|
||||
context.lineStart,
|
||||
context.lineEnd,
|
||||
context.createdAt,
|
||||
context.text,
|
||||
].join("\u001f"),
|
||||
)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
function clampExpandedCursor(value: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return value.length;
|
||||
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function getComposerInlineTokenTextLength(_node: ComposerInlineTokenNode): 1 {
|
||||
return 1;
|
||||
}
|
||||
|
||||
function getComposerInlineTokenExpandedTextLength(node: ComposerInlineTokenNode): number {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
|
||||
function getAbsoluteOffsetForInlineTokenPoint(
|
||||
node: ComposerInlineTokenNode,
|
||||
absoluteOffset: number,
|
||||
pointOffset: number,
|
||||
): number {
|
||||
return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenTextLength(node) : 0);
|
||||
}
|
||||
|
||||
function getExpandedAbsoluteOffsetForInlineTokenPoint(
|
||||
node: ComposerInlineTokenNode,
|
||||
absoluteOffset: number,
|
||||
pointOffset: number,
|
||||
): number {
|
||||
return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenExpandedTextLength(node) : 0);
|
||||
}
|
||||
|
||||
function findSelectionPointForInlineToken(
|
||||
node: ComposerInlineTokenNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "element" } | null {
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === getComposerInlineTokenTextLength(node)) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= getComposerInlineTokenTextLength(node);
|
||||
return null;
|
||||
}
|
||||
|
||||
function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return 1;
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenTextLength(node);
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
@@ -198,6 +354,9 @@ function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
}
|
||||
|
||||
function getComposerNodeExpandedTextLength(node: LexicalNode): number {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenExpandedTextLength(node);
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
@@ -233,10 +392,13 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return offset + (pointOffset > 0 ? 1 : 0);
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
@@ -277,10 +439,13 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return offset + (pointOffset > 0 ? node.getTextContentSize() : 0);
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
@@ -305,25 +470,10 @@ function findSelectionPointAtOffset(
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === 1) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= 1;
|
||||
return null;
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
@@ -438,40 +588,67 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function $setComposerEditorPrompt(prompt: string): void {
|
||||
function $setComposerEditorPrompt(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>,
|
||||
): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
const paragraph = $createParagraphNode();
|
||||
root.append(paragraph);
|
||||
|
||||
const segments = splitPromptIntoComposerSegments(prompt);
|
||||
const segments = splitPromptIntoComposerSegments(prompt, terminalContexts);
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
paragraph.append($createComposerMentionNode(segment.path));
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (segment.context) {
|
||||
paragraph.append($createComposerTerminalContextNode(segment.context));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$appendTextWithLineBreaks(paragraph, segment.text);
|
||||
}
|
||||
}
|
||||
|
||||
function collectTerminalContextIds(node: LexicalNode): string[] {
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return [node.__context.id];
|
||||
}
|
||||
if ($isElementNode(node)) {
|
||||
return node.getChildren().flatMap((child) => collectTerminalContextIds(child));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export interface ComposerPromptEditorHandle {
|
||||
focus: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
focusAtEnd: () => void;
|
||||
readSnapshot: () => { value: string; cursor: number; expandedCursor: number };
|
||||
readSnapshot: () => {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
};
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorProps {
|
||||
value: string;
|
||||
cursor: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
onRemoveTerminalContext: (contextId: string) => void;
|
||||
onChange: (
|
||||
nextValue: string,
|
||||
nextCursor: number,
|
||||
expandedCursor: number,
|
||||
cursorAdjacentToMention: boolean,
|
||||
terminalContextIds: string[],
|
||||
) => void;
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
@@ -540,7 +717,7 @@ function ComposerCommandKeyPlugin(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionArrowPlugin() {
|
||||
function ComposerInlineTokenArrowPlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -554,7 +731,7 @@ function ComposerMentionArrowPlugin() {
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
if (currentOffset <= 0) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "left")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset - 1;
|
||||
@@ -581,7 +758,7 @@ function ComposerMentionArrowPlugin() {
|
||||
const composerLength = $getComposerRootLength();
|
||||
if (currentOffset >= composerLength) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "right")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset + 1;
|
||||
@@ -606,7 +783,7 @@ function ComposerMentionArrowPlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionSelectionNormalizePlugin() {
|
||||
function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -616,7 +793,7 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
if (!(anchorNode instanceof ComposerMentionNode)) return;
|
||||
if (!isComposerInlineTokenNode(anchorNode)) return;
|
||||
if (selection.anchor.offset === 0) return;
|
||||
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
|
||||
afterOffset = beforeOffset + 1;
|
||||
@@ -634,8 +811,9 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
function ComposerInlineTokenBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const { onRemoveTerminalContext } = useContext(ComposerTerminalContextActionsContext);
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
@@ -647,18 +825,23 @@ function ComposerMentionBackspacePlugin() {
|
||||
}
|
||||
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const removeMentionNode = (candidate: unknown): boolean => {
|
||||
if (!(candidate instanceof ComposerMentionNode)) {
|
||||
const selectionOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const removeInlineTokenNode = (candidate: unknown): boolean => {
|
||||
if (!isComposerInlineTokenNode(candidate)) {
|
||||
return false;
|
||||
}
|
||||
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
const tokenStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
candidate.remove();
|
||||
$setSelectionAtComposerOffset(mentionStart);
|
||||
if (candidate instanceof ComposerTerminalContextNode) {
|
||||
onRemoveTerminalContext(candidate.__context.id);
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
} else {
|
||||
$setSelectionAtComposerOffset(tokenStart);
|
||||
}
|
||||
event?.preventDefault();
|
||||
return true;
|
||||
};
|
||||
|
||||
if (removeMentionNode(anchorNode)) {
|
||||
if (removeInlineTokenNode(anchorNode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -666,13 +849,13 @@ function ComposerMentionBackspacePlugin() {
|
||||
if (selection.anchor.offset > 0) {
|
||||
return false;
|
||||
}
|
||||
if (removeMentionNode(anchorNode.getPreviousSibling())) {
|
||||
if (removeInlineTokenNode(anchorNode.getPreviousSibling())) {
|
||||
return true;
|
||||
}
|
||||
const parent = anchorNode.getParent();
|
||||
if ($isElementNode(parent)) {
|
||||
const index = anchorNode.getIndexWithinParent();
|
||||
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
|
||||
if (index > 0 && removeInlineTokenNode(parent.getChildAtIndex(index - 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -681,7 +864,7 @@ function ComposerMentionBackspacePlugin() {
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
if (childIndex >= 0 && removeInlineTokenNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -690,7 +873,7 @@ function ComposerMentionBackspacePlugin() {
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}, [editor]);
|
||||
}, [editor, onRemoveTerminalContext]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -698,9 +881,11 @@ function ComposerMentionBackspacePlugin() {
|
||||
function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
@@ -709,12 +894,19 @@ function ComposerPromptEditorInner({
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const onChangeRef = useRef(onChange);
|
||||
const initialCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const terminalContextsSignature = terminalContextSignature(terminalContexts);
|
||||
const terminalContextsSignatureRef = useRef(terminalContextsSignature);
|
||||
const snapshotRef = useRef({
|
||||
value,
|
||||
cursor: initialCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, initialCursor),
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
});
|
||||
const isApplyingControlledUpdateRef = useRef(false);
|
||||
const terminalContextActions = useMemo(
|
||||
() => ({ onRemoveTerminalContext }),
|
||||
[onRemoveTerminalContext],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
@@ -727,7 +919,12 @@ function ComposerPromptEditorInner({
|
||||
useLayoutEffect(() => {
|
||||
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
|
||||
const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
|
||||
if (
|
||||
previousSnapshot.value === value &&
|
||||
previousSnapshot.cursor === normalizedCursor &&
|
||||
!contextsChanged
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -735,28 +932,30 @@ function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor: normalizedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, normalizedCursor),
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
};
|
||||
terminalContextsSignatureRef.current = terminalContextsSignature;
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
|
||||
if (previousSnapshot.value === value && !isFocused) {
|
||||
if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
|
||||
return;
|
||||
}
|
||||
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
const valueChanged = previousSnapshot.value !== value;
|
||||
if (previousSnapshot.value !== value) {
|
||||
$setComposerEditorPrompt(value);
|
||||
const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
|
||||
if (shouldRewriteEditorState) {
|
||||
$setComposerEditorPrompt(value, terminalContexts);
|
||||
}
|
||||
if (valueChanged || isFocused) {
|
||||
if (shouldRewriteEditorState || isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
}
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
}, [cursor, editor, value]);
|
||||
}, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
@@ -771,12 +970,14 @@ function ComposerPromptEditorInner({
|
||||
value: snapshotRef.current.value,
|
||||
cursor: boundedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
|
||||
terminalContextIds: snapshotRef.current.terminalContextIds,
|
||||
};
|
||||
onChangeRef.current(
|
||||
snapshotRef.current.value,
|
||||
boundedCursor,
|
||||
snapshotRef.current.expandedCursor,
|
||||
false,
|
||||
snapshotRef.current.terminalContextIds,
|
||||
);
|
||||
},
|
||||
[editor],
|
||||
@@ -786,6 +987,7 @@ function ComposerPromptEditorInner({
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
} => {
|
||||
let snapshot = snapshotRef.current;
|
||||
editor.getEditorState().read(() => {
|
||||
@@ -803,10 +1005,12 @@ function ComposerPromptEditorInner({
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
snapshot = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
});
|
||||
snapshotRef.current = snapshot;
|
||||
@@ -849,11 +1053,14 @@ function ComposerPromptEditorInner({
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (
|
||||
previousSnapshot.value === nextValue &&
|
||||
previousSnapshot.cursor === nextCursor &&
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor &&
|
||||
previousSnapshot.terminalContextIds.length === terminalContextIds.length &&
|
||||
previousSnapshot.terminalContextIds.every((id, index) => id === terminalContextIds[index])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -864,43 +1071,54 @@ function ComposerPromptEditorInner({
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, cursorAdjacentToMention);
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(
|
||||
nextValue,
|
||||
nextCursor,
|
||||
nextExpandedCursor,
|
||||
cursorAdjacentToMention,
|
||||
terminalContextIds,
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerMentionArrowPlugin />
|
||||
<ComposerMentionSelectionNormalizePlugin />
|
||||
<ComposerMentionBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
<ComposerTerminalContextActionsContext.Provider value={terminalContextActions}>
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
terminalContexts.length > 0 ? null : (
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerInlineTokenArrowPlugin />
|
||||
<ComposerInlineTokenSelectionNormalizePlugin />
|
||||
<ComposerInlineTokenBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
</ComposerTerminalContextActionsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -908,17 +1126,29 @@ export const ComposerPromptEditor = forwardRef<
|
||||
ComposerPromptEditorHandle,
|
||||
ComposerPromptEditorProps
|
||||
>(function ComposerPromptEditor(
|
||||
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
|
||||
{
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialTerminalContextsRef = useRef(terminalContexts);
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode],
|
||||
nodes: [ComposerMentionNode, ComposerTerminalContextNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current);
|
||||
$setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
@@ -932,8 +1162,10 @@ export const ComposerPromptEditor = forwardRef<
|
||||
<ComposerPromptEditorInner
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
terminalContexts={terminalContexts}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onRemoveTerminalContext={onRemoveTerminalContext}
|
||||
onChange={onChange}
|
||||
onPaste={onPaste}
|
||||
editorRef={ref}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
import { useAppSettings } from "~/appSettings";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Checkbox } from "~/components/ui/checkbox";
|
||||
import {
|
||||
@@ -154,6 +155,7 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
|
||||
const { settings } = useAppSettings();
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||
[activeThreadId],
|
||||
@@ -191,7 +193,11 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const runImmediateGitActionMutation = useMutation(
|
||||
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
gitRunStackedActionMutationOptions({
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
model: settings.textGenerationModel ?? null,
|
||||
}),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
|
||||
@@ -41,7 +41,9 @@ function createBaseServerConfig(): ServerConfig {
|
||||
return {
|
||||
cwd: "/repo/project",
|
||||
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
|
||||
themesConfigPath: "/repo/project/.t3/themes.json",
|
||||
keybindings: [],
|
||||
customThemes: [],
|
||||
issues: [],
|
||||
providers: [
|
||||
{
|
||||
@@ -203,6 +205,7 @@ function sendServerConfigUpdatedPush(issues: Array<{ kind: string; message: stri
|
||||
data: {
|
||||
issues,
|
||||
providers: fixture.serverConfig.providers,
|
||||
updated: ["keybindings"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -51,7 +51,7 @@ export function resolveThreadRowClassName(input: {
|
||||
isSelected: boolean;
|
||||
}): string {
|
||||
const baseClassName =
|
||||
"h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
|
||||
"h-7 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
|
||||
|
||||
if (input.isSelected && input.isActive) {
|
||||
return cn(
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type DragEndEvent,
|
||||
} from "@dnd-kit/core";
|
||||
import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
|
||||
import { restrictToParentElement, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
@@ -561,7 +561,6 @@ export default function Sidebar() {
|
||||
if (!api) return;
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
const threadProject = projects.find((project) => project.id === thread.projectId);
|
||||
// When bulk-deleting, exclude the other threads being deleted so
|
||||
// getOrphanedWorktreePathForThread correctly detects that no surviving
|
||||
@@ -665,7 +664,7 @@ export default function Sidebar() {
|
||||
],
|
||||
);
|
||||
|
||||
const { copyToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
onCopy: (ctx) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
@@ -681,21 +680,40 @@ export default function Sidebar() {
|
||||
});
|
||||
},
|
||||
});
|
||||
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
|
||||
onCopy: (ctx) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Path copied",
|
||||
description: ctx.path,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy path",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
},
|
||||
});
|
||||
const handleThreadContextMenu = useCallback(
|
||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
const threadWorkspacePath =
|
||||
thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
{ id: "copy-thread-id", label: "Copy Thread ID" },
|
||||
{ id: "delete", label: "Delete", destructive: true },
|
||||
],
|
||||
position,
|
||||
);
|
||||
const thread = threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
|
||||
if (clicked === "rename") {
|
||||
setRenamingThreadId(threadId);
|
||||
@@ -708,8 +726,20 @@ export default function Sidebar() {
|
||||
markThreadUnread(threadId);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
if (!threadWorkspacePath) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Path unavailable",
|
||||
description: "This thread does not have a workspace path to copy.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath });
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-thread-id") {
|
||||
copyToClipboard(threadId, { threadId });
|
||||
copyThreadIdToClipboard(threadId, { threadId });
|
||||
return;
|
||||
}
|
||||
if (clicked !== "delete") return;
|
||||
@@ -726,7 +756,15 @@ export default function Sidebar() {
|
||||
}
|
||||
await deleteThread(threadId);
|
||||
},
|
||||
[appSettings.confirmThreadDelete, copyToClipboard, deleteThread, markThreadUnread, threads],
|
||||
[
|
||||
appSettings.confirmThreadDelete,
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
projectCwdById,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const handleMultiSelectContextMenu = useCallback(
|
||||
@@ -1282,7 +1320,7 @@ export default function Sidebar() {
|
||||
<DndContext
|
||||
sensors={projectDnDSensors}
|
||||
collisionDetection={projectCollisionDetection}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
|
||||
onDragStart={handleProjectDragStart}
|
||||
onDragEnd={handleProjectDragEnd}
|
||||
onDragCancel={handleProjectDragCancel}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveTerminalSelectionActionPosition,
|
||||
shouldHandleTerminalSelectionMouseUp,
|
||||
terminalSelectionActionDelayForClickCount,
|
||||
} from "./ThreadTerminalDrawer";
|
||||
|
||||
describe("resolveTerminalSelectionActionPosition", () => {
|
||||
it("prefers the selection rect over the last pointer position", () => {
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: { right: 260, bottom: 140 },
|
||||
pointer: { x: 520, y: 200 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 260,
|
||||
y: 144,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the pointer position when no selection rect is available", () => {
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: null,
|
||||
pointer: { x: 180, y: 130 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 180,
|
||||
y: 130,
|
||||
});
|
||||
});
|
||||
|
||||
it("clamps the pointer fallback into the terminal drawer bounds", () => {
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: null,
|
||||
pointer: { x: 720, y: 340 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 600,
|
||||
y: 270,
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveTerminalSelectionActionPosition({
|
||||
bounds: { left: 100, top: 50, width: 500, height: 220 },
|
||||
selectionRect: null,
|
||||
pointer: { x: 40, y: 20 },
|
||||
viewport: { width: 1024, height: 768 },
|
||||
}),
|
||||
).toEqual({
|
||||
x: 100,
|
||||
y: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("delays multi-click selection actions so triple-click selection can complete", () => {
|
||||
expect(terminalSelectionActionDelayForClickCount(1)).toBe(0);
|
||||
expect(terminalSelectionActionDelayForClickCount(2)).toBe(260);
|
||||
expect(terminalSelectionActionDelayForClickCount(3)).toBe(260);
|
||||
});
|
||||
|
||||
it("only handles mouseup when the selection gesture started in the terminal", () => {
|
||||
expect(shouldHandleTerminalSelectionMouseUp(true, 0)).toBe(true);
|
||||
expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
|
||||
expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { type TerminalContextSelection } from "~/lib/terminalContext";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import {
|
||||
extractTerminalLinks,
|
||||
@@ -29,6 +30,7 @@ import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
const MIN_DRAWER_HEIGHT = 180;
|
||||
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
|
||||
const MULTI_CLICK_SELECTION_ACTION_DELAY_MS = 260;
|
||||
|
||||
function maxDrawerHeight(): number {
|
||||
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
|
||||
@@ -107,12 +109,85 @@ function terminalThemeFromApp(): ITheme {
|
||||
};
|
||||
}
|
||||
|
||||
function getTerminalSelectionRect(mountElement: HTMLElement): DOMRect | null {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const range = selection.getRangeAt(0);
|
||||
const commonAncestor = range.commonAncestorContainer;
|
||||
const selectionRoot =
|
||||
commonAncestor instanceof Element ? commonAncestor : commonAncestor.parentElement;
|
||||
if (!(selectionRoot instanceof Element) || !mountElement.contains(selectionRoot)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rects = Array.from(range.getClientRects()).filter(
|
||||
(rect) => rect.width > 0 || rect.height > 0,
|
||||
);
|
||||
if (rects.length > 0) {
|
||||
return rects[rects.length - 1] ?? null;
|
||||
}
|
||||
|
||||
const boundingRect = range.getBoundingClientRect();
|
||||
return boundingRect.width > 0 || boundingRect.height > 0 ? boundingRect : null;
|
||||
}
|
||||
|
||||
export function resolveTerminalSelectionActionPosition(options: {
|
||||
bounds: { left: number; top: number; width: number; height: number };
|
||||
selectionRect: { right: number; bottom: number } | null;
|
||||
pointer: { x: number; y: number } | null;
|
||||
viewport?: { width: number; height: number } | null;
|
||||
}): { x: number; y: number } {
|
||||
const { bounds, selectionRect, pointer, viewport } = options;
|
||||
const viewportWidth =
|
||||
viewport?.width ??
|
||||
(typeof window === "undefined" ? bounds.left + bounds.width + 8 : window.innerWidth);
|
||||
const viewportHeight =
|
||||
viewport?.height ??
|
||||
(typeof window === "undefined" ? bounds.top + bounds.height + 8 : window.innerHeight);
|
||||
const drawerLeft = Math.round(bounds.left);
|
||||
const drawerTop = Math.round(bounds.top);
|
||||
const drawerRight = Math.round(bounds.left + bounds.width);
|
||||
const drawerBottom = Math.round(bounds.top + bounds.height);
|
||||
const preferredX =
|
||||
selectionRect !== null
|
||||
? Math.round(selectionRect.right)
|
||||
: pointer === null
|
||||
? Math.round(bounds.left + bounds.width - 140)
|
||||
: Math.max(drawerLeft, Math.min(Math.round(pointer.x), drawerRight));
|
||||
const preferredY =
|
||||
selectionRect !== null
|
||||
? Math.round(selectionRect.bottom + 4)
|
||||
: pointer === null
|
||||
? Math.round(bounds.top + 12)
|
||||
: Math.max(drawerTop, Math.min(Math.round(pointer.y), drawerBottom));
|
||||
return {
|
||||
x: Math.max(8, Math.min(preferredX, Math.max(viewportWidth - 8, 8))),
|
||||
y: Math.max(8, Math.min(preferredY, Math.max(viewportHeight - 8, 8))),
|
||||
};
|
||||
}
|
||||
|
||||
export function terminalSelectionActionDelayForClickCount(clickCount: number): number {
|
||||
return clickCount >= 2 ? MULTI_CLICK_SELECTION_ACTION_DELAY_MS : 0;
|
||||
}
|
||||
|
||||
export function shouldHandleTerminalSelectionMouseUp(
|
||||
selectionGestureActive: boolean,
|
||||
button: number,
|
||||
): boolean {
|
||||
return selectionGestureActive && button === 0;
|
||||
}
|
||||
|
||||
interface TerminalViewportProps {
|
||||
threadId: ThreadId;
|
||||
terminalId: string;
|
||||
terminalLabel: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
onSessionExited: () => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
resizeEpoch: number;
|
||||
@@ -122,9 +197,11 @@ interface TerminalViewportProps {
|
||||
function TerminalViewport({
|
||||
threadId,
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
onSessionExited,
|
||||
onAddTerminalContext,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
@@ -134,12 +211,27 @@ function TerminalViewport({
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const onSessionExitedRef = useRef(onSessionExited);
|
||||
const onAddTerminalContextRef = useRef(onAddTerminalContext);
|
||||
const terminalLabelRef = useRef(terminalLabel);
|
||||
const hasHandledExitRef = useRef(false);
|
||||
const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const selectionGestureActiveRef = useRef(false);
|
||||
const selectionActionRequestIdRef = useRef(0);
|
||||
const selectionActionOpenRef = useRef(false);
|
||||
const selectionActionTimerRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
onSessionExitedRef.current = onSessionExited;
|
||||
}, [onSessionExited]);
|
||||
|
||||
useEffect(() => {
|
||||
onAddTerminalContextRef.current = onAddTerminalContext;
|
||||
}, [onAddTerminalContext]);
|
||||
|
||||
useEffect(() => {
|
||||
terminalLabelRef.current = terminalLabel;
|
||||
}, [terminalLabel]);
|
||||
|
||||
useEffect(() => {
|
||||
const mount = containerRef.current;
|
||||
if (!mount) return;
|
||||
@@ -165,6 +257,81 @@ function TerminalViewport({
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
const clearSelectionAction = () => {
|
||||
selectionActionRequestIdRef.current += 1;
|
||||
if (selectionActionTimerRef.current !== null) {
|
||||
window.clearTimeout(selectionActionTimerRef.current);
|
||||
selectionActionTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const readSelectionAction = (): {
|
||||
position: { x: number; y: number };
|
||||
selection: TerminalContextSelection;
|
||||
} | null => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
const mountElement = containerRef.current;
|
||||
if (!activeTerminal || !mountElement || !activeTerminal.hasSelection()) {
|
||||
return null;
|
||||
}
|
||||
const selectionText = activeTerminal.getSelection();
|
||||
const selectionPosition = activeTerminal.getSelectionPosition();
|
||||
const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
|
||||
if (!selectionPosition || normalizedText.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const lineStart = selectionPosition.start.y + 1;
|
||||
const lineCount = normalizedText.split("\n").length;
|
||||
const lineEnd = Math.max(lineStart, lineStart + lineCount - 1);
|
||||
const bounds = mountElement.getBoundingClientRect();
|
||||
const selectionRect = getTerminalSelectionRect(mountElement);
|
||||
const position = resolveTerminalSelectionActionPosition({
|
||||
bounds,
|
||||
selectionRect:
|
||||
selectionRect === null
|
||||
? null
|
||||
: { right: selectionRect.right, bottom: selectionRect.bottom },
|
||||
pointer: selectionPointerRef.current,
|
||||
});
|
||||
return {
|
||||
position,
|
||||
selection: {
|
||||
terminalId,
|
||||
terminalLabel: terminalLabelRef.current,
|
||||
lineStart,
|
||||
lineEnd,
|
||||
text: normalizedText,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const showSelectionAction = async () => {
|
||||
if (selectionActionOpenRef.current) {
|
||||
return;
|
||||
}
|
||||
const nextAction = readSelectionAction();
|
||||
if (!nextAction) {
|
||||
clearSelectionAction();
|
||||
return;
|
||||
}
|
||||
const requestId = ++selectionActionRequestIdRef.current;
|
||||
selectionActionOpenRef.current = true;
|
||||
try {
|
||||
const clicked = await api.contextMenu.show(
|
||||
[{ id: "add-to-chat", label: "Add to chat" }],
|
||||
nextAction.position,
|
||||
);
|
||||
if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
|
||||
return;
|
||||
}
|
||||
onAddTerminalContextRef.current(nextAction.selection);
|
||||
terminalRef.current?.clearSelection();
|
||||
terminalRef.current?.focus();
|
||||
} finally {
|
||||
selectionActionOpenRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const sendTerminalInput = async (data: string, fallbackError: string) => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
@@ -259,6 +426,38 @@ function TerminalViewport({
|
||||
);
|
||||
});
|
||||
|
||||
const selectionDisposable = terminal.onSelectionChange(() => {
|
||||
if (terminalRef.current?.hasSelection()) {
|
||||
return;
|
||||
}
|
||||
clearSelectionAction();
|
||||
});
|
||||
|
||||
const handleMouseUp = (event: MouseEvent) => {
|
||||
const shouldHandle = shouldHandleTerminalSelectionMouseUp(
|
||||
selectionGestureActiveRef.current,
|
||||
event.button,
|
||||
);
|
||||
selectionGestureActiveRef.current = false;
|
||||
if (!shouldHandle) {
|
||||
return;
|
||||
}
|
||||
selectionPointerRef.current = { x: event.clientX, y: event.clientY };
|
||||
const delay = terminalSelectionActionDelayForClickCount(event.detail);
|
||||
selectionActionTimerRef.current = window.setTimeout(() => {
|
||||
selectionActionTimerRef.current = null;
|
||||
window.requestAnimationFrame(() => {
|
||||
void showSelectionAction();
|
||||
});
|
||||
}, delay);
|
||||
};
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
clearSelectionAction();
|
||||
selectionGestureActiveRef.current = event.button === 0;
|
||||
};
|
||||
window.addEventListener("mouseup", handleMouseUp);
|
||||
mount.addEventListener("pointerdown", handlePointerDown);
|
||||
|
||||
const themeObserver = new MutationObserver(() => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
@@ -310,11 +509,13 @@ function TerminalViewport({
|
||||
|
||||
if (event.type === "output") {
|
||||
activeTerminal.write(event.data);
|
||||
clearSelectionAction();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "started" || event.type === "restarted") {
|
||||
hasHandledExitRef.current = false;
|
||||
clearSelectionAction();
|
||||
activeTerminal.write("\u001bc");
|
||||
if (event.snapshot.history.length > 0) {
|
||||
activeTerminal.write(event.snapshot.history);
|
||||
@@ -323,6 +524,7 @@ function TerminalViewport({
|
||||
}
|
||||
|
||||
if (event.type === "cleared") {
|
||||
clearSelectionAction();
|
||||
activeTerminal.clear();
|
||||
activeTerminal.write("\u001bc");
|
||||
return;
|
||||
@@ -383,7 +585,13 @@ function TerminalViewport({
|
||||
window.clearTimeout(fitTimer);
|
||||
unsubscribe();
|
||||
inputDisposable.dispose();
|
||||
selectionDisposable.dispose();
|
||||
terminalLinksDisposable.dispose();
|
||||
if (selectionActionTimerRef.current !== null) {
|
||||
window.clearTimeout(selectionActionTimerRef.current);
|
||||
}
|
||||
window.removeEventListener("mouseup", handleMouseUp);
|
||||
mount.removeEventListener("pointerdown", handlePointerDown);
|
||||
themeObserver.disconnect();
|
||||
terminalRef.current = null;
|
||||
fitAddonRef.current = null;
|
||||
@@ -430,7 +638,9 @@ function TerminalViewport({
|
||||
window.cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [drawerHeight, resizeEpoch, terminalId, threadId]);
|
||||
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
|
||||
return (
|
||||
<div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-[4px]" />
|
||||
);
|
||||
}
|
||||
|
||||
interface ThreadTerminalDrawerProps {
|
||||
@@ -451,6 +661,7 @@ interface ThreadTerminalDrawerProps {
|
||||
onActiveTerminalChange: (terminalId: string) => void;
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
}
|
||||
|
||||
interface TerminalActionButtonProps {
|
||||
@@ -500,6 +711,7 @@ export default function ThreadTerminalDrawer({
|
||||
onActiveTerminalChange,
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
onAddTerminalContext,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
|
||||
const [resizeEpoch, setResizeEpoch] = useState(0);
|
||||
@@ -796,9 +1008,11 @@ export default function ThreadTerminalDrawer({
|
||||
<TerminalViewport
|
||||
threadId={threadId}
|
||||
terminalId={terminalId}
|
||||
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(terminalId)}
|
||||
onAddTerminalContext={onAddTerminalContext}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||
resizeEpoch={resizeEpoch}
|
||||
@@ -814,9 +1028,11 @@ export default function ThreadTerminalDrawer({
|
||||
key={resolvedActiveTerminalId}
|
||||
threadId={threadId}
|
||||
terminalId={resolvedActiveTerminalId}
|
||||
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
onAddTerminalContext={onAddTerminalContext}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={resizeEpoch}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ComposerPendingTerminalContextChip } from "./ComposerPendingTerminalContexts";
|
||||
|
||||
describe("ComposerPendingTerminalContextChip", () => {
|
||||
it("renders expired terminal contexts with error styling", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ComposerPendingTerminalContextChip
|
||||
context={{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 2,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T18:42:05.449Z",
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-terminal-context-expired="true"');
|
||||
expect(markup).toContain("border-destructive/35");
|
||||
expect(markup).toContain("Terminal 1 lines 2-4");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { cn } from "~/lib/utils";
|
||||
import {
|
||||
type TerminalContextDraft,
|
||||
formatTerminalContextLabel,
|
||||
isTerminalContextExpired,
|
||||
} from "~/lib/terminalContext";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
|
||||
interface ComposerPendingTerminalContextsProps {
|
||||
contexts: ReadonlyArray<TerminalContextDraft>;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface ComposerPendingTerminalContextChipProps {
|
||||
context: TerminalContextDraft;
|
||||
}
|
||||
|
||||
export function ComposerPendingTerminalContextChip({
|
||||
context,
|
||||
}: ComposerPendingTerminalContextChipProps) {
|
||||
const label = formatTerminalContextLabel(context);
|
||||
const expired = isTerminalContextExpired(context);
|
||||
const tooltipText = expired
|
||||
? `Terminal context expired. Remove and re-add ${label} to include it in your message.`
|
||||
: context.text;
|
||||
|
||||
return <TerminalContextInlineChip label={label} tooltipText={tooltipText} expired={expired} />;
|
||||
}
|
||||
|
||||
export function ComposerPendingTerminalContexts(props: ComposerPendingTerminalContextsProps) {
|
||||
const { contexts, className } = props;
|
||||
|
||||
if (contexts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-wrap gap-1.5", className)}>
|
||||
{contexts.map((context) => (
|
||||
<ComposerPendingTerminalContextChip key={context.id} context={context} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { MessageId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
function matchMedia() {
|
||||
return {
|
||||
matches: false,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
const classList = {
|
||||
add: () => {},
|
||||
remove: () => {},
|
||||
toggle: () => {},
|
||||
contains: () => false,
|
||||
};
|
||||
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: () => null,
|
||||
setItem: () => {},
|
||||
removeItem: () => {},
|
||||
clear: () => {},
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
matchMedia,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
classList,
|
||||
offsetHeight: 0,
|
||||
},
|
||||
});
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 0;
|
||||
});
|
||||
});
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
it("renders inline terminal labels with the composer chip UI", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "message",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
message: {
|
||||
id: MessageId.makeUnsafe("message-2"),
|
||||
role: "user",
|
||||
text: [
|
||||
"yoo what's @terminal-1:1-5 mean",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 1-5:",
|
||||
" 1 | julius@mac effect-http-ws-cli % bun i",
|
||||
" 2 | bun install v1.3.9 (cf6cdbbb)",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
]}
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Terminal 1 lines 1-5");
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,14 @@
|
||||
import { type MessageId, type TurnId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
measureElement as measureVirtualElement,
|
||||
type VirtualItem,
|
||||
@@ -33,9 +42,19 @@ import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
import {
|
||||
deriveDisplayedUserMessageState,
|
||||
type ParsedTerminalContextEntry,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { type TimestampFormat } from "../../appSettings";
|
||||
import { formatTimestamp } from "../../timestampFormat";
|
||||
import {
|
||||
buildInlineTerminalContextText,
|
||||
formatInlineTerminalContextLabel,
|
||||
textContainsInlineTerminalContextLabels,
|
||||
} from "./userMessageTerminalContexts";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
|
||||
@@ -337,6 +356,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
row.message.role === "user" &&
|
||||
(() => {
|
||||
const userImages = row.message.attachments ?? [];
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
|
||||
const terminalContexts = displayedUserMessage.contexts;
|
||||
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
@@ -378,14 +399,18 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{row.message.text && (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{row.message.text}
|
||||
</pre>
|
||||
{(displayedUserMessage.visibleText.trim().length > 0 ||
|
||||
terminalContexts.length > 0) && (
|
||||
<UserMessageBody
|
||||
text={displayedUserMessage.visibleText}
|
||||
terminalContexts={terminalContexts}
|
||||
/>
|
||||
)}
|
||||
<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">
|
||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
||||
{displayedUserMessage.copyText && (
|
||||
<MessageCopyButton text={displayedUserMessage.copyText} />
|
||||
)}
|
||||
{canRevertAgentWork && (
|
||||
<Button
|
||||
type="button"
|
||||
@@ -636,6 +661,110 @@ function formatMessageMeta(
|
||||
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
|
||||
}
|
||||
|
||||
const UserMessageTerminalContextInlineLabel = memo(
|
||||
function UserMessageTerminalContextInlineLabel(props: { context: ParsedTerminalContextEntry }) {
|
||||
const tooltipText =
|
||||
props.context.body.length > 0
|
||||
? `${props.context.header}\n${props.context.body}`
|
||||
: props.context.header;
|
||||
|
||||
return <TerminalContextInlineChip label={props.context.header} tooltipText={tooltipText} />;
|
||||
},
|
||||
);
|
||||
|
||||
const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
text: string;
|
||||
terminalContexts: ParsedTerminalContextEntry[];
|
||||
}) {
|
||||
if (props.terminalContexts.length > 0) {
|
||||
const hasEmbeddedInlineLabels = textContainsInlineTerminalContextLabels(
|
||||
props.text,
|
||||
props.terminalContexts,
|
||||
);
|
||||
const inlinePrefix = buildInlineTerminalContextText(props.terminalContexts);
|
||||
const inlineNodes: ReactNode[] = [];
|
||||
|
||||
if (hasEmbeddedInlineLabels) {
|
||||
let cursor = 0;
|
||||
|
||||
for (const context of props.terminalContexts) {
|
||||
const label = formatInlineTerminalContextLabel(context.header);
|
||||
const matchIndex = props.text.indexOf(label, cursor);
|
||||
if (matchIndex === -1) {
|
||||
inlineNodes.length = 0;
|
||||
break;
|
||||
}
|
||||
if (matchIndex > cursor) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
|
||||
{props.text.slice(cursor, matchIndex)}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
inlineNodes.push(
|
||||
<UserMessageTerminalContextInlineLabel
|
||||
key={`user-terminal-context-inline:${context.header}`}
|
||||
context={context}
|
||||
/>,
|
||||
);
|
||||
cursor = matchIndex + label.length;
|
||||
}
|
||||
|
||||
if (inlineNodes.length > 0) {
|
||||
if (cursor < props.text.length) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-message-terminal-context-inline-rest:${cursor}`}>
|
||||
{props.text.slice(cursor)}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
|
||||
{inlineNodes}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (const context of props.terminalContexts) {
|
||||
inlineNodes.push(
|
||||
<UserMessageTerminalContextInlineLabel
|
||||
key={`user-terminal-context-inline:${context.header}`}
|
||||
context={context}
|
||||
/>,
|
||||
);
|
||||
inlineNodes.push(
|
||||
<span key={`user-terminal-context-inline-space:${context.header}`} aria-hidden="true">
|
||||
{" "}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
|
||||
if (props.text.length > 0) {
|
||||
inlineNodes.push(<span key="user-message-terminal-context-inline-text">{props.text}</span>);
|
||||
} else if (inlinePrefix.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
|
||||
{inlineNodes}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.text.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{props.text}
|
||||
</pre>
|
||||
);
|
||||
});
|
||||
|
||||
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
|
||||
icon: LucideIcon;
|
||||
className: string;
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import { type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { ProviderModelPicker } from "./ProviderModelPicker";
|
||||
|
||||
const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
claudeAgent: [
|
||||
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
{ slug: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
|
||||
],
|
||||
codex: [
|
||||
{ slug: "gpt-5-codex", name: "GPT-5 Codex" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
],
|
||||
} as const satisfies Record<ProviderKind, ReadonlyArray<{ slug: ModelSlug; name: string }>>;
|
||||
|
||||
async function mountPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
lockedProvider: ProviderKind | null;
|
||||
}) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onProviderModelChange = vi.fn();
|
||||
const screen = await render(
|
||||
<ProviderModelPicker
|
||||
provider={props.provider}
|
||||
model={props.model}
|
||||
lockedProvider={props.lockedProvider}
|
||||
modelOptionsByProvider={MODEL_OPTIONS_BY_PROVIDER}
|
||||
onProviderModelChange={onProviderModelChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
onProviderModelChange,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProviderModelPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("shows provider submenus when provider switching is allowed", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: null,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Codex");
|
||||
expect(text).toContain("Claude");
|
||||
expect(text).not.toContain("Claude Sonnet 4.6");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows models directly when the provider is locked mid-thread", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: "claudeAgent",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Claude Sonnet 4.6");
|
||||
expect(text).toContain("Claude Haiku 4.5");
|
||||
expect(text).not.toContain("Codex");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,7 @@ function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): o
|
||||
label: string;
|
||||
available: true;
|
||||
} {
|
||||
return option.available;
|
||||
return option.available && option.value !== "claudeCode";
|
||||
}
|
||||
|
||||
function resolveModelForProviderPicker(
|
||||
@@ -63,7 +63,7 @@ function resolveModelForProviderPicker(
|
||||
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind, Icon> = {
|
||||
codex: OpenAI,
|
||||
claudeAgent: ClaudeAI,
|
||||
claudeCode: ClaudeAI,
|
||||
cursor: CursorIcon,
|
||||
};
|
||||
|
||||
@@ -84,23 +84,10 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const activeProvider = props.lockedProvider ?? props.provider;
|
||||
const selectedProviderOptions = props.modelOptionsByProvider[activeProvider];
|
||||
const selectedProviderOptions = props.modelOptionsByProvider[props.provider];
|
||||
const selectedModelLabel =
|
||||
selectedProviderOptions.find((option) => option.slug === props.model)?.name ?? props.model;
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider];
|
||||
const handleModelChange = (provider: ProviderKind, value: string) => {
|
||||
if (props.disabled) return;
|
||||
if (!value) return;
|
||||
const resolvedModel = resolveModelForProviderPicker(
|
||||
provider,
|
||||
value,
|
||||
props.modelOptionsByProvider[provider],
|
||||
);
|
||||
if (!resolvedModel) return;
|
||||
props.onProviderModelChange(provider, resolvedModel);
|
||||
setIsMenuOpen(false);
|
||||
};
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.provider];
|
||||
|
||||
return (
|
||||
<Menu
|
||||
@@ -135,88 +122,84 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{props.lockedProvider !== null ? (
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.model}
|
||||
onValueChange={(value) => handleModelChange(props.lockedProvider!, value)}
|
||||
>
|
||||
{props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => (
|
||||
<MenuRadioItem
|
||||
key={`${props.lockedProvider}:${modelOption.slug}`}
|
||||
value={modelOption.slug}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
{modelOption.name}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : (
|
||||
<>
|
||||
{AVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
|
||||
return (
|
||||
<MenuSub key={option.value}>
|
||||
<MenuSubTrigger>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/85"
|
||||
/>
|
||||
{option.label}
|
||||
</MenuSubTrigger>
|
||||
<MenuSubPopup className="[--available-height:min(24rem,70vh)]">
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.provider === option.value ? props.model : ""}
|
||||
onValueChange={(value) => handleModelChange(option.value, value)}
|
||||
{AVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
|
||||
const isDisabledByProviderLock =
|
||||
props.lockedProvider !== null && props.lockedProvider !== option.value;
|
||||
return (
|
||||
<MenuSub key={option.value}>
|
||||
<MenuSubTrigger disabled={isDisabledByProviderLock}>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/85"
|
||||
/>
|
||||
{option.label}
|
||||
</MenuSubTrigger>
|
||||
<MenuSubPopup className="[--available-height:min(24rem,70vh)]">
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.provider === option.value ? props.model : ""}
|
||||
onValueChange={(value) => {
|
||||
if (props.disabled) return;
|
||||
if (isDisabledByProviderLock) return;
|
||||
if (!value) return;
|
||||
const resolvedModel = resolveModelForProviderPicker(
|
||||
option.value,
|
||||
value,
|
||||
props.modelOptionsByProvider[option.value],
|
||||
);
|
||||
if (!resolvedModel) return;
|
||||
props.onProviderModelChange(option.value, resolvedModel);
|
||||
setIsMenuOpen(false);
|
||||
}}
|
||||
>
|
||||
{props.modelOptionsByProvider[option.value].map((modelOption) => (
|
||||
<MenuRadioItem
|
||||
key={`${option.value}:${modelOption.slug}`}
|
||||
value={modelOption.slug}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
{props.modelOptionsByProvider[option.value].map((modelOption) => (
|
||||
<MenuRadioItem
|
||||
key={`${option.value}:${modelOption.slug}`}
|
||||
value={modelOption.slug}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
{modelOption.name}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuSubPopup>
|
||||
</MenuSub>
|
||||
);
|
||||
})}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && <MenuDivider />}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
|
||||
return (
|
||||
<MenuItem key={option.value} disabled>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/85 opacity-80"
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
|
||||
Coming soon
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.length === 0 && <MenuDivider />}
|
||||
{COMING_SOON_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = option.icon;
|
||||
return (
|
||||
<MenuItem key={option.id} disabled>
|
||||
<OptionIcon aria-hidden="true" className="size-4 shrink-0 opacity-80" />
|
||||
<span>{option.label}</span>
|
||||
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
|
||||
Coming soon
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
{modelOption.name}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuSubPopup>
|
||||
</MenuSub>
|
||||
);
|
||||
})}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && <MenuDivider />}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
|
||||
return (
|
||||
<MenuItem key={option.value} disabled>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0 opacity-80",
|
||||
option.value === "claudeCode" ? "" : "text-muted-foreground/85",
|
||||
)}
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
|
||||
Coming soon
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.length === 0 && <MenuDivider />}
|
||||
{COMING_SOON_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = option.icon;
|
||||
return (
|
||||
<MenuItem key={option.id} disabled>
|
||||
<OptionIcon aria-hidden="true" className="size-4 shrink-0 opacity-80" />
|
||||
<span>{option.label}</span>
|
||||
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
|
||||
Coming soon
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { TerminalIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
} from "../composerInlineChip";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
interface TerminalContextInlineChipProps {
|
||||
label: string;
|
||||
tooltipText: string;
|
||||
expired?: boolean;
|
||||
}
|
||||
|
||||
export function TerminalContextInlineChip(props: TerminalContextInlineChipProps) {
|
||||
const { label, tooltipText, expired = false } = props;
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
className={cn(
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
expired && "border-destructive/35 bg-destructive/8 text-destructive",
|
||||
)}
|
||||
data-terminal-context-expired={expired ? "true" : undefined}
|
||||
>
|
||||
<TerminalIcon
|
||||
className={cn(
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
"size-3.5",
|
||||
expired && "opacity-100",
|
||||
)}
|
||||
/>
|
||||
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{label}</span>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
|
||||
{tooltipText}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildInlineTerminalContextText,
|
||||
formatInlineTerminalContextLabel,
|
||||
textContainsInlineTerminalContextLabels,
|
||||
} from "./userMessageTerminalContexts";
|
||||
|
||||
describe("userMessageTerminalContexts", () => {
|
||||
it("builds plain inline terminal text labels", () => {
|
||||
expect(
|
||||
buildInlineTerminalContextText([
|
||||
{ header: "Terminal 1 lines 12-13" },
|
||||
{ header: "Terminal 2 line 4" },
|
||||
]),
|
||||
).toBe("@terminal-1:12-13 @terminal-2:4");
|
||||
});
|
||||
|
||||
it("formats individual inline terminal labels compactly", () => {
|
||||
expect(formatInlineTerminalContextLabel("Terminal 1 lines 12-13")).toBe("@terminal-1:12-13");
|
||||
expect(formatInlineTerminalContextLabel("Terminal 2 line 4")).toBe("@terminal-2:4");
|
||||
});
|
||||
|
||||
it("detects inline terminal labels embedded in user message text", () => {
|
||||
expect(
|
||||
textContainsInlineTerminalContextLabels("yo @terminal-1:12-13 whats up", [
|
||||
{ header: "Terminal 1 lines 12-13" },
|
||||
]),
|
||||
).toBe(true);
|
||||
expect(
|
||||
textContainsInlineTerminalContextLabels("yo whats up", [
|
||||
{ header: "Terminal 1 lines 12-13" },
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { formatInlineTerminalContextLabel as formatInlineTerminalContextSelectionLabel } from "~/lib/terminalContext";
|
||||
|
||||
const TERMINAL_CONTEXT_HEADER_PATTERN = /^(.*?)\s+line(?:s)?\s+(\d+)(?:-(\d+))?$/i;
|
||||
|
||||
export function buildInlineTerminalContextText(
|
||||
contexts: ReadonlyArray<{
|
||||
header: string;
|
||||
}>,
|
||||
): string {
|
||||
return contexts
|
||||
.map((context) => context.header.trim())
|
||||
.filter((header) => header.length > 0)
|
||||
.map(formatInlineTerminalContextLabel)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function formatInlineTerminalContextLabel(header: string): string {
|
||||
const trimmedHeader = header.trim();
|
||||
const match = TERMINAL_CONTEXT_HEADER_PATTERN.exec(trimmedHeader);
|
||||
if (!match) {
|
||||
return `@${trimmedHeader.toLowerCase().replace(/\s+/g, "-")}`;
|
||||
}
|
||||
|
||||
const lineStart = Number.parseInt(match[2] ?? "", 10);
|
||||
const lineEnd = Number.parseInt(match[3] ?? match[2] ?? "", 10);
|
||||
if (!Number.isFinite(lineStart) || !Number.isFinite(lineEnd)) {
|
||||
return `@${trimmedHeader.toLowerCase().replace(/\s+/g, "-")}`;
|
||||
}
|
||||
|
||||
return formatInlineTerminalContextSelectionLabel({
|
||||
terminalLabel: match[1]?.trim() || "terminal",
|
||||
lineStart,
|
||||
lineEnd,
|
||||
});
|
||||
}
|
||||
|
||||
export function textContainsInlineTerminalContextLabels(
|
||||
text: string,
|
||||
contexts: ReadonlyArray<{
|
||||
header: string;
|
||||
}>,
|
||||
): boolean {
|
||||
let searchStartIndex = 0;
|
||||
|
||||
for (const context of contexts) {
|
||||
const label = formatInlineTerminalContextLabel(context.header);
|
||||
const matchIndex = text.indexOf(label, searchStartIndex);
|
||||
if (matchIndex === -1) {
|
||||
return false;
|
||||
}
|
||||
searchStartIndex = matchIndex + label.length;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export const COMPOSER_INLINE_CHIP_CLASS_NAME =
|
||||
"inline-flex max-w-full select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-3.5 shrink-0 opacity-85";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = "truncate select-none leading-tight";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME =
|
||||
"ml-0.5 inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground/72 transition-colors hover:bg-foreground/6 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring";
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appendTerminalContextsToPrompt } from "../lib/terminalContext";
|
||||
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
describe("estimateTimelineMessageHeight", () => {
|
||||
@@ -75,6 +77,35 @@ describe("estimateTimelineMessageHeight", () => {
|
||||
).toBe(162);
|
||||
});
|
||||
|
||||
it("adds terminal context chrome without counting the hidden block as message text", () => {
|
||||
const prompt = appendTerminalContextsToPrompt("Investigate this", [
|
||||
{
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 40,
|
||||
lineEnd: 43,
|
||||
text: [
|
||||
"git status",
|
||||
"M apps/web/src/components/chat/MessagesTimeline.tsx",
|
||||
"?? tmp",
|
||||
"",
|
||||
].join("\n"),
|
||||
},
|
||||
]);
|
||||
|
||||
expect(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: prompt,
|
||||
}),
|
||||
).toBe(
|
||||
estimateTimelineMessageHeight({
|
||||
role: "user",
|
||||
text: `${buildInlineTerminalContextText([{ header: "Terminal 1 lines 40-43" }])} Investigate this`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses narrower width to increase user line wrapping", () => {
|
||||
const message = {
|
||||
role: "user" as const,
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { deriveDisplayedUserMessageState } from "../lib/terminalContext";
|
||||
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
|
||||
|
||||
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
|
||||
const USER_CHARS_PER_LINE_FALLBACK = 56;
|
||||
const LINE_HEIGHT_PX = 22;
|
||||
@@ -75,7 +78,17 @@ export function estimateTimelineMessageHeight(
|
||||
|
||||
if (message.role === "user") {
|
||||
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(message.text);
|
||||
const renderedText =
|
||||
displayedUserMessage.contexts.length > 0
|
||||
? [
|
||||
buildInlineTerminalContextText(displayedUserMessage.contexts),
|
||||
displayedUserMessage.visibleText,
|
||||
]
|
||||
.filter((part) => part.length > 0)
|
||||
.join(" ")
|
||||
: displayedUserMessage.visibleText;
|
||||
const estimatedLines = estimateWrappedLineCount(renderedText, charsPerLine);
|
||||
const attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
|
||||
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuSubButton,
|
||||
SidebarProvider,
|
||||
} from "./sidebar";
|
||||
|
||||
function renderSidebarButton(className?: string) {
|
||||
return renderToStaticMarkup(
|
||||
<SidebarProvider>
|
||||
<SidebarMenuButton className={className}>Projects</SidebarMenuButton>
|
||||
</SidebarProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("sidebar interactive cursors", () => {
|
||||
it("uses a pointer cursor for menu buttons by default", () => {
|
||||
const html = renderSidebarButton();
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-button"');
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("lets project drag handles override the default pointer cursor", () => {
|
||||
const html = renderSidebarButton("cursor-grab");
|
||||
|
||||
expect(html).toContain("cursor-grab");
|
||||
expect(html).not.toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("uses a pointer cursor for menu actions", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarMenuAction aria-label="Create thread">
|
||||
<span>+</span>
|
||||
</SidebarMenuAction>,
|
||||
);
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-action"');
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("uses a pointer cursor for submenu buttons", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarMenuSubButton render={<button type="button" />}>Show more</SidebarMenuSubButton>,
|
||||
);
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-sub-button"');
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
});
|
||||
@@ -750,7 +750,7 @@ function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
"peer/menu-button flex w-full cursor-pointer items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
@@ -834,7 +834,7 @@ function SidebarMenuAction({
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 cursor-pointer items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:-inset-2 after:absolute md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
@@ -946,7 +946,7 @@ function SidebarMenuSubButton({
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"-translate-x-px flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-lg px-2 text-sidebar-foreground outline-hidden ring-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"-translate-x-px flex h-7 min-w-0 cursor-pointer items-center gap-2 overflow-hidden rounded-lg px-2 text-sidebar-foreground outline-hidden ring-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
describe("splitPromptIntoComposerSegments", () => {
|
||||
it("splits mention tokens followed by whitespace into mention segments", () => {
|
||||
@@ -24,4 +25,17 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
{ type: "text", text: " \ntwo" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps inline terminal context placeholders at their prompt positions", () => {
|
||||
expect(
|
||||
splitPromptIntoComposerSegments(
|
||||
`Inspect ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}@AGENTS.md please`,
|
||||
),
|
||||
).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "terminal-context", context: null },
|
||||
{ type: "mention", path: "AGENTS.md" },
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "./lib/terminalContext";
|
||||
|
||||
export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "text";
|
||||
@@ -6,6 +11,10 @@ export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "mention";
|
||||
path: string;
|
||||
}
|
||||
| {
|
||||
type: "terminal-context";
|
||||
context: TerminalContextDraft | null;
|
||||
};
|
||||
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
|
||||
@@ -20,14 +29,14 @@ function pushTextSegment(segments: ComposerPromptSegment[], text: string): void
|
||||
segments.push({ type: "text", text });
|
||||
}
|
||||
|
||||
export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
|
||||
function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegment[] {
|
||||
const segments: ComposerPromptSegment[] = [];
|
||||
if (!prompt) {
|
||||
if (!text) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
const prefix = match[1] ?? "";
|
||||
const path = match[2] ?? "";
|
||||
@@ -36,20 +45,55 @@ export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptS
|
||||
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
|
||||
|
||||
if (mentionStart > cursor) {
|
||||
pushTextSegment(segments, prompt.slice(cursor, mentionStart));
|
||||
pushTextSegment(segments, text.slice(cursor, mentionStart));
|
||||
}
|
||||
|
||||
if (path.length > 0) {
|
||||
segments.push({ type: "mention", path });
|
||||
} else {
|
||||
pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
|
||||
pushTextSegment(segments, text.slice(mentionStart, mentionEnd));
|
||||
}
|
||||
|
||||
cursor = mentionEnd;
|
||||
}
|
||||
|
||||
if (cursor < prompt.length) {
|
||||
pushTextSegment(segments, prompt.slice(cursor));
|
||||
if (cursor < text.length) {
|
||||
pushTextSegment(segments, text.slice(cursor));
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function splitPromptIntoComposerSegments(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft> = [],
|
||||
): ComposerPromptSegment[] {
|
||||
if (!prompt) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const segments: ComposerPromptSegment[] = [];
|
||||
let textCursor = 0;
|
||||
let terminalContextIndex = 0;
|
||||
|
||||
for (let index = 0; index < prompt.length; index += 1) {
|
||||
if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index > textCursor) {
|
||||
segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor, index)));
|
||||
}
|
||||
segments.push({
|
||||
type: "terminal-context",
|
||||
context: terminalContexts[terminalContextIndex] ?? null,
|
||||
});
|
||||
terminalContextIndex += 1;
|
||||
textCursor = index + 1;
|
||||
}
|
||||
|
||||
if (textCursor < prompt.length) {
|
||||
segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor)));
|
||||
}
|
||||
|
||||
return segments;
|
||||
|
||||
@@ -5,10 +5,11 @@ import {
|
||||
collapseExpandedComposerCursor,
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
parseStandaloneComposerSlashCommand,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
@@ -192,16 +193,16 @@ describe("replaceTextRange trailing space consumption", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
describe("isCollapsedCursorAdjacentToInlineToken", () => {
|
||||
it("returns false when no mention exists", () => {
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps @query typing non-adjacent while no mention pill exists", () => {
|
||||
const text = "hello @pac";
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects left adjacency only when cursor is directly after a mention", () => {
|
||||
@@ -209,9 +210,9 @@ describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd + 1, "left")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects right adjacency only when cursor is directly before a mention", () => {
|
||||
@@ -219,9 +220,18 @@ describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart - 1, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("treats terminal pills as inline tokens for adjacency checks", () => {
|
||||
const text = `open ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} next`;
|
||||
const tokenStart = "open ".length;
|
||||
const tokenEnd = tokenStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, tokenEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, tokenStart, "right")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||
export type ComposerSlashCommand = "model" | "plan" | "default";
|
||||
@@ -11,6 +12,9 @@ export interface ComposerTrigger {
|
||||
}
|
||||
|
||||
const SLASH_COMMANDS: readonly ComposerSlashCommand[] = ["model", "plan", "default"];
|
||||
const isInlineTokenSegment = (
|
||||
segment: { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" },
|
||||
): boolean => segment.type !== "text";
|
||||
|
||||
function clampCursor(text: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return text.length;
|
||||
@@ -18,7 +22,13 @@ function clampCursor(text: string, cursor: number): number {
|
||||
}
|
||||
|
||||
function isWhitespace(char: string): boolean {
|
||||
return char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
return (
|
||||
char === " " ||
|
||||
char === "\n" ||
|
||||
char === "\t" ||
|
||||
char === "\r" ||
|
||||
char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER
|
||||
);
|
||||
}
|
||||
|
||||
function tokenStartForCursor(text: string, cursor: number): number {
|
||||
@@ -49,6 +59,14 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
expandedCursor += expandedLength;
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (remaining <= 1) {
|
||||
return expandedCursor + remaining;
|
||||
}
|
||||
remaining -= 1;
|
||||
expandedCursor += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const segmentLength = segment.text.length;
|
||||
if (remaining <= segmentLength) {
|
||||
@@ -62,13 +80,18 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
}
|
||||
|
||||
function collapsedSegmentLength(
|
||||
segment: { type: "text"; text: string } | { type: "mention" },
|
||||
segment: { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" },
|
||||
): number {
|
||||
return segment.type === "mention" ? 1 : segment.text.length;
|
||||
if (segment.type === "text") {
|
||||
return segment.text.length;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function clampCollapsedComposerCursorForSegments(
|
||||
segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
|
||||
segments: ReadonlyArray<
|
||||
{ type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" }
|
||||
>,
|
||||
cursorInput: number,
|
||||
): number {
|
||||
const collapsedLength = segments.reduce(
|
||||
@@ -111,6 +134,14 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
|
||||
collapsedCursor += 1;
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (remaining <= 1) {
|
||||
return collapsedCursor + remaining;
|
||||
}
|
||||
remaining -= 1;
|
||||
collapsedCursor += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const segmentLength = segment.text.length;
|
||||
if (remaining <= segmentLength) {
|
||||
@@ -123,13 +154,13 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
|
||||
return collapsedCursor;
|
||||
}
|
||||
|
||||
export function isCollapsedCursorAdjacentToMention(
|
||||
export function isCollapsedCursorAdjacentToInlineToken(
|
||||
text: string,
|
||||
cursorInput: number,
|
||||
direction: "left" | "right",
|
||||
): boolean {
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (!segments.some((segment) => segment.type === "mention")) {
|
||||
if (!segments.some(isInlineTokenSegment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -137,7 +168,7 @@ export function isCollapsedCursorAdjacentToMention(
|
||||
let collapsedOffset = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
if (isInlineTokenSegment(segment)) {
|
||||
if (direction === "left" && cursor === collapsedOffset + 1) {
|
||||
return true;
|
||||
}
|
||||
@@ -151,6 +182,8 @@ export function isCollapsedCursorAdjacentToMention(
|
||||
return false;
|
||||
}
|
||||
|
||||
export const isCollapsedCursorAdjacentToMention = isCollapsedCursorAdjacentToInlineToken;
|
||||
|
||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||
const cursor = clampCursor(text, cursorInput);
|
||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||
|
||||
@@ -6,6 +6,11 @@ import {
|
||||
createDebouncedStorage,
|
||||
useComposerDraftStore,
|
||||
} from "./composerDraftStore";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
type TerminalContextDraft,
|
||||
} from "./lib/terminalContext";
|
||||
|
||||
function makeImage(input: {
|
||||
id: string;
|
||||
@@ -34,6 +39,26 @@ function makeImage(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalContext(input: {
|
||||
id: string;
|
||||
text?: string;
|
||||
terminalId?: string;
|
||||
terminalLabel?: string;
|
||||
lineStart?: number;
|
||||
lineEnd?: number;
|
||||
}): TerminalContextDraft {
|
||||
return {
|
||||
id: input.id,
|
||||
threadId: ThreadId.makeUnsafe("thread-dedupe"),
|
||||
terminalId: input.terminalId ?? "default",
|
||||
terminalLabel: input.terminalLabel ?? "Terminal 1",
|
||||
lineStart: input.lineStart ?? 4,
|
||||
lineEnd: input.lineEnd ?? 5,
|
||||
text: input.text ?? "git status\nOn branch main",
|
||||
createdAt: "2026-03-13T12:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("composerDraftStore addImages", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
@@ -158,6 +183,148 @@ describe("composerDraftStore clearComposerContent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore terminal contexts", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("deduplicates identical terminal contexts by selection signature", () => {
|
||||
const first = makeTerminalContext({ id: "ctx-1" });
|
||||
const duplicate = makeTerminalContext({ id: "ctx-2" });
|
||||
|
||||
useComposerDraftStore.getState().addTerminalContexts(threadId, [first, duplicate]);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-1"]);
|
||||
});
|
||||
|
||||
it("clears terminal contexts when clearing composer content", () => {
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.addTerminalContext(threadId, makeTerminalContext({ id: "ctx-1" }));
|
||||
|
||||
useComposerDraftStore.getState().clearComposerContent(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("inserts terminal contexts at the requested inline prompt position", () => {
|
||||
const firstInsertion = insertInlineTerminalContextPlaceholder("alpha beta", 6);
|
||||
const secondInsertion = insertInlineTerminalContextPlaceholder(firstInsertion.prompt, 0);
|
||||
|
||||
expect(
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.insertTerminalContext(
|
||||
threadId,
|
||||
firstInsertion.prompt,
|
||||
makeTerminalContext({ id: "ctx-1" }),
|
||||
firstInsertion.contextIndex,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
useComposerDraftStore.getState().insertTerminalContext(
|
||||
threadId,
|
||||
secondInsertion.prompt,
|
||||
makeTerminalContext({
|
||||
id: "ctx-2",
|
||||
terminalLabel: "Terminal 2",
|
||||
lineStart: 9,
|
||||
lineEnd: 10,
|
||||
}),
|
||||
secondInsertion.contextIndex,
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.prompt).toBe(
|
||||
`${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} alpha ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} beta`,
|
||||
);
|
||||
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-2", "ctx-1"]);
|
||||
});
|
||||
|
||||
it("omits terminal context text from persisted drafts", () => {
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.addTerminalContext(threadId, makeTerminalContext({ id: "ctx-persist" }));
|
||||
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
|
||||
};
|
||||
};
|
||||
const persistedState = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
|
||||
draftsByThreadId?: Record<string, { terminalContexts?: Array<Record<string, unknown>> }>;
|
||||
};
|
||||
|
||||
expect(
|
||||
persistedState.draftsByThreadId?.[threadId]?.terminalContexts?.[0],
|
||||
"Expected terminal context metadata to be persisted.",
|
||||
).toMatchObject({
|
||||
id: "ctx-persist",
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 5,
|
||||
});
|
||||
expect(
|
||||
persistedState.draftsByThreadId?.[threadId]?.terminalContexts?.[0]?.text,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("hydrates persisted terminal contexts without in-memory snapshot text", () => {
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
merge: (
|
||||
persistedState: unknown,
|
||||
currentState: ReturnType<typeof useComposerDraftStore.getState>,
|
||||
) => ReturnType<typeof useComposerDraftStore.getState>;
|
||||
};
|
||||
};
|
||||
const mergedState = persistApi.getOptions().merge(
|
||||
{
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
prompt: INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
attachments: [],
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-rehydrated",
|
||||
threadId,
|
||||
createdAt: "2026-03-13T12:00:00.000Z",
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
},
|
||||
useComposerDraftStore.getInitialState(),
|
||||
);
|
||||
|
||||
expect(mergedState.draftsByThreadId[threadId]?.terminalContexts).toMatchObject([
|
||||
{
|
||||
id: "ctx-rehydrated",
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 5,
|
||||
text: "",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore project draft thread mapping", () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-a");
|
||||
const otherProjectId = ProjectId.makeUnsafe("project-b");
|
||||
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
|
||||
import {
|
||||
type TerminalContextDraft,
|
||||
ensureInlineTerminalContextPlaceholders,
|
||||
normalizeTerminalContextText,
|
||||
} from "./lib/terminalContext";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";
|
||||
@@ -71,9 +76,20 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
|
||||
file: File;
|
||||
}
|
||||
|
||||
interface PersistedTerminalContextDraft {
|
||||
id: string;
|
||||
threadId: ThreadId;
|
||||
createdAt: string;
|
||||
terminalId: string;
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}
|
||||
|
||||
interface PersistedComposerThreadDraftState {
|
||||
prompt: string;
|
||||
attachments: PersistedComposerImageAttachment[];
|
||||
terminalContexts?: PersistedTerminalContextDraft[];
|
||||
provider?: ProviderKind | null;
|
||||
model?: string | null;
|
||||
runtimeMode?: RuntimeMode | null;
|
||||
@@ -104,6 +120,7 @@ interface ComposerThreadDraftState {
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
terminalContexts: TerminalContextDraft[];
|
||||
provider: ProviderKind | null;
|
||||
model: string | null;
|
||||
runtimeMode: RuntimeMode | null;
|
||||
@@ -160,6 +177,7 @@ interface ComposerDraftStoreState {
|
||||
clearProjectDraftThreadById: (projectId: ProjectId, threadId: ThreadId) => void;
|
||||
clearDraftThread: (threadId: ThreadId) => void;
|
||||
setPrompt: (threadId: ThreadId, prompt: string) => void;
|
||||
setTerminalContexts: (threadId: ThreadId, contexts: TerminalContextDraft[]) => void;
|
||||
setProvider: (threadId: ThreadId, provider: ProviderKind | null | undefined) => void;
|
||||
setModel: (threadId: ThreadId, model: string | null | undefined) => void;
|
||||
setRuntimeMode: (threadId: ThreadId, runtimeMode: RuntimeMode | null | undefined) => void;
|
||||
@@ -172,6 +190,16 @@ interface ComposerDraftStoreState {
|
||||
addImage: (threadId: ThreadId, image: ComposerImageAttachment) => void;
|
||||
addImages: (threadId: ThreadId, images: ComposerImageAttachment[]) => void;
|
||||
removeImage: (threadId: ThreadId, imageId: string) => void;
|
||||
insertTerminalContext: (
|
||||
threadId: ThreadId,
|
||||
prompt: string,
|
||||
context: TerminalContextDraft,
|
||||
index: number,
|
||||
) => boolean;
|
||||
addTerminalContext: (threadId: ThreadId, context: TerminalContextDraft) => void;
|
||||
addTerminalContexts: (threadId: ThreadId, contexts: TerminalContextDraft[]) => void;
|
||||
removeTerminalContext: (threadId: ThreadId, contextId: string) => void;
|
||||
clearTerminalContexts: (threadId: ThreadId) => void;
|
||||
clearPersistedAttachments: (threadId: ThreadId) => void;
|
||||
syncPersistedAttachments: (
|
||||
threadId: ThreadId,
|
||||
@@ -190,14 +218,17 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE: PersistedComposerDraftStoreState = {
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
const EMPTY_IDS: string[] = [];
|
||||
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
|
||||
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
|
||||
Object.freeze(EMPTY_IMAGES);
|
||||
Object.freeze(EMPTY_IDS);
|
||||
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
||||
Object.freeze(EMPTY_TERMINAL_CONTEXTS);
|
||||
const EMPTY_THREAD_DRAFT = Object.freeze({
|
||||
prompt: "",
|
||||
images: EMPTY_IMAGES,
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
|
||||
provider: null,
|
||||
model: null,
|
||||
runtimeMode: null,
|
||||
@@ -216,6 +247,7 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: null,
|
||||
model: null,
|
||||
runtimeMode: null,
|
||||
@@ -231,11 +263,63 @@ function composerImageDedupKey(image: ComposerImageAttachment): string {
|
||||
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
|
||||
}
|
||||
|
||||
function terminalContextDedupKey(context: TerminalContextDraft): string {
|
||||
return `${context.terminalId}\u0000${context.lineStart}\u0000${context.lineEnd}`;
|
||||
}
|
||||
|
||||
function normalizeTerminalContextForThread(
|
||||
threadId: ThreadId,
|
||||
context: TerminalContextDraft,
|
||||
): TerminalContextDraft | null {
|
||||
const terminalId = context.terminalId.trim();
|
||||
const terminalLabel = context.terminalLabel.trim();
|
||||
if (terminalId.length === 0 || terminalLabel.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const lineStart = Math.max(1, Math.floor(context.lineStart));
|
||||
const lineEnd = Math.max(lineStart, Math.floor(context.lineEnd));
|
||||
return {
|
||||
...context,
|
||||
threadId,
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
lineStart,
|
||||
lineEnd,
|
||||
text: normalizeTerminalContextText(context.text),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeTerminalContextsForThread(
|
||||
threadId: ThreadId,
|
||||
contexts: ReadonlyArray<TerminalContextDraft>,
|
||||
): TerminalContextDraft[] {
|
||||
const existingIds = new Set<string>();
|
||||
const existingDedupKeys = new Set<string>();
|
||||
const normalizedContexts: TerminalContextDraft[] = [];
|
||||
|
||||
for (const context of contexts) {
|
||||
const normalizedContext = normalizeTerminalContextForThread(threadId, context);
|
||||
if (!normalizedContext) {
|
||||
continue;
|
||||
}
|
||||
const dedupKey = terminalContextDedupKey(normalizedContext);
|
||||
if (existingIds.has(normalizedContext.id) || existingDedupKeys.has(dedupKey)) {
|
||||
continue;
|
||||
}
|
||||
normalizedContexts.push(normalizedContext);
|
||||
existingIds.add(normalizedContext.id);
|
||||
existingDedupKeys.add(dedupKey);
|
||||
}
|
||||
|
||||
return normalizedContexts;
|
||||
}
|
||||
|
||||
function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
return (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.images.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.runtimeMode === null &&
|
||||
@@ -246,7 +330,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
}
|
||||
|
||||
function normalizeProviderKind(value: unknown): ProviderKind | null {
|
||||
return value === "codex" || value === "claudeAgent" ? value : null;
|
||||
return value === "codex" ? value : null;
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
@@ -290,6 +374,51 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePersistedTerminalContextDraft(
|
||||
value: unknown,
|
||||
): PersistedTerminalContextDraft | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
const id = candidate.id;
|
||||
const threadId = candidate.threadId;
|
||||
const createdAt = candidate.createdAt;
|
||||
const lineStart = candidate.lineStart;
|
||||
const lineEnd = candidate.lineEnd;
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
id.length === 0 ||
|
||||
typeof threadId !== "string" ||
|
||||
threadId.length === 0 ||
|
||||
typeof createdAt !== "string" ||
|
||||
createdAt.length === 0 ||
|
||||
typeof lineStart !== "number" ||
|
||||
!Number.isFinite(lineStart) ||
|
||||
typeof lineEnd !== "number" ||
|
||||
!Number.isFinite(lineEnd)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const terminalId = typeof candidate.terminalId === "string" ? candidate.terminalId.trim() : "";
|
||||
const terminalLabel =
|
||||
typeof candidate.terminalLabel === "string" ? candidate.terminalLabel.trim() : "";
|
||||
if (terminalId.length === 0 || terminalLabel.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const normalizedLineStart = Math.max(1, Math.floor(lineStart));
|
||||
const normalizedLineEnd = Math.max(normalizedLineStart, Math.floor(lineEnd));
|
||||
return {
|
||||
id,
|
||||
threadId: threadId as ThreadId,
|
||||
createdAt,
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
lineStart: normalizedLineStart,
|
||||
lineEnd: normalizedLineEnd,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeDraftThreadEnvMode(
|
||||
value: unknown,
|
||||
fallbackWorktreePath: string | null,
|
||||
@@ -397,13 +526,19 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
continue;
|
||||
}
|
||||
const draftCandidate = draftValue as Record<string, unknown>;
|
||||
const prompt = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
|
||||
const promptCandidate = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
|
||||
const attachments = Array.isArray(draftCandidate.attachments)
|
||||
? draftCandidate.attachments.flatMap((entry) => {
|
||||
const normalized = normalizePersistedAttachment(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const terminalContexts = Array.isArray(draftCandidate.terminalContexts)
|
||||
? draftCandidate.terminalContexts.flatMap((entry) => {
|
||||
const normalized = normalizePersistedTerminalContextDraft(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
})
|
||||
: [];
|
||||
const provider = normalizeProviderKind(draftCandidate.provider);
|
||||
const model =
|
||||
typeof draftCandidate.model === "string"
|
||||
@@ -427,9 +562,14 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
const codexFastMode =
|
||||
draftCandidate.codexFastMode === true ||
|
||||
(typeof draftCandidate.serviceTier === "string" && draftCandidate.serviceTier === "fast");
|
||||
const prompt = ensureInlineTerminalContextPlaceholders(
|
||||
promptCandidate,
|
||||
terminalContexts.length,
|
||||
);
|
||||
if (
|
||||
prompt.length === 0 &&
|
||||
promptCandidate.length === 0 &&
|
||||
attachments.length === 0 &&
|
||||
terminalContexts.length === 0 &&
|
||||
!provider &&
|
||||
!model &&
|
||||
!runtimeMode &&
|
||||
@@ -442,6 +582,7 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
|
||||
nextDraftsByThreadId[threadId as ThreadId] = {
|
||||
prompt,
|
||||
attachments,
|
||||
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(model ? { model } : {}),
|
||||
...(runtimeMode ? { runtimeMode } : {}),
|
||||
@@ -548,6 +689,11 @@ function toHydratedThreadDraft(
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: persistedDraft.attachments,
|
||||
terminalContexts:
|
||||
persistedDraft.terminalContexts?.map((context) => ({
|
||||
...context,
|
||||
text: "",
|
||||
})) ?? [],
|
||||
provider: persistedDraft.provider ?? null,
|
||||
model: persistedDraft.model ?? null,
|
||||
runtimeMode: persistedDraft.runtimeMode ?? null,
|
||||
@@ -817,6 +963,30 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setTerminalContexts: (threadId, contexts) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedContexts = normalizeTerminalContextsForThread(threadId, contexts);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
prompt: ensureInlineTerminalContextPlaceholders(
|
||||
existing.prompt,
|
||||
normalizedContexts.length,
|
||||
),
|
||||
terminalContexts: normalizedContexts,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProvider: (threadId, provider) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
@@ -1066,6 +1236,124 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
insertTerminalContext: (threadId, prompt, context, index) => {
|
||||
if (threadId.length === 0) {
|
||||
return false;
|
||||
}
|
||||
let inserted = false;
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const normalizedContext = normalizeTerminalContextForThread(threadId, context);
|
||||
if (!normalizedContext) {
|
||||
return state;
|
||||
}
|
||||
const dedupKey = terminalContextDedupKey(normalizedContext);
|
||||
if (
|
||||
existing.terminalContexts.some((entry) => entry.id === normalizedContext.id) ||
|
||||
existing.terminalContexts.some((entry) => terminalContextDedupKey(entry) === dedupKey)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
inserted = true;
|
||||
const boundedIndex = Math.max(0, Math.min(existing.terminalContexts.length, index));
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
prompt,
|
||||
terminalContexts: [
|
||||
...existing.terminalContexts.slice(0, boundedIndex),
|
||||
normalizedContext,
|
||||
...existing.terminalContexts.slice(boundedIndex),
|
||||
],
|
||||
};
|
||||
return {
|
||||
draftsByThreadId: {
|
||||
...state.draftsByThreadId,
|
||||
[threadId]: nextDraft,
|
||||
},
|
||||
};
|
||||
});
|
||||
return inserted;
|
||||
},
|
||||
addTerminalContext: (threadId, context) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
get().addTerminalContexts(threadId, [context]);
|
||||
},
|
||||
addTerminalContexts: (threadId, contexts) => {
|
||||
if (threadId.length === 0 || contexts.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const acceptedContexts = normalizeTerminalContextsForThread(threadId, [
|
||||
...existing.terminalContexts,
|
||||
...contexts,
|
||||
]).slice(existing.terminalContexts.length);
|
||||
if (acceptedContexts.length === 0) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
draftsByThreadId: {
|
||||
...state.draftsByThreadId,
|
||||
[threadId]: {
|
||||
...existing,
|
||||
prompt: ensureInlineTerminalContextPlaceholders(
|
||||
existing.prompt,
|
||||
existing.terminalContexts.length + acceptedContexts.length,
|
||||
),
|
||||
terminalContexts: [...existing.terminalContexts, ...acceptedContexts],
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
removeTerminalContext: (threadId, contextId) => {
|
||||
if (threadId.length === 0 || contextId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
terminalContexts: current.terminalContexts.filter(
|
||||
(context) => context.id !== contextId,
|
||||
),
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
clearTerminalContexts: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadId[threadId];
|
||||
if (!current || current.terminalContexts.length === 0) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
terminalContexts: [],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
clearPersistedAttachments: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
@@ -1159,6 +1447,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1218,6 +1507,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.provider === null &&
|
||||
draft.model === null &&
|
||||
draft.runtimeMode === null &&
|
||||
@@ -1231,6 +1521,17 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
prompt: draft.prompt,
|
||||
attachments: draft.persistedAttachments,
|
||||
};
|
||||
if (draft.terminalContexts.length > 0) {
|
||||
persistedDraft.terminalContexts = draft.terminalContexts.map((context) => ({
|
||||
id: context.id,
|
||||
threadId: context.threadId,
|
||||
createdAt: context.createdAt,
|
||||
terminalId: context.terminalId,
|
||||
terminalLabel: context.terminalLabel,
|
||||
lineStart: context.lineStart,
|
||||
lineEnd: context.lineEnd,
|
||||
}));
|
||||
}
|
||||
if (draft.model) {
|
||||
persistedDraft.model = draft.model;
|
||||
}
|
||||
|
||||
+161
-62
@@ -1,49 +1,86 @@
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import type { ThemePaletteDefinition } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_THEME_PALETTE_ID,
|
||||
getThemePaletteCatalog,
|
||||
type ThemePalette,
|
||||
type ThemePreference,
|
||||
} from "../lib/themePalettes";
|
||||
|
||||
type Theme = "light" | "dark" | "system";
|
||||
type ThemeSnapshot = {
|
||||
theme: Theme;
|
||||
systemDark: boolean;
|
||||
readonly theme: ThemePreference;
|
||||
readonly systemDark: boolean;
|
||||
readonly requestedPaletteId: string;
|
||||
readonly paletteId: string;
|
||||
readonly palette: ThemePalette;
|
||||
readonly palettes: readonly ThemePalette[];
|
||||
readonly resolvedTheme: "light" | "dark";
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "t3code:theme";
|
||||
const THEME_STORAGE_KEY = "t3code:theme";
|
||||
const PALETTE_STORAGE_KEY = "t3code:theme-palette";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let listeners = new Set<() => void>();
|
||||
let lastSnapshot: ThemeSnapshot | null = null;
|
||||
let lastDesktopTheme: Theme | null = null;
|
||||
let lastDesktopTheme: ThemePreference | null = null;
|
||||
let customThemes: readonly ThemePaletteDefinition[] = [];
|
||||
let customThemesSerialized = "[]";
|
||||
let customThemesRevision = 0;
|
||||
let cachedPalettes: { revision: number; palettes: readonly ThemePalette[] } | null = null;
|
||||
|
||||
function emitChange() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function getSystemDark(): boolean {
|
||||
function getSystemDark() {
|
||||
if (typeof window.matchMedia !== "function") {
|
||||
return false;
|
||||
}
|
||||
return window.matchMedia(MEDIA_QUERY).matches;
|
||||
}
|
||||
|
||||
function getStored(): Theme {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw === "light" || raw === "dark" || raw === "system") return raw;
|
||||
function getStoredTheme(): ThemePreference {
|
||||
const raw = localStorage.getItem(THEME_STORAGE_KEY);
|
||||
if (raw === "light" || raw === "dark" || raw === "system") {
|
||||
return raw;
|
||||
}
|
||||
return "system";
|
||||
}
|
||||
|
||||
function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
if (suppressTransitions) {
|
||||
document.documentElement.classList.add("no-transitions");
|
||||
}
|
||||
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
syncDesktopTheme(theme);
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
});
|
||||
}
|
||||
function getStoredPaletteId() {
|
||||
const raw = localStorage.getItem(PALETTE_STORAGE_KEY)?.trim();
|
||||
return raw && raw.length > 0 ? raw : DEFAULT_THEME_PALETTE_ID;
|
||||
}
|
||||
|
||||
function syncDesktopTheme(theme: Theme) {
|
||||
function getPaletteCatalog() {
|
||||
if (cachedPalettes && cachedPalettes.revision === customThemesRevision) {
|
||||
return cachedPalettes.palettes;
|
||||
}
|
||||
|
||||
const palettes = getThemePaletteCatalog(customThemes);
|
||||
cachedPalettes = {
|
||||
revision: customThemesRevision,
|
||||
palettes,
|
||||
};
|
||||
return palettes;
|
||||
}
|
||||
|
||||
function resolvePalette(paletteId: string) {
|
||||
const palettes = getPaletteCatalog();
|
||||
const fallbackPalette =
|
||||
palettes.find((candidate) => candidate.id === DEFAULT_THEME_PALETTE_ID) ?? palettes[0];
|
||||
if (!fallbackPalette) {
|
||||
throw new Error("No theme palettes are registered.");
|
||||
}
|
||||
|
||||
return {
|
||||
palettes,
|
||||
palette: palettes.find((candidate) => candidate.id === paletteId) ?? fallbackPalette,
|
||||
};
|
||||
}
|
||||
|
||||
function syncDesktopTheme(theme: ThemePreference) {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || lastDesktopTheme === theme) {
|
||||
return;
|
||||
@@ -57,65 +94,127 @@ function syncDesktopTheme(theme: Theme) {
|
||||
});
|
||||
}
|
||||
|
||||
// Apply immediately on module load to prevent flash
|
||||
applyTheme(getStored());
|
||||
function applyThemeSnapshot(snapshot: ThemeSnapshot, suppressTransitions = false) {
|
||||
if (suppressTransitions) {
|
||||
document.documentElement.classList.add("no-transitions");
|
||||
}
|
||||
|
||||
document.documentElement.classList.toggle("dark", snapshot.resolvedTheme === "dark");
|
||||
document.documentElement.dataset.themePalette = snapshot.paletteId;
|
||||
document.documentElement.dataset.themeMode = snapshot.resolvedTheme;
|
||||
|
||||
const paletteTokens =
|
||||
snapshot.resolvedTheme === "dark" ? snapshot.palette.dark : snapshot.palette.light;
|
||||
for (const [token, value] of Object.entries(paletteTokens)) {
|
||||
document.documentElement.style.setProperty(`--${token}`, value);
|
||||
}
|
||||
|
||||
syncDesktopTheme(snapshot.theme);
|
||||
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal.
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getSnapshot(): ThemeSnapshot {
|
||||
const theme = getStored();
|
||||
const theme = getStoredTheme();
|
||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||
const resolvedTheme = theme === "system" ? (systemDark ? "dark" : "light") : theme;
|
||||
const requestedPaletteId = getStoredPaletteId();
|
||||
const { palette, palettes } = resolvePalette(requestedPaletteId);
|
||||
|
||||
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
|
||||
if (
|
||||
lastSnapshot &&
|
||||
lastSnapshot.theme === theme &&
|
||||
lastSnapshot.systemDark === systemDark &&
|
||||
lastSnapshot.requestedPaletteId === requestedPaletteId &&
|
||||
lastSnapshot.paletteId === palette.id &&
|
||||
lastSnapshot.palettes === palettes
|
||||
) {
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
lastSnapshot = { theme, systemDark };
|
||||
lastSnapshot = {
|
||||
theme,
|
||||
systemDark,
|
||||
requestedPaletteId,
|
||||
paletteId: palette.id,
|
||||
palette,
|
||||
palettes,
|
||||
resolvedTheme,
|
||||
};
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.push(listener);
|
||||
function updateSnapshot(suppressTransitions = false) {
|
||||
const snapshot = getSnapshot();
|
||||
applyThemeSnapshot(snapshot, suppressTransitions);
|
||||
emitChange();
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
|
||||
// Listen for system preference changes
|
||||
const mq = window.matchMedia(MEDIA_QUERY);
|
||||
const handleChange = () => {
|
||||
if (getStored() === "system") applyTheme("system", true);
|
||||
emitChange();
|
||||
if (getStoredTheme() === "system") {
|
||||
updateSnapshot(true);
|
||||
}
|
||||
};
|
||||
mq.addEventListener("change", handleChange);
|
||||
const mq = typeof window.matchMedia === "function" ? window.matchMedia(MEDIA_QUERY) : null;
|
||||
mq?.addEventListener("change", handleChange);
|
||||
|
||||
// Listen for storage changes from other tabs
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEY) {
|
||||
applyTheme(getStored(), true);
|
||||
emitChange();
|
||||
const handleStorage = (event: StorageEvent) => {
|
||||
if (event.key === THEME_STORAGE_KEY || event.key === PALETTE_STORAGE_KEY) {
|
||||
updateSnapshot(true);
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", handleStorage);
|
||||
|
||||
return () => {
|
||||
listeners = listeners.filter((l) => l !== listener);
|
||||
mq.removeEventListener("change", handleChange);
|
||||
listeners.delete(listener);
|
||||
mq?.removeEventListener("change", handleChange);
|
||||
window.removeEventListener("storage", handleStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function setCustomThemes(nextThemes: readonly ThemePaletteDefinition[]) {
|
||||
const nextSerialized = JSON.stringify(nextThemes);
|
||||
if (nextSerialized === customThemesSerialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
customThemes = nextThemes;
|
||||
customThemesSerialized = nextSerialized;
|
||||
customThemesRevision += 1;
|
||||
cachedPalettes = null;
|
||||
updateSnapshot(true);
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
|
||||
const theme = snapshot.theme;
|
||||
|
||||
const resolvedTheme: "light" | "dark" =
|
||||
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
applyTheme(next, true);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
// Keep DOM in sync on mount/change
|
||||
useEffect(() => {
|
||||
applyTheme(theme);
|
||||
}, [theme]);
|
||||
|
||||
return { theme, setTheme, resolvedTheme } as const;
|
||||
return {
|
||||
theme: snapshot.theme,
|
||||
resolvedTheme: snapshot.resolvedTheme,
|
||||
palette: snapshot.palette,
|
||||
paletteId: snapshot.paletteId,
|
||||
palettes: snapshot.palettes,
|
||||
setTheme(next: ThemePreference) {
|
||||
localStorage.setItem(THEME_STORAGE_KEY, next);
|
||||
updateSnapshot(true);
|
||||
},
|
||||
setPaletteId(nextPaletteId: string) {
|
||||
localStorage.setItem(PALETTE_STORAGE_KEY, nextPaletteId);
|
||||
updateSnapshot(true);
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
||||
applyThemeSnapshot(getSnapshot());
|
||||
}
|
||||
@@ -112,6 +112,7 @@ export function gitCheckoutMutationOptions(input: {
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
model?: string | null;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
@@ -134,6 +135,7 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
},
|
||||
onSettled: async () => {
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
appendTerminalContextsToPrompt,
|
||||
buildTerminalContextPreviewTitle,
|
||||
buildTerminalContextBlock,
|
||||
countInlineTerminalContextPlaceholders,
|
||||
deriveDisplayedUserMessageState,
|
||||
ensureInlineTerminalContextPlaceholders,
|
||||
extractTrailingTerminalContexts,
|
||||
filterTerminalContextsWithText,
|
||||
formatInlineTerminalContextLabel,
|
||||
formatTerminalContextLabel,
|
||||
hasTerminalContextText,
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
isTerminalContextExpired,
|
||||
materializeInlineTerminalContextPrompt,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "./terminalContext";
|
||||
|
||||
function makeContext(overrides?: Partial<TerminalContextDraft>): TerminalContextDraft {
|
||||
return {
|
||||
id: "context-1",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 12,
|
||||
lineEnd: 13,
|
||||
text: "git status\nOn branch main",
|
||||
createdAt: "2026-03-13T12:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("terminalContext", () => {
|
||||
it("formats terminal labels with line ranges", () => {
|
||||
expect(formatTerminalContextLabel(makeContext())).toBe("Terminal 1 lines 12-13");
|
||||
expect(
|
||||
formatTerminalContextLabel(
|
||||
makeContext({
|
||||
lineStart: 9,
|
||||
lineEnd: 9,
|
||||
}),
|
||||
),
|
||||
).toBe("Terminal 1 line 9");
|
||||
});
|
||||
|
||||
it("builds a numbered terminal context block", () => {
|
||||
expect(buildTerminalContextBlock([makeContext()])).toBe(
|
||||
[
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 12-13:",
|
||||
" 12 | git status",
|
||||
" 13 | On branch main",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("appends terminal context blocks after prompt text", () => {
|
||||
expect(appendTerminalContextsToPrompt("Investigate this", [makeContext()])).toBe(
|
||||
[
|
||||
"Investigate this",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 12-13:",
|
||||
" 12 | git status",
|
||||
" 13 | On branch main",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces inline placeholders with inline terminal labels before appending context blocks", () => {
|
||||
expect(
|
||||
appendTerminalContextsToPrompt(
|
||||
`Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
|
||||
[makeContext()],
|
||||
),
|
||||
).toBe(
|
||||
[
|
||||
"Investigate @terminal-1:12-13 carefully",
|
||||
"",
|
||||
"<terminal_context>",
|
||||
"- Terminal 1 lines 12-13:",
|
||||
" 12 | git status",
|
||||
" 13 | On branch main",
|
||||
"</terminal_context>",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("extracts terminal context blocks from message text", () => {
|
||||
const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
|
||||
expect(extractTrailingTerminalContexts(prompt)).toEqual({
|
||||
promptText: "Investigate this",
|
||||
contextCount: 1,
|
||||
previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
|
||||
contexts: [
|
||||
{
|
||||
header: "Terminal 1 lines 12-13",
|
||||
body: "12 | git status\n13 | On branch main",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("derives displayed user message state from terminal context prompts", () => {
|
||||
const prompt = appendTerminalContextsToPrompt("Investigate this", [makeContext()]);
|
||||
expect(deriveDisplayedUserMessageState(prompt)).toEqual({
|
||||
visibleText: "Investigate this",
|
||||
copyText: prompt,
|
||||
contextCount: 1,
|
||||
previewTitle: "Terminal 1 lines 12-13\n12 | git status\n13 | On branch main",
|
||||
contexts: [
|
||||
{
|
||||
header: "Terminal 1 lines 12-13",
|
||||
body: "12 | git status\n13 | On branch main",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves prompt text when no trailing terminal context block exists", () => {
|
||||
expect(extractTrailingTerminalContexts("No attached context")).toEqual({
|
||||
promptText: "No attached context",
|
||||
contextCount: 0,
|
||||
previewTitle: null,
|
||||
contexts: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null preview title when every context is invalid", () => {
|
||||
expect(
|
||||
buildTerminalContextPreviewTitle([
|
||||
makeContext({
|
||||
terminalId: " ",
|
||||
}),
|
||||
makeContext({
|
||||
id: "context-2",
|
||||
text: "\n\n",
|
||||
}),
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks inline terminal context placeholders in prompt text", () => {
|
||||
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
expect(countInlineTerminalContextPlaceholders(`a${placeholder}b${placeholder}`)).toBe(2);
|
||||
expect(ensureInlineTerminalContextPlaceholders("Investigate this", 2)).toBe(
|
||||
`${placeholder}${placeholder}Investigate this`,
|
||||
);
|
||||
expect(insertInlineTerminalContextPlaceholder("abc", 1)).toEqual({
|
||||
prompt: `a ${placeholder} bc`,
|
||||
cursor: 4,
|
||||
contextIndex: 0,
|
||||
});
|
||||
expect(removeInlineTerminalContextPlaceholder(`a${placeholder}b${placeholder}c`, 1)).toEqual({
|
||||
prompt: `a${placeholder}bc`,
|
||||
cursor: 3,
|
||||
});
|
||||
expect(stripInlineTerminalContextPlaceholders(`a${placeholder}b`)).toBe("ab");
|
||||
});
|
||||
|
||||
it("inserts a placeholder after a file mention when given the expanded prompt cursor", () => {
|
||||
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
expect(insertInlineTerminalContextPlaceholder("Inspect @package.json ", 22)).toEqual({
|
||||
prompt: `Inspect @package.json ${placeholder} `,
|
||||
cursor: 24,
|
||||
contextIndex: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("adds a trailing space and consumes an existing trailing space at the insertion point", () => {
|
||||
const placeholder = INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
expect(insertInlineTerminalContextPlaceholder("yo whats", 3)).toEqual({
|
||||
prompt: `yo ${placeholder} whats`,
|
||||
cursor: 5,
|
||||
contextIndex: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks contexts without snapshot text as expired and filters them from sendable contexts", () => {
|
||||
const liveContext = makeContext();
|
||||
const expiredContext = makeContext({
|
||||
id: "context-2",
|
||||
text: "",
|
||||
});
|
||||
|
||||
expect(hasTerminalContextText(liveContext)).toBe(true);
|
||||
expect(isTerminalContextExpired(liveContext)).toBe(false);
|
||||
expect(hasTerminalContextText(expiredContext)).toBe(false);
|
||||
expect(isTerminalContextExpired(expiredContext)).toBe(true);
|
||||
expect(filterTerminalContextsWithText([expiredContext, liveContext])).toEqual([liveContext]);
|
||||
});
|
||||
|
||||
it("formats and materializes inline terminal labels from placeholder positions", () => {
|
||||
expect(formatInlineTerminalContextLabel(makeContext())).toBe("@terminal-1:12-13");
|
||||
expect(
|
||||
materializeInlineTerminalContextPrompt(
|
||||
`Investigate ${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} carefully`,
|
||||
[makeContext()],
|
||||
),
|
||||
).toBe("Investigate @terminal-1:12-13 carefully");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,356 @@
|
||||
import { type ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export interface TerminalContextSelection {
|
||||
terminalId: string;
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface TerminalContextDraft extends TerminalContextSelection {
|
||||
id: string;
|
||||
threadId: ThreadId;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface ExtractedTerminalContexts {
|
||||
promptText: string;
|
||||
contextCount: number;
|
||||
previewTitle: string | null;
|
||||
contexts: ParsedTerminalContextEntry[];
|
||||
}
|
||||
|
||||
export interface DisplayedUserMessageState {
|
||||
visibleText: string;
|
||||
copyText: string;
|
||||
contextCount: number;
|
||||
previewTitle: string | null;
|
||||
contexts: ParsedTerminalContextEntry[];
|
||||
}
|
||||
|
||||
export interface ParsedTerminalContextEntry {
|
||||
header: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export const INLINE_TERMINAL_CONTEXT_PLACEHOLDER = "\uFFFC";
|
||||
|
||||
const TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN =
|
||||
/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/;
|
||||
|
||||
export function normalizeTerminalContextText(text: string): string {
|
||||
return text.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
|
||||
}
|
||||
|
||||
export function hasTerminalContextText(context: { text: string }): boolean {
|
||||
return normalizeTerminalContextText(context.text).length > 0;
|
||||
}
|
||||
|
||||
export function isTerminalContextExpired(context: { text: string }): boolean {
|
||||
return !hasTerminalContextText(context);
|
||||
}
|
||||
|
||||
export function filterTerminalContextsWithText<T extends { text: string }>(
|
||||
contexts: ReadonlyArray<T>,
|
||||
): T[] {
|
||||
return contexts.filter((context) => hasTerminalContextText(context));
|
||||
}
|
||||
|
||||
function previewTerminalContextText(text: string): string {
|
||||
const normalized = normalizeTerminalContextText(text);
|
||||
if (normalized.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const lines = normalized.split("\n");
|
||||
const visibleLines = lines.slice(0, 3);
|
||||
if (lines.length > 3) {
|
||||
visibleLines.push("...");
|
||||
}
|
||||
const preview = visibleLines.join("\n");
|
||||
return preview.length > 180 ? `${preview.slice(0, 177)}...` : preview;
|
||||
}
|
||||
|
||||
export function normalizeTerminalContextSelection(
|
||||
selection: TerminalContextSelection,
|
||||
): TerminalContextSelection | null {
|
||||
const text = normalizeTerminalContextText(selection.text);
|
||||
const terminalId = selection.terminalId.trim();
|
||||
const terminalLabel = selection.terminalLabel.trim();
|
||||
if (text.length === 0 || terminalId.length === 0 || terminalLabel.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const lineStart = Math.max(1, Math.floor(selection.lineStart));
|
||||
const lineEnd = Math.max(lineStart, Math.floor(selection.lineEnd));
|
||||
return {
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
lineStart,
|
||||
lineEnd,
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTerminalContextRange(selection: {
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}): string {
|
||||
return selection.lineStart === selection.lineEnd
|
||||
? `line ${selection.lineStart}`
|
||||
: `lines ${selection.lineStart}-${selection.lineEnd}`;
|
||||
}
|
||||
|
||||
export function formatTerminalContextLabel(selection: {
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}): string {
|
||||
return `${selection.terminalLabel} ${formatTerminalContextRange(selection)}`;
|
||||
}
|
||||
|
||||
export function formatInlineTerminalContextLabel(selection: {
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}): string {
|
||||
const terminalLabel = selection.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
|
||||
const range =
|
||||
selection.lineStart === selection.lineEnd
|
||||
? `${selection.lineStart}`
|
||||
: `${selection.lineStart}-${selection.lineEnd}`;
|
||||
return `@${terminalLabel}:${range}`;
|
||||
}
|
||||
|
||||
export function buildTerminalContextPreviewTitle(
|
||||
contexts: ReadonlyArray<TerminalContextSelection>,
|
||||
): string | null {
|
||||
if (contexts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const previews = contexts
|
||||
.map((context) => {
|
||||
const normalized = normalizeTerminalContextSelection(context);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const preview = previewTerminalContextText(normalized.text);
|
||||
return preview.length > 0
|
||||
? `${formatTerminalContextLabel(normalized)}\n${preview}`
|
||||
: formatTerminalContextLabel(normalized);
|
||||
})
|
||||
.filter((value): value is string => value !== null)
|
||||
.join("\n\n");
|
||||
return previews.length > 0 ? previews : null;
|
||||
}
|
||||
|
||||
function buildTerminalContextBodyLines(selection: TerminalContextSelection): string[] {
|
||||
return normalizeTerminalContextText(selection.text)
|
||||
.split("\n")
|
||||
.map((line, index) => ` ${selection.lineStart + index} | ${line}`);
|
||||
}
|
||||
|
||||
export function buildTerminalContextBlock(
|
||||
contexts: ReadonlyArray<TerminalContextSelection>,
|
||||
): string {
|
||||
const normalizedContexts = contexts
|
||||
.map((context) => normalizeTerminalContextSelection(context))
|
||||
.filter((context): context is TerminalContextSelection => context !== null);
|
||||
if (normalizedContexts.length === 0) {
|
||||
return "";
|
||||
}
|
||||
const lines: string[] = [];
|
||||
for (let index = 0; index < normalizedContexts.length; index += 1) {
|
||||
const context = normalizedContexts[index]!;
|
||||
lines.push(`- ${formatTerminalContextLabel(context)}:`);
|
||||
lines.push(...buildTerminalContextBodyLines(context));
|
||||
if (index < normalizedContexts.length - 1) {
|
||||
lines.push("");
|
||||
}
|
||||
}
|
||||
return ["<terminal_context>", ...lines, "</terminal_context>"].join("\n");
|
||||
}
|
||||
|
||||
export function materializeInlineTerminalContextPrompt(
|
||||
prompt: string,
|
||||
contexts: ReadonlyArray<{
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
}>,
|
||||
): string {
|
||||
let nextContextIndex = 0;
|
||||
let result = "";
|
||||
|
||||
for (const char of prompt) {
|
||||
if (char !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
result += char;
|
||||
continue;
|
||||
}
|
||||
const context = contexts[nextContextIndex] ?? null;
|
||||
nextContextIndex += 1;
|
||||
if (!context) {
|
||||
continue;
|
||||
}
|
||||
result += formatInlineTerminalContextLabel(context);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function appendTerminalContextsToPrompt(
|
||||
prompt: string,
|
||||
contexts: ReadonlyArray<TerminalContextSelection>,
|
||||
): string {
|
||||
const trimmedPrompt = materializeInlineTerminalContextPrompt(prompt, contexts).trim();
|
||||
const contextBlock = buildTerminalContextBlock(contexts);
|
||||
if (contextBlock.length === 0) {
|
||||
return trimmedPrompt;
|
||||
}
|
||||
return trimmedPrompt.length > 0 ? `${trimmedPrompt}\n\n${contextBlock}` : contextBlock;
|
||||
}
|
||||
|
||||
export function extractTrailingTerminalContexts(prompt: string): ExtractedTerminalContexts {
|
||||
const match = TRAILING_TERMINAL_CONTEXT_BLOCK_PATTERN.exec(prompt);
|
||||
if (!match) {
|
||||
return {
|
||||
promptText: prompt,
|
||||
contextCount: 0,
|
||||
previewTitle: null,
|
||||
contexts: [],
|
||||
};
|
||||
}
|
||||
const promptText = prompt.slice(0, match.index).replace(/\n+$/, "");
|
||||
const parsedContexts = parseTerminalContextEntries(match[1] ?? "");
|
||||
return {
|
||||
promptText,
|
||||
contextCount: parsedContexts.length,
|
||||
previewTitle:
|
||||
parsedContexts.length > 0
|
||||
? parsedContexts
|
||||
.map(({ header, body }) => (body.length > 0 ? `${header}\n${body}` : header))
|
||||
.join("\n\n")
|
||||
: null,
|
||||
contexts: parsedContexts,
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveDisplayedUserMessageState(prompt: string): DisplayedUserMessageState {
|
||||
const extractedContexts = extractTrailingTerminalContexts(prompt);
|
||||
return {
|
||||
visibleText: extractedContexts.promptText,
|
||||
copyText: prompt,
|
||||
contextCount: extractedContexts.contextCount,
|
||||
previewTitle: extractedContexts.previewTitle,
|
||||
contexts: extractedContexts.contexts,
|
||||
};
|
||||
}
|
||||
|
||||
function parseTerminalContextEntries(block: string): ParsedTerminalContextEntry[] {
|
||||
const entries: ParsedTerminalContextEntry[] = [];
|
||||
let current: { header: string; bodyLines: string[] } | null = null;
|
||||
|
||||
const commitCurrent = () => {
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
entries.push({
|
||||
header: current.header,
|
||||
body: current.bodyLines.join("\n").trimEnd(),
|
||||
});
|
||||
current = null;
|
||||
};
|
||||
|
||||
for (const rawLine of block.split("\n")) {
|
||||
const headerMatch = /^- (.+):$/.exec(rawLine);
|
||||
if (headerMatch) {
|
||||
commitCurrent();
|
||||
current = {
|
||||
header: headerMatch[1]!,
|
||||
bodyLines: [],
|
||||
};
|
||||
continue;
|
||||
}
|
||||
if (!current) {
|
||||
continue;
|
||||
}
|
||||
if (rawLine.startsWith(" ")) {
|
||||
current.bodyLines.push(rawLine.slice(2));
|
||||
continue;
|
||||
}
|
||||
if (rawLine.length === 0) {
|
||||
current.bodyLines.push("");
|
||||
}
|
||||
}
|
||||
|
||||
commitCurrent();
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function countInlineTerminalContextPlaceholders(prompt: string): number {
|
||||
let count = 0;
|
||||
for (const char of prompt) {
|
||||
if (char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
export function ensureInlineTerminalContextPlaceholders(
|
||||
prompt: string,
|
||||
terminalContextCount: number,
|
||||
): string {
|
||||
const missingCount = terminalContextCount - countInlineTerminalContextPlaceholders(prompt);
|
||||
if (missingCount <= 0) {
|
||||
return prompt;
|
||||
}
|
||||
return `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER.repeat(missingCount)}${prompt}`;
|
||||
}
|
||||
|
||||
function isInlineTerminalContextBoundaryWhitespace(char: string | undefined): boolean {
|
||||
return char === undefined || char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
}
|
||||
|
||||
export function insertInlineTerminalContextPlaceholder(
|
||||
prompt: string,
|
||||
cursorInput: number,
|
||||
): { prompt: string; cursor: number; contextIndex: number } {
|
||||
const cursor = Math.max(0, Math.min(prompt.length, Math.floor(cursorInput)));
|
||||
const needsLeadingSpace = !isInlineTerminalContextBoundaryWhitespace(prompt[cursor - 1]);
|
||||
const replacement = `${needsLeadingSpace ? " " : ""}${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} `;
|
||||
const rangeEnd = prompt[cursor] === " " ? cursor + 1 : cursor;
|
||||
return {
|
||||
prompt: `${prompt.slice(0, cursor)}${replacement}${prompt.slice(rangeEnd)}`,
|
||||
cursor: cursor + replacement.length,
|
||||
contextIndex: countInlineTerminalContextPlaceholders(prompt.slice(0, cursor)),
|
||||
};
|
||||
}
|
||||
|
||||
export function stripInlineTerminalContextPlaceholders(prompt: string): string {
|
||||
return prompt.replaceAll(INLINE_TERMINAL_CONTEXT_PLACEHOLDER, "");
|
||||
}
|
||||
|
||||
export function removeInlineTerminalContextPlaceholder(
|
||||
prompt: string,
|
||||
contextIndex: number,
|
||||
): { prompt: string; cursor: number } {
|
||||
if (contextIndex < 0) {
|
||||
return { prompt, cursor: prompt.length };
|
||||
}
|
||||
|
||||
let placeholderIndex = 0;
|
||||
for (let index = 0; index < prompt.length; index += 1) {
|
||||
if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
|
||||
continue;
|
||||
}
|
||||
if (placeholderIndex === contextIndex) {
|
||||
return {
|
||||
prompt: prompt.slice(0, index) + prompt.slice(index + 1),
|
||||
cursor: index,
|
||||
};
|
||||
}
|
||||
placeholderIndex += 1;
|
||||
}
|
||||
|
||||
return { prompt, cursor: prompt.length };
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_THEME_PALETTE_ID, getThemePaletteCatalog } from "./themePalettes";
|
||||
|
||||
describe("getThemePaletteCatalog", () => {
|
||||
it("keeps built-in palettes ahead of custom themes", () => {
|
||||
const palettes = getThemePaletteCatalog([
|
||||
{
|
||||
id: "midnight-mint",
|
||||
label: "Midnight Mint",
|
||||
dark: {
|
||||
primary: "oklch(0.79 0.16 170)",
|
||||
ring: "oklch(0.79 0.16 170)",
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(palettes[0]?.id).toBe(DEFAULT_THEME_PALETTE_ID);
|
||||
expect(palettes.at(-1)?.id).toBe("midnight-mint");
|
||||
expect(palettes.at(-1)?.source).toBe("custom");
|
||||
});
|
||||
|
||||
it("merges custom palettes with the default token set for both modes", () => {
|
||||
const palette = getThemePaletteCatalog([
|
||||
{
|
||||
id: "midnight-mint",
|
||||
label: "Midnight Mint",
|
||||
dark: {
|
||||
primary: "oklch(0.79 0.16 170)",
|
||||
},
|
||||
},
|
||||
]).find((candidate) => candidate.id === "midnight-mint");
|
||||
|
||||
expect(palette).toBeDefined();
|
||||
expect(palette?.dark.primary).toBe("oklch(0.79 0.16 170)");
|
||||
expect(palette?.dark.background).toBeTruthy();
|
||||
expect(palette?.light.primary).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import {
|
||||
THEME_TOKEN_NAMES,
|
||||
type ThemePaletteDefinition,
|
||||
type ThemeTokenName,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export type ResolvedThemeMode = "light" | "dark";
|
||||
export type ThemePreference = ResolvedThemeMode | "system";
|
||||
export type ThemeTokenMap = Record<ThemeTokenName, string>;
|
||||
export type ThemeTokenOverrides = Partial<ThemeTokenMap>;
|
||||
|
||||
export interface ThemePalette {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
readonly source: "built-in" | "custom";
|
||||
readonly light: ThemeTokenMap;
|
||||
readonly dark: ThemeTokenMap;
|
||||
}
|
||||
|
||||
interface ThemePaletteInput {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
readonly light?: ThemeTokenOverrides;
|
||||
readonly dark?: ThemeTokenOverrides;
|
||||
}
|
||||
|
||||
export const DEFAULT_THEME_PALETTE_ID = "default";
|
||||
|
||||
const DEFAULT_LIGHT_TOKENS: ThemeTokenMap = {
|
||||
background: "var(--color-white)",
|
||||
foreground: "var(--color-neutral-800)",
|
||||
card: "var(--color-white)",
|
||||
"card-foreground": "var(--color-neutral-800)",
|
||||
popover: "var(--color-white)",
|
||||
"popover-foreground": "var(--color-neutral-800)",
|
||||
primary: "oklch(0.488 0.217 264)",
|
||||
"primary-foreground": "var(--color-white)",
|
||||
secondary: "color-mix(in srgb, var(--color-black) 4%, transparent)",
|
||||
"secondary-foreground": "var(--color-neutral-800)",
|
||||
muted: "color-mix(in srgb, var(--color-black) 4%, transparent)",
|
||||
"muted-foreground": "color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-black))",
|
||||
accent: "color-mix(in srgb, var(--color-black) 4%, transparent)",
|
||||
"accent-foreground": "var(--color-neutral-800)",
|
||||
destructive: "var(--color-red-500)",
|
||||
"destructive-foreground": "var(--color-red-700)",
|
||||
border: "color-mix(in srgb, var(--color-black) 8%, transparent)",
|
||||
input: "color-mix(in srgb, var(--color-black) 10%, transparent)",
|
||||
ring: "oklch(0.488 0.217 264)",
|
||||
info: "var(--color-blue-500)",
|
||||
"info-foreground": "var(--color-blue-700)",
|
||||
success: "var(--color-emerald-500)",
|
||||
"success-foreground": "var(--color-emerald-700)",
|
||||
warning: "var(--color-amber-500)",
|
||||
"warning-foreground": "var(--color-amber-700)",
|
||||
};
|
||||
|
||||
const DEFAULT_DARK_TOKENS: ThemeTokenMap = {
|
||||
background: "color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white))",
|
||||
foreground: "var(--color-neutral-100)",
|
||||
card: "color-mix(in srgb, var(--background) 98%, var(--color-white))",
|
||||
"card-foreground": "var(--color-neutral-100)",
|
||||
popover: "color-mix(in srgb, var(--background) 98%, var(--color-white))",
|
||||
"popover-foreground": "var(--color-neutral-100)",
|
||||
primary: "oklch(0.588 0.217 264)",
|
||||
"primary-foreground": "var(--color-white)",
|
||||
secondary: "color-mix(in srgb, var(--color-white) 4%, transparent)",
|
||||
"secondary-foreground": "var(--color-neutral-100)",
|
||||
muted: "color-mix(in srgb, var(--color-white) 4%, transparent)",
|
||||
"muted-foreground": "color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white))",
|
||||
accent: "color-mix(in srgb, var(--color-white) 4%, transparent)",
|
||||
"accent-foreground": "var(--color-neutral-100)",
|
||||
destructive: "color-mix(in srgb, var(--color-red-500) 90%, var(--color-white))",
|
||||
"destructive-foreground": "var(--color-red-400)",
|
||||
border: "color-mix(in srgb, var(--color-white) 6%, transparent)",
|
||||
input: "color-mix(in srgb, var(--color-white) 8%, transparent)",
|
||||
ring: "oklch(0.588 0.217 264)",
|
||||
info: "var(--color-blue-500)",
|
||||
"info-foreground": "var(--color-blue-400)",
|
||||
success: "var(--color-emerald-500)",
|
||||
"success-foreground": "var(--color-emerald-400)",
|
||||
warning: "var(--color-amber-500)",
|
||||
"warning-foreground": "var(--color-amber-400)",
|
||||
};
|
||||
|
||||
const BUILT_IN_THEME_PALETTES: readonly ThemePaletteInput[] = [
|
||||
{
|
||||
id: DEFAULT_THEME_PALETTE_ID,
|
||||
label: "Default",
|
||||
description: "Neutral surfaces with violet accents.",
|
||||
},
|
||||
{
|
||||
id: "ocean",
|
||||
label: "Ocean",
|
||||
description: "Cool blue surfaces with cyan highlights.",
|
||||
light: {
|
||||
background: "oklch(0.985 0.01 240)",
|
||||
card: "oklch(0.995 0.004 240)",
|
||||
popover: "oklch(0.995 0.004 240)",
|
||||
primary: "oklch(0.55 0.18 240)",
|
||||
ring: "oklch(0.55 0.18 240)",
|
||||
accent: "oklch(0.93 0.02 235)",
|
||||
info: "oklch(0.62 0.16 230)",
|
||||
"info-foreground": "oklch(0.42 0.08 230)",
|
||||
border: "color-mix(in srgb, oklch(0.55 0.18 240) 10%, transparent)",
|
||||
input: "color-mix(in srgb, oklch(0.55 0.18 240) 12%, transparent)",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.18 0.03 245)",
|
||||
card: "oklch(0.22 0.03 245)",
|
||||
popover: "oklch(0.22 0.03 245)",
|
||||
primary: "oklch(0.74 0.16 225)",
|
||||
ring: "oklch(0.74 0.16 225)",
|
||||
accent: "color-mix(in srgb, oklch(0.74 0.16 225) 12%, transparent)",
|
||||
info: "oklch(0.78 0.12 220)",
|
||||
border: "color-mix(in srgb, oklch(0.74 0.16 225) 16%, transparent)",
|
||||
input: "color-mix(in srgb, oklch(0.74 0.16 225) 18%, transparent)",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "forest",
|
||||
label: "Forest",
|
||||
description: "Mossy greens with softer neutrals.",
|
||||
light: {
|
||||
background: "oklch(0.985 0.01 150)",
|
||||
card: "oklch(0.995 0.004 150)",
|
||||
popover: "oklch(0.995 0.004 150)",
|
||||
primary: "oklch(0.56 0.16 155)",
|
||||
ring: "oklch(0.56 0.16 155)",
|
||||
success: "oklch(0.62 0.17 155)",
|
||||
"success-foreground": "oklch(0.4 0.08 155)",
|
||||
accent: "oklch(0.94 0.02 155)",
|
||||
border: "color-mix(in srgb, oklch(0.56 0.16 155) 10%, transparent)",
|
||||
input: "color-mix(in srgb, oklch(0.56 0.16 155) 12%, transparent)",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.19 0.02 155)",
|
||||
card: "oklch(0.22 0.02 155)",
|
||||
popover: "oklch(0.22 0.02 155)",
|
||||
primary: "oklch(0.76 0.16 155)",
|
||||
ring: "oklch(0.76 0.16 155)",
|
||||
success: "oklch(0.78 0.15 155)",
|
||||
accent: "color-mix(in srgb, oklch(0.76 0.16 155) 12%, transparent)",
|
||||
border: "color-mix(in srgb, oklch(0.76 0.16 155) 16%, transparent)",
|
||||
input: "color-mix(in srgb, oklch(0.76 0.16 155) 18%, transparent)",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "sunset",
|
||||
label: "Sunset",
|
||||
description: "Warm amber accents with soft rose highlights.",
|
||||
light: {
|
||||
background: "oklch(0.988 0.008 40)",
|
||||
card: "oklch(0.998 0.004 30)",
|
||||
popover: "oklch(0.998 0.004 30)",
|
||||
primary: "oklch(0.66 0.17 40)",
|
||||
ring: "oklch(0.66 0.17 40)",
|
||||
warning: "oklch(0.74 0.16 70)",
|
||||
"warning-foreground": "oklch(0.47 0.12 70)",
|
||||
accent: "oklch(0.95 0.02 20)",
|
||||
border: "color-mix(in srgb, oklch(0.66 0.17 40) 10%, transparent)",
|
||||
input: "color-mix(in srgb, oklch(0.66 0.17 40) 12%, transparent)",
|
||||
},
|
||||
dark: {
|
||||
background: "oklch(0.2 0.02 28)",
|
||||
card: "oklch(0.24 0.02 28)",
|
||||
popover: "oklch(0.24 0.02 28)",
|
||||
primary: "oklch(0.76 0.16 55)",
|
||||
ring: "oklch(0.76 0.16 55)",
|
||||
warning: "oklch(0.79 0.15 75)",
|
||||
accent: "color-mix(in srgb, oklch(0.76 0.16 55) 12%, transparent)",
|
||||
border: "color-mix(in srgb, oklch(0.76 0.16 55) 16%, transparent)",
|
||||
input: "color-mix(in srgb, oklch(0.76 0.16 55) 18%, transparent)",
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const CUSTOM_THEME_FILE_EXAMPLE = `[
|
||||
{
|
||||
"id": "midnight-mint",
|
||||
"label": "Midnight Mint",
|
||||
"description": "Custom palette loaded from ~/.t3/themes.json",
|
||||
"dark": {
|
||||
"background": "oklch(0.17 0.02 220)",
|
||||
"card": "oklch(0.21 0.02 220)",
|
||||
"primary": "oklch(0.79 0.16 170)",
|
||||
"ring": "oklch(0.79 0.16 170)"
|
||||
}
|
||||
}
|
||||
]`;
|
||||
|
||||
function resolveThemePalette(
|
||||
input: ThemePaletteInput | ThemePaletteDefinition,
|
||||
source: ThemePalette["source"],
|
||||
) {
|
||||
const description =
|
||||
"description" in input && typeof input.description === "string"
|
||||
? input.description
|
||||
: source === "custom"
|
||||
? "Loaded from your ~/.t3 themes file."
|
||||
: "Built into T3 Code.";
|
||||
|
||||
return {
|
||||
id: input.id,
|
||||
label: input.label,
|
||||
description,
|
||||
source,
|
||||
light: { ...DEFAULT_LIGHT_TOKENS, ...sanitizeThemeTokenOverrides(input.light) },
|
||||
dark: { ...DEFAULT_DARK_TOKENS, ...sanitizeThemeTokenOverrides(input.dark) },
|
||||
} satisfies ThemePalette;
|
||||
}
|
||||
|
||||
function sanitizeThemeTokenOverrides(overrides: Record<string, string> | undefined) {
|
||||
const sanitized: ThemeTokenOverrides = {};
|
||||
if (!overrides) {
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
for (const tokenName of THEME_TOKEN_NAMES) {
|
||||
const value = overrides[tokenName];
|
||||
if (typeof value === "string") {
|
||||
sanitized[tokenName] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
const BUILT_IN_THEME_PALETTE_MAP = new Map(
|
||||
BUILT_IN_THEME_PALETTES.map((palette) => [palette.id, resolveThemePalette(palette, "built-in")]),
|
||||
);
|
||||
|
||||
export function getBuiltInThemePalettes() {
|
||||
return [...BUILT_IN_THEME_PALETTE_MAP.values()];
|
||||
}
|
||||
|
||||
export function getThemePaletteCatalog(customThemes: readonly ThemePaletteDefinition[] = []) {
|
||||
return [
|
||||
...getBuiltInThemePalettes(),
|
||||
...customThemes.map((palette) => resolveThemePalette(palette, "custom")),
|
||||
];
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { createHashHistory, createBrowserHistory } from "@tanstack/react-router"
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "./index.css";
|
||||
import "./hooks/useTheme";
|
||||
|
||||
import { isElectron } from "./env";
|
||||
import { getRouter } from "./router";
|
||||
|
||||
@@ -20,6 +20,7 @@ import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDra
|
||||
import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { setCustomThemes } from "../hooks/useTheme";
|
||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||
@@ -153,6 +154,19 @@ function EventRouter() {
|
||||
let pending = false;
|
||||
let needsProviderInvalidation = false;
|
||||
|
||||
const syncThemeConfig = async () => {
|
||||
try {
|
||||
const config = await queryClient.fetchQuery(serverConfigQueryOptions());
|
||||
if (disposed) {
|
||||
return null;
|
||||
}
|
||||
setCustomThemes(config.customThemes);
|
||||
return config;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const flushSnapshotSync = async (): Promise<void> => {
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
if (disposed) return;
|
||||
@@ -229,9 +243,11 @@ function EventRouter() {
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
});
|
||||
void syncThemeConfig();
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
void (async () => {
|
||||
await syncSnapshot();
|
||||
await syncThemeConfig();
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
@@ -261,34 +277,79 @@ function EventRouter() {
|
||||
let subscribed = false;
|
||||
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
||||
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
|
||||
if (!subscribed) return;
|
||||
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
|
||||
if (!issue) {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
description: "Keybindings configuration reloaded successfully.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const themeIssue = payload.issues.find((entry) => entry.kind.startsWith("themes."));
|
||||
const keybindingIssue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
|
||||
const themeUpdated = payload.updated.includes("themes");
|
||||
const keybindingsUpdated = payload.updated.includes("keybindings");
|
||||
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Invalid keybindings configuration",
|
||||
description: issue.message,
|
||||
actionProps: {
|
||||
children: "Open keybindings.json",
|
||||
onClick: () => {
|
||||
void queryClient
|
||||
.ensureQueryData(serverConfigQueryOptions())
|
||||
.then((config) => {
|
||||
const editor = resolveAndPersistPreferredEditor(config.availableEditors);
|
||||
if (!editor) {
|
||||
throw new Error("No available editors found.");
|
||||
}
|
||||
return api.shell.openInEditor(config.keybindingsConfigPath, editor);
|
||||
})
|
||||
.catch((error) => {
|
||||
void syncThemeConfig().then((config) => {
|
||||
if (!subscribed || !config) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (themeUpdated) {
|
||||
if (themeIssue) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Invalid themes configuration",
|
||||
description: themeIssue.message,
|
||||
actionProps: {
|
||||
children: "Open themes.json",
|
||||
onClick: () => {
|
||||
const editor = resolveAndPersistPreferredEditor(config.availableEditors);
|
||||
if (!editor) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open themes file",
|
||||
description: "No available editors found.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
void api.shell.openInEditor(config.themesConfigPath, editor).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open themes file",
|
||||
description:
|
||||
error instanceof Error ? error.message : "Unknown error opening file.",
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keybindingsUpdated) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keybindingIssue) {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
description: "Keybindings configuration reloaded successfully.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Invalid keybindings configuration",
|
||||
description: keybindingIssue.message,
|
||||
actionProps: {
|
||||
children: "Open keybindings.json",
|
||||
onClick: () => {
|
||||
const editor = resolveAndPersistPreferredEditor(config.availableEditors);
|
||||
if (!editor) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open keybindings file",
|
||||
description: "No available editors found.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
void api.shell.openInEditor(config.keybindingsConfigPath, editor).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open keybindings file",
|
||||
@@ -296,8 +357,9 @@ function EventRouter() {
|
||||
error instanceof Error ? error.message : "Unknown error opening file.",
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
subscribed = true;
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { type ProviderKind, DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { getAppModelOptions, MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
CUSTOM_THEME_FILE_EXAMPLE,
|
||||
type ResolvedThemeMode,
|
||||
type ThemePalette,
|
||||
} from "../lib/themePalettes";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { ensureNativeApi } from "../nativeApi";
|
||||
import { Button } from "../components/ui/button";
|
||||
@@ -54,13 +59,6 @@ const MODEL_PROVIDER_SETTINGS: Array<{
|
||||
placeholder: "your-codex-model-slug",
|
||||
example: "gpt-6.7-codex-ultra-preview",
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
title: "Claude",
|
||||
description: "Save additional Claude model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-claude-model-slug",
|
||||
example: "claude-sonnet-5-0",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const TIMESTAMP_FORMAT_LABELS = {
|
||||
@@ -74,8 +72,6 @@ function getCustomModelsForProvider(
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "claudeAgent":
|
||||
return settings.customClaudeModels;
|
||||
case "codex":
|
||||
default:
|
||||
return settings.customCodexModels;
|
||||
@@ -87,8 +83,6 @@ function getDefaultCustomModelsForProvider(
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "claudeAgent":
|
||||
return defaults.customClaudeModels;
|
||||
case "codex":
|
||||
default:
|
||||
return defaults.customCodexModels;
|
||||
@@ -97,25 +91,84 @@ function getDefaultCustomModelsForProvider(
|
||||
|
||||
function patchCustomModels(provider: ProviderKind, models: string[]) {
|
||||
switch (provider) {
|
||||
case "claudeAgent":
|
||||
return { customClaudeModels: models };
|
||||
case "codex":
|
||||
default:
|
||||
return { customCodexModels: models };
|
||||
}
|
||||
}
|
||||
|
||||
function ThemePaletteCard(props: {
|
||||
palette: ThemePalette;
|
||||
resolvedTheme: ResolvedThemeMode;
|
||||
selected: boolean;
|
||||
onSelect: () => void;
|
||||
}) {
|
||||
const tokens = props.resolvedTheme === "dark" ? props.palette.dark : props.palette.light;
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={props.selected}
|
||||
className={`rounded-xl border px-4 py-3 text-left transition-colors ${
|
||||
props.selected
|
||||
? "border-primary/60 bg-primary/8"
|
||||
: "border-border bg-background hover:bg-accent"
|
||||
}`}
|
||||
onClick={props.onSelect}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium text-foreground">{props.palette.label}</p>
|
||||
<span className="rounded-full border border-border px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">
|
||||
{props.palette.source}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{props.palette.description}</p>
|
||||
</div>
|
||||
{props.selected ? (
|
||||
<span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
|
||||
Selected
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex items-center gap-2">
|
||||
<ThemeSwatch color={tokens.background} outline />
|
||||
<ThemeSwatch color={tokens.card} outline />
|
||||
<ThemeSwatch color={tokens.primary} />
|
||||
<ThemeSwatch color={tokens.accent} />
|
||||
<ThemeSwatch color={tokens.success} />
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function ThemeSwatch(props: { color: string; outline?: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex h-6 w-6 rounded-full border ${
|
||||
props.outline ? "border-border" : "border-transparent"
|
||||
}`}
|
||||
style={{ backgroundColor: props.color }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SettingsRouteView() {
|
||||
const { theme, setTheme, resolvedTheme } = useTheme();
|
||||
const { theme, setTheme, resolvedTheme, palette, paletteId, palettes, setPaletteId } = useTheme();
|
||||
const { settings, defaults, updateSettings } = useAppSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [isOpeningThemes, setIsOpeningThemes] = useState(false);
|
||||
const [openThemesError, setOpenThemesError] = useState<string | null>(null);
|
||||
const [customModelInputByProvider, setCustomModelInputByProvider] = useState<
|
||||
Record<ProviderKind, string>
|
||||
>({
|
||||
codex: "",
|
||||
claudeAgent: "",
|
||||
});
|
||||
const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<
|
||||
Partial<Record<ProviderKind, string | null>>
|
||||
@@ -124,7 +177,21 @@ function SettingsRouteView() {
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
const themesConfigPath = serverConfigQuery.data?.themesConfigPath ?? null;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||
const themeIssues =
|
||||
serverConfigQuery.data?.issues.filter((issue) => issue.kind.startsWith("themes.")) ?? [];
|
||||
|
||||
const gitTextGenerationModelOptions = getAppModelOptions(
|
||||
"codex",
|
||||
settings.customCodexModels,
|
||||
settings.textGenerationModel,
|
||||
);
|
||||
const selectedGitTextGenerationModelLabel =
|
||||
gitTextGenerationModelOptions.find(
|
||||
(option) =>
|
||||
option.slug === (settings.textGenerationModel ?? DEFAULT_GIT_TEXT_GENERATION_MODEL),
|
||||
)?.name ?? settings.textGenerationModel;
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
if (!keybindingsConfigPath) return;
|
||||
@@ -149,6 +216,27 @@ function SettingsRouteView() {
|
||||
});
|
||||
}, [availableEditors, keybindingsConfigPath]);
|
||||
|
||||
const openThemesFile = useCallback(() => {
|
||||
if (!themesConfigPath) return;
|
||||
setOpenThemesError(null);
|
||||
setIsOpeningThemes(true);
|
||||
const api = ensureNativeApi();
|
||||
const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);
|
||||
if (!editor) {
|
||||
setOpenThemesError("No available editors found.");
|
||||
setIsOpeningThemes(false);
|
||||
return;
|
||||
}
|
||||
void api.shell
|
||||
.openInEditor(themesConfigPath, editor)
|
||||
.catch((error) => {
|
||||
setOpenThemesError(error instanceof Error ? error.message : "Unable to open themes file.");
|
||||
})
|
||||
.finally(() => {
|
||||
setIsOpeningThemes(false);
|
||||
});
|
||||
}, [availableEditors, themesConfigPath]);
|
||||
|
||||
const addCustomModel = useCallback(
|
||||
(provider: ProviderKind) => {
|
||||
const customModelInput = customModelInputByProvider[provider];
|
||||
@@ -272,9 +360,96 @@ function SettingsRouteView() {
|
||||
})}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Active theme: <span className="font-medium text-foreground">{resolvedTheme}</span>
|
||||
</p>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">Color palette</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Built-in palettes apply instantly, and custom palettes load from{" "}
|
||||
<code>themes.json</code>.
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{palettes.filter((candidate) => candidate.source === "custom").length} custom
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="grid gap-3 sm:grid-cols-2"
|
||||
role="radiogroup"
|
||||
aria-label="Color palette"
|
||||
>
|
||||
{palettes.map((candidate) => (
|
||||
<ThemePaletteCard
|
||||
key={candidate.id}
|
||||
palette={candidate}
|
||||
resolvedTheme={resolvedTheme}
|
||||
selected={paletteId === candidate.id}
|
||||
onSelect={() => setPaletteId(candidate.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Active appearance:{" "}
|
||||
<span className="font-medium text-foreground">
|
||||
{resolvedTheme} / {palette.label}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 rounded-xl border border-border bg-background/60 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-foreground">Custom theme file</p>
|
||||
<p className="mt-1 break-all font-mono text-[11px] text-muted-foreground">
|
||||
{themesConfigPath ?? "Resolving themes path..."}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!themesConfigPath || isOpeningThemes}
|
||||
onClick={openThemesFile}
|
||||
>
|
||||
{isOpeningThemes ? "Opening..." : "Open themes.json"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Custom themes hot-reload when you save this file. Omitted tokens inherit the
|
||||
default palette for that mode.
|
||||
</p>
|
||||
|
||||
<pre className="overflow-x-auto rounded-lg border border-border bg-background px-3 py-3 text-[11px] text-muted-foreground">
|
||||
{CUSTOM_THEME_FILE_EXAMPLE}
|
||||
</pre>
|
||||
|
||||
{openThemesError ? (
|
||||
<p className="text-xs text-destructive">{openThemesError}</p>
|
||||
) : null}
|
||||
{themeIssues.length > 0 ? (
|
||||
<div className="space-y-1 rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2">
|
||||
<p className="text-xs font-medium text-destructive">
|
||||
Invalid custom theme entries
|
||||
</p>
|
||||
{themeIssues.map((issue) => (
|
||||
<p
|
||||
key={
|
||||
issue.kind === "themes.invalid-entry"
|
||||
? `${issue.kind}:${issue.index}`
|
||||
: `${issue.kind}:${issue.message}`
|
||||
}
|
||||
className="text-xs text-destructive"
|
||||
>
|
||||
{issue.kind === "themes.invalid-entry"
|
||||
? `Entry ${issue.index + 1}: ${issue.message}`
|
||||
: issue.message}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
|
||||
<div>
|
||||
@@ -516,6 +691,65 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Git</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Configure the model used for generating commit messages, PR titles, and branch
|
||||
names.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 rounded-lg border border-border bg-background px-3 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-foreground">Text generation model</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Model used for auto-generated git content.
|
||||
</p>
|
||||
</div>
|
||||
<Select
|
||||
value={settings.textGenerationModel ?? DEFAULT_GIT_TEXT_GENERATION_MODEL}
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
updateSettings({
|
||||
textGenerationModel: value,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
className="w-full shrink-0 sm:w-48"
|
||||
aria-label="Git text generation model"
|
||||
>
|
||||
<SelectValue>{selectedGitTextGenerationModelLabel}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end">
|
||||
{gitTextGenerationModelOptions.map((option) => (
|
||||
<SelectItem key={option.slug} value={option.slug}>
|
||||
{option.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{settings.textGenerationModel !== defaults.textGenerationModel ? (
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
textGenerationModel: defaults.textGenerationModel,
|
||||
})
|
||||
}
|
||||
>
|
||||
Restore default
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Threads</h2>
|
||||
|
||||
@@ -673,18 +673,18 @@ describe("deriveActiveWorkStartedAt", () => {
|
||||
});
|
||||
|
||||
describe("PROVIDER_OPTIONS", () => {
|
||||
it("advertises Claude as available while keeping Cursor as a placeholder", () => {
|
||||
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeAgent");
|
||||
it("keeps Claude Code and Cursor visible as unavailable placeholders in the stack base", () => {
|
||||
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeCode");
|
||||
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
|
||||
expect(PROVIDER_OPTIONS).toEqual([
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeAgent", label: "Claude", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code", available: false },
|
||||
{ value: "cursor", label: "Cursor", available: false },
|
||||
]);
|
||||
expect(claude).toEqual({
|
||||
value: "claudeAgent",
|
||||
label: "Claude",
|
||||
available: true,
|
||||
value: "claudeCode",
|
||||
label: "Claude Code",
|
||||
available: false,
|
||||
});
|
||||
expect(cursor).toEqual({
|
||||
value: "cursor",
|
||||
|
||||
@@ -18,7 +18,7 @@ import type {
|
||||
TurnDiffSummary,
|
||||
} from "./types";
|
||||
|
||||
export type ProviderPickerKind = ProviderKind | "cursor";
|
||||
export type ProviderPickerKind = ProviderKind | "claudeCode" | "cursor";
|
||||
|
||||
export const PROVIDER_OPTIONS: Array<{
|
||||
value: ProviderPickerKind;
|
||||
@@ -26,7 +26,7 @@ export const PROVIDER_OPTIONS: Array<{
|
||||
available: boolean;
|
||||
}> = [
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeAgent", label: "Claude", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code", available: false },
|
||||
{ value: "cursor", label: "Cursor", available: false },
|
||||
];
|
||||
|
||||
|
||||
@@ -191,7 +191,7 @@ describe("store pure functions", () => {
|
||||
});
|
||||
|
||||
describe("store read model sync", () => {
|
||||
it("preserves claude model slugs without an active session", () => {
|
||||
it("falls back to the codex default for unsupported provider models without an active session", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
@@ -201,29 +201,7 @@ describe("store read model sync", () => {
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("resolves claude aliases when session provider is claudeAgent", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
model: "sonnet",
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("claude-sonnet-4-6");
|
||||
expect(next.threads[0]?.model).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("preserves the current project order when syncing incoming read model updates", () => {
|
||||
|
||||
+11
-4
@@ -7,7 +7,8 @@ import {
|
||||
type OrchestrationSessionStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
inferProviderForModel,
|
||||
getModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
@@ -188,20 +189,26 @@ function toLegacySessionStatus(
|
||||
}
|
||||
|
||||
function toLegacyProvider(providerName: string | null): ProviderKind {
|
||||
if (providerName === "codex" || providerName === "claudeAgent") {
|
||||
if (providerName === "codex") {
|
||||
return providerName;
|
||||
}
|
||||
return "codex";
|
||||
}
|
||||
|
||||
const CODEX_MODEL_SLUGS = new Set<string>(getModelOptions("codex").map((option) => option.slug));
|
||||
|
||||
function inferProviderForThreadModel(input: {
|
||||
readonly model: string;
|
||||
readonly sessionProviderName: string | null;
|
||||
}): ProviderKind {
|
||||
if (input.sessionProviderName === "codex" || input.sessionProviderName === "claudeAgent") {
|
||||
if (input.sessionProviderName === "codex") {
|
||||
return input.sessionProviderName;
|
||||
}
|
||||
return inferProviderForModel(input.model);
|
||||
const normalizedCodex = normalizeModelSlug(input.model, "codex");
|
||||
if (normalizedCodex && CODEX_MODEL_SLUGS.has(normalizedCodex)) {
|
||||
return "codex";
|
||||
}
|
||||
return "codex";
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
|
||||
@@ -75,6 +75,17 @@ export function basenameOfPath(pathValue: string): string {
|
||||
return pathValue.slice(slashIndex + 1);
|
||||
}
|
||||
|
||||
export function inferEntryKindFromPath(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
}
|
||||
return "directory";
|
||||
}
|
||||
|
||||
function extensionCandidates(fileName: string): string[] {
|
||||
const candidates = new Set<string>();
|
||||
if (fileName.includes(".")) {
|
||||
|
||||
@@ -198,6 +198,7 @@ describe("wsNativeApi", () => {
|
||||
},
|
||||
],
|
||||
providers: defaultProviders,
|
||||
updated: ["keybindings"],
|
||||
} as const;
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, payload);
|
||||
|
||||
@@ -220,16 +221,19 @@ describe("wsNativeApi", () => {
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
|
||||
providers: defaultProviders,
|
||||
updated: ["keybindings"],
|
||||
});
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
updated: ["themes"],
|
||||
});
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
expect(listener).toHaveBeenLastCalledWith({
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
updated: ["themes"],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 1,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [], providers: [], updated: ["themes"] },
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -107,7 +107,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 1,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [], providers: [], updated: ["themes"] },
|
||||
});
|
||||
|
||||
transport.dispose();
|
||||
@@ -160,7 +160,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [], providers: [], updated: ["themes"] },
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -169,7 +169,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [], providers: [], updated: ["themes"] },
|
||||
});
|
||||
expect(warnSpy).toHaveBeenCalledTimes(2);
|
||||
expect(warnSpy).toHaveBeenNthCalledWith(
|
||||
|
||||
@@ -15,7 +15,10 @@ export default mergeConfig(
|
||||
},
|
||||
},
|
||||
test: {
|
||||
include: ["src/components/**/*.browser.tsx"],
|
||||
include: [
|
||||
"src/components/ChatView.browser.tsx",
|
||||
"src/components/KeybindingsToast.browser.tsx",
|
||||
],
|
||||
browser: {
|
||||
enabled: true,
|
||||
provider: playwright(),
|
||||
|
||||
@@ -48,7 +48,6 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.76",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
@@ -183,15 +182,13 @@
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
"packages": {
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.2.76", "", { "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-HZxvnT8ZWkzCnQygaYCA0dl8RSUzuVbxE1YG4ecy6vh4nQbTT36CxUxBy+QVdR12pPQluncC0mCOLhI2918Eaw=="],
|
||||
"@astrojs/check": ["@astrojs/check@0.9.7", "", { "dependencies": { "@astrojs/language-server": "^2.16.1", "chokidar": "^4.0.3", "kleur": "^4.1.5", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": "^5.0.0" }, "bin": { "astro-check": "bin/astro-check.js" } }, "sha512-dA7U5/OFg8/xaMUb2vUOOJuuJXnMpHy6F0BM8ZhL7WT5OkTBwJ0GoW38n4fC4CXt+lT9mLWL0y8Pa74tFByBpQ=="],
|
||||
|
||||
"@astrojs/check": ["@astrojs/[email protected]", "", { "dependencies": { "@astrojs/language-server": "^2.16.5", "chokidar": "^4.0.3", "kleur": "^4.1.5", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": "^5.0.0" }, "bin": { "astro-check": "bin/astro-check.js" } }, "sha512-LDng8446QLS5ToKjRHd3bgUdirvemVVExV7nRyJfW2wV36xuv7vDxwy5NWN9zqeSEDgg0Tv84sP+T3yEq+Zlkw=="],
|
||||
|
||||
"@astrojs/compiler": ["@astrojs/[email protected]", "", {}, "sha512-z97oYbdebO5aoWzuJ/8q5hLK232+17KcLZ7cJ8BCWk6+qNzVxn/gftC0KzMBUTD8WAaBkPpNSQK6PXLnNrZ0CA=="],
|
||||
"@astrojs/compiler": ["@astrojs/compiler@3.0.0", "", {}, "sha512-MwAbDE5mawZ1SS+D8qWiHdprdME5Tlj2e0YjxnEICvcOpbSukNS7Sa7hA5PK+6RrmUr/t6Gi5YgrdZKjbO/WPQ=="],
|
||||
|
||||
"@astrojs/internal-helpers": ["@astrojs/[email protected]", "", { "dependencies": { "picomatch": "^4.0.3" } }, "sha512-J56GrhEiV+4dmrGLPNOl2pZjpHXAndWVyiVDYGDuw6MWKpBSEMLdFxHzeM/6sqaknw9M+HFfHZAcvi3OfT3D/w=="],
|
||||
|
||||
"@astrojs/language-server": ["@astrojs/[email protected].5", "", { "dependencies": { "@astrojs/compiler": "^2.13.1", "@astrojs/yaml2ts": "^0.2.3", "@jridgewell/sourcemap-codec": "^1.5.5", "@volar/kit": "~2.4.28", "@volar/language-core": "~2.4.28", "@volar/language-server": "~2.4.28", "@volar/language-service": "~2.4.28", "muggle-string": "^0.4.1", "tinyglobby": "^0.2.15", "volar-service-css": "0.0.70", "volar-service-emmet": "0.0.70", "volar-service-html": "0.0.70", "volar-service-prettier": "0.0.70", "volar-service-typescript": "0.0.70", "volar-service-typescript-twoslash-queries": "0.0.70", "volar-service-yaml": "0.0.70", "vscode-html-languageservice": "^5.6.2", "vscode-uri": "^3.1.0" }, "peerDependencies": { "prettier": "^3.0.0", "prettier-plugin-astro": ">=0.11.0" }, "optionalPeers": ["prettier", "prettier-plugin-astro"], "bin": { "astro-ls": "bin/nodeServer.js" } }, "sha512-MEQvrbuiFDEo+LCO4vvYuTr3eZ4IluZ/n4BbUv77AWAJNEj/n0j7VqTvdL1rGloNTIKZTUd46p5RwYKsxQGY8w=="],
|
||||
"@astrojs/language-server": ["@astrojs/[email protected].4", "", { "dependencies": { "@astrojs/compiler": "^2.13.1", "@astrojs/yaml2ts": "^0.2.3", "@jridgewell/sourcemap-codec": "^1.5.5", "@volar/kit": "~2.4.28", "@volar/language-core": "~2.4.28", "@volar/language-server": "~2.4.28", "@volar/language-service": "~2.4.28", "muggle-string": "^0.4.1", "tinyglobby": "^0.2.15", "volar-service-css": "0.0.68", "volar-service-emmet": "0.0.68", "volar-service-html": "0.0.68", "volar-service-prettier": "0.0.68", "volar-service-typescript": "0.0.68", "volar-service-typescript-twoslash-queries": "0.0.68", "volar-service-yaml": "0.0.68", "vscode-html-languageservice": "^5.6.1", "vscode-uri": "^3.1.0" }, "peerDependencies": { "prettier": "^3.0.0", "prettier-plugin-astro": ">=0.11.0" }, "optionalPeers": ["prettier", "prettier-plugin-astro"], "bin": { "astro-ls": "bin/nodeServer.js" } }, "sha512-42oqz9uX+hU1/rFniJvtYW9FbfZJ6syM2fYZFi7Ub71/kOvF1GSeMS8sA3Ogs3iOeNUWefk/ImwBiiHeNmJfSA=="],
|
||||
|
||||
"@astrojs/markdown-remark": ["@astrojs/[email protected]", "", { "dependencies": { "@astrojs/internal-helpers": "0.8.0", "@astrojs/prism": "4.0.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "js-yaml": "^4.1.1", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", "remark-smartypants": "^3.0.2", "shiki": "^4.0.0", "smol-toml": "^1.6.0", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.1.0", "unist-util-visit-parents": "^6.0.2", "vfile": "^6.0.3" } }, "sha512-jTAXHPy45L7o1ljH4jYV+ShtOHtyQUa1mGp3a5fJp1soX8lInuTJQ6ihmldHzVM4Q7QptU4SzIDIcKbBJO7sXQ=="],
|
||||
|
||||
@@ -551,45 +548,45 @@
|
||||
|
||||
"@oxfmt/binding-win32-x64-msvc": ["@oxfmt/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-/Zmj0yTYSvmha6TG1QnoLqVT7ZMRDqXvFXXBQpIjteEwx9qvUYMBH2xbiOFhDeMUJkGwC3D6fdKsFtaqUvkwNA=="],
|
||||
|
||||
"@oxlint/binding-android-arm-eabi": ["@oxlint/[email protected]6.0", "", { "os": "android", "cpu": "arm" }, "sha512-IyfYPthZyiSKwAv/dLjeO18SaK8MxLI9Yss2JrRDyweQAkuL3LhEy7pwIwI7uA3KQc1Vdn20kdmj3q0oUIQL6A=="],
|
||||
"@oxlint/binding-android-arm-eabi": ["@oxlint/[email protected]5.0", "", { "os": "android", "cpu": "arm" }, "sha512-NhvgAhncTSOhRahQSCnkK/4YIGPjTmhPurQQ2dwt2IvwCMTvZRW5vF2K10UBOxFve4GZDMw6LtXZdC2qeuYIVQ=="],
|
||||
|
||||
"@oxlint/binding-android-arm64": ["@oxlint/[email protected]6.0", "", { "os": "android", "cpu": "arm64" }, "sha512-Ga5zYrzH6vc/VFxhn6MmyUnYEfy9vRpwTIks99mY3j6Nz30yYpIkWryI0QKPCgvGUtDSXVLEaMum5nA+WrNOSg=="],
|
||||
"@oxlint/binding-android-arm64": ["@oxlint/[email protected]5.0", "", { "os": "android", "cpu": "arm64" }, "sha512-P9iWRh+Ugqhg+D7rkc7boHX8o3H2h7YPcZHQIgvVBgnua5tk4LR2L+IBlreZs58/95cd2x3/004p5VsQM9z4SA=="],
|
||||
|
||||
"@oxlint/binding-darwin-arm64": ["@oxlint/[email protected]6.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ogmbdJysnw/D4bDcpf1sPLpFThZ48lYp4aKYm10Z/6Nh1SON6NtnNhTNOlhEY296tDFItsZUz+2tgcSYqh8Eyw=="],
|
||||
"@oxlint/binding-darwin-arm64": ["@oxlint/[email protected]5.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-esakkJIt7WFAhT30P/Qzn96ehFpzdZ1mNuzpOb8SCW7lI4oB8VsyQnkSHREM671jfpuBb/o2ppzBCx5l0jpgMA=="],
|
||||
|
||||
"@oxlint/binding-darwin-x64": ["@oxlint/[email protected]6.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-x8QE1h+RAtQ2g+3KPsP6Fk/tdz6zJQUv5c7fTrJxXV3GHOo+Ry5p/PsogU4U+iUZg0rj6hS+E4xi+mnwwlDCWQ=="],
|
||||
"@oxlint/binding-darwin-x64": ["@oxlint/[email protected]5.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-xDMFRCCAEK9fOH6As2z8ELsC+VDGSFRHwIKVSilw+xhgLwTDFu37rtmRbmUlx8rRGS6cWKQPTc47AVxAZEVVPQ=="],
|
||||
|
||||
"@oxlint/binding-freebsd-x64": ["@oxlint/[email protected]6.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-6G+WMZvwJpMvY7my+/SHEjb7BTk/PFbePqLpmVmUJRIsJMy/UlyYqjpuh0RCgYYkPLcnXm1rUM04kbTk8yS1Yg=="],
|
||||
"@oxlint/binding-freebsd-x64": ["@oxlint/[email protected]5.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-mYZqnwUD7ALCRxGenyLd1uuG+rHCL+OTT6S8FcAbVm/ZT2AZMGjvibp3F6k1SKOb2aeqFATmwRykrE41Q0GWVw=="],
|
||||
|
||||
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "arm" }, "sha512-YYHBsk/sl7fYwQOok+6W5lBPeUEvisznV/HZD2IfZmF3Bns6cPC3Z0vCtSEOaAWTjYWN3jVsdu55jMxKlsdlhg=="],
|
||||
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "arm" }, "sha512-LcX6RYcF9vL9ESGwJW3yyIZ/d/ouzdOKXxCdey1q0XJOW1asrHsIg5MmyKdEBR4plQx+shvYeQne7AzW5f3T1w=="],
|
||||
|
||||
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "arm" }, "sha512-+AZK8rOUr78y8WT6XkDb04IbMRqauNV+vgT6f8ZLOH8wnpQ9i7Nol0XLxAu+Cq7Sb+J9wC0j6Km5hG8rj47/yQ=="],
|
||||
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "arm" }, "sha512-C+8GS1rPtK+dI7mJFkqoRBkDuqbrNihnyYQsJPS9ez+8zF9JzfvU19lawqt4l/Y23o5uQswE/DORa8aiXUih3w=="],
|
||||
|
||||
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-urse2SnugwJRojUkGSSeH2LPMaje5Q50yQtvtL9HFckiyeqXzoFwOAZqD5TR29R2lq7UHidfFDM9EGcchcbb8A=="],
|
||||
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-ErLE4XbmcCopA4/CIDiH6J1IAaDOMnf/KSx/aFObs4/OjAAM3sFKWGZ57pNOMxhhyBdcmcXwYymph9GwcpcqgQ=="],
|
||||
|
||||
"@oxlint/binding-linux-arm64-musl": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-rkTZkBfJ4TYLjansjSzL6mgZOdN5IvUnSq3oNJSLwBcNvy3dlgQtpHPrRxrCEbbcp7oQ6If0tkNaqfOsphYZ9g=="],
|
||||
"@oxlint/binding-linux-arm64-musl": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-/kp65avi6zZfqEng56TTuhiy3P/3pgklKIdf38yvYeJ9/PgEeRA2A2AqKAKbZBNAqUzrzHhz9jF6j/PZvhJzTQ=="],
|
||||
|
||||
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-uqL1kMH3u69/e1CH2EJhP3CP28jw2ExLsku4o8RVAZ7fySo9zOyI2fy9pVlTAp4voBLVgzndXi3SgtdyCTa2aA=="],
|
||||
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-A6pTdXwcEEwL/nmz0eUJ6WxmxcoIS+97GbH96gikAyre3s5deC7sts38ZVVowjS2QQFuSWkpA4ZmQC0jZSNvJQ=="],
|
||||
|
||||
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "none" }, "sha512-j0CcMBOgV6KsRaBdsebIeiy7hCjEvq2KdEsiULf2LZqAq0v1M1lWjelhCV57LxsqaIGChXFuFJ0RiFrSRHPhSg=="],
|
||||
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "none" }, "sha512-clj0lnIN+V52G9tdtZl0LbdTSurnZ1NZj92Je5X4lC7gP5jiCSW+Y/oiDiSauBAD4wrHt2S7nN3pA0zfKYK/6Q=="],
|
||||
|
||||
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "none" }, "sha512-7VDOiL8cDG3DQ/CY3yKjbV1c4YPvc4vH8qW09Vv+5ukq3l/Kcyr6XGCd5NvxUmxqDb2vjMpM+eW/4JrEEsUetA=="],
|
||||
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "none" }, "sha512-NNu08pllN5x/O94/sgR3DA8lbrGBnTHsINZZR0hcav1sj79ksTiKKm1mRzvZvacwQ0hUnGinFo+JO75ok2PxYg=="],
|
||||
|
||||
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-JGRpX0M+ikD3WpwJ7vKcHKV6Kg0dT52BW2Eu2BupXotYeqGXBrbY+QPkAyKO6MNgKozyTNaRh3r7g+VWgyAQYQ=="],
|
||||
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-BvfQz3PRlWZRoEZ17dZCqgQsMRdpzGZomJkVATwCIGhHVVeHJMQdmdXPSjcT1DCNUrOjXnVyj1RGDj5+/Je2+Q=="],
|
||||
|
||||
"@oxlint/binding-linux-x64-gnu": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "x64" }, "sha512-dNaICPvtmuxFP/VbqdofrLqdS3bM/AKJN3LMJD52si44ea7Be1cBk6NpfIahaysG9Uo+L98QKddU9CD5L8UHnQ=="],
|
||||
"@oxlint/binding-linux-x64-gnu": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ngSOoFCSBMKVQd24H8zkbcBNc7EHhjnF1sv3mC9NNXQ/4rRjI/4Dj9+9XoDZeFEkF1SX1COSBXF1b2Pr9rqdEw=="],
|
||||
|
||||
"@oxlint/binding-linux-x64-musl": ["@oxlint/[email protected]6.0", "", { "os": "linux", "cpu": "x64" }, "sha512-pF1vOtM+GuXmbklM1hV8WMsn6tCNPvkUzklj/Ej98JhlanbmA2RB1BILgOpwSuCTRTIYx2MXssmEyQQ90QF5aA=="],
|
||||
"@oxlint/binding-linux-x64-musl": ["@oxlint/[email protected]5.0", "", { "os": "linux", "cpu": "x64" }, "sha512-BDpP7W8GlaG7BR6QjGZAleYzxoyKc/D24spZIF2mB3XsfALQJJT/OBmP8YpeTb1rveFSBHzl8T7l0aqwkWNdGA=="],
|
||||
|
||||
"@oxlint/binding-openharmony-arm64": ["@oxlint/[email protected]6.0", "", { "os": "none", "cpu": "arm64" }, "sha512-bp8NQ4RE6fDIFLa4bdBiOA+TAvkNkg+rslR+AvvjlLTYXLy9/uKAYLQudaQouWihLD/hgkrXIKKzXi5IXOewwg=="],
|
||||
"@oxlint/binding-openharmony-arm64": ["@oxlint/[email protected]5.0", "", { "os": "none", "cpu": "arm64" }, "sha512-PS6GFvmde/pc3fCA2Srt51glr8Lcxhpf6WIBFfLphndjRrD34NEcses4TSxQrEcxYo6qVywGfylM0ZhSCF2gGA=="],
|
||||
|
||||
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/[email protected]6.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-PxT4OJDfMOQBzo3OlzFb9gkoSD+n8qSBxyVq2wQSZIHFQYGEqIRTo9M0ZStvZm5fdhMqaVYpOnJvH2hUMEDk/g=="],
|
||||
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/[email protected]5.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-P6JcLJGs/q1UOvDLzN8otd9JsH4tsuuPDv+p7aHqHM3PrKmYdmUvkNj4K327PTd35AYcznOCN+l4ZOaq76QzSw=="],
|
||||
|
||||
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/[email protected]6.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-PTRy6sIEPqy2x8PTP1baBNReN/BNEFmde0L+mYeHmjXE1Vlcc9+I5nsqENsB2yAm5wLkzPoTNCMY/7AnabT4/A=="],
|
||||
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/[email protected]5.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-gzkk4zE2zsE+WmRxFOiAZHpCpUNDFytEakqNXoNHW+PnYEOTPKDdW6nrzgSeTbGKVPXNAKQnRnMgrh7+n3Xueg=="],
|
||||
|
||||
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]6.0", "", { "os": "win32", "cpu": "x64" }, "sha512-ZHa0clocjLmIDr+1LwoWtxRcoYniAvERotvwKUYKhH41NVfl0Y4LNbyQkwMZzwDvKklKGvGZ5+DAG58/Ik47tQ=="],
|
||||
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]5.0", "", { "os": "win32", "cpu": "x64" }, "sha512-ZFALNow2/og75gvYzNP7qe+rREQ5xunktwA+lgykoozHZ6hw9bqg4fn5j2UvG4gIn1FXqrZHkOAXuPf5+GOYTQ=="],
|
||||
|
||||
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@pierre/theme": "0.0.22", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-wbxrzcmanJuHZb81iir09j42uU9AnKxXDtAuEQJbAnti5f2UfYdCQYejawuHZStFrlsMacCZLh/dDHmqvAaQCw=="],
|
||||
"@pierre/diffs": ["@pierre/[email protected]-beta.19", "", { "dependencies": { "@pierre/theme": "0.0.22", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-XxGPKkVW+1t2KJQfgjmSnS+93nI9+ACJl1XjhF3Lo4BdQJOxV3pHeyix31ySn/m/1llq6O/7bXucE0OYCK6Kog=="],
|
||||
|
||||
"@pierre/theme": ["@pierre/[email protected]", "", {}, "sha512-ePUIdQRNGjrveELTU7fY89Xa7YGHHEy5Po5jQy/18lm32eRn96+tnYJEtFooGdffrx55KBUtOXfvVy/7LDFFhA=="],
|
||||
|
||||
@@ -629,7 +626,7 @@
|
||||
|
||||
"@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-a4VUQZH7LxGbUJ3qJ/TzQG8HxdHvf+jOnqf7B7oFx1TEBm+j2KNL2zr5SQ7wHkNAcaPevF6gf9tQnVBnC4mD+A=="],
|
||||
|
||||
"@rolldown/plugin-babel": ["@rolldown/[email protected].1", "", { "dependencies": { "picomatch": "^4.0.3" }, "peerDependencies": { "@babel/core": "^7.29.0 || ^8.0.0-rc.1", "@babel/plugin-transform-runtime": "^7.29.0 || ^8.0.0-rc.1", "@babel/runtime": "^7.27.0 || ^8.0.0-rc.1", "rolldown": "^1.0.0-rc.5", "vite": "^8.0.0" }, "optionalPeers": ["@babel/plugin-transform-runtime", "@babel/runtime", "vite"] }, "sha512-pHDVHqFv26JNC8I500JZ0H4h1kvSyiE3V9gjEO9pRAgD1KrIdJvcHCokV6f7gG7Rx4vMOD11V8VUOpqdyGbKBw=="],
|
||||
"@rolldown/plugin-babel": ["@rolldown/[email protected].0", "", { "dependencies": { "picomatch": "^4.0.3" }, "peerDependencies": { "@babel/core": "^7.29.0 || ^8.0.0-rc.1", "@babel/plugin-transform-runtime": "^7.29.0 || ^8.0.0-rc.1", "@babel/runtime": "^7.27.0 || ^8.0.0-rc.1", "rolldown": "^1.0.0-rc.5", "vite": "^8.0.0" }, "optionalPeers": ["@babel/plugin-transform-runtime", "@babel/runtime", "vite"] }, "sha512-ZkajPtfcBTfLSZTmm40k2E0cwT5HDosBcj71fdUURXl7FfETb50jEbV39ujPw2RFp3ZpOugK3ATdX+HuFfWr9Q=="],
|
||||
|
||||
"@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA=="],
|
||||
|
||||
@@ -703,7 +700,7 @@
|
||||
|
||||
"@tanstack/devtools-event-client": ["@tanstack/[email protected]", "", { "bin": { "intent": "bin/intent.js" } }, "sha512-OZI6QyULw0FI0wjgmeYzCIfbgPsOEzwJtCpa69XrfLMtNXLGnz3d/dIabk7frg0TmHo+Ah49w5I4KC7Tufwsvw=="],
|
||||
|
||||
"@tanstack/history": ["@tanstack/[email protected].6", "", {}, "sha512-NaOGLRrddszbQj9upGat6HG/4TKvXLvu+osAIgfxPYA+eIvYKv8GKDJOrY2D3/U9MRnKfMWD7bU4jeD4xmqyIg=="],
|
||||
"@tanstack/history": ["@tanstack/[email protected].4", "", {}, "sha512-Kp/WSt411ZWYvgXy6uiv5RmhHrz9cAml05AQPrtdAp7eUqvIDbMGPnML25OKbzR3RJ1q4wgENxDTvlGPa9+Mww=="],
|
||||
|
||||
"@tanstack/pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.0", "@tanstack/store": "^0.8.0" } }, "sha512-qhCRSFei0hokQr3xYcQXqxsRD/LKlgHCxHXtKHrQoImp4x2Zu6tUOpUGVH4y2qexIrzSu3aibQBNNfC3Eay6Mg=="],
|
||||
|
||||
@@ -713,25 +710,25 @@
|
||||
|
||||
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
|
||||
|
||||
"@tanstack/react-router": ["@tanstack/[email protected]7.3", "", { "dependencies": { "@tanstack/history": "1.161.6", "@tanstack/react-store": "^0.9.1", "@tanstack/router-core": "1.167.3", "isbot": "^5.1.22", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-1qbSy4r+O7IBdmPLlcKsjB041Gq2MMnIEAYSGIjaMZIL4duUIQnOWLw4jTfjKil/IJz/9rO5JcvrbxOG5UTSdg=="],
|
||||
"@tanstack/react-router": ["@tanstack/[email protected]6.7", "", { "dependencies": { "@tanstack/history": "1.161.4", "@tanstack/react-store": "^0.9.1", "@tanstack/router-core": "1.166.7", "isbot": "^5.1.22", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-LLcXu2nrCn2WL+w0YAbg3CRZIIO2cYVSC3y+ZYlFBxBs4hh8eoNP1EWFvRLZGCFYpqON7x6qUf1u0W7tH0cJJw=="],
|
||||
|
||||
"@tanstack/react-store": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "0.8.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-XItJt+rG8c5Wn/2L/bnxys85rBpm0BfMbhb4zmPVLXAKY9POrp1xd6IbU4PKoOI+jSEGc3vntPRfLGSgXfE2Ig=="],
|
||||
|
||||
"@tanstack/react-virtual": ["@tanstack/[email protected]3", "", { "dependencies": { "@tanstack/virtual-core": "3.13.23" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-XnMRnHQ23piOVj2bzJqHrRrLg4r+F86fuBcwteKfbIjJrtGxb4z7tIvPVAe4B+4UVwo9G4Giuz5fmapcrnZ0OQ=="],
|
||||
"@tanstack/react-virtual": ["@tanstack/[email protected]2", "", { "dependencies": { "@tanstack/virtual-core": "3.13.22" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-EaOrBBJLi3M0bTMQRjGkxLXRw7Gizwntoy5E2Q2UnSbML7Mo2a1P/Hfkw5tw9FLzK62bj34Jl6VNbQfRV6eJcA=="],
|
||||
|
||||
"@tanstack/router-core": ["@tanstack/[email protected]7.3", "", { "dependencies": { "@tanstack/history": "1.161.6", "@tanstack/store": "^0.9.1", "cookie-es": "^2.0.0", "seroval": "^1.4.2", "seroval-plugins": "^1.4.2", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" } }, "sha512-M/CxrTGKk1fsySJjd+Pzpbi3YLDz+cJSutDjSTMy12owWlOgHV/I6kzR0UxyaBlHraM6XgMHNA0XdgsS1fa4Nw=="],
|
||||
"@tanstack/router-core": ["@tanstack/[email protected]6.7", "", { "dependencies": { "@tanstack/history": "1.161.4", "@tanstack/store": "^0.9.1", "cookie-es": "^2.0.0", "seroval": "^1.4.2", "seroval-plugins": "^1.4.2", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" } }, "sha512-MCc8wYIIcxmbeidM8PL2QeaAjUIHyhEDIZPW6NGfn/uwvyi+K2ucn3AGCxxcXl4JGGm0Mx9+7buYl1v3HdcFrg=="],
|
||||
|
||||
"@tanstack/router-generator": ["@tanstack/[email protected].11", "", { "dependencies": { "@tanstack/router-core": "1.167.3", "@tanstack/router-utils": "1.161.6", "@tanstack/virtual-file-routes": "1.161.6", "prettier": "^3.5.0", "recast": "^0.23.11", "source-map": "^0.7.4", "tsx": "^4.19.2", "zod": "^3.24.2" } }, "sha512-Q/49wxURbft1oNOvo/eVAWZq/lNLK3nBGlavqhLToAYXY6LCzfMtRlE/y3XPHzYC9pZc09u5jvBR1k1E4hyGDQ=="],
|
||||
"@tanstack/router-generator": ["@tanstack/[email protected].7", "", { "dependencies": { "@tanstack/router-core": "1.166.7", "@tanstack/router-utils": "1.161.4", "@tanstack/virtual-file-routes": "1.161.4", "prettier": "^3.5.0", "recast": "^0.23.11", "source-map": "^0.7.4", "tsx": "^4.19.2", "zod": "^3.24.2" } }, "sha512-lBI0VS7J1zMrJhfvT+3FMq9jPdOrJ3VgciPXyYvZBF/a9Mr8T94MU78PqrBNuJbYh7qCFO14ZhArUFqkYGuozQ=="],
|
||||
|
||||
"@tanstack/router-plugin": ["@tanstack/[email protected].12", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-syntax-typescript": "^7.27.1", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.5", "@babel/types": "^7.28.5", "@tanstack/router-core": "1.167.3", "@tanstack/router-generator": "1.166.11", "@tanstack/router-utils": "1.161.6", "@tanstack/virtual-file-routes": "1.161.6", "chokidar": "^3.6.0", "unplugin": "^2.1.2", "zod": "^3.24.2" }, "peerDependencies": { "@rsbuild/core": ">=1.0.2", "@tanstack/react-router": "^1.167.3", "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0", "vite-plugin-solid": "^2.11.10", "webpack": ">=5.92.0" }, "optionalPeers": ["@rsbuild/core", "@tanstack/react-router", "vite", "vite-plugin-solid", "webpack"] }, "sha512-PYsnN6goK6zBaVo63UVKjofv69+HHMKRQXymwN55JYKguNnNR8OZ6E12icPb0Olc5uIpPiGz1YI2+rbpmNKGHA=="],
|
||||
"@tanstack/router-plugin": ["@tanstack/[email protected].7", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-syntax-typescript": "^7.27.1", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.5", "@babel/types": "^7.28.5", "@tanstack/router-core": "1.166.7", "@tanstack/router-generator": "1.166.7", "@tanstack/router-utils": "1.161.4", "@tanstack/virtual-file-routes": "1.161.4", "chokidar": "^3.6.0", "unplugin": "^2.1.2", "zod": "^3.24.2" }, "peerDependencies": { "@rsbuild/core": ">=1.0.2", "@tanstack/react-router": "^1.166.7", "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0", "vite-plugin-solid": "^2.11.10", "webpack": ">=5.92.0" }, "optionalPeers": ["@rsbuild/core", "@tanstack/react-router", "vite", "vite-plugin-solid", "webpack"] }, "sha512-R06qe5UwApb/u02wDITVxN++6QE4xsLFQCr029VZ+4V8gyIe35kr8UCg3Jiyl6D5GXxhj62U2Ei8jccdkQaivw=="],
|
||||
|
||||
"@tanstack/router-utils": ["@tanstack/[email protected].6", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/generator": "^7.28.5", "@babel/parser": "^7.28.5", "@babel/types": "^7.28.5", "ansis": "^4.1.0", "babel-dead-code-elimination": "^1.0.12", "diff": "^8.0.2", "pathe": "^2.0.3", "tinyglobby": "^0.2.15" } }, "sha512-nRcYw+w2OEgK6VfjirYvGyPLOK+tZQz1jkYcmH5AjMamQ9PycnlxZF2aEZtPpNoUsaceX2bHptn6Ub5hGXqNvw=="],
|
||||
"@tanstack/router-utils": ["@tanstack/[email protected].4", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/generator": "^7.28.5", "@babel/parser": "^7.28.5", "@babel/types": "^7.28.5", "ansis": "^4.1.0", "babel-dead-code-elimination": "^1.0.12", "diff": "^8.0.2", "pathe": "^2.0.3", "tinyglobby": "^0.2.15" } }, "sha512-r8TpjyIZoqrXXaf2DDyjd44gjGBoyE+/oEaaH68yLI9ySPO1gUWmQENZ1MZnmBnpUGN24NOZxdjDLc8npK0SAw=="],
|
||||
|
||||
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-K013lUJEFJK2ofFQ/hZKJUmCnpcV00ebLyOyFOWQvyQHUOZp/iYO84BM6aOGiV81JzwbX0APTVmW8YI7yiG5oA=="],
|
||||
|
||||
"@tanstack/virtual-core": ["@tanstack/[email protected]3", "", {}, "sha512-zSz2Z2HNyLjCplANTDyl3BcdQJc2k1+yyFoKhNRmCr7V7dY8o8q5m8uFTI1/Pg1kL+Hgrz6u3Xo6eFUB7l66cg=="],
|
||||
"@tanstack/virtual-core": ["@tanstack/[email protected]2", "", {}, "sha512-isuUGKsc5TAPDoHSbWTbl1SCil54zOS2MiWz/9GCWHPUQOvNTQx8qJEWC7UWR0lShhbK0Lmkcf0SZYxvch7G3g=="],
|
||||
|
||||
"@tanstack/virtual-file-routes": ["@tanstack/[email protected].6", "", {}, "sha512-EGWs9yvJA821pUkwkiZLQW89CzUumHyJy8NKq229BubyoWXfDw1oWnTJYSS/hhbLiwP9+KpopjeF5wWwnCCyeQ=="],
|
||||
"@tanstack/virtual-file-routes": ["@tanstack/[email protected].4", "", {}, "sha512-42WoRePf8v690qG8yGRe/YOh+oHni9vUaUUfoqlS91U2scd3a5rkLtVsc6b7z60w3RogH0I00vdrC5AaeiZ18w=="],
|
||||
|
||||
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
|
||||
|
||||
@@ -789,7 +786,7 @@
|
||||
|
||||
"@ungap/structured-clone": ["@ungap/[email protected]", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="],
|
||||
|
||||
"@vitejs/plugin-react": ["@vitejs/[email protected].1", "", { "dependencies": { "@rolldown/pluginutils": "1.0.0-rc.7" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ=="],
|
||||
"@vitejs/plugin-react": ["@vitejs/[email protected].0", "", { "dependencies": { "@rolldown/pluginutils": "1.0.0-rc.7" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-Bu5/eP6td3WI654+tRq+ryW1PbgA90y5pqMKpb3U7UpNk6VjI53P/ncPUd192U9dSrepLy7DHnq1XEMDz5H++w=="],
|
||||
|
||||
"@vitest/browser": ["@vitest/[email protected]", "", { "dependencies": { "@blazediff/core": "1.9.1", "@vitest/mocker": "4.1.0", "@vitest/utils": "4.1.0", "magic-string": "^0.30.21", "pngjs": "^7.0.0", "sirv": "^3.0.2", "tinyrainbow": "^3.0.3", "ws": "^8.19.0" }, "peerDependencies": { "vitest": "4.1.0" } }, "sha512-tG/iOrgbiHQks0ew7CdelUyNEHkv8NLrt+CqdTivIuoSnXvO7scWMn4Kqo78/UGY1NJ6Hv+vp8BvRnED/bjFdQ=="],
|
||||
|
||||
@@ -855,7 +852,7 @@
|
||||
|
||||
"ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="],
|
||||
|
||||
"astro": ["[email protected].5", "", { "dependencies": { "@astrojs/compiler": "^3.0.0", "@astrojs/internal-helpers": "0.8.0", "@astrojs/markdown-remark": "7.0.0", "@astrojs/telemetry": "3.3.0", "@capsizecss/unpack": "^4.0.0", "@clack/prompts": "^1.0.1", "@oslojs/encoding": "^1.1.0", "@rollup/pluginutils": "^5.3.0", "aria-query": "^5.3.2", "axobject-query": "^4.1.0", "ci-info": "^4.4.0", "clsx": "^2.1.1", "common-ancestor-path": "^2.0.0", "cookie": "^1.1.1", "devalue": "^5.6.3", "diff": "^8.0.3", "dlv": "^1.1.3", "dset": "^3.1.4", "es-module-lexer": "^2.0.0", "esbuild": "^0.27.3", "flattie": "^1.1.1", "fontace": "~0.4.1", "github-slugger": "^2.0.0", "html-escaper": "3.0.3", "http-cache-semantics": "^4.2.0", "js-yaml": "^4.1.1", "magic-string": "^0.30.21", "magicast": "^0.5.2", "mrmime": "^2.0.1", "neotraverse": "^0.6.18", "obug": "^2.1.1", "p-limit": "^7.3.0", "p-queue": "^9.1.0", "package-manager-detector": "^1.6.0", "piccolore": "^0.1.3", "picomatch": "^4.0.3", "rehype": "^13.0.2", "semver": "^7.7.4", "shiki": "^4.0.0", "smol-toml": "^1.6.0", "svgo": "^4.0.0", "tinyclip": "^0.1.6", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tsconfck": "^3.1.6", "ultrahtml": "^1.6.0", "unifont": "~0.7.4", "unist-util-visit": "^5.1.0", "unstorage": "^1.17.4", "vfile": "^6.0.3", "vite": "^7.3.1", "vitefu": "^1.1.2", "xxhash-wasm": "^1.1.0", "yargs-parser": "^22.0.0", "zod": "^4.3.6" }, "optionalDependencies": { "sharp": "^0.34.0" }, "bin": { "astro": "bin/astro.mjs" } }, "sha512-JnLCwaoCaRXIHuIB8yNztJrd7M3hXrHUMAoQmeXtEBKxRu/738REhaCZ1lapjrS9HlpHsWTu3JUXTERB/0PA7g=="],
|
||||
"astro": ["[email protected].4", "", { "dependencies": { "@astrojs/compiler": "^3.0.0", "@astrojs/internal-helpers": "0.8.0", "@astrojs/markdown-remark": "7.0.0", "@astrojs/telemetry": "3.3.0", "@capsizecss/unpack": "^4.0.0", "@clack/prompts": "^1.0.1", "@oslojs/encoding": "^1.1.0", "@rollup/pluginutils": "^5.3.0", "aria-query": "^5.3.2", "axobject-query": "^4.1.0", "ci-info": "^4.4.0", "clsx": "^2.1.1", "common-ancestor-path": "^2.0.0", "cookie": "^1.1.1", "devalue": "^5.6.3", "diff": "^8.0.3", "dlv": "^1.1.3", "dset": "^3.1.4", "es-module-lexer": "^2.0.0", "esbuild": "^0.27.3", "flattie": "^1.1.1", "fontace": "~0.4.1", "github-slugger": "^2.0.0", "html-escaper": "3.0.3", "http-cache-semantics": "^4.2.0", "js-yaml": "^4.1.1", "magic-string": "^0.30.21", "magicast": "^0.5.2", "mrmime": "^2.0.1", "neotraverse": "^0.6.18", "obug": "^2.1.1", "p-limit": "^7.3.0", "p-queue": "^9.1.0", "package-manager-detector": "^1.6.0", "piccolore": "^0.1.3", "picomatch": "^4.0.3", "rehype": "^13.0.2", "semver": "^7.7.4", "shiki": "^4.0.0", "smol-toml": "^1.6.0", "svgo": "^4.0.0", "tinyclip": "^0.1.6", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tsconfck": "^3.1.6", "ultrahtml": "^1.6.0", "unifont": "~0.7.4", "unist-util-visit": "^5.1.0", "unstorage": "^1.17.4", "vfile": "^6.0.3", "vite": "^7.3.1", "vitefu": "^1.1.2", "xxhash-wasm": "^1.1.0", "yargs-parser": "^22.0.0", "zod": "^4.3.6" }, "optionalDependencies": { "sharp": "^0.34.0" }, "bin": { "astro": "bin/astro.mjs" } }, "sha512-1piLJCPTL/x7AMO2cjVFSTFyRqKuC3W8sSEySCt1aJio+p/wGs5H3K+Xr/rE9ftKtknLUtjxCqCE7/0NsXfGpQ=="],
|
||||
|
||||
"asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],
|
||||
|
||||
@@ -869,7 +866,7 @@
|
||||
|
||||
"bail": ["[email protected]", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
"baseline-browser-mapping": ["[email protected].8", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-PCLz/LXGBsNTErbtB6i5u4eLpHeMfi93aUv5duMmj6caNu6IphS4q6UevDnL36sZQv9lrP11dbPKGMaXPwMKfQ=="],
|
||||
"baseline-browser-mapping": ["[email protected].7", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-1ghYO3HnxGec0TCGBXiDLVns4eCSx4zJpxnHrlqFQajmhfKMQBzUGDdkMK7fUW7PTHTeLf+j87aTuKuuwWzMGw=="],
|
||||
|
||||
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
|
||||
|
||||
@@ -899,7 +896,7 @@
|
||||
|
||||
"call-bind-apply-helpers": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
|
||||
|
||||
"caniuse-lite": ["[email protected]9", "", {}, "sha512-U5og2PN7V4DMgF50YPNtnZJGWVLFjjsN3zb6uMT5VGYIewieDj1upwfuVNXf4Kor+89c3iCRJnSzMD5LmTvsfA=="],
|
||||
"caniuse-lite": ["[email protected]8", "", {}, "sha512-PN7uxFL+ExFJO61aVmP1aIEG4i9whQd4eoSCebav62UwDyp5OHh06zN4jqKSMePVgxHifCw1QJxdRkA1Pisekg=="],
|
||||
|
||||
"ccount": ["[email protected]", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
|
||||
|
||||
@@ -1159,7 +1156,7 @@
|
||||
|
||||
"headers-polyfill": ["[email protected]", "", {}, "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ=="],
|
||||
|
||||
"hookable": ["hookable@6.1.0", "", {}, "sha512-ZoKZSJgu8voGK2geJS+6YtYjvIzu9AOM/KZXsBxr83uhLL++e9pEv/dlgwgy3dvHg06kTz6JOh1hk3C8Ceiymw=="],
|
||||
"hookable": ["hookable@6.0.1", "", {}, "sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw=="],
|
||||
|
||||
"html-escaper": ["[email protected]", "", {}, "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ=="],
|
||||
|
||||
@@ -1285,7 +1282,7 @@
|
||||
|
||||
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
|
||||
|
||||
"lru-cache": ["[email protected].7", "", {}, "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA=="],
|
||||
"lru-cache": ["[email protected].6", "", {}, "sha512-ESL2CrkS/2wTPfuend7Zhkzo2u0daGJ/A2VucJOgQ/C48S/zB8MMeMHSGKYpXhIjbPxfuezITkaBH1wqv00DDQ=="],
|
||||
|
||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||
|
||||
@@ -1409,7 +1406,7 @@
|
||||
|
||||
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
|
||||
|
||||
"msw": ["[email protected]1", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-dVg20zi2I2EvnwH/+WupzsOC2mCa7qsIhyMAWtfRikn6RKtwL9+7SaF1IQ5LyZry4tlUtf6KyTVhnlQiZXozTQ=="],
|
||||
"msw": ["[email protected]0", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-G3VUymSE0/iegFnuipujpwyTM2GuZAKXNeerUSrG2+Eg391wW63xFs5ixWsK9MWzr1AGoSkYGmyAzNgbR3+urw=="],
|
||||
|
||||
"muggle-string": ["[email protected]", "", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="],
|
||||
|
||||
@@ -1453,7 +1450,7 @@
|
||||
|
||||
"oniguruma-parser": ["[email protected]", "", {}, "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w=="],
|
||||
|
||||
"oniguruma-to-es": ["[email protected].5", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ=="],
|
||||
"oniguruma-to-es": ["[email protected].4", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.0.1", "regex-recursion": "^6.0.2" } }, "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA=="],
|
||||
|
||||
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
||||
|
||||
@@ -1461,7 +1458,7 @@
|
||||
|
||||
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.40.0", "@oxfmt/binding-android-arm64": "0.40.0", "@oxfmt/binding-darwin-arm64": "0.40.0", "@oxfmt/binding-darwin-x64": "0.40.0", "@oxfmt/binding-freebsd-x64": "0.40.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", "@oxfmt/binding-linux-arm64-gnu": "0.40.0", "@oxfmt/binding-linux-arm64-musl": "0.40.0", "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-musl": "0.40.0", "@oxfmt/binding-linux-s390x-gnu": "0.40.0", "@oxfmt/binding-linux-x64-gnu": "0.40.0", "@oxfmt/binding-linux-x64-musl": "0.40.0", "@oxfmt/binding-openharmony-arm64": "0.40.0", "@oxfmt/binding-win32-arm64-msvc": "0.40.0", "@oxfmt/binding-win32-ia32-msvc": "0.40.0", "@oxfmt/binding-win32-x64-msvc": "0.40.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ=="],
|
||||
|
||||
"oxlint": ["[email protected]6.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.56.0", "@oxlint/binding-android-arm64": "1.56.0", "@oxlint/binding-darwin-arm64": "1.56.0", "@oxlint/binding-darwin-x64": "1.56.0", "@oxlint/binding-freebsd-x64": "1.56.0", "@oxlint/binding-linux-arm-gnueabihf": "1.56.0", "@oxlint/binding-linux-arm-musleabihf": "1.56.0", "@oxlint/binding-linux-arm64-gnu": "1.56.0", "@oxlint/binding-linux-arm64-musl": "1.56.0", "@oxlint/binding-linux-ppc64-gnu": "1.56.0", "@oxlint/binding-linux-riscv64-gnu": "1.56.0", "@oxlint/binding-linux-riscv64-musl": "1.56.0", "@oxlint/binding-linux-s390x-gnu": "1.56.0", "@oxlint/binding-linux-x64-gnu": "1.56.0", "@oxlint/binding-linux-x64-musl": "1.56.0", "@oxlint/binding-openharmony-arm64": "1.56.0", "@oxlint/binding-win32-arm64-msvc": "1.56.0", "@oxlint/binding-win32-ia32-msvc": "1.56.0", "@oxlint/binding-win32-x64-msvc": "1.56.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.15.0" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-Q+5Mj5PVaH/R6/fhMMFzw4dT+KPB+kQW4kaL8FOIq7tfhlnEVp6+3lcWqFruuTNlUo9srZUW3qH7Id4pskeR6g=="],
|
||||
"oxlint": ["[email protected]5.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.55.0", "@oxlint/binding-android-arm64": "1.55.0", "@oxlint/binding-darwin-arm64": "1.55.0", "@oxlint/binding-darwin-x64": "1.55.0", "@oxlint/binding-freebsd-x64": "1.55.0", "@oxlint/binding-linux-arm-gnueabihf": "1.55.0", "@oxlint/binding-linux-arm-musleabihf": "1.55.0", "@oxlint/binding-linux-arm64-gnu": "1.55.0", "@oxlint/binding-linux-arm64-musl": "1.55.0", "@oxlint/binding-linux-ppc64-gnu": "1.55.0", "@oxlint/binding-linux-riscv64-gnu": "1.55.0", "@oxlint/binding-linux-riscv64-musl": "1.55.0", "@oxlint/binding-linux-s390x-gnu": "1.55.0", "@oxlint/binding-linux-x64-gnu": "1.55.0", "@oxlint/binding-linux-x64-musl": "1.55.0", "@oxlint/binding-openharmony-arm64": "1.55.0", "@oxlint/binding-win32-arm64-msvc": "1.55.0", "@oxlint/binding-win32-ia32-msvc": "1.55.0", "@oxlint/binding-win32-x64-msvc": "1.55.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.15.0" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-T+FjepiyWpaZMhekqRpH8Z3I4vNM610p6w+Vjfqgj5TZUxHXl7N8N5IPvmOU8U4XdTRxqtNNTh9Y4hLtr7yvFg=="],
|
||||
|
||||
"p-cancelable": ["[email protected]", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="],
|
||||
|
||||
@@ -1513,7 +1510,7 @@
|
||||
|
||||
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
|
||||
|
||||
"pure-rand": ["pure-rand@8.1.0", "", {}, "sha512-53B3MB8wetRdD6JZ4W/0gDKaOvKwuXrEmV1auQc0hASWge8rieKV4PCCVNVbJ+i24miiubb4c/B+dg8Ho0ikYw=="],
|
||||
"pure-rand": ["pure-rand@8.0.0", "", {}, "sha512-7rgWlxG2gAvFPIQfUreo1XYlNvrQ9VnQPFWdncPkdl3icucLK0InOxsaafbvxGTnI6Bk/Rxmslg0lQlRCuzOXw=="],
|
||||
|
||||
"quansync": ["[email protected]", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
|
||||
|
||||
@@ -1679,7 +1676,7 @@
|
||||
|
||||
"tinyclip": ["[email protected]", "", {}, "sha512-Ae3OVUqifDw0wBriIBS7yVaW44Dp6eSHQcyq4Igc7eN2TJH/2YsicswaW+J/OuMvhpDPOKEgpAZCjkb4hpoyeA=="],
|
||||
|
||||
"tinyexec": ["[email protected].4", "", {}, "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw=="],
|
||||
"tinyexec": ["[email protected].2", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="],
|
||||
|
||||
"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
|
||||
|
||||
@@ -1687,9 +1684,9 @@
|
||||
|
||||
"tinyrainbow": ["[email protected]", "", {}, "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw=="],
|
||||
|
||||
"tldts": ["[email protected]6", "", { "dependencies": { "tldts-core": "^7.0.26" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-WiGwQjr0qYdNNG8KpMKlSvpxz652lqa3Rd+/hSaDcY4Uo6SKWZq2LAF+hsAhUewTtYhXlorBKgNF3Kk8hnjGoQ=="],
|
||||
"tldts": ["[email protected]5", "", { "dependencies": { "tldts-core": "^7.0.25" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-keinCnPbwXEUG3ilrWQZU+CqcTTzHq9m2HhoUP2l7Xmi8l1LuijAXLpAJ5zRW+ifKTNscs4NdCkfkDCBYm352w=="],
|
||||
|
||||
"tldts-core": ["[email protected]6", "", {}, "sha512-5WJ2SqFsv4G2Dwi7ZFVRnz6b2H1od39QME1lc2y5Ew3eWiZMAeqOAfWpRP9jHvhUl881406QtZTODvjttJs+ew=="],
|
||||
"tldts-core": ["[email protected]5", "", {}, "sha512-ZjCZK0rppSBu7rjHYDYsEaMOIbbT+nWF57hKkv4IUmZWBNrBWBOjIElc0mKRgLM8bm7x/BBlof6t2gi/Oq/Asw=="],
|
||||
|
||||
"to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
|
||||
|
||||
@@ -1713,19 +1710,19 @@
|
||||
|
||||
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
|
||||
|
||||
"turbo": ["[email protected]7", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.17", "turbo-darwin-arm64": "2.8.17", "turbo-linux-64": "2.8.17", "turbo-linux-arm64": "2.8.17", "turbo-windows-64": "2.8.17", "turbo-windows-arm64": "2.8.17" }, "bin": { "turbo": "bin/turbo" } }, "sha512-YwPsNSqU2f/RXU/+Kcb7cPkPZARxom4+me7LKEdN5jsvy2tpfze3zDZ4EiGrJnvOm9Avu9rK0aaYsP7qZ3iz7A=="],
|
||||
"turbo": ["[email protected]6", "", { "optionalDependencies": { "turbo-darwin-64": "2.8.16", "turbo-darwin-arm64": "2.8.16", "turbo-linux-64": "2.8.16", "turbo-linux-arm64": "2.8.16", "turbo-windows-64": "2.8.16", "turbo-windows-arm64": "2.8.16" }, "bin": { "turbo": "bin/turbo" } }, "sha512-u6e9e3cTTpE2adQ1DYm3A3r8y3LAONEx1jYvJx6eIgSY4bMLxIxs0riWzI0Z/IK903ikiUzRPZ2c1Ph5lVLkhA=="],
|
||||
|
||||
"turbo-darwin-64": ["[email protected]7", "", { "os": "darwin", "cpu": "x64" }, "sha512-ZFkv2hv7zHpAPEXBF6ouRRXshllOavYc+jjcrYyVHvxVTTwJWsBZwJ/gpPzmOKGvkSjsEyDO5V6aqqtZzwVF+Q=="],
|
||||
"turbo-darwin-64": ["[email protected]6", "", { "os": "darwin", "cpu": "x64" }, "sha512-KWa4hUMWrpADC6Q/wIHRkBLw6X6MV9nx6X7hSXbTrrMz0KdaKhmfudUZ3sS76bJFmgArBU25cSc0AUyyrswYxg=="],
|
||||
|
||||
"turbo-darwin-arm64": ["[email protected]7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5DXqhQUt24ycEryXDfMNKEkW5TBHs+QmU23a2qxXwwFDaJsWcPo2obEhBxxdEPOv7qmotjad+09RGeWCcJ9JDw=="],
|
||||
"turbo-darwin-arm64": ["[email protected]6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-NBgaqBDLQSZlJR4D5XCkQq6noaO0RvIgwm5eYFJYL3bH5dNu8o0UBpq7C5DYnQI8+ybyoHFjT5/icN4LeUYLow=="],
|
||||
|
||||
"turbo-linux-64": ["[email protected]7", "", { "os": "linux", "cpu": "x64" }, "sha512-KLUbz6w7F73D/Ihh51hVagrKR0/CTsPEbRkvXLXvoND014XJ4BCrQUqSxlQ4/hu+nqp1v5WlM85/h3ldeyujuA=="],
|
||||
"turbo-linux-64": ["[email protected]6", "", { "os": "linux", "cpu": "x64" }, "sha512-VYPdcCRevI9kR/hr1H1xwXy7QQt/jNKiim1e1mjANBXD2E9VZWMkIL74J1Huad5MbU3/jw7voHOqDPLJPC2p6w=="],
|
||||
|
||||
"turbo-linux-arm64": ["[email protected]7", "", { "os": "linux", "cpu": "arm64" }, "sha512-pJK67XcNJH40lTAjFu7s/rUlobgVXyB3A3lDoq+/JccB3hf+SysmkpR4Itlc93s8LEaFAI4mamhFuTV17Z6wOg=="],
|
||||
"turbo-linux-arm64": ["[email protected]6", "", { "os": "linux", "cpu": "arm64" }, "sha512-beq8tgUVI3uwkQkXJMiOr/hfxQRw54M3elpBwqgYFfemiK5LhCjjcwO0DkE8GZZfElBIlk+saMAQOZy3885wNQ=="],
|
||||
|
||||
"turbo-windows-64": ["[email protected]7", "", { "os": "win32", "cpu": "x64" }, "sha512-EijeQ6zszDMmGZLP2vT2RXTs/GVi9rM0zv2/G4rNu2SSRSGFapgZdxgW4b5zUYLVaSkzmkpWlGfPfj76SW9yUg=="],
|
||||
"turbo-windows-64": ["[email protected]6", "", { "os": "win32", "cpu": "x64" }, "sha512-Ig7b46iUgiOIkea/D3Z7H+zNzvzSnIJcLYFpZLA0RxbUTrbLhv9qIPwv3pT9p/abmu0LXVKHxaOo+p26SuDhzw=="],
|
||||
|
||||
"turbo-windows-arm64": ["[email protected]7", "", { "os": "win32", "cpu": "arm64" }, "sha512-crpfeMPkfECd4V1PQ/hMoiyVcOy04+bWedu/if89S15WhOalHZ2BYUi6DOJhZrszY+mTT99OwpOsj4wNfb/GHQ=="],
|
||||
"turbo-windows-arm64": ["[email protected]6", "", { "os": "win32", "cpu": "arm64" }, "sha512-fOWjbEA2PiE2HEnFQrwNZKYEdjewyPc2no9GmrXklZnTCuMsxeCN39aVlKpKpim03Zq/ykIuvApGwq8ZbfS2Yw=="],
|
||||
|
||||
"type-fest": ["[email protected]", "", { "dependencies": { "tagged-tag": "^1.0.0" } }, "sha512-JnTrzGu+zPV3aXIUhnyWJj4z/wigMsdYajGLIYakqyOW1nPllzXEJee0QQbHj+CTIQtXGlAjuK0UY+2xTyjVAw=="],
|
||||
|
||||
@@ -1743,7 +1740,7 @@
|
||||
|
||||
"uncrypto": ["[email protected]", "", {}, "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="],
|
||||
|
||||
"undici": ["[email protected].4", "", {}, "sha512-BM/JzwwaRXxrLdElV2Uo6cTLEjhSb3WXboncJamZ15NgUURmvlXvxa6xkwIOILIjPNo9i8ku136ZvWV0Uly8+w=="],
|
||||
"undici": ["[email protected].0", "", {}, "sha512-jxytwMHhsbdpBXxLAcuu0fzlQeXCNnWdDyRHpvWsUl8vd98UwYdl9YTyn8/HcpcJPC3pwUveefsa3zTxyD/ERg=="],
|
||||
|
||||
"undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
@@ -1797,21 +1794,21 @@
|
||||
|
||||
"vitest": ["[email protected]", "", { "dependencies": { "@vitest/expect": "4.1.0", "@vitest/mocker": "4.1.0", "@vitest/pretty-format": "4.1.0", "@vitest/runner": "4.1.0", "@vitest/snapshot": "4.1.0", "@vitest/spy": "4.1.0", "@vitest/utils": "4.1.0", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.0.3", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.0", "@vitest/browser-preview": "4.1.0", "@vitest/browser-webdriverio": "4.1.0", "@vitest/ui": "4.1.0", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-YbDrMF9jM2Lqc++2530UourxZHmkKLxrs4+mYhEwqWS97WJ7wOYEkcr+QfRgJ3PW9wz3odRijLZjHEaRLTNbqw=="],
|
||||
|
||||
"vitest-browser-react": ["vitest-browser-react@2.1.0", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "vitest": "^4.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/cOVQ+dZojhavfsbHjcfzB3zrUxG39HIbGdvK9vSBdGc8b8HRu5Bql0p8aXtKw4sb8/E8n5XEncQxvqHtfjjag=="],
|
||||
"vitest-browser-react": ["vitest-browser-react@2.0.5", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "vitest": "^4.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YODQX8mHTJCyKNVYTWJrLEYrUtw+QfLl78owgvuE7C5ydgmGBq6v5s4jK2w6wdPhIZsN9PpV1rQbmAevWJjO9g=="],
|
||||
|
||||
"volar-service-css": ["[email protected].70", "", { "dependencies": { "vscode-css-languageservice": "^6.3.0", "vscode-languageserver-textdocument": "^1.0.11", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-K1qyOvBpE3rzdAv3e4/6Rv5yizrYPy5R/ne3IWCAzLBuMO4qBMV3kSqWzj6KUVe6S0AnN6wxF7cRkiaKfYMYJw=="],
|
||||
"volar-service-css": ["[email protected].68", "", { "dependencies": { "vscode-css-languageservice": "^6.3.0", "vscode-languageserver-textdocument": "^1.0.11", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-lJSMh6f3QzZ1tdLOZOzovLX0xzAadPhx8EKwraDLPxBndLCYfoTvnNuiFFV8FARrpAlW5C0WkH+TstPaCxr00Q=="],
|
||||
|
||||
"volar-service-emmet": ["[email protected].70", "", { "dependencies": { "@emmetio/css-parser": "^0.4.1", "@emmetio/html-matcher": "^1.3.0", "@vscode/emmet-helper": "^2.9.3", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-xi5bC4m/VyE3zy/n2CXspKeDZs3qA41tHLTw275/7dNWM/RqE2z3BnDICQybHIVp/6G1iOQj5c1qXMgQC08TNg=="],
|
||||
"volar-service-emmet": ["[email protected].68", "", { "dependencies": { "@emmetio/css-parser": "^0.4.1", "@emmetio/html-matcher": "^1.3.0", "@vscode/emmet-helper": "^2.9.3", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-nHvixrRQ83EzkQ4G/jFxu9Y4eSsXS/X2cltEPDM+K9qZmIv+Ey1w0tg1+6caSe8TU5Hgw4oSTwNMf/6cQb3LzQ=="],
|
||||
|
||||
"volar-service-html": ["[email protected].70", "", { "dependencies": { "vscode-html-languageservice": "^5.3.0", "vscode-languageserver-textdocument": "^1.0.11", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-eR6vCgMdmYAo4n+gcT7DSyBQbwB8S3HZZvSagTf0sxNaD4WppMCFfpqWnkrlGStPKMZvMiejRRVmqsX9dYcTvQ=="],
|
||||
"volar-service-html": ["[email protected].68", "", { "dependencies": { "vscode-html-languageservice": "^5.3.0", "vscode-languageserver-textdocument": "^1.0.11", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-fru9gsLJxy33xAltXOh4TEdi312HP80hpuKhpYQD4O5hDnkNPEBdcQkpB+gcX0oK0VxRv1UOzcGQEUzWCVHLfA=="],
|
||||
|
||||
"volar-service-prettier": ["[email protected].70", "", { "dependencies": { "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0", "prettier": "^2.2 || ^3.0" }, "optionalPeers": ["@volar/language-service", "prettier"] }, "sha512-Z6BCFSpGVCd8BPAsZ785Kce1BGlWd5ODqmqZGVuB14MJvrR4+CYz6cDy4F+igmE1gMifqfvMhdgT8Aud4M5ngg=="],
|
||||
"volar-service-prettier": ["[email protected].68", "", { "dependencies": { "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0", "prettier": "^2.2 || ^3.0" }, "optionalPeers": ["@volar/language-service", "prettier"] }, "sha512-grUmWHkHlebMOd6V8vXs2eNQUw/bJGJMjekh/EPf/p2ZNTK0Uyz7hoBRngcvGfJHMsSXZH8w/dZTForIW/4ihw=="],
|
||||
|
||||
"volar-service-typescript": ["[email protected].70", "", { "dependencies": { "path-browserify": "^1.0.1", "semver": "^7.6.2", "typescript-auto-import-cache": "^0.3.5", "vscode-languageserver-textdocument": "^1.0.11", "vscode-nls": "^5.2.0", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-l46Bx4cokkUedTd74ojO5H/zqHZJ8SUuyZ0IB8JN4jfRqUM3bQFBHoOwlZCyZmOeO0A3RQNkMnFclxO4c++gsg=="],
|
||||
"volar-service-typescript": ["[email protected].68", "", { "dependencies": { "path-browserify": "^1.0.1", "semver": "^7.6.2", "typescript-auto-import-cache": "^0.3.5", "vscode-languageserver-textdocument": "^1.0.11", "vscode-nls": "^5.2.0", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-z7B/7CnJ0+TWWFp/gh2r5/QwMObHNDiQiv4C9pTBNI2Wxuwymd4bjEORzrJ/hJ5Yd5+OzeYK+nFCKevoGEEeKw=="],
|
||||
|
||||
"volar-service-typescript-twoslash-queries": ["[email protected].70", "", { "dependencies": { "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-IdD13Z9N2Bu8EM6CM0fDV1E69olEYGHDU25X51YXmq8Y0CmJ2LNj6gOiBJgpS5JGUqFzECVhMNBW7R0sPdRTMQ=="],
|
||||
"volar-service-typescript-twoslash-queries": ["[email protected].68", "", { "dependencies": { "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-NugzXcM0iwuZFLCJg47vI93su5YhTIweQuLmZxvz5ZPTaman16JCvmDZexx2rd5T/75SNuvvZmrTOTNYUsfe5w=="],
|
||||
|
||||
"volar-service-yaml": ["[email protected].70", "", { "dependencies": { "vscode-uri": "^3.0.8", "yaml-language-server": "~1.20.0" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-0c8bXDBeoATF9F6iPIlOuYTuZAC4c+yi0siQo920u7eiBJk8oQmUmg9cDUbR4+Gl++bvGP4plj3fErbJuPqdcQ=="],
|
||||
"volar-service-yaml": ["[email protected].68", "", { "dependencies": { "vscode-uri": "^3.0.8", "yaml-language-server": "~1.19.2" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-84XgE02LV0OvTcwfqhcSwVg4of3MLNUWPMArO6Aj8YXqyEVnPu8xTEMY2btKSq37mVAPuaEVASI4e3ptObmqcA=="],
|
||||
|
||||
"vscode-css-languageservice": ["[email protected]", "", { "dependencies": { "@vscode/l10n": "^0.0.18", "vscode-languageserver-textdocument": "^1.0.12", "vscode-languageserver-types": "3.17.5", "vscode-uri": "^3.1.0" } }, "sha512-eq5N9Er3fC4vA9zd9EFhyBG90wtCCuXgRSpAndaOgXMh1Wgep5lBgRIeDgjZBW9pa+332yC9+49cZMW8jcL3MA=="],
|
||||
|
||||
@@ -1859,7 +1856,7 @@
|
||||
|
||||
"yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A=="],
|
||||
|
||||
"yaml-language-server": ["yaml-language-server@1.20.0", "", { "dependencies": { "@vscode/l10n": "^0.0.18", "ajv": "^8.17.1", "ajv-draft-04": "^1.0.0", "prettier": "^3.5.0", "request-light": "^0.5.7", "vscode-json-languageservice": "4.1.8", "vscode-languageserver": "^9.0.0", "vscode-languageserver-textdocument": "^1.0.1", "vscode-languageserver-types": "^3.16.0", "vscode-uri": "^3.0.2", "yaml": "2.7.1" }, "bin": { "yaml-language-server": "bin/yaml-language-server" } }, "sha512-qhjK/bzSRZ6HtTvgeFvjNPJGWdZ0+x5NREV/9XZWFjIGezew2b4r5JPy66IfOhd5OA7KeFwk1JfmEbnTvev0cA=="],
|
||||
"yaml-language-server": ["yaml-language-server@1.19.2", "", { "dependencies": { "@vscode/l10n": "^0.0.18", "ajv": "^8.17.1", "ajv-draft-04": "^1.0.0", "lodash": "4.17.21", "prettier": "^3.5.0", "request-light": "^0.5.7", "vscode-json-languageservice": "4.1.8", "vscode-languageserver": "^9.0.0", "vscode-languageserver-textdocument": "^1.0.1", "vscode-languageserver-types": "^3.16.0", "vscode-uri": "^3.0.2", "yaml": "2.7.1" }, "bin": { "yaml-language-server": "bin/yaml-language-server" } }, "sha512-9F3myNmJzUN/679jycdMxqtydPSDRAarSj3wPiF7pchEPnO9Dg07Oc+gIYLqXR4L+g+FSEVXXv2+mr54StLFOg=="],
|
||||
|
||||
"yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
|
||||
|
||||
@@ -1867,7 +1864,7 @@
|
||||
|
||||
"yauzl": ["[email protected]", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
|
||||
|
||||
"yjs": ["[email protected].30", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-vv/9h42eCMC81ZHDFswuu/MKzkl/vyq1BhaNGfHyOonwlG4CJbQF4oiBBJPvfdeCt/PlVDWh7Nov9D34YY09uQ=="],
|
||||
"yjs": ["[email protected].29", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-kHqDPdltoXH+X4w1lVmMtddE3Oeqq48nM40FD5ojTd8xYhQpzIDcfE2keMSU5bAgRPJBe225WTUdyUgj1DtbiQ=="],
|
||||
|
||||
"yocto-queue": ["[email protected]", "", {}, "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ=="],
|
||||
|
||||
@@ -1875,7 +1872,7 @@
|
||||
|
||||
"zod": ["[email protected]", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
|
||||
|
||||
"zustand": ["[email protected]2", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-i77ae3aZq4dhMlRhJVCYgMLKuSiZAaUPAct2AksxQ+gOtimhGMdXljRT21P5BNpeT4kXlLIckvkPM029OljD7g=="],
|
||||
"zustand": ["[email protected]1", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg=="],
|
||||
|
||||
"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
|
||||
|
||||
@@ -1901,13 +1898,13 @@
|
||||
|
||||
"@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
|
||||
|
||||
"@effect/platform-node/effect": ["[email protected]3", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
"@effect/platform-node/effect": ["[email protected]1", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-w3QwJnlaLtWWiUSzhCXUTIisnULPsxLzpO6uqaBFjXybKx6FvCqsLJT6v4dV7G9eA9jeTtG6Gv7kF+jGe3HxzA=="],
|
||||
|
||||
"@effect/platform-node-shared/effect": ["[email protected]3", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
"@effect/platform-node-shared/effect": ["[email protected]1", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-w3QwJnlaLtWWiUSzhCXUTIisnULPsxLzpO6uqaBFjXybKx6FvCqsLJT6v4dV7G9eA9jeTtG6Gv7kF+jGe3HxzA=="],
|
||||
|
||||
"@effect/sql-sqlite-bun/effect": ["[email protected]3", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
"@effect/sql-sqlite-bun/effect": ["[email protected]1", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-w3QwJnlaLtWWiUSzhCXUTIisnULPsxLzpO6uqaBFjXybKx6FvCqsLJT6v4dV7G9eA9jeTtG6Gv7kF+jGe3HxzA=="],
|
||||
|
||||
"@effect/vitest/effect": ["[email protected]3", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
"@effect/vitest/effect": ["[email protected]1", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-w3QwJnlaLtWWiUSzhCXUTIisnULPsxLzpO6uqaBFjXybKx6FvCqsLJT6v4dV7G9eA9jeTtG6Gv7kF+jGe3HxzA=="],
|
||||
|
||||
"@electron/get/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
@@ -1991,6 +1988,8 @@
|
||||
|
||||
"vscode-json-languageservice/jsonc-parser": ["[email protected]", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],
|
||||
|
||||
"yaml-language-server/lodash": ["[email protected]", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="],
|
||||
|
||||
"yaml-language-server/request-light": ["[email protected]", "", {}, "sha512-3Zjgh+8b5fhRJBQZoy+zbVKpAQGLyka0MPgW3zruTF4dFFJ8Fqcfu9YsAvi/rvdcaTeWG3MkbZv4WKxAn/84Lg=="],
|
||||
|
||||
"yaml-language-server/yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-10ULxpnOCQXxJvBgxsn9ptjq6uviG/htZKk9veJGhlqn3w/DxQ631zFF+nlQXLwmImeS5amR2dl2U8sg6U9jsQ=="],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import { Option, Schema } from "effect";
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "./model";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
|
||||
@@ -64,6 +65,9 @@ export const GitRunStackedActionInput = Schema.Struct({
|
||||
filePaths: Schema.optional(
|
||||
Schema.Array(TrimmedNonEmptyStringSchema).check(Schema.isMinLength(1)),
|
||||
),
|
||||
textGenerationModel: Schema.optional(TrimmedNonEmptyStringSchema).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(DEFAULT_GIT_TEXT_GENERATION_MODEL)),
|
||||
),
|
||||
});
|
||||
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ export * from "./providerRuntime";
|
||||
export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./theme";
|
||||
export * from "./server";
|
||||
export * from "./git";
|
||||
export * from "./orchestration";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProviderKind } from "./orchestration";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
|
||||
export const CODEX_REASONING_EFFORT_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_OPTIONS)[number];
|
||||
@@ -10,14 +10,8 @@ export const CodexModelOptions = Schema.Struct({
|
||||
});
|
||||
export type CodexModelOptions = typeof CodexModelOptions.Type;
|
||||
|
||||
export const ClaudeModelOptions = Schema.Struct({
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
|
||||
|
||||
export const ProviderModelOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexModelOptions),
|
||||
claudeAgent: Schema.optional(ClaudeModelOptions),
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
|
||||
@@ -29,32 +23,25 @@ type ModelOption = {
|
||||
export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
codex: [
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ slug: "gpt-5.4-mini", name: "GPT-5.4 Mini" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
{ slug: "gpt-5.3-codex-spark", name: "GPT-5.3 Codex Spark" },
|
||||
{ slug: "gpt-5.2-codex", name: "GPT-5.2 Codex" },
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
],
|
||||
claudeAgent: [
|
||||
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
{ slug: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
|
||||
],
|
||||
} as const satisfies Record<ProviderKind, readonly ModelOption[]>;
|
||||
export type ModelOptionsByProvider = typeof MODEL_OPTIONS_BY_PROVIDER;
|
||||
|
||||
type BuiltInModelSlug = (typeof MODEL_OPTIONS_BY_PROVIDER)[ProviderKind][number]["slug"];
|
||||
type BuiltInModelSlug = ModelOptionsByProvider[ProviderKind][number]["slug"];
|
||||
export type ModelSlug = BuiltInModelSlug | (string & {});
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, ModelSlug> = {
|
||||
export const DEFAULT_MODEL_BY_PROVIDER = {
|
||||
codex: "gpt-5.4",
|
||||
claudeAgent: "claude-sonnet-4-6",
|
||||
};
|
||||
} as const satisfies Record<ProviderKind, ModelSlug>;
|
||||
|
||||
// Backward compatibility for existing Codex-only call sites.
|
||||
export const MODEL_OPTIONS = MODEL_OPTIONS_BY_PROVIDER.codex;
|
||||
export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini" as const;
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, ModelSlug>> = {
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER = {
|
||||
codex: {
|
||||
"5.4": "gpt-5.4",
|
||||
"5.3": "gpt-5.3-codex",
|
||||
@@ -62,28 +49,12 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
},
|
||||
claudeAgent: {
|
||||
opus: "claude-opus-4-6",
|
||||
"opus-4.6": "claude-opus-4-6",
|
||||
"claude-opus-4.6": "claude-opus-4-6",
|
||||
"claude-opus-4-6-20251117": "claude-opus-4-6",
|
||||
sonnet: "claude-sonnet-4-6",
|
||||
"sonnet-4.6": "claude-sonnet-4-6",
|
||||
"claude-sonnet-4.6": "claude-sonnet-4-6",
|
||||
"claude-sonnet-4-6-20251117": "claude-sonnet-4-6",
|
||||
haiku: "claude-haiku-4-5",
|
||||
"haiku-4.5": "claude-haiku-4-5",
|
||||
"claude-haiku-4.5": "claude-haiku-4-5",
|
||||
"claude-haiku-4-5-20251001": "claude-haiku-4-5",
|
||||
},
|
||||
};
|
||||
} as const satisfies Record<ProviderKind, Record<string, ModelSlug>>;
|
||||
|
||||
export const REASONING_EFFORT_OPTIONS_BY_PROVIDER = {
|
||||
codex: CODEX_REASONING_EFFORT_OPTIONS,
|
||||
claudeAgent: [],
|
||||
} as const satisfies Record<ProviderKind, readonly CodexReasoningEffort[]>;
|
||||
|
||||
export const DEFAULT_REASONING_EFFORT_BY_PROVIDER = {
|
||||
codex: "high",
|
||||
claudeAgent: null,
|
||||
} as const satisfies Record<ProviderKind, CodexReasoningEffort | null>;
|
||||
@@ -27,7 +27,7 @@ export const ORCHESTRATION_WS_CHANNELS = {
|
||||
domainEvent: "orchestration.domainEvent",
|
||||
} as const;
|
||||
|
||||
export const ProviderKind = Schema.Literals(["codex", "claudeAgent"]);
|
||||
export const ProviderKind = Schema.Literal("codex");
|
||||
export type ProviderKind = typeof ProviderKind.Type;
|
||||
export const ProviderApprovalPolicy = Schema.Literals([
|
||||
"untrusted",
|
||||
@@ -43,24 +43,13 @@ export const ProviderSandboxMode = Schema.Literals([
|
||||
]);
|
||||
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
|
||||
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
|
||||
|
||||
export const CodexProviderStartOptions = Schema.Struct({
|
||||
const CodexProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
homePath: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
export const ClaudeProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
permissionMode: Schema.optional(TrimmedNonEmptyString),
|
||||
maxThinkingTokens: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
|
||||
export const ProviderStartOptions = Schema.Struct({
|
||||
const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
claudeAgent: Schema.optional(ClaudeProviderStartOptions),
|
||||
});
|
||||
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
|
||||
|
||||
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
|
||||
export type RuntimeMode = typeof RuntimeMode.Type;
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
|
||||
@@ -42,28 +42,6 @@ describe("ProviderSessionStartInput", () => {
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("accepts claude runtime knobs", () => {
|
||||
const parsed = decodeProviderSessionStartInput({
|
||||
threadId: "thread-1",
|
||||
provider: "claudeAgent",
|
||||
cwd: "/tmp/workspace",
|
||||
model: "claude-sonnet-4-6",
|
||||
providerOptions: {
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
permissionMode: "plan",
|
||||
maxThinkingTokens: 12_000,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
expect(parsed.provider).toBe("claudeAgent");
|
||||
expect(parsed.providerOptions?.claudeAgent?.binaryPath).toBe("/usr/local/bin/claude");
|
||||
expect(parsed.providerOptions?.claudeAgent?.permissionMode).toBe("plan");
|
||||
expect(parsed.providerOptions?.claudeAgent?.maxThinkingTokens).toBe(12_000);
|
||||
expect(parsed.runtimeMode).toBe("full-access");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ProviderSendTurnInput", () => {
|
||||
|
||||
@@ -19,11 +19,11 @@ import {
|
||||
ProviderKind,
|
||||
ProviderRequestKind,
|
||||
ProviderSandboxMode,
|
||||
ProviderStartOptions,
|
||||
ProviderUserInputAnswers,
|
||||
RuntimeMode,
|
||||
} from "./orchestration";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const ProviderSessionStatus = Schema.Literals([
|
||||
"connecting",
|
||||
"ready",
|
||||
@@ -36,22 +36,32 @@ export const ProviderSession = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
status: ProviderSessionStatus,
|
||||
runtimeMode: RuntimeMode,
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
cwd: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
threadId: ThreadId,
|
||||
resumeCursor: Schema.optional(Schema.Unknown),
|
||||
activeTurnId: Schema.optional(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
lastError: Schema.optional(TrimmedNonEmptyString),
|
||||
lastError: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type ProviderSession = typeof ProviderSession.Type;
|
||||
|
||||
const CodexProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
homePath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
|
||||
export const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
});
|
||||
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
|
||||
|
||||
export const ProviderSessionStartInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
provider: Schema.optional(ProviderKind),
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
cwd: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
resumeCursor: Schema.optional(Schema.Unknown),
|
||||
approvalPolicy: Schema.optional(ProviderApprovalPolicy),
|
||||
@@ -64,12 +74,12 @@ export type ProviderSessionStartInput = typeof ProviderSessionStartInput.Type;
|
||||
export const ProviderSendTurnInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
input: Schema.optional(
|
||||
TrimmedNonEmptyString.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)),
|
||||
TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)),
|
||||
),
|
||||
attachments: Schema.optional(
|
||||
Schema.Array(ChatAttachment).check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)),
|
||||
),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
});
|
||||
@@ -115,8 +125,8 @@ export const ProviderEvent = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
createdAt: IsoDateTime,
|
||||
method: TrimmedNonEmptyString,
|
||||
message: Schema.optional(TrimmedNonEmptyString),
|
||||
method: TrimmedNonEmptyStringSchema,
|
||||
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
turnId: Schema.optional(TurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
requestId: Schema.optional(ApprovalRequestId),
|
||||
|
||||
@@ -10,7 +10,7 @@ describe("ProviderRuntimeEvent", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "turn.plan.updated",
|
||||
eventId: "event-1",
|
||||
provider: "claudeAgent",
|
||||
provider: "codex",
|
||||
sessionId: "runtime-session-1",
|
||||
createdAt: "2026-02-28T00:00:00.000Z",
|
||||
threadId: "thread-1",
|
||||
@@ -56,7 +56,7 @@ describe("ProviderRuntimeEvent", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
eventId: "event-2",
|
||||
provider: "claudeAgent",
|
||||
provider: "codex",
|
||||
sessionId: "runtime-session-2",
|
||||
createdAt: "2026-02-28T00:00:01.000Z",
|
||||
threadId: "thread-2",
|
||||
@@ -94,7 +94,7 @@ describe("ProviderRuntimeEvent", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
eventId: "event-3",
|
||||
provider: "claudeAgent",
|
||||
provider: "codex",
|
||||
sessionId: "runtime-session-2",
|
||||
createdAt: "2026-02-28T00:00:02.000Z",
|
||||
threadId: "thread-2",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Option, Schema } from "effect";
|
||||
import { Schema } from "effect";
|
||||
import {
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
@@ -19,8 +19,6 @@ const RuntimeEventRawSource = Schema.Literals([
|
||||
"codex.app-server.notification",
|
||||
"codex.app-server.request",
|
||||
"codex.eventmsg",
|
||||
"claude.sdk.message",
|
||||
"claude.sdk.permission",
|
||||
"codex.sdk.thread-event",
|
||||
]);
|
||||
export type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type;
|
||||
@@ -413,9 +411,6 @@ export const UserInputQuestion = Schema.Struct({
|
||||
header: TrimmedNonEmptyStringSchema,
|
||||
question: TrimmedNonEmptyStringSchema,
|
||||
options: Schema.Array(UserInputQuestionOption),
|
||||
multiSelect: Schema.optional(Schema.Boolean).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
});
|
||||
export type UserInputQuestion = typeof UserInputQuestion.Type;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { EditorId } from "./editor";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
import { ThemePaletteDefinition } from "./theme";
|
||||
|
||||
const KeybindingsMalformedConfigIssue = Schema.Struct({
|
||||
kind: Schema.Literal("keybindings.malformed-config"),
|
||||
@@ -15,9 +16,22 @@ const KeybindingsInvalidEntryIssue = Schema.Struct({
|
||||
index: Schema.Number,
|
||||
});
|
||||
|
||||
const ThemesMalformedConfigIssue = Schema.Struct({
|
||||
kind: Schema.Literal("themes.malformed-config"),
|
||||
message: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const ThemesInvalidEntryIssue = Schema.Struct({
|
||||
kind: Schema.Literal("themes.invalid-entry"),
|
||||
message: TrimmedNonEmptyString,
|
||||
index: Schema.Number,
|
||||
});
|
||||
|
||||
export const ServerConfigIssue = Schema.Union([
|
||||
KeybindingsMalformedConfigIssue,
|
||||
KeybindingsInvalidEntryIssue,
|
||||
ThemesMalformedConfigIssue,
|
||||
ThemesInvalidEntryIssue,
|
||||
]);
|
||||
export type ServerConfigIssue = typeof ServerConfigIssue.Type;
|
||||
|
||||
@@ -48,7 +62,9 @@ const ServerProviderStatuses = Schema.Array(ServerProviderStatus);
|
||||
export const ServerConfig = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
keybindingsConfigPath: TrimmedNonEmptyString,
|
||||
themesConfigPath: TrimmedNonEmptyString,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
customThemes: Schema.Array(ThemePaletteDefinition),
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
availableEditors: Schema.Array(EditorId),
|
||||
@@ -67,5 +83,9 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T
|
||||
export const ServerConfigUpdatedPayload = Schema.Struct({
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
updated: Schema.Array(Schema.Literals(["keybindings", "themes", "providers"])).check(
|
||||
Schema.isMinLength(1),
|
||||
Schema.isMaxLength(3),
|
||||
),
|
||||
});
|
||||
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const THEME_TOKEN_NAMES = [
|
||||
"background",
|
||||
"foreground",
|
||||
"card",
|
||||
"card-foreground",
|
||||
"popover",
|
||||
"popover-foreground",
|
||||
"primary",
|
||||
"primary-foreground",
|
||||
"secondary",
|
||||
"secondary-foreground",
|
||||
"muted",
|
||||
"muted-foreground",
|
||||
"accent",
|
||||
"accent-foreground",
|
||||
"destructive",
|
||||
"destructive-foreground",
|
||||
"border",
|
||||
"input",
|
||||
"ring",
|
||||
"info",
|
||||
"info-foreground",
|
||||
"success",
|
||||
"success-foreground",
|
||||
"warning",
|
||||
"warning-foreground",
|
||||
] as const;
|
||||
|
||||
export type ThemeTokenName = (typeof THEME_TOKEN_NAMES)[number];
|
||||
|
||||
export const ThemePaletteId = TrimmedNonEmptyString.check(
|
||||
Schema.isMaxLength(64),
|
||||
Schema.isPattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
||||
);
|
||||
export type ThemePaletteId = typeof ThemePaletteId.Type;
|
||||
|
||||
const ThemePaletteLabel = TrimmedNonEmptyString.check(Schema.isMaxLength(48));
|
||||
const ThemePaletteDescription = TrimmedNonEmptyString.check(Schema.isMaxLength(160));
|
||||
const ThemeTokenValue = TrimmedNonEmptyString.check(
|
||||
Schema.isMaxLength(160),
|
||||
Schema.isPattern(/^[^\n\r{};]+$/),
|
||||
);
|
||||
|
||||
export const ThemePaletteTokens = Schema.Record(Schema.String, ThemeTokenValue);
|
||||
export type ThemePaletteTokens = typeof ThemePaletteTokens.Type;
|
||||
|
||||
export const ThemePaletteDefinition = Schema.Struct({
|
||||
id: ThemePaletteId,
|
||||
label: ThemePaletteLabel,
|
||||
description: Schema.optional(ThemePaletteDescription),
|
||||
light: Schema.optional(ThemePaletteTokens),
|
||||
dark: Schema.optional(ThemePaletteTokens),
|
||||
});
|
||||
export type ThemePaletteDefinition = typeof ThemePaletteDefinition.Type;
|
||||
|
||||
export const ThemePaletteConfig = Schema.Array(ThemePaletteDefinition).check(
|
||||
Schema.isMaxLength(64),
|
||||
);
|
||||
export type ThemePaletteConfig = typeof ThemePaletteConfig.Type;
|
||||
@@ -1,22 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_OPTIONS,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, MODEL_OPTIONS_BY_PROVIDER } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getModelOptions,
|
||||
getReasoningEffortOptions,
|
||||
inferProviderForModel,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "./model";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
@@ -41,80 +32,38 @@ describe("normalizeModelSlug", () => {
|
||||
expect(normalizeModelSlug("toString")).toBe("toString");
|
||||
expect(normalizeModelSlug("constructor")).toBe("constructor");
|
||||
});
|
||||
|
||||
it("uses provider-specific aliases", () => {
|
||||
expect(normalizeModelSlug("sonnet", "claudeAgent")).toBe("claude-sonnet-4-6");
|
||||
expect(normalizeModelSlug("opus-4.6", "claudeAgent")).toBe("claude-opus-4-6");
|
||||
expect(normalizeModelSlug("claude-haiku-4-5-20251001", "claudeAgent")).toBe("claude-haiku-4-5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns default only when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("preserves unknown custom models", () => {
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("resolves only supported model options", () => {
|
||||
for (const model of MODEL_OPTIONS) {
|
||||
for (const model of MODEL_OPTIONS_BY_PROVIDER.codex) {
|
||||
expect(resolveModelSlug(model.slug)).toBe(model.slug);
|
||||
}
|
||||
});
|
||||
|
||||
it("supports provider-aware resolution", () => {
|
||||
expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
|
||||
);
|
||||
expect(resolveModelSlugForProvider("claudeAgent", "sonnet")).toBe("claude-sonnet-4-6");
|
||||
expect(resolveModelSlugForProvider("claudeAgent", "gpt-5.3-codex")).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps codex defaults for backward compatibility", () => {
|
||||
expect(getDefaultModel()).toBe(DEFAULT_MODEL);
|
||||
expect(getModelOptions()).toEqual(MODEL_OPTIONS);
|
||||
expect(getModelOptions("claudeAgent")).toEqual(MODEL_OPTIONS_BY_PROVIDER.claudeAgent);
|
||||
expect(getDefaultModel()).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
expect(getModelOptions()).toEqual(MODEL_OPTIONS_BY_PROVIDER.codex);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getReasoningEffortOptions", () => {
|
||||
it("returns codex reasoning options for codex", () => {
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("returns no reasoning options for claudeAgent", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inferProviderForModel", () => {
|
||||
it("detects known provider model slugs", () => {
|
||||
expect(inferProviderForModel("gpt-5.3-codex")).toBe("codex");
|
||||
expect(inferProviderForModel("claude-sonnet-4-6")).toBe("claudeAgent");
|
||||
expect(inferProviderForModel("sonnet")).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
it("falls back when the model is unknown", () => {
|
||||
expect(inferProviderForModel("custom/internal-model")).toBe("codex");
|
||||
expect(inferProviderForModel("custom/internal-model", "claudeAgent")).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
it("treats claude-prefixed custom slugs as claude", () => {
|
||||
expect(inferProviderForModel("claude-custom-internal")).toBe("claudeAgent");
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(["xhigh", "high", "medium", "low"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDefaultReasoningEffort", () => {
|
||||
it("returns provider-scoped defaults", () => {
|
||||
expect(getDefaultReasoningEffort("codex")).toBe(DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex);
|
||||
expect(getDefaultReasoningEffort("claudeAgent")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeAgent,
|
||||
);
|
||||
expect(getDefaultReasoningEffort("codex")).toBe("high");
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,16 @@
|
||||
import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
type CodexReasoningEffort,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> = {
|
||||
claudeAgent: new Set(MODEL_OPTIONS_BY_PROVIDER.claudeAgent.map((option) => option.slug)),
|
||||
type CatalogProvider = keyof typeof MODEL_OPTIONS_BY_PROVIDER;
|
||||
|
||||
const MODEL_SLUG_SET_BY_PROVIDER: Record<CatalogProvider, ReadonlySet<ModelSlug>> = {
|
||||
codex: new Set(MODEL_OPTIONS_BY_PROVIDER.codex.map((option) => option.slug)),
|
||||
};
|
||||
|
||||
@@ -37,9 +36,7 @@ export function normalizeModelSlug(
|
||||
}
|
||||
|
||||
const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record<string, ModelSlug>;
|
||||
const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
|
||||
? aliases[trimmed]
|
||||
: undefined;
|
||||
const aliased = aliases[trimmed];
|
||||
return typeof aliased === "string" ? aliased : (trimmed as ModelSlug);
|
||||
}
|
||||
|
||||
@@ -49,12 +46,12 @@ export function resolveModelSlug(
|
||||
): ModelSlug {
|
||||
const normalized = normalizeModelSlug(model, provider);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
return getDefaultModel(provider);
|
||||
}
|
||||
|
||||
return MODEL_SLUG_SET_BY_PROVIDER[provider].has(normalized)
|
||||
? normalized
|
||||
: DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
: getDefaultModel(provider);
|
||||
}
|
||||
|
||||
export function resolveModelSlugForProvider(
|
||||
@@ -64,27 +61,10 @@ export function resolveModelSlugForProvider(
|
||||
return resolveModelSlug(model, provider);
|
||||
}
|
||||
|
||||
export function inferProviderForModel(
|
||||
model: string | null | undefined,
|
||||
fallback: ProviderKind = "codex",
|
||||
): ProviderKind {
|
||||
const normalizedClaude = normalizeModelSlug(model, "claudeAgent");
|
||||
if (normalizedClaude && MODEL_SLUG_SET_BY_PROVIDER.claudeAgent.has(normalizedClaude)) {
|
||||
return "claudeAgent";
|
||||
}
|
||||
|
||||
const normalizedCodex = normalizeModelSlug(model, "codex");
|
||||
if (normalizedCodex && MODEL_SLUG_SET_BY_PROVIDER.codex.has(normalizedCodex)) {
|
||||
return "codex";
|
||||
}
|
||||
|
||||
return typeof model === "string" && model.trim().startsWith("claude-") ? "claudeAgent" : fallback;
|
||||
}
|
||||
|
||||
export function getReasoningEffortOptions(
|
||||
provider: ProviderKind = "codex",
|
||||
): ReadonlyArray<CodexReasoningEffort> {
|
||||
return REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider];
|
||||
return provider === "codex" ? CODEX_REASONING_EFFORT_OPTIONS : [];
|
||||
}
|
||||
|
||||
export function getDefaultReasoningEffort(provider: "codex"): CodexReasoningEffort;
|
||||
@@ -92,7 +72,7 @@ export function getDefaultReasoningEffort(provider: ProviderKind): CodexReasonin
|
||||
export function getDefaultReasoningEffort(
|
||||
provider: ProviderKind = "codex",
|
||||
): CodexReasoningEffort | null {
|
||||
return DEFAULT_REASONING_EFFORT_BY_PROVIDER[provider];
|
||||
return provider === "codex" ? "high" : null;
|
||||
}
|
||||
|
||||
export { CODEX_REASONING_EFFORT_OPTIONS };
|
||||
Reference in new issue
Block a user